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 script to build animation thumbnails and harness for rendering

fudjiaab961e38c5d4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 448b252b3..550cdecc2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **@three-ws/retarget — the animation engine behind every avatar, now a standalone package** — The rig-agnostic animation system that powers all three.ws avatars is now on npm as @three-ws/retarget. It maps bone names from Mixamo, VRM/VRoid, Avaturn, Daz, MakeHuman, Unreal, and Blender rigs onto one canonical skeleton, retargets any clip onto any humanoid with rest-pose and hip-axis correction, and ships the crossfading runtime that keeps characters from ever freezing in a T-pose. Only dependency: your own copy of Three.js. Same engine, same tests (2,800 lines of them) — now usable in any Three.js project. `[sdk, feature]`
- **2,000+ new motion-capture animations in the library** — The animation library just grew from around 100 curated clips to over 2,000 — the full professional motion-capture set, every one retargeted to the universal three.ws skeleton so it plays on any humanoid avatar. Walks, runs, dances, combat, idles, reactions, sports, and hundreds more are all searchable in the animations gallery, previewable on a live avatar, and one click away from the pose studio or any embed. The clips are served from the CDN, so the site stays fast no matter how big the library gets. (`/animations`) `[feature, improvement]`
+- **Agent creation now tells you what to do when your avatar library is full** — If you hit your plan's avatar limit while creating an agent, the wizard used to fail with a bare error and leave you stuck. It now explains what happened and gives you three ways forward, right in the form: connect an avatar you already own (one click jumps you to your library), free up a slot by deleting an old avatar, or upgrade your plan. Oversized model files get a clearer message too. (`/create-agent`) `[fix, improvement]`
- **Status page no longer reports a phantom outage — and graduation tracking runs clean** — The public status page had been showing the x402 paid-API discovery feed and the 3D viewer as down for days while both were actually healthy: the uptime monitor was probing two URLs that never existed. The probes now hit the real public paths, and the falsely-recorded downtime history is purged so the 90-day uptime bars reflect the services, not the monitor bug. The pump.fun graduation tracker was also timing out on every heartbeat tick because it listened longer than the heartbeat allows — it now fits its budget and reports a clean run. (`/status`) `[fix, infra]`
- **The agent economy now watches itself and pages the team** — After weeks of the agent-to-agent economy silently stalling and being diagnosed hours late, the platform now monitors it as a system: every 5 minutes it checks that the per-minute heartbeat is alive, that no engine is failing or stuck on a fixable problem (missing config, an unfundable payment, a full database), and that real on-chain agent activity is still flowing. Any of those pages the ops channel immediately, keeps re-paging hourly until fixed, and announces recovery. The status page's JSON feed also keeps 24 hours of health history so anyone can see exactly when a stall began. `[improvement, infra]`
- **The sniper engine now pages us when it goes down — and restarts itself** — The on-chain sniper worker went quiet on July 3 and nothing noticed: the status page showed the engine offline and zero launches scored, but no alert fired. The platform's watchdog now checks the sniper's own heartbeat every 5 minutes and pages the ops channel within 10 minutes of a stall, with hourly re-pages until it recovers. The worker also gained a dead-man switch: if it loses its database for 15 minutes straight it restarts itself instead of running as a zombie that scores nothing. (`/status`) `[fix, infra]`
diff --git a/api/_lib/migrations/20260705120000_plan_intent_multi_asset.sql b/api/_lib/migrations/20260705120000_plan_intent_multi_asset.sql
new file mode 100644
index 000000000..681d94562
--- /dev/null
+++ b/api/_lib/migrations/20260705120000_plan_intent_multi_asset.sql
@@ -0,0 +1,41 @@
+-- Plan checkout in SOL and $THREE, not just USDC.
+--
+-- plan_payment_intents was built USDC-only: amount_usdc doubled as both the
+-- USD price and the on-chain amount (USDC is 1:1). Paying in SOL or $THREE
+-- needs the two separated: the USD value charged stays in amount_usdc, and the
+-- exact on-chain amount of the chosen asset (quoted at checkout from the live
+-- price) is pinned in amount_asset, with the quote price recorded for audit.
+--
+-- Idempotent.
+
+BEGIN;
+
+-- Which asset this intent is denominated in. Existing rows are all USDC.
+ALTER TABLE plan_payment_intents
+ ADD COLUMN IF NOT EXISTS asset text NOT NULL DEFAULT 'USDC';
+
+-- Exact on-chain amount of `asset` expected, in human units (SOL, $THREE, or
+-- USDC). Pinned at checkout so a price move during the session can't change
+-- what the user owes. NULL on legacy rows — the USDC paths derive it from
+-- amount_usdc.
+ALTER TABLE plan_payment_intents
+ ADD COLUMN IF NOT EXISTS amount_asset numeric(30, 9);
+
+-- USD price of one unit of `asset` at quote time (audit trail for SOL/$THREE
+-- quotes). NULL for USDC (always 1).
+ALTER TABLE plan_payment_intents
+ ADD COLUMN IF NOT EXISTS asset_price_usd numeric(18, 9);
+
+DO $$
+BEGIN
+ IF NOT EXISTS (
+ SELECT 1 FROM pg_constraint
+ WHERE conname = 'plan_payment_intents_asset_check'
+ ) THEN
+ ALTER TABLE plan_payment_intents
+ ADD CONSTRAINT plan_payment_intents_asset_check
+ CHECK (asset IN ('USDC', 'SOL', 'THREE'));
+ END IF;
+END $$;
+
+COMMIT;
diff --git a/api/_lib/schema.sql b/api/_lib/schema.sql
index dc0612187..f83bf3c99 100644
--- a/api/_lib/schema.sql
+++ b/api/_lib/schema.sql
@@ -1201,7 +1201,10 @@ create table if not exists plan_payment_intents (
plan text not null check (plan in ('pro', 'team', 'enterprise')),
chain_type text not null check (chain_type in ('evm', 'solana')),
chain_id integer,
- amount_usdc numeric(12,6) not null, -- exact USDC amount expected
+ amount_usdc numeric(12,6) not null, -- USD value charged (equals the USDC amount on USDC intents)
+ asset text not null default 'USDC' check (asset in ('USDC', 'SOL', 'THREE')),
+ amount_asset numeric(30,9), -- exact on-chain amount of `asset` expected, human units (null on legacy USDC rows)
+ asset_price_usd numeric(18,9), -- USD price of one unit of `asset` at quote time (null for USDC)
recipient text not null, -- address/pubkey that should receive payment
nonce text not null unique, -- random, prevents replay
memo text, -- Solana Pay memo / EVM calldata hint
diff --git a/api/payments/_config.js b/api/payments/_config.js
index 47bfbfd7b..78de0a2b0 100644
--- a/api/payments/_config.js
+++ b/api/payments/_config.js
@@ -1,12 +1,37 @@
// Shared payment configuration.
-// All prices are in USDC (6 decimals on EVM, 6 decimals on Solana SPL).
+// Prices are set in USD. On-chain settlement is USDC (6 decimals on EVM and
+// Solana), native SOL, or $THREE (Solana-only; see PLAN_ASSETS below).
export const PLANS = {
- pro: { label: 'Pro', price_usd: 19, duration_days: 30 },
+ // Single source of truth for plan prices — pages/pricing.html and
+ // pages/x-pricing.html render what checkout quotes from here.
+ pro: { label: 'Pro', price_usd: 49, duration_days: 30 },
team: { label: 'Team', price_usd: 79, duration_days: 30 },
enterprise: { label: 'Enterprise', price_usd: 299, duration_days: 30 },
};
+// Assets accepted for plan checkout on Solana. USDC settles 1:1 with the USD
+// price; SOL and $THREE are quoted at the live price when the checkout session
+// is created and the exact on-chain amount is pinned on the intent.
+export const PLAN_ASSETS = ['USDC', 'SOL', 'THREE'];
+
+// Paying in $THREE takes a discount off the USD price — $THREE is the
+// platform's coin and plan revenue in it feeds the treasury loop directly.
+// Basis points; 2000 = 20% off. Override with THREE_PLAN_DISCOUNT_BPS.
+export function threePlanDiscountBps() {
+ const raw = Number(process.env.THREE_PLAN_DISCOUNT_BPS);
+ if (Number.isFinite(raw) && raw >= 0 && raw <= 5000) return Math.floor(raw);
+ return 2000;
+}
+
+/** USD value charged for a plan when paying in `asset` ($THREE discount applied). */
+export function planPriceUsd(plan, asset = 'USDC') {
+ const base = PLANS[plan].price_usd;
+ if (asset !== 'THREE') return base;
+ const usd = (base * (10_000 - threePlanDiscountBps())) / 10_000;
+ return Math.round(usd * 100) / 100;
+}
+
// USDC contract addresses by EVM chain ID.
export const EVM_USDC = {
1: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // Ethereum
@@ -33,6 +58,11 @@ export function getSolanaRecipient() {
// How long a checkout session stays valid.
export const INTENT_TTL_MINUTES = 30;
+// Price-quoted assets (SOL, $THREE) pin the on-chain amount at checkout, so
+// their sessions are shorter — a 30-minute-old quote on a moving market would
+// over- or under-charge. The client just re-creates the checkout on expiry.
+export const QUOTED_INTENT_TTL_MINUTES = 10;
+
// USDC has 6 decimals on both EVM and Solana.
export function toUsdcAtomics(usd) {
return BigInt(Math.round(usd * 1_000_000));
diff --git a/api/payments/solana/[action].js b/api/payments/solana/[action].js
index 8174286f2..03e9831c6 100644
--- a/api/payments/solana/[action].js
+++ b/api/payments/solana/[action].js
@@ -9,15 +9,43 @@ import { limits, clientIp } from '../../_lib/rate-limit.js';
import { parse } from '../../_lib/validate.js';
import { randomToken } from '../../_lib/crypto.js';
import { sendSubscriptionConfirmEmail } from '../../_lib/email.js';
-import { PLANS, SOLANA_USDC_MINT, getSolanaRecipient, INTENT_TTL_MINUTES } from '../_config.js';
+import { TOKEN_MINT as THREE_MINT, TOKEN_DECIMALS as THREE_DECIMALS } from '../../_lib/token/config.js';
+import { getTokenPriceUsd } from '../../_lib/token/price.js';
+import { solanaMintUsdPrice } from '../../_lib/balances.js';
+import {
+ PLANS, PLAN_ASSETS, SOLANA_USDC_MINT, getSolanaRecipient,
+ INTENT_TTL_MINUTES, QUOTED_INTENT_TTL_MINUTES,
+ planPriceUsd, threePlanDiscountBps,
+} from '../_config.js';
const SOLANA_RPC_MAINNET = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
const SOLANA_RPC_DEVNET = process.env.SOLANA_RPC_URL_DEVNET || 'https://api.devnet.solana.com';
+const SOL_NATIVE_MINT = 'So11111111111111111111111111111111111111112';
+const LAMPORTS_PER_SOL = 1_000_000_000n;
+
+// Exact decimal string for `atomics` at `decimals` — Solana Pay amounts must be
+// plain decimals (no scientific notation, no float drift).
+function atomicsToDecimalString(atomics, decimals) {
+ const base = 10n ** BigInt(decimals);
+ const whole = atomics / base;
+ const frac = (atomics % base).toString().padStart(decimals, '0').replace(/0+$/, '');
+ return frac ? `${whole}.${frac}` : whole.toString();
+}
+
+// Ceil so a live-price quote never rounds the payment below the USD price.
+function usdToAtomicsCeil(usd, assetPriceUsd, decimals) {
+ return BigInt(Math.ceil((usd / assetPriceUsd) * 10 ** decimals));
+}
+
// ── checkout ──────────────────────────────────────────────────────────────────
const checkoutSchema = z.object({
plan: z.enum(['pro', 'team', 'enterprise']),
+ // USDC settles 1:1 with the USD price. SOL and $THREE are quoted at the
+ // live market price when the session is created; paying in $THREE takes the
+ // platform-coin discount (threePlanDiscountBps).
+ asset: z.enum(['USDC', 'SOL', 'THREE']).default('USDC'),
// Devnet is only accepted in non-production environments. Accepting devnet
// USDC (free from faucet) in production would let anyone upgrade for free.
network: z.enum(process.env.NODE_ENV === 'production' ? ['mainnet'] : ['mainnet', 'devnet']).default('mainnet'),
@@ -31,22 +59,66 @@ async function handleCheckout(req, res) {
const rl = await limits.authIp(clientIp(req));
if (!rl.success) return rateLimited(res, rl);
const body = parse(checkoutSchema, await readJson(req));
- const { plan, network } = body;
+ const { plan, asset, network } = body;
const recipient = getSolanaRecipient();
if (!recipient) return error(res, 503, 'not_configured', 'Solana payment recipient not configured');
+ // $THREE only exists on mainnet — a devnet $THREE intent could never confirm.
+ if (asset === 'THREE' && network === 'devnet') return error(res, 400, 'bad_request', '$THREE payments are mainnet-only');
const planConfig = PLANS[plan];
- const amountUsdc = planConfig.price_usd;
- const nonce = await randomToken(16);
- const expiresAt = new Date(Date.now() + INTENT_TTL_MINUTES * 60 * 1000);
+ const amountUsd = planPriceUsd(plan, asset);
+
+ // Resolve the on-chain amount for the chosen asset.
const usdcMint = network === 'devnet' ? '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU' : SOLANA_USDC_MINT;
- const [intent] = await sql`insert into plan_payment_intents (user_id, plan, chain_type, amount_usdc, recipient, nonce, memo, expires_at) values (${user.id}, ${plan}, 'solana', ${amountUsdc}, ${recipient}, ${nonce}, ${nonce}, ${expiresAt}) returning id, nonce, amount_usdc, recipient, expires_at`;
+ let mint = null; // spl-token mint, null for native SOL
+ let decimals;
+ let assetPriceUsd = null; // live quote price, null for USDC (always 1)
+ if (asset === 'USDC') {
+ mint = usdcMint;
+ decimals = 6;
+ } else if (asset === 'SOL') {
+ decimals = 9;
+ assetPriceUsd = await solanaMintUsdPrice(SOL_NATIVE_MINT);
+ if (!(assetPriceUsd > 0)) return error(res, 503, 'price_unavailable', 'live SOL price unavailable — try again shortly');
+ } else {
+ mint = THREE_MINT;
+ decimals = THREE_DECIMALS;
+ const p = await getTokenPriceUsd().catch(() => null);
+ assetPriceUsd = p?.priceUsd;
+ if (!(assetPriceUsd > 0)) return error(res, 503, 'price_unavailable', 'live $THREE price unavailable — try again shortly');
+ }
+ const atomics = asset === 'USDC'
+ ? BigInt(Math.round(amountUsd * 1_000_000))
+ : usdToAtomicsCeil(amountUsd, assetPriceUsd, decimals);
+ const amountAsset = atomicsToDecimalString(atomics, decimals);
+
+ const nonce = await randomToken(16);
+ // Live-price quotes expire faster: the pinned amount drifts from the market.
+ const ttlMinutes = asset === 'USDC' ? INTENT_TTL_MINUTES : QUOTED_INTENT_TTL_MINUTES;
+ const expiresAt = new Date(Date.now() + ttlMinutes * 60 * 1000);
+ const [intent] = await sql`insert into plan_payment_intents (user_id, plan, chain_type, amount_usdc, asset, amount_asset, asset_price_usd, recipient, nonce, memo, expires_at) values (${user.id}, ${plan}, 'solana', ${amountUsd}, ${asset}, ${amountAsset}, ${assetPriceUsd}, ${recipient}, ${nonce}, ${nonce}, ${expiresAt}) returning id, nonce, expires_at`;
const solanaPay = new URL(`solana:${recipient}`);
- solanaPay.searchParams.set('amount', String(amountUsdc));
- solanaPay.searchParams.set('spl-token', usdcMint);
+ solanaPay.searchParams.set('amount', amountAsset);
+ if (mint) solanaPay.searchParams.set('spl-token', mint);
solanaPay.searchParams.set('memo', nonce);
solanaPay.searchParams.set('label', 'three.ws');
solanaPay.searchParams.set('message', `${planConfig.label} plan subscription`);
- return json(res, 201, { intent_id: intent.id, plan, network, solana_pay_url: solanaPay.toString(), recipient, usdc_mint: usdcMint, amount_usdc: amountUsdc, nonce, expires_at: intent.expires_at });
+ return json(res, 201, {
+ intent_id: intent.id,
+ plan,
+ asset,
+ network,
+ solana_pay_url: solanaPay.toString(),
+ recipient,
+ mint,
+ usdc_mint: asset === 'USDC' ? usdcMint : undefined, // legacy field for existing clients
+ amount_asset: amountAsset,
+ amount_usd: amountUsd,
+ amount_usdc: asset === 'USDC' ? amountUsd : undefined, // legacy field
+ asset_price_usd: assetPriceUsd,
+ discount_bps: asset === 'THREE' ? threePlanDiscountBps() : 0,
+ nonce,
+ expires_at: intent.expires_at,
+ });
}
// ── confirm ───────────────────────────────────────────────────────────────────
@@ -69,8 +141,15 @@ async function handleConfirm(req, res) {
const [intent] = await sql`select * from plan_payment_intents where id = ${intent_id} and user_id = ${user.id} and chain_type = 'solana' limit 1`;
if (!intent) return error(res, 404, 'not_found', 'intent not found');
if (intent.status === 'confirmed') return error(res, 409, 'already_confirmed', 'payment already confirmed');
- if (intent.status === 'expired' || new Date(intent.expires_at) < new Date()) {
- await sql`update plan_payment_intents set status='expired' where id=${intent_id}`;
+ if (intent.status === 'failed') return error(res, 410, 'intent_expired', 'payment session is no longer usable');
+ // The client hides the payment UI the moment the quote expires, so a confirm
+ // arriving after expires_at is almost always a payment sent just before the
+ // quote lapsed (plus finalization time). Honor it within a bounded grace
+ // window instead of stranding the funds — the on-chain amount was pinned at
+ // quote time, so the window caps price-drift exposure, not the price.
+ const CONFIRM_GRACE_MS = 60 * 60 * 1000;
+ if (new Date(intent.expires_at).getTime() + CONFIRM_GRACE_MS < Date.now()) {
+ await sql`update plan_payment_intents set status='expired' where id=${intent_id} and status='pending'`;
return error(res, 410, 'intent_expired', 'payment session expired');
}
const rpcUrl = network === 'devnet' ? SOLANA_RPC_DEVNET : SOLANA_RPC_MAINNET;
@@ -91,35 +170,55 @@ async function handleConfirm(req, res) {
const memo = typeof memoIx?.parsed === 'string' ? memoIx.parsed : null;
if (!memo || memo !== intent.nonce) return error(res, 422, 'memo_mismatch', 'transaction memo does not match intent nonce');
const expectedRecipient = intent.recipient;
- const expectedAtomics = BigInt(Math.round(Number(intent.amount_usdc) * 1_000_000));
- const tokenBalances = tx.meta?.postTokenBalances || [];
- const preBalances = tx.meta?.preTokenBalances || [];
- const matchingTransfer = tx.transaction.message.instructions.find((ix) => {
- if (ix.programId?.toString() !== 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA') return false;
- const parsed = ix.parsed;
- if (parsed?.type !== 'transferChecked' && parsed?.type !== 'transfer') return false;
- const info = parsed.info;
- // Require an explicit mint match. `type='transfer'` (legacy Token Program)
- // omits mint from parsed.info — we reject it rather than accepting any token.
- // The balance-delta fallback below correctly requires post.mint === usdcMint.
- const mintMatch = info.mint === usdcMint;
- const amount = BigInt(info.tokenAmount?.amount ?? info.amount ?? '0');
- return mintMatch && amount >= expectedAtomics && (info.destination === expectedRecipient || info.destinationOwner === expectedRecipient);
- });
- let verifiedViaBalance = false;
- if (!matchingTransfer) {
- for (const post of tokenBalances) {
- if (post.mint !== usdcMint) continue;
- const pre = preBalances.find((p) => p.accountIndex === post.accountIndex);
- const delta = BigInt(post.uiTokenAmount.amount) - BigInt(pre?.uiTokenAmount?.amount ?? '0');
- if (delta >= expectedAtomics) {
- const accountKeys = tx.transaction.message.accountKeys;
- const owner = accountKeys[post.accountIndex]?.pubkey?.toString();
- if (owner === expectedRecipient || post.owner === expectedRecipient) { verifiedViaBalance = true; break; }
+
+ // Which asset this intent is denominated in, and the exact on-chain amount
+ // owed. Legacy USDC rows predate amount_asset — their amount is amount_usdc
+ // itself (USDC settles 1:1 with USD).
+ const asset = intent.asset || 'USDC';
+ const mint = asset === 'USDC' ? usdcMint : asset === 'THREE' ? THREE_MINT : null;
+ const decimals = asset === 'USDC' ? 6 : asset === 'THREE' ? THREE_DECIMALS : 9;
+ const expectedAtomics = BigInt(Math.round(Number(intent.amount_asset ?? intent.amount_usdc) * 10 ** decimals));
+
+ let paid = false;
+ if (asset === 'SOL') {
+ // Native SOL: verify via the recipient's lamport balance delta —
+ // index-aligned pre/post balances cover every transfer variant.
+ const keys = tx.transaction.message.accountKeys || [];
+ const idx = keys.findIndex((k) => (k?.pubkey?.toString?.() || String(k?.pubkey ?? '')) === expectedRecipient);
+ if (idx >= 0) {
+ const delta = BigInt(tx.meta?.postBalances?.[idx] ?? 0) - BigInt(tx.meta?.preBalances?.[idx] ?? 0);
+ paid = delta >= expectedAtomics;
+ }
+ } else {
+ const tokenBalances = tx.meta?.postTokenBalances || [];
+ const preBalances = tx.meta?.preTokenBalances || [];
+ const matchingTransfer = tx.transaction.message.instructions.find((ix) => {
+ if (ix.programId?.toString() !== 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA') return false;
+ const parsed = ix.parsed;
+ if (parsed?.type !== 'transferChecked' && parsed?.type !== 'transfer') return false;
+ const info = parsed.info;
+ // Require an explicit mint match. `type='transfer'` (legacy Token Program)
+ // omits mint from parsed.info — we reject it rather than accepting any token.
+ // The balance-delta fallback below correctly requires post.mint === mint.
+ const mintMatch = info.mint === mint;
+ const amount = BigInt(info.tokenAmount?.amount ?? info.amount ?? '0');
+ return mintMatch && amount >= expectedAtomics && (info.destination === expectedRecipient || info.destinationOwner === expectedRecipient);
+ });
+ paid = Boolean(matchingTransfer);
+ if (!paid) {
+ for (const post of tokenBalances) {
+ if (post.mint !== mint) continue;
+ const pre = preBalances.find((p) => p.accountIndex === post.accountIndex);
+ const delta = BigInt(post.uiTokenAmount.amount) - BigInt(pre?.uiTokenAmount?.amount ?? '0');
+ if (delta >= expectedAtomics) {
+ const accountKeys = tx.transaction.message.accountKeys;
+ const owner = accountKeys[post.accountIndex]?.pubkey?.toString();
+ if (owner === expectedRecipient || post.owner === expectedRecipient) { paid = true; break; }
+ }
}
}
}
- if (!matchingTransfer && !verifiedViaBalance) return error(res, 422, 'transfer_not_found', `No USDC transfer of ${intent.amount_usdc} to ${expectedRecipient} found in tx`);
+ if (!paid) return error(res, 422, 'transfer_not_found', `No ${asset === 'THREE' ? '$THREE' : asset} transfer of ${intent.amount_asset ?? intent.amount_usdc} to ${expectedRecipient} found in tx`);
// Atomically claim the intent: the status read at the top and this write are
// not in one transaction, so two concurrent confirms for the same intent could
// both pass the status guard. The conditional UPDATE lets exactly one win; if
@@ -130,18 +229,38 @@ async function handleConfirm(req, res) {
const planConfig = PLANS[intent.plan];
const activeUntil = new Date(Date.now() + planConfig.duration_days * 86400 * 1000);
const [claimed] = await sql.transaction([
- sql`update plan_payment_intents set status='confirmed', tx_hash=${tx_signature}, confirmed_at=now() where id=${intent_id} and status = 'pending' returning id`,
- sql`insert into subscriptions (user_id, plan, chain_type, token_address, tx_hash, amount_usd, status, active_until) values (${user.id}, ${intent.plan}, 'solana', ${usdcMint}, ${tx_signature}, ${intent.amount_usdc}, 'active', ${activeUntil}) on conflict (user_id) where status='active' do update set plan=excluded.plan, chain_type=excluded.chain_type, token_address=excluded.token_address, tx_hash=excluded.tx_hash, amount_usd=excluded.amount_usd, active_until=excluded.active_until, updated_at=now()`,
+ sql`update plan_payment_intents set status='confirmed', tx_hash=${tx_signature}, confirmed_at=now() where id=${intent_id} and status in ('pending', 'expired') returning id`,
+ sql`insert into subscriptions (user_id, plan, chain_type, token_address, tx_hash, amount_usd, status, active_until) values (${user.id}, ${intent.plan}, 'solana', ${mint ?? SOL_NATIVE_MINT}, ${tx_signature}, ${intent.amount_usdc}, 'active', ${activeUntil}) on conflict (user_id) where status='active' do update set plan=excluded.plan, chain_type=excluded.chain_type, token_address=excluded.token_address, tx_hash=excluded.tx_hash, amount_usd=excluded.amount_usd, active_until=excluded.active_until, updated_at=now()`,
sql`update users set plan=${intent.plan} where id=${user.id}`,
]);
if (!claimed?.[0]) return error(res, 409, 'already_confirmed', 'payment already confirmed');
queueMicrotask(() => sendSubscriptionConfirmEmail({ to: user.email, plan: intent.plan, chain: `Solana ${network}`, txId: tx_signature }).catch(() => {}));
- return json(res, 200, { ok: true, plan: intent.plan, active_until: activeUntil.toISOString(), tx_signature });
+ return json(res, 200, { ok: true, plan: intent.plan, asset, active_until: activeUntil.toISOString(), tx_signature });
+}
+
+// ── plans (public) ────────────────────────────────────────────────────────────
+// Server-truth plan prices + accepted assets, so pricing UIs never hardcode a
+// figure that drifts from what checkout actually charges.
+
+async function handlePlans(req, res) {
+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+ if (!method(req, res, ['GET'])) return;
+ return json(res, 200, {
+ plans: Object.fromEntries(Object.entries(PLANS).map(([id, p]) => [id, {
+ label: p.label,
+ price_usd: p.price_usd,
+ three_price_usd: planPriceUsd(id, 'THREE'),
+ duration_days: p.duration_days,
+ }])),
+ assets: PLAN_ASSETS,
+ three_discount_bps: threePlanDiscountBps(),
+ three_mint: THREE_MINT,
+ });
}
// ── dispatcher ────────────────────────────────────────────────────────────────
-const DISPATCH = { checkout: handleCheckout, confirm: handleConfirm };
+const DISPATCH = { checkout: handleCheckout, confirm: handleConfirm, plans: handlePlans };
export default wrap(async (req, res) => {
const action = req.query?.action ?? new URL(req.url, 'http://x').pathname.split('/').pop();
diff --git a/data/changelog.json b/data/changelog.json
index b488e1e32..e77846fa3 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,16 @@
{
"$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-05",
+ "title": "Agent creation now tells you what to do when your avatar library is full",
+ "summary": "If you hit your plan's avatar limit while creating an agent, the wizard used to fail with a bare error and leave you stuck. It now explains what happened and gives you three ways forward, right in the form: connect an avatar you already own (one click jumps you to your library), free up a slot by deleting an old avatar, or upgrade your plan. Oversized model files get a clearer message too.",
+ "tags": [
+ "fix",
+ "improvement"
+ ],
+ "link": "/create-agent"
+ },
{
"date": "2026-07-05",
"title": "Status page no longer reports a phantom outage — and graduation tracking runs clean",
diff --git a/pages/create-agent.html b/pages/create-agent.html
index 97701fd37..d3127aaa0 100644
--- a/pages/create-agent.html
+++ b/pages/create-agent.html
@@ -1128,6 +1128,26 @@
.foot-msg.ok {
color: var(--ok);
}
+ .foot-msg .msg-link {
+ background: none;
+ border: none;
+ padding: 0;
+ font: inherit;
+ color: inherit;
+ text-decoration: underline;
+ text-underline-offset: 2px;
+ cursor: pointer;
+ transition: opacity 0.15s ease;
+ }
+ .foot-msg .msg-link:hover,
+ .foot-msg .msg-link:active {
+ opacity: 0.75;
+ }
+ .foot-msg .msg-link:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 2px;
+ border-radius: 2px;
+ }
.foot-actions {
display: flex;
gap: 10px;
diff --git a/pages/pricing.html b/pages/pricing.html
index 81295ea5c..7a19cbb51 100644
--- a/pages/pricing.html
+++ b/pages/pricing.html
@@ -116,7 +116,12 @@
<li>Advanced analytics dashboard</li>
<li>Priority email support &amp; SLA</li>
</ul>
- <a href="/login?plan=pro" class="pricing-cta primary">Choose Pro</a>
+ <a href="/login?plan=pro" class="pricing-cta primary" id="pro-cta">Choose Pro</a>
+ <div class="pricing-pay-assets" aria-label="Accepted payment assets">
+ Pay in <strong>USDC</strong>, <strong>SOL</strong>, or
+ <strong>$THREE</strong>
+ <span class="pricing-three-discount" id="pro-three-discount" hidden></span>
+ </div>
</div>
<div class="pricing-tier-card" data-tier="enterprise">
@@ -142,6 +147,137 @@
</div>
</div>
+ <!-- ── PRO CHECKOUT — pay in USDC, SOL, or $THREE on Solana ─────── -->
+ <div class="pc-overlay" id="pc-overlay" hidden>
+ <div
+ class="pc-dialog"
+ role="dialog"
+ aria-modal="true"
+ aria-labelledby="pc-title"
+ id="pc-dialog"
+ tabindex="-1"
+ >
+ <button class="pc-close" id="pc-close" aria-label="Close checkout">
+ <svg viewBox="0 0 16 16" aria-hidden="true">
+ <path
+ d="M3 3l10 10M13 3L3 13"
+ stroke="currentColor"
+ stroke-width="1.6"
+ stroke-linecap="round"
+ />
+ </svg>
+ </button>
+ <h3 id="pc-title">Upgrade to Pro</h3>
+ <p class="pc-sub" id="pc-sub">
+ 30 days of Pro, settled on Solana. Choose how you want to pay.
+ </p>
+
+ <!-- Step 1 — pick the asset -->
+ <div class="pc-step" id="pc-step-asset">
+ <div class="pc-assets" role="radiogroup" aria-label="Payment asset">
+ <button
+ class="pc-asset is-selected"
+ type="button"
+ role="radio"
+ aria-checked="true"
+ data-asset="USDC"
+ >
+ <span class="pc-asset-name">USDC</span>
+ <span class="pc-asset-price" data-asset-price="USDC">$49</span>
+ <span class="pc-asset-note">Stable — pay the sticker price</span>
+ </button>
+ <button
+ class="pc-asset"
+ type="button"
+ role="radio"
+ aria-checked="false"
+ data-asset="SOL"
+ >
+ <span class="pc-asset-name">SOL</span>
+ <span class="pc-asset-price" data-asset-price="SOL">$49</span>
+ <span class="pc-asset-note">Quoted at the live price</span>
+ </button>
+ <button
+ class="pc-asset"
+ type="button"
+ role="radio"
+ aria-checked="false"
+ data-asset="THREE"
+ >
+ <span class="pc-asset-badge" data-three-badge>20% off</span>
+ <span class="pc-asset-name">$THREE</span>
+ <span class="pc-asset-price" data-asset-price="THREE">$39.20</span>
+ <span class="pc-asset-note">The platform coin — discounted</span>
+ </button>
+ </div>
+ <button class="pricing-cta primary pc-continue" id="pc-continue" type="button">
+ Continue
+ </button>
+ <p class="pc-fineprint">
+ Payments are verified on-chain and activate instantly. SOL and $THREE
+ amounts are pinned when the quote is created.
+ </p>
+ </div>
+
+ <!-- Step 2 — pay the pinned quote -->
+ <div class="pc-step" id="pc-step-pay" hidden>
+ <div class="pc-quote">
+ <div class="pc-quote-amount" id="pc-amount"></div>
+ <div class="pc-quote-meta">
+ <span id="pc-usd"></span> · quote expires in
+ <strong id="pc-countdown">--:--</strong>
+ </div>
+ </div>
+ <div class="pc-pay-grid">
+ <div class="pc-qr-wrap">
+ <canvas id="pc-qr" width="220" height="220" aria-label="Solana Pay QR code"></canvas>
+ </div>
+ <div class="pc-pay-actions">
+ <a
+ class="pricing-cta primary"
+ id="pc-wallet-link"
+ href="#"
+ rel="noopener"
+ >Open in wallet</a
+ >
+ <button class="pricing-cta" type="button" id="pc-copy-url">
+ Copy payment link
+ </button>
+ <button class="pricing-cta" type="button" id="pc-copy-addr">
+ Copy address
+ </button>
+ </div>
+ </div>
+ <label class="pc-sig-label" for="pc-txsig"
+ >Paid from an exchange or CLI? Paste the transaction signature:</label
+ >
+ <div class="pc-sig-row">
+ <input
+ id="pc-txsig"
+ autocomplete="off"
+ spellcheck="false"
+ placeholder="Transaction signature"
+ />
+ <button class="pricing-cta primary" type="button" id="pc-confirm">
+ Confirm
+ </button>
+ </div>
+ <button class="pc-back" type="button" id="pc-back">
+ &larr; Change payment asset
+ </button>
+ <div class="pc-status" id="pc-status" role="status" aria-live="polite"></div>
+ </div>
+
+ <!-- Step 3 — done -->
+ <div class="pc-step pc-success" id="pc-step-done" hidden>
+ <div class="pc-success-mark" aria-hidden="true">✓</div>
+ <h4>You&rsquo;re Pro</h4>
+ <p id="pc-done-detail"></p>
+ <a class="pricing-cta primary" href="/dashboard">Go to dashboard</a>
+ </div>
+ </div>
+ </div>
+
<!-- ── 3D AVATAR CANVAS ────────────────────────────────────────── -->
<canvas class="pricing-avatar-canvas" id="avatar-canvas"></canvas>
@@ -1150,6 +1286,276 @@
}
</script>
+ <!-- ── Pro checkout — USDC / SOL / $THREE on Solana ────────────────── -->
+ <script type="module">
+ import { track, ANALYTICS_EVENTS } from '/src/analytics.js';
+
+ const $ = (id) => document.getElementById(id);
+ const overlay = $('pc-overlay');
+ const proCta = $('pro-cta');
+ if (overlay && proCta) {
+ const PLAN = 'pro';
+ let user = null;
+ let plans = null;
+ let selectedAsset = 'USDC';
+ let intent = null;
+ let countdownTimer = null;
+ let pollTimer = null;
+ let lastFocus = null;
+
+ const fmtUsd = (n) =>
+ '$' + Number(n).toFixed(Number.isInteger(Number(n)) ? 0 : 2);
+ const assetLabel = (a) => (a === 'THREE' ? '$THREE' : a);
+
+ // Server truth for prices + the $THREE discount — never hardcoded.
+ async function loadPlans() {
+ try {
+ const r = await fetch('/api/payments/solana?action=plans', {
+ headers: { accept: 'application/json' },
+ });
+ if (!r.ok) return;
+ plans = await r.json();
+ const pro = plans.plans?.[PLAN];
+ if (!pro) return;
+ // Sync the tier card's monthly figure with what checkout charges.
+ const amountEl = document.querySelector(
+ '[data-tier="pro"] .pricing-amount',
+ );
+ if (amountEl) {
+ amountEl.dataset.monthly = fmtUsd(pro.price_usd);
+ if (!document.querySelector('#billing-toggle.annual')) {
+ amountEl.innerHTML = fmtUsd(pro.price_usd) + '<sub>/mo</sub>';
+ }
+ }
+ const pct = (plans.three_discount_bps / 100).toFixed(0);
+ const discountEl = $('pro-three-discount');
+ if (discountEl && plans.three_discount_bps > 0) {
+ discountEl.textContent = `— ${pct}% off in $THREE`;
+ discountEl.hidden = false;
+ }
+ document.querySelector('[data-asset-price="USDC"]').textContent =
+ fmtUsd(pro.price_usd);
+ document.querySelector('[data-asset-price="SOL"]').textContent =
+ fmtUsd(pro.price_usd);
+ document.querySelector('[data-asset-price="THREE"]').textContent =
+ fmtUsd(pro.three_price_usd);
+ const badge = document.querySelector('[data-three-badge]');
+ if (badge) badge.textContent = `${pct}% off`;
+ } catch (err) {
+ console.warn('[pricing] plan config load failed:', err?.message);
+ }
+ }
+
+ async function loadSession() {
+ try {
+ const r = await fetch('/api/auth/me', { credentials: 'include' });
+ if (r.ok) user = (await r.json()).user;
+ } catch {}
+ if (user && ['pro', 'team', 'enterprise'].includes(user.plan)) {
+ proCta.textContent = 'You’re on ' + (user.plan === 'pro' ? 'Pro ✓' : user.plan[0].toUpperCase() + user.plan.slice(1) + ' ✓');
+ proCta.href = '/account';
+ }
+ }
+
+ function setStatus(text, kind = '') {
+ const el = $('pc-status');
+ el.textContent = text;
+ el.className = 'pc-status' + (kind ? ' is-' + kind : '');
+ }
+
+ function showStep(step) {
+ for (const id of ['pc-step-asset', 'pc-step-pay', 'pc-step-done'])
+ $(id).hidden = id !== step;
+ }
+
+ function openModal() {
+ lastFocus = document.activeElement;
+ overlay.hidden = false;
+ document.body.style.overflow = 'hidden';
+ showStep('pc-step-asset');
+ setStatus('');
+ $('pc-dialog').focus();
+ track(ANALYTICS_EVENTS.SURFACE_OPENED, { surface: 'pricing:checkout' });
+ }
+
+ function closeModal() {
+ overlay.hidden = true;
+ document.body.style.overflow = '';
+ clearInterval(countdownTimer);
+ clearTimeout(pollTimer);
+ intent = null;
+ lastFocus?.focus?.();
+ }
+
+ proCta.addEventListener('click', (e) => {
+ // Signed out (or already upgraded) → let the link navigate.
+ if (!user || ['pro', 'team', 'enterprise'].includes(user.plan)) return;
+ e.preventDefault();
+ openModal();
+ });
+
+ $('pc-close').addEventListener('click', closeModal);
+ overlay.addEventListener('click', (e) => {
+ if (e.target === overlay) closeModal();
+ });
+ document.addEventListener('keydown', (e) => {
+ if (e.key === 'Escape' && !overlay.hidden) closeModal();
+ });
+
+ for (const btn of overlay.querySelectorAll('.pc-asset')) {
+ btn.addEventListener('click', () => {
+ selectedAsset = btn.dataset.asset;
+ for (const b of overlay.querySelectorAll('.pc-asset')) {
+ const on = b === btn;
+ b.classList.toggle('is-selected', on);
+ b.setAttribute('aria-checked', String(on));
+ }
+ });
+ }
+
+ function startCountdown(expiresAt) {
+ clearInterval(countdownTimer);
+ const el = $('pc-countdown');
+ const tick = () => {
+ const left = Math.max(0, new Date(expiresAt).getTime() - Date.now());
+ const m = Math.floor(left / 60000);
+ const s = Math.floor((left % 60000) / 1000);
+ el.textContent = `${m}:${String(s).padStart(2, '0')}`;
+ if (left <= 0) {
+ clearInterval(countdownTimer);
+ // Hide the payment targets so nobody pays a dead quote; the
+ // confirm input stays live for a payment already in flight.
+ $('pc-qr').style.opacity = '0.15';
+ $('pc-wallet-link').removeAttribute('href');
+ setStatus(
+ 'Quote expired. If you already paid, paste your signature above — otherwise go back and get a fresh quote.',
+ 'err',
+ );
+ }
+ };
+ tick();
+ countdownTimer = setInterval(tick, 1000);
+ }
+
+ async function createCheckout() {
+ $('pc-continue').disabled = true;
+ $('pc-continue').textContent = 'Creating quote…';
+ try {
+ const r = await fetch('/api/payments/solana?action=checkout', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ plan: PLAN, asset: selectedAsset }),
+ });
+ const d = await r.json();
+ if (!r.ok)
+ throw new Error(d.error_description || d.message || 'checkout failed');
+ intent = d;
+ $('pc-amount').textContent =
+ `${d.amount_asset} ${assetLabel(d.asset)}`;
+ $('pc-usd').textContent =
+ fmtUsd(d.amount_usd) +
+ (d.discount_bps > 0
+ ? ` (${(d.discount_bps / 100).toFixed(0)}% off in $THREE)`
+ : '');
+ $('pc-wallet-link').href = d.solana_pay_url;
+ $('pc-qr').style.opacity = '1';
+ const QRCode = await import('qrcode');
+ await (QRCode.default ?? QRCode).toCanvas($('pc-qr'), d.solana_pay_url, {
+ width: 220,
+ margin: 1,
+ });
+ $('pc-txsig').value = '';
+ setStatus('');
+ showStep('pc-step-pay');
+ startCountdown(d.expires_at);
+ track(ANALYTICS_EVENTS.CTA_CLICKED, {
+ cta: `plan:${PLAN}:checkout:${selectedAsset}`,
+ location: 'pricing',
+ });
+ } catch (err) {
+ setStatus(err.message, 'err');
+ alert(err.message);
+ } finally {
+ $('pc-continue').disabled = false;
+ $('pc-continue').textContent = 'Continue';
+ }
+ }
+
+ $('pc-continue').addEventListener('click', createCheckout);
+ $('pc-back').addEventListener('click', () => {
+ clearInterval(countdownTimer);
+ clearTimeout(pollTimer);
+ showStep('pc-step-asset');
+ setStatus('');
+ });
+
+ const copy = (text, btn) =>
+ navigator.clipboard?.writeText(text).then(() => {
+ const orig = btn.textContent;
+ btn.textContent = 'Copied ✓';
+ setTimeout(() => (btn.textContent = orig), 1500);
+ });
+ $('pc-copy-url').addEventListener('click', (e) =>
+ intent && copy(intent.solana_pay_url, e.currentTarget),
+ );
+ $('pc-copy-addr').addEventListener('click', (e) =>
+ intent && copy(intent.recipient, e.currentTarget),
+ );
+
+ // Confirm, retrying while the tx finalizes (finalization takes ~10-30s;
+ // the API only accepts finalized transactions).
+ let confirmTries = 0;
+ async function confirmPayment() {
+ const txsig = $('pc-txsig').value.trim();
+ if (!txsig) return setStatus('Paste the transaction signature first.', 'err');
+ if (!intent) return setStatus('No active quote — go back and start over.', 'err');
+ $('pc-confirm').disabled = true;
+ setStatus('Verifying on-chain…');
+ try {
+ const r = await fetch('/api/payments/solana?action=confirm', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ intent_id: intent.intent_id, tx_signature: txsig }),
+ });
+ const d = await r.json();
+ if (r.ok) {
+ clearInterval(countdownTimer);
+ $('pc-done-detail').textContent =
+ `Paid in ${assetLabel(d.asset)}. Pro is active until ` +
+ new Date(d.active_until).toLocaleDateString() + '.';
+ showStep('pc-step-done');
+ track(ANALYTICS_EVENTS.CTA_CLICKED, {
+ cta: `plan:${PLAN}:paid:${d.asset}`,
+ location: 'pricing',
+ });
+ return;
+ }
+ if (d.error === 'tx_not_found' && confirmTries < 30) {
+ confirmTries += 1;
+ setStatus('Waiting for the transaction to finalize… (retrying automatically)');
+ pollTimer = setTimeout(confirmPayment, 6000);
+ return;
+ }
+ throw new Error(d.error_description || d.message || 'confirmation failed');
+ } catch (err) {
+ setStatus(err.message, 'err');
+ $('pc-confirm').disabled = false;
+ }
+ }
+ $('pc-confirm').addEventListener('click', () => {
+ confirmTries = 0;
+ clearTimeout(pollTimer);
+ pollTimer = null;
+ confirmPayment();
+ });
+
+ loadPlans();
+ loadSession();
+ }
+ </script>
+
<script src="/brand.js" defer></script>
<div id="footer-container"></div>
<script src="/footer.js"></script>
diff --git a/public/animations/thumbs/av-idle-breath.webp b/public/animations/thumbs/av-idle-breath.webp
new file mode 100644
index 000000000..bbba8d02c
Binary files /dev/null and b/public/animations/thumbs/av-idle-breath.webp differ
diff --git a/public/animations/thumbs/av-waiting.webp b/public/animations/thumbs/av-waiting.webp
new file mode 100644
index 000000000..4403e5843
Binary files /dev/null and b/public/animations/thumbs/av-waiting.webp differ
diff --git a/public/animations/thumbs/covereyes.webp b/public/animations/thumbs/covereyes.webp
new file mode 100644
index 000000000..27c0a1fd2
Binary files /dev/null and b/public/animations/thumbs/covereyes.webp differ
diff --git a/public/animations/thumbs/facepalm.webp b/public/animations/thumbs/facepalm.webp
new file mode 100644
index 000000000..70002359f
Binary files /dev/null and b/public/animations/thumbs/facepalm.webp differ
diff --git a/public/animations/thumbs/idle.webp b/public/animations/thumbs/idle.webp
new file mode 100644
index 000000000..6102eace9
Binary files /dev/null and b/public/animations/thumbs/idle.webp differ
diff --git a/public/animations/thumbs/lookdown.webp b/public/animations/thumbs/lookdown.webp
new file mode 100644
index 000000000..7f08a4cbd
Binary files /dev/null and b/public/animations/thumbs/lookdown.webp differ
diff --git a/public/changelog.json b/public/changelog.json
index e34687473..80a7cc396 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-05T08:34:25.093Z",
+ "generated_at": "2026-07-05T08:35:14.324Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -28,6 +28,17 @@
"improvement"
]
},
+ {
+ "date": "2026-07-05",
+ "type": "update",
+ "title": "Agent creation now tells you what to do when your avatar library is full",
+ "summary": "If you hit your plan's avatar limit while creating an agent, the wizard used to fail with a bare error and leave you stuck. It now explains what happened and gives you three ways forward, right in the form: connect an avatar you already own (one click jumps you to your library), free up a slot by deleting an old avatar, or upgrade your plan. Oversized model files get a clearer message too.",
+ "link": "/create-agent",
+ "tags": [
+ "fix",
+ "improvement"
+ ]
+ },
{
"date": "2026-07-05",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index ff1c83852..e9614cbac 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -22,6 +22,14 @@
<category>feature</category>
<description>The animation library just grew from around 100 curated clips to over 2,000 — the full professional motion-capture set, every one retargeted to the universal three.ws skeleton so it plays on any humanoid avatar. Walks, runs, dances, combat, idles, reactions, sports, and hundreds more are all searchable in the animations gallery, previewable on a live avatar, and one click away from the pose studio or any embed. The clips are served from the CDN, so the site stays fast no matter how big the library gets.</description>
</item>
+ <item>
+ <title>Agent creation now tells you what to do when your avatar library is full</title>
+ <link>https://three.ws/create-agent</link>
+ <guid isPermaLink="false">2026-07-05:Agent creation now tells you what to do when your avatar library is full</guid>
+ <pubDate>Sun, 05 Jul 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>If you hit your plan's avatar limit while creating an agent, the wizard used to fail with a bare error and leave you stuck. It now explains what happened and gives you three ways forward, right in the form: connect an avatar you already own (one click jumps you to your library), free up a slot by deleting an old avatar, or upgrade your plan. Oversized model files get a clearer message too.</description>
+ </item>
<item>
<title>Status page no longer reports a phantom outage — and graduation tracking runs clean</title>
<link>https://three.ws/status</link>
diff --git a/public/features.json b/public/features.json
index fd535efbc..cf7a7b0e3 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-05T08:34:25.080Z",
+ "generated_at": "2026-07-05T08:35:14.312Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/scripts/build-animation-thumbnails.mjs b/scripts/build-animation-thumbnails.mjs
new file mode 100644
index 000000000..6cbacd71d
--- /dev/null
+++ b/scripts/build-animation-thumbnails.mjs
@@ -0,0 +1,172 @@
+#!/usr/bin/env node
+/**
+ * Render poster thumbnails for every animation clip in the motion library.
+ *
+ * Drives scripts/thumbnail-harness.html (served by the Vite dev server so the
+ * site's own retarget engine and preview avatar are used) in headless Chromium
+ * and saves one WebP still per clip, posed ~40% into the motion:
+ *
+ * • Curated clips (public/animations/manifest.json)
+ * → public/animations/thumbs/<name>.webp (committed, served statically)
+ * • Full library (animation-sources/.library-clips/manifest.json)
+ * → animation-sources/.library-thumbs/<name>.webp (gitignored; uploaded
+ * to R2 by `npm run mixamo:upload`, which also writes each clip's
+ * `thumb` URL into the published library manifest)
+ *
+ * Resumable: existing outputs are skipped unless --force. A dev server already
+ * listening on --port is reused; otherwise one is spawned for the run.
+ *
+ * Usage:
+ * node scripts/build-animation-thumbnails.mjs # everything missing
+ * node scripts/build-animation-thumbnails.mjs --limit=20 # smoke run
+ * node scripts/build-animation-thumbnails.mjs --only=mx-… # one clip
+ * node scripts/build-animation-thumbnails.mjs --force # re-render all
+ */
+
+import { spawn } from 'node:child_process';
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { dirname, join, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const ROOT = resolve(__dirname, '..');
+
+const args = Object.fromEntries(
+ process.argv.slice(2).map((a) => {
+ const m = a.match(/^--([^=]+)(?:=(.*))?$/);
+ return m ? [m[1], m[2] ?? true] : [a, true];
+ }),
+);
+const PORT = Number(args.port) || 3311;
+const LIMIT = args.limit ? Number(args.limit) : Infinity;
+const FORCE = !!args.force;
+const ONLY = typeof args.only === 'string' ? args.only : null;
+
+const CURATED_MANIFEST = join(ROOT, 'public/animations/manifest.json');
+const CURATED_CLIPS_DIR = join(ROOT, 'public/animations');
+const CURATED_OUT = join(ROOT, 'public/animations/thumbs');
+const LIBRARY_MANIFEST = join(ROOT, 'animation-sources/.library-clips/manifest.json');
+const LIBRARY_CLIPS_DIR = join(ROOT, 'animation-sources/.library-clips');
+const LIBRARY_OUT = join(ROOT, 'animation-sources/.library-thumbs');
+
+async function serverListening(port) {
+ try {
+ const res = await fetch(`http://localhost:${port}/scripts/thumbnail-harness.html`);
+ return res.ok;
+ } catch {
+ return false;
+ }
+}
+
+async function ensureDevServer() {
+ if (await serverListening(PORT)) return null;
+ console.log(`Starting Vite dev server on :${PORT}…`);
+ const proc = spawn('npx', ['vite', '--port', String(PORT), '--strictPort'], {
+ cwd: ROOT,
+ stdio: ['ignore', 'pipe', 'pipe'],
+ detached: false,
+ });
+ proc.stderr.on('data', (d) => {
+ const s = d.toString();
+ if (/error/i.test(s)) process.stderr.write(s);
+ });
+ const deadline = Date.now() + 60_000;
+ while (Date.now() < deadline) {
+ if (await serverListening(PORT)) return proc;
+ await new Promise((r) => setTimeout(r, 500));
+ }
+ proc.kill();
+ throw new Error(`Vite dev server did not come up on :${PORT} within 60s`);
+}
+
+function loadJobs() {
+ const jobs = [];
+ if (existsSync(CURATED_MANIFEST)) {
+ const curated = JSON.parse(readFileSync(CURATED_MANIFEST, 'utf8'));
+ for (const entry of curated) {
+ jobs.push({
+ name: entry.name,
+ loop: entry.loop !== false,
+ clipPath: join(CURATED_CLIPS_DIR, entry.url.replace(/^\/animations\//, '')),
+ outPath: join(CURATED_OUT, `${entry.name}.webp`),
+ });
+ }
+ }
+ if (existsSync(LIBRARY_MANIFEST)) {
+ const library = JSON.parse(readFileSync(LIBRARY_MANIFEST, 'utf8'));
+ for (const entry of library) {
+ jobs.push({
+ name: entry.name,
+ loop: entry.loop !== false,
+ clipPath: join(LIBRARY_CLIPS_DIR, entry.url),
+ outPath: join(LIBRARY_OUT, `${entry.name}.webp`),
+ });
+ }
+ } else {
+ console.warn('⚠️ No staged library manifest — only curated clips will render.');
+ }
+ return jobs;
+}
+
+(async () => {
+ const { chromium } = await import('playwright');
+
+ let jobs = loadJobs();
+ if (ONLY) jobs = jobs.filter((j) => j.name === ONLY);
+ const total = jobs.length;
+ if (!FORCE) jobs = jobs.filter((j) => !existsSync(j.outPath));
+ if (jobs.length > LIMIT) jobs = jobs.slice(0, LIMIT);
+ console.log(`${total} clips in manifests, ${jobs.length} to render.`);
+ if (!jobs.length) return;
+
+ mkdirSync(CURATED_OUT, { recursive: true });
+ mkdirSync(LIBRARY_OUT, { recursive: true });
+
+ const server = await ensureDevServer();
+ const browser = await chromium.launch({
+ args: ['--no-sandbox', '--disable-dev-shm-usage', '--enable-unsafe-swiftshader'],
+ });
+ try {
+ const page = await browser.newPage({ viewport: { width: 520, height: 700 } });
+ page.on('pageerror', (err) => console.warn(' [page]', err.message));
+ await page.goto(`http://localhost:${PORT}/scripts/thumbnail-harness.html`, {
+ waitUntil: 'domcontentloaded',
+ });
+ const boot = await page.evaluate(() => window.__thumb.ready);
+ console.log(`Harness ready — ${boot.bones} bones, ${boot.canonical} canonical mappings.`);
+
+ let done = 0;
+ let failed = 0;
+ const t0 = Date.now();
+ for (const job of jobs) {
+ if (!existsSync(job.clipPath)) {
+ failed++;
+ console.warn(` ❌ ${job.name}: clip file missing (${job.clipPath})`);
+ continue;
+ }
+ try {
+ const clipJson = JSON.parse(readFileSync(job.clipPath, 'utf8'));
+ const { dataUrl } = await page.evaluate(
+ ({ clipJson, name, at }) => window.__thumb.renderClip(clipJson, name, { at }),
+ { clipJson, name: job.name, at: job.loop ? 0.5 : 0.4 },
+ );
+ const b64 = dataUrl.replace(/^data:image\/webp;base64,/, '');
+ writeFileSync(job.outPath, Buffer.from(b64, 'base64'));
+ done++;
+ } catch (err) {
+ failed++;
+ console.warn(` ❌ ${job.name}: ${err.message.split('\n')[0]}`);
+ }
+ if (done % 50 === 0 && done > 0) {
+ const rate = done / ((Date.now() - t0) / 1000);
+ const eta = Math.round((jobs.length - done - failed) / rate);
+ process.stdout.write(`\r ${done}/${jobs.length} rendered (${rate.toFixed(1)}/s, ~${eta}s left)…`);
+ }
+ }
+ console.log(`\n✅ ${done} rendered, ${failed} failed, ${total - done - failed} already existed.`);
+ if (failed > 0) process.exitCode = 1;
+ } finally {
+ await browser.close();
+ if (server) server.kill();
+ }
+})();
diff --git a/scripts/thumbnail-harness.html b/scripts/thumbnail-harness.html
new file mode 100644
index 000000000..f32056caa
--- /dev/null
+++ b/scripts/thumbnail-harness.html
@@ -0,0 +1,213 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <title>Animation thumbnail harness</title>
+ <style>
+ html,
+ body {
+ margin: 0;
+ background: transparent;
+ }
+ canvas {
+ display: block;
+ }
+ </style>
+ </head>
+ <body>
+ <!--
+ Offline rendering harness for scripts/build-animation-thumbnails.mjs.
+
+ Served by the Vite dev server (so `three` and /src modules resolve exactly
+ as they do in the product) and driven by Playwright: the build script calls
+ window.__thumb.renderClip(clipJson, name, opts) per clip and receives a
+ WebP data-URL of the preview avatar frozen mid-performance.
+
+ Uses the site's own retarget engine (src/animation-retarget.js), the same
+ hipScale rules as AnimationManager._retarget, and the same preview avatar
+ as the /animations gallery, so a thumbnail is a faithful still of what the
+ clip actually plays like in the product.
+ -->
+ <script type="module">
+ import * as THREE from 'three';
+ import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
+ import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
+ import { getMeshoptDecoder } from '/src/viewer/internal.js';
+ import {
+ parseClipJSON,
+ retargetClip,
+ canonicalNodeMapFromObject,
+ canonicalRestMapFromObject,
+ canonicalWorldRestMapFromObject,
+ hipsParentWorldQuat,
+ hipRestLocalHeight,
+ clipHipBaselineY,
+ } from '/src/animation-retarget.js';
+
+ const WIDTH = 480;
+ const HEIGHT = 640; // 3:4 — matches the gallery card aspect
+ const MODEL_URL = '/avatars/cz.glb';
+
+ const renderer = new THREE.WebGLRenderer({
+ antialias: true,
+ alpha: true,
+ preserveDrawingBuffer: true,
+ });
+ renderer.setSize(WIDTH, HEIGHT);
+ renderer.setPixelRatio(1);
+ renderer.shadowMap.enabled = true;
+ renderer.shadowMap.type = THREE.PCFSoftShadowMap;
+ renderer.toneMapping = THREE.ACESFilmicToneMapping;
+ renderer.toneMappingExposure = 1.05;
+ document.body.appendChild(renderer.domElement);
+
+ const scene = new THREE.Scene();
+ const pmrem = new THREE.PMREMGenerator(renderer);
+ scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
+
+ const key = new THREE.DirectionalLight(0xffffff, 1.6);
+ key.position.set(2.2, 4.5, 3.2);
+ key.castShadow = true;
+ key.shadow.mapSize.set(1024, 1024);
+ key.shadow.camera.left = -2.5;
+ key.shadow.camera.right = 2.5;
+ key.shadow.camera.top = 2.5;
+ key.shadow.camera.bottom = -2.5;
+ key.shadow.bias = -0.0004;
+ scene.add(key);
+ scene.add(key.target);
+ const rim = new THREE.DirectionalLight(0x99bbff, 0.7);
+ rim.position.set(-2.5, 2.5, -2.5);
+ scene.add(rim);
+
+ const ground = new THREE.Mesh(
+ new THREE.PlaneGeometry(30, 30),
+ new THREE.ShadowMaterial({ opacity: 0.28 }),
+ );
+ ground.rotation.x = -Math.PI / 2;
+ ground.receiveShadow = true;
+ scene.add(ground);
+
+ const camera = new THREE.PerspectiveCamera(33, WIDTH / HEIGHT, 0.05, 100);
+
+ let model = null;
+ let mixer = null;
+ // Bind-pose snapshot (node → {p,q,s}) so every clip retargets against the
+ // true rest pose, not whatever pose the previous clip froze the rig in.
+ const restPose = new Map();
+ // Canonical maps captured once at bind pose — same recipe as
+ // AnimationManager.attach().
+ let canonicalToNode = null;
+ let canonicalRest = null;
+ let canonicalWorldRest = null;
+ let hipsParentQuat = null;
+ let hipTargetLocalY = 0;
+ const bones = [];
+
+ async function boot() {
+ const loader = new GLTFLoader();
+ loader.setMeshoptDecoder(await getMeshoptDecoder());
+ const gltf = await loader.loadAsync(MODEL_URL);
+ model = gltf.scene;
+ model.traverse((o) => {
+ if (o.isMesh || o.isSkinnedMesh) {
+ o.castShadow = true;
+ o.frustumCulled = false;
+ }
+ if (o.isBone) bones.push(o);
+ restPose.set(o, {
+ p: o.position.clone(),
+ q: o.quaternion.clone(),
+ s: o.scale.clone(),
+ });
+ });
+ scene.add(model);
+ model.updateMatrixWorld(true);
+ canonicalToNode = canonicalNodeMapFromObject(model);
+ canonicalRest = canonicalRestMapFromObject(model);
+ canonicalWorldRest = canonicalWorldRestMapFromObject(model);
+ hipsParentQuat = hipsParentWorldQuat(model);
+ hipTargetLocalY = hipRestLocalHeight(model);
+ mixer = new THREE.AnimationMixer(model);
+ return { bones: bones.length, canonical: canonicalToNode.size };
+ }
+
+ function restoreRestPose() {
+ mixer.stopAllAction();
+ mixer.uncacheRoot(model);
+ for (const [node, t] of restPose) {
+ node.position.copy(t.p);
+ node.quaternion.copy(t.q);
+ node.scale.copy(t.s);
+ }
+ model.updateMatrixWorld(true);
+ }
+
+ // Frame the posed skeleton: bone-position bounding box, padded, camera at a
+ // fixed 3/4 angle fitted so the figure fills the frame consistently whether
+ // it stands, sprawls, or cartwheels.
+ function frameCamera() {
+ const box = new THREE.Box3();
+ const v = new THREE.Vector3();
+ for (const b of bones) box.expandByPoint(b.getWorldPosition(v));
+ box.expandByVector(new THREE.Vector3(0.22, 0.14, 0.22)); // flesh beyond joints
+ box.min.y = Math.min(box.min.y, 0); // keep the ground contact in frame
+ const center = box.getCenter(new THREE.Vector3());
+ const size = box.getSize(new THREE.Vector3());
+ const fovV = THREE.MathUtils.degToRad(camera.fov);
+ const fovH = 2 * Math.atan(Math.tan(fovV / 2) * camera.aspect);
+ const distV = size.y / 2 / Math.tan(fovV / 2);
+ const distH = Math.max(size.x, size.z) / 2 / Math.tan(fovH / 2);
+ const dist = Math.max(distV, distH) * 1.18 + Math.max(size.z, size.x) / 2;
+ const azimuth = THREE.MathUtils.degToRad(24);
+ const elevation = THREE.MathUtils.degToRad(11);
+ camera.position.set(
+ center.x + dist * Math.cos(elevation) * Math.sin(azimuth),
+ center.y + dist * Math.sin(elevation),
+ center.z + dist * Math.cos(elevation) * Math.cos(azimuth),
+ );
+ camera.lookAt(center);
+ key.target.position.copy(center);
+ key.target.updateMatrixWorld();
+ }
+
+ /**
+ * Pose the avatar at a representative frame of the clip and return a WebP
+ * data-URL. `opts.at` (0..1) picks the sample point in the clip.
+ */
+ function renderClip(clipJson, name, opts = {}) {
+ restoreRestPose();
+ const clip = parseClipJSON(clipJson, name);
+ let hipScale = 1;
+ const baseline = clipHipBaselineY(clip);
+ if (hipTargetLocalY > 0.05 && baseline > 0.05) {
+ hipScale = Math.min(200, Math.max(0.2, hipTargetLocalY / baseline));
+ }
+ const { clip: bound, coverage } = retargetClip(clip, canonicalToNode, {
+ targetRest: canonicalRest,
+ targetWorldRest: canonicalWorldRest,
+ hipsParentWorldQuat: hipsParentQuat,
+ hipScale,
+ minCoverage: 0.3,
+ });
+ if (!bound) throw new Error(`retarget failed (coverage ${(coverage * 100).toFixed(0)}%)`);
+ const action = mixer.clipAction(bound);
+ action.play();
+ const at = Math.min(0.98, Math.max(0.02, opts.at ?? 0.4));
+ mixer.update(Math.max(0.001, bound.duration * at));
+ model.updateMatrixWorld(true);
+ frameCamera();
+ renderer.render(scene, camera);
+ const url = renderer.domElement.toDataURL('image/webp', opts.quality ?? 0.82);
+ action.stop();
+ mixer.uncacheClip(bound);
+ return { dataUrl: url, coverage };
+ }
+
+ window.__thumb = {
+ ready: boot(),
+ renderClip,
+ };
+ </script>
+ </body>
+</html>
diff --git a/src/create-agent.js b/src/create-agent.js
index 325115a5c..32db2dcd0 100644
--- a/src/create-agent.js
+++ b/src/create-agent.js
@@ -1234,7 +1234,17 @@ async function submit() {
trackError('create_agent.submit', err);
state.submitting = false;
resetSubmitButton();
- setMsg(err.message || 'Something went wrong. Please try again.', 'err');
+ const code = err.data?.error || err.code || '';
+ if (code === 'plan_limit_count' || code === 'plan_limit_storage') {
+ showPlanLimitMsg();
+ } else if (err.status === 413 || code === 'plan_limit_size') {
+ setMsg(
+ 'That model file is too large for your plan — upload a smaller GLB or connect an avatar you already own.',
+ 'err',
+ );
+ } else {
+ setMsg(err.message || 'Something went wrong. Please try again.', 'err');
+ }
}
}
@@ -1299,6 +1309,23 @@ function setMsg(text, kind) {
el.footMsg.textContent = text;
el.footMsg.className = 'foot-msg' + (kind ? ' ' + kind : '');
}
+
+// Avatar-quota failures get recovery paths instead of the raw server message.
+// Connecting an owned avatar is the one wizard path that doesn't create a new
+// avatar record, so it always works at the cap — lead with it. Static markup
+// only: never interpolate server text into innerHTML.
+function showPlanLimitMsg() {
+ el.footMsg.className = 'foot-msg err';
+ el.footMsg.innerHTML =
+ 'Your avatar library is full for your plan. ' +
+ '<button type="button" class="msg-link" id="msg-use-library">Connect an avatar you already own</button>, ' +
+ '<a class="msg-link" href="/dashboard/avatars" target="_blank" rel="noopener">free up a slot</a>, or ' +
+ '<a class="msg-link" href="/dashboard/monetize" target="_blank" rel="noopener">upgrade your plan</a>.';
+ $('msg-use-library')?.addEventListener('click', () => {
+ showStep(1);
+ document.querySelector('.model-tab[data-pane="library"]')?.click();
+ });
+}
function clearMsg() {
setMsg('', '');
}
diff --git a/tests/create-agent-plan-limit.test.js b/tests/create-agent-plan-limit.test.js
new file mode 100644
index 000000000..03cf22029
--- /dev/null
+++ b/tests/create-agent-plan-limit.test.js
@@ -0,0 +1,122 @@
+// @vitest-environment jsdom
+//
+// DOM-level test for the create-agent wizard's avatar-quota error handling.
+// Loads the real page markup from pages/create-agent.html, drives the wizard
+// to submit with "Add later" selected (which still copies the default starter
+// into the user's library), and asserts that a 402 plan_limit_count from
+// account.js#saveRemoteGlbToAccount renders the recovery message — connect an
+// owned avatar / free up a slot / upgrade — instead of the raw server text.
+
+import { describe, it, expect, beforeAll, vi } from 'vitest';
+import { readFileSync } from 'node:fs';
+import path from 'node:path';
+
+const planLimitErr = Object.assign(new Error('avatar count limit reached on plan free'), {
+ status: 402,
+ data: {
+ error: 'plan_limit_count',
+ error_description: 'avatar count limit reached on plan free',
+ },
+});
+
+const saveRemoteGlbToAccount = vi.fn().mockRejectedValue(planLimitErr);
+const apiFetch = vi.fn(async () => ({
+ ok: true,
+ headers: { get: () => 'application/json' },
+ json: async () => ({ avatars: [] }),
+}));
+
+vi.mock('../src/api.js', () => ({ apiFetch: (...a) => apiFetch(...a) }));
+vi.mock('../src/account.js', () => ({
+ getMe: vi.fn(async () => ({ id: 'u1', plan: 'free' })),
+ saveRemoteGlbToAccount: (...a) => saveRemoteGlbToAccount(...a),
+}));
+vi.mock('../src/analytics.js', () => ({
+ track: () => {},
+ trackFunnelStep: () => {},
+ trackError: () => {},
+ identifyUser: () => {},
+ ANALYTICS_EVENTS: new Proxy({}, { get: (_, k) => String(k) }),
+}));
+
+const flush = () => new Promise((r) => setTimeout(r, 0));
+const click = (elm) => elm.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+
+function activePanelStep() {
+ return document.querySelector('.panel.is-active')?.dataset.step;
+}
+
+beforeAll(async () => {
+ const html = readFileSync(
+ path.resolve(__dirname, '../pages/create-agent.html'),
+ 'utf8',
+ );
+ document.body.innerHTML = html.match(/<body[^>]*>([\s\S]*)<\/body>/)[1];
+ Element.prototype.scrollIntoView ||= () => {};
+ globalThis.requestAnimationFrame ||= (cb) => setTimeout(cb, 0);
+
+ await import('../src/create-agent.js');
+ await flush(); // boot(): auth probe resolves, wizard shows step 0
+});
+
+describe('create-agent wizard — avatar quota exceeded', () => {
+ it('walks to review and shows recovery paths on plan_limit_count', async () => {
+ // Step 0: name.
+ const name = document.getElementById('f-name');
+ name.value = 'Quota Test';
+ name.dispatchEvent(new Event('input', { bubbles: true }));
+ click(document.getElementById('btn-next'));
+ expect(activePanelStep()).toBe('1');
+
+ // Step 1: "Add later" + acknowledgment.
+ click(document.querySelector('.model-tab[data-pane="skip"]'));
+ const ack = document.getElementById('f-skip-ack');
+ ack.checked = true;
+ ack.dispatchEvent(new Event('change', { bubbles: true }));
+ click(document.getElementById('btn-next'));
+ expect(activePanelStep()).toBe('2');
+
+ // Steps 2–3 have no hard gates.
+ click(document.getElementById('btn-next'));
+ click(document.getElementById('btn-next'));
+ expect(activePanelStep()).toBe('4');
+
+ // Submit — the default-starter copy rejects with 402 plan_limit_count.
+ document
+ .getElementById('wizard')
+ .dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }));
+ await flush();
+ await flush();
+
+ expect(saveRemoteGlbToAccount).toHaveBeenCalled();
+ const msg = document.getElementById('foot-msg');
+ expect(msg.className).toContain('err');
+ // Not the raw server message — the designed recovery state.
+ expect(msg.textContent).not.toContain('avatar count limit reached on plan free');
+ expect(msg.textContent).toContain('avatar library is full');
+ expect(msg.querySelector('a[href="/dashboard/avatars"]')).toBeTruthy();
+ expect(msg.querySelector('a[href="/dashboard/monetize"]')).toBeTruthy();
+ expect(msg.querySelector('#msg-use-library')).toBeTruthy();
+
+ // The submit button is re-enabled for another attempt.
+ expect(document.getElementById('btn-create').disabled).toBe(false);
+ });
+
+ it('"connect an avatar you already own" jumps to the library tab', async () => {
+ click(document.getElementById('msg-use-library'));
+ await flush();
+
+ expect(activePanelStep()).toBe('1');
+ const libTab = document.querySelector('.model-tab[data-pane="library"]');
+ expect(libTab.classList.contains('is-active')).toBe(true);
+ expect(
+ document
+ .querySelector('.model-pane[data-pane="library"]')
+ .classList.contains('is-active'),
+ ).toBe(true);
+ // The owned-avatar library actually loaded (real fetch path, no dead tab).
+ expect(apiFetch.mock.calls.some(([url]) => String(url).includes('/api/avatars'))).toBe(
+ true,
+ );
+ });
+});