Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat([issue-2952]): image-to-3D model records + create/generate/download endpoints
[._.]/ Adam Eivy3fc75b23b7a4
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex d485d69bc1..e49e1ac5bf 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,7 @@## 3D+- **[issue-2952] Turn a rendered image into a downloadable 3D mesh** — once TRELLIS.2 is installed, PortOS can now take one of your gallery images and render it into a real 3D model (a `.glb` mesh with PBR textures) entirely on-device. Each render is saved as its own record you can list, re-render, download, or delete, and it tracks live status (generating → ready, with progress) and its render history — so the 3D page has a working "create a 3D model" path end to end. The render only ever runs when you ask for it (never in the background), and is refused with a clear reason if the model isn't installed or your hardware can't run it.- **[issue-2953] Install image-to-3D models from a new 3D page** — a new **3D** page under Create lists the available image-to-3D models (starting with Microsoft TRELLIS.2) and shows each one's state at a glance: **Ready**, an **Install** button, or a note explaining why your hardware can't run it (e.g. needs an Apple Silicon Mac with enough memory). Installing runs entirely on-device with a live progress log — the same in-app install experience as the image generators — so you never touch a terminal. Reachable from the sidebar, ⌘K, and voice. (Turning one of your rendered images into a 3D mesh from this page lands next.)- **[issue-2952] TRELLIS.2 install now survives network hiccups** — the multi-gigabyte TRELLIS.2 install pulls from several code repositories, and a single dropped connection mid-download used to abort the whole thing with a cryptic error. The installer now automatically retries a step that fails from a transient network drop (with a short backoff), and already-downloaded pieces are kept — so a flaky connection resumes instead of starting over. If it still can't finish, the error now says plainly that it was a network hiccup and that clicking **Install** again picks up where it left off.diff --git a/server/index.js b/server/index.jsindex a138b48338..2a194eb07b 100644--- a/server/index.js+++ b/server/index.js@@ -386,6 +386,9 @@ app.use('/data/video-thumbnails', express.static(PATHS.videoThumbnails, ASSET_ST// Sprite Manager library previews (anchors, strips, atlases) render inline// via <img src="/data/sprites/<id>/<rel>"> (#2895).app.use('/data/sprites', express.static(PATHS.sprites, ASSET_STATIC_OPTS));+// Image-to-3D GLB meshes (#2952) — the /media/3d R3F viewer loads them inline+// via drei useGLTF from <model.assetPath> (/data/image-to-3d/<id>/model.glb).+app.use('/data/image-to-3d', express.static(PATHS.imageTo3d, ASSET_STATIC_OPTS));// Voice-over WAVs rendered by the pipeline audio stage — the AudioStage UI// pulls them inline via <audio src="/data/audio/<filename>">.app.use('/data/audio', express.static(PATHS.audio));diff --git a/server/lib/db/schema/audit.js b/server/lib/db/schema/audit.jsindex edbbf1a2a5..11c35e5ca6 100644--- a/server/lib/db/schema/audit.js+++ b/server/lib/db/schema/audit.js@@ -89,7 +89,7 @@ export const auditedTables = ['universes', 'universe_runs', 'pipeline_series', 'pipeline_issues','story_builder_sessions', 'writers_room_works', 'writers_room_folders','writers_room_draft_versions', 'catalog_ingredients', 'catalog_scraps',- 'catalog_user_types', 'creative_director_projects', 'threejs_models', 'mood_boards',+ 'catalog_user_types', 'creative_director_projects', 'threejs_models', 'image_to_3d_models', 'mood_boards','lora_training_runs', 'authors', 'artists', 'albums', 'tracks', 'tribe_people', 'tribe_touchpoints',];diff --git a/server/lib/db/schema/media.js b/server/lib/db/schema/media.jsindex 8904ed5ae0..d469679e07 100644--- a/server/lib/db/schema/media.js+++ b/server/lib/db/schema/media.js@@ -46,6 +46,26 @@ export const mediaDdl = [)`,`CREATE INDEX IF NOT EXISTS idx_threejs_models_live_updated ON threejs_models (updated_at DESC) WHERE deleted = FALSE`,+ // Image-to-3D models (issue #2952). The neural image→GLB record — distinct+ // from the procedural threejs_models above (that authors JS source; this+ // lands a real .glb mesh). Source gallery image reference, selected target+ // (trellis2 today), status, run history, and the exported GLB's served path+ // live in JSONB; the binary GLB stays on disk at data/image-to-3d/<id>/+ // model.glb and is referenced by path. Soft deletes keep recovery and future+ // peer-sync additive (the GLB is a local, host-specific render, so this is+ // NOT federated in this phase — like threejs_models). Mirrors init-db.sql.+ `CREATE TABLE IF NOT EXISTS image_to_3d_models (+ id TEXT PRIMARY KEY,+ name TEXT NOT NULL,+ status VARCHAR(32) NOT NULL DEFAULT 'draft',+ data JSONB NOT NULL DEFAULT '{}'::jsonb,+ created_at TIMESTAMPTZ DEFAULT NOW(),+ updated_at TIMESTAMPTZ DEFAULT NOW(),+ deleted BOOLEAN DEFAULT FALSE,+ deleted_at TIMESTAMPTZ+ )`,+ `CREATE INDEX IF NOT EXISTS idx_image_to_3d_models_live_updated ON image_to_3d_models (updated_at DESC) WHERE deleted = FALSE`,+// Music Video projects (issue #1760). The director scene board's db-primary// record: id/status/created_at/updated_at mirrored as columns, the full// project (track link, cached audioAnalysis, scenes[]) in `data` JSONB —diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.jsindex f4b7a7381d..c22a43c6da 100644--- a/server/lib/fileUtils.js+++ b/server/lib/fileUtils.js@@ -117,6 +117,10 @@ export const PATHS = {// (sprites/<id>/{reference,walk,runs,runtime,atlas}/...). Records live in// Postgres (sprite_records); only binary artifacts + manifests live here.sprites: join(INSTALL_ROOT, 'data/sprites'),+ // Image-to-3D (issue #2952): per-record GLB meshes rendered locally by a+ // target (TRELLIS.2 today), stored as image-to-3d/<id>/model.glb. Records+ // live in Postgres (image_to_3d_models); only the binary GLB lives here.+ imageTo3d: join(INSTALL_ROOT, 'data/image-to-3d'),// Persisted audio renders (voice-over lines). Kept distinct from// the in-memory voice-agent synthesis path in services/voice/ — that path// streams WAV over Socket.IO without ever touching disk.diff --git a/server/routes/imageTo3d.js b/server/routes/imageTo3d.jsindex fa24148afa..fab1bc3c21 100644--- a/server/routes/imageTo3d.js+++ b/server/routes/imageTo3d.js@@ -1,17 +1,38 @@import { Router } from 'express';-import { asyncHandler } from '../lib/errorHandler.js';+import { createReadStream } from 'node:fs';+import { z } from 'zod';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { validateRequest } from '../lib/validation.js';import {listTargets,detectHostCapabilities,isTargetAvailable,unavailableReason,+ IMAGE_TO_3D_TARGET_IDS,} from '../services/imageTo3d/targets.js';import { isTrellis2Installed, installTrellis2, trellis2Root } from '../services/imageTo3d/trellis2.js';+import {+ listModels,+ getModel,+ createModel,+ startGeneration,+ deleteModel,+ getModelAsset,+} from '../services/imageTo3d/models.js';import { createInstallLogger } from '../lib/installLogger.js';import { openSseStream } from '../lib/sseDownload.js';const router = Router();+const galleryFilenameSchema = z.string().trim().min(1).max(256)+ .regex(/^[^/\\]+\.(png|jpe?g|webp)$/i, 'filename must be a gallery image basename');++const createModelSchema = z.object({+ name: z.string().trim().min(1).max(120),+ filename: galleryFilenameSchema,+ target: z.enum([...IMAGE_TO_3D_TARGET_IDS]).optional(),+});+// In-flight singleton — a rapid double-click would otherwise race two clone/setup// processes against the same install dir. isTrellis2Installed() can't gate the// second click (the first install hasn't produced the venv yet). Mirrors@@ -100,4 +121,54 @@ router.get('/trellis2/install', asyncHandler(async (req, res) => {req.on('close', () => { installLog.cancel(); kill(); safeEnd(); });}));+// ── Image-to-3D model records ─────────────────────────────────────────────+// Namespaced under /models so `/:id` never shadows the `/targets` and+// `/trellis2/install` routes above. These drive the /media/3d page: create a+// record from a gallery image (which kicks off the local render), poll the+// record for status, re-generate, delete, and download the exported GLB.++router.get('/models', asyncHandler(async (_req, res) => {+ res.json(await listModels());+}));++router.post('/models', asyncHandler(async (req, res) => {+ const input = validateRequest(createModelSchema, req.body);+ const model = await createModel(input);+ res.status(202).json(model);+}));++router.get('/models/:id/asset', asyncHandler(async (req, res) => {+ const { path, filename } = await getModelAsset(req.params.id);+ res.set('Content-Type', 'model/gltf-binary');+ res.set('Content-Disposition', `attachment; filename="${filename}"`);+ // The 'error' event fires outside the asyncHandler promise chain, so a throw+ // here would crash the process — emit the error envelope instead (a file+ // removed between the readiness check and the stream just 404s the download).+ const stream = createReadStream(path);+ stream.on('error', (err) => {+ console.warn(`⚠️ Image-to-3D asset stream error: ${err.code || err.message}`);+ if (!res.headersSent) {+ res.status(404).json({ error: 'Mesh file not found', code: 'ASSET_MISSING', timestamp: new Date().toISOString() });+ } else {+ res.destroy(err);+ }+ });+ stream.pipe(res);+}));++router.get('/models/:id', asyncHandler(async (req, res) => {+ const model = await getModel(req.params.id);+ if (!model) throw new ServerError('Image-to-3D model not found', { status: 404, code: 'NOT_FOUND' });+ res.json(model);+}));++router.post('/models/:id/generate', asyncHandler(async (req, res) => {+ const model = await startGeneration(req.params.id);+ res.status(202).json(model);+}));++router.delete('/models/:id', asyncHandler(async (req, res) => {+ res.json(await deleteModel(req.params.id));+}));+export default router;diff --git a/server/routes/imageTo3d.test.js b/server/routes/imageTo3d.test.jsindex 36f9a00d50..6310fb1598 100644--- a/server/routes/imageTo3d.test.js+++ b/server/routes/imageTo3d.test.js@@ -1,5 +1,8 @@-import { describe, expect, it, vi } from 'vitest';+import { beforeEach, describe, expect, it, vi } from 'vitest';import express from 'express';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import { writeFile, rm } from 'node:fs/promises';import { request } from '../lib/testHelper.js';import { errorMiddleware } from '../lib/errorHandler.js';@@ -19,6 +22,7 @@ vi.mock('../services/imageTo3d/targets.js', () => ({]),isTargetAvailable: vi.fn(() => true),unavailableReason: vi.fn(() => 'requires-apple-silicon'),+ IMAGE_TO_3D_TARGET_IDS: ['trellis2'],}));vi.mock('../services/imageTo3d/trellis2.js', () => ({@@ -31,8 +35,18 @@ vi.mock('../services/imageTo3d/trellis2.js', () => ({}),}));+vi.mock('../services/imageTo3d/models.js', () => ({+ listModels: vi.fn(),+ getModel: vi.fn(),+ createModel: vi.fn(),+ startGeneration: vi.fn(),+ deleteModel: vi.fn(),+ getModelAsset: vi.fn(),+}));+import * as targets from '../services/imageTo3d/targets.js';import * as trellis2 from '../services/imageTo3d/trellis2.js';+import * as models from '../services/imageTo3d/models.js';import routes from './imageTo3d.js';const makeApp = () => {@@ -125,3 +139,79 @@ describe('GET /trellis2/install (SSE)', () => {expect(trellis2.installTrellis2).not.toHaveBeenCalled();});});++describe('image-to-3d model records', () => {+ beforeEach(() => vi.clearAllMocks());++ it('GET /models lists records', async () => {+ models.listModels.mockResolvedValue([{ id: 'image3d-1', status: 'ready' }]);+ const res = await request(makeApp()).get('/api/image-to-3d/models');+ expect(res.status).toBe(200);+ expect(res.body).toEqual([{ id: 'image3d-1', status: 'ready' }]);+ });++ it('POST /models creates a record (202) from a validated gallery image', async () => {+ models.createModel.mockResolvedValue({ id: 'image3d-1', status: 'generating' });+ const res = await request(makeApp())+ .post('/api/image-to-3d/models')+ .send({ name: 'Beacon', filename: 'shot.png' });+ expect(res.status).toBe(202);+ expect(res.body).toMatchObject({ id: 'image3d-1', status: 'generating' });+ expect(models.createModel).toHaveBeenCalledWith(expect.objectContaining({ name: 'Beacon', filename: 'shot.png' }));+ });++ it('POST /models 400s on a non-image filename', async () => {+ const res = await request(makeApp())+ .post('/api/image-to-3d/models')+ .send({ name: 'Beacon', filename: 'not-an-image.txt' });+ expect(res.status).toBe(400);+ expect(models.createModel).not.toHaveBeenCalled();+ });++ it('POST /models 400s on a path-traversal filename', async () => {+ const res = await request(makeApp())+ .post('/api/image-to-3d/models')+ .send({ name: 'Beacon', filename: '../secrets.png' });+ expect(res.status).toBe(400);+ expect(models.createModel).not.toHaveBeenCalled();+ });++ it('GET /models/:id 404s when absent', async () => {+ models.getModel.mockResolvedValue(null);+ const res = await request(makeApp()).get('/api/image-to-3d/models/nope');+ expect(res.status).toBe(404);+ });++ it('POST /models/:id/generate re-renders (202)', async () => {+ models.startGeneration.mockResolvedValue({ id: 'image3d-1', status: 'generating' });+ const res = await request(makeApp()).post('/api/image-to-3d/models/image3d-1/generate');+ expect(res.status).toBe(202);+ expect(models.startGeneration).toHaveBeenCalledWith('image3d-1');+ });++ it('DELETE /models/:id soft-deletes', async () => {+ models.deleteModel.mockResolvedValue({ ok: true });+ const res = await request(makeApp()).delete('/api/image-to-3d/models/image3d-1');+ expect(res.status).toBe(200);+ expect(res.body).toEqual({ ok: true });+ });++ it('GET /models/:id/asset streams the GLB with a download filename', async () => {+ const tmp = join(tmpdir(), `it-asset-${process.pid}.glb`);+ await writeFile(tmp, 'GLB-BYTES');+ models.getModelAsset.mockResolvedValue({ path: tmp, filename: 'beacon.glb' });+ const res = await request(makeApp()).get('/api/image-to-3d/models/image3d-1/asset');+ expect(res.status).toBe(200);+ expect(res.headers['content-type']).toMatch(/model\/gltf-binary/);+ expect(res.headers['content-disposition']).toMatch(/beacon\.glb/);+ expect(res.text).toBe('GLB-BYTES');+ await rm(tmp, { force: true });+ });++ it('GET /models/:id/asset 409s when the mesh is not ready', async () => {+ const { ServerError } = await import('../lib/errorHandler.js');+ models.getModelAsset.mockRejectedValue(new ServerError('not ready', { status: 409, code: 'MODEL_NOT_READY' }));+ const res = await request(makeApp()).get('/api/image-to-3d/models/image3d-1/asset');+ expect(res.status).toBe(409);+ });+});diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sqlindex d2b48d51ac..b8bc1e2f08 100644--- a/server/scripts/init-db.sql+++ b/server/scripts/init-db.sql@@ -702,6 +702,23 @@ CREATE TABLE IF NOT EXISTS threejs_models ();CREATE INDEX IF NOT EXISTS idx_threejs_models_live_updated ON threejs_models (updated_at DESC) WHERE deleted = FALSE;+-- Image-to-3D models (issue #2952). Neural image→GLB records — distinct from+-- threejs_models above (procedural JS source vs. a real .glb mesh). The GLB+-- binary stays on disk at data/image-to-3d/<id>/model.glb; each row owns the+-- source gallery image reference, selected target, generation state, run+-- history, and the exported GLB's served path. Not federated in this phase.+CREATE TABLE IF NOT EXISTS image_to_3d_models (+ id TEXT PRIMARY KEY,+ name TEXT NOT NULL,+ status VARCHAR(32) NOT NULL DEFAULT 'draft',+ data JSONB NOT NULL DEFAULT '{}'::jsonb,+ created_at TIMESTAMPTZ DEFAULT NOW(),+ updated_at TIMESTAMPTZ DEFAULT NOW(),+ deleted BOOLEAN DEFAULT FALSE,+ deleted_at TIMESTAMPTZ+);+CREATE INDEX IF NOT EXISTS idx_image_to_3d_models_live_updated ON image_to_3d_models (updated_at DESC) WHERE deleted = FALSE;+-- Music Video projects (issue #1760). The director scene board's db-primary-- record: id/status/created_at/updated_at mirrored as columns, the full project-- (track link, cached audioAnalysis, scenes[]) in `data` JSONB — same shape as@@ -1335,6 +1352,8 @@ DROP TRIGGER IF EXISTS trg_creative_director_projects_audit ON creative_directorCREATE TRIGGER trg_creative_director_projects_audit AFTER UPDATE OR DELETE ON creative_director_projects FOR EACH ROW EXECUTE FUNCTION record_audit_log();DROP TRIGGER IF EXISTS trg_threejs_models_audit ON threejs_models;CREATE TRIGGER trg_threejs_models_audit AFTER UPDATE OR DELETE ON threejs_models FOR EACH ROW EXECUTE FUNCTION record_audit_log();+DROP TRIGGER IF EXISTS trg_image_to_3d_models_audit ON image_to_3d_models;+CREATE TRIGGER trg_image_to_3d_models_audit AFTER UPDATE OR DELETE ON image_to_3d_models FOR EACH ROW EXECUTE FUNCTION record_audit_log();DROP TRIGGER IF EXISTS trg_mood_boards_audit ON mood_boards;CREATE TRIGGER trg_mood_boards_audit AFTER UPDATE OR DELETE ON mood_boards FOR EACH ROW EXECUTE FUNCTION record_audit_log();DROP TRIGGER IF EXISTS trg_lora_training_runs_audit ON lora_training_runs;diff --git a/server/services/bootstrap.js b/server/services/bootstrap.jsindex f0091789ef..b7ed4615af 100644--- a/server/services/bootstrap.js+++ b/server/services/bootstrap.js@@ -81,6 +81,7 @@ import { recoverStuckAutoRuns } from './pipeline/autoRunner.js';import { recoverStuckAutopilots } from './pipeline/seriesAutopilot.js';import { recoverInFlightProjects } from './creativeDirector/recovery.js';import { recoverInterruptedModels as recoverInterruptedThreejsModels } from './threejsModels/index.js';+import { recoverInterruptedModels as recoverInterruptedImageTo3dModels } from './imageTo3d/models.js';import { ensureSelf, startPolling } from './instances.js';import { initSyncLog } from './brainSyncLog.js';import { backfillOriginInstanceId, brainCollectionStores } from './brainStorage.js';@@ -306,6 +307,7 @@ const startBackgroundServices = ({ spawnerReady }) => {// Three.js generations retryable; this is state recovery only, never a// cold-bootstrap provider call.recoverInterruptedThreejsModels().catch(err => console.error(`❌ Three.js model recovery failed: ${err.message}`));+ recoverInterruptedImageTo3dModels().catch(err => console.error(`❌ Image-to-3D model recovery failed: ${err.message}`));// Initialize brain scheduler for daily digests and weekly reviewsstartBrainScheduler();// Initialize activity-digest scheduler — OFF by default; drafts daily-logdiff --git a/server/services/imageTo3d/db.js b/server/services/imageTo3d/db.jsnew file mode 100644index 0000000000..e462419466--- /dev/null+++ b/server/services/imageTo3d/db.js@@ -0,0 +1,146 @@+/**+ * PostgreSQL store for image-to-3D model records (issue #2952).+ *+ * The full record lives in `data` JSONB; name/status/timestamps/deleted are+ * mirrored columns for list queries and audit triggers. Mirrors the shape of+ * `server/services/threejsModels/db.js` — the two are sibling media records+ * (procedural JS source vs. a neural GLB mesh). The binary GLB itself stays on+ * disk (data/image-to-3d/<id>/model.glb) and is referenced by path.+ */++import { randomUUID } from 'crypto';+import { query, withTransaction } from '../../lib/db.js';+import { ServerError } from '../../lib/errorHandler.js';++const rowToModel = (row) => row?.data ?? null;++async function persist(exec, model) {+ await exec(+ `INSERT INTO image_to_3d_models (id, name, status, data, created_at, updated_at, deleted, deleted_at)+ VALUES ($1, $2, $3, $4::jsonb, $5, $6, $7, $8)+ ON CONFLICT (id) DO UPDATE SET+ name = EXCLUDED.name,+ status = EXCLUDED.status,+ data = EXCLUDED.data,+ updated_at = EXCLUDED.updated_at,+ deleted = EXCLUDED.deleted,+ deleted_at = EXCLUDED.deleted_at`,+ [+ model.id,+ model.name,+ model.status,+ JSON.stringify(model),+ model.createdAt,+ model.updatedAt,+ model.deleted === true,+ model.deletedAt || null,+ ],+ );+ return model;+}++export async function listModels({ includeDeleted = false } = {}) {+ const result = includeDeleted+ ? await query('SELECT data FROM image_to_3d_models ORDER BY updated_at DESC')+ : await query('SELECT data FROM image_to_3d_models WHERE deleted = FALSE ORDER BY updated_at DESC');+ return result.rows.map(rowToModel);+}++export async function getModel(id, { includeDeleted = false } = {}) {+ const result = await query('SELECT data FROM image_to_3d_models WHERE id = $1', [id]);+ const model = rowToModel(result.rows[0]);+ if (!model || (!includeDeleted && model.deleted)) return null;+ return model;+}++export async function createModel(input) {+ const now = new Date().toISOString();+ const model = {+ id: `image3d-${randomUUID()}`,+ schemaVersion: 1,+ name: input.name,+ target: input.target,+ sourceImage: {+ filename: input.filename,+ path: `/data/images/${encodeURIComponent(input.filename)}`,+ },+ status: 'draft',+ assetPath: null,+ error: null,+ generationOperationId: null,+ runs: [],+ createdAt: now,+ updatedAt: now,+ generatedAt: null,+ deleted: false,+ deletedAt: null,+ };+ return persist(query, model);+}++export async function mutateModel(id, mutate, { includeDeleted = false } = {}) {+ return withTransaction(async (client) => {+ const result = await client.query('SELECT data FROM image_to_3d_models WHERE id = $1 FOR UPDATE', [id]);+ const current = rowToModel(result.rows[0]);+ if (!current || (!includeDeleted && current.deleted)) {+ throw new ServerError('Image-to-3D model not found', { status: 404, code: 'NOT_FOUND' });+ }+ const next = mutate(current);+ if (!next) return current;+ next.updatedAt = new Date().toISOString();+ await persist(client.query.bind(client), next);+ return next;+ });+}++export function updateModel(id, patch) {+ return mutateModel(id, (current) => ({ ...current, ...patch }));+}++export async function deleteModel(id) {+ const now = new Date().toISOString();+ await mutateModel(id, (current) => ({+ ...current,+ status: current.status === 'generating' ? 'canceled' : current.status,+ deleted: true,+ deletedAt: now,+ }));+ return { ok: true };+}++/**+ * A render child cannot survive the PortOS process. Mark interrupted records+ * failed-retryable on boot without launching any new render work (the GLB+ * render is user-triggered only — CLAUDE.md no-cold-bootstrap policy).+ */+export async function recoverInterruptedModels() {+ const result = await query(+ `SELECT data FROM image_to_3d_models WHERE deleted = FALSE AND status = 'generating'`,+ );+ let recovered = 0;+ for (const row of result.rows) {+ const current = rowToModel(row);+ await mutateModel(current.id, (fresh) => {+ if (fresh.status !== 'generating') return null;+ recovered += 1;+ const runs = Array.isArray(fresh.runs) ? [...fresh.runs] : [];+ const activeIndex = runs.findLastIndex((run) => run.status === 'running');+ if (activeIndex !== -1) {+ runs[activeIndex] = {+ ...runs[activeIndex],+ status: 'failed',+ error: 'Render was interrupted by a server restart',+ completedAt: new Date().toISOString(),+ };+ }+ return {+ ...fresh,+ status: 'failed',+ error: 'Render was interrupted by a server restart. Generate again to retry.',+ generationOperationId: null,+ runs,+ };+ });+ }+ return { recovered };+}diff --git a/server/services/imageTo3d/models.js b/server/services/imageTo3d/models.jsnew file mode 100644index 0000000000..2a1c01ab33--- /dev/null+++ b/server/services/imageTo3d/models.js@@ -0,0 +1,236 @@+/**+ * Image-to-3D model orchestration (issue #2952) — gallery-image lineage, target+ * dispatch, guarded local render, persistence, and GLB export.+ *+ * This is the record/create/generate layer that sits on top of the pluggable+ * target registry (`targets.js`) and the TRELLIS.2 runner (`trellis2.js`). It+ * mirrors the role `threejsModels/index.js` plays for procedural models, but the+ * inference is a LOCAL on-device render (no AI provider) landing a real `.glb`+ * mesh on disk rather than an LLM-authored scene spec.+ *+ * The render NEVER auto-runs: it is only reached from an explicit user create /+ * generate request, and it is gated on the target being installed + runnable on+ * this host (CLAUDE.md no-cold-bootstrap AI policy + the host's sensitivity to+ * sustained GPU load). Adding a second target is a registration in `TARGET_RUNNERS`,+ * not a rewrite here.+ */++import { randomUUID } from 'crypto';+import { join } from 'node:path';+import { ServerError } from '../../lib/errorHandler.js';+import { PATHS, resolveGalleryImage, ensureDir } from '../../lib/fileUtils.js';+import { detectHostCapabilities, resolveTarget, DEFAULT_IMAGE_TO_3D_TARGET } from './targets.js';+import { isTrellis2Installed, runTrellis2Generate } from './trellis2.js';+import * as store from './db.js';++const MAX_RUNS = 30;+const activeOperations = new Set();++/**+ * Per-target install-probe + runner. One dispatch point so registering a new+ * image→3D backend is an entry here, not new branches through create/generate.+ * A runner takes `{ imagePath, outputPath, onProgress }` and resolves+ * `{ assetPath }` (see `runTrellis2Generate`).+ */+const TARGET_RUNNERS = {+ trellis2: { isInstalled: isTrellis2Installed, run: runTrellis2Generate },+};++const trimRuns = (runs) => runs.slice(-MAX_RUNS);+const cleanError = (error) => String(error?.message || error || 'Render failed').slice(0, 2_000);++const slugify = (name) => String(name || '')+ .toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');++/** The served URL for a record's exported GLB (static-mounted under /data). */+const assetUrl = (id) => `/data/image-to-3d/${id}/model.glb`;+/** The on-disk destination the runner writes the GLB to. */+const assetDiskPath = (id) => join(PATHS.imageTo3d, id, 'model.glb');++/**+ * Verify a target can actually run on this host right now — unknown target →+ * 400, hardware-unsupported → 409 (reason surfaced), not-installed → 409 so the+ * UI can open the install flow. Returns the resolved runner entry. Pure w.r.t.+ * the DB; `caps` is injected so the check is deterministic.+ */+function assertTargetReady(targetId, caps) {+ const { target, available, reason } = resolveTarget(targetId, caps);+ if (!target) {+ throw new ServerError(`Unknown image-to-3D target: ${targetId}`, { status: 400, code: 'UNKNOWN_TARGET' });+ }+ if (!available) {+ throw new ServerError(+ `This host cannot run ${target.label} (${reason}).`,+ { status: 409, code: 'TARGET_UNAVAILABLE', context: { reason } },+ );+ }+ const runner = TARGET_RUNNERS[targetId];+ if (!runner) {+ throw new ServerError(`Target ${target.label} has no runner wired`, { status: 501, code: 'TARGET_NO_RUNNER' });+ }+ if (!runner.isInstalled()) {+ throw new ServerError(+ `${target.label} is not installed. Install it before generating.`,+ { status: 409, code: 'TARGET_NOT_INSTALLED' },+ );+ }+ return runner;+}++function updateRun(runs, operationId, patch) {+ return trimRuns((Array.isArray(runs) ? runs : []).map((run) => (+ run.operationId === operationId ? { ...run, ...patch } : run+ )));+}++async function failGeneration(id, operationId, error) {+ const message = cleanError(error);+ await store.mutateModel(id, (current) => {+ if (current.generationOperationId !== operationId) return null;+ return {+ ...current,+ status: 'failed',+ error: message,+ generationOperationId: null,+ runs: updateRun(current.runs, operationId, {+ status: 'failed',+ error: message,+ completedAt: new Date().toISOString(),+ }),+ };+ }).catch((persistError) => {+ console.error(`❌ Image-to-3D model ${id} failure could not be persisted: ${persistError.message}`);+ });+}++async function executeRender({ id, operationId, runner, sourcePath }) {+ const outputPath = assetDiskPath(id);+ let lastPersistedPercent = -1;+ try {+ await ensureDir(join(PATHS.imageTo3d, id));+ await runner.run({+ imagePath: sourcePath,+ outputPath,+ onProgress: (frame) => {+ // Sparse, low-frequency render progress — persist only when the whole+ // percent actually advances so a chatty parser can't hot-write the row.+ const percent = Number.isFinite(frame?.percent) ? Math.round(frame.percent) : null;+ if (percent === null || percent <= lastPersistedPercent) return;+ lastPersistedPercent = percent;+ void store.mutateModel(id, (current) => {+ if (current.generationOperationId !== operationId) return null;+ return { ...current, runs: updateRun(current.runs, operationId, { percent }) };+ }).catch(() => {}); // progress is best-effort; a lost frame is not fatal+ },+ });++ const completedAt = new Date().toISOString();+ await store.mutateModel(id, (current) => {+ if (current.generationOperationId !== operationId) return null;+ return {+ ...current,+ status: 'ready',+ assetPath: assetUrl(id),+ error: null,+ generationOperationId: null,+ generatedAt: completedAt,+ runs: updateRun(current.runs, operationId, {+ status: 'completed',+ percent: 100,+ completedAt,+ }),+ };+ });+ console.log(`🧊 Image-to-3D mesh ready: ${id}`);+ } catch (error) {+ console.error(`❌ Image-to-3D render failed for ${id}: ${cleanError(error)}`);+ await failGeneration(id, operationId, error);+ } finally {+ activeOperations.delete(operationId);+ }+}++export const listModels = store.listModels;+export const getModel = store.getModel;+export const deleteModel = store.deleteModel;++export async function createModel(input, { caps = detectHostCapabilities() } = {}) {+ const sourcePath = resolveGalleryImage(input.filename);+ if (!sourcePath) {+ throw new ServerError('Gallery image not found', { status: 400, code: 'GALLERY_IMAGE_NOT_FOUND' });+ }+ const targetId = input.target || DEFAULT_IMAGE_TO_3D_TARGET;+ // Validate the target is runnable BEFORE persisting a record so we never leave+ // a dangling draft when the host can't render / the model isn't installed.+ assertTargetReady(targetId, caps);+ const created = await store.createModel({ ...input, target: targetId });+ return startGeneration(created.id, { caps });+}++export async function startGeneration(id, { caps = detectHostCapabilities() } = {}) {+ const current = await store.getModel(id);+ if (!current) throw new ServerError('Image-to-3D model not found', { status: 404, code: 'NOT_FOUND' });+ if (current.status === 'generating'+ || (current.generationOperationId && activeOperations.has(current.generationOperationId))) {+ throw new ServerError('This model is already generating', { status: 409, code: 'MODEL_BUSY' });+ }++ const runner = assertTargetReady(current.target, caps);+ const sourcePath = resolveGalleryImage(current.sourceImage?.filename);+ if (!sourcePath) {+ throw new ServerError('The source gallery image is no longer available', { status: 409, code: 'GALLERY_IMAGE_NOT_FOUND' });+ }++ const operationId = randomUUID();+ const startedAt = new Date().toISOString();+ const next = await store.mutateModel(id, (fresh) => {+ if (fresh.status === 'generating') {+ throw new ServerError('This model is already generating', { status: 409, code: 'MODEL_BUSY' });+ }+ return {+ ...fresh,+ status: 'generating',+ error: null,+ generationOperationId: operationId,+ runs: trimRuns([+ ...(Array.isArray(fresh.runs) ? fresh.runs : []),+ {+ operationId,+ status: 'running',+ target: fresh.target,+ percent: 0,+ startedAt,+ completedAt: null,+ error: null,+ },+ ]),+ };+ });++ activeOperations.add(operationId);+ setImmediate(() => {+ void executeRender({ id, operationId, runner, sourcePath });+ });+ return next;+}++/**+ * Resolve a ready record's exported GLB for download — 404 when the record is+ * gone, 409 while it has no rendered mesh yet.+ */+export async function getModelAsset(id) {+ const model = await store.getModel(id);+ if (!model) throw new ServerError('Image-to-3D model not found', { status: 404, code: 'NOT_FOUND' });+ if (model.status !== 'ready' || !model.assetPath) {+ throw new ServerError('This model has no generated mesh yet', { status: 409, code: 'MODEL_NOT_READY' });+ }+ return { path: assetDiskPath(id), filename: `${slugify(model.name) || 'model'}.glb` };+}++export async function recoverInterruptedModels() {+ const result = await store.recoverInterruptedModels();+ if (result.recovered > 0) {+ console.log(`🧊 Recovered ${result.recovered} interrupted image-to-3D render(s)`);+ }+ return result;+}diff --git a/server/services/imageTo3d/models.test.js b/server/services/imageTo3d/models.test.jsnew file mode 100644index 0000000000..b72b693075--- /dev/null+++ b/server/services/imageTo3d/models.test.js@@ -0,0 +1,150 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++vi.mock('../../lib/fileUtils.js', () => ({+ PATHS: { imageTo3d: '/mock/data/image-to-3d' },+ resolveGalleryImage: vi.fn((filename) => (+ filename === 'missing.png' ? null : `/mock/data/images/${filename}`+ )),+ ensureDir: vi.fn(() => Promise.resolve()),+}));++vi.mock('./targets.js', () => ({+ DEFAULT_IMAGE_TO_3D_TARGET: 'trellis2',+ detectHostCapabilities: vi.fn(() => ({ appleSilicon: true, unifiedMemoryGb: 128, cuda: false })),+ resolveTarget: vi.fn((id) => (+ id === 'trellis2'+ ? { targetId: 'trellis2', target: { id: 'trellis2', label: 'TRELLIS.2' }, available: true, reason: null }+ : { targetId: id, target: null, available: false, reason: 'unknown-target' }+ )),+}));++vi.mock('./trellis2.js', () => ({+ isTrellis2Installed: vi.fn(() => true),+ runTrellis2Generate: vi.fn(() => Promise.resolve({ assetPath: '/mock/data/image-to-3d/x/model.glb' })),+}));++vi.mock('./db.js', () => ({+ listModels: vi.fn(),+ getModel: vi.fn(),+ createModel: vi.fn(),+ mutateModel: vi.fn(),+ deleteModel: vi.fn(),+ recoverInterruptedModels: vi.fn(),+}));++import { resolveTarget } from './targets.js';+import { isTrellis2Installed, runTrellis2Generate } from './trellis2.js';+import * as store from './db.js';+import { createModel, startGeneration, getModelAsset } from './models.js';++const draftRecord = () => ({+ id: 'image3d-example',+ name: 'Beacon',+ target: 'trellis2',+ sourceImage: { filename: 'example.png', path: '/data/images/example.png' },+ status: 'draft',+ assetPath: null,+ generationOperationId: null,+ runs: [],+});++describe('image-to-3D model orchestration', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ isTrellis2Installed.mockReturnValue(true);+ resolveTarget.mockImplementation((id) => (+ id === 'trellis2'+ ? { targetId: 'trellis2', target: { id: 'trellis2', label: 'TRELLIS.2' }, available: true, reason: null }+ : { targetId: id, target: null, available: false, reason: 'unknown-target' }+ ));+ runTrellis2Generate.mockResolvedValue({ assetPath: '/mock/data/image-to-3d/x/model.glb' });+ });++ it('rejects a source that is no longer in the gallery', async () => {+ await expect(createModel({ name: 'Missing', filename: 'missing.png' }))+ .rejects.toMatchObject({ status: 400, code: 'GALLERY_IMAGE_NOT_FOUND' });+ expect(store.createModel).not.toHaveBeenCalled();+ });++ it('refuses to persist a record when the target is not installed', async () => {+ isTrellis2Installed.mockReturnValue(false);+ await expect(createModel({ name: 'Beacon', filename: 'example.png' }))+ .rejects.toMatchObject({ status: 409, code: 'TARGET_NOT_INSTALLED' });+ expect(store.createModel).not.toHaveBeenCalled();+ expect(runTrellis2Generate).not.toHaveBeenCalled();+ });++ it('refuses when the host cannot run the target', async () => {+ resolveTarget.mockReturnValue({ targetId: 'trellis2', target: { id: 'trellis2', label: 'TRELLIS.2' }, available: false, reason: 'insufficient-memory' });+ await expect(createModel({ name: 'Beacon', filename: 'example.png' }))+ .rejects.toMatchObject({ status: 409, code: 'TARGET_UNAVAILABLE', context: { reason: 'insufficient-memory' } });+ expect(store.createModel).not.toHaveBeenCalled();+ });++ it('rejects an unknown target', async () => {+ await expect(createModel({ name: 'Beacon', filename: 'example.png', target: 'nope' }))+ .rejects.toMatchObject({ status: 400, code: 'UNKNOWN_TARGET' });+ });++ it('rejects a duplicate generate while already generating', async () => {+ store.getModel.mockResolvedValue({ ...draftRecord(), status: 'generating', generationOperationId: 'op-1' });+ await expect(startGeneration('image3d-example'))+ .rejects.toMatchObject({ status: 409, code: 'MODEL_BUSY' });+ expect(runTrellis2Generate).not.toHaveBeenCalled();+ });++ it('creates the record, renders, and lands a ready mesh with an assetPath', async () => {+ let current = draftRecord();+ store.createModel.mockImplementation(async () => current);+ store.getModel.mockImplementation(async () => current);+ store.mutateModel.mockImplementation(async (_id, mutate) => {+ const next = mutate(current);+ if (next) current = next;+ return current;+ });++ const started = await createModel({ name: 'Beacon', filename: 'example.png' });+ expect(started.status).toBe('generating');++ await vi.waitFor(() => expect(current.status).toBe('ready'));+ expect(runTrellis2Generate).toHaveBeenCalledWith(expect.objectContaining({+ imagePath: '/mock/data/images/example.png',+ outputPath: expect.stringMatching(/image-to-3d\/image3d-example\/model\.glb$/),+ }));+ expect(current.assetPath).toBe('/data/image-to-3d/image3d-example/model.glb');+ expect(current.generationOperationId).toBeNull();+ expect(current.runs.at(-1)).toMatchObject({ status: 'completed', percent: 100 });+ });++ it('marks the record failed when the render throws', async () => {+ let current = draftRecord();+ store.createModel.mockImplementation(async () => current);+ store.getModel.mockImplementation(async () => current);+ store.mutateModel.mockImplementation(async (_id, mutate) => {+ const next = mutate(current);+ if (next) current = next;+ return current;+ });+ runTrellis2Generate.mockRejectedValue(new Error('TRELLIS.2 generate exited 1'));++ await createModel({ name: 'Beacon', filename: 'example.png' });+ await vi.waitFor(() => expect(current.status).toBe('failed'));+ expect(current.error).toMatch(/exited 1/);+ expect(current.runs.at(-1)).toMatchObject({ status: 'failed' });+ });++ it('getModelAsset 409s until a mesh is rendered, then returns the download path', async () => {+ store.getModel.mockResolvedValueOnce({ ...draftRecord(), status: 'generating' });+ await expect(getModelAsset('image3d-example'))+ .rejects.toMatchObject({ status: 409, code: 'MODEL_NOT_READY' });++ store.getModel.mockResolvedValueOnce({+ ...draftRecord(), status: 'ready', name: 'My Beacon', assetPath: '/data/image-to-3d/image3d-example/model.glb',+ });+ const asset = await getModelAsset('image3d-example');+ expect(asset).toMatchObject({+ path: expect.stringMatching(/image-to-3d\/image3d-example\/model\.glb$/),+ filename: 'my-beacon.glb',+ });+ });+});