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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: activity feed, Forge gallery + persistence, terrain/physics polish
nirholas812e543c626a
diff --git a/.env.example b/.env.exampleindex c92978264..71774702f 100644--- a/.env.example+++ b/.env.example@@ -149,6 +149,16 @@ REPLICATE_REMESH_MODEL=REPLICATE_RETEX_MODEL=REPLICATE_RERIG_MODEL=+# /forge text→3D — reference-image model for the flux pass that precedes TRELLIS+# reconstruction. Optional: defaults to black-forest-labs/flux-schnell (Apache-2.0,+# fast). Override with any owner/name[:version] or version hash on Replicate.+REPLICATE_TXT2IMG_MODEL=+# /forge persists every generation (durable GLB + reference image + the human+# keep/discard verdict — the text→3D data flywheel) when BOTH a database+# (DATABASE_URL) and object storage (S3_* above) are configured. With either+# missing, /forge still generates models; it just doesn't retain them or show+# the "Your creations" gallery. No extra config needed beyond those two.+# Hugging Face provider (when AVATAR_REGEN_PROVIDER=huggingface, or auto-# detected when only HF_TOKEN is set). Read-only token is sufficient since# the default target Space is public. Get one at huggingface.co/settings/tokens.diff --git a/README.md b/README.mdindex 23aeda769..daf13d56b 100644--- a/README.md+++ b/README.md@@ -39,7 +39,6 @@ https://github.com/user-attachments/assets/d52515d1-cb04-4dd6-98bd-fef233312dc4- [The Club](#the-club)- [Walk & Multiplayer](#walk--multiplayer)- [Coin Communities](#coin-communities)-- [Adventure — Onchain RPG](#adventure--onchain-rpg)- [City](#city)- [Friends, Presence & Social](#friends-presence--social)- [In-Game Economy](#in-game-economy)@@ -292,7 +291,6 @@ If you want to support the project — compute credits, grants, partnerships, or**Social & Multiplayer 3D**- **Coin Communities** at `/communities` + `/play` — every Solana token gets a live 3D world; pick the same coin and land together, with peer avatars, chat, emotes, voxel building, and a live market-cap screen-- **Adventure** at `/game` — an authoritative onchain RPG: trainable skills, gathering, combat, banking, mounts, multi-realm world, daily quests, cosmetics shop, player marketplace, and $THREE/gold economy- **City** at `/city` — free-roam walkable 3D city scene- **Friends, presence & DMs** — account-level social graph with live presence ("Online · Mainland"), direct messages, and a per-account realtime delivery hub- **The Club** at `/club` — multiplayer venue with rigged dancers, audio tracks, tips, leaderboard, payouts cron, perf-aware renderer that auto-downgrades on slow frames@@ -340,7 +338,6 @@ A map of every user-facing route. Full detail (source files, feature description| **Club** | `/club` | Multiplayer 3D venue — tips, leaderboard, audio tracks, perf-aware renderer || **Walk** | `/walk` | Authoritative multiplayer walk scene (Colyseus on Fly.io) || **Coin Communities** | `/communities`, `/communities/[mint]`, `/worlds`, `/play` | Live 3D world per Solana token — lobby, coin profile, and the shared coin-keyed world |-| **Adventure** | `/game` | Onchain RPG — skills, gathering, combat, quests, cosmetics, player marketplace, $THREE/gold economy || **City** | `/city` | Free-roam walkable 3D city scene || **Bazaar (x402)** | `/x402`, `/x402-discover`, `/x402-pay` | Paid-API marketplace, discovery, Stripe-style checkout || **Artifacts** | `/artifact`, `/artifact/snippet`, `/artifact-example` | Claude Artifact viewer |@@ -821,14 +818,14 @@ For sandboxed iframes use the widget embed path instead — it runs in its own b## Project Structure-- `src/`: The core frontend JavaScript for the main application, including the 3D viewer, agent protocol, custom element, and feature modules (`club-*.js`, `walk*.js`, `pose-*.js`, `voice/`, `selfie-*.js`). Social/gameplay surfaces live in `game/` (Coin Communities + Adventure RPG: `coincommunities*`, `iso-game*`, `game-hud`, `spin-wheel-ui`, `cosmetics-visual`, `avatar-rig`), `city/` (the `/city` world), `social/` (sentiment, X-post impact), `community/` (coin lobby/town), plus `friends.js`, `communities.js`, `marketplace*.js`, and `token-pay.js`.+- `src/`: The core frontend JavaScript for the main application, including the 3D viewer, agent protocol, custom element, and feature modules (`club-*.js`, `walk*.js`, `pose-*.js`, `voice/`, `selfie-*.js`). Social/gameplay surfaces live in `game/` (Coin Communities: `coincommunities*`, `spin-wheel-ui`, `cosmetics-visual`, `avatar-rig`), `city/` (the `/city` world), `social/` (sentiment, X-post impact), `community/` (coin lobby/town), plus `friends.js`, `communities.js`, `marketplace*.js`, and `token-pay.js`.- `api/`: Vercel serverless functions that form the backend API. Subdirectories include `x402/`, `a2a/`, `club/`, `pump/`, `persona/`, `news/`, `admin/`, `agents/`, `auth/`, `oauth/`, `cron/`, plus the social/game surfaces `play/`, `token/`, `three-token/`, `friends/`, `social/`, `community/`, `marketplace/`, and `mocap/`.- `public/`: Static assets and various sub-applications (`club/`, `seeker/`, `news/`, `persona/`, `vanity-wallet.html`, `pumpfun.html`).- `chat/`: A standalone Svelte application for the chat interface.- `character-studio/`: A sub-project for in-browser character creation; also serves the rebranded **Avatar Studio** marketplace.- `rider/`: A-Frame WebVR music visualization experiment.- `contracts/`: Solidity smart contracts for on-chain identity (ERC-8004) and the multichain payment factory.-- `multiplayer/`: Colyseus WebSocket server for `/walk`, `/play` (WalkRoom), and `/game` (GameRoom); deployable on Fly.io. Holds the authoritative game logic and single sources of truth — `items.js`, `quests.js`, `cosmetics.js`, `spin-wheel.js`, `marketplaceStore.js`, `playerStore.js`, `realms.js`, `game-token.js`, `play-pass.js`, `holder-pass.js`, and the per-account `social-hub.js`.+- `multiplayer/`: Colyseus WebSocket server for `/walk` and `/play` (WalkRoom); deployable on Fly.io. Holds the authoritative world logic and single sources of truth — `items.js`, `playerStore.js`, `game-token.js`, `play-pass.js`, `holder-pass.js`, and the per-account `social-hub.js`.- `sdk/`: `@nirholas/agent-kit` and the Avatar SDK (`sdk/agent-sdk/`).- `agent-payments-sdk/`: EVM agent payments SDK (Base / BSC / other EVM chains).- `solana-agent-sdk/`: SDK for Solana blockchain interactions (Metaplex Core mints, SIWS, attestations).@@ -1223,7 +1220,7 @@ Vercel doesn't host long-lived WebSockets, so the multiplayer server lives in itnpm run dev:walk-all # Vite (:3000) + Colyseus (:2567)```-**WalkRoom** (`multiplayer/src/rooms/WalkRoom.js`) is the authoritative state container — position, rotation, gesture, presence. Origin allow-listing is enforced at the WS upgrade (`ALLOWED_ORIGINS` env, with `*.vercel.app` and `*.three.ws` always permitted for preview deploys). The same Colyseus server now hosts a second authoritative room — **GameRoom** (the Adventure RPG, see below) — alongside WalkRoom, plus a per-account **social hub** (`multiplayer/src/social-hub.js`) for presence and live event delivery.+**WalkRoom** (`multiplayer/src/rooms/WalkRoom.js`) is the authoritative state container — position, rotation, gesture, presence. Origin allow-listing is enforced at the WS upgrade (`ALLOWED_ORIGINS` env, with `*.vercel.app` and `*.three.ws` always permitted for preview deploys). The same Colyseus server also runs a per-account **social hub** (`multiplayer/src/social-hub.js`) for presence and live event delivery.---@@ -1240,7 +1237,7 @@ Every Solana token gets a **live 3D world**. Coin Communities turns a mint addre**How it works**- **Real pump.fun data, no mocks.** The lobby and coin profiles pull live trending coins, search results, bonding-curve pricing, and recent trades from the pump.fun feed.-- **Bring any avatar.** Use a default, an uploaded GLB/VRM, or paste a model URL. The same rig (`src/game/avatar-rig.js`) drives `/play` and `/game` with no drift.+- **Bring any avatar.** Use a default, an uploaded GLB/VRM, or paste a model URL. The same rig (`src/game/avatar-rig.js`) drives `/play`, `/walk`, and `/city` with no drift.- **Realtime presence + chat.** Each coin is its own room. Town chat is backed by the [CoinCommunities](https://coin-communities.xyz) service — reads work out of the box; posting unlocks behind X-OAuth sign-in + a linked wallet. If `CC_API_KEY` is unset, chat renders its designed locked state.- **Voxel building & spatial voice.** Collaborative block placement (server-capped) and optional geofenced WebRTC voice (`src/game/voice-chat.js`).- **Holder-gated rooms.** A coin can require token holders (tier `holders` vs general); gating is enforced server-side via a sealed play-pass.@@ -1249,31 +1246,6 @@ Every Solana token gets a **live 3D world**. Coin Communities turns a mint addre----## Adventure — Onchain RPG--`/game` is an authoritative multiplayer RPG. It's a tile-stepped isometric world with trainable skills, gathering, combat, banking, quests, cosmetics, a player-to-player marketplace, and onchain payments — all validated server-side so nothing can be spoofed by the client.--**Core loop**--| System | What it is |-| -------------- | ---------------------------------------------------------------------------------------------------------------------- |-| **Skills** | Five trainable skills (combat, woodcutting, mining, fishing, cooking), level 1–99, XP-gated |-| **Gathering** | Resource nodes (trees, rocks, coal, fishing spots) worked with the right tool; server-authoritative loot rolls |-| **Inventory** | 6-slot hotbar, 24-slot backpack, 48-slot account bank; stackable resources, non-stackable tools |-| **Combat & death** | Mobs drop trophies; in danger realms death drops a lootable tombstone (TTL), safe realms preserve inventory |-| **Cooking** | Raw fish → cooked food at a roast pit; heal value scales with cooking level |-| **Mounts** | Rare drops (dire wolf, war boar) — non-stackable, rideable for faster travel |-| **Realms** | Multi-realm world (Mainland, Wilderness, Whisperwood, Pond, Mine, Arena…), each a 48×48 grid with portals and stat gates |-| **Quests** | An 8-step tutorial + 3 deterministic daily quests per UTC day, with gold/XP/item/badge rewards |--**Wallet-first entry (play-gate).** There's no password. `GET /api/play/nonce` issues a nonce + gate config; `POST /api/play/verify` checks the wallet signature and on-chain token balance, then mints a short-lived HMAC-sealed **play-pass** the game server trusts without re-querying the RPC. Gating is configured via `PLAY_GATE_MINT` / `PLAY_GATE_MIN` and `HOLDER_PASS_SECRET`.--**Server-authoritative.** `multiplayer/src/rooms/GameRoom.js` owns all state; `multiplayer/src/` holds the single sources of truth — `items.js` (item registry, loot tables, mount stats), `quests.js` (tutorial + daily pool + badges), `cosmetics.js` (shop catalog + rotation), `spin-wheel.js`, `marketplaceStore.js`, `playerStore.js`, and `realms.js`/`realm-transfer.js` (layouts, portals, signed stat-gated transfers).--**Client:** `src/game/iso-game.js` (scene), `iso-controls.js` + `keybindings.js` (input), `game-hud.js` (hotbar, skills, quests, bank, shop, marketplace panels), `game-net.js` (socket bridge), `spin-wheel-ui.js`, `cosmetics-visual.js`.------## City`/city` is a free-roam 3D city scene — a walkable urban world with a follow camera, map, and player controller, built on the same Three.js stack as the rest of the platform.@@ -1294,25 +1266,7 @@ A full account-level social layer spans the multiplayer surfaces. Friendships ar| **Presence** | Short-lived signed ticket (`GET /api/friends/presence-ticket`) → multiplayer server writes `presence:<uid>` to Redis (75s TTL, 30s heartbeat) || **Live delivery** | The social hub (`multiplayer/src/social-hub.js`) pushes DM + friend events to every open socket for an account |-Friends are stored in Postgres (`friendships`, `direct_messages`, `user_mutes` — see migration `api/_lib/migrations/2026-06-01-friends.sql`); presence lives in Upstash Redis and self-heals if a process dies. Muting is send-side only — a muted account is never told it was muted. The friends panel UI (`src/friends.js`, `src/game/friends-panel.js`) surfaces requests, DM threads, and "Online · Mainland" / "Offline" status inside `/play` and `/game`. The `src/social/` module adds sentiment + X-post-impact scoring used by community surfaces.-------## In-Game Economy--The game runs on two currencies and a real onchain settlement path.--**Gold (soft currency)** — earned from quests, gathering, and combat; spent in the cosmetics shop and the player marketplace. Used for fee-free trades.--**$THREE (onchain, Solana)** — an SPL token with a server-authoritative **quote → sign → settle** flow (`api/token/*`, `src/token-pay.js`, `api/_lib/token/`). The server issues a purpose-scoped, HMAC-sealed quote (`spin`, `marketplace_sale`); the client signs an atomic split transaction; the server verifies it on-chain (destination + amount + memo) before crediting. Live USD pricing comes from Jupiter (primary, pump.fun-aware) with a Birdeye fallback. The **$THREE protocol** layer (`api/three-token/*`) tracks holder revenue-share, a deploy-to-burn ledger, and an activity feed. Game-server config: `GAME_TOKEN_MINT`, `GAME_TOKEN_TREASURY`, `GAME_TOKEN_BURN`, `GAME_TOKEN_SECRET`.--| Sink | Detail |-| --------------- | ------------------------------------------------------------------------------------------------------------ |-| **Cosmetics shop** | ~15-item catalog across five rarity tiers; daily (3) + weekly (2) rotations are seeded and deterministic per UTC day. Cosmetics are visual only — tints, props (`.glb` accessories at head/face anchors), and auras. High-price buys gate behind a two-click confirm. |-| **Player marketplace** | Peer-to-peer listing board (`multiplayer/src/marketplaceStore.js`). List items or gold; settle in gold (fee-free) or $THREE (95% seller / 5% treasury). Offline sellers receive pending payouts on next login; Redis-persisted across restarts. |-| **Spin wheel** | A Mainland wheel — one free spin every 12h or a paid spin in $THREE. The outcome is rolled and sealed server-side before the client animates, so the wheel can't be gamed. |--The separate **agent/avatar marketplace** at `/marketplace` (discovery, fork, bookmark, Solana-Pay asset purchase, skill pricing) is documented under [API Reference](#api-reference); the in-game economy above is distinct and lives in the Colyseus rooms.+Friends are stored in Postgres (`friendships`, `direct_messages`, `user_mutes` — see migration `api/_lib/migrations/2026-06-01-friends.sql`); presence lives in Upstash Redis and self-heals if a process dies. Muting is send-side only — a muted account is never told it was muted. The friends panel UI (`src/friends.js`, `src/game/friends-panel.js`) surfaces requests, DM threads, and "Online" / "Offline" status inside `/play`. The `src/social/` module adds sentiment + X-post-impact scoring used by community surfaces.---diff --git a/api/_lib/feed.js b/api/_lib/feed.jsnew file mode 100644index 000000000..7c6b7599c--- /dev/null+++ b/api/_lib/feed.js@@ -0,0 +1,132 @@+// Live activity feed store — the cross-surface "something is always happening+// here" ticker that makes three.ws feel alive on every page.+//+// Events are produced from many places — a coin buy confirmed in api/pump, an+// agent deployed in api/agents, a level-up or a world-join in the standalone+// multiplayer server — and read by the site-wide widget (public/feed.js) via+// GET /api/feed. Storage is a single capped Redis list `feed:events` ordered+// newest-first.+//+// Like presence-store, the multiplayer server writes to the SAME key directly+// (multiplayer/src/feed.js) rather than calling back through HTTP: Redis is the+// shared bus between the serverless API and the long-running game server. Both+// producers MUST emit the identical event shape documented below.+//+// ── Event shape ──────────────────────────────────────────────────────────────+// { id, type, ts, actor, ...typeSpecific }+// id — opaque unique key; the widget de-dupes and uses it as a render key+// type — one of ALLOWED_TYPES+// ts — epoch ms+// actor — short, already-sanitized display label (truncated wallet, player+// name, agent name). NEVER a raw secret or full address we wouldn't+// show publicly — this list is world-readable.+// coin-buy → { mint, sol, network }+// agent-deploy → { agentId, name }+// level-up → { skill, level, coin }+// world-join → { coin, coinName }+// jackpot → { reward, coin }+//+// All writes are best-effort. The feed is a delight layer, never on a critical+// path: a Redis outage degrades to an empty feed, never a thrown error.++import { Redis } from '@upstash/redis';+import { env } from './env.js';++const FEED_KEY = 'feed:events';+const MAX_EVENTS = 200; // capped list — the widget shows ~30; we keep headroom++export const ALLOWED_TYPES = new Set([+ 'coin-buy',+ 'agent-deploy',+ 'level-up',+ 'world-join',+ 'jackpot',+]);++let _redis = null;+let _redisTried = false;+function redis() {+ if (_redisTried) return _redis;+ _redisTried = true;+ if (env.UPSTASH_REDIS_REST_URL && env.UPSTASH_REDIS_REST_TOKEN) {+ _redis = new Redis({ url: env.UPSTASH_REDIS_REST_URL, token: env.UPSTASH_REDIS_REST_TOKEN });+ }+ return _redis;+}++let _seq = 0;+// A sortable, collision-resistant id: a base36 timestamp prefix plus a per-+// process counter so two events in the same millisecond still differ.+function eventId(ts) {+ _seq = (_seq + 1) % 1_000_000;+ return `${ts.toString(36)}-${_seq.toString(36)}`;+}++// Append an event to the feed. Returns the stored record (with id + ts filled+// in) or null on a no-op (unknown type, Redis down, malformed input). Never+// throws — every caller is fire-and-forget on a non-critical path.+export async function publishFeedEvent(event) {+ const r = redis();+ if (!r || !event || !ALLOWED_TYPES.has(event.type)) return null;+ const ts = Number.isFinite(event.ts) ? event.ts : Date.now();+ const record = { ...event, ts, id: event.id || eventId(ts) };+ try {+ await r.lpush(FEED_KEY, JSON.stringify(record));+ await r.ltrim(FEED_KEY, 0, MAX_EVENTS - 1);+ return record;+ } catch (err) {+ console.warn('[feed] publish failed:', err?.message);+ return null;+ }+}++// Short-lived in-process read cache. The widget is mounted on every page and+// polls this endpoint continuously, so without dedup each poll becomes a Redis+// command — at platform scale that alone can exhaust the Upstash request quota.+// A warm serverless instance serving a burst of polls reuses one underlying+// read for READ_CACHE_MS; we always fetch the top CACHE_N (cheap — one command+// regardless of count) and slice per caller, so every limit ≤ CACHE_N is served+// from the same cached array. This bounds Redis reads to ~one per instance per+// window instead of one per client poll. The feed is a delight layer, so a few+// seconds of staleness is invisible.+const READ_CACHE_MS = 8_000;+const CACHE_N = 60; // ≥ any limit the widget requests (30) with headroom+let _readCache = { at: 0, events: [] };++// Read the most recent events, newest-first. `limit` is clamped to+// [1, MAX_EVENTS]. Returns [] on a Redis outage so the widget renders its empty+// state rather than surfacing an error to the user.+export async function readFeedEvents(limit = 30) {+ const r = redis();+ if (!r) return [];+ const n = Math.max(1, Math.min(MAX_EVENTS, Math.floor(Number(limit)) || 30));++ // Serve from the in-process cache when fresh and large enough.+ if (n <= CACHE_N && Date.now() - _readCache.at < READ_CACHE_MS) {+ return _readCache.events.slice(0, n);+ }++ const want = Math.max(n, CACHE_N);+ try {+ const rows = await r.lrange(FEED_KEY, 0, want - 1);+ const out = [];+ for (const row of rows || []) {+ // Upstash auto-deserializes JSON-looking values; tolerate both shapes.+ const obj = typeof row === 'string' ? safeParse(row) : row;+ if (obj && typeof obj === 'object' && obj.type) out.push(obj);+ }+ if (want >= CACHE_N) _readCache = { at: Date.now(), events: out.slice(0, CACHE_N) };+ return out.slice(0, n);+ } catch (err) {+ console.warn('[feed] read failed:', err?.message);+ return [];+ }+}++function safeParse(s) {+ try {+ return JSON.parse(s);+ } catch {+ return null;+ }+}diff --git a/api/_lib/forge-store.js b/api/_lib/forge-store.jsnew file mode 100644index 000000000..4b7eaebd5--- /dev/null+++ b/api/_lib/forge-store.js@@ -0,0 +1,255 @@+// Forge creation store — durable persistence + the text→3D data flywheel.+//+// /forge runs the real flux-schnell → TRELLIS pipeline (see api/forge.js) and+// hands back the Replicate delivery URL, which expires in ~1h. This module is+// the layer that makes a generator a *data engine*: it copies every generated+// mesh (and its reference image) into our own object storage so they're+// permanent, records the (prompt → image → mesh) pair, and captures the human+// verdict (kept / discarded / downloaded) — the labeled signal a future+// in-house model trains on.+//+// Every function is best-effort and fail-soft. /forge is auth-free and works on+// deployments without a database or object storage configured; when either is+// missing, these helpers no-op (return null/false/[]) and the endpoint falls+// back to returning the raw provider URL. Persistence is a bonus, never a gate.++import { createHash } from 'node:crypto';+import { randomUUID } from 'node:crypto';+import { sql } from './db.js';+import { putObject, publicUrl } from './r2.js';++// Stable, non-secret salt so a leaked DB row can't be trivially reversed to the+// raw browser-local id. The id is anonymous to begin with; this is hygiene, not+// a security boundary.+const CLIENT_SALT = 'forge:v1';++// Generations larger than this are almost certainly a runaway TRELLIS output;+// refuse to copy them into our bucket rather than ingest an unbounded blob.+const MAX_GLB_BYTES = 64 * 1024 * 1024;+const MAX_IMAGE_BYTES = 8 * 1024 * 1024;++// Forge persistence needs both a database (the creation rows) and object+// storage (durable copies). Detect from the raw env so a partially-configured+// deployment degrades to the stateless path instead of throwing on first use.+export function forgeStoreEnabled() {+ return Boolean(+ process.env.DATABASE_URL &&+ process.env.S3_ENDPOINT &&+ process.env.S3_BUCKET &&+ process.env.S3_PUBLIC_DOMAIN &&+ process.env.S3_ACCESS_KEY_ID &&+ process.env.S3_SECRET_ACCESS_KEY,+ );+}++// Hash a caller-supplied anonymous client id. Empty / missing ids collapse to a+// shared 'anon' bucket so the column is never null and gallery scoping is total.+export function hashClient(raw) {+ const value = typeof raw === 'string' ? raw.trim() : '';+ if (!value) return 'anon';+ return createHash('sha256').update(`${CLIENT_SALT}:${value}`).digest('hex');+}++export function hashIp(ip) {+ if (!ip) return null;+ return createHash('sha256').update(`${CLIENT_SALT}:ip:${ip}`).digest('hex');+}++// Record a generation the moment it starts, so the prompt + reference image are+// retained even if the mesh step later fails. Returns the new creation id (used+// as the durable object key and the client-facing handle) or null when the+// store is unavailable.+export async function createCreation({+ clientKey,+ ipHash,+ prompt,+ aspect,+ previewImageUrl,+ replicateJobId,+ textToImageModel,+}) {+ if (!forgeStoreEnabled()) return null;+ const id = randomUUID();+ try {+ await sql`+ insert into forge_creations+ (id, client_key, ip_hash, prompt, aspect, preview_image_url,+ replicate_job_id, text_to_image_model, status, outcome)+ values+ (${id}, ${clientKey}, ${ipHash ?? null}, ${prompt}, ${aspect ?? null},+ ${previewImageUrl ?? null}, ${replicateJobId ?? null},+ ${textToImageModel ?? null}, 'generating', 'generated')+ `;+ return id;+ } catch (err) {+ console.error('[forge-store] createCreation failed:', err?.message);+ return null;+ }+}++// Look up an in-flight creation by its TRELLIS prediction id, scoped to the+// requesting client so one browser can't poll another's job into existence.+export async function findByJob({ replicateJobId, clientKey }) {+ if (!forgeStoreEnabled() || !replicateJobId) return null;+ try {+ const rows = await sql`+ select id, status, glb_url, glb_key, prompt, preview_image_url+ from forge_creations+ where replicate_job_id = ${replicateJobId} and client_key = ${clientKey}+ limit 1+ `;+ return rows[0] ?? null;+ } catch (err) {+ console.error('[forge-store] findByJob failed:', err?.message);+ return null;+ }+}++async function copyToBucket({ sourceUrl, key, fallbackContentType, maxBytes }) {+ const resp = await fetch(sourceUrl);+ if (!resp.ok) throw new Error(`fetch ${sourceUrl}: ${resp.status}`);+ const buf = Buffer.from(await resp.arrayBuffer());+ if (buf.length > maxBytes) throw new Error(`asset too large: ${buf.length} bytes`);+ const contentType = resp.headers.get('content-type') || fallbackContentType;+ await putObject({ key, body: buf, contentType, metadata: { source: 'forge' } });+ return { bytes: buf.length, publicUrl: publicUrl(key) };+}++function imageExtFor(url) {+ const m = /\.(png|jpe?g|webp)(\?|$)/i.exec(url || '');+ return m ? m[1].toLowerCase().replace('jpeg', 'jpg') : 'webp';+}++// Copy a finished generation into durable storage and flip the row to 'done'.+// Copies the mesh (required) and the reference image (best-effort). Returns the+// durable { id, glbUrl, previewImageUrl } or null on any failure so the caller+// can fall back to the provider URL.+export async function materializeCreation({ replicateJobId, clientKey, glbUrl }) {+ if (!forgeStoreEnabled() || !replicateJobId || !glbUrl) return null;+ const existing = await findByJob({ replicateJobId, clientKey });+ if (!existing) return null;+ // Idempotent: a repeat poll after completion returns the durable copy.+ if (existing.status === 'done' && existing.glb_url) {+ return {+ id: existing.id,+ glbUrl: existing.glb_url,+ previewImageUrl: existing.preview_image_url ?? null,+ };+ }++ const keyPrefix = `forge/${clientKey.slice(0, 12)}/${existing.id}`;+ try {+ const glb = await copyToBucket({+ sourceUrl: glbUrl,+ key: `${keyPrefix}.glb`,+ fallbackContentType: 'model/gltf-binary',+ maxBytes: MAX_GLB_BYTES,+ });++ // Reference image is part of the training pair but never blocks the mesh.+ let preview = { key: null, url: existing.preview_image_url ?? null };+ if (existing.preview_image_url) {+ try {+ const ext = imageExtFor(existing.preview_image_url);+ const copied = await copyToBucket({+ sourceUrl: existing.preview_image_url,+ key: `${keyPrefix}.${ext}`,+ fallbackContentType: 'image/webp',+ maxBytes: MAX_IMAGE_BYTES,+ });+ preview = { key: `${keyPrefix}.${ext}`, url: copied.publicUrl };+ } catch (imgErr) {+ console.error('[forge-store] preview copy failed:', imgErr?.message);+ }+ }++ await sql`+ update forge_creations+ set status = 'done',+ glb_key = ${`${keyPrefix}.glb`},+ glb_url = ${glb.publicUrl},+ preview_key = ${preview.key},+ preview_image_url = ${preview.url},+ size_bytes = ${glb.bytes},+ updated_at = now()+ where id = ${existing.id} and client_key = ${clientKey}+ `;+ return { id: existing.id, glbUrl: glb.publicUrl, previewImageUrl: preview.url };+ } catch (err) {+ console.error('[forge-store] materializeCreation failed:', err?.message);+ return null;+ }+}++export async function markFailed({ replicateJobId, clientKey, error }) {+ if (!forgeStoreEnabled() || !replicateJobId) return;+ try {+ await sql`+ update forge_creations+ set status = 'failed', error = ${String(error || 'generation failed').slice(0, 500)}, updated_at = now()+ where replicate_job_id = ${replicateJobId} and client_key = ${clientKey} and status != 'done'+ `;+ } catch (err) {+ console.error('[forge-store] markFailed failed:', err?.message);+ }+}++const VALID_OUTCOMES = new Set(['accepted', 'rejected', 'generated']);++// Capture the human verdict on a creation. Scoped to the owning client so a+// verdict can't be forged for someone else's row. Returns true on a real write.+export async function recordFeedback({ id, clientKey, outcome, downloaded, rating, note }) {+ if (!forgeStoreEnabled() || !id) return false;+ const nextOutcome = VALID_OUTCOMES.has(outcome) ? outcome : null;+ const nextRating =+ Number.isInteger(rating) && rating >= 1 && rating <= 5 ? rating : null;+ const nextNote = typeof note === 'string' && note.trim() ? note.trim().slice(0, 500) : null;+ const markDownloaded = downloaded === true;+ // Nothing meaningful to record → don't touch the row.+ if (!nextOutcome && nextRating === null && nextNote === null && !markDownloaded) return false;+ try {+ const rows = await sql`+ update forge_creations+ set outcome = coalesce(${nextOutcome}, outcome),+ rating = coalesce(${nextRating}, rating),+ note = coalesce(${nextNote}, note),+ downloaded = (downloaded or ${markDownloaded}),+ feedback_at = now(),+ updated_at = now()+ where id = ${id} and client_key = ${clientKey}+ returning id+ `;+ return rows.length > 0;+ } catch (err) {+ console.error('[forge-store] recordFeedback failed:', err?.message);+ return false;+ }+}++// Newest durable creations for one anonymous client — powers the gallery.+export async function listCreations({ clientKey, limit = 24 }) {+ if (!forgeStoreEnabled()) return [];+ const capped = Math.min(Math.max(Number(limit) || 24, 1), 48);+ try {+ const rows = await sql`+ select id, prompt, aspect, glb_url, preview_image_url, outcome, downloaded, created_at+ from forge_creations+ where client_key = ${clientKey} and status = 'done' and glb_url is not null+ order by created_at desc+ limit ${capped}+ `;+ return rows.map((r) => ({+ id: r.id,+ prompt: r.prompt,+ aspect: r.aspect,+ glb_url: r.glb_url,+ preview_image_url: r.preview_image_url,+ outcome: r.outcome,+ downloaded: r.downloaded,+ created_at: r.created_at,+ }));+ } catch (err) {+ console.error('[forge-store] listCreations failed:', err?.message);+ return [];+ }+}diff --git a/api/_lib/migrations/20260604000000_forge_creations.sql b/api/_lib/migrations/20260604000000_forge_creations.sqlnew file mode 100644index 000000000..88268b0c5--- /dev/null+++ b/api/_lib/migrations/20260604000000_forge_creations.sql@@ -0,0 +1,51 @@+-- Forge creations — durable text→3D generations + the data flywheel signal.+--+-- The /forge pipeline (flux-schnell reference image → Microsoft TRELLIS mesh)+-- previously returned the ephemeral Replicate delivery URL and forgot the job.+-- Those URLs expire in ~1h, so generated models evaporated and nothing about+-- the (prompt → image → mesh → human verdict) loop was retained.+--+-- This table is the proprietary data engine: one row per generation, the GLB ++-- reference image copied into our own object storage so they're permanent, and+-- the human outcome (kept / discarded / downloaded) captured as the training+-- signal that lets the in-house model eventually beat the open weights it forks.+--+-- Auth-free by design: /forge has no login, so creations are scoped to a stable+-- anonymous client key (a hashed browser-local id) rather than a user_id.++CREATE TABLE IF NOT EXISTS forge_creations (+ id uuid PRIMARY KEY,+ client_key text NOT NULL, -- sha256 of the browser-local anon id+ ip_hash text, -- sha256 of client ip (abuse triage only)+ prompt text NOT NULL,+ aspect text, -- reference-image aspect ratio (1:1, 4:3, …)+ preview_image_url text, -- durable reference image (our CDN) when copied+ preview_key text, -- object-storage key for the reference image+ replicate_job_id text, -- TRELLIS prediction id (poll correlation)+ text_to_image_model text, -- e.g. black-forest-labs/flux-schnell+ glb_key text, -- object-storage key for the durable mesh+ glb_url text, -- durable public CDN url for the mesh+ size_bytes integer,+ status text NOT NULL DEFAULT 'generating', -- generating | done | failed+ outcome text NOT NULL DEFAULT 'generated', -- generated | accepted | rejected+ downloaded boolean NOT NULL DEFAULT false,+ rating smallint, -- optional 1–5 quality signal+ note text, -- optional free-text feedback+ error text,+ created_at timestamptz NOT NULL DEFAULT now(),+ updated_at timestamptz NOT NULL DEFAULT now(),+ feedback_at timestamptz+);++-- Gallery: newest creations for a given anonymous client.+CREATE INDEX IF NOT EXISTS idx_forge_creations_client+ ON forge_creations (client_key, created_at DESC);++-- Poll correlation: forge.js looks a row up by its TRELLIS prediction id.+CREATE INDEX IF NOT EXISTS idx_forge_creations_job+ ON forge_creations (replicate_job_id);++-- Flywheel export: pull the labeled (kept vs discarded) training pairs.+CREATE INDEX IF NOT EXISTS idx_forge_creations_outcome+ ON forge_creations (outcome, created_at DESC)+ WHERE status = 'done';diff --git a/api/_lib/reconstruct-finalize.js b/api/_lib/reconstruct-finalize.jsnew file mode 100644index 000000000..0387981b9--- /dev/null+++ b/api/_lib/reconstruct-finalize.js@@ -0,0 +1,251 @@+// Reconstruct-finalize — the shared tail of the selfie → 3D pipeline, called by+// both the /api/avatars/regenerate-status poll and the Replicate webhook so the+// two completion paths never drift.+//+// A reconstruction model returns a textured mesh. Whether that mesh is rigged+// depends on the model family: Hunyuan3D's generation_all and our GCP UniRig+// pipeline emit a skeleton; TRELLIS / TripoSR return a static mesh. The /scan+// page promises a *rigged* model you can animate, so when the reconstructed+// mesh has no skeleton AND the active provider has a rig model configured, we+// chain a 'rerig' job and only surface the avatar once it's rigged. If no rig+// model is configured, or rigging fails, we deliver the static mesh tagged+// `unrigged` — the user is never left empty-handed.+//+// Auto-rig is dormant by default: it activates only when the provider reports+// supportsMode('rerig') (e.g. REPLICATE_RERIG_MODEL is set), so existing+// deployments keep their exact current behavior until rigging is wired.++import { sql } from './db.js';+import { putObject, publicUrl } from './r2.js';+import { storageKeyFor, createAvatar } from './avatars.js';+import { inspectGlb, isValidGlbHeader } from './glb-inspect.js';+import { dispatchWebhooks } from './webhook-dispatch.js';+import { getRegenProvider } from './regen-provider.js';++const MAX_GLB_BYTES = 64 * 1024 * 1024; // 64 MB ceiling on a fetched model++async function fetchGlbBuffer(url) {+ const resp = await fetch(url);+ if (!resp.ok) throw new Error(`fetch glb: ${resp.status}`);+ const len = Number(resp.headers.get('content-length') || 0);+ if (len && len > MAX_GLB_BYTES) throw new Error(`glb too large: ${len} bytes`);+ const buf = Buffer.from(await resp.arrayBuffer());+ if (buf.length > MAX_GLB_BYTES) throw new Error(`glb too large: ${buf.length} bytes`);+ return buf;+}++function glbMetaFrom(info) {+ return info+ ? {+ is_rigged: info.isRigged,+ skin_count: info.skinCount,+ skeleton_joint_count: info.skeletonJointCount,+ node_count: info.nodeCount,+ mesh_count: info.meshCount,+ animation_count: info.animationCount,+ glb_generator: info.generator,+ }+ : { is_rigged: null, glb_inspect_error: 'invalid_glb_header' };+}++// Store a reconstructed GLB into R2 and create the durable avatar row, marking+// the job done. Shared by every terminal path (rigged-as-is, rigged-after-chain,+// unrigged fallback) so all three produce an identical avatar shape.+async function materializeReconstructAvatar({+ userId,+ jobId,+ job,+ glbBuf,+ glbInfo,+ storageKey,+ slug,+ extraTags = [],+ sourceMetaExtra = {},+}) {+ const params = job.params || {};+ const name = String(params.name || 'My selfie avatar').slice(0, 120);+ const description = params.description ? String(params.description).slice(0, 500) : null;+ const visibility = ['private', 'unlisted', 'public'].includes(params.visibility)+ ? params.visibility+ : 'private';++ await putObject({+ key: storageKey,+ body: glbBuf,+ contentType: 'model/gltf-binary',+ metadata: { source: 'reconstruct', job_id: jobId },+ });++ const tags = ['selfie', ...extraTags];+ if (glbInfo && !glbInfo.isRigged && !tags.includes('unrigged')) tags.push('unrigged');++ const avatar = await createAvatar({+ userId,+ storageKey,+ input: {+ slug,+ name,+ description,+ size_bytes: glbBuf.length,+ content_type: 'model/gltf-binary',+ source: 'reconstruct',+ source_meta: { jobId, provider: job.provider, ...glbMetaFrom(glbInfo), ...sourceMetaExtra },+ visibility,+ tags,+ checksum_sha256: null,+ parent_avatar_id: null,+ },+ });++ await sql`+ update avatar_regen_jobs+ set result_avatar_id = ${avatar.id}, status = 'done', updated_at = now()+ where job_id = ${jobId} and user_id = ${userId}+ `;++ dispatchWebhooks({+ userId,+ eventType: 'avatar.created',+ data: { id: avatar.id, name: avatar.name, slug: avatar.slug, source: 'reconstruct' },+ }).catch(() => {});++ return avatar;+}++// Stage 1: a reconstruct job just succeeded. Inspect the mesh and either+// deliver it immediately (already rigged, or no rig model available) or kick+// off an auto-rig job and move the parent job into the 'rigging' state.+//+// Returns { status, resultAvatarId? } reflecting the post-call job state.+export async function finalizeReconstructStage({ userId, jobId, job, glbUrl }) {+ const glbBuf = await fetchGlbBuffer(glbUrl);+ const info = isValidGlbHeader(glbBuf) ? inspectGlb(glbBuf) : null;+ const slug = `selfie-${Math.random().toString(36).slice(2, 8)}`;+ const storageKey = storageKeyFor({ userId, slug });++ let provider = null;+ try {+ provider = await getRegenProvider();+ } catch (_) {+ provider = null;+ }+ const canRig = !!(+ info &&+ !info.isRigged &&+ provider?.instance &&+ typeof provider.instance.supportsMode === 'function' &&+ provider.instance.supportsMode('rerig')+ );++ if (!canRig) {+ const avatar = await materializeReconstructAvatar({ userId, jobId, job, glbBuf, glbInfo: info, storageKey, slug });+ return { status: 'done', resultAvatarId: avatar.id };+ }++ // Store the bare mesh durably first: it gives the rig model a stable URL to+ // fetch and guarantees a fallback if rigging fails.+ await putObject({+ key: storageKey,+ body: glbBuf,+ contentType: 'model/gltf-binary',+ metadata: { source: 'reconstruct', job_id: jobId, stage: 'unrigged' },+ });+ const unriggedUrl = publicUrl(storageKey);++ let rigSubmission;+ try {+ rigSubmission = await provider.instance.submit({+ userId,+ mode: 'rerig',+ params: { ...(job.params || {}) },+ sourceUrl: unriggedUrl,+ sourceStorageKey: storageKey,+ });+ } catch (rigErr) {+ // Couldn't even start rigging — deliver the bare mesh now rather than+ // failing the whole reconstruction the user already waited for.+ const avatar = await materializeReconstructAvatar({+ userId,+ jobId,+ job,+ glbBuf,+ glbInfo: info,+ storageKey,+ slug,+ extraTags: ['unrigged'],+ sourceMetaExtra: { rigError: String(rigErr?.message || rigErr) },+ });+ return { status: 'done', resultAvatarId: avatar.id };+ }++ // Drop the (multi-MB base64) source images from the persisted params now that+ // reconstruction is done — the rig stage works off the stored GLB, not the+ // photos — so the job row stays lean across the remaining 'rigging' polls.+ const { images: _images, image: _image, ...leanParams } = job.params || {};+ const nextParams = {+ ...leanParams,+ rig: { extJobId: rigSubmission.extJobId ?? null, storageKey, slug, unriggedUrl },+ };+ await sql`+ update avatar_regen_jobs+ set status = 'rigging', params = ${JSON.stringify(nextParams)}, updated_at = now()+ where job_id = ${jobId} and user_id = ${userId}+ `;+ return { status: 'rigging' };+}++// Stage 2: the parent job is in 'rigging' — poll the child rig job. On success+// swap in the rigged GLB; on failure fall back to the stored bare mesh. Returns+// { status, resultAvatarId? }; status stays 'rigging' while the rig job runs.+export async function pollRiggingStage({ userId, jobId, job }) {+ const rig = (job.params && job.params.rig) || {};+ const slug = rig.slug || `selfie-${Math.random().toString(36).slice(2, 8)}`;+ const storageKey = rig.storageKey || storageKeyFor({ userId, slug });++ let provider = null;+ try {+ provider = await getRegenProvider();+ } catch (_) {+ provider = null;+ }++ // No way to advance (provider gone or no child id): salvage the bare mesh so+ // the job can't hang forever in 'rigging'.+ if (!provider?.instance || !rig.extJobId) {+ if (!rig.unriggedUrl) return { status: 'rigging' };+ const glbBuf = await fetchGlbBuffer(rig.unriggedUrl);+ const info = isValidGlbHeader(glbBuf) ? inspectGlb(glbBuf) : null;+ const avatar = await materializeReconstructAvatar({+ userId, jobId, job, glbBuf, glbInfo: info, storageKey, slug,+ extraTags: ['unrigged'],+ sourceMetaExtra: { rigError: 'rig job not pollable' },+ });+ return { status: 'done', resultAvatarId: avatar.id };+ }++ const update = await provider.instance.status(rig.extJobId);++ if (update.status === 'done' && update.resultGlbUrl) {+ const glbBuf = await fetchGlbBuffer(update.resultGlbUrl);+ const info = isValidGlbHeader(glbBuf) ? inspectGlb(glbBuf) : null;+ const avatar = await materializeReconstructAvatar({+ userId, jobId, job, glbBuf, glbInfo: info, storageKey, slug,+ sourceMetaExtra: { rigged: true, rigJobId: rig.extJobId, reconstructGlb: rig.unriggedUrl },+ });+ return { status: 'done', resultAvatarId: avatar.id };+ }++ if (update.status === 'failed') {+ // Rigging failed — deliver the bare mesh we stored before rigging.+ const glbBuf = await fetchGlbBuffer(rig.unriggedUrl);+ const info = isValidGlbHeader(glbBuf) ? inspectGlb(glbBuf) : null;+ const avatar = await materializeReconstructAvatar({+ userId, jobId, job, glbBuf, glbInfo: info, storageKey, slug,+ extraTags: ['unrigged'],+ sourceMetaExtra: { rigFailed: true, rigError: update.error || null },+ });+ return { status: 'done', resultAvatarId: avatar.id };+ }++ return { status: 'rigging' };+}diff --git a/api/_lib/regen-provider.js b/api/_lib/regen-provider.jsnew file mode 100644index 000000000..ba7739a2d--- /dev/null+++ b/api/_lib/regen-provider.js@@ -0,0 +1,57 @@+// Avatar regeneration provider loader — shared by the regenerate / reconstruct+// endpoints, the reconstruct-finalize stage, and the Replicate webhook.+//+// Dynamically imports a provider module by name so we don't pay the cost of+// loading e.g. the Replicate SDK on every request when regeneration is unused.+// Cached per-process after first load.+//+// Provider name precedence:+// 1. Explicit env: AVATAR_REGEN_PROVIDER=replicate|huggingface|gcp+// 2. Inferred from credentials: REPLICATE_API_TOKEN → replicate,+// GCP_RECONSTRUCTION_URL → gcp, HF_TOKEN → huggingface. Keeps the deploy+// path 1-step: drop the token in env, ship.++let _regenProviderCache = null;+let _regenProviderName = null;++export function resolveProviderName() {+ const explicit = (process.env.AVATAR_REGEN_PROVIDER || '').trim().toLowerCase();+ if (explicit) return explicit;+ // Auto-detect order is paid → free: prefer Replicate's pinned-version+ // reliability, then our own GCP Cloud Run service, then the HF Spaces queue+ // (free GPU but variable wait + cold starts).+ if (process.env.REPLICATE_API_TOKEN) return 'replicate';+ if (process.env.GCP_RECONSTRUCTION_URL) return 'gcp';+ if (process.env.HF_TOKEN) return 'huggingface';+ return 'none';+}++export async function getRegenProvider() {+ const name = resolveProviderName();+ if (name === 'none' || !name) return { name, instance: null };+ if (_regenProviderCache && _regenProviderName === name) {+ return { name, instance: _regenProviderCache };+ }+ if (name === 'replicate') {+ const mod = await import('../_providers/replicate.js');+ _regenProviderCache = mod.createRegenProvider();+ _regenProviderName = name;+ return { name, instance: _regenProviderCache };+ }+ if (name === 'huggingface' || name === 'hf') {+ const mod = await import('../_providers/huggingface.js');+ _regenProviderCache = mod.createRegenProvider();+ _regenProviderName = name;+ return { name, instance: _regenProviderCache };+ }+ if (name === 'gcp') {+ const mod = await import('../_providers/gcp.js');+ _regenProviderCache = mod.createRegenProvider();+ _regenProviderName = name;+ return { name, instance: _regenProviderCache };+ }+ throw Object.assign(new Error(`unknown AVATAR_REGEN_PROVIDER: ${name}`), {+ code: 'regen_provider_unknown',+ status: 501,+ });+}diff --git a/api/_providers/replicate.js b/api/_providers/replicate.jsindex e74529b0c..2b7b8718d 100644--- a/api/_providers/replicate.js+++ b/api/_providers/replicate.js@@ -66,35 +66,57 @@ function modelForMode(mode) {return readEnv(envName) || DEFAULT_MODELS[mode] || null;}-// Map our 5 modes onto the input shape each model expects. The exact shape-// depends on the model; we default to a generic payload and let provider-side-// models pick the fields they care about. Caller-supplied params always win.+// Keys that belong to OUR job/contract envelope and must never be forwarded to+// a Replicate model. Replicate validates prediction input against each model's+// OpenAPI schema; leaking these (or the multi-MB base64 image list) risks a 422+// that fails the whole reconstruction. We map the meaningful ones onto the+// model's real input fields (e.g. `images`) and drop the rest.+const INTERNAL_PARAM_KEYS = Object.freeze([+ 'mode',+ 'name',+ 'description',+ 'visibility',+ 'bodyType',+ 'style',+ 'image',+ 'images',+ 'rig', // chain bookkeeping written by the reconstruct-finalize stage+]);++function stripInternal(params) {+ const out = {};+ for (const [key, value] of Object.entries(params || {})) {+ if (INTERNAL_PARAM_KEYS.includes(key)) continue;+ if (value === undefined) continue;+ out[key] = value;+ }+ return out;+}++// Map our modes onto the input shape each model expects. Caller-supplied+// generation params (seed, texture_size, …) survive and win; internal envelope+// keys are stripped so they never reach the model schema.//-// For `reconstruct` (image-to-3D, no source GLB) we feed `image` from the-// caller's first photo and pass the full list through as `images` for models-// that accept multi-view. This matches the input contracts of the Hunyuan3D-// family and TripoSR — both ignore unrecognized fields.+// For `reconstruct` (image-to-3D) the canonical input across the Hunyuan3D+// family, TRELLIS and TripoSR is an `images` array of URIs — we always send+// that and never the singular `image`/`mode` fields the old payload leaked.function buildInput({ mode, sourceUrl, params }) {+ const clean = stripInternal(params);if (mode === 'reconstruct') {- const photos = Array.isArray(params?.images) ? params.images : [];- const primary = photos[0] || params?.image || sourceUrl;- const base = {- mode,- image: primary,- images: photos.length ? photos : undefined,- prompt: typeof params?.prompt === 'string' ? params.prompt : undefined,- };- return { ...base, ...(params || {}) };+ const photos = Array.isArray(params?.images)+ ? params.images.filter((u) => typeof u === 'string' && u.length > 0)+ : [];+ const primary = photos[0] || (typeof params?.image === 'string' ? params.image : sourceUrl);+ const images = photos.length ? photos : primary ? [primary] : [];+ return { images, ...clean };}- const base = {- mode,+ // remesh / retex / rerig / restyle operate on an existing GLB. Send the+ // source under the two field names cog GLB-pipelines commonly accept.+ return {source_url: sourceUrl,source_glb: sourceUrl,- // Pass through every caller param; later spread wins so explicit- // overrides take precedence over the defaults above.- prompt: typeof params?.prompt === 'string' ? params.prompt : undefined,+ ...clean,};- return { ...base, ...(params || {}) };}function translateStatus(replicateStatus) {@@ -156,6 +178,13 @@ export function createRegenProvider() {|| (readEnv('APP_ORIGIN') ? `${readEnv('APP_ORIGIN').replace(/\/$/, '')}/api/webhooks/replicate` : null);return {+ // True when a model is configured for `mode`. The reconstruct-finalize+ // auto-rig stage consults this before chaining a 'rerig' job, so rigging+ // stays dormant (mesh delivered as-is) until REPLICATE_RERIG_MODEL is set.+ supportsMode(mode) {+ return !!modelForMode(mode);+ },+async submit(request) {const modelRef = modelForMode(request.mode);if (!modelRef) {diff --git a/api/agents.js b/api/agents.jsindex b3acde12d..ac3f1a61e 100644--- a/api/agents.js+++ b/api/agents.js@@ -20,6 +20,7 @@ import { generateAgentWallet, generateSolanaAgentWallet } from './_lib/agent-walimport { checkIdentityIntegrity } from './_lib/identity-integrity.js';import { publicUrl } from './_lib/r2.js';import { pingIndexNow } from './_lib/indexnow.js';+import { publishFeedEvent } from './_lib/feed.js';import { env } from './_lib/env.js';import { z } from 'zod';@@ -287,6 +288,16 @@ async function handleCreate(req, res) {// failures must never block agent creation.pingIndexNow(`${env.APP_ORIGIN}/agent/${agent.id}`).catch(() => {});+ // Announce the new agent on the site-wide live activity ticker — discovery ++ // social proof. Fire-and-forget; never block or fail creation on the feed.+ publishFeedEvent({+ type: 'agent-deploy',+ ts: Date.now(),+ actor: name,+ agentId: agent.id,+ name,+ }).catch(() => {});+return json(res, 201, { agent: decorate(agent) });}diff --git a/api/avatars/_actions.js b/api/avatars/_actions.jsindex 28d9c3825..cda88bd92 100644--- a/api/avatars/_actions.js+++ b/api/avatars/_actions.js@@ -4,7 +4,7 @@import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';import { presignUpload, headObject, r2, publicUrl, putObject } from '../_lib/r2.js';import { storageKeyFor, enforceQuotas, searchPublicAvatars, stripOwnerFor } from '../_lib/avatars.js';-import { listAvatars, createAvatar } from '../_lib/avatars.js';+import { listAvatars } from '../_lib/avatars.js';import { env } from '../_lib/env.js';import { sql } from '../_lib/db.js';import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';@@ -12,63 +12,11 @@ import { parse, presignUploadBody, slug as slugSchema, createAvatarBody } from 'import { recordEvent } from '../_lib/usage.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { requireCsrf } from '../_lib/csrf.js';-import { dispatchWebhooks } from '../_lib/webhook-dispatch.js';import { z } from 'zod';import { randomUUID } from 'crypto';-import { isValidGlbHeader, inspectGlb } from '../_lib/glb-inspect.js';--// ── regen provider loader ─────────────────────────────────────────────────────-// Dynamically import a provider module by name so we don't pay the cost of-// loading e.g. the Replicate SDK on every request when regeneration is unused.-// Cached per-process after first load.-//-// Provider name precedence:-// 1. Explicit env: AVATAR_REGEN_PROVIDER=replicate|huggingface|gcp-// 2. Inferred from credentials: if REPLICATE_API_TOKEN is set with no-// explicit provider, default to 'replicate'. Same for GCP_RECONSTRUCTION_URL.-// This keeps the deploy path 1-step: drop the token in env, ship.-let _regenProviderCache = null;-let _regenProviderName = null;-function resolveProviderName() {- const explicit = (process.env.AVATAR_REGEN_PROVIDER || '').trim().toLowerCase();- if (explicit) return explicit;- // Auto-detect order is paid → free: prefer Replicate's pinned-version- // reliability, then our own GCP Cloud Run service, then the HF Spaces- // queue (free GPU but variable wait + cold starts).- if (process.env.REPLICATE_API_TOKEN) return 'replicate';- if (process.env.GCP_RECONSTRUCTION_URL) return 'gcp';- if (process.env.HF_TOKEN) return 'huggingface';- return 'none';-}-async function getRegenProvider() {- const name = resolveProviderName();- if (name === 'none' || !name) return { name, instance: null };- if (_regenProviderCache && _regenProviderName === name) {- return { name, instance: _regenProviderCache };- }- if (name === 'replicate') {- const mod = await import('../_providers/replicate.js');- _regenProviderCache = mod.createRegenProvider();- _regenProviderName = name;- return { name, instance: _regenProviderCache };- }- if (name === 'huggingface' || name === 'hf') {- const mod = await import('../_providers/huggingface.js');- _regenProviderCache = mod.createRegenProvider();- _regenProviderName = name;- return { name, instance: _regenProviderCache };- }- if (name === 'gcp') {- const mod = await import('../_providers/gcp.js');- _regenProviderCache = mod.createRegenProvider();- _regenProviderName = name;- return { name, instance: _regenProviderCache };- }- throw Object.assign(new Error(`unknown AVATAR_REGEN_PROVIDER: ${name}`), {- code: 'regen_provider_unknown',- status: 501,- });-}+import { isValidGlbHeader } from '../_lib/glb-inspect.js';+import { getRegenProvider } from '../_lib/regen-provider.js';+import { finalizeReconstructStage, pollRiggingStage } from '../_lib/reconstruct-finalize.js';// ── presign ───────────────────────────────────────────────────────────────────@@ -388,10 +336,22 @@ const handleRegenerateStatus = wrap(async (req, res) => {}}- // Materialize the avatar row when a reconstruct job finishes successfully- // but hasn't yet been materialized. We copy the result GLB from the- // provider's URL into our R2 bucket so the avatar is durable, then create- // the avatars row with the user-supplied name/description.+ // Stage 2 — the reconstructed mesh was bare and we kicked off an auto-rig+ // job. Poll that child job; the shared stage swaps in the rigged GLB when it+ // lands, or falls back to the bare mesh so the user is never left empty.+ if (job.status === 'rigging' && job.mode === 'reconstruct' && !job.result_avatar_id) {+ try {+ const result = await pollRiggingStage({ userId, jobId, job });+ job = { ...job, status: result.status, result_avatar_id: result.resultAvatarId ?? job.result_avatar_id };+ } catch (err) {+ job = { ...job, error: job.error || `rig stage failed: ${err?.message}` };+ }+ }++ // Stage 1 — the reconstruct job finished successfully but isn't materialized+ // yet. The shared stage copies the GLB into R2 and either creates the avatar+ // immediately or, when the mesh is unrigged and a rig model is configured,+ // chains a rigging job and moves us into 'rigging' (handled above next poll).if (job.status === 'done' &&job.mode === 'reconstruct' &&@@ -400,69 +360,8 @@ const handleRegenerateStatus = wrap(async (req, res) => {job.result_glb_url) {try {- const params = job.params || {};- const name = (params.name || 'My selfie avatar').toString().slice(0, 120);- const description = params.description ? String(params.description).slice(0, 500) : null;- const visibility = ['private', 'unlisted', 'public'].includes(params.visibility) ? params.visibility : 'private';- const glbResp = await fetch(job.result_glb_url);- if (!glbResp.ok) throw new Error(`fetch result_glb_url: ${glbResp.status}`);- const glbBuf = Buffer.from(await glbResp.arrayBuffer());-- // Probe the GLB to capture rigging state. Reconstruction families- // differ on whether they emit a skeleton (Hunyuan3D yes, TRELLIS/- // TripoSR no) — the UI uses source_meta.is_rigged to badge- // "needs rigging" and to gate animation features.- const info = inspectGlb(glbBuf);- const glbMeta = info- ? {- is_rigged: info.isRigged,- skin_count: info.skinCount,- skeleton_joint_count: info.skeletonJointCount,- node_count: info.nodeCount,- mesh_count: info.meshCount,- animation_count: info.animationCount,- glb_generator: info.generator,- }- : { is_rigged: null, glb_inspect_error: 'invalid_glb_header' };-- const slug = `selfie-${Math.random().toString(36).slice(2, 8)}`;- const key = storageKeyFor({ userId, slug });- await putObject({- key,- body: glbBuf,- contentType: 'model/gltf-binary',- metadata: { source: 'reconstruct', job_id: jobId },- });- const tags = ['selfie'];- if (info && !info.isRigged) tags.push('unrigged');- const avatar = await createAvatar({- userId,- storageKey: key,- input: {- slug,- name,- description,- size_bytes: glbBuf.length,- content_type: 'model/gltf-binary',- source: 'reconstruct',- source_meta: { jobId, provider: job.provider, replicateGlb: job.result_glb_url, ...glbMeta },- visibility,- tags,- checksum_sha256: null,- parent_avatar_id: null,- },- });- await sql`- update avatar_regen_jobs- set result_avatar_id = ${avatar.id}, updated_at = now()- where job_id = ${jobId} and user_id = ${userId}- `;- dispatchWebhooks({- userId,- eventType: 'avatar.created',- data: { id: avatar.id, name: avatar.name, slug: avatar.slug, source: 'reconstruct' },- }).catch(() => {});- job = { ...job, result_avatar_id: avatar.id };+ const result = await finalizeReconstructStage({ userId, jobId, job, glbUrl: job.result_glb_url });+ job = { ...job, status: result.status, result_avatar_id: result.resultAvatarId ?? job.result_avatar_id };} catch (err) {job = { ...job, error: job.error || `materialize failed: ${err?.message}` };}diff --git a/api/chat.js b/api/chat.jsindex 635f6e5e5..d535a7b9b 100644--- a/api/chat.js+++ b/api/chat.js@@ -318,7 +318,9 @@ export default wrap(async (req, res) => {if (body.provider && !ANON_PROVIDERS.has(body.provider)) {return error(res, 401, 'unauthorized', 'sign in to use this model');}- body.provider = 'groq';+ // Honor an explicitly-requested free-tier provider (groq/openrouter);+ // only default to groq when the caller didn't pick one.+ if (!body.provider) body.provider = 'groq';anonymous = true;}@@ -360,7 +362,11 @@ export default wrap(async (req, res) => {// Provider/model failover chain. The first entry is the picked route; if it// returns 429 (rate-limit) or 5xx (provider down) we cycle through a// pre-built fallback list before surfacing an error.- const fallbackRoutes = buildFallbackChain(route, userProviderKeys);+ let fallbackRoutes = buildFallbackChain(route, userProviderKeys);+ // Anonymous traffic must never fail over onto paid providers (OpenAI/+ // Anthropic). Clamp the whole chain to the free-tier anon providers so a+ // rate-limited free model degrades to another free model, never paid keys.+ if (anonymous) fallbackRoutes = fallbackRoutes.filter((r) => ANON_PROVIDERS.has(r.name));let upstream;let routeIdx = 0;diff --git a/api/config.js b/api/config.jsindex feb9bbeb0..f989d8ddd 100644--- a/api/config.js+++ b/api/config.js@@ -1,23 +1,38 @@// Public client-config. Returns non-secret config values the browser needs.import { cors, json, method, wrap } from './_lib/http.js';+import { resolveProviderName } from './_lib/regen-provider.js';export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,OPTIONS', credentials: false })) return;if (!method(req, res, ['GET'])) return;- const regen = (process.env.AVATAR_REGEN_PROVIDER || '').trim().toLowerCase();- const reconstructEnabled = regen !== '' && regen !== 'none';+ // Mirror the reconstruct endpoint's own resolution: an explicit+ // AVATAR_REGEN_PROVIDER, else inferred from a provider credential+ // (REPLICATE_API_TOKEN / GCP_RECONSTRUCTION_URL / HF_TOKEN). Computing it the+ // same way here keeps the feature flag from lying when only a token is set.+ const provider = resolveProviderName();+ const reconstructEnabled = provider !== 'none';++ // Whether the delivered model is auto-rigged (animation-ready). The GCP+ // pipeline rigs inline via UniRig; Replicate rigs only when a rerig model is+ // configured. HF Spaces return static meshes. The /scan page uses this to set+ // honest expectations instead of promising a rig we can't produce.+ const riggingEnabled =+ provider === 'gcp' ||+ (provider === 'replicate' && !!(process.env.REPLICATE_RERIG_MODEL || '').trim());const videoAvatarEnabled = !!(process.env.LONGCAT_WORKER_URL || '').trim();return json(res, 200, {walletConnectProjectId: process.env.VITE_WALLETCONNECT_PROJECT_ID || '',features: {- // /create/selfie uses /api/avatars/reconstruct, which 501s unless an- // ML backend is wired. The selfie page reads this to either show the+ // /create/selfie + /scan use /api/avatars/reconstruct, which 501s+ // unless an ML backend is wired. The pages read this to either show the// capture flow or fall through to a "coming soon — try /create" panel.avatarReconstruct: reconstructEnabled,+ // True when the pipeline returns a rigged (animation-ready) model.+ avatarRigging: riggingEnabled,// /create/video uses the LongCat GPU worker on Cloud Run; only// available once LONGCAT_WORKER_URL is set in Vercel env.videoAvatar: videoAvatarEnabled,diff --git a/api/feed.js b/api/feed.jsnew file mode 100644index 000000000..b73471924--- /dev/null+++ b/api/feed.js@@ -0,0 +1,30 @@+// GET /api/feed — data source for the site-wide live activity ticker.+//+// Public, read-only and cache-friendly. Events are produced across the platform+// (see api/_lib/feed.js); the widget (public/feed.js) polls this every few+// seconds and prepends anything new it hasn't seen. Returns newest-first.++import { wrap, cors, method, json } from './_lib/http.js';+import { readFeedEvents } from './_lib/feed.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET'])) return;++ const url = new URL(req.url, 'http://x');+ const limit = Number(url.searchParams.get('limit')) || 30;+ const events = await readFeedEvents(limit);++ return json(+ res,+ 200,+ { events, count: events.length },+ // Shared edge cache bounds how often polls fall through to Redis. The+ // widget polls every ~20s; an s-maxage at least that long means the CDN+ // serves most polls without an origin hit, and stale-while-revalidate+ // keeps the ticker instant while it refreshes in the background. The feed+ // is a delight layer, so this much staleness is invisible — and it keeps+ // the Upstash request quota from being drained by idle open tabs.+ { 'cache-control': 'public, s-maxage=20, stale-while-revalidate=60' },+ );+});diff --git a/api/forge-feedback.js b/api/forge-feedback.jsnew file mode 100644index 000000000..5ec859d75--- /dev/null+++ b/api/forge-feedback.js@@ -0,0 +1,60 @@+/**+ * Forge feedback — capture the human verdict on a generated 3D model.+ *+ * POST /api/forge-feedback { creation_id, outcome?, downloaded?, rating?, note? }+ *+ * This is the labeled half of the text→3D data flywheel. /forge stores every+ * (prompt → reference image → mesh) triple; this endpoint attaches whether a+ * human kept it, threw it away, downloaded it, or rated it — the signal a future+ * in-house reconstruction model trains and evaluates against.+ *+ * Auth-free like the rest of /forge: writes are scoped to the anonymous client+ * key (x-forge-client header) so a verdict can only be recorded against a row+ * the same browser created. When the store is unconfigured the endpoint returns+ * a clean { ok: false, stored: false } instead of failing.+ */++import { cors, json, method, readJson, wrap } from './_lib/http.js';+import { limits, clientIp } from './_lib/rate-limit.js';+import { hashClient, recordFeedback, forgeStoreEnabled } from './_lib/forge-store.js';++const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS' })) return;+ if (!method(req, res, ['POST'])) return;++ const rl = await limits.mcp3dStatus(clientIp(req));+ if (!rl.success) {+ return json(res, 429, {+ error: 'rate_limited',+ retry_after: Math.ceil((rl.reset - Date.now()) / 1000),+ });+ }++ if (!forgeStoreEnabled()) {+ return json(res, 200, { ok: false, stored: false, reason: 'persistence_unconfigured' });+ }++ const body = await readJson(req, 8_000).catch(() => null);+ const creationId = typeof body?.creation_id === 'string' ? body.creation_id.trim() : '';+ if (!UUID_RE.test(creationId)) {+ return json(res, 400, { error: 'invalid_creation', message: 'creation_id must be a uuid.' });+ }++ const rawClient = req.headers['x-forge-client'];+ const clientKey = hashClient(Array.isArray(rawClient) ? rawClient[0] : rawClient);++ const stored = await recordFeedback({+ id: creationId,+ clientKey,+ outcome: body?.outcome,+ downloaded: body?.downloaded === true,+ rating: Number.isInteger(body?.rating) ? body.rating : undefined,+ note: typeof body?.note === 'string' ? body.note : undefined,+ });++ // `stored: false` means no row matched this client+id (or nothing to write) —+ // not an error worth surfacing to the user, but honest to the caller.+ return json(res, 200, { ok: true, stored });+});diff --git a/api/forge-gallery.js b/api/forge-gallery.jsnew file mode 100644index 000000000..ad051ef30--- /dev/null+++ b/api/forge-gallery.js@@ -0,0 +1,43 @@+/**+ * Forge gallery — the durable creations belonging to one anonymous client.+ *+ * GET /api/forge-gallery → { creations: [...], enabled }+ *+ * Reads the persisted (and durably stored) text→3D models for the browser+ * identified by the x-forge-client header, newest first. Powers the "Your+ * creations" strip on /forge so generated meshes are reusable instead of lost+ * the moment the tab closes.+ *+ * When persistence isn't configured on the deployment it returns+ * { enabled: false, creations: [] } so the page can hide the strip cleanly+ * rather than show a broken state.+ */++import { cors, json, method, wrap } from './_lib/http.js';+import { limits, clientIp } from './_lib/rate-limit.js';+import { hashClient, listCreations, forgeStoreEnabled } from './_lib/forge-store.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.mcp3dStatus(clientIp(req));+ if (!rl.success) {+ return json(res, 429, {+ error: 'rate_limited',+ retry_after: Math.ceil((rl.reset - Date.now()) / 1000),+ });+ }++ if (!forgeStoreEnabled()) {+ return json(res, 200, { enabled: false, creations: [] });+ }++ const rawClient = req.headers['x-forge-client'];+ const clientKey = hashClient(Array.isArray(rawClient) ? rawClient[0] : rawClient);+ const url = new URL(req.url, 'http://localhost');+ const limit = Number(url.searchParams.get('limit')) || 24;++ const creations = await listCreations({ clientKey, limit });+ return json(res, 200, { enabled: true, creations });+});diff --git a/api/forge.js b/api/forge.jsindex 3019d7efd..0c97979a8 100644--- a/api/forge.js+++ b/api/forge.js@@ -20,6 +20,13 @@ import { cors, json, method, readJson, wrap } from './_lib/http.js';import { limits, clientIp } from './_lib/rate-limit.js';import { textToImage } from './_mcp3d/text-to-image.js';import { createRegenProvider } from './_providers/replicate.js';+import {+ hashClient,+ hashIp,+ createCreation,+ materializeCreation,+ markFailed,+} from './_lib/forge-store.js';const VALID_ASPECT = new Set(['1:1', '4:3', '3:4', '16:9', '9:16']);@@ -27,6 +34,14 @@ const VALID_ASPECT = new Set(['1:1', '4:3', '3:4', '16:9', '9:16']);// poll parameter to that shape so we never forward arbitrary strings upstream.const JOB_ID_RE = /^[a-z0-9]{16,64}$/;+// Stable anonymous handle for the browser making the request (/forge has no+// login). Used to scope durable creations + the gallery to one client without+// trusting any of its other input.+function clientKeyFrom(req) {+ const raw = req.headers['x-forge-client'];+ return hashClient(Array.isArray(raw) ? raw[0] : raw);+}+function unconfigured(res) {return json(res, 503, {error: 'unconfigured',@@ -69,8 +84,23 @@ async function startJob(req, res) {mode: 'reconstruct',params: { image: imageUrl, prompt },});++ // Record the generation the moment it starts so the prompt + reference+ // image survive even if the mesh step later fails. Fail-soft: a missing+ // store just means no durable copy + no gallery entry for this run.+ const creationId = await createCreation({+ clientKey: clientKeyFrom(req),+ ipHash: hashIp(ip),+ prompt,+ aspect,+ previewImageUrl: imageUrl,+ replicateJobId: job.extJobId,+ textToImageModel: model,+ });+return json(res, 200, {job_id: job.extJobId,+ creation_id: creationId,status: 'queued',prompt,preview_image_url: imageUrl,@@ -106,11 +136,27 @@ async function pollJob(req, res, jobId) {return unconfigured(res);}+ const clientKey = clientKeyFrom(req);const result = await provider.status(jobId);if (result.status === 'done' && result.resultGlbUrl) {- return json(res, 200, { job_id: jobId, status: 'done', glb_url: result.resultGlbUrl });+ // Copy the mesh + reference image into our own storage so the model is+ // permanent (Replicate delivery URLs expire in ~1h) and serve the durable+ // CDN url. Falls back to the provider url where the store is unavailable.+ const durable = await materializeCreation({+ replicateJobId: jobId,+ clientKey,+ glbUrl: result.resultGlbUrl,+ });+ return json(res, 200, {+ job_id: jobId,+ creation_id: durable?.id ?? null,+ status: 'done',+ glb_url: durable?.glbUrl ?? result.resultGlbUrl,+ durable: Boolean(durable),+ });}if (result.status === 'failed') {+ await markFailed({ replicateJobId: jobId, clientKey, error: result.error });return json(res, 200, {job_id: jobId,status: 'failed',diff --git a/api/pump/[action].js b/api/pump/[action].jsindex 69235caf1..b21dec91a 100644--- a/api/pump/[action].js+++ b/api/pump/[action].js@@ -60,6 +60,7 @@ import { env } from '../_lib/env.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { parse } from '../_lib/validate.js';import { randomToken } from '../_lib/crypto.js';+import { publishFeedEvent } from '../_lib/feed.js';import { normalizeGatewayURL } from '../../src/ipfs.js';import {getConnection,@@ -417,6 +418,18 @@ async function handleBuyConfirm(req, res) {`;}+ // Surface the buy on the site-wide live activity ticker. The tx is already+ // verified on-chain above, so this is a real, confirmed purchase. Fire-and-+ // forget: never let the delight layer delay or fail the buy response.+ publishFeedEvent({+ type: 'coin-buy',+ ts: Date.now(),+ actor: shortAddr(body.wallet_address),+ mint: body.mint,+ sol: body.sol,+ network: body.network,+ }).catch(() => {});+return json(res, 200, {ok: true,tracked: !!mintId,@@ -426,6 +439,13 @@ async function handleBuyConfirm(req, res) {});}+// Truncate a base58 address for public display: "AbCd…WxYz". The feed is world-+// readable, so we only ever surface the head/tail, never the full key.+function shortAddr(addr) {+ const s = String(addr || '');+ return s.length > 10 ? `${s.slice(0, 4)}…${s.slice(-4)}` : s;+}+// ── sell-prep ──────────────────────────────────────────────────────────────const sellPrepSchema = z.object({diff --git a/api/webhooks/replicate.js b/api/webhooks/replicate.jsindex 774cca861..dfa17184b 100644--- a/api/webhooks/replicate.js+++ b/api/webhooks/replicate.js@@ -22,10 +22,8 @@import { createHmac, timingSafeEqual } from 'node:crypto';import { sql } from '../_lib/db.js';-import { putObject } from '../_lib/r2.js';-import { storageKeyFor, createAvatar } from '../_lib/avatars.js';import { json, method, wrap, error } from '../_lib/http.js';-import { inspectGlb } from '../_lib/glb-inspect.js';+import { finalizeReconstructStage } from '../_lib/reconstruct-finalize.js';const REPLAY_WINDOW_SECONDS = 5 * 60;@@ -196,9 +194,12 @@ export default wrap(async (req, res) => {where job_id = ${job.job_id}`;- // Materialize the avatar inline when this is a reconstruct job that just- // succeeded — the user's status poll will see resultAvatarId on its next- // hit instead of waiting one more round-trip for the fetch+putObject pair.+ // Finalize inline when this is a reconstruct job that just succeeded — the+ // user's status poll then sees resultAvatarId (or the 'rigging' stage) on its+ // next hit instead of waiting a round-trip. The shared stage handles the+ // rig-or-materialize decision, identical to the poll path, so the two never+ // drift. isAllowedResultUrl pins the fetch to Replicate's delivery hosts+ // (SSRF guard) before we hand the URL off.if (nextStatus === 'done' &&nextGlbUrl &&@@ -207,78 +208,16 @@ export default wrap(async (req, res) => {!job.result_avatar_id) {try {- const params = job.params || {};- const name = String(params.name || 'My selfie avatar').slice(0, 120);- const description = params.description ? String(params.description).slice(0, 500) : null;- const visibility = ['private', 'unlisted', 'public'].includes(params.visibility)- ? params.visibility- : 'private';-- const glbResp = await fetch(nextGlbUrl);- if (!glbResp.ok) throw new Error(`fetch result_glb_url: ${glbResp.status}`);- const glbBuf = Buffer.from(await glbResp.arrayBuffer());-- // Probe the GLB JSON chunk to capture rigging state. Reconstruction- // model families differ on this: Hunyuan3D's generation_all returns- // a rigged textured GLB, but TRELLIS / TripoSR return static- // meshes. Surfacing is_rigged in source_meta lets the UI badge- // "needs rigging" + lets a future auto-rig pass enqueue itself- // against avatars that lack a skeleton.- const info = inspectGlb(glbBuf);- const glbMeta = info- ? {- is_rigged: info.isRigged,- skin_count: info.skinCount,- skeleton_joint_count: info.skeletonJointCount,- node_count: info.nodeCount,- mesh_count: info.meshCount,- animation_count: info.animationCount,- glb_generator: info.generator,- }- : { is_rigged: null, glb_inspect_error: 'invalid_glb_header' };-- const slug = `selfie-${Math.random().toString(36).slice(2, 8)}`;- const key = storageKeyFor({ userId: job.user_id, slug });- await putObject({- key,- body: glbBuf,- contentType: 'model/gltf-binary',- metadata: { source: 'reconstruct', job_id: job.job_id },- });- const tags = ['selfie'];- if (info && !info.isRigged) tags.push('unrigged');- const avatar = await createAvatar({+ await finalizeReconstructStage({userId: job.user_id,- storageKey: key,- input: {- slug,- name,- description,- size_bytes: glbBuf.length,- content_type: 'model/gltf-binary',- source: 'reconstruct',- source_meta: {- jobId: job.job_id,- provider: 'replicate',- replicateGlb: nextGlbUrl,- via: 'webhook',- ...glbMeta,- },- visibility,- tags,- checksum_sha256: null,- parent_avatar_id: null,- },+ jobId: job.job_id,+ job: { ...job, provider: 'replicate' },+ glbUrl: nextGlbUrl,});- await sql`- update avatar_regen_jobs- set result_avatar_id = ${avatar.id}, updated_at = now()- where job_id = ${job.job_id}- `;} catch (err) {- // Materialization failure isn't fatal for the webhook ack — the- // next /regenerate-status poll will retry the materialize path.- console.warn('[replicate-webhook] materialize failed', { jobId: job.job_id, error: err?.message });+ // Finalize failure isn't fatal for the webhook ack — the next+ // /regenerate-status poll will retry the materialize/rig path.+ console.warn('[replicate-webhook] finalize failed', { jobId: job.job_id, error: err?.message });}}diff --git a/docs/nvidia-inception/index.html b/docs/nvidia-inception/index.htmlindex cd028db53..aa8c26dab 100644--- a/docs/nvidia-inception/index.html+++ b/docs/nvidia-inception/index.html@@ -139,7 +139,7 @@<tr><td><strong>Embed</strong></td><td><code><agent-3d></code> web component + 5 widgets, OpenGraph/oEmbed, versioned CDN — agent into any site</td><td><span style="color:var(--nv);font-family:'JetBrains Mono';font-size:.85em;">✅ Live</span></td></tr></tbody></table>- <p class="sub" style="margin-top:1em;"><strong style="color:#fff;">Plus a shipped social layer:</strong> multiplayer 3D worlds (/play, /club, /city, /game), presence & DMs, voice/pose/mocap studios, and a paid agent-to-agent economy (x402).</p>+ <p class="sub" style="margin-top:1em;"><strong style="color:#fff;">Plus a shipped social layer:</strong> multiplayer 3D worlds (/play, /club, /city), presence & DMs, voice/pose/mocap studios, and a paid agent-to-agent economy (x402).</p><div class="foot"><span class="logo">three<span class="dot">.</span>ws</span><span>Product</span></div></section>diff --git a/docs/roadmap/3d-world-fun.md b/docs/roadmap/3d-world-fun.mdindex 33b6aadf9..d4ef9c2f7 100644--- a/docs/roadmap/3d-world-fun.md+++ b/docs/roadmap/3d-world-fun.md@@ -1,8 +1,8 @@-# three.ws — 3D World "Make It Fun" Roadmap (25 agent tasks)+# three.ws — 3D World "Make It Fun" Roadmap (18 agent tasks)Goal: turn the existing 3D worlds from a pretty hangout into a place with things to **do**-together — Roblox-style social play + mini-games + avatar economy, plus rendering the-already-built Kintara RPG, plus a Minecraft-style shared sandbox.+together — Roblox-style social play + mini-games + avatar economy, plus a Minecraft-style+shared sandbox.## How to run this@@ -18,7 +18,6 @@ Key existing files (for reference, don't make agents re-discover these):- `/play` scene: `src/game/coincommunities.js`, `coincommunities-ui.js`, `coincommunities.css`- `/play` net client: `src/game/community-net.js`- Server: `multiplayer/src/rooms/WalkRoom.js`, `multiplayer/src/schemas.js`-- RPG server (done, unrendered): `multiplayer/src/rooms/GameRoom.js`, `multiplayer/src/schemas/game.js`, `multiplayer/src/rooms/realms.js`; client net `src/game/game-net.js`- Avatars/anim: `src/animation-manager.js`, `public/animations/manifest.json` (70 clips)- Accessory GLBs (unwired): `public/accessories/` (hats, glasses, earrings)- Payments: `api/x402/`, `agent-payments-sdk/`, `solana-agent-sdk/`@@ -125,78 +124,12 @@ and broadcasts via the existing emote path, accessible (keyboard + screen-reader----## WAVE 2 — Render the Kintara RPG (mostly sequential; this is the big one)--> The server (`GameRoom.js`), schema (`schemas/game.js`), realms (`realms.js`), and client net-> (`game-net.js`) are COMPLETE. These tasks build the missing 3D client. Do them in order.--### Task 10 — Kintara scene scaffold + tile renderer-Create the entry: `pages/game.html` + `src/game/kintara.js` (mirror how `play.html` →-`coincommunities.js` is wired). Connect via `GameNet` (`src/game/game-net.js`) to `GameRoom`. Set up-a Three.js scene with an **orthographic isometric** camera (rotatable yaw, fixed pitch ~35°), and on-the `realm` message render the tile grid: floor tiles, blocked/water tiles, zone tints-(safe/PvP/danger), bank zone, fishing/cooking tiles, fountain. Reuse the renderer/lighting/loop-structure from `coincommunities.js`. No players/nodes yet.-**Done:** entering loads a realm and draws its grid correctly with zones visually distinct; camera-orbits/zooms; matches the realm data in `realms.js`.--### Task 11 — Kintara players: avatars on the tile grid-Render local + remote players from `GamePlayer` state. Reuse the avatar rig + AnimationManager from-`coincommunities.js` (`buildAvatar`, `RemotePlayer` interpolation). Convert tile coords (`tx,ty`) →-world position, animate tile-stepped movement (smooth glide between adjacent tiles), drive-idle/walk/run motion states, render name labels (reuse the projected-label system) and HP bars.-Send `step` intents from WASD/click-to-move respecting the server's 8-way adjacency.-**Depends on:** Task 10. **Done:** you and others walk the grid smoothly, animations match motion,-names + HP show, movement is server-validated (no teleport).--### Task 12 — Resource nodes + gathering-Render `ResourceNode` state (trees, rocks, coal) as meshes on their tiles; show depleted/respawning-states. Wire the `gather` intent: walk adjacent + click a node to harvest (server gates on-tool+skill). Add harvest feedback — swing animation, a glow/particle on hit, an item-gained toast,-and node depletion/respawn visuals.-**Depends on:** Task 11. **Done:** gathering works end-to-end against the server (wood/stone/coal),-respects tool/skill gates, feels responsive with clear feedback.--### Task 13 — Combat + mobs-Render `Mob` state (training dummy, goblin, ogre) with HP bars, idle/roam animation, aggro, hit-flashes, death + respawn. Wire the `attack` intent (sword equipped + adjacent). Add hit feedback-(damage numbers, flash, knockback tween), death VFX, and your own death/respawn handling. Respect-PvP/safe zones from realm data.-**Depends on:** Task 11. **Done:** combat loop works vs mobs, HP/damage/death/respawn all sync,-zones enforced, feels punchy.--### Task 14 — Inventory + hotbar + bank UI-Build the RPG UI chrome (new `src/game/kintara-ui.js`, styled to match the `cc-*` token system):-24-slot backpack with drag-reorder (`invMove`), 6-slot hotbar with equip (`equip`/`activeSlot`),-item tooltips/icons/stack counts, and the bank window (`bankOpen`/`bankDeposit`/`bankWithdraw`) that-opens near the Mainland bank zone. All wired to `GameNet`.-**Depends on:** Tasks 12, 13 (so there are items to hold). **Done:** drag/drop, equip, and banking-all work against the server with correct state; polished, keyboard-navigable, designed empty states.--### Task 15 — Skills HUD + XP/level feedback-A skills panel (combat, woodcutting, mining, fishing, cooking) showing level + XP progress from-player state, with level-up celebration VFX/sound and floating XP toasts on each gather/kill. Fishing-(cast at fishing tiles) and cooking (at the roast pit) action UIs — the server logic exists; add the-client interactions + a small timing element to make them feel like mini-games.-**Depends on:** Tasks 12, 13. **Done:** levels/XP display live, level-ups feel rewarding, fishing &-cooking are playable and fun, all server-validated.--### Task 16 — Realm portals + travel + minimap-Render portals as meshes at their tiles; walking into one triggers the realm transition (re-render-via Task 10's path) with a transition wipe. Add a minimap (top-down of the current realm with-players/nodes/portals) and a zone banner ("⚔️ Wilderness — PvP"). Add a discovery/world-select entry-so players can find Kintara from the site.-**Depends on:** Task 10. **Done:** travel between all 4 realms works smoothly, minimap is accurate,-zones are clearly communicated, Kintara is reachable from navigation.------## WAVE 3 — Sandbox building (Minecraft-style; depends on Wave 0 object sync)### Task 17 — Persistence layer for world objectsMake placed objects durable per coin world. Add a storage-backed API/worker (use the existing`api/`/`workers/` patterns and whatever KV/DB the repo already uses — inspect, don't invent a new-provider) keyed by coin mint. `GameRoom`/`WalkRoom` loads saved objects on room create and persists+provider) keyed by coin mint. `WalkRoom` loads saved objects on room create and persistson `obj:spawn/update/remove` (debounced). Real backend, no in-memory-only.**Depends on:** Task 1. **Done:** placing objects, leaving, and re-entering a coin world shows thesame build; persistence survives server restart.@@ -270,10 +203,9 @@ flex/leaderboard surface is live and links back into worlds.1. **Wave 0** (Tasks 1→2→3) — sequential, unblocks everything. ~3 chats.2. **Wave 1** (Tasks 4–9) — parallel, 6 chats. Fastest visible fun.-3. **Wave 2** (Tasks 10→11→{12,13}→{14,15,16}) — the RPG, ~7 chats, mostly ordered.-4. **Wave 3** (Tasks 17→18→19→20) — building, 4 chats.-5. **Wave 4** (Tasks 21→22→{23,24,25}) — economy, 5 chats.+3. **Wave 3** (Tasks 17→18→19→20) — building, 4 chats.+4. **Wave 4** (Tasks 21→22→{23,24,25}) — economy, 5 chats.-Total: 25. Within a wave, only parallelize tasks that don't edit the same file — Wave-1 tasks each+Total: 18. Within a wave, only parallelize tasks that don't edit the same file — Wave-1 tasks eachadd their own modules but several touch `WalkRoom.js`/`coincommunities-ui.js`, so stagger those orhave one agent own the shared file per wave.diff --git a/multiplayer/src/avatar-url.js b/multiplayer/src/avatar-url.jsindex 9c174a0df..763c773f3 100644--- a/multiplayer/src/avatar-url.js+++ b/multiplayer/src/avatar-url.js@@ -1,4 +1,4 @@-// Shared avatar-URL sanitizer for every authoritative room (WalkRoom, GameRoom).+// Shared avatar-URL sanitizer for the authoritative room (WalkRoom).//// We only ever broadcast avatar URLs we'd be willing to load cross-origin: our// own origins and the public model hosts. Site-relative paths are always fine.diff --git a/multiplayer/src/economy.js b/multiplayer/src/economy.jsindex 11e3c1421..a75ae35e9 100644--- a/multiplayer/src/economy.js+++ b/multiplayer/src/economy.js@@ -1,11 +1,9 @@// Economy & progression for the /play coin worlds.//-// The /game isometric MMO (GameRoom) keeps inventory, hotbar, gold and skills on-// the synced Colyseus schema because peers render each other's equipped tools and-// mounts on a tile grid. /play is a free-roam, per-coin social world where a-// player's pack and purse are PRIVATE — no peer needs to see them — so we keep all-// of it OFF the shared WalkState schema and stream each owner only their own state-// via targeted messages (the same pattern GameRoom already uses for skills/xpgain).+// /play is a free-roam, per-coin social world where a player's pack and purse are+// PRIVATE — no peer needs to see them — so we keep all of it OFF the shared+// WalkState schema and stream each owner only their own state via targeted+// messages.//// That keeps the /walk experience (which shares the same schema) untouched, costs// peers zero extra wire bytes, and lets the economy grow (cooking, gathering,@@ -31,8 +29,8 @@ export const SKILLS = ['combat', 'woodcutting', 'mining', 'fishing', 'cooking'];// the later phases (woodcutting/mining/combat) will use. Tools occupy the hotbar.const STARTER_HOTBAR = ['rod', 'axe', 'pickaxe', 'sword'];-// XP curve — identical to GameRoom's so progression is consistent across the-// platform: level n needs 50 * n^1.8 cumulative XP, capped at LEVEL_CAP.+// XP curve — the canonical progression for the platform: level n needs+// 50 * n^1.8 cumulative XP, capped at LEVEL_CAP.export function levelForXp(xp) {let lvl = 1;while (lvl < LEVEL_CAP && xp >= Math.floor(50 * Math.pow(lvl, 1.8))) lvl++;@@ -98,8 +96,7 @@ export function restoreProfile(saved, playerId = '') {return base;}-// The persisted slice (mirrors GameRoom._serializeProfile so the two stores stay-// interchangeable for an account that plays both surfaces).+// The persisted slice written through to the account-keyed player store.export function serializeProfile(profile) {const slots = (arr) => arr.map((s) => ({ item: s.item, qty: s.qty }));return {@@ -127,7 +124,7 @@ export function hasRoomFor(profile, item) {}// Add `qty` of `item` to the backpack, filling existing stacks first. Returns the-// quantity that did NOT fit (0 = everything landed). Mirrors GameRoom._addItem.+// quantity that did NOT fit (0 = everything landed).export function addItem(profile, item, qty) {let left = qty;const inv = profile.inv;@@ -157,7 +154,7 @@ export function addItem(profile, item, qty) {}// Resolve a client slot reference { zone:'inv'|'hotbar', i } to the live slot-// object, or null when out of range. Validated like GameRoom._resolveSlot so a+// object, or null when out of range. Validated server-side so a// crafted index can never read outside the arrays.export function resolveSlot(profile, ref) {if (!ref || typeof ref !== 'object') return null;diff --git a/multiplayer/src/feed.js b/multiplayer/src/feed.jsnew file mode 100644index 000000000..75b99a0a0--- /dev/null+++ b/multiplayer/src/feed.js@@ -0,0 +1,86 @@+// Live activity feed — the multiplayer server's producer half.+//+// The standalone game server emits the in-world half of the site-wide activity+// ticker (level-ups, world-joins, jackpots). It writes to the SAME capped Redis+// list the serverless API reads from (`feed:events`), mirroring how+// presence-store splits writer (this server) from reader (api/_lib/feed.js).+// Keep the key and event shape in lockstep with api/_lib/feed.js.+//+// Every publish is best-effort and self-throttled: the feed is a delight layer,+// never on the gameplay critical path. Redis being unreachable, or the server+// running memory-only, simply means no events — never a thrown error in a room+// handler.++const REDIS_URL = process.env.UPSTASH_REDIS_REST_URL || '';+const REDIS_TOKEN = process.env.UPSTASH_REDIS_REST_TOKEN || '';++const FEED_KEY = 'feed:events';+const MAX_EVENTS = 200;+const ALLOWED_TYPES = new Set(['coin-buy', 'agent-deploy', 'level-up', 'world-join', 'jackpot']);++// Per-event-kind cooldown so a busy world can't flood the global ticker with a+// hundred near-identical lines. Keyed by `${type}:${dedupeKey}`.+const THROTTLE_MS = 60_000;+const _lastByKey = new Map();++let _redis = null;+let _redisReady = null;+let _seq = 0;++if (REDIS_URL && REDIS_TOKEN) {+ _redisReady = import('@upstash/redis')+ .then(async ({ Redis }) => {+ _redis = new Redis({ url: REDIS_URL, token: REDIS_TOKEN });+ await _redis.ping();+ console.log('[feed] activity feed: writing to Upstash Redis (verified)');+ })+ .catch((err) => {+ _redis = null;+ console.warn('[feed] Redis unreachable — activity events will be dropped:', err?.message);+ });+} else {+ console.log('[feed] activity feed disabled (no UPSTASH_REDIS_REST_URL/_TOKEN)');+}++function eventId(ts) {+ _seq = (_seq + 1) % 1_000_000;+ return `${ts.toString(36)}-${_seq.toString(36)}`;+}++// Fire-and-forget. `dedupeKey` collapses repeats of the same kind within the+// throttle window (e.g. the same player levelling several skills in a flurry).+// Returns a promise only so callers may await in tests; room handlers should+// not await it.+export function publishFeedEvent(event, dedupeKey = '') {+ if (!_redis || !event || !ALLOWED_TYPES.has(event.type)) return Promise.resolve(null);++ const now = Date.now();+ const throttleKey = `${event.type}:${dedupeKey}`;+ if (dedupeKey) {+ const last = _lastByKey.get(throttleKey) || 0;+ if (now - last < THROTTLE_MS) return Promise.resolve(null);+ _lastByKey.set(throttleKey, now);+ // Bound the throttle map: drop entries older than the window on each write.+ if (_lastByKey.size > 5000) {+ for (const [k, t] of _lastByKey) if (now - t > THROTTLE_MS) _lastByKey.delete(k);+ }+ }++ const ts = Number.isFinite(event.ts) ? event.ts : now;+ const record = { ...event, ts, id: event.id || eventId(ts) };+ return (async () => {+ try {+ await _redis.lpush(FEED_KEY, JSON.stringify(record));+ await _redis.ltrim(FEED_KEY, 0, MAX_EVENTS - 1);+ return record;+ } catch (err) {+ console.warn('[feed] publish failed:', err?.message);+ return null;+ }+ })();+}++// Exposed for tests / graceful shutdown sequencing.+export function feedReady() {+ return _redisReady || Promise.resolve();+}diff --git a/multiplayer/src/game-token.js b/multiplayer/src/game-token.jsindex 85a235433..3eda58e3a 100644--- a/multiplayer/src/game-token.js+++ b/multiplayer/src/game-token.js@@ -12,8 +12,8 @@// and checks both legs landed at the right destinations for the right amounts.//// Quotes are sealed into an HMAC-SHA256 token (identical construction to-// realm-transfer.js / holder-pass.js) so a client can't move the price, swap the-// recipient, or replay an old quote after the market moves.+// holder-pass.js) so a client can't move the price, swap the recipient, or+// replay an old quote after the market moves.import crypto from 'node:crypto';import { Connection, PublicKey, Transaction, TransactionInstruction } from '@solana/web3.js';@@ -283,7 +283,7 @@ function accountKeyAt(tx, index) {// treasury) and a memo binding the on-chain tx to the exact quote it settles:// buildSpinPayment() → client signs+broadcasts → verifySpinPayment().// Replay protection (a settled signature/nonce can't roll a second prize) is the-// caller's responsibility — the GameRoom tracks consumed nonces per process and+// caller's responsibility — the caller tracks consumed nonces per process and// the short quote TTL bounds the window.// Split a total into burn + treasury legs by basis points. Treasury absorbs thediff --git a/multiplayer/src/index.js b/multiplayer/src/index.jsindex 55ba58827..d7e5948e0 100644--- a/multiplayer/src/index.js+++ b/multiplayer/src/index.js@@ -23,7 +23,6 @@ import { WalkRoom } from './rooms/WalkRoom.js';import { blockStore } from './block-store.js';import { worldPersistence } from './persistence.js';import { flushAllPlayers } from './playerStore.js';-import { marketplaceStore } from './marketplaceStore.js';import { socialHub } from './social-hub.js';import { verifyNotifySignature } from './presence-token.js';@@ -193,9 +192,7 @@ gameServer.listen(PORT, HOST).then(() => {console.log(`[multiplayer] listening on ws://${HOST}:${PORT}`);- console.log(`[multiplayer] rooms: walk_world, game_{${Object.keys(REALMS).join(',')}}`);- console.log(`[multiplayer] world instances: ${SERVERS.map((s) => `${s.id} (${s.name})`).join(', ')}`);- console.log(`[multiplayer] discovery: GET /servers`);+ console.log(`[multiplayer] rooms: walk_world`);console.log(`[multiplayer] allowed origins: ${ALLOWED_ORIGINS.join(', ')}`);}).catch((err) => {@@ -245,13 +242,6 @@ const shutdown = async (signal) => {} catch (err) {console.error('[multiplayer] final player flush error:', err);}- // And the marketplace (Task 20): flush any debounced listing/payout writes so a- // redeploy never drops an active listing or a seller's owed proceeds.- try {- await marketplaceStore.flushAll();- } catch (err) {- console.error('[multiplayer] final market flush error:', err);- }process.exit(0);};process.on('SIGTERM', () => shutdown('SIGTERM'));diff --git a/multiplayer/src/items.js b/multiplayer/src/items.jsindex a068dd91f..40be49b56 100644--- a/multiplayer/src/items.js+++ b/multiplayer/src/items.js@@ -3,7 +3,7 @@// item ids inline, so stacking, edibility, heal values, and mount tuning are// data-driven and an item means the same thing everywhere it appears.//-// Reused by the GameRoom (gather/cook/consume/banking/loot/mounts) and, going+// Reused by the /play coin-world economy (gather/cook/consume/banking) and, going// forward, by the marketplace and the shop — they all describe items in the// same vocabulary so a "cookedFish" is identical whether it was cooked, looted,// or bought.diff --git a/multiplayer/src/playerStore.js b/multiplayer/src/playerStore.jsindex 296be7703..279fb9242 100644--- a/multiplayer/src/playerStore.js+++ b/multiplayer/src/playerStore.js@@ -12,7 +12,7 @@// instance, so the Map alone already carries a profile between realms (each// realm is its own room in one process) and across a reconnect. It is also// the synchronous read/write cache that keeps loadPlayer/savePlayer cheap on-// the hot path — the GameRoom persists on every meaningful change and reads+// the hot path — the WalkRoom persists on every meaningful change and reads// back inside its eviction/leave paths, all synchronously against the Map.// 2. Upstash Redis (REST), used when UPSTASH_REDIS_REST_URL + _TOKEN are set.// This is what makes a profile durable across restarts and shareable across@@ -27,7 +27,7 @@// only); with it, progress outlives the process.//// One-active-session-per-account integrity (Task 16 rule 6) is enforced upstream-// by the presence-based eviction in GameRoom (see presence-keys.js): a fresh+// by the presence-based eviction in WalkRoom (see presence-keys.js): a fresh// login persists and disconnects the stale session before taking over, so two// sessions never fork-and-clobber one profile. This module is purely the store.@@ -177,11 +177,11 @@ class PlayerStore {}}-// One store shared by every GameRoom instance in the process — that shared memory+// One store shared by every WalkRoom instance in the process — that shared memory// is what lets a profile travel between realms without a Redis hop.export const playerStore = new PlayerStore();-// Backwards-compatible functional API. The GameRoom persists synchronously on the+// Backwards-compatible functional API. The WalkRoom persists synchronously on the// hot path (loadPlayer/savePlayer), and the durable Redis tier rides underneath// via the write-behind cache. hydratePlayer/flushPlayer/flushAllPlayers expose the// async durability hooks for the join, leave/dispose, and shutdown paths.diff --git a/multiplayer/src/rooms/WalkRoom.js b/multiplayer/src/rooms/WalkRoom.jsindex 23fecd4d6..502e70a48 100644--- a/multiplayer/src/rooms/WalkRoom.js+++ b/multiplayer/src/rooms/WalkRoom.js@@ -23,6 +23,7 @@ import {import { itemLabel, fishCatchChance, fishDoubleChance } from '../items.js';import { fishingSpotInRange } from '../world-features.js';import { hydratePlayer, loadPlayer, savePlayer, flushPlayer } from '../playerStore.js';+import { publishFeedEvent } from '../feed.js';// Platform entry gate (wallet-first sign-in + game-token balance). When a game// token is pinned (PLAY_GATE_MINT, falling back to THREE_MINT) every join must@@ -348,6 +349,20 @@ export class WalkRoom extends Room {console.log(`[walk_world ${this.roomId} coin=${this.state.coin || 'mainland'}${tierTag}] +join ${client.sessionId} ${name} (n=${this.state.players.size})`,);++ // "Someone is hanging out in <world>" — social proof + FOMO on the site-wide+ // ticker. Throttled per world so a popular coin emits at most once a minute,+ // not once per arrival. Mainland falls back to a friendly label.+ publishFeedEvent(+ {+ type: 'world-join',+ ts: Date.now(),+ actor: name,+ coin: this.state.coin || '',+ coinName: this.state.coinName || (this.state.coin ? '' : 'Mainland'),+ },+ this.state.coin || 'mainland',+ );}onLeave(client) {@@ -557,7 +572,27 @@ export class WalkRoom extends Room {skill: res.skill, amount: res.amount, xp: res.xp,level: res.level, levelXp: res.levelXp, nextXp: res.nextXp,});- if (res.leveledUp) client.send('levelup', { skill: res.skill, level: res.level });+ if (res.leveledUp) {+ client.send('levelup', { skill: res.skill, level: res.level });+ // Broadcast milestone level-ups (every 10th + the level-99 cap) to the+ // site-wide ticker. Early levels come fast and would be noise; milestones+ // are real achievements worth celebrating publicly. Throttled per+ // player+skill so a burst can't spam the global feed.+ if (res.level === 99 || res.level % 10 === 0) {+ const player = this.state.players.get(client.sessionId);+ publishFeedEvent(+ {+ type: 'level-up',+ ts: Date.now(),+ actor: player?.name || 'A player',+ skill: res.skill,+ level: res.level,+ coin: this.state.coin || '',+ },+ `${player?.account || client.sessionId}:${res.skill}`,+ );+ }+ }}// Cast a line. Validates (rod on the active slot, beside a pond, off cooldown,@@ -644,8 +679,8 @@ export class WalkRoom extends Room {}// Write this session's economy profile through to the account-keyed store,- // merging onto any existing record so non-economy fields (e.g. a /game profile- // for the same account) are preserved. Synchronous + debounced like GameRoom.+ // merging onto any existing record so unrelated fields for the same account+ // are preserved. Synchronous + debounced._persistEcon(sessionId) {const profile = this.econ.get(sessionId);if (!profile || !profile.playerId) return;diff --git a/pages/forge.html b/pages/forge.htmlindex 88cfac1cb..5402c8a1f 100644--- a/pages/forge.html+++ b/pages/forge.html@@ -331,6 +331,132 @@flex: none;}+ /* Keep / discard verdict (the flywheel signal) */+ .verdict {+ display: inline-flex;+ gap: 2px;+ background: var(--surface-1);+ border: 1px solid var(--stroke);+ border-radius: var(--radius-md);+ padding: 2px;+ }+ .verdict button {+ background: transparent;+ border: none;+ color: var(--ink-dim);+ font-size: var(--text-sm);+ padding: 0.34rem 0.6rem;+ border-radius: var(--radius-sm);+ cursor: pointer;+ transition: background 0.15s, color 0.15s;+ }+ .verdict button:hover {+ color: var(--ink);+ }+ .verdict button:focus-visible {+ outline: 2px solid var(--accent);+ outline-offset: 2px;+ }+ .verdict button[aria-pressed='true'][data-outcome='accepted'] {+ background: color-mix(in srgb, var(--success) 22%, transparent);+ color: var(--success);+ }+ .verdict button[aria-pressed='true'][data-outcome='rejected'] {+ background: color-mix(in srgb, var(--danger) 20%, transparent);+ color: var(--danger);+ }++ /* Your creations gallery -------------------------------------- */+ .creations {+ margin-top: var(--space-2xl);+ }+ .creations-head {+ display: flex;+ align-items: baseline;+ justify-content: space-between;+ gap: var(--space-sm);+ margin-bottom: var(--space-md);+ }+ .creations-head h2 {+ font-family: var(--font-display);+ font-size: var(--text-lg);+ margin: 0;+ }+ .creations-head .count {+ font-family: var(--font-mono);+ font-size: var(--text-xs);+ color: var(--ink-dim);+ }+ .creations-grid {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));+ gap: var(--space-sm);+ }+ .creation {+ position: relative;+ display: flex;+ flex-direction: column;+ text-align: left;+ background: var(--surface-1);+ border: 1px solid var(--stroke);+ border-radius: var(--radius-md);+ overflow: hidden;+ cursor: pointer;+ padding: 0;+ color: inherit;+ font: inherit;+ transition: border-color 0.15s, transform 0.12s, box-shadow 0.15s;+ }+ .creation:hover {+ border-color: var(--stroke-strong);+ transform: translateY(-2px);+ box-shadow: 0 16px 36px -24px rgba(0, 0, 0, 0.9);+ }+ .creation:focus-visible {+ outline: 2px solid var(--accent);+ outline-offset: 2px;+ }+ .creation .thumb {+ aspect-ratio: 1 / 1;+ width: 100%;+ object-fit: cover;+ background: var(--surface-2);+ display: block;+ }+ .creation .thumb.placeholder {+ display: grid;+ place-items: center;+ color: var(--ink-dim);+ font-size: 1.6rem;+ }+ .creation .meta {+ padding: 0.5rem 0.6rem;+ font-size: var(--text-xs);+ color: var(--ink-dim);+ line-height: var(--leading-snug);+ display: -webkit-box;+ -webkit-line-clamp: 2;+ -webkit-box-orient: vertical;+ overflow: hidden;+ }+ .creation .badge {+ position: absolute;+ top: 6px;+ right: 6px;+ font-size: 0.65rem;+ font-family: var(--font-mono);+ padding: 1px 6px;+ border-radius: 999px;+ background: rgba(0, 0, 0, 0.55);+ backdrop-filter: blur(4px);+ }+ .creation .badge[data-outcome='accepted'] {+ color: var(--success);+ }+ .creation .badge[data-outcome='rejected'] {+ color: var(--danger);+ }+/* Empty + error + unconfigured */.notice {padding: var(--space-2xl) var(--space-lg);@@ -475,6 +601,29 @@<div class="result-bar"><span class="label" id="result-label"></span><div class="actions">+ <div+ class="verdict"+ id="verdict"+ role="group"+ aria-label="Rate this model"+ >+ <button+ type="button"+ data-outcome="accepted"+ aria-pressed="false"+ title="Keep — good result"+ >+ 👍 Keep+ </button>+ <button+ type="button"+ data-outcome="rejected"+ aria-pressed="false"+ title="Discard — bad result"+ >+ 👎 Discard+ </button>+ </div><a class="btn btn-ghost" id="download" download>Download GLB</a><button class="btn" type="button" id="again">Make another</button></div>@@ -503,6 +652,15 @@</div></section>+ <!-- Your creations — durable, reusable models tied to this browser -->+ <section class="creations is-hidden" id="creations" aria-label="Your forged models">+ <div class="creations-head">+ <h2>Your creations</h2>+ <span class="count" id="creations-count"></span>+ </div>+ <div class="creations-grid" id="creations-grid"></div>+ </section>+<p class="hint-foot">Powered by flux-schnell + Microsoft TRELLIS on Replicate. Best results come from oneclearly described subject. The same pipeline is available to agents over MCP atdiff --git a/pages/home.html b/pages/home.htmlindex 797d20f32..d299a159a 100644--- a/pages/home.html+++ b/pages/home.html@@ -2283,18 +2283,24 @@.bento-action-btn:active{transform:translateY(0)}.bento-action-btn:focus-visible{outline:2px solid rgba(255,255,255,.5);outline-offset:2px}.bento-action-btn.sm{padding:5px 11px;font-size:10.5px}+ .bento-action-btn.primary{background:var(--text);color:var(--bg);border-color:var(--text);font-weight:600}+ .bento-action-btn.primary:hover{background:#fff;border-color:#fff}+ .bento-action-btn.ghost{background:transparent;color:var(--text-2)}.studio-zone{display:flex;gap:8px;align-items:stretch}.studio-drop{flex:1;border:1px dashed var(--hairline-strong);border-radius:8px;padding:16px;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:6px;cursor:pointer;transition:border-color .2s,background .2s;font-family:var(--font-mono);font-size:11px;color:var(--text-3);text-align:center;min-height:80px}.studio-drop:hover,.studio-drop.drag-over{border-color:var(--text-2);background:rgba(255,255,255,.03)}.studio-drop-icon{font-size:22px;opacity:.5}- .studio-processing{display:none;align-items:center;justify-content:center;gap:10px;padding:12px;font-family:var(--font-mono);font-size:11px;color:var(--text-3)}- .studio-processing.active{display:flex}- .studio-processing-ring{width:18px;height:18px;border:2px solid var(--hairline-strong);border-top-color:var(--text-2);border-radius:50%;animation:walk-spin .7s linear infinite}- .studio-preview-img{width:48px;height:48px;border-radius:50%;object-fit:cover;border:1px solid var(--hairline-strong);display:none}- .studio-preview-img.show{display:block}- .studio-done{display:none;align-items:center;gap:8px;font-family:var(--font-mono);font-size:11px;color:var(--text-2)}- .studio-done.show{display:flex}- .studio-done-check{width:18px;height:18px;border-radius:50%;background:var(--text);color:var(--bg);display:flex;align-items:center;justify-content:center;font-size:11px;font-weight:700}+ .studio-preview-img{width:44px;height:44px;border-radius:50%;object-fit:cover;border:1px solid var(--hairline-strong);flex:none}+ .studio-ready{display:none;flex-direction:column;align-items:stretch;gap:12px;padding:14px;border:1px solid var(--hairline-strong);border-radius:8px;background:rgba(255,255,255,.02)}+ .studio-ready.show{display:flex}+ .studio-ready > .studio-preview-img{align-self:flex-start}+ .studio-ready-body{display:flex;flex-direction:column;gap:4px}+ .studio-ready-title{font-family:var(--font-display);font-size:14px;font-weight:600;color:var(--text)}+ .studio-ready-sub{font-family:var(--font-mono);font-size:11px;line-height:1.5;color:var(--text-3)}+ .studio-ready-actions{display:flex;gap:8px;flex-wrap:wrap}+ .studio-ready-actions .bento-action-btn{text-decoration:none;display:inline-flex;align-items:center;justify-content:center}+ .studio-error{display:none;align-items:center;gap:8px;padding:10px 12px;border:1px solid var(--hairline-strong);border-radius:8px;font-family:var(--font-mono);font-size:11px;color:var(--text-2)}+ .studio-error.show{display:flex}.mocap-demo{display:flex;flex-direction:column;gap:8px}.mocap-bar{display:flex;align-items:center;gap:10px}.mocap-waveform{width:100%;height:48px;border-radius:6px;background:var(--surface-2);border:1px solid var(--hairline-strong);display:block}@@ -3169,17 +3175,20 @@<span>Drop a selfie or click to upload</span><input type="file" accept="image/*" id="studio-file" style="display:none" /></div>- <button class="bento-action-btn studio-webcam-btn" id="studio-webcam-btn">Webcam</button>+ <button class="bento-action-btn studio-webcam-btn" id="studio-webcam-btn" type="button">Webcam</button></div>- <div class="studio-processing" id="studio-processing">- <div class="studio-processing-ring"></div>- <img class="studio-preview-img" id="studio-preview-img" alt="" />- <span id="studio-processing-text">Generating 3D mesh...</span>- </div>- <div class="studio-done" id="studio-done">- <div class="studio-done-check">✓</div>- <span>Avatar generated — rigged & ready</span>+ <div class="studio-ready" id="studio-ready">+ <img class="studio-preview-img" id="studio-preview-img" alt="The photo you just captured" />+ <div class="studio-ready-body">+ <span class="studio-ready-title">Photo ready.</span>+ <span class="studio-ready-sub">Finish in Avatar Studio — we'll build a rigged 3D avatar from it. Add side angles, a personality, and a voice.</span>+ </div>+ <div class="studio-ready-actions">+ <a class="bento-action-btn primary" id="studio-continue" href="/create/selfie">Continue in Avatar Studio →</a>+ <button class="bento-action-btn ghost" id="studio-reset" type="button">Use a different photo</button>+ </div></div>+ <div class="studio-error" id="studio-error" role="alert" hidden></div></div><div class="bento-screenshot"><div class="bento-agent" id="bento-studio"></div>@@ -4308,7 +4317,9 @@message: msg,system_prompt: HERO_SYSTEM_PROMPT,history: history.slice(0, -1),- context: {}+ context: {},+ provider: 'openrouter',+ model: 'openai/gpt-oss-120b:free'})}).then(function(res) {if (!res.ok) throw new Error('Chat request failed');@@ -5179,68 +5190,132 @@// ── Interactive Bento Features ─────────────────────────────────────(function initBentoInteractives() {- // ── 1. Avatar Studio: webcam + drag-drop ────────────────────────+ // ── 1. Avatar Studio: capture a real photo, hand it to the real flow ──+ // This is a teaser. It does NOT fabricate a build — it captures the+ // visitor's photo, stashes it for the real selfie pipeline, and sends+ // them to /create-selfie where the actual reconstruction runs. The photo+ // is downscaled before storage so it fits comfortably in sessionStorage.(function() {+ var HANDOFF_KEY = 'threews:selfie-handoff';+ var MAX_DIM = 1024;+var drop = document.getElementById('studio-drop');var fileInput = document.getElementById('studio-file');var webcamBtn = document.getElementById('studio-webcam-btn');var zone = document.getElementById('studio-zone');- var processing = document.getElementById('studio-processing');+ var ready = document.getElementById('studio-ready');var previewImg = document.getElementById('studio-preview-img');- var processingText = document.getElementById('studio-processing-text');- var done = document.getElementById('studio-done');+ var resetBtn = document.getElementById('studio-reset');+ var errorEl = document.getElementById('studio-error');if (!drop) return;- function runPipeline(imgUrl) {+ function showError(msg) {+ if (!errorEl) return;+ errorEl.textContent = msg;+ errorEl.classList.add('show');+ errorEl.hidden = false;+ }+ function clearError() {+ if (!errorEl) return;+ errorEl.classList.remove('show');+ errorEl.hidden = true;+ }++ // Load → downscale → JPEG data URL. Keeps storage small and strips EXIF.+ function toDataUrl(file) {+ return new Promise(function(resolve, reject) {+ if (!file || !/^image\//.test(file.type)) { reject(new Error('not an image')); return; }+ var url = URL.createObjectURL(file);+ var img = new Image();+ img.onload = function() {+ var scale = Math.min(1, MAX_DIM / Math.max(img.naturalWidth, img.naturalHeight));+ var w = Math.max(1, Math.round(img.naturalWidth * scale));+ var h = Math.max(1, Math.round(img.naturalHeight * scale));+ var canvas = document.createElement('canvas');+ canvas.width = w; canvas.height = h;+ canvas.getContext('2d').drawImage(img, 0, 0, w, h);+ URL.revokeObjectURL(url);+ try { resolve(canvas.toDataURL('image/jpeg', 0.9)); }+ catch (e) { reject(e); }+ };+ img.onerror = function() { URL.revokeObjectURL(url); reject(new Error('decode failed')); };+ img.src = url;+ });+ }++ function present(dataUrl, name) {+ try {+ sessionStorage.setItem(HANDOFF_KEY, JSON.stringify({ dataUrl: dataUrl, name: name || 'selfie.jpg' }));+ } catch (e) {+ // Storage blocked or quota exceeded — the visitor can still start+ // fresh in Avatar Studio, so degrade gracefully instead of lying.+ }+ previewImg.src = dataUrl;zone.style.display = 'none';- previewImg.src = imgUrl;- previewImg.classList.add('show');- processing.classList.add('active');- var steps = ['Detecting face...', 'Generating 3D mesh...', 'Auto-rigging skeleton...', 'Retargeting animations...'];- var i = 0;- var iv = setInterval(function() {- i++;- if (i < steps.length) {- processingText.textContent = steps[i];- } else {- clearInterval(iv);- processing.classList.remove('active');- done.classList.add('show');- }- }, 700);+ ready.classList.add('show');+ }++ function accept(file) {+ clearError();+ toDataUrl(file).then(function(dataUrl) {+ present(dataUrl, file.name);+ }).catch(function() {+ showError('Could not read that image. Try a JPG or PNG.');+ });}drop.addEventListener('click', function() { fileInput.click(); });fileInput.addEventListener('change', function() {- if (fileInput.files && fileInput.files[0]) {- var url = URL.createObjectURL(fileInput.files[0]);- runPipeline(url);- }+ if (fileInput.files && fileInput.files[0]) accept(fileInput.files[0]);});drop.addEventListener('dragover', function(e) { e.preventDefault(); drop.classList.add('drag-over'); });drop.addEventListener('dragleave', function() { drop.classList.remove('drag-over'); });drop.addEventListener('drop', function(e) {e.preventDefault(); drop.classList.remove('drag-over');- if (e.dataTransfer.files && e.dataTransfer.files[0]) {- var url = URL.createObjectURL(e.dataTransfer.files[0]);- runPipeline(url);- }+ if (e.dataTransfer.files && e.dataTransfer.files[0]) accept(e.dataTransfer.files[0]);});++ resetBtn && resetBtn.addEventListener('click', function() {+ try { sessionStorage.removeItem(HANDOFF_KEY); } catch (e) {}+ ready.classList.remove('show');+ zone.style.display = '';+ fileInput.value = '';+ clearError();+ });+webcamBtn.addEventListener('click', function() {- navigator.mediaDevices.getUserMedia({ video: { facingMode: 'user', width: 256, height: 256 } })+ if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {+ showError('Webcam not available in this browser. Upload a photo instead.');+ return;+ }+ clearError();+ webcamBtn.disabled = true;+ navigator.mediaDevices.getUserMedia({ video: { facingMode: 'user', width: 640, height: 640 } }).then(function(stream) {var video = document.createElement('video');video.srcObject = stream;+ video.muted = true;+ video.playsInline = true;video.play();- setTimeout(function() {+ var done = false;+ function snap() {+ if (done) return;+ done = true;+ var size = Math.min(video.videoWidth || 640, video.videoHeight || 640) || 640;var canvas = document.createElement('canvas');- canvas.width = 256; canvas.height = 256;- canvas.getContext('2d').drawImage(video, 0, 0, 256, 256);+ canvas.width = size; canvas.height = size;+ var sx = ((video.videoWidth || size) - size) / 2;+ var sy = ((video.videoHeight || size) - size) / 2;+ canvas.getContext('2d').drawImage(video, sx, sy, size, size, 0, 0, size, size);stream.getTracks().forEach(function(t) { t.stop(); });- runPipeline(canvas.toDataURL('image/jpeg'));- }, 500);+ webcamBtn.disabled = false;+ present(canvas.toDataURL('image/jpeg', 0.9), 'webcam.jpg');+ }+ // Snap once the first frame is actually available.+ video.addEventListener('loadeddata', function() { setTimeout(snap, 250); }, { once: true });}).catch(function() {- runPipeline('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64"><rect width="64" height="64" fill="%23222"/><text x="32" y="36" text-anchor="middle" fill="%23666" font-size="12">cam</text></svg>');+ webcamBtn.disabled = false;+ showError('Camera access was blocked. Upload a photo instead.');});});})();diff --git a/public/feed.css b/public/feed.cssnew file mode 100644index 000000000..acb61b00d--- /dev/null+++ b/public/feed.css@@ -0,0 +1,282 @@+/* three.ws live activity ticker — the site-wide "something is always happening+ * here" widget. Loaded on every page by nav.js, mounted bottom-left (the Walk+ * Companion owns bottom-right). Tokens fall back to literals so the widget looks+ * right on pages that don't load style.css. */++.tws-feed {+ position: fixed;+ left: 16px;+ bottom: 16px;+ z-index: 2147482000; /* below the Walk Companion (…483000), above page chrome */+ font-family: system-ui, -apple-system, 'Segoe UI', sans-serif;+ color: var(--ink, #e8e8e8);+ -webkit-user-select: none;+ user-select: none;+}++.tws-feed[hidden] {+ display: none;+}++/* ── Collapsed pill ─────────────────────────────────────────────────────── */+.tws-feed-pill {+ display: inline-flex;+ align-items: center;+ gap: 8px;+ max-width: min(320px, calc(100vw - 32px));+ padding: 8px 12px 8px 11px;+ border: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));+ border-radius: 999px;+ background: var(--surface-2, rgba(20, 21, 28, 0.82));+ backdrop-filter: blur(12px);+ -webkit-backdrop-filter: blur(12px);+ box-shadow: 0 8px 28px rgba(0, 0, 0, 0.35);+ color: inherit;+ font: inherit;+ font-size: 12.5px;+ line-height: 1.2;+ cursor: pointer;+ transition: transform 0.18s ease, border-color 0.18s ease, background 0.18s ease;+}+.tws-feed-pill:hover {+ transform: translateY(-1px);+ border-color: var(--stroke-strong, rgba(255, 255, 255, 0.18));+ background: var(--surface-3, rgba(28, 30, 40, 0.9));+}+.tws-feed-pill:focus-visible {+ outline: 2px solid var(--success, #4ade80);+ outline-offset: 2px;+}++.tws-feed-dot {+ flex: 0 0 auto;+ width: 8px;+ height: 8px;+ border-radius: 50%;+ background: var(--success, #4ade80);+ box-shadow: 0 0 0 0 rgba(74, 222, 128, 0.5);+ animation: tws-feed-pulse 2.4s ease-out infinite;+}+@keyframes tws-feed-pulse {+ 0% { box-shadow: 0 0 0 0 rgba(74, 222, 128, 0.45); }+ 70% { box-shadow: 0 0 0 7px rgba(74, 222, 128, 0); }+ 100% { box-shadow: 0 0 0 0 rgba(74, 222, 128, 0); }+}++.tws-feed-pill-text {+ overflow: hidden;+ white-space: nowrap;+ text-overflow: ellipsis;+ color: var(--ink, #e8e8e8);+}+.tws-feed-pill-text b {+ font-weight: 600;+}++.tws-feed-count {+ flex: 0 0 auto;+ min-width: 18px;+ height: 18px;+ padding: 0 5px;+ border-radius: 999px;+ background: var(--success, #4ade80);+ color: #06210f;+ font-size: 11px;+ font-weight: 700;+ line-height: 18px;+ text-align: center;+}+.tws-feed-count[hidden] {+ display: none;+}++/* ── Expanded panel ─────────────────────────────────────────────────────── */+.tws-feed-panel {+ width: min(330px, calc(100vw - 32px));+ border: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));+ border-radius: var(--radius-card, 14px);+ background: var(--surface-2, rgba(16, 17, 24, 0.92));+ backdrop-filter: blur(16px);+ -webkit-backdrop-filter: blur(16px);+ box-shadow: 0 18px 48px rgba(0, 0, 0, 0.5);+ overflow: hidden;+ transform-origin: bottom left;+ animation: tws-feed-open 0.18s ease;+}+@keyframes tws-feed-open {+ from { opacity: 0; transform: translateY(8px) scale(0.98); }+ to { opacity: 1; transform: translateY(0) scale(1); }+}++.tws-feed-head {+ display: flex;+ align-items: center;+ gap: 8px;+ padding: 11px 12px;+ border-bottom: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));+}+.tws-feed-head .tws-feed-dot {+ width: 7px;+ height: 7px;+}+.tws-feed-title {+ flex: 1 1 auto;+ font-size: 12.5px;+ font-weight: 600;+ letter-spacing: 0.02em;+ color: var(--ink, #e8e8e8);+}+.tws-feed-close {+ flex: 0 0 auto;+ width: 24px;+ height: 24px;+ display: grid;+ place-items: center;+ border: none;+ border-radius: 8px;+ background: transparent;+ color: var(--ink-dim, #888);+ font-size: 17px;+ line-height: 1;+ cursor: pointer;+ transition: background 0.15s ease, color 0.15s ease;+}+.tws-feed-close:hover {+ background: var(--surface-3, rgba(255, 255, 255, 0.08));+ color: var(--ink, #e8e8e8);+}+.tws-feed-close:focus-visible {+ outline: 2px solid var(--success, #4ade80);+ outline-offset: 1px;+}++.tws-feed-list {+ max-height: min(56vh, 420px);+ overflow-y: auto;+ overscroll-behavior: contain;+ padding: 4px;+ margin: 0;+ list-style: none;+ scrollbar-width: thin;+ scrollbar-color: rgba(255, 255, 255, 0.18) transparent;+}+.tws-feed-list::-webkit-scrollbar { width: 8px; }+.tws-feed-list::-webkit-scrollbar-thumb {+ background: rgba(255, 255, 255, 0.16);+ border-radius: 8px;+}++/* ── Rows ───────────────────────────────────────────────────────────────── */+.tws-feed-item {+ display: flex;+ align-items: flex-start;+ gap: 10px;+ padding: 9px 9px;+ border-radius: 10px;+ text-decoration: none;+ color: inherit;+ transition: background 0.14s ease;+ animation: tws-feed-row-in 0.32s ease both;+}+a.tws-feed-item:hover {+ background: var(--surface-3, rgba(255, 255, 255, 0.06));+}+a.tws-feed-item:focus-visible {+ outline: 2px solid var(--success, #4ade80);+ outline-offset: -2px;+}+@keyframes tws-feed-row-in {+ from { opacity: 0; transform: translateY(-6px); }+ to { opacity: 1; transform: translateY(0); }+}++.tws-feed-ico {+ flex: 0 0 auto;+ width: 26px;+ height: 26px;+ display: grid;+ place-items: center;+ border-radius: 8px;+ background: var(--surface-3, rgba(255, 255, 255, 0.08));+ font-size: 14px;+ line-height: 1;+}+.tws-feed-ico[data-kind='coin-buy'] { color: var(--success, #4ade80); }+.tws-feed-ico[data-kind='agent-deploy'] { color: #c4b5fd; }+.tws-feed-ico[data-kind='level-up'] { color: var(--warn, #fbbf24); }+.tws-feed-ico[data-kind='world-join'] { color: #7dd3fc; }+.tws-feed-ico[data-kind='jackpot'] { color: var(--warn, #fbbf24); }++.tws-feed-body {+ flex: 1 1 auto;+ min-width: 0;+}+.tws-feed-text {+ font-size: 12.5px;+ line-height: 1.35;+ color: var(--ink, #e8e8e8);+ word-break: break-word;+}+.tws-feed-text b {+ font-weight: 600;+}+.tws-feed-time {+ margin-top: 2px;+ font-size: 11px;+ color: var(--ink-dim, #888);+}++/* ── Skeleton / empty / error ───────────────────────────────────────────── */+.tws-feed-skel {+ display: flex;+ gap: 10px;+ padding: 9px;+ align-items: center;+}+.tws-feed-skel span {+ display: block;+ height: 10px;+ border-radius: 6px;+ background: linear-gradient(90deg, rgba(255, 255, 255, 0.06), rgba(255, 255, 255, 0.12), rgba(255, 255, 255, 0.06));+ background-size: 200% 100%;+ animation: tws-feed-shimmer 1.3s linear infinite;+}+.tws-feed-skel .s-ico { width: 26px; height: 26px; border-radius: 8px; flex: 0 0 auto; }+.tws-feed-skel .s-a { width: 70%; }+.tws-feed-skel .s-b { width: 40%; margin-top: 6px; }+@keyframes tws-feed-shimmer {+ from { background-position: 200% 0; }+ to { background-position: -200% 0; }+}++.tws-feed-msg {+ padding: 22px 18px;+ text-align: center;+ color: var(--ink-dim, #888);+ font-size: 12.5px;+ line-height: 1.5;+}+.tws-feed-msg strong {+ display: block;+ color: var(--ink, #e8e8e8);+ font-weight: 600;+ margin-bottom: 3px;+}+.tws-feed-msg a {+ color: var(--success, #4ade80);+ text-decoration: none;+}+.tws-feed-msg a:hover { text-decoration: underline; }++/* ── Motion / responsive ────────────────────────────────────────────────── */+@media (max-width: 520px) {+ .tws-feed { left: 10px; bottom: 10px; }+ .tws-feed-pill .tws-feed-pill-text { max-width: 150px; }+}+@media (prefers-reduced-motion: reduce) {+ .tws-feed-dot { animation: none; }+ .tws-feed-panel,+ .tws-feed-item { animation: none; }+ .tws-feed-skel span { animation: none; }+ .tws-feed-pill { transition: none; }+}diff --git a/public/feed.js b/public/feed.jsnew file mode 100644index 000000000..cb9b92e92--- /dev/null+++ b/public/feed.js@@ -0,0 +1,428 @@+// three.ws live activity ticker — the site-wide "something is always happening+// here" widget. Self-mounting: nav.js loads this on every page. Renders a small+// pulsing pill bottom-left that expands into a live panel of recent platform+// events (coin buys, agent deploys, level-ups, world joins). Polls GET /api/feed+// and prepends anything new.+//+// Opt out per page with <html data-feed="off"> or window.__twsFeedOff = true.+// The data source and event shape live in api/_lib/feed.js.++(function () {+ 'use strict';++ if (window.__twsFeed) return; // idempotent — never double-mount+ if (typeof document === 'undefined') return;+ if (document.documentElement.getAttribute('data-feed') === 'off') return;+ if (window.__twsFeedOff) return;++ var API = '/api/feed?limit=30';+ // Polled from every page the widget mounts on. Kept at/above the endpoint's+ // edge-cache window so the CDN absorbs most polls instead of each one hitting+ // Redis — the feed is a delight layer, so 20s feels live and saves quota.+ var POLL_MS = 20000;+ var STORE_KEY = 'tws-feed:open'; // remember collapsed vs expanded across pages++ // ── State ────────────────────────────────────────────────────────────────+ var events = []; // newest-first, capped+ var seenIds = Object.create(null);+ var unseen = 0; // new since last time the panel was open+ var open = false;+ var loaded = false;+ var errored = false;+ var pollTimer = null;+ var root, pill, pillText, pillCount, panel, list;++ try {+ open = localStorage.getItem(STORE_KEY) === '1';+ } catch (_) {}++ // ── Rendering helpers ─────────────────────────────────────────────────────+ function el(tag, cls, text) {+ var n = document.createElement(tag);+ if (cls) n.className = cls;+ if (text != null) n.textContent = text;+ return n;+ }++ function shortMint(m) {+ m = String(m || '');+ return m.length > 8 ? m.slice(0, 4) + '…' + m.slice(-4) : m;+ }++ function fmtSol(n) {+ var v = Number(n);+ if (!isFinite(v) || v <= 0) return '';+ if (v >= 100) return Math.round(v).toString();+ // up to 3 significant decimals, trimmed+ return parseFloat(v.toFixed(3)).toString();+ }++ function relTime(ts) {+ var s = Math.max(0, Math.floor((Date.now() - ts) / 1000));+ if (s < 10) return 'just now';+ if (s < 60) return s + 's ago';+ var m = Math.floor(s / 60);+ if (m < 60) return m + 'm ago';+ var h = Math.floor(m / 60);+ if (h < 24) return h + 'h ago';+ var d = Math.floor(h / 24);+ return d + 'd ago';+ }++ // Per-type presentation. Returns { icon, href, build(textNode) } where build+ // fills a container with text — user-supplied strings go in via textContent+ // (createTextNode / el(text)), never innerHTML, so the world-readable feed+ // can't inject markup.+ var KINDS = {+ 'coin-buy': {+ icon: '↗',+ href: function (e) { return e.mint ? '/play?coin=' + encodeURIComponent(e.mint) : '/play'; },+ parts: function (e) {+ var sol = fmtSol(e.sol);+ return [+ bold(e.actor || 'Someone'),+ ' aped ',+ sol ? bold(sol + ' SOL') : 'in',+ ' into ',+ bold(shortMint(e.mint)),+ ];+ },+ },+ 'agent-deploy': {+ icon: '✦',+ href: function (e) { return e.agentId ? '/agent/' + encodeURIComponent(e.agentId) : '/discover'; },+ parts: function (e) { return [bold(e.name || e.actor || 'A new agent'), ' just deployed on-chain']; },+ },+ 'level-up': {+ icon: '⬆',+ href: function () { return '/play'; },+ parts: function (e) {+ return [bold(e.actor || 'A player'), ' reached ', bold(cap(e.skill) + ' ' + e.level)];+ },+ },+ 'world-join': {+ icon: '◉',+ href: function (e) { return e.coin ? '/play?coin=' + encodeURIComponent(e.coin) : '/play'; },+ parts: function (e) {+ return [bold(e.actor || 'Someone'), ' is hanging out in ', bold(e.coinName || 'a world')];+ },+ },+ jackpot: {+ icon: '★',+ href: function () { return '/play'; },+ parts: function (e) { return [bold(e.actor || 'A player'), ' won ', bold(e.reward || 'the jackpot')]; },+ },+ };++ function bold(t) {+ var b = document.createElement('b');+ b.textContent = t == null ? '' : String(t);+ return b;+ }+ function cap(s) {+ s = String(s || '');+ return s ? s.charAt(0).toUpperCase() + s.slice(1) : '';+ }++ // Flatten a parts array (strings + <b> nodes) into a target element.+ function fillText(target, parts) {+ for (var i = 0; i < parts.length; i++) {+ var p = parts[i];+ target.appendChild(typeof p === 'string' ? document.createTextNode(p) : p);+ }+ }++ function buildRow(e) {+ var kind = KINDS[e.type];+ if (!kind) return null;+ var href = kind.href(e);+ var row = el(href ? 'a' : 'div', 'tws-feed-item');+ if (href) {+ row.href = href;+ row.setAttribute('role', 'listitem');+ }+ var ico = el('span', 'tws-feed-ico');+ ico.setAttribute('data-kind', e.type);+ ico.setAttribute('aria-hidden', 'true');+ ico.textContent = kind.icon;+ var body = el('div', 'tws-feed-body');+ var text = el('div', 'tws-feed-text');+ fillText(text, kind.parts(e));+ var time = el('div', 'tws-feed-time', relTime(e.ts));+ time.setAttribute('data-ts', e.ts);+ body.appendChild(text);+ body.appendChild(time);+ row.appendChild(ico);+ row.appendChild(body);+ return row;+ }++ // One-line summary for the collapsed pill (latest event).+ function pillSummary(e) {+ var kind = KINDS[e.type];+ if (!kind) return null;+ var frag = document.createDocumentFragment();+ fillText(frag, kind.parts(e));+ return frag;+ }++ // ── DOM build ──────────────────────────────────────────────────────────────+ function mount() {+ ensureCss();+ root = el('div', 'tws-feed');+ root.setAttribute('aria-live', 'off');++ pill = el('button', 'tws-feed-pill');+ pill.type = 'button';+ pill.appendChild(el('span', 'tws-feed-dot'));+ pillText = el('span', 'tws-feed-pill-text');+ pillText.appendChild(document.createTextNode('Live activity'));+ pill.appendChild(pillText);+ pillCount = el('span', 'tws-feed-count');+ pillCount.hidden = true;+ pill.appendChild(pillCount);+ pill.addEventListener('click', expand);++ panel = el('div', 'tws-feed-panel');+ panel.hidden = true;+ var head = el('div', 'tws-feed-head');+ head.appendChild(el('span', 'tws-feed-dot'));+ head.appendChild(el('span', 'tws-feed-title', 'Live activity'));+ var close = el('button', 'tws-feed-close', '×');+ close.type = 'button';+ close.setAttribute('aria-label', 'Collapse activity feed');+ close.addEventListener('click', collapse);+ head.appendChild(close);+ list = el('ul', 'tws-feed-list');+ list.setAttribute('role', 'log');+ list.setAttribute('aria-label', 'Recent activity');+ list.setAttribute('aria-live', 'polite');+ panel.appendChild(head);+ panel.appendChild(list);++ root.appendChild(pill);+ root.appendChild(panel);+ document.body.appendChild(root);++ applyOpenState();+ renderSkeleton();++ // Keyboard: Escape collapses an open panel.+ document.addEventListener('keydown', function (ev) {+ if (ev.key === 'Escape' && open) collapse();+ });+ // Pause polling on hidden tabs; refresh immediately on return.+ document.addEventListener('visibilitychange', function () {+ if (document.hidden) {+ stopPolling();+ } else {+ poll();+ startPolling();+ }+ });+ // Hide entirely while a page element is fullscreen (immersive 3D etc.).+ document.addEventListener('fullscreenchange', function () {+ root.hidden = !!document.fullscreenElement;+ });+ }++ function ensureCss() {+ if (document.querySelector('link[href="/feed.css"]')) return;+ var link = document.createElement('link');+ link.rel = 'stylesheet';+ link.href = '/feed.css';+ document.head.appendChild(link);+ }++ // ── State transitions ──────────────────────────────────────────────────────+ function applyOpenState() {+ panel.hidden = !open;+ pill.hidden = open;+ pill.setAttribute('aria-expanded', open ? 'true' : 'false');+ if (open) {+ unseen = 0;+ updateCount();+ }+ }+ function expand() {+ open = true;+ try { localStorage.setItem(STORE_KEY, '1'); } catch (_) {}+ applyOpenState();+ render();+ }+ function collapse() {+ open = false;+ try { localStorage.setItem(STORE_KEY, '0'); } catch (_) {}+ applyOpenState();+ updatePill();+ }++ function updateCount() {+ if (unseen > 0) {+ pillCount.hidden = false;+ pillCount.textContent = unseen > 9 ? '9+' : String(unseen);+ pill.setAttribute('aria-label', 'Live activity — ' + unseen + ' new. Open feed.');+ } else {+ pillCount.hidden = true;+ pill.setAttribute('aria-label', 'Live activity. Open feed.');+ }+ }++ function updatePill() {+ var latest = events[0];+ // Empty the text node container, then refill.+ while (pillText.firstChild) pillText.removeChild(pillText.firstChild);+ if (latest) {+ var frag = pillSummary(latest);+ if (frag) pillText.appendChild(frag);+ else pillText.appendChild(document.createTextNode('Live activity'));+ } else if (errored && !loaded) {+ pillText.appendChild(document.createTextNode('Activity'));+ } else {+ pillText.appendChild(document.createTextNode(loaded ? "It's quiet right now" : 'Live activity'));+ }+ updateCount();+ }++ // ── Render the panel list ──────────────────────────────────────────────────+ function renderSkeleton() {+ list.textContent = '';+ for (var i = 0; i < 4; i++) {+ var li = el('li', 'tws-feed-skel');+ li.appendChild(el('span', 's-ico'));+ var col = el('div');+ col.style.flex = '1';+ col.appendChild(el('span', 's-a'));+ col.appendChild(el('span', 's-b'));+ li.appendChild(col);+ list.appendChild(li);+ }+ }++ function renderMessage(strongTxt, rest) {+ list.textContent = '';+ var li = el('li');+ var msg = el('div', 'tws-feed-msg');+ msg.appendChild(el('strong', null, strongTxt));+ if (rest) msg.appendChild(rest);+ li.appendChild(msg);+ list.appendChild(li);+ }++ function render() {+ if (!open) { updatePill(); return; }+ if (!loaded && !errored) { renderSkeleton(); return; }+ if (!events.length) {+ if (errored) {+ var retry = document.createElement('a');+ retry.href = '#';+ retry.textContent = 'Try again';+ retry.addEventListener('click', function (e) { e.preventDefault(); poll(); });+ renderMessage('Activity paused', wrapMsg('Couldn’t reach the feed. ', retry));+ } else {+ var go = document.createElement('a');+ go.href = '/play';+ go.textContent = 'Drop into a world';+ renderMessage("It's quiet right now", wrapMsg('Be the first — ', go));+ }+ return;+ }+ list.textContent = '';+ for (var i = 0; i < events.length; i++) {+ var row = buildRow(events[i]);+ if (row) list.appendChild(row);+ }+ }++ function wrapMsg(text, node) {+ var span = el('span', null, text);+ if (node) span.appendChild(node);+ return span;+ }++ // Refresh the "2m ago" labels in place without rebuilding rows.+ function refreshTimes() {+ var nodes = list.querySelectorAll('.tws-feed-time');+ for (var i = 0; i < nodes.length; i++) {+ var ts = Number(nodes[i].getAttribute('data-ts'));+ if (ts) nodes[i].textContent = relTime(ts);+ }+ }++ // ── Data ───────────────────────────────────────────────────────────────────+ function merge(incoming) {+ var added = 0;+ var fresh = [];+ for (var i = 0; i < incoming.length; i++) {+ var e = incoming[i];+ if (!e || !e.id || seenIds[e.id]) continue;+ seenIds[e.id] = 1;+ fresh.push(e);+ added++;+ }+ if (added) {+ // Incoming is newest-first; prepend and keep the list bounded.+ events = fresh.concat(events).slice(0, 40);+ if (!open && loaded) unseen = Math.min(99, unseen + added);+ }+ return added;+ }++ function poll() {+ fetch(API, { headers: { accept: 'application/json' }, credentials: 'omit' })+ .then(function (r) {+ if (!r.ok) throw new Error('http ' + r.status);+ return r.json();+ })+ .then(function (data) {+ errored = false;+ var first = !loaded;+ loaded = true;+ var added = merge(Array.isArray(data.events) ? data.events : []);+ if (open) {+ if (first || added) render();+ else refreshTimes();+ } else {+ updatePill();+ }+ })+ .catch(function () {+ errored = true;+ if (!loaded) {+ if (open) render();+ else updatePill();+ }+ });+ }++ function startPolling() {+ stopPolling();+ pollTimer = setInterval(function () {+ poll();+ refreshTimes();+ }, POLL_MS);+ }+ function stopPolling() {+ if (pollTimer) { clearInterval(pollTimer); pollTimer = null; }+ }++ // ── Public surface ─────────────────────────────────────────────────────────+ window.__twsFeed = {+ open: expand,+ close: collapse,+ refresh: poll,+ events: function () { return events.slice(); },+ };++ function boot() {+ mount();+ poll();+ startPolling();+ }++ if (document.readyState === 'loading') {+ document.addEventListener('DOMContentLoaded', boot);+ } else {+ boot();+ }+})();diff --git a/public/nav.js b/public/nav.jsindex 45f916b66..58aef71d5 100644--- a/public/nav.js+++ b/public/nav.js@@ -7,7 +7,19 @@// styles (public/nav.css) and behavior here mirror pages/home.html so every// page reads as the same site.+// Load the site-wide live activity ticker (public/feed.js) on every page that+// carries the shared nav. Self-mounting + idempotent; honours <html data-feed="off">.+function loadActivityFeed() {+ if (document.documentElement.getAttribute('data-feed') === 'off') return;+ if (document.querySelector('script[src="/feed.js"]')) return;+ const s = document.createElement('script');+ s.src = '/feed.js';+ s.defer = true;+ document.head.appendChild(s);+}+function boot() {+ loadActivityFeed();const navContainer = document.getElementById('nav-container');if (!navContainer) return;if (!document.querySelector('link[href="/nav.css"]')) {diff --git a/scripts/feed-widget-smoke.mjs b/scripts/feed-widget-smoke.mjsnew file mode 100644index 000000000..6dba1180f--- /dev/null+++ b/scripts/feed-widget-smoke.mjs@@ -0,0 +1,103 @@+// Headless smoke test for the live activity ticker (public/feed.js + feed.css).+// Stubs window.fetch so we exercise every render state without a backend:+// loading → populated, empty, and error. Asserts DOM (robust) and saves one+// screenshot of the populated panel to /tmp for a visual gut-check.+//+// node scripts/feed-widget-smoke.mjs+import { readFileSync } from 'node:fs';+import puppeteer from 'puppeteer';++const css = readFileSync(new URL('../public/feed.css', import.meta.url), 'utf8');+const js = readFileSync(new URL('../public/feed.js', import.meta.url), 'utf8');++const SAMPLE = [+ { id: 'a1', type: 'coin-buy', ts: Date.now() - 4000, actor: '7xKq…9aP2', mint: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump', sol: 0.42, network: 'mainnet' },+ { id: 'a2', type: 'agent-deploy', ts: Date.now() - 60000, actor: 'Nova Scout', agentId: 'abc-123', name: 'Nova Scout' },+ { id: 'a3', type: 'level-up', ts: Date.now() - 600000, actor: 'pixelpilot', skill: 'fishing', level: 50 },+ { id: 'a4', type: 'world-join', ts: Date.now() - 3600000, actor: 'gm_frog', coin: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump', coinName: '$THREE home town' },+ // An XSS attempt in a user-controlled field — must render as inert text.+ { id: 'a5', type: 'world-join', ts: Date.now() - 7200000, actor: '<img src=x onerror=alert(1)>', coin: '', coinName: 'Mainland' },+];++function harness(payloadMode) {+ return `<!doctype html><html><head><meta charset="utf8"><style>body{background:#0b0c10;margin:0;height:100vh}${css}</style></head>+<body>+<script>+window.__FEED_MODE = ${JSON.stringify(payloadMode)};+window.fetch = function(){+ if (window.__FEED_MODE === 'error') return Promise.reject(new Error('network down'));+ var events = window.__FEED_MODE === 'empty' ? [] : ${JSON.stringify(SAMPLE)};+ return Promise.resolve({ ok:true, status:200, json:function(){ return Promise.resolve({ events:events, count:events.length }); } });+};+<\/script>+<script>${js}<\/script>+</body></html>`;+}++async function scenario(browser, mode) {+ const page = await browser.newPage();+ await page.setViewport({ width: 900, height: 700 });+ const errors = [];+ page.on('pageerror', (e) => errors.push(String(e)));+ page.on('dialog', async (d) => { errors.push('DIALOG(xss?):' + d.message()); await d.dismiss(); });+ await page.setContent(harness(mode), { waitUntil: 'load' });+ await page.waitForSelector('.tws-feed', { timeout: 5000 });+ // Let poll() resolve so the collapsed pill summary fills in.+ await new Promise((r) => setTimeout(r, 300));+ const pillText = await page.$eval('.tws-feed-pill-text', (n) => n.textContent.trim());+ // Drive the real expand path (the harness origin has no localStorage).+ await page.evaluate(() => window.__twsFeed.open());+ await new Promise((r) => setTimeout(r, 200));++ const out = await page.evaluate(() => {+ const rows = [...document.querySelectorAll('.tws-feed-item')];+ const msg = document.querySelector('.tws-feed-msg');+ return {+ panelOpen: !document.querySelector('.tws-feed-panel').hidden,+ rowCount: rows.length,+ firstRowText: rows[0] ? rows[0].querySelector('.tws-feed-text').textContent : null,+ firstRowHref: rows[0] ? rows[0].getAttribute('href') : null,+ message: msg ? msg.querySelector('strong').textContent : null,+ hasInjectedImg: !!document.querySelector('.tws-feed-list img'),+ listRole: document.querySelector('.tws-feed-list').getAttribute('role'),+ };+ });+ out.pillText = pillText;++ let shot = null;+ if (mode === 'full') {+ shot = '/tmp/feed-populated.png';+ await page.screenshot({ path: shot });+ }+ await page.close();+ return { mode, out, errors, shot };+}++const browser = await puppeteer.launch({ headless: 'new', args: ['--no-sandbox'] });+let pass = true;+for (const mode of ['full', 'empty', 'error']) {+ const { out, errors, shot } = await scenario(browser, mode);+ const checks = [];+ if (mode === 'full') {+ checks.push(['5 rows render', out.rowCount === 5]);+ checks.push(['collapsed pill summarizes latest', /aped 0\.42 SOL/.test(out.pillText || '')]);+ checks.push(['coin-buy text', /aped 0\.42 SOL into/.test(out.firstRowText || '')]);+ checks.push(['row links to /play?coin=', /\/play\?coin=/.test(out.firstRowHref || '')]);+ checks.push(['XSS rendered inert (no <img>)', out.hasInjectedImg === false]);+ checks.push(['no alert dialog fired', !errors.some((e) => e.includes('DIALOG'))]);+ }+ if (mode === 'empty') checks.push(['empty state shown', out.message === "It's quiet right now"]);+ if (mode === 'error') checks.push(['error state shown', out.message === 'Activity paused']);+ checks.push(['log role for a11y', out.listRole === 'log']);+ checks.push(['no page errors', errors.filter((e) => !e.includes('DIALOG')).length === 0]);++ console.log(`\n[${mode}]` + (shot ? ` (screenshot: ${shot})` : ''));+ for (const [name, ok] of checks) {+ console.log(` ${ok ? '✓' : '✗'} ${name}`);+ if (!ok) pass = false;+ }+ if (errors.length) console.log(' errors:', errors);+}+await browser.close();+console.log(pass ? '\nPASS — all widget states verified' : '\nFAIL');+process.exit(pass ? 0 : 1);diff --git a/scripts/verify-terrain-physics.mjs b/scripts/verify-terrain-physics.mjsnew file mode 100644index 000000000..4c890a5df--- /dev/null+++ b/scripts/verify-terrain-physics.mjs@@ -0,0 +1,119 @@+// Headless verification that the Rapier heightfield collider is aligned with+// the rendered terrain surface (terrain.heightAt). Casts vertical rays at+// sample points and compares the physics hit height to the analytic height —+// this proves the row/col convention + scale mapping are correct without WebGL.+//+// Run: node scripts/verify-terrain-physics.mjs++import { createTerrain } from '../src/game/terrain.js';+import { PhysicsWorld, initRapier } from '../src/physics/physics-world.js';++const RAPIER = await initRapier();+const terrain = createTerrain();++// ── 1. Terrain sanity ──────────────────────────────────────────────────────+const n = terrain.points;+let assertFails = 0;+const check = (cond, msg) => {+ if (!cond) {+ console.error(' ✗', msg);+ assertFails++;+ } else {+ console.log(' ✓', msg);+ }+};++console.log('Terrain sanity:');+check(terrain.heights.length === n * n, `heights buffer is ${n}×${n} = ${n * n}`);+check(+ Number.isFinite(terrain.heights[0]) && Number.isFinite(terrain.heights[n * n - 1]),+ 'heights are finite',+);+check(+ Math.abs(terrain.heightAt(0, 0)) < 0.05,+ `spawn (0,0) is flat: h=${terrain.heightAt(0, 0).toFixed(3)}`,+);+let maxAbs = 0;+for (const h of terrain.heights) maxAbs = Math.max(maxAbs, Math.abs(h));+check(+ maxAbs <= terrain.amplitude + 1e-3,+ `peak height ${maxAbs.toFixed(2)} ≤ amplitude ${terrain.amplitude}`,+);+check(maxAbs > 0.3, `terrain has real relief (peak ${maxAbs.toFixed(2)}m), not flat`);++// ── 2. Collider ↔ visual alignment ─────────────────────────────────────────+const phys = new PhysicsWorld(RAPIER);+phys.addHeightfield(terrain);+phys.world.step(); // build the query pipeline before ray casts++// Cast a ray straight down from high above each sample point; the hit height+// must match terrain.heightAt within a cell-size tolerance (the collider is+// piecewise-linear between the same samples heightAt interpolates).+const tol = terrain.cellSize * 1.5;+const samples = [+ [0, 0],+ [3, 4],+ [-5, 2],+ [8, -7],+ [-9, -9],+ [11, 0],+ [0, -11],+ [6.5, 6.5],+ [-7.2, 3.3],+];+let worst = 0;+console.log('\nCollider vs visual height (tol ±' + tol.toFixed(3) + 'm):');+for (const [x, z] of samples) {+ const expected = terrain.heightAt(x, z);+ const ray = new RAPIER.Ray({ x, y: 50, z }, { x: 0, y: -1, z: 0 });+ const hit = phys.world.castRay(ray, 100, true);+ if (!hit) {+ console.error(` ✗ (${x}, ${z}) — ray missed the collider entirely`);+ assertFails++;+ continue;+ }+ const hitY = 50 + -1 * hit.timeOfImpact;+ const err = Math.abs(hitY - expected);+ worst = Math.max(worst, err);+ const ok = err <= tol;+ if (!ok) assertFails++;+ console.log(+ ` ${ok ? '✓' : '✗'} (${String(x).padStart(5)}, ${String(z).padStart(5)}) ` ++ `visual=${expected.toFixed(3)} physics=${hitY.toFixed(3)} Δ=${err.toFixed(3)}`,+ );+}+console.log(`\nWorst alignment error: ${worst.toFixed(4)}m (tol ${tol.toFixed(4)}m)`);++// ── 3. Character drops onto the surface ────────────────────────────────────+const spawnX = 8,+ spawnZ = -7;+const ch = phys.createCharacter({+ position: { x: spawnX, y: terrain.heightAt(spawnX, spawnZ) + 3, z: spawnZ },+ radius: 0.3,+ halfHeight: 0.55,+});+let grounded = false;+let feetY = 0;+for (let i = 0; i < 120; i++) {+ const res = ch.move({ x: 0, y: -0.3, z: 0 }); // gravity-ish pull each frame+ phys.step(1 / 60);+ feetY = res.position.y;+ if (res.grounded) {+ grounded = true;+ break;+ }+}+console.log('\nCharacter drop test:');+const expectedFeet = terrain.heightAt(spawnX, spawnZ);+check(grounded, 'character became grounded after falling');+check(+ Math.abs(feetY - expectedFeet) < 0.2,+ `feet settled on terrain: feet=${feetY.toFixed(3)} terrain=${expectedFeet.toFixed(3)}`,+);++phys.dispose();++console.log(+ `\n${assertFails === 0 ? '✅ ALL CHECKS PASSED' : `❌ ${assertFails} CHECK(S) FAILED`}`,+);+process.exit(assertFails === 0 ? 0 : 1);diff --git a/src/forge.js b/src/forge.jsindex 814d7b4b1..ee5d2fa18 100644--- a/src/forge.js+++ b/src/forge.js@@ -35,16 +35,43 @@ const els = {cancel: document.getElementById('cancel'),viewer: document.getElementById('viewer'),resultLabel: document.getElementById('result-label'),+ verdict: document.getElementById('verdict'),download: document.getElementById('download'),again: document.getElementById('again'),retry: document.getElementById('retry'),errorMessage: document.getElementById('error-message'),+ creations: document.getElementById('creations'),+ creationsGrid: document.getElementById('creations-grid'),+ creationsCount: document.getElementById('creations-count'),};let aspectRatio = '1:1';let elapsedTimer = null;let pollAbort = false;let lastPrompt = '';+let currentCreationId = null;++// Stable anonymous handle for this browser. /forge has no login, so durable+// creations + the gallery are scoped to this id (hashed server-side). Sent on+// every request via the x-forge-client header.+const CLIENT_ID = (() => {+ const KEY = 'forge:cid';+ try {+ let id = localStorage.getItem(KEY);+ if (!id) {+ id =+ crypto?.randomUUID?.() ||+ `c-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;+ localStorage.setItem(KEY, id);+ }+ return id;+ } catch {+ // Private mode / storage blocked — fall back to an ephemeral per-load id.+ return `c-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;+ }+})();++const CLIENT_HEADERS = { 'x-forge-client': CLIENT_ID };function showState(name) {for (const [key, node] of Object.entries(els.states)) {@@ -86,7 +113,7 @@ function sleep(ms) {async function startJob(prompt) {const res = await fetch('/api/forge', {method: 'POST',- headers: { 'content-type': 'application/json' },+ headers: { 'content-type': 'application/json', ...CLIENT_HEADERS },body: JSON.stringify({ prompt, aspect_ratio: aspectRatio }),});const data = await res.json().catch(() => ({}));@@ -106,14 +133,16 @@ async function pollUntilDone(jobId) {while (!pollAbort && performance.now() < deadline) {await sleep(POLL_INTERVAL_MS);if (pollAbort) return null;- const res = await fetch(`/api/forge?job=${encodeURIComponent(jobId)}`);+ const res = await fetch(`/api/forge?job=${encodeURIComponent(jobId)}`, {+ headers: CLIENT_HEADERS,+ });const data = await res.json().catch(() => ({}));if (data.error === 'unconfigured') {const e = new Error(data.message || 'unconfigured');e.kind = 'unconfigured';throw e;}- if (data.status === 'done' && data.glb_url) return data.glb_url;+ if (data.status === 'done' && data.glb_url) return data;if (data.status === 'failed') throw new Error(data.error || 'Generation failed.');if (data.status === 'running') setStep('mesh', 'active');}@@ -121,8 +150,28 @@ async function pollUntilDone(jobId) {throw new Error('Generation timed out. The model may be too complex — try a simpler prompt.');}+// Post the human verdict on a creation — the labeled half of the data flywheel.+// Fire-and-forget: a missing store or a network blip must never disrupt the UI.+function sendFeedback(payload) {+ if (!currentCreationId) return;+ fetch('/api/forge-feedback', {+ method: 'POST',+ headers: { 'content-type': 'application/json', ...CLIENT_HEADERS },+ body: JSON.stringify({ creation_id: currentCreationId, ...payload }),+ keepalive: true,+ }).catch(() => {});+}++function resetVerdict() {+ if (!els.verdict) return;+ for (const b of els.verdict.querySelectorAll('button')) {+ b.setAttribute('aria-pressed', 'false');+ }+}+function showResult(glbUrl, prompt) {stopElapsed();+ resetVerdict();els.viewer.setAttribute('src', glbUrl);els.viewer.setAttribute('alt', `3D model: ${prompt}`);els.resultLabel.textContent = prompt;@@ -134,6 +183,76 @@ function showResult(glbUrl, prompt) {showState('result');}+// Load (or reload) the "Your creations" strip from durable storage. Hidden+// entirely when persistence is off or the client has no creations yet.+async function loadGallery() {+ if (!els.creations) return;+ let data;+ try {+ const res = await fetch('/api/forge-gallery?limit=24', { headers: CLIENT_HEADERS });+ data = await res.json().catch(() => ({}));+ } catch {+ return;+ }+ const creations = Array.isArray(data?.creations) ? data.creations : [];+ if (!data?.enabled || creations.length === 0) {+ els.creations.classList.add('is-hidden');+ return;+ }+ els.creationsGrid.innerHTML = '';+ for (const c of creations) {+ const card = document.createElement('button');+ card.type = 'button';+ card.className = 'creation';+ card.title = c.prompt || 'Forged model';+ card.setAttribute('aria-label', `Open: ${c.prompt || 'forged model'}`);++ if (c.preview_image_url) {+ const img = document.createElement('img');+ img.className = 'thumb';+ img.loading = 'lazy';+ img.alt = '';+ img.src = c.preview_image_url;+ card.appendChild(img);+ } else {+ const ph = document.createElement('span');+ ph.className = 'thumb placeholder';+ ph.textContent = '◳';+ card.appendChild(ph);+ }++ if (c.outcome === 'accepted' || c.outcome === 'rejected') {+ const badge = document.createElement('span');+ badge.className = 'badge';+ badge.dataset.outcome = c.outcome;+ badge.textContent = c.outcome === 'accepted' ? '👍' : '👎';+ card.appendChild(badge);+ }++ const meta = document.createElement('span');+ meta.className = 'meta';+ meta.textContent = c.prompt || 'Untitled';+ card.appendChild(meta);++ card.addEventListener('click', () => {+ currentCreationId = c.id;+ lastPrompt = c.prompt || '';+ showResult(c.glb_url, c.prompt || 'Forged model');+ // Reflect any verdict already on record.+ if (els.verdict) {+ for (const b of els.verdict.querySelectorAll('button')) {+ b.setAttribute('aria-pressed', String(b.dataset.outcome === c.outcome));+ }+ }+ els.stage.scrollIntoView({ behavior: 'smooth', block: 'start' });+ });++ els.creationsGrid.appendChild(card);+ }+ els.creationsCount.textContent = `${creations.length} saved`;+ els.creations.classList.remove('is-hidden');+}+function showError(message) {stopElapsed();els.errorMessage.textContent = message;@@ -143,6 +262,7 @@ function showError(message) {async function run(prompt) {lastPrompt = prompt;pollAbort = false;+ currentCreationId = null;setBusy(true);// Reset generating UI to its initial real state.@@ -155,6 +275,7 @@ async function run(prompt) {try {const job = await startJob(prompt);+ if (job.creation_id) currentCreationId = job.creation_id;// Text-to-image really resolved before the POST returned: show it.if (job.preview_image_url) {@@ -169,12 +290,15 @@ async function run(prompt) {};}- const glbUrl = await pollUntilDone(job.job_id);- if (pollAbort || !glbUrl) return; // cancelled+ const done = await pollUntilDone(job.job_id);+ if (pollAbort || !done) return; // cancelled+ // Prefer the durable creation id resolved at completion time.+ if (done.creation_id) currentCreationId = done.creation_id;setStep('mesh', 'done');setStep('finish', 'done');- showResult(glbUrl, prompt);+ showResult(done.glb_url, prompt);+ loadGallery();} catch (err) {if (pollAbort) return;if (err.kind === 'unconfigured') {@@ -249,3 +373,27 @@ els.retry.addEventListener('click', () => {els.prompt.focus();}});++// Keep / discard — the explicit training signal. Toggling re-records so a+// mistaken click is correctable; the verdict is scoped server-side to the+// creation this browser made.+if (els.verdict) {+ els.verdict.addEventListener('click', (e) => {+ const btn = e.target.closest('button[data-outcome]');+ if (!btn || !currentCreationId) return;+ const outcome = btn.dataset.outcome;+ for (const b of els.verdict.querySelectorAll('button')) {+ b.setAttribute('aria-pressed', String(b === btn));+ }+ sendFeedback({ outcome });+ });+}++// A download is an implicit positive signal — capture it alongside the keep/+// discard verdict without requiring a second click.+els.download.addEventListener('click', () => {+ sendFeedback({ downloaded: true });+});++// Surface any previously forged models for this browser on load.+loadGallery();diff --git a/src/game/avatar-rig.js b/src/game/avatar-rig.jsindex c3f6fa123..786748bf9 100644--- a/src/game/avatar-rig.js+++ b/src/game/avatar-rig.js@@ -1,8 +1,8 @@// Shared avatar rig helpers — the single path for loading a GLB/VRM avatar into// a Three.js rig, wiring its AnimationManager (idle/walk + emotes), and playing// one-shot emotes. Used by every multiplayer 3D scene (the social walkaround in-// coincommunities.js, the isometric RPG in iso-game.js) so avatar loading,-// fallbacks, and the animation clip set never drift between experiences.+// coincommunities.js, plus /walk and /city) so avatar loading, fallbacks, and+// the animation clip set never drift between experiences.//// Scene-specific concerns (chat bubbles, nameplates, position interpolation,// HP bars) live in each scene's own player class — this module only owns thediff --git a/src/game/friends-panel.js b/src/game/friends-panel.jsindex 85eabed6a..0795b6464 100644--- a/src/game/friends-panel.js+++ b/src/game/friends-panel.js@@ -1,8 +1,8 @@-// Friends panel UI (Task 15) — a pure view over the shared FriendsClient. It-// renders into a container the host owns (the /play "friends" surface in-// iso-controls) and drives every account-level social interaction: incoming /-// outgoing requests, the friends list with live online + realm badges, a-// search-to-add flow, and per-friend DM threads with unread indicators.+// Friends panel UI — a pure view over the shared FriendsClient. It renders into a+// container the host owns (the /play "friends" surface, and /walk) and drives every+// account-level social interaction: incoming / outgoing requests, the friends list+// with live online badges, a search-to-add flow, and per-friend DM threads with+// unread indicators.//// All state lives in the FriendsClient; this module subscribes to its 'change'// signal and re-renders. Every state is designed: loading, signed-out, network@@ -13,9 +13,8 @@ import panelCss from '../friends-panel.css?inline';const HOTKEY_NOTE = 'Press F to toggle this panel.';-// Inject the standalone friends-panel CSS once per document. Harmless in /play-// where iso-game.css already covers the .kg-fr-* rules (duplicate selectors are-// idempotent). In /walk the --kg-* vars are absent so .wf-friends provides them.+// Inject the standalone friends-panel CSS once per document. In /walk the --kg-*+// vars are absent so .wf-friends provides them; duplicate selectors are idempotent.let _cssInjected = false;function ensureCss() {if (_cssInjected || typeof document === 'undefined') return;diff --git a/src/game/play-handoff.js b/src/game/play-handoff.jsindex e65710132..e01e1b258 100644--- a/src/game/play-handoff.js+++ b/src/game/play-handoff.js@@ -1,9 +1,9 @@-// Avatar handoff between the creation surfaces and the live worlds (/play, /game).+// Avatar handoff between the creation surfaces and the live worlds (/play, /walk).//// One localStorage key — `cc-avatar` — is the contract that ties the platform's// avatar tools to its multiplayer scenes. The lobby avatar bar, the boot loader,-// the social walkaround (coincommunities.js) and the isometric RPG (iso-game.js)-// all read it. This module is the single writer used by every "use this avatar"+// and the social walkaround (coincommunities.js) all read it. This module is the+// single writer used by every "use this avatar"// affordance, so the value stored is always something the scenes can resolve://// • a three.ws avatar id — canonical identity, resolved via /api/avatars/:id@@ -55,7 +55,7 @@ export function setPlayName(name) {* @param {Blob} [opts.blob] a freshly-created GLB not yet uploaded* @param {string} [opts.name] player display name to carry in* @param {string} [opts.source] provenance label when staging a blob- * @param {'/play'|'/game'|null} [opts.dest='/play'] where to navigate; null = stay+ * @param {'/play'|null} [opts.dest='/play'] where to navigate; null = stay* @param {object} [opts.coin] optional { mint, name, symbol, image } deep-link* @returns {Promise<string>} the value stored in cc-avatar*/diff --git a/src/game/terrain.js b/src/game/terrain.jsindex d1b8188bc..b964b3138 100644--- a/src/game/terrain.js+++ b/src/game/terrain.js@@ -21,7 +21,7 @@ import {// Deterministic PRNG (LCG) so a given seed always yields the same terrain —// important for multiplayer: every client must generate an identical surface.function makePRNG(seed) {- let s = (seed >>> 0) || 1;+ let s = seed >>> 0 || 1;return () => {s = (s * 1664525 + 1013904223) >>> 0;return s / 4294967296;diff --git a/src/physics/physics-world.js b/src/physics/physics-world.jsindex a7785ddfc..9551b8b82 100644--- a/src/physics/physics-world.js+++ b/src/physics/physics-world.js@@ -86,13 +86,14 @@ export class PhysicsWorld {this.world.removeRigidBody(this._ground.body);this._ground = null;}- const n = terrain.points; // samples per side; heights.length === n*n+ // Rapier's nrows/ncols are SEGMENT counts; it requires+ // heights.length === (nrows+1)·(ncols+1). terrain.points = segments+1,+ // so pass points-1 and the points²-length column-major buffer fits exactly.+ const segs = terrain.points - 1;const scale = { x: terrain.size, y: 1, z: terrain.size };- const body = this.world.createRigidBody(- R.RigidBodyDesc.fixed().setTranslation(0, y, 0),- );+ const body = this.world.createRigidBody(R.RigidBodyDesc.fixed().setTranslation(0, y, 0));this.world.createCollider(- R.ColliderDesc.heightfield(n, n, terrain.heights, scale).setFriction(friction),+ R.ColliderDesc.heightfield(segs, segs, terrain.heights, scale).setFriction(friction),body,);this._ground = { body };@@ -150,7 +151,10 @@ export class PhysicsWorld {.setAngularDamping(0.5),);this.world.createCollider(- R.ColliderDesc.ball(radius).setRestitution(restitution).setDensity(density).setFriction(0.6),+ R.ColliderDesc.ball(radius)+ .setRestitution(restitution)+ .setDensity(density)+ .setFriction(0.6),body,);const entry = { body, mesh, spawn: { x: p.x, y: p.y, z: p.z } };@@ -191,10 +195,19 @@ export class PhysicsWorld {* A kinematic capsule whose body translation tracks the FEET position.* Returns a controller façade with move()/setPosition().*/- createCharacter({ position = { x: 0, y: 0, z: 0 }, radius = 0.3, halfHeight = 0.55, offset = 0.04 } = {}) {+ createCharacter({+ position = { x: 0, y: 0, z: 0 },+ radius = 0.3,+ halfHeight = 0.55,+ offset = 0.04,+ } = {}) {const R = this.RAPIER;const body = this.world.createRigidBody(- R.RigidBodyDesc.kinematicPositionBased().setTranslation(position.x, position.y, position.z),+ R.RigidBodyDesc.kinematicPositionBased().setTranslation(+ position.x,+ position.y,+ position.z,+ ),);// Lift the capsule so the body origin is the feet, not the capsule center.const collider = this.world.createCollider(@@ -227,7 +240,10 @@ export class PhysicsWorld {_v.y = t.y + m.y;_v.z = t.z + m.z;body.setNextKinematicTranslation(_v);- return { position: { x: _v.x, y: _v.y, z: _v.z }, grounded: controller.computedGrounded() };+ return {+ position: { x: _v.x, y: _v.y, z: _v.z },+ grounded: controller.computedGrounded(),+ };},/** Hard-teleport (respawn, boundary snap) — bypasses collision. */setPosition: (p) => {diff --git a/src/selfie-capture.js b/src/selfie-capture.jsindex b0f163532..f7c4081e2 100644--- a/src/selfie-capture.js+++ b/src/selfie-capture.js@@ -658,6 +658,55 @@ function confirmCamShot() {setSlot(slot, file);}+// ── Homepage handoff ─────────────────────────────────────────────────────────+// The homepage Avatar Studio teaser lets a visitor drop/capture a selfie, then+// sends them here to finish the real build. It stashes that photo in+// sessionStorage; pick it up as the frontal slot so they don't re-capture.+(function ingestHandoff() {+ let raw;+ try {+ raw = sessionStorage.getItem('threews:selfie-handoff');+ if (raw) sessionStorage.removeItem('threews:selfie-handoff');+ } catch {+ return; // storage blocked (private mode / cookies off)+ }+ if (!raw) return;+ let parsed;+ try {+ parsed = JSON.parse(raw);+ } catch {+ return;+ }+ const dataUrl = parsed?.dataUrl;+ if (typeof dataUrl !== 'string' || !dataUrl.startsWith('data:image/')) return;+ const file = dataUrlToFile(dataUrl, typeof parsed?.name === 'string' ? parsed.name : 'selfie.jpg');+ if (file) setSlot(REQUIRED_SLOT, file);+})();++/**+ * @param {string} dataUrl+ * @param {string} name+ * @returns {File | null}+ */+function dataUrlToFile(dataUrl, name) {+ const comma = dataUrl.indexOf(',');+ if (comma < 0) return null;+ const header = dataUrl.slice(0, comma);+ const mime = (header.match(/^data:([^;]+)/) || [])[1] || 'image/jpeg';+ const body = dataUrl.slice(comma + 1);+ let bytes;+ try {+ const bin = /;base64/i.test(header) ? atob(body) : decodeURIComponent(body);+ bytes = new Uint8Array(bin.length);+ for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);+ } catch {+ return null;+ }+ const ext = mime === 'image/png' ? 'png' : mime === 'image/webp' ? 'webp' : 'jpg';+ const safeName = /\.[a-z0-9]+$/i.test(name) ? name : `${name}.${ext}`;+ return new File([bytes], safeName, { type: mime });+}+// ── Utilities ──────────────────────────────────────────────────────────────/** @param {string} slot */function slotPretty(slot) {diff --git a/src/selfie-pipeline.js b/src/selfie-pipeline.jsindex 6f1843361..ded1cd057 100644--- a/src/selfie-pipeline.js+++ b/src/selfie-pipeline.js@@ -303,12 +303,13 @@ function backoffInterval(errors) {}/**- * @param {'queued'|'running'|'done'|'failed'|undefined} status+ * @param {'queued'|'running'|'rigging'|'done'|'failed'|undefined} status* @param {number} attempt* @param {number} elapsedMs*/function statusLabel(status, attempt, elapsedMs) {if (status === 'queued') return 'Queued -- waiting for a reconstruction slot...';+ if (status === 'rigging') return 'Auto-rigging skeleton and skinning...';if (status === 'running') {if (attempt <= 4) return 'Generating 3D mesh from your photo...';if (attempt <= 12) return 'Building geometry and textures...';diff --git a/src/walk.js b/src/walk.jsindex 613ba0d27..3be4bc792 100644--- a/src/walk.js+++ b/src/walk.js@@ -50,6 +50,7 @@ import { WalkNet } from './walk-net.js';import { getPresenceTicket, friendsClient } from './friends.js';import { FriendsPanel } from './game/friends-panel.js';import { PhysicsWorld } from './physics/physics-world.js';+import { createTerrain } from './game/terrain.js';const AVATAR_URL_DEFAULT = '/avatars/default.glb';@@ -393,6 +394,15 @@ const groundOpaque = new Mesh(groundOpaque.rotation.x = -Math.PI / 2;groundOpaque.receiveShadow = true;scene.add(groundOpaque);+// The flat disc is kept only as the AR shadow backing; the rolling heightfield+// terrain below supersedes it as the visible, walkable ground in non-AR mode.+groundOpaque.visible = false;++// Procedural heightfield terrain — the single source of truth for ground shape.+// Its column-major height buffer feeds both this mesh and the Rapier heightfield+// collider (see initWalkPhysics), so the surface you see is the surface you walk.+const terrain = createTerrain({ color: 0x202833 });+scene.add(terrain.mesh);const groundShadowCatcher = new Mesh(new CircleGeometry(GROUND_RADIUS, 64),@@ -1218,7 +1228,7 @@ async function enableAR() {arActive = true;stage.classList.add('is-ar');arBtn.setAttribute('aria-pressed', 'true');- groundOpaque.visible = false;+ terrain.mesh.visible = false; // hide the world ground; the room is the floor in ARgroundShadowCatcher.visible = true;groundShadowCatcher.material.opacity = 0.55;renderer.setClearColor(0x000000, 0);@@ -1265,7 +1275,7 @@ function disableAR() {arActive = false;stage.classList.remove('is-ar');arBtn.setAttribute('aria-pressed', 'false');- groundOpaque.visible = true;+ terrain.mesh.visible = true; // restore the rolling ground when leaving ARgroundShadowCatcher.visible = false;groundShadowCatcher.material.opacity = 0.32;scene.background = null; // CSS gradient on #walk-stage shows through@@ -1585,8 +1595,10 @@ function tick() {if (!usePhysics && jumpActive && avatar) {jumpVelocity += GRAVITY * dt;avatarRig.position.y += jumpVelocity * dt;- if (avatarRig.position.y <= GROUND_Y) {- avatarRig.position.y = GROUND_Y;+ // Land on the terrain surface (flat GROUND_Y while floating in AR).+ const landY = arActive ? GROUND_Y : terrain.heightAt(avatarRig.position.x, avatarRig.position.z);+ if (avatarRig.position.y <= landY) {+ avatarRig.position.y = landY;jumpVelocity = 0;jumpActive = false;}@@ -1628,6 +1640,10 @@ function tick() {avatarRig.position.x *= k;avatarRig.position.z *= k;}+ // Follow the terrain surface until the physics solver takes over.+ if (!jumpActive) {+ avatarRig.position.y = terrain.heightAt(avatarRig.position.x, avatarRig.position.z);+ }}}@@ -2486,7 +2502,8 @@ function applyEnvironment(index) {const env = ENVIRONMENTS[index];if (!env) return;currentEnvIndex = index;- // Ground color+ // Ground color — recolor the terrain surface (the flat disc stays hidden).+ terrain.setColor(env.groundColor);groundOpaque.material.color.setHex(env.groundColor);// Stage background gradientif (stage) stage.style.background = `radial-gradient(80% 60% at 50% 30%, ${env.skyTop} 0%, ${env.skyBot} 70%) ${env.skyBot}`;@@ -2539,17 +2556,18 @@ function buildParkProps() {const x = Math.cos(angle) * r;const z = Math.sin(angle) * r;const scale = 0.8 + Math.random() * 0.6;- dummy.position.set(x, 0.4 * scale, z);+ const gy = terrain.heightAt(x, z); // sit the tree on the rolling ground+ dummy.position.set(x, gy + 0.4 * scale, z);dummy.scale.set(scale, scale, scale);dummy.updateMatrix();trunkMesh.setMatrixAt(i, dummy.matrix);- dummy.position.y = 1.1 * scale;+ dummy.position.y = gy + 1.1 * scale;dummy.updateMatrix();foliageMesh.setMatrixAt(i, dummy.matrix);// Solid trunk: a cylinder you can't walk through, sized to the canopy base.worldObstacles.push({type: 'cylinder',- position: { x, y: 0.9 * scale, z },+ position: { x, y: gy + 0.9 * scale, z },radius: 0.32 * scale,halfHeight: 0.9 * scale,});@@ -2576,14 +2594,15 @@ function buildCityProps() {const w = 0.8 + Math.random() * 1.2;const d = 0.8 + Math.random() * 1.2;const rotationY = Math.random() * Math.PI;- dummy.position.set(x, h / 2, z);+ const gy = terrain.heightAt(x, z); // base the building on the terrain surface+ dummy.position.set(x, gy + h / 2, z);dummy.scale.set(w, h, d);dummy.rotation.y = rotationY;dummy.updateMatrix();mesh.setMatrixAt(i, dummy.matrix);worldObstacles.push({type: 'box',- position: { x, y: h / 2, z },+ position: { x, y: gy + h / 2, z },halfExtents: { x: w / 2, y: h / 2, z: d / 2 },rotationY,});@@ -2626,17 +2645,18 @@ function buildBeachProps() {const r = 6 + Math.random() * 4;const x = Math.cos(angle) * r;const z = Math.sin(angle) * r;- dummy.position.set(x, 1.25, z);+ const gy = terrain.heightAt(x, z); // root the palm in the sand+ dummy.position.set(x, gy + 1.25, z);dummy.rotation.set(Math.random() * 0.15, 0, Math.random() * 0.15);dummy.scale.setScalar(1);dummy.updateMatrix();palmTrunks.setMatrixAt(i, dummy.matrix);- dummy.position.y = 2.6;+ dummy.position.y = gy + 2.6;dummy.updateMatrix();palmLeaves.setMatrixAt(i, dummy.matrix);worldObstacles.push({type: 'cylinder',- position: { x, y: 1.25, z },+ position: { x, y: gy + 1.25, z },radius: 0.28,halfHeight: 1.25,});@@ -3093,7 +3113,9 @@ function rebuildPhysicsWorld() {async function initWalkPhysics() {try {physics = await PhysicsWorld.create({ gravity: { x: 0, y: GRAVITY, z: 0 } });- physics.addGround(GROUND_Y, GROUND_RADIUS + 40);+ // Heightfield ground matching the rendered terrain (not a flat plane), so+ // the character climbs slopes, follows dips, and stands on the real surface.+ physics.addHeightfield(terrain);character = physics.createCharacter({position: { x: avatarRig.position.x, y: avatarRig.position.y, z: avatarRig.position.z },radius: 0.3,@@ -3147,6 +3169,25 @@ loadAvatar()requestAnimationFrame(tick);});+// Dev-only introspection hook for verifying the physics integration from a+// headless browser. Stripped from production builds (import.meta.env.DEV is+// statically false there, so the whole block is dead-code-eliminated).+if (import.meta.env?.DEV) {+ window.__walkPhysics = () => ({+ ready: physicsReady,+ grounded: characterGrounded,+ pos: { x: avatarRig.position.x, y: avatarRig.position.y, z: avatarRig.position.z },+ obstacles: worldObstacles.length,+ props: worldDynamicProps.map((p) => ({+ kind: p.kind,+ x: p.mesh.position.x,+ y: p.mesh.position.y,+ z: p.mesh.position.z,+ })),+ env: ENVIRONMENTS[currentEnvIndex]?.name,+ });+}+// ── Avatar picker ────────────────────────────────────────────────────────{const pickerPanel = document.getElementById('walk-avatar-picker');diff --git a/tests/api/reconstruct-finalize.test.js b/tests/api/reconstruct-finalize.test.jsnew file mode 100644index 000000000..36a6be4ec--- /dev/null+++ b/tests/api/reconstruct-finalize.test.js@@ -0,0 +1,126 @@+// Unit tests for the shared selfie → 3D finalize stage: the rig-or-materialize+// decision, the auto-rig chain, and the never-empty-handed fallbacks. Providers+// and storage are mocked so the control flow is exercised without live ML.++import { describe, it, expect, vi, beforeEach } from 'vitest';++// ── mocks ──────────────────────────────────────────────────────────────────+const sqlMock = vi.fn(async () => []);+vi.mock('../../api/_lib/db.js', () => ({ sql: (...args) => sqlMock(...args) }));++const putObjectMock = vi.fn(async () => undefined);+const publicUrlMock = vi.fn((key) => `https://cdn.test/${key}`);+vi.mock('../../api/_lib/r2.js', () => ({+ putObject: (...a) => putObjectMock(...a),+ publicUrl: (...a) => publicUrlMock(...a),+}));++const createAvatarMock = vi.fn(async ({ input }) => ({ id: 'avatar-1', name: input.name, slug: input.slug }));+vi.mock('../../api/_lib/avatars.js', () => ({+ storageKeyFor: ({ userId, slug }) => `u/${userId}/${slug}/m.glb`,+ createAvatar: (...a) => createAvatarMock(...a),+}));++const inspectGlbMock = vi.fn();+vi.mock('../../api/_lib/glb-inspect.js', () => ({+ inspectGlb: (...a) => inspectGlbMock(...a),+ isValidGlbHeader: () => true,+}));++vi.mock('../../api/_lib/webhook-dispatch.js', () => ({ dispatchWebhooks: async () => {} }));++const providerMock = { name: 'replicate', instance: null };+vi.mock('../../api/_lib/regen-provider.js', () => ({+ getRegenProvider: async () => providerMock,+}));++const { finalizeReconstructStage, pollRiggingStage } = await import('../../api/_lib/reconstruct-finalize.js');++const RIGGED = { isRigged: true, skinCount: 1, skeletonJointCount: 30, nodeCount: 40, meshCount: 1, animationCount: 0, generator: 'test' };+const UNRIGGED = { isRigged: false, skinCount: 0, skeletonJointCount: 0, nodeCount: 2, meshCount: 1, animationCount: 0, generator: 'test' };++function mockFetchGlb() {+ global.fetch = vi.fn(async () => ({+ ok: true,+ headers: { get: () => '1024' },+ arrayBuffer: async () => new Uint8Array([0x67, 0x6c, 0x54, 0x46]).buffer,+ }));+}++const baseJob = { provider: 'replicate', params: { name: 'Me', visibility: 'private' } };++beforeEach(() => {+ vi.clearAllMocks();+ mockFetchGlb();+ providerMock.instance = null;+});++describe('finalizeReconstructStage', () => {+ it('materializes immediately when the mesh is already rigged', async () => {+ inspectGlbMock.mockReturnValue(RIGGED);+ const out = await finalizeReconstructStage({ userId: 'u1', jobId: 'j1', job: baseJob, glbUrl: 'https://x/m.glb' });+ expect(out).toEqual({ status: 'done', resultAvatarId: 'avatar-1' });+ expect(createAvatarMock).toHaveBeenCalledOnce();+ // No 'unrigged' tag on a rigged mesh.+ expect(createAvatarMock.mock.calls[0][0].input.tags).not.toContain('unrigged');+ });++ it('materializes unrigged (tagged) when no rig model is configured', async () => {+ inspectGlbMock.mockReturnValue(UNRIGGED);+ providerMock.instance = { supportsMode: () => false }; // rerig unavailable+ const out = await finalizeReconstructStage({ userId: 'u1', jobId: 'j1', job: baseJob, glbUrl: 'https://x/m.glb' });+ expect(out.status).toBe('done');+ expect(createAvatarMock.mock.calls[0][0].input.tags).toContain('unrigged');+ });++ it('chains an auto-rig job when the mesh is unrigged and a rig model exists', async () => {+ inspectGlbMock.mockReturnValue(UNRIGGED);+ const submit = vi.fn(async () => ({ extJobId: 'rig-ext-1' }));+ providerMock.instance = { supportsMode: (m) => m === 'rerig', submit };+ const out = await finalizeReconstructStage({ userId: 'u1', jobId: 'j1', job: baseJob, glbUrl: 'https://x/m.glb' });+ expect(out).toEqual({ status: 'rigging' });+ expect(submit).toHaveBeenCalledOnce();+ expect(submit.mock.calls[0][0].mode).toBe('rerig');+ // Bare mesh stored so the rig model can fetch it, but NO avatar yet.+ expect(putObjectMock).toHaveBeenCalled();+ expect(createAvatarMock).not.toHaveBeenCalled();+ });++ it('falls back to delivering the bare mesh if the rig job cannot be submitted', async () => {+ inspectGlbMock.mockReturnValue(UNRIGGED);+ providerMock.instance = { supportsMode: () => true, submit: vi.fn(async () => { throw new Error('rig down'); }) };+ const out = await finalizeReconstructStage({ userId: 'u1', jobId: 'j1', job: baseJob, glbUrl: 'https://x/m.glb' });+ expect(out.status).toBe('done');+ expect(createAvatarMock.mock.calls[0][0].input.tags).toContain('unrigged');+ });+});++describe('pollRiggingStage', () => {+ const rigJob = {+ provider: 'replicate',+ params: { name: 'Me', visibility: 'private', rig: { extJobId: 'rig-ext-1', storageKey: 'u/u1/selfie-x/m.glb', slug: 'selfie-x', unriggedUrl: 'https://cdn.test/bare.glb' } },+ };++ it('materializes the rigged GLB when the rig job completes', async () => {+ inspectGlbMock.mockReturnValue(RIGGED);+ providerMock.instance = { status: vi.fn(async () => ({ status: 'done', resultGlbUrl: 'https://x/rigged.glb' })) };+ const out = await pollRiggingStage({ userId: 'u1', jobId: 'j1', job: rigJob });+ expect(out).toEqual({ status: 'done', resultAvatarId: 'avatar-1' });+ expect(createAvatarMock.mock.calls[0][0].input.source_meta.rigged).toBe(true);+ });++ it('falls back to the bare mesh when the rig job fails', async () => {+ inspectGlbMock.mockReturnValue(UNRIGGED);+ providerMock.instance = { status: vi.fn(async () => ({ status: 'failed', error: 'rig oom' })) };+ const out = await pollRiggingStage({ userId: 'u1', jobId: 'j1', job: rigJob });+ expect(out.status).toBe('done');+ expect(createAvatarMock.mock.calls[0][0].input.tags).toContain('unrigged');+ });++ it('stays in rigging while the rig job is still running', async () => {+ providerMock.instance = { status: vi.fn(async () => ({ status: 'running' })) };+ const out = await pollRiggingStage({ userId: 'u1', jobId: 'j1', job: rigJob });+ expect(out).toEqual({ status: 'rigging' });+ expect(createAvatarMock).not.toHaveBeenCalled();+ });+});