Skip to content

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

refactor([issue-2952]): reuse shared helpers + collapse create/generate double-validation

[._.]/ Adam Eivy82e3dd2132e0
diff --git a/server/routes/imageTo3d.js b/server/routes/imageTo3d.js
index fab1bc3c21..628994bde9 100644
--- a/server/routes/imageTo3d.js
+++ b/server/routes/imageTo3d.js
@@ -1,7 +1,7 @@
import { Router } from 'express';
import { createReadStream } from 'node:fs';
import { z } from 'zod';
-import { asyncHandler, ServerError } from '../lib/errorHandler.js';
+import { asyncHandler, ServerError, sendErrorResponse } from '../lib/errorHandler.js';
import { validateRequest } from '../lib/validation.js';
import {
listTargets,
@@ -142,16 +142,17 @@ router.get('/models/:id/asset', asyncHandler(async (req, res) => {
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).
+ // here would crash the process — route it through sendErrorResponse (the shared
+ // envelope + headers-sent guard) 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);
- }
+ // Pre-stream (common: file removed after the readiness check) → shared 404
+ // envelope. Mid-stream (headers already flushed) → tear the socket down, since
+ // sendErrorResponse no-ops once headers are sent.
+ if (res.headersSent) res.destroy(err);
+ else sendErrorResponse(res, new ServerError('Mesh file not found', { status: 404, code: 'ASSET_MISSING' }));
});
stream.pipe(res);
}));
diff --git a/server/services/imageTo3d/db.js b/server/services/imageTo3d/db.js
index e462419466..70b2ef94db 100644
--- a/server/services/imageTo3d/db.js
+++ b/server/services/imageTo3d/db.js
@@ -93,10 +93,6 @@ export async function mutateModel(id, mutate, { includeDeleted = false } = {}) {
});
}
-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) => ({
diff --git a/server/services/imageTo3d/models.js b/server/services/imageTo3d/models.js
index 2a1c01ab33..8c62c3deae 100644
--- a/server/services/imageTo3d/models.js
+++ b/server/services/imageTo3d/models.js
@@ -19,6 +19,7 @@ import { randomUUID } from 'crypto';
import { join } from 'node:path';
import { ServerError } from '../../lib/errorHandler.js';
import { PATHS, resolveGalleryImage, ensureDir } from '../../lib/fileUtils.js';
+import { slugifyForFilename } from '../../lib/civitai.js';
import { detectHostCapabilities, resolveTarget, DEFAULT_IMAGE_TO_3D_TARGET } from './targets.js';
import { isTrellis2Installed, runTrellis2Generate } from './trellis2.js';
import * as store from './db.js';
@@ -39,9 +40,6 @@ const TARGET_RUNNERS = {
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. */
@@ -162,9 +160,13 @@ export async function createModel(input, { caps = detectHostCapabilities() } = {
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 runner = assertTargetReady(targetId, caps);
const created = await store.createModel({ ...input, target: targetId });
- return startGeneration(created.id, { caps });
+ // Thread the already-validated runner + resolved source straight into the
+ // render — createModel and startGeneration share `beginRender`, so the create
+ // path does NOT re-resolve the gallery image, re-assert readiness, or re-fetch
+ // the row it just wrote.
+ return beginRender(created, runner, sourcePath);
}
export async function startGeneration(id, { caps = detectHostCapabilities() } = {}) {
@@ -180,7 +182,18 @@ export async function startGeneration(id, { caps = detectHostCapabilities() } =
if (!sourcePath) {
throw new ServerError('The source gallery image is no longer available', { status: 409, code: 'GALLERY_IMAGE_NOT_FOUND' });
}
+ return beginRender(current, runner, sourcePath);
+}
+/**
+ * Flip a validated record to `generating`, append a run, and dispatch the async
+ * render. The single write path shared by create + regenerate — callers do the
+ * validation (target readiness, gallery-image resolution) and pass the resolved
+ * runner + source through. The transactional `status==='generating'` guard here
+ * is the authoritative race check (the callers' pre-check is just a fast 409).
+ */
+async function beginRender(record, runner, sourcePath) {
+ const { id } = record;
const operationId = randomUUID();
const startedAt = new Date().toISOString();
const next = await store.mutateModel(id, (fresh) => {
@@ -224,7 +237,7 @@ export async function getModelAsset(id) {
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` };
+ return { path: assetDiskPath(id), filename: `${slugifyForFilename(model.name)}.glb` };
}
export async function recoverInterruptedModels() {