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(walk-sdk): coalesce concurrent avatar GLB loads to stop a three.js internal unhandled rejection

nirholas278e53fff15d
diff --git a/walk-sdk/src/internal/load-avatar.js b/walk-sdk/src/internal/load-avatar.js
index 9774840d8..3c6b9cc11 100644
--- a/walk-sdk/src/internal/load-avatar.js
+++ b/walk-sdk/src/internal/load-avatar.js
@@ -74,6 +74,41 @@ async function makeLoader() {
return _loaderPromise;
}
+// Coalesce concurrent requests for the same key into one underlying load.
+// three.js's FileLoader keeps its own duplicate-request table (`loading[url]`
+// in node_modules/three/src/loaders/FileLoader.js), but that table's cleanup
+// has an edge where a second queued callback can see the entry already
+// deleted and rethrow into a promise chain FileLoader itself never returns or
+// awaits: an unhandled rejection no caller-side try/catch can intercept,
+// because it is not the promise loadAsync() ever handed back to us. Never
+// letting two of our own calls register against the same URL concurrently
+// means FileLoader's table never holds more than one callback for it. Pure
+// and loader-agnostic so it can be exercised directly in tests; exported for
+// that reason (see walk-sdk/test/load-avatar.test.mjs).
+const _inFlight = new Map();
+export function coalesceLoad(key, start) {
+ const existing = _inFlight.get(key);
+ if (existing) return existing.then((value) => ({ value, owner: false }));
+ const promise = start();
+ _inFlight.set(key, promise);
+ // Separate listener from the one below: cleans up the table on either
+ // outcome without affecting what the caller below awaits. Needs its own
+ // .catch(): a bare .finally() with nothing after it is exactly the
+ // floating-promise shape this whole fix exists to avoid.
+ promise.finally(() => {
+ if (_inFlight.get(key) === promise) _inFlight.delete(key);
+ }).catch(() => {});
+ return promise.then((value) => ({ value, owner: true }));
+}
+
+// A joiner must never share the owner's live gltf.scene: it gets attached to
+// its own rig and its own AnimationMixer/AnimationManager, and Object3D.add()
+// reparents (steals) a child already attached elsewhere, which would yank the
+// model out from under whichever caller mounted first.
+function cloneGltfForJoiner(gltf) {
+ return { ...gltf, scene: gltf.scene.clone(true) };
+}
+
/**
* Load a roster entry and build its controller.
* @returns {Promise<{ model: import('three').Object3D, controller: object, gltf: object }>}
@@ -94,7 +129,8 @@ export async function loadWalkAvatar(entry, opts = {}) {
let active = entry;
let gltf;
try {
- gltf = await loader.loadAsync(url);
+ const primary = await coalesceLoad(url, () => loader.loadAsync(url));
+ gltf = primary.owner ? primary.value : cloneGltfForJoiner(primary.value);
} catch (err) {
if (fallbackEntry && fallbackEntry.id !== entry.id) {
log.warn(
@@ -102,7 +138,9 @@ export async function loadWalkAvatar(entry, opts = {}) {
err?.message || err,
);
active = fallbackEntry;
- gltf = await loader.loadAsync(resolveAvatarUrl(fallbackEntry, { assetBase, apiBase }));
+ const fallbackUrl = resolveAvatarUrl(fallbackEntry, { assetBase, apiBase });
+ const fallback = await coalesceLoad(fallbackUrl, () => loader.loadAsync(fallbackUrl));
+ gltf = fallback.owner ? fallback.value : cloneGltfForJoiner(fallback.value);
} else {
throw err;
}
diff --git a/walk-sdk/test/load-avatar.test.mjs b/walk-sdk/test/load-avatar.test.mjs
new file mode 100644
index 000000000..c87bf873a
--- /dev/null
+++ b/walk-sdk/test/load-avatar.test.mjs
@@ -0,0 +1,79 @@
+// @three-ws/walk: concurrent-load coalescing for the same avatar URL.
+// ====================================================================
+// Production telemetry (three.ws order 426) showed a steady stream of
+// unhandled `TypeError: Failed to fetch` rejections whose async stack traces
+// resolve to three.js's own FileLoader.load(): a floating `fetch().then()...`
+// chain that FileLoader never returns or awaits. Its `.catch()` rethrows with
+// nothing after it when `loading[url]` (FileLoader's own module-level
+// duplicate-request table, keyed only by URL) was already cleared by the time
+// the rejection runs: a bookkeeping edge that only exists when more than one
+// caller has registered a callback for the same URL. No try/catch in
+// loadWalkAvatar()/companion.js can intercept that: it rejects a promise
+// walk-sdk never created a handle to.
+//
+// loadWalkAvatar() cannot change FileLoader's internals (vendored
+// dependency), but it can make sure it never hands FileLoader more than one
+// in-flight request for the same URL itself. coalesceLoad() is that guard:
+// a second concurrent request for a URL already loading joins the first
+// caller's promise instead of starting a second `loader.loadAsync()` call.
+// Pure; exercised directly the same way resolveEmotes() is elsewhere in this
+// file, no GLTFLoader/network/WASM needed to prove the coalescing itself.
+
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { coalesceLoad } from '../src/internal/load-avatar.js';
+
+test('coalesceLoad starts the underlying load only once for concurrent requests to the same key', async () => {
+ let starts = 0;
+ const start = () => {
+ starts++;
+ return Promise.resolve({ n: starts });
+ };
+ const [a, b] = await Promise.all([
+ coalesceLoad('same-url', start),
+ coalesceLoad('same-url', start),
+ ]);
+ assert.equal(starts, 1, 'a second concurrent caller must not trigger its own load');
+ assert.equal(a.owner, true, 'the first caller owns the load');
+ assert.equal(b.owner, false, 'the second caller joined instead of starting its own');
+ assert.deepEqual(a.value, { n: 1 });
+ assert.deepEqual(b.value, { n: 1 });
+});
+
+test('coalesceLoad starts a fresh load once the prior one for that key has settled', async () => {
+ let starts = 0;
+ const start = () => {
+ starts++;
+ return Promise.resolve({ n: starts });
+ };
+ await coalesceLoad('same-url-sequential', start);
+ await coalesceLoad('same-url-sequential', start);
+ assert.equal(starts, 2, 'a load that already finished must not be reused for a later, separate request');
+});
+
+test('coalesceLoad propagates a rejection to every waiter instead of swallowing it', async () => {
+ const start = () => Promise.reject(new TypeError('Failed to fetch'));
+ await assert.rejects(
+ Promise.all([coalesceLoad('same-url-reject', start), coalesceLoad('same-url-reject', start)]),
+ /Failed to fetch/,
+ );
+});
+
+test('coalesceLoad tracks each key independently', async () => {
+ let startsA = 0;
+ let startsB = 0;
+ const [a, b] = await Promise.all([
+ coalesceLoad('key-a', () => {
+ startsA++;
+ return Promise.resolve('a');
+ }),
+ coalesceLoad('key-b', () => {
+ startsB++;
+ return Promise.resolve('b');
+ }),
+ ]);
+ assert.equal(startsA, 1);
+ assert.equal(startsB, 1);
+ assert.equal(a.value, 'a');
+ assert.equal(b.value, 'b');
+});