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(element,avatar-page,marketplace): fall back to the default avatar GLB when a body load fails

nirholas99ed7680b36e
diff --git a/src/avatar-page.js b/src/avatar-page.js
index 0382805f0..bb1bdfe3c 100644
--- a/src/avatar-page.js
+++ b/src/avatar-page.js
@@ -41,6 +41,7 @@ import { mountCoinStatus } from './pump/coin-status-card.js';
import { mountEarningsCard } from './shared/agent-earnings-card.js';
import { renderHomeConfirmation } from './home-confirm-card.js';
import { GROK_MENU_MODELS, grokMenuModelId } from '../api/_lib/chat-models.js';
+import { wireModelViewerFallback } from './shared/model-viewer-fallback.js';
const ATTACHED_KEY_PREFIX = 'avatar_attached_v1:';
@@ -822,9 +823,15 @@ function renderShell(glbUrl) {
positionThoughtHotspot(viewer);
setupAnimationControls(viewer);
});
- viewer?.addEventListener('error', () => {
- const ld = $('av-stage-loading');
- if (ld) ld.textContent = 'Failed to load 3D model.';
+ wireModelViewerFallback(viewer, {
+ onFallback: () => {
+ const ld = $('av-stage-loading');
+ if (ld) ld.textContent = "Couldn't load this avatar's body. Showing a placeholder.";
+ },
+ onFinalError: () => {
+ const ld = $('av-stage-loading');
+ if (ld) ld.textContent = 'Failed to load 3D model.';
+ },
});
// The wallet aura is an independent sibling layer over the stage — mount it
diff --git a/src/element.js b/src/element.js
index 580917cb3..4a2a21f8f 100644
--- a/src/element.js
+++ b/src/element.js
@@ -12,6 +12,7 @@ import { SkillRegistry } from './skills/index.js';
import { Memory } from './memory/index.js';
import { loadManifest, fetchRelative } from './manifest.js';
import { uriCandidates } from './ipfs.js';
+import { DEFAULT_AVATAR_GLB } from './shared/model-viewer-fallback.js';
import {
resolveAgentById,
resolveByAvatarId,
@@ -1960,6 +1961,7 @@ class Agent3DElement extends HTMLElement {
const bodyCandidates = uriCandidates(manifest.body?.uri);
let loadedCandidate = null;
let loadedGltf = null;
+ let usedFallbackBody = false;
if (bodyCandidates.length) {
let bodyErr;
let loaded = false;
@@ -1979,8 +1981,34 @@ class Agent3DElement extends HTMLElement {
}
}
}
+ // Every gateway for the real body failed. The local default avatar
+ // (bundled, same-origin, no R2/IPFS dependency) gets one try before
+ // giving up outright, so an object-storage outage degrades to a
+ // placeholder body instead of a dead viewer. Skipped when the real
+ // body candidates already included the default (nothing new to try).
+ if (!loaded && !bodyCandidates.includes(DEFAULT_AVATAR_GLB)) {
+ try {
+ loadedGltf = await viewer.load(DEFAULT_AVATAR_GLB, '', new Map());
+ loadedCandidate = DEFAULT_AVATAR_GLB;
+ loaded = true;
+ usedFallbackBody = true;
+ console.warn(
+ '[agent-3d] body load failed on %s, falling back to the default avatar',
+ bodyCandidates[bodyCandidates.length - 1],
+ );
+ } catch {
+ // Fallback also failed; the original error is the useful one.
+ }
+ }
if (!loaded)
throw bodyErr || new Error('avatar body could not be loaded from any gateway');
+ if (usedFallbackBody) {
+ this._emit(
+ 'agent:body-fallback',
+ { uri: bodyCandidates[bodyCandidates.length - 1], fallbackUri: DEFAULT_AVATAR_GLB },
+ { bubbles: true, composed: true },
+ );
+ }
// 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).
@@ -2485,7 +2513,7 @@ class Agent3DElement extends HTMLElement {
spec: 'agent-manifest/0.1',
_baseURI: '',
name: this.getAttribute('name') || 'Agent',
- body: { uri: 'https://three.ws/avatars/default.glb', format: 'gltf-binary' },
+ body: { uri: DEFAULT_AVATAR_GLB, format: 'gltf-binary' },
brain: this._brainConfig(instructionsAttr),
voice: { tts: { provider: 'browser' }, stt: { provider: 'browser' } },
skills: [],
diff --git a/src/marketplace.js b/src/marketplace.js
index b04fdb276..7fcc6241e 100644
--- a/src/marketplace.js
+++ b/src/marketplace.js
@@ -32,6 +32,7 @@ import { resizedImageUrl } from './shared/image-url.js';
import { leaveAppForPayment } from './shared/native-handoff.js';
import { withPayoutStepUp } from './payout-step-up.js';
import { shortAddress as shortWalletAddress } from './shared/address.js';
+import { wireModelViewerFallback } from './shared/model-viewer-fallback.js';
ensureStateKitStyles();
@@ -1660,11 +1661,18 @@ function openAvatarModal(avatar) {
const label = progressEl.querySelector('.modal-load-label');
if (label) label.textContent = 'Failed to load 3D — try refreshing.';
}, 15_000);
- mv.addEventListener('error', () => {
- clearTimeout(loadTimeout);
- const label = progressEl.querySelector('.modal-load-label');
- if (label) label.textContent = 'Failed to load 3D model.';
- }, { once: true });
+ wireModelViewerFallback(mv, {
+ onFallback: () => {
+ clearTimeout(loadTimeout);
+ const label = progressEl.querySelector('.modal-load-label');
+ if (label) label.textContent = "Couldn't load this avatar's body. Showing a placeholder.";
+ },
+ onFinalError: () => {
+ clearTimeout(loadTimeout);
+ const label = progressEl.querySelector('.modal-load-label');
+ if (label) label.textContent = 'Failed to load 3D model.';
+ },
+ });
mv.addEventListener('load', () => clearTimeout(loadTimeout), { once: true });
$('avatar-modal-title').textContent = avatar.name || 'Untitled avatar';
diff --git a/src/shared/model-viewer-fallback.js b/src/shared/model-viewer-fallback.js
new file mode 100644
index 000000000..892556296
--- /dev/null
+++ b/src/shared/model-viewer-fallback.js
@@ -0,0 +1,34 @@
+/**
+ * Shared GLB-load-failure recovery for `<model-viewer>` elements.
+ *
+ * When a body GLB fails to load (an R2 outage, a missing object, a corrupt
+ * upload), the local default avatar (`public/avatars/default.glb`, same
+ * origin, no object-storage dependency) stands in once rather than leaving a
+ * dead viewer. Only if the default avatar itself also fails does the final
+ * unrecoverable state apply.
+ */
+
+export const DEFAULT_AVATAR_GLB = 'https://three.ws/avatars/default.glb';
+
+/**
+ * Wires the fallback onto a `<model-viewer>`-like element.
+ *
+ * @param {EventTarget & { getAttribute(name: string): string | null, setAttribute(name: string, value: string): void }} viewer
+ * @param {{ onFallback?: () => void, onFinalError?: () => void }} [handlers]
+ */
+export function wireModelViewerFallback(viewer, { onFallback, onFinalError } = {}) {
+ if (!viewer) return;
+ viewer.addEventListener(
+ 'error',
+ () => {
+ if (viewer.getAttribute('src') === DEFAULT_AVATAR_GLB) {
+ onFinalError?.();
+ return;
+ }
+ viewer.setAttribute('src', DEFAULT_AVATAR_GLB);
+ onFallback?.();
+ viewer.addEventListener('error', () => onFinalError?.(), { once: true });
+ },
+ { once: true },
+ );
+}
diff --git a/tests/src/element-body-fallback.test.js b/tests/src/element-body-fallback.test.js
new file mode 100644
index 000000000..cc8dc40f4
--- /dev/null
+++ b/tests/src/element-body-fallback.test.js
@@ -0,0 +1,137 @@
+// @vitest-environment jsdom
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// Same stubbing strategy as element-boot-race.test.js, but `ipfs.js` is left
+// unmocked here: the fallback compares the *resolved* candidate against
+// DEFAULT_AVATAR_GLB, so the test needs uriCandidates()'s real behavior for a
+// plain HTTPS URL (one entry, per tests/ipfs-uri-candidates.test.js).
+const { state, DEFAULT_AVATAR_GLB, REAL_BODY_URL } = vi.hoisted(() => ({
+ state: { failDefaultToo: false },
+ DEFAULT_AVATAR_GLB: 'https://three.ws/avatars/default.glb',
+ REAL_BODY_URL: 'https://three.ws/api/avatars/test-id/glb',
+}));
+
+vi.mock('../../src/viewer.js', () => ({
+ Viewer: class {
+ constructor(stage) {
+ this.stage = stage;
+ this.scene = { background: null };
+ this.renderer = { setClearAlpha() {} };
+ }
+ async load(uri) {
+ if (uri === DEFAULT_AVATAR_GLB) {
+ if (state.failDefaultToo) throw new Error('default avatar also failed');
+ return {};
+ }
+ throw new Error(`body load failed for ${uri}`);
+ }
+ invalidate() {}
+ dispose() {}
+ },
+}));
+vi.mock('../../src/runtime/index.js', () => ({
+ Runtime: class extends EventTarget {
+ constructor() { super(); }
+ destroy() {}
+ },
+}));
+vi.mock('../../src/runtime/scene.js', () => ({
+ SceneController: class {
+ playClipByName() {}
+ },
+}));
+vi.mock('../../src/skills/index.js', () => ({
+ SkillRegistry: class { async install() { return { name: 'x', uri: 'x' }; } all() { return []; } },
+}));
+vi.mock('../../src/memory/index.js', () => ({
+ Memory: { async load() { return { recall() { return []; } }; } },
+}));
+vi.mock('../../src/manifest.js', () => ({
+ loadManifest: vi.fn(async () => ({
+ spec: 'agent-manifest/0.1',
+ _baseURI: '',
+ name: 'Test',
+ body: { uri: '' },
+ brain: { provider: 'none' },
+ voice: {},
+ skills: [],
+ })),
+ fetchRelative: vi.fn(async () => ''),
+}));
+vi.mock('../../src/agent-resolver.js', () => ({
+ resolveAgentById: vi.fn(),
+ resolveByAgentId: vi.fn(async () => null),
+ AgentResolveError: class extends Error {},
+}));
+vi.mock('../../src/erc8004/resolver.js', () => ({
+ parseAgentRef: () => null,
+ resolveOnchainAgent: vi.fn(),
+ toManifest: vi.fn(),
+}));
+vi.mock('../../src/pump/trade-reactions.js', () => ({
+ attachTradeReactions: () => () => {},
+}));
+vi.mock('../../src/embed-action-bridge.js', () => ({ EmbedActionBridge: class { start() {} stop() {} } }));
+vi.mock('../../src/agent-protocol.js', () => ({
+ protocol: { emit() {}, on() {}, off() {} },
+ ACTION_TYPES: {},
+}));
+
+globalThis.fetch = vi.fn(async () => ({
+ ok: false,
+ status: 404,
+ json: async () => ({}),
+}));
+
+beforeEach(async () => {
+ state.failDefaultToo = false;
+ if (!customElements.get('agent-3d')) {
+ await import('../../src/element.js');
+ }
+ document.body.innerHTML = '';
+});
+
+describe('<agent-3d> body-load fallback', () => {
+ it('falls back to the default avatar and reaches ready when the real body fails', async () => {
+ const el = document.createElement('agent-3d');
+ el.setAttribute('body', REAL_BODY_URL);
+ el.setAttribute('eager', '');
+
+ const events = [];
+ el.addEventListener('agent:ready', () => events.push('ready'));
+ el.addEventListener('agent:error', () => events.push('error'));
+ el.addEventListener('agent:body-fallback', (e) => events.push({ type: 'fallback', detail: e.detail }));
+
+ document.body.appendChild(el);
+ await new Promise((r) => setTimeout(r, 100));
+
+ expect(events).toContainEqual({
+ type: 'fallback',
+ detail: { uri: REAL_BODY_URL, fallbackUri: DEFAULT_AVATAR_GLB },
+ });
+ expect(events).toContain('ready');
+ expect(events).not.toContain('error');
+ expect(el.shadowRoot.querySelector('.error')).toBeNull();
+ });
+
+ it('still shows the existing error path when the default avatar also fails to load', async () => {
+ state.failDefaultToo = true;
+ const el = document.createElement('agent-3d');
+ el.setAttribute('body', REAL_BODY_URL);
+ el.setAttribute('eager', '');
+ el.setAttribute('chat', '');
+
+ const events = [];
+ el.addEventListener('agent:ready', () => events.push('ready'));
+ el.addEventListener('agent:error', (e) => events.push({ type: 'error', detail: e.detail }));
+ el.addEventListener('agent:body-fallback', () => events.push('fallback'));
+
+ document.body.appendChild(el);
+ await new Promise((r) => setTimeout(r, 100));
+
+ expect(events).not.toContain('ready');
+ expect(events).not.toContain('fallback');
+ expect(events.some((e) => e && e.type === 'error' && e.detail?.phase === 'boot')).toBe(true);
+ expect(el.shadowRoot.querySelector('.error')).toBeTruthy();
+ });
+});
diff --git a/tests/src/model-viewer-fallback.test.js b/tests/src/model-viewer-fallback.test.js
new file mode 100644
index 000000000..ed3063fd9
--- /dev/null
+++ b/tests/src/model-viewer-fallback.test.js
@@ -0,0 +1,62 @@
+// @vitest-environment jsdom
+//
+// avatar-page.js and marketplace.js each wire a <model-viewer> `error`
+// listener to this shared helper. Neither module is importable in isolation
+// under jsdom (avatar-page.js resolves a real entity via network on import;
+// marketplace.js's init() queries full-page markup that doesn't exist in a
+// bare DOM), so this tests the helper directly rather than importing either
+// page controller, per the work order's "minimal harness" guidance.
+import { describe, it, expect, vi } from 'vitest';
+import { wireModelViewerFallback, DEFAULT_AVATAR_GLB } from '../../src/shared/model-viewer-fallback.js';
+
+function makeViewer(src) {
+ const mv = document.createElement('model-viewer');
+ mv.setAttribute('src', src);
+ document.body.appendChild(mv);
+ return mv;
+}
+
+describe('wireModelViewerFallback', () => {
+ it('swaps src to the default avatar and calls onFallback on the first error', () => {
+ const mv = makeViewer('https://three.ws/api/avatars/abc/glb');
+ const onFallback = vi.fn();
+ const onFinalError = vi.fn();
+ wireModelViewerFallback(mv, { onFallback, onFinalError });
+
+ mv.dispatchEvent(new Event('error'));
+
+ expect(mv.getAttribute('src')).toBe(DEFAULT_AVATAR_GLB);
+ expect(onFallback).toHaveBeenCalledTimes(1);
+ expect(onFinalError).not.toHaveBeenCalled();
+ });
+
+ it('calls onFinalError and stops swapping src when the fallback also errors', () => {
+ const mv = makeViewer('https://three.ws/api/avatars/abc/glb');
+ const onFallback = vi.fn();
+ const onFinalError = vi.fn();
+ wireModelViewerFallback(mv, { onFallback, onFinalError });
+
+ mv.dispatchEvent(new Event('error'));
+ mv.dispatchEvent(new Event('error'));
+
+ expect(mv.getAttribute('src')).toBe(DEFAULT_AVATAR_GLB);
+ expect(onFallback).toHaveBeenCalledTimes(1);
+ expect(onFinalError).toHaveBeenCalledTimes(1);
+ });
+
+ it('goes straight to onFinalError when the src is already the default avatar', () => {
+ const mv = makeViewer(DEFAULT_AVATAR_GLB);
+ const onFallback = vi.fn();
+ const onFinalError = vi.fn();
+ wireModelViewerFallback(mv, { onFallback, onFinalError });
+
+ mv.dispatchEvent(new Event('error'));
+
+ expect(onFallback).not.toHaveBeenCalled();
+ expect(onFinalError).toHaveBeenCalledTimes(1);
+ });
+
+ it('does nothing when no viewer is passed', () => {
+ expect(() => wireModelViewerFallback(null, {})).not.toThrow();
+ });
+});