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 private GLB owner access; selfie quality UI; walk-embed + tests

nirholasedbf4dd98c21
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 67b71d897..565d6bfc3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,7 +8,11 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Pitch Deck** (`/pitch`) — The three.ws story as a presentable slide deck: one platform that gives any AI a real-time 3D body you can embed anywhere in one line. Arrow-key navigation, a live in-browser 3D character, and one-click export to PDF.
- **Chat embeds now load on any site** — The embed editor's Chat mode produced a snippet that worked in the live preview but stayed blank once pasted onto an external site. The agent chat page was served with a frame-ancestors policy that only allowed three.ws itself, so every other domain's browser blocked the iframe. Chat embeds now ship the same open framing policy as the avatar embed modes, and the embedded chat page can use the microphone for voice input. Paste the snippet anywhere and it just works. (`/embed`) `[fix]`
+- **Credits deposits: clearer 'verify by signature' copy** — The manual 'verify by signature' option on the Credits page now spells out how deposit verification actually works: we check on-chain that the transaction was signed by a wallet linked to your account, so only you can claim your deposit and pasting someone else's signature can never credit your balance. The old wording ('Sent from another wallet?') made the safe, server-verified flow look like anyone could claim any transfer — it never could. If you send from a wallet that isn't linked yet, the page now tells you to sign in with it or link it first. (`/credits`) `[improvement, security]`
+- **Forge: engine picker no longer overflows, clearer text-to-3D wording** — The Forge engine picker now wraps all eight lanes — NVIDIA, Hunyuan3D, Fast, Meshy, Tripo, Rodin, Stability, Replicate — cleanly inside its selector instead of spilling past the panel edge, so every engine stays readable at a glance. The build estimate is also honest to the tab you're on: on Describe it it reads 'renders a preview image, then builds 3D' (it never asked you for an image), and on From photos it reads 'builds from your reference photos'. (`/forge`) `[fix, improvement]`
+- **Live webinar stage on the IBM x402 demo page** — The IBM × three.ws demo page now opens with a webinar stage: a live countdown to the session, with one-click Add to Calendar (Google + .ics). When the talk goes live, the same stage becomes the player — a pre-recorded video plays synced to wall-clock like a broadcast premiere (everyone sees the same moment, latecomers join in progress), or a live feed streams in its place. The recording stays on the page afterward, and the x402 demos sit right below so you can watch and try them on one screen. (`/ibm/x402-demo`) `[feature]`
- **New doc: every NVIDIA model three.ws runs for free** — A new docs page maps the entire free NVIDIA inference layer the platform runs on — one free key unlocks all of it. It covers what each model does and where it's used: TRELLIS for free text→3D in Forge, FLUX.1-schnell for text→image, the Llama 3.3 / Nemotron / Llama 4 chat lineup in the Brain workbench, Nemotron vision for photo checks and alt-text, nv-embedqa embeddings for agent memory, the cross-encoder reranker, NemoGuard content safety, and Magpie multilingual text-to-speech. Each entry lists the model, the use case, and the free-first fallback behind it. (`/docs/nvidia-models`) `[docs]`
+- **Sharper selfie → avatar: your subject, isolated and reframed** — Selfie to Avatar now cleans up your photo before building. The moment you add a shot it checks for a clear face and warns you on the spot if it's a drawing, blurry, or too far away — so you can swap it before waiting on a build instead of after. Then it cuts you out from the background, drops you onto a neutral studio backdrop, and reframes to a centred head-and-shoulders crop. That's the composition the 3D engine reconstructs best, so results come back as a real, rounded avatar instead of the flat 'photo on a card' that busy backgrounds and tight face crops used to produce. It all runs in your browser — your raw photo isn't uploaded as-is. (`/create/selfie`) `[improvement]`
## 2026-06-21
diff --git a/api/avatars/[id]/[action].js b/api/avatars/[id]/[action].js
index 222eab753..a332c8e33 100644
--- a/api/avatars/[id]/[action].js
+++ b/api/avatars/[id]/[action].js
@@ -623,11 +623,16 @@ async function handleGlb(req, res) {
const id = req.query?.id || new URL(req.url, 'http://x').pathname.split('/').filter(Boolean)[2];
if (!id) return error(res, 400, 'invalid_request', 'avatar id required');
- const avatar = await getAvatar({ id, requesterId: null });
+ // Resolve the caller BEFORE the lookup: getAvatar() drops private avatars for
+ // non-owners (returns null), so passing requesterId: null here made the
+ // private branch below dead code — an owner could never fetch their own
+ // private GLB with a valid session/bearer. Thread the authenticated id in so
+ // the documented "private: owner only" contract actually holds.
+ const auth = await resolveVersionsAuth(req);
+ const avatar = await getAvatar({ id, requesterId: auth?.userId ?? null });
if (!avatar) return error(res, 404, 'not_found', 'avatar not found');
if (avatar.visibility === 'private') {
- const auth = await resolveVersionsAuth(req);
if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
if (auth.userId !== avatar.owner_id) return error(res, 403, 'forbidden', 'not your avatar');
}
diff --git a/data/changelog.json b/data/changelog.json
index 26c3841c5..6c0186515 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,34 @@
{
"$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-06-22",
+ "title": "Forge: engine picker no longer overflows, clearer text-to-3D wording",
+ "summary": "The Forge engine picker now wraps all eight lanes — NVIDIA, Hunyuan3D, Fast, Meshy, Tripo, Rodin, Stability, Replicate — cleanly inside its selector instead of spilling past the panel edge, so every engine stays readable at a glance. The build estimate is also honest to the tab you're on: on Describe it it reads 'renders a preview image, then builds 3D' (it never asked you for an image), and on From photos it reads 'builds from your reference photos'.",
+ "tags": ["fix", "improvement"],
+ "link": "/forge"
+ },
+ {
+ "date": "2026-06-22",
+ "title": "Sharper selfie → avatar: your subject, isolated and reframed",
+ "summary": "Selfie to Avatar now cleans up your photo before building. The moment you add a shot it checks for a clear face and warns you on the spot if it's a drawing, blurry, or too far away — so you can swap it before waiting on a build instead of after. Then it cuts you out from the background, drops you onto a neutral studio backdrop, and reframes to a centred head-and-shoulders crop. That's the composition the 3D engine reconstructs best, so results come back as a real, rounded avatar instead of the flat 'photo on a card' that busy backgrounds and tight face crops used to produce. It all runs in your browser — your raw photo isn't uploaded as-is.",
+ "tags": ["improvement"],
+ "link": "/create/selfie"
+ },
+ {
+ "date": "2026-06-22",
+ "title": "Credits deposits: clearer 'verify by signature' copy",
+ "summary": "The manual 'verify by signature' option on the Credits page now spells out how deposit verification actually works: we check on-chain that the transaction was signed by a wallet linked to your account, so only you can claim your deposit and pasting someone else's signature can never credit your balance. The old wording ('Sent from another wallet?') made the safe, server-verified flow look like anyone could claim any transfer — it never could. If you send from a wallet that isn't linked yet, the page now tells you to sign in with it or link it first.",
+ "tags": ["improvement", "security"],
+ "link": "/credits"
+ },
+ {
+ "date": "2026-06-22",
+ "title": "Live webinar stage on the IBM x402 demo page",
+ "summary": "The IBM × three.ws demo page now opens with a webinar stage: a live countdown to the session, with one-click Add to Calendar (Google + .ics). When the talk goes live, the same stage becomes the player — a pre-recorded video plays synced to wall-clock like a broadcast premiere (everyone sees the same moment, latecomers join in progress), or a live feed streams in its place. The recording stays on the page afterward, and the x402 demos sit right below so you can watch and try them on one screen.",
+ "tags": ["feature"],
+ "link": "/ibm/x402-demo"
+ },
{
"date": "2026-06-22",
"title": "New doc: every NVIDIA model three.ws runs for free",
diff --git a/pages/create-selfie.html b/pages/create-selfie.html
index 0cbf171a3..8edc5b49a 100644
--- a/pages/create-selfie.html
+++ b/pages/create-selfie.html
@@ -1971,6 +1971,67 @@
await import('/src/selfie-capture.js');
const pipeline = await import('/src/selfie-pipeline.js');
+ // ── Photo quality feedback ────────────────────────────────────────────
+ // Assess each frontal photo the moment it's added so the user can swap a
+ // drawing / blurry / no-face shot BEFORE waiting out a full build.
+ const { assessPhoto } = await import('/src/selfie-refine.js');
+ const qNotice = document.getElementById('quality-notice');
+ let _qSeq = 0;
+
+ function showQuality(kind, text) {
+ if (!qNotice) return;
+ if (!text) {
+ qNotice.hidden = true;
+ return;
+ }
+ qNotice.classList.remove('warn', 'good');
+ if (kind) qNotice.classList.add(kind);
+ qNotice.querySelector('.qn-text').textContent = text;
+ qNotice.hidden = false;
+ }
+
+ async function bitmapFromFile(file) {
+ if (typeof createImageBitmap === 'function') {
+ try {
+ return await createImageBitmap(file);
+ } catch (_) {}
+ }
+ return await new Promise((resolve, reject) => {
+ const img = new Image();
+ img.onload = () => resolve(img);
+ img.onerror = () => reject(new Error('decode failed'));
+ img.src = URL.createObjectURL(file);
+ });
+ }
+
+ document.addEventListener('selfie:photo-added', async (e) => {
+ const { slot, file } = e.detail || {};
+ if (slot !== 'frontal' || !file) return;
+ const seq = ++_qSeq;
+ showQuality(null, 'Checking your photo…');
+ try {
+ const bmp = await bitmapFromFile(file);
+ const a = await assessPhoto(bmp);
+ try {
+ bmp.close?.();
+ } catch (_) {}
+ if (seq !== _qSeq) return; // a newer photo superseded this check
+ if (a.verdict === 'good') showQuality('good', 'Looks great — clear face, good framing.');
+ else showQuality('warn', a.message);
+ } catch (_) {
+ if (seq === _qSeq) showQuality(null, '');
+ }
+ });
+
+ // Re-surface warnings discovered during the (higher-res) submit pass.
+ document.addEventListener('selfie:quality', (e) => {
+ const warnings = e.detail?.warnings || [];
+ const frontal = warnings.find((w) => w.slot === 'frontal') || warnings[0];
+ if (frontal) showQuality('warn', frontal.message);
+ });
+
+ document.addEventListener('selfie:reset', () => showQuality(null, ''));
+
// ── BYOK key entry form wiring ────────────────────────────────────────
let _selectedProvider = 'meshy';
diff --git a/pages/credits.html b/pages/credits.html
index 67d24ee62..e9f1a8958 100644
--- a/pages/credits.html
+++ b/pages/credits.html
@@ -487,9 +487,10 @@
<div class="status" id="status" role="status" aria-live="polite"></div>
<details class="manual">
- <summary>Sent from another wallet? Verify by signature</summary>
+ <summary>Already sent it yourself? Verify by signature</summary>
<p class="muted" style="font-size: 0.82rem; margin: 0.6rem 0 0.3rem">
- Send to this three.ws deposit wallet:
+ Send from a wallet linked to your account to this three.ws
+ deposit address, then paste the signature:
</p>
<div class="addr" id="deposit-addr">—</div>
<input
@@ -505,6 +506,12 @@
>
Verify deposit
</button>
+ <p class="muted" style="font-size: 0.76rem; margin: 0.5rem 0 0">
+ We verify on-chain that the transaction was signed by your
+ linked wallet, so only you can claim your deposit — pasting
+ someone else's signature won't credit your balance. Sent from a
+ wallet that isn't linked yet? Sign in with it or link it first.
+ </p>
</details>
</section>
</div>
diff --git a/pages/ibm/x402-demo.html b/pages/ibm/x402-demo.html
index f3324a6cb..b29d72387 100644
--- a/pages/ibm/x402-demo.html
+++ b/pages/ibm/x402-demo.html
@@ -556,7 +556,7 @@ agent-3d:defined ~ .agent-skel{display:none}
<div class="wb-fill wb-holding" id="wbHolding" hidden>
<div class="wb-spinner" aria-hidden="true"></div>
<h3 class="wb-stage-title">We're about to begin</h3>
- <p class="wb-soon">The stream goes live here any moment — this page refreshes itself, no need to reload.</p>
+ <p class="wb-soon">The stream will appear here the moment it starts.</p>
</div>
<!-- LIVE / REPLAY · player mounts here -->
@@ -762,8 +762,10 @@ agent-3d:defined ~ .agent-skel{display:none}
});
}
+ // Assign the interval BEFORE the first render() so an at/after-start load that
+ // clears it on the opening tick doesn't hit `timer` in its temporal dead zone.
+ let timer = setInterval(render, 1000);
render();
- const timer = setInterval(render, 1000);
})();
</script>
diff --git a/public/changelog.json b/public/changelog.json
index fdb1dcb10..a69e507c1 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-22T03:50:43.925Z",
+ "generated_at": "2026-06-22T04:19:07.101Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -26,6 +26,38 @@
"fix"
]
},
+ {
+ "date": "2026-06-22",
+ "type": "update",
+ "title": "Credits deposits: clearer 'verify by signature' copy",
+ "summary": "The manual 'verify by signature' option on the Credits page now spells out how deposit verification actually works: we check on-chain that the transaction was signed by a wallet linked to your account, so only you can claim your deposit and pasting someone else's signature can never credit your balance. The old wording ('Sent from another wallet?') made the safe, server-verified flow look like anyone could claim any transfer — it never could. If you send from a wallet that isn't linked yet, the page now tells you to sign in with it or link it first.",
+ "link": "/credits",
+ "tags": [
+ "improvement",
+ "security"
+ ]
+ },
+ {
+ "date": "2026-06-22",
+ "type": "update",
+ "title": "Forge: engine picker no longer overflows, clearer text-to-3D wording",
+ "summary": "The Forge engine picker now wraps all eight lanes — NVIDIA, Hunyuan3D, Fast, Meshy, Tripo, Rodin, Stability, Replicate — cleanly inside its selector instead of spilling past the panel edge, so every engine stays readable at a glance. The build estimate is also honest to the tab you're on: on Describe it it reads 'renders a preview image, then builds 3D' (it never asked you for an image), and on From photos it reads 'builds from your reference photos'.",
+ "link": "/forge",
+ "tags": [
+ "fix",
+ "improvement"
+ ]
+ },
+ {
+ "date": "2026-06-22",
+ "type": "update",
+ "title": "Live webinar stage on the IBM x402 demo page",
+ "summary": "The IBM × three.ws demo page now opens with a webinar stage: a live countdown to the session, with one-click Add to Calendar (Google + .ics). When the talk goes live, the same stage becomes the player — a pre-recorded video plays synced to wall-clock like a broadcast premiere (everyone sees the same moment, latecomers join in progress), or a live feed streams in its place. The recording stays on the page afterward, and the x402 demos sit right below so you can watch and try them on one screen.",
+ "link": "/ibm/x402-demo",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-06-22",
"type": "update",
@@ -36,6 +68,16 @@
"docs"
]
},
+ {
+ "date": "2026-06-22",
+ "type": "update",
+ "title": "Sharper selfie → avatar: your subject, isolated and reframed",
+ "summary": "Selfie to Avatar now cleans up your photo before building. The moment you add a shot it checks for a clear face and warns you on the spot if it's a drawing, blurry, or too far away — so you can swap it before waiting on a build instead of after. Then it cuts you out from the background, drops you onto a neutral studio backdrop, and reframes to a centred head-and-shoulders crop. That's the composition the 3D engine reconstructs best, so results come back as a real, rounded avatar instead of the flat 'photo on a card' that busy backgrounds and tight face crops used to produce. It all runs in your browser — your raw photo isn't uploaded as-is.",
+ "link": "/create/selfie",
+ "tags": [
+ "improvement"
+ ]
+ },
{
"date": "2026-06-21",
"type": "launch",
diff --git a/public/changelog.xml b/public/changelog.xml
index 42487917c..d35f0f022 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -22,6 +22,30 @@
<category>fix</category>
<description>The embed editor's Chat mode produced a snippet that worked in the live preview but stayed blank once pasted onto an external site. The agent chat page was served with a frame-ancestors policy that only allowed three.ws itself, so every other domain's browser blocked the iframe. Chat embeds now ship the same open framing policy as the avatar embed modes, and the embedded chat page can use the microphone for voice input. Paste the snippet anywhere and it just works.</description>
</item>
+ <item>
+ <title>Credits deposits: clearer 'verify by signature' copy</title>
+ <link>https://three.ws/credits</link>
+ <guid isPermaLink="false">2026-06-22:Credits deposits: clearer 'verify by signature' copy</guid>
+ <pubDate>Mon, 22 Jun 2026 12:00:00 GMT</pubDate>
+ <category>improvement</category>
+ <description>The manual 'verify by signature' option on the Credits page now spells out how deposit verification actually works: we check on-chain that the transaction was signed by a wallet linked to your account, so only you can claim your deposit and pasting someone else's signature can never credit your balance. The old wording ('Sent from another wallet?') made the safe, server-verified flow look like anyone could claim any transfer — it never could. If you send from a wallet that isn't linked yet, the page now tells you to sign in with it or link it first.</description>
+ </item>
+ <item>
+ <title>Forge: engine picker no longer overflows, clearer text-to-3D wording</title>
+ <link>https://three.ws/forge</link>
+ <guid isPermaLink="false">2026-06-22:Forge: engine picker no longer overflows, clearer text-to-3D wording</guid>
+ <pubDate>Mon, 22 Jun 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>The Forge engine picker now wraps all eight lanes — NVIDIA, Hunyuan3D, Fast, Meshy, Tripo, Rodin, Stability, Replicate — cleanly inside its selector instead of spilling past the panel edge, so every engine stays readable at a glance. The build estimate is also honest to the tab you're on: on Describe it it reads 'renders a preview image, then builds 3D' (it never asked you for an image), and on From photos it reads 'builds from your reference photos'.</description>
+ </item>
+ <item>
+ <title>Live webinar stage on the IBM x402 demo page</title>
+ <link>https://three.ws/ibm/x402-demo</link>
+ <guid isPermaLink="false">2026-06-22:Live webinar stage on the IBM x402 demo page</guid>
+ <pubDate>Mon, 22 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>The IBM × three.ws demo page now opens with a webinar stage: a live countdown to the session, with one-click Add to Calendar (Google + .ics). When the talk goes live, the same stage becomes the player — a pre-recorded video plays synced to wall-clock like a broadcast premiere (everyone sees the same moment, latecomers join in progress), or a live feed streams in its place. The recording stays on the page afterward, and the x402 demos sit right below so you can watch and try them on one screen.</description>
+ </item>
<item>
<title>New doc: every NVIDIA model three.ws runs for free</title>
<link>https://three.ws/docs/nvidia-models</link>
@@ -30,6 +54,14 @@
<category>docs</category>
<description>A new docs page maps the entire free NVIDIA inference layer the platform runs on — one free key unlocks all of it. It covers what each model does and where it's used: TRELLIS for free text→3D in Forge, FLUX.1-schnell for text→image, the Llama 3.3 / Nemotron / Llama 4 chat lineup in the Brain workbench, Nemotron vision for photo checks and alt-text, nv-embedqa embeddings for agent memory, the cross-encoder reranker, NemoGuard content safety, and Magpie multilingual text-to-speech. Each entry lists the model, the use case, and the free-first fallback behind it.</description>
</item>
+ <item>
+ <title>Sharper selfie → avatar: your subject, isolated and reframed</title>
+ <link>https://three.ws/create/selfie</link>
+ <guid isPermaLink="false">2026-06-22:Sharper selfie → avatar: your subject, isolated and reframed</guid>
+ <pubDate>Mon, 22 Jun 2026 12:00:00 GMT</pubDate>
+ <category>improvement</category>
+ <description>Selfie to Avatar now cleans up your photo before building. The moment you add a shot it checks for a clear face and warns you on the spot if it's a drawing, blurry, or too far away — so you can swap it before waiting on a build instead of after. Then it cuts you out from the background, drops you onto a neutral studio backdrop, and reframes to a centred head-and-shoulders crop. That's the composition the 3D engine reconstructs best, so results come back as a real, rounded avatar instead of the flat 'photo on a card' that busy backgrounds and tight face crops used to produce. It all runs in your browser — your raw photo isn't uploaded as-is.</description>
+ </item>
<item>
<title>Arm your agent — automate Oracle conviction</title>
<link>https://three.ws/oracle/arm</link>
diff --git a/public/features.json b/public/features.json
index 455aedf68..3b0286981 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-22T03:50:43.911Z",
+ "generated_at": "2026-06-22T04:19:07.071Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/src/walk-embed.js b/src/walk-embed.js
index 562d65de0..70005eb38 100644
--- a/src/walk-embed.js
+++ b/src/walk-embed.js
@@ -486,9 +486,30 @@ function getAvatarLoader() {
async function loadAvatar() {
setStatus('loading avatar…', { sticky: true });
- const avatarUrl = await resolveAvatarUrl();
+ const requestedUrl = await resolveAvatarUrl();
const loader = await getAvatarLoader();
- const gltf = await loader.loadAsync(avatarUrl);
+
+ // Honor the contract that the embed ALWAYS renders a walking body: if the
+ // requested avatar can't be fetched (deleted/expired id, a private avatar an
+ // anonymous host can't read, a typo'd id → 404, or a transient network
+ // failure) we fall back to the default avatar instead of leaving the host
+ // with an empty, all-black stage. The failure is still reported to the host
+ // over the typed bridge, and a legible status tells the viewer what happened.
+ let gltf;
+ let usedFallback = false;
+ try {
+ gltf = await loader.loadAsync(requestedUrl);
+ } catch (err) {
+ if (requestedUrl === AVATAR_URL_DEFAULT) throw err; // default itself failed — let boot's catch surface it
+ log.warn('[walk-embed] avatar load failed, falling back to default:', err?.message || err);
+ emit(OUTBOUND.ERROR, {
+ code: 'avatar_load_failed',
+ message: String(err?.message || err),
+ fallback: true,
+ });
+ usedFallback = true;
+ gltf = await loader.loadAsync(AVATAR_URL_DEFAULT);
+ }
avatar = gltf.scene;
avatar.traverse((n) => {
if (n.isMesh) {
@@ -533,9 +554,13 @@ async function loadAvatar() {
input.autoplay.t = 0;
}
- setStatus('walk it');
+ if (usedFallback) {
+ setStatus("couldn't load that avatar — showing the default", { sticky: true });
+ } else {
+ setStatus('walk it');
+ }
isReady = true;
- emit(OUTBOUND.READY, { avatarId: currentAvatarId, env: currentEnv });
+ emit(OUTBOUND.READY, { avatarId: currentAvatarId, env: currentEnv, fallback: usedFallback });
}
// ── Resize ────────────────────────────────────────────────────────────────
diff --git a/tests/selfie-refine.test.js b/tests/selfie-refine.test.js
new file mode 100644
index 000000000..e50370662
--- /dev/null
+++ b/tests/selfie-refine.test.js
@@ -0,0 +1,181 @@
+/**
+ * Selfie refinement — unit tests for the deterministic helpers.
+ *
+ * The DOM/MediaPipe wrappers (segmentation, detection, canvas compositing) are
+ * exercised in the browser; these tests pin the pure math that decides whether
+ * a photo is usable and how the subject gets framed — the logic that turns the
+ * "whole photo on a card" input into a clean, centred subject.
+ */
+
+import { describe, it, expect } from 'vitest';
+import {
+ laplacianVariance,
+ flatnessScore,
+ meanSaturation,
+ assessPhotoQuality,
+ computeSubjectFrame,
+ maskBoundingBox,
+ smoothstep,
+} from '../src/selfie-refine.js';
+
+// Build a w×h grey buffer from a (x,y)=>value fn.
+function grey(w, h, fn) {
+ const a = new Uint8Array(w * h);
+ for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) a[y * w + x] = fn(x, y) | 0;
+ return a;
+}
+// Build a w×h RGBA buffer from a (x,y)=>[r,g,b,a] fn.
+function rgba(w, h, fn) {
+ const a = new Uint8ClampedArray(w * h * 4);
+ for (let y = 0; y < h; y++)
+ for (let x = 0; x < w; x++) {
+ const [r, g, b, al = 255] = fn(x, y);
+ const i = (y * w + x) * 4;
+ a[i] = r; a[i + 1] = g; a[i + 2] = b; a[i + 3] = al;
+ }
+ return a;
+}
+
+describe('laplacianVariance', () => {
+ it('is ~0 for a flat image', () => {
+ expect(laplacianVariance(grey(16, 16, () => 128), 16, 16)).toBe(0);
+ });
+
+ it('is higher for an edged image than a flat one', () => {
+ const flat = laplacianVariance(grey(16, 16, () => 128), 16, 16);
+ const edged = laplacianVariance(grey(16, 16, (x) => (x < 8 ? 0 : 255)), 16, 16);
+ expect(edged).toBeGreaterThan(flat);
+ });
+
+ it('returns 0 on degenerate sizes', () => {
+ expect(laplacianVariance(grey(2, 2, () => 50), 2, 2)).toBe(0);
+ });
+});
+
+describe('flatnessScore', () => {
+ it('is 1 for a perfectly flat image', () => {
+ expect(flatnessScore(grey(12, 12, () => 90), 12, 12)).toBe(1);
+ });
+
+ it('is low for a high-frequency checkerboard', () => {
+ const checker = grey(12, 12, (x, y) => ((x + y) % 2 ? 255 : 0));
+ expect(flatnessScore(checker, 12, 12)).toBeLessThan(0.1);
+ });
+});
+
+describe('meanSaturation', () => {
+ it('is 0 for greyscale', () => {
+ expect(meanSaturation(rgba(8, 8, () => [120, 120, 120]), 8, 8, 1)).toBe(0);
+ });
+
+ it('is ~1 for fully saturated red', () => {
+ expect(meanSaturation(rgba(8, 8, () => [255, 0, 0]), 8, 8, 1)).toBeCloseTo(1, 5);
+ });
+});
+
+describe('assessPhotoQuality', () => {
+ const sharpClearFace = {
+ width: 1000, height: 1000,
+ faceCount: 1,
+ faceBox: { x: 350, y: 300, w: 300, h: 300 },
+ sharpness: 500, flatness: 0.2, saturation: 0.2,
+ };
+
+ it('blocks when there is no face', () => {
+ const r = assessPhotoQuality({ ...sharpClearFace, faceCount: 0, faceBox: null });
+ expect(r.verdict).toBe('block');
+ expect(r.primary).toBe('no-face');
+ });
+
+ it('passes a sharp, well-framed real photo', () => {
+ const r = assessPhotoQuality(sharpClearFace);
+ expect(r.verdict).toBe('good');
+ expect(r.issues).toEqual([]);
+ });
+
+ it('warns "blurry" on a soft photo', () => {
+ const r = assessPhotoQuality({ ...sharpClearFace, sharpness: 10 });
+ expect(r.verdict).toBe('warn');
+ expect(r.primary).toBe('blurry');
+ });
+
+ it('flags a flat, saturated illustration', () => {
+ const r = assessPhotoQuality({ ...sharpClearFace, flatness: 0.85, saturation: 0.6 });
+ expect(r.issues).toContain('illustration');
+ expect(r.primary).toBe('illustration'); // illustration outranks other warnings
+ });
+
+ it('does NOT flag a plain-background photo as an illustration (flat but desaturated)', () => {
+ const r = assessPhotoQuality({ ...sharpClearFace, flatness: 0.85, saturation: 0.1 });
+ expect(r.issues).not.toContain('illustration');
+ });
+
+ it('warns "far" when the face is small in frame', () => {
+ const r = assessPhotoQuality({ ...sharpClearFace, faceBox: { x: 470, y: 470, w: 90, h: 90 } });
+ expect(r.issues).toContain('far');
+ });
+});
+
+describe('computeSubjectFrame', () => {
+ it('returns a centred square within bounds for a centred face', () => {
+ const f = computeSubjectFrame({ x: 400, y: 300, w: 200, h: 200 }, 1000, 1000);
+ expect(f.w).toBe(f.h);
+ expect(f.x).toBeGreaterThanOrEqual(0);
+ expect(f.y).toBeGreaterThanOrEqual(0);
+ expect(f.x + f.w).toBeLessThanOrEqual(1000);
+ expect(f.y + f.h).toBeLessThanOrEqual(1000);
+ // Horizontally centred on the face centre (500).
+ expect(f.x + f.w / 2).toBeCloseTo(500, 0);
+ });
+
+ it('clamps a square against the right edge without overflow', () => {
+ const f = computeSubjectFrame({ x: 900, y: 300, w: 200, h: 200 }, 1000, 1000);
+ expect(f.x + f.w).toBeLessThanOrEqual(1000);
+ expect(f.w).toBe(f.h);
+ });
+
+ it('fits the largest square inside a small image', () => {
+ const f = computeSubjectFrame({ x: 150, y: 80, w: 120, h: 120 }, 400, 300);
+ expect(f.w).toBe(f.h);
+ expect(f.w).toBeLessThanOrEqual(300);
+ expect(f.x + f.w).toBeLessThanOrEqual(400);
+ expect(f.y + f.h).toBeLessThanOrEqual(300);
+ });
+
+ it('widens to include a broad subject (shoulders)', () => {
+ const narrow = computeSubjectFrame({ x: 450, y: 300, w: 100, h: 100 }, 2000, 2000);
+ const wide = computeSubjectFrame({ x: 450, y: 300, w: 100, h: 100 }, 2000, 2000, {
+ subjectBox: { x: 200, y: 250, w: 1000, h: 1200 },
+ });
+ expect(wide.w).toBeGreaterThan(narrow.w);
+ });
+});
+
+describe('maskBoundingBox', () => {
+ it('scales the foreground box into image space', () => {
+ // 4×4 mask, a 2×2 foreground block at (1,1)-(2,2); image is 8×8 (scale 2).
+ const mask = new Float32Array(16);
+ for (const [x, y] of [[1, 1], [2, 1], [1, 2], [2, 2]]) mask[y * 4 + x] = 1;
+ const box = maskBoundingBox(mask, 4, 4, 8, 8, 0.5);
+ expect(box).toEqual({ x: 2, y: 2, w: 4, h: 4 });
+ });
+
+ it('returns null when nothing crosses the threshold', () => {
+ expect(maskBoundingBox(new Float32Array(16), 4, 4, 8, 8, 0.5)).toBeNull();
+ });
+});
+
+describe('smoothstep', () => {
+ it('clamps below/above the edges', () => {
+ expect(smoothstep(0, 1, -2)).toBe(0);
+ expect(smoothstep(0, 1, 5)).toBe(1);
+ });
+ it('is 0.5 at the midpoint and monotonic', () => {
+ expect(smoothstep(0, 1, 0.5)).toBeCloseTo(0.5, 5);
+ expect(smoothstep(0, 1, 0.25)).toBeLessThan(smoothstep(0, 1, 0.75));
+ });
+ it('degenerates to a step when edges are equal', () => {
+ expect(smoothstep(0.5, 0.5, 0.4)).toBe(0);
+ expect(smoothstep(0.5, 0.5, 0.6)).toBe(1);
+ });
+});