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: track restyled models onto the creator portfolio
nirholase2ece2828853
diff --git a/STRUCTURE.md b/STRUCTURE.mdindex a7a395587..33cb418f6 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -27,7 +27,7 @@ bottom.| Avatar builder (full app) | [character-studio/](character-studio) | Fork of [m3-org/CharacterStudio](https://github.com/M3-org/CharacterStudio), MIT, see [character-studio/LICENSE](character-studio/LICENSE) | Web-first character creator || Scene Studio (3D scene editor) | [src/scene-studio/](src/scene-studio) `→ /scene` | Vendored [mrdoob/three.js](https://github.com/mrdoob/three.js) r184 editor, MIT, see [src/scene-studio/vendor/README.md](src/scene-studio/vendor/README.md) | Import GLBs, compose scenes, edit materials/lights, export || Diorama (text → 3D world) | [src/diorama/](src/diorama) `→ /diorama` | In-repo · backend [api/diorama.js](api/diorama.js) | One sentence → an explorable 3D diorama: Claude composes the scene, each object is forged to a real GLB, assembled live, saved to a public gallery + shareable permalink |-| Creator portfolio (human profile) | [pages/profile.html](pages/profile.html) `→ /u/:username` (self-view `/profile`), backend [api/users/[username].js](api/users/%5Busername%5D.js) + paginated [api/users/[username]/creations.js](api/users/%5Busername%5D/creations.js) `→ /api/users/:username/creations` | Live | Every three.ws user's public portfolio: avatars, agents, widgets, skills, plugins, coins, memories, items for sale, and (added 2026-07-12) a **Creations** tab merging forged 3D models + Scene Studio worlds — real, live, spinning `<model-viewer>` cards, cursor-paginated for 100+ items. `/forge` and `/diorama` stay anonymous by default (no login required); a signed-in creator's `user_id` is now attached to `forge_creations`/`dioramas` rows at generation/save time (migration [api/_lib/migrations/20260712010000_creator_portfolio_user_ids.sql](api/_lib/migrations/20260712010000_creator_portfolio_user_ids.sql)) so those creations surface here. The same opt-in attribution now links back from the diorama viewer HUD, the diorama gallery cards, and the forge result bar ("by @user") whenever a creation's creator is known. `/@:handle` ([pages/handle.html](pages/handle.html)) is a separate, narrower agent-embed page — not the human portfolio. |+| Creator portfolio (human profile) | [pages/profile.html](pages/profile.html) `→ /u/:username` (self-view `/profile`), backend [api/users/[username].js](api/users/%5Busername%5D.js) + paginated [api/users/[username]/creations.js](api/users/%5Busername%5D/creations.js) `→ /api/users/:username/creations` | Live | Every three.ws user's public portfolio: avatars, agents, widgets, skills, plugins, coins, memories, items for sale, and (added 2026-07-12, extended 2026-07-23) a **Creations** tab merging forged 3D models + Scene Studio worlds + Material Studio restyles — real, live, spinning `<model-viewer>` cards, cursor-paginated for 100+ items. `/forge`, `/diorama`, and `/restyle` all stay anonymous by default (no login required); a signed-in creator's `user_id` is attached to `forge_creations`/`dioramas` rows at generation/save time (migration [api/_lib/migrations/20260712010000_creator_portfolio_user_ids.sql](api/_lib/migrations/20260712010000_creator_portfolio_user_ids.sql)) and to a new `material_restyles` row per AI restyle or colorway variant (migration [api/_lib/migrations/20260723140000_material_restyles.sql](api/_lib/migrations/20260723140000_material_restyles.sql), store [api/_lib/material-restyle-store.js](api/_lib/material-restyle-store.js)) so those creations surface here. The same opt-in attribution now links back from the diorama viewer HUD, the diorama gallery cards, and the forge result bar ("by @user") whenever a creation's creator is known. `/@:handle` ([pages/handle.html](pages/handle.html)) is a separate, narrower agent-embed page — not the human portfolio. || Labs (hidden-gems hub) | [pages/labs.html](pages/labs.html) + [src/labs.js](src/labs.js) `→ /labs` | In-repo | Data-driven discovery hub: renders every `data/pages.json` entry flagged `showcase: true` as a live card (status check + iframe preview), filterable by category || Cross-entity search | [pages/search.html](pages/search.html) `→ /search`, backend [api/search.js](api/search.js) + query layer [api/_lib/cross-search.js](api/_lib/cross-search.js) | Live | The one search across every creation type — avatars, on-chain/Solana agents, forged 3D models, worlds, and coins. Federates (not one SQL UNION — the stores are genuinely heterogeneous, two of five aren't even in the same database) five parallel queries, normalizes into one card shape, and ranks by recency plus real signals (follower count via `user_follows`, remix count, view count) — see the file header in `api/search.js` for the full unify-vs-federate writeup. Model results carry a working "Remix — $0.25" action against the existing paid rail ([api/x402/remix-asset.js](api/x402/remix-asset.js)), reused from [pages/creations.html](pages/creations.html) rather than re-derived. Coin search checks three.ws's own launch directory (`pump_agent_mints`) first, then falls back to market-wide pump.fun/Birdeye search for broader coverage (those external matches carry no verified timestamp or creator profile, and are ranked/labelled accordingly). Linked from the Discover nav menu. || Cross-surface rankings, streaks & badges | [pages/rankings.html](pages/rankings.html) `→ /rankings`, backend [api/leaderboard/unified.js](api/leaderboard/unified.js), streak/badge engine [api/_lib/streaks.js](api/_lib/streaks.js) (migration [api/_lib/migrations/20260712020000_leaderboard_streaks_badges.sql](api/_lib/migrations/20260712020000_leaderboard_streaks_badges.sql)), daily Top-10 badge sweep [api/cron/leaderboard-rollup.js](api/cron/leaderboard-rollup.js) | Live | Five real, queried leaderboard metrics — creations (forge models + worlds), remixes received, coin launches, followers, and walk distance (signed-in walkers, all-time) — ranked live with the viewer's own rank pinned even off-page. Every signed-in qualifying action (login, a finished forge model, a saved world, a `/walk` session) rolls a per-user daily streak in `user_streaks` via `recordDailyActivity()`, called from [api/_lib/auth.js](api/_lib/auth.js), [api/_lib/forge-store.js](api/_lib/forge-store.js), [api/_lib/diorama-store.js](api/_lib/diorama-store.js), and [api/walk/metrics.js](api/walk/metrics.js). Four real earned badges persist in `user_badges`: First Creation, Remixed (awarded in [api/x402/remix-asset.js](api/x402/remix-asset.js) when a remix lands on your creation), 7-Day Streak, and a daily-refreshed `top10_<metric>` per leaderboard. Streak + badges surface on the profile ([pages/profile.html](pages/profile.html)) and the Rankings page itself. Rejected metrics (documented in `api/leaderboard/unified.js`'s header): royalties earned in USD (the settlement record is a single overwritten JSONB column, not a cumulative ledger) and `/play` activity (no per-human-user session table exists). |diff --git a/api/_lib/material-restyle-store.js b/api/_lib/material-restyle-store.jsnew file mode 100644index 000000000..706859760--- /dev/null+++ b/api/_lib/material-restyle-store.js@@ -0,0 +1,121 @@+// Material restyle history — durable, best-effort record of Material Studio+// outputs so a signed-in creator's restyles show up on their public portfolio+// (the "Creations" tab at /u/:username), matching forge_creations and+// dioramas. See api/_lib/migrations/20260723140000_material_restyles.sql for+// the schema and the "why" (restyleMaterialFromInstruction / generateSeededVariants+// in api/_lib/material-studio-store.js are otherwise stateless — no account+// required, nothing recorded).+//+// Every function here is best-effort and fail-soft: a database hiccup or a+// deployment that hasn't run the migration yet must never break the actual+// restyle/variants response. Persistence is a bonus, never a gate.++import { randomUUID } from 'node:crypto';+import { sql, isDbUnavailableError } from './db.js';+import { databaseConfigured } from './env.js';+import { recordDailyActivity, maybeAwardFirstCreation } from './streaks.js';++function enabled() {+ return databaseConfigured();+}++/**+ * Record one Material Studio output. Called once per restyle result, and+ * once per variant in a variants fan-out. `userId` is only ever set when the+ * caller carried a session cookie (see getSessionUser in api/_lib/auth.js);+ * anonymous calls pass userId: null and the row is written for analytics but+ * never surfaced on a profile.+ */+export async function recordMaterialRestyle({+ userId = null,+ clientKey = null,+ action,+ label = null,+ sourceUrl,+ resultUrl,+ instruction = null,+ preset = null,+ seed = null,+ materialIndex = null,+} = {}) {+ if (!enabled() || !sourceUrl || !resultUrl) return null;+ try {+ const id = randomUUID();+ await sql`+ insert into material_restyles+ (id, user_id, client_key, action, label, source_url, result_url,+ instruction, preset, seed, material_index)+ values+ (${id}, ${userId}, ${clientKey}, ${action}, ${label}, ${sourceUrl}, ${resultUrl},+ ${instruction}, ${preset}, ${seed}, ${materialIndex ?? null})+ `;+ if (userId) {+ recordDailyActivity(userId).catch(() => {});+ maybeAwardFirstCreation(userId).catch(() => {});+ }+ return id;+ } catch (err) {+ if (isDbUnavailableError(err)) {+ console.warn('[material-restyle-store] recordMaterialRestyle skipped (db unavailable):', err?.message);+ } else {+ // Most likely the migration hasn't landed on this deployment yet+ // (undefined_table). Never let a tracking failure break the actual+ // restyle response.+ console.error('[material-restyle-store] recordMaterialRestyle failed:', err?.message);+ }+ return null;+ }+}++/** A signed-in creator's restyled models, newest first, cursor-paginated. */+export async function listRestylesByUser({ userId, limit = 24, before } = {}) {+ if (!enabled() || !userId) return [];+ const lim = Math.min(60, Math.max(1, Number(limit) || 24));+ try {+ const rows = before+ ? await sql`+ select id, action, label, source_url, result_url, instruction, preset, created_at+ from material_restyles+ where user_id = ${userId} and created_at < ${before}+ order by created_at desc limit ${lim}`+ : await sql`+ select id, action, label, source_url, result_url, instruction, preset, created_at+ from material_restyles+ where user_id = ${userId}+ order by created_at desc limit ${lim}`;+ return rows.map((r) => ({+ id: r.id,+ type: 'restyle',+ action: r.action,+ label: r.label,+ glbUrl: r.result_url,+ sourceUrl: r.source_url,+ prompt: r.instruction || r.preset || null,+ category: r.action === 'variants' ? 'colorway variant' : 'AI restyle',+ createdAt: r.created_at,+ }));+ } catch (err) {+ if (isDbUnavailableError(err)) {+ console.warn('[material-restyle-store] listRestylesByUser skipped (db unavailable):', err?.message);+ } else {+ console.error('[material-restyle-store] listRestylesByUser failed:', err?.message);+ }+ return [];+ }+}++/** Count of a signed-in creator's restyled models — profile stat strip. */+export async function countRestylesByUser({ userId } = {}) {+ if (!enabled() || !userId) return 0;+ try {+ const [row] = await sql`select count(*)::int as n from material_restyles where user_id = ${userId}`;+ return row?.n ?? 0;+ } catch (err) {+ if (isDbUnavailableError(err)) {+ console.warn('[material-restyle-store] countRestylesByUser skipped (db unavailable):', err?.message);+ } else {+ console.error('[material-restyle-store] countRestylesByUser failed:', err?.message);+ }+ return 0;+ }+}diff --git a/api/_lib/migrations/20260723140000_material_restyles.sql b/api/_lib/migrations/20260723140000_material_restyles.sqlnew file mode 100644index 000000000..1bae799f8--- /dev/null+++ b/api/_lib/migrations/20260723140000_material_restyles.sql@@ -0,0 +1,44 @@+begin;++-- Material restyle history (prompts/user-value/01-creator-profile.md follow-up)+-- ========================================================================+-- api/material-studio.js (the /restyle page + the paid restyle_material MCP+-- tool) is a stateless transform today: it reads a GLB, re-skins it, and+-- returns a durable https URL — no row anywhere records who made it. That's+-- fine for the tool itself (no account required, same "hosted FREE lane"+-- doctrine as forge_free), but it means restyled models were the one creation+-- type genuinely untracked and therefore invisible on a creator's public+-- portfolio (/u/:username).+--+-- This table is the minimal, best-effort record: one row per generated output+-- (a restyle call writes one row; a variants call writes one row per variant).+-- user_id is nullable and only ever set when the caller carried a session+-- cookie — anonymous restyles (the majority) simply never surface on any+-- profile, same pattern as forge_creations.user_id / dioramas.user_id.++create table if not exists material_restyles (+ id uuid primary key default gen_random_uuid(),+ user_id uuid references users(id) on delete set null,+ client_key text,+ action text not null check (action in ('restyle', 'variants')),+ label text,+ source_url text not null,+ result_url text not null,+ instruction text,+ preset text,+ seed integer,+ material_index integer,+ created_at timestamptz not null default now()+);++-- Power "this user's restyled models" on the profile Creations tab.+create index if not exists material_restyles_user_created+ on material_restyles (user_id, created_at desc)+ where user_id is not null;++comment on table material_restyles is+ 'One row per Material Studio output (AI PBR restyle or a seeded colorway '+ 'variant). user_id is set best-effort when the caller was signed in; NULL '+ 'for anonymous restyles, which never appear on any profile.';++commit;diff --git a/api/material-studio.js b/api/material-studio.jsindex 2bd5ec7e5..f4515f1b6 100644--- a/api/material-studio.js+++ b/api/material-studio.js@@ -33,6 +33,8 @@ import {generateSeededVariants,validateAndPersistGlb,} from './_lib/material-studio-store.js';+import { getSessionUser } from './_lib/auth.js';+import { recordMaterialRestyle } from './_lib/material-restyle-store.js';const ROUTE = '/api/material-studio';const MAX_GLB_UPLOAD_BYTES = 64 * 1024 * 1024;@@ -131,6 +133,17 @@ async function handleRestyle(req, res, ip) {parentLineage: parseParentLineage(body.parent_lineage),parentIndex: parseParentIndex(body.parent_index),});+ // Best-effort: attribute to the signed-in caller so it shows up on their+ // public portfolio's Creations tab. Never blocks or fails generation.+ const userId = await getSessionUser(req).then((u) => u?.id || null).catch(() => null);+ recordMaterialRestyle({+ userId,+ action: 'restyle',+ sourceUrl: result.sourceGlbUrl || glbUrl,+ resultUrl: result.glbUrl,+ instruction,+ materialIndex: parseMaterialIndex(body.material_index) ?? null,+ }).catch(() => {});return json(res, 200, { ok: true, ...result });}@@ -149,6 +162,25 @@ async function handleVariants(req, res, ip) {parentLineage: parseParentLineage(body.parent_lineage),parentIndex: parseParentIndex(body.parent_index),});+ // Best-effort: one row per generated variant so a prolific creator's whole+ // colorway fan-out shows up on their portfolio, not just a single card.+ const userId = await getSessionUser(req).then((u) => u?.id || null).catch(() => null);+ if (userId && Array.isArray(result.variants)) {+ Promise.all(+ result.variants.map((v) =>+ recordMaterialRestyle({+ userId,+ action: 'variants',+ label: v.label || null,+ sourceUrl: glbUrl,+ resultUrl: v.glbUrl,+ preset: typeof body.preset === 'string' ? body.preset : null,+ seed: Number.isFinite(v.seed) ? v.seed : null,+ materialIndex: parseMaterialIndex(body.material_index) ?? null,+ }),+ ),+ ).catch(() => {});+ }return json(res, 200, { ok: true, ...result });}diff --git a/api/users/[username].js b/api/users/[username].jsindex eeffe3578..9ac4029e7 100644--- a/api/users/[username].js+++ b/api/users/[username].js@@ -4,6 +4,7 @@ import { limits, clientIp } from '../_lib/rate-limit.js';import { publicUrl, thumbnailUrl } from '../_lib/r2.js';import { listCreationsByUser, countCreationsByUser } from '../_lib/forge-store.js';import { listDioramasByUser, countDioramasByUser } from '../_lib/diorama-store.js';+import { listRestylesByUser, countRestylesByUser } from '../_lib/material-restyle-store.js';import { getStreak, listBadges } from '../_lib/streaks.js';const CREATIONS_PAGE_SIZE = 24;@@ -14,28 +15,41 @@ const SITE = 'https://three.ws';// lazily from GET /api/users/:username/creations (same merge logic, cursor// paginated) so this main endpoint stays fast even for a prolific creator.function toCreationCard(it) {- return it.type === 'world'- ? {- id: it.id,- type: 'world',- title: it.title,- prompt: it.prompt,- thumbnailUrl: it.thumbnailGlb,- category: it.mood,- viewerUrl: `${SITE}/diorama?id=${it.id}`,- createdAt: it.createdAt,- }- : {- id: it.id,- type: 'model',- title: it.prompt,- prompt: it.prompt,- thumbnailUrl: it.glbUrl,- category: it.category,- isRemix: it.isRemix,- viewerUrl: `${SITE}/viewer?src=${encodeURIComponent(it.glbUrl)}`,- createdAt: it.createdAt,- };+ if (it.type === 'world') {+ return {+ id: it.id,+ type: 'world',+ title: it.title,+ prompt: it.prompt,+ thumbnailUrl: it.thumbnailGlb,+ category: it.mood,+ viewerUrl: `${SITE}/diorama?id=${it.id}`,+ createdAt: it.createdAt,+ };+ }+ if (it.type === 'restyle') {+ return {+ id: it.id,+ type: 'restyle',+ title: it.prompt || (it.action === 'variants' ? 'Colorway variant' : 'Restyled model'),+ prompt: it.prompt,+ thumbnailUrl: it.glbUrl,+ category: it.category,+ viewerUrl: `${SITE}/viewer?src=${encodeURIComponent(it.glbUrl)}`,+ createdAt: it.createdAt,+ };+ }+ return {+ id: it.id,+ type: 'model',+ title: it.prompt,+ prompt: it.prompt,+ thumbnailUrl: it.glbUrl,+ category: it.category,+ isRemix: it.isRemix,+ viewerUrl: `${SITE}/viewer?src=${encodeURIComponent(it.glbUrl)}`,+ createdAt: it.createdAt,+ };}export default wrap(async (req, res) => {@@ -72,8 +86,10 @@ export default wrap(async (req, res) => {shopRows,modelRows,worldRows,+ restyleRows,modelsCount,worldsCount,+ restylesCount,] = await Promise.all([sql`select id, name, slug, description, storage_key, thumbnail_key, tags,@@ -209,15 +225,18 @@ export default wrap(async (req, res) => {order by ap.updated_at desclimit 48`.catch(() => []),- // Forged 3D models + saved worlds (dioramas) made while signed in — the- // two creation types that live in their own anonymous-by-design tables- // rather than an owner_id-keyed one (see api/_lib/migrations/- // 20260712010000_creator_portfolio_user_ids.sql). First page only;- // deeper pages come from GET /api/users/:username/creations.+ // Forged 3D models, saved worlds (dioramas), and restyled models made+ // while signed in — the three creation types that live in their own+ // anonymous-by-design tables rather than an owner_id-keyed one (see+ // api/_lib/migrations/20260712010000_creator_portfolio_user_ids.sql and+ // 20260723140000_material_restyles.sql). First page only; deeper pages+ // come from GET /api/users/:username/creations.listCreationsByUser({ userId: user.id, limit: CREATIONS_PAGE_SIZE }),listDioramasByUser({ userId: user.id, limit: CREATIONS_PAGE_SIZE }),+ listRestylesByUser({ userId: user.id, limit: CREATIONS_PAGE_SIZE }),countCreationsByUser({ userId: user.id }),countDioramasByUser({ userId: user.id }),+ countRestylesByUser({ userId: user.id }),]);// Streak + badges — the retention layer for the cross-surface leaderboard.@@ -384,14 +403,15 @@ export default wrap(async (req, res) => {social[row.provider] = row.username;}- // Merge forged models + saved worlds into one recency-ordered feed. Each- // list is independently already sorted+capped at CREATIONS_PAGE_SIZE, so- // slicing after the merge is the true top-N across both types.- const creations = [...modelRows, ...worldRows]+ // Merge forged models + saved worlds + restyled models into one+ // recency-ordered feed. Each list is independently already sorted+capped+ // at CREATIONS_PAGE_SIZE, so slicing after the merge is the true top-N+ // across all three types.+ const creations = [...modelRows, ...worldRows, ...restyleRows].map(toCreationCard).sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt)).slice(0, CREATIONS_PAGE_SIZE);- const creationsTotal = (modelsCount ?? 0) + (worldsCount ?? 0);+ const creationsTotal = (modelsCount ?? 0) + (worldsCount ?? 0) + (restylesCount ?? 0);const creationsNext =creationsTotal > creations.length && creations.length? creations[creations.length - 1].createdAt@@ -418,6 +438,7 @@ export default wrap(async (req, res) => {creations: creationsTotal,models: modelsCount ?? 0,worlds: worldsCount ?? 0,+ restyles: restylesCount ?? 0,widget_views: Number(statsRow?.[0]?.total_widget_views ?? 0),followers: followCounts?.followers ?? 0,following: followCounts?.following ?? 0,diff --git a/api/users/[username]/creations.js b/api/users/[username]/creations.jsindex af73fc756..c411f8200 100644--- a/api/users/[username]/creations.js+++ b/api/users/[username]/creations.js@@ -4,18 +4,19 @@// The main /api/users/:username response (api/users/[username].js) already// carries a user's avatars, agents, widgets, skills, plugins, coins, and// memories — everything that lives on a row keyed by owner_id/user_id in-// its own first-class table. Forged 3D models (forge_creations) and worlds-// (dioramas) are different: both tables are deliberately anonymous-by-design-// (scoped to a hashed browser client_key so /forge and /diorama work with no+// its own first-class table. Forged 3D models (forge_creations), worlds+// (dioramas), and restyled models (material_restyles) are different: all+// three tables are deliberately anonymous-by-design (scoped to a hashed+// browser client_key so /forge, /diorama, and /restyle work with no// account), and only carry a user_id when the creator happened to be signed-// in at generation/save time. This endpoint is the one place those two-// creation types get aggregated and paginated for the profile's "Creations"-// tab — split out of the main endpoint (like collectibles.js) so a prolific+// in at generation/save time. This endpoint is the one place those creation+// types get aggregated and paginated for the profile's "Creations" tab —+// split out of the main endpoint (like collectibles.js) so a prolific// creator with hundreds of rows never slows down the profile's first paint.//// GET /api/users/:username/creations → first page (24)// GET /api/users/:username/creations?before=<iso> → next page (cursor)-// GET /api/users/:username/creations?type=model|world → one type only+// GET /api/users/:username/creations?type=model|world|restyle → one type only//// Public, no auth: the profile it backs is public. Anonymous creations// (user_id null — the majority of forge_creations/dioramas rows) never@@ -26,6 +27,7 @@ import { cors, json, method, wrap, error, rateLimited } from '../../_lib/http.jsimport { limits, clientIp } from '../../_lib/rate-limit.js';import { listCreationsByUser } from '../../_lib/forge-store.js';import { listDioramasByUser } from '../../_lib/diorama-store.js';+import { listRestylesByUser } from '../../_lib/material-restyle-store.js';const SITE = 'https://three.ws';@@ -51,48 +53,64 @@ export default wrap(async (req, res) => {if (!user) return error(res, 404, 'not_found', 'user not found');const url = new URL(req.url, 'http://x');- const typeFilter = url.searchParams.get('type'); // 'model' | 'world' | null (both)+ const typeFilter = url.searchParams.get('type'); // 'model' | 'world' | 'restyle' | null (all)const before = url.searchParams.get('before') || undefined;const limit = Math.min(Math.max(Number(url.searchParams.get('limit')) || 24, 1), 48);- // Over-fetch each source so merging two independently-paginated lists still+ // Over-fetch each source so merging independently-paginated lists still// yields a full page of the true recency-merged feed, not an undercount.const fetchLimit = limit + 1;- const [models, worlds] =+ const [models, worlds, restyles] =typeFilter === 'world'- ? [[], await listDioramasByUser({ userId: user.id, limit: fetchLimit, before })]+ ? [[], await listDioramasByUser({ userId: user.id, limit: fetchLimit, before }), []]: typeFilter === 'model'- ? [await listCreationsByUser({ userId: user.id, limit: fetchLimit, before }), []]- : await Promise.all([- listCreationsByUser({ userId: user.id, limit: fetchLimit, before }),- listDioramasByUser({ userId: user.id, limit: fetchLimit, before }),- ]);+ ? [await listCreationsByUser({ userId: user.id, limit: fetchLimit, before }), [], []]+ : typeFilter === 'restyle'+ ? [[], [], await listRestylesByUser({ userId: user.id, limit: fetchLimit, before })]+ : await Promise.all([+ listCreationsByUser({ userId: user.id, limit: fetchLimit, before }),+ listDioramasByUser({ userId: user.id, limit: fetchLimit, before }),+ listRestylesByUser({ userId: user.id, limit: fetchLimit, before }),+ ]);- const items = [...models, ...worlds]- .map((it) =>- it.type === 'world'- ? {- id: it.id,- type: 'world',- title: it.title,- prompt: it.prompt,- thumbnailUrl: it.thumbnailGlb,- category: it.mood,- viewerUrl: `${SITE}/diorama?id=${it.id}`,- createdAt: it.createdAt,- }- : {- id: it.id,- type: 'model',- title: it.prompt,- prompt: it.prompt,- thumbnailUrl: it.glbUrl,- category: it.category,- isRemix: it.isRemix,- viewerUrl: `${SITE}/viewer?src=${encodeURIComponent(it.glbUrl)}`,- createdAt: it.createdAt,- },- )+ const items = [...models, ...worlds, ...restyles]+ .map((it) => {+ if (it.type === 'world') {+ return {+ id: it.id,+ type: 'world',+ title: it.title,+ prompt: it.prompt,+ thumbnailUrl: it.thumbnailGlb,+ category: it.mood,+ viewerUrl: `${SITE}/diorama?id=${it.id}`,+ createdAt: it.createdAt,+ };+ }+ if (it.type === 'restyle') {+ return {+ id: it.id,+ type: 'restyle',+ title: it.prompt || (it.action === 'variants' ? 'Colorway variant' : 'Restyled model'),+ prompt: it.prompt,+ thumbnailUrl: it.glbUrl,+ category: it.category,+ viewerUrl: `${SITE}/viewer?src=${encodeURIComponent(it.glbUrl)}`,+ createdAt: it.createdAt,+ };+ }+ return {+ id: it.id,+ type: 'model',+ title: it.prompt,+ prompt: it.prompt,+ thumbnailUrl: it.glbUrl,+ category: it.category,+ isRemix: it.isRemix,+ viewerUrl: `${SITE}/viewer?src=${encodeURIComponent(it.glbUrl)}`,+ createdAt: it.createdAt,+ };+ }).sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt)).slice(0, limit);diff --git a/data/changelog.json b/data/changelog.jsonindex 707b33167..08088a8df 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -9,6 +9,15 @@"security"]},+ {+ "date": "2026-07-23",+ "title": "Restyled models now show up on your creator portfolio",+ "summary": "Your public portfolio at /u/:username (and /profile for yourself) already collected your forged 3D models and saved worlds into one \"Creations\" feed alongside your avatars, agents, launched coins, skills, and plugins. Restyled models were the missing piece: an AI material restyle (\"make it chrome\", \"cyberpunk neon\") or a seeded colorway variant fan-out from the Restyle Studio now records to your account when you're signed in, and shows up in Creations with a live 3D thumbnail, the instruction or preset used, and a link to the viewer, right next to your other work.",+ "tags": [+ "feature"+ ],+ "link": "/profile"+ },{"date": "2026-07-23","title": "The Concierge becomes a Shopify shopping assistant, with product cards",diff --git a/pages/profile.html b/pages/profile.htmlindex 913a77c74..02ee9802f 100644--- a/pages/profile.html+++ b/pages/profile.html@@ -2934,8 +2934,8 @@`camera-orbit="35deg 78deg auto" shadow-intensity="0" exposure="0.9" ` +`style="width:100%;height:100%;pointer-events:none;--poster-color:transparent" ` +`aria-hidden="true"></model-viewer>`- : `<div class="up-card-thumb-placeholder">${c.type === 'world' ? '⛰' : '◎'}</div>`;- const badge = c.type === 'world' ? 'World' : 'Model';+ : `<div class="up-card-thumb-placeholder">${c.type === 'world' ? '⛰' : c.type === 'restyle' ? '✦' : '◎'}</div>`;+ const badge = c.type === 'world' ? 'World' : c.type === 'restyle' ? 'Restyle' : 'Model';const date = c.createdAt? new Date(c.createdAt).toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' }): '';diff --git a/tests/api/material-restyle-store.test.js b/tests/api/material-restyle-store.test.jsnew file mode 100644index 000000000..84740afc4--- /dev/null+++ b/tests/api/material-restyle-store.test.js@@ -0,0 +1,111 @@+// Tests for api/_lib/material-restyle-store.js — the durable, best-effort+// record of Material Studio outputs that powers the "Creations" tab on a+// signed-in creator's public portfolio (/u/:username). DB is mocked: these+// prove the write/read shape and the fail-soft behavior (a DB hiccup or a+// deployment that hasn't run the migration yet must never throw).++import { describe, it, expect, vi, beforeEach } from 'vitest';++const queue = [];+vi.mock('../../api/_lib/db.js', () => {+ const sql = vi.fn(async () => (queue.length ? queue.shift() : []));+ return { sql, isDbUnavailableError: () => false };+});+vi.mock('../../api/_lib/env.js', () => ({ databaseConfigured: () => true }));+vi.mock('../../api/_lib/streaks.js', () => ({+ recordDailyActivity: vi.fn(async () => {}),+ maybeAwardFirstCreation: vi.fn(async () => {}),+}));++import {+ recordMaterialRestyle,+ listRestylesByUser,+ countRestylesByUser,+} from '../../api/_lib/material-restyle-store.js';+import { sql } from '../../api/_lib/db.js';++beforeEach(() => {+ queue.length = 0;+ vi.clearAllMocks();+});++describe('recordMaterialRestyle', () => {+ it('inserts a row and returns its id for a signed-in restyle', async () => {+ queue.push([]); // insert+ const id = await recordMaterialRestyle({+ userId: 'user-1',+ action: 'restyle',+ sourceUrl: 'https://cdn.three.ws/src.glb',+ resultUrl: 'https://cdn.three.ws/out.glb',+ instruction: 'make it chrome',+ });+ expect(typeof id).toBe('string');+ expect(sql).toHaveBeenCalledOnce();+ });++ it('no-ops (returns null) when resultUrl is missing', async () => {+ const id = await recordMaterialRestyle({ userId: 'user-1', action: 'restyle', sourceUrl: 'x' });+ expect(id).toBeNull();+ expect(sql).not.toHaveBeenCalled();+ });++ it('fails soft to null when the insert throws (e.g. migration not applied yet)', async () => {+ sql.mockImplementationOnce(async () => {+ throw new Error('relation "material_restyles" does not exist');+ });+ const id = await recordMaterialRestyle({+ userId: 'user-1',+ action: 'variants',+ sourceUrl: 'https://cdn.three.ws/src.glb',+ resultUrl: 'https://cdn.three.ws/variant-1.glb',+ preset: 'chrome',+ seed: 42,+ });+ expect(id).toBeNull();+ });+});++describe('listRestylesByUser / countRestylesByUser', () => {+ it('returns [] with no userId, without querying the db', async () => {+ const rows = await listRestylesByUser({ userId: null });+ expect(rows).toEqual([]);+ expect(sql).not.toHaveBeenCalled();+ });++ it('maps rows into the shared creation-card shape', async () => {+ queue.push([+ {+ id: 'r1',+ action: 'restyle',+ label: null,+ source_url: 'https://cdn.three.ws/src.glb',+ result_url: 'https://cdn.three.ws/out.glb',+ instruction: 'make it wooden',+ preset: null,+ created_at: '2026-07-23T00:00:00Z',+ },+ ]);+ const rows = await listRestylesByUser({ userId: 'user-1' });+ expect(rows).toHaveLength(1);+ expect(rows[0]).toMatchObject({+ type: 'restyle',+ glbUrl: 'https://cdn.three.ws/out.glb',+ prompt: 'make it wooden',+ category: 'AI restyle',+ });+ });++ it('counts a user\'s restyles', async () => {+ queue.push([{ n: 7 }]);+ const n = await countRestylesByUser({ userId: 'user-1' });+ expect(n).toBe(7);+ });++ it('fails soft to 0 on a query error', async () => {+ sql.mockImplementationOnce(async () => {+ throw new Error('db unavailable');+ });+ const n = await countRestylesByUser({ userId: 'user-1' });+ expect(n).toBe(0);+ });+});