Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
fix(embeds): give a swallowed third-party chart a deadline and a way out
nirholas238c7e2b4596
diff --git a/src/coin-page.js b/src/coin-page.jsindex c602ae889..9e0f7e70c 100644--- a/src/coin-page.js+++ b/src/coin-page.js@@ -7,6 +7,7 @@// /api/coin/* proxies (CoinGecko + the native three.ws news aggregator) —// never mocked.+import { watchEmbed, renderEmbedFallback, DEFAULT_EMBED_TIMEOUT_MS } from './shared/embed-guard.js';import {formatUsd,formatPrice,@@ -217,72 +218,11 @@ function ensureThemeRemount(coin) {themeObserver.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] });}-// How long a third-party embed gets to show something before we replace it-// with an explanation. Generous: these are heavy terminals on someone else's-// infrastructure. Short enough that a blocked embed does not leave a 300px-// void for the length of the visit.-const EMBED_TIMEOUT_MS = 12_000;--/**- * Replace a dead embed with a designed panel that says what happened and how to- * see the chart anyway. A blocked or down terminal used to leave an empty box- * with no text, which reads as a broken page rather than a blocked third party.- *- * @param {HTMLElement} host- * @param {{ name: string, href: string, label: string, onRetry: () => void }} opts- */-function embedFallback(host, { name, href, label, onRetry }) {- const panel = document.createElement('div');- panel.className = 'cv-chart-state col';- panel.setAttribute('role', 'status');- panel.innerHTML = `- <p>${esc(name)} did not load. It may be blocked by an ad blocker, an extension or your network.</p>- <p><a href="${esc(href)}" target="_blank" rel="noopener nofollow noreferrer">${esc(label)} ↗</a></p>`;- const retry = document.createElement('button');- retry.type = 'button';- retry.className = 'cv-range-btn';- retry.textContent = 'Try again';- retry.addEventListener('click', onRetry);- panel.appendChild(retry);- host.replaceChildren(panel);-}-/**- * Run `onTimeout` unless `cancel()` is called first. Lazy iframes only start- * fetching once they scroll into view, so the clock starts at first- * intersection; starting it at mount would report every below-the-fold embed as- * dead. Browsers without IntersectionObserver start immediately.+ * A terminal iframe that replaces itself with a designed panel when the+ * provider never renders. See src/shared/embed-guard.js for why `load` and+ * `error` alone are not enough on a cross-origin embed.*- * @returns {() => void} cancel- */-function watchdog(el, ms, onTimeout) {- let timer = null;- let observer = null;- const start = () => {- if (timer === null) timer = setTimeout(onTimeout, ms);- };- const cancel = () => {- if (timer !== null) clearTimeout(timer);- timer = null;- observer?.disconnect();- observer = null;- };- if (typeof IntersectionObserver === 'function') {- observer = new IntersectionObserver((entries) => {- if (entries.some((e) => e.isIntersecting)) {- observer.disconnect();- observer = null;- start();- }- });- observer.observe(el);- } else {- start();- }- return cancel;-}--/*** @param {string} src* @param {string} title* @param {{ name: string, href: string, label: string, onRetry: () => void }} fallback@@ -294,16 +234,17 @@ function iframeEl(src, title, fallback) {iframe.loading = 'lazy';iframe.allow = 'clipboard-write';iframe.style.cssText = 'width:100%;height:100%;border:0;display:block';- // A cross-origin frame gives us `load` and `error` and nothing else, and a- // frame a blocker swallows often fires neither. The deadline is what- // actually catches that case; load/error just settle it sooner.- const cancel = watchdog(iframe, EMBED_TIMEOUT_MS, () => {- if (iframe.isConnected) embedFallback(iframe.parentElement || iframe, fallback);+ const fail = () => renderEmbedFallback(iframe.parentElement || iframe, fallback);+ const cancel = watchEmbed(iframe, {+ timeoutMs: DEFAULT_EMBED_TIMEOUT_MS,+ onTimeout: () => {+ if (iframe.isConnected) fail();+ },});iframe.addEventListener('load', cancel);iframe.addEventListener('error', () => {cancel();- embedFallback(iframe.parentElement || iframe, fallback);+ fail();});return iframe;}@@ -336,12 +277,15 @@ function mountTradingView(host, symbol, fallback) {// chart asynchronously, so neither `onerror` alone nor a deadline alone is// enough: onerror catches an outright block, and the deadline catches a// script that loads and then never renders its iframe.- const cancel = watchdog(container, EMBED_TIMEOUT_MS, () => {- if (!widget.querySelector('iframe')) embedFallback(host, fallback);+ const cancel = watchEmbed(container, {+ timeoutMs: DEFAULT_EMBED_TIMEOUT_MS,+ onTimeout: () => {+ if (!widget.querySelector('iframe')) renderEmbedFallback(host, fallback);+ },});script.onerror = () => {cancel();- embedFallback(host, fallback);+ renderEmbedFallback(host, fallback);};container.appendChild(script);host.replaceChildren(container);diff --git a/src/shared/embed-guard.js b/src/shared/embed-guard.jsnew file mode 100644index 000000000..39a16561e--- /dev/null+++ b/src/shared/embed-guard.js@@ -0,0 +1,128 @@+// Failure handling for third-party <iframe> and widget-script embeds.+//+// A cross-origin embed gives the host page almost nothing to work with: `load`+// fires even for the other side's error page, and an embed an ad blocker or a+// network policy swallows outright often fires neither `load` nor `error`. So+// the page sat on a 300px empty box with no text, which reads as "three.ws is+// broken" rather than "your blocker ate DexScreener".+//+// Two pieces, both used by the coin page's chart terminals (TradingView,+// DexScreener, GeckoTerminal):+// watchEmbed() a deadline that only starts once the embed is actually+// on screen, because a lazy iframe below the fold has not+// begun loading and must not be reported as dead.+// embedFallbackNode() the designed replacement: what happened, a link that+// opens the chart on the provider, and a retry.++export const DEFAULT_EMBED_TIMEOUT_MS = 12_000;++/**+ * Call `onTimeout` unless `cancel()` runs first.+ *+ * The clock starts at first intersection, not at mount: `loading="lazy"` frames+ * do not begin fetching until they scroll into view, and starting the timer at+ * mount reported every below-the-fold embed as dead. Where IntersectionObserver+ * is missing the timer starts immediately, which is the safe direction (a false+ * "did not load" beats a permanent skeleton).+ *+ * @param {Element} node+ * @param {object} [opts]+ * @param {number} [opts.timeoutMs]+ * @param {() => void} opts.onTimeout+ * @param {(cb: IntersectionObserverCallback) => IntersectionObserver} [opts.observerFactory] Injectable for tests.+ * @returns {() => void} cancel+ */+export function watchEmbed(node, { timeoutMs = DEFAULT_EMBED_TIMEOUT_MS, onTimeout, observerFactory } = {}) {+ let timer = null;+ let observer = null;+ // Once cancelled, stay cancelled. disconnect() should stop the callback, but+ // an observer that fires one queued entry after disconnect would otherwise+ // restart the clock on an embed the caller already settled.+ let cancelled = false;++ const start = () => {+ if (cancelled || timer !== null) return;+ timer = setTimeout(onTimeout, timeoutMs);+ };+ const cancel = () => {+ cancelled = true;+ if (timer !== null) clearTimeout(timer);+ timer = null;+ observer?.disconnect();+ observer = null;+ };++ const makeObserver = observerFactory+ || (typeof IntersectionObserver === 'function' ? (cb) => new IntersectionObserver(cb) : null);+ if (!makeObserver) {+ start();+ return cancel;+ }+ observer = makeObserver((entries) => {+ if (!entries.some((e) => e.isIntersecting)) return;+ observer?.disconnect();+ observer = null;+ start();+ });+ observer.observe(node);+ return cancel;+}++/**+ * The panel that replaces a dead embed: one sentence naming what failed and the+ * likeliest cause, a link that opens the same chart on the provider's own site,+ * and a retry. Never a bare empty box.+ *+ * @param {object} opts+ * @param {string} opts.name e.g. 'The TradingView chart'.+ * @param {string} opts.href Where to see the same content.+ * @param {string} opts.label Link text (an arrow is appended).+ * @param {() => void} opts.onRetry+ * @param {string} [opts.className] Wrapper classes.+ * @param {string} [opts.buttonClassName] Retry-button classes.+ * @returns {HTMLElement}+ */+export function embedFallbackNode({+ name,+ href,+ label,+ onRetry,+ className = 'cv-chart-state col',+ buttonClassName = 'cv-range-btn',+}) {+ const panel = document.createElement('div');+ panel.className = className;+ panel.setAttribute('role', 'status');++ const why = document.createElement('p');+ why.textContent = `${name} did not load. It may be blocked by an ad blocker, an extension or your network.`;+ panel.appendChild(why);++ const linkRow = document.createElement('p');+ const link = document.createElement('a');+ link.href = href;+ link.target = '_blank';+ link.rel = 'noopener nofollow noreferrer';+ link.textContent = `${label} ↗`;+ linkRow.appendChild(link);+ panel.appendChild(linkRow);++ const retry = document.createElement('button');+ retry.type = 'button';+ retry.className = buttonClassName;+ retry.textContent = 'Try again';+ retry.addEventListener('click', onRetry);+ panel.appendChild(retry);++ return panel;+}++/**+ * Swap a dead embed for the fallback panel, in place.+ *+ * @param {HTMLElement} host The element holding the embed.+ * @param {Parameters<typeof embedFallbackNode>[0]} opts+ */+export function renderEmbedFallback(host, opts) {+ host.replaceChildren(embedFallbackNode(opts));+}diff --git a/tests/embed-guard.test.js b/tests/embed-guard.test.jsnew file mode 100644index 000000000..720fb55e9--- /dev/null+++ b/tests/embed-guard.test.js@@ -0,0 +1,149 @@+// @vitest-environment jsdom+//+// The coin page mounts three third-party chart terminals (TradingView,+// DexScreener, GeckoTerminal) and had no failure handling on any of them. A+// cross-origin embed tells the host page almost nothing: `load` fires even for+// the provider's own error page, and an embed an ad blocker swallows fires+// neither `load` nor `error`. So a blocked terminal left a 300px empty box with+// no text, which reads as "this site is broken".+//+// The guard is timing logic, which is exactly the kind that rots silently, so+// both halves are pinned: the deadline must not start before a lazy iframe is+// on screen (or every below-the-fold embed reports itself dead), and the+// replacement panel must always carry a way out.+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { watchEmbed, embedFallbackNode, renderEmbedFallback, DEFAULT_EMBED_TIMEOUT_MS } from '../src/shared/embed-guard.js';++// A hand-driven IntersectionObserver: the test decides when the node scrolls in.+function fakeObserver() {+ const state = { observed: [], disconnected: false, cb: null };+ const factory = (cb) => {+ state.cb = cb;+ return {+ observe: (node) => state.observed.push(node),+ disconnect: () => { state.disconnected = true; },+ };+ };+ state.enter = () => state.cb?.([{ isIntersecting: true }]);+ state.scrollPast = () => state.cb?.([{ isIntersecting: false }]);+ return { factory, state };+}++describe('watchEmbed', () => {+ beforeEach(() => vi.useFakeTimers());+ afterEach(() => vi.useRealTimers());++ it('does not fire while the embed is still below the fold', () => {+ const onTimeout = vi.fn();+ const { factory } = fakeObserver();+ watchEmbed(document.createElement('iframe'), { timeoutMs: 1000, onTimeout, observerFactory: factory });++ vi.advanceTimersByTime(60_000);++ // A lazy iframe has not begun loading yet, so it cannot have failed.+ expect(onTimeout).not.toHaveBeenCalled();+ });++ it('starts the clock when the embed scrolls into view', () => {+ const onTimeout = vi.fn();+ const { factory, state } = fakeObserver();+ watchEmbed(document.createElement('iframe'), { timeoutMs: 1000, onTimeout, observerFactory: factory });++ state.scrollPast();+ vi.advanceTimersByTime(5000);+ expect(onTimeout).not.toHaveBeenCalled();++ state.enter();+ vi.advanceTimersByTime(999);+ expect(onTimeout).not.toHaveBeenCalled();+ vi.advanceTimersByTime(1);+ expect(onTimeout).toHaveBeenCalledTimes(1);+ });++ it('stops watching once the embed reports it loaded', () => {+ const onTimeout = vi.fn();+ const { factory, state } = fakeObserver();+ const cancel = watchEmbed(document.createElement('iframe'), { timeoutMs: 1000, onTimeout, observerFactory: factory });++ state.enter();+ cancel();+ vi.advanceTimersByTime(60_000);++ expect(onTimeout).not.toHaveBeenCalled();+ expect(state.disconnected).toBe(true);+ });++ it('cancels cleanly before the embed was ever seen, leaking no observer', () => {+ const onTimeout = vi.fn();+ const { factory, state } = fakeObserver();+ const cancel = watchEmbed(document.createElement('iframe'), { timeoutMs: 1000, onTimeout, observerFactory: factory });++ cancel();+ state.enter();+ vi.advanceTimersByTime(60_000);++ expect(onTimeout).not.toHaveBeenCalled();+ expect(state.disconnected).toBe(true);+ });++ it('falls back to starting immediately with no IntersectionObserver', () => {+ // A false "did not load" is the safe direction; a permanent skeleton is not.+ const onTimeout = vi.fn();+ const real = globalThis.IntersectionObserver;+ delete globalThis.IntersectionObserver;+ try {+ watchEmbed(document.createElement('iframe'), { timeoutMs: 1000, onTimeout });+ vi.advanceTimersByTime(1000);+ } finally {+ if (real) globalThis.IntersectionObserver = real;+ }+ expect(onTimeout).toHaveBeenCalledTimes(1);+ });++ it('defaults to a deadline generous enough for a heavy third-party terminal', () => {+ expect(DEFAULT_EMBED_TIMEOUT_MS).toBeGreaterThanOrEqual(10_000);+ });+});++describe('embedFallbackNode', () => {+ const opts = {+ name: 'The DexScreener chart',+ href: 'https://dexscreener.com/solana/FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',+ label: 'Open in DexScreener',+ onRetry: () => {},+ };++ it('says what failed and why, not just that something went wrong', () => {+ const node = embedFallbackNode(opts);+ expect(node.textContent).toContain('The DexScreener chart did not load');+ expect(node.textContent).toMatch(/ad blocker|extension|network/);+ });++ it('always offers a way to see the chart anyway', () => {+ const node = embedFallbackNode(opts);+ const link = node.querySelector('a');+ expect(link.href).toBe(opts.href);+ expect(link.target).toBe('_blank');+ // An untrusted outbound link must not hand the provider window.opener.+ expect(link.rel).toContain('noopener');+ });++ it('offers a retry that actually calls back', () => {+ const onRetry = vi.fn();+ const node = embedFallbackNode({ ...opts, onRetry });+ node.querySelector('button').click();+ expect(onRetry).toHaveBeenCalledTimes(1);+ });++ it('is announced to a screen reader rather than appearing silently', () => {+ expect(embedFallbackNode(opts).getAttribute('role')).toBe('status');+ });++ it('replaces the dead embed in place instead of appending beside it', () => {+ const host = document.createElement('div');+ host.appendChild(document.createElement('iframe'));+ renderEmbedFallback(host, opts);+ expect(host.querySelector('iframe')).toBeNull();+ expect(host.children).toHaveLength(1);+ });+});