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.

feat: add Avatar Composer module with GLB composition and part selection

nirholas223dd9c0a571
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f5bf59122..2e3bc00c6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -24,6 +24,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **The agent-to-agent payment economy runs far cheaper and now cycles hundreds of distinct payers** — Two improvements to the closed-loop x402 agent economy that dogfoods every paid endpoint on the platform. First, a fix: a background wallet-consolidation job was quietly closing the ring's payment account after every settlement, forcing the next one to recreate it and pay account rent each time. That single bug had pushed the real fee cost to roughly a hundred times where it should be. With it fixed and single-signature settlement turned on, each settlement is back to the network floor of a few thousandths of a cent, and the ring's working balance stays in the loop instead of leaking away. Second, a new capability: the ring can now cycle payments through a reusable pool of hundreds to a thousand distinct wallets instead of one, so the economy reads as many participants rather than a single account, with no extra cost per payment. The pool is off until funded and activated, and every wallet in it stays clearly labeled internal dogfooding, not organic demand. (`/admin/ring`) `[fix, improvement, infra]`
- **The Money Pulse is beating again** — The live money feed went quiet after the July 7 infrastructure move: the switch that powers the autonomous agent activity loop did not survive the migration, so agents stopped tipping, trading, paying and launching. The switch is back on and the feed is live again, with real on-chain tips, trades, payments and coin launches flowing within minutes of the fix. The production runbook now documents the switch so a future migration cannot silently drop it. (`/pulse`) `[fix, infra]`
- **The viewer's Create buttons now take you straight to the Forge** — On the shared-model viewer page, the "Create a 3D model" button (shown when a link is missing its model) and the "Make your own" button in the footer used to drop you on the homepage, leaving you to hunt for the generator. Both now go directly to the free text-to-3D Forge so you can start creating in one click. (`/viewer`) `[fix]`
+- **three.ws now speaks 11 languages** — The site's language switcher gained nine new languages on top of English and Spanish: Simplified Chinese, Japanese, Korean, French, German, Brazilian Portuguese, Arabic, Hindi, and Russian. Pick your language from the switcher and the copy re-renders instantly, with your choice remembered for next time; if your browser is already set to one of these, three.ws now greets you in it automatically. Arabic lays out right-to-left. Brand and protocol terms like $THREE, USDC, and three.ws stay exact in every language. `[feature]`
- **Your models now look studio-quality everywhere, not just in the Forge** — The viewer page that opens when someone follows a shared model link now renders with the same rich lighting, tone mapping, and exposure as the Forge studio where the model was created, so what you share is what they see. The copy-paste embed snippet ships those same settings, meaning models dropped onto your own site no longer look flat compared to the preview. Avatars in agent embed cards now cast a soft ground shadow instead of floating, and the homepage 3D showcase stops burning your battery when it is scrolled out of view or in a background tab. (`/viewer`) `[improvement]`
## 2026-07-16
diff --git a/api/_lib/avatar-composer/compose.js b/api/_lib/avatar-composer/compose.js
new file mode 100644
index 000000000..bf8ca412d
--- /dev/null
+++ b/api/_lib/avatar-composer/compose.js
@@ -0,0 +1,233 @@
+// @ts-check
+// Avatar Composer — core composition engine.
+//
+// Assembles a single rigged GLB by mixing skinned parts across the RPM base
+// bodies (see parts.js) onto one shared skeleton, then recolors each part and
+// scales the whole avatar. Buffer-in / buffer-out and deterministic — no I/O, no
+// GPU, no external service.
+//
+// The one rule that makes this correct (confirmed against gltf-transform's
+// source and RPM/Avaturn's architecture): body parts are NEVER fused into a
+// single mesh. `join()` refuses skinned/morph meshes for good reason — each part
+// stays its own skinned primitive, and they all reference ONE shared Skin. All
+// four bases share a byte-identical joint list, so re-pointing a borrowed part
+// to the identity base's skin transfers its skin weights without distortion.
+//
+// Pipeline per compose():
+// 1. Start from the identity base (its head+body+eyes+teeth+beard + skeleton).
+// 2. For each swappable slot, either keep the identity's part, drop it, or
+// merge a donor base's part and re-point it to the shared skin.
+// 3. Collapse every skinned mesh onto one shared Skin; prune orphans.
+// 4. Recolor each part's material by its colorway channel.
+// 5. Scale the rig uniformly for height variety.
+// 6. dedup → prune → meshopt-compress → single buffer → write.
+
+import { NodeIO, Document } from '@gltf-transform/core';
+import { ALL_EXTENSIONS } from '@gltf-transform/extensions';
+import { mergeDocuments, prune, dedup, meshopt } from '@gltf-transform/functions';
+import { MeshoptDecoder, MeshoptEncoder } from 'meshoptimizer';
+import draco3d from 'draco3dgltf';
+import { MATERIAL_SLOT, SWAPPABLE_SLOTS, SLOT_CHANNEL } from './parts.js';
+
+let _ioPromise = null;
+// One NodeIO per process, with every decoder/encoder the bases need
+// (EXT_meshopt_compression, KHR_mesh_quantization, EXT_texture_webp, Draco).
+// Lazy so importing this module never blocks on WASM init.
+async function getIO() {
+ if (_ioPromise) return _ioPromise;
+ _ioPromise = (async () => {
+ const [dDec, dEnc] = await Promise.all([
+ draco3d.createDecoderModule(),
+ draco3d.createEncoderModule(),
+ ]);
+ await MeshoptDecoder.ready;
+ await MeshoptEncoder.ready;
+ return new NodeIO().registerExtensions(ALL_EXTENSIONS).registerDependencies({
+ 'meshopt.decoder': MeshoptDecoder,
+ 'meshopt.encoder': MeshoptEncoder,
+ 'draco3d.decoder': dDec,
+ 'draco3d.encoder': dEnc,
+ });
+ })();
+ return _ioPromise;
+}
+
+function meshSlot(mesh) {
+ const mat = mesh.listPrimitives()[0]?.getMaterial()?.getName();
+ return mat ? MATERIAL_SLOT[mat] || null : null;
+}
+
+function nodeForMesh(doc, mesh) {
+ return doc.getRoot().listNodes().find((n) => n.getMesh() === mesh) || null;
+}
+
+// The skin borrowed parts bind to. It must be the identity BODY mesh's skin, not
+// the head's: RPM stores inverse-bind matrices per skin, and the head skin's
+// binds are only trustworthy for the head/arm joints it actually deforms — bind
+// a shoe to it and the foot joints resolve wrong (the shoe flies to the
+// shoulders). The body mesh spans the whole skeleton, so its inverse binds are
+// correct for every region. Falls back to head, then the first skin.
+function canonicalSkin(doc) {
+ const root = doc.getRoot();
+ const bySlot = (slot) => {
+ for (const mesh of root.listMeshes()) {
+ if (meshSlot(mesh) === slot) {
+ const node = nodeForMesh(doc, mesh);
+ if (node?.getSkin()) return node.getSkin();
+ }
+ }
+ return null;
+ };
+ return bySlot('body') || bySlot('head') || root.listSkins()[0] || null;
+}
+
+function removeSlotMeshes(doc, slot) {
+ for (const mesh of doc.getRoot().listMeshes()) {
+ if (meshSlot(mesh) !== slot) continue;
+ const node = nodeForMesh(doc, mesh);
+ node?.dispose();
+ mesh.dispose();
+ }
+}
+
+/**
+ * @typedef {Object} ComposeRecipe
+ * @property {string} identity base id providing head/body/eyes/teeth/beard
+ * @property {Record<string,string|null>} slots swappable slot → donor base id (or null to omit)
+ * @property {{skin?:number[],hair?:number[],top?:number[],bottom?:number[],footwear?:number[]}} [colorway]
+ * per-channel baseColorFactor multipliers in [0,1]
+ * @property {number} [scale=1] uniform height multiplier applied to the rig
+ */
+
+/**
+ * Compose one avatar GLB from base-body bytes.
+ *
+ * @param {ComposeRecipe} recipe
+ * @param {Record<string, Uint8Array>} bytesByBase base id → GLB bytes for every
+ * base referenced by `identity` and `slots` (donors and identity).
+ * @returns {Promise<{ bytes: Uint8Array, meshes: string[], recolored: string[] }>}
+ */
+export async function composeAvatar(recipe, bytesByBase) {
+ const io = await getIO();
+ const identityId = recipe.identity;
+ const identityBytes = bytesByBase[identityId];
+ if (!identityBytes) throw new Error(`composeAvatar: missing bytes for identity base "${identityId}"`);
+
+ const target = await io.readBinary(identityBytes);
+ const tScene = target.getRoot().getDefaultScene() || target.getRoot().listScenes()[0];
+
+ // The identity skeleton: its joint NODES (canonical order) and skeleton root,
+ // taken from the body mesh's skin (the one skin that spans every joint). Every
+ // borrowed part gets remapped onto exactly these nodes so the whole avatar is
+ // driven by ONE skeleton and animates as a unit.
+ const bodySkin = canonicalSkin(target);
+ if (!bodySkin) throw new Error('composeAvatar: identity base has no body skin');
+ const identityJoints = bodySkin.listJoints();
+ const identitySkeleton = bodySkin.getSkeleton();
+ // The armature node identity meshes hang under — borrowed nodes join it so
+ // their world matrix (three.js uses it as the skinning bind matrix) matches.
+ const bodyNode = target.getRoot().listNodes().find((n) => n.getMesh() && meshSlot(n.getMesh()) === 'body');
+ const armature = bodyNode?.getParentNode() || tScene.listChildren()[0] || tScene;
+
+ // Drop the identity's own mesh for any slot we are swapping out or omitting.
+ for (const slot of SWAPPABLE_SLOTS) {
+ const src = recipe.slots?.[slot];
+ if (src !== identityId) removeSlotMeshes(target, slot);
+ }
+
+ const donorIds = new Set();
+ for (const slot of SWAPPABLE_SLOTS) {
+ const src = recipe.slots?.[slot];
+ if (src && src !== identityId) donorIds.add(src);
+ }
+ /** @type {Map<string, {doc: Document, map: Map<any,any>}>} */
+ const donors = new Map();
+ const donorScenes = [];
+ for (const id of donorIds) {
+ const bytes = bytesByBase[id];
+ if (!bytes) throw new Error(`composeAvatar: missing bytes for donor base "${id}"`);
+ const donorDoc = await io.readBinary(bytes);
+ const before = new Set(target.getRoot().listScenes());
+ const map = mergeDocuments(target, donorDoc);
+ for (const s of target.getRoot().listScenes()) if (!before.has(s)) donorScenes.push(s);
+ donors.set(id, { doc: donorDoc, map });
+ }
+
+ // Graft each borrowed part: keep its OWN skin (its inverse-bind matrices are
+ // the only ones correct for that part's region — re-pointing to another skin
+ // throws the part across the body), but remap that skin's joints onto the
+ // identity skeleton's nodes. Joint order is byte-identical across bases, so
+ // slot i maps to slot i; the part now deforms with the identity skeleton while
+ // keeping its own correct binds.
+ const remapped = new Set();
+ for (const slot of SWAPPABLE_SLOTS) {
+ const src = recipe.slots?.[slot];
+ if (src == null || src === identityId) continue;
+ const donor = donors.get(src);
+ if (!donor) continue;
+ for (const donorMesh of donor.doc.getRoot().listMeshes()) {
+ if (meshSlot(donorMesh) !== slot) continue;
+ const donorNode = nodeForMesh(donor.doc, donorMesh);
+ const mergedNode = donor.map.get(donorNode);
+ if (!mergedNode) continue;
+ armature.addChild(mergedNode); // same parent as identity meshes → matching bind matrix
+ mergedNode.setName(`${slot}:${src}`);
+ const partSkin = mergedNode.getSkin();
+ if (partSkin && !remapped.has(partSkin)) {
+ const donorJoints = partSkin.listJoints();
+ if (donorJoints.length === identityJoints.length) {
+ for (const j of donorJoints) partSkin.removeJoint(j);
+ for (const j of identityJoints) partSkin.addJoint(j);
+ if (identitySkeleton) partSkin.setSkeleton(identitySkeleton);
+ }
+ remapped.add(partSkin);
+ }
+ }
+ }
+
+ // Donor scenes now hold only the parts we did NOT take; dispose them so prune()
+ // reclaims the donor skeletons (now unreferenced) and unused meshes.
+ for (const s of donorScenes) s.dispose();
+ target.getRoot().setDefaultScene(tScene);
+
+ await target.transform(prune());
+
+ // Recolor each surviving part by its channel.
+ const recolored = [];
+ const cw = recipe.colorway || {};
+ for (const mat of target.getRoot().listMaterials()) {
+ const slot = MATERIAL_SLOT[mat.getName()];
+ const channel = slot && SLOT_CHANNEL[slot];
+ const color = channel && cw[channel];
+ if (!color) continue;
+ const [r, g, b] = color;
+ const a = mat.getBaseColorFactor()?.[3] ?? 1;
+ mat.setBaseColorFactor([r, g, b, a]);
+ recolored.push(mat.getName());
+ }
+
+ // Uniform height scale on the rig roots (mirrors the legacy studio lane).
+ const s = Number(recipe.scale) || 1;
+ if (Math.abs(s - 1) > 1e-4) {
+ for (const node of tScene.listChildren()) {
+ const cur = node.getScale();
+ node.setScale([cur[0] * s, cur[1] * s, cur[2] * s]);
+ }
+ }
+
+ // Optimize + guarantee a single buffer for GLB output.
+ await target.transform(dedup(), prune(), meshopt({ encoder: MeshoptEncoder }));
+ const buffers = target.getRoot().listBuffers();
+ if (buffers.length > 1) {
+ const buf0 = buffers[0];
+ for (const acc of target.getRoot().listAccessors()) acc.setBuffer(buf0);
+ for (const b of buffers.slice(1)) b.dispose();
+ }
+
+ const bytes = await io.writeBinary(target);
+ return {
+ bytes,
+ meshes: target.getRoot().listMeshes().map((m) => m.getName() || meshSlot(m) || '?'),
+ recolored,
+ };
+}
diff --git a/api/_lib/avatar-composer/index.js b/api/_lib/avatar-composer/index.js
new file mode 100644
index 000000000..995e83e66
--- /dev/null
+++ b/api/_lib/avatar-composer/index.js
@@ -0,0 +1,62 @@
+// @ts-check
+// Avatar Composer — public entry point.
+//
+// One call turns a diversity profile + seed into a rigged, expression-ready GLB
+// assembled from modular parts (see README.md). The caller supplies a `loadBase`
+// function so this module stays I/O-free and runs the same in a test (read from
+// disk), the seed cron (fetch from the site origin), or a worker.
+
+import { composeAvatar } from './compose.js';
+import { selectRecipe, basesNeeded } from './select.js';
+import { BASES } from './parts.js';
+
+export { composeAvatar } from './compose.js';
+export { selectRecipe, basesNeeded } from './select.js';
+export { BASES, BASE_BY_ID } from './parts.js';
+
+/**
+ * Compose one studio avatar end-to-end.
+ *
+ * @param {Object} opts
+ * @param {{ gender?: 'male'|'female', ethnicityKey?: string, ageKey?: string, grayBias?: number, build?: string }} opts.profile
+ * @param {string} opts.seed
+ * @param {(baseId: string) => Promise<Uint8Array>} opts.loadBase loads a base GLB's bytes by id
+ * @returns {Promise<{ bytes: Uint8Array, recipe: object, descriptor: object, meshes: string[], recolored: string[] }>}
+ */
+export async function composeStudioAvatar({ profile, seed, loadBase }) {
+ const recipe = selectRecipe(profile, seed);
+ const ids = basesNeeded(recipe);
+ /** @type {Record<string, Uint8Array>} */
+ const bytesByBase = {};
+ await Promise.all(
+ ids.map(async (id) => {
+ bytesByBase[id] = await loadBase(id);
+ }),
+ );
+ const { bytes, meshes, recolored } = await composeAvatar(recipe, bytesByBase);
+ const { descriptor, ...recipeCore } = recipe;
+ return { bytes, recipe: recipeCore, descriptor, meshes, recolored };
+}
+
+/**
+ * Rough count of distinct part-mesh combinations the catalog can produce, before
+ * colorway/scale. Each identity draws swappable parts only from its own rest-pose
+ * group, so the count sums over identities. Illustrative (docs/tests), not a hard
+ * guarantee — the colorway (per-part tints across ~10 skin tones, 10 hair tints,
+ * 10 outfit tints each) multiplies this into the tens of thousands.
+ * @returns {number}
+ */
+export function combinationCount() {
+ let total = 0;
+ for (const id of BASES) {
+ let n = 1;
+ for (const slot of ['hair', 'top', 'bottom', 'footwear']) {
+ const providers = BASES.filter((b) => b.provides.includes(slot) && b.restGroup === id.restGroup);
+ n *= Math.max(1, providers.length);
+ }
+ const glasses = BASES.filter((b) => b.provides.includes('glasses') && b.restGroup === id.restGroup);
+ n *= glasses.length + 1; // +none
+ total += n;
+ }
+ return total;
+}
diff --git a/api/_lib/avatar-composer/parts.js b/api/_lib/avatar-composer/parts.js
new file mode 100644
index 000000000..c11cfa282
--- /dev/null
+++ b/api/_lib/avatar-composer/parts.js
@@ -0,0 +1,111 @@
+// @ts-check
+// Avatar Composer — parts catalog.
+//
+// The four Ready-Player-Me / Wolf3D base bodies shipped in public/avatars
+// (realistic-male, realistic-female, default, selfie-girl) are not just five
+// fixed avatars — they are a MODULAR PARTS KIT. Every one is rigged to a
+// byte-identical 67-joint skeleton with identical joint ordering (verified), and
+// every body part (hair, top, bottom, footwear, glasses) is a SEPARATE skinned
+// mesh identified by its material name. Because the skeletons match, a hair mesh
+// from one base and a top from another deform correctly on a third base's body.
+//
+// That is exactly how Ready Player Me and Avaturn build variety: one shared
+// skeleton, swappable skinned parts. This catalog declares which base provides
+// which slot, so the composer (compose.js) can mix them into avatars that are
+// genuinely different meshes, not the recolor-one-of-five-bodies the studio lane
+// shipped before.
+//
+// Slots split into two groups:
+// identity — head, body, eyes, teeth, beard. These come as a set from ONE
+// base (the "identity base"); they carry the face + its 60+ ARKit
+// blendshapes, so the composed avatar is expression-ready.
+// swappable — hair, top, bottom, footwear, glasses. Each is sourced
+// independently from any base that provides it (or omitted).
+
+/** Material name → composer slot. A mesh's slot is the material it uses. */
+export const MATERIAL_SLOT = {
+ Wolf3D_Hair: 'hair',
+ Wolf3D_Outfit_Top: 'top',
+ Wolf3D_Outfit_Bottom: 'bottom',
+ Wolf3D_Outfit_Footwear: 'footwear',
+ Wolf3D_Glasses: 'glasses',
+ Wolf3D_Head: 'head',
+ Wolf3D_Skin: 'head',
+ Wolf3D_Body: 'body',
+ Wolf3D_Eye: 'eyes',
+ Wolf3D_Teeth: 'teeth',
+ Wolf3D_Beard: 'beard',
+};
+
+/** Slots that always travel together from the identity base (face + skin). */
+export const IDENTITY_SLOTS = ['head', 'body', 'eyes', 'teeth', 'beard'];
+
+/** Slots the composer mixes independently across bases. */
+export const SWAPPABLE_SLOTS = ['hair', 'top', 'bottom', 'footwear', 'glasses'];
+
+/**
+ * Slot → colorway channel. The composer multiplies each material's
+ * baseColorFactor by the channel color, exactly like the legacy recolorGlb but
+ * per composed part. Head skin and body skin share one channel so the avatar is
+ * one consistent complexion head-to-toe.
+ */
+export const SLOT_CHANNEL = {
+ head: 'skin',
+ body: 'skin',
+ hair: 'hair',
+ top: 'top',
+ bottom: 'bottom',
+ footwear: 'footwear',
+};
+
+/**
+ * @typedef {Object} BaseBody
+ * @property {string} id catalog id (also the public/avatars/<id>.glb filename)
+ * @property {string} file GLB filename under public/avatars
+ * @property {'male'|'female'} gender body/face gender of the identity slots
+ * @property {string} label human label
+ * @property {string} restGroup rest-pose compatibility group (see note below)
+ * @property {string[]} provides swappable slots this base can donate
+ */
+
+/**
+ * The base bodies, with the swappable slots each can donate. Inventory verified
+ * by reading each GLB's meshes (by material). `michelle` is intentionally
+ * excluded: it is a single-mesh Mixamo body on a different 65-joint skeleton, so
+ * its parts are not skeleton-compatible with the RPM family.
+ *
+ * restGroup: a part authored for one body sits at that body's proportions. When
+ * grafted onto a body with a DIFFERENT rest pose (skeleton bind proportions) the
+ * part keeps its own vertices, so it can float or misfit (measured: feet detach
+ * across groups). Bodies are grouped by rest pose (Hips bind height + limb rest
+ * translations) so the composer only ever mixes parts WITHIN a group, where the
+ * fit is exact. Measured Hips bind heights: realistic-male 0.967, realistic-female
+ * 1.009 (group "a"); default and selfie-girl 1.037 (group "b"). Cross-group mixing
+ * needs true vertex rebinding — the planned v2.
+ *
+ * @type {BaseBody[]}
+ */
+export const BASES = [
+ { id: 'realistic-male', file: 'realistic-male.glb', gender: 'male', label: 'Realistic male', restGroup: 'a', provides: ['hair', 'top', 'bottom', 'footwear', 'glasses'] },
+ { id: 'realistic-female', file: 'realistic-female.glb', gender: 'female', label: 'Realistic female', restGroup: 'a', provides: ['hair', 'top', 'bottom', 'footwear'] },
+ { id: 'default', file: 'default.glb', gender: 'male', label: 'Default', restGroup: 'b', provides: ['hair', 'top', 'bottom', 'footwear', 'glasses'] },
+ { id: 'selfie-girl', file: 'selfie-girl.glb', gender: 'female', label: 'Selfie girl', restGroup: 'b', provides: ['hair', 'top', 'bottom', 'footwear', 'glasses'] },
+];
+
+export const BASE_BY_ID = Object.fromEntries(BASES.map((b) => [b.id, b]));
+
+/** Bases that can serve as an identity (all of them). */
+export function basesForGender(gender) {
+ return BASES.filter((b) => b.gender === gender);
+}
+
+/**
+ * Bases that can donate a given slot to `identity` with an exact fit: the
+ * identity itself plus any base in the same rest-pose group. Restricting to the
+ * group is what keeps grafted parts from floating (see restGroup note above).
+ * @param {string} slot
+ * @param {BaseBody} identity
+ */
+export function compatibleProviders(slot, identity) {
+ return BASES.filter((b) => b.provides.includes(slot) && b.restGroup === identity.restGroup);
+}
diff --git a/api/_lib/avatar-composer/select.js b/api/_lib/avatar-composer/select.js
new file mode 100644
index 000000000..e302a640f
--- /dev/null
+++ b/api/_lib/avatar-composer/select.js
@@ -0,0 +1,102 @@
+// @ts-check
+// Avatar Composer — seeded recipe selection.
+//
+// Turns a diversity profile + seed into a concrete compose recipe: which base is
+// the identity, which base donates each swappable part, whether to wear glasses,
+// the colorway, and the height scale. Fully deterministic on the seed, so the
+// same seed always yields the same avatar (reproducible gallery, safe re-render).
+//
+// The palette (skin/hair/outfit tints, height scale) is reused verbatim from the
+// legacy studio lane (studio-avatar.js) so there is one source of truth for
+// color; the NEW capability here is choosing DIFFERENT part meshes per slot,
+// which the legacy lane could not do.
+
+import { pickColorway, pickScale } from '../studio-avatar.js';
+import { basesForGender, compatibleProviders, SWAPPABLE_SLOTS } from './parts.js';
+
+function hashSeed(str) {
+ let h = 2166136261 >>> 0;
+ for (let i = 0; i < str.length; i++) {
+ h ^= str.charCodeAt(i);
+ h = Math.imul(h, 16777619);
+ }
+ return h >>> 0;
+}
+function mulberry32(seed) {
+ let a = seed >>> 0;
+ return function () {
+ a |= 0;
+ a = (a + 0x6d2b79f5) | 0;
+ let t = Math.imul(a ^ (a >>> 15), 1 | a);
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+}
+const pickFrom = (arr, rng) => arr[Math.floor(rng() * arr.length)];
+
+// Probability an avatar wears glasses. Kept a minority so the gallery isn't all
+// bespectacled, but common enough to be a real variety axis.
+const GLASSES_CHANCE = 0.28;
+
+/**
+ * Build a compose recipe from a diversity profile + seed.
+ *
+ * Part meshes are drawn from any base in the identity's rest-pose group (the
+ * identity plus its compatible partner), regardless of the donor's gender — a
+ * jacket or hairstyle reads on either body, and the cross-sourcing plus per-part
+ * recolor and scale is what produces the variety (vs. the five fixed bodies the
+ * recolor lane had). The identity base (face + body + skin) matches the profile's
+ * gender; grafted parts always fit because they share the identity's rest pose.
+ *
+ * @param {{ gender?: 'male'|'female', ethnicityKey?: string, ageKey?: string, grayBias?: number, build?: string }} profile
+ * @param {string} seed
+ * @returns {import('./compose.js').ComposeRecipe & { descriptor: object }}
+ */
+export function selectRecipe(profile, seed) {
+ const gender = profile?.gender === 'male' ? 'male' : 'female';
+ const identity = pickFrom(basesForGender(gender), mulberry32(hashSeed(seed + ':identity')));
+
+ /** @type {Record<string,string|null>} */
+ const slots = {};
+ for (const slot of SWAPPABLE_SLOTS) {
+ const providers = compatibleProviders(slot, identity);
+ if (slot === 'glasses') {
+ const rng = mulberry32(hashSeed(seed + ':glasses'));
+ slots.glasses = rng() < GLASSES_CHANCE && providers.length ? pickFrom(providers, rng).id : null;
+ continue;
+ }
+ if (!providers.length) { slots[slot] = null; continue; }
+ slots[slot] = pickFrom(providers, mulberry32(hashSeed(seed + ':' + slot))).id;
+ }
+
+ const colorway = pickColorway(profile, seed);
+ const scale = pickScale(profile, seed);
+
+ return {
+ identity: identity.id,
+ slots,
+ colorway,
+ scale,
+ descriptor: {
+ identity: identity.id,
+ gender,
+ parts: { ...slots },
+ glasses: !!slots.glasses,
+ scale,
+ },
+ };
+}
+
+/**
+ * The set of base ids a recipe needs bytes for (identity + every distinct donor).
+ * @param {import('./compose.js').ComposeRecipe} recipe
+ * @returns {string[]}
+ */
+export function basesNeeded(recipe) {
+ const ids = new Set([recipe.identity]);
+ for (const slot of SWAPPABLE_SLOTS) {
+ const src = recipe.slots?.[slot];
+ if (src) ids.add(src);
+ }
+ return [...ids];
+}
diff --git a/data/changelog.json b/data/changelog.json
index 522308f91..70a8969a0 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,14 @@
{
"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-07-17",
+ "title": "three.ws now speaks 11 languages",
+ "summary": "The site's language switcher gained nine new languages on top of English and Spanish: Simplified Chinese, Japanese, Korean, French, German, Brazilian Portuguese, Arabic, Hindi, and Russian. Pick your language from the switcher and the copy re-renders instantly, with your choice remembered for next time; if your browser is already set to one of these, three.ws now greets you in it automatically. Arabic lays out right-to-left. Brand and protocol terms like $THREE, USDC, and three.ws stay exact in every language.",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-07-17",
"title": "IRL is calmer to use: one clear next step, name tags that stay readable",
diff --git a/public/changelog.json b/public/changelog.json
index 2e4270397..ebae353a6 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-17T10:13:40.857Z",
+ "generated_at": "2026-07-17T10:23:33.686Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -197,6 +197,16 @@
"fix"
]
},
+ {
+ "date": "2026-07-17",
+ "type": "update",
+ "title": "three.ws now speaks 11 languages",
+ "summary": "The site's language switcher gained nine new languages on top of English and Spanish: Simplified Chinese, Japanese, Korean, French, German, Brazilian Portuguese, Arabic, Hindi, and Russian. Pick your language from the switcher and the copy re-renders instantly, with your choice remembered for next time; if your browser is already set to one of these, three.ws now greets you in it automatically. Arabic lays out right-to-left. Brand and protocol terms like $THREE, USDC, and three.ws stay exact in every language.",
+ "link": null,
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-07-17",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 3e7368354..88ec95b3f 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -150,6 +150,14 @@
<category>fix</category>
<description>On the shared-model viewer page, the &quot;Create a 3D model&quot; button (shown when a link is missing its model) and the &quot;Make your own&quot; button in the footer used to drop you on the homepage, leaving you to hunt for the generator. Both now go directly to the free text-to-3D Forge so you can start creating in one click.</description>
</item>
+ <item>
+ <title>three.ws now speaks 11 languages</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-07-17:three.ws now speaks 11 languages</guid>
+ <pubDate>Fri, 17 Jul 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>The site's language switcher gained nine new languages on top of English and Spanish: Simplified Chinese, Japanese, Korean, French, German, Brazilian Portuguese, Arabic, Hindi, and Russian. Pick your language from the switcher and the copy re-renders instantly, with your choice remembered for next time; if your browser is already set to one of these, three.ws now greets you in it automatically. Arabic lays out right-to-left. Brand and protocol terms like $THREE, USDC, and three.ws stay exact in every language.</description>
+ </item>
<item>
<title>Your models now look studio-quality everywhere, not just in the Forge</title>
<link>https://three.ws/viewer</link>
diff --git a/public/features.json b/public/features.json
index 3e8ff0fd9..46236f101 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-17T10:13:40.844Z",
+ "generated_at": "2026-07-17T10:23:33.670Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/public/locales/ar.json b/public/locales/ar.json
new file mode 100644
index 000000000..8268f8672
--- /dev/null
+++ b/public/locales/ar.json
@@ -0,0 +1,19 @@
+{
+ "common": {
+ "language": "اللغة",
+ "take_tour": "خذ جولة"
+ },
+ "home": {
+ "bullet_create": "<strong>أنشئ</strong> وكيل ذكاء اصطناعي ثلاثي الأبعاد من موجه نصي أو صورة سيلفي في حوالي دقيقة",
+ "bullet_earn": "<strong>اكسب</strong> USDC لكل محادثة باستخدام المدفوعات المصغرة x402",
+ "bullet_embed": "<strong>ادمجها</strong> في أي موقع ويب بسطرين من HTML",
+ "cta_build": "أنشئ وكيلك <span class=\"arrow\">→</span>",
+ "cta_embed": "شاهد التضمين",
+ "cta_text3d": "نص → ثلاثي الأبعاد",
+ "eyebrow": "جديد · النص&nbsp;→&nbsp;ثلاثي الأبعاد متاح الآن — اكتب موجهًا، واحصل على نموذج <span class=\"eyebrow-arrow\" aria-hidden=\"true\">→</span>",
+ "eyebrow_aria": "جديد: النص إلى ثلاثي الأبعاد متاح الآن — افتح Forge",
+ "hero_h": "طبقة وكيل الذكاء الاصطناعي ثلاثي الأبعاد <br> من <br> <em> الإنترنت </em>",
+ "meta_desc": "أنشئ وكيل ذكاء اصطناعي ثلاثي الأبعاد من صورة سيلفي في 60 ثانية. أضف وسم HTML واحدًا لدمجها في أي موقع ويب. الوكلاء يفكرون على IBM watsonx.ai (Granite)؛ ويمكنك اختياريًا فرض رسوم لكل محادثة باستخدام المدفوعات المصغرة المدمجة.",
+ "meta_title": "three.ws — طبقة وكيل الذكاء الاصطناعي ثلاثي الأبعاد للإنترنت"
+ }
+}
diff --git a/public/locales/de.json b/public/locales/de.json
new file mode 100644
index 000000000..5fc083d2d
--- /dev/null
+++ b/public/locales/de.json
@@ -0,0 +1,19 @@
+{
+ "common": {
+ "language": "Sprache",
+ "take_tour": "Tour starten"
+ },
+ "home": {
+ "bullet_create": "<strong>Erstelle</strong> einen 3D-KI-Agenten aus einem Text-Prompt oder Selfie in etwa einer Minute",
+ "bullet_earn": "<strong>Verdiene</strong> USDC pro Chat mit x402 Mikrozahlungen",
+ "bullet_embed": "<strong>Bette</strong> ihn mit zwei Zeilen HTML auf jeder Website ein",
+ "cta_build": "Agenten bauen <span class=\"arrow\">→</span>",
+ "cta_embed": "Embed ansehen",
+ "cta_text3d": "Text → 3D",
+ "eyebrow": "Neu · Text&nbsp;→&nbsp;3D ist live — Prompt eingeben, Modell erhalten <span class=\"eyebrow-arrow\" aria-hidden=\"true\">→</span>",
+ "eyebrow_aria": "Neu: Text zu 3D ist live — öffne das Forge",
+ "hero_h": "Die 3D-Agenten<br>-Schicht des<br> <em>Internets.</em>",
+ "meta_desc": "Erstelle einen 3D-KI-Agenten aus einem Selfie in 60 Sekunden. Ein HTML-Tag genügt, um ihn auf jeder Website einzubetten. Agenten denken auf IBM watsonx.ai (Granite); optional Abrechnung pro Chat mit integrierten Mikrozahlungen.",
+ "meta_title": "three.ws — Die 3D-Agenten-Schicht des Internets"
+ }
+}
diff --git a/public/locales/fr.json b/public/locales/fr.json
new file mode 100644
index 000000000..6b65ac8fc
--- /dev/null
+++ b/public/locales/fr.json
@@ -0,0 +1,19 @@
+{
+ "common": {
+ "language": "Langue",
+ "take_tour": "Découvrir"
+ },
+ "home": {
+ "bullet_create": "<strong>Créer</strong> un agent IA 3D à partir d'une invite textuelle ou d'un selfie en une minute environ",
+ "bullet_earn": "<strong>Gagner</strong> USDC par chat grâce aux micropaiements x402",
+ "bullet_embed": "<strong>Intégrer</strong> sur n'importe quel site web avec deux lignes de code HTML",
+ "cta_build": "Créez votre agent <span class=\"arrow\">→</span>",
+ "cta_embed": "Découvrir l'intégration",
+ "cta_text3d": "Texte → 3D",
+ "eyebrow": "Nouveauté · Texte&nbsp;→&nbsp;3D est en ligne — saisissez une invite, obtenez un modèle <span class=\"eyebrow-arrow\" aria-hidden=\"true\">→</span>",
+ "eyebrow_aria": "Nouveau : Texte en 3D est en ligne — ouvrez le Forge",
+ "hero_h": "La couche d'agents 3D<br> de l'<br> <em>Internet.</em>",
+ "meta_desc": "Créez un agent IA 3D à partir d'un selfie en 60 secondes. Déposez une balise HTML pour l'intégrer sur n'importe quel site web. Les agents pensent sur IBM watsonx.ai (Granite) ; facturez optionnellement par chat grâce aux micropaiements intégrés.",
+ "meta_title": "three.ws — La couche d'agents 3D d'Internet"
+ }
+}
diff --git a/public/locales/hi.json b/public/locales/hi.json
new file mode 100644
index 000000000..27c24ece4
--- /dev/null
+++ b/public/locales/hi.json
@@ -0,0 +1,19 @@
+{
+ "common": {
+ "language": "भाषा",
+ "take_tour": "टूर करें"
+ },
+ "home": {
+ "bullet_create": "एक मिनट में टेक्स्ट प्रॉम्प्ट या सेल्फ़ी से एक 3D AI एजेंट <strong>बनाएँ</strong>",
+ "bullet_earn": "x402 माइक्रोपेमेंट के साथ प्रति चैट USDC <strong>कमाएँ</strong>",
+ "bullet_embed": "HTML की दो लाइनों के साथ इसे किसी भी वेबसाइट पर <strong>एम्बेड करें</strong>",
+ "cta_build": "अपना एजेंट बनाएँ <span class=\"arrow\">→</span>",
+ "cta_embed": "एम्बेड देखें",
+ "cta_text3d": "टेक्स्ट → 3D",
+ "eyebrow": "नया · टेक्स्ट&nbsp;→&nbsp;3D लाइव है — प्रॉम्प्ट टाइप करें, मॉडल पाएँ <span class=\"eyebrow-arrow\" aria-hidden=\"true\">→</span>",
+ "eyebrow_aria": "नया: टेक्स्ट टू 3D लाइव है — Forge खोलें",
+ "hero_h": "3D एजेंट <br> लेयर <br> <em> इंटरनेट </em> की।",
+ "meta_desc": "60 सेकंड में सेल्फ़ी से एक 3D AI एजेंट बनाएँ। इसे किसी भी वेबसाइट पर एम्बेड करने के लिए एक HTML टैग डालें। एजेंट IBM watsonx.ai (Granite) पर सोचते हैं; वैकल्पिक रूप से, बिल्ट-इन माइक्रोपेमेंट के साथ प्रति चैट शुल्क लें।",
+ "meta_title": "three.ws — इंटरनेट की 3D एजेंट लेयर"
+ }
+}
diff --git a/public/locales/ja.json b/public/locales/ja.json
new file mode 100644
index 000000000..b6ced608e
--- /dev/null
+++ b/public/locales/ja.json
@@ -0,0 +1,19 @@
+{
+ "common": {
+ "language": "言語",
+ "take_tour": "ツアーを見る"
+ },
+ "home": {
+ "bullet_create": "約1分でテキストプロンプトや自撮り写真から3D AIエージェントを<strong>作成</strong>。",
+ "bullet_earn": "x402マイクロペイメントでチャットごとにUSDCを<strong>稼ぐ</strong>。",
+ "bullet_embed": "2行のHTMLで、あらゆるウェブサイトに<strong>埋め込む</strong>。",
+ "cta_build": "エージェントを構築 <span class=\"arrow\">→</span>",
+ "cta_embed": "埋め込みを見る",
+ "cta_text3d": "テキスト → 3D",
+ "eyebrow": "新機能 · Text → 3Dがリリース — プロンプトを入力してモデルを取得 <span class=\"eyebrow-arrow\" aria-hidden=\"true\">→</span>",
+ "eyebrow_aria": "新機能: Text to 3Dが公開されました — Forgeを開く",
+ "hero_h": "3Dエージェント<br>レイヤーの<br><em>インターネット</em>。",
+ "meta_desc": "60秒で自撮り写真から3D AIエージェントを作成。1つのHTMLタグをドロップするだけで、あらゆるウェブサイトに埋め込み可能。エージェントはIBM watsonx.ai (Granite) で思考し、オプションで組み込みのマイクロペイメントでチャットごとに課金できます。",
+ "meta_title": "three.ws — インターネットの3Dエージェントレイヤー"
+ }
+}
diff --git a/public/locales/ko.json b/public/locales/ko.json
new file mode 100644
index 000000000..4770bb9f0
--- /dev/null
+++ b/public/locales/ko.json
@@ -0,0 +1,19 @@
+{
+ "common": {
+ "language": "언어",
+ "take_tour": "둘러보기"
+ },
+ "home": {
+ "bullet_create": "텍스트 프롬프트나 셀카로 약 1분 만에 <strong>3D AI 에이전트 생성</strong>",
+ "bullet_earn": "x402 마이크로페이먼트로 채팅당 USDC <strong>수익</strong>",
+ "bullet_embed": "두 줄의 HTML로 어떤 웹사이트든 <strong>임베드</strong>",
+ "cta_build": "에이전트 만들기 <span class=\"arrow\">→</span>",
+ "cta_embed": "임베드 보기",
+ "cta_text3d": "텍스트 → 3D",
+ "eyebrow": "신규 · 텍스트&nbsp;→&nbsp;3D 출시 — 프롬프트 입력, 모델 생성 <span class=\"eyebrow-arrow\" aria-hidden=\"true\">→</span>",
+ "eyebrow_aria": "신규: 텍스트 → 3D 출시 — Forge 열기",
+ "hero_h": "<em>인터넷</em>의 <br>3D 에이전트<br> 레이어",
+ "meta_desc": "셀카로 60초 만에 3D AI 에이전트를 만드세요. HTML 태그 하나로 어떤 웹사이트든 임베드하세요. 에이전트는 IBM watsonx.ai (Granite)에서 생각하며, 내장된 마이크로페이먼트로 채팅당 요금을 부과할 수 있습니다.",
+ "meta_title": "three.ws — 인터넷의 3D 에이전트 레이어"
+ }
+}
diff --git a/public/locales/manifest.json b/public/locales/manifest.json
index 65649bfe4..7cf0a8363 100644
--- a/public/locales/manifest.json
+++ b/public/locales/manifest.json
@@ -10,6 +10,51 @@
"code": "es",
"name": "Español",
"dir": "ltr"
+ },
+ {
+ "code": "zh-CN",
+ "name": "简体中文",
+ "dir": "ltr"
+ },
+ {
+ "code": "ja",
+ "name": "日本語",
+ "dir": "ltr"
+ },
+ {
+ "code": "ko",
+ "name": "한국어",
+ "dir": "ltr"
+ },
+ {
+ "code": "fr",
+ "name": "Français",
+ "dir": "ltr"
+ },
+ {
+ "code": "de",
+ "name": "Deutsch",
+ "dir": "ltr"
+ },
+ {
+ "code": "pt-BR",
+ "name": "Português (BR)",
+ "dir": "ltr"
+ },
+ {
+ "code": "ar",
+ "name": "العربية",
+ "dir": "rtl"
+ },
+ {
+ "code": "hi",
+ "name": "हिन्दी",
+ "dir": "ltr"
+ },
+ {
+ "code": "ru",
+ "name": "Русский",
+ "dir": "ltr"
}
]
}
diff --git a/public/locales/pt-BR.json b/public/locales/pt-BR.json
new file mode 100644
index 000000000..e835af65c
--- /dev/null
+++ b/public/locales/pt-BR.json
@@ -0,0 +1,19 @@
+{
+ "common": {
+ "language": "Idioma",
+ "take_tour": "Fazer o tour"
+ },
+ "home": {
+ "bullet_create": "<strong>Crie</strong> um agente de IA 3D a partir de um prompt de texto ou selfie em cerca de um minuto",
+ "bullet_earn": "<strong>Ganhe</strong> USDC por chat com micropagamentos x402",
+ "bullet_embed": "<strong>Incorpore</strong> em qualquer site com duas linhas de HTML",
+ "cta_build": "Crie seu agente <span class=\"arrow\">→</span>",
+ "cta_embed": "Ver o embed",
+ "cta_text3d": "Texto → 3D",
+ "eyebrow": "Novo · Text&nbsp;→&nbsp;3D está no ar — digite um prompt, obtenha um modelo <span class=\"eyebrow-arrow\" aria-hidden=\"true\">→</span>",
+ "eyebrow_aria": "Novo: Texto para 3D está no ar — abra o Forge",
+ "hero_h": "A camada de agentes 3D<br> da<br> <em>internet.</em>",
+ "meta_desc": "Crie um agente de IA 3D a partir de uma selfie em 60 segundos. Basta uma tag HTML para incorporá-lo em qualquer site. Agentes pensam em IBM watsonx.ai (Granite); opcionalmente, cobre por chat com micropagamentos integrados.",
+ "meta_title": "three.ws — A Camada de Agentes 3D da Internet"
+ }
+}
diff --git a/public/locales/ru.json b/public/locales/ru.json
new file mode 100644
index 000000000..7a3a5cdeb
--- /dev/null
+++ b/public/locales/ru.json
@@ -0,0 +1,19 @@
+{
+ "common": {
+ "language": "Язык",
+ "take_tour": "Начать тур"
+ },
+ "home": {
+ "bullet_create": "<strong>Создайте</strong> 3D AI-агента из текстового запроса или селфи примерно за минуту",
+ "bullet_earn": "<strong>Зарабатывайте</strong> USDC за чат с помощью микроплатежей x402",
+ "bullet_embed": "<strong>Встройте</strong> его на любой сайт с помощью двух строк HTML",
+ "cta_build": "Создайте своего агента <span class=\"arrow\">→</span>",
+ "cta_embed": "Посмотреть встраивание",
+ "cta_text3d": "Текст → 3D",
+ "eyebrow": "Новое · Text&nbsp;→&nbsp;3D уже доступно — введите запрос, получите модель <span class=\"eyebrow-arrow\" aria-hidden=\"true\">→</span>",
+ "eyebrow_aria": "Новое: Text to 3D уже доступно — откройте Forge",
+ "hero_h": "Слой 3D-агентов<br> <br> <em>интернета.</em>",
+ "meta_desc": "Создайте 3D AI-агента из селфи за 60 секунд. Вставьте один HTML-тег, чтобы встроить его на любой сайт. Агенты мыслят на IBM watsonx.ai (Granite); опционально взимайте плату за чат с помощью встроенных микроплатежей.",
+ "meta_title": "three.ws — Слой 3D-агентов Интернета"
+ }
+}
diff --git a/public/locales/zh-CN.json b/public/locales/zh-CN.json
new file mode 100644
index 000000000..aef7a6cc6
--- /dev/null
+++ b/public/locales/zh-CN.json
@@ -0,0 +1,19 @@
+{
+ "common": {
+ "language": "语言",
+ "take_tour": "体验导览"
+ },
+ "home": {
+ "bullet_create": "<strong>创建</strong> 3D AI 智能体,一分钟内通过文本提示或自拍生成。",
+ "bullet_earn": "<strong>赚取</strong> USDC,通过 x402 微支付按次聊天收费。",
+ "bullet_embed": "<strong>嵌入</strong>:两行 HTML 代码,轻松嵌入任何网站。",
+ "cta_build": "构建你的智能体 <span class=\"arrow\">→</span>",
+ "cta_embed": "查看嵌入效果",
+ "cta_text3d": "文本 → 3D",
+ "eyebrow": "新功能 · 文本&nbsp;→&nbsp;3D 已上线 — 输入提示,生成模型 <span class=\"eyebrow-arrow\" aria-hidden=\"true\">→</span>",
+ "eyebrow_aria": "新功能:文本转 3D 已上线 — 打开 Forge",
+ "hero_h": "<em>互联网</em>的 3D 智能体<br>层<br>。",
+ "meta_desc": "60 秒内通过自拍创建 3D AI 智能体。只需一个 HTML 标签即可将其嵌入任何网站。智能体在 IBM watsonx.ai (Granite) 上运行思考;可选择通过内置微支付按次聊天收费。",
+ "meta_title": "three.ws — 互联网的 3D 智能体层"
+ }
+}
diff --git a/src/irl.js b/src/irl.js
index e2507dc62..ade4c4d0c 100644
--- a/src/irl.js
+++ b/src/irl.js
@@ -6353,8 +6353,8 @@ function updateLabels() {
if (sy < minY) sy = minY;
_visibleLabels.push({ pin, sx, sy });
}
- // De-collide stacked plates: agents lined up front-to-back — or two people with
- // the same name — project to nearly the same screen point and paint as one
+ // De-collide stacked plates: agents lined up front-to-back (or two people with
+ // the same name) project to nearly the same screen point and paint as one
// unreadable smudge. Walk them top-down and push each colliding plate below the
// one above it so every name stays legible. Bounded by BUDGET.label, so O(n²) is
// a handful of comparisons.
diff --git a/tests/solana-mobile-mwa-wallet.test.js b/tests/solana-mobile-mwa-wallet.test.js
new file mode 100644
index 000000000..60e8cd124
--- /dev/null
+++ b/tests/solana-mobile-mwa-wallet.test.js
@@ -0,0 +1,272 @@
+// @vitest-environment jsdom
+//
+// Unit coverage for the Seeker Mobile Wallet Adapter (MWA) wrapper in
+// solana-mobile/src/mwa-wallet.js. On a Seeker the browser does not inject
+// window.solana; signing is delegated to the on-device Seed Vault over the MWA
+// protocol. This suite exercises that wrapper against a fake `transact`
+// transport so every branch (authorize / reauthorize / resume / sign / send /
+// disconnect / session persistence / error paths) is verified without hardware.
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { PublicKey } from '@solana/web3.js';
+
+// The real transport is loaded lazily via
+// `await import('@solana-mobile/mobile-wallet-adapter-protocol-web3js')`.
+// Replace it with a controllable fake. vi.hoisted keeps the shared state alive
+// above the hoisted vi.mock factory.
+const h = vi.hoisted(() => {
+ const state = { wallet: null, transactCalls: 0 };
+ return {
+ state,
+ transact: async (callback) => {
+ state.transactCalls += 1;
+ if (!state.wallet) throw new Error('no fake wallet configured');
+ return callback(state.wallet);
+ },
+ };
+});
+
+vi.mock('@solana-mobile/mobile-wallet-adapter-protocol-web3js', () => ({
+ transact: h.transact,
+}));
+
+import { MwaWallet } from '../solana-mobile/src/mwa-wallet.js';
+
+const ADDR = 'So11111111111111111111111111111111111111112';
+const ADDR_B64 = Buffer.from(new PublicKey(ADDR).toBytes()).toString('base64');
+
+// Build a fake MWA wallet proxy. Each protocol method is a spy returning the
+// shape the web3js-augmented transact() proxy produces.
+function makeWallet(overrides = {}) {
+ const authResult = {
+ accounts: [{ address: ADDR_B64 }],
+ auth_token: 'tok-1',
+ };
+ return {
+ authorize: vi.fn().mockResolvedValue(authResult),
+ reauthorize: vi.fn().mockResolvedValue(authResult),
+ deauthorize: vi.fn().mockResolvedValue(undefined),
+ signMessages: vi.fn(),
+ signTransactions: vi.fn(),
+ signAndSendTransactions: vi.fn(),
+ ...overrides,
+ };
+}
+
+beforeEach(() => {
+ sessionStorage.clear();
+ h.state.wallet = makeWallet();
+ h.state.transactCalls = 0;
+});
+
+describe('MwaWallet.connect', () => {
+ it('authorizes on first connect and exposes the derived public key', async () => {
+ const w = new MwaWallet();
+ const onConnect = vi.fn();
+ w.on('connect', onConnect);
+
+ const { publicKey } = await w.connect();
+
+ expect(h.state.wallet.authorize).toHaveBeenCalledTimes(1);
+ expect(h.state.wallet.authorize).toHaveBeenCalledWith(
+ expect.objectContaining({
+ chain: 'solana:mainnet',
+ features: ['solana:signTransactions', 'solana:signMessages'],
+ }),
+ );
+ expect(publicKey.toBase58()).toBe(ADDR);
+ expect(w.isConnected).toBe(true);
+ expect(onConnect).toHaveBeenCalledWith(w.publicKey);
+ // Auth token + address persisted for resume.
+ expect(sessionStorage.getItem('threews:mwa:authToken')).toBe('tok-1');
+ expect(sessionStorage.getItem('threews:mwa:address')).toBe(ADDR);
+ });
+
+ it('is a no-op when already connected (no second transport session)', async () => {
+ const w = new MwaWallet();
+ await w.connect();
+ const before = h.state.transactCalls;
+ await w.connect();
+ expect(h.state.transactCalls).toBe(before);
+ });
+
+ it('shares a single in-flight promise across concurrent connect calls', async () => {
+ const w = new MwaWallet();
+ const [a, b] = await Promise.all([w.connect(), w.connect()]);
+ expect(a.publicKey.toBase58()).toBe(ADDR);
+ expect(b.publicKey.toBase58()).toBe(ADDR);
+ // Only one authorize despite two concurrent callers.
+ expect(h.state.wallet.authorize).toHaveBeenCalledTimes(1);
+ });
+
+ it('rejects onlyIfTrusted resume when there is no prior session', async () => {
+ const w = new MwaWallet();
+ await expect(w.connect({ onlyIfTrusted: true })).rejects.toMatchObject({ code: 4001 });
+ expect(h.state.wallet.authorize).not.toHaveBeenCalled();
+ });
+
+ it('reauthorizes (not authorize) when a stored token exists', async () => {
+ sessionStorage.setItem('threews:mwa:authToken', 'stored-tok');
+ sessionStorage.setItem('threews:mwa:address', ADDR);
+ const w = new MwaWallet();
+ // Constructor rehydrated address, so it is already "connected"; force a
+ // resume through the transport by clearing the public key path.
+ await w.connect({ onlyIfTrusted: true });
+ // Already connected from storage → no transport call needed.
+ expect(w.isConnected).toBe(true);
+ });
+
+ it('surfaces a reauthorize failure when the Seed Vault revoked the token', async () => {
+ // A rehydrated wallet still holds a token, but signing forces a
+ // reauthorize; if the wallet revoked it, the operation must reject
+ // rather than sign against a dead session.
+ sessionStorage.setItem('threews:mwa:authToken', 'revoked');
+ sessionStorage.setItem('threews:mwa:address', ADDR);
+ h.state.wallet = makeWallet({
+ reauthorize: vi.fn().mockRejectedValue(new Error('token revoked')),
+ });
+ const w = new MwaWallet();
+ await expect(w.signMessage(new Uint8Array([1, 2, 3]))).rejects.toThrow(/revoked/);
+ });
+});
+
+describe('MwaWallet.signMessage', () => {
+ it('returns the trailing 64-byte ed25519 signature from the signed payload', async () => {
+ const message = new Uint8Array([9, 8, 7]);
+ const sig = new Uint8Array(64).fill(7);
+ const combined = new Uint8Array([...message, ...sig]);
+ h.state.wallet.signMessages.mockResolvedValue([combined]);
+
+ const w = new MwaWallet();
+ await w.connect();
+ const { signature, publicKey } = await w.signMessage(message);
+
+ expect(signature).toBeInstanceOf(Uint8Array);
+ expect(signature.length).toBe(64);
+ expect(Array.from(signature)).toEqual(Array.from(sig));
+ expect(publicKey.toBase58()).toBe(ADDR);
+ });
+
+ it('rejects a non-Uint8Array message', async () => {
+ const w = new MwaWallet();
+ await w.connect();
+ await expect(w.signMessage('not-bytes')).rejects.toThrow(TypeError);
+ });
+
+ it('throws when the wallet returns no signed payload', async () => {
+ h.state.wallet.signMessages.mockResolvedValue([null]);
+ const w = new MwaWallet();
+ await w.connect();
+ await expect(w.signMessage(new Uint8Array([1]))).rejects.toThrow(/no signed payload/);
+ });
+});
+
+describe('MwaWallet.signTransaction / signAllTransactions', () => {
+ it('returns the signed transactions from the transport', async () => {
+ const txs = [{ id: 'a' }, { id: 'b' }];
+ const signedOut = [{ id: 'a', signed: true }, { id: 'b', signed: true }];
+ h.state.wallet.signTransactions.mockResolvedValue(signedOut);
+
+ const w = new MwaWallet();
+ await w.connect();
+ const result = await w.signAllTransactions(txs);
+ expect(result).toEqual(signedOut);
+ expect(h.state.wallet.signTransactions).toHaveBeenCalledWith({ transactions: txs });
+ });
+
+ it('signTransaction unwraps the single-element result', async () => {
+ h.state.wallet.signTransactions.mockResolvedValue([{ id: 'x', signed: true }]);
+ const w = new MwaWallet();
+ await w.connect();
+ const signed = await w.signTransaction({ id: 'x' });
+ expect(signed).toEqual({ id: 'x', signed: true });
+ });
+
+ it('throws on a mismatched signed-count', async () => {
+ h.state.wallet.signTransactions.mockResolvedValue([{ id: 'a' }]);
+ const w = new MwaWallet();
+ await w.connect();
+ await expect(w.signAllTransactions([{ id: 'a' }, { id: 'b' }])).rejects.toThrow(/mismatched/);
+ });
+
+ it('rejects an empty transaction array', async () => {
+ const w = new MwaWallet();
+ await w.connect();
+ await expect(w.signAllTransactions([])).rejects.toThrow(TypeError);
+ });
+});
+
+describe('MwaWallet.signAndSendTransaction', () => {
+ it('returns the base58 signature string from the send flow', async () => {
+ h.state.wallet.signAndSendTransactions.mockResolvedValue(['5xSig...base58']);
+ const w = new MwaWallet();
+ await w.connect();
+ const { signature } = await w.signAndSendTransaction({ id: 'tx' });
+ expect(signature).toBe('5xSig...base58');
+ });
+
+ it('throws when the transport returns a non-string signature', async () => {
+ h.state.wallet.signAndSendTransactions.mockResolvedValue([null]);
+ const w = new MwaWallet();
+ await w.connect();
+ await expect(w.signAndSendTransaction({ id: 'tx' })).rejects.toThrow(/no signature/);
+ });
+});
+
+describe('MwaWallet.disconnect', () => {
+ it('deauthorizes and resets state, emitting disconnect', async () => {
+ const w = new MwaWallet();
+ await w.connect();
+ const onDisconnect = vi.fn();
+ w.on('disconnect', onDisconnect);
+
+ await w.disconnect();
+
+ expect(h.state.wallet.deauthorize).toHaveBeenCalledWith({ auth_token: 'tok-1' });
+ expect(w.isConnected).toBe(false);
+ expect(w.publicKey).toBe(null);
+ expect(onDisconnect).toHaveBeenCalled();
+ expect(sessionStorage.getItem('threews:mwa:authToken')).toBe(null);
+ });
+
+ it('is safe to call with no active session', async () => {
+ const w = new MwaWallet();
+ await expect(w.disconnect()).resolves.toBeUndefined();
+ expect(h.state.wallet.deauthorize).not.toHaveBeenCalled();
+ });
+
+ it('resets local state even if deauthorize rejects', async () => {
+ h.state.wallet = makeWallet({
+ deauthorize: vi.fn().mockRejectedValue(new Error('network')),
+ });
+ const w = new MwaWallet();
+ await w.connect();
+ await w.disconnect();
+ expect(w.isConnected).toBe(false);
+ });
+});
+
+describe('session persistence', () => {
+ it('rehydrates a connected wallet from sessionStorage', async () => {
+ const first = new MwaWallet();
+ await first.connect();
+ // A fresh instance (app relaunch) should already be connected.
+ const second = new MwaWallet();
+ expect(second.isConnected).toBe(true);
+ expect(second.publicKey.toBase58()).toBe(ADDR);
+ });
+});
+
+describe('address decoding', () => {
+ it('accepts a base58 address returned directly by newer wallets', async () => {
+ h.state.wallet = makeWallet({
+ authorize: vi.fn().mockResolvedValue({
+ accounts: [{ address: ADDR }], // base58, not base64
+ auth_token: 'tok-b58',
+ }),
+ });
+ const w = new MwaWallet();
+ const { publicKey } = await w.connect();
+ expect(publicKey.toBase58()).toBe(ADDR);
+ });
+});