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
fix(daily): keep the i18n pass from reverting the live theme and make the modal keyboard-safe
nirholasc00abd83cc90
diff --git a/pages/daily.html b/pages/daily.htmlindex 9ab5d3c90..e986f2deb 100644--- a/pages/daily.html+++ b/pages/daily.html@@ -26,9 +26,11 @@<link rel="icon" type="image/svg+xml" href="/favicon.svg" /><link rel="apple-touch-icon" href="/apple-touch-icon.png" /><meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />- <!-- Meshopt decoder before <model-viewer> (Forge GLBs are meshopt-compressed). -->+ <!-- Meshopt decoder before <model-viewer> (Forge GLBs are meshopt-compressed).+ <model-viewer> itself is loaded by the bootstrap at the end of <body>, only+ once WebGL is confirmed: it builds a THREE.WebGLRenderer the moment it+ upgrades, which throws on a browser that has no WebGL context to give it. --><script src="/model-viewer-meshopt.js"></script>- <script type="module" src="https://cdn.jsdelivr.net/npm/@google/[email protected]/dist/model-viewer.min.js"></script><style>:root {--bg: #0b0c10; --ink: #ecedf2; --ink-dim: #9aa0af; --ink-faint: #6b7080;@@ -128,7 +130,7 @@.h { font-size: 15px; font-weight: 650; }.muted { color: var(--ink-dim); font-size: 13px; line-height: 1.5; max-width: 40ch; }.elapsed { font-variant-numeric: tabular-nums; color: var(--ink-faint); font-size: 12px; }- .actions { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; padding: 12px 14px; border-top: 1px solid var(--line); background: rgba(10,11,14,0.45); }+ .actions { position: relative; z-index: 2; display: flex; align-items: center; gap: 8px; flex-wrap: wrap; padding: 12px 14px; border-top: 1px solid var(--line); background: rgba(10,11,14,0.6); }.actions .meta { flex: 1 1 100%; color: var(--ink-dim); font-size: 12.5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }a.btn, button.btn {appearance: none; cursor: pointer; text-decoration: none; display: inline-flex; align-items: center; gap: 7px;@@ -158,6 +160,12 @@.milestone-card h3 { margin: 12px 0 6px; font-size: 22px; }.milestone-card p { margin: 0 0 16px; color: var(--ink-dim); font-size: 14px; line-height: 1.5; }+ :where(a, button, input, [tabindex]):focus-visible {+ outline: 2px solid color-mix(in srgb, var(--theme, var(--accent)) 85%, #fff);+ outline-offset: 2px; border-radius: 8px;+ }+ .ask input:focus-visible { outline: 2px solid color-mix(in srgb, var(--theme, var(--accent)) 85%, #fff); outline-offset: 0; }+footer.foot { border-top: 1px solid var(--line); padding: 14px 16px; text-align: center; color: var(--ink-faint); font-size: 12px; }footer.foot a { color: var(--ink-dim); }footer.foot a:hover { color: var(--ink); }@@ -258,10 +266,51 @@function webglSupported() {try { const c = document.createElement('canvas'); return !!(window.WebGLRenderingContext && (c.getContext('webgl') || c.getContext('experimental-webgl'))); } catch { return false; }}- if (webglSupported()) import('/src/daily.js');- else {+ // Loaded as a tag rather than a dynamic import so the bundler leaves the CDN+ // URL alone, and so a CDN outage is a rejected promise we can design for+ // instead of an unhandled module failure.+ function loadModelViewer() {+ return new Promise((resolve, reject) => {+ const el = document.createElement('script');+ el.type = 'module';+ el.src = 'https://cdn.jsdelivr.net/npm/@google/[email protected]/dist/model-viewer.min.js';+ el.onload = () => resolve();+ el.onerror = () => reject(new Error('model-viewer failed to load'));+ document.head.appendChild(el);+ });+ }++ if (webglSupported()) {+ // Whatever happens to the CDN, the page script boots: daily.js checks+ // whether <model-viewer> actually registered and hands over download and+ // AR links instead of a preview when it did not.+ const viewerReady = loadModelViewer().then(() => customElements.whenDefined('model-viewer')).catch(() => {});+ const cap = new Promise((resolve) => { setTimeout(resolve, 8000); });+ Promise.race([viewerReady, cap]).then(() => import('/src/daily.js'));+ } else {+ // No WebGL means no preview, but the day's theme is pure data and still+ // worth showing: without this the visitor sat on "Loading today's+ // challenge..." forever and never learned what the challenge was.+ import('/src/daily/daily-theme.js').then(({ themeForDate }) => {+ const theme = themeForDate(new Date());+ document.documentElement.style.setProperty('--theme', theme.accent);+ const own = (el) => { if (el) el.setAttribute('data-i18n-owned', '1'); return el; };+ own(document.querySelector('.theme h1'));+ own(document.getElementById('theme-day')).textContent = `Day ${theme.day} · Daily challenge`;+ document.getElementById('theme-emoji').textContent = theme.emoji;+ document.getElementById('theme-title').textContent = theme.title;+ own(document.getElementById('theme-hint')).textContent = theme.hint;+ own(document.querySelector('title'));+ document.title = `${theme.emoji} ${theme.title} · Daily Forge · three.ws`;+ const input = document.getElementById('prompt');+ if (input) input.placeholder = `Your take on "${theme.title}"…`;+ }).catch(() => {});+ const form = document.getElementById('ask');+ if (form) form.addEventListener('submit', (e) => e.preventDefault());+ const go = document.getElementById('go');+ if (go) { go.disabled = true; go.title = 'Forging needs a browser that can render 3D.'; }const s = document.getElementById('idle');- if (s) s.innerHTML = '<div class="idleart">🛰️</div><div class="h">This browser can’t render 3D</div><div class="muted">Reopen Daily Forge in an up-to-date Chrome or Safari to join today’s challenge.</div>';+ if (s) s.innerHTML = '<div class="idleart">🛰️</div><div class="h">This browser can’t render 3D</div><div class="muted">Daily Forge needs WebGL to show your model. Reopen this page in an up-to-date Chrome, Edge, Firefox, or Safari to join today’s challenge.</div>';}</script><!-- Runtime i18n: detects locale, swaps annotated copy, mounts <lang-switcher>. -->diff --git a/src/daily.js b/src/daily.jsindex 3586b6550..08cf87196 100644--- a/src/daily.js+++ b/src/daily.js@@ -22,6 +22,22 @@ const log = createLogger('daily');const $ = (id) => document.getElementById(id);const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));+// The day's theme is live data, not copy. src/i18n.js applies its catalog after+// an async /api/locale fetch, which lands well after this module renders, so an+// annotated element it still owns gets reverted to its pre-render placeholder+// ("Today's theme", "Loading today's challenge…"). Claiming the element with+// data-i18n-owned="1" before writing is the platform-wide opt-out.+const own = (el) => { el?.setAttribute?.('data-i18n-owned', '1'); return el; };++// Copy this module writes itself still has to localize. The catalog is loaded by+// the time a user acts; a miss echoes the key back, so fall through to English.+function i18nText(key, fallback) {+ try {+ const v = window.threewsI18n?.t?.(key);+ return v && v !== key ? v : fallback;+ } catch { return fallback; }+}+const RECENT_KEY = 'twx_ar_forge_recent'; // shared with /ar + AR Studioconst POLL_MS = 3000;const MAX_POLL_MS = 300000;@@ -42,10 +58,14 @@ const theme = themeForDate(new Date());// ── Render the day ─────────────────────────────────────────────────────────────document.documentElement.style.setProperty('--theme', theme.accent);-$('theme-day').textContent = `Day ${theme.day} · Daily challenge`;+own($('theme-day')).textContent = `Day ${theme.day} · Daily challenge`;+// The <h1> itself carries data-i18n-html, so an unowned catalog pass replaces its+// innerHTML wholesale and takes the emoji and title spans with it.+own(document.querySelector('.theme h1'));$('theme-emoji').textContent = theme.emoji;$('theme-title').textContent = theme.title;-$('theme-hint').textContent = theme.hint;+own($('theme-hint')).textContent = theme.hint;+own(document.querySelector('title'));document.title = `${theme.emoji} ${theme.title} · Daily Forge · three.ws`;const input = $('prompt');@@ -98,18 +118,35 @@ function bumpStreak() {if (milestone) celebrate(milestone, state.current);}+let milestoneReturnFocus = null;function celebrate(milestone, current) {const emoji = milestone >= 100 ? '👑' : milestone >= 30 ? '🌟' : milestone >= 7 ? '🔥' : '✨';$('ms-emoji').textContent = emoji;- $('ms-title').textContent = `${milestone}-day streak!`;- $('ms-body').textContent = milestone >= 30- ? `${current} days of daily creation. You're a machine — keep the flame burning.`+ own($('ms-title')).textContent = `${milestone}-day streak!`;+ own($('ms-body')).textContent = milestone >= 30+ ? `${current} days of daily creation. You are a machine, keep the flame burning.`: `You've forged something ${milestone} days running. That's a real habit forming.`;$('milestone').classList.remove('hidden');+ milestoneReturnFocus = document.activeElement;+ $('ms-close').focus();try { navigator.vibrate?.([12, 40, 12]); } catch {}}-$('ms-close').addEventListener('click', () => $('milestone').classList.add('hidden'));-$('milestone').addEventListener('click', (e) => { if (e.target === $('milestone')) $('milestone').classList.add('hidden'); });+function closeMilestone() {+ if ($('milestone').classList.contains('hidden')) return;+ $('milestone').classList.add('hidden');+ const back = milestoneReturnFocus;+ milestoneReturnFocus = null;+ if (back && document.contains(back)) back.focus();+}+$('ms-close').addEventListener('click', closeMilestone);+$('milestone').addEventListener('click', (e) => { if (e.target === $('milestone')) closeMilestone(); });+// A modal dialog that only closes by mouse strands a keyboard visitor: Escape+// dismisses it, and Tab stays inside it (the card holds a single control).+document.addEventListener('keydown', (e) => {+ if ($('milestone').classList.contains('hidden')) return;+ if (e.key === 'Escape') { e.preventDefault(); closeMilestone(); }+ else if (e.key === 'Tab') { e.preventDefault(); $('ms-close').focus(); }+});// ── Forge flow (free NVIDIA lane) ──────────────────────────────────────────────const mv = $('mv');@@ -122,9 +159,9 @@ function overlay(el) {if (el) $(el).classList.remove('hidden');}function setBusy(b) {- const go = $('go');+ const go = own($('go'));go.disabled = b;- go.innerHTML = b ? 'Forging…' : 'Forge<span aria-hidden="true">✦</span>';+ go.innerHTML = b ? `${esc(i18nText('daily.forging', 'Forging…'))}` : i18nText('daily.forge', 'Forge<span aria-hidden="true">✦</span>');}function startElapsed() {const t0 = Date.now();@@ -132,7 +169,16 @@ function startElapsed() {elapsedTimer = setInterval(() => { $('elapsed').textContent = `${Math.round((Date.now() - t0) / 1000)}s`; }, 1000);}function stopElapsed() { if (elapsedTimer) { clearInterval(elapsedTimer); elapsedTimer = null; } $('elapsed').textContent = ''; }-function isHttps(u) { try { return new URL(u).protocol === 'https:'; } catch { return false; } }+// A model link is safe to load if it is absolute https or a same-origin path.+// Requiring absolute https rejected the same-origin /r2-proxy/... links the dev+// server rewrites R2 assets to, which silently emptied the community rail.+function safeModelUrl(u) {+ try {+ const parsed = new URL(String(u), location.href);+ if (parsed.protocol === 'https:' || parsed.origin === location.origin) return parsed.href;+ return '';+ } catch { return ''; }+}async function forge(prompt) {prompt = String(prompt || '').trim();@@ -174,11 +220,22 @@ async function forge(prompt) {if (seq !== runSeq) return;stopElapsed();setBusy(false);- $('failmsg').textContent = (err && err.message) || 'Generation failed.';+ $('failmsg').textContent = friendlyError(err);overlay('failed');}}+// A thrown fetch surfaces as "Failed to fetch"/"NetworkError", which tells a+// visitor nothing and no action. Everything this module throws itself is already+// written for a human, so only the transport failures need translating.+function friendlyError(err) {+ const raw = (err && err.message) || '';+ if (!raw || /failed to fetch|networkerror|network request failed|load failed/i.test(raw)) {+ return 'Could not reach the forge. Check your connection, then try again.';+ }+ return raw;+}+async function pollUntilDone(jobId, seq) {const deadline = Date.now() + MAX_POLL_MS;for (;;) {@@ -186,7 +243,8 @@ async function pollUntilDone(jobId, seq) {if (Date.now() > deadline) throw new Error('Generation timed out. Try a simpler, single-object prompt.');await new Promise((r) => setTimeout(r, POLL_MS));if (seq !== runSeq) return null;- const res = await fetch(`/api/forge?job=${encodeURIComponent(jobId)}`, { headers: { 'x-forge-client': CLIENT_ID } });+ const res = await fetch(`/api/forge?job=${encodeURIComponent(jobId)}`, { headers: { 'x-forge-client': CLIENT_ID } })+ .catch(() => { throw new Error('Lost contact with the forge while it was working. Your creation may still finish, try again in a moment.'); });const data = await res.json().catch(() => ({}));if (data.status === 'done' && data.glb_url) return data;if (data.status === 'failed') throw new Error(data.error || 'Generation failed. Try rephrasing the prompt.');@@ -195,39 +253,60 @@ async function pollUntilDone(jobId, seq) {}function showResult(glbUrl, prompt, { forged = true } = {}) {- if (!isHttps(glbUrl)) { $('failmsg').textContent = 'The forge returned an invalid model link.'; overlay('failed'); setBusy(false); return; }- current = { glb: glbUrl, prompt, forged };+ const src = safeModelUrl(glbUrl);+ if (!src) { $('failmsg').textContent = 'That model link is not one we can open. Forge a new one to continue.'; overlay('failed'); setBusy(false); return; }+ current = { glb: src, prompt, forged };overlay('working');$('worktitle').textContent = 'Loading your creation…';$('workmsg').textContent = 'Almost there.';+ if (!window.customElements?.get('model-viewer')) {+ previewUnavailable('The 3D preview could not load. Your model is ready below: download it or open it in AR.');+ return;+ }mv.setAttribute('alt', prompt ? `3D model: ${prompt}` : 'Your 3D creation');- mv.setAttribute('src', glbUrl);+ mv.setAttribute('src', src);}-mv.addEventListener('load', () => {- if (!current || mv.getAttribute('src') !== current.glb) return;- overlay(null);- setBusy(false);- mv.classList.remove('veiled');- $('actions').classList.remove('hidden');+// Reveal the action bar with every link resolved. Both the success path and the+// preview-failed path run this: the failure copy tells the visitor to download+// the GLB, so its href has to be live there too, and an <a> with no href is not+// even keyboard reachable.+function wireActions() {$('meta').textContent = current.prompt || 'Your creation';$('meta').title = current.prompt || '';$('download').href = current.glb;$('download').setAttribute('download', `${fileName(current.prompt)}.glb`);$('studio-btn').href = `/ar/studio?src=${encodeURIComponent(current.glb)}&title=${encodeURIComponent((current.prompt || '').slice(0, 80))}`;- if (mv.canActivateAR) $('ar-btn').textContent = '📱 View in your room';- else $('ar-btn').textContent = '📱 Open AR on your phone';+ own($('ar-btn')).textContent = mv.canActivateAR+ ? i18nText('daily.view_in_your_room', '📱 View in your room')+ : '📱 Open AR on your phone';+ $('actions').classList.remove('hidden');+}++// The creation is real even when the preview is not: a model-viewer that never+// registered (CDN outage) or a GLB the renderer rejects still leaves a usable+// GLB, so hand over the links rather than stranding the visitor on a spinner.+function previewUnavailable(msg) {+ setBusy(false);+ $('failmsg').textContent = msg;+ overlay('failed');+ wireActions();+ if (current?.forged) bumpStreak();+}++mv.addEventListener('load', () => {+ if (!current || mv.getAttribute('src') !== current.glb) return;+ overlay(null);+ setBusy(false);+ mv.classList.remove('veiled');+ wireActions();// The creation itself is the qualifying action — light the streak now (but not// for a deep-linked model the viewer didn't forge themselves).if (current.forged) bumpStreak();});mv.addEventListener('error', () => {if (!current) return;- setBusy(false);- $('failmsg').textContent = 'The model was generated but could not be displayed. You can still download the GLB.';- overlay('failed');- $('actions').classList.remove('hidden');- if (current.forged) bumpStreak(); // a real generation happened even if the preview failed+ previewUnavailable('The model was generated but could not be displayed. You can still download the GLB below.');});function arLink() {@@ -268,11 +347,13 @@ $('ask').addEventListener('submit', (e) => { e.preventDefault(); forge(input.val(async function loadCommunity() {try {const res = await fetch('/api/forge-gallery?scope=community&limit=12');- if (!res.ok) return;+ // The strip is a bonus, never a blocker: a gallery outage leaves the section+ // unrendered rather than showing a broken shelf, and the page still forges.+ if (!res.ok) { log.warn('community gallery returned', res.status); return; }const data = await res.json();const items = (data.creations || [])- .map((c) => ({ src: c.glb_url || c.glbUrl || '', title: c.prompt || c.title || '', poster: c.preview_image_url || c.previewImageUrl || '' }))- .filter((c) => c.src && isHttps(c.src))+ .map((c) => ({ src: safeModelUrl(c.glb_url || c.glbUrl || ''), title: c.prompt || c.title || '', poster: c.preview_image_url || c.previewImageUrl || '' }))+ .filter((c) => c.src).slice(0, 12);if (!items.length) return;const rail = $('rail');@@ -289,5 +370,14 @@ $('ask').addEventListener('submit', (e) => { e.preventDefault(); forge(input.val(function fromQuery() {const q = new URLSearchParams(location.search);const src = q.get('src') || '';- if (src && isHttps(src)) showResult(src, q.get('title') || q.get('prompt') || 'Shared creation', { forged: false });+ if (!src) return;+ if (safeModelUrl(src)) showResult(src, q.get('title') || q.get('prompt') || 'Shared creation', { forged: false });+ else { $('failmsg').textContent = 'That shared model link is not one we can open. Forge today’s theme instead.'; overlay('failed'); }})();++// Re-render the labels this module owns when the visitor switches locale: an+// owned element is skipped by the catalog pass, so it has to refresh itself.+window.addEventListener('i18n:change', () => {+ if (!$('go').disabled) setBusy(false);+ if (!$('actions').classList.contains('hidden')) wireActions();+});