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(constellation): widen the pick target so a node is hittable on a phone
nirholas42ed4b66e24c
diff --git a/api/_lib/clip-director.js b/api/_lib/clip-director.jsindex 4c6ddbf2b..cf1183a82 100644--- a/api/_lib/clip-director.js+++ b/api/_lib/clip-director.js@@ -42,7 +42,7 @@ Output STRICT JSON only, no prose, no code fence:"cta": "fork-this-trade|copy-the-agent|view-track-record","alt_text": "accessibility description of the card" }-Rules: feature the real number. If the trade was a LOSS, still produce an honest card (brand = transparency) with a 'live to trade again' tone. Tune length/voice to the surface (X punchier, Telegram chattier, Feed mid). Reference no token other than the traded one or $THREE. Always keep a verifiable angle (the record is on-chain). Never invent numbers not present in the input.`;+Rules: feature the real number. If the trade was a LOSS, still produce an honest card (brand = transparency) with a 'live to trade again' tone. Tune length/voice to the surface (X punchier, Telegram chattier, Feed mid). Name NO ticker other than the traded one. Always keep a verifiable angle (the record is on-chain). State NO number that is not in the input: every figure you write is machine-checked against the trade, and a card that states a ticker or a number the trade does not contain is discarded.`;// Build the compact, real trade view the director reasons over. Accepts a raw// agent_sniper_positions row (or an equivalent object) and derives only from@@ -83,8 +83,13 @@ export async function directClip({ agentName, avatarStyle = null, trade, copiedBif (llmConfigured()) {try {- artifact = await llmClip({ agentName, avatarStyle, trade, copiedByCount, surface: surf, userId });- if (artifact) source = 'llm';+ const written = await llmClip({ agentName, avatarStyle, trade, copiedByCount, surface: surf, userId });+ // The model writes the voice, never the facts. An artifact that states a+ // ticker or a figure the trade does not contain is discarded outright.+ if (written && isGrounded(written, trade, copiedByCount)) {+ artifact = written;+ source = 'llm';+ }} catch (err) {if (!(err instanceof LlmUnavailableError)) artifact = null;}@@ -125,6 +130,80 @@ async function llmClip({ agentName, avatarStyle, trade, copiedByCount, surface,return parsed;}+// ---------------------------------------------------------------------------+// Grounding: the one guarantee this page sells is "the real number, never a+// screenshot", so a generated card is checked against the trade it claims to+// describe before it is allowed out. This is not hypothetical: a provider in the+// chain answered a real +1.89x win on one coin with "-8.2% realized loss" on a+// completely different ticker, gesture "celebrate", every word fluent and every+// fact invented. Nothing downstream could have caught that. An artifact that+// names a foreign ticker or states a figure absent from the trade is rejected+// and the deterministic director answers instead.+// ---------------------------------------------------------------------------++/** @returns {string} the trade's ticker, no leading $, uppercase. */+function tickerOf(trade) {+ const sym = trade.symbol || trade.name || (trade.mint ? trade.mint.slice(0, 4) : '');+ return String(sym).replace(/^\$/, '').toUpperCase();+}++// Same rounding the API renders with, so "1.89" written by the model matches the+// 1.89 the card shows rather than a raw 1.8899999.+const normNum = (n) => String(Math.round(n * 100) / 100);++function groundedNumbers(trade, copiedByCount) {+ const ok = new Set();+ const add = (n) => {+ if (n == null || !Number.isFinite(Number(n))) return;+ const v = Number(n);+ ok.add(normNum(v));+ ok.add(normNum(Math.abs(v)));+ ok.add(normNum(Math.round(v)));+ };+ add(trade.multiple);+ add(trade.pnl_pct);+ add(trade.entry_sol);+ add(trade.exit_sol);+ add(trade.realized_pnl_sol);+ add(trade.hold_min);+ // holdLabel renders the same duration in minutes, hours, or days; all three+ // readings are the same real fact.+ if (trade.hold_min != null && Number.isFinite(Number(trade.hold_min))) {+ add(Math.round(Number(trade.hold_min) / 60));+ add(Math.round(Number(trade.hold_min) / 1440));+ }+ add(copiedByCount);+ return ok;+}++/**+ * Does every ticker and every number in the copy trace to this trade?+ * @param {object} artifact the parsed LLM artifact+ * @param {object} trade the real closed round-trip+ * @param {number} copiedByCount follower count, the one non-trade figure allowed+ * @returns {boolean}+ */+export function isGrounded(artifact, trade, copiedByCount = 0) {+ const copy = [artifact.hook, artifact.feature_stat, artifact.body, artifact.alt_text]+ .filter((s) => typeof s === 'string').join(' ');+ if (!copy.trim()) return false;++ const allowedTickers = new Set([tickerOf(trade), String(trade.symbol || '').toUpperCase(), String(trade.name || '').toUpperCase()]+ .filter(Boolean).map((t) => t.replace(/^\$/, '')));+ for (const m of copy.matchAll(/\$([A-Za-z][A-Za-z0-9_]*)/g)) {+ if (!allowedTickers.has(m[1].toUpperCase())) return false;+ }++ // Tickers are stripped first so a symbol like $W3B does not read as the+ // number 3, and "SOL" style unit words carry no digits to begin with.+ const numbers = copy.replace(/\$[A-Za-z][A-Za-z0-9_]*/g, ' ').matchAll(/-?\d+(?:\.\d+)?/g);+ const allowed = groundedNumbers(trade, copiedByCount);+ for (const m of numbers) {+ if (!allowed.has(normNum(Number(m[0])))) return false;+ }+ return true;+}+// Deterministic director, honest, surface-tuned copy from the real numbers.function deterministicClip({ agentName, trade, copiedByCount, surface }) {const sym = trade.symbol || trade.name || (trade.mint ? `$${trade.mint.slice(0, 4).toUpperCase()}` : 'the coin');@@ -184,8 +263,16 @@ function trimReason(reason) {const VALID_CTA = new Set(['fork-this-trade', 'copy-the-agent', 'view-track-record']);+// A gesture pointing the wrong way (celebrating a loss) reads as sarcasm at best+// and a bug at worst, so the reaction is constrained to the direction the trade+// actually went rather than trusted from the writer.+const LOSS_GESTURES = new Set(['sweat', 'shrug']);+const WIN_GESTURES = new Set(['celebrate', 'point', 'wave']);+function finalize({ artifact, source, trade, surface }) {- const gesture = GESTURES.includes(artifact.avatar_gesture) ? artifact.avatar_gesture : (trade.is_win === false ? 'sweat' : 'celebrate');+ const asked = GESTURES.includes(artifact.avatar_gesture) ? artifact.avatar_gesture : null;+ const allowed = trade.is_win === false ? LOSS_GESTURES : WIN_GESTURES;+ const gesture = asked && allowed.has(asked) ? asked : (trade.is_win === false ? 'sweat' : 'celebrate');const cta = VALID_CTA.has(artifact.cta) ? artifact.cta : (trade.is_win === false ? 'view-track-record' : 'copy-the-agent');return {source,diff --git a/api/_providers/nvidia-cosmos.js b/api/_providers/nvidia-cosmos.jsindex e7e43829a..4468f7240 100644--- a/api/_providers/nvidia-cosmos.js+++ b/api/_providers/nvidia-cosmos.js@@ -48,7 +48,10 @@//// Error codes match the established provider contract (nvidia.js / replicate.js):// provider_unreachable / invalid_key / insufficient_credits / rate_limited /-// provider_error — so callers can route around a dead/limited lane.+// provider_error, so callers can route around a dead/limited lane. One code is+// specific to this lane: lane_unavailable, raised when NVIDIA has retired every+// hosted cosmos-predict route this account can reach (see the route chain+// below), so the caller degrades instead of offering a pointless retry.import { env } from '../_lib/env.js';diff --git a/api/avatar/video-generate.js b/api/avatar/video-generate.jsindex 7dc226221..07d6f5929 100644--- a/api/avatar/video-generate.js+++ b/api/avatar/video-generate.js@@ -9,12 +9,18 @@// image_url string — publicly accessible reference image (PNG/JPG)// audio_url string — publicly accessible audio file (WAV/MP3)// prompt string? — optional text description-// avatar_id string? — three.ws avatar id; resolved to a render URL-// when image_url is not supplied+// avatar_id string? three.ws avatar id, resolved to a reference image+// when image_url is not supplied//// Response 202:// { job_id, status: "queued" }//+// GET returns an availability document instead of a job:+// { endpoint, available, reason, free_generations }+// so a client can tell a visitor the renderer is offline BEFORE it walks them+// through uploading audio. Without it the only signal was a 503 raised after+// the upload had already happened.+//// Errors:// 400 invalid_request - missing required fields// 402 free_trial_used - free user has already used their 1 free generation@@ -24,9 +30,14 @@import { cors, error, json, wrap, rateLimited } from '../_lib/http.js';import { limits } from '../_lib/rate-limit.js';import { sql } from '../_lib/db.js';-import { publicUrl } from '../_lib/r2.js';+import { publicUrl, thumbnailUrl } from '../_lib/r2.js';import { getSessionUser } from '../_lib/auth.js';import { env } from '../_lib/env.js';+import { resolveRenderParams, renderAvatarImage } from '../_lib/avatar-render.js';++// Rendering a fresh reference image runs headless chromium, so this handler can+// legitimately outrun the 10 s default on a first-time avatar.+export const maxDuration = 60;// Mirror of trustedOrigin() in api/avatar/optimize.js: image_url/audio_url are// forwarded to the LongCat worker, which fetches them server-side. Restrict them@@ -68,6 +79,20 @@ function workerConfig() {return { url: url.replace(/\/$/, ''), key };}+// The worker writes whatever this resolves to straight into `ref_image.png` and+// hands it to inference as `cond_image`, so it has to be an actual raster image.+// Returning the avatar's GLB (which is what this did) produced a job that always+// failed deep inside the worker, minutes after the caller was told "queued".+// Order: the stored thumbnail if one exists, otherwise a portrait render through+// the same cached pipeline /api/avatar/render uses, so the second video from an+// avatar costs a HEAD instead of a chromium launch.+const REFERENCE_RENDER = resolveRenderParams({+ scene: 'portrait',+ size: '768',+ bg: '#101010',+ format: 'png',+}).params;+async function resolveImageUrl(avatarId, requesterId) {if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(String(avatarId || ''))) {throw Object.assign(new Error('avatar not found'), { code: 'avatar_not_found', status: 404 });@@ -76,7 +101,7 @@ async function resolveImageUrl(avatarId, requesterId) {// avatar they own or one that is public/unlisted — never another user's// private avatar. (Previously resolved by id alone — an IDOR.)const rows = await sql`- select storage_key from avatars+ select id, storage_key, thumbnail_key, updated_at from avatarswhere id = ${avatarId} and deleted_at is nulland (owner_id = ${requesterId} or visibility in ('public', 'unlisted'))limit 1@@ -86,11 +111,53 @@ async function resolveImageUrl(avatarId, requesterId) {code: 'avatar_not_found',status: 404,});- return publicUrl(rows[0].storage_key);++ const stored = thumbnailUrl(rows[0].thumbnail_key);+ if (stored) return stored;++ try {+ const out = await renderAvatarImage({+ avatar: { id: rows[0].id, updated_at: rows[0].updated_at },+ glbUrl: publicUrl(rows[0].storage_key),+ params: REFERENCE_RENDER,+ awaitUpload: true,+ });+ return out.imageUrl;+ } catch (err) {+ console.error('[video-generate] reference render failed:', err?.message || err);+ throw Object.assign(+ new Error('Could not render a reference image for this avatar. Give it a thumbnail and try again.'),+ { code: 'reference_image_failed', status: 502 },+ );+ }}export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;++ if (req.method === 'GET') {+ const configured = workerConfig() !== null;+ return json(+ res,+ 200,+ {+ endpoint: 'POST /api/avatar/video-generate',+ description:+ 'Render a talking-head video from a three.ws avatar and a spoken audio clip.',+ available: configured,+ reason: configured ? 'ready' : 'worker_unconfigured',+ free_generations: 1,+ accepts: {+ avatar_id: 'three.ws avatar UUID; resolved server-side to a reference image',+ image_url: 'https URL on a three.ws host, used instead of avatar_id',+ audio_url: 'https URL on a three.ws host (WAV/MP3/M4A)',+ prompt: 'optional scene description',+ },+ },+ { 'cache-control': 'no-store' },+ );+ }+if (req.method !== 'POST')return error(res, 405, 'method_not_allowed', `method ${req.method} not allowed`);diff --git a/api/cosmos.js b/api/cosmos.jsindex 65f09f133..f517a2eb6 100644--- a/api/cosmos.js+++ b/api/cosmos.js@@ -18,6 +18,10 @@** Reuses the platform NVIDIA_API_KEY (free NIM tier). When it is absent the lane* reports itself unconfigured (503) and the page degrades to a static backdrop.+ * The same 503 shape (error:'lane_unavailable') answers the case where the key is+ * present but NVIDIA has retired every hosted cosmos-predict route this account+ * can reach, so the page lands in the same designed offline state instead of+ * asking the user to retry something that cannot succeed.*/import { cors, json, method, readJson, wrap, rateLimited } from './_lib/http.js';@@ -39,6 +43,31 @@ function unconfigured(res) {});}+// User-facing copy per normalized provider code. The upstream detail is operator+// diagnostics (it has carried NVCF function ids and the account id) and is logged,+// never returned: a caller can act on "the lane is down", not on a function uuid.+const FAILURE_COPY = {+ lane_unavailable:+ 'NVIDIA Cosmos world generation is offline right now. Your avatar keeps its living backdrop above; ' ++ 'check back soon for generated worlds.',+ invalid_key: 'The Cosmos lane rejected this deployment’s NVIDIA credentials. An operator needs to refresh the key.',+ insufficient_credits: 'The Cosmos lane is out of NVIDIA credits for now.',+ rate_limited: 'NVIDIA Cosmos is rate limiting right now.',+ provider_unreachable: 'NVIDIA Cosmos did not answer. Try again in a moment.',+ provider_error: 'Cosmos could not start this world. Try again, or try a simpler prompt.',+};++function failureResponse(res, err) {+ const code = FAILURE_COPY[err?.code] ? err.code : 'provider_error';+ const status = code === 'lane_unavailable' ? 503 : code === 'rate_limited' ? 429 : code === 'invalid_key' ? 401 : code === 'insufficient_credits' ? 402 : 502;+ console.warn('[cosmos] submit failed (%s/%s): %s', code, err?.providerStatus ?? '-', err?.message || 'no detail');+ return json(res, status, {+ error: code,+ message: FAILURE_COPY[code],+ ...(err?.retryAfter ? { retry_after: err.retryAfter } : {}),+ });+}+async function startJob(req, res) {const rl = await limits.mcp3dGenerate(clientIp(req));if (!rl.success) return rateLimited(res, rl);@@ -74,12 +103,7 @@ async function startJob(req, res) {eta_seconds: ETA_SECONDS,});} catch (err) {- const status = err?.code === 'rate_limited' ? 429 : err?.code === 'invalid_key' ? 401 : 502;- return json(res, status, {- error: err?.code || 'cosmos_failed',- message: err?.message || 'Cosmos world generation could not start.',- ...(err?.retryAfter ? { retry_after: err.retryAfter } : {}),- });+ return failureResponse(res, err);}}@@ -101,11 +125,15 @@ async function pollJob(req, res, jobId) {}const result = await provider.status({ taskId: jobId });+ // The provider's `error` is operator diagnostics on both the running and failed+ // paths (upstream statuses, persist failures). Log it, hand the caller a stable+ // sentence it can render, and never echo it while the job is still alive.+ if (result.error) console.warn('[cosmos] poll %s (%s): %s', jobId, result.status, result.error);return json(res, 200, {job_id: jobId,status: result.status,video_url: result.resultVideoUrl || null,- error: result.error || null,+ error: result.status === 'failed' ? 'Cosmos could not finish this world. Try again, or try a different prompt.' : null,});}diff --git a/pages/concierge.html b/pages/concierge.htmlindex 72c1347d4..3dcbf55f7 100644--- a/pages/concierge.html+++ b/pages/concierge.html@@ -75,14 +75,16 @@max-width: 1080px;margin: 0 auto;padding: 0 var(--space-md);- /* body is display:flex site-wide, so this main is a flex item and- inherits min-width:auto. Its min-content size is set by the- longest unbreakable line in the install <pre>, which pushed the- whole column to ~609px inside a 320px viewport; mobile.css clips- horizontal overflow, so that content was cut off with no way to- scroll to it. min-width:0 lets the column shrink and hands the- scrolling back to the <pre>, which is built for it. */- min-width: 0;+ /* body is display:flex (column) site-wide, so this main is a flex+ item whose auto width resolves against the min-content of the+ longest unbreakable line in the install <pre>. That pushed the+ column to ~609px inside a 320px viewport, and mobile.css clips+ horizontal overflow, so the copy was cut off with no way to+ scroll to it. An explicit width makes the cross size definite,+ which caps the column at the viewport and hands the scrolling+ back to the <pre>, which is built for it. box-sizing is+ border-box, so the padding above stays inside the viewport. */+ width: 100%;}.cl-hero {padding: calc(var(--space-xl) * 2) 0 var(--space-xl);diff --git a/pages/constellation.html b/pages/constellation.htmlindex dc37b3b7d..f3ecbfae5 100644--- a/pages/constellation.html+++ b/pages/constellation.html@@ -164,7 +164,8 @@<div class="c-overlay" id="c-overlay"><div class="c-spinner" id="c-spinner"></div>- <div class="msg" id="c-overlay-msg"><strong data-i18n="constellation.loading_the_constellation">Loading the constellation…</strong><br/>Fetching live trending tokens.</div>+ <div class="msg" id="c-overlay-msg" role="status" aria-live="polite"><strong data-i18n="constellation.loading_the_constellation">Loading the constellation…</strong><br/>Fetching live trending tokens.</div>+ <button class="c-retry" id="c-retry" hidden>Try again</button></div><script type="module" src="/src/constellation/main.js"></script>diff --git a/pages/create/video.html b/pages/create/video.htmlindex c02ffabe4..be1ec8bfd 100644--- a/pages/create/video.html+++ b/pages/create/video.html@@ -307,6 +307,7 @@.avatar-thumb {width: 48px;height: 48px;+ padding: 0;border-radius: 10px;border: 2px solid var(--border);overflow: hidden;@@ -316,6 +317,9 @@transition: border-color 0.15s;position: relative;}+ .avatar-thumb:hover {+ border-color: #3a3a3a;+ }.avatar-thumb.is-selected {border-color: var(--accent);}@@ -341,6 +345,85 @@font-size: 12px;padding: 4px 0;}+ /* Empty ("no avatars yet") and failed ("could not load them") states+ for the selector strip. Both replace the strip's contents, so they+ lay out as a full-width row rather than another thumbnail. */+ .avatar-bar-note {+ display: none;+ align-items: center;+ gap: 10px;+ width: 100%;+ font-size: 12.5px;+ color: var(--muted);+ line-height: 1.4;+ }+ .avatar-bar-note.is-visible {+ display: flex;+ }+ .avatar-bar-note .note-text {+ flex: 1;+ min-width: 0;+ }+ .avatar-bar-note .note-action {+ flex-shrink: 0;+ padding: 6px 12px;+ border-radius: 8px;+ background: rgba(255, 255, 255, 0.06);+ border: 1px solid var(--border);+ color: var(--text);+ font: inherit;+ font-size: 12px;+ font-weight: 500;+ text-decoration: none;+ cursor: pointer;+ white-space: nowrap;+ transition:+ background 0.15s,+ border-color 0.15s;+ }+ .avatar-bar-note .note-action:hover {+ background: rgba(255, 255, 255, 0.1);+ border-color: #2e2e2e;+ }++ /* Renderer-offline banner: the generation worker is a separate GPU+ service, and when it is not configured on a deployment there is no+ point walking a visitor through an upload that can only 503. */+ .offline-banner {+ display: none;+ gap: 12px;+ align-items: flex-start;+ padding: 14px 16px;+ margin-bottom: 20px;+ border-radius: 12px;+ border: 1px solid rgba(255, 176, 92, 0.3);+ background: rgba(255, 176, 92, 0.07);+ font-size: 13px;+ line-height: 1.5;+ }+ .offline-banner.is-visible {+ display: flex;+ }+ .offline-banner svg {+ width: 18px;+ height: 18px;+ flex-shrink: 0;+ margin-top: 1px;+ color: #ffb05c;+ }+ .offline-banner strong {+ display: block;+ margin-bottom: 3px;+ color: #ffcf9e;+ font-weight: 600;+ }+ .offline-banner p {+ margin: 0;+ color: var(--muted);+ }+ .offline-banner a {+ color: var(--text);+ }/* ── Right: controls ────────────────────────────────────────── */.controls-panel {diff --git a/src/coin3d/main.js b/src/coin3d/main.jsindex e40780c71..9c6db34c6 100644--- a/src/coin3d/main.js+++ b/src/coin3d/main.js@@ -95,20 +95,23 @@ async function mcpCall(name, args = {}, timeoutMs = 15_000) {return env.result?.structuredContent ?? null;}-// Pull the core data sources in parallel. Holder + curve data are best-effort:-// if a source is unavailable we keep the snapshot but degrade the matching-// visual, rather than failing the whole scene.+// Identity frame: everything the HUD and the medallion need to paint. Curve+// data is best-effort, so an unavailable source degrades the matching visual+// rather than failing the whole scene.+//+// The holder scan is deliberately NOT in here. It is by far the slowest source+// (a full token-account walk, ~10s on a cold cache for a large holder set) and+// waiting on it held the entire page behind the loading spinner for the whole+// duration. It now loads in the background and fills in when it lands.async function loadSnapshot() {- const [details, curve, holders, meta] = await Promise.allSettled([+ const [details, curve, meta] = await Promise.allSettled([mcpCall('getTokenDetails', { mint }),mcpCall('getBondingCurve', { mint, network }),- mcpCall('getTokenHolders', { mint, limit: 12, network }),fetchTokenMeta(mint),]);const d = details.status === 'fulfilled' ? details.value || {} : {};const c = curve.status === 'fulfilled' ? curve.value || null : null;- const h = holders.status === 'fulfilled' ? holders.value || null : null;- // GeckoTerminal token info — the reliable name/symbol/logo/market-cap source+ // GeckoTerminal token info: the reliable name/symbol/logo/market-cap source// for graduated coins, whose on-chain metadata authority is renounced so// getTokenDetails comes back null (e.g. $THREE itself).const gt = meta.status === 'fulfilled' ? meta.value || null : null;@@ -128,11 +131,40 @@ async function loadSnapshot() {volume24: gt?.volume24 ?? null,graduationProgress: clamp01(numOrNull(c?.graduationProgress ?? c?.progress)),graduated: Boolean(c?.graduated || c?.complete),- topHolderPercent: numOrNull(h?.topHolderPercent),- holders: Array.isArray(h?.holders) ? h.holders : [],+ topHolderPercent: null,+ holders: [],};}+// The token exists as far as any of our sources are concerned. Used to tell a+// real coin whose enrichment happened to be thin apart from a mint that simply+// is not a token.+function isKnownToken(s) {+ return (+ s.name !== 'Unknown token' ||+ Boolean(s.image) ||+ s.marketCapUsd !== null ||+ s.priceUsd !== null ||+ s.graduationProgress !== null ||+ s.graduated+ );+}++// Top holders, loaded after the HUD has painted. Best-effort by design: a+// failure leaves the galaxy empty and the concentration stat unknown, both of+// which have designed states.+async function loadHolders() {+ try {+ const h = await mcpCall('getTokenHolders', { mint, limit: 12, network }, 25_000);+ return {+ topHolderPercent: numOrNull(h?.topHolderPercent),+ holders: Array.isArray(h?.holders) ? h.holders : [],+ };+ } catch {+ return { topHolderPercent: null, holders: [] };+ }+}+// Token info from three keyless, CORS-enabled sources, tried in order// (GeckoTerminal → DexScreener → Jupiter). Resolves the canonical name,// symbol, logo and market cap for any token — including graduated coins that@@ -245,17 +277,21 @@ function clamp01(v) {function setStatus(kind, title, detail, action) {if (kind === null) {statusEl.hidden = true;+ statusEl.removeAttribute('data-kind');statusEl.innerHTML = '';return;}statusEl.hidden = false;statusEl.dataset.kind = kind;+ // The overlay owns the page's only heading while it is up (the HUD's <h1>+ // exists only after the overlay is cleared), so this is an <h1>, not an+ // <h2> under a heading that never rendered.statusEl.innerHTML = `- <div class="status-card">+ <div class="status-card" role="status" aria-live="polite">${kind === 'loading' ? '<div class="spinner" aria-hidden="true"></div>' : ''}- <h2>${escapeHtml(title)}</h2>+ <h1>${escapeHtml(title)}</h1>${detail ? `<p>${escapeHtml(detail)}</p>` : ''}- ${action ? `<a class="status-action" href="${action.href}">${escapeHtml(action.label)}</a>` : ''}+ ${action ? `<a class="status-action" href="${escapeHtml(action.href)}">${escapeHtml(action.label)}</a>` : ''}</div>`;}@@ -273,7 +309,23 @@ function compact(n) {if (abs >= 1e9) return (n / 1e9).toFixed(2) + 'B';if (abs >= 1e6) return (n / 1e6).toFixed(2) + 'M';if (abs >= 1e3) return (n / 1e3).toFixed(1) + 'K';- return n.toFixed(0);+ if (abs >= 100) return n.toFixed(0);+ // Meme-coin tape entries are routinely worth cents. Rounding those to a+ // whole number printed every real swap as "$0", which reads as a bug.+ if (abs >= 1) return n.toFixed(2);+ if (abs >= 0.01) return n.toFixed(3);+ if (abs > 0) return n.toFixed(4);+ return '0';+}++// SOL leg of a tape row. Same problem as `compact`: a 0.0004 SOL swap must not+// print as "0.000 SOL".+function fmtSol(n) {+ if (!Number.isFinite(n) || n < 0) return '';+ if (n >= 1) return n.toFixed(2);+ if (n >= 0.01) return n.toFixed(3);+ if (n > 0) return n.toPrecision(2).replace(/0+$/, '').replace(/\.$/, '');+ return '0';}// Price formatting that survives sub-cent meme-coin prices without lying about@@ -500,6 +552,9 @@ function buildHolderGalaxy(snapshot) {const angle = (i / holders.length) * Math.PI * 2;const y = MathUtils.lerp(-0.6, 0.6, (i % 4) / 3);mesh.position.set(Math.cos(angle) * radius, y, Math.sin(angle) * radius);+ // The scan resolves after the scene is already turning, so each sphere+ // scales up on a short stagger instead of popping into frame.+ mesh.scale.setScalar(0.001);holderGalaxy.add(mesh);holderOrbits.push({mesh,@@ -509,6 +564,7 @@ function buildHolderGalaxy(snapshot) {speed: 0.0008 + (i % 3) * 0.0004,bob: 0.6 + (i % 5) * 0.15,phase: i,+ spawn: performance.now() / 1000 + i * 0.04,});});}@@ -809,18 +865,23 @@ function renderTape() {const usd = Number(t.sol_value_usd);const usdLabel = Number.isFinite(usd) ? `$${compact(usd)}` : '—';const sol = Number(t.sol_amount);- const solLabel = Number.isFinite(sol) ? `${sol.toFixed(sol < 1 ? 3 : 2)} SOL` : '';+ const solText = fmtSol(sol);+ const solLabel = solText ? `${solText} SOL` : '';const href = t.signature ? `https://solscan.io/tx/${encodeURIComponent(t.signature)}` : null;const trader = shortAddr(t.trader);const ago = timeAgo(t.timestamp);+ // A trade with no readable SOL leg drops that segment rather than+ // rendering an empty one between two separators.+ const mid = [solLabel, trader].filter(Boolean).map(escapeHtml).join(' · ');const inner = `<span class="t-side" aria-hidden="true"></span>- <span class="t-mid"><span class="t-usd">${t.is_buy ? '↑' : '↓'} ${usdLabel}</span> · ${escapeHtml(solLabel)} · ${escapeHtml(trader)}</span>+ <span class="t-mid"><span class="t-usd">${t.is_buy ? '↑' : '↓'} ${usdLabel}</span> · ${mid}</span><span class="t-time">${ago}</span>`;// New rows (only the top one on a fresh poll) animate in.const cls = `c3d-trade ${side}${i === 0 ? ' enter' : ''}`;+ const label = `${side} ${usdLabel} by ${trader}, ${ago} ago. Opens the transaction on Solscan.`;return href- ? `<a class="${cls}" href="${href}" target="_blank" rel="noopener" aria-label="${side} ${usdLabel} by ${escapeHtml(trader)} ${ago} ago — view transaction">${inner}</a>`+ ? `<a class="${cls}" href="${href}" target="_blank" rel="noopener" aria-label="${escapeHtml(label)}">${inner}</a>`: `<div class="${cls}">${inner}</div>`;}).join('');@@ -888,7 +949,7 @@ function renderHud(s) {<dl class="hud-stats"><div><dt>Market cap</dt><dd id="c3d-mcap">${s.marketCapUsd !== null ? '$' + compact(s.marketCapUsd) : '—'}</dd></div><div><dt>24h volume</dt><dd id="c3d-vol">${s.volume24 !== null ? '$' + compact(s.volume24) : '—'}</dd></div>- <div><dt>Top-holder share</dt><dd id="c3d-conc">${s.topHolderPercent !== null ? s.topHolderPercent.toFixed(1) + '%' : '—'}</dd></div>+ <div><dt>Top-holder share</dt><dd id="c3d-conc">${s.topHolderPercent !== null ? escapeHtml(s.topHolderPercent.toFixed(1)) + '%' : '<span class="c3d-dd-sk" role="img" aria-label="Loading top-holder share"></span>'}</dd></div><div><dt>Status</dt><dd id="c3d-status">${escapeHtml(gradLabel(s))}</dd></div><div><dt>Quality</dt><dd id="c3d-quality">—</dd></div><div><dt>Smart money</dt><dd id="c3d-smart">—</dd></div>@@ -942,6 +1003,30 @@ function applyMarket(m) {if (spark) spark.innerHTML = sparklineSvg(m.closes, (m.change ?? 0) >= 0);}+// Set once the on-chain holder scan has produced a top-holder share, so the+// intel engine's estimate never overwrites it.+let concOwned = false;++// Fold the (late) holder scan into a HUD that has already painted: fill the+// concentration stat and grow the galaxy in, rather than popping 12 spheres+// into an established scene.+function applyHolders(s, result, sceneOk) {+ s.topHolderPercent = result.topHolderPercent;+ s.holders = result.holders;++ const conc = document.getElementById('c3d-conc');+ if (conc) {+ if (result.topHolderPercent !== null) {+ conc.textContent = `${result.topHolderPercent.toFixed(1)}%`;+ concOwned = true;+ } else if (conc.querySelector('.c3d-dd-sk')) {+ // The scan came back empty. Say so instead of pulsing forever.+ conc.textContent = 'Unknown';+ }+ }+ if (sceneOk) buildHolderGalaxy(s);+}+function applyIntel(intel) {if (!intel || intel.error) return;const cat = document.getElementById('c3d-cat');@@ -955,9 +1040,11 @@ function applyIntel(intel) {if (smart && intel.smart_money_count != null) {smart.textContent = intel.smart_money_count > 0 ? `${intel.smart_money_count} wallet${intel.smart_money_count === 1 ? '' : 's'}` : 'None';}- // Prefer the intel engine's concentration when MCP didn't supply one.+ // Prefer the intel engine's concentration when the holder scan didn't supply+ // one. `concOwned` is the authority flag: the holder scan can land after the+ // intel call, and the on-chain number must win whichever order they arrive in.const conc = document.getElementById('c3d-conc');- if (conc && conc.textContent === '—' && intel.concentration_top1 != null) {+ if (conc && !concOwned && intel.concentration_top1 != null) {conc.textContent = `${(intel.concentration_top1 * (intel.concentration_top1 <= 1 ? 100 : 1)).toFixed(1)}%`;}// Risk flags → chips (danger flags only; a clean coin shows a green "Clean").@@ -989,7 +1076,7 @@ function renderLanding() {statusEl.dataset.kind = 'empty';statusEl.innerHTML = `<div class="c3d-landing">- <h2>See any token in 3D</h2>+ <h1>See any token in 3D</h1><p class="lede">Paste a pump.fun or Solana mint to render it as a live scene — a logo medallion, holder galaxy, graduation ring, and real-time trade pulses, all from on-chain data.</p><form class="c3d-search" id="c3d-form" autocomplete="off"><input id="c3d-mint-input" type="text" inputmode="text" spellcheck="false"diff --git a/src/constellation/main.js b/src/constellation/main.jsindex 111a170fb..015bc51ba 100644--- a/src/constellation/main.js+++ b/src/constellation/main.js@@ -14,6 +14,13 @@// Granite embeddings arrive the stars animate into their semantic positions. If// watsonx is not configured the page says so plainly and keeps the rank layout —// it never fabricates vectors or an analysis.+//+// Attribution is load-bearing here. Both backing endpoints have failover chains+// (the embed endpoint falls through to NVIDIA/Vertex/OpenAI; /api/brain/chat+// falls through to its free-tier routes and announces it with an SSE `fallback`+// event). This page therefore labels what ACTUALLY served the request rather+// than what it hoped for: crediting IBM Granite for another model's output would+// be a fabrication, the same class of defect as inventing the data itself.import {Scene, PerspectiveCamera, WebGLRenderer, Color, Group,@@ -38,10 +45,20 @@ const hint = $('c-hint');const overlay = $('c-overlay');const overlayMsg = $('c-overlay-msg');const spinner = $('c-spinner');+const retryBtn = $('c-retry');const panel = $('c-panel');+const liveRegion = $('c-a11y-live');-const EMBED_MODEL_HINT = 'ibm/granite-embedding-278m-multilingual';const RADIUS = 28; // target galaxy radius for the semantic / rank layouts+// A star is ~1-2 world units across at a camera distance of ~74, so an exact+// ray hit demands near-pixel precision, on a phone it is unhittable, and even+// with a mouse the pick can miss the star the tooltip is naming. Falling back to+// the nearest star within this screen-space radius makes the target the visible+// glow rather than the geometry.+const PICK_RADIUS_PX = 22;+const PICK_RADIUS_COARSE_PX = 34;+const SIGN_IN_HREF = '/login?next=%2Fconstellation';+const REGISTER_HREF = '/register?next=%2Fconstellation';// WebGL-dependent objects, assigned in boot(). Functions below close over these// module bindings, so they resolve correctly once boot() has run.@@ -52,6 +69,7 @@ const pointer = new Vector2();/** @type {{token:object, mesh:Mesh, glow:Sprite, baseColor:Color, baseScale:number, target:Vector3}[]} */let nodes = [];let vectorsByIndex = null; // number[][] aligned with nodes, for neighbor lookups+let signedIn = false; // resolved once at boot; gates the Granite analysis call// ---- status / overlay helpers ---------------------------------------------function setStatus(kind, html) {@@ -59,11 +77,27 @@ function setStatus(kind, html) {if (kind) statusEl.classList.add(kind);statusText.innerHTML = html;}-function hideOverlay() { overlay.classList.add('hidden'); }-function fatalOverlay(html) {+function hideOverlay() {+ overlay.classList.add('hidden');+ overlay.setAttribute('aria-hidden', 'true');+ retryBtn.hidden = true;+}+function loadingOverlay(html) {+ spinner.style.display = '';+ retryBtn.hidden = true;+ overlayMsg.innerHTML = html;+ overlay.classList.remove('hidden');+ overlay.removeAttribute('aria-hidden');+}+// A dead end the visitor can act on: every recoverable failure offers the retry+// button, so the page never leaves someone staring at an error with no way out.+function fatalOverlay(html, { retryable = false } = {}) {spinner.style.display = 'none';overlayMsg.innerHTML = html;+ retryBtn.hidden = !retryable;overlay.classList.remove('hidden');+ overlay.removeAttribute('aria-hidden');+ if (retryable) retryBtn.focus();}function webglAvailable() {try {@@ -124,8 +158,22 @@ function fibonacciPoint(i, n, radius) {}function buildNodes(tokens) {- for (const n of nodes) { nodesGroup.remove(n.mesh); nodesGroup.remove(n.glow); }+ // Retrying after a failed load rebuilds the galaxy, so the previous pass's+ // per-node materials are disposed rather than left on the GPU. The sphere+ // geometry and glow texture are shared across every node and every rebuild,+ // so they are deliberately kept.+ for (const n of nodes) {+ nodesGroup.remove(n.mesh);+ nodesGroup.remove(n.glow);+ n.mesh.material.dispose();+ n.glow.material.dispose();+ }nodes = [];+ hovered = null;+ selectedNode = null;+ focusIndex = -1;+ keyboardFocused = false;+ hideTooltip();const N = tokens.length;tokens.forEach((token, i) => {const rank = Number.isFinite(token.rank) ? token.rank : i + 1;@@ -212,9 +260,13 @@ async function embedTokens(tokens) {return res.json(); // { model, dimensions, vectors }}-// ---- interaction: hover + click ------------------------------------------+// ---- interaction: hover + click + keyboard --------------------------------let hovered = null;let selectedNode = null;+let focusIndex = -1; // keyboard cursor into `nodes`+let keyboardFocused = false; // the tooltip is tracking a keyboard-picked star+const pointerPx = [0, 0];+const _projected = new Vector3();// The glow scale for a node depends on its state: selected stars stay largest,// hovered stars enlarge for feedback, everything else sits at its base size.@@ -225,35 +277,80 @@ function glowScaleFor(node) {}function updatePointer(e) {+ pointerPx[0] = e.clientX;+ pointerPx[1] = e.clientY;pointer.x = (e.clientX / window.innerWidth) * 2 - 1;pointer.y = -(e.clientY / window.innerHeight) * 2 + 1;}++// Where a star currently sits on screen, in CSS pixels. Used for proximity+// picking and for anchoring the tooltip to a keyboard-selected star.+function screenXY(node) {+ _projected.copy(node.mesh.position).project(camera);+ return [+ ((_projected.x + 1) / 2) * window.innerWidth,+ ((1 - _projected.y) / 2) * window.innerHeight,+ ];+}+function pickTolerancePx() {+ return window.matchMedia?.('(pointer: coarse)')?.matches ? PICK_RADIUS_COARSE_PX : PICK_RADIUS_PX;+}+function nearestNodeToScreen(px, py, maxPx) {+ let best = null;+ let bestD = maxPx;+ for (const node of nodes) {+ const [x, y] = screenXY(node);+ const d = Math.hypot(x - px, y - py);+ if (d < bestD) { bestD = d; best = node; }+ }+ return best;+}+// Exact ray hit first (it respects depth, so the front star wins where two+// overlap), then the screen-space fallback so the visible glow is the target.function pickNode() {raycaster.setFromCamera(pointer, camera);const hits = raycaster.intersectObjects(nodes.map((n) => n.mesh), false);- return hits.length ? nodes[hits[0].object.userData.index] : null;+ if (hits.length) return nodes[hits[0].object.userData.index];+ return nearestNodeToScreen(pointerPx[0], pointerPx[1], pickTolerancePx());+}++function hideTooltip() {+ tooltip.style.opacity = '0';+ keyboardFocused = false;+}+// Keep the tooltip inside the viewport: it is translated (-50%, -130%) from this+// anchor, so a star near an edge would otherwise push it off screen.+function placeTooltip(x, y) {+ const half = (tooltip.offsetWidth || 0) / 2;+ tooltip.style.left = `${Math.min(Math.max(x, half + 10), window.innerWidth - half - 10)}px`;+ tooltip.style.top = `${Math.max(y, (tooltip.offsetHeight || 28) + 12)}px`;}+function showTooltip(node, x, y) {+ tipSym.textContent = node.token.symbol;+ tipNm.textContent = node.token.name;+ placeTooltip(x, y);+ tooltip.style.opacity = '1';+}++function setHovered(node) {+ if (node === hovered) return;+ const prev = hovered;+ hovered = node;+ if (prev) prev.glow.scale.setScalar(glowScaleFor(prev));+ if (node) node.glow.scale.setScalar(glowScaleFor(node));+}+function onPointerMove(e) {updatePointer(e);const node = pickNode();if (node !== hovered) {- const prev = hovered;- hovered = node;- if (prev) prev.glow.scale.setScalar(glowScaleFor(prev));+ setHovered(node);+ keyboardFocused = false;renderer.domElement.style.cursor = node ? 'pointer' : 'grab';- if (node) {- node.glow.scale.setScalar(glowScaleFor(node));- tipSym.textContent = node.token.symbol;- tipNm.textContent = node.token.name;- tooltip.style.left = `${e.clientX}px`;- tooltip.style.top = `${e.clientY}px`;- tooltip.style.opacity = '1';- } else {- tooltip.style.opacity = '0';- }- } else if (node) {- tooltip.style.left = `${e.clientX}px`;- tooltip.style.top = `${e.clientY}px`;+ if (node) showTooltip(node, e.clientX, e.clientY);+ else hideTooltip();+ } else if (node && !keyboardFocused) {+ placeTooltip(e.clientX, e.clientY);}}@@ -261,19 +358,56 @@ let downAt = 0; let downXY = [0, 0];function onPointerDown(e) { downAt = performance.now(); downXY = [e.clientX, e.clientY]; }function onPointerUp(e) {const moved = Math.hypot(e.clientX - downXY[0], e.clientY - downXY[1]);- if (moved < 6 && performance.now() - downAt < 450) {- updatePointer(e);- const node = pickNode();- if (node) selectNode(node.mesh.userData.index);+ if (moved >= 6 || performance.now() - downAt >= 450) return; // an orbit drag, not a tap+ updatePointer(e);+ // The star under the release wins; if the ray and the proximity sweep both+ // come up empty, fall back to whatever the tooltip was naming, that is the+ // star the visitor was aiming at, and the scene keeps auto-rotating under the+ // cursor between the hover and the release.+ const node = pickNode() || hovered;+ if (node) { keyboardFocused = false; selectNode(node.mesh.userData.index, { fromKeyboard: false }); }+}++// Keyboard path to the same flow: arrows walk the stars in trending-rank order,+// Enter/Space opens the analysis panel. Without this the page's only real+// interaction is mouse-only.+function focusStar(index) {+ if (!nodes.length) return;+ focusIndex = ((index % nodes.length) + nodes.length) % nodes.length;+ const node = nodes[focusIndex];+ setHovered(node);+ keyboardFocused = true;+ const [x, y] = screenXY(node);+ showTooltip(node, x, y);+ liveRegion.textContent = `${node.token.symbol}, ${node.token.name}, trending rank ${node.token.rank}. ${focusIndex + 1} of ${nodes.length}. Press Enter for a live analysis.`;+}+function onCanvasKeyDown(e) {+ if (!nodes.length) return;+ const step = { ArrowRight: 1, ArrowDown: 1, ArrowLeft: -1, ArrowUp: -1 }[e.key];+ if (step) {+ e.preventDefault();+ focusStar(focusIndex < 0 ? (step > 0 ? 0 : nodes.length - 1) : focusIndex + step);+ return;+ }+ if (e.key === 'Home' || e.key === 'End') {+ e.preventDefault();+ focusStar(e.key === 'Home' ? 0 : nodes.length - 1);+ return;+ }+ if ((e.key === 'Enter' || e.key === ' ') && focusIndex >= 0) {+ e.preventDefault();+ selectNode(focusIndex, { fromKeyboard: true });}}// ---- detail panel + Granite analysis stream -------------------------------let analysisAbort = null;+let returnFocusToCanvas = false;-function selectNode(index) {+function selectNode(index, { fromKeyboard = false } = {}) {const prev = selectedNode;selectedNode = nodes[index];+ focusIndex = index;if (prev && prev !== selectedNode) prev.glow.scale.setScalar(glowScaleFor(prev));selectedNode.glow.scale.setScalar(glowScaleFor(selectedNode));const { token } = nodes[index];@@ -282,7 +416,11 @@ function selectNode(index) {$('c-panel-sym').textContent = token.symbol;$('c-panel-nm').textContent = token.name;const logo = $('c-panel-logo');- if (token.logo) { logo.src = token.logo; logo.style.display = ''; } else { logo.style.display = 'none'; }+ // A token logo is caller-supplied and often dead; a 404 must not leave a+ // broken-image glyph (or the previous token's art) in the header.+ logo.style.display = token.logo ? '' : 'none';+ if (token.logo) logo.src = token.logo; else logo.removeAttribute('src');+ logo.alt = token.logo ? `${token.symbol} token logo` : '';$('c-panel-price').textContent = token.price_usd ? formatPrice(token.price_usd) : '—';$('c-panel-rank').textContent = `#${token.rank}`;@@ -296,6 +434,9 @@ function selectNode(index) {panel.classList.add('open');panel.setAttribute('aria-hidden', 'false');+ panel.removeAttribute('inert');+ returnFocusToCanvas = fromKeyboard;+ if (fromKeyboard) $('c-close').focus();runGraniteAnalysis(token, neigh);}diff --git a/src/cosmos.js b/src/cosmos.jsindex 40776990d..85aa8fdea 100644--- a/src/cosmos.js+++ b/src/cosmos.js@@ -58,6 +58,15 @@ const DEFAULT_AVATAR = BUNDLED[0].url;const POLL_INTERVAL_MS = 4000;const POLL_TIMEOUT_MS = 5 * 60 * 1000;+// Reveal the clip even if `canplay` was missed (cache/seek edge); cleared the+// moment the video reports it can play, or that it cannot.+const REVEAL_FALLBACK_MS = 1200;++// Shown whenever the lane itself reports it is down (unconfigured deployment, or+// NVIDIA retired every hosted Cosmos route this account can reach). The aurora+// backdrop stays, so the stage is a designed scene rather than a dead void.+const LANE_OFFLINE_COPY =+ 'NVIDIA Cosmos world generation is offline right now. Your avatar keeps its living backdrop above; check back soon for generated worlds.';let activeAvatarUrl = null;let job = null; // { id, startedAt }@@ -74,17 +83,31 @@ function toast(msg) {toast._t = setTimeout(() => els.toast.classList.remove('show'), 2400);}-function showNote(kind, html) {+// Notes render as text plus an optional real <button>. Server copy is never+// interpolated into innerHTML: the upstream lane has answered with vendor detail+// before, and a banner is not a template.+function showNote(kind, message, action = null) {els.note.className = `cz-note show ${kind}`;- els.note.innerHTML = html;+ els.note.replaceChildren(document.createTextNode(message));+ if (!action) return;+ els.note.appendChild(document.createTextNode(' '));+ const btn = document.createElement('button');+ btn.type = 'button';+ btn.textContent = action.label;+ btn.addEventListener('click', action.onClick);+ els.note.appendChild(btn);}function clearNote() {els.note.className = 'cz-note';- els.note.innerHTML = '';+ els.note.replaceChildren();}-function setBadge(on, text) {- els.statusBadge.classList.toggle('is-off', !on);+// Three honest badge states: idle (nothing attempted yet), live (the lane just+// accepted a job), off (the lane told us it is down). The dot never claims a+// health we have not observed.+function setBadge(state, text) {+ els.statusBadge.classList.toggle('is-off', state === 'off');+ els.statusBadge.classList.toggle('is-idle', state === 'idle');els.statusText.textContent = text;}@@ -224,27 +247,25 @@ async function generate() {});data = await res.json();} catch {- return failGeneration(- res && res.status === 404- ? 'The Cosmos lane isn’t deployed on this environment yet.'- : 'Couldn’t reach the Cosmos service. Check your connection and try again.',- { unconfigured: true },- );+ // A dropped connection or an unparseable body is recoverable, so it keeps a+ // Retry: only the lane telling us it is offline drops the retry affordance.+ if (res && res.status === 404) {+ setBadge('off', 'Cosmos offline');+ return failGeneration(LANE_OFFLINE_COPY, { unconfigured: true });+ }+ return failGeneration('Could not reach the Cosmos service. Check your connection and try again.');}- if (res.status === 503 || res.status === 404 || data?.error === 'unconfigured') {- setBadge(false, 'Cosmos offline');- return failGeneration(- 'NVIDIA Cosmos isn’t available on this environment yet. Your avatar still shines on the living backdrop above — check back soon for generated worlds.',- { unconfigured: true },- );+ if (res.status === 503 || res.status === 404 || data?.error === 'unconfigured' || data?.error === 'lane_unavailable') {+ setBadge('off', 'Cosmos offline');+ return failGeneration(LANE_OFFLINE_COPY, { unconfigured: true });}if (!res.ok) {const retry = data?.retry_after ? ` Try again in ~${data.retry_after}s.` : '';- return failGeneration((data?.message || 'Cosmos couldn’t start this world.') + retry);+ return failGeneration((data?.message || 'Cosmos could not start this world.') + retry);}- setBadge(true, 'NVIDIA Cosmos');+ setBadge('live', 'NVIDIA Cosmos');// Rare synchronous completion.if (data.status === 'done' && data.video_url) {@@ -263,21 +284,33 @@ async function poll() {if (Date.now() - job.startedAt > POLL_TIMEOUT_MS) {return failGeneration('This world is taking unusually long. Try a simpler prompt or generate again.');}- let data;+ let data, res;try {- const res = await fetch(`/api/cosmos?job=${encodeURIComponent(job.id)}`, { headers: { accept: 'application/json' } });+ res = await fetch(`/api/cosmos?job=${encodeURIComponent(job.id)}`, { headers: { accept: 'application/json' } });data = await res.json();} catch {// transient network hiccup — keep the job alivepollTimer = setTimeout(poll, POLL_INTERVAL_MS);return;}++ // The lane can go down mid-render (a redeploy that drops the key, a retired+ // upstream route). Land in the designed offline state instead of polling a job+ // nobody is answering for the full five-minute ceiling.+ if (res.status === 503 || data?.error === 'unconfigured' || data?.error === 'lane_unavailable') {+ setBadge('off', 'Cosmos offline');+ return failGeneration(LANE_OFFLINE_COPY, { unconfigured: true });+ }+ if (!res.ok) {+ return failGeneration('Lost track of this world while it was rendering. Generate it again.');+ }+job.status = data?.status || 'running';renderProgress(job.status);if (data?.status === 'done' && data.video_url) return succeed(data.video_url);if (data?.status === 'failed') {- return failGeneration(data?.error || 'Cosmos couldn’t finish this world. Try a different prompt.');+ return failGeneration(data?.error || 'Cosmos could not finish this world. Try a different prompt.');}pollTimer = setTimeout(poll, POLL_INTERVAL_MS);}@@ -286,15 +319,27 @@ function succeed(videoUrl) {stopTimers();lastVideoUrl = videoUrl;const v = els.world;- v.src = videoUrl;- v.removeAttribute('aria-hidden');+ let revealTimer = null;const reveal = () => {+ clearTimeout(revealTimer);v.classList.add('is-live');v.play().catch(() => {});};v.oncanplay = reveal;+ // A durable URL that will not decode (storage hiccup, expired object) must not+ // leave a "done" stage with nothing in it.+ v.onerror = () => {+ clearTimeout(revealTimer);+ v.classList.remove('is-live');+ v.setAttribute('aria-hidden', 'true');+ els.stage.classList.remove('is-done');+ lastVideoUrl = null;+ failGeneration('The world rendered but its clip would not play. Generate it again.');+ };+ v.src = videoUrl;+ v.removeAttribute('aria-hidden');// Safety: reveal even if canplay was missed (cache/seek edge).- setTimeout(reveal, 1200);+ revealTimer = setTimeout(reveal, REVEAL_FALLBACK_MS);job = null;setBusy(false);@@ -311,14 +356,13 @@ function failGeneration(message, { unconfigured = false } = {}) {setBusy(false);els.regen.style.display = lastVideoUrl ? 'inline-block' : 'none';els.secondary.style.display = lastVideoUrl ? 'flex' : 'none';+ // An offline lane gets no Retry: the same request would fail the same way, and+ // a button that cannot work is worse than none.showNote(unconfigured ? 'info' : 'err',- `${message}${unconfigured ? '' : ' <button type="button" id="cz-retry">Retry</button>'}`,+ message,+ unconfigured ? null : { label: 'Retry', onClick: () => generate() },);- const retry = $('cz-retry');- if (retry) {- retry.addEventListener('click', () => generate());- }}function cancelJob() {