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(embed): stop a lost host realm turning a handled boot failure into a crash

nirholas8d70251ecb6f
diff --git a/src/element.js b/src/element.js
index 7d89c549e..ccf55d318 100644
--- a/src/element.js
+++ b/src/element.js
@@ -1876,9 +1876,7 @@ class Agent3DElement extends HTMLElement {
'memory:write',
]) {
this._runtime.addEventListener(ev, (e) => {
- this.dispatchEvent(
- new CustomEvent(ev, { detail: e.detail, bubbles: true, composed: true }),
- );
+ this._emit(ev, e.detail, { bubbles: true, composed: true });
if (ev === 'brain:message') {
// Transfer sentiment from the most recent tool call to
// this assistant message so the bubble tints correctly.
@@ -2041,13 +2039,10 @@ class Agent3DElement extends HTMLElement {
}
}
} catch {}
- this.dispatchEvent(
- new CustomEvent('skill:purchased', {
- detail: e.detail,
- bubbles: true,
- composed: true,
- }),
- );
+ this._emit('skill:purchased', e.detail, {
+ bubbles: true,
+ composed: true,
+ });
}
});
}
@@ -2664,19 +2659,30 @@ class Agent3DElement extends HTMLElement {
);
}
- // Dispatch an element event using the constructor from THIS element's own
- // window. `new CustomEvent(...)` reads whichever global is bound at call
- // time, and _boot is fire-and-forget: an await inside it can settle after the
- // host's document was replaced (an SPA remount, or a test runner tearing a
- // DOM down between files), leaving the element in one realm and the global in
- // another. dispatchEvent then rejects the object as "not of type Event",
- // which throws out of _boot's own catch and becomes an unhandled rejection:
- // a handled boot failure reported as a crash. Same-realm construction cannot
- // mismatch, and an element whose window is gone has nobody left to notify.
+ // The single path every element event goes out through. Notifying the host is
+ // a boundary, not a control-flow step, so it must never be able to throw back
+ // into its caller.
+ //
+ // Two things make that a real risk. `new CustomEvent(...)` reads whichever
+ // global is bound at call time, so we construct from THIS element's own
+ // window instead. And _boot is fire-and-forget: an await inside it can settle
+ // after the host's document was replaced (an SPA remount, or a test runner
+ // tearing a DOM down between files), which leaves the element in one realm
+ // while its window object has been handed a foreign CustomEvent. dispatchEvent
+ // rejects that object as "not of type Event", and thrown from inside _boot's
+ // own catch it becomes an unhandled rejection: a handled boot failure reported
+ // as a crash. An element whose realm no longer accepts its events has nobody
+ // left to notify, so dropping the event is the whole correct response. Nothing
+ // else escapes here: a listener that throws is reported by the DOM itself and
+ // never propagates out of dispatchEvent.
_emit(type, detail, { bubbles = false, composed = false } = {}) {
const view = this.ownerDocument?.defaultView;
if (!view) return;
- this.dispatchEvent(new view.CustomEvent(type, { detail, bubbles, composed }));
+ try {
+ this.dispatchEvent(new view.CustomEvent(type, { detail, bubbles, composed }));
+ } catch (err) {
+ log.debug('[agent-3d] dropped', type, 'event: host realm is gone', err);
+ }
}
_showError(err) {
@@ -2724,12 +2730,10 @@ class Agent3DElement extends HTMLElement {
// Bare avatars report policy failures through the event only, with no
// visible error banner. Chat agents also render a banner below.
if (!this._isChatMode()) {
- this.dispatchEvent(
- new CustomEvent('agent:error', {
- detail: { phase: 'policy', error: { code, message } },
- bubbles: true,
- composed: true,
- }),
+ this._emit(
+ 'agent:error',
+ { phase: 'policy', error: { code, message } },
+ { bubbles: true, composed: true },
);
return;
}
@@ -2737,12 +2741,10 @@ class Agent3DElement extends HTMLElement {
el.className = 'error';
el.textContent = message;
this.shadowRoot.appendChild(el);
- this.dispatchEvent(
- new CustomEvent('agent:error', {
- detail: { phase: 'policy', error: { code, message } },
- bubbles: true,
- composed: true,
- }),
+ this._emit(
+ 'agent:error',
+ { phase: 'policy', error: { code, message } },
+ { bubbles: true, composed: true },
);
}
@@ -2944,12 +2946,10 @@ class Agent3DElement extends HTMLElement {
type: ACTION_TYPES.EMOTE,
payload: { trigger: 'concern', weight: 0.8 },
});
- this.dispatchEvent(
- new CustomEvent('agent:error', {
- detail: { phase: 'send', error: err },
- bubbles: true,
- composed: true,
- }),
+ this._emit(
+ 'agent:error',
+ { phase: 'send', error: err },
+ { bubbles: true, composed: true },
);
}
}
diff --git a/tests/src/element-emit-realm.test.js b/tests/src/element-emit-realm.test.js
new file mode 100644
index 000000000..db225a4b0
--- /dev/null
+++ b/tests/src/element-emit-realm.test.js
@@ -0,0 +1,116 @@
+// @vitest-environment jsdom
+import { describe, it, expect, vi } from 'vitest';
+
+// element.js pulls in a WebGL Viewer and the dat.GUI debug panel on boot,
+// neither of which survives jsdom. Nothing here exercises rendering: the
+// subject is _emit, which runs entirely in the DOM.
+vi.mock('../../src/viewer.js', () => ({ Viewer: class {} }));
+vi.mock('dat.gui', () => ({
+ GUI: class {
+ addFolder() { return this; }
+ add() { return { onChange: () => this, name: () => this }; }
+ addColor() { return { onChange: () => this, name: () => this }; }
+ destroy() {}
+ },
+}));
+
+import '../../src/element.js';
+
+// Stands in for the CustomEvent an element is left holding once its realm has
+// moved on: a constructor whose products the element's own dispatchEvent
+// refuses as "not of type 'Event'". That is exactly what a host page hands the
+// element after an SPA remount, and what a test runner hands it when it
+// restores the platform globals it swapped out for a DOM.
+class ForeignCustomEvent {
+ constructor(type, init = {}) {
+ this.type = type;
+ this.detail = init.detail;
+ }
+}
+
+const withForeignCustomEvent = (view, run) => {
+ const original = view.CustomEvent;
+ view.CustomEvent = ForeignCustomEvent;
+ try {
+ return run();
+ } finally {
+ view.CustomEvent = original;
+ }
+};
+
+describe('<agent-3d> event dispatch across a lost realm', () => {
+ it('delivers an event normally when the realm is intact', () => {
+ const el = document.createElement('agent-3d');
+ document.body.appendChild(el);
+
+ const seen = [];
+ el.addEventListener('agent:error', (e) => seen.push(e.detail));
+ el._emit('agent:error', { phase: 'boot' }, { bubbles: true, composed: true });
+
+ expect(seen).toEqual([{ phase: 'boot' }]);
+ });
+
+ it('drops the event instead of throwing when the realm no longer accepts it', () => {
+ const el = document.createElement('agent-3d');
+ document.body.appendChild(el);
+ const view = el.ownerDocument.defaultView;
+
+ const seen = [];
+ el.addEventListener('agent:error', (e) => seen.push(e.detail));
+
+ withForeignCustomEvent(view, () => {
+ // The whole point: this is called from inside _boot's catch, so a throw
+ // here turns a handled boot failure into an unhandled rejection that
+ // fails the process rather than the element.
+ expect(() =>
+ el._emit('agent:error', { phase: 'boot' }, { bubbles: true, composed: true }),
+ ).not.toThrow();
+ });
+
+ // Nobody was reachable, so nothing was delivered. That is the correct
+ // outcome, not a swallowed delivery.
+ expect(seen).toEqual([]);
+ });
+
+ it('lets a boot failure settle after the realm is gone without an unhandled rejection', async () => {
+ const el = document.createElement('agent-3d');
+ document.body.appendChild(el);
+ const view = el.ownerDocument.defaultView;
+
+ // Let the connect-time boot settle first. The stubbed Viewer has no load(),
+ // so it fails, runs the catch, and leaves the element bootable again --
+ // _boot() early-returns while _booting is still true.
+ const settle = async () => {
+ for (let i = 0; i < 200 && el._booting; i += 1) {
+ await new Promise((r) => setTimeout(r, 5));
+ }
+ };
+ await settle();
+ expect(el._booting).toBe(false);
+ expect(el._mounted).toBeFalsy();
+
+ const rejections = [];
+ const onRejection = (err) => rejections.push(err);
+ process.on('unhandledRejection', onRejection);
+
+ try {
+ const original = view.CustomEvent;
+ view.CustomEvent = ForeignCustomEvent;
+ try {
+ // Fire-and-forget, exactly how every production caller invokes it.
+ // Nothing is holding this promise, so a throw out of the catch block
+ // has nowhere to go but the process.
+ el._boot();
+ await settle();
+ } finally {
+ view.CustomEvent = original;
+ }
+ // Give a rejection a turn to surface before we stop listening.
+ await new Promise((r) => setTimeout(r, 10));
+ } finally {
+ process.off('unhandledRejection', onRejection);
+ }
+
+ expect(rejections).toEqual([]);
+ });
+});