Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

docs(skill-bundles): explain how a bundle is priced from the seller's own ledger

nirholas36aea0a6f754
diff --git a/api/scene-capture.js b/api/scene-capture.js
index f98acbfdb..7bc3d706e 100644
--- a/api/scene-capture.js
+++ b/api/scene-capture.js
@@ -33,13 +33,17 @@ function clampInt(v, lo, hi, dflt) {
return Number.isFinite(n) ? Math.min(hi, Math.max(lo, n)) : dflt;
}
+// The 503 body is read straight into the /capture error overlay, so `message` is
+// written for a visitor. Operator instructions live in `hint`, which the page
+// never renders: telling a first-time user to set two GCP env vars is not an
+// actionable error state.
function unconfigured(res) {
return json(res, 503, {
error: 'unconfigured',
- message:
- 'Scene capture is not configured on this deployment. Set GCP_VIDEO2SCENE_URL ' +
- 'and GCP_RECONSTRUCTION_KEY to the URL and bearer secret of your deployed ' +
- 'workers/model-video2scene Cloud Run service.',
+ message: 'Video reconstruction is offline on this deployment, so a video cannot be turned into a point cloud right now.',
+ hint:
+ 'Set GCP_VIDEO2SCENE_URL and GCP_RECONSTRUCTION_KEY to the URL and bearer ' +
+ 'secret of your deployed workers/model-video2scene Cloud Run service.',
});
}
@@ -121,7 +125,20 @@ async function pollJob(req, res, jobId) {
return unconfigured(res);
}
- const result = await provider.status(jobId);
+ // The client polls this on a fixed interval; a thrown decode error here would
+ // hand it a 500 it can only keep retrying. Report the failure in the payload.
+ let result;
+ try {
+ result = await provider.status(jobId);
+ } catch (err) {
+ return json(res, 200, {
+ job_id: jobId,
+ status: 'failed',
+ result_url: null,
+ error: err?.message || 'Job status could not be read.',
+ });
+ }
+
return json(res, 200, {
job_id: jobId,
status: result.status,
diff --git a/docs/nav.json b/docs/nav.json
index 0b8c630f1..83a96fa06 100644
--- a/docs/nav.json
+++ b/docs/nav.json
@@ -535,6 +535,10 @@
"label": "Marketplace",
"path": "marketplace"
},
+ {
+ "label": "Skill bundles",
+ "path": "skill-bundles"
+ },
{
"label": "Coin launches",
"path": "coin-launches"
diff --git a/docs/skill-bundles.md b/docs/skill-bundles.md
new file mode 100644
index 000000000..815d10932
--- /dev/null
+++ b/docs/skill-bundles.md
@@ -0,0 +1,182 @@
+# Skill bundles
+
+A **skill bundle** sells several of one agent's skills as a single purchase. One
+payment, one confirmation, and every skill in the bundle unlocks at once.
+
+The hard part of a bundle was never grouping the skills. It was the price. The
+usual answer is "take 20% off the sum of the parts", which is a guess dressed as
+advice. three.ws answers it from the seller's own ledger instead: some buyers have
+already bought two or more of these skills separately, and what they actually paid
+is real evidence of what the combination is worth.
+
+Build one at **[three.ws/bundles](https://three.ws/bundles)**. The page is
+owner-only: it lists the agents you own, the skills on each that carry an active
+price, and a price panel that backtests any price you type against those buyers.
+
+> Source: [`pages/bundles.html`](../pages/bundles.html) (the builder),
+> [`api/agents/[id]/bundles.js`](../api/agents/[id]/bundles.js) (management and
+> pricing), [`api/_lib/bundle-pricing.js`](../api/_lib/bundle-pricing.js) (the
+> arithmetic), [`api/marketplace/purchase-bundle.js`](../api/marketplace/purchase-bundle.js)
+> (checkout and unlock).
+
+---
+
+## How the price is derived
+
+Two bases, and the API always says which one it used, so a default is never
+mistaken for a finding.
+
+| `history.basis` | When | What the suggested price is |
+|---|---|---|
+| `median_basket` | At least one buyer bought 2+ of the selected skills | The **median** of what those buyers really spent across them, capped at the sum of the parts |
+| `discount_off_list` | Nobody has bought 2+ of them yet | A flat **20% off** the sum of the parts, labelled as a starting point |
+
+Only confirmed, paid purchases count. Trials and access rows granted by an earlier
+bundle are excluded (`kind` is filtered to the paid kinds
+[`api/_lib/marketplace-kinds.js`](../api/_lib/marketplace-kinds.js) publishes), so
+nothing inflates the evidence a seller is shown.
+
+Every amount in and out of these endpoints is an **atomic integer as a string**
+(the currency's smallest unit). A 9-decimal mint puts real balances past
+`Number.MAX_SAFE_INTEGER`, so the server carries every amount as a BigInt and the
+browser scales through `BigInt` too. `mint_decimals` in the pricing response is
+how a client turns an atomic amount into a human one.
+
+---
+
+## Endpoints
+
+All four live under the agent. `:id` is the agent's UUID.
+
+| Method | Path | Auth | Does |
+|---|---|---|---|
+| `GET` | `/api/agents/:id/bundles` | public | List the agent's active bundles |
+| `GET` | `/api/agents/:id/bundles?action=pricing&skills=a,b` | public | Price a candidate bundle against real sales |
+| `POST` | `/api/agents/:id/bundles` | owner | Publish a bundle |
+| `PATCH` | `/api/agents/:id/bundles/:bundleId` | owner | Rename, reprice, or change its skills |
+| `DELETE` | `/api/agents/:id/bundles/:bundleId` | owner | Deactivate it (nothing is deleted) |
+
+Owner calls need a session cookie (plus the `x-csrf-token` header that
+[`src/api.js`](../src/api.js) attaches automatically in the browser) or a bearer
+token. The two `GET`s are public on purpose: they read only aggregate counts and
+the agent's own list prices, both of which the marketplace already publishes per
+skill. No buyer identity and no row-level history ever leaves the handler.
+
+### Price a candidate bundle
+
+```bash
+curl -s "https://three.ws/api/agents/$AGENT_ID/bundles?action=pricing&skills=research,summarize"
+```
+
+```json
+{
+ "data": {
+ "agent_id": "00000000-0000-4000-8000-00000000a9e7",
+ "currency_mint": "FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump",
+ "chain": "solana",
+ "mint_decimals": 6,
+ "skills": [
+ { "skill": "research", "list_amount": "2000000", "units_sold": 0, "gross_atomic": "0", "buyers": 0 },
+ { "skill": "summarize", "list_amount": "1000000", "units_sold": 0, "gross_atomic": "0", "buyers": 0 }
+ ],
+ "unpriced_skills": [],
+ "sum_of_parts_atomic": "3000000",
+ "history": {
+ "multi_skill_buyers": 0,
+ "revenue_atomic": "0",
+ "median_basket_atomic": null,
+ "basis": "discount_off_list"
+ },
+ "suggested": {
+ "price": "2400000",
+ "discount_atomic": "600000",
+ "discount_percent": 20,
+ "backtest_revenue_atomic": "0",
+ "revenue_delta_atomic": "0",
+ "buyers_better_off": 0
+ },
+ "asked": null
+ }
+}
+```
+
+Add `&price=<atomic>` to backtest a specific price. The response's `asked` block
+then carries the same shape as `suggested` for that price: what the bundle would
+have collected from the same buyers (`backtest_revenue_atomic`), how that compares
+to what they really paid (`revenue_delta_atomic`, negative means the price left
+money on the table), and how many of them would have come out ahead
+(`buyers_better_off`). The builder page calls exactly this as you drag the price.
+
+A skill you named that has no active price is not silently dropped: it comes back
+in `unpriced_skills` and is left out of the sum. Skills priced in **different
+mints** are refused with `409 mixed_currency`, because adding two currencies
+produces a number that means nothing.
+
+### Publish
+
+```bash
+curl -s -X POST "https://three.ws/api/agents/$AGENT_ID/bundles" \
+ -H "authorization: Bearer $THREE_WS_TOKEN" \
+ -H "content-type: application/json" \
+ -d '{
+ "name": "Research starter pack",
+ "description": "Research plus summarize, one payment.",
+ "price_amount": "2400000",
+ "currency_mint": "FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump",
+ "chain": "solana",
+ "skills": ["research", "summarize"]
+ }'
+```
+
+`price_amount` takes an atomic integer as a string or a number; a string is the
+safe form on a 9-decimal mint. `skills` needs at least two names and takes at most
+fifty. The response is `201` with the created bundle and its skills.
+
+`DELETE` sets `is_active = false`. Buyers who already paid keep their access,
+because access lives on their `skill_purchases` rows, not on the bundle.
+
+---
+
+## Checkout
+
+A bundle is bought through the marketplace, not through the bundle endpoints:
+
+```
+POST /api/marketplace/purchase-bundle { "bundle_id": "..." }
+POST /api/marketplace/purchase-bundle/:id/confirm { } # Solana
+POST /api/marketplace/purchase-bundle/:id/confirm { "tx_signature": "0x..." } # EVM
+```
+
+`create` writes a `pending` row in `bundle_purchases` and returns Solana Pay
+parameters: recipient (the creator's payout wallet), `price_amount`,
+`currency_mint`, `chain`, a freshly minted `reference`, and the platform fee split.
+`confirm` proves the payment on-chain **before** anything unlocks: Solana is
+located by the reference the server minted (no client-supplied signature is
+trusted), EVM by the submitted tx hash. On a confirmed verdict the handler writes
+one `skill_purchases` row per skill with `kind = 'bundle'` and `amount = 0`, which
+is what [`hasSkillAccess()`](../api/_lib/skill-access.js) reads, and records a
+single bundle-level revenue event so one bundle sale is never counted as N skill
+sales in GMV.
+
+**Reach today:** the builder, the two public `GET`s, and this checkout are live.
+The buyer-facing *browser* surface is not: no marketplace or agent-profile view
+renders a published bundle yet, so a human buyer reaches one through the API
+above, while the seller-side builder is fully wired. Rendering bundles on the
+agent's marketplace listing is the next step.
+
+---
+
+## Storage
+
+| Table | Holds |
+|---|---|
+| `skill_bundles` | One row per bundle: name, description, `price_amount`, `currency_mint`, `chain`, `is_active` |
+| `bundle_items` | The skill names in a bundle, one row each |
+| `bundle_purchases` | One row per checkout: status, reference, tx signature, platform fee |
+| `skill_purchases` | The unlock itself, one row per skill, `kind = 'bundle'` |
+
+## Related
+
+- [Marketplace](marketplace.md): how skills and assets are listed, bought, and settled
+- [Agent skills](agent-skills.md): what a skill is in the first place
+- [Agent wallets](agent-wallets.md): where a bundle's payment lands
diff --git a/pages/assistant.html b/pages/assistant.html
index 79410baba..8cd6dac25 100644
--- a/pages/assistant.html
+++ b/pages/assistant.html
@@ -245,6 +245,8 @@
color: #fecaca;
}
.preview-status[data-state='error'] .dot { background: #f87171; }
+ .preview-status[data-state='degraded'] { border-color: rgba(251, 191, 36, 0.4); }
+ .preview-status[data-state='degraded'] .dot { background: #fbbf24; }
.preview-status button {
margin-left: auto;
appearance: none;
@@ -379,7 +381,13 @@
<button type="button" class="copy-btn" id="copy-btn" data-i18n="assistant.copy_snippet">Copy snippet</button>
<p class="preview-status" id="preview-status" data-state="loading" role="status" aria-live="polite">
<span class="dot" aria-hidden="true"></span>
- <span id="preview-status-text" data-i18n="assistant.starting_the_live_preview">Starting the live preview...</span>
+ <!-- One span per state, toggled by src/assistant-page.js. The copy stays
+ in the markup (rather than in JS strings) so the i18n catalog pass
+ translates every state and can never revert a live one. -->
+ <span class="preview-msg" data-preview-state="loading" data-i18n="assistant.starting_the_live_preview">Starting the live preview...</span>
+ <span class="preview-msg" data-preview-state="ready" hidden data-i18n="assistant.live_preview_running_in_the_corner_every">Live preview running in the corner. Every change above re-mounts it.</span>
+ <span class="preview-msg" data-preview-state="degraded" hidden data-i18n="assistant.the_preview_mounted_but_its_3d_avatar">The preview mounted, but its 3D avatar did not load. Your snippet above is still correct.</span>
+ <span class="preview-msg" data-preview-state="error" hidden data-i18n="assistant.the_live_preview_could_not_start_the">The live preview could not start (the widget script did not load). Your snippet above is still correct, and the widget works on your own site.</span>
<button type="button" id="preview-retry" hidden data-i18n="assistant.retry">Retry</button>
</p>
<p class="snippet-note" data-i18n-html="assistant.paste_it_before_on_any_site_chat">
diff --git a/pages/avatar-artifact.html b/pages/avatar-artifact.html
index 067a8b50a..e54fa5246 100644
--- a/pages/avatar-artifact.html
+++ b/pages/avatar-artifact.html
@@ -19,6 +19,11 @@
padding: 0;
box-sizing: border-box;
}
+ /* three.ws hidden-guard: make the `hidden` attribute authoritative even
+ against the display rules below; see scripts/lib/hidden-guard.mjs */
+ [hidden] {
+ display: none !important;
+ }
:root {
--ink: #eaf0ff;
--muted: #8b94b8;
@@ -132,6 +137,13 @@
.status:empty {
display: none;
}
+ /* The artifact's own name, once one is loaded: the h1 stops being a
+ tagline and starts being the subject's title. */
+ h1.hint[data-i18n-owned='1'] {
+ font-size: 14px;
+ font-weight: 700;
+ color: var(--ink);
+ }
/* Embed snippet: the manual path when the clipboard is unavailable
(cross-origin iframes and Safari both refuse the write). */
@@ -317,7 +329,10 @@
<meta property="og:image:alt" content="Avatar Artifact, a live Three.js portrait on three.ws">
<meta name="twitter:site" content="@trythreews">
</head>
- <body>
+ <body
+ data-canvas-label="Interactive 3D avatar that follows your cursor, touch, or arrow keys"
+ data-i18n-attr="data-canvas-label:avatar_artifact.canvas_label"
+ >
<!-- Persistent chrome so the standalone viewer is never a dead-end -->
<div class="chrome">
<div class="bar top">
@@ -328,8 +343,9 @@
<span class="hint" data-i18n="avatar_artifact.move_your_cursor_drag_on_touch_arrow">Move your cursor · drag on touch · arrow keys</span>
</div>
<div class="bar bottom">
- <h1 class="hint" data-i18n="avatar_artifact.avatar_artifact_a_live_three_js_portrait">Avatar Artifact: a live Three.js portrait</h1>
+ <h1 class="hint" id="artifact-title" data-i18n="avatar_artifact.avatar_artifact_a_live_three_js_portrait">Avatar Artifact: a live Three.js portrait</h1>
<div class="foot-links">
+ <a id="artifact-source" href="/agents" hidden data-i18n="avatar_artifact.open_profile">Open profile</a>
<button
type="button"
id="copy-embed"
@@ -350,20 +366,47 @@
</div>
</div>
- <!-- Loading state while the Three.js runtime + scene resolve -->
- <div class="overlay" id="loading">
+ <!-- Loading state while the Three.js runtime + scene resolve. The three
+ data-note-* strings are the same overlay narrating the artifact lane:
+ resolving the agent, then fetching its model, then its byte progress. -->
+ <div
+ class="overlay"
+ id="loading"
+ data-note-agent="Looking up the agent…"
+ data-note-model="Fetching the model…"
+ data-note-progress="Fetching the model… {pct}%"
+ data-i18n-attr="data-note-agent:avatar_artifact.note_agent;data-note-model:avatar_artifact.note_model;data-note-progress:avatar_artifact.note_progress"
+ >
<div class="spinner" role="status" aria-label="Loading avatar"></div>
- <p data-i18n="avatar_artifact.summoning_the_avatar">Summoning the avatar…</p>
+ <p id="loading-note" data-i18n="avatar_artifact.summoning_the_avatar">Summoning the avatar…</p>
</div>
- <!-- Designed failure state if the 3D runtime can't load -->
- <div class="overlay" id="error" hidden>
+ <!-- Designed failure states. Every way this viewer can fail gets its own
+ sentence and its own next move; the data-msg-* copy is selected by
+ src/avatar-artifact.js and stays translatable here with the rest. -->
+ <div
+ class="overlay"
+ id="error"
+ hidden
+ data-msg-both="Pass either an agent id or a model URL, not both. Drop one from the link and load it again."
+ data-msg-not-found="No agent on three.ws matches that id. The link may be old, or the agent may have been deleted."
+ data-msg-agent-fetch="The agent lookup did not come back. That is usually a network hiccup, so a retry is worth it."
+ data-msg-no-avatar="This agent has not been given an avatar yet, so there is nothing to render. Its profile has the rest of its identity."
+ data-msg-avatar-private="This agent's avatar is private, so it cannot be shown outside three.ws. Its profile is still public."
+ data-msg-model-blocked="That model link is not an https URL on a host this viewer accepts. Models must be served from three.ws or a known asset host."
+ data-msg-model-failed="The model file could not be loaded. It may have moved, or it may use a compression format this viewer does not carry."
+ data-msg-no-webgl="This browser could not start WebGL, so the 3D portrait cannot render here. Try another browser or enable hardware acceleration."
+ data-action-agents="Browse agents"
+ data-action-profile="Open profile"
+ data-i18n-attr="data-msg-both:avatar_artifact.err_both;data-msg-not-found:avatar_artifact.err_not_found;data-msg-agent-fetch:avatar_artifact.err_agent_fetch;data-msg-no-avatar:avatar_artifact.err_no_avatar;data-msg-avatar-private:avatar_artifact.err_avatar_private;data-msg-model-blocked:avatar_artifact.err_model_blocked;data-msg-model-failed:avatar_artifact.err_model_failed;data-msg-no-webgl:avatar_artifact.err_no_webgl;data-action-agents:avatar_artifact.action_agents;data-action-profile:avatar_artifact.open_profile"
+ >
<h2 data-i18n="avatar_artifact.couldn_t_load_the_3d_viewer">Couldn’t load the 3D viewer</h2>
<p id="error-detail" data-i18n="avatar_artifact.the_graphics_runtime_failed_to_load_this">
The graphics runtime failed to load. That usually means a network
hiccup, so a reload is worth a try.
</p>
<div class="foot-links">
+ <a id="error-action" href="/agents" hidden data-i18n="avatar_artifact.action_agents">Browse agents</a>
<button type="button" id="artifact-retry" data-i18n="avatar_artifact.retry">Retry</button>
<a href="/" data-i18n="avatar_artifact.back_to_three_ws">Back to three.ws</a>
</div>
@@ -371,13 +414,28 @@
<script>
// Designed failure state, shared by every boot path: a runtime that
- // never arrives, a browser without WebGL, and the watchdog below.
- window.__avatarArtifactFailed = function (detail) {
+ // never arrives, a browser without WebGL, an agent or model that can't
+ // be resolved, and the watchdog below. `action` is the one next move
+ // that fits the failure (the agent's profile, the agent index).
+ window.__avatarArtifactFailed = function (detail, action) {
if (window.__avatarArtifactPainted) return;
+ clearTimeout(window.__avatarArtifactWatchdog);
document.getElementById('loading')?.setAttribute('hidden', '');
if (detail) {
const el = document.getElementById('error-detail');
- if (el) el.textContent = detail;
+ if (el) {
+ el.dataset.i18nOwned = '1';
+ el.textContent = detail;
+ }
+ }
+ const link = document.getElementById('error-action');
+ if (link && action && action.href) {
+ link.href = action.href;
+ if (action.label) {
+ link.dataset.i18nOwned = '1';
+ link.textContent = action.label;
+ }
+ link.removeAttribute('hidden');
}
document.getElementById('error')?.removeAttribute('hidden');
};
@@ -387,14 +445,22 @@
// Watchdog: covers the case where the module script itself never runs
// (asset 404, blocked by an extension), which no in-script catch can
- // see. Cleared by the first painted frame.
- window.__avatarArtifactWatchdog = setTimeout(() => {
- window.__avatarArtifactFailed();
- }, 12000);
+ // see. Cleared by the first painted frame; re-armed by the heartbeat
+ // so a large model that is genuinely still downloading is not called
+ // dead at twelve seconds.
+ window.__avatarArtifactHeartbeat = function () {
+ clearTimeout(window.__avatarArtifactWatchdog);
+ window.__avatarArtifactWatchdog = setTimeout(() => {
+ window.__avatarArtifactFailed();
+ }, 12000);
+ };
+ window.__avatarArtifactHeartbeat();
// Embed + share. The snippet is the page's own URL, so the viewer is
// shareable from inside itself, which is the point of a standalone
- // artifact page.
+ // artifact page. Once a specific artifact resolves, the module hands
+ // its query back through __avatarArtifactSetEmbed so the copied iframe
+ // shows the avatar on screen rather than the house portrait.
(function embedControls() {
const button = document.getElementById('copy-embed');
const status = document.getElementById('copy-status');
@@ -402,12 +468,17 @@
const field = document.getElementById('embed-code');
if (!button || !status || !panel || !field) return;
- const url = new URL('/avatar-artifact', location.href).href;
- const snippet =
- '<iframe src="' +
- url +
- '" width="100%" height="600" style="border:0" loading="lazy" title="Avatar Artifact"></iframe>';
- field.value = snippet;
+ let snippet = '';
+ function setEmbed(query) {
+ const url = new URL('/avatar-artifact' + (query || ''), location.href).href;
+ snippet =
+ '<iframe src="' +
+ url +
+ '" width="100%" height="600" style="border:0" loading="lazy" title="Avatar Artifact"></iframe>';
+ field.value = snippet;
+ }
+ window.__avatarArtifactSetEmbed = setEmbed;
+ setEmbed('');
let clearStatus;
function announce(message) {
@@ -434,455 +505,10 @@
});
})();
</script>
- <script type="module">
- // Three.js ships with the app rather than a third-party CDN: this page
- // is meant to be embedded in other sites, where an extra cross-origin
- // script is a dependency the host never agreed to.
- let THREE;
- try {
- THREE = await import('three');
- } catch {
- window.__avatarArtifactFailed();
- }
- if (THREE) boot(THREE);
-
- function boot(THREE) {
- const W = window.innerWidth,
- H = window.innerHeight;
- const scene = new THREE.Scene();
- const camera = new THREE.PerspectiveCamera(42, W / H, 0.1, 100);
- camera.position.set(0, 1.6, 4.2);
- camera.lookAt(0, 1.6, 0);
-
- // Coarse pointer (phones/tablets) -> lighter render: fewer DPR samples
- // and no shadow pass, so the canvas stays smooth on mobile GPUs.
- const isCoarse =
- window.matchMedia && window.matchMedia('(pointer: coarse)').matches;
- const reduceMotion =
- window.matchMedia &&
- window.matchMedia('(prefers-reduced-motion: reduce)').matches;
-
- let renderer;
- try {
- renderer = new THREE.WebGLRenderer({
- antialias: !isCoarse,
- alpha: true,
- });
- } catch {
- // No WebGL context available: show the designed error state.
- window.__avatarArtifactFailed(
- 'This browser could not start WebGL, so the 3D portrait cannot render here. Try another browser or enable hardware acceleration.',
- );
- return;
- }
- renderer.setSize(W, H);
- renderer.setPixelRatio(Math.min(devicePixelRatio, isCoarse ? 1.5 : 2));
- renderer.shadowMap.enabled = !isCoarse;
- document.body.appendChild(renderer.domElement);
-
- // Lights. Intensities are in physical units (three r155+ dropped the
- // legacy PI scaling), so they read high next to the old CDN build.
- scene.add(new THREE.AmbientLight(0x2a2a5a, 3.8));
-
- const key = new THREE.DirectionalLight(0x99aaff, 6.9);
- key.position.set(2, 5, 4);
- key.castShadow = true;
- scene.add(key);
-
- const rim = new THREE.PointLight(0xff4488, 22, 10, 1.4);
- rim.position.set(-3, 2, -1);
- scene.add(rim);
-
- const fill = new THREE.PointLight(0x4488ff, 12, 8, 1.4);
- fill.position.set(3, 0, 2);
- scene.add(fill);
-
- // Materials
- const skinMat = new THREE.MeshStandardMaterial({
- color: 0x7ba3d4,
- roughness: 0.25,
- metalness: 0.05,
- });
- const darkMat = new THREE.MeshStandardMaterial({
- color: 0x0d1a2e,
- roughness: 0.2,
- metalness: 0.6,
- });
- const irisMat = new THREE.MeshStandardMaterial({
- color: 0x55aaff,
- roughness: 0.05,
- metalness: 0.3,
- emissive: 0x1144cc,
- emissiveIntensity: 0.6,
- });
- const suitMat = new THREE.MeshStandardMaterial({
- color: 0x1a2540,
- roughness: 0.6,
- metalness: 0.3,
- });
- const glareMat = new THREE.MeshStandardMaterial({
- color: 0xffffff,
- roughness: 0,
- metalness: 0,
- transparent: true,
- opacity: 0.55,
- });
-
- // Avatar
- const avatar = new THREE.Group();
- scene.add(avatar);
-
- // Torso
- const torsoMesh = new THREE.Mesh(
- new THREE.CylinderGeometry(0.38, 0.32, 1.0, 20),
- suitMat,
- );
- torsoMesh.position.y = 0.82;
- torsoMesh.castShadow = true;
- avatar.add(torsoMesh);
-
- // Neck
- const neck = new THREE.Mesh(new THREE.CylinderGeometry(0.17, 0.19, 0.28, 16), skinMat);
- neck.position.y = 1.47;
- avatar.add(neck);
-
- // Head group (rotates for gaze tracking)
- const headGroup = new THREE.Group();
- headGroup.position.y = 1.94;
- avatar.add(headGroup);
-
- const headMesh = new THREE.Mesh(new THREE.SphereGeometry(0.52, 40, 40), skinMat);
- headMesh.scale.set(1, 1.08, 0.96);
- headMesh.castShadow = true;
- headGroup.add(headMesh);
-
- // Eyes
- function makeEye(x) {
- const group = new THREE.Group();
- group.position.set(x, 0.06, 0.44);
-
- // White
- const white = new THREE.Mesh(
- new THREE.SphereGeometry(0.105, 20, 20),
- new THREE.MeshStandardMaterial({
- color: 0xddeeff,
- roughness: 0.3,
- metalness: 0,
- }),
- );
- group.add(white);
-
- // Iris
- const iris = new THREE.Mesh(new THREE.SphereGeometry(0.065, 16, 16), irisMat);
- iris.position.z = 0.055;
- group.add(iris);
-
- // Pupil
- const pupil = new THREE.Mesh(new THREE.SphereGeometry(0.036, 12, 12), darkMat);
- pupil.position.z = 0.088;
- group.add(pupil);
-
- // Glare
- const glare = new THREE.Mesh(new THREE.SphereGeometry(0.014, 8, 8), glareMat);
- glare.position.set(0.022, 0.025, 0.1);
- group.add(glare);
-
- return group;
- }
-
- headGroup.add(makeEye(-0.185), makeEye(0.185));
-
- // Eyelids: a blink is a Y scale on these caps.
- function makeLid(x) {
- const lid = new THREE.Mesh(
- new THREE.SphereGeometry(0.112, 20, 10, 0, Math.PI * 2, 0, Math.PI * 0.5),
- new THREE.MeshStandardMaterial({
- color: 0x6a95c0,
- roughness: 0.3,
- side: THREE.FrontSide,
- }),
- );
- lid.position.set(x, 0.06, 0.43);
- lid.rotation.x = Math.PI;
- lid.scale.y = 0.01; // open; blinking animates this to 1
- return lid;
- }
- const leftLid = makeLid(-0.185);
- const rightLid = makeLid(0.185);
- headGroup.add(leftLid, rightLid);
-
- // Eyebrows
- function makeBrow(x) {
- const geo = new THREE.BoxGeometry(0.16, 0.03, 0.04);
- const brow = new THREE.Mesh(
- geo,
- new THREE.MeshStandardMaterial({ color: 0x3a6090, roughness: 0.5 }),
- );
- brow.position.set(x, 0.215, 0.455);
- brow.rotation.z = x > 0 ? -0.12 : 0.12;
- return brow;
- }
- headGroup.add(makeBrow(-0.185), makeBrow(0.185));
-
- // Nose
- const noseMesh = new THREE.Mesh(new THREE.SphereGeometry(0.07, 12, 12), skinMat);
- noseMesh.scale.set(0.7, 0.65, 0.8);
- noseMesh.position.set(0, -0.07, 0.5);
- headGroup.add(noseMesh);
-
- // Mouth
- const mouthGeo = new THREE.TorusGeometry(0.1, 0.025, 8, 20, Math.PI);
- const mouth = new THREE.Mesh(
- mouthGeo,
- new THREE.MeshStandardMaterial({ color: 0x3a5a80, roughness: 0.5 }),
- );
- mouth.position.set(0, -0.2, 0.46);
- mouth.rotation.z = Math.PI;
- headGroup.add(mouth);
-
- // Shoulders / arms
- function makeArm(x) {
- const arm = new THREE.Mesh(
- new THREE.CylinderGeometry(0.11, 0.09, 0.75, 14),
- suitMat,
- );
- arm.position.set(x, 0.85, 0);
- arm.rotation.z = x > 0 ? -0.35 : 0.35;
- arm.castShadow = true;
- return arm;
- }
- avatar.add(makeArm(-0.52), makeArm(0.52));
-
- // Shoulder pads
- function makePad(x) {
- const pad = new THREE.Mesh(new THREE.SphereGeometry(0.18, 16, 16), suitMat);
- pad.scale.set(1, 0.7, 1);
- pad.position.set(x, 1.3, 0);
- return pad;
- }
- avatar.add(makePad(-0.52), makePad(0.52));
-
- // Chest detail (glowing panel)
- const panelMat = new THREE.MeshStandardMaterial({
- color: 0x1155cc,
- emissive: 0x0033aa,
- emissiveIntensity: 1.2,
- roughness: 0.2,
- });
- const panel = new THREE.Mesh(new THREE.BoxGeometry(0.22, 0.14, 0.04), panelMat);
- panel.position.set(0, 0.88, 0.37);
- avatar.add(panel);
-
- // Ground plane (subtle)
- const ground = new THREE.Mesh(
- new THREE.CircleGeometry(3, 48),
- new THREE.MeshStandardMaterial({ color: 0x0a0a20, roughness: 0.9, metalness: 0.1 }),
- );
- ground.rotation.x = -Math.PI / 2;
- ground.receiveShadow = true;
- scene.add(ground);
-
- // Fog
- scene.fog = new THREE.FogExp2(0x070714, 0.06);
-
- // Particles
- const pCount = 120;
- const pPos = new Float32Array(pCount * 3);
- const pVel = new Float32Array(pCount);
- for (let i = 0; i < pCount; i++) {
- pPos[i * 3] = (Math.random() - 0.5) * 8;
- pPos[i * 3 + 1] = Math.random() * 5;
- pPos[i * 3 + 2] = (Math.random() - 0.5) * 8;
- pVel[i] = 0.003 + Math.random() * 0.008;
- }
- const pGeo = new THREE.BufferGeometry();
- pGeo.setAttribute('position', new THREE.BufferAttribute(pPos, 3));
- const pMat = new THREE.PointsMaterial({
- color: 0x6699ff,
- size: 0.04,
- transparent: true,
- opacity: 0.55,
- });
- const pts = new THREE.Points(pGeo, pMat);
- scene.add(pts);
-
- // Input tracking (mouse, touch, keyboard). The avatar's gaze follows
- // a single normalized look-target so every input modality drives the
- // same code path.
- const mouse = { x: 0, y: 0 };
- let keyTarget = null; // when set, keyboard overrides pointer
-
- function aim(clientX, clientY) {
- mouse.x = (clientX / window.innerWidth - 0.5) * 2;
- mouse.y = (clientY / window.innerHeight - 0.5) * 2;
- }
-
- window.addEventListener('mousemove', (e) => {
- keyTarget = null;
- aim(e.clientX, e.clientY);
- });
-
- // Touch: track a finger drag so the portrait is interactive on phones.
- window.addEventListener(
- 'touchmove',
- (e) => {
- const tch = e.touches && e.touches[0];
- if (!tch) return;
- keyTarget = null;
- aim(tch.clientX, tch.clientY);
- },
- { passive: true },
- );
-
- // Keyboard: arrow keys and WASD nudge the gaze, so the viewer is
- // usable without a pointer. Only the arrows suppress their default
- // (scrolling); the letters stay available to the browser.
- const canvasEl = renderer.domElement;
- canvasEl.tabIndex = 0;
- canvasEl.setAttribute('role', 'img');
- canvasEl.setAttribute(
- 'aria-label',
- 'Interactive 3D avatar portrait that follows your cursor, touch, or arrow keys',
- );
- const KEY_STEP = 0.25;
- const KEY_MAP = {
- arrowleft: [-1, 0],
- a: [-1, 0],
- arrowright: [1, 0],
- d: [1, 0],
- arrowup: [0, -1],
- w: [0, -1],
- arrowdown: [0, 1],
- s: [0, 1],
- };
- window.addEventListener('keydown', (e) => {
- if (e.metaKey || e.ctrlKey || e.altKey) return;
- const target = e.target;
- // Never steal a keystroke aimed at the embed field or a control.
- if (target && (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA')) return;
- const k = e.key.toLowerCase();
- const v = KEY_MAP[k];
- if (!v) return;
- if (k.startsWith('arrow')) e.preventDefault();
- if (!keyTarget) keyTarget = { x: mouse.x, y: mouse.y };
- keyTarget.x = Math.max(-1, Math.min(1, keyTarget.x + v[0] * KEY_STEP));
- keyTarget.y = Math.max(-1, Math.min(1, keyTarget.y + v[1] * KEY_STEP));
- mouse.x = keyTarget.x;
- mouse.y = keyTarget.y;
- });
-
- // Animate
- let t = 0;
- let blinkTimer = 0;
- let blinkInterval = 3 + Math.random() * 3;
- let blinking = false;
- let blinkT = 0;
- let firstFramePainted = false;
-
- const targetHeadRot = { x: 0, y: 0 };
- const currentHeadRot = { x: 0, y: 0 };
-
- function frame() {
- t += 0.016;
-
- // Breathing
- const breathe = reduceMotion ? 0 : Math.sin(t * 1.15) * 0.025;
- torsoMesh.scale.y = 1 + breathe;
- torsoMesh.position.y = 0.82 + breathe * 0.3;
-
- // Chest glow pulse
- panelMat.emissiveIntensity = reduceMotion ? 1.0 : 1.0 + Math.sin(t * 2.3) * 0.3;
-
- // Head follows the look-target (smoothed)
- targetHeadRot.y = mouse.x * 0.35;
- targetHeadRot.x = -mouse.y * 0.2;
- currentHeadRot.x += (targetHeadRot.x - currentHeadRot.x) * 0.06;
- currentHeadRot.y += (targetHeadRot.y - currentHeadRot.y) * 0.06;
- headGroup.rotation.x = currentHeadRot.x;
- headGroup.rotation.y = currentHeadRot.y;
-
- // Idle body sway
- avatar.rotation.y = reduceMotion ? 0 : Math.sin(t * 0.35) * 0.06;
-
- // Blink
- if (!reduceMotion) {
- blinkTimer += 0.016;
- if (!blinking && blinkTimer > blinkInterval) {
- blinking = true;
- blinkT = 0;
- blinkInterval = 2.5 + Math.random() * 4;
- blinkTimer = 0;
- }
- if (blinking) {
- blinkT += 0.016;
- const half = 0.09;
- const progress =
- blinkT < half
- ? blinkT / half
- : blinkT < half * 2
- ? 1 - (blinkT - half) / half
- : -1;
- if (progress < 0) {
- leftLid.scale.y = 0.01;
- rightLid.scale.y = 0.01;
- blinking = false;
- } else {
- leftLid.scale.y = progress;
- rightLid.scale.y = progress;
- }
- }
- }
-
- // Particles drift upward
- if (!reduceMotion) {
- const pos = pGeo.attributes.position;
- for (let i = 0; i < pCount; i++) {
- pos.array[i * 3 + 1] += pVel[i];
- if (pos.array[i * 3 + 1] > 5) pos.array[i * 3 + 1] = 0;
- }
- pos.needsUpdate = true;
- pts.rotation.y += 0.0006;
- }
-
- renderer.render(scene, camera);
-
- // Fade out the loading overlay once the first frame is on screen.
- if (!firstFramePainted) {
- firstFramePainted = true;
- window.__avatarArtifactPainted = true;
- clearTimeout(window.__avatarArtifactWatchdog);
- // A slow runtime can trip the watchdog and still arrive; the
- // error state must not outlive a working scene.
- document.getElementById('error')?.setAttribute('hidden', '');
- const loading = document.getElementById('loading');
- if (loading) {
- loading.classList.add('fade');
- setTimeout(() => loading.setAttribute('hidden', ''), 450);
- }
- }
- }
-
- renderer.setAnimationLoop(frame);
-
- // A hidden tab has nothing to animate: stop the loop so an embedded
- // viewer never burns a host page's GPU in the background.
- document.addEventListener('visibilitychange', () => {
- renderer.setAnimationLoop(document.hidden ? null : frame);
- });
-
- // Keep the canvas matched to the viewport (handles orientation changes
- // and mobile browser-chrome resize, not just desktop window drags).
- function onResize() {
- const w = window.innerWidth,
- h = window.innerHeight;
- camera.aspect = w / h;
- camera.updateProjectionMatrix();
- renderer.setSize(w, h);
- }
- window.addEventListener('resize', onResize);
- window.addEventListener('orientationchange', onResize);
- }
- </script>
+ <!-- Scene + artifact loader. Extracted from this page so the viewer is
+ a real module (src/avatar-artifact.js) the bundler can split, not 450
+ lines of markup-embedded script. -->
+ <script type="module" src="/src/avatar-artifact.js"></script>
<!-- Shared bottom-right corner stack. Without it the widgets that mount
themselves there (the Atlas Ctrl+K chip, the language switcher) each fall
back to their own fixed position and pile onto the same pixel. -->
diff --git a/pages/avatar-embed.html b/pages/avatar-embed.html
index 2eb65f872..e0a32bc16 100644
--- a/pages/avatar-embed.html
+++ b/pages/avatar-embed.html
@@ -301,7 +301,12 @@
body.overlay-mode #anim-picker { display: none !important; }
</style>
</head>
- <body>
+ <!-- No floating language picker: this shell is a chrome-less widget that
+ always renders inside a host page, and i18n.js's bottom-right fallback
+ parked a stray "English" pill on top of the avatar in every embed. The
+ copy still translates from the detected locale and ?lang; the host page
+ owns the picker. -->
+ <body data-no-lang-switcher>
<div id="stage"></div>
<div id="name-plate"></div>
<div id="state-pill" aria-live="polite">idle</div>
diff --git a/pages/avatar-wallet-chat.html b/pages/avatar-wallet-chat.html
index 2fc80df7d..fb4b92d54 100644
--- a/pages/avatar-wallet-chat.html
+++ b/pages/avatar-wallet-chat.html
@@ -455,6 +455,10 @@
@media (max-width: 520px) {
#chat { flex-basis: 52%; }
.msg { max-width: 90%; }
+ /* Phone widths: the chip carries network, balance, address, copy and
+ the language picker, and the picker gives up width first. */
+ #wallet { gap: 10px; }
+ #wallet lang-switcher { max-width: 104px; }
}
</style>
@@ -479,34 +483,38 @@
</head>
<body>
<div id="app">
+ <h1 class="sr-only" data-i18n="avatar_wallet_chat.page_h1">Avatar Wallet: a 3D agent that holds a Solana wallet, chats, and can send SOL</h1>
<div id="stage">
<iframe id="avatar-frame" title="3D avatar" allow="autoplay; microphone; camera"></iframe>
<div id="stage-fade"></div>
- <div id="wallet" aria-live="polite">
- <span class="net" id="net"><span class="dot"></span><span id="net-label">…</span></span>
- <span class="bal">
- <span class="amt" id="bal-amt"><span class="skel"></span></span>
- <span class="usd" id="bal-usd"></span>
- </span>
- <a class="addr" id="addr-link" target="_blank" rel="noopener" title="View on Solscan" data-i18n-attr="title:avatar_wallet_chat.view_on_solscan_title">
- <span id="addr-short">—</span>
- </a>
- <button class="copy" id="copy-btn" title="Copy address" aria-label="Copy wallet address" data-i18n-attr="aria-label:avatar_wallet_chat.copy_wallet_address_arialabel;title:avatar_wallet_chat.copy_address_title">
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
- </button>
- </div>
- <div id="fund-hint" role="status">
- <span class="fh-ic" aria-hidden="true">
- <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="6" width="20" height="13" rx="2"/><path d="M2 10h20"/><path d="M7 15h2"/></svg>
- </span>
- <div class="fh-body">
- <div class="fh-title" id="fund-title">Fund your avatar's wallet</div>
- <div class="fh-sub" id="fund-sub">It can't send SOL until there's a balance to send from. Send some SOL to the address below and it'll be ready.</div>
- <div class="fh-addr-row">
- <span class="fh-addr" id="fund-addr" title="Avatar wallet address" data-i18n-attr="title:avatar_wallet_chat.avatar_wallet_address_title">—</span>
- <button class="fh-copy" id="fund-copy" title="Copy address" aria-label="Copy wallet address to fund" data-i18n-attr="aria-label:avatar_wallet_chat.copy_wallet_address_to_fund_arialabel;title:avatar_wallet_chat.copy_address_title_2">
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
- </button>
+ <div id="overlay">
+ <div id="wallet" aria-live="polite">
+ <span class="net" id="net"><span class="dot"></span><span id="net-label">…</span></span>
+ <span class="bal">
+ <span class="amt" id="bal-amt"><span class="skel"></span></span>
+ <span class="usd" id="bal-usd"></span>
+ </span>
+ <a class="addr" id="addr-link" target="_blank" rel="noopener" title="View on Solscan" data-i18n-attr="title:avatar_wallet_chat.view_on_solscan_title">
+ <span id="addr-short">…</span>
+ </a>
+ <button class="copy" id="copy-btn" title="Copy address" aria-label="Copy wallet address" data-i18n-attr="aria-label:avatar_wallet_chat.copy_wallet_address_arialabel;title:avatar_wallet_chat.copy_address_title">
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
+ </button>
+ <lang-switcher></lang-switcher>
+ </div>
+ <div id="fund-hint" role="status">
+ <span class="fh-ic" aria-hidden="true">
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="6" width="20" height="13" rx="2"/><path d="M2 10h20"/><path d="M7 15h2"/></svg>
+ </span>
+ <div class="fh-body">
+ <div class="fh-title" id="fund-title">Fund your avatar's wallet</div>
+ <div class="fh-sub" id="fund-sub">It can't send SOL until there's a balance to send from. Send some SOL to the address below and it'll be ready.</div>
+ <div class="fh-addr-row">
+ <span class="fh-addr" id="fund-addr" title="Avatar wallet address" data-i18n-attr="title:avatar_wallet_chat.avatar_wallet_address_title">…</span>
+ <button class="fh-copy" id="fund-copy" title="Copy address" aria-label="Copy wallet address to fund" data-i18n-attr="aria-label:avatar_wallet_chat.copy_wallet_address_to_fund_arialabel;title:avatar_wallet_chat.copy_address_title_2">
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
+ </button>
+ </div>
</div>
</div>
</div>
@@ -520,12 +528,14 @@
<div class="chips" id="chips"></div>
</div>
</div>
- <form id="composer" autocomplete="off">
- <input id="input" type="text" placeholder="Ask me anything…" aria-label="Message" />
- <button id="send" type="submit" aria-label="Send message" data-i18n-attr="aria-label:avatar_wallet_chat.send_message_arialabel">
- <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 2 11 13"/><path d="M22 2 15 22l-4-9-9-4 20-7z"/></svg>
- </button>
- </form>
+ <div id="composer-bar">
+ <form id="composer" autocomplete="off">
+ <input id="input" type="text" placeholder="Ask me anything…" aria-label="Message" />
+ <button id="send" type="submit" aria-label="Send message" data-i18n-attr="aria-label:avatar_wallet_chat.send_message_arialabel">
+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 2 11 13"/><path d="M22 2 15 22l-4-9-9-4 20-7z"/></svg>
+ </button>
+ </form>
+ </div>
</section>
<div id="toast" role="alert"></div>
@@ -653,7 +663,7 @@
sub.textContent = "It can't send SOL until there's a balance to send from. Send some SOL to the address below and it'll be ready.";
} else {
title.textContent = 'Low balance';
- sub.textContent = `Only ${fmtSol(sol)} SOL—not enough to cover a $1 send plus fees. Top it up at the address below.`;
+ sub.textContent = `Only ${fmtSol(sol)} SOL, not enough to cover a $1 send plus fees. Top it up at the address below.`;
}
el('fund-addr').textContent = wallet.address || '—';
hint.classList.add('show');
@@ -706,6 +716,30 @@
return d;
}
+ // Turn a failed turn into something the reader can act on: the reason the
+ // server actually gave (capacity, rate limit, an offline provider) plus a
+ // control that retries the same message without retyping it.
+ function botError(bubble, message, retryMessage) {
+ bubble.classList.add('errored');
+ bubble.textContent = '';
+ const line = document.createElement('span');
+ line.textContent = message;
+ bubble.appendChild(line);
+ const btn = document.createElement('button');
+ btn.type = 'button';
+ btn.className = 'retry';
+ btn.textContent = 'Try again';
+ btn.addEventListener('click', () => {
+ const prev = bubble.previousElementSibling;
+ bubble.remove();
+ if (prev?.classList.contains('user')) prev.remove();
+ if (history[history.length - 1]?.role === 'user') history.pop();
+ ask(retryMessage);
+ });
+ bubble.appendChild(btn);
+ log.scrollTop = log.scrollHeight;
+ }
+
function paymentCard(usd, to) {
clearEmpty();
const card = document.createElement('div');
@@ -751,7 +785,7 @@
const data = await r.json().catch(() => ({}));
if (!r.ok || !data.ok) throw new Error(data.error_description || data.message || `send failed (${r.status})`);
card.ok(data);
- avatarSpeak(`Done — I just sent ${fmtSol(data.sol)} SOL, about a dollar, to your wallet.`);
+ avatarSpeak(`Done. I just sent ${fmtSol(data.sol)} SOL, about a dollar, to your wallet.`);
avatarGesture('celebrate');
refreshWallet();
} catch (err) {
@@ -778,7 +812,7 @@
chip.className = 'gov-chip';
chip.innerHTML =
'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/><path d="M9 12l2 2 4-4"/></svg>' +
- `<span>Send held by <a href="/ibm/x402-demo" target="_blank" rel="noopener">IBM Granite Guardian</a> — ${escapeHtml(reason)}.</span>`;
+ `<span>Send held by <a href="/ibm/x402-demo" target="_blank" rel="noopener">IBM Granite Guardian</a>: ${escapeHtml(reason)}.</span>`;
log.appendChild(chip);
log.scrollTop = log.scrollHeight;
}
@@ -809,7 +843,13 @@
headers: { 'content-type': 'application/json' },
body: JSON.stringify(body),
});
- if (!r.ok || !r.body) throw new Error(`chat ${r.status}`);
+ // The chat API answers a refusal with a JSON body that names the
+ // cause ("at capacity right now", a rejected model). Surface that
+ // sentence instead of a bare status code the reader can't act on.
+ if (!r.ok || !r.body) {
+ const detail = await r.json().catch(() => null);
+ throw new Error(detail?.error_description || detail?.message || `The chat service answered ${r.status}. Try again in a moment.`);
+ }
const reader = r.body.getReader();
const dec = new TextDecoder();
@@ -847,8 +887,12 @@
governanceNote(governance);
await runActions(actions);
} catch (err) {
- bot.textContent = 'I had trouble reaching my brain. Try again in a moment.';
- toast(err.message || 'chat failed');
+ // A dead fetch carries no server sentence, only "Failed to fetch",
+ // which tells the reader nothing. Name the connection instead.
+ const offline = !err.message || /failed to fetch|networkerror|load failed/i.test(err.message);
+ const reason = offline ? "I couldn't reach my brain. Check your connection and try again." : err.message;
+ botError(bot, reason, message);
+ toast(reason);
} finally {
busy = false;
sendBtn.disabled = false;
@@ -901,7 +945,7 @@
if (t.direction !== 'in') continue;
receiveCard(t);
toast('Received ' + fmtSol(t.sol) + ' SOL' + (t.usd != null ? ' ($' + t.usd.toFixed(2) + ')' : ''));
- avatarSpeak('I just received ' + fmtSol(t.sol) + ' SOL' + (t.usd != null ? ', about $' + t.usd.toFixed(2) : '') + ' — thank you!');
+ avatarSpeak('I just received ' + fmtSol(t.sol) + ' SOL' + (t.usd != null ? ', about $' + t.usd.toFixed(2) : '') + '. Thank you!');
avatarGesture('celebrate');
refreshWallet();
}
diff --git a/pages/bnb-latency.html b/pages/bnb-latency.html
index 9f2fe027b..c19dee3c2 100644
--- a/pages/bnb-latency.html
+++ b/pages/bnb-latency.html
@@ -174,6 +174,12 @@
font-weight: 500;
margin-left: 6px;
}
+ /* A reading whose chain has gone quiet: dimmed so it can never be
+ mistaken for the live number, and paired with its age in the
+ sub-line below. */
+ .bnbl-headline-num.bnbl-stale {
+ opacity: 0.45;
+ }
.bnbl-headline-sub {
font-size: 13.5px;
color: var(--ink-dim, #888);
@@ -229,6 +235,13 @@
outline: 2px solid rgba(255, 255, 255, 0.4);
outline-offset: 2px;
}
+ .bnbl-retry:disabled {
+ opacity: 0.55;
+ cursor: progress;
+ }
+ .bnbl-retry:disabled:hover {
+ background: var(--surface-2, rgba(255, 255, 255, 0.05));
+ }
/* ── Race grid ────────────────────────────────────────────────── */
.bnbl-race-section {
diff --git a/pages/brain.html b/pages/brain.html
index 11de3fbc0..79c437051 100644
--- a/pages/brain.html
+++ b/pages/brain.html
@@ -43,7 +43,7 @@
<aside class="br-side" id="brSide">
<div class="br-side-head">
<span class="br-side-title" data-i18n="brain.sessions">Sessions</span>
- <button class="br-side-new" id="brNewChat" title="New session" data-i18n="brain.new" data-i18n-attr="title:brain.new_session_title">+ New</button>
+ <button class="br-side-new" id="brNewChat" type="button" title="New session" data-i18n="brain.new" data-i18n-attr="title:brain.new_session_title">+ New</button>
</div>
<div class="br-sessions" id="brSessions"></div>
<div class="br-side-persona" id="brSidePersona">
@@ -51,18 +51,20 @@
<div class="br-persona-mini" id="brPersonaMini">
<div class="br-persona-mini-tone" id="brMiniTone"></div>
<div class="br-persona-mini-style" id="brMiniStyle"></div>
- <button class="br-persona-mini-clear" id="brMiniClear" data-i18n="brain.clear_persona">Clear persona</button>
+ <button class="br-persona-mini-clear" id="brMiniClear" type="button" data-i18n="brain.clear_persona">Clear persona</button>
</div>
<button class="br-btn br-btn-secondary br-btn-sm" id="brBuildPersonaBtn" style="width:100%" data-i18n="brain.build_persona">Build Persona</button>
</div>
</aside>
+ <div class="br-side-backdrop" id="brSideBackdrop"></div>
<div class="br-body">
<div class="br-topbar">
- <button class="br-tab active" data-tab="persona" data-i18n-html="brain.persona">Persona<span class="br-tab-badge" id="brPersonaBadge"></span></button>
- <button class="br-tab" data-tab="playground" data-i18n="brain.playground">Playground</button>
+ <button class="br-side-toggle" id="brSideToggle" type="button" aria-expanded="false" aria-controls="brSide" aria-label="Show sessions">☰</button>
+ <button class="br-tab active" type="button" data-tab="persona" data-i18n-html="brain.persona">Persona<span class="br-tab-badge" id="brPersonaBadge"></span></button>
+ <button class="br-tab" type="button" data-tab="playground" data-i18n="brain.playground">Playground</button>
<div class="br-topbar-right">
- <button class="br-topbar-btn" id="brExport" data-i18n="brain.export">Export</button>
+ <button class="br-topbar-btn" id="brExport" type="button" data-i18n="brain.export">Export</button>
<a href="/dashboard/agents" class="br-topbar-btn" data-i18n="brain.my_agents">My Agents</a>
</div>
</div>
@@ -74,8 +76,8 @@
<!-- Agent target bar -->
<div class="br-agent-bar" id="brAgentBar">
- <span class="br-agent-bar-label" data-i18n="brain.persona_for">Persona for</span>
- <select class="br-agent-bar-sel" id="brAgentSelect">
+ <label class="br-agent-bar-label" for="brAgentSelect" data-i18n="brain.persona_for">Persona for</label>
+ <select class="br-agent-bar-sel" id="brAgentSelect" disabled>
<option value="" data-i18n="brain.loading_agents">Loading agents…</option>
</select>
<a href="/dashboard/agents" class="br-agent-bar-manage" data-i18n="brain.manage_agents">Manage agents</a>
@@ -95,6 +97,7 @@
<div class="br-describe-divider"><span data-i18n="brain.or_describe_your_agent">or describe your agent</span></div>
<div class="br-describe-wrap">
<textarea class="br-describe-input" id="brDescribeInput"
+ aria-label="Describe your agent's personality"
placeholder="A sharp crypto trader who speaks plainly and hates buzzwords. Direct, a little sardonic, always on-chain."
rows="2"></textarea>
<div class="br-describe-hint">Press Enter to generate · Shift+Enter for new line</div>
@@ -102,7 +105,7 @@
</div>
<!-- Loading -->
- <div class="br-loading" id="brLoading">
+ <div class="br-loading" id="brLoading" role="status">
<div class="br-loading-spinner"></div>
<span data-i18n="brain.synthesizing_persona">Synthesizing persona…</span>
</div>
@@ -112,9 +115,9 @@
<span class="br-status-icon">✓</span>
<span class="br-status-text" id="brStatusText"></span>
<div class="br-status-actions">
- <button class="br-status-btn" id="brTestInPlayground" data-i18n="brain.test_it">Test it</button>
- <button class="br-status-btn" id="brToggleAdvanced" data-i18n="brain.customize">Customize</button>
- <button class="br-status-btn br-status-btn-clear" id="brResetPersona" data-i18n="brain.clear">Clear</button>
+ <button class="br-status-btn" id="brTestInPlayground" type="button" data-i18n="brain.test_it">Test it</button>
+ <button class="br-status-btn" id="brToggleAdvanced" type="button" data-i18n="brain.customize">Customize</button>
+ <button class="br-status-btn br-status-btn-clear" id="brResetPersona" type="button" data-i18n="brain.clear">Clear</button>
</div>
</div>
@@ -157,11 +160,11 @@
<!-- Inline editor (hidden by default) -->
<div class="br-pc-edit-body" id="brPcEditBody" style="display:none">
<div class="br-edit-row">
- <label class="br-edit-label" data-i18n="brain.tone">Tone</label>
+ <label class="br-edit-label" for="brEditTone" data-i18n="brain.tone">Tone</label>
<input class="br-edit-input" id="brEditTone" />
</div>
<div class="br-edit-row">
- <label class="br-edit-label" data-i18n="brain.style">Style</label>
+ <label class="br-edit-label" for="brEditStyle" data-i18n="brain.style">Style</label>
<select class="br-agent-select" id="brEditStyle" style="width:100%">
<option value="terse" data-i18n="brain.terse">Terse</option>
<option value="detailed" data-i18n="brain.detailed">Detailed</option>
@@ -171,19 +174,19 @@
</select>
</div>
<div class="br-edit-row">
- <label class="br-edit-label" data-i18n="brain.vocabulary">Vocabulary</label>
+ <label class="br-edit-label" for="brEditVocab" data-i18n="brain.vocabulary">Vocabulary</label>
<input class="br-edit-input" id="brEditVocab" placeholder="Comma-separated" />
</div>
<div class="br-edit-row">
- <label class="br-edit-label" data-i18n="brain.interests">Interests</label>
+ <label class="br-edit-label" for="brEditInterests" data-i18n="brain.interests">Interests</label>
<input class="br-edit-input" id="brEditInterests" placeholder="Comma-separated" />
</div>
<div class="br-edit-row">
- <label class="br-edit-label" data-i18n="brain.don_t_say">Don't Say</label>
+ <label class="br-edit-label" for="brEditDont" data-i18n="brain.don_t_say">Don't Say</label>
<input class="br-edit-input" id="brEditDont" placeholder="Comma-separated" />
</div>
<div class="br-edit-row">
- <label class="br-edit-label" data-i18n="brain.greeting">Greeting</label>
+ <label class="br-edit-label" for="brEditGreet" data-i18n="brain.greeting">Greeting</label>
<textarea class="br-edit-textarea" id="brEditGreet" rows="2"></textarea>
</div>
<div class="br-actions" style="justify-content:flex-start">
@@ -202,9 +205,9 @@
<div class="br-panel" id="brPanelPlayground">
<div class="br-play">
<div class="br-play-bar" id="brPlayBar">
- <div class="br-mode-toggle">
- <button class="br-mode-btn active" data-mode="compare" data-i18n="brain.compare">Compare</button>
- <button class="br-mode-btn" data-mode="chat" data-i18n="brain.chat">Chat</button>
+ <div class="br-mode-toggle" role="group" aria-label="Playground mode">
+ <button class="br-mode-btn active" type="button" data-mode="compare" aria-pressed="true" data-i18n="brain.compare">Compare</button>
+ <button class="br-mode-btn" type="button" data-mode="chat" aria-pressed="false" data-i18n="brain.chat">Chat</button>
</div>
<span class="br-play-label" id="brPlayLabel" data-i18n="brain.models">Models</span>
<div id="brPlayControls"></div>
@@ -212,18 +215,18 @@
<div class="br-persona-banner" id="brPersonaBanner">
<span class="br-persona-banner-dot"></span>
Persona active: <strong id="brBannerTone"></strong>
- <button class="br-persona-banner-dismiss" id="brBannerDismiss" data-i18n="brain.disable_for_session">Disable for session</button>
+ <button class="br-persona-banner-dismiss" id="brBannerDismiss" type="button" data-i18n="brain.disable_for_session">Disable for session</button>
</div>
<div class="br-canvas" id="brCanvas"></div>
<div class="br-input-wrap">
- <div class="br-notice" id="brNotice"></div>
+ <div class="br-notice" id="brNotice" role="status"></div>
<details class="br-sys-details" id="brSysDetails">
<summary data-i18n="brain.system_prompt">System prompt</summary>
- <textarea class="br-sys-textarea" id="brSystem" placeholder="You are a helpful assistant..." rows="3"></textarea>
+ <textarea class="br-sys-textarea" id="brSystem" aria-label="System prompt" placeholder="You are a helpful assistant..." rows="3"></textarea>
</details>
<div class="br-input-row">
- <textarea class="br-prompt" id="brPrompt" placeholder="Send a message..." rows="1"></textarea>
- <button class="br-send" id="brSend" data-i18n="brain.send">Send</button>
+ <textarea class="br-prompt" id="brPrompt" aria-label="Message" placeholder="Send a message..." rows="1"></textarea>
+ <button class="br-send" id="brSend" type="button" data-i18n="brain.send">Send</button>
</div>
<div class="br-hint">Ctrl+Enter to send</div>
</div>
@@ -232,7 +235,7 @@
</div>
</div>
- <div class="br-toast" id="brToast"></div>
+ <div class="br-toast" id="brToast" role="status" aria-live="polite"></div>
<script src="/nav.js" defer></script>
<script type="module" src="/src/brain.js"></script>
diff --git a/pages/bundles.html b/pages/bundles.html
index 59f2d3f6e..67aab5274 100644
--- a/pages/bundles.html
+++ b/pages/bundles.html
@@ -304,7 +304,7 @@
<section class="bd-section" aria-labelledby="bd-live-h">
<h2 id="bd-live-h">Published bundles</h2>
- <p>Live on this agent right now. Buyers see these on the agent's marketplace listing; one payment unlocks every skill inside.</p>
+ <p>Live on this agent right now, served publicly at <code>/api/agents/&lt;id&gt;/bundles</code> and bought in one payment that unlocks every skill inside. <a href="/docs/skill-bundles">How checkout works</a>.</p>
<div id="bd-list" class="bd-list"></div>
<div id="bd-list-empty" class="bd-note bd-hide" style="margin-top:14px"></div>
</section>
@@ -776,7 +776,7 @@
if (!bundles.length) {
list.innerHTML = '';
note.classList.remove('bd-note--error');
- note.innerHTML = '<b>No bundles yet.</b> Pick two skills above, set a price, and publish. Buyers will see it on this agent’s listing.';
+ note.innerHTML = '<b>No bundles yet.</b> Pick two skills above, set a price, and publish. It goes live on this agent immediately.';
show(note, true);
return;
}
diff --git a/pages/capture.html b/pages/capture.html
index afeaf04ad..b7f8739f2 100644
--- a/pages/capture.html
+++ b/pages/capture.html
@@ -59,6 +59,10 @@
.pc-head a { color: var(--text, #f6f6f6); }
.pc-layout { display: grid; grid-template-columns: 1fr 320px; gap: 18px; margin-top: 28px; align-items: start; }
+ /* Grid items default to min-width:auto, so the stage's aspect-ratio plus its
+ min-height would force a 553px min-content width and scroll the page
+ sideways on a phone. Let the track win instead. */
+ .pc-layout > * { min-width: 0; }
/* Stage */
.pc-stage {
@@ -85,10 +89,14 @@
animation: pc-spin 0.8s linear infinite;
}
@keyframes pc-spin { to { transform: rotate(360deg); } }
- .pc-overlay h3 { font-family: var(--font-display, 'Space Grotesk', sans-serif); font-size: 17px; margin: 0; color: var(--text, #f6f6f6); }
- .pc-overlay p { font-size: 13px; color: var(--text-3, #8a8a8a); margin: 0; max-width: 380px; line-height: 1.5; }
- .pc-overlay--drop { pointer-events: auto; cursor: pointer; transition: background 0.15s; }
+ .pc-overlay h3, .pc-overlay-title { font-family: var(--font-display, 'Space Grotesk', sans-serif); font-size: 17px; font-weight: 700; margin: 0; color: var(--text, #f6f6f6); }
+ .pc-overlay p, .pc-overlay-sub { font-size: 13px; color: var(--text-3, #8a8a8a); margin: 0; max-width: 380px; line-height: 1.5; }
+ .pc-overlay--drop {
+ pointer-events: auto; cursor: pointer; transition: background 0.15s;
+ width: 100%; border: 0; background: transparent; font: inherit; color: inherit;
+ }
.pc-overlay--drop:hover, .pc-stage.is-dragover .pc-overlay--drop { background: rgba(255,255,255,0.03); }
+ .pc-overlay--drop:focus-visible { outline: 2px solid var(--text, #fff); outline-offset: -4px; }
.pc-glyph {
width: 56px; height: 56px; border-radius: 14px; display: grid; place-items: center;
color: var(--text, #f6f6f6); background: var(--surface-1, #141414); border: 1px solid var(--hairline-strong, #2a2a2a);
@@ -179,6 +187,13 @@
.pc-note a { color: var(--text-2, #cfcfcf); }
@media (max-width: 880px) { .pc-layout { grid-template-columns: 1fr; } }
+ /* Below ~640px the 16:11 stage would be shorter than its min-height, which
+ is what re-introduces the sideways scroll. Give it a plain viewport-
+ relative height there so width always follows the column. */
+ @media (max-width: 640px) {
+ .pc-stage { aspect-ratio: auto; height: 62vh; min-height: 300px; }
+ .pc-hud-label { max-width: 44%; }
+ }
/* Embed mode (?embed=1) — chrome-less full-bleed stage for the MCP /
agent point-cloud artifact iframe. Hide nav, footer, header, panel. */
@@ -218,13 +233,13 @@
<div class="pc-host" id="pc-host"></div>
<!-- Idle / drop -->
- <div class="pc-overlay pc-overlay--drop" id="pc-idle">
- <div class="pc-glyph">
- <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6"><path d="M12 2 2 7l10 5 10-5-10-5Z"/><path d="M2 17l10 5 10-5"/><path d="M2 12l10 5 10-5"/></svg>
- </div>
- <h3 data-i18n="capture.capture_a_scene_to_begin">Capture a scene to begin</h3>
- <p data-i18n-html="capture.paste_a_video_url_on_the_right">Paste a video URL on the right to reconstruct, drop a <code>.ply</code> here, or try the sample cloud.</p>
- </div>
+ <button class="pc-overlay pc-overlay--drop" id="pc-idle" type="button" aria-label="Choose a .ply file to render" data-i18n-attr="aria-label:capture.choose_a_ply_file_to_render_arialabel">
+ <span class="pc-glyph">
+ <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" aria-hidden="true"><path d="M12 2 2 7l10 5 10-5-10-5Z"/><path d="M2 17l10 5 10-5"/><path d="M2 12l10 5 10-5"/></svg>
+ </span>
+ <span class="pc-overlay-title" data-i18n="capture.capture_a_scene_to_begin">Capture a scene to begin</span>
+ <span class="pc-overlay-sub" data-i18n-html="capture.paste_a_video_url_on_the_right">Paste a video URL on the right to reconstruct, drop a <code>.ply</code> here, or try the sample cloud.</span>
+ </button>
<!-- Loading -->
<div class="pc-overlay" id="pc-loading" hidden>
@@ -279,6 +294,7 @@
Capture from video
</h2>
<div class="pc-field">
+ <label class="pc-label" for="pc-url" data-i18n="capture.video_url">Video URL</label>
<input class="pc-input" id="pc-url" type="url" placeholder="https://…/walkthrough.mp4" autocomplete="off" />
<button class="pc-btn pc-btn--primary" id="pc-run" type="button">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M5 12h14 M13 5l7 7-7 7"/></svg>
@@ -288,21 +304,21 @@
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="m22 8-6 4 6 4V8Z"/><rect x="2" y="6" width="14" height="12" rx="2"/></svg>
Upload a video
</button>
- <input id="pc-video-file" type="file" accept="video/mp4,video/quicktime,video/webm" hidden />
+ <input id="pc-video-file" type="file" accept="video/mp4,video/quicktime,video/webm" hidden aria-label="Video file to reconstruct" data-i18n-attr="aria-label:capture.video_file_to_reconstruct_arialabel" />
</div>
<details class="pc-adv">
<summary data-i18n="capture.reconstruction_settings">Reconstruction settings</summary>
<div class="pc-adv-body">
<div class="pc-row">
<div class="pc-field">
- <span class="pc-label" data-i18n="capture.mode">Mode</span>
+ <label class="pc-label" for="pc-mode" data-i18n="capture.mode">Mode</label>
<select class="pc-select" id="pc-mode">
<option value="streaming" selected data-i18n="capture.streaming">Streaming</option>
<option value="windowed" data-i18n="capture.windowed_3k_frames">Windowed (&gt;3k frames)</option>
</select>
</div>
<div class="pc-field">
- <span class="pc-label" data-i18n="capture.sample_fps">Sample FPS</span>
+ <label class="pc-label" for="pc-fps" data-i18n="capture.sample_fps">Sample FPS</label>
<select class="pc-select" id="pc-fps">
<option value="4">4</option>
<option value="8" selected>8</option>
@@ -311,7 +327,7 @@
</div>
</div>
<div class="pc-field">
- <span class="pc-label" data-i18n="capture.keyframe_interval">Keyframe interval</span>
+ <label class="pc-label" for="pc-kf" data-i18n="capture.keyframe_interval">Keyframe interval</label>
<select class="pc-select" id="pc-kf">
<option value="2" data-i18n="capture.2_denser_slower">2 · denser, slower</option>
<option value="4" selected data-i18n="capture.4_balanced">4 · balanced</option>
@@ -330,6 +346,7 @@
Load a point cloud
</h2>
<div class="pc-field">
+ <label class="pc-label" for="pc-ply-url" data-i18n="capture.point_cloud_url">Point cloud URL</label>
<input class="pc-input" id="pc-ply-url" type="url" placeholder="https://…/scene.ply" autocomplete="off" />
<button class="pc-btn" id="pc-load-url" type="button" data-i18n="capture.render_url">Render URL</button>
</div>
@@ -338,7 +355,7 @@
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 3v12 M7 11l5 4 5-4 M5 21h14"/></svg>
Upload a .ply
</button>
- <input id="pc-file" type="file" accept=".ply" hidden />
+ <input id="pc-file" type="file" accept=".ply" hidden aria-label="Point cloud .ply file" data-i18n-attr="aria-label:capture.point_cloud_ply_file_arialabel" />
<div class="pc-or">or</div>
<button class="pc-sample-btn" id="pc-sample" type="button" data-i18n-html="capture.sample_interior_90k_points"><span class="pc-sample-dot"></span> Sample interior · 90k points</button>
<p class="pc-hint" data-i18n="capture.files_stay_on_your_device_decoding_and">Files stay on your device — decoding and rendering run entirely in your browser.</p>
diff --git a/public/brain.css b/public/brain.css
index c5342e616..8506fae71 100644
--- a/public/brain.css
+++ b/public/brain.css
@@ -695,8 +695,19 @@ body {
color: #4a4a4a;
}
-.br-provider-pills { display: flex; gap: 6px; flex-wrap: wrap; flex: 1; }
+/* The roster runs to 30+ models, so the wrapped pill row scrolls inside a
+ capped height instead of pushing the canvas off the screen. */
+.br-provider-pills {
+ display: flex;
+ gap: 6px;
+ flex-wrap: wrap;
+ flex: 1;
+ max-height: 92px;
+ overflow-y: auto;
+ padding-right: 2px;
+}
.br-pill {
+ font: inherit;
display: inline-flex;
align-items: center;
gap: 5px;
@@ -711,10 +722,11 @@ body {
transition: all 0.12s;
}
.br-pill.on { border-color: var(--pc); color: var(--pc); }
-.br-pill.unavailable {
+/* Disabled rather than pointer-events:none, so the tooltip explaining WHY the
+ model is out still reaches a keyboard and a hover. */
+.br-pill:disabled {
opacity: 0.38;
cursor: not-allowed;
- pointer-events: none;
}
.br-pill-na {
font-size: 9px;
@@ -1073,9 +1085,108 @@ body {
}
@keyframes brSpin { to { transform: rotate(360deg); } }
+/* ── Roster loading / failure states ─────────────────────────────────────── */
+.br-play-status {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ font-size: 12.5px;
+ color: #7b7b7b;
+ flex-wrap: wrap;
+}
+.br-play-status-error { color: #ff8a8a; }
+
+.br-canvas-state {
+ flex: 1;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 12px;
+ padding: 32px 24px;
+ text-align: center;
+ color: #7b7b7b;
+}
+.br-canvas-state h3 {
+ margin: 0;
+ font-size: 15px;
+ font-weight: 700;
+ color: #dde0f0;
+}
+.br-canvas-state p {
+ margin: 0;
+ max-width: 46ch;
+ font-size: 13px;
+ line-height: 1.55;
+}
+.br-canvas-state-error h3 { color: #ff8a8a; }
+
+/* ── Sessions drawer trigger (mobile only) ───────────────────────────────── */
+.br-side-toggle {
+ display: none;
+ background: none;
+ border: none;
+ color: #7b7b7b;
+ font-size: 16px;
+ line-height: 1;
+ padding: 10px 8px;
+ margin-right: 2px;
+ cursor: pointer;
+ border-radius: 7px;
+}
+.br-side-toggle:hover { color: #dde0f0; background: #141414; }
+.br-side-backdrop {
+ display: none;
+ position: fixed;
+ inset: 0;
+ background: rgba(0, 0, 0, 0.6);
+ z-index: 39;
+}
+
+/* ── Focus visibility ────────────────────────────────────────────────────── */
+.br-tab:focus-visible,
+.br-topbar-btn:focus-visible,
+.br-side-toggle:focus-visible,
+.br-side-new:focus-visible,
+.br-sess-name:focus-visible,
+.br-sess-del:focus-visible,
+.br-archetype-chip:focus-visible,
+.br-status-btn:focus-visible,
+.br-mode-btn:focus-visible,
+.br-pill:focus-visible,
+.br-focus-sel:focus-visible,
+.br-col-copy:focus-visible,
+.br-btn:focus-visible,
+.br-send:focus-visible,
+.br-persona-mini-clear:focus-visible,
+.br-persona-banner-dismiss:focus-visible,
+.br-agent-bar-sel:focus-visible,
+.br-agent-bar-manage:focus-visible,
+.br-sys-details summary:focus-visible {
+ outline: 2px solid #5dccff;
+ outline-offset: 2px;
+}
+/* The delete control only fades in on row hover, so keyboard focus has to
+ reveal it too or the ring lands on something invisible. */
+.br-sess-del:focus-visible { opacity: 1; }
+
/* ── Responsive ──────────────────────────────────────────────────────────── */
@media (max-width: 900px) {
- .br-side { display: none; }
+ .br-side-toggle { display: block; }
+ /* Off-canvas rather than display:none, because the session list and the New
+ button live only here, and hiding them stranded every mobile visitor. */
+ .br-side {
+ position: fixed;
+ top: 0;
+ left: 0;
+ bottom: 0;
+ z-index: 40;
+ width: min(280px, 84vw);
+ transform: translateX(-100%);
+ transition: transform 0.22s ease;
+ }
+ .br-side.open { transform: translateX(0); }
+ body.br-side-open .br-side-backdrop { display: block; }
.br-persona-inner { padding: 20px 16px 60px; }
.br-archetype-grid { grid-template-columns: repeat(2, 1fr); }
.br-pc-body { grid-template-columns: 1fr; }
@@ -1090,3 +1201,13 @@ body {
.br-pc-save-wrap { margin-left: 0; width: 100%; }
.br-agent-select { flex: 1; }
}
+/* At 360px and under the tabs plus both topbar actions no longer fit, and the
+ actions were clipped off the right edge. Tighten every element in the row
+ instead of hiding one. */
+@media (max-width: 400px) {
+ .br-topbar { padding: 0 6px; }
+ .br-side-toggle { padding: 10px 6px; margin-right: 0; }
+ .br-tab { padding: 12px 8px; font-size: 12px; }
+ .br-topbar-right { gap: 5px; }
+ .br-topbar-btn { padding: 5px 8px; font-size: 11.5px; }
+}
diff --git a/src/agents-live.js b/src/agents-live.js
index bbde59e4c..4cdf8c10b 100644
--- a/src/agents-live.js
+++ b/src/agents-live.js
@@ -394,7 +394,7 @@ function renderAge(state) {
// beat reveals character by character off a real frame clock and the high/
// celebratory ones carry a severity glow. Honors prefers-reduced-motion.
function paintActivity(state) {
- const { card, entries, name } = state;
+ const { card, entries } = state;
const canvas = card.querySelector('canvas');
const ctx = canvas.getContext('2d');
const W = canvas.width, H = canvas.height;
@@ -407,18 +407,15 @@ function paintActivity(state) {
ctx.fillRect(0, 0, W, H);
ctx.shadowBlur = 0;
- // header
+ // Title bar. Its CONTENT is the live/idle badge, which the card overlays on
+ // exactly this strip: the canvas used to draw the agent name and a dot here
+ // too, and the badge sat straight on top of both, so the name was never
+ // readable. The name already leads the card's info row directly below, so the
+ // strip is chrome only and the badge owns it.
ctx.fillStyle = 'rgba(255,255,255,0.03)';
ctx.fillRect(0, 0, W, 30);
- ctx.beginPath();
- ctx.arc(16, 15, 3.5, 0, Math.PI * 2);
- ctx.fillStyle = 'rgba(120,120,128,0.6)';
- ctx.fill();
- ctx.font = '600 11px Inter, system-ui, sans-serif';
- ctx.fillStyle = 'rgba(255,255,255,0.55)';
ctx.textAlign = 'left';
ctx.textBaseline = 'middle';
- ctx.fillText(`${(name || 'Agent').slice(0, 28)} · activity`, 28, 15);
// Empty → a designed standby card, not a blank void. Three honest variants:
// the stream is being opened, the agent has a real history we have not pulled
diff --git a/src/assistant-frame.js b/src/assistant-frame.js
index 9081e8f78..892b9ef9f 100644
--- a/src/assistant-frame.js
+++ b/src/assistant-frame.js
@@ -571,6 +571,31 @@ function pushHistory(role, content) {
while (history.length > MAX_HISTORY_TURNS * 2) history.shift();
}
+/**
+ * Turn an /api/chat failure into a line the visitor can act on.
+ *
+ * The route already explains itself (`error_description`, plus `retry_after`
+ * seconds when the free provider chain is saturated), so surface that instead
+ * of a bare status code, and name the escape hatch the widget actually has:
+ * the visitor's own Groq or OpenRouter key, set in the settings panel.
+ */
+async function chatErrorMessage(res) {
+ let description = '';
+ let retryAfter = 0;
+ try {
+ const body = await res.json();
+ description = String(body?.error_description || '').trim();
+ retryAfter = Number(body?.retry_after) || 0;
+ } catch {
+ description = '';
+ }
+ if (res.status === 429 || res.status === 503) {
+ const wait = retryAfter ? `Try again in ${retryAfter}s` : 'Try again in a moment';
+ return `${description || 'The free chat lane is busy right now.'} ${wait}, or add your own Groq or OpenRouter key under Settings.`;
+ }
+ return description || `Chat failed (HTTP ${res.status}).`;
+}
+
/** Stream a reply from /api/chat (platform free chain). */
async function chatFree(message, onChunk) {
const res = await fetch('/api/chat', {
@@ -578,10 +603,7 @@ async function chatFree(message, onChunk) {
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ message, history: history.slice(0, -1), system_prompt: systemPrompt() }),
});
- if (!res.ok || !res.body) {
- if (res.status === 429) throw new Error('Too many messages — give it a moment.');
- throw new Error(`Chat failed (HTTP ${res.status}).`);
- }
+ if (!res.ok || !res.body) throw new Error(await chatErrorMessage(res));
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
@@ -697,7 +719,10 @@ async function handleChat(message) {
} catch (err) {
history.pop(); // failed turn doesn't poison the next one
setTalking(false);
- showBubble(err?.message || 'Something went wrong — try again.', { error: true, holdMs: 6000 });
+ // Hold an error as long as it takes to read: the at-capacity line names a
+ // wait and a settings escape hatch, and blinking away at 6s loses both.
+ const text = err?.message || 'Something went wrong, try again.';
+ showBubble(text, { error: true, holdMs: Math.max(6000, estimateSpeechMs(text)) });
}
}
diff --git a/src/assistant-page.js b/src/assistant-page.js
index 8af4fd697..3e84f128e 100644
--- a/src/assistant-page.js
+++ b/src/assistant-page.js
@@ -28,7 +28,7 @@ const greetingInput = document.getElementById('cfg-greeting');
const contextInput = document.getElementById('cfg-context');
const accentInput = document.getElementById('cfg-accent');
const previewStatusEl = document.getElementById('preview-status');
-const previewStatusTextEl = document.getElementById('preview-status-text');
+const previewMsgEls = document.querySelectorAll('.preview-msg');
const previewRetryBtn = document.getElementById('preview-retry');
// ── Snippet rendering ─────────────────────────────────────────────────────
@@ -67,20 +67,37 @@ function snippetText() {
}
// ── Live widget (the real loader, re-inited on every change) ──────────────
-const PREVIEW_COPY = {
- loading: 'Starting the live preview...',
- ready: 'Live preview running in the corner. Every change above re-mounts it.',
- error:
- "The live preview couldn't start (the widget script didn't load). Your snippet " +
- 'above is still correct, and the widget works on your own site.',
-};
-
+//
+// State copy lives in the markup (one .preview-msg span per state) so the i18n
+// catalog pass translates every state; writing it from here would be reverted
+// the moment that async pass landed, and the page would claim it was still
+// starting up long after the widget was running.
function setPreviewState(state) {
previewStatusEl.dataset.state = state;
- previewStatusTextEl.textContent = PREVIEW_COPY[state];
- previewRetryBtn.hidden = state !== 'error';
+ for (const el of previewMsgEls) el.hidden = el.dataset.previewState !== state;
+ previewRetryBtn.hidden = state === 'loading' || state === 'ready';
}
+// The widget is only "running" once the frame inside it reports ready. Until
+// then the loader script having parsed proves nothing: a blocked iframe or an
+// avatar that never loads would otherwise be reported as a healthy preview.
+const FRAME_READY_TIMEOUT_MS = 20000;
+let mountSeq = 0;
+let readySeq = -1;
+let readyTimer = 0;
+
+window.addEventListener('three-assistant', (event) => {
+ const type = event.detail?.type;
+ if (type === 'ready') {
+ readySeq = mountSeq;
+ clearTimeout(readyTimer);
+ setPreviewState('ready');
+ } else if (type === 'error') {
+ clearTimeout(readyTimer);
+ setPreviewState('degraded');
+ }
+});
+
let loaderReady = null;
function ensureLoader() {
if (loaderReady) return loaderReady;
@@ -109,30 +126,50 @@ function removeLoaderTag() {
for (const tag of document.querySelectorAll('script[src="/assistant/v1.js"]')) tag.remove();
}
+// Every config key ends up in the frame URL, so a re-mount tears the iframe
+// down and refetches the avatar. Skip the ones that would change nothing (a
+// re-click on the active swatch, a keystroke that trims to the same value):
+// they cost a GLB download and reset the conversation for no visible gain.
+let mountedSignature = '';
+
let applyTimer = 0;
-function applyLive() {
+function applyLive({ delay = 250, force = false } = {}) {
clearTimeout(applyTimer);
applyTimer = setTimeout(async () => {
+ const signature = JSON.stringify(config);
+ if (!force && signature === mountedSignature && window.ThreeAssistant?.instance) return;
+ if (readySeq < 0) setPreviewState('loading');
try {
await ensureLoader();
const wasOpen = Boolean(window.ThreeAssistant?.instance?.isOpen);
+ const seq = ++mountSeq;
window.ThreeAssistant.init({ ...config, open: wasOpen });
- setPreviewState('ready');
+ mountedSignature = signature;
+ clearTimeout(readyTimer);
+ readyTimer = setTimeout(() => {
+ if (readySeq !== seq) setPreviewState('degraded');
+ }, FRAME_READY_TIMEOUT_MS);
} catch {
+ mountedSignature = '';
setPreviewState('error');
}
- }, 250);
+ }, delay);
}
previewRetryBtn.addEventListener('click', () => {
+ readySeq = -1;
setPreviewState('loading');
- applyLive();
+ applyLive({ delay: 0, force: true });
});
-function update(patch) {
+// Free-text fields get a longer debounce than the discrete controls: a pause
+// mid-sentence should not cost a full widget re-mount.
+const TYPING_DEBOUNCE_MS = 600;
+
+function update(patch, options) {
Object.assign(config, patch);
renderSnippet();
- applyLive();
+ applyLive(options);
}
// ── Control wiring ────────────────────────────────────────────────────────
@@ -142,7 +179,9 @@ avatarSelect.addEventListener('change', () => {
update({ avatar: custom ? avatarUrlInput.value.trim() : avatarSelect.value });
if (custom) avatarUrlInput.focus();
});
-avatarUrlInput.addEventListener('input', () => update({ avatar: avatarUrlInput.value.trim() }));
+avatarUrlInput.addEventListener('input', () =>
+ update({ avatar: avatarUrlInput.value.trim() }, { delay: TYPING_DEBOUNCE_MS }),
+);
for (const swatch of document.querySelectorAll('.swatch')) {
swatch.addEventListener('click', () => {
@@ -171,10 +210,11 @@ for (const btn of document.querySelectorAll('[data-pos]')) {
});
}
-nameInput.addEventListener('input', () => update({ name: nameInput.value.trim() }));
-greetingInput.addEventListener('input', () => update({ greeting: greetingInput.value.trim() }));
-contextInput.addEventListener('input', () => update({ context: contextInput.value.trim() }));
-accentInput.addEventListener('input', () => update({ accent: sanitizeAccent(accentInput.value) }));
+const typing = { delay: TYPING_DEBOUNCE_MS };
+nameInput.addEventListener('input', () => update({ name: nameInput.value.trim() }, typing));
+greetingInput.addEventListener('input', () => update({ greeting: greetingInput.value.trim() }, typing));
+contextInput.addEventListener('input', () => update({ context: contextInput.value.trim() }, typing));
+accentInput.addEventListener('input', () => update({ accent: sanitizeAccent(accentInput.value) }, typing));
let copyBtnLabel = '';
copyBtn.addEventListener('click', async () => {
diff --git a/src/autopilot.js b/src/autopilot.js
index 8f53dab32..85f59cbca 100644
--- a/src/autopilot.js
+++ b/src/autopilot.js
@@ -237,7 +237,7 @@ function activityRow(a, coinsById) {
a.status === 'confirmed'
? `Burned ${a.amount_atomics ? esc(fmtUsdc(a.amount_atomics)) : 'fees'} of ${sym}`
: a.status === 'skipped'
- ? `No buyback for ${sym} — below threshold or empty vault`
+ ? `No buyback for ${sym}: below threshold or empty vault`
: a.status === 'failed'
? `Buyback failed for ${sym}: ${esc((a.error || '').slice(0, 80))}`
: `Buyback queued for ${sym}`;
@@ -246,7 +246,7 @@ function activityRow(a, coinsById) {
a.status === 'confirmed'
? `Distributed ${a.amount_atomics ? esc(fmtUsdc(a.amount_atomics)) : 'fees'} to ${sym} holders`
: a.status === 'skipped'
- ? `No distribution for ${sym} — below threshold or empty vault`
+ ? `No distribution for ${sym}: below threshold or empty vault`
: a.status === 'failed'
? `Distribution failed for ${sym}: ${esc((a.error || '').slice(0, 80))}`
: `Distribution queued for ${sym}`;
@@ -264,6 +264,16 @@ function activityRow(a, coinsById) {
</div>`;
}
+/** Every bare state (empty / signed out / failed) has to leave the activity
+ * column saying something. Left alone it keeps the boot skeletons shimmering,
+ * which reads as "still loading" forever. */
+function renderActivityNote(text) {
+ const el = $('#activity');
+ if (!el) return;
+ el.innerHTML = `<div class="quiet">${esc(text)}</div>`;
+ settle(el);
+}
+
function renderEmpty() {
$('#coins').innerHTML = `
<div class="empty">
@@ -271,7 +281,8 @@ function renderEmpty() {
<p>Launch a coin for one of your agents, then it can run itself here.</p>
<a class="btn primary" href="/dashboard">Launch a coin →</a>
</div>`;
- $('#activity').innerHTML = `<div class="empty" style="border:none;padding:24px 0;text-align:left;color:var(--text-4)">Activity will appear once your coins start acting.</div>`;
+ settle($('#coins'));
+ renderActivityNote('Activity will appear once your coins start acting.');
$('#narrator').style.display = 'none';
}
@@ -282,18 +293,57 @@ function renderSignedOut() {
<p>Connect your three.ws account to control your coins' autonomous buybacks and fee distribution.</p>
<a class="btn primary" href="/dashboard">Go to dashboard →</a>
</div>`;
- $('#activity').innerHTML = '';
+ settle($('#coins'));
+ renderActivityNote('Sign in to see what your agents have been doing on-chain.');
$('#narrator').style.display = 'none';
+ // Nothing here changes until the visitor signs in, so stop the poll rather
+ // than log a 401 every 20 seconds for as long as the tab stays open.
+ stopPolling();
}
function renderError(msg) {
- $('#coins').innerHTML = `<div class="empty"><h3>Couldn't load</h3><p>${esc(msg)}</p><button class="btn" id="retry">Retry</button></div>`;
+ $('#coins').innerHTML = `
+ <div class="empty">
+ <h3>Couldn't load your coins</h3>
+ <p>${esc(msg)}</p>
+ <button class="btn" id="retry" type="button">Retry</button>
+ </div>`;
+ settle($('#coins'));
+ renderActivityNote('Activity is unavailable while the autopilot service is unreachable. It reloads by itself once the connection is back.');
+ $('#narrator').style.display = 'none';
$('#retry')?.addEventListener('click', () => load());
}
// ── Save (debounced per coin) ────────────────────────────────────────────────
const _saveTimers = new Map();
+const _savedTimers = new Map();
+
+/** The card owns the truth about whether its rules reached the database. A
+ * toast disappears; a rule the owner believes they set but that never landed
+ * costs them real fees, so the failure stays on the card with a retry. */
+function setSaveState(card, state, msg) {
+ const el = card.querySelector('[data-role="save-state"]');
+ if (!el) return;
+ clearTimeout(_savedTimers.get(card.dataset.mint));
+ if (!state) {
+ el.removeAttribute('data-state');
+ el.textContent = '';
+ return;
+ }
+ el.dataset.state = state;
+ if (state === 'error') {
+ el.innerHTML = `${esc(msg || 'Not saved')} <button class="save-retry" type="button" data-role="save-retry">Retry</button>`;
+ return;
+ }
+ el.textContent = state === 'saving' ? 'Saving' : 'Saved';
+ if (state === 'saved') {
+ _savedTimers.set(
+ card.dataset.mint,
+ setTimeout(() => setSaveState(card, null), 2600),
+ );
+ }
+}
function collectPolicy(card) {
const get = (f) => card.querySelector(`[data-field="${f}"]`);
@@ -312,6 +362,7 @@ function collectPolicy(card) {
async function savePolicy(card) {
const body = collectPolicy(card);
+ setSaveState(card, 'saving');
try {
const r = await fetch(API, {
method: 'POST',
@@ -323,8 +374,12 @@ async function savePolicy(card) {
const d = await r.json().catch(() => ({}));
throw new Error(d.error_description || d.error || `save failed (${r.status})`);
}
+ setSaveState(card, 'saved');
+ // The coin now has a policy row, so it is no longer running on defaults.
+ card.querySelector('[data-role="default-pill"]')?.remove();
toast('Autopilot updated');
} catch (e) {
+ setSaveState(card, 'error', e.message || 'Not saved');
toast(e.message || 'Save failed', true);
}
}
@@ -333,29 +388,80 @@ function queueSave(card, immediate = false) {
const key = card.dataset.mint;
clearTimeout(_saveTimers.get(key));
if (immediate) {
+ _saveTimers.delete(key);
savePolicy(card);
return;
}
- _saveTimers.set(key, setTimeout(() => savePolicy(card), 600));
+ _saveTimers.set(
+ key,
+ setTimeout(() => {
+ _saveTimers.delete(key);
+ savePolicy(card);
+ }, 600),
+ );
+}
+
+/** Flush anything still sitting in the debounce before the page goes away.
+ * A threshold the owner typed and then navigated off would otherwise be lost
+ * with no sign it never saved. */
+function flushPendingSaves() {
+ if (!_saveTimers.size) return;
+ for (const [key, timer] of _saveTimers) {
+ clearTimeout(timer);
+ const card = $(`.coin-card[data-mint="${CSS.escape(key)}"]`);
+ if (card) savePolicy(card);
+ }
+ _saveTimers.clear();
+}
+
+/** A number field the owner blanked or typed a negative into is coerced to 0 on
+ * the wire; show that in the field too, instead of saving one value and
+ * displaying another. */
+function normalizeAmount(input) {
+ const n = Number(input.value);
+ if (input.value.trim() === '' || !Number.isFinite(n) || n < 0) {
+ input.value = '0';
+ return;
+ }
+ const rounded = parseFloat((Math.round(n * 10 ** USDC_DECIMALS) / 10 ** USDC_DECIMALS).toFixed(USDC_DECIMALS));
+ if (String(rounded) !== input.value) input.value = String(rounded);
+}
+
+function applyFieldSideEffects(card, field, el) {
+ if (field === 'enabled') {
+ const on = el.checked;
+ card.classList.toggle('on', on);
+ const pill = card.querySelector('[data-role="status-pill"]');
+ if (pill) {
+ pill.className = `pill ${on ? 'live' : 'paused'}`;
+ pill.innerHTML = `<span class="dot"></span>${on ? 'Autopilot on' : 'Paused'}`;
+ }
+ }
+ if (field === 'buyback_enabled') card.querySelector('[data-rule="buyback"]').classList.toggle('off', !el.checked);
+ if (field === 'distribute_enabled') card.querySelector('[data-rule="distribute"]').classList.toggle('off', !el.checked);
}
function wireCard(card) {
+ // Checkboxes save on `change` (one deliberate flip, one write). The number
+ // fields listen on `input`: `change` only fires when they lose focus, so a
+ // typed threshold followed by a tab close never reached the server at all.
card.addEventListener('change', (e) => {
const field = e.target.dataset?.field;
- if (!field) return;
- // Reflect master + per-rule enable visually right away.
- if (field === 'enabled') {
- const on = e.target.checked;
- card.classList.toggle('on', on);
- const pill = card.querySelector('[data-role="status-pill"]');
- if (pill) {
- pill.className = `pill ${on ? 'live' : 'paused'}`;
- pill.innerHTML = `<span class="dot"></span>${on ? 'Autopilot on' : 'Paused'}`;
- }
- }
- if (field === 'buyback_enabled') card.querySelector('[data-rule="buyback"]').classList.toggle('off', !e.target.checked);
- if (field === 'distribute_enabled') card.querySelector('[data-rule="distribute"]').classList.toggle('off', !e.target.checked);
- queueSave(card, e.target.type === 'checkbox');
+ if (!field || e.target.type !== 'checkbox') return;
+ applyFieldSideEffects(card, field, e.target);
+ queueSave(card, true);
+ });
+ card.addEventListener('input', (e) => {
+ const field = e.target.dataset?.field;
+ if (!field || e.target.type !== 'number') return;
+ queueSave(card);
+ });
+ card.addEventListener('blur', (e) => {
+ if (e.target.dataset?.field && e.target.type === 'number') normalizeAmount(e.target);
+ }, true);
+ card.addEventListener('click', (e) => {
+ if (!e.target.closest('[data-role="save-retry"]')) return;
+ savePolicy(card);
});
}
@@ -363,29 +469,61 @@ function wireCard(card) {
let _coinsById = new Map();
let _agentImage = null;
+// 'coins' once cards are on the page: the tick then refreshes only the activity
+// feed so it never clobbers a control the owner is editing. In any other state
+// the tick re-runs the full load, so a page that failed to load heals itself
+// the moment the API comes back.
+let _view = 'boot';
+let _pollTimer = null;
+
+function stopPolling() {
+ clearInterval(_pollTimer);
+ _pollTimer = null;
+}
+
+function startPolling() {
+ if (_pollTimer) return;
+ _pollTimer = setInterval(tick, POLL_MS);
+}
+
+function tick() {
+ if (document.hidden) return;
+ if (_view === 'coins') return refreshActivity();
+ return load();
+}
async function load() {
let data;
try {
const r = await fetch(API, { credentials: 'include' });
- if (r.status === 401) return renderSignedOut();
+ if (r.status === 401) {
+ _view = 'signed-out';
+ return renderSignedOut();
+ }
if (!r.ok) {
const d = await r.json().catch(() => ({}));
+ _view = 'error';
return renderError(d.error_description || d.error || `request failed (${r.status})`);
}
data = await r.json();
} catch {
- return renderError('Network error — check your connection and retry.');
+ _view = 'error';
+ return renderError('Network error. Check your connection; this page retries on its own.');
}
const coins = data.coins || [];
- if (!coins.length) return renderEmpty();
+ if (!coins.length) {
+ _view = 'empty';
+ return renderEmpty();
+ }
_coinsById = new Map(coins.map((c) => [c.id, c]));
_agentImage = coins.find((c) => c.image)?.image || null;
$('#coins').innerHTML = coins.map(coinCard).join('');
$('#coins').querySelectorAll('.coin-card').forEach(wireCard);
+ settle($('#coins'));
+ _view = 'coins';
renderActivity(data.activity || []);
narrate(data.activity || [], _coinsById, _agentImage);
@@ -395,27 +533,41 @@ function renderActivity(activity) {
const el = $('#activity');
if (!el) return;
if (!activity.length) {
- el.innerHTML = `<div class="empty" style="border:none;padding:24px 0;text-align:left;color:var(--text-4)">No autonomous actions yet. Your agent acts as fees accumulate past your thresholds.</div>`;
+ renderActivityNote('No autonomous actions yet. Your agent acts as fees accumulate past your thresholds.');
return;
}
el.innerHTML = activity.map((a) => activityRow(a, _coinsById)).join('');
+ settle(el);
}
-/** Lightweight refresh — only the activity feed + narrator, never clobbers
- * the control inputs the user may be editing. */
+/** Lightweight refresh: only the activity feed and the narrator, so it never
+ * clobbers the control inputs the owner may be editing. A failed tick keeps
+ * the last good render on screen; the next one retries. */
async function refreshActivity() {
- if (document.hidden) return;
try {
const r = await fetch(API, { credentials: 'include' });
+ if (r.status === 401) {
+ // The session expired under the page. Fall back to the full load so
+ // the signed-out state replaces stale controls that can no longer save.
+ _view = 'signed-out';
+ return renderSignedOut();
+ }
if (!r.ok) return;
const data = await r.json();
if (data.coins) _coinsById = new Map(data.coins.map((c) => [c.id, c]));
renderActivity(data.activity || []);
narrate(data.activity || [], _coinsById, _agentImage);
} catch {
- /* transient — next tick retries */
+ /* transient: the next tick retries */
}
}
+// A tab that comes back into view after a long sleep should not wait out a
+// whole poll interval before it is current again.
+document.addEventListener('visibilitychange', () => {
+ if (!document.hidden && _pollTimer) tick();
+});
+window.addEventListener('pagehide', flushPendingSaves);
+
load();
-setInterval(refreshActivity, POLL_MS);
+startPolling();
diff --git a/src/avatar-artifact.js b/src/avatar-artifact.js
index 36b806e7b..63804b7df 100644
--- a/src/avatar-artifact.js
+++ b/src/avatar-artifact.js
@@ -57,10 +57,15 @@ function fail(mode, action) {
window.__avatarArtifactFailed(detail || '', action);
}
-/** Replace a translated node's text and drop its key, so i18n can't clobber it. */
+/**
+ * Write live data into a translated node. `data-i18n-owned` is the platform's
+ * hand-off marker (see applyCatalog in src/i18n.js): the catalog pass lands
+ * after an async fetch and would otherwise revert an agent's name back to the
+ * English placeholder.
+ */
function setOwnText(el, text) {
if (!el) return;
- el.removeAttribute('data-i18n');
+ el.dataset.i18nOwned = '1';
el.textContent = text;
}
@@ -464,11 +469,22 @@ function buildArtifactStage(scene, camera, renderer, artifact) {
// every one of them fails to parse.
loader.setMeshoptDecoder(meshoptDecoder);
+ function stop() {
+ fatal = true;
+ renderer.setAnimationLoop(null);
+ }
+
+ // A multi-megabyte GLB on a slow connection legitimately outlives the boot
+ // watchdog, so the download re-arms it on every progress tick. A transfer
+ // that goes quiet for the full window still lands in the error state.
+ window.__avatarArtifactHeartbeat?.();
+
loader.load(
resolveDevR2Url(artifact.url),
(gltf) => {
const root = gltf.scene || gltf.scenes?.[0];
if (!root) {
+ stop();
fail('msgModelFailed');
return;
}
@@ -503,11 +519,13 @@ function buildArtifactStage(scene, camera, renderer, artifact) {
loaded = true;
},
(progress) => {
+ window.__avatarArtifactHeartbeat?.();
if (!progress?.lengthComputable || !els.loading?.dataset.noteProgress) return;
const pct = Math.min(99, Math.round((progress.loaded / progress.total) * 100));
setLoadingNote(els.loading.dataset.noteProgress.replace('{pct}', String(pct)));
},
() => {
+ stop();
fail(
'msgModelFailed',
artifact.href ? { href: artifact.href, label: artifact.linkLabel || '' } : null,
diff --git a/src/bnb-latency-helpers.js b/src/bnb-latency-helpers.js
index 940c89b61..026a72148 100644
--- a/src/bnb-latency-helpers.js
+++ b/src/bnb-latency-helpers.js
@@ -101,6 +101,41 @@ export function sparklineBars(values, { maxBars = 24, floor = 8 } = {}) {
});
}
+/**
+ * The headline BNB readout's state, which needs one more distinction than a
+ * lane does: a headline number that is no longer live must not keep rendering
+ * as if it were. `stale` is "the last poll failed but we DID measure this
+ * chain earlier" (show the old number, visibly marked old, with its age);
+ * `unavailable` is "polls are failing and we never got a reading at all"
+ * (show nothing rather than invent one). Both replace the frozen full-opacity
+ * number the page used to leave on screen through an outage.
+ * @param {{ hasFetchedOnce: boolean, ok: boolean, hasSample?: boolean, hasPrevious?: boolean }} input
+ * @returns {'measuring'|'live'|'stale'|'unavailable'}
+ */
+export function headlineState({ hasFetchedOnce, ok, hasSample = true, hasPrevious = false }) {
+ if (!hasFetchedOnce) return 'measuring';
+ if (ok && hasSample) return 'live';
+ return hasPrevious ? 'stale' : 'unavailable';
+}
+
+/**
+ * Seconds-resolution age label for a measurement taken `ms` ago ("8s ago").
+ * The shared `timeAgo` collapses everything under a minute to "just now",
+ * which is useless on a page that re-measures every few seconds: an outage
+ * that has run for 45 seconds must not read as fresh. Returns `''` for a
+ * missing or invalid age.
+ * @param {number} ms
+ * @returns {string}
+ */
+export function ageLabel(ms) {
+ if (!Number.isFinite(ms) || ms < 0) return '';
+ const s = Math.floor(ms / 1000);
+ if (s < 60) return `${s}s ago`;
+ if (s < 3600) return `${Math.floor(s / 60)}m ago`;
+ if (s < 86400) return `${Math.floor(s / 3600)}h ago`;
+ return `${Math.floor(s / 86400)}d ago`;
+}
+
/**
* Honest speedup ratio between two REAL measured averages ("BNB confirms
* N.Nx faster than Base right now") — always computed from live numbers on
diff --git a/src/bnb-latency.js b/src/bnb-latency.js
index 1f14291ff..cf64503c3 100644
--- a/src/bnb-latency.js
+++ b/src/bnb-latency.js
@@ -8,11 +8,13 @@
// See the bnb-chain campaign, work order 17 (latency proof page; retired, see git history), and 00-CONTEXT.md (verified
// fact #3 — 0.45s blocks live; never claim BEP-670's 250ms target).
-import { escapeHtml as esc, timeAgo } from './shared/coin-format.js';
+import { escapeHtml as esc } from './shared/coin-format.js';
import {
formatBlockTime,
formatBlockNumber,
laneState,
+ headlineState,
+ ageLabel,
allLanesDown,
sparklineBars,
speedupRatio,
@@ -20,6 +22,7 @@ import {
const $ = (id) => document.getElementById(id);
const POLL_MS = 5000;
+const AGE_TICK_MS = 1000;
const MAX_HISTORY = 24;
const prefersReducedMotion =
@@ -36,12 +39,18 @@ const LANE_META = {
};
const LANE_ORDER = ['bnb', 'base', 'ethereum', 'solana'];
-/** @type {Record<string, { hasFetchedOnce: boolean, history: number[], last: any }>} */
+/** @type {Record<string, { hasFetchedOnce: boolean, history: number[], last: any, lastLiveAt: number|null }>} */
const laneStore = {};
-for (const id of LANE_ORDER) laneStore[id] = { hasFetchedOnce: false, history: [], last: null };
+for (const id of LANE_ORDER) laneStore[id] = { hasFetchedOnce: false, history: [], last: null, lastLiveAt: null };
let pollTimer = null;
-let inFlight = false;
+let ageTimer = null;
+/** @type {Promise<void>|null} the in-flight poll, shared by the retry button. */
+let inFlight = null;
+// Epoch ms of the last poll that actually measured something. The "Updated"
+// stamp and every staleness label age off THIS, never off the last request:
+// a request that came back with four dead lanes measured nothing.
+let lastSuccessAt = null;
function renderSkeleton() {
const grid = $('bnbl-grid');
@@ -50,10 +59,10 @@ function renderSkeleton() {
<article class="bnbl-lane" data-lane="${id}">
<div class="bnbl-lane-head">
<span class="bnbl-lane-name">${esc(LANE_META[id].label)}</span>
- <span class="bnbl-lane-status" data-state="measuring">Measuring…</span>
+ <span class="bnbl-lane-status" data-state="measuring" role="status">Measuring…</span>
</div>
<p class="bnbl-lane-kicker">${esc(LANE_META[id].kicker)}</p>
- <div class="bnbl-lane-num" aria-live="polite">
+ <div class="bnbl-lane-num">
<span class="bnbl-spinner" aria-hidden="true"></span>
</div>
<div class="bnbl-sparkline" data-sparkline aria-hidden="true"></div>
@@ -79,7 +88,11 @@ function renderLane(lane) {
el.dataset.state = state;
const pill = el.querySelector('.bnbl-lane-status');
pill.dataset.state = state;
- pill.textContent = state === 'live' ? 'Live' : state === 'reconnecting' ? 'Reconnecting…' : 'Measuring…';
+ // The pill is a role="status" region, so only write when the state really
+ // changed: rewriting the same word every 5s would make a screen reader
+ // re-announce all four lanes twelve times a minute.
+ const pillText = state === 'live' ? 'Live' : state === 'reconnecting' ? 'Reconnecting…' : 'Measuring…';
+ if (pill.textContent !== pillText) pill.textContent = pillText;
const numEl = el.querySelector('.bnbl-lane-num');
if (state === 'live') {
@@ -104,17 +117,35 @@ function renderLane(lane) {
const label = lane.id === 'solana' ? 'slot' : 'block';
metaEl.textContent = `latest ${label} ${formatBlockNumber(lane.latestBlock)} · sampled ${lane.sampleBlocks ?? '—'} real ${label}s`;
} else if (state === 'reconnecting') {
- metaEl.textContent = `RPC unreachable right now — still trying, last live ${store.lastLiveAt ? timeAgo(store.lastLiveAt) : 'reading above'}`;
+ // A lane that has never returned a reading has no "last live" to point
+ // at, so say that plainly instead of referring to a number that isn't
+ // on screen.
+ metaEl.textContent = store.lastLiveAt
+ ? `RPC unreachable right now, still trying. Last live reading ${ageLabel(Date.now() - store.lastLiveAt)}.`
+ : 'RPC unreachable right now, still trying. No successful sample from this chain yet.';
} else {
metaEl.textContent = 'Sampling real blocks off a public RPC — first read lands in a few seconds…';
}
}
+// The headline is the page's loudest claim, so it is the one number that must
+// never keep reading "live" through an outage. `bnbLane` is the CURRENT poll's
+// BNB lane (possibly failed); the last good reading comes from the store.
function renderHeadline(bnbLane) {
const el = $('bnbl-headline-num');
const sub = $('bnbl-headline-sub');
- if (!el) return;
- if (bnbLane?.ok && bnbLane.avgBlockTimeMs > 0) {
+ if (!el || !sub) return;
+ const store = laneStore.bnb;
+ const previous = store.last;
+ const state = headlineState({
+ hasFetchedOnce: store.hasFetchedOnce,
+ ok: Boolean(bnbLane?.ok),
+ hasSample: Boolean(bnbLane?.ok) && bnbLane.avgBlockTimeMs > 0,
+ hasPrevious: Boolean(previous),
+ });
+
+ el.classList.toggle('bnbl-stale', state === 'stale');
+ if (state === 'live') {
el.innerHTML = `${esc(formatBlockTime(bnbLane.avgBlockTimeMs))}<span class="unit">avg block time</span>`;
const base = laneStore.base.last;
const eth = laneStore.ethereum.last;
@@ -125,26 +156,42 @@ function renderHeadline(bnbLane) {
if (vsEth) bits.push(`${esc(vsEth)} faster than Ethereum's live average`);
sub.textContent = bits.length
? bits.join(' · ')
- : `sampled ${bnbLane.sampleBlocks ?? '—'} real blocks off a public BSC RPC, updated ${timeAgo(bnbLane.measuredAt)}`;
+ : bnbLane.sampleBlocks
+ ? `sampled ${bnbLane.sampleBlocks} real blocks off a public BSC RPC`
+ : 'measured off a public BSC RPC on this poll';
+ } else if (state === 'stale') {
+ // Show the old number, visibly marked old, with its real age. The
+ // speedup claims are dropped: comparing a stale BNB reading against a
+ // live one would be exactly the fabricated number this page refuses.
+ el.innerHTML = `${esc(formatBlockTime(previous.avgBlockTimeMs))}<span class="unit">last measured</span>`;
+ sub.textContent = `BSC RPC unreachable right now, reconnecting. This reading is from ${ageLabel(Date.now() - (store.lastLiveAt ?? Date.now()))}, not live.`;
+ } else if (state === 'unavailable') {
+ el.innerHTML = `${esc(formatBlockTime(null))}<span class="unit">no reading yet</span>`;
+ sub.textContent = 'No public BSC RPC has answered yet. Retrying every few seconds.';
} else {
el.innerHTML = `<span class="bnbl-spinner" aria-hidden="true"></span>`;
sub.textContent = 'Measuring live BNB Chain block time from a public RPC…';
}
}
-function renderUpdated(measuredAt) {
+// Ages off the last poll that actually measured something, and is re-rendered
+// on a ticker so a stalled page visibly ages instead of freezing on
+// "Updated just now".
+function renderUpdated() {
const el = $('bnbl-updated');
- if (el && measuredAt) el.textContent = `Updated ${timeAgo(measuredAt)}`;
+ if (!el) return;
+ el.textContent = lastSuccessAt ? `Updated ${ageLabel(Date.now() - lastSuccessAt)}` : '';
}
function renderPageError(show) {
const err = $('bnbl-page-error');
- const race = $('bnbl-race');
- if (!err || !race) return;
+ if (!err) return;
err.hidden = !show;
- race.setAttribute('aria-hidden', show ? 'true' : 'false');
}
+/** The most recent poll's lanes, so the age ticker can re-render them. */
+let lastLanes = [];
+
function applyPayload(payload) {
let anyLive = false;
for (const lane of payload.lanes) {
@@ -155,20 +202,44 @@ function applyPayload(payload) {
store.history.push(lane.avgBlockTimeMs);
if (store.history.length > MAX_HISTORY) store.history.shift();
store.last = lane;
- store.lastLiveAt = lane.measuredAt;
+ store.lastLiveAt = Date.parse(lane.measuredAt) || Date.now();
anyLive = true;
}
renderLane(lane);
}
- const bnbLane = payload.lanes.find((l) => l.id === 'bnb');
- renderHeadline(bnbLane?.ok ? bnbLane : laneStore.bnb.last);
- renderUpdated(payload.measuredAt);
- renderPageError(allLanesDown(payload.lanes) && !anyLive && !Object.values(laneStore).some((s) => s.last));
+ lastLanes = payload.lanes;
+ if (anyLive) lastSuccessAt = Date.now();
+ renderHeadline(payload.lanes.find((l) => l.id === 'bnb'));
+ renderUpdated();
+ // Every lane down is an outage the user can act on (retry), whether it
+ // started on the first poll or after an hour of racing. Gating this on
+ // "no lane has ever been live" kept the banner, and its retry button,
+ // permanently unreachable once the page had loaded once.
+ renderPageError(allLanesDown(payload.lanes));
+}
+
+// Staleness is a function of wall-clock time, not of poll results: without
+// this, an outage's "last measured 4s ago" would sit frozen at 4s forever.
+function tickAges() {
+ renderUpdated();
+ const bnbLane = lastLanes.find((l) => l.id === 'bnb');
+ if (!(bnbLane?.ok && bnbLane.avgBlockTimeMs > 0)) renderHeadline(bnbLane);
+ for (const lane of lastLanes) {
+ if (!lane.ok && laneStore[lane.id]) renderLane(lane);
+ }
}
async function poll() {
- if (inFlight) return;
- inFlight = true;
+ // Return the running request rather than a resolved promise, so the retry
+ // button awaits real work even when it lands mid-poll.
+ if (inFlight) return inFlight;
+ inFlight = runPoll().finally(() => {
+ inFlight = null;
+ });
+ return inFlight;
+}
+
+async function runPoll() {
try {
const res = await fetch('/api/bnb/latency', {
headers: { accept: 'application/json' },
@@ -178,35 +249,48 @@ async function poll() {
const payload = await res.json();
applyPayload(payload);
} catch {
- // A total network failure (not just a down chain — the endpoint itself
- // unreachable): mark every lane reconnecting/measuring via a synthetic
- // all-down payload, same rendering path as a partial outage.
- const synthetic = { lanes: LANE_ORDER.map((id) => ({ id, ok: false })), measuredAt: null };
- applyPayload(synthetic);
- } finally {
- inFlight = false;
+ // A total network failure (not just a down chain: the endpoint itself
+ // unreachable) marks every lane reconnecting via a synthetic all-down
+ // payload, the same rendering path a partial outage takes.
+ applyPayload({ lanes: LANE_ORDER.map((id) => ({ id, ok: false })), measuredAt: null });
}
}
function startPolling() {
poll();
pollTimer = window.setInterval(poll, POLL_MS);
+ ageTimer = window.setInterval(tickAges, AGE_TICK_MS);
}
-function retry() {
- renderPageError(false);
- poll();
+function stopPolling() {
+ if (pollTimer) window.clearInterval(pollTimer);
+ if (ageTimer) window.clearInterval(ageTimer);
+ pollTimer = null;
+ ageTimer = null;
+}
+
+async function retry(btn) {
+ // Leave the outage banner up until the retry actually resolves: hiding it
+ // on click would flash success the page has not earned yet.
+ const label = btn.textContent;
+ btn.disabled = true;
+ btn.textContent = 'Retrying…';
+ try {
+ await poll();
+ } finally {
+ btn.disabled = false;
+ btn.textContent = label;
+ }
}
function init() {
renderSkeleton();
const retryBtn = $('bnbl-retry');
- if (retryBtn) retryBtn.addEventListener('click', retry);
+ if (retryBtn) retryBtn.addEventListener('click', () => retry(retryBtn));
startPolling();
document.addEventListener('visibilitychange', () => {
if (document.hidden) {
- if (pollTimer) window.clearInterval(pollTimer);
- pollTimer = null;
+ stopPolling();
} else if (!pollTimer) {
startPolling();
}
diff --git a/src/brain.js b/src/brain.js
index b6ae5480b..bf4de4838 100644
--- a/src/brain.js
+++ b/src/brain.js
@@ -640,11 +640,7 @@ function renderPlayControls() {
label.textContent = 'Models';
ctrl.innerHTML = `<div class="br-provider-pills">${
[...PMAP.values()].map(p => {
- const cls = [
- 'br-pill',
- state.active.has(p.key) ? 'on' : '',
- !p.available ? 'unavailable' : '',
- ].filter(Boolean).join(' ');
+ const cls = ['br-pill', state.active.has(p.key) ? 'on' : ''].filter(Boolean).join(' ');
return `<button type="button" class="${cls}" style="--pc:${p.color}" data-key="${escHtml(p.key)}"
aria-pressed="${state.active.has(p.key)}"${p.available ? '' : ' disabled'}
title="${escHtml(providerTitle(p))}">
@@ -1120,11 +1116,26 @@ function deleteSession(id) {
function setPlayMode(m) {
state.playMode = m;
- document.querySelectorAll('.br-mode-btn').forEach(b => b.classList.toggle('active', b.dataset.mode === m));
+ document.querySelectorAll('.br-mode-btn').forEach(b => {
+ const on = b.dataset.mode === m;
+ b.classList.toggle('active', on);
+ b.setAttribute('aria-pressed', String(on));
+ });
renderPlayControls();
renderCanvas();
}
+// Below 900px the sessions rail is off-canvas, so the topbar carries the only
+// route to it. Without this the New-session button and the whole session list
+// were unreachable on a phone.
+function setSideOpen(open) {
+ $('brSide').classList.toggle('open', open);
+ document.body.classList.toggle('br-side-open', open);
+ const toggle = $('brSideToggle');
+ toggle.setAttribute('aria-expanded', String(open));
+ toggle.setAttribute('aria-label', open ? 'Hide sessions' : 'Show sessions');
+}
+
// ── Bind playground control events ───────────────────────────────────────────
function bindPlayControlEvents() {
if (state.playMode === 'compare') {
@@ -1158,6 +1169,15 @@ function bindEvents() {
t.addEventListener('click', () => setTab(t.dataset.tab));
});
+ // Sessions drawer (mobile)
+ $('brSideToggle').addEventListener('click', () => {
+ setSideOpen(!$('brSide').classList.contains('open'));
+ });
+ $('brSideBackdrop').addEventListener('click', () => setSideOpen(false));
+ document.addEventListener('keydown', e => {
+ if (e.key === 'Escape' && $('brSide').classList.contains('open')) setSideOpen(false);
+ });
+
// Describe input — Enter submits (Shift+Enter = newline)
$('brDescribeInput').addEventListener('keydown', e => {
if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); synthesizeFromDescription(); }
@@ -1220,6 +1240,7 @@ function bindEvents() {
persistSessions();
renderSidebar();
renderCanvas();
+ setSideOpen(false);
});
// Export
@@ -1230,7 +1251,7 @@ function bindEvents() {
const del = e.target.closest('[data-del]');
if (del) { deleteSession(del.dataset.del); return; }
const item = e.target.closest('[data-id]');
- if (item) loadSession(item.dataset.id);
+ if (item) { loadSession(item.dataset.id); setSideOpen(false); }
});
// Canvas clicks (delegated)
diff --git a/src/chains.css b/src/chains.css
index c40f07ee9..c051393d5 100644
--- a/src/chains.css
+++ b/src/chains.css
@@ -11,12 +11,6 @@
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
}
-/* Rows are informational, not navigable — reset the shared table's pointer
- cursor so nothing signals a click target that doesn't exist. */
-#chains-table .cv-table tbody tr {
- cursor: default;
-}
-
/* Inline dominance bar. Fixed-width track so bars read as a shared scale down
the column; the fill is scaled to the leading chain in chains.js. */
.chains-bar-cell {
diff --git a/src/chains.js b/src/chains.js
index 386b77241..b195b69b2 100644
--- a/src/chains.js
+++ b/src/chains.js
@@ -130,12 +130,14 @@ function renderTable() {
}
if (state.error) {
el.innerHTML =
- '<div class="cv-empty">Chain TVL data is temporarily unavailable. <a href="/chains">Try again</a> shortly.</div>';
+ '<div class="cv-empty">Chain TVL data is temporarily unavailable. The upstream provider did not answer. <button type="button" class="cv-linkbtn" data-act="retry">Try again</button>.</div>';
+ el.querySelector('[data-act="retry"]')?.addEventListener('click', () => load());
return;
}
if (!state.chains.length) {
el.innerHTML =
- '<div class="cv-empty">No chain data to show right now. <a href="/chains">Refresh</a> to retry.</div>';
+ '<div class="cv-empty">No chain TVL is being reported right now. <button type="button" class="cv-linkbtn" data-act="retry">Refresh</button> to check again.</div>';
+ el.querySelector('[data-act="retry"]')?.addEventListener('click', () => load());
return;
}
@@ -149,23 +151,26 @@ function renderTable() {
}
const active = col.key === state.sortKey;
const arrow = active ? (state.sortDir === 'asc' ? '↑' : '↓') : '↕';
- return `<th scope="col" tabindex="0" data-key="${col.key}" class="${col.left ? 'left' : ''} ${col.hide || ''}"${active ? ` aria-sort="${state.sortDir === 'asc' ? 'ascending' : 'descending'}"` : ''}>${esc(col.label)}<span class="arrow" aria-hidden="true">${arrow}</span></th>`;
+ const sort = active ? (state.sortDir === 'asc' ? 'ascending' : 'descending') : 'none';
+ return `<th scope="col" tabindex="0" data-key="${col.key}" aria-sort="${sort}" class="${col.left ? 'left' : ''} ${col.hide || ''}">${esc(col.label)}<span class="arrow" aria-hidden="true">${arrow}</span></th>`;
}).join('');
const body = sortedChains()
.map((c) => {
const barPct = Math.max(2, ((c.share_pct || 0) / maxShare) * 100);
- // Whole row opens the internal /chain/:name detail page; keyboard-accessible.
- const nav = c.name
- ? ` data-href="/chain/${encodeURIComponent(c.name)}" tabindex="0" role="link" aria-label="Open ${esc(c.name)} chain detail"`
- : '';
- return `
- <tr${nav}>
- <td class="rank hide-sm cv-mono">${c.__rank}</td>
- <td class="left name-cell"><span class="inner">
+ // The chain name is a real anchor so the /chain/:name detail page is
+ // crawlable, middle-clickable, and reachable by keyboard as a link. The
+ // row keeps data-href purely as a click convenience, which is why the
+ // <tr> stays a plain table row instead of claiming role="link".
+ const href = c.name ? `/chain/${encodeURIComponent(c.name)}` : '';
+ const inner = `<span class="inner">
<span class="nm">${esc(c.name)}</span>
${c.token_symbol ? `<span class="sym">${esc(c.token_symbol)}</span>` : ''}
- </span></td>
+ </span>`;
+ return `
+ <tr${href ? ` data-href="${esc(href)}"` : ''}>
+ <td class="rank hide-sm cv-mono">${c.__rank}</td>
+ <td class="left name-cell">${href ? `<a href="${esc(href)}">${inner}</a>` : inner}</td>
<td class="price">${esc(formatUsd(c.tvl))}</td>
<td class="pct cv-mono">${(c.share_pct || 0).toFixed(2)}%</td>
<td class="left hide-md chains-bar-cell">
@@ -205,15 +210,13 @@ function renderTable() {
});
});
- // Row → /chain/:name navigation (header clicks sort, never navigate).
+ // Clicking anywhere in the row follows the name cell's link. The anchor
+ // handles its own click (and the whole keyboard path), so bail out on it
+ // rather than navigating twice.
el.querySelectorAll('tr[data-href]').forEach((tr) => {
- const go = () => location.assign(tr.dataset.href);
- tr.addEventListener('click', go);
- tr.addEventListener('keydown', (e) => {
- if (e.key === 'Enter' || e.key === ' ') {
- e.preventDefault();
- go();
- }
+ tr.addEventListener('click', (e) => {
+ if (e.target.closest('a')) return;
+ location.assign(tr.dataset.href);
});
});
}
@@ -221,6 +224,10 @@ function renderTable() {
// ── Boot ──────────────────────────────────────────────────────────────────
async function load() {
+ // A retry re-enters here from the error state, so reset to loading before
+ // painting or the skeleton would be replaced by the stale error message.
+ state.loading = true;
+ state.error = false;
statsSkeleton();
renderTable();
try {
@@ -231,14 +238,23 @@ async function load() {
state.updated_at = data.updated_at || Date.now();
state.loading = false;
state.error = false;
- renderStats();
+ // An empty payload has no totals worth showing: a "$0.00" card would read
+ // as a claim that cross-chain TVL is zero rather than as missing data.
+ if (state.chains.length) {
+ renderStats();
+ $('chains-updated').textContent =
+ `Top ${state.chains.length} chains by TVL · Data: DeFiLlama · updated ${new Date(state.updated_at).toLocaleTimeString('en-US')}`;
+ } else {
+ $('chains-stats').innerHTML = '';
+ $('chains-updated').textContent = '';
+ }
renderTable();
- $('chains-updated').textContent =
- `Top ${state.chains.length} chains by TVL · Data: DeFiLlama · updated ${new Date(state.updated_at).toLocaleTimeString('en-US')}`;
} catch {
state.loading = false;
state.error = true;
+ state.chains = [];
$('chains-stats').innerHTML = '';
+ $('chains-updated').textContent = 'Data: DeFiLlama';
renderTable();
}
}
diff --git a/src/scene-capture.js b/src/scene-capture.js
index 826d51a3a..af7d77163 100644
--- a/src/scene-capture.js
+++ b/src/scene-capture.js
@@ -49,13 +49,21 @@ function showOnly(id) {
}
if (id !== null) $('#pc-hud').hidden = true;
}
+// These two headings ship with a translatable placeholder but are rewritten from
+// here on every state change. `data-i18n-owned` hands ownership to this script so
+// the catalog pass (which lands after an async /api/locale fetch) cannot revert a
+// live "Couldn't fetch that point cloud" back to "Something went wrong".
+function own(el, text) {
+ el.textContent = text;
+ el.setAttribute('data-i18n-owned', '1');
+}
function setLoading(title, sub) {
- $('#pc-loading-title').textContent = title;
+ own($('#pc-loading-title'), title);
if (sub != null) $('#pc-loading-sub').textContent = sub;
showOnly('pc-loading');
}
function setError(title, sub) {
- $('#pc-error-title').textContent = title;
+ own($('#pc-error-title'), title);
$('#pc-error-sub').textContent = sub || '';
showOnly('pc-error');
}
@@ -82,21 +90,26 @@ function setDownload(url, filename) {
function fmt(n) { return n.toLocaleString('en-US'); }
// ── render a point cloud from an ArrayBuffer ──────────────────────────────────
-function renderBuffer(buffer, label, downloadName) {
+const INVALID_PLY = 'Expected a binary or ASCII .ply with xyz + rgb vertices.';
+
+function renderBuffer(buffer, label, downloadName, extra) {
setLoading('Decoding point cloud…', `${(buffer.byteLength / 1024 / 1024).toFixed(1)} MB`);
try {
const v = ensureViewer();
const { count } = v.loadBuffer(buffer);
- setLive(`${label} · ${fmt(count)} points`);
+ // A file that is not a PLY decodes to an empty geometry rather than throwing,
+ // which used to read as a successful "0 points" render over a blank stage.
+ if (!count) throw new Error('no vertices in point cloud');
+ setLive([`${label} · ${fmt(count)} points`, extra].filter(Boolean).join(' · '));
setDownload(URL.createObjectURL(new Blob([buffer])), downloadName);
$('#pc-size').disabled = false;
} catch (err) {
console.error('[scene-capture] decode failed', err);
- setError('That isn’t a valid point cloud', 'Expected a binary or ASCII .ply with xyz + rgb vertices.');
+ setError('That isn’t a valid point cloud', INVALID_PLY);
}
}
-async function loadFromUrl(url, label) {
+async function loadFromUrl(url, label, extra) {
let parsed;
try { parsed = new URL(url, location.href); } catch { setError('That doesn’t look like a URL', url); return; }
setLoading('Fetching point cloud…', parsed.hostname);
@@ -104,7 +117,7 @@ async function loadFromUrl(url, label) {
const res = await fetch(parsed.href);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const buffer = await res.arrayBuffer();
- renderBuffer(buffer, label || 'Point cloud', parsed.pathname.split('/').pop() || 'scene.ply');
+ renderBuffer(buffer, label || 'Point cloud', parsed.pathname.split('/').pop() || 'scene.ply', extra);
} catch (err) {
console.error('[scene-capture] fetch failed', err);
setError('Couldn’t fetch that point cloud', `${err.message}. The host may block cross-origin reads (CORS).`);
@@ -141,6 +154,10 @@ function loadSample() {
}
// ── reconstruction job (real backend) ─────────────────────────────────────────
+const POLL_INTERVAL_MS = 3000;
+const MAX_POLL_MISSES = 8; // ~24s of unreadable polls before we say so
+const POLL_DEADLINE_MS = 20 * 60 * 1000;
+
function stopPolling() {
if (pollTimer) { clearTimeout(pollTimer); pollTimer = null; }
if (elapsedTimer) { clearInterval(elapsedTimer); elapsedTimer = null; }
@@ -243,31 +260,50 @@ async function startCapture() {
processingCopy(Math.round((Date.now() - t0) / 1000), eta);
}, 1000);
+ // A job that never resolves must not poll forever behind a counter that only
+ // climbs. Give up after a run of unreadable polls or past the wall clock.
+ let misses = 0;
+ const giveUp = (title, sub) => {
+ stopPolling();
+ $('#pc-run').disabled = false;
+ setError(title, sub);
+ };
+
const poll = async () => {
+ if (Date.now() - t0 > POLL_DEADLINE_MS) {
+ giveUp('Reconstruction timed out', `The worker did not finish within ${Math.round(POLL_DEADLINE_MS / 60000)} minutes. Try a shorter clip, a lower sample FPS, or a wider keyframe interval.`);
+ return;
+ }
let data;
try {
const res = await fetch(`/api/scene-capture?job=${encodeURIComponent(jobId)}`);
data = await res.json().catch(() => ({}));
- } catch {
- pollTimer = setTimeout(poll, 3000);
+ if (!res.ok) throw new Error(data.message || `HTTP ${res.status}`);
+ misses = 0;
+ } catch (err) {
+ if (++misses >= MAX_POLL_MISSES) {
+ giveUp('Lost contact with the reconstruction', `${err.message}. The job may still be running; reload and paste the video URL again to restart it.`);
+ return;
+ }
+ pollTimer = setTimeout(poll, POLL_INTERVAL_MS);
return;
}
if (data.status === 'done' && data.result_url) {
stopPolling();
$('#pc-run').disabled = false;
const label = data.frames ? `Captured · ${fmt(data.frames)} frames` : 'Captured scene';
- await loadFromUrl(data.result_url, label);
+ // The worker caps a job at its frame budget. Say so, rather than let a
+ // partial reconstruction pass for the whole clip.
+ await loadFromUrl(data.result_url, label, data.frames_truncated ? 'clip truncated to the frame budget' : null);
return;
}
if (data.status === 'failed') {
- stopPolling();
- $('#pc-run').disabled = false;
- setError('Reconstruction failed', data.error || 'The worker reported a failure. Try a shorter or steadier clip.');
+ giveUp('Reconstruction failed', data.error || 'The worker reported a failure. Try a shorter or steadier clip.');
return;
}
- pollTimer = setTimeout(poll, 3000);
+ pollTimer = setTimeout(poll, POLL_INTERVAL_MS);
};
- pollTimer = setTimeout(poll, 3000);
+ pollTimer = setTimeout(poll, POLL_INTERVAL_MS);
}
// ── wiring ────────────────────────────────────────────────────────────────────
diff --git a/tests/bnb-latency-helpers.test.js b/tests/bnb-latency-helpers.test.js
index 1322130b9..bc665a300 100644
--- a/tests/bnb-latency-helpers.test.js
+++ b/tests/bnb-latency-helpers.test.js
@@ -10,6 +10,8 @@ import {
blockIntervals,
rollingAverageFromTimestamps,
laneState,
+ headlineState,
+ ageLabel,
allLanesDown,
sparklineBars,
speedupRatio,
@@ -60,6 +62,42 @@ describe('laneState', () => {
});
});
+describe('headlineState', () => {
+ it('is measuring before the first fetch resolves', () => {
+ expect(headlineState({ hasFetchedOnce: false, ok: false })).toBe('measuring');
+ });
+ it('is live on a fresh good sample', () => {
+ expect(headlineState({ hasFetchedOnce: true, ok: true })).toBe('live');
+ });
+ it('is stale, not live, when a poll fails after an earlier reading', () => {
+ expect(headlineState({ hasFetchedOnce: true, ok: false, hasPrevious: true })).toBe('stale');
+ });
+ it('is unavailable when polls fail and no reading was ever taken', () => {
+ expect(headlineState({ hasFetchedOnce: true, ok: false, hasPrevious: false })).toBe('unavailable');
+ });
+ it('treats an ok response carrying no usable sample as not live', () => {
+ expect(headlineState({ hasFetchedOnce: true, ok: true, hasSample: false, hasPrevious: true })).toBe('stale');
+ });
+});
+
+describe('ageLabel', () => {
+ it('returns an empty label for a missing or negative age', () => {
+ expect(ageLabel(undefined)).toBe('');
+ expect(ageLabel(NaN)).toBe('');
+ expect(ageLabel(-1)).toBe('');
+ });
+ it('keeps seconds resolution where the shared timeAgo would say "just now"', () => {
+ expect(ageLabel(0)).toBe('0s ago');
+ expect(ageLabel(8_400)).toBe('8s ago');
+ expect(ageLabel(59_000)).toBe('59s ago');
+ });
+ it('rolls up to minutes, hours, and days', () => {
+ expect(ageLabel(60_000)).toBe('1m ago');
+ expect(ageLabel(3_600_000)).toBe('1h ago');
+ expect(ageLabel(86_400_000)).toBe('1d ago');
+ });
+});
+
describe('allLanesDown', () => {
it('is false for an empty or missing list — nothing to race yet', () => {
expect(allLanesDown([])).toBe(false);