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
refactor(forge): share base64 image persistence through the image-persist lib
nirholas27f201adde07
diff --git a/api/_lib/forge-reference-image.js b/api/_lib/forge-reference-image.jsindex dfa609109..e6354206f 100644--- a/api/_lib/forge-reference-image.js+++ b/api/_lib/forge-reference-image.js@@ -56,7 +56,7 @@import { createHash } from 'node:crypto';import { getGcpAccessToken } from './gcp-auth.js';-import { putObject, publicUrl } from './r2.js';+import { persistImageBase64 } from './image-persist.js';import { subjectNegativePrompt } from '../forge-enhance.js';import { isProviderRefusal } from './ai-image-lanes.js';import { textToImage } from '../_mcp3d/text-to-image.js';@@ -177,20 +177,6 @@ export function buildReferenceInstruction(prompt, negativePrompt) {return lines.join(' ');}-// Persist a base64 image to R2 and return a durable public https URL. The 3D-// backends take URLs (Replicate caps inline data URIs at ~256 KB), so neither-// the Vertex inline data nor a NIM artifact can be forwarded as-is. Format is-// sniffed from the magic bytes so the key extension and Content-Type match the-// real payload (Gemini image returns PNG; sniff keeps it correct if that changes).-async function persistImageBase64(b64) {- const body = Buffer.from(b64, 'base64');- const isJpeg = body.length > 2 && body[0] === 0xff && body[1] === 0xd8 && body[2] === 0xff;- const ext = isJpeg ? 'jpg' : 'png';- const key = `forge/refs/${globalThis.crypto.randomUUID()}.${ext}`;- await putObject({ key, body, contentType: isJpeg ? 'image/jpeg' : 'image/png' });- return publicUrl(key);-}-// One Vertex Gemini image generation. Returns { b64, mime } on success; throws a// designed error on any failure so the caller can fall through. Retries once// without imageConfig.imageSize if the tier rejects that field (defensive: thediff --git a/docs/forge-pipeline.md b/docs/forge-pipeline.mdindex 69ce5d327..b8d8d3217 100644--- a/docs/forge-pipeline.md+++ b/docs/forge-pipeline.md@@ -217,6 +217,8 @@ The env vars that shape a deployment (production values live on the Cloud Run se| `FORGE_SELFHOST_PRIMARY` | Default off; hoist self-host lanes above hosted free lanes. || `JWT_SECRET` | Signs job handle tokens. || `DATABASE_URL`, R2 `S3_*` config | Persistence and durable storage; both fail soft. |+| `LIVEPEER_FEDERATION_ENABLED` | Default off; inserts the federated Livepeer text-to-image lane (`api/_providers/livepeer.js`) into the reference-image chain after the free lanes and before the paid Replicate backstop. See [ops/livepeer-federation.md](./ops/livepeer-federation.md) for the measured state before flipping it. |+| `LIVEPEER_API_KEY`, `LIVEPEER_GATEWAY_URL`, `LIVEPEER_T2I_MODEL` | Studio gateway key (absent today), gateway base-URL override, and pipeline model override (`ByteDance/SDXL-Lightning` default) for the federated lane. |Fast diagnostics: `forge_creations` carries per-generation backend, status, error, and prompt, so it is the quickest ground truth for generation issues. `GET /api/forge?health=1` shows the live lane picture.diff --git a/tests/api/regenerate-status.test.js b/tests/api/regenerate-status.test.jsnew file mode 100644index 000000000..fc69559f8--- /dev/null+++ b/tests/api/regenerate-status.test.js@@ -0,0 +1,209 @@+// Contract coverage for GET /api/avatars/regenerate-status, the endpoint a+// /scan or /create/selfie client polls from capture submission to a stored+// rigged GLB. The GPU worker fleet and database are stubbed at their module+// boundaries; the handler itself (auth, job lookup, provider poll, error+// masking, finalize dispatch) runs for real.+//+// What this pins, and why each case is the thing that breaks:+//+// 1. queued -> running -> done progression: a job the worker just finished+// is finalized through finalizeReconstructStage and the client receives+// the new avatar id, the terminal proof the capture became a model.+// 2. The input-error relay: the worker classifies a bad capture ("no face+// detected") as error_kind 'input' whose copy is caller-facing by+// contract; the endpoint must return that copy verbatim instead of+// collapsing it into the generic retry message, or every user with a+// faceless photo is told "try again" forever.+// 3. Internal failures stay masked: error_kind 'internal' (or absent)+// collapses to neutral copy, since the raw value can carry a vendor name+// or correlation id meant for operators only.+// 4. Ownership: another user's job id is a 404, not an oracle.+// 5. The rig chain: a job parked at 'rigging' polls its child rig job via+// pollRiggingStage and reports the real post-call status.++import { describe, it, expect, vi, beforeEach } from 'vitest';++vi.mock('../api/_lib/zauth.js', () => ({ instrument: () => {}, drain: async () => {} }));+vi.mock('../api/_lib/sentry.js', () => ({ captureException: () => {} }));++const state = {+ job: null,+ userId: 'u1',+ statusReturn: null,+ persisted: [],+};++function resetState() {+ state.job = null;+ state.userId = 'u1';+ state.statusReturn = null;+ state.persisted = [];+}++// Job lookup + the in-flight status persist update. Branching on query text,+// same pattern as the auto-rig SSRF suite.+const sqlMock = vi.fn(async (strings, ...values) => {+ const text = (Array.isArray(strings) ? strings.join('?') : String(strings)).toLowerCase();+ if (text.includes('update avatar_regen_jobs')) {+ state.persisted.push({ status: values[0], result_glb_url: values[1], error: values[2], error_kind: values[3] });+ return [];+ }+ if (text.includes('from avatar_regen_jobs')) {+ return state.job ? [state.job] : [];+ }+ return [];+});+vi.mock('../api/_lib/db.js', () => ({ sql: (...a) => sqlMock(...a), isDbUnavailableError: () => false, isDbCapacityError: () => false }));++vi.mock('../api/_lib/auth.js', () => ({+ getSessionUser: async () => ({ id: state.userId }),+ authenticateBearer: async () => null,+ extractBearer: () => null,+ hasScope: () => true,+}));++const providerInstance = { status: vi.fn(async () => state.statusReturn) };+vi.mock('../api/_lib/regen-provider.js', () => ({+ getRegenProvider: async () => ({ name: 'gcp', instance: providerInstance }),+ getRegenProviderForMode: async () => ({ name: 'gcp', instance: providerInstance }),+ getRegenProviderForJob: async () => ({ name: 'gcp', instance: providerInstance }),+ getRegenProviderByName: async () => ({ name: 'gcp', instance: providerInstance }),+ getRegenProviderCandidates: async () => [{ name: 'gcp', instance: providerInstance }],+ BYOK_REGEN_PROVIDERS: [],+}));++const finalizeReconstructStageMock = vi.fn(async () => ({ status: 'done', resultAvatarId: 'avatar-1' }));+const pollRiggingStageMock = vi.fn(async () => ({ status: 'rigging' }));+vi.mock('../api/_lib/reconstruct-finalize.js', () => ({+ finalizeReconstructStage: (...a) => finalizeReconstructStageMock(...a),+ pollRiggingStage: (...a) => pollRiggingStageMock(...a),+}));+vi.mock('../api/_lib/auto-rig.js', () => ({+ finalizeAutoRigStage: vi.fn(async () => ({ status: 'done', resultAvatarId: 'sib-1' })),+ rigInfoIsRigged: () => false,+}));++const { dispatch } = await import('../api/avatars/_actions.js');++function makeRes() {+ return {+ statusCode: 200,+ _h: {},+ headersSent: false,+ writableEnded: false,+ setHeader(k, v) { this._h[k.toLowerCase()] = v; },+ getHeader(k) { return this._h[k.toLowerCase()]; },+ end(body) { this._body = body; this.writableEnded = true; },+ };+}++async function poll(jobId) {+ const req = { method: 'GET', url: `/api/avatars/regenerate-status?jobId=${jobId}`, headers: {} };+ const res = makeRes();+ await dispatch('regenerate-status', req, res);+ return { statusCode: res.statusCode, body: JSON.parse(res._body) };+}++function baseJob(overrides = {}) {+ return {+ job_id: 'gcp-job-1',+ user_id: 'u1',+ status: 'running',+ result_avatar_id: null,+ result_glb_url: null,+ error: null,+ error_kind: null,+ provider: 'gcp',+ ext_job_id: 'ext-1',+ created_at: new Date().toISOString(),+ mode: 'reconstruct',+ params: {},+ source_avatar_id: null,+ ...overrides,+ };+}++const VALID_GLB = 'https://storage.googleapis.com/three-ws-avatar-reconstructions/avatars/x.glb';++beforeEach(() => {+ vi.clearAllMocks();+ resetState();+});++describe('regenerate-status — capture-to-avatar poll contract', () => {+ it('finalizes a finished worker job and returns the new avatar id', async () => {+ state.job = baseJob();+ state.statusReturn = { status: 'done', resultGlbUrl: VALID_GLB };+ const { statusCode, body } = await poll('gcp-job-1');+ expect(statusCode).toBe(200);+ expect(body.status).toBe('done');+ expect(body.resultAvatarId).toBe('avatar-1');+ expect(finalizeReconstructStageMock).toHaveBeenCalledTimes(1);+ // The fresh worker verdict is persisted before finalize runs, so a+ // finalize crash still leaves the cron sweep a durable URL to resume from.+ expect(state.persisted[0]).toMatchObject({ status: 'done', result_glb_url: VALID_GLB });+ });++ it('relays a caller-facing input error verbatim instead of masking it', async () => {+ state.job = baseJob();+ state.statusReturn = {+ status: 'failed',+ error: 'no face detected in any of the provided photos',+ errorKind: 'input',+ };+ const { body } = await poll('gcp-job-1');+ expect(body.status).toBe('failed');+ expect(body.error).toBe('no face detected in any of the provided photos');+ expect(state.persisted[0]).toMatchObject({ status: 'failed', error_kind: 'input' });+ });++ it('masks an internal worker failure into neutral retry copy', async () => {+ state.job = baseJob();+ state.statusReturn = {+ status: 'failed',+ error: 'internal error (ref a73c09c9cb5b)',+ errorKind: 'internal',+ };+ const { body } = await poll('gcp-job-1');+ expect(body.status).toBe('failed');+ expect(body.error).toBeTruthy();+ expect(body.error).not.toContain('a73c09c9cb5b');+ expect(body.error).not.toContain('internal error');+ });++ it('never returns a raw stored provider error to the client', async () => {+ state.job = baseJob({ status: 'failed', error: 'Replicate API 402: account out of credits', error_kind: null });+ const { body } = await poll('gcp-job-1');+ expect(body.status).toBe('failed');+ expect(body.error).not.toContain('Replicate');+ expect(body.error).not.toContain('402');+ });++ it("returns 404 for another user's job id", async () => {+ state.job = baseJob({ user_id: 'someone-else' });+ state.userId = 'u1';+ // The lookup is user-scoped at the SQL layer; simulate the empty result.+ state.job = null;+ const { statusCode, body } = await poll('gcp-job-1');+ expect(statusCode).toBe(404);+ expect(body.error).toBe('not_found');+ });++ it('polls the child rig job for a job parked at rigging', async () => {+ state.job = baseJob({ status: 'rigging', params: { rig: { extJobId: 'rig-9', unriggedUrl: VALID_GLB, storageKey: 'k', slug: 's' } } });+ pollRiggingStageMock.mockResolvedValueOnce({ status: 'done', resultAvatarId: 'avatar-rigged' });+ const { body } = await poll('gcp-job-1');+ expect(pollRiggingStageMock).toHaveBeenCalledTimes(1);+ expect(body.status).toBe('done');+ expect(body.resultAvatarId).toBe('avatar-rigged');+ });++ it('keeps polling live for a job the worker is still running', async () => {+ state.job = baseJob({ status: 'queued' });+ state.statusReturn = { status: 'running' };+ const { body } = await poll('gcp-job-1');+ expect(body.status).toBe('running');+ expect(finalizeReconstructStageMock).not.toHaveBeenCalled();+ expect(state.persisted[0]).toMatchObject({ status: 'running' });+ });+});diff --git a/tests/image-persist.test.js b/tests/image-persist.test.jsnew file mode 100644index 000000000..d39ab6b10--- /dev/null+++ b/tests/image-persist.test.js@@ -0,0 +1,78 @@+// Shared image persistence (api/_lib/image-persist.js) unit tests. The module+// is the single home for the "every generated image becomes a durable R2 URL"+// rule the NIM FLUX lane, the Vertex reference-image lane, and the Livepeer+// federation provider all share.++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';++import { looksLikeImageBytes, sniffImageFormat, persistImageBase64, persistImageBytes } from '../api/_lib/image-persist.js';+import { putObject, publicUrl } from '../api/_lib/r2.js';++vi.mock('../api/_lib/r2.js', () => ({+ putObject: vi.fn(async () => ({})),+ publicUrl: vi.fn((key) => `https://cdn.example.com/${key}`),+}));++const PNG_SIG = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];+const JPEG_SIG = [0xff, 0xd8, 0xff, 0xe0];++beforeEach(() => {+ vi.clearAllMocks();+});+afterEach(() => {+ vi.resetAllMocks();+});++describe('sniffImageFormat', () => {+ it('detects JPEG from the FF D8 FF magic header', () => {+ expect(sniffImageFormat(Buffer.from([...JPEG_SIG, 0, 1, 2]))).toBe('jpg');+ });++ it('labels everything else png (the legacy default)', () => {+ expect(sniffImageFormat(Buffer.from([...PNG_SIG]))).toBe('png');+ expect(sniffImageFormat(Buffer.from([0x00, 0x01]))).toBe('png');+ });+});++describe('looksLikeImageBytes', () => {+ it('accepts real JPEG and PNG signatures', () => {+ expect(looksLikeImageBytes(Buffer.from([...JPEG_SIG, 0, 1]))).toBe(true);+ expect(looksLikeImageBytes(Buffer.from([...PNG_SIG, 0, 1]))).toBe(true);+ });++ it('rejects text, tiny payloads, and empty buffers', () => {+ expect(looksLikeImageBytes(Buffer.from('<html>error</html>'))).toBe(false);+ expect(looksLikeImageBytes(Buffer.from([0xff]))).toBe(false);+ expect(looksLikeImageBytes(Buffer.alloc(0))).toBe(false);+ expect(looksLikeImageBytes(null)).toBe(false);+ });+});++describe('persistImageBytes', () => {+ it('writes under forge/refs/ with a sniffed extension and content type', async () => {+ const body = Buffer.from([...JPEG_SIG, 9, 9, 9]);+ const url = await persistImageBytes(body);+ const call = putObject.mock.calls[0][0];+ expect(call.key).toMatch(/^forge\/refs\/[0-9a-f-]+\.jpg$/);+ expect(call.contentType).toBe('image/jpeg');+ expect(Buffer.compare(call.body, body)).toBe(0);+ expect(url).toBe(`https://cdn.example.com/${call.key}`);+ });++ it('keeps png labeling for non-JPEG payloads', async () => {+ const body = Buffer.from([...PNG_SIG, 9, 9, 9]);+ await persistImageBytes(body);+ const call = putObject.mock.calls[0][0];+ expect(call.key).toMatch(/\.png$/);+ expect(call.contentType).toBe('image/png');+ });+});++describe('persistImageBase64', () => {+ it('decodes base64 and persists the decoded bytes', async () => {+ const body = Buffer.from([...PNG_SIG, 1, 2, 3, 4]);+ await persistImageBase64(body.toString('base64'));+ const call = putObject.mock.calls[0][0];+ expect(Buffer.compare(call.body, body)).toBe(0);+ });+});