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(gallery/forge/selfie): forge feed in gallery, selfie UX polish, regen provider hardening
nirholas0e201b9b5633
diff --git a/api/_lib/regen-provider.js b/api/_lib/regen-provider.jsindex ba7739a2d..515998b43 100644--- a/api/_lib/regen-provider.js+++ b/api/_lib/regen-provider.js@@ -5,11 +5,155 @@// loading e.g. the Replicate SDK on every request when regeneration is unused.// Cached per-process after first load.//-// Provider name precedence:+// Provider name precedence (platform-level, env-configured):// 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.+// GCP_RECONSTRUCTION_URL → gcp, HF_TOKEN → huggingface.+//+// BYOK providers (Meshy, Tripo) are NOT in this precedence chain — they are+// request-scoped (the caller supplies the key) and are loaded via+// getRegenProviderByName(). The reconstruct endpoint checks platform first and+// falls back to a user's stored BYOK key when the platform is unconfigured.++// Tier used when adapting BYOK geometry providers for the regen interface.+// Mirrors the forge "standard" tier: solid polycount, PBR textures, no HD+// surcharge so the selfie pipeline isn't pay-gated without warning.+const REGEN_TIER = Object.freeze({ polycount: 30_000, pbr: true, hd: false });++// BYOK provider names that support the reconstruct (image → 3D) mode.+export const BYOK_REGEN_PROVIDERS = Object.freeze(['meshy', 'tripo']);++// Wraps createMeshyProvider to speak the regen submit/status interface.+// ext_job_id is the raw Meshy task id — job.provider === 'meshy' tells the+// status handler which adapter to use, so no kind prefix is needed.+function createMeshyRegenAdapter(key) {+ let _meshy;+ async function meshy() {+ if (!_meshy) {+ const mod = await import('../_providers/meshy.js');+ _meshy = mod.createMeshyProvider(key);+ }+ return _meshy;+ }++ return {+ supportsMode(mode) {+ return mode === 'reconstruct';+ },+ supportsMultiview() {+ return false;+ },++ async submit({ mode, params, sourceUrl }) {+ if (mode !== 'reconstruct') {+ throw Object.assign(+ new Error(`meshy BYOK regen does not support mode "${mode}"`),+ { code: 'mode_unconfigured', status: 501 },+ );+ }+ const images = Array.isArray(params?.images) ? params.images : [];+ const imageUrl = images[0] || sourceUrl;+ if (!imageUrl) {+ throw Object.assign(new Error('meshy regen: no image URL provided'), {+ code: 'invalid_request',+ status: 400,+ });+ }+ const provider = await meshy();+ const result = await provider.imageTo3d({+ imageUrl,+ prompt: params?.name || '',+ tier: REGEN_TIER,+ });+ // result.taskId is the Meshy task id; stored directly as ext_job_id.+ return {+ extJobId: result.taskId,+ eta: 90,+ backend: 'meshy',+ };+ },++ async status(extJobId) {+ if (!extJobId) return { status: 'failed', error: 'missing ext_job_id' };+ const provider = await meshy();+ // Meshy status always uses kind 'image-to-3d' for selfie submissions.+ return provider.status({ kind: 'image-to-3d', taskId: extJobId });+ },+ };+}++// Wraps createTripoProvider to speak the regen submit/status interface.+function createTripoRegenAdapter(key) {+ let _tripo;+ async function tripo() {+ if (!_tripo) {+ const mod = await import('../_providers/tripo.js');+ _tripo = mod.createTripoProvider(key);+ }+ return _tripo;+ }++ return {+ supportsMode(mode) {+ return mode === 'reconstruct';+ },+ supportsMultiview() {+ return false;+ },++ async submit({ mode, params, sourceUrl }) {+ if (mode !== 'reconstruct') {+ throw Object.assign(+ new Error(`tripo BYOK regen does not support mode "${mode}"`),+ { code: 'mode_unconfigured', status: 501 },+ );+ }+ const images = Array.isArray(params?.images) ? params.images : [];+ const imageUrl = images[0] || sourceUrl;+ if (!imageUrl) {+ throw Object.assign(new Error('tripo regen: no image URL provided'), {+ code: 'invalid_request',+ status: 400,+ });+ }+ const provider = await tripo();+ const result = await provider.imageTo3d({ imageUrl, tier: REGEN_TIER });+ return {+ extJobId: result.taskId,+ eta: 60,+ backend: 'tripo',+ };+ },++ async status(extJobId) {+ if (!extJobId) return { status: 'failed', error: 'missing ext_job_id' };+ const provider = await tripo();+ return provider.status({ taskId: extJobId });+ },+ };+}++// Instantiate a named BYOK regen adapter with the given API key. Only the+// providers listed in BYOK_REGEN_PROVIDERS are supported here.+export function getRegenProviderByName(name, key) {+ if (!key) {+ throw Object.assign(new Error(`${name} regen: API key is required`), {+ code: 'missing_key',+ status: 400,+ });+ }+ switch (name) {+ case 'meshy':+ return { name, instance: createMeshyRegenAdapter(key) };+ case 'tripo':+ return { name, instance: createTripoRegenAdapter(key) };+ default:+ throw Object.assign(new Error(`unknown BYOK regen provider: ${name}`), {+ code: 'regen_provider_unknown',+ status: 501,+ });+ }+}let _regenProviderCache = null;let _regenProviderName = null;@@ -55,3 +199,32 @@ export async function getRegenProvider() {status: 501,});}++// Resolve the provider for a job that's already in flight, routing by the+// provider name stored on the job row. BYOK providers (meshy, tripo) need the+// user's stored key to poll — fetched from the DB via the request session.+// Platform providers (replicate, gcp, huggingface) use env credentials as usual.+export async function getRegenProviderForJob(jobProvider, req) {+ if (!jobProvider) return { name: 'none', instance: null };++ // Platform providers: use the existing env-credential path.+ if (['replicate', 'gcp', 'huggingface', 'hf'].includes(jobProvider)) {+ return getRegenProvider();+ }++ // BYOK providers: re-resolve the user's stored key at poll time. The key+ // is never stored on the job row itself (it's a secret); the user's session+ // is the authority.+ if (BYOK_REGEN_PROVIDERS.includes(jobProvider)) {+ try {+ const { resolveProviderKey } = await import('./forge-provider-key.js');+ const key = await resolveProviderKey(req, null, jobProvider);+ if (!key) return { name: jobProvider, instance: null };+ return getRegenProviderByName(jobProvider, key);+ } catch {+ return { name: jobProvider, instance: null };+ }+ }++ return { name: 'none', instance: null };+}diff --git a/api/_lib/x402-paid-endpoint.js b/api/_lib/x402-paid-endpoint.jsindex efb014d69..37d6d6d0f 100644--- a/api/_lib/x402-paid-endpoint.js+++ b/api/_lib/x402-paid-endpoint.js@@ -269,7 +269,8 @@ export function paidEndpoint(spec) {}const routeConfig = { path: route, method: method.toUpperCase(), requiredScope };- const allowMethods = `${method.toUpperCase()},OPTIONS`;+ const httpMethod = method.toUpperCase();+ const allowMethods = httpMethod === 'GET' ? 'GET,HEAD,OPTIONS' : `${httpMethod},OPTIONS`;const pidRequired = Boolean(paymentIdentifier.required);const pidTtlSeconds = paymentIdentifier.ttlSeconds;const pidExtension = paymentIdentifierExtension(pidRequired);@@ -282,9 +283,10 @@ export function paidEndpoint(spec) {return wrap(async function paidHandler(req, res) {const requestStartTime = Date.now();if (cors(req, res, { methods: allowMethods, origins: '*' })) return;- if (req.method !== method.toUpperCase()) {- res.setHeader('allow', method.toUpperCase());- return error(res, 405, 'method_not_allowed', `use ${method.toUpperCase()}`);+ const isHead = req.method === 'HEAD' && httpMethod === 'GET';+ if (req.method !== httpMethod && !isHead) {+ res.setHeader('allow', allowMethods);+ return error(res, 405, 'method_not_allowed', `use ${httpMethod}`);}const resourceUrl =diff --git a/api/_lib/x402/offer-receipt-issuer.js b/api/_lib/x402/offer-receipt-issuer.jsindex e86b412eb..c06d43ed1 100644--- a/api/_lib/x402/offer-receipt-issuer.js+++ b/api/_lib/x402/offer-receipt-issuer.js@@ -156,7 +156,10 @@ async function buildJwsIssuer() {* configured. Throws if a key is configured but invalid (fail-fast on boot).*/export async function getIssuer() {- if (_issuerError) throw _issuerError;+ // After the first initialization failure the error was already logged by the+ // caller. Re-throwing on every subsequent request would spam the error log;+ // return null so the offers extension is silently skipped instead.+ if (_issuerError) return null;if (_issuerCache !== null) return _issuerCache;const format = (env.OFFER_RECEIPT_FORMAT || 'eip712').toLowerCase();try {diff --git a/api/avatars/_actions.js b/api/avatars/_actions.jsindex 079877b99..7d30f4e0b 100644--- a/api/avatars/_actions.js+++ b/api/avatars/_actions.js@@ -15,7 +15,8 @@ import { requireCsrf } from '../_lib/csrf.js';import { z } from 'zod';import { randomUUID } from 'crypto';import { isValidGlbHeader } from '../_lib/glb-inspect.js';-import { getRegenProvider } from '../_lib/regen-provider.js';+import { getRegenProvider, getRegenProviderByName, getRegenProviderForJob, BYOK_REGEN_PROVIDERS } from '../_lib/regen-provider.js';+import { resolveProviderKey } from '../_lib/forge-provider-key.js';import { finalizeReconstructStage, pollRiggingStage } from '../_lib/reconstruct-finalize.js';import { textToImage } from '../_mcp3d/text-to-image.js';@@ -431,9 +432,11 @@ const handleRegenerateStatus = wrap(async (req, res) => {// Pull a fresh status from the provider when the job is still in flight// and we have an external id to query. The status endpoint serves as our// poll trigger — no separate cron needed for short-lived jobs.+ // Route by job.provider so BYOK jobs (meshy, tripo) load the right adapter+ // with the user's stored key, not the platform env credential.if ((job.status === 'queued' || job.status === 'running') && job.provider && job.ext_job_id) {try {- const provider = await getRegenProvider();+ const provider = await getRegenProviderForJob(job.provider, req);if (provider.instance) {const update = await provider.instance.status(job.ext_job_id);const nextStatus = update.status;@@ -812,13 +815,19 @@ const handleAutoTag = wrap(async (req, res) => {});// ── reconstruct (Phase 1 — Selfie → Avatar engine) ────────────────────────────-// Submits a Replicate reconstruct job from selfie photos. No source avatar-// exists yet; the avatar row is materialized when the status handler observes-// a successful result and copies the generated GLB into R2.+// Submits a reconstruct job from selfie photos. No source avatar exists yet;+// the avatar row is materialized when the status handler observes a successful+// result and copies the generated GLB into R2.+//+// Provider resolution order:+// 1. Platform env (REPLICATE_API_TOKEN / GCP_RECONSTRUCTION_URL / HF_TOKEN)+// 2. Inline BYOK key in request body (provider_name + provider_key)+// 3. User's stored BYOK key for a supported provider (meshy > tripo)+// When none is available, returns needs_key so the client can prompt for a key.// Photos may be either:// • http(s):// URL — typically an R2 object URL the client uploaded first-// • data:image/...;base64,... — inline base64 (Replicate accepts these natively)+// • data:image/...;base64,... — inline base64 (Replicate / Meshy accept these)const photoUrlOrDataUri = z.string().max(8 * 1024 * 1024) // generous cap to allow inline JPEGs up to ~6 MB pre-base64@@ -840,6 +849,10 @@ const reconstructSchema = zprompt: z.string().trim().min(3).max(600).optional(),visibility: z.enum(['private', 'unlisted', 'public']).optional(),params: z.record(z.unknown()).optional(),+ // BYOK: caller can supply their own provider key when the platform backend+ // is unconfigured. Never stored on the job row.+ provider_key: z.string().trim().max(512).optional(),+ provider_name: z.enum(['meshy', 'tripo']).optional(),}).refine((v) => (Array.isArray(v.photos) && v.photos.length > 0) || !!v.prompt, {message: 'provide either photos or a prompt',@@ -861,19 +874,50 @@ const handleReconstruct = wrap(async (req, res) => {if (!rl.success) return rateLimited(res, rl);const body = parse(reconstructSchema, await readJson(req));+ // ── Provider resolution ──────────────────────────────────────────────────let provider;try {provider = await getRegenProvider();} catch (err) {return error(res, err.status || 501, err.code || 'regen_provider_error', err.message);}++ // Platform provider not configured — try BYOK fallback.if (provider.name === 'none') {- return error(- res,- 501,- 'regen_unconfigured',- 'Avatar reconstruction requires a configured backend. Set AVATAR_REGEN_PROVIDER and the matching API token (REPLICATE_API_TOKEN, HF_TOKEN, or GCP_RECONSTRUCTION_URL).',- );+ // 1. Inline key supplied by the client (provider_name + provider_key).+ if (body.provider_key && body.provider_name) {+ try {+ provider = getRegenProviderByName(body.provider_name, body.provider_key);+ } catch (err) {+ return error(res, err.status || 400, err.code || 'invalid_key', err.message);+ }+ }++ // 2. User's stored BYOK key — iterate preferred providers in order.+ if (provider.name === 'none') {+ for (const pName of BYOK_REGEN_PROVIDERS) {+ try {+ const key = await resolveProviderKey(req, null, pName);+ if (key) {+ provider = getRegenProviderByName(pName, key);+ break;+ }+ } catch {+ // resolveProviderKey can fail when there is no DB session — skip.+ }+ }+ }++ // 3. Still nothing — tell the client which BYOK providers are accepted.+ if (provider.name === 'none') {+ return json(res, 402, {+ ok: false,+ code: 'regen_needs_byok',+ message:+ 'Avatar reconstruction requires an API key. Add your Meshy or Tripo key in settings, or pass provider_key + provider_name in this request.',+ providers: BYOK_REGEN_PROVIDERS,+ });+ }}// Text → avatar: turn the prompt into a frontal reference image, then treatdiff --git a/api/config.js b/api/config.jsindex d45135b05..04c6f592a 100644--- a/api/config.js+++ b/api/config.js@@ -1,18 +1,14 @@// 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';+import { resolveProviderName, BYOK_REGEN_PROVIDERS } 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;- // 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';+ const hasPlatformProvider = 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@@ -38,10 +34,16 @@ export default wrap(async (req, res) => {samlEnabled,samlLabel: process.env.SAML_BUTTON_LABEL || 'Single sign-on (SSO)',features: {- // /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,+ // avatarReconstruct is always true: BYOK providers (Meshy, Tripo) are+ // always available — the selfie page handles key entry inline when the+ // platform backend isn't configured. The reconstruct endpoint returns+ // { code: 'regen_needs_byok' } rather than 501 in that case.+ avatarReconstruct: true,+ // 'platform' = server has configured creds (no key needed by user).+ // 'byok' = reconstruction works but user must supply an API key.+ avatarReconstructMode: hasPlatformProvider ? 'platform' : 'byok',+ // Which BYOK providers the user can use when platform is unconfigured.+ avatarByokProviders: hasPlatformProvider ? [] : [...BYOK_REGEN_PROVIDERS],// True when the pipeline returns a rigged (animation-ready) model.avatarRigging: riggingEnabled,// /create/video uses the LongCat GPU worker on Cloud Run; onlydiff --git a/pages/create-selfie.html b/pages/create-selfie.htmlindex 01742cab7..fad125b4e 100644--- a/pages/create-selfie.html+++ b/pages/create-selfie.html@@ -1624,35 +1624,218 @@</section></main>- <!-- Step "unavailable" — shown when the avatar-reconstruction backend isn't- wired in this environment (no AVATAR_REGEN_PROVIDER + provider creds).- Hidden by default; the boot script swaps to this and hides the others- when /api/config.features.avatarReconstruct === false. -->- <section- class="step"- data-step="unavailable"- hidden- style="text-align: center; max-width: 520px; margin: 0 auto; padding: 48px 24px"- >- <h1 style="margin: 0 0 12px">Selfie avatars are still warming up</h1>- <p class="sub" style="margin: 0 0 24px; color: #9aa3b2">- The photo-to-avatar engine is being provisioned for this environment. In the- meantime, you can build an avatar in the studio — same outputs, same workflow, fully- ready today.- </p>- <div class="done-actions" style="justify-content: center">- <a- href="/create"- class="btn-save"- style="text-decoration: none; display: inline-block"- >Open the avatar studio →</a- >- <a- href="/app"- class="btn-ghost"- style="text-decoration: none; display: inline-block"- >Back to my workspace</a- >+ <!-- Step "api-key" — shown when reconstruction requires a BYOK API key.+ Displayed either at boot (BYOK mode, no cached key) or when the+ selfie:needs-byok event fires mid-flow (no key was cached and the+ platform has no configured backend). -->+ <section class="step" data-step="api-key" hidden>+ <style>+ .byok-card {+ max-width: 480px;+ margin: 0 auto;+ padding: 40px 24px;+ }+ .byok-card h1 {+ font-size: 1.5rem;+ font-weight: 700;+ margin: 0 0 8px;+ letter-spacing: -0.02em;+ }+ .byok-card .sub {+ color: #9aa3b2;+ margin: 0 0 32px;+ font-size: 0.9rem;+ }+ .byok-provider-row {+ display: flex;+ gap: 12px;+ margin-bottom: 24px;+ }+ .byok-provider-btn {+ flex: 1;+ padding: 14px 16px;+ border: 1.5px solid var(--border, #222);+ border-radius: 10px;+ background: var(--panel-elev, #111);+ color: var(--text, #e8e8e8);+ cursor: pointer;+ text-align: left;+ transition: border-color 0.15s, background 0.15s;+ font-size: 0.875rem;+ }+ .byok-provider-btn:hover {+ border-color: #555;+ background: #1a1a1a;+ }+ .byok-provider-btn.selected {+ border-color: #fff;+ background: #1c1c1c;+ }+ .byok-provider-btn .provider-name {+ font-weight: 600;+ display: block;+ margin-bottom: 2px;+ }+ .byok-provider-btn .provider-desc {+ color: #9aa3b2;+ font-size: 0.78rem;+ }+ .byok-key-group {+ position: relative;+ margin-bottom: 20px;+ }+ .byok-key-input {+ width: 100%;+ padding: 12px 44px 12px 14px;+ background: var(--panel-elev, #111);+ border: 1.5px solid var(--border, #222);+ border-radius: 8px;+ color: var(--text, #e8e8e8);+ font-size: 0.875rem;+ font-family: 'SF Mono', 'Fira Mono', monospace;+ outline: none;+ box-sizing: border-box;+ transition: border-color 0.15s;+ }+ .byok-key-input:focus {+ border-color: #555;+ }+ .byok-key-input.invalid {+ border-color: #f87171;+ }+ .byok-key-toggle {+ position: absolute;+ right: 12px;+ top: 50%;+ transform: translateY(-50%);+ background: none;+ border: none;+ color: #666;+ cursor: pointer;+ padding: 4px;+ font-size: 0.8rem;+ }+ .byok-key-toggle:hover { color: #aaa; }+ .byok-hint {+ font-size: 0.78rem;+ color: #777;+ margin-bottom: 20px;+ }+ .byok-hint a {+ color: #9aa3b2;+ text-decoration: underline;+ }+ .byok-hint a:hover { color: #e8e8e8; }+ .byok-error {+ font-size: 0.82rem;+ color: #f87171;+ margin-bottom: 12px;+ display: none;+ }+ .byok-error.show { display: block; }+ .byok-actions {+ display: flex;+ flex-direction: column;+ gap: 10px;+ }+ .byok-submit {+ width: 100%;+ padding: 13px 20px;+ background: #fff;+ color: #000;+ border: none;+ border-radius: 8px;+ font-size: 0.9rem;+ font-weight: 600;+ cursor: pointer;+ transition: opacity 0.15s;+ }+ .byok-submit:disabled {+ opacity: 0.45;+ cursor: not-allowed;+ }+ .byok-divider {+ text-align: center;+ color: #555;+ font-size: 0.78rem;+ margin: 2px 0;+ }+ .byok-alt {+ text-align: center;+ font-size: 0.82rem;+ color: #666;+ }+ .byok-alt a {+ color: #9aa3b2;+ text-decoration: underline;+ }+ .byok-alt a:hover { color: #e8e8e8; }+ </style>++ <div class="byok-card">+ <h1>Connect your 3D engine</h1>+ <p class="sub">+ Selfie → avatar uses a professional 3D AI API. Add your key to continue — it takes 30 seconds.+ </p>++ <!-- Provider selector -->+ <div class="byok-provider-row" role="radiogroup" aria-label="Choose 3D engine">+ <button+ type="button"+ class="byok-provider-btn selected"+ data-byok-provider="meshy"+ aria-pressed="true"+ >+ <span class="provider-name">Meshy</span>+ <span class="provider-desc">Image → 3D · ~90s · free trial credits</span>+ </button>+ <button+ type="button"+ class="byok-provider-btn"+ data-byok-provider="tripo"+ aria-pressed="false"+ >+ <span class="provider-name">Tripo</span>+ <span class="provider-desc">Image → 3D · ~60s · high quality</span>+ </button>+ </div>++ <!-- Key input -->+ <div class="byok-key-group">+ <input+ type="password"+ id="byok-key-input"+ class="byok-key-input"+ placeholder="msy_…"+ autocomplete="off"+ spellcheck="false"+ aria-label="API key"+ />+ <button+ type="button"+ class="byok-key-toggle"+ id="byok-key-toggle"+ aria-label="Show key"+ >show</button>+ </div>++ <p class="byok-hint" id="byok-key-hint">+ Get a free key at <a href="https://www.meshy.ai" target="_blank" rel="noopener">meshy.ai</a>+ — it takes under a minute. The key stays in your browser and is never stored on our servers.+ </p>++ <p class="byok-error" id="byok-key-error"></p>++ <div class="byok-actions">+ <button type="button" class="byok-submit" id="byok-submit-btn" disabled>+ Continue →+ </button>+ <div class="byok-divider">or</div>+ <p class="byok-alt">+ Already saved a key?+ <a href="/dashboard/settings#api-keys">Manage keys in settings →</a>+ </p>+ </div></div></section>diff --git a/pages/forge.html b/pages/forge.htmlindex 30f15cf42..110252bb2 100644--- a/pages/forge.html+++ b/pages/forge.html@@ -2028,37 +2028,68 @@}}- /* Remix flash: border pulse on the prompt box when a prompt is loaded */+ /* Remix flash: border pulse + glow on the prompt box when a prompt loads */@keyframes prompt-remix-flash {- 0% { box-shadow: 0 0 0 0 var(--accent); border-color: var(--accent); }- 40% { box-shadow: 0 0 0 6px transparent; border-color: var(--accent); }- 100% { box-shadow: 0 0 0 0 transparent; }+ 0% {+ box-shadow: 0 0 0 0 color-mix(in srgb, var(--accent) 60%, transparent);+ border-color: var(--accent);+ background: color-mix(in srgb, var(--accent) 6%, transparent);+ }+ 30% {+ box-shadow: 0 0 0 5px color-mix(in srgb, var(--accent) 18%, transparent);+ border-color: var(--accent);+ }+ 100% {+ box-shadow: 0 0 0 0 transparent;+ border-color: var(--stroke);+ background: var(--surface-2, transparent);+ }}#prompt.remix-flash {- animation: prompt-remix-flash 0.7s ease forwards;+ animation: prompt-remix-flash 0.9s cubic-bezier(0.22, 1, 0.36, 1) forwards;}- /* Remix toast — floats at top of viewport, fades out */+ /* Remix toast — slides in from above, then fades out */+ @keyframes toast-enter {+ from { opacity: 0; transform: translateX(-50%) translateY(-10px); }+ to { opacity: 1; transform: translateX(-50%) translateY(0); }+ }.remix-toast {position: fixed;- top: 5rem;+ top: 5.5rem;left: 50%;transform: translateX(-50%) translateY(0);- background: var(--surface-3, #1e1e1e);- border: 1px solid var(--accent);+ background: color-mix(in srgb, var(--surface-3, #1a1a1a) 92%, transparent);+ backdrop-filter: blur(12px);+ -webkit-backdrop-filter: blur(12px);+ border: 1px solid color-mix(in srgb, var(--accent) 55%, transparent);color: var(--ink);- font-size: 0.8rem;- padding: 0.5rem 1.1rem;+ font-size: 0.78rem;+ font-weight: 500;+ letter-spacing: 0.01em;+ padding: 0.45rem 1.1rem 0.45rem 0.9rem;border-radius: 999px;pointer-events: none;white-space: nowrap;z-index: 1000;opacity: 1;- transition: opacity 0.4s ease, transform 0.4s ease;+ display: flex;+ align-items: center;+ gap: 0.45rem;+ box-shadow: 0 4px 24px rgba(0, 0, 0, 0.4);+ animation: toast-enter 0.3s cubic-bezier(0.22, 1, 0.36, 1) forwards;+ transition: opacity 0.35s ease, transform 0.35s ease;+ }+ .remix-toast .toast-dot {+ width: 6px;+ height: 6px;+ border-radius: 50%;+ background: var(--accent);+ flex: none;}.remix-toast.fade-out {opacity: 0;- transform: translateX(-50%) translateY(-6px);+ transform: translateX(-50%) translateY(-8px);}/* Empty + error + unconfigured */diff --git a/public/gallery/gallery.css b/public/gallery/gallery.cssindex e96abff63..a023f6165 100644--- a/public/gallery/gallery.css+++ b/public/gallery/gallery.css@@ -779,148 +779,148 @@ body.gallery-page {}}-/* ─── From the Forge section ─────────────────────────────────────────────── */++/* =============================================================================+ From the Forge — section divider + card overrides+ Cards use the same .gallery-card base, so hover/border/shadow all inherit.+ Only the thumb and identity pieces need overrides.+ ============================================================================= */++/* Section wrapper */.gallery-forge-section {- max-width: 1200px;- margin: 0 auto 4rem;- padding: 0 1.5rem;+ margin-top: clamp(40px, 6vw, 72px);+ padding-top: clamp(32px, 5vw, 56px);+ border-top: 1px solid rgba(255, 255, 255, 0.07);+ position: relative;}++/* Section header row */.gallery-forge-head {display: flex;align-items: flex-start;justify-content: space-between;gap: 1rem;- margin-bottom: 1.25rem;+ margin-bottom: 1.5rem;flex-wrap: wrap;}+.gallery-forge-title-row {+ display: flex;+ align-items: center;+ gap: 10px;+ margin-bottom: 6px;+}+.gallery-forge-icon {+ width: 22px;+ height: 22px;+ flex: none;+ opacity: 0.6;+}.gallery-forge-title {- font-size: 1.2rem;- font-weight: 600;- color: var(--ink, #f0f0f0);- margin: 0 0 0.3rem;+ font-size: 1.15rem;+ font-weight: 700;+ color: #fff;+ margin: 0;+ letter-spacing: -0.01em;+}+.gallery-forge-count {+ font-size: 0.7rem;+ font-weight: 500;+ padding: 2px 7px;+ border-radius: 999px;+ background: rgba(255, 255, 255, 0.07);+ border: 1px solid rgba(255, 255, 255, 0.1);+ color: rgba(255, 255, 255, 0.5);+ font-variant-numeric: tabular-nums;}.gallery-forge-sub {font-size: 0.85rem;- color: var(--ink-dim, #888);+ color: rgba(255, 255, 255, 0.45);margin: 0;- max-width: 48ch;+ max-width: 56ch;+ line-height: 1.5;}.gallery-forge-cta {flex: none;font-size: 0.8rem;- color: var(--accent, #5b8af0);+ font-weight: 500;+ color: rgba(165, 180, 252, 0.9);text-decoration: none;white-space: nowrap;- margin-top: 0.25rem;- transition: opacity 0.15s;+ margin-top: 2px;+ transition: color 0.15s, opacity 0.15s;+ display: inline-flex;+ align-items: center;+ gap: 4px;+}+.gallery-forge-cta:hover {+ color: #fff;}-.gallery-forge-cta:hover { opacity: 0.75; }+/* Grid — matches the main gallery's column width exactly */.gallery-forge-grid {display: grid;- grid-template-columns: repeat(auto-fill, minmax(170px, 1fr));- gap: 0.75rem;+ grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));+ gap: 12px;}-/* Individual forge cards */-.forge-gallery-card {- background: var(--surface-2, #111);- border: 1px solid var(--stroke, #222);- border-radius: 10px;- overflow: hidden;- display: flex;- flex-direction: column;- cursor: pointer;- transition: border-color 0.15s, transform 0.15s;-}-.forge-gallery-card:hover {- border-color: var(--accent, #5b8af0);- transform: translateY(-2px);-}-.forge-gallery-card:focus-visible {- outline: 2px solid var(--accent, #5b8af0);- outline-offset: 2px;-}-.forge-gallery-thumb {- aspect-ratio: 1 / 1;- background: var(--surface-3, #1a1a1a);- position: relative;+/* Forge card thumb: don't override the gallery's default radial gradient bg+ for image cards; for no-image cards we set style.background inline so+ the gradient shows through regardless. */+.forge-card .gallery-card-thumb {overflow: hidden;}-.forge-gallery-thumb img {- width: 100%;- height: 100%;- object-fit: cover;- display: block;-}-.forge-gallery-thumb-placeholder {- width: 100%;- height: 100%;+/* Placeholder for cards with no preview image —+ centered cube icon with accent color on the gradient bg */+.forge-card-ph {+ width: 48px;+ height: 48px;display: flex;align-items: center;justify-content: center;- font-size: 2rem;- color: var(--ink-dim, #555);- user-select: none;+ border-radius: 12px;+ background: rgba(255, 255, 255, 0.06);+ border: 1px solid rgba(255, 255, 255, 0.1);+ color: rgba(255, 255, 255, 0.4);+ font-size: 0;+ /* override inherited .gallery-card-ph opacity */+ opacity: 1;+ filter: none;}-.forge-gallery-body {- padding: 0.6rem 0.75rem 0.5rem;- flex: 1;- display: flex;- flex-direction: column;- gap: 0.4rem;- min-width: 0;+.forge-card-ph svg {+ width: 22px;+ height: 22px;+ opacity: 0.7;}-.forge-gallery-prompt {- font-size: 0.72rem;- color: var(--ink-dim, #aaa);- overflow: hidden;- display: -webkit-box;+/* Image cards: scale on hover like regular gallery */+.forge-card:hover .gallery-card-thumb img {+ transform: scale(1.04);+}+/* Card name: 2-line clamp so longer prompts don't explode the card */+.forge-card .gallery-card-name {+ font-size: 13.5px;-webkit-line-clamp: 2;- -webkit-box-orient: vertical;line-height: 1.4;}-.forge-gallery-foot {- display: flex;- align-items: center;- justify-content: space-between;- gap: 0.4rem;- padding: 0 0.75rem 0.6rem;-}-.forge-gallery-when {- font-size: 0.62rem;- color: var(--ink-dim, #666);- font-variant-numeric: tabular-nums;-}-.forge-gallery-remix {- font-size: 0.62rem;- padding: 2px 8px;- border-radius: 999px;- border: 1px solid var(--stroke, #333);- background: transparent;- color: var(--ink-dim, #aaa);- cursor: pointer;- transition: color 0.15s, border-color 0.15s, background 0.15s;- white-space: nowrap;-}-.forge-gallery-remix:hover {- color: var(--ink, #f0f0f0);- border-color: var(--accent, #5b8af0);- background: var(--accent-soft, rgba(91,138,240,0.12));+/* Tags: slightly smaller than avatar tags */+.forge-card .gallery-card-tag {+ font-size: 10px;+ padding: 2px 7px;}-/* Skeleton cards for loading state */-.forge-gallery-card--skel .forge-gallery-thumb {- animation: forge-skel-pulse 1.4s ease-in-out infinite;-}-.forge-gallery-card--skel .forge-gallery-prompt,-.forge-gallery-card--skel .forge-gallery-when {- background: var(--surface-3, #1a1a1a);- border-radius: 4px;- color: transparent;- animation: forge-skel-pulse 1.4s ease-in-out infinite;+@media (max-width: 744px) {+ .gallery-forge-grid {+ grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));+ }}-@keyframes forge-skel-pulse {- 0%, 100% { opacity: 0.5; }- 50% { opacity: 1; }+@media (max-width: 640px) {+ .gallery-forge-head {+ flex-direction: column;+ gap: 0.5rem;+ }+ .gallery-forge-cta {+ margin-top: 0;+ }+ .gallery-forge-grid {+ grid-template-columns: repeat(2, 1fr);+ }}diff --git a/public/gallery/gallery.js b/public/gallery/gallery.jsindex e48381127..b4f1f0cdc 100644--- a/public/gallery/gallery.js+++ b/public/gallery/gallery.js@@ -312,13 +312,10 @@ function renderCard(a) {const studioUrl = `/studio?avatar=${encodeURIComponent(a.id)}`;const thumbSrc = a.thumbnail_url || `/api/avatars/${encodeURIComponent(a.id)}/og`;- // Prefer the vision-generated accessibility description; fall back to the name- // when alt text hasn't been generated/backfilled yet (T4.1).const altText = a.alt_text || a.name || 'Avatar';const views = a.view_count != null ? Number(a.view_count) : 0;const created = formatRelative(a.created_at);- // Use model-viewer for 3D inline preview if GLB is available, else static thumbnailconst thumbContent = glbUrl? `<model-viewersrc="${escapeAttr(glbUrl)}"@@ -347,10 +344,6 @@ function renderCard(a) {const viewsLabel = views >= 1 ? `${formatCompact(views)} view${views === 1 ? '' : 's'}` : '';- // Same "deployed on-chain" badge used across the platform. gallery.js is a- // static public asset (not bundled), so the shared module is reached via the- // global set by /src/shared/onchain-badge.js loaded in index.html; degrades- // to no badge if unavailable. Only avatars backing an on-chain agent show it.const onchainBadge = window.twsOnchainBadge?.onchainBadgeHTML? window.twsOnchainBadge.onchainBadgeHTML(a, { link: false, showChain: true, size: 'sm' }): '';@@ -416,7 +409,7 @@ function escapeAttr(s) {return escapeHtml(s).replace(/'/g, ''');}-// ─── Embed modal ──────────────────────────────────────────────────────────+// Embed modalconst LIB_CDN_URL = 'https://three.ws/agent-3d/latest/agent-3d.js';function openAvatarEmbedModal({ avatarId, glbUrl, name }) {@@ -531,15 +524,27 @@ function openAvatarEmbedModal({ avatarId, glbUrl, name }) {resetAndLoad();-// ─── From the Forge section ────────────────────────────────────────────────-// Loads community forge models from /api/forge-gallery?scope=community and-// renders them below the avatar grid as a separate "From the Forge" strip.+// =============================================================================+// From the Forge — community 3D models auto-saved when users generate on /forge+// Cards use the same gallery-card design system for visual consistency.+// =============================================================================const forgeEls = {section: document.getElementById('forge-section'),grid: document.getElementById('forge-grid'),+ count: document.getElementById('forge-count'),};+// Deterministic gradient from prompt text — same string always same colors,+// so placeholders aren't a uniform dark void.+function forgePromptGradient(str) {+ let h = 0;+ for (let i = 0; i < (str || '').length; i++) h = (Math.imul(31, h) + str.charCodeAt(i)) | 0;+ const hue = Math.abs(h) % 360;+ const hue2 = (hue + 50) % 360;+ return `linear-gradient(135deg, hsl(${hue},30%,13%) 0%, hsl(${hue2},22%,8%) 100%)`;+}+function forgeTimeAgo(iso) {const t = Date.parse(iso);if (!Number.isFinite(t)) return '';@@ -555,97 +560,163 @@ function forgeTimeAgo(iso) {return `${Math.floor(d / 30)}mo ago`;}+const FORGE_ENGINE_LABELS = {+ nvidia: 'Free',+ trellis: 'Trellis',+ meshy: 'Meshy',+ tripo: 'Tripo',+ hunyuan3d: 'Hunyuan3D',+ triposg: 'TripoSG',+};+function renderForgeCard(c) {+ const label = c.prompt || 'Forged model';+ const openUrl = c.id+ ? `/forge?share=${encodeURIComponent(c.id)}`+ : c.glb_url+ ? `/app#model=${encodeURIComponent(c.glb_url)}`+ : '/forge';+const card = document.createElement('div');- card.className = 'forge-gallery-card';+ card.className = 'gallery-card forge-card';card.tabIndex = 0;card.setAttribute('role', 'button');- const label = c.prompt || 'Forged model';card.setAttribute('aria-label', `Open in Forge: ${escapeAttr(label)}`);+ // Thumbnail — real image when available, deterministic gradient otherwiseconst thumb = document.createElement('div');- thumb.className = 'forge-gallery-thumb';+ thumb.className = 'gallery-card-thumb forge-card-thumb';+if (c.preview_image_url) {const img = document.createElement('img');img.src = c.preview_image_url;img.alt = '';img.loading = 'lazy';+ img.decoding = 'async';thumb.appendChild(img);} else {- const ph = document.createElement('div');- ph.className = 'forge-gallery-thumb-placeholder';- ph.setAttribute('aria-hidden', 'true');- ph.textContent = '◳';- thumb.appendChild(ph);+ // Gradient placeholder — visually distinctive, not a void+ thumb.style.background = forgePromptGradient(label);+ const glyph = document.createElement('span');+ glyph.className = 'gallery-card-ph forge-card-ph';+ glyph.setAttribute('aria-hidden', 'true');+ // Use the first meaningful word of the prompt as a visual hint+ const firstWord = label.replace(/^(a|an|the)\s+/i, '').split(/\s+/)[0] || '';+ glyph.textContent = firstWord.length > 0 && firstWord.length <= 12 ? firstWord : '◳';+ thumb.appendChild(glyph);}++ // 3D badge — consistent with the avatar cards+ const pill = document.createElement('span');+ pill.className = 'gallery-card-3dpill';+ pill.textContent = '3D';+ thumb.appendChild(pill);++ // Hover play icon+ const play = document.createElement('div');+ play.className = 'gallery-card-play';+ play.setAttribute('aria-hidden', 'true');+ play.innerHTML = `<svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M8 5.14v14l11-7-11-7Z"/></svg>`;+ thumb.appendChild(play);+card.appendChild(thumb);+ // Bodyconst body = document.createElement('div');- body.className = 'forge-gallery-body';- const prompt = document.createElement('p');- prompt.className = 'forge-gallery-prompt';- prompt.textContent = label;- body.appendChild(prompt);- card.appendChild(body);+ body.className = 'gallery-card-body';++ const name = document.createElement('h3');+ name.className = 'gallery-card-name';+ name.title = label;+ // Limit display to keep cards compact — full prompt in title attr+ name.textContent = label.length > 60 ? label.slice(0, 57) + '…' : label;+ body.appendChild(name);++ // Engine/tier tags when available+ const tagsRow = document.createElement('div');+ tagsRow.className = 'gallery-card-tags';+ const tierStr = c.tier ? c.tier.charAt(0).toUpperCase() + c.tier.slice(1) : null;+ const backendStr = c.backend && c.backend !== 'trellis' ? FORGE_ENGINE_LABELS[c.backend] || c.backend : null;+ if (tierStr) {+ const t = document.createElement('span');+ t.className = 'gallery-card-tag';+ t.textContent = tierStr;+ tagsRow.appendChild(t);+ }+ if (backendStr) {+ const b = document.createElement('span');+ b.className = 'gallery-card-tag';+ b.textContent = backendStr;+ tagsRow.appendChild(b);+ }+ if (tagsRow.children.length) body.appendChild(tagsRow);+ // Footerconst foot = document.createElement('div');- foot.className = 'forge-gallery-foot';- const when = document.createElement('span');- when.className = 'forge-gallery-when';- when.textContent = forgeTimeAgo(c.created_at);- foot.appendChild(when);+ foot.className = 'gallery-card-foot';++ const meta = document.createElement('span');+ meta.className = 'gallery-card-meta';+ meta.textContent = forgeTimeAgo(c.created_at);+ foot.appendChild(meta);++ const actions = document.createElement('div');+ actions.className = 'gallery-card-actions';if (c.prompt) {const remixBtn = document.createElement('button');remixBtn.type = 'button';- remixBtn.className = 'forge-gallery-remix';+ remixBtn.className = 'gallery-card-btn gallery-card-btn--ghost';remixBtn.textContent = 'Remix';- remixBtn.title = 'Open in the Forge with this prompt pre-loaded';+ remixBtn.title = 'Open in Forge with this prompt pre-loaded';remixBtn.addEventListener('click', (e) => {e.stopPropagation();window.location.href = `/forge?prompt=${encodeURIComponent(c.prompt)}`;});- foot.appendChild(remixBtn);+ actions.appendChild(remixBtn);}- card.appendChild(foot);- const openForge = () => {- if (c.id) {- window.location.href = `/forge?share=${encodeURIComponent(c.id)}`;- } else if (c.glb_url) {- window.location.href = `/app#model=${encodeURIComponent(c.glb_url)}`;- }- };- card.addEventListener('click', openForge);+ const openBtn = document.createElement('a');+ openBtn.className = 'gallery-card-btn';+ openBtn.href = openUrl;+ openBtn.textContent = 'Open';+ openBtn.setAttribute('aria-label', `Open "${label}" in Forge`);+ openBtn.addEventListener('click', (e) => e.stopPropagation());+ actions.appendChild(openBtn);++ foot.appendChild(actions);+ body.appendChild(foot);+ card.appendChild(body);++ card.addEventListener('click', (e) => {+ if (e.target.closest('button, a')) return;+ window.location.href = openUrl;+ });card.addEventListener('keydown', (e) => {- if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); openForge(); }+ if (e.key === 'Enter' || e.key === ' ') {+ e.preventDefault();+ window.location.href = openUrl;+ }});return card;}function renderForgeSkeleton(n) {+ const frag = document.createDocumentFragment();for (let i = 0; i < n; i++) {const card = document.createElement('div');- card.className = 'forge-gallery-card forge-gallery-card--skel';- const thumb = document.createElement('div');- thumb.className = 'forge-gallery-thumb';- card.appendChild(thumb);- const body = document.createElement('div');- body.className = 'forge-gallery-body';- const p = document.createElement('p');- p.className = 'forge-gallery-prompt';- p.textContent = ' ';- body.appendChild(p);- card.appendChild(body);- const foot = document.createElement('div');- foot.className = 'forge-gallery-foot';- const w = document.createElement('span');- w.className = 'forge-gallery-when';- w.textContent = ' ';- foot.appendChild(w);- card.appendChild(foot);- forgeEls.grid.appendChild(card);+ card.className = 'gallery-card gallery-card--skel forge-card';+ card.innerHTML = `+ <div class="gallery-card-thumb"></div>+ <div class="gallery-card-body">+ <div class="gallery-card-name"> </div>+ <div class="gallery-card-desc"> </div>+ <div class="gallery-card-tags"> </div>+ </div>+ `;+ frag.appendChild(card);}+ forgeEls.grid.appendChild(frag);}async function loadForgeSection() {@@ -656,11 +727,28 @@ async function loadForgeSection() {if (!res.ok) return;const data = await res.json().catch(() => ({}));forgeEls.grid.innerHTML = '';- const creations = Array.isArray(data?.creations) ? data.creations : [];+ const all = Array.isArray(data?.creations) ? data.creations : [];++ // Dedupe by normalized prompt — no gallery of six identical teapots+ const seen = new Set();+ const creations = all.filter((c) => {+ const key = (c.prompt || c.id || '').toLowerCase().replace(/\s+/g, ' ').trim();+ if (seen.has(key)) return false;+ seen.add(key);+ return true;+ });+if (!data?.enabled || creations.length === 0) return;+for (const c of creations) forgeEls.grid.appendChild(renderForgeCard(c));++ if (forgeEls.count) {+ forgeEls.count.textContent = `${creations.length} recent`;+ }+forgeEls.section.hidden = false;} catch {+ // Silently suppress — forge section is additive, never blocks the galleryforgeEls.grid.innerHTML = '';}}diff --git a/public/gallery/index.html b/public/gallery/index.htmlindex 6915a3636..bf8ed4021 100644--- a/public/gallery/index.html+++ b/public/gallery/index.html@@ -144,16 +144,25 @@</div></section>- <!-- From the Forge — auto-saved community 3D models from /forge -->+ <!-- From the Forge — community 3D models auto-saved from /forge --><section class="gallery-forge-section" id="forge-section" hidden><div class="gallery-forge-head"><div>- <h2 class="gallery-forge-title">From the Forge</h2>- <p class="gallery-forge-sub">- 3D models auto-saved as the community generates them. Click to open in the viewer, or Remix the prompt.- </p>+ <div class="gallery-forge-title-row">+ <svg class="gallery-forge-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">+ <path d="M12 2 3 7v10l9 5 9-5V7l-9-5Z"/>+ <path d="m3 7 9 5 9-5"/>+ <line x1="12" y1="12" x2="12" y2="22"/>+ </svg>+ <h2 class="gallery-forge-title">From the Forge</h2>+ <span class="gallery-forge-count" id="forge-count"></span>+ </div>+ <p class="gallery-forge-sub">3D models auto-saved as the community generates them. Remix any prompt to start from something that works.</p></div>- <a href="/forge" class="gallery-forge-cta">Create your own →</a>+ <a href="/forge" class="gallery-forge-cta">+ Generate your own+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 12h14"/><path d="m12 5 7 7-7 7"/></svg>+ </a></div><div class="gallery-forge-grid" id="forge-grid"></div></section>diff --git a/src/forge-showcase.js b/src/forge-showcase.jsindex 5f1587562..ebfc5bb9f 100644--- a/src/forge-showcase.js+++ b/src/forge-showcase.js@@ -338,10 +338,14 @@ function showRemixToast() {if (existing) existing.remove();const toast = document.createElement('div');toast.className = 'remix-toast';- toast.textContent = 'Prompt loaded — edit and Generate';+ const dot = document.createElement('span');+ dot.className = 'toast-dot';+ dot.setAttribute('aria-hidden', 'true');+ toast.appendChild(dot);+ toast.appendChild(document.createTextNode('Prompt loaded — edit and Generate'));document.body.appendChild(toast);- setTimeout(() => toast.classList.add('fade-out'), 2200);- setTimeout(() => toast.remove(), 2700);+ setTimeout(() => toast.classList.add('fade-out'), 2400);+ setTimeout(() => toast.remove(), 2800);}async function loadShowcase() {diff --git a/src/selfie-pipeline.js b/src/selfie-pipeline.jsindex ccf5705a6..4c137f78b 100644--- a/src/selfie-pipeline.js+++ b/src/selfie-pipeline.js@@ -26,6 +26,37 @@ const POLL_INTERVAL_MS = 3000;const POLL_TIMEOUT_MS = 8 * 60 * 1000;const RATE_LIMIT_COOLDOWN_MS = 60_000;+// BYOK key session storage keys — readable by the page to pre-populate the+// key entry form and by the pipeline to attach the key to submit requests.+const BYOK_KEY_STORAGE = 'selfie:byok:key';+const BYOK_PROVIDER_STORAGE = 'selfie:byok:provider';++/** Read the BYOK credentials stored for this session, if any. */+export function getStoredByokKey() {+ try {+ const key = sessionStorage.getItem(BYOK_KEY_STORAGE);+ const provider = sessionStorage.getItem(BYOK_PROVIDER_STORAGE);+ if (key && provider) return { key, provider };+ } catch (_) {}+ return null;+}++/** Persist BYOK credentials to the session. */+export function storeByokKey(provider, key) {+ try {+ sessionStorage.setItem(BYOK_PROVIDER_STORAGE, provider);+ sessionStorage.setItem(BYOK_KEY_STORAGE, key);+ } catch (_) {}+}++/** Clear any stored BYOK credentials (e.g. after an invalid-key error). */+export function clearStoredByokKey() {+ try {+ sessionStorage.removeItem(BYOK_KEY_STORAGE);+ sessionStorage.removeItem(BYOK_PROVIDER_STORAGE);+ } catch (_) {}+}+let _building = false;let _lastSlotsSent = /** @type {string[]} */ ([]);let _jobStartTime = 0;@@ -40,6 +71,13 @@ document.addEventListener('selfie:submit', (event) => {window.location.assign(err.redirect);return;}+ // No platform backend + no BYOK key: surface the key-entry form.+ if (err?.needsByok) {+ document.dispatchEvent(new CustomEvent('selfie:needs-byok', {+ detail: { providers: err.providers || ['meshy', 'tripo'] },+ }));+ return;+ }if (_building) {document.dispatchEvent(new CustomEvent('selfie:build-error', {detail: {@@ -143,20 +181,31 @@ async function run(detail) {}));setStatus('Submitting to avatar engine...');+ const byok = getStoredByokKey();+ const submitBody = {+ name: defaultAvatarName(),+ photos,+ visibility: 'private',+ params: { bodyType: detail.bodyType, style: detail.avatarType },+ ...(byok ? { provider_key: byok.key, provider_name: byok.provider } : {}),+ };const submitRes = await fetch(SUBMIT_ENDPOINT, {method: 'POST',credentials: 'include',headers: { 'content-type': 'application/json' },- body: JSON.stringify({- name: defaultAvatarName(),- photos,- visibility: 'private',- params: { bodyType: detail.bodyType, style: detail.avatarType },- }),+ body: JSON.stringify(submitBody),});if (!submitRes.ok) {const payload = await submitRes.json().catch(() => ({}));+ // The platform has no backend and the user has no stored BYOK key.+ // Dispatch a dedicated event so the page can show the key entry form.+ if (payload.code === 'regen_needs_byok') {+ const e = new Error('regen_needs_byok');+ /** @type {any} */ (e).needsByok = true;+ /** @type {any} */ (e).providers = payload.providers || ['meshy', 'tripo'];+ throw e;+ }throw mapApiError(submitRes.status, payload);}@@ -439,6 +488,18 @@ function mapApiError(status, payload) {/** @type {any} */ (e).rateLimited = true;return e;}+ if (status === 401 && (code === 'invalid_key' || code === 'missing_key')) {+ clearStoredByokKey();+ return withMessage(+ new Error(code),+ 'Your API key was rejected. Check the key and try again.',+ );+ }+ if (status === 402 && code === 'insufficient_credits')+ return withMessage(+ new Error(code),+ 'Your API key is out of credits. Top up your account and try again.',+ );if (status === 501)return withMessage(new Error(code || 'not_configured'),