Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
chat: sign into the camera, get transcribed ASL in the message box
nirholas79b219fb1224
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 601d58da0..0e56f8aa7 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -62,6 +62,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Graduated-coin prices now match PumpSwap exactly** — PumpSwap changed how pool prices are calculated: a pool can now hold quote-side liquidity that is not sitting in its vault, and prices have to count it. Every place we price a graduated coin has been updated to match, so quotes, price impact, market caps, and agent trade fills line up with what actually executes on-chain. Coins that have not graduated are unaffected, and the change is exact rather than approximate: where a pool carries none of this liquidity, prices are identical to before. `[fix, infra]`- **hood-traders gains an LLM-piloted strategy, hood-alerts now posts to X** — The open-source Robinhood Chain trading fleet, hood-traders, shipped a fourth strategy: bring your own key (Claude, OpenAI, Groq, or OpenRouter) and an LLM weighs the same on-chain launch signals the mechanical sniper already checks, holistically instead of against fixed cutoffs, gated behind the exact same risk engine as every other trade. The real-time alert bot, hood-alerts, now posts to X in addition to Telegram and Discord, with a choice of the official X API or a free self-hosted xactions instance. A new `hood init` command in hood-cli walks through setting up the wallet, the LLM key, and Telegram/Discord/X in one pass, so getting the whole stack running is one command instead of hand-editing env files. (`/markets/robinhood`) `[feature, sdk]`- **One page for every policy, and a clear way to report something** — three.ws had six legal documents and no index, so /legal itself went nowhere. It is now a real page: every policy listed with a plain-language summary and its effective date, plus which address actually reaches the right desk (copyright, abuse, privacy, general, support). Publishers who think we are showing too much of their work get a direct answer and a direct address instead of a search. (`/legal`) `[improvement, docs]`+- **Sign to the chat with your camera** — The agent chat now understands fingerspelled ASL. Click the camera button, sign at your webcam with a live mirrored preview, and your fingerspelling is transcribed into the message box, ready to review and send. Recognition runs on the first-place model from Google’s ASL fingerspelling challenge, and your video never leaves your device: the browser extracts hand and body landmarks locally and only those coordinates are sent. Together with signed replies, the chat now works in both directions for sign language users. (`/docs/sign-language`) `[feature]`- **Swap quotes now show the reserves they were priced from** — The pump.fun MCP swap-quote tool used to hand back a price and nothing else, so there was no way to check it. It now also returns the pool reserves the quote was computed from, including the virtual quote reserves PumpSwap added last week, so an agent or a person can reproduce the number instead of trusting it. The tool descriptions were also rewritten to keep the bonding curve and the PumpSwap pool apart: both now have a field called virtual_quote_reserves, they mean different things, and conflating them was an easy way to read a coin's price as zero. (`/docs/mcp`) `[improvement, sdk]`- **The crypto news feed now filters out the noise** — three.ws pulls headlines from around 190 sources, and some of them (major financial outlets, regulators, world-news desks) run plenty of stories that have nothing to do with crypto. The news feed now shows only crypto-relevant articles from those broad sources, while still keeping every headline from crypto-native publishers. Off-topic items like general stock movers or world-politics headlines no longer clutter the feed. Sources below a quality bar are held back too. This is a display filter only: the full firehose still feeds the searchable archive and the agents behind the scenes. (`/markets/news`) `[improvement]`- **The live economy now paces itself instead of going quiet** — The agent economy used to run at a fixed rate until its treasury ran dry, then fall silent for hours until someone refilled it by hand. It now measures what it can afford each minute and paces itself: when funds are lean it keeps trials, reviews, and marketplace listings flowing while pausing the actions that spend, then automatically speeds back up as revenue comes in. The result is a Money Pulse that stays alive continuously rather than running in bursts. (`/pulse`) `[improvement, infra]`diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.jsindex 47bdd9ada..f3cf19629 100644--- a/api/_lib/rate-limit.js+++ b/api/_lib/rate-limit.js@@ -482,6 +482,11 @@ export const limits = {// 40 per 5 min per IP comfortably covers rapid rerolling, well under abuse.surpriseIp: (ip) =>getLimiter('avatar:surprise:ip', { limit: 40, window: '5 m', local: true }).limit(ip),+ // Webcam sign-language transcription (/api/asl-recognition). Each call runs+ // a sub-second CPU inference on the worker; 30 per 5 min per IP covers an+ // active signed conversation while stopping scripted hammering.+ aslTranscribeIp: (ip) =>+ getLimiter('asl:transcribe:ip', { limit: 30, window: '5 m', local: true }).limit(ip),// Auth buckets gate credential guessing / account-creation spam. They are// sensitive (critical) but use degradeToMemory: on a Redis outage they fall// back to the per-instance memory limiter rather than failing closed. Failingdiff --git a/api/asl-recognition.js b/api/asl-recognition.jsnew file mode 100644index 000000000..db4bb733e--- /dev/null+++ b/api/asl-recognition.js@@ -0,0 +1,85 @@+/**+ * /api/asl-recognition — webcam ASL fingerspelling → text.+ *+ * GET /api/asl-recognition+ * → { columns: [390 landmark column names], max_frames, min_frames }+ * The feature schema the browser must assemble per video frame+ * (MediaPipe Holistic landmark selection, served by the worker).+ *+ * POST /api/asl-recognition { frames: [[390 numbers|null]…] }+ * → { text, frames, ms }+ *+ * Thin authenticated proxy to workers/model-asl-recognition (Kaggle-2023+ * ASLFR 1st-place model, Apache-2.0 weights, FSboard CC BY 4.0 corpus).+ * Landmarks are extracted client-side (src/sign-input.js), so raw video+ * never reaches the platform — only pose coordinates.+ */++import { cors, json, method, readJson, wrap, rateLimited } from './_lib/http.js';+import { limits, clientIp } from './_lib/rate-limit.js';++// 1500 frames × 390 floats serializes to ~10–20 MB; cap the body above that.+const MAX_BODY_BYTES = 24_000_000;++function config() {+ const base = (process.env.GCP_ASL_RECOGNITION_URL || '').replace(/\/$/, '');+ const key = process.env.GCP_RECONSTRUCTION_KEY || '';+ return base && key ? { base, key } : null;+}++function unconfigured(res) {+ return json(res, 503, {+ error: 'unconfigured',+ message:+ 'Sign recognition is not configured. Set GCP_ASL_RECOGNITION_URL and ' ++ 'GCP_RECONSTRUCTION_KEY on the API service.',+ });+}++let _schemaCache = null;+let _schemaAt = 0;+const SCHEMA_TTL_MS = 10 * 60 * 1000;++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;+ if (!method(req, res, ['GET', 'POST'])) return;++ const cfg = config();+ if (!cfg) return unconfigured(res);++ if (req.method === 'GET') {+ if (_schemaCache && Date.now() - _schemaAt < SCHEMA_TTL_MS) {+ return json(res, 200, _schemaCache);+ }+ const r = await fetch(`${cfg.base}/schema`, {+ headers: { authorization: `Bearer ${cfg.key}` },+ });+ if (!r.ok) return json(res, 502, { error: 'worker_error', status: r.status });+ _schemaCache = await r.json();+ _schemaAt = Date.now();+ return json(res, 200, _schemaCache);+ }++ const rl = await limits.aslTranscribeIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl, 'Sign recognition limit reached. Try again shortly.');+ const body = await readJson(req, MAX_BODY_BYTES).catch(() => null);+ if (!body || !Array.isArray(body.frames)) {+ return json(res, 400, { error: 'bad_request', message: 'Body must be { frames: [[…]] }.' });+ }+ const r = await fetch(`${cfg.base}/transcribe`, {+ method: 'POST',+ headers: {+ 'content-type': 'application/json',+ authorization: `Bearer ${cfg.key}`,+ },+ body: JSON.stringify({ frames: body.frames }),+ });+ const out = await r.json().catch(() => ({}));+ if (!r.ok) {+ return json(res, r.status === 400 ? 400 : 502, {+ error: r.status === 400 ? 'bad_frames' : 'worker_error',+ message: out.detail || out.message || `worker returned ${r.status}`,+ });+ }+ return json(res, 200, out);+});diff --git a/data/changelog.json b/data/changelog.jsonindex abf428869..61554b93e 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -15482,6 +15482,15 @@"improvement"],"link": "/api/avatar/render"+ },+ {+ "date": "2026-07-20",+ "title": "Sign to the chat with your camera",+ "summary": "The agent chat now understands fingerspelled ASL. Click the camera button, sign at your webcam with a live mirrored preview, and your fingerspelling is transcribed into the message box, ready to review and send. Recognition runs on the first-place model from Google\u2019s ASL fingerspelling challenge, and your video never leaves your device: the browser extracts hand and body landmarks locally and only those coordinates are sent. Together with signed replies, the chat now works in both directions for sign language users.",+ "tags": [+ "feature"+ ],+ "link": "/docs/sign-language"}]}diff --git a/docs/sign-language.md b/docs/sign-language.mdindex 206fbaa97..db8592b38 100644--- a/docs/sign-language.md+++ b/docs/sign-language.md@@ -13,6 +13,7 @@ three.ws avatars can communicate in American Sign Language. Today that means ASL<agent-3d agent-id="your-agent" chat sign-language></agent-3d>```+- **Sign INTO the chat with your camera.** The 🎥 button in the agent chat opens your webcam with a mirrored self-view: fingerspell at the camera, click again, and the transcription lands in the message box for review before sending. Landmarks are extracted in your browser (MediaPipe Holistic), so video never leaves your device — only pose coordinates go to the recognizer ([workers/model-asl-recognition](../workers/model-asl-recognition), the Kaggle-2023 1st-place fingerspelling model; Apache-2.0 weights, CC BY 4.0 corpus). Expect a 10–20% character error rate on webcam fingerspelling; the chat model is robust to it.- **Motion capture with hands.** The video-to-motion worker tracks 21 landmarks per hand and solves all 30 finger joints, so a video of a real signer becomes a retargetable animation clip. This is the pipeline that will populate the lexical sign dictionary.## How it works@@ -38,7 +39,7 @@ Fingerspelling spells English words letter by letter; it is not grammatical ASL,## Roadmap1. **Lexical sign dictionary** — captured clips (commissioned signers, community capture through [Motion Swap](https://three.ws/motion-swap), permissively licensed video) served as a `sign-language` library category and fed to `compileUtterance` so common words are signed, not spelled.-2. **Sign recognition** — webcam ASL input transcribed to text for the chat (the reverse direction), so signed conversations work both ways. The recognition worker is built ([workers/model-asl-recognition](../workers/model-asl-recognition)): continuous fingerspelling transcription on CPU using the Kaggle-2023 1st-place model (Apache-2.0 weights, CC BY 4.0 corpus), with landmarks extracted in the browser so video never leaves the device. Remaining: deploy plus the webcam capture UI in chat.+2. **Word-level sign recognition** — the current recognizer reads fingerspelling; a 250-sign vocabulary model (MIT architecture retrained on the CC BY 4.0 PopSign corpus) will let common signs be recognized directly.3. **Non-manual markers** — eyebrow and mouth blendshape tracks alongside the hand tracks.4. **Standalone package** — the engines are platform-free by design and will ship as an npm package plus reference integration.diff --git a/public/changelog.json b/public/changelog.jsonindex 8aaeaeaff..810321f21 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-23T03:09:35.894Z",+ "generated_at": "2026-07-23T03:25:42.308Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -499,6 +499,16 @@"docs"]},+ {+ "date": "2026-07-20",+ "type": "update",+ "title": "Sign to the chat with your camera",+ "summary": "The agent chat now understands fingerspelled ASL. Click the camera button, sign at your webcam with a live mirrored preview, and your fingerspelling is transcribed into the message box, ready to review and send. Recognition runs on the first-place model from Google’s ASL fingerspelling challenge, and your video never leaves your device: the browser extracts hand and body landmarks locally and only those coordinates are sent. Together with signed replies, the chat now works in both directions for sign language users.",+ "link": "/docs/sign-language",+ "tags": [+ "feature"+ ]+ },{"date": "2026-07-20","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 9072db2cd..f5e63c77e 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -382,6 +382,14 @@<category>improvement</category><description>three.ws had six legal documents and no index, so /legal itself went nowhere. It is now a real page: every policy listed with a plain-language summary and its effective date, plus which address actually reaches the right desk (copyright, abuse, privacy, general, support). Publishers who think we are showing too much of their work get a direct answer and a direct address instead of a search.</description></item>+ <item>+ <title>Sign to the chat with your camera</title>+ <link>https://three.ws/docs/sign-language</link>+ <guid isPermaLink="false">2026-07-20:Sign to the chat with your camera</guid>+ <pubDate>Mon, 20 Jul 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>The agent chat now understands fingerspelled ASL. Click the camera button, sign at your webcam with a live mirrored preview, and your fingerspelling is transcribed into the message box, ready to review and send. Recognition runs on the first-place model from Google’s ASL fingerspelling challenge, and your video never leaves your device: the browser extracts hand and body landmarks locally and only those coordinates are sent. Together with signed replies, the chat now works in both directions for sign language users.</description>+ </item><item><title>Swap quotes now show the reserves they were priced from</title><link>https://three.ws/docs/mcp</link>diff --git a/public/features.json b/public/features.jsonindex 1984956b5..9a11a6528 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-23T03:09:35.888Z",+ "generated_at": "2026-07-23T03:25:42.302Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/public/style.css b/public/style.cssindex eda93474e..91894a518 100644--- a/public/style.css+++ b/public/style.css@@ -5891,6 +5891,62 @@ body[data-viewer-mode='explore'] #layout-switch {border-color: rgba(167, 139, 250, 0.6);}+.nich-signcam {+ appearance: none;+ background: rgba(255, 255, 255, 0.06);+ border: 1px solid rgba(255, 255, 255, 0.1);+ border-radius: var(--radius-sm);+ padding: 4px 8px;+ font-size: 14px;+ line-height: 1.2;+ cursor: pointer;+ filter: grayscale(1) opacity(0.7);+ transition:+ filter 0.15s ease,+ border-color 0.15s ease,+ background 0.15s ease;+}++.nich-signcam:hover:not(:disabled) {+ filter: grayscale(0.4) opacity(0.95);+ border-color: rgba(255, 255, 255, 0.25);+}++.nich-signcam:focus-visible {+ outline: none;+ border-color: rgba(167, 139, 250, 0.85);+ box-shadow: 0 0 0 2px rgba(167, 139, 250, 0.3);+}++.nich-signcam.active {+ filter: none;+ background: rgba(239, 68, 68, 0.16);+ border-color: rgba(239, 68, 68, 0.6);+ animation: nich-signcam-pulse 1.6s ease-in-out infinite;+}++.nich-signcam:disabled {+ opacity: 0.5;+ cursor: default;+}++@keyframes nich-signcam-pulse {+ 50% {+ box-shadow: 0 0 0 4px rgba(239, 68, 68, 0.18);+ }+}++.nich-sign-preview {+ width: calc(100% - 20px);+ margin: 0 10px 6px;+ height: 150px;+ object-fit: cover;+ border-radius: var(--radius-sm);+ border: 1px solid rgba(239, 68, 68, 0.45);+ transform: scaleX(-1);+ background: #000;+}+.nich-model-select {background: rgba(255, 255, 255, 0.06);color: rgba(255, 255, 255, 0.78);diff --git a/src/nich-agent.js b/src/nich-agent.jsindex 10bc44eed..523329022 100644--- a/src/nich-agent.js+++ b/src/nich-agent.js@@ -161,6 +161,7 @@ export class NichAgent {</div><div class="nich-controls"><input type="text" class="nich-input" placeholder="Ask the agent…" autocomplete="off" maxlength="4000" />+ <button class="nich-signcam" aria-label="Sign in ASL with your camera" aria-pressed="false" title="Sign into your camera and I’ll transcribe the fingerspelling into the message box">🎥</button><button class="nich-send" aria-label="Send"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/></svg></button>@@ -217,6 +218,7 @@ export class NichAgent {});this.panel.querySelector('.nich-mic')?.addEventListener('click', () => this._toggleMic());this.panel.querySelector('.nich-sign')?.addEventListener('click', (e) => this._toggleSignLanguage(e.currentTarget));+ this.panel.querySelector('.nich-signcam')?.addEventListener('click', (e) => this._toggleSignInput(e.currentTarget));this.panel.querySelector('.nich-model-select')?.addEventListener('change', (e) => {this._modelChoice = e.target.value;try {@@ -855,6 +857,57 @@ export class NichAgent {if (on) this._addMessage('agent', 'Sign language on — I’ll sign every reply in ASL.', 'status');}+ /**+ * Webcam sign input: first click opens the camera and captures signing+ * (with a mirrored self-view for framing); second click stops, transcribes+ * the fingerspelling (src/sign-input.js → /api/asl-recognition), and drops+ * the text into the message box for review before sending.+ */+ async _toggleSignInput(btn) {+ if (this._signInput?.capturing) {+ btn.disabled = true;+ try {+ const { text } = await this._signInput.stop();+ const input = this.panel.querySelector('.nich-input');+ if (text) {+ input.value = (input.value ? `${input.value} ` : '') + text;+ input.focus();+ } else {+ this._addMessage('agent', 'I couldn’t read any fingerspelling there — face the camera and spell a little slower.', 'status');+ }+ } catch (e) {+ this._addMessage('agent', e?.message || 'Transcription failed.', 'status');+ }+ btn.disabled = false;+ btn.classList.remove('active');+ btn.setAttribute('aria-pressed', 'false');+ this._signPreview?.remove();+ this._signPreview = null;+ return;+ }+ try {+ if (!this._signInput) {+ const { SignInput } = await import('./sign-input.js');+ this._signInput = new SignInput({ apiBase: window.ASL_API_BASE || undefined });+ }+ await this._signInput.start();+ const video = this._signInput.videoElement;+ video.className = 'nich-sign-preview';+ const controls = this.panel.querySelector('.nich-controls');+ controls.parentNode.insertBefore(video, controls);+ this._signPreview = video;+ btn.classList.add('active');+ btn.setAttribute('aria-pressed', 'true');+ } catch (e) {+ this._addMessage(+ 'agent',+ e?.message || 'Camera unavailable — check browser permissions.',+ 'status',+ );+ this._signInput?.cancel();+ }+ }+// ── Message Rendering ────────────────────────────────────────────────────_addMessage(role, text, type = '') {diff --git a/src/sign-input.js b/src/sign-input.jsnew file mode 100644index 000000000..9612040b9--- /dev/null+++ b/src/sign-input.js@@ -0,0 +1,186 @@+// SignInput — webcam ASL fingerspelling capture → text.+//+// The input half of the platform's sign-language loop (the output half is+// src/sign-speech.js). Opens the user's camera, runs MediaPipe's Holistic+// landmarker in the browser, assembles per-frame feature rows in the exact+// column order the recognition worker publishes (GET /api/asl-recognition),+// and on stop POSTs the frame matrix for transcription. Raw video never+// leaves the device — only landmark coordinates.+//+// Usage:+// const input = new SignInput({ onState });+// await input.start(); // camera on, capturing+// const { text } = await input.stop(); // camera off, transcribed+//+// The recognizer reads continuous fingerspelling (Kaggle-2023 ASLFR+// 1st-place model — see workers/model-asl-recognition/README.md for the+// full provenance chain).++import { FilesetResolver, HolisticLandmarker } from '@mediapipe/tasks-vision';++const WASM_URL = 'https://cdn.jsdelivr.net/npm/@mediapipe/[email protected]/wasm';+const MODEL_URL =+ 'https://storage.googleapis.com/mediapipe-models/holistic_landmarker/holistic_landmarker/float16/latest/holistic_landmarker.task';++const COLUMN_RE = /^([xyz])_(face|left_hand|right_hand|pose)_(\d+)$/;++// Result-field lookup per schema group. Holistic returns arrays-of-arrays+// (one entry per detected person; we take the first).+const GROUP_FIELDS = {+ face: 'faceLandmarks',+ left_hand: 'leftHandLandmarks',+ right_hand: 'rightHandLandmarks',+ pose: 'poseLandmarks',+};++/** Parse the worker's column names once into fast extractors. */+export function buildColumnExtractors(columns) {+ return columns.map((name) => {+ const m = COLUMN_RE.exec(name);+ if (!m) throw new Error(`unrecognized landmark column: ${name}`);+ const [, coord, group, idxStr] = m;+ return { field: GROUP_FIELDS[group], coord, idx: parseInt(idxStr, 10) };+ });+}++/** One Holistic result → a schema row ([number|null] per column). */+export function extractRow(result, extractors) {+ return extractors.map(({ field, coord, idx }) => {+ const lm = result?.[field]?.[0]?.[idx];+ if (!lm) return null;+ const v = lm[coord];+ return Number.isFinite(v) ? v : null;+ });+}++export class SignInput {+ /**+ * @param {{+ * apiBase?: string,+ * onState?: (state: 'loading'|'capturing'|'transcribing'|'idle', detail?: object) => void,+ * maxSeconds?: number,+ * targetFps?: number,+ * }} [opts]+ */+ constructor(opts = {}) {+ this.apiBase = opts.apiBase ?? '/api/asl-recognition';+ this.onState = opts.onState ?? (() => {});+ this.maxSeconds = opts.maxSeconds ?? 20;+ this.targetFps = opts.targetFps ?? 24;++ this._landmarker = null;+ this._extractors = null;+ this._minFrames = 8;+ this._video = null;+ this._stream = null;+ this._frames = [];+ this._raf = 0;+ this._lastSampleT = 0;+ this._lastVideoTime = -1;+ this.capturing = false;+ }++ /** Camera preview element (attach it to the page while capturing). */+ get videoElement() {+ return this._video;+ }++ async _ensureReady() {+ if (this._landmarker && this._extractors) return;+ this.onState('loading');+ const [schemaRes, fileset] = await Promise.all([+ fetch(this.apiBase, { headers: { accept: 'application/json' } }),+ FilesetResolver.forVisionTasks(WASM_URL),+ ]);+ if (!schemaRes.ok) {+ const body = await schemaRes.json().catch(() => ({}));+ throw new Error(body.message || `sign recognition unavailable (${schemaRes.status})`);+ }+ const schema = await schemaRes.json();+ this._extractors = buildColumnExtractors(schema.columns);+ this._minFrames = schema.min_frames ?? 8;+ this._landmarker = await HolisticLandmarker.createFromOptions(fileset, {+ baseOptions: { modelAssetPath: MODEL_URL, delegate: 'GPU' },+ runningMode: 'VIDEO',+ });+ }++ /** Open the camera and start collecting frames. */+ async start() {+ if (this.capturing) return;+ await this._ensureReady();+ this._stream = await navigator.mediaDevices.getUserMedia({+ video: { width: 640, height: 480, facingMode: 'user' },+ audio: false,+ });+ const video = document.createElement('video');+ video.playsInline = true;+ video.muted = true;+ video.srcObject = this._stream;+ await video.play();+ this._video = video;+ this._frames = [];+ this._lastSampleT = 0;+ this._lastVideoTime = -1;+ this.capturing = true;+ this.onState('capturing', { frames: 0 });+ const step = (t) => {+ if (!this.capturing) return;+ this._raf = requestAnimationFrame(step);+ if (t - this._lastSampleT < 1000 / this.targetFps) return;+ if (video.currentTime === this._lastVideoTime) return;+ this._lastVideoTime = video.currentTime;+ this._lastSampleT = t;+ const result = this._landmarker.detectForVideo(video, performance.now());+ this._frames.push(extractRow(result, this._extractors));+ if (this._frames.length % 12 === 0) {+ this.onState('capturing', { frames: this._frames.length });+ }+ if (this._frames.length >= this.maxSeconds * this.targetFps) {+ // Hard cap — auto-stop into transcription rather than dropping data.+ this.stop().catch(() => {});+ }+ };+ this._raf = requestAnimationFrame(step);+ }++ /** Stop the camera and transcribe what was captured. */+ async stop() {+ if (!this.capturing) return { text: '', frames: 0 };+ this.capturing = false;+ cancelAnimationFrame(this._raf);+ this._stream?.getTracks().forEach((tr) => tr.stop());+ this._stream = null;+ const frames = this._frames;+ this._frames = [];+ this._video = null;+ if (frames.length < this._minFrames) {+ this.onState('idle');+ throw new Error('Not enough signing captured — hold the sign a moment longer.');+ }+ this.onState('transcribing', { frames: frames.length });+ try {+ const res = await fetch(this.apiBase, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ frames }),+ });+ const out = await res.json().catch(() => ({}));+ if (!res.ok) throw new Error(out.message || `transcription failed (${res.status})`);+ return { text: out.text ?? '', frames: frames.length, ms: out.ms };+ } finally {+ this.onState('idle');+ }+ }++ /** Abandon capture without transcribing. */+ cancel() {+ this.capturing = false;+ cancelAnimationFrame(this._raf);+ this._stream?.getTracks().forEach((tr) => tr.stop());+ this._stream = null;+ this._frames = [];+ this._video = null;+ this.onState('idle');+ }+}diff --git a/tests/sign-input.test.js b/tests/sign-input.test.jsnew file mode 100644index 000000000..d77073810--- /dev/null+++ b/tests/sign-input.test.js@@ -0,0 +1,44 @@+import { describe, expect, it } from 'vitest';++import { buildColumnExtractors, extractRow } from '../src/sign-input.js';++describe('buildColumnExtractors', () => {+ it('parses the worker column naming', () => {+ const ex = buildColumnExtractors(['x_face_61', 'y_left_hand_4', 'z_pose_17', 'x_right_hand_0']);+ expect(ex[0]).toEqual({ field: 'faceLandmarks', coord: 'x', idx: 61 });+ expect(ex[1]).toEqual({ field: 'leftHandLandmarks', coord: 'y', idx: 4 });+ expect(ex[2]).toEqual({ field: 'poseLandmarks', coord: 'z', idx: 17 });+ expect(ex[3]).toEqual({ field: 'rightHandLandmarks', coord: 'x', idx: 0 });+ });++ it('rejects unknown columns', () => {+ expect(() => buildColumnExtractors(['x_torso_3'])).toThrow();+ });++ it('parses the real 390-column schema', async () => {+ const { readFileSync } = await import('node:fs');+ const args = JSON.parse(+ readFileSync('workers/model-asl-recognition/inference_args.json', 'utf8'),+ );+ const ex = buildColumnExtractors(args.selected_columns);+ expect(ex).toHaveLength(390);+ });+});++describe('extractRow', () => {+ const ex = buildColumnExtractors(['x_pose_0', 'y_left_hand_2', 'z_face_1']);++ it('reads coordinates and nulls missing groups', () => {+ const result = {+ poseLandmarks: [[{ x: 0.5, y: 0.2, z: -0.1 }]],+ faceLandmarks: [[{ x: 0, y: 0, z: 0 }, { x: 0.1, y: 0.2, z: 0.3 }]],+ // no hands detected+ };+ expect(extractRow(result, ex)).toEqual([0.5, null, 0.3]);+ });++ it('nulls everything on an empty result', () => {+ expect(extractRow({}, ex)).toEqual([null, null, null]);+ expect(extractRow(null, ex)).toEqual([null, null, null]);+ });+});