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(avatar): stop the GLB optimizer returning a bigger file than it was given

nirholasf42c80d27cd6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index bf82b324e..97731c2dc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -57,6 +57,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **The Examples Gallery came back, and seven docs pages stopped describing code that had changed**: The Examples Gallery doc had been reduced to three lines of placeholder text by an interrupted test run, so a page advertised as copy-paste-ready code for the most common use cases opened to nothing at all; the full guide is restored, from the one-tag minimal embed through the React wrapper, the multi-agent scene, and the complete Coach Leo manifest, and its index of every runnable example in the repo is regenerated from what is actually on disk. Alongside it: the JavaScript API reference described a validator toggle, a scene-graph printer, and an alert-based error handler that no longer exist, and missed the load-progress callback and the model-loaded event that do; the Introduction listed five embeddable widgets when ten ship; two pages named older chat models than the brain router now offers; the Internationalization page called its lint command a build gate when nothing runs it for you; and the IRL page linked its retention cron at a live endpoint that answers with an authorization error instead of at the source file. (`/docs/examples`) `[docs, fix]`
- **The extra views behind a 3D generation stop being rejected for the wrong file type**: Before a prompt becomes a 3D model, the forge draws a reference picture, then draws two more views of it so the reconstruction can see the sides and back instead of guessing them. Those extra views sent the reference picture to the image model labelled as a PNG no matter what it actually was, so a JPEG or WebP reference could be refused outright and you would quietly get fewer views and a rougher model. The real format is now read from the picture and sent with it. A reference that is unreachable, oversized, or not actually an image is now refused with a clear reason instead of being forwarded as-is and failing further down. And every image this step fetches, including the optional edit mask, now goes through the same address safety check the rest of the platform uses, so a supplied link cannot be aimed at an internal address. (`/create`) `[fix, security]`
- **The free inference-receipt verifier is now in the public x402 catalog**: /api/x402/inference-verify audits a metered-inference receipt from a paid llm-proxy call: it re-checks the issuer signature, the node's response signature, the prompt and response hashes against the raw text you supply, whether the settlement transaction actually confirmed on-chain, and whether the issuer is one of the platform's published signers. It is free and keyless, but it was missing from docs/x402-endpoints.md, so buyers and node operators had no way to find it. It now has a row in the free read surfaces table alongside the other verifier tools. (`/docs/x402-endpoints`) `[docs]`
+- **The GLB optimizer no longer hands back a bigger file than you gave it**: Asking /api/avatar/optimize for Draco compression could return a model up to 19% LARGER than the source, with nothing in the response to warn you. Stored three.ws avatars are already quantized and meshopt-packed, and the optimizer was stacking Draco on top of that instead of choosing one scheme, then re-quantizing data that was already quantized. It now drops the competing compression, restores full-precision attributes before encoding, and keeps whichever result is genuinely smaller. If nothing beats the original it returns the original bytes untouched. Every response now says what you got: x-three-ws-optimize reports draco, meshopt, none or source, and x-three-ws-optimize-refused appears when Draco was asked for and dropped for making the file worse. Those headers plus the byte counts are readable from browser code for the first time. Measured on the two production sample avatars: Draco went from +19.0% to 0.0% on one and from +14.6% to a real -4.4% saving on the other. (`/docs/media-api`) `[fix, improvement]`
- **The Granite forecast tool now ships a copy-and-run example**: The IBM Granite forecasting tool on our x402 MCP endpoint advertised a two-point sample series, but the tool needs at least 64 points of history to forecast anything. Any agent that copied the published example got a validation error back instead of a forecast. The example is now a real 64-day daily series you can paste straight into a call, and it is identical on the hosted endpoint and in the @three-ws/ibm-x402-mcp package. A test now dials every published example through the server the way a client would, so a sample that does not actually work cannot ship again. (`/docs/ibm-x402-mcp`) `[fix, sdk]`
- **The image step behind 3D generation now times out, checks its inputs, and stops mislabelling them**: Before a prompt becomes a 3D model, the forge draws a reference picture, then draws two extra views of it so the reconstruction can see the sides and back instead of guessing them. Three problems sat in that step. The calls to the image service had no time limit, so a connection that opened and then stalled held a generation open indefinitely rather than falling back to the free image lane; they now give up after ninety seconds and hand off. The extra views sent the reference picture to the model labelled as a PNG no matter what it actually was, so a JPEG or WebP reference could be rejected and you would quietly get fewer views; the real format is now read from the picture and sent with it. And a reference that is unreachable or oversized is refused with a clear reason instead of being forwarded as-is. Alongside that, every image this step fetches, including the optional mask, now goes through the same address safety check the rest of the platform uses, so a supplied URL cannot be aimed at an internal address. (`/create`) `[fix, security]`
- **The Integrations page and its docs stopped showing "avatar not found" where the 3D demo should be**: Every copy-paste avatar snippet on the Integrations page, the embed demo, and the Integrations doc pointed at a demo avatar whose record had been deleted in an earlier cleanup, so the headline 3D Avatar example rendered the words "avatar not found" instead of a character, and anyone who pasted the snippet into their own site got the same empty box. All nine references now use a live featured avatar, verified end to end in a real browser: the web component loads with no failed requests and a real 3D character renders on the page and in the pasted snippet. (`/integrations`) `[fix, docs]`
diff --git a/ISSUES.md b/ISSUES.md
index 5cca346be..3b745373a 100644
--- a/ISSUES.md
+++ b/ISSUES.md
@@ -231,6 +231,18 @@ wrong version is what a future reader would otherwise trust.
stall (streaming 50 MB cap returning `413`/`504`, covered by
`tests/avatar-optimize-source-cap.test.js`).
+ A second, unrelated defect on the same endpoint was found once the 500 was
+ gone and is **also closed (2026-08-13)**: `?draco=1` returned a file BIGGER
+ than its input (default.glb 748,088 to 890,160, +19.0%; michelle.glb 849,756
+ to 974,036, +14.6%) and said nothing about it. Cause: stored avatars are
+ quantized and meshopt-packed, gltf-transform keeps `EXT_meshopt_compression`
+ attached after reading, so Draco was layered beside the meshopt payload and
+ re-quantized already-quantized attributes. The pipeline now drops the other
+ mesh-compression scheme and dequantizes before encoding, keeps whichever
+ encoding is actually smaller, and falls back to the original bytes when
+ nothing helped. `x-three-ws-optimize` / `x-three-ws-optimize-refused` report
+ which happened. Pinned by `tests/avatar-optimize-never-inflates.test.js`.
+
- **The autopilot spend default.** `POST /api/agents/:id/autopilot/run` read
`body?.dry_run === true`, so a bare `POST {}` ran a REAL cycle while the
sibling runner on the same wallet (`api/agents/wallet-intents.js`) read
diff --git a/api/avatar/optimize.js b/api/avatar/optimize.js
index 195e32e68..c89be07b9 100644
--- a/api/avatar/optimize.js
+++ b/api/avatar/optimize.js
@@ -16,13 +16,27 @@
// morphs=arkit52|all morph target filter.
// arkit52 = drop morphs not in the ARKit-52 standard.
// all = keep every morph (default).
-// draco=1 apply KHR_draco_mesh_compression. Smaller bytes, but
-// requires a Draco decoder on the client.
+// draco=1 prefer KHR_draco_mesh_compression. Requires a Draco
+// decoder on the client. Honoured only when it actually
+// shrinks the file (see the size contract below).
//
// Response:
// model/gltf-binary body, cached at the edge for 1 year (immutable per
// src+params), browser cache 30d.
//
+// Size contract: this endpoint never returns more bytes than it was given for a
+// content-preserving request (no lod, no morph filter, no explicit textureSize).
+// The output declares at most ONE mesh-compression scheme, and the response says
+// which:
+// x-three-ws-optimize: draco | meshopt | none | source
+// `source` means the pipeline could not beat the original and the original
+// bytes were returned unchanged.
+// x-three-ws-optimize-refused: draco
+// present when draco=1 was asked for and dropped because it grew the file.
+// x-three-ws-source-bytes / x-three-ws-output-bytes: the measured sizes.
+// All four are listed in access-control-expose-headers so browser callers can
+// read them.
+//
// Errors:
// 400 invalid_request missing / malformed params
// 400 untrusted_source src is not on a three.ws-controlled origin
@@ -130,6 +144,10 @@ async function resolveSource({ src, id }) {
// names + canonical aliases + visemes). Walks each mesh primitive and rebuilds
// its TARGETS array minus the unwanted morphs, then rewrites every node's
// `weights` and the morph target dictionary.
+//
+// Returns true only when a morph was actually dropped. A model that already
+// carries nothing but ARKit morphs is unchanged, and the caller uses that to
+// decide whether the request is still content-preserving.
function filterMorphsToArkit52(doc) {
const allowed = new Set([
...ARKIT_52,
@@ -137,6 +155,7 @@ function filterMorphsToArkit52(doc) {
...Object.keys(MORPH_ALIASES),
]);
+ let changed = false;
for (const mesh of doc.getRoot().listMeshes()) {
const extras = mesh.getExtras() || {};
const names = Array.isArray(extras.targetNames) ? extras.targetNames : null;
@@ -162,7 +181,9 @@ function filterMorphsToArkit52(doc) {
...extras,
targetNames: keep.map((i) => names[i]),
});
+ changed = true;
}
+ return changed;
}
// Simplify mesh density via a heuristic decimation. Real meshopt simplification
@@ -170,14 +191,37 @@ function filterMorphsToArkit52(doc) {
// drop trailing morph data and let `weld` collapse duplicate vertices, which
// has a meaningful (10–25%) effect for hand-modeled meshes without quality
// loss.
+// Total vertices across every primitive, used to tell a weld that collapsed
+// something from one that had nothing to collapse.
+function vertexCount(doc) {
+ let total = 0;
+ for (const mesh of doc.getRoot().listMeshes()) {
+ for (const prim of mesh.listPrimitives()) {
+ total += prim.getAttribute('POSITION')?.getCount() || 0;
+ }
+ }
+ return total;
+}
+
async function applyLod(doc, lod) {
- if (lod <= 0) return;
+ if (lod <= 0) return false;
// Compose the dedup+weld+prune passes for the lossless lod=1 tier.
+ const before = vertexCount(doc);
await doc.transform(weld({ tolerance: lod === 2 ? 0.0005 : 0.0001 }));
+ return vertexCount(doc) !== before;
}
async function applyTextureCap(doc, maxEdge) {
- if (!maxEdge) return;
+ if (!maxEdge) return false;
+ // Only a texture that is actually over the cap loses pixels. Re-encoding one
+ // that already fits is a pure size optimization, so it must not count as a
+ // content change: otherwise a default (or ineffective) textureSize would stop
+ // the size guard from handing back the original bytes.
+ const resized = doc.getRoot().listTextures().some((tex) => {
+ const [w, h] = tex.getSize() || [0, 0];
+ return w > maxEdge || h > maxEdge;
+ });
+
// `textureCompress` from gltf-transform handles resize+re-encode in one
// pass; force webp output for ~30% size reduction over JPEG/PNG at
// equivalent perceptual quality.
@@ -185,7 +229,7 @@ async function applyTextureCap(doc, maxEdge) {
try {
sharp = (await import('sharp')).default;
} catch (_) {
- return;
+ return false;
}
await doc.transform(
textureCompress({
@@ -195,6 +239,7 @@ async function applyTextureCap(doc, maxEdge) {
resize: [maxEdge, maxEdge],
}),
);
+ return resized;
}
let _ioPromise = null;
@@ -233,10 +278,101 @@ function transcodeIo() {
return _ioPromise;
}
+// Mesh-compression schemes are mutually exclusive: a primitive compressed with
+// EXT_meshopt_compression cannot also be compressed with
+// KHR_draco_mesh_compression. Our stored avatars ship meshopt-packed, and
+// gltf-transform keeps the extension attached to the Document after reading, so
+// simply calling draco() re-encoded the meshopt payload AND added Draco beside
+// it. That is what made `?draco=1` return files 17-19% LARGER than the source.
+function dropMeshCompression(doc) {
+ for (const ext of doc.getRoot().listExtensionsUsed()) {
+ const name = ext.extensionName;
+ if (name === 'EXT_meshopt_compression' || name === 'KHR_draco_mesh_compression') {
+ ext.dispose();
+ }
+ }
+}
+
async function applyDraco(doc) {
- const { draco } = await import('@gltf-transform/functions');
- // Draco encodes indexed primitives only, so weld before handing it the mesh.
- await doc.transform(weld(), draco());
+ const { draco, dequantize } = await import('@gltf-transform/functions');
+ dropMeshCompression(doc);
+ // Draco quantizes internally. Handing it attributes that KHR_mesh_quantization
+ // already packed into normalized shorts is the classic way to grow a file, so
+ // restore float attributes first and let Draco do the quantization once.
+ // Draco also encodes indexed primitives only, hence the weld.
+ await doc.transform(dequantize(), weld(), draco());
+}
+
+// Which mesh-compression scheme a written document actually declares, so the
+// response can state what the caller received instead of what was requested.
+function meshCompressionScheme(doc) {
+ const used = doc.getRoot().listExtensionsUsed().map((e) => e.extensionName);
+ if (used.includes('KHR_draco_mesh_compression')) return 'draco';
+ if (used.includes('EXT_meshopt_compression')) return 'meshopt';
+ return 'none';
+}
+
+/**
+ * The whole transcode, with no HTTP or network in it: source GLB bytes in,
+ * optimized GLB bytes out, plus what was actually done to them.
+ *
+ * Guarantees, in order of application:
+ * - the output declares at most ONE mesh-compression scheme;
+ * - `draco` is honoured only when it beats the alternative encoding;
+ * - a request that changed nothing about the model never returns more bytes
+ * than it was given (the source is handed back instead).
+ *
+ * @param {Buffer} sourceBytes
+ * @param {{ lod?: number, textureSize?: number, morphs?: string, draco?: boolean }} opts
+ * @returns {Promise<{ bytes: Buffer|Uint8Array, scheme: 'draco'|'meshopt'|'none'|'source', refused: 'draco'|null }>}
+ */
+export async function optimizeGlb(sourceBytes, opts = {}) {
+ const { lod = 0, textureSize = 2048, morphs = 'all', draco = false } = opts;
+
+ const io = await transcodeIo();
+ const doc = await io.readBinary(sourceBytes);
+
+ await doc.transform(dedup(), prune({ keepLeaves: false, keepAttributes: false }));
+
+ // A requested transform that changed nothing leaves the request
+ // content-preserving, so an ineffective lod / morph filter / texture cap
+ // cannot cost the caller bytes.
+ let contentChanged = false;
+ if (morphs === 'arkit52' && filterMorphsToArkit52(doc)) contentChanged = true;
+ if (await applyLod(doc, lod)) contentChanged = true;
+ if (await applyTextureCap(doc, textureSize)) contentChanged = true;
+
+ let bytes = await io.writeBinary(doc);
+ let scheme = meshCompressionScheme(doc);
+ let refused = null;
+
+ if (draco) {
+ // Draco is a bet, not a guarantee: it compresses mesh primitives only, so
+ // on animation- or texture-dominated avatars it loses to the meshopt
+ // packing already on the source. Encode both and ship the smaller one
+ // rather than honouring the flag into a worse file.
+ await applyDraco(doc);
+ const dracoBytes = await io.writeBinary(doc);
+ if (dracoBytes.byteLength < bytes.byteLength) {
+ bytes = dracoBytes;
+ scheme = meshCompressionScheme(doc);
+ } else {
+ refused = 'draco';
+ }
+ }
+
+ // Last guard: when nothing about the model actually changed and the pipeline
+ // still produced something bigger than it was given, the honest answer is the
+ // original bytes. A transform that DID change the model (a real decimation, a
+ // real morph filter, a real texture downscale) is never substituted this way,
+ // because the caller wants the transformed model, not the smallest one.
+ if (!contentChanged && bytes.byteLength >= sourceBytes.byteLength) {
+ bytes = sourceBytes;
+ scheme = 'source';
+ if (draco) refused = 'draco';
+ }
+
+ return { bytes, scheme, refused };
}
export default wrap(async (req, res) => {
@@ -308,22 +444,13 @@ export default wrap(async (req, res) => {
clearTimeout(fetchTimer);
}
- let outBytes;
+ let result;
try {
- const io = await transcodeIo();
- const doc = await io.readBinary(sourceBytes);
-
- await doc.transform(dedup(), prune({ keepLeaves: false, keepAttributes: false }));
-
- if (morphs === 'arkit52') filterMorphsToArkit52(doc);
- await applyLod(doc, lod);
- await applyTextureCap(doc, textureSize);
- if (draco) await applyDraco(doc);
-
- outBytes = await io.writeBinary(doc);
+ result = await optimizeGlb(sourceBytes, { lod, textureSize, morphs, draco });
} catch (err) {
return error(res, 500, 'transcode_failed', err?.message || 'transcode pipeline failed');
}
+ const { bytes: outBytes, scheme, refused } = result;
res.setHeader('content-type', 'model/gltf-binary');
res.setHeader('content-length', String(outBytes.byteLength));
@@ -331,6 +458,14 @@ export default wrap(async (req, res) => {
res.setHeader('access-control-allow-origin', '*');
res.setHeader('x-three-ws-source-bytes', String(sourceBytes.byteLength));
res.setHeader('x-three-ws-output-bytes', String(outBytes.byteLength));
+ res.setHeader('x-three-ws-optimize', scheme);
+ if (refused) res.setHeader('x-three-ws-optimize-refused', refused);
+ // Without this a browser fetch() cannot read any of the above, which made the
+ // byte headers unusable from the very clients this endpoint serves.
+ res.setHeader(
+ 'access-control-expose-headers',
+ 'x-three-ws-source-bytes, x-three-ws-output-bytes, x-three-ws-optimize, x-three-ws-optimize-refused',
+ );
res.statusCode = 200;
res.end(Buffer.from(outBytes));
});
diff --git a/data/changelog.json b/data/changelog.json
index c301caa0a..2f68a35e9 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -20896,6 +20896,16 @@
"docs"
],
"link": "/docs/x402-endpoints"
+ },
+ {
+ "date": "2026-08-13",
+ "title": "The GLB optimizer no longer hands back a bigger file than you gave it",
+ "summary": "Asking /api/avatar/optimize for Draco compression could return a model up to 19% LARGER than the source, with nothing in the response to warn you. Stored three.ws avatars are already quantized and meshopt-packed, and the optimizer was stacking Draco on top of that instead of choosing one scheme, then re-quantizing data that was already quantized. It now drops the competing compression, restores full-precision attributes before encoding, and keeps whichever result is genuinely smaller. If nothing beats the original it returns the original bytes untouched. Every response now says what you got: x-three-ws-optimize reports draco, meshopt, none or source, and x-three-ws-optimize-refused appears when Draco was asked for and dropped for making the file worse. Those headers plus the byte counts are readable from browser code for the first time. Measured on the two production sample avatars: Draco went from +19.0% to 0.0% on one and from +14.6% to a real -4.4% saving on the other.",
+ "tags": [
+ "fix",
+ "improvement"
+ ],
+ "link": "/docs/media-api"
}
]
}
diff --git a/docs/media-api.md b/docs/media-api.md
index 718906f81..4d25d047a 100644
--- a/docs/media-api.md
+++ b/docs/media-api.md
@@ -177,13 +177,36 @@ Provide exactly one of `src` or `id`; the rest are optional.
| `lod` | enum | `0` | `0` = source, `1` = conservative weld/dedup, `2` = more aggressive weld. |
| `textureSize` | enum | `2048` | Max texture edge: `128`, `256`, `512`, `1024`, or `2048`. Larger textures are downscaled and re-encoded as WebP. |
| `morphs` | enum | `all` | `arkit52` drops every morph target not in the ARKit-52 standard set (plus canonical aliases and visemes); `all` keeps everything. |
-| `draco` | flag | off | `draco=1` applies `KHR_draco_mesh_compression`. Smaller bytes, but the client needs a Draco decoder. |
+| `draco` | flag | off | `draco=1` *prefers* `KHR_draco_mesh_compression`, and the client then needs a Draco decoder. It is applied only when it actually shrinks the file (see the size contract below). |
### Response
`200` with `model/gltf-binary` bytes, cached immutably (30 days in the
-browser, 1 year at the edge, keyed on the full URL). Headers
-`x-three-ws-source-bytes` and `x-three-ws-output-bytes` report the size delta.
+browser, 1 year at the edge, keyed on the full URL).
+
+### Size contract
+
+The endpoint never returns more bytes than it was given unless you asked for a
+change that genuinely alters the model. Stored three.ws avatars are already
+quantized and meshopt-packed, so layering Draco on top of that can easily make a
+file bigger; when it does, the endpoint keeps the better encoding (or hands back
+the original bytes) instead of honouring the flag into a worse result. The
+output declares **at most one** mesh-compression scheme, never Draco and meshopt
+together. Four response headers say exactly what happened, and all four are
+listed in `access-control-expose-headers` so browser `fetch()` can read them:
+
+| Header | Meaning |
+|--------|---------|
+| `x-three-ws-source-bytes` | Size of the source GLB. |
+| `x-three-ws-output-bytes` | Size of the body you received. |
+| `x-three-ws-optimize` | What the body is: `draco`, `meshopt`, `none` (no mesh compression), or `source` (the original bytes, returned unchanged because nothing the pipeline produced was smaller). |
+| `x-three-ws-optimize-refused` | `draco` when `draco=1` was requested and dropped because it grew the file. Absent otherwise. |
+
+The one case where the output may exceed the source is a request that really
+changed the model: a `lod` that collapsed vertices, a `morphs=arkit52` that
+dropped morph targets, or a `textureSize` that downscaled a texture. There you
+asked for different content, so you get it, and the byte headers still report
+the exact cost.
### Errors
diff --git a/public/changelog.json b/public/changelog.json
index 4947c7049..72ecb5f66 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-08-13T16:20:35.820Z",
+ "generated_at": "2026-08-13T16:39:43.927Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -548,6 +548,17 @@
"docs"
]
},
+ {
+ "date": "2026-08-13",
+ "type": "update",
+ "title": "The GLB optimizer no longer hands back a bigger file than you gave it",
+ "summary": "Asking /api/avatar/optimize for Draco compression could return a model up to 19% LARGER than the source, with nothing in the response to warn you. Stored three.ws avatars are already quantized and meshopt-packed, and the optimizer was stacking Draco on top of that instead of choosing one scheme, then re-quantizing data that was already quantized. It now drops the competing compression, restores full-precision attributes before encoding, and keeps whichever result is genuinely smaller. If nothing beats the original it returns the original bytes untouched. Every response now says what you got: x-three-ws-optimize reports draco, meshopt, none or source, and x-three-ws-optimize-refused appears when Draco was asked for and dropped for making the file worse. Those headers plus the byte counts are readable from browser code for the first time. Measured on the two production sample avatars: Draco went from +19.0% to 0.0% on one and from +14.6% to a real -4.4% saving on the other.",
+ "link": "/docs/media-api",
+ "tags": [
+ "fix",
+ "improvement"
+ ]
+ },
{
"date": "2026-08-13",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 9ac241140..368914b84 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -414,6 +414,14 @@
<category>docs</category>
<description>/api/x402/inference-verify audits a metered-inference receipt from a paid llm-proxy call: it re-checks the issuer signature, the node's response signature, the prompt and response hashes against the raw text you supply, whether the settlement transaction actually confirmed on-chain, and whether the issuer is one of the platform's published signers. It is free and keyless, but it was missing from docs/x402-endpoints.md, so buyers and node operators had no way to find it. It now has a row in the free read surfaces table alongside the other verifier tools.</description>
</item>
+ <item>
+ <title>The GLB optimizer no longer hands back a bigger file than you gave it</title>
+ <link>https://three.ws/docs/media-api</link>
+ <guid isPermaLink="false">2026-08-13:The GLB optimizer no longer hands back a bigger file than you gave it</guid>
+ <pubDate>Thu, 13 Aug 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>Asking /api/avatar/optimize for Draco compression could return a model up to 19% LARGER than the source, with nothing in the response to warn you. Stored three.ws avatars are already quantized and meshopt-packed, and the optimizer was stacking Draco on top of that instead of choosing one scheme, then re-quantizing data that was already quantized. It now drops the competing compression, restores full-precision attributes before encoding, and keeps whichever result is genuinely smaller. If nothing beats the original it returns the original bytes untouched. Every response now says what you got: x-three-ws-optimize reports draco, meshopt, none or source, and x-three-ws-optimize-refused appears when Draco was asked for and dropped for making the file worse. Those headers plus the byte counts are readable from browser code for the first time. Measured on the two production sample avatars: Draco went from +19.0% to 0.0% on one and from +14.6% to a real -4.4% saving on the other.</description>
+ </item>
<item>
<title>The Granite forecast tool now ships a copy-and-run example</title>
<link>https://three.ws/docs/ibm-x402-mcp</link>
diff --git a/public/features.json b/public/features.json
index 7a65762fd..1db7cc9be 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-08-13T16:31:41.075Z",
+ "generated_at": "2026-08-13T16:39:43.920Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/tests/avatar-optimize-never-inflates.test.js b/tests/avatar-optimize-never-inflates.test.js
new file mode 100644
index 000000000..4ef24612f
--- /dev/null
+++ b/tests/avatar-optimize-never-inflates.test.js
@@ -0,0 +1,164 @@
+// /api/avatar/optimize must never hand back more bytes than it was given.
+//
+// The defect this pins: our stored avatars ship meshopt-compressed, and
+// gltf-transform keeps EXT_meshopt_compression attached to the Document after
+// reading it. Calling draco() on top re-encoded the meshopt payload AND added
+// KHR_draco_mesh_compression beside it, so `?draco=1` returned files 17-19%
+// LARGER than the source with no indication that anything had gone wrong.
+// Measured on production 2026-08-01: default.glb 748,088 -> 890,160 (+19.0%),
+// michelle.glb 849,756 -> 974,036 (+14.6%).
+//
+// These tests build a real meshopt-compressed GLB in memory and run it through
+// the actual pipeline. No network, no fixture files: the source is constructed
+// with the same gltf-transform stack the handler uses, so the test reproduces
+// the exact "already compressed, now compress it again" shape.
+
+import { describe, expect, it, beforeAll } from 'vitest';
+import { Document, NodeIO } from '@gltf-transform/core';
+import { ALL_EXTENSIONS, EXTMeshoptCompression } from '@gltf-transform/extensions';
+import { quantize } from '@gltf-transform/functions';
+
+const { optimizeGlb } = await import('../api/avatar/optimize.js');
+
+// A mesh big enough that compression has something to work on. A handful of
+// triangles is dominated by JSON overhead and would prove nothing about size.
+const GRID = 48;
+
+function buildGrid(doc, scene) {
+ const positions = [];
+ const normals = [];
+ const uvs = [];
+ const indices = [];
+ for (let y = 0; y <= GRID; y++) {
+ for (let x = 0; x <= GRID; x++) {
+ // A gentle dome, so normals vary and the data is not trivially
+ // compressible into a constant.
+ const fx = x / GRID;
+ const fy = y / GRID;
+ const h = Math.sin(fx * Math.PI) * Math.sin(fy * Math.PI);
+ positions.push(fx - 0.5, h * 0.25, fy - 0.5);
+ normals.push(0, 1, 0);
+ uvs.push(fx, fy);
+ }
+ }
+ for (let y = 0; y < GRID; y++) {
+ for (let x = 0; x < GRID; x++) {
+ const a = y * (GRID + 1) + x;
+ const b = a + 1;
+ const c = a + GRID + 1;
+ const d = c + 1;
+ indices.push(a, c, b, b, c, d);
+ }
+ }
+
+ const buffer = doc.createBuffer();
+ const prim = doc
+ .createPrimitive()
+ .setAttribute('POSITION', doc.createAccessor().setType('VEC3').setArray(new Float32Array(positions)).setBuffer(buffer))
+ .setAttribute('NORMAL', doc.createAccessor().setType('VEC3').setArray(new Float32Array(normals)).setBuffer(buffer))
+ .setAttribute('TEXCOORD_0', doc.createAccessor().setType('VEC2').setArray(new Float32Array(uvs)).setBuffer(buffer))
+ .setIndices(doc.createAccessor().setType('SCALAR').setArray(new Uint32Array(indices)).setBuffer(buffer))
+ .setMaterial(doc.createMaterial('mat').setBaseColorFactor([0.8, 0.8, 0.8, 1]));
+
+ const mesh = doc.createMesh('grid').addPrimitive(prim);
+ scene.addChild(doc.createNode('grid').setMesh(mesh));
+}
+
+async function meshoptIo() {
+ const io = new NodeIO().registerExtensions(ALL_EXTENSIONS);
+ const meshopt = await import('meshoptimizer');
+ const dracoMod = await import('draco3dgltf');
+ const draco3d = dracoMod.default ?? dracoMod;
+ const [, , decoder, encoder] = await Promise.all([
+ meshopt.MeshoptEncoder.ready,
+ meshopt.MeshoptDecoder.ready,
+ draco3d.createDecoderModule(),
+ draco3d.createEncoderModule(),
+ ]);
+ return io.registerDependencies({
+ 'meshopt.encoder': meshopt.MeshoptEncoder,
+ 'meshopt.decoder': meshopt.MeshoptDecoder,
+ 'draco3d.decoder': decoder,
+ 'draco3d.encoder': encoder,
+ });
+}
+
+let meshoptSource;
+let plainSource;
+
+beforeAll(async () => {
+ const io = await meshoptIo();
+
+ const doc = new Document();
+ buildGrid(doc, doc.createScene('scene'));
+ plainSource = Buffer.from(await io.writeBinary(doc));
+
+ // The same model, quantized and then meshopt-packed: exactly what our stored
+ // avatars look like (KHR_mesh_quantization + EXT_meshopt_compression). Both
+ // halves matter. Without the quantization the old pipeline happened to shrink
+ // this mesh, so a size assertion alone would have passed against the bug;
+ // re-quantizing already-quantized attributes is what actually inflates.
+ const packed = new Document();
+ buildGrid(packed, packed.createScene('scene'));
+ await packed.transform(quantize());
+ packed
+ .createExtension(EXTMeshoptCompression)
+ .setRequired(true)
+ .setEncoderOptions({ method: EXTMeshoptCompression.EncoderMethod.QUANTIZE });
+ meshoptSource = Buffer.from(await io.writeBinary(packed));
+}, 120_000);
+
+describe('optimizeGlb size contract', () => {
+ it('builds a genuinely quantized, meshopt-compressed source to work from', () => {
+ expect(meshoptSource.byteLength).toBeGreaterThan(0);
+ // If either of these stops being true the rest of the file tests nothing:
+ // the bug only appears when both are present on the source.
+ expect(meshoptSource.includes(Buffer.from('EXT_meshopt_compression'))).toBe(true);
+ expect(meshoptSource.includes(Buffer.from('KHR_mesh_quantization'))).toBe(true);
+ });
+
+ it('never returns more bytes than it was given for draco=1 on a meshopt source', async () => {
+ const { bytes } = await optimizeGlb(meshoptSource, { draco: true });
+ expect(bytes.byteLength).toBeLessThanOrEqual(meshoptSource.byteLength);
+ });
+
+ it('never returns more bytes than it was given for a plain source', async () => {
+ const { bytes } = await optimizeGlb(plainSource, { draco: true });
+ expect(bytes.byteLength).toBeLessThanOrEqual(plainSource.byteLength);
+ });
+
+ it('emits at most one mesh-compression extension, never draco layered on meshopt', async () => {
+ const { bytes } = await optimizeGlb(meshoptSource, { draco: true });
+ const hasDraco = bytes.includes(Buffer.from('KHR_draco_mesh_compression'));
+ const hasMeshopt = bytes.includes(Buffer.from('EXT_meshopt_compression'));
+ expect(hasDraco && hasMeshopt).toBe(false);
+ });
+});
+
+describe('optimizeGlb reporting contract', () => {
+ it('names the scheme the caller actually received', async () => {
+ const { scheme } = await optimizeGlb(meshoptSource, { draco: true });
+ expect(['draco', 'meshopt', 'none', 'source']).toContain(scheme);
+ });
+
+ it('says draco was refused whenever draco was asked for and not applied', async () => {
+ const { scheme, refused } = await optimizeGlb(meshoptSource, { draco: true });
+ if (scheme === 'draco') {
+ expect(refused).toBeNull();
+ } else {
+ expect(refused).toBe('draco');
+ }
+ });
+
+ it('never claims a refusal when draco was not requested', async () => {
+ const { refused } = await optimizeGlb(meshoptSource, {});
+ expect(refused).toBeNull();
+ });
+
+ it('reports scheme "source" only when it returns the original bytes untouched', async () => {
+ const { bytes, scheme } = await optimizeGlb(meshoptSource, { draco: true });
+ if (scheme === 'source') {
+ expect(Buffer.from(bytes).equals(meshoptSource)).toBe(true);
+ }
+ });
+});