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.

feat(embed): embed doctor diagnostics API

nirholas6c1250bf93a1
diff --git a/api/_lib/embed-doctor.js b/api/_lib/embed-doctor.js
new file mode 100644
index 000000000..8debe6c7c
--- /dev/null
+++ b/api/_lib/embed-doctor.js
@@ -0,0 +1,1017 @@
+// Embed Doctor — tells a developer exactly why their `<agent-3d>` embed is not
+// showing up, by loading their real page in a real browser and watching it boot.
+//
+// The problem it replaces: an embed that renders nothing produces no error the
+// developer can act on. The tag is present, the console may be empty, and the
+// cause is one of a dozen unrelated things — a Content-Security-Policy that
+// silently dropped the module, a container with zero height, a private agent id,
+// WebGL disabled in a hardened browser, a copy-pasted duplicate script. Until
+// now the answer lived in a wall of troubleshooting prose in the embed tutorial,
+// which is documentation standing in for a missing tool.
+//
+// ── Shape ─────────────────────────────────────────────────────────────────────
+// The module is split so the decision logic never needs a browser:
+//
+// collectFromUrl / collectFromSnippet → an `observations` object (raw facts)
+// analyze(observations) → { verdict, findings[] } ← PURE
+//
+// `analyze` is a pure function over a plain object. Every rule in it is unit
+// tested against synthetic observations, so the catalogue of failures is
+// verified without booting chromium. The browser layer only gathers facts; it
+// never decides anything.
+//
+// ── Honesty rules ─────────────────────────────────────────────────────────────
+// Two behaviours exist to stop the report lying, and they matter more than any
+// individual check:
+//
+// 1. A check that could not run reports `status: 'unknown'`, never `'pass'`.
+// Reporting an unrun check as healthy is how a diagnostic tool teaches
+// people to distrust it.
+// 2. Findings are ordered by how much they explain. The first finding is the
+// one to fix; the rest are frequently downstream of it (a blocked loader
+// guarantees an un-upgraded element, and saying both with equal weight
+// sends the developer to the wrong line).
+
+import { assertSafePublicUrl, SsrfBlockedError } from './ssrf-guard.js';
+
+/** The custom element the platform's embed runtime registers. */
+export const EMBED_TAG = 'agent-3d';
+
+/** Loader bundles that register {@link EMBED_TAG}. Order is longest-first so a
+ * versioned path is recognised before the generic prefix match. */
+export const LOADER_PATTERNS = [
+ /\/agent-3d\/[^/]+\/agent-3d(\.min)?\.js(\?|$)/i,
+ /\/embed(\/v1)?\.js(\?|$)/i,
+];
+
+/** Attributes that give the element something to load. Without one of these the
+ * element deliberately does nothing (see `src/element.js` → `_hasSource`). */
+export const SOURCE_ATTRIBUTES = ['agent-id', 'src', 'manifest', 'body', 'avatar-id'];
+
+const SEVERITY_RANK = { fatal: 0, error: 1, warn: 2, info: 3 };
+
+/** Verdict from the worst severity present. */
+function verdictFor(findings) {
+ const failing = findings.filter((f) => f.status === 'fail');
+ if (failing.some((f) => f.severity === 'fatal')) return 'broken';
+ if (failing.some((f) => f.severity === 'error')) return 'broken';
+ if (failing.some((f) => f.severity === 'warn')) return 'degraded';
+ if (findings.some((f) => f.status === 'unknown')) return 'inconclusive';
+ return 'healthy';
+}
+
+function isLoaderUrl(url) {
+ if (!url) return false;
+ return LOADER_PATTERNS.some((re) => re.test(String(url)));
+}
+
+/**
+ * Classify a URL as belonging to the embed runtime so network noise from the
+ * host page (analytics, fonts, the site's own bundles) never lands in a report
+ * about the embed.
+ */
+export function isEmbedRelated(url, { platformOrigin = 'https://three.ws' } = {}) {
+ if (!url) return false;
+ const s = String(url);
+ if (isLoaderUrl(s)) return true;
+ try {
+ const host = new URL(s, platformOrigin).host;
+ const platformHost = new URL(platformOrigin).host;
+ if (host === platformHost) return true;
+ // The runtime pulls model + animation bytes from the asset CDN.
+ return /(^|\.)three\.ws$/i.test(host) || /(^|\.)storage\.googleapis\.com$/i.test(host);
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Does this console message describe the browser refusing to run the loader?
+ * CSP violations are the single most common invisible cause: the tag is in the
+ * DOM, the file is fine, and the browser declined to execute it.
+ */
+export function looksLikeCspBlock(text) {
+ if (!text) return false;
+ return /refused to (load|execute|connect)|content security policy|violates the following/i.test(
+ String(text),
+ );
+}
+
+// ── Finding constructors ──────────────────────────────────────────────────────
+// Each returns the full user-facing record: what is wrong, the evidence that
+// proves it, and the exact change that fixes it. A finding with no `fix` is a
+// finding the developer cannot act on, so every failure carries one.
+
+function finding(id, severity, status, title, detail, fix, evidence) {
+ return { id, severity, status, title, detail, fix, evidence: evidence ?? null };
+}
+
+const pass = (id, title, detail, evidence) =>
+ finding(id, 'info', 'pass', title, detail, null, evidence);
+const unknown = (id, title, detail, evidence) =>
+ finding(id, 'info', 'unknown', title, detail, null, evidence);
+
+/**
+ * Turn raw page observations into a ranked, actionable report.
+ *
+ * Pure: no I/O, no clock, no randomness. Everything it knows arrives in `obs`.
+ *
+ * @param {object} obs Observations from {@link collectFromUrl} or {@link collectFromSnippet}.
+ * @returns {{verdict: string, findings: object[], summary: object}}
+ */
+export function analyze(obs) {
+ const findings = [];
+ const page = obs?.page || {};
+ const el = obs?.element || null;
+ const net = Array.isArray(obs?.network) ? obs.network : [];
+ const consoleMsgs = Array.isArray(obs?.console) ? obs.console : [];
+ const pageErrors = Array.isArray(obs?.pageErrors) ? obs.pageErrors : [];
+ const scripts = Array.isArray(obs?.scripts) ? obs.scripts : [];
+
+ // ── 1. The page itself ────────────────────────────────────────────────────
+ if (page.reachable === false) {
+ findings.push(
+ finding(
+ 'page_unreachable',
+ 'fatal',
+ 'fail',
+ 'The page could not be loaded',
+ page.error
+ ? `Loading the URL failed: ${page.error}`
+ : 'The browser could not load this URL, so nothing about the embed could be checked.',
+ 'Confirm the page is published and reachable from the public internet. A page behind a login, a firewall, or on localhost cannot be inspected from our servers — use the snippet mode instead and paste the two tags directly.',
+ { status: page.status ?? null, error: page.error ?? null },
+ ),
+ );
+ // Nothing downstream is knowable. Return early rather than reporting a
+ // cascade of "missing" findings that are all the same problem.
+ return { verdict: 'broken', findings, summary: summarize(findings, obs) };
+ }
+ if (page.status && page.status >= 400) {
+ findings.push(
+ finding(
+ 'page_error_status',
+ 'fatal',
+ 'fail',
+ `The page returned HTTP ${page.status}`,
+ 'The server answered with an error status, so the browser rendered an error page rather than your site.',
+ 'Check the URL for a typo and confirm the page is published. If the page requires a login, our servers see the signed-out version.',
+ { status: page.status, finalUrl: page.finalUrl ?? null },
+ ),
+ );
+ return { verdict: 'broken', findings, summary: summarize(findings, obs) };
+ }
+
+ // ── 2. The loader script ──────────────────────────────────────────────────
+ const loaderTags = scripts.filter((s) => isLoaderUrl(s.src));
+ const loaderRequests = net.filter((r) => isLoaderUrl(r.url));
+ const loaderOk = loaderRequests.find((r) => r.ok);
+ const cspMessages = consoleMsgs.filter((m) => looksLikeCspBlock(m.text));
+
+ if (!loaderTags.length && !loaderRequests.length) {
+ findings.push(
+ finding(
+ 'loader_missing',
+ 'fatal',
+ 'fail',
+ 'The embed runtime script is not on the page',
+ `Nothing on the page loads the three.ws runtime, so <${EMBED_TAG}> is never registered as a custom element and the browser treats it as an unknown, invisible tag.`,
+ 'Add the loader above your embed tag:\n<script type="module" src="https://three.ws/agent-3d/latest/agent-3d.js"></script>',
+ { scriptsSeen: scripts.slice(0, 12).map((s) => s.src).filter(Boolean) },
+ ),
+ );
+ } else if (cspMessages.length && !loaderOk) {
+ findings.push(
+ finding(
+ 'loader_blocked_csp',
+ 'fatal',
+ 'fail',
+ 'Your Content-Security-Policy blocked the runtime',
+ 'The script tag is on the page but the browser refused to execute it. This is the most common cause of an embed that fails silently: there is no visible error, and the console message is easy to miss.',
+ "Allow the three.ws origin in your CSP. At minimum:\nscript-src 'self' https://three.ws;\nconnect-src 'self' https://three.ws;\nimg-src 'self' data: blob: https://three.ws;\nworker-src 'self' blob:;",
+ {
+ csp: page.csp ?? null,
+ messages: cspMessages.slice(0, 3).map((m) => m.text),
+ },
+ ),
+ );
+ } else if (loaderRequests.length && !loaderOk) {
+ const failed = loaderRequests[0];
+ findings.push(
+ finding(
+ 'loader_failed',
+ 'fatal',
+ 'fail',
+ 'The runtime script failed to download',
+ failed.failure
+ ? `The request for the runtime failed: ${failed.failure}`
+ : `The runtime URL answered HTTP ${failed.status}, so no code ran.`,
+ 'Check the src for a typo. The current URL is https://three.ws/agent-3d/latest/agent-3d.js — a pinned version must exist (for example /agent-3d/1.5.2/agent-3d.js).',
+ { url: failed.url, status: failed.status ?? null, failure: failed.failure ?? null },
+ ),
+ );
+ } else if (loaderOk) {
+ findings.push(
+ pass(
+ 'loader_loaded',
+ 'The embed runtime loaded',
+ `The runtime downloaded successfully${loaderOk.bytes ? ` (${Math.round(loaderOk.bytes / 1024)} KB)` : ''}.`,
+ { url: loaderOk.url, status: loaderOk.status ?? 200 },
+ ),
+ );
+ } else {
+ findings.push(
+ unknown(
+ 'loader_loaded',
+ 'Could not confirm the runtime loaded',
+ 'A loader tag is present but no matching network request was observed before the check timed out.',
+ { tags: loaderTags.map((s) => s.src) },
+ ),
+ );
+ }
+
+ // A module bundle loaded without type="module" throws a syntax error on its
+ // first `import` and registers nothing — a one-word fix that is invisible
+ // unless you read the console carefully.
+ const moduleLoaders = loaderTags.filter((s) => /\/agent-3d\//i.test(String(s.src)));
+ const nonModule = moduleLoaders.filter((s) => (s.type || '').toLowerCase() !== 'module');
+ if (moduleLoaders.length && nonModule.length === moduleLoaders.length) {
+ findings.push(
+ finding(
+ 'loader_not_module',
+ 'error',
+ 'fail',
+ 'The runtime script is missing type="module"',
+ 'The agent-3d bundle is an ES module. Loaded as a classic script it fails on its first import statement and registers nothing.',
+ 'Add type="module" to the script tag:\n<script type="module" src="https://three.ws/agent-3d/latest/agent-3d.js"></script>',
+ { tags: nonModule.map((s) => ({ src: s.src, type: s.type || '(none)' })) },
+ ),
+ );
+ }
+
+ if (loaderTags.length > 1) {
+ findings.push(
+ finding(
+ 'duplicate_loader',
+ 'warn',
+ 'fail',
+ `The runtime is loaded ${loaderTags.length} times`,
+ 'Each copy downloads and parses the full bundle. The first one wins the custom-element registration, so the extra copies are pure download cost for your visitors.',
+ 'Keep exactly one loader script tag, usually in your site template rather than on individual pages.',
+ { srcs: loaderTags.map((s) => s.src) },
+ ),
+ );
+ }
+
+ // ── 3. The element ────────────────────────────────────────────────────────
+ if (!el || !el.count) {
+ findings.push(
+ finding(
+ 'element_missing',
+ 'fatal',
+ 'fail',
+ `There is no <${EMBED_TAG}> element on the page`,
+ `The runtime only renders where you place the tag. With no <${EMBED_TAG}> in the DOM there is nothing for it to bring to life.`,
+ `Add the element where you want the agent to appear:\n<${EMBED_TAG} agent-id="YOUR_AGENT_ID" mode="floating"></${EMBED_TAG}>\n\nCustom elements are never self-closing — the separate closing tag is required.`,
+ null,
+ ),
+ );
+ return { verdict: verdictFor(findings), findings: rank(findings), summary: summarize(findings, obs) };
+ }
+
+ if (el.count > 1) {
+ findings.push(
+ finding(
+ 'duplicate_element',
+ 'warn',
+ 'fail',
+ `There are ${el.count} embed elements on this page`,
+ 'Each element boots its own WebGL context and downloads its own model. Browsers cap the number of live contexts, so beyond a handful the later ones silently fail to render.',
+ 'Keep one element per page unless you deliberately want several agents on screen at once.',
+ { count: el.count },
+ ),
+ );
+ }
+
+ if (el.defined === true) {
+ findings.push(
+ pass(
+ 'element_upgraded',
+ 'The element was upgraded by the runtime',
+ `customElements.get('${EMBED_TAG}') resolved, so the tag is a live component rather than an unknown element.`,
+ null,
+ ),
+ );
+ } else if (el.defined === false) {
+ findings.push(
+ finding(
+ 'element_not_upgraded',
+ 'fatal',
+ 'fail',
+ 'The element was never upgraded',
+ `The tag is in the DOM but the browser does not know what <${EMBED_TAG}> is, so it renders as an empty inline element with no size. This is always a consequence of the runtime not executing.`,
+ 'Fix the loader finding above first. If the loader reports healthy, check that the script tag comes from https://three.ws and is not deferred behind a consent gate that never fires.',
+ null,
+ ),
+ );
+ } else {
+ findings.push(unknown('element_upgraded', 'Could not confirm the element was upgraded', 'The page did not finish booting within the time budget.', null));
+ }
+
+ // ── 4. What the element was told to load ──────────────────────────────────
+ const source = SOURCE_ATTRIBUTES.find((a) => el.attributes && el.attributes[a]);
+ if (!source) {
+ findings.push(
+ finding(
+ 'source_missing',
+ 'fatal',
+ 'fail',
+ 'The element has nothing to load',
+ `<${EMBED_TAG}> stays deliberately inert until it is given a source. Without one of ${SOURCE_ATTRIBUTES.map((a) => `\`${a}\``).join(', ')} it renders nothing rather than guessing.`,
+ `Add your agent id:\n<${EMBED_TAG} agent-id="YOUR_AGENT_ID" mode="floating"></${EMBED_TAG}>\n\nYour agent id is the string after /agent/ in its three.ws profile URL.`,
+ { attributes: el.attributes || {} },
+ ),
+ );
+ } else if (source === 'agent-id' && obs.agent) {
+ if (obs.agent.resolved === false) {
+ findings.push(
+ finding(
+ 'agent_unresolved',
+ 'fatal',
+ 'fail',
+ 'That agent id does not resolve',
+ obs.agent.error
+ ? `Looking the agent up returned: ${obs.agent.error}`
+ : 'The platform has no public agent with that id, so the runtime has no body, personality, or animations to load.',
+ 'Copy the id again from the agent\'s profile URL (the part after /agent/). If the agent is private, publish it or embed one that is public — the embed runs in your visitors\' browsers and can only read public agents.',
+ { agentId: obs.agent.id, status: obs.agent.status ?? null },
+ ),
+ );
+ } else if (obs.agent.resolved === true) {
+ findings.push(
+ pass(
+ 'agent_resolved',
+ 'The agent id resolves',
+ obs.agent.name
+ ? `The embed points at "${obs.agent.name}", which is public and loadable.`
+ : 'The agent exists and is publicly readable.',
+ { agentId: obs.agent.id },
+ ),
+ );
+ }
+ }
+
+ // ── 5. Is it actually visible? ────────────────────────────────────────────
+ // An embed that boots perfectly and is 0px tall is indistinguishable from a
+ // broken one at the only place it matters: the visitor's screen.
+ const rect = el.rect || null;
+ const styles = el.styles || {};
+ const hiddenReason =
+ styles.display === 'none'
+ ? 'display: none'
+ : styles.visibility === 'hidden'
+ ? 'visibility: hidden'
+ : Number(styles.opacity) === 0
+ ? 'opacity: 0'
+ : null;
+
+ if (hiddenReason) {
+ findings.push(
+ finding(
+ 'element_hidden',
+ 'error',
+ 'fail',
+ 'The embed is hidden by CSS',
+ `The element resolves to ${hiddenReason}, usually inherited from a collapsed parent (a closed accordion, an inactive tab panel, or a "hidden until loaded" wrapper that never un-hides).`,
+ 'Inspect the element in devtools and walk up the tree to find the ancestor applying it. If the embed lives inside a tab or accordion, mount it when that panel opens rather than hiding it.',
+ { styles, hiddenBy: el.hiddenAncestor || null },
+ ),
+ );
+ } else if (rect && (rect.width < 2 || rect.height < 2)) {
+ findings.push(
+ finding(
+ 'element_zero_size',
+ 'error',
+ 'fail',
+ `The embed has no size (${Math.round(rect.width)}×${Math.round(rect.height)}px)`,
+ 'In inline mode the element fills its container, and a container with no height collapses it to nothing. The runtime is running correctly and drawing into a box with zero area.',
+ `Give the element or its parent a height:\n<${EMBED_TAG} agent-id="…" style="display:block;width:100%;height:480px"></${EMBED_TAG}>\n\nOr switch to mode="floating", which pins itself to a corner and sizes itself.`,
+ { rect, mode: el.attributes?.mode || '(default)' },
+ ),
+ );
+ } else if (rect) {
+ findings.push(
+ pass(
+ 'element_visible',
+ `The embed occupies ${Math.round(rect.width)}×${Math.round(rect.height)}px`,
+ 'The element has real layout size and is not hidden by CSS.',
+ { rect },
+ ),
+ );
+ }
+
+ if (el.offscreen === true) {
+ findings.push(
+ finding(
+ 'element_offscreen',
+ 'warn',
+ 'fail',
+ 'The embed sits outside the visible viewport',
+ 'It renders, but at a position no visitor scrolls to. This is usually an absolutely-positioned ancestor with a negative offset.',
+ 'Check for a parent with a negative top/left or a transform that moves it off-canvas.',
+ { rect },
+ ),
+ );
+ }
+
+ // ── 6. Can the browser draw 3D at all? ────────────────────────────────────
+ if (obs.webgl?.available === false) {
+ findings.push(
+ finding(
+ 'webgl_unavailable',
+ 'fatal',
+ 'fail',
+ 'WebGL is unavailable in this browser session',
+ 'The runtime needs a WebGL2 context to draw. Without one it cannot render regardless of how correct your markup is. Hardened browsers, some privacy extensions, and remote desktop sessions all disable it.',
+ 'Test in a standard browser profile with hardware acceleration enabled. For visitors who genuinely cannot run WebGL, render a static portrait instead: https://three.ws/api/avatar/render?avatar=YOUR_AVATAR_ID',
+ { renderer: obs.webgl?.renderer || null },
+ ),
+ );
+ } else if (obs.webgl?.available === true) {
+ findings.push(
+ pass('webgl_available', 'WebGL is available', obs.webgl.renderer ? `Renderer: ${obs.webgl.renderer}` : 'The browser can create a WebGL context.', null),
+ );
+ }
+
+ // ── 7. Did anything actually get drawn? ───────────────────────────────────
+ const canvas = el.canvas || null;
+ if (canvas?.present === true && canvas.blank === false) {
+ findings.push(
+ pass(
+ 'canvas_rendered',
+ 'The agent rendered pixels',
+ `A ${Math.round(canvas.width)}×${Math.round(canvas.height)}px canvas is drawing inside the element.`,
+ { width: canvas.width, height: canvas.height },
+ ),
+ );
+ } else if (canvas?.present === true && canvas.blank === true) {
+ findings.push(
+ finding(
+ 'canvas_blank',
+ 'warn',
+ 'fail',
+ 'The canvas is present but still blank',
+ 'The runtime created its drawing surface but had not painted a frame when we looked. On a slow connection the model may simply still be downloading; if it stays blank, the model bytes failed.',
+ 'Re-run the check. If it stays blank, look at the failed-request finding below — a 404 or CORS failure on the model is the usual cause.',
+ { width: canvas.width, height: canvas.height },
+ ),
+ );
+ } else if (el.defined === true) {
+ findings.push(
+ finding(
+ 'canvas_missing',
+ 'error',
+ 'fail',
+ 'No canvas was created',
+ 'The element upgraded but never built its renderer, which means it stopped during boot rather than while drawing.',
+ 'Check the console findings below for the error the runtime threw, and confirm the agent id resolves.',
+ null,
+ ),
+ );
+ }
+
+ // ── 8. Transport-level problems ───────────────────────────────────────────
+ if (page.https === true) {
+ const insecure = net.filter((r) => /^http:\/\//i.test(String(r.url)) && isEmbedRelated(r.url));
+ if (insecure.length) {
+ findings.push(
+ finding(
+ 'mixed_content',
+ 'error',
+ 'fail',
+ 'Insecure requests on an HTTPS page',
+ 'The browser blocks plain-http subresources on an https page. Any embed asset requested over http is dropped before it reaches the network.',
+ 'Change every three.ws URL in your markup from http:// to https://.',
+ { urls: insecure.slice(0, 5).map((r) => r.url) },
+ ),
+ );
+ }
+ }
+
+ const failedEmbedRequests = net.filter(
+ (r) => !r.ok && isEmbedRelated(r.url) && !isLoaderUrl(r.url),
+ );
+ if (failedEmbedRequests.length) {
+ findings.push(
+ finding(
+ 'asset_requests_failed',
+ 'error',
+ 'fail',
+ `${failedEmbedRequests.length} embed request${failedEmbedRequests.length === 1 ? '' : 's'} failed`,
+ 'The runtime booted but could not fetch something it needs — typically the agent manifest or the GLB body.',
+ 'Open each URL below directly. A 404 means the agent or its model was removed; a CORS error means a proxy in front of your site is rewriting the request.',
+ {
+ requests: failedEmbedRequests.slice(0, 6).map((r) => ({
+ url: r.url,
+ status: r.status ?? null,
+ failure: r.failure ?? null,
+ })),
+ },
+ ),
+ );
+ }
+
+ // ── 9. What the page said out loud ────────────────────────────────────────
+ const relevantErrors = [
+ ...pageErrors,
+ ...consoleMsgs.filter((m) => m.type === 'error').map((m) => m.text),
+ ].filter(Boolean);
+ if (relevantErrors.length) {
+ findings.push(
+ finding(
+ 'console_errors',
+ 'warn',
+ 'fail',
+ `${relevantErrors.length} console error${relevantErrors.length === 1 ? '' : 's'} on the page`,
+ 'Errors from anywhere on the page are listed because a crash in unrelated code can abort the script that would have booted the embed.',
+ 'Read the messages below in order. The first one is usually the cause; the rest are often consequences of it.',
+ { messages: relevantErrors.slice(0, 6).map((t) => String(t).slice(0, 400)) },
+ ),
+ );
+ }
+
+ if (typeof el.bootMs === 'number' && el.bootMs > 6000) {
+ findings.push(
+ finding(
+ 'slow_boot',
+ 'warn',
+ 'fail',
+ `The agent took ${(el.bootMs / 1000).toFixed(1)}s to appear`,
+ 'It works, but a visitor on a slower connection may leave before the agent arrives.',
+ 'Pin a version instead of "latest" so the bundle caches for longer, and keep the model under a few megabytes.',
+ { bootMs: el.bootMs },
+ ),
+ );
+ }
+
+ return { verdict: verdictFor(findings), findings: rank(findings), summary: summarize(findings, obs) };
+}
+
+/** Failures first, worst severity first, then passes. Stable within a bucket so
+ * the report reads in the order the checks run. */
+function rank(findings) {
+ return findings
+ .map((f, i) => ({ f, i }))
+ .sort((a, b) => {
+ const af = a.f.status === 'fail' ? 0 : a.f.status === 'unknown' ? 1 : 2;
+ const bf = b.f.status === 'fail' ? 0 : b.f.status === 'unknown' ? 1 : 2;
+ if (af !== bf) return af - bf;
+ const as = SEVERITY_RANK[a.f.severity] ?? 9;
+ const bs = SEVERITY_RANK[b.f.severity] ?? 9;
+ if (as !== bs) return as - bs;
+ return a.i - b.i;
+ })
+ .map((x) => x.f);
+}
+
+function summarize(findings, obs) {
+ const failed = findings.filter((f) => f.status === 'fail');
+ return {
+ checks: findings.length,
+ failed: failed.length,
+ passed: findings.filter((f) => f.status === 'pass').length,
+ unknown: findings.filter((f) => f.status === 'unknown').length,
+ headline: failed.length ? failed[0].title : 'The embed is working',
+ target: obs?.target || null,
+ };
+}
+
+// ── Browser layer ─────────────────────────────────────────────────────────────
+// Everything below drives a real chromium. It gathers facts and hands them to
+// `analyze`; it makes no judgements of its own.
+
+const DEFAULT_CHROMIUM_PACK =
+ 'https://github.com/Sparticuz/chromium/releases/download/v148.0.0/chromium-v148.0.0-pack.x64.tar';
+
+let _browserPromise = null;
+
+/**
+ * Boot (or reuse) a headless chromium. Mirrors `render-clip.js`: puppeteer-core
+ * plus @sparticuz/chromium-min are imported lazily so route bundling never has
+ * to statically trace the chromium tree.
+ */
+async function getBrowser() {
+ if (_browserPromise) return _browserPromise;
+ _browserPromise = (async () => {
+ const [{ default: puppeteer }, { default: chromium }] = await Promise.all([
+ import('puppeteer-core'),
+ import('@sparticuz/chromium-min'),
+ ]);
+ const pack = process.env.CHROMIUM_PACK_URL || DEFAULT_CHROMIUM_PACK;
+ const executablePath = await chromium.executablePath(pack);
+ return puppeteer.launch({
+ args: chromium.args,
+ defaultViewport: { width: 1280, height: 800, deviceScaleFactor: 1 },
+ executablePath,
+ headless: chromium.headless,
+ });
+ })().catch((err) => {
+ _browserPromise = null;
+ throw err;
+ });
+ return _browserPromise;
+}
+
+/** Released between requests in serverless-style environments where a warm
+ * browser would outlive its usefulness. Safe to call when none is open. */
+export async function closeBrowser() {
+ const p = _browserPromise;
+ _browserPromise = null;
+ if (!p) return;
+ try {
+ const b = await p;
+ await b.close();
+ } catch {
+ /* already gone */
+ }
+}
+
+/** Runs inside the page. Returns the DOM facts `analyze` needs. Written as a
+ * plain string-serialisable function: it cannot close over anything. */
+function inPageProbe(tag, sourceAttrs) {
+ function deepQueryAll(selector) {
+ const out = [];
+ const walk = (root) => {
+ for (const el of root.querySelectorAll(selector)) out.push(el);
+ for (const el of root.querySelectorAll('*')) {
+ if (el.shadowRoot) walk(el.shadowRoot);
+ }
+ };
+ walk(document);
+ return out;
+ }
+
+ const scripts = Array.from(document.querySelectorAll('script[src]')).map((s) => ({
+ src: s.getAttribute('src') || '',
+ type: s.getAttribute('type') || '',
+ }));
+
+ let webglAvailable = false;
+ let webglRenderer = null;
+ try {
+ const c = document.createElement('canvas');
+ const gl = c.getContext('webgl2') || c.getContext('webgl');
+ if (gl) {
+ webglAvailable = true;
+ const dbg = gl.getExtension('WEBGL_debug_renderer_info');
+ if (dbg) webglRenderer = String(gl.getParameter(dbg.UNMASKED_RENDERER_WEBGL) || '');
+ }
+ } catch {
+ webglAvailable = false;
+ }
+
+ const els = deepQueryAll(tag);
+ let element = null;
+ if (els.length) {
+ const node = els[0];
+ const cs = getComputedStyle(node);
+ const rect = node.getBoundingClientRect();
+
+ const attributes = {};
+ for (const a of Array.from(node.attributes || [])) attributes[a.name] = a.value;
+
+ // Which ancestor applies the hiding, so the report can name it rather
+ // than telling the developer to go hunting.
+ let hiddenAncestor = null;
+ for (let p = node; p && p !== document.documentElement; p = p.parentElement) {
+ const s = getComputedStyle(p);
+ if (s.display === 'none' || s.visibility === 'hidden' || Number(s.opacity) === 0) {
+ hiddenAncestor =
+ p === node
+ ? 'the element itself'
+ : p.tagName.toLowerCase() +
+ (p.id ? '#' + p.id : '') +
+ (p.className && typeof p.className === 'string'
+ ? '.' + p.className.trim().split(/\s+/).slice(0, 2).join('.')
+ : '');
+ break;
+ }
+ }
+
+ // The runtime draws into a canvas inside its shadow root.
+ let canvas = { present: false, width: 0, height: 0, blank: true };
+ const root = node.shadowRoot || node;
+ const cv = root.querySelector('canvas');
+ if (cv) {
+ canvas = { present: true, width: cv.width, height: cv.height, blank: true };
+ try {
+ // A WebGL canvas cannot be read back with getImageData, so blankness
+ // is judged from a downscaled copy: cheap, and it only needs to
+ // answer "did anything paint at all".
+ const probe = document.createElement('canvas');
+ probe.width = 24;
+ probe.height = 24;
+ const ctx = probe.getContext('2d');
+ ctx.drawImage(cv, 0, 0, 24, 24);
+ const data = ctx.getImageData(0, 0, 24, 24).data;
+ let first = null;
+ for (let i = 0; i < data.length; i += 4) {
+ const px = `${data[i]},${data[i + 1]},${data[i + 2]},${data[i + 3]}`;
+ if (first === null) first = px;
+ else if (px !== first) {
+ canvas.blank = false;
+ break;
+ }
+ }
+ } catch {
+ // Tainted or unreadable: leave `blank` true rather than claiming a
+ // render we did not observe.
+ }
+ }
+
+ element = {
+ count: els.length,
+ defined: !!(window.customElements && window.customElements.get(tag)),
+ attributes,
+ rect: { width: rect.width, height: rect.height, top: rect.top, left: rect.left },
+ styles: { display: cs.display, visibility: cs.visibility, opacity: cs.opacity },
+ hiddenAncestor,
+ offscreen:
+ rect.width > 0 &&
+ rect.height > 0 &&
+ (rect.bottom < 0 ||
+ rect.right < 0 ||
+ rect.left > document.documentElement.clientWidth ||
+ rect.top > document.documentElement.scrollHeight),
+ canvas,
+ source: sourceAttrs.find((a) => attributes[a]) || null,
+ };
+ }
+
+ return {
+ scripts,
+ element,
+ webgl: { available: webglAvailable, renderer: webglRenderer },
+ title: document.title || '',
+ };
+}
+
+/**
+ * Wait until the embed has clearly settled — a painted canvas — or the budget
+ * runs out. Polls rather than racing a fixed sleep so a fast page returns fast
+ * and a slow one still gets its full allowance.
+ */
+async function waitForEmbed(page, tag, budgetMs) {
+ const started = Date.now();
+ while (Date.now() - started < budgetMs) {
+ const done = await page
+ .evaluate((t) => {
+ const el = document.querySelector(t);
+ if (!el) return false;
+ const root = el.shadowRoot || el;
+ const cv = root.querySelector('canvas');
+ return !!(cv && cv.width > 0 && cv.height > 0);
+ }, tag)
+ .catch(() => false);
+ if (done) return Date.now() - started;
+ await new Promise((r) => setTimeout(r, 250));
+ }
+ return null;
+}
+
+/** Resolve an agent id against the live platform so "that id is wrong" is an
+ * answer the report can give instead of a guess. */
+async function resolveAgent(agentId, { platformOrigin, timeoutMs = 6000 } = {}) {
+ if (!agentId) return null;
+ // Only plain platform ids are resolvable here; CAIP-10 / on-chain forms are
+ // resolved by the runtime itself against a registry, so we report unknown
+ // rather than pretending to check them.
+ if (!/^[A-Za-z0-9_-]{1,64}$/.test(agentId)) {
+ return { id: agentId, resolved: null, note: 'on-chain or URI form, not resolvable here' };
+ }
+ try {
+ const res = await fetch(`${platformOrigin}/api/agents/${encodeURIComponent(agentId)}`, {
+ signal: AbortSignal.timeout(timeoutMs),
+ headers: { accept: 'application/json' },
+ });
+ if (!res.ok) {
+ return { id: agentId, resolved: false, status: res.status, error: `HTTP ${res.status}` };
+ }
+ const json = await res.json().catch(() => null);
+ const name = json?.name || json?.agent?.name || json?.displayName || null;
+ return { id: agentId, resolved: true, status: res.status, name };
+ } catch (err) {
+ return { id: agentId, resolved: false, error: String(err?.message || err) };
+ }
+}
+
+/** Attach network + console recorders to a page. Returns the arrays they fill. */
+function instrument(page) {
+ const network = [];
+ const consoleMsgs = [];
+ const pageErrors = [];
+
+ page.on('response', (res) => {
+ try {
+ const headers = res.headers() || {};
+ network.push({
+ url: res.url(),
+ status: res.status(),
+ ok: res.status() < 400,
+ bytes: Number(headers['content-length']) || null,
+ });
+ } catch {
+ /* response gone */
+ }
+ });
+ page.on('requestfailed', (req) => {
+ try {
+ network.push({
+ url: req.url(),
+ status: null,
+ ok: false,
+ failure: req.failure()?.errorText || 'request failed',
+ });
+ } catch {
+ /* request gone */
+ }
+ });
+ page.on('console', (msg) => {
+ try {
+ consoleMsgs.push({ type: msg.type(), text: String(msg.text()).slice(0, 600) });
+ } catch {
+ /* message gone */
+ }
+ });
+ page.on('pageerror', (err) => pageErrors.push(String(err?.message || err).slice(0, 600)));
+
+ return { network, console: consoleMsgs, pageErrors };
+}
+
+/** Everything a diagnosis needs from a booted page, once it has settled. */
+async function harvest(page, { recorders, response, bootMs, platformOrigin, screenshot }) {
+ const probe = await page.evaluate(inPageProbe, EMBED_TAG, SOURCE_ATTRIBUTES).catch(() => ({
+ scripts: [],
+ element: null,
+ webgl: { available: null, renderer: null },
+ title: '',
+ }));
+
+ const headers = (() => {
+ try {
+ return response?.headers?.() || {};
+ } catch {
+ return {};
+ }
+ })();
+
+ const finalUrl = page.url();
+ const agentId = probe.element?.attributes?.['agent-id'] || null;
+ const agent = agentId ? await resolveAgent(agentId, { platformOrigin }) : null;
+
+ let shot = null;
+ if (screenshot) {
+ shot = await page
+ .screenshot({ type: 'jpeg', quality: 62, encoding: 'base64', fullPage: false })
+ .catch(() => null);
+ }
+
+ return {
+ page: {
+ reachable: true,
+ status: response?.status?.() ?? 200,
+ finalUrl,
+ https: /^https:/i.test(finalUrl),
+ csp: headers['content-security-policy'] || null,
+ title: probe.title,
+ },
+ scripts: probe.scripts,
+ element: probe.element ? { ...probe.element, bootMs } : null,
+ webgl: probe.webgl,
+ network: recorders.network,
+ console: recorders.console,
+ pageErrors: recorders.pageErrors,
+ agent,
+ screenshot: shot,
+ };
+}
+
+/**
+ * Diagnose a live URL.
+ *
+ * @param {object} opts
+ * @param {string} opts.url The page to inspect. Validated against the SSRF guard.
+ * @param {number} [opts.budgetMs] How long to wait for the embed to paint.
+ * @param {boolean} [opts.screenshot] Include a base64 JPEG of what actually rendered.
+ * @param {string} [opts.platformOrigin]
+ */
+export async function collectFromUrl({
+ url,
+ budgetMs = 12000,
+ screenshot = true,
+ platformOrigin = 'https://three.ws',
+} = {}) {
+ // The URL comes from an anonymous caller and is fetched by our servers, so
+ // it goes through the same guard as every other user-supplied fetch target.
+ await assertSafePublicUrl(url, { allowHttp: true });
+
+ const browser = await getBrowser();
+ const page = await browser.newPage();
+ const target = { kind: 'url', url };
+ try {
+ await page.setUserAgent(
+ 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.0.0 Safari/537.36 three.ws-EmbedDoctor/1.0 (+https://three.ws/embed-doctor)',
+ );
+ const recorders = instrument(page);
+ let response = null;
+ try {
+ response = await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 25000 });
+ } catch (err) {
+ return {
+ target,
+ page: { reachable: false, error: String(err?.message || err).slice(0, 300) },
+ scripts: [],
+ element: null,
+ network: recorders.network,
+ console: recorders.console,
+ pageErrors: recorders.pageErrors,
+ };
+ }
+ const bootMs = await waitForEmbed(page, EMBED_TAG, budgetMs);
+ const obs = await harvest(page, { recorders, response, bootMs, platformOrigin, screenshot });
+ return { target, ...obs };
+ } finally {
+ await page.close().catch(() => {});
+ }
+}
+
+/** The minimal, dependency-free host document a snippet is tested inside. Kept
+ * deliberately plain so any failure belongs to the snippet, not the harness. */
+export function snippetHostHtml(snippet) {
+ return `<!doctype html>
+<html lang="en"><head><meta charset="utf-8"><title>Embed Doctor sandbox</title>
+<style>html,body{margin:0;min-height:100vh;background:#0a0a0a;color:#eee;font:15px/1.5 system-ui,sans-serif}
+main{padding:24px;min-height:60vh}</style></head>
+<body><main>${snippet}</main></body></html>`;
+}
+
+/**
+ * Diagnose a snippet before it is deployed anywhere. The snippet is loaded in a
+ * blank sandbox page served from the platform origin, so the result isolates
+ * mistakes in the markup itself from anything the host site does to it.
+ */
+export async function collectFromSnippet({
+ snippet,
+ budgetMs = 12000,
+ screenshot = true,
+ platformOrigin = 'https://three.ws',
+} = {}) {
+ const browser = await getBrowser();
+ const page = await browser.newPage();
+ const target = { kind: 'snippet', snippet: String(snippet).slice(0, 4000) };
+ try {
+ const recorders = instrument(page);
+ // Served from the platform origin so relative URLs and module imports
+ // resolve exactly as they would in a browser, which `data:` URLs break.
+ let response = null;
+ await page.setRequestInterception(true);
+ const sandboxUrl = `${platformOrigin}/__embed-doctor-sandbox`;
+ page.on('request', (req) => {
+ if (req.url() === sandboxUrl) {
+ req
+ .respond({
+ status: 200,
+ contentType: 'text/html; charset=utf-8',
+ body: snippetHostHtml(snippet),
+ })
+ .catch(() => {});
+ return;
+ }
+ req.continue().catch(() => {});
+ });
+ response = await page.goto(sandboxUrl, { waitUntil: 'domcontentloaded', timeout: 25000 });
+ const bootMs = await waitForEmbed(page, EMBED_TAG, budgetMs);
+ const obs = await harvest(page, { recorders, response, bootMs, platformOrigin, screenshot });
+ return { target, ...obs };
+ } finally {
+ await page.close().catch(() => {});
+ }
+}
+
+/** Collect + analyze in one call. */
+export async function diagnose(input) {
+ const started = Date.now();
+ const observations = input.snippet
+ ? await collectFromSnippet(input)
+ : await collectFromUrl(input);
+ const report = analyze(observations);
+ return {
+ ...report,
+ target: observations.target,
+ screenshot: observations.screenshot || null,
+ pageTitle: observations.page?.title || null,
+ durationMs: Date.now() - started,
+ };
+}
+
+export { SsrfBlockedError };
diff --git a/api/embed/diagnose.js b/api/embed/diagnose.js
new file mode 100644
index 000000000..07b9931b8
--- /dev/null
+++ b/api/embed/diagnose.js
@@ -0,0 +1,183 @@
+// POST /api/embed/diagnose — the Embed Doctor API.
+//
+// Loads a developer's page (or a bare snippet) in a real headless browser and
+// reports exactly why their `<agent-3d>` embed is not appearing. The decision
+// logic lives in api/_lib/embed-doctor.js; this file is transport, validation,
+// and abuse control.
+//
+// Body (JSON), exactly one of:
+// { "url": "https://your-site.example/page" } inspect a live page
+// { "snippet": "<script …></script><agent-3d …></agent-3d>" }
+// inspect markup before deploy
+//
+// Options:
+// screenshot: boolean include a base64 JPEG of what actually rendered (default true)
+// budgetMs: number how long to wait for the agent to paint (2000-20000, default 12000)
+//
+// Response 200:
+// {
+// verdict: "healthy" | "degraded" | "broken" | "inconclusive",
+// summary: { checks, failed, passed, unknown, headline },
+// findings: [{ id, severity, status, title, detail, fix, evidence }],
+// screenshot: "<base64 jpeg>" | null,
+// durationMs: number
+// }
+//
+// Safety:
+// - The URL goes through the shared SSRF guard, so an internal address, cloud
+// metadata endpoint, or a redirect into one is refused rather than fetched.
+// - Booting chromium is expensive, so the budget is small and per-IP: 12 runs
+// per 10 minutes is far more than a developer debugging one embed needs and
+// well under what makes this a free browser-as-a-service for someone else.
+// - Snippets are capped at 8 KB. The sandbox they run in is a blank page on
+// our origin with no credentials, so a snippet can reach the public web and
+// nothing else.
+
+import { cors, error, json, method, readJson, rateLimited, wrap } from '../_lib/http.js';
+import { clientIp } from '../_lib/rate-limit.js';
+import { diagnose, SsrfBlockedError } from '../_lib/embed-doctor.js';
+
+export const maxDuration = 60;
+
+const MAX_SNIPPET_BYTES = 8 * 1024;
+const MIN_BUDGET_MS = 2000;
+const MAX_BUDGET_MS = 20000;
+const RATE_WINDOW_MS = 10 * 60 * 1000;
+const RATE_MAX = 12;
+
+// Per-instance limiter, matching /api/render/glb. The resource being protected
+// is this instance's CPU and memory (one chromium per run), so a per-instance
+// cap is the honest unit: it bounds exactly what it is defending.
+const rateMap = new Map();
+function rateCheck(ip) {
+ const now = Date.now();
+ if (!ip) return { success: true, limit: RATE_MAX, remaining: RATE_MAX, reset: now + RATE_WINDOW_MS };
+ const hits = (rateMap.get(ip) || []).filter((t) => now - t < RATE_WINDOW_MS);
+ if (hits.length >= RATE_MAX) {
+ rateMap.set(ip, hits);
+ return { success: false, limit: RATE_MAX, remaining: 0, reset: hits[0] + RATE_WINDOW_MS };
+ }
+ hits.push(now);
+ rateMap.set(ip, hits);
+ // Unbounded growth would be a slow leak on a long-lived instance; entries
+ // are only useful for one window.
+ if (rateMap.size > 5000) {
+ for (const [k, v] of rateMap) {
+ if (!v.length || now - v[v.length - 1] > RATE_WINDOW_MS) rateMap.delete(k);
+ }
+ }
+ return { success: true, limit: RATE_MAX, remaining: RATE_MAX - hits.length, reset: now + RATE_WINDOW_MS };
+}
+
+function platformOrigin(req) {
+ const envOrigin = process.env.PUBLIC_ORIGIN || process.env.SITE_ORIGIN;
+ if (envOrigin) return String(envOrigin).replace(/\/$/, '');
+ const host = req.headers['x-forwarded-host'] || req.headers.host;
+ if (!host) return 'https://three.ws';
+ const proto = String(req.headers['x-forwarded-proto'] || 'https').split(',')[0];
+ return `${proto}://${host}`;
+}
+
+export default wrap(async function handler(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS' })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const ip = clientIp(req);
+ const rate = rateCheck(ip);
+ if (!rate.success) {
+ return rateLimited(
+ res,
+ rate,
+ 'Too many diagnoses from this address. Each run boots a real browser, so the budget is small. Try again shortly.',
+ );
+ }
+
+ const body = await readJson(req, 32 * 1024).catch(() => null);
+ if (!body || typeof body !== 'object') {
+ return error(res, 400, 'invalid_body', 'Send a JSON body with either a `url` or a `snippet`.');
+ }
+
+ const rawUrl = typeof body.url === 'string' ? body.url.trim() : '';
+ const rawSnippet = typeof body.snippet === 'string' ? body.snippet : '';
+
+ if (rawUrl && rawSnippet) {
+ return error(
+ res,
+ 400,
+ 'ambiguous_target',
+ 'Send either `url` or `snippet`, not both. A snippet is checked in a clean sandbox; a URL is checked on your real page.',
+ );
+ }
+ if (!rawUrl && !rawSnippet.trim()) {
+ return error(
+ res,
+ 400,
+ 'missing_target',
+ 'Send `url` (a public page carrying your embed) or `snippet` (the two tags, to check before you deploy).',
+ );
+ }
+
+ if (rawSnippet && Buffer.byteLength(rawSnippet, 'utf8') > MAX_SNIPPET_BYTES) {
+ return error(
+ res,
+ 413,
+ 'snippet_too_large',
+ `Snippets are capped at ${MAX_SNIPPET_BYTES / 1024} KB. Paste just the script tag and the embed element.`,
+ );
+ }
+
+ let url = '';
+ if (rawUrl) {
+ let parsed;
+ try {
+ parsed = new URL(rawUrl.includes('://') ? rawUrl : `https://${rawUrl}`);
+ } catch {
+ return error(res, 400, 'invalid_url', 'That does not look like a URL. Include the full address, for example https://example.com/page.');
+ }
+ if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
+ return error(res, 400, 'unsupported_scheme', 'Only http and https pages can be inspected.');
+ }
+ url = parsed.toString();
+ }
+
+ const budgetMs = Math.min(
+ MAX_BUDGET_MS,
+ Math.max(MIN_BUDGET_MS, Number(body.budgetMs) || 12000),
+ );
+ const screenshot = body.screenshot !== false;
+
+ try {
+ const report = await diagnose({
+ ...(url ? { url } : { snippet: rawSnippet }),
+ budgetMs,
+ screenshot,
+ platformOrigin: platformOrigin(req),
+ });
+ // A diagnosis is about one moment in time on someone else's server, so it
+ // must never be cached and handed to the next caller as fresh.
+ return json(res, 200, report, { 'cache-control': 'no-store' });
+ } catch (err) {
+ if (err instanceof SsrfBlockedError || err?.code === 'ssrf_blocked') {
+ return error(
+ res,
+ 400,
+ 'url_not_public',
+ 'That address is not reachable from the public internet (it resolves to a private or internal host). Paste your snippet instead and we will check the markup in a sandbox.',
+ );
+ }
+ if (/executablePath|chromium|Failed to launch/i.test(String(err?.message || ''))) {
+ return error(
+ res,
+ 503,
+ 'browser_unavailable',
+ 'The diagnostic browser could not start. This is on our side, not your page. Please try again in a minute.',
+ );
+ }
+ return error(
+ res,
+ 502,
+ 'diagnosis_failed',
+ `The diagnosis could not complete: ${String(err?.message || err).slice(0, 200)}`,
+ );
+ }
+});
diff --git a/tests/embed-doctor.test.js b/tests/embed-doctor.test.js
new file mode 100644
index 000000000..d48ac37f5
--- /dev/null
+++ b/tests/embed-doctor.test.js
@@ -0,0 +1,506 @@
+// The Embed Doctor's verdict logic, exercised without a browser.
+//
+// `analyze()` is deliberately pure so the whole failure catalogue can be pinned
+// here: each test builds the observations a real page would have produced and
+// asserts the report a developer would read. The browser layer only gathers
+// facts, so these tests cover every decision the tool makes.
+
+import { describe, it, expect } from 'vitest';
+import {
+ analyze,
+ isEmbedRelated,
+ looksLikeCspBlock,
+ snippetHostHtml,
+ EMBED_TAG,
+ SOURCE_ATTRIBUTES,
+} from '../api/_lib/embed-doctor.js';
+
+const LOADER = 'https://three.ws/agent-3d/latest/agent-3d.js';
+
+/** A page where everything works. Individual tests break one thing at a time,
+ * which is also how the report is meant to be read. */
+function healthyObservations(overrides = {}) {
+ return {
+ target: { kind: 'url', url: 'https://example.com/' },
+ page: { reachable: true, status: 200, finalUrl: 'https://example.com/', https: true, csp: null },
+ scripts: [{ src: LOADER, type: 'module' }],
+ network: [
+ { url: LOADER, status: 200, ok: true, bytes: 4214540 },
+ { url: 'https://three.ws/api/agents/abc123', status: 200, ok: true },
+ ],
+ console: [],
+ pageErrors: [],
+ webgl: { available: true, renderer: 'ANGLE' },
+ agent: { id: 'abc123', resolved: true, name: 'Nova' },
+ element: {
+ count: 1,
+ defined: true,
+ attributes: { 'agent-id': 'abc123', mode: 'floating' },
+ rect: { width: 320, height: 420, top: 100, left: 40 },
+ styles: { display: 'block', visibility: 'visible', opacity: '1' },
+ hiddenAncestor: null,
+ offscreen: false,
+ canvas: { present: true, width: 640, height: 840, blank: false },
+ bootMs: 1800,
+ },
+ ...overrides,
+ };
+}
+
+const idsOf = (report) => report.findings.map((f) => f.id);
+const byId = (report, id) => report.findings.find((f) => f.id === id);
+const failed = (report) => report.findings.filter((f) => f.status === 'fail');
+
+describe('analyze — a working embed', () => {
+ it('reports healthy and fails nothing', () => {
+ const report = analyze(healthyObservations());
+ expect(report.verdict).toBe('healthy');
+ expect(failed(report)).toHaveLength(0);
+ expect(report.summary.headline).toBe('The embed is working');
+ });
+
+ it('confirms each stage of the boot rather than a single opaque pass', () => {
+ const ids = idsOf(analyze(healthyObservations()));
+ // A developer needs to see WHICH parts are proven working, otherwise a
+ // green result is unfalsifiable.
+ expect(ids).toEqual(
+ expect.arrayContaining([
+ 'loader_loaded',
+ 'element_upgraded',
+ 'agent_resolved',
+ 'element_visible',
+ 'webgl_available',
+ 'canvas_rendered',
+ ]),
+ );
+ });
+});
+
+describe('analyze — the page itself', () => {
+ it('stops at an unreachable page instead of cascading downstream failures', () => {
+ const report = analyze({
+ target: { kind: 'url', url: 'https://nope.example/' },
+ page: { reachable: false, error: 'net::ERR_NAME_NOT_RESOLVED' },
+ scripts: [],
+ element: null,
+ network: [],
+ console: [],
+ pageErrors: [],
+ });
+ expect(report.verdict).toBe('broken');
+ // Exactly one finding: everything else is unknowable, and reporting
+ // "element missing" here would send the developer to the wrong file.
+ expect(report.findings).toHaveLength(1);
+ expect(report.findings[0].id).toBe('page_unreachable');
+ expect(report.findings[0].evidence.error).toContain('ERR_NAME_NOT_RESOLVED');
+ });
+
+ it('treats an HTTP error status as terminal and names the status', () => {
+ const report = analyze(healthyObservations({ page: { reachable: true, status: 404 } }));
+ expect(report.findings).toHaveLength(1);
+ expect(report.findings[0].id).toBe('page_error_status');
+ expect(report.findings[0].title).toContain('404');
+ });
+});
+
+describe('analyze — the loader script', () => {
+ it('flags a missing runtime as fatal and shows what scripts it did see', () => {
+ const report = analyze(
+ healthyObservations({
+ scripts: [{ src: 'https://cdn.example/analytics.js', type: '' }],
+ network: [],
+ element: { ...healthyObservations().element, defined: false, canvas: { present: false, width: 0, height: 0, blank: true } },
+ }),
+ );
+ const f = byId(report, 'loader_missing');
+ expect(f.severity).toBe('fatal');
+ expect(f.evidence.scriptsSeen).toContain('https://cdn.example/analytics.js');
+ expect(f.fix).toContain('type="module"');
+ });
+
+ it('identifies a CSP block, which is otherwise invisible', () => {
+ const report = analyze(
+ healthyObservations({
+ page: { reachable: true, status: 200, https: true, csp: "script-src 'self'" },
+ network: [],
+ console: [
+ {
+ type: 'error',
+ text: "Refused to load the script 'https://three.ws/agent-3d/latest/agent-3d.js' because it violates the following Content Security Policy directive: \"script-src 'self'\".",
+ },
+ ],
+ element: { ...healthyObservations().element, defined: false, canvas: { present: false, width: 0, height: 0, blank: true } },
+ }),
+ );
+ const f = byId(report, 'loader_blocked_csp');
+ expect(f).toBeTruthy();
+ expect(f.severity).toBe('fatal');
+ expect(f.evidence.csp).toBe("script-src 'self'");
+ expect(f.fix).toContain('script-src');
+ // The blocked loader must outrank the un-upgraded element it caused.
+ expect(report.findings[0].id).toBe('loader_blocked_csp');
+ });
+
+ it('reports a 404 on the runtime separately from a CSP block', () => {
+ const report = analyze(
+ healthyObservations({
+ scripts: [{ src: 'https://three.ws/agent-3d/9.9.9/agent-3d.js', type: 'module' }],
+ network: [{ url: 'https://three.ws/agent-3d/9.9.9/agent-3d.js', status: 404, ok: false }],
+ element: { ...healthyObservations().element, defined: false },
+ }),
+ );
+ const f = byId(report, 'loader_failed');
+ expect(f.severity).toBe('fatal');
+ expect(f.evidence.status).toBe(404);
+ });
+
+ it('catches a module bundle loaded without type="module"', () => {
+ const report = analyze(
+ healthyObservations({ scripts: [{ src: LOADER, type: '' }] }),
+ );
+ const f = byId(report, 'loader_not_module');
+ expect(f.severity).toBe('error');
+ expect(f.evidence.tags[0].type).toBe('(none)');
+ });
+
+ it('does not flag type="module" when at least one loader has it', () => {
+ const report = analyze(
+ healthyObservations({
+ scripts: [
+ { src: LOADER, type: '' },
+ { src: LOADER, type: 'module' },
+ ],
+ }),
+ );
+ expect(byId(report, 'loader_not_module')).toBeUndefined();
+ });
+
+ it('warns about a duplicated loader without calling the page broken', () => {
+ const report = analyze(
+ healthyObservations({
+ scripts: [
+ { src: LOADER, type: 'module' },
+ { src: LOADER, type: 'module' },
+ ],
+ }),
+ );
+ const f = byId(report, 'duplicate_loader');
+ expect(f.severity).toBe('warn');
+ expect(report.verdict).toBe('degraded');
+ });
+});
+
+describe('analyze — the element', () => {
+ it('stops after a missing element, since nothing below it is knowable', () => {
+ const report = analyze(healthyObservations({ element: null }));
+ expect(byId(report, 'element_missing').severity).toBe('fatal');
+ // The loader still gets reported (it is upstream and independently useful).
+ expect(idsOf(report)).toContain('loader_loaded');
+ expect(idsOf(report)).not.toContain('element_visible');
+ });
+
+ it('explains an un-upgraded element as downstream of the runtime', () => {
+ const report = analyze(
+ healthyObservations({ element: { ...healthyObservations().element, defined: false } }),
+ );
+ const f = byId(report, 'element_not_upgraded');
+ expect(f.severity).toBe('fatal');
+ expect(f.fix).toMatch(/loader/i);
+ });
+
+ it('flags an element with no source attribute', () => {
+ const report = analyze(
+ healthyObservations({
+ element: { ...healthyObservations().element, attributes: { mode: 'floating' } },
+ agent: null,
+ }),
+ );
+ const f = byId(report, 'source_missing');
+ expect(f.severity).toBe('fatal');
+ for (const attr of SOURCE_ATTRIBUTES) expect(f.detail).toContain(attr);
+ });
+
+ it('accepts any documented source attribute, not just agent-id', () => {
+ for (const attr of SOURCE_ATTRIBUTES) {
+ const report = analyze(
+ healthyObservations({
+ element: { ...healthyObservations().element, attributes: { [attr]: 'x' } },
+ agent: null,
+ }),
+ );
+ expect(byId(report, 'source_missing'), `${attr} should count as a source`).toBeUndefined();
+ }
+ });
+
+ it('warns when several embeds share a page, because contexts are capped', () => {
+ const report = analyze(
+ healthyObservations({ element: { ...healthyObservations().element, count: 4 } }),
+ );
+ expect(byId(report, 'duplicate_element').evidence.count).toBe(4);
+ });
+});
+
+describe('analyze — the agent id', () => {
+ it('reports an unresolvable id as fatal with the lookup status', () => {
+ const report = analyze(
+ healthyObservations({ agent: { id: 'ghost', resolved: false, status: 404, error: 'HTTP 404' } }),
+ );
+ const f = byId(report, 'agent_unresolved');
+ expect(f.severity).toBe('fatal');
+ expect(f.evidence.agentId).toBe('ghost');
+ expect(f.fix).toMatch(/public/i);
+ });
+
+ it('stays silent when the id form cannot be resolved server-side', () => {
+ // On-chain / CAIP-10 ids are resolved by the runtime against a registry.
+ // Claiming either verdict here would be a guess.
+ const report = analyze(
+ healthyObservations({ agent: { id: 'eip155:8453:0xabc:42', resolved: null } }),
+ );
+ expect(byId(report, 'agent_unresolved')).toBeUndefined();
+ expect(byId(report, 'agent_resolved')).toBeUndefined();
+ });
+});
+
+describe('analyze — visibility', () => {
+ it('names the ancestor that hid the embed', () => {
+ const report = analyze(
+ healthyObservations({
+ element: {
+ ...healthyObservations().element,
+ styles: { display: 'none', visibility: 'visible', opacity: '1' },
+ hiddenAncestor: 'div#tab-panel-2.tab-panel',
+ },
+ }),
+ );
+ const f = byId(report, 'element_hidden');
+ expect(f.evidence.hiddenBy).toBe('div#tab-panel-2.tab-panel');
+ expect(f.detail).toContain('display: none');
+ });
+
+ it('treats opacity:0 as hidden, not merely faint', () => {
+ const report = analyze(
+ healthyObservations({
+ element: {
+ ...healthyObservations().element,
+ styles: { display: 'block', visibility: 'visible', opacity: '0' },
+ },
+ }),
+ );
+ expect(byId(report, 'element_hidden').detail).toContain('opacity: 0');
+ });
+
+ it('catches the collapsed-container case and offers both fixes', () => {
+ const report = analyze(
+ healthyObservations({
+ element: {
+ ...healthyObservations().element,
+ rect: { width: 900, height: 0, top: 10, left: 0 },
+ attributes: { 'agent-id': 'abc123' },
+ },
+ }),
+ );
+ const f = byId(report, 'element_zero_size');
+ expect(f.title).toContain('900×0');
+ expect(f.fix).toMatch(/height/);
+ expect(f.fix).toMatch(/floating/);
+ });
+
+ it('reports an off-screen embed as a warning, not a failure to render', () => {
+ const report = analyze(
+ healthyObservations({ element: { ...healthyObservations().element, offscreen: true } }),
+ );
+ expect(byId(report, 'element_offscreen').severity).toBe('warn');
+ });
+});
+
+describe('analyze — rendering', () => {
+ it('calls missing WebGL fatal and points at the image fallback', () => {
+ const report = analyze(
+ healthyObservations({ webgl: { available: false, renderer: null } }),
+ );
+ const f = byId(report, 'webgl_unavailable');
+ expect(f.severity).toBe('fatal');
+ expect(f.fix).toContain('/api/avatar/render');
+ });
+
+ it('separates "still blank" from "never built a canvas"', () => {
+ const blank = analyze(
+ healthyObservations({
+ element: {
+ ...healthyObservations().element,
+ canvas: { present: true, width: 640, height: 480, blank: true },
+ },
+ }),
+ );
+ expect(byId(blank, 'canvas_blank').severity).toBe('warn');
+
+ const missing = analyze(
+ healthyObservations({
+ element: {
+ ...healthyObservations().element,
+ canvas: { present: false, width: 0, height: 0, blank: true },
+ },
+ }),
+ );
+ expect(byId(missing, 'canvas_missing').severity).toBe('error');
+ expect(byId(missing, 'canvas_blank')).toBeUndefined();
+ });
+
+ it('flags a slow boot without calling it broken', () => {
+ const report = analyze(
+ healthyObservations({ element: { ...healthyObservations().element, bootMs: 9400 } }),
+ );
+ expect(byId(report, 'slow_boot').title).toContain('9.4s');
+ expect(report.verdict).toBe('degraded');
+ });
+});
+
+describe('analyze — transport', () => {
+ it('reports mixed content only on an https page', () => {
+ const insecure = { url: 'http://three.ws/agent-3d/latest/agent-3d.js', status: 0, ok: false };
+ const onHttps = analyze(
+ healthyObservations({ network: [...healthyObservations().network, insecure] }),
+ );
+ expect(byId(onHttps, 'mixed_content')).toBeTruthy();
+
+ const onHttp = analyze(
+ healthyObservations({
+ page: { reachable: true, status: 200, https: false, finalUrl: 'http://example.com/' },
+ network: [...healthyObservations().network, insecure],
+ }),
+ );
+ expect(byId(onHttp, 'mixed_content')).toBeUndefined();
+ });
+
+ it('reports failed embed asset requests but ignores unrelated site noise', () => {
+ const report = analyze(
+ healthyObservations({
+ network: [
+ ...healthyObservations().network,
+ { url: 'https://three.ws/cdn/forge/body.glb', status: 404, ok: false },
+ { url: 'https://ads.example/track.gif', status: 500, ok: false },
+ ],
+ }),
+ );
+ const f = byId(report, 'asset_requests_failed');
+ expect(f.evidence.requests).toHaveLength(1);
+ expect(f.evidence.requests[0].url).toContain('body.glb');
+ });
+
+ it('surfaces console errors from anywhere on the page', () => {
+ const report = analyze(
+ healthyObservations({
+ pageErrors: ['TypeError: t.init is not a function'],
+ console: [{ type: 'error', text: 'Uncaught (in promise) NetworkError' }],
+ }),
+ );
+ const f = byId(report, 'console_errors');
+ expect(f.evidence.messages).toHaveLength(2);
+ expect(f.title).toContain('2 console errors');
+ });
+});
+
+describe('analyze — report ordering and shape', () => {
+ it('puts the finding that explains the failure first', () => {
+ const report = analyze(
+ healthyObservations({
+ scripts: [],
+ network: [],
+ element: {
+ ...healthyObservations().element,
+ defined: false,
+ canvas: { present: false, width: 0, height: 0, blank: true },
+ },
+ }),
+ );
+ expect(report.findings[0].id).toBe('loader_missing');
+ expect(report.findings[0].severity).toBe('fatal');
+ });
+
+ it('sorts failures above passes and never buries a fatal', () => {
+ const report = analyze(
+ healthyObservations({
+ element: {
+ ...healthyObservations().element,
+ rect: { width: 300, height: 0, top: 0, left: 0 },
+ },
+ }),
+ );
+ const firstPass = report.findings.findIndex((f) => f.status === 'pass');
+ const lastFail = report.findings.map((f) => f.status).lastIndexOf('fail');
+ expect(lastFail).toBeLessThan(firstPass);
+ });
+
+ it('gives every failure an actionable fix', () => {
+ // A finding without a fix is a finding the developer cannot act on.
+ const cases = [
+ healthyObservations({ scripts: [], network: [] }),
+ healthyObservations({ element: null }),
+ healthyObservations({ webgl: { available: false } }),
+ healthyObservations({ agent: { id: 'x', resolved: false } }),
+ healthyObservations({
+ element: { ...healthyObservations().element, rect: { width: 0, height: 0, top: 0, left: 0 } },
+ }),
+ ];
+ for (const obs of cases) {
+ for (const f of analyze(obs).findings.filter((x) => x.status === 'fail')) {
+ expect(f.fix, `${f.id} must tell the developer what to change`).toBeTruthy();
+ }
+ }
+ });
+
+ it('never reports an unrun check as passing', () => {
+ const report = analyze(
+ healthyObservations({
+ element: { ...healthyObservations().element, defined: null },
+ }),
+ );
+ const f = byId(report, 'element_upgraded');
+ expect(f.status).toBe('unknown');
+ expect(report.verdict).toBe('inconclusive');
+ });
+
+ it('summarises with the headline a developer should act on', () => {
+ const report = analyze(healthyObservations({ element: null }));
+ expect(report.summary.failed).toBeGreaterThan(0);
+ expect(report.summary.headline).toBe(report.findings[0].title);
+ expect(report.summary.checks).toBe(report.findings.length);
+ });
+});
+
+describe('helpers', () => {
+ it('recognises both the versioned and legacy loader URLs', () => {
+ expect(isEmbedRelated('https://three.ws/agent-3d/1.5.2/agent-3d.js')).toBe(true);
+ expect(isEmbedRelated('https://three.ws/embed.js')).toBe(true);
+ expect(isEmbedRelated('https://cdn.jsdelivr.net/npm/three')).toBe(false);
+ });
+
+ it('treats platform and asset-CDN hosts as embed traffic', () => {
+ expect(isEmbedRelated('https://three.ws/api/agents/x')).toBe(true);
+ expect(isEmbedRelated('https://storage.googleapis.com/three-ws/body.glb')).toBe(true);
+ expect(isEmbedRelated('https://analytics.example/p.gif')).toBe(false);
+ });
+
+ it('does not mistake a lookalike hostname for the platform', () => {
+ expect(isEmbedRelated('https://three.ws.evil.example/agent.js')).toBe(false);
+ expect(isEmbedRelated('https://notthree.ws/x.js')).toBe(false);
+ });
+
+ it('detects the wording browsers actually use for a CSP refusal', () => {
+ expect(looksLikeCspBlock("Refused to load the script 'https://three.ws/x.js'")).toBe(true);
+ expect(looksLikeCspBlock('because it violates the following Content Security Policy directive')).toBe(true);
+ expect(looksLikeCspBlock('Failed to fetch')).toBe(false);
+ expect(looksLikeCspBlock('')).toBe(false);
+ });
+
+ it('builds a sandbox page that adds nothing the snippet could trip over', () => {
+ const html = snippetHostHtml(`<${EMBED_TAG} agent-id="x"></${EMBED_TAG}>`);
+ expect(html).toContain(`<${EMBED_TAG} agent-id="x">`);
+ expect(html).toContain('<!doctype html>');
+ // No framework, no CSP, no third-party script: any failure belongs to the
+ // snippet rather than the harness.
+ expect(html).not.toMatch(/<script src=/i);
+ expect(html).not.toMatch(/content-security-policy/i);
+ });
+});