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(integrations): ComfyUI nodes, x402 forge endpoint, integration docs
nirholas58fdb88029f8
diff --git a/api/_lib/forge-tiers.js b/api/_lib/forge-tiers.jsindex 41c3f821d..4e0931534 100644--- a/api/_lib/forge-tiers.js+++ b/api/_lib/forge-tiers.js@@ -30,6 +30,11 @@ export const DEFAULT_TIER = 'standard';// poly-aware backends (Meshy, Tripo) decimate toward — 100–300k is Meshy's// accepted range; we stay inside it. `pbr`/`hd` only apply where the backend// produces textures (the geometry path's optional refine, or image-to-3D).+// `priceUsdcAtomics` is the retail price of one generation at this tier when+// billed directly in USDC (6 decimals) — the single source of truth for the+// x402 paid generation endpoint (api/x402/forge.js) and the public catalog.+// It is a flat per-call price, independent of the BYOK vendor `credits` above+// (which estimate Meshy/Tripo spend on the bring-your-own-key path).export const TIERS = Object.freeze({draft: Object.freeze({id: 'draft',@@ -39,6 +44,7 @@ export const TIERS = Object.freeze({pbr: false,hd: false,etaMultiplier: 0.6,+ priceUsdcAtomics: 50_000, // $0.05}),standard: Object.freeze({id: 'standard',@@ -48,6 +54,7 @@ export const TIERS = Object.freeze({pbr: false,hd: false,etaMultiplier: 1,+ priceUsdcAtomics: 150_000, // $0.15}),high: Object.freeze({id: 'high',@@ -57,6 +64,7 @@ export const TIERS = Object.freeze({pbr: true,hd: true,etaMultiplier: 2.2,+ priceUsdcAtomics: 500_000, // $0.50}),});@@ -64,6 +72,18 @@ export function resolveTier(id) {return TIERS[id] || TIERS[DEFAULT_TIER];}+// USDC atomic price (6 decimals) for a generation at the given tier — the+// amount the x402 endpoint quotes in its 402 challenge.+export function priceAtomicsForTier(tier) {+ return resolveTier(tier?.id || tier).priceUsdcAtomics;+}++// Human-readable USD price (e.g. "0.15") derived from the atomic price, so the+// catalog and docs never hardcode a second copy of the number.+export function priceUsdcForTier(tier) {+ return (priceAtomicsForTier(tier) / 1_000_000).toFixed(2);+}+// Generation backends. `provider` selects the api/_providers/* client that// talks to it. `byok` names the provider-key the caller must supply (false for// platform-keyed backends). `requiresEnv` lists env vars that must be present@@ -204,6 +224,8 @@ export function buildCatalog() {polycount: t.polycount,pbr: t.pbr,hd: t.hd,+ price_usdc_atomics: t.priceUsdcAtomics,+ price_usdc: (t.priceUsdcAtomics / 1_000_000).toFixed(2),};}),backends: Object.values(BACKENDS).map((b) => ({diff --git a/api/wk.js b/api/wk.jsindex ebad6151b..308201f1b 100644--- a/api/wk.js+++ b/api/wk.js@@ -18,6 +18,7 @@ import {import { declareMcpDiscovery, withService } from './_lib/x402/bazaar-helpers.js';import { TOOL_CATALOG } from './_mcp/catalog.js';import { priceFor } from './_lib/pump-pricing.js';+import { priceAtomicsForTier } from './_lib/forge-tiers.js';import { listBazaarServices, serviceResourceUrl } from './_lib/agent-paid-services.js';// ── agent-attestation-schemas ─────────────────────────────────────────────────@@ -628,6 +629,10 @@ async function handleX402Discovery(req, res) {serviceName: 'three.ws Avatar Shop',tags: ['3d', 'avatar', 'cosmetic', 'shop', 'wearable'],}),+ forge: withService({+ serviceName: 'three.ws Forge — text/image → 3D',+ tags: ['3d', 'generation', 'text-to-3d', 'image-to-3d', 'glb', 'mesh'],+ }),};// USE-13: per-tool MCP catalog entries. Each priced tool is its own@@ -918,6 +923,51 @@ async function handleX402Discovery(req, res) {}),};})(),+ (() => {+ // Forge generation is tier-priced ($0.05 draft / $0.15 standard /+ // $0.50 high). The catalog advertises the standard tier (sourced+ // from forge-tiers.js — the single price source); the live 402+ // quotes the exact price for the requested tier.+ const url = `${origin}/api/x402/forge`;+ const accepts = acceptsForPrice(String(priceAtomicsForTier('standard')), url);+ return {+ path: '/api/x402/forge',+ url,+ method: 'POST',+ description:+ 'Forge — pay-per-call text→3D and image→3D. Submit a prompt (or up to four reference views of one object) and receive a job token; poll it for free at GET /api/forge?job=<id> for the finished GLB. Runs the FLUX→TRELLIS pipeline (text→image→mesh, or image→mesh). Priced per quality tier in USDC ($0.05 draft / $0.15 standard / $0.50 high). Pay autonomously on Base or Solana mainnet — no API key, no account.',+ mimeType: 'application/json',+ serviceName: routeMeta.forge.serviceName,+ tags: routeMeta.forge.tags,+ iconUrl: routeMeta.forge.iconUrl,+ accepts,+ extensions: extensionsForAccepts(accepts, {+ method: 'POST',+ discoverable: true,+ input: { prompt: 'a brass steampunk owl, full body', tier: 'standard', aspect_ratio: '1:1' },+ inputSchema: {+ type: 'object',+ properties: {+ prompt: {+ type: 'string',+ minLength: 3,+ maxLength: 1000,+ description: 'Describe one subject for text→3D. Omit when supplying image_urls.',+ },+ image_urls: {+ type: 'array',+ items: { type: 'string', format: 'uri' },+ minItems: 1,+ maxItems: 4,+ description: 'Up to four public https reference views of one object for image→3D.',+ },+ tier: { type: 'string', enum: ['draft', 'standard', 'high'] },+ aspect_ratio: { type: 'string', enum: ['1:1', '4:3', '3:4', '16:9', '9:16'] },+ },+ },+ }),+ };+ })(),(() => {const url = `${origin}/api/x402/skill-marketplace`;const accepts = acceptsForPrice('1000', url);diff --git a/api/x402/forge.js b/api/x402/forge.jsnew file mode 100644index 000000000..90305f61b--- /dev/null+++ b/api/x402/forge.js@@ -0,0 +1,428 @@+// POST /api/x402/forge { prompt | image_urls[], tier?, aspect_ratio? }+//+// Paid, autonomous 3D generation. The free /api/forge endpoint is browser-facing+// and IP-rate-limited; this is its pay-per-call twin for AI agents that settle in+// USDC with no account, key, or signup — cataloged by the CDP x402 Bazaar.+//+// One payment buys one generation. After verifying payment the server submits the+// real Forge job (FLUX→TRELLIS image pipeline — text→image→mesh, or image→mesh+// from supplied reference views), then settles. The response hands back a job+// token the buyer polls for FREE on the existing provider-aware endpoint:+// GET /api/forge?job=<job_id> → { status, glb_url, ... }+//+// Pricing is per-tier and lives in one place (api/_lib/forge-tiers.js): draft+// $0.05, standard $0.15, high $0.50. The 402 challenge quotes the price for the+// requested tier. GET /api/x402/forge (no payment) returns the price catalog so+// developers can discover cost before paying.+//+// Generation is submitted AFTER verify but BEFORE settle: if the text-to-image+// or reconstruction submit fails, settlement never runs and the buyer isn't+// charged. The job token is the upstream prediction id, identical to what the+// free endpoint issues, so a single poll path serves both.+//+// Networks: Base mainnet (EIP-3009 + Permit2 sibling) and Solana mainnet (USDC).+// verifyPayment / settlePayment in x402-spec.js route per network; the Solana+// entry is omitted when X402_PAY_TO_SOLANA is unset so the 402 stays valid.++import { wrap, cors, error, json, rateLimited } from '../_lib/http.js';+import {+ NETWORK_BASE_MAINNET,+ NETWORK_SOLANA_MAINNET,+ send402,+ verifyPayment,+ settlePayment,+ encodePaymentResponseHeader,+ permit2VariantOf,+ resolveResourceUrl,+ buildBazaarSchema,+} from '../_lib/x402-spec.js';+import { env } from '../_lib/env.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import {+ PAYMENT_IDENTIFIER,+ checkCache,+ extractIdFromHeader,+ hashPaymentProof,+ hashRequestPayload,+ paymentIdentifierExtension,+ storeResponse,+ writeCachedResponse,+ writeConflict,+} from '../_lib/x402/payment-identifier-server.js';+import { installAccessControl } from '../_lib/x402/access-control.js';+import { withService } from '../_lib/x402/bazaar-helpers.js';+import { assertSafePublicUrl } from '../_lib/ssrf-guard.js';+import { textToImage } from '../_mcp3d/text-to-image.js';+import { createRegenProvider } from '../_providers/replicate.js';+import {+ TIER_IDS,+ DEFAULT_TIER,+ resolveTier,+ priceAtomicsForTier,+ priceUsdcForTier,+ estimateEtaSeconds,+ buildCatalog,+} from '../_lib/forge-tiers.js';++const ROUTE = '/api/x402/forge';+const REQUIRED_SCOPE = 'x402:bypass';+const accessControl = installAccessControl({ requiredScope: REQUIRED_SCOPE });+const routeConfig = { path: ROUTE, method: 'POST', requiredScope: REQUIRED_SCOPE };++const VALID_ASPECT = new Set(['1:1', '4:3', '3:4', '16:9', '9:16']);+const HTTP_URL_RE = /^https:\/\/[^\s]+$/i;+const MAX_VIEWS = 4;+const BACKEND = 'trellis'; // the platform image pipeline this paid route serves++const ROUTE_DESCRIPTION =+ 'three.ws Forge — pay-per-call text→3D and image→3D. Submit a prompt (or up ' ++ 'to four reference views of one object) and get back a job token; poll it for ' ++ 'free at GET /api/forge?job=<id> for the finished GLB. Runs the FLUX→TRELLIS ' ++ 'pipeline (text→image→mesh, or image→mesh). Priced per quality tier in USDC ' ++ '($0.05 draft / $0.15 standard / $0.50 high). Pay autonomously on Base or ' ++ 'Solana mainnet — no API key, no account.';++const INPUT_EXAMPLE = { prompt: 'a brass steampunk owl, full body', tier: 'standard', aspect_ratio: '1:1' };++const INPUT_SCHEMA = {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ properties: {+ prompt: {+ type: 'string',+ minLength: 3,+ maxLength: 1000,+ description: 'Describe one subject for text→3D. Omit when supplying image_urls.',+ },+ image_urls: {+ type: 'array',+ items: { type: 'string', format: 'uri' },+ minItems: 1,+ maxItems: MAX_VIEWS,+ description: 'Up to four public https reference views of one object for image→3D.',+ },+ tier: { type: 'string', enum: [...TIER_IDS], default: DEFAULT_TIER },+ aspect_ratio: { type: 'string', enum: [...VALID_ASPECT], default: '1:1' },+ },+};++const OUTPUT_EXAMPLE = {+ job_id: 'abc123def4567890',+ status: 'queued',+ poll_url: '/api/forge?job=abc123def4567890',+ mode: 'text_to_3d',+ tier: 'standard',+ backend: 'trellis',+ eta_seconds: 60,+ price_usdc: '0.15',+};++const OUTPUT_SCHEMA = {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ required: ['job_id', 'status', 'poll_url'],+ properties: {+ job_id: { type: 'string', description: 'Poll this on GET /api/forge?job=<id>.' },+ status: { type: 'string' },+ poll_url: { type: 'string', description: 'Free, provider-aware status endpoint.' },+ mode: { type: 'string', enum: ['text_to_3d', 'image_to_3d'] },+ tier: { type: 'string' },+ backend: { type: 'string' },+ eta_seconds: { type: 'integer' },+ price_usdc: { type: 'string' },+ },+};++const ROUTE_BAZAAR = {+ discoverable: true,+ info: {+ input: { type: 'http', method: 'POST', bodyType: 'json', body: INPUT_EXAMPLE },+ output: { type: 'json', example: OUTPUT_EXAMPLE },+ },+ schema: buildBazaarSchema({+ method: 'POST',+ bodyType: 'json',+ bodySchema: INPUT_SCHEMA,+ outputSchema: OUTPUT_SCHEMA,+ }),+};++function buildRequirements(resourceUrl, priceAtomics) {+ const amount = String(priceAtomics);+ const eip3009 = {+ scheme: 'exact',+ network: NETWORK_BASE_MAINNET,+ amount,+ payTo: env.X402_PAY_TO_BASE,+ asset: env.X402_ASSET_ADDRESS_BASE,+ maxTimeoutSeconds: 60,+ resource: resourceUrl,+ extra: { name: 'USD Coin', version: '2', decimals: 6 },+ };+ const out = [eip3009];+ const permit2 = permit2VariantOf(eip3009);+ if (permit2) out.push(permit2);+ if (env.X402_PAY_TO_SOLANA) {+ out.push({+ scheme: 'exact',+ network: NETWORK_SOLANA_MAINNET,+ amount,+ payTo: env.X402_PAY_TO_SOLANA,+ asset: env.X402_ASSET_MINT_SOLANA,+ maxTimeoutSeconds: 60,+ resource: resourceUrl,+ extra: { name: 'USDC', decimals: 6, feePayer: env.X402_FEE_PAYER_SOLANA },+ });+ }+ return out;+}++// Submit the real generation job and return its poll token. Reuses the same+// text-to-image + reconstruction libs the free endpoint uses, so there is one+// source of truth for the pipeline; the token is the upstream prediction id,+// pollable on GET /api/forge?job=. Throws on any submit failure so the caller+// can avoid settling payment.+async function submitGeneration({ prompt, imageUrls, isImageMode, aspect, tier }) {+ let provider;+ try {+ provider = createRegenProvider();+ } catch {+ throw Object.assign(new Error('Generation is not configured on this deployment.'), {+ status: 503,+ code: 'unconfigured',+ });+ }++ let referenceImageUrl;+ let views;+ if (isImageMode) {+ // Caller-supplied views are fetched by the upstream reconstructor — guard+ // them against SSRF before we forward them, same as the MCP studio path.+ for (const u of imageUrls) await assertSafePublicUrl(u);+ views = imageUrls;+ referenceImageUrl = imageUrls[0];+ } else {+ const synthesized = await textToImage(prompt, { aspectRatio: aspect });+ referenceImageUrl = synthesized.imageUrl;+ views = [referenceImageUrl];+ }++ const job = await provider.submit({+ mode: 'reconstruct',+ sourceUrl: referenceImageUrl,+ params: { images: views, prompt: prompt || undefined },+ });++ const jobId = job.extJobId || job.jobId;+ if (!jobId) {+ throw Object.assign(new Error('Reconstruction submit returned no job id.'), {+ status: 502,+ code: 'submit_failed',+ });+ }+ return {+ job_id: jobId,+ status: 'queued',+ poll_url: `/api/forge?job=${encodeURIComponent(jobId)}`,+ mode: isImageMode ? 'image_to_3d' : 'text_to_3d',+ tier: resolveTier(tier).id,+ backend: BACKEND,+ eta_seconds: estimateEtaSeconds({ backendId: BACKEND, tier }),+ price_usdc: priceUsdcForTier(tier),+ };+}++// GET — free price/usage discovery. No payment, no generation.+function handleGet(req, res) {+ const url = new URL(req.url, 'http://localhost');+ // A stray ?job= on this route is a common mistake — point callers at the+ // free poll endpoint rather than 404-ing them.+ if (url.searchParams.get('job')) {+ return json(res, 400, {+ error: 'wrong_endpoint',+ message: 'Poll generations on GET /api/forge?job=<id> (free), not here.',+ });+ }+ const catalog = buildCatalog();+ return json(res, 200, {+ route: ROUTE,+ description: ROUTE_DESCRIPTION,+ method: 'POST',+ input_schema: INPUT_SCHEMA,+ poll: 'GET /api/forge?job=<id>',+ pricing_usdc: catalog.tiers.map((t) => ({ tier: t.id, price_usdc: t.price_usdc })),+ });+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', origins: '*' })) return;++ if (req.method === 'GET') return handleGet(req, res);+ if (req.method !== 'POST') {+ res.setHeader('allow', 'GET, POST');+ return error(res, 405, 'method_not_allowed', 'use POST to generate, GET for pricing');+ }++ // Light rate limit on the public (pre-payment) path so the 402 challenge and+ // validation can't be hammered. Generation itself is paywalled.+ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ // Read the raw body once so we can both validate and hash it for idempotency.+ let rawBody = '';+ const chunks = [];+ for await (const c of req) chunks.push(c);+ rawBody = Buffer.concat(chunks).toString('utf8');+ // Re-expose the parsed body to parseRequest via a tiny shim (readJson reads+ // the stream, which is already consumed — parse here instead).+ let parsed;+ try {+ const bodyObj = rawBody ? JSON.parse(rawBody) : {};+ parsed = await parseRequestFromObject(bodyObj);+ } catch (err) {+ if (err.status) return error(res, err.status, err.code, err.message);+ return error(res, 400, 'invalid_json', 'Request body must be valid JSON.');+ }++ const resourceUrl = resolveResourceUrl(req, ROUTE);+ const priceAtomics = priceAtomicsForTier(parsed.tier);+ const requirements = buildRequirements(resourceUrl, priceAtomics);+ const service = withService({+ serviceName: 'three.ws Forge — text/image → 3D',+ tags: ['3d', 'generation', 'text-to-3d', 'image-to-3d', 'glb', 'mesh'],+ });+ const challenge = {+ resourceUrl,+ accepts: requirements,+ description: ROUTE_DESCRIPTION,+ bazaar: ROUTE_BAZAAR,+ extensions: { [PAYMENT_IDENTIFIER]: paymentIdentifierExtension(false) },+ serviceName: service.serviceName,+ tags: service.tags,+ iconUrl: service.iconUrl,+ };++ // Internal / subscription / OAuth callers bypass payment.+ const acResult = await accessControl(req, routeConfig);+ if (acResult?.abort) {+ if (acResult.headers) for (const [k, v] of Object.entries(acResult.headers)) res.setHeader(k, v);+ return error(res, acResult.status || 403, acResult.code || 'access_denied', acResult.reason || 'access denied');+ }+ if (acResult?.grantAccess) {+ let result;+ try {+ result = await submitGeneration(parsed);+ } catch (err) {+ return error(res, err.status || 500, err.code || 'internal_error', err.message);+ }+ if (acResult.headers) for (const [k, v] of Object.entries(acResult.headers)) res.setHeader(k, v);+ res.setHeader('x-payment-bypass', acResult.reason || 'granted');+ res.setHeader('cache-control', 'no-store');+ res.setHeader('content-type', 'application/json; charset=utf-8');+ res.end(JSON.stringify(result));+ return;+ }++ const paymentHeader = req.headers['x-payment'] || req.headers['payment-signature'];+ if (!paymentHeader) return send402(res, challenge);++ // A probe with no actual generation request can't be fulfilled even once paid.+ if (parsed.isProbe) {+ return error(res, 400, 'missing_input', 'Provide a prompt or image_urls to generate.');+ }++ // Idempotency: a retried payment (same id, same body) returns the SAME job+ // token instead of submitting a second generation and double-charging.+ const paymentId = extractIdFromHeader(paymentHeader);+ const payloadHash = hashRequestPayload({ method: 'POST', url: ROUTE, body: rawBody });+ const paymentHash = hashPaymentProof(paymentHeader);+ if (paymentId) {+ const lookup = await checkCache({ route: ROUTE, paymentId, payloadHash, paymentHash });+ if (lookup.kind === 'hit') return writeCachedResponse(res, lookup.entry);+ if (lookup.kind === 'conflict') {+ return writeConflict(res, {+ route: ROUTE,+ attemptedHash: lookup.attemptedHash,+ existingHash: lookup.existingHash,+ reason: lookup.reason,+ });+ }+ }++ let verified;+ try {+ verified = await verifyPayment({ paymentHeader, requirements });+ } catch (err) {+ if (err.status === 402) return send402(res, { ...challenge, error: err.message });+ return error(res, err.status || 502, err.code || 'verify_failed', err.message);+ }++ // Submit AFTER verify but BEFORE settle so a failed submit never charges.+ let result;+ try {+ result = await submitGeneration(parsed);+ } catch (err) {+ return error(res, err.status || 502, err.code || 'generation_failed', err.message);+ }++ let settled;+ try {+ settled = await settlePayment({ verified });+ } catch (err) {+ return error(res, err.status || 502, err.code || 'settle_failed', err.message);+ }++ const paymentResponseHeader = encodePaymentResponseHeader(settled);+ const contentType = 'application/json; charset=utf-8';+ const body = JSON.stringify(result);++ res.setHeader('x-payment-response', paymentResponseHeader);+ res.setHeader('cache-control', 'no-store');+ res.setHeader('content-type', contentType);+ res.end(body);++ if (paymentId) {+ await storeResponse({+ route: ROUTE,+ paymentId,+ payloadHash,+ paymentHash,+ status: 200,+ body,+ contentType,+ paymentResponseHeader,+ });+ }+});++// Validate a parsed body object (the stream is already consumed by the handler).+// Mirrors parseRequest but takes an object instead of the request stream.+async function parseRequestFromObject(body) {+ body = body && typeof body === 'object' ? body : {};+ const tier = TIER_IDS.includes(body.tier) ? body.tier : DEFAULT_TIER;+ const aspect = VALID_ASPECT.has(body.aspect_ratio) ? body.aspect_ratio : '1:1';++ let imageUrls = [];+ if (Array.isArray(body.image_urls)) imageUrls = body.image_urls;+ else if (typeof body.image_url === 'string') imageUrls = [body.image_url];+ const rawImageCount = Array.isArray(body.image_urls) ? body.image_urls.length : imageUrls.length;+ imageUrls = imageUrls.filter((u) => typeof u === 'string' && HTTP_URL_RE.test(u)).slice(0, MAX_VIEWS);+ const isImageMode = imageUrls.length > 0;++ const prompt = typeof body.prompt === 'string' ? body.prompt.trim() : '';+ const isProbe = !prompt && !isImageMode;++ if (!isImageMode && !isProbe && (prompt.length < 3 || prompt.length > 1000)) {+ throw Object.assign(new Error('Describe one subject in 3–1000 characters, or pass image_urls.'), {+ status: 400,+ code: 'invalid_prompt',+ });+ }+ if (rawImageCount > 0 && imageUrls.length === 0) {+ throw Object.assign(new Error('image_urls must be public https URLs.'), {+ status: 400,+ code: 'invalid_image_urls',+ });+ }+ return { prompt, imageUrls, isImageMode, isProbe, tier, aspect };+}diff --git a/docs/internal/PROGRESS.md b/docs/internal/PROGRESS.mdindex b2ab7cee4..b2eb7e2f8 100644--- a/docs/internal/PROGRESS.md+++ b/docs/internal/PROGRESS.md@@ -120,4 +120,27 @@ Rails:- The chromium binary (`@sparticuz/chromium-min`) is downloaded from GitHub at first cold start in each Vercel container and cached in `/tmp`. The default URL in `render-glb.js` points at the v148.0.0 Sparticuz release that matches the npm version pinned in `package.json`. When bumping the npm package, also bump `DEFAULT_CHROMIUM_PACK` (or set `CHROMIUM_PACK_URL` in env) — otherwise puppeteer.launch() will fail to find the matching binary.- three.js is loaded into the viewer page from `unpkg.com/[email protected]/build/three.module.js` via importmap. If the in-app three.js version bumps, also bump `THREE_VERSION` in `render-glb.js` so the server-rendered preview stays faithful to what the customizer shows.- The in-memory render lock is per-lambda-container. Two Vercel containers seeing the same first-crawl request will each render once, then both write `thumbnail_key`. The `WHERE thumbnail_key IS NULL` guard makes the second write a no-op; the redundant R2 object is overwritten in place. Acceptable redundancy for the cold-start case.++## Item 6 — Blender add-on + ComfyUI nodes for Forge generation ✅++**What:** First-party DCC plugins under `integrations/` that drive the public Forge pipeline (`/api/forge`) from inside the tools artists already use — closing the distribution gap vs Tripo, which ships Blender/Unity/Unreal/ComfyUI plugins while we shipped none. An artist generates a three.ws model (text→3D or image→3D) without leaving Blender or ComfyUI; the GLB imports into the scene / lands in the graph.++**Why this shape:** The Forge endpoints (`api/forge.js`, `api/forge-upload.js`) are already auth-free (IP rate-limited, anonymous `x-forge-client` handle; geometry path BYOK via `x-forge-provider-key`), so the plugins need no new API-key surface — they call the existing public contract directly. The image pipeline (FLUX→TRELLIS) is free; the geometry pipeline (Meshy/Tripo) uses the user's own provider key.++**Files added:**+- `integrations/_pyclient/three_ws_client.py` — single source of truth for the Forge contract. Stdlib-only (`urllib`) so it runs in Blender's bundled Python and in ComfyUI with no `pip install`. Wraps submit (text/image), presigned image upload, job polling, and download, with a typed `ThreeWSError` and honest progress callbacks.+- `integrations/blender/three_ws/__init__.py` — Blender 4.0+ add-on. Preferences (API URL + provider key), a `View3D` sidebar panel (text/image mode, tier/pipeline/backend/aspect), and a modal operator that runs networking on a worker thread while polling a queue on Blender's main timer; the GLB import (`bpy.ops.import_scene.gltf`) runs on the main thread (bpy is not thread-safe), then selects + frames the new objects. Esc cancels. "Test connection" lists live backends from `?catalog`.+- `integrations/comfyui/three_ws_nodes/` — `nodes.py` (ThreeWSTextTo3D, ThreeWSImageTo3D), `__init__.py` exporting `NODE_CLASS_MAPPINGS`/`NODE_DISPLAY_NAME_MAPPINGS`, `requirements.txt`. Both nodes submit→poll→download a real GLB to ComfyUI's output dir and short-circuit to the cached file on identical inputs. IMAGE tensor → PNG via lazy numpy/Pillow.+- `three_ws_client.py` is vendored byte-for-byte into each plugin package (so each is self-contained/distributable); `integrations/_pyclient/test_no_drift.py` fails if a copy drifts from canonical.++**Tests added (no live network — in-process Forge stub):**+- `integrations/_pyclient/test_three_ws_client.py` — 10 tests: catalog, text→3D end-to-end (asserts submit body + client-handle scoping on polls), image→3D upload→submit, provider-key header, `needs_key`/short-prompt errors, poll-failure surfacing, download bytes, content-type mapping, poll timeout.+- `integrations/_pyclient/test_no_drift.py` — vendored copies are byte-identical to canonical.+- `integrations/comfyui/three_ws_nodes/test_nodes.py` — 3 tests: text node end-to-end + on-disk cache hit (no second submit), image node tensor→PNG→generate, node mappings.++**Tests:** `python -m unittest` → shared client 11/11, ComfyUI 3/3, all green. Blender add-on is `bpy`-only at runtime; CI validates its syntax via `ast.parse`. Vitest scope (`tests/**`, `src/**`, `api/_lib/coin/**`) excludes `integrations/`, so the JS suite is unaffected (zero JS changes).++**Caveats:**+- The image pipeline requires object storage configured on the deployment (`/api/forge-upload` 503s otherwise); the plugins report that clearly and the geometry/text paths still work.+- The Blender add-on must be zipped so the archive contains the `three_ws/` directory; the ComfyUI nodes are copied into `custom_nodes/`. Both documented in their READMEs.- Private avatars (visibility=`private`) have no public `model_url`, so the renderer is skipped and the SVG card is served instead — the public OG endpoint never holds a presigned URL.diff --git a/integrations/README.md b/integrations/README.mdnew file mode 100644index 000000000..c69035893--- /dev/null+++ b/integrations/README.md@@ -0,0 +1,52 @@+# three.ws integrations++First-party plugins that drive the public **three.ws Forge** generation pipeline+(`/api/forge`) from inside the tools artists already use — so a model can be+generated without leaving the DCC.++| Plugin | Folder | Host |+|---|---|---|+| Blender add-on | [`blender/three_ws/`](blender/three_ws/) | Blender 4.0+ |+| ComfyUI nodes | [`comfyui/three_ws_nodes/`](comfyui/three_ws_nodes/) | ComfyUI |++Both speak to the same auth-free endpoints:++- `POST /api/forge` — text→3D and image→3D+- `GET /api/forge?job=<id>` — poll+- `GET /api/forge?catalog` — tier/backend matrix+- `POST /api/forge-upload` — presigned image upload (image→3D)++The **image pipeline** (FLUX→TRELLIS) is free and platform-keyed. The+**geometry pipeline** (Meshy/Tripo) is BYOK — supply your own provider key in+the add-on preferences / node input and it travels as `x-forge-provider-key`.++## Single source of truth++The Forge contract lives in exactly one file:+[`_pyclient/three_ws_client.py`](_pyclient/three_ws_client.py) — stdlib-only+(`urllib`), so it runs unmodified in Blender's bundled Python and in ComfyUI with+no `pip install`. Each plugin ships a **byte-identical vendored copy** so it stays+self-contained and distributable (a Blender zip / a ComfyUI clone).++`_pyclient/test_no_drift.py` fails CI if a copy drifts. To update the client,+edit the canonical file and re-copy:++```bash+cp integrations/_pyclient/three_ws_client.py integrations/blender/three_ws/three_ws_client.py+cp integrations/_pyclient/three_ws_client.py integrations/comfyui/three_ws_nodes/three_ws_client.py+```++## Tests++No live network — every test runs an in-process stub of the Forge contract.++```bash+# shared client + drift guard+python -m unittest discover -s integrations/_pyclient -p 'test_*.py'++# comfyui nodes+( cd integrations/comfyui/three_ws_nodes && python -m unittest test_nodes )+```++The Blender add-on is import-guarded on `bpy` (only present inside Blender); its+syntax is validated in CI via `ast.parse`.diff --git a/integrations/_pyclient/test_no_drift.py b/integrations/_pyclient/test_no_drift.pynew file mode 100644index 000000000..04db0a236--- /dev/null+++ b/integrations/_pyclient/test_no_drift.py@@ -0,0 +1,40 @@+"""Guard the single-source invariant for the vendored Forge client.++``three_ws_client.py`` is the one source of truth for the Forge contract. Each+plugin ships a byte-identical copy so it stays self-contained and distributable+(a Blender add-on zip / a ComfyUI custom_nodes clone). This test fails if any+copy drifts from the canonical file — re-copy it and the contract stays in lockstep.+"""++from __future__ import annotations++import os+import unittest++_HERE = os.path.dirname(os.path.abspath(__file__))+_ROOT = os.path.dirname(_HERE) # integrations/+_CANONICAL = os.path.join(_HERE, "three_ws_client.py")+_VENDORED = [+ os.path.join(_ROOT, "blender", "three_ws", "three_ws_client.py"),+ os.path.join(_ROOT, "comfyui", "three_ws_nodes", "three_ws_client.py"),+]+++class NoDriftTest(unittest.TestCase):+ def test_vendored_copies_match_canonical(self):+ with open(_CANONICAL, "rb") as fh:+ canonical = fh.read()+ for path in _VENDORED:+ self.assertTrue(os.path.isfile(path), f"missing vendored copy: {path}")+ with open(path, "rb") as fh:+ copy = fh.read()+ self.assertEqual(+ canonical,+ copy,+ f"{path} drifted from the canonical three_ws_client.py — "+ f"re-copy it: cp {_CANONICAL} {path}",+ )+++if __name__ == "__main__":+ unittest.main()diff --git a/integrations/blender/README.md b/integrations/blender/README.mdnew file mode 100644index 000000000..88e826334--- /dev/null+++ b/integrations/blender/README.md@@ -0,0 +1,44 @@+# three.ws — Blender add-on++Generate a 3D model from a text prompt or a reference image with three.ws Forge,+directly inside Blender. The model is reconstructed on three.ws and imported into+your scene, selected and framed.++## Install++1. Zip the add-on folder so the archive contains the `three_ws/` directory:+ ```bash+ cd integrations/blender+ zip -r three_ws.zip three_ws+ ```+2. In Blender: **Edit ▸ Preferences ▸ Add-ons ▸ Install…**, pick `three_ws.zip`,+ then tick **three.ws** to enable it.+3. (Optional) In the add-on's preferences, set:+ - **API URL** — defaults to `https://three.ws`. Point at your own deployment+ if self-hosting.+ - **Provider API key** — only needed for the Meshy/Tripo *geometry* pipeline.+ The default *image* pipeline (FLUX→TRELLIS) is free.++## Use++Open the 3D Viewport sidebar (press **N**) → **three.ws** tab.++- **Text** mode: type a prompt, pick a quality tier, hit **Generate 3D model**.+- **Image** mode: choose a PNG/JPEG/WebP reference, hit **Generate**.+- **Pipeline**: *Image* (free, FLUX→TRELLIS) or *Geometry* (Meshy/Tripo, needs a+ provider key).+- **Test connection** confirms the deployment is reachable and lists live backends.++Generation runs on a background thread — Blender stays responsive, the panel+shows the real job status + elapsed seconds, and **Esc** cancels. The GLB import+happens on Blender's main thread when the job completes (bpy is not thread-safe).++## Notes++- Nothing is mocked: the panel reflects the real job state, and failures+ (unreachable deployment, missing provider key, generation error) surface as+ Blender error reports — never a fake model.+- The image pipeline requires object storage configured on the deployment for+ upload; if it isn't, the add-on reports that clearly.+- The Forge client (`three_ws_client.py`) is a vendored copy of+ `integrations/_pyclient/three_ws_client.py` — see the integrations README.diff --git a/integrations/comfyui/README.md b/integrations/comfyui/README.mdnew file mode 100644index 000000000..9d95adc34--- /dev/null+++ b/integrations/comfyui/README.md@@ -0,0 +1,45 @@+# three.ws — ComfyUI nodes++Two nodes that drive the three.ws Forge pipeline from a ComfyUI graph:++- **three.ws Text→3D** — prompt → `glb_path`+- **three.ws Image→3D** — `IMAGE` → `glb_path`++The `glb_path` STRING output is a real `.glb` written to ComfyUI's output+directory — feed it to any 3D node (e.g. ComfyUI-3D-Pack viewers/savers) or use+it as the final artifact.++## Install++```bash+cd ComfyUI/custom_nodes+git clone <this-repo> three_ws_tmp # or copy the folder+cp -r three_ws_tmp/integrations/comfyui/three_ws_nodes ./three_ws_nodes+rm -rf three_ws_tmp+```++Or simply copy `integrations/comfyui/three_ws_nodes/` into+`ComfyUI/custom_nodes/`. Restart ComfyUI. The nodes appear under the **three.ws**+category. They use only numpy + Pillow (already shipped with ComfyUI) plus the+Python standard library — nothing to install.++## Inputs++- **tier** — `draft` / `standard` / `high`.+- **pipeline** — `image` (free, FLUX→TRELLIS) or `geometry` (Meshy/Tripo, BYOK).+- **backend** — `auto`, or a specific backend.+- **api_url** — defaults to `https://three.ws`.+- **provider_key** — required only for the geometry pipeline.++## Caching++ComfyUI re-runs a node only when its inputs change, and the node also short-+circuits to the on-disk GLB when an identical request was already generated+(status `cached`). Change any input to force a fresh generation.++## Notes++- Failures raise a clear `RuntimeError` (shown in the ComfyUI error toast) — the+ node never emits a placeholder model.+- The Forge client (`three_ws_client.py`) is a vendored copy of+ `integrations/_pyclient/three_ws_client.py` — see the integrations README.diff --git a/integrations/comfyui/three_ws_nodes/__init__.py b/integrations/comfyui/three_ws_nodes/__init__.pynew file mode 100644index 000000000..d0e654998--- /dev/null+++ b/integrations/comfyui/three_ws_nodes/__init__.py@@ -0,0 +1,9 @@+"""three.ws Forge nodes for ComfyUI.++Drop this folder into ``ComfyUI/custom_nodes/`` and restart ComfyUI. Two nodes+appear under the "three.ws" category: Text→3D and Image→3D.+"""++from .nodes import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS++__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS"]diff --git a/integrations/comfyui/three_ws_nodes/nodes.py b/integrations/comfyui/three_ws_nodes/nodes.pynew file mode 100644index 000000000..fb84e16f2--- /dev/null+++ b/integrations/comfyui/three_ws_nodes/nodes.py@@ -0,0 +1,184 @@+"""three.ws Forge nodes for ComfyUI.++Two nodes drive the public three.ws Forge pipeline:++* **three.ws Text→3D** — prompt → GLB path+* **three.ws Image→3D** — IMAGE → GLB path++Each submits a real generation job, polls to completion, and downloads the GLB+into ComfyUI's output directory. The ``glb_path`` STRING output can feed any 3D+node (e.g. ComfyUI-3D-Pack viewers/savers). Generation is free on the image+pipeline (FLUX→TRELLIS); the geometry pipeline (Meshy/Tripo) uses your own+provider key.++Caching: ComfyUI re-runs a node only when its inputs change, so an identical+prompt+settings returns the cached GLB instead of re-generating. Change any+input (or the ``label``) to force a fresh run.+"""++import hashlib+import io+import os++from .three_ws_client import BACKENDS, DEFAULT_BASE_URL, PATHS, TIERS, ThreeWSClient, ThreeWSError++_TIER_ITEMS = list(TIERS)+_PATH_ITEMS = list(PATHS)+_BACKEND_ITEMS = ["auto"] + list(BACKENDS)+_ASPECTS = ["1:1", "4:3", "3:4", "16:9", "9:16"]+++def _output_dir():+ """ComfyUI output dir when running inside ComfyUI, else a temp dir."""+ try:+ import folder_paths # provided by ComfyUI at runtime+ return folder_paths.get_output_directory()+ except Exception:+ import tempfile+ d = os.path.join(tempfile.gettempdir(), "three-ws")+ os.makedirs(d, exist_ok=True)+ return d+++def _progress_reporter():+ """Return a callable(status, elapsed) wired to ComfyUI's progress bar if present."""+ try:+ from comfy.utils import ProgressBar+ bar = ProgressBar(100)+ seen = {"v": 0}++ def report(status, elapsed):+ # No real percentage from the job; nudge the bar so the UI shows life.+ seen["v"] = min(95, seen["v"] + 3)+ bar.update_absolute(seen["v"])+ return report+ except Exception:+ return lambda status, elapsed: None+++def _client(api_url, provider_key):+ return ThreeWSClient(+ (api_url or DEFAULT_BASE_URL).strip(),+ provider_key=(provider_key or "").strip() or None,+ )+++def _dest(prefix, key_material):+ digest = hashlib.sha256(key_material.encode("utf-8")).hexdigest()[:16]+ return os.path.join(_output_dir(), f"{prefix}-{digest}.glb")+++class ThreeWSTextTo3D:+ """Generate a 3D model from a text prompt via three.ws Forge."""++ CATEGORY = "three.ws"+ RETURN_TYPES = ("STRING", "STRING")+ RETURN_NAMES = ("glb_path", "status")+ FUNCTION = "generate"++ @classmethod+ def INPUT_TYPES(cls):+ return {+ "required": {+ "prompt": ("STRING", {"multiline": True, "default": "a brass steampunk owl"}),+ "tier": (_TIER_ITEMS, {"default": "standard"}),+ "pipeline": (_PATH_ITEMS, {"default": "image"}),+ "backend": (_BACKEND_ITEMS, {"default": "auto"}),+ "aspect_ratio": (_ASPECTS, {"default": "1:1"}),+ },+ "optional": {+ "api_url": ("STRING", {"default": DEFAULT_BASE_URL}),+ "provider_key": ("STRING", {"default": ""}),+ },+ }++ def generate(self, prompt, tier, pipeline, backend, aspect_ratio, api_url="", provider_key=""):+ client = _client(api_url, provider_key)+ dest = _dest("text3d", f"{prompt}|{tier}|{pipeline}|{backend}|{aspect_ratio}|{api_url}")+ if os.path.isfile(dest):+ return (dest, "cached")+ try:+ glb_url = client.generate_text_to_3d(+ prompt, tier=tier, path=pipeline,+ backend=None if backend == "auto" else backend,+ aspect_ratio=aspect_ratio, on_progress=_progress_reporter(),+ )+ client.download(glb_url, dest)+ except ThreeWSError as exc:+ raise RuntimeError(f"three.ws Forge: {exc.message}") from exc+ return (dest, "done")+++class ThreeWSImageTo3D:+ """Generate a 3D model from a reference image via three.ws Forge."""++ CATEGORY = "three.ws"+ RETURN_TYPES = ("STRING", "STRING")+ RETURN_NAMES = ("glb_path", "status")+ FUNCTION = "generate"++ @classmethod+ def INPUT_TYPES(cls):+ return {+ "required": {+ "image": ("IMAGE",),+ "tier": (_TIER_ITEMS, {"default": "standard"}),+ "pipeline": (_PATH_ITEMS, {"default": "image"}),+ "backend": (_BACKEND_ITEMS, {"default": "auto"}),+ },+ "optional": {+ "prompt": ("STRING", {"multiline": True, "default": ""}),+ "api_url": ("STRING", {"default": DEFAULT_BASE_URL}),+ "provider_key": ("STRING", {"default": ""}),+ },+ }++ def generate(self, image, tier, pipeline, backend, prompt="", api_url="", provider_key=""):+ png_bytes = _image_tensor_to_png(image)+ client = _client(api_url, provider_key)+ key = hashlib.sha256(png_bytes).hexdigest()[:12]+ dest = _dest("image3d", f"{key}|{prompt}|{tier}|{pipeline}|{backend}|{api_url}")+ if os.path.isfile(dest):+ return (dest, "cached")+ try:+ glb_url = client.generate_image_to_3d(+ png_bytes, "image/png", prompt=prompt, tier=tier, path=pipeline,+ backend=None if backend == "auto" else backend, on_progress=_progress_reporter(),+ )+ client.download(glb_url, dest)+ except ThreeWSError as exc:+ raise RuntimeError(f"three.ws Forge: {exc.message}") from exc+ return (dest, "done")+++def _image_tensor_to_png(image) -> bytes:+ """ComfyUI IMAGE tensor (B,H,W,C float 0..1) → PNG bytes of the first frame."""+ try:+ import numpy as np+ from PIL import Image+ except ImportError as exc: # pragma: no cover - ComfyUI always ships these+ raise RuntimeError("three.ws Image→3D needs numpy + Pillow.") from exc++ arr = image+ # Torch tensor or numpy array — normalize to a numpy HWC uint8 frame.+ if hasattr(arr, "cpu"):+ arr = arr.cpu().numpy()+ arr = np.asarray(arr)+ if arr.ndim == 4:+ arr = arr[0]+ arr = np.clip(arr * 255.0, 0, 255).astype("uint8")+ img = Image.fromarray(arr)+ buf = io.BytesIO()+ img.save(buf, format="PNG")+ return buf.getvalue()+++NODE_CLASS_MAPPINGS = {+ "ThreeWSTextTo3D": ThreeWSTextTo3D,+ "ThreeWSImageTo3D": ThreeWSImageTo3D,+}++NODE_DISPLAY_NAME_MAPPINGS = {+ "ThreeWSTextTo3D": "three.ws Text→3D",+ "ThreeWSImageTo3D": "three.ws Image→3D",+}diff --git a/integrations/comfyui/three_ws_nodes/requirements.txt b/integrations/comfyui/three_ws_nodes/requirements.txtnew file mode 100644index 000000000..0dae1acb6--- /dev/null+++ b/integrations/comfyui/three_ws_nodes/requirements.txt@@ -0,0 +1,5 @@+# The three.ws nodes use only the Python standard library plus numpy + Pillow,+# both of which ComfyUI already ships. Nothing to install in a normal ComfyUI+# environment; these are listed for completeness / non-ComfyUI hosts.+numpy+Pillowdiff --git a/integrations/comfyui/three_ws_nodes/test_nodes.py b/integrations/comfyui/three_ws_nodes/test_nodes.pynew file mode 100644index 000000000..7b247f14d--- /dev/null+++ b/integrations/comfyui/three_ws_nodes/test_nodes.py@@ -0,0 +1,129 @@+"""Smoke test for the ComfyUI nodes against a stub Forge server.++Validates that the nodes submit, poll, download, and cache — without ComfyUI,+torch, or a live network. The IMAGE path is exercised with a plain numpy array+(the node accepts anything array-like). Run:+ python -m unittest integrations/comfyui/three_ws_nodes/test_nodes.py+"""++from __future__ import annotations++import json+import os+import sys+import threading+import unittest+import urllib.parse+from http.server import BaseHTTPRequestHandler, HTTPServer++# Import the node module as part of its package so its relative import+# (`from .three_ws_client import ...`) resolves the same way ComfyUI loads it.+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))++from three_ws_nodes import nodes # noqa: E402+++class _Handler(BaseHTTPRequestHandler):+ def log_message(self, *a):+ pass++ def _send(self, status, obj):+ body = json.dumps(obj).encode()+ self.send_response(status)+ self.send_header("content-type", "application/json")+ self.send_header("content-length", str(len(body)))+ self.end_headers()+ self.wfile.write(body)++ def do_GET(self):+ st = self.server.state+ p = urllib.parse.urlparse(self.path)+ q = urllib.parse.parse_qs(p.query, keep_blank_values=True)+ if p.path == "/api/forge" and "job" in q:+ return self._send(200, {"job_id": q["job"][0], "status": "done", "glb_url": st["glb_url"]})+ if p.path == "/_glb":+ data = b"glb-bytes"+ self.send_response(200)+ self.send_header("content-length", str(len(data)))+ self.end_headers()+ self.wfile.write(data)+ return+ return self._send(404, {"error": "nf"})++ def do_POST(self):+ st = self.server.state+ length = int(self.headers.get("content-length", 0))+ self.rfile.read(length)+ p = urllib.parse.urlparse(self.path)+ if p.path == "/api/forge-upload":+ host = f"http://127.0.0.1:{self.server.server_address[1]}"+ return self._send(200, {+ "upload_url": f"{host}/_put",+ "public_url": "https://cdn.example/y.png",+ "headers": {"content-type": "image/png"},+ })+ if p.path == "/api/forge":+ st["submits"] += 1+ return self._send(200, {"job_id": "j1", "status": "queued"})+ return self._send(404, {"error": "nf"})++ def do_PUT(self):+ length = int(self.headers.get("content-length", 0))+ self.rfile.read(length)+ self.send_response(200)+ self.send_header("content-length", "0")+ self.end_headers()+++class NodesTest(unittest.TestCase):+ def setUp(self):+ self.server = HTTPServer(("127.0.0.1", 0), _Handler)+ port = self.server.server_address[1]+ self.server.state = {"glb_url": f"http://127.0.0.1:{port}/_glb", "submits": 0}+ self.base = f"http://127.0.0.1:{port}"+ self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)+ self.thread.start()++ def tearDown(self):+ self.server.shutdown()+ self.server.server_close()+ self.thread.join(timeout=2)++ def test_text_to_3d_node(self):+ node = nodes.ThreeWSTextTo3D()+ glb_path, status = node.generate(+ "a unique prompt for caching test 9921", "draft", "image", "auto", "1:1", api_url=self.base+ )+ self.assertTrue(os.path.isfile(glb_path))+ self.assertEqual(status, "done")+ with open(glb_path, "rb") as fh:+ self.assertEqual(fh.read(), b"glb-bytes")+ # Second identical call hits the on-disk cache, no new submit.+ before = self.server.state["submits"]+ _, status2 = node.generate(+ "a unique prompt for caching test 9921", "draft", "image", "auto", "1:1", api_url=self.base+ )+ self.assertEqual(status2, "cached")+ self.assertEqual(self.server.state["submits"], before)+ os.remove(glb_path)++ def test_image_to_3d_node(self):+ try:+ import numpy as np+ except ImportError:+ self.skipTest("numpy not available")+ img = np.zeros((1, 4, 4, 3), dtype="float32")+ node = nodes.ThreeWSImageTo3D()+ glb_path, status = node.generate(img, "draft", "image", "auto", prompt="", api_url=self.base)+ self.assertTrue(os.path.isfile(glb_path))+ self.assertEqual(status, "done")+ os.remove(glb_path)++ def test_node_mappings(self):+ self.assertIn("ThreeWSTextTo3D", nodes.NODE_CLASS_MAPPINGS)+ self.assertIn("ThreeWSImageTo3D", nodes.NODE_CLASS_MAPPINGS)+ self.assertEqual(nodes.NODE_DISPLAY_NAME_MAPPINGS["ThreeWSTextTo3D"], "three.ws Text→3D")+++if __name__ == "__main__":+ unittest.main()diff --git a/public/nav.js b/public/nav.jsindex 1846b54fd..49e46786d 100644--- a/public/nav.js+++ b/public/nav.js@@ -224,30 +224,74 @@ function initActivePage(root) {}// ── Auth-aware CTAs ──────────────────────────────────────────────────────────-// When a signed-in hint exists, swap "Sign in" for the dashboard/My Agents-// entry points. Mirrors the hint written by the account layer.-function initAuthHint(root) {+// Swap "Sign in" for the dashboard / My Agents entry points when the visitor is+// authenticated. The localStorage hint (written by the login flows) gives an+// instant, flicker-free first paint for returning users; the server session at+// /api/auth/me is the source of truth and reconciles the UI afterwards. That+// reconciliation is what fixes the "I'm signed in but the nav still says Sign+// in" case — any session without a local hint (Google/SAML redirect, a fresh+// browser or device, cleared storage) is now resolved against the real cookie.+const AUTH_HINT_KEY = '3dagent:auth-hint';++function applyAuthState(root, { authed, name }) {+ const signIn = root.querySelector('#home-nav-cta');+ if (signIn) signIn.hidden = authed;+ const myAgents = root.querySelector('#home-nav-my-agents-li');+ if (myAgents) myAgents.hidden = !authed;+ const console = root.querySelector('#home-nav-user');+ if (console) console.textContent = authed && name ? name : 'Console →';++ // Mobile drawer equivalents.+ const drawerSignIn = root.querySelector('#home-nav-drawer-cta');+ if (drawerSignIn) drawerSignIn.hidden = authed;+ const drawerMyAgents = root.querySelector('#home-nav-drawer-my-agents');+ if (drawerMyAgents) drawerMyAgents.hidden = !authed;+}++function readAuthHint() {+ try {+ const raw = localStorage.getItem(AUTH_HINT_KEY);+ if (!raw) return null;+ return JSON.parse(raw);+ } catch (_) {+ return null;+ }+}++function writeAuthHint(hint) {try {- const raw = localStorage.getItem('3dagent:auth-hint');- if (!raw) return;- const { authed, name } = JSON.parse(raw);- if (!authed) return;-- const signIn = root.querySelector('#home-nav-cta');- if (signIn) signIn.hidden = true;- const myAgents = root.querySelector('#home-nav-my-agents-li');- if (myAgents) myAgents.hidden = false;- const console = root.querySelector('#home-nav-user');- if (console && name) console.textContent = name;-- // Mobile drawer equivalents.- const drawerSignIn = root.querySelector('#home-nav-drawer-cta');- if (drawerSignIn) drawerSignIn.hidden = true;- const drawerMyAgents = root.querySelector('#home-nav-drawer-my-agents');- if (drawerMyAgents) drawerMyAgents.hidden = false;+ if (hint) localStorage.setItem(AUTH_HINT_KEY, JSON.stringify(hint));+ else localStorage.removeItem(AUTH_HINT_KEY);} catch (_) {}}+function initAuthHint(root) {+ // 1. Instant first paint from the local hint, if any — no network wait.+ const hint = readAuthHint();+ if (hint && hint.authed) applyAuthState(root, { authed: true, name: hint.name });++ // 2. Reconcile against the real session. /api/auth/me returns { user } when+ // signed in and { user: null } (or 401 for a stale cookie) otherwise.+ fetch('/api/auth/me', { credentials: 'include' })+ .then((r) => (r.ok ? r.json() : null))+ .then((data) => {+ const user = data && data.user;+ if (user) {+ const name = user.display_name || user.username || hint?.name || null;+ applyAuthState(root, { authed: true, name });+ writeAuthHint({ authed: true, name });+ } else {+ // No live session — revert any optimistic swap and drop the stale hint.+ applyAuthState(root, { authed: false });+ writeAuthHint(null);+ }+ })+ .catch(() => {+ // Network/transient failure: leave the optimistic hint paint untouched+ // rather than flashing the visitor back to a signed-out nav.+ });+}+// ── Walk Companion toggle ─────────────────────────────────────────────────────// Loads the stable, unhashed /walk-companion.js module (built from// src/walk-companion.js — see vite.config.js) only when enabled, so pages pay