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
Add unit tests for decodeWorkerEnvelope function in forge-finalize.js
nirholas126cf7298457
diff --git a/api/_lib/email.js b/api/_lib/email.jsindex ae368e75b..3d059cdd9 100644--- a/api/_lib/email.js+++ b/api/_lib/email.js@@ -142,6 +142,34 @@ export function sendReferralCommissionEmail({ to, amount, currency, fromHandle,return sendEmail({ to, ...renderReferralCommission({ amount, currency, fromHandle, skillName, date }) });}+// Unattended forge completion: sent only by the server-side finalizer when a+// generation finished after the creator left the page. `creationPath` is the+// site-relative share path (/forge?share=<id>).+export function renderForgeComplete({ prompt, creationPath, previewImageUrl }) {+ const url = `${APP_URL}${creationPath}`;+ const subjectPrompt = prompt ? `"${prompt.length > 60 ? `${prompt.slice(0, 57)}…` : prompt}"` : 'your model';+ const preview = previewImageUrl+ ? `<img src="${esc(previewImageUrl)}" alt="Model preview" style="width:100%;max-width:456px;border-radius:12px;border:1px solid #2a2a36;margin:0 0 16px" />`+ : '';+ return {+ subject: `Your 3D model is ready: ${subjectPrompt}`,+ html: layout('Your 3D model is ready', `+ <p class="brand">three.ws</p>+ <h1>Your 3D model is ready</h1>+ ${prompt ? `<p>Your generation ${esc(subjectPrompt)} finished while you were away. It's saved to your gallery and ready to view, share, or refine.</p>` : `<p>Your 3D generation finished while you were away. It's saved to your gallery and ready to view, share, or refine.</p>`}+ ${preview}+ <a class="btn" href="${esc(url)}">View your model</a>+ <hr>+ <p class="muted">You're getting this because a generation you started on three.ws finished after you left the page. Turn these off any time in your <a href="${APP_URL}/dashboard/" style="color:#6a5cff">notification preferences</a>.</p>+ `),+ text: `Your 3D model is ready\n\n${prompt ? `Your generation ${subjectPrompt} finished while you were away.` : 'Your 3D generation finished while you were away.'} It's saved to your gallery.\n\nView it: ${url}\n\nManage notifications: ${APP_URL}/dashboard/`,+ };+}++export function sendForgeCompleteEmail({ to, prompt, creationPath, previewImageUrl }) {+ return sendEmail({ to, ...renderForgeComplete({ prompt, creationPath, previewImageUrl }) });+}+// Double opt-in newsletter confirmation. Minimal localization (prompt 38) so a// subscriber confirms in their own language; unknown locales fall back to en.const NEWSLETTER_I18N = {diff --git a/api/_lib/forge-notify.js b/api/_lib/forge-notify.jsnew file mode 100644index 000000000..c4623f01e--- /dev/null+++ b/api/_lib/forge-notify.js@@ -0,0 +1,63 @@+// Unattended-completion notifications for forge generations.+//+// Called ONLY from the server-side finalizer (api/cron/forge-finalize.js) -+// i.e. exactly when a generation finished while the creator was away from the+// page. The attended browser-poll path never notifies: the result is already+// on screen, and a push/email about it would be noise.+//+// Channels ride the standard preference-gated fan-out: insertNotification+// handles the bell inbox + Web Push; email goes out here when the user's+// 'creations' category has email enabled (the default: an unattended finish+// is precisely the moment email earns its keep). All best-effort: a delivery+// failure never touches the creation row.++import { sql } from './db.js';+import { insertNotification, emailAllowedForType } from './notify.js';+import { sendForgeCompleteEmail } from './email.js';++// Real, sendable email for a user. Skips missing addresses and the synthetic+// `…@privy.local` placeholders minted for wallet-only Privy accounts.+async function deliverableEmail(userId) {+ if (!userId) return null;+ try {+ const [row] = await sql`select email from users where id = ${userId} and deleted_at is null`;+ const email = row?.email;+ if (!email || /@privy\.local$/i.test(email)) return null;+ return email;+ } catch {+ return null;+ }+}++export function notifyForgeComplete({ userId, creationId, prompt, previewImageUrl }) {+ return deliverComplete({ userId, creationId, prompt, previewImageUrl }).catch((err) => {+ console.error('[forge-notify] complete delivery failed:', err?.message);+ });+}++async function deliverComplete({ userId, creationId, prompt, previewImageUrl }) {+ if (!userId || !creationId) return;+ const link = `/forge?share=${encodeURIComponent(creationId)}`;+ await insertNotification(userId, 'forge_complete', {+ prompt: prompt || null,+ creation_id: creationId,+ preview_image_url: previewImageUrl || null,+ link,+ });+ if (await emailAllowedForType(userId, 'forge_complete')) {+ const to = await deliverableEmail(userId);+ if (to) {+ sendForgeCompleteEmail({ to, prompt, creationPath: link, previewImageUrl }).catch(() => {});+ }+ }+}++export function notifyForgeFailed({ userId, prompt, error }) {+ if (!userId) return Promise.resolve();+ // Bell + push only: a failure email for a free generation would be noise.+ return insertNotification(userId, 'forge_failed', {+ prompt: prompt || null,+ error: error ? String(error).slice(0, 200) : null,+ link: '/forge',+ });+}diff --git a/api/_lib/notify-prefs.js b/api/_lib/notify-prefs.jsindex f0c333ba9..de36588e2 100644--- a/api/_lib/notify-prefs.js+++ b/api/_lib/notify-prefs.js@@ -41,6 +41,11 @@ export const CATEGORIES = [label: 'Market alerts',description: 'Pump.fun rules and token signals you configured.',},+ {+ key: 'creations',+ label: 'Creations',+ description: 'A 3D generation you started finished (or failed) while you were away.',+ },{key: 'account',label: 'Account & security',@@ -84,6 +89,9 @@ const TYPE_CATEGORY = {pump_alert: 'alerts',+ forge_complete: 'creations',+ forge_failed: 'creations',+withdrawal_completed: 'account',withdrawal_failed: 'account',payment_mismatch: 'account',@@ -109,6 +117,10 @@ const DEFAULTS = {social: { in_app: true, push: true, email: false, telegram: false },irl: { in_app: true, push: true, email: false, telegram: false },alerts: { in_app: true, push: true, email: false, telegram: true },+ // Only unattended completions notify (api/cron/forge-finalize.js), so email+ // defaulting on is the feature, not spam: the user left the page and asked+ // to hear back.+ creations: { in_app: true, push: true, email: true, telegram: false },account: { in_app: true, push: true, email: true, telegram: false },};@@ -210,6 +222,8 @@ const PUSH_COPY = {irl_interaction: (p) => ['Met in person 📍', p.message ? `“${p.message}”` : 'Someone interacted with your agent in person'],irl_reply: (p) => ['Agent replied 💬', p.message ? `“${p.message}”` : 'An agent replied to your message'],pump_alert: (p) => ['Market alert 📈', p.summary || 'A token alert you configured just fired'],+ forge_complete: (p) => ['Your 3D model is ready ✨', p.prompt ? `"${String(p.prompt).slice(0, 80)}" finished generating` : 'Your generation finished. Tap to view it'],+ forge_failed: (p) => ['Generation failed ⚠️', p.prompt ? `"${String(p.prompt).slice(0, 80)}" could not be generated. Tap to retry` : 'A generation could not be completed. Tap to retry'],withdrawal_completed: () => ['Withdrawal complete ✅', 'Your withdrawal has been sent'],withdrawal_failed: () => ['Withdrawal failed ⚠️', 'A withdrawal could not be completed — tap to review'],payment_mismatch: () => ['Payment mismatch ⚠️', 'Check your agent payment settings'],diff --git a/api/cron/forge-finalize.js b/api/cron/forge-finalize.jsnew file mode 100644index 000000000..35a953551--- /dev/null+++ b/api/cron/forge-finalize.js@@ -0,0 +1,176 @@+// GET /api/cron/forge-finalize: server-side completion for forge generations.+//+// Historically a forge_creations row only flipped from 'generating' to+// 'done'/'failed' when the creator's browser polled GET /api/forge?job=… to+// completion (materializeCreation runs inside that poll). Close the tab and the+// generation is orphaned at 'generating' forever, even though the GPU worker+// finished and the GLB is sitting in GCS. This cron makes completion+// server-authoritative so users can leave the page mid-generation:+//+// 1. Sweep 'generating' rows older than GRACE (the browser poll path gets+// first shot: most generations still finish attended).+// 2. Rows whose replicate_job_id is a GCP worker envelope (the async+// self-host lanes: trellis_selfhost, hunyuan3d, sketch/triposg: exactly+// the minutes-long lanes that get orphaned) are polled directly on the+// worker. done → materializeCreation (same durable-copy writer the+// browser poll uses, so gallery/showcase/streaks all light up+// identically). failed → markFailed.+// 3. Anything still not terminal after HARD_TTL is marked failed as timed+// out, so no row is ever stuck at 'generating' forever. Envelope rows are+// still polled once first: recovering a finished model always beats+// declaring it dead.+// 4. A creation finalized here completed UNATTENDED: the user wasn't+// watching: so this is the one place completion notifications fire+// (bell + push + email via api/_lib/forge-notify). The attended path+// never notifies: the result is already on screen.+//+// Idempotent + swarm-safe: materializeCreation short-circuits on already-done+// rows, markFailed is guarded by status != 'done', and the batch is bounded so+// overlapping ticks just split the work.+//+// Auth: CRON_SECRET header, same pattern as every other cron in /api/cron/.++import { sql } from '../_lib/db.js';+import { cors, json, wrapCron } from '../_lib/http.js';+import { constantTimeEquals } from '../_lib/crypto.js';+import { materializeCreation, markFailed, forgeStoreEnabled } from '../_lib/forge-store.js';+import { notifyForgeComplete, notifyForgeFailed } from '../_lib/forge-notify.js';+import { createRegenProvider as createGcpProvider } from '../_providers/gcp.js';++export const maxDuration = 60;++const BATCH_LIMIT = Number(process.env.FORGE_FINALIZE_BATCH) || 25;+// Leave fresh rows to the attended browser poll path.+const GRACE_MINUTES = 2;+// Past this age a non-terminal generation is declared dead. The slowest real+// lane (self-host TRELLIS high tier behind a full queue) finishes well inside+// 30 minutes; beyond it the worker task has been evicted or lost.+const HARD_TTL_MINUTES = 45;++function requireCron(req, res) {+ const secret = process.env.CRON_SECRET;+ if (!secret) return false; // allow in dev if no secret set+ const provided = req.headers['x-cron-secret'] || req.headers['authorization']?.replace(/^Bearer\s+/i, '');+ if (!provided || !constantTimeEquals(provided, secret)) {+ res.writeHead(401, { 'content-type': 'application/json' });+ res.end(JSON.stringify({ error: 'unauthorized' }));+ return true; // handled+ }+ return false;+}++// The async GCP worker lanes wrap their upstream task in a base64url JSON+// envelope ({ mode, taskId, baseUrl, resultKey }): see api/_providers/gcp.js.+// That shape is the reliable discriminator between "a worker we can poll" and+// an opaque third-party id (Replicate prediction, HF job) we cannot.+export function decodeWorkerEnvelope(replicateJobId) {+ try {+ const obj = JSON.parse(Buffer.from(String(replicateJobId), 'base64url').toString('utf8'));+ return obj?.taskId && obj?.baseUrl ? obj : null;+ } catch {+ return null;+ }+}++export default wrapCron(async (req, res) => {+ cors(req, res, { methods: 'GET,POST,OPTIONS' });+ if (req.method?.toUpperCase() === 'OPTIONS') return;+ if (requireCron(req, res)) return;+ if (!forgeStoreEnabled()) {+ return json(res, 200, { enabled: false, swept: 0 });+ }++ const t0 = Date.now();++ const rows = await sql`+ select id, replicate_job_id, client_key, user_id, prompt, preview_image_url,+ backend, tier, created_at+ from forge_creations+ where status = 'generating'+ and replicate_job_id is not null+ and created_at < now() - (${GRACE_MINUTES} * interval '1 minute')+ order by created_at asc+ limit ${BATCH_LIMIT}+ `;++ let gcp = null;+ try {+ gcp = createGcpProvider();+ } catch {+ // No GCP_RECONSTRUCTION_KEY on this deployment: envelope rows can't be+ // polled here; the hard TTL below still reaps them.+ }++ const out = { done: 0, failed: 0, timed_out: 0, still_running: 0, unpollable: 0 };++ for (const row of rows) {+ const ageMinutes = (Date.now() - Date.parse(row.created_at)) / 60_000;+ const envelope = decodeWorkerEnvelope(row.replicate_job_id);++ if (envelope && gcp) {+ const status = await gcp.status(row.replicate_job_id).catch(() => null);++ if (status?.status === 'done' && status.resultGlbUrl) {+ const durable = await materializeCreation({+ replicateJobId: row.replicate_job_id,+ clientKey: row.client_key,+ glbUrl: status.resultGlbUrl,+ });+ if (durable) {+ out.done++;+ if (row.user_id) {+ notifyForgeComplete({+ userId: row.user_id,+ creationId: durable.id,+ prompt: row.prompt,+ previewImageUrl: durable.previewImageUrl ?? row.preview_image_url ?? null,+ });+ }+ continue;+ }+ // Copy-to-durable failed (transient storage/network): leave the row+ // for the next tick rather than failing a finished model.+ out.still_running++;+ continue;+ }++ if (status?.status === 'failed') {+ await markFailed({+ replicateJobId: row.replicate_job_id,+ clientKey: row.client_key,+ error: status.error || 'generation failed',+ });+ out.failed++;+ if (row.user_id) {+ notifyForgeFailed({ userId: row.user_id, prompt: row.prompt, error: status.error });+ }+ continue;+ }++ // queued / running / poll blip: fall through to the TTL check.+ } else if (!envelope) {+ out.unpollable++;+ }++ if (ageMinutes > HARD_TTL_MINUTES) {+ await markFailed({+ replicateJobId: row.replicate_job_id,+ clientKey: row.client_key,+ error: `generation timed out after ${Math.round(ageMinutes)} minutes`,+ });+ out.timed_out++;+ if (row.user_id) {+ notifyForgeFailed({ userId: row.user_id, prompt: row.prompt, error: 'generation timed out' });+ }+ } else if (envelope) {+ out.still_running++;+ }+ }++ return json(res, 200, {+ enabled: true,+ swept: rows.length,+ ...out,+ elapsed_ms: Date.now() - t0,+ });+});diff --git a/docs/tutorials/connect-ai-brain.md b/docs/tutorials/connect-ai-brain.mdindex 30280d425..d468adef5 100644--- a/docs/tutorials/connect-ai-brain.md+++ b/docs/tutorials/connect-ai-brain.md@@ -1,4 +1,4 @@-# Connect Anthropic or OpenAI as the brain+# Connect Anthropic, OpenAI, or xAI (Grok) as the brainThe agent's body is the avatar. The agent's voice is the TTS. The agent's *brain* is whatever LLM is generating its replies. By default the platform routes through a managed Claude endpoint, which works out of the box but bills against your free tier. The moment you want real production traffic, full control over which model runs, or your own usage observability, you bring your own API key.@@ -11,7 +11,7 @@ This tutorial covers the whole brain layer. Where the LLM call actually happens- A streaming-enabled brain so replies feel responsive- An observability dashboard you can use to monitor spend per agent-**Prerequisites:** You have an agent at [three.ws/my-agents](https://three.ws/my-agents). You have an API key from Anthropic ([console.anthropic.com](https://console.anthropic.com)) or OpenAI ([platform.openai.com](https://platform.openai.com)). Familiarity with the concept of system prompts (see [agent personality](/tutorials/agent-personality)).+**Prerequisites:** You have an agent at [three.ws/my-agents](https://three.ws/my-agents). You have an API key from Anthropic ([console.anthropic.com](https://console.anthropic.com)), OpenAI ([platform.openai.com](https://platform.openai.com)), or xAI ([console.x.ai](https://console.x.ai)). Familiarity with the concept of system prompts (see [agent personality](/tutorials/agent-personality)).---@@ -58,7 +58,15 @@ For OpenAI:4. In three.ws My Agents, **API Keys → OpenAI → Add key.**5. Paste, save.-You can store both keys at once and route different agents to different providers.+For xAI (Grok):++1. Open [console.x.ai](https://console.x.ai).+2. **API Keys → Create API key.** Label it.+3. Copy (starts with `xai-`).+4. In three.ws My Agents, **API Keys → Grok (xAI) → Add key.**+5. Paste, save.++You can store all three keys at once and route different agents to different providers.After saving, the keys are stored encrypted at rest. The dashboard shows the last four characters and a creation timestamp; the full key is never displayed back. If you suspect a leak, rotate the key on the provider side and replace it in the dashboard — the platform invalidates the old one immediately.@@ -126,6 +134,19 @@ The platform also carries the wider OpenAI lineup: GPT-5.5 and GPT-5.5 Pro, theLegacy ids keep working: `gpt-4o`, `gpt-4o-mini`, and `o3-mini` are accepted as aliases and resolve to `gpt-5.6-sol`, `gpt-5.6-luna`, and `o3` (the GPT-4o family was deprecated upstream in July 2026), so existing agents upgrade in place with no config change.+### xAI (Grok) models++**Grok 4.5** (`grok-4.5`) is the xAI flagship.++- **Cost:** $2 per million input, $6 per million output. Cheaper than Sonnet per token.+- **Latency:** First token in roughly a second.+- **Capability:** Frontier reasoning with strong real-time knowledge of X. Tool use is reliable. A good pick for agents that discuss current events or social sentiment.+- **Context window:** 500K tokens.++**Grok 4.3** (`grok-4.3`) is the long-context option ($1.25 in / $2.50 out, 1M-token window). Reach for it when the agent carries very large system prompts or memory.++**Grok 4.1 Fast** (`grok-4.1-fast`) is the budget workhorse ($0.20 in / $0.50 out, 2M-token window). Comparable to Haiku for short interactions and dramatically cheaper.+### Picking a modelA practical rule of thumb:diff --git a/marketing/quicknode/quicknode-announcement-dark.png b/marketing/quicknode/quicknode-announcement-dark.pngnew file mode 100644index 000000000..682af31e3Binary files /dev/null and b/marketing/quicknode/quicknode-announcement-dark.png differdiff --git a/marketing/quicknode/quicknode-announcement-light.png b/marketing/quicknode/quicknode-announcement-light.pngnew file mode 100644index 000000000..d13f7c83cBinary files /dev/null and b/marketing/quicknode/quicknode-announcement-light.png differdiff --git a/packages/brain-mcp/README.md b/packages/brain-mcp/README.mdindex 0364e1351..140157250 100644--- a/packages/brain-mcp/README.md+++ b/packages/brain-mcp/README.md@@ -16,7 +16,7 @@----> A [Model Context Protocol](https://modelcontextprotocol.io) server that gives any AI assistant the three.ws **multi-provider LLM router** over stdio. Discover which models are available — Claude, the GPT-5.6 family, o3, Qwen, DeepSeek, NVIDIA Nemotron, IBM Granite, and more — and run a chat completion through whichever one fits, without wiring each vendor SDK yourself.+> A [Model Context Protocol](https://modelcontextprotocol.io) server that gives any AI assistant the three.ws **multi-provider LLM router** over stdio. Discover which models are available — Claude, the GPT-5.6 family, o3, Grok, Qwen, DeepSeek, NVIDIA Nemotron, IBM Granite, and more — and run a chat completion through whichever one fits, without wiring each vendor SDK yourself.The router fronts every provider behind one endpoint and transparently falls back across mirrors and free tiers if the chosen model is briefly down. The free open-weight tiers (GPT-OSS 120B, NVIDIA NIM models) work with **no key**; the paid first-party flagships unlock with a three.ws API key.diff --git a/pages/forge.html b/pages/forge.htmlindex 534a29480..b9ce18323 100644--- a/pages/forge.html+++ b/pages/forge.html@@ -1382,6 +1382,15 @@color: var(--ink);font-weight: 600;}+ /* Leave-the-page reassurance: the generation is server-tracked, so the+ user is free to navigate away and pick the result up from the gallery+ (or a notification) later. */+ .gen-leave-hint {+ margin: var(--space-xs) 0 0;+ font-size: var(--text-xs);+ line-height: 1.5;+ color: var(--ink-dim);+ }/* Lane-switch notice, shown when the server (or the client's automaticretry) moved this generation onto a backup engine mid-flight, so afailover is informative rather than silent. Filled by forge.js. */@@ -2981,6 +2990,11 @@<div class="gen-progress-fill" id="gen-progress-fill"></div></div><div class="gen-meta" id="gen-meta">Elapsed 0s</div>+ <p class="gen-leave-hint">+ Feel free to leave this page. Your model keeps generating, lands in+ your gallery automatically, and signed-in creators get notified when+ it's ready.+ </p><div class="gen-note is-hidden" id="gen-note" role="status" aria-live="polite"></div><div style="margin-top: var(--space-sm)"><button class="btn btn-ghost" type="button" id="cancel">Cancel</button>diff --git a/public/features.json b/public/features.jsonindex 1a0c0e3ac..f60901a10 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-16T21:48:37.931Z",+ "generated_at": "2026-07-16T22:23:06.573Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/src/avatar-page.js b/src/avatar-page.jsindex d03bb8afb..0134eb772 100644--- a/src/avatar-page.js+++ b/src/avatar-page.js@@ -105,6 +105,8 @@ const MODEL_OPTIONS = [{ id: 'openai:gpt-5.6-sol', label: 'GPT-5.6 Sol', provider: 'openai', model: 'gpt-5.6-sol' },{ id: 'openai:gpt-5.6-terra', label: 'GPT-5.6 Terra', provider: 'openai', model: 'gpt-5.6-terra' },{ id: 'openai:gpt-5.6-luna', label: 'GPT-5.6 Luna', provider: 'openai', model: 'gpt-5.6-luna' },+ { id: 'grok:grok-4.5', label: 'Grok 4.5 (xAI)', provider: 'grok', model: 'grok-4.5' },+ { id: 'grok:grok-4.1-fast', label: 'Grok 4.1 Fast (xAI)', provider: 'grok', model: 'grok-4.1-fast' },{ id: 'watsonx:granite', label: 'IBM Granite 3 (watsonx)', provider: 'watsonx', model: 'ibm/granite-3-8b-instruct' },{ id: 'orchestrate:agent', label: 'watsonx Orchestrate', provider: 'orchestrate', model: 'orchestrate-agent' },];diff --git a/src/forge.js b/src/forge.jsindex b9b381351..cfd84f164 100644--- a/src/forge.js+++ b/src/forge.js@@ -258,6 +258,64 @@ const CLIENT_ID = (() => {const CLIENT_HEADERS = { 'x-forge-client': CLIENT_ID };+// Leave-the-page continuity. The active async job persists here so a reload,+// a navigation away, or a closed tab does not lose the generation: returning+// to /forge inside RESUME_WINDOW_MS resumes polling the same job id (all real+// state lives server-side). Cleared on completion, terminal failure, or+// cancel. Even a user who never comes back is covered: the server-side+// finalizer (api/cron/forge-finalize.js) completes the row into their gallery+// and notifies signed-in creators.+const INFLIGHT_KEY = 'forge:inflight';+const RESUME_WINDOW_MS = 30 * 60 * 1000;++function saveInflight(job, label) {+ if (!job?.job_id) return;+ try {+ localStorage.setItem(+ INFLIGHT_KEY,+ JSON.stringify({+ jobId: job.job_id,+ creationId: job.creation_id || null,+ label: label || '',+ previewImageUrl: job.preview_image_url || null,+ backend: job.backend || null,+ tier: job.tier || null,+ path: job.path || null,+ startedAt: Date.now(),+ }),+ );+ } catch {+ // Private mode / storage blocked: resume simply won't be available.+ }+}++function readInflight() {+ try {+ const raw = localStorage.getItem(INFLIGHT_KEY);+ if (!raw) return null;+ const j = JSON.parse(raw);+ if (!j?.jobId || !Number.isFinite(j.startedAt)) {+ clearInflight();+ return null;+ }+ if (Date.now() - j.startedAt > RESUME_WINDOW_MS) {+ clearInflight();+ return null;+ }+ return j;+ } catch {+ return null;+ }+}++function clearInflight() {+ try {+ localStorage.removeItem(INFLIGHT_KEY);+ } catch {+ /* storage blocked */+ }+}+const REDUCED_MOTION =typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;@@ -329,8 +387,10 @@ function setProgress(pct) {els.genProgress.setAttribute('aria-valuenow', String(Math.round(clamped)));}-function startElapsed() {- const started = performance.now();+function startElapsed(offsetMs = 0) {+ // `offsetMs` backdates the counter for a resumed job, so the elapsed line+ // stays honest about how long the generation has really been running.+ const started = performance.now() - Math.max(0, offsetMs);stopElapsed();const typical = currentEtaSeconds();// Reset the meter to a clean running state for this job.@@ -2153,8 +2213,11 @@ async function run(cfg) {// itself returns the finished model with a null job_id. Polling that// null id would loop on invalid_job until the timeout, losing a result// that already succeeded.- const done = job.status === 'done' && job.glb_url ? job : await pollUntilDone(job.job_id);+ const isAsync = !(job.status === 'done' && job.glb_url);+ if (isAsync) saveInflight(job, label);+ const done = !isAsync ? job : await pollUntilDone(job.job_id);if (pollAbort || !done) return; // cancelled+ clearInflight();// A pay-per-use proof is single-use and now redeemed on the server — drop it// so a later Retry/Refine of this job never replays a spent payment.@@ -2195,6 +2258,11 @@ async function run(cfg) {}} catch (err) {if (pollAbort) return;+ // Every catch path either terminates this job with a designed state or+ // re-runs (which writes a fresh inflight record), so the old record is+ // dead either way. The server-side finalizer still completes the row+ // into the gallery if the lane actually finished after our timeout.+ clearInflight();if (err.kind === 'unconfigured') {stopElapsed();showState('unconfigured');@@ -2301,6 +2369,72 @@ async function run(cfg) {}}+// Resume an in-flight generation persisted before a reload/navigation. The+// server holds all job state, so picking it back up is just polling the same+// job id; the panel restores in its mesh phase with an honest elapsed count.+async function resumeInflight() {+ const inflight = readInflight();+ if (!inflight) return false;++ pollAbort = false;+ currentCreationId = inflight.creationId || null;+ setBusy(true);+ setStepLabel('image', 'Reference ready');+ setStep('image', 'done');+ setStepLabel('mesh', 'Reconstructing textured mesh');+ setStep('mesh', 'active');+ setStep('finish', 'pending');+ els.genPreview.innerHTML = '<div class="shimmer" aria-hidden="true"></div>';+ if (inflight.previewImageUrl) {+ const img = new Image();+ img.alt = 'Reference image';+ img.src = inflight.previewImageUrl;+ img.onload = () => {+ els.genPreview.innerHTML = '';+ els.genPreview.appendChild(img);+ };+ }+ setLaneNote('Welcome back. This generation kept running while you were away.');+ startElapsed(Date.now() - inflight.startedAt);+ showState('generating');++ try {+ const done = await pollUntilDone(inflight.jobId);+ if (pollAbort || !done) return true;+ clearInflight();+ if (done.creation_id) currentCreationId = done.creation_id;+ setStep('mesh', 'done');+ setStep('finish', 'done');+ markProgressDone();+ showResult(+ done.glb_url,+ inflight.label || 'Forged model',+ {+ views_used: done.views_used,+ multiview: done.multiview,+ backend: done.backend ?? inflight.backend,+ tier: done.tier ?? inflight.tier,+ path: done.path ?? inflight.path,+ },+ { autoSaved: !!done.creation_id },+ );+ loadGallery();+ if (!done.preview_image_url && !inflight.previewImageUrl) {+ capturePoster(currentCreationId);+ }+ } catch (err) {+ if (pollAbort) return true;+ clearInflight();+ showError(+ err.message ||+ 'Something went wrong resuming your generation. Check your gallery: finished models land there automatically.',+ );+ } finally {+ setBusy(false);+ }+ return true;+}+// Gather + validate the active mode's composer inputs into a run cfg, or null// when something's missing (focusing/flagging the offending field as a side// effect, exactly as submit always has). Shared by the Generate button and the@@ -2560,6 +2694,7 @@ els.providerKey?.addEventListener('input', () => {els.cancel.addEventListener('click', () => {pollAbort = true;+ clearInflight();stopElapsed();setBusy(false);if (els.categoryPicker) els.categoryPicker.hidden = true;@@ -2816,8 +2951,15 @@ window.addEventListener('wallet:changed', () => {updatePerkLine();});-// Surface any previously forged models for this browser on load.+// Surface any previously forged models for this browser on load, then pick an+// interrupted generation back up. A share link wins over a resume: the visitor+// explicitly asked to see that creation, and the resumed job stays pollable in+// storage for the next plain visit.loadGallery().then(() => {const shareId = window.__forgeShareId;- if (shareId) openSharedCreation(shareId);+ if (shareId) {+ openSharedCreation(shareId);+ return;+ }+ resumeInflight();});diff --git a/src/nich-agent.js b/src/nich-agent.jsindex aa0e218a1..8c4924a83 100644--- a/src/nich-agent.js+++ b/src/nich-agent.js@@ -943,6 +943,8 @@ const MODEL_OPTIONS = [{ id: 'openai:gpt-5.6-sol', label: 'GPT-5.6 Sol', provider: 'openai', model: 'gpt-5.6-sol' },{ id: 'openai:gpt-5.6-terra', label: 'GPT-5.6 Terra', provider: 'openai', model: 'gpt-5.6-terra' },{ id: 'openai:gpt-5.6-luna', label: 'GPT-5.6 Luna', provider: 'openai', model: 'gpt-5.6-luna' },+ { id: 'grok:grok-4.5', label: 'Grok 4.5 (xAI)', provider: 'grok', model: 'grok-4.5' },+ { id: 'grok:grok-4.1-fast', label: 'Grok 4.1 Fast (xAI)', provider: 'grok', model: 'grok-4.1-fast' },{id: 'watsonx:granite',label: 'IBM Granite 3 (watsonx)',diff --git a/src/notifications.js b/src/notifications.jsindex bea570943..65f9980de 100644--- a/src/notifications.js+++ b/src/notifications.js@@ -85,6 +85,8 @@ const TYPE_ICON = {dm_received: '💬',pump_launch_filled: '🚀',agent_review: '⭐',+ forge_complete: '✨',+ forge_failed: '⚠️',};function notifLabel(n) {@@ -141,6 +143,14 @@ function notifLabel(n) {: `Someone messaged your agent in person`;case 'irl_reply':return p.message ? `An agent replied: “${p.message}”` : `An agent replied to your message`;+ case 'forge_complete':+ return p.prompt+ ? `Your 3D model "${String(p.prompt).slice(0, 60)}" is ready`+ : `Your 3D model finished generating`;+ case 'forge_failed':+ return p.prompt+ ? `Your generation "${String(p.prompt).slice(0, 60)}" failed. Tap to retry`+ : `A 3D generation failed. Tap to retry`;default:return n.type.replace(/_/g, ' ');}diff --git a/tests/chat-models.test.js b/tests/chat-models.test.jsindex bc31530ab..b68183da3 100644--- a/tests/chat-models.test.js+++ b/tests/chat-models.test.js@@ -74,11 +74,11 @@ describe('usableModels (route selector)', () => {describe('free-first ordering', () => {it('every free provider ranks ahead of every paid provider', () => {// Free providers (Groq → OpenRouter → NVIDIA NIM) always lead; the paid- // keys (Anthropic, OpenAI) are last-resort backstops only reached when- // all three free lanes have failed.- expect(DEFAULT_PROVIDER_ORDER).toEqual(['groq', 'openrouter', 'nvidia', 'anthropic', 'openai']);+ // keys (Anthropic, OpenAI, Grok) are last-resort backstops only reached+ // when all three free lanes have failed.+ expect(DEFAULT_PROVIDER_ORDER).toEqual(['groq', 'openrouter', 'nvidia', 'anthropic', 'openai', 'grok']);const free = ['groq', 'openrouter', 'nvidia'];- const paid = ['anthropic', 'openai'];+ const paid = ['anthropic', 'openai', 'grok'];for (const f of free) {for (const p of paid) {expect(DEFAULT_PROVIDER_ORDER.indexOf(f), `${f} before ${p}`).toBeLessThan(DEFAULT_PROVIDER_ORDER.indexOf(p));diff --git a/tests/email.test.js b/tests/email.test.jsindex aad6c15fb..db181cb1e 100644--- a/tests/email.test.js+++ b/tests/email.test.js@@ -386,4 +386,27 @@ describe('email — template wrappers compose payloads via buildPayload', () =>expect(payload.html).toContain('Solana');expect(payload.html).toContain('tx-1');});++ it('forge completion payload carries the prompt, share link, and preview', () => {+ const rendered = mod.renderForgeComplete({+ prompt: 'a brass desk lamp, articulated arm',+ creationPath: '/forge?share=abc-123',+ previewImageUrl: 'https://cdn.example.test/preview.webp',+ });+ const payload = mod.buildPayload({ to: '[email protected]', ...rendered });+ expect(payload.subject).toContain('a brass desk lamp');+ expect(payload.html).toContain('/forge?share=abc-123');+ expect(payload.html).toContain('https://cdn.example.test/preview.webp');+ expect(payload.text).toContain('/forge?share=abc-123');+ });++ it('forge completion payload escapes a hostile prompt and stands without a preview', () => {+ const rendered = mod.renderForgeComplete({+ prompt: '<script>alert(1)</script>',+ creationPath: '/forge?share=abc-123',+ previewImageUrl: null,+ });+ expect(rendered.html).not.toContain('<script>alert(1)</script>');+ expect(rendered.html).not.toContain('<img');+ });});diff --git a/tests/forge-finalize.test.js b/tests/forge-finalize.test.jsnew file mode 100644index 000000000..b296f38a9--- /dev/null+++ b/tests/forge-finalize.test.js@@ -0,0 +1,44 @@+// Unit tests for the finalizer's job-id discriminator: the base64url JSON+// envelope the GCP worker lanes store in forge_creations.replicate_job_id+// (see api/_providers/gcp.js) vs. opaque third-party ids the cron cannot poll.+// Importing the cron module is safe: db/neon clients are created lazily.++import { describe, it, expect } from 'vitest';+import { decodeWorkerEnvelope } from '../api/cron/forge-finalize.js';++function pack(obj) {+ return Buffer.from(JSON.stringify(obj), 'utf8').toString('base64url');+}++describe('decodeWorkerEnvelope', () => {+ it('decodes a real GCP worker envelope', () => {+ const envelope = pack({+ mode: 'trellis',+ taskId: '8e033fff-6ba2-4324-a388-e093a30ed083',+ baseUrl: 'https://model-trellis.example.test',+ resultKey: 'result_gcs_url',+ });+ const decoded = decodeWorkerEnvelope(envelope);+ expect(decoded).not.toBeNull();+ expect(decoded.taskId).toBe('8e033fff-6ba2-4324-a388-e093a30ed083');+ expect(decoded.baseUrl).toBe('https://model-trellis.example.test');+ });++ it('rejects an envelope missing taskId or baseUrl', () => {+ expect(decodeWorkerEnvelope(pack({ taskId: 'only-task' }))).toBeNull();+ expect(decodeWorkerEnvelope(pack({ baseUrl: 'https://x.test' }))).toBeNull();+ expect(decodeWorkerEnvelope(pack({}))).toBeNull();+ });++ it('rejects opaque third-party ids (Replicate predictions, HF jobs)', () => {+ expect(decodeWorkerEnvelope('rr2p7dbwd5rmyk4b3xyz')).toBeNull();+ expect(decodeWorkerEnvelope('hf-space-job-42')).toBeNull();+ expect(decodeWorkerEnvelope('')).toBeNull();+ expect(decodeWorkerEnvelope(null)).toBeNull();+ });++ it('rejects base64url payloads that are not JSON objects', () => {+ expect(decodeWorkerEnvelope(Buffer.from('"a string"').toString('base64url'))).toBeNull();+ expect(decodeWorkerEnvelope(Buffer.from('42').toString('base64url'))).toBeNull();+ });+});diff --git a/tests/notify-prefs.test.js b/tests/notify-prefs.test.jsindex 528e54db5..61317a221 100644--- a/tests/notify-prefs.test.js+++ b/tests/notify-prefs.test.js@@ -18,9 +18,9 @@ import {} from '../api/_lib/notify-prefs.js';describe('category model', () => {- it('exposes the six display categories and four channels', () => {+ it('exposes the seven display categories and four channels', () => {expect(CATEGORIES.map((c) => c.key)).toEqual([- 'sales', 'purchases', 'social', 'irl', 'alerts', 'account',+ 'sales', 'purchases', 'social', 'irl', 'alerts', 'creations', 'account',]);expect(CHANNELS).toEqual(['in_app', 'push', 'email', 'telegram']);});@@ -42,6 +42,8 @@ describe('categoryForType', () => {expect(categoryForType('remix')).toBe('social');expect(categoryForType('irl_interaction')).toBe('irl');expect(categoryForType('pump_alert')).toBe('alerts');+ expect(categoryForType('forge_complete')).toBe('creations');+ expect(categoryForType('forge_failed')).toBe('creations');expect(categoryForType('withdrawal_failed')).toBe('account');});@@ -69,11 +71,14 @@ describe('defaultMatrix / mergeWithDefaults', () => {}});- it('email defaults on only for money + security categories', () => {+ it('email defaults on only for money, security, and unattended creations', () => {const m = defaultMatrix();expect(m.sales.email).toBe(true);expect(m.purchases.email).toBe(true);expect(m.account.email).toBe(true);+ // Creations email only ever fires for an unattended completion (the+ // finalizer path), so defaulting on is the feature the user asked for.+ expect(m.creations.email).toBe(true);expect(m.social.email).toBe(false);expect(m.irl.email).toBe(false);expect(m.alerts.email).toBe(false);@@ -162,6 +167,25 @@ describe('pushPayloadFor', () => {expect(p.tag).toBe('skill_purchased');});+ it('builds forge completion copy with the prompt and the share link', () => {+ const p = pushPayloadFor(+ 'forge_complete',+ { prompt: 'a brass desk lamp', link: '/forge?share=abc-123' },+ 'n-9',+ );+ expect(p.title).toMatch(/ready/i);+ expect(p.body).toContain('a brass desk lamp');+ expect(p.url).toBe('/forge?share=abc-123');+ expect(p.category).toBe('creations');+ });++ it('builds forge failure copy that points back at the forge', () => {+ const p = pushPayloadFor('forge_failed', { prompt: 'a lamp', link: '/forge' });+ expect(p.title).toMatch(/failed/i);+ expect(p.url).toBe('/forge');+ expect(p.category).toBe('creations');+ });+it('prefers an explicit safe link and rejects javascript: urls', () => {expect(pushPayloadFor('reply', { link: '/agent/x' }).url).toBe('/agent/x');expect(pushPayloadFor('reply', { link: 'javascript:alert(1)' }).url).toBe('/dashboard/');diff --git a/vercel.json b/vercel.jsonindex 5b4266751..d214c660d 100644--- a/vercel.json+++ b/vercel.json@@ -5175,6 +5175,10 @@"path": "/api/cron/forge-smoke","schedule": "30 9 * * *"},+ {+ "path": "/api/cron/forge-finalize",+ "schedule": "* * * * *"+ },{"path": "/api/llm/health","schedule": "0 * * * *"diff --git a/workers/model-hunyuan3d/Dockerfile.hunyuan21 b/workers/model-hunyuan3d/Dockerfile.hunyuan21index 90d48e398..31899abbe 100644--- a/workers/model-hunyuan3d/Dockerfile.hunyuan21+++ b/workers/model-hunyuan3d/Dockerfile.hunyuan21@@ -38,6 +38,19 @@ RUN pip install torch==2.5.1 torchvision==0.20.1 torchaudio==2.5.1 \COPY requirements.hunyuan21.txt /app/requirements.txtRUN pip install -r /app/requirements.txt+# Blender's `bpy` has no cp310 PyPI wheel and is only reached through the unused+# save_glb OBJ->GLB exporter in DifferentiableRenderer.mesh_utils. Drop a tiny+# stub module so the top-level `import bpy` in that file resolves; this worker+# assembles the PBR GLB with pygltflib and never calls a bpy function.+RUN python - <<'PY'+import os, sysconfig+dest = os.path.join(sysconfig.get_paths()["purelib"], "bpy.py")+with open(dest, "w") as f:+ f.write("# stub: real Blender bpy is only needed for the unused save_glb "+ "OBJ->GLB exporter. This worker builds the PBR GLB with pygltflib.\n")+print("wrote bpy stub to", dest)+PY+# The 2.1 code (hy3dshape + hy3dpaint packages) is cloned in-tree from a pinned# Tencent-Hunyuan/Hunyuan3D-2.1 commit — the texgen extensions must be compiled# from this tree, and a moving `main` breaks the reproducibility bar. Build thediff --git a/workers/model-hunyuan3d/requirements.hunyuan21.txt b/workers/model-hunyuan3d/requirements.hunyuan21.txtindex 6db4a50ad..760cafd26 100644--- a/workers/model-hunyuan3d/requirements.hunyuan21.txt+++ b/workers/model-hunyuan3d/requirements.hunyuan21.txt@@ -4,11 +4,19 @@# torchaudio are installed separately in the Dockerfile from the cu124 wheel# index (they must match the base image's CUDA 12.4).#-# Deliberately excluded from upstream's list: gradio (demo UI only) and-# deepspeed (training-only; its sole import in the shape stack sits inside a-# training-EMA branch that inference never reaches). Added on top: httpx (the-# SSRF guard in worker_security), google-cloud-storage (task state + weight-# staging + result upload).+# Deliberately excluded from upstream's list:+# - gradio: demo UI only.+# - deepspeed: training-only; its sole import in the shape stack sits inside a+# training-EMA branch that inference never reaches.+# - bpy (Blender): has no cp310 wheel on PyPI, and it is only reached through+# DifferentiableRenderer.mesh_utils.convert_obj_to_glb (the save_glb=True OBJ+# to GLB exporter). This worker never calls it — it paints with+# save_glb=False and assembles the final PBR GLB with pygltflib via+# hy3dpaint.convert_utils.create_glb_with_pbr_materials. The Dockerfile+# drops a tiny stub `bpy` module so the top-level `import bpy` in+# mesh_utils resolves; no bpy function is ever executed.+# Added on top: httpx (the SSRF guard in worker_security), google-cloud-storage+# (task state + weight staging + result upload).# ── Build tools (custom_rasterizer CUDA ext + mesh_inpaint_processor pybind11) ─ninja==1.11.1.1@@ -64,8 +72,8 @@ torchdiffeq# ── GPU computing ────────────────────────────────────────────────────────────cupy-cuda12x==13.4.1-# ── Blender (headless, used by DifferentiableRenderer.mesh_utils on import) ───-bpy==4.0+# ── Blender (bpy): intentionally NOT installed — stubbed in the Dockerfile ────+# (only reachable via the unused save_glb OBJ->GLB exporter; see header note).# ── ONNX runtime (rembg background removal) ──────────────────────────────────onnxruntime==1.16.3