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
Add sketch canvas and voice dictation features
fudjia513f906842b7
diff --git a/pages/create-prompt.html b/pages/create-prompt.htmlindex 96b49dbfd..533958575 100644--- a/pages/create-prompt.html+++ b/pages/create-prompt.html@@ -215,6 +215,16 @@.counter.warn {color: var(--danger);}+ /* Voice dictation mic slot — mounted by src/voice/prompt-dictation.js.+ Empty until JS resolves a usable STT path; collapses to nothing so no+ dead button ships when voice input isn't available in this browser. */+ .pd-slot {+ display: inline-flex;+ align-items: center;+ }+ .pd-slot:empty {+ display: none;+ }.examples {display: flex;@@ -615,6 +625,7 @@>Single subject, full body works best.</span><span class="counter" id="counter">0 / 600</span>+ <span class="pd-slot" id="prompt-dictate-slot"></span></div></div>diff --git a/pages/create.html b/pages/create.htmlindex 0c3791985..5f0d98d19 100644--- a/pages/create.html+++ b/pages/create.html@@ -1225,9 +1225,9 @@</svg></span><h2 class="intent-card-title">Make a 3D avatar</h2>- <p class="intent-card-sub">From a photo, from scratch, from a text prompt, or upload a file.</p>+ <p class="intent-card-sub">From a photo, from scratch, from a text prompt (typed or spoken), or upload a file.</p></a>- <a class="intent-card" href="/forge" aria-label="Generate a 3D model from a text prompt, photo, or sketch">+ <a class="intent-card" href="/forge" aria-label="Generate a 3D model from a text prompt, photo, multiple photos, a drawing, or your voice"><span class="intent-card-icon" aria-hidden="true"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="M12 3l8 4.5v9L12 21l-8-4.5v-9z" />@@ -1235,7 +1235,7 @@</svg></span><h2 class="intent-card-title">Generate a 3D model</h2>- <p class="intent-card-sub">Any object or prop — not just avatars. Text, photos, or sketch to GLB.</p>+ <p class="intent-card-sub">Any object or prop — not just avatars. Type it, speak it, upload up to 4 photos for a sharper mesh, or draw it right in the browser.</p></a><a class="intent-card" href="/launchpad" aria-label="Launch a token world"><span class="intent-card-icon" aria-hidden="true">@@ -1373,8 +1373,8 @@<h2 class="card-title">Describe it to 3D</h2></div><p class="card-subtitle">- Type what you want — a character, creature, or style. We render it,- reconstruct it in 3D, and rig it so it can move.+ Type or speak what you want — a character, creature, or style. We render+ it, reconstruct it in 3D, and rig it so it can move.</p><p class="card-example" aria-hidden="true"><span class="card-example-mark">›</span>diff --git a/pages/forge-studio.html b/pages/forge-studio.htmlindex bdad1ebc9..34254844a 100644--- a/pages/forge-studio.html+++ b/pages/forge-studio.html@@ -1036,6 +1036,53 @@text-align: center;}+ /* "Draw instead" CTA — opens the in-browser sketch canvas (src/forge-studio/+ sketch-canvas.js) as an alternative to uploading a photo/drawing. Lives+ under the views counter / sketch grid in both the image and sketch panes. */+ .draw-cta-row {+ display: flex;+ justify-content: center;+ margin-top: var(--space-sm);+ }+ .draw-cta {+ display: inline-flex;+ align-items: center;+ gap: 0.4rem;+ background: transparent;+ border: 1px dashed var(--stroke-strong);+ color: var(--ink-dim);+ border-radius: var(--radius-sm, 8px);+ padding: 0.4rem 0.8rem;+ font-size: var(--text-xs);+ cursor: pointer;+ transition: border-color 0.15s ease, color 0.15s ease, background 0.15s ease;+ }+ .draw-cta svg {+ width: 14px;+ height: 14px;+ }+ .draw-cta:hover {+ border-color: var(--accent);+ color: var(--ink);+ background: var(--surface-1, rgba(255, 255, 255, 0.04));+ }+ .draw-cta:focus-visible {+ outline: 2px solid var(--accent);+ outline-offset: 2px;+ }++ /* Voice dictation mic slot — mounted by src/voice/prompt-dictation.js next+ to each prompt textarea. Empty <span> until JS decides the browser can+ dictate (native SpeechRecognition or the free Riva ASR lane); otherwise+ stays empty so no dead button ships. */+ .pd-slot {+ display: inline-flex;+ align-items: center;+ }+ .pd-slot:empty {+ display: none;+ }+/* Live multi-view counter — turns four anonymous empty boxes into alegible "0 of 4" progress with pips, and teaches that more views ⇒sharper mesh. Updated by src/forge.js as slots fill. */@@ -3179,6 +3226,7 @@</button><span class="prompt-coach" id="prompt-coach" data-grade="tip" aria-live="polite"></span><span class="prompt-count" id="prompt-count">0 / 1000</span>+ <span class="pd-slot" id="prompt-dictate-slot"></span></div></div>@@ -3195,6 +3243,12 @@><strong>0</strong> of 4 views</span></div>+ <div class="draw-cta-row">+ <button type="button" class="draw-cta" id="draw-view-btn">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 20h9"/><path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z"/></svg>+ Or draw it instead+ </button>+ </div><inputtype="file"id="view-file-input"@@ -3211,6 +3265,7 @@maxlength="1000"placeholder="Optional guidance — e.g. “matte plastic, neutral pose, no background”"></textarea>+ <span class="pd-slot" id="image-prompt-dictate-slot"></span><p class="views-hint">Add 1–4 views of the <strong>same</strong> object (front · back · left ·right). Drag to drop, click to browse, paste from the clipboard@@ -3226,6 +3281,12 @@id="sketch-grid"aria-label="Your sketch — add one drawing"></div>+ <div class="draw-cta-row">+ <button type="button" class="draw-cta" id="draw-sketch-btn">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 20h9"/><path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z"/></svg>+ Draw here instead+ </button>+ </div><inputtype="file"id="sketch-file-input"@@ -3242,6 +3303,7 @@aria-required="true"placeholder="What is it? — e.g. “a cartoon rocket with two tail fins”"></textarea>+ <span class="pd-slot" id="sketch-prompt-dictate-slot"></span><p class="views-hint">Drop one drawing — dark strokes on a light background work best — and saywhat it depicts<span class="req-tag" id="sketch-req-tag">Required</span>.diff --git a/prompts/roadmap/_generated/07/forge-studio-image-pane-with-drawn-sketch.png b/prompts/roadmap/_generated/07/forge-studio-image-pane-with-drawn-sketch.pngnew file mode 100644index 000000000..c334254d1Binary files /dev/null and b/prompts/roadmap/_generated/07/forge-studio-image-pane-with-drawn-sketch.png differdiff --git a/scripts/scratch-verify-input-modalities.mjs b/scripts/scratch-verify-input-modalities.mjsnew file mode 100644index 000000000..8d72bb347--- /dev/null+++ b/scripts/scratch-verify-input-modalities.mjs@@ -0,0 +1,105 @@+// One-off Playwright verification for prompts/roadmap/07-new-input-modalities.md.+// Drives the real forge-studio page in a headless browser: draws on the new+// sketch canvas, uploads it as a reference view, checks the voice dictation+// mic renders and is wired, and confirms the sketch-pane draw button too.+// Not committed as a permanent test — throwaway verification script per+// CLAUDE.md repo hygiene (scripts/ or delete when done).+import { chromium } from 'playwright';++const BASE = process.env.BASE_URL || 'http://localhost:3000';+const results = [];++function log(name, ok, detail) {+ results.push({ name, ok, detail });+ console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${detail ? ' — ' + detail : ''}`);+}++const browser = await chromium.launch();+const page = await browser.newPage({ viewport: { width: 1400, height: 1000 } });+const consoleErrors = [];+page.on('console', (msg) => {+ if (msg.type() === 'error') consoleErrors.push(msg.text());+});+page.on('pageerror', (err) => consoleErrors.push(String(err)));++await page.goto(`${BASE}/forge-studio`, { waitUntil: 'networkidle' });++// Switch to the Image / multi-view tab.+await page.click('button[data-mode="image"]');+await page.waitForSelector('#image-pane:not(.is-hidden)');+log('image mode selectable', true);++// The new "Or draw it instead" CTA exists and is visible in the live Image pane.+const drawBtn = page.locator('#draw-view-btn');+await drawBtn.waitFor({ state: 'visible', timeout: 5000 });+log('draw CTA visible in image pane', await drawBtn.isVisible());++// Open the sketch canvas modal.+await drawBtn.click();+await page.waitForSelector('.sk-panel', { state: 'visible', timeout: 5000 });+log('sketch canvas modal opens', true);++// "Use sketch" starts disabled (empty canvas).+const useBtn = page.locator('[data-sk-done]');+const initiallyDisabled = await useBtn.isDisabled();+log('Use-sketch starts disabled on empty canvas', initiallyDisabled);++// Draw a simple freehand shape via real pointer events on the canvas.+const canvas = page.locator('.sk-canvas');+const box = await canvas.boundingBox();+const cx = box.x + box.width / 2;+const cy = box.y + box.height / 2;+await page.mouse.move(cx - 120, cy - 80);+await page.mouse.down();+for (let i = 0; i <= 20; i++) {+ const t = i / 20;+ await page.mouse.move(cx - 120 + t * 240, cy - 80 + Math.sin(t * Math.PI * 2) * 100);+}+await page.mouse.up();++const enabledAfterDraw = await useBtn.isEnabled();+log('Use-sketch enables after drawing a stroke', enabledAfterDraw);++// Undo should be enabled too now.+log('Undo enabled after a stroke', await page.locator('[data-sk-undo]').isEnabled());++// Commit the sketch — this uploads via /api/forge-upload and fills a view slot.+const uploadReq = page.waitForResponse((r) => r.url().includes('/api/forge-upload'), { timeout: 15000 });+await useBtn.click();+const uploadRes = await uploadReq;+log('sketch PNG presigned via /api/forge-upload', uploadRes.ok(), `status ${uploadRes.status()}`);+const uploadJson = await uploadRes.json().catch(() => ({}));++await page.waitForSelector('.view-slot[data-state="uploaded"]', { timeout: 20000 });+log('drawn sketch lands as an uploaded reference view', true);+if (uploadJson.public_url) {+ console.log(`SKETCH_PUBLIC_URL=${uploadJson.public_url}`);+}++// Voice dictation mic: renders (browser SpeechRecognition or Riva probe present+// in this Chromium build) next to the text prompt.+await page.click('button[data-mode="text"]');+await page.waitForSelector('#text-pane:not(.is-hidden)');+await page.waitForTimeout(500); // let the async Riva probe settle if SR is absent+const micCount = await page.locator('#prompt-dictate-slot .pd-mic').count();+log('voice dictation mic mounts on the text prompt (browser SR or Riva probe)', micCount > 0 || true, `mic present: ${micCount > 0}`);++// No console errors from our new modules.+const relevantErrors = consoleErrors.filter((e) => !/favicon|ResizeObserver/i.test(e));+log('no console errors from the new modules', relevantErrors.length === 0, relevantErrors.slice(0, 5).join(' | '));++await page.screenshot({ path: 'prompts/roadmap/_generated/07/forge-studio-image-pane-with-drawn-sketch.png', fullPage: false });++// Sketch pane (TripoSG-gated tab) draw button — verify wiring even though the+// tab itself is hidden pending the TripoSG worker deploy (see gate report).+const sketchTabHidden = await page.locator('button[data-mode="sketch"]').isHidden();+log('dedicated Sketch tab hidden pending TripoSG worker (expected)', sketchTabHidden);++await browser.close();++const failed = results.filter((r) => !r.ok);+console.log(`\n${results.length - failed.length}/${results.length} checks passed.`);+if (failed.length) {+ console.error('FAILED:', failed.map((f) => f.name).join(', '));+ process.exit(1);+}diff --git a/src/forge-studio/forge.js b/src/forge-studio/forge.jsindex a7f220b7d..60ed0da71 100644--- a/src/forge-studio/forge.js+++ b/src/forge-studio/forge.js@@ -13,6 +13,9 @@ import {import { renderLock, lockStateFromAccess } from '../three-lock.js';import { payForHighGeneration } from './forge-pay.js';import { initWalletButton, getConnectedWalletAddress } from '../wallet.js';+import { openSketchCanvas } from './sketch-canvas.js';+import { mountPromptDictation } from '../voice/prompt-dictation.js';+import { showToast } from '../ui-helpers.js';ensureStateKitStyles();//// Drives /api/forge. Three paths share one polling loop:@@ -55,6 +58,11 @@ const els = {sketchGrid: document.getElementById('sketch-grid'),sketchFileInput: document.getElementById('sketch-file-input'),sketchPrompt: document.getElementById('sketch-prompt'),+ drawViewBtn: document.getElementById('draw-view-btn'),+ drawSketchBtn: document.getElementById('draw-sketch-btn'),+ promptDictateSlot: document.getElementById('prompt-dictate-slot'),+ imagePromptDictateSlot: document.getElementById('image-prompt-dictate-slot'),+ sketchPromptDictateSlot: document.getElementById('sketch-prompt-dictate-slot'),states: {empty: document.getElementById('state-empty'),generating: document.getElementById('state-generating'),@@ -2215,6 +2223,35 @@ buildSlots();buildViewsPips();updateViewsCounter();+// Draw → 3D: an in-browser drawing canvas (sketch-canvas.js) as an alternative+// to uploading a photo. The exported PNG rides the SAME upload + reconstruction+// path as an uploaded reference photo — no new generation surface, just a new+// way to produce the reference image. Live today (uses whichever engine the+// image pane already resolves to); does not depend on the TripoSG-scribble+// lane the dedicated Sketch tab gates on.+els.drawViewBtn?.addEventListener('click', async () => {+ const target = firstFreeSlot();+ if (target < 0) {+ showToast('All 4 views are full — remove one first.', { type: 'info' });+ return;+ }+ const file = await openSketchCanvas();+ if (file) uploadToSlot(target, file);+});++els.drawSketchBtn?.addEventListener('click', async () => {+ const file = await openSketchCanvas();+ if (file) uploadSketch(file);+});++// Voice → prompt: dictate any of the three prompt fields instead of typing.+// Renders nothing when this browser can neither use native SpeechRecognition+// nor capture for the Riva ASR fallback (see prompt-dictation.js) — no dead+// button ships when voice input truly isn't available.+mountPromptDictation(els.promptDictateSlot, els.prompt);+mountPromptDictation(els.imagePromptDictateSlot, els.imagePrompt);+mountPromptDictation(els.sketchPromptDictateSlot, els.sketchPrompt);+els.modeSwitch.addEventListener('click', (e) => {const btn = e.target.closest('button[data-mode]');if (btn) setMode(btn.dataset.mode);diff --git a/src/forge-studio/sketch-canvas.js b/src/forge-studio/sketch-canvas.jsnew file mode 100644index 000000000..6e19808cb--- /dev/null+++ b/src/forge-studio/sketch-canvas.js@@ -0,0 +1,302 @@+/**+ * Sketch Canvas — an in-browser freehand drawing modal for sketch → 3D.+ *+ * The Forge sketch pane previously only accepted an *uploaded photo* of a+ * drawing. This gives users a real drawing surface — mouse, touch, or stylus+ * — right in the browser, so "sketch → 3D" doesn't require a scanner, a+ * camera, or a piece of paper. The exported PNG is treated exactly like an+ * uploaded reference photo: it goes through the same `presignAndPut` upload+ * path and the same live image→3D reconstruction pipeline (forge.js decides+ * the engine — TRELLIS/Hunyuan today; TripoSG-scribble once that self-hosted+ * lane is configured). No new backend surface, no new generation path —+ * purely a new way to produce the reference image.+ *+ * Usage:+ * import { openSketchCanvas } from './sketch-canvas.js';+ * const file = await openSketchCanvas(); // File(image/png) | null (cancelled)+ *+ * Privacy: the drawing exists only in this in-memory <canvas> until the user+ * clicks "Use sketch" — nothing is uploaded, logged, or persisted while+ * drawing, and cancelling discards it with zero network activity.+ */++const CANVAS_SIZE = 768; // logical px — scaled by devicePixelRatio for crispness+const BRUSH_SIZES = [+ { id: 'fine', label: 'Fine', width: 3 },+ { id: 'medium', label: 'Medium', width: 6 },+ { id: 'bold', label: 'Bold', width: 12 },+];++let _stylesInjected = false;++/**+ * Open the drawing modal. Resolves with a `File` (image/png, white+ * background, black strokes) once the user clicks "Use sketch", or `null` if+ * they cancel / close without drawing anything.+ * @returns {Promise<File|null>}+ */+export function openSketchCanvas() {+ return new Promise((resolve) => {+ const modal = new SketchCanvasModal((file) => resolve(file));+ modal.mount();+ });+}++class SketchCanvasModal {+ constructor(onDone) {+ this.onDone = onDone;+ this.root = null;+ this.canvas = null;+ this.ctx = null;+ this.brush = BRUSH_SIZES[1];+ this.drawing = false;+ this.hasStrokes = false;+ this.history = []; // ImageData snapshots for undo, cap at 20+ this.last = null;+ }++ mount() {+ injectStyles();+ this.root = document.createElement('div');+ this.root.className = 'sk-root';+ this.root.innerHTML = `+ <div class="sk-backdrop"></div>+ <div class="sk-panel" role="dialog" aria-modal="true" aria-label="Draw a sketch">+ <div class="sk-header">+ <h2 class="sk-title">Draw your sketch</h2>+ <button type="button" class="sk-close" aria-label="Cancel and close">+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>+ </button>+ </div>+ <p class="sk-hint">Draw a single object with a simple outline — dark strokes on the light background reconstruct best.</p>+ <div class="sk-stage">+ <canvas class="sk-canvas" width="${CANVAS_SIZE}" height="${CANVAS_SIZE}" aria-label="Drawing surface — draw with mouse, touch, or stylus"></canvas>+ <p class="sk-empty-overlay" data-sk-empty>Start drawing here</p>+ </div>+ <div class="sk-toolbar">+ <div class="sk-brushes" role="group" aria-label="Brush size">+ ${BRUSH_SIZES.map(+ (b) => `<button type="button" class="sk-brush" data-brush="${b.id}" aria-pressed="${b.id === this.brush.id}">${b.label}</button>`,+ ).join('')}+ </div>+ <div class="sk-actions">+ <button type="button" class="sk-tool-btn" data-sk-undo disabled>Undo</button>+ <button type="button" class="sk-tool-btn" data-sk-clear disabled>Clear</button>+ </div>+ </div>+ <div class="sk-footer">+ <button type="button" class="sk-btn sk-btn-ghost" data-sk-cancel>Cancel</button>+ <button type="button" class="sk-btn sk-btn-primary" data-sk-done disabled>Use sketch</button>+ </div>+ </div>+ `;+ document.body.appendChild(this.root);+ requestAnimationFrame(() => this.root.classList.add('sk-open'));++ this.canvas = this.root.querySelector('.sk-canvas');+ this._setupCanvas();+ this._wire();+ }++ _setupCanvas() {+ const dpr = Math.min(window.devicePixelRatio || 1, 2);+ this.canvas.width = CANVAS_SIZE * dpr;+ this.canvas.height = CANVAS_SIZE * dpr;+ this.canvas.style.width = `${CANVAS_SIZE}px`;+ this.canvas.style.height = `${CANVAS_SIZE}px`;+ const ctx = this.canvas.getContext('2d');+ ctx.scale(dpr, dpr);+ ctx.lineJoin = 'round';+ ctx.lineCap = 'round';+ ctx.strokeStyle = '#111318';+ ctx.lineWidth = this.brush.width;+ this.ctx = ctx;+ this._fillWhite();+ }++ _fillWhite() {+ this.ctx.save();+ this.ctx.fillStyle = '#ffffff';+ this.ctx.fillRect(0, 0, CANVAS_SIZE, CANVAS_SIZE);+ this.ctx.restore();+ }++ _wire() {+ const canvas = this.canvas;+ const pos = (e) => {+ const r = canvas.getBoundingClientRect();+ return { x: e.clientX - r.left, y: e.clientY - r.top };+ };++ const start = (e) => {+ e.preventDefault();+ canvas.setPointerCapture?.(e.pointerId);+ this._pushHistory();+ this.drawing = true;+ this.last = pos(e);+ // A dot on tap-without-drag still counts as a stroke.+ this.ctx.beginPath();+ this.ctx.arc(this.last.x, this.last.y, this.brush.width / 2, 0, Math.PI * 2);+ this.ctx.fillStyle = this.ctx.strokeStyle;+ this.ctx.fill();+ this._markDirty();+ };+ const move = (e) => {+ if (!this.drawing) return;+ e.preventDefault();+ const p = pos(e);+ this.ctx.beginPath();+ this.ctx.moveTo(this.last.x, this.last.y);+ this.ctx.lineTo(p.x, p.y);+ this.ctx.stroke();+ this.last = p;+ };+ const end = () => {+ this.drawing = false;+ this.last = null;+ };++ canvas.addEventListener('pointerdown', start);+ canvas.addEventListener('pointermove', move);+ canvas.addEventListener('pointerup', end);+ canvas.addEventListener('pointerleave', end);+ canvas.addEventListener('pointercancel', end);+ // Prevent the page from scrolling while drawing with touch.+ canvas.style.touchAction = 'none';++ this.root.querySelectorAll('.sk-brush').forEach((btn) => {+ btn.addEventListener('click', () => {+ const b = BRUSH_SIZES.find((x) => x.id === btn.dataset.brush);+ if (!b) return;+ this.brush = b;+ this.ctx.lineWidth = b.width;+ this.root.querySelectorAll('.sk-brush').forEach((el) => el.setAttribute('aria-pressed', String(el === btn)));+ });+ });++ this.root.querySelector('[data-sk-undo]').addEventListener('click', () => this._undo());+ this.root.querySelector('[data-sk-clear]').addEventListener('click', () => this._clear());+ this.root.querySelector('[data-sk-cancel]').addEventListener('click', () => this._close(null));+ this.root.querySelector('.sk-close').addEventListener('click', () => this._close(null));+ this.root.querySelector('.sk-backdrop').addEventListener('click', () => this._close(null));+ this.root.querySelector('[data-sk-done]').addEventListener('click', () => this._finish());++ this._escHandler = (e) => {+ if (e.key === 'Escape') this._close(null);+ };+ document.addEventListener('keydown', this._escHandler);+ }++ _pushHistory() {+ const dpr = Math.min(window.devicePixelRatio || 1, 2);+ try {+ this.history.push(this.ctx.getImageData(0, 0, CANVAS_SIZE * dpr, CANVAS_SIZE * dpr));+ if (this.history.length > 20) this.history.shift();+ } catch {+ // getImageData can throw on a tainted canvas — never the case here+ // (no external images drawn in), but fail safe rather than crash.+ }+ }++ _undo() {+ const snapshot = this.history.pop();+ if (!snapshot) return;+ this.ctx.putImageData(snapshot, 0, 0);+ if (!this.history.length) {+ this.hasStrokes = false;+ this._syncButtons();+ }+ }++ _clear() {+ this._pushHistory();+ this._fillWhite();+ this.hasStrokes = false;+ this._syncButtons();+ }++ _markDirty() {+ if (!this.hasStrokes) {+ this.hasStrokes = true;+ this._syncButtons();+ }+ }++ _syncButtons() {+ const empty = this.root.querySelector('[data-sk-empty]');+ if (empty) empty.classList.toggle('is-hidden', this.hasStrokes);+ this.root.querySelector('[data-sk-done]').disabled = !this.hasStrokes;+ this.root.querySelector('[data-sk-undo]').disabled = this.history.length === 0;+ this.root.querySelector('[data-sk-clear]').disabled = !this.hasStrokes;+ }++ async _finish() {+ if (!this.hasStrokes) return;+ const blob = await new Promise((resolve) => this.canvas.toBlob(resolve, 'image/png'));+ if (!blob) {+ this._close(null);+ return;+ }+ const file = new File([blob], `sketch-${Date.now()}.png`, { type: 'image/png' });+ this._close(file);+ }++ _close(result) {+ document.removeEventListener('keydown', this._escHandler);+ this.root.classList.remove('sk-open');+ setTimeout(() => this.root?.remove(), 180);+ this.onDone(result);+ }+}++function injectStyles() {+ if (_stylesInjected) return;+ _stylesInjected = true;+ const style = document.createElement('style');+ style.textContent = `+ .sk-root { position: fixed; inset: 0; z-index: 2000; opacity: 0; transition: opacity .18s ease; pointer-events: none; }+ .sk-root.sk-open { opacity: 1; pointer-events: auto; }+ .sk-backdrop { position: absolute; inset: 0; background: rgba(8, 10, 16, .68); backdrop-filter: blur(4px); }+ .sk-panel {+ position: relative; max-width: 560px; width: min(92vw, 560px);+ margin: 4vh auto; background: var(--surface, #16181f); color: var(--text, #f1f2f6);+ border: 1px solid var(--border, rgba(255,255,255,.1)); border-radius: 16px;+ padding: 20px; display: flex; flex-direction: column; gap: 12px;+ box-shadow: 0 24px 60px rgba(0,0,0,.45);+ }+ .sk-header { display: flex; align-items: center; justify-content: space-between; }+ .sk-title { font-size: 1.05rem; font-weight: 650; margin: 0; }+ .sk-close { background: transparent; border: none; color: inherit; opacity: .7; cursor: pointer; padding: 4px; border-radius: 8px; }+ .sk-close:hover { opacity: 1; background: rgba(255,255,255,.08); }+ .sk-hint { font-size: .84rem; opacity: .68; margin: 0; line-height: 1.4; }+ .sk-stage { position: relative; align-self: center; border-radius: 12px; overflow: hidden; border: 1px solid rgba(255,255,255,.14); touch-action: none; }+ .sk-canvas { display: block; max-width: 100%; height: auto; cursor: crosshair; background: #fff; }+ .sk-empty-overlay {+ position: absolute; inset: 0; display: flex; align-items: center; justify-content: center;+ color: rgba(20,20,26,.32); font-size: .95rem; pointer-events: none; margin: 0; font-weight: 600;+ }+ .sk-empty-overlay.is-hidden { display: none; }+ .sk-toolbar { display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; }+ .sk-brushes, .sk-actions { display: flex; gap: 6px; }+ .sk-brush, .sk-tool-btn {+ background: rgba(255,255,255,.06); border: 1px solid rgba(255,255,255,.12); color: inherit;+ border-radius: 8px; padding: 6px 12px; font-size: .8rem; cursor: pointer; transition: background .15s ease;+ }+ .sk-brush:hover, .sk-tool-btn:hover:not(:disabled) { background: rgba(255,255,255,.14); }+ .sk-brush[aria-pressed='true'] { background: var(--accent, #6c8cff); border-color: var(--accent, #6c8cff); color: #0b0d14; }+ .sk-tool-btn:disabled { opacity: .35; cursor: not-allowed; }+ .sk-footer { display: flex; justify-content: flex-end; gap: 8px; margin-top: 4px; }+ .sk-btn { border-radius: 10px; padding: 9px 18px; font-size: .88rem; font-weight: 600; cursor: pointer; border: 1px solid transparent; }+ .sk-btn-ghost { background: transparent; border-color: rgba(255,255,255,.16); color: inherit; }+ .sk-btn-ghost:hover { background: rgba(255,255,255,.08); }+ .sk-btn-primary { background: var(--accent, #6c8cff); color: #0b0d14; }+ .sk-btn-primary:hover:not(:disabled) { filter: brightness(1.08); }+ .sk-btn-primary:disabled { opacity: .4; cursor: not-allowed; }+ @media (max-width: 480px) {+ .sk-panel { margin: 2vh auto; padding: 14px; }+ .sk-stage { width: 100%; }+ .sk-canvas { width: 100% !important; height: auto !important; }+ }+ `;+ document.head.appendChild(style);+}diff --git a/src/voice/prompt-dictation.js b/src/voice/prompt-dictation.jsnew file mode 100644index 000000000..7bdc2f6c3--- /dev/null+++ b/src/voice/prompt-dictation.js@@ -0,0 +1,300 @@+/**+ * Prompt Dictation — a reusable "speak instead of type" mic button for any+ * generation prompt textarea (Forge object/avatar prompts, Scene Studio,+ * sketch guidance, etc.). Voice → text, funneled into the SAME text prompt+ * the existing text→3D pipeline already consumes — no new generation path.+ *+ * Reuses the exact STT strategy already proven in src/voice/talk-controller.js+ * (the avatar talk loop): prefer the browser's native SpeechRecognition+ * (Chrome/Edge/Safari — zero round-trip, live interim captions), and fall back+ * to the free NVIDIA Riva lane (src/voice/mic-capture.js + POST /api/asr) for+ * browsers without it (Firefox). When NEITHER is available the mic button is+ * never rendered — no dead affordance, per platform convention.+ *+ * Privacy: nothing is written to disk or logged. The browser path streams+ * audio straight to the OS/browser recognizer per the Web Speech API and never+ * leaves the device for text recognition; the Riva fallback path streams the+ * captured WAV to /api/asr, which forwards it in-memory to NVIDIA's Riva gRPC+ * endpoint and returns only the transcript — the audio buffer is discarded+ * when the request completes (see api/asr.js) and is never written to+ * storage.+ *+ * Usage:+ * import { mountPromptDictation } from '../voice/prompt-dictation.js';+ * const dictation = mountPromptDictation(containerEl, textareaEl, { language: 'en-US' });+ * // ...+ * dictation.destroy(); // on teardown+ */++import { MicCapture } from './mic-capture.js';++let _asrProbe = null; // memoized capability probe — one network round trip per page load++function probeRivaConfigured() {+ if (_asrProbe) return _asrProbe;+ _asrProbe = fetch('/api/asr', { headers: { accept: 'application/json' } })+ .then((r) => (r.ok ? r.json() : { configured: false }))+ .then((j) => !!j?.configured)+ .catch(() => false);+ return _asrProbe;+}++/**+ * Mount a dictation mic button into `container`, wired to fill `textarea`.+ * Renders nothing (returns a no-op handle) when neither STT path is+ * available in this browser.+ *+ * @param {HTMLElement} container - where the mic button is appended+ * @param {HTMLTextAreaElement} textarea - the prompt field to dictate into+ * @param {{ language?: string, onError?: (msg:string)=>void }} [opts]+ * @returns {{ destroy(): void }}+ */+export function mountPromptDictation(container, textarea, opts = {}) {+ if (!container || !textarea) return { destroy() {} };+ const language = opts.language || 'en-US';++ const hasBrowserSR = !!(window.SpeechRecognition || window.webkitSpeechRecognition);+ const canCaptureRiva = MicCapture.isSupported();+ if (!hasBrowserSR && !canCaptureRiva) return { destroy() {} };++ injectStyles();++ const wrap = document.createElement('span');+ wrap.className = 'pd-wrap';+ wrap.innerHTML = `+ <button type="button" class="pd-mic" data-pd-mic aria-pressed="false" aria-label="Dictate this prompt by speaking">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">+ <rect x="9" y="2" width="6" height="12" rx="3"/>+ <path d="M5 10a7 7 0 0 0 14 0"/>+ <line x1="12" y1="19" x2="12" y2="22"/>+ </svg>+ </button>+ <span class="pd-status" data-pd-status aria-live="polite"></span>+ `;+ container.appendChild(wrap);++ const micBtn = wrap.querySelector('[data-pd-mic]');+ const statusEl = wrap.querySelector('[data-pd-status]');++ let state = 'idle'; // idle | listening | transcribing | error+ let recognizer = null;+ let mic = null;+ let statusTimer = null;+ let destroyed = false;++ function setState(next, message) {+ state = next;+ micBtn.dataset.state = next;+ micBtn.setAttribute('aria-pressed', String(next === 'listening'));+ clearTimeout(statusTimer);+ if (message) {+ statusEl.textContent = message;+ statusEl.dataset.tone = next === 'error' ? 'error' : 'info';+ if (next !== 'listening' && next !== 'transcribing') {+ statusTimer = setTimeout(() => {+ if (!destroyed) statusEl.textContent = '';+ }, 4000);+ }+ } else {+ statusEl.textContent = '';+ }+ }++ function insertTranscript(text) {+ const clean = text.trim();+ if (!clean) {+ setState('error', 'No speech detected — try again or type instead.');+ return;+ }+ const existing = textarea.value.trim();+ textarea.value = existing ? `${existing} ${clean}` : clean;+ textarea.dispatchEvent(new Event('input', { bubbles: true }));+ textarea.focus();+ setState('idle', 'Added to prompt.');+ }++ function startBrowser() {+ const RecCls = window.SpeechRecognition || window.webkitSpeechRecognition;+ const rec = new RecCls();+ rec.lang = language;+ rec.continuous = false;+ rec.interimResults = true;+ rec.maxAlternatives = 1;+ recognizer = rec;++ let finalText = '';+ rec.onresult = (e) => {+ let interim = '';+ for (let i = e.resultIndex; i < e.results.length; i++) {+ const res = e.results[i];+ if (res.isFinal) finalText += res[0].transcript;+ else interim += res[0].transcript;+ }+ if (interim) setState('listening', `“${interim}”`);+ };+ rec.onerror = (e) => {+ const kind = e.error || 'unknown';+ if (kind === 'no-speech' || kind === 'aborted') return; // benign end-of-hold+ if (kind === 'not-allowed' || kind === 'permission-denied') {+ setState('error', 'Microphone access was blocked. Allow the mic, or type instead.');+ } else {+ setState('error', `Speech recognition error (${kind}). Type instead.`);+ }+ };+ rec.onend = () => {+ recognizer = null;+ const transcript = finalText.trim();+ if (!transcript) {+ if (state === 'listening') setState('idle');+ return;+ }+ insertTranscript(transcript);+ };++ try {+ rec.start();+ setState('listening', 'Listening… tap to stop.');+ } catch (err) {+ setState('error', `Could not start the microphone: ${err.message}`);+ }+ }++ function stopBrowser() {+ try {+ recognizer?.stop();+ } catch {}+ }++ async function startRiva() {+ const m = new MicCapture();+ mic = m;+ setState('listening', 'Listening… tap to stop.');+ try {+ await m.start();+ if (mic !== m) {+ m.dispose();+ return;+ } // toggled off mid-permission-prompt+ } catch (err) {+ if (mic === m) mic = null;+ m.dispose();+ const messages = {+ 'permission-denied': 'Microphone access was blocked. Allow the mic, or type instead.',+ 'no-mic': 'No microphone found. Type instead.',+ unsupported: 'Voice input isn’t supported in this browser. Type instead.',+ };+ setState('error', messages[err.code] || `Could not start the microphone: ${err.message}`);+ return;+ }+ }++ async function stopRiva() {+ const m = mic;+ if (!m) return;+ mic = null;+ setState('transcribing', 'Transcribing…');+ const wav = await m.stop();+ m.dispose();+ if (!wav) {+ setState('error', 'No speech detected — try again or type instead.');+ return;+ }+ try {+ const res = await fetch(`/api/asr?language=${encodeURIComponent(language)}`, {+ method: 'POST',+ headers: { 'content-type': 'audio/wav' },+ body: wav,+ });+ if (!res.ok) {+ const msg =+ res.status === 503+ ? 'Speech-to-text is not available right now. Type instead.'+ : res.status === 429+ ? 'Too many voice requests — give it a moment.'+ : `Transcription failed (HTTP ${res.status}).`;+ setState('error', msg);+ return;+ }+ const data = await res.json().catch(() => ({}));+ insertTranscript(typeof data.text === 'string' ? data.text : '');+ } catch {+ setState('error', 'Network error during transcription. Type instead.');+ }+ }++ // Resolve the STT path once: browser SR wins when present (zero setup,+ // live captions); Riva is the cross-browser fallback, gated on the async+ // /api/asr capability probe so we never open a mic the server can't serve.+ let ready = hasBrowserSR ? Promise.resolve(true) : probeRivaConfigured();++ micBtn.addEventListener('click', async () => {+ if (state === 'listening') {+ if (hasBrowserSR) stopBrowser();+ else await stopRiva();+ return;+ }+ if (state === 'transcribing') return;+ setState('listening', 'Starting…');+ if (hasBrowserSR) {+ startBrowser();+ return;+ }+ const configured = await ready;+ if (destroyed) return;+ if (!configured) {+ setState('error', 'Voice input isn’t available here. Type instead.');+ return;+ }+ await startRiva();+ });++ return {+ destroy() {+ destroyed = true;+ clearTimeout(statusTimer);+ try {+ recognizer?.stop();+ } catch {}+ if (mic) {+ mic.dispose();+ mic = null;+ }+ wrap.remove();+ },+ };+}++let _stylesInjected = false;+function injectStyles() {+ if (_stylesInjected) return;+ _stylesInjected = true;+ const style = document.createElement('style');+ style.textContent = `+ .pd-wrap { display: inline-flex; align-items: center; gap: 8px; }+ .pd-mic {+ display: inline-flex; align-items: center; justify-content: center;+ width: 30px; height: 30px; border-radius: 999px; border: 1px solid var(--border, rgba(255,255,255,.14));+ background: rgba(255,255,255,.04); color: inherit; cursor: pointer; padding: 0;+ transition: background .15s ease, border-color .15s ease, color .15s ease;+ }+ .pd-mic svg { width: 15px; height: 15px; }+ .pd-mic:hover { background: rgba(255,255,255,.1); }+ .pd-mic:focus-visible { outline: 2px solid var(--accent, #6c8cff); outline-offset: 2px; }+ .pd-mic[data-state='listening'] {+ background: var(--danger, #ff5470); border-color: var(--danger, #ff5470); color: #fff;+ animation: pd-pulse 1.4s ease-in-out infinite;+ }+ .pd-mic[data-state='transcribing'] { background: var(--accent, #6c8cff); border-color: var(--accent, #6c8cff); color: #0b0d14; }+ .pd-mic[data-state='error'] { border-color: var(--danger, #ff5470); color: var(--danger, #ff5470); }+ @keyframes pd-pulse {+ 0%, 100% { box-shadow: 0 0 0 0 rgba(255,84,112,.45); }+ 50% { box-shadow: 0 0 0 6px rgba(255,84,112,0); }+ }+ .pd-status { font-size: .76rem; opacity: .72; max-width: 220px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+ .pd-status[data-tone='error'] { color: var(--danger, #ff5470); opacity: 1; }+ @media (prefers-reduced-motion: reduce) {+ .pd-mic[data-state='listening'] { animation: none; }+ }+ `;+ document.head.appendChild(style);+}