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.

fix(embeds): retry an agent's avatar across every IPFS gateway so one rate-limited gateway stops blanking agent pages and third-party embeds

nirholase266c2e3e2d7
diff --git a/src/element.js b/src/element.js
index cdc7f3bbe..81fd8279d 100644
--- a/src/element.js
+++ b/src/element.js
@@ -9,7 +9,7 @@ import { SceneController } from './runtime/scene.js';
import { SkillRegistry } from './skills/index.js';
import { Memory } from './memory/index.js';
import { loadManifest, fetchRelative } from './manifest.js';
-import { resolveURI } from './ipfs.js';
+import { uriCandidates } from './ipfs.js';
import {
resolveAgentById,
resolveByAgentId,
@@ -1626,9 +1626,26 @@ class Agent3DElement extends HTMLElement {
}
} catch {}
- const bodyURI = resolveURI(manifest.body?.uri);
- if (bodyURI) {
- await viewer.load(bodyURI, '', new Map());
+ // Every gateway that can serve this body, in order. A single baked-in
+ // gateway (ipfs.io rate-limits browsers routinely) used to leave a
+ // third-party embed with a name and no avatar and no way to recover.
+ const bodyCandidates = uriCandidates(manifest.body?.uri);
+ if (bodyCandidates.length) {
+ let bodyErr;
+ let loaded = false;
+ for (const candidate of bodyCandidates) {
+ try {
+ await viewer.load(candidate, '', new Map());
+ loaded = true;
+ break;
+ } catch (err) {
+ bodyErr = err;
+ if (candidate !== bodyCandidates[bodyCandidates.length - 1]) {
+ console.warn('[agent-3d] body load failed on %s, trying the next gateway', candidate);
+ }
+ }
+ }
+ if (!loaded) throw bodyErr || new Error('avatar body could not be loaded from any gateway');
// Ensure walk + idle are hot before the first brain:stream fires.
// setAnimationDefs above registered the defs; ensureLoaded now
// actually fetches the clips (or returns immediately if cached).
diff --git a/src/ipfs.js b/src/ipfs.js
index 3f2e807bc..7ea1fa5fe 100644
--- a/src/ipfs.js
+++ b/src/ipfs.js
@@ -21,6 +21,10 @@ const IPFS_GATEWAYS = [
const AR_GATEWAY = 'https://arweave.net/';
+// Per-gateway budget. Public gateways routinely accept a connection and then
+// never answer; without a deadline the first such host holds the whole chain.
+const GATEWAY_TIMEOUT_MS = 8_000;
+
// Hosts that no longer resolve. Any HTTPS gateway URL using one of these is
// rewritten onto the primary working gateway (preserving the /ipfs/<cid>/path).
const DEAD_GATEWAY_HOST_RE = /^https?:\/\/(?:cf-ipfs\.com|cloudflare-ipfs\.com)\/ipfs\/(.+)$/i;
@@ -160,19 +164,52 @@ export function proxiedImageURL(url, seed = '') {
return `/api/img?${q.toString()}`;
}
+// Pull the CID (plus any path) back out of a URL that already names a gateway,
+// so content whose gateway was baked in upstream can still be rotated. Matches
+// the /ipfs/<cid>[/path] form every gateway in the list serves.
+const GATEWAY_URL_RE = /^https?:\/\/[^/]+\/ipfs\/(.+)$/i;
+
+/**
+ * Every HTTPS URL that can serve one piece of decentralised content, in
+ * preference order. An `ipfs://` URI expands to one URL per gateway; so does a
+ * URL that already points at a gateway (its CID is re-extracted), which is what
+ * makes content whose gateway was chosen upstream recoverable. Anything else
+ * (a plain CDN URL, `ar://`) yields the single normalised URL, so callers can
+ * loop over the result unconditionally.
+ *
+ * @param {string} uri
+ * @returns {string[]}
+ */
+export function uriCandidates(uri) {
+ if (!uri) return [];
+ const ipfsMatch = String(uri).match(/^ipfs:\/\/(.+)$/i);
+ const cid = ipfsMatch ? ipfsMatch[1] : (String(uri).match(GATEWAY_URL_RE) || [])[1];
+ if (cid) {
+ const first = resolveURI(uri, 0);
+ const all = IPFS_GATEWAYS.map((gw) => gw + cid);
+ // Keep whatever the caller (or an upstream resolver) already chose at the
+ // head of the list: it is the one most likely to be warm in a CDN.
+ return [first, ...all.filter((u) => u !== first)];
+ }
+ const single = resolveURI(uri, 0);
+ return single ? [single] : [];
+}
+
/**
* Try to fetch from the primary gateway; on failure, cycle through fallbacks.
*
- * @param {string} ipfsURI An ipfs:// URI.
+ * @param {string} ipfsURI An ipfs:// URI, or any URL uriCandidates understands.
* @returns {Promise<Response>}
*/
export async function fetchWithFallback(ipfsURI) {
let lastError;
- for (let i = 0; i < IPFS_GATEWAYS.length; i++) {
- const url = resolveURI(ipfsURI, i);
+ for (const url of uriCandidates(ipfsURI)) {
try {
- const res = await fetch(url);
+ // Bounded per gateway: a black-holing gateway used to block the whole
+ // chain behind it, which made the fallback list decorative.
+ const res = await fetch(url, { signal: AbortSignal.timeout(GATEWAY_TIMEOUT_MS) });
if (res.ok) return res;
+ lastError = new Error(`${url} responded ${res.status}`);
} catch (err) {
lastError = err;
}
diff --git a/tests/ipfs-uri-candidates.test.js b/tests/ipfs-uri-candidates.test.js
new file mode 100644
index 000000000..250a98faa
--- /dev/null
+++ b/tests/ipfs-uri-candidates.test.js
@@ -0,0 +1,51 @@
+// Gateway rotation for decentralised content (src/ipfs.js).
+//
+// A CID is served identically by every IPFS gateway, but the app kept picking
+// one and dead-ending on it: the ERC-8004 resolver baked `ipfs.io` into an
+// agent's `image` and `body.uri` before the browser ever saw the `ipfs://`
+// scheme, so a rate-limited ipfs.io (which happens to browsers routinely) left
+// every /a/:chainId/:agentId page and every third-party <agent-3d> embed with a
+// name, no avatar, and no way to recover. uriCandidates exists so a caller can
+// walk the whole list, including when the gateway was already chosen upstream.
+
+import { describe, it, expect } from 'vitest';
+
+import { uriCandidates, resolveURI } from '../src/ipfs.js';
+
+describe('uriCandidates', () => {
+ it('expands an ipfs:// URI across every gateway, primary first', () => {
+ const out = uriCandidates('ipfs://bafyCID/model.glb');
+ expect(out.length).toBeGreaterThan(1);
+ expect(out[0]).toBe(resolveURI('ipfs://bafyCID/model.glb'));
+ expect(new Set(out).size).toBe(out.length);
+ for (const url of out) expect(url.endsWith('bafyCID/model.glb')).toBe(true);
+ });
+
+ it('re-extracts the CID from a URL whose gateway was already chosen', () => {
+ const out = uriCandidates('https://ipfs.io/ipfs/bafyCID');
+ // The caller's own choice stays first (most likely warm in a CDN), and the
+ // other gateways follow as recovery options.
+ expect(out[0]).toBe('https://ipfs.io/ipfs/bafyCID');
+ expect(out.length).toBeGreaterThan(1);
+ expect(out.some((url) => url.startsWith('https://dweb.link/ipfs/bafyCID'))).toBe(true);
+ });
+
+ it('rewrites a retired gateway host onto a live one', () => {
+ const out = uriCandidates('https://cloudflare-ipfs.com/ipfs/bafyCID');
+ expect(out.every((url) => !url.includes('cloudflare-ipfs.com'))).toBe(true);
+ expect(out.every((url) => url.endsWith('bafyCID'))).toBe(true);
+ });
+
+ it('returns one entry for a plain URL so callers can loop unconditionally', () => {
+ expect(uriCandidates('https://cdn.example/model.glb')).toEqual(['https://cdn.example/model.glb']);
+ });
+
+ it('resolves an ar:// URI to its single gateway', () => {
+ expect(uriCandidates('ar://TX123')).toEqual(['https://arweave.net/TX123']);
+ });
+
+ it('returns nothing for an empty URI', () => {
+ expect(uriCandidates('')).toEqual([]);
+ expect(uriCandidates(null)).toEqual([]);
+ });
+});