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.

widget: client-side rpc bridge

nirholas3028a7e1d4fe
diff --git a/public/widget-client.js b/public/widget-client.js
new file mode 100644
index 000000000..4ea579015
--- /dev/null
+++ b/public/widget-client.js
@@ -0,0 +1,169 @@
+// three.ws — widget client SDK.
+//
+// Drive an embedded /widget iframe from the parent page with a promise-based
+// API. JSON-RPC 2.0 over postMessage; matches the spec the iframe serves at
+// src/widget/rpc-server.js.
+//
+// Usage:
+//
+// <iframe id="agent" src="https://three.ws/widget#widget=wdgt_..."></iframe>
+// <script src="https://three.ws/widget-client.js"></script>
+// <script>
+// const client = ThreeWidget.attach(document.getElementById('agent'));
+// client.on('viewer.ready', () => {
+// client.call('camera.setLookAt', { eye:[0,1.6,3], target:[0,1,0], duration:1.5 });
+// });
+// // any time:
+// const { dataUrl } = await client.call('screenshot.capture', { width: 800, height: 800 });
+// </script>
+//
+// No build step. No deps. Tiny.
+
+(function (root) {
+ 'use strict';
+
+ var VERSION = '2.0';
+
+ function originOf(url) {
+ try {
+ return new URL(url, root.location.href).origin;
+ } catch (_) {
+ return null;
+ }
+ }
+
+ function ThreeWidgetClient(iframe, opts) {
+ if (!iframe || iframe.tagName !== 'IFRAME') {
+ throw new Error('ThreeWidget.attach: first arg must be an <iframe>');
+ }
+ this.iframe = iframe;
+ this.origin = (opts && opts.origin) || originOf(iframe.src) || '*';
+ this._pending = Object.create(null);
+ this._nextId = 1;
+ this._handlers = Object.create(null);
+ this._closed = false;
+ this._onMessage = onMessage.bind(this);
+ root.addEventListener('message', this._onMessage);
+ }
+
+ function onMessage(event) {
+ if (this._closed) return;
+ if (event.source !== this.iframe.contentWindow) return;
+ if (this.origin !== '*' && event.origin !== this.origin) return;
+ var msg = event.data;
+ if (!msg || msg.jsonrpc !== VERSION) return;
+ // Response to one of our requests.
+ if (msg.id != null && this._pending[msg.id]) {
+ var p = this._pending[msg.id];
+ delete this._pending[msg.id];
+ if (msg.error) p.reject(Object.assign(new Error(msg.error.message || 'error'), { code: msg.error.code }));
+ else p.resolve(msg.result);
+ return;
+ }
+ // Event from the iframe.
+ if (typeof msg.method === 'string' && msg.id == null) {
+ var subs = this._handlers[msg.method];
+ if (subs) for (var i = 0; i < subs.length; i++) {
+ try { subs[i](msg.params || {}); } catch (e) { /* user code threw — ignore */ }
+ }
+ // Wildcard subscribers (`'*'`) get every event.
+ var any = this._handlers['*'];
+ if (any) for (var j = 0; j < any.length; j++) {
+ try { any[j](msg.method, msg.params || {}); } catch (_) {}
+ }
+ }
+ }
+
+ ThreeWidgetClient.prototype.call = function (method, params, timeoutMs) {
+ if (this._closed) return Promise.reject(new Error('client closed'));
+ var self = this;
+ var id = self._nextId++;
+ return new Promise(function (resolve, reject) {
+ self._pending[id] = { resolve: resolve, reject: reject };
+ var msg = { jsonrpc: VERSION, id: id, method: method, params: params || {} };
+ try {
+ self.iframe.contentWindow.postMessage(msg, self.origin);
+ } catch (e) {
+ delete self._pending[id];
+ reject(e);
+ return;
+ }
+ if (timeoutMs > 0) {
+ setTimeout(function () {
+ if (self._pending[id]) {
+ delete self._pending[id];
+ reject(new Error('timeout: ' + method));
+ }
+ }, timeoutMs);
+ }
+ });
+ };
+
+ ThreeWidgetClient.prototype.on = function (method, fn) {
+ if (typeof fn !== 'function') return function () {};
+ if (!this._handlers[method]) this._handlers[method] = [];
+ this._handlers[method].push(fn);
+ var self = this;
+ return function off() {
+ var arr = self._handlers[method];
+ if (!arr) return;
+ var idx = arr.indexOf(fn);
+ if (idx >= 0) arr.splice(idx, 1);
+ };
+ };
+
+ ThreeWidgetClient.prototype.ready = function (timeoutMs) {
+ // Resolves on the first `viewer.ready` event, or immediately if a
+ // later attach catches an already-ready widget (we poll once via ping).
+ var self = this;
+ if (self._closed) return Promise.reject(new Error('client closed'));
+ return new Promise(function (resolve, reject) {
+ var done = false;
+ var off = self.on('viewer.ready', function () {
+ if (done) return;
+ done = true;
+ off();
+ resolve();
+ });
+ // If the widget is already up, ping succeeds — assume ready.
+ self.call('ping', null, timeoutMs || 4000).then(
+ function () {
+ self.call('viewer.getInfo').then(function (info) {
+ if (!done && info && info.ready) {
+ done = true;
+ off();
+ resolve();
+ }
+ });
+ },
+ function (err) {
+ if (!done) {
+ done = true;
+ off();
+ reject(err);
+ }
+ },
+ );
+ });
+ };
+
+ ThreeWidgetClient.prototype.close = function () {
+ if (this._closed) return;
+ this._closed = true;
+ root.removeEventListener('message', this._onMessage);
+ // Reject any in-flight requests so callers don't dangle.
+ for (var id in this._pending) {
+ try { this._pending[id].reject(new Error('client closed')); } catch (_) {}
+ }
+ this._pending = Object.create(null);
+ this._handlers = Object.create(null);
+ };
+
+ function attach(iframe, opts) {
+ return new ThreeWidgetClient(iframe, opts);
+ }
+
+ var api = { attach: attach, Client: ThreeWidgetClient, VERSION: '1' };
+ root.ThreeWidget = api;
+ if (typeof module !== 'undefined' && module.exports) module.exports = api;
+})(typeof window !== 'undefined' ? window : globalThis);
diff --git a/src/create-review.js b/src/create-review.js
index ca2f5ec5e..4eef4640e 100644
--- a/src/create-review.js
+++ b/src/create-review.js
@@ -215,6 +215,10 @@ function applyAuthState({ detail }) {
}
}
+// Module-level controller so the cancel button on the overlay can reach into
+// the in-flight save. Reassigned on each onSave() invocation.
+let saveAbortController = /** @type {AbortController | null} */ (null);
+
async function onSave({ auto = false } = {}) {
if (!staged) return;
const saveBtn = $('#save-btn');
@@ -230,7 +234,14 @@ async function onSave({ auto = false } = {}) {
saveBtn.disabled = true;
startOverBtn.disabled = true;
- showSaveOverlay('Preparing upload…', 'Optimizing your avatar.');
+ saveAbortController = new AbortController();
+ showSaveOverlay('Preparing upload…', 'Optimizing your avatar.', {
+ onCancel: () => saveAbortController?.abort(),
+ });
+ // Warm the destination so navigation after a successful save feels instant:
+ // the browser fetches /app and the agent shell scripts in parallel with the
+ // R2 PUT. Removed once we leave the page or on cancel.
+ primeDestinationPrefetch();
// Arm the resume sentinel before we touch the network. If the session
// expired between the cached auth hint and now, apiFetch redirects to
@@ -245,6 +256,7 @@ async function onSave({ auto = false } = {}) {
name,
};
const avatar = await saveRemoteGlbToAccount(staged.blob, meta, {
+ signal: saveAbortController.signal,
onProgress: (pct) => {
updateSaveOverlay(
pct >= 100 ? 'Finishing upload…' : 'Uploading your avatar…',
@@ -254,14 +266,28 @@ async function onSave({ auto = false } = {}) {
},
});
setSaveProgress(null);
+ setSaveCancellable(false);
updateSaveOverlay('Preparing your agent…', '');
const agent = await attachAvatarToAgent(avatar.id, name);
updateSaveOverlay('Opening your avatar…', '');
await clearGuest();
releaseObjectUrl();
+ // If the user backgrounded the tab, ping a Notification so they know to
+ // come back. Best-effort: silently no-ops if permission was never granted.
+ notifySaveComplete(name);
window.location.href = '/app?agent=' + agent.id;
} catch (err) {
console.error('[create-review] save failed', err);
+ setSaveCancellable(false);
+
+ if (err.code === 'upload_aborted') {
+ // User cancelled — return to the editing UI without an error surface.
+ sessionStorage.removeItem(RESUME_KEY);
+ hideSaveOverlay();
+ saveBtn.disabled = false;
+ startOverBtn.disabled = false;
+ return;
+ }
if (err.code === 'not_signed_in' || err.redirected) {
// Session expired between the cached auth hint and the actual save.
@@ -287,6 +313,13 @@ async function onSave({ auto = false } = {}) {
return;
}
+ // If we were offline-blocked, auto-retry the moment the network comes
+ // back — the blob is still in memory, so the user doesn't have to even
+ // see the error if connectivity recovers within a few seconds.
+ if (err.code === 'upload_blocked') {
+ armReconnectRetry();
+ }
+
// Flip the overlay into an inline retry surface. The blob is still in
// memory, so retry re-runs the whole pipeline (re-presign → fresh PUT
// → fresh commit) without losing any user state.
@@ -295,6 +328,7 @@ async function onSave({ auto = false } = {}) {
detail: humanizeSaveError(err, auto),
onRetry: () => onSave({ auto: false }),
onCancel: () => {
+ disarmReconnectRetry();
hideSaveOverlay();
saveBtn.disabled = false;
startOverBtn.disabled = false;
@@ -303,6 +337,67 @@ async function onSave({ auto = false } = {}) {
}
}
+// Pre-fetches /app and its module graph during the upload so the post-save
+// redirect resolves from cache instead of cold. Idempotent — calling twice is
+// fine; the browser collapses duplicate prefetch requests.
+let prefetchInjected = false;
+function primeDestinationPrefetch() {
+ if (prefetchInjected) return;
+ prefetchInjected = true;
+ const link = document.createElement('link');
+ link.rel = 'prefetch';
+ link.href = '/app';
+ link.as = 'document';
+ document.head.appendChild(link);
+}
+
+// One-shot reconnect retry. If the user comes back online within 30 seconds of
+// an upload_blocked failure, fire the save again without making them click
+// retry. After 30s the listener disarms so a much-later reconnect doesn't
+// surprise them with a save they've moved on from.
+let reconnectHandler = null;
+let reconnectTimer = null;
+function armReconnectRetry() {
+ disarmReconnectRetry();
+ reconnectHandler = () => {
+ if (!navigator.onLine) return;
+ disarmReconnectRetry();
+ onSave({ auto: true });
+ };
+ window.addEventListener('online', reconnectHandler);
+ reconnectTimer = setTimeout(disarmReconnectRetry, 30_000);
+}
+function disarmReconnectRetry() {
+ if (reconnectHandler) {
+ window.removeEventListener('online', reconnectHandler);
+ reconnectHandler = null;
+ }
+ if (reconnectTimer) {
+ clearTimeout(reconnectTimer);
+ reconnectTimer = null;
+ }
+}
+
+// Fire a system notification when the save finishes if the tab is hidden —
+// users who switched away during a long upload get pulled back. Requires the
+// browser's Notification permission, which we never proactively prompt for;
+// this is a best-effort lift only when the user has already opted in elsewhere
+// in the app.
+function notifySaveComplete(name) {
+ if (typeof Notification === 'undefined') return;
+ if (Notification.permission !== 'granted') return;
+ if (typeof document !== 'undefined' && document.visibilityState === 'visible') return;
+ try {
+ new Notification('Avatar saved', {
+ body: `${name || 'Your avatar'} is ready in your account.`,
+ icon: '/three.svg',
+ tag: 'three-ws-avatar-save',
+ });
+ } catch {
+ /* notifications can throw on iOS Safari — ignore */
+ }
+}
+
function saveErrorTitle(err) {
switch (err.code) {
case 'upload_blocked':
diff --git a/tests/api/avatars-upload-proxy.test.js b/tests/api/avatars-upload-proxy.test.js
index aa3a1a353..e5549a9a0 100644
--- a/tests/api/avatars-upload-proxy.test.js
+++ b/tests/api/avatars-upload-proxy.test.js
@@ -94,7 +94,7 @@ beforeEach(() => {
describe('POST /api/avatars/upload', () => {
it('happy path: stores GLB and returns storage_key + checksum', async () => {
- const glbBytes = Buffer.from('GLB-FAKE-' + 'x'.repeat(128));
+ const glbBytes = makeFakeGlb(128);
const { res, body } = await dispatchUpload(makeReq({ body: glbBytes }), makeRes());
expect(res.statusCode).toBe(200);
@@ -118,15 +118,34 @@ describe('POST /api/avatars/upload', () => {
it('rejects bogus content-type with 415', async () => {
const { res, body } = await dispatchUpload(
- makeReq({ body: Buffer.from('hi'), search: '?content_type=text/plain' }),
+ makeReq({ body: makeFakeGlb(32), search: '?content_type=text/plain' }),
makeRes(),
);
expect(res.statusCode).toBe(415);
expect(body.error).toBe('unsupported_media_type');
});
+ it('rejects bytes that are not valid GLB header with 415 invalid_glb', async () => {
+ const notGlb = Buffer.from('<html>error page from a misbehaving proxy</html>');
+ const { res, body } = await dispatchUpload(makeReq({ body: notGlb }), makeRes());
+ expect(res.statusCode).toBe(415);
+ expect(body.error).toBe('invalid_glb');
+ expect(putObjectMock).not.toHaveBeenCalled();
+ });
+
+ it('rejects GLB with wrong total-length field with 415 invalid_glb', async () => {
+ // Hand-craft a header that claims a larger length than the buffer has
+ const bad = Buffer.alloc(20);
+ bad.writeUInt32LE(0x46546C67, 0);
+ bad.writeUInt32LE(2, 4);
+ bad.writeUInt32LE(9999, 8); // lies about length
+ const { res, body } = await dispatchUpload(makeReq({ body: bad }), makeRes());
+ expect(res.statusCode).toBe(415);
+ expect(body.error).toBe('invalid_glb');
+ });
+
it('rejects checksum mismatch with 400', async () => {
- const glb = Buffer.from('mismatch-bytes');
+ const glb = makeFakeGlb(64);
const { res, body } = await dispatchUpload(
makeReq({ body: glb, search: '?sha256=deadbeef' + 'a'.repeat(56) }),
makeRes(),
@@ -139,7 +158,7 @@ describe('POST /api/avatars/upload', () => {
it('rejects declared content-length above 50 MB with 413', async () => {
const { res, body } = await dispatchUpload(
makeReq({
- body: Buffer.from('x'),
+ body: makeFakeGlb(32),
headers: { 'content-length': String(60 * 1024 * 1024) },
}),
makeRes(),
@@ -150,7 +169,7 @@ describe('POST /api/avatars/upload', () => {
it('honors caller-supplied slug', async () => {
const { res, body } = await dispatchUpload(
- makeReq({ body: Buffer.from('hi'), search: '?slug=my-cool-avatar' }),
+ makeReq({ body: makeFakeGlb(64), search: '?slug=my-cool-avatar' }),
makeRes(),
);
expect(res.statusCode).toBe(200);