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(agora): stop leaking orphaned deliverable models on back-to-back completions

nirholasa3660d323ee0
diff --git a/src/agora/economy-fx.js b/src/agora/economy-fx.js
index 463111d79..98e26143d 100644
--- a/src/agora/economy-fx.js
+++ b/src/agora/economy-fx.js
@@ -58,6 +58,8 @@ export class EconomyFx {
this._coins = []; // active coin sprites
this._labels = []; // active floating HTML labels
this._t = 0;
+ this._deliverableGen = 0; // guards overlapping GLB loads (see showDeliverable)
+ this._disposed = false;
this._buildPlinth();
}
@@ -107,10 +109,21 @@ export class EconomyFx {
async showDeliverable(url) {
this._retireDeliverableModel();
if (!isGlb(url)) return false;
+ // Completions can land back-to-back, and a GLB load is slow enough that two
+ // can be in flight at once. Without a generation guard the loser's model
+ // still gets parented to the plinth and then orphaned when `_plinthModel`
+ // is overwritten, invisible to `_retireDeliverableModel` and to dispose(),
+ // i.e. exactly the leak this file is supposed to prevent. Stamp each load
+ // and let only the newest mount; anything stale is disposed on arrival.
+ const generation = ++this._deliverableGen;
try {
await _meshoptWired;
const gltf = await _gltf.loadAsync(url);
const model = gltf.scene;
+ if (generation !== this._deliverableGen || this._disposed) {
+ disposeObject(model);
+ return false;
+ }
// Normalise to ~1.6m tall, centred on the plinth top.
const box = new THREE.Box3().setFromObject(model);
@@ -137,10 +150,16 @@ export class EconomyFx {
}
_retireDeliverableModel() {
- if (!this._plinthModel) return;
- this._plinthModelHolder.remove(this._plinthModel);
- disposeObject(this._plinthModel);
+ // Invalidate any load still in flight so it can't mount behind this retire.
+ this._deliverableGen++;
+ // Dispose by walking the holder, not just the tracked handle, so nothing
+ // parented here can survive as an orphan.
+ for (const child of [...this._plinthModelHolder.children]) {
+ this._plinthModelHolder.remove(child);
+ disposeObject(child);
+ }
this._plinthModel = null;
+ this._plinthModelHolder.rotation.y = 0;
this._spotLight.intensity = 0;
}
@@ -249,13 +268,23 @@ export class EconomyFx {
}
}
+ // Live prefers-reduced-motion change. Coins already in flight keep their arc
+ // (yanking them mid-air is its own jolt); everything that loops (the plinth
+ // spin, label rise, future coin flows) settles from the next frame on.
+ setReducedMotion(on) {
+ this.reducedMotion = !!on;
+ if (this.reducedMotion) this._plinthModelHolder.rotation.y = 0;
+ }
+
dispose() {
+ this._disposed = true;
for (const c of this._coins) { this.scene.remove(c.mesh); c.mat.dispose(); }
this._coins = [];
for (const l of this._labels) l.el.remove();
this._labels = [];
this._retireDeliverableModel();
for (const d of this._plinthDisposables) d.dispose?.();
+ this._spotLight.dispose?.();
this.scene.remove(this._plinthGroup);
// _coinGeo is module-shared across the page lifetime — not disposed here.
}
diff --git a/tests/agora-economy-fx.test.js b/tests/agora-economy-fx.test.js
new file mode 100644
index 000000000..d7fb67e9d
--- /dev/null
+++ b/tests/agora-economy-fx.test.js
@@ -0,0 +1,208 @@
+// @vitest-environment jsdom
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import * as THREE from 'three';
+
+// The deliverable loader is the one piece of EconomyFx that reaches the network.
+// We drive it directly so the completion moment (coin flow, reward label, rep
+// tick, plinth model, and above all the DISPOSAL of a retired model) is
+// verifiable without a live GLB fetch. The models handed back are real
+// THREE.Object3D graphs, so the disposal assertions exercise the real traversal.
+const loadCalls = [];
+vi.mock('three/addons/loaders/GLTFLoader.js', () => ({
+ GLTFLoader: class {
+ setDRACOLoader() {}
+ setMeshoptDecoder() {}
+ loadAsync(url) {
+ let resolve;
+ const promise = new Promise((r) => { resolve = r; });
+ loadCalls.push({ url, resolve });
+ return promise;
+ }
+ },
+}));
+vi.mock('../src/game/avatar-rig.js', () => ({
+ dracoLoader: {},
+ meshoptReady: Promise.resolve(null),
+}));
+
+const { EconomyFx } = await import('../src/agora/economy-fx.js');
+
+// A loaded deliverable: one mesh with a geometry, material and a texture map,
+// i.e. every handle EconomyFx is responsible for releasing.
+function fakeGltf(name) {
+ const geometry = new THREE.BoxGeometry(1, 1, 1);
+ const map = new THREE.Texture();
+ const material = new THREE.MeshStandardMaterial({ map });
+ const mesh = new THREE.Mesh(geometry, material);
+ mesh.name = name;
+ const scene = new THREE.Group();
+ scene.add(mesh);
+ return {
+ gltf: { scene },
+ spies: {
+ geometry: vi.spyOn(geometry, 'dispose'),
+ material: vi.spyOn(material, 'dispose'),
+ map: vi.spyOn(map, 'dispose'),
+ },
+ };
+}
+
+// showDeliverable awaits the meshopt decoder before it reaches loadAsync, so the
+// pending load only appears after the microtask queue drains.
+const tick = () => new Promise((r) => setTimeout(r, 0));
+
+function makeFx(overrides = {}) {
+ const scene = new THREE.Scene();
+ const root = document.createElement('div');
+ document.body.appendChild(root);
+ const fx = new EconomyFx({
+ scene, root,
+ worldToScreen: () => ({ x: 10, y: 10, visible: true }),
+ reducedMotion: false,
+ focusOn: vi.fn(),
+ boardPosition: new THREE.Vector3(0, 0, -6),
+ ...overrides,
+ });
+ return { fx, scene, root };
+}
+
+beforeEach(() => {
+ loadCalls.length = 0;
+ document.body.innerHTML = '';
+});
+
+describe('EconomyFx deliverable plinth', () => {
+ it('mounts a loaded GLB on the plinth and lights it', async () => {
+ const { fx } = makeFx();
+ const p = fx.showDeliverable('https://cdn.test/model.glb');
+ await tick();
+ const { gltf } = fakeGltf('a');
+ loadCalls[0].resolve(gltf);
+ await p;
+
+ expect(fx._plinthModelHolder.children).toHaveLength(1);
+ expect(fx._spotLight.intensity).toBeGreaterThan(0);
+ });
+
+ it('disposes the loser when two deliverables load concurrently', async () => {
+ // Two completions land back-to-back; both loads are already in flight. Only
+ // the newest may mount, and the other must be released, or it stays
+ // parented to the plinth, invisible to every later retire, and leaks.
+ const { fx } = makeFx();
+ const first = fx.showDeliverable('https://cdn.test/first.glb');
+ const second = fx.showDeliverable('https://cdn.test/second.glb');
+ await tick();
+ expect(loadCalls).toHaveLength(2);
+
+ const a = fakeGltf('first');
+ const b = fakeGltf('second');
+ // The second request resolves first, then the stale first arrives late.
+ loadCalls[1].resolve(b.gltf);
+ await second;
+ loadCalls[0].resolve(a.gltf);
+ await first;
+
+ expect(fx._plinthModelHolder.children).toHaveLength(1);
+ expect(fx._plinthModelHolder.children[0].children[0].name).toBe('second');
+ expect(a.spies.geometry).toHaveBeenCalled();
+ expect(a.spies.material).toHaveBeenCalled();
+ expect(a.spies.map).toHaveBeenCalled();
+ expect(b.spies.geometry).not.toHaveBeenCalled();
+ });
+
+ it('disposes the previous deliverable when a new one replaces it', async () => {
+ const { fx } = makeFx();
+ const p1 = fx.showDeliverable('https://cdn.test/one.glb');
+ await tick();
+ const a = fakeGltf('one');
+ loadCalls[0].resolve(a.gltf);
+ await p1;
+
+ const p2 = fx.showDeliverable('https://cdn.test/two.glb');
+ await tick();
+ const b = fakeGltf('two');
+ loadCalls[1].resolve(b.gltf);
+ await p2;
+
+ expect(a.spies.geometry).toHaveBeenCalled();
+ expect(fx._plinthModelHolder.children).toHaveLength(1);
+ expect(b.spies.geometry).not.toHaveBeenCalled();
+ });
+
+ it('drops a load that arrives after dispose instead of resurrecting the plinth', async () => {
+ const { fx } = makeFx();
+ const p = fx.showDeliverable('https://cdn.test/late.glb');
+ await tick();
+ fx.dispose();
+ const late = fakeGltf('late');
+ loadCalls[0].resolve(late.gltf);
+ await p;
+
+ expect(fx._plinthModelHolder.children).toHaveLength(0);
+ expect(late.spies.geometry).toHaveBeenCalled();
+ });
+
+ it('ignores a non-GLB deliverable without touching the plinth', async () => {
+ const { fx } = makeFx();
+ await expect(fx.showDeliverable('https://cdn.test/report.pdf')).resolves.toBe(false);
+ expect(loadCalls).toHaveLength(0);
+ });
+});
+
+describe('EconomyFx completion moment', () => {
+ it('flows coins to the worker and floats the real reward label', () => {
+ const { fx, scene, root } = makeFx();
+ const before = scene.children.length;
+ fx.onCompletion({
+ workerPos: new THREE.Vector3(3, 0, 2),
+ rewardLabel: '25,000 $THREE',
+ narrative: 'Vector Smith completed a Sculptor job; reputation 14 → 19.',
+ });
+
+ expect(scene.children.length).toBeGreaterThan(before); // coins in flight
+ const labels = [...root.querySelectorAll('.agora-econ-float')].map((el) => el.textContent);
+ expect(labels).toContain('+25,000 $THREE');
+ // The rep tick reads the delta out of the engine's real narrative wording.
+ expect(labels.some((t) => t.includes('rep 14 → 19'))).toBe(true);
+ });
+
+ it('never invents a reputation move the narrative does not carry', () => {
+ const { fx, root } = makeFx();
+ fx.onCompletion({
+ workerPos: new THREE.Vector3(1, 0, 1),
+ rewardLabel: '5 $THREE',
+ narrative: 'Vector Smith earned 5 $THREE.',
+ });
+ const labels = [...root.querySelectorAll('.agora-econ-float')].map((el) => el.textContent);
+ expect(labels.some((t) => t.includes('rep'))).toBe(false);
+ });
+
+ it('swaps the coin flight for a calm paid pulse under reduced motion', () => {
+ const { fx, scene, root } = makeFx({ reducedMotion: true });
+ const before = scene.children.length;
+ fx.onCompletion({ workerPos: new THREE.Vector3(2, 0, 2), rewardLabel: '9 $THREE', narrative: '' });
+
+ expect(scene.children.length).toBe(before); // no coin meshes added
+ const labels = [...root.querySelectorAll('.agora-econ-float')].map((el) => el.textContent);
+ expect(labels).toContain('$THREE paid');
+ });
+
+ it('retires coins and labels so a long session does not accumulate them', () => {
+ const { fx, scene, root } = makeFx();
+ const before = scene.children.length;
+ fx.onCompletion({ workerPos: new THREE.Vector3(1, 0, 1), rewardLabel: '1 $THREE', narrative: '' });
+ // Run past the coin flight and the label TTL.
+ for (let i = 0; i < 200; i++) fx.update(1 / 60);
+
+ expect(scene.children.length).toBe(before);
+ expect(root.querySelectorAll('.agora-econ-float')).toHaveLength(0);
+ });
+
+ it('dispose() removes the plinth group and releases its geometry', () => {
+ const { fx, scene } = makeFx();
+ const spy = vi.spyOn(fx._plinthDisposables[0], 'dispose');
+ fx.dispose();
+ expect(spy).toHaveBeenCalled();
+ expect(scene.children).not.toContain(fx._plinthGroup);
+ });
+});