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

feat([issue-2972]): kill in-flight TRELLIS.2 render and clean orphaned GLB on delete

[._.]/ Adam Eivyc2262e1eda80
diff --git a/server/services/imageTo3d/models.js b/server/services/imageTo3d/models.js
index e69d86a350..952cebbb1b 100644
--- a/server/services/imageTo3d/models.js
+++ b/server/services/imageTo3d/models.js
@@ -17,6 +17,7 @@
import { randomUUID } from 'crypto';
import { join } from 'node:path';
+import { rm } from 'node:fs/promises';
import { ServerError } from '../../lib/errorHandler.js';
import { PATHS, resolveGalleryImage, ensureDir } from '../../lib/fileUtils.js';
import { slugifyForFilename } from '../../lib/civitai.js';
@@ -26,12 +27,17 @@ import * as store from './db.js';
const MAX_RUNS = 30;
const activeOperations = new Set();
+// operationId → the runner's SIGTERM handle for an in-flight render, so deleting a
+// record mid-render can terminate its subprocess promptly. Populated when the render
+// spawns (executeRender) and drained in its `finally`.
+const activeRenders = new Map();
/**
* 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`).
+ * A runner takes `{ imagePath, outputPath, onProgress }` and returns a
+ * `{ promise, kill }` pair — `promise` resolves `{ assetPath }`; `kill` SIGTERMs the
+ * render so a mid-flight delete can terminate it (see `runTrellis2Generate`).
*/
const TARGET_RUNNERS = {
trellis2: { isInstalled: isTrellis2Installed, run: runTrellis2Generate },
@@ -45,6 +51,17 @@ 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');
+/**
+ * Remove a record's render directory (the exported GLB + its folder). Used to
+ * clean the orphaned mesh a killed/deleted render may have left on disk. `force`
+ * makes an absent path a no-op ("if written"), so this is safe to call whether or
+ * not the render got far enough to emit a file.
+ */
+async function cleanupRenderDir(id) {
+ await rm(join(PATHS.imageTo3d, id), { recursive: true, force: true })
+ .catch((err) => console.error(`❌ Image-to-3D cleanup failed for ${id}: ${err.message}`));
+}
+
/**
* Verify a target can actually run on this host right now — unknown target →
* 400, hardware-unsupported → 409 (reason surfaced), not-installed → 409 so the
@@ -109,7 +126,10 @@ async function executeRender({ id, operationId, runner, sourcePath }) {
let lastPersistedPercent = -1;
try {
await ensureDir(join(PATHS.imageTo3d, id));
- await runner.run({
+ // The runner returns a { promise, kill } pair (see runTrellis2Generate) — retain
+ // the kill handle so deleteModel can SIGTERM this render if the record is deleted
+ // mid-flight.
+ const { promise, kill } = runner.run({
imagePath: sourcePath,
outputPath,
onProgress: (frame) => {
@@ -124,6 +144,8 @@ async function executeRender({ id, operationId, runner, sourcePath }) {
}).catch(() => {}); // progress is best-effort; a lost frame is not fatal
},
});
+ activeRenders.set(operationId, kill);
+ await promise;
const completedAt = new Date().toISOString();
// includeDeleted + `deleted` guard: if the user deleted the record while the
@@ -150,13 +172,40 @@ async function executeRender({ id, operationId, runner, sourcePath }) {
console.error(`❌ Image-to-3D render failed for ${id}: ${cleanError(error)}`);
await failGeneration(id, operationId, error);
} finally {
+ activeRenders.delete(operationId);
activeOperations.delete(operationId);
+ // If the record was deleted while the render ran, the completion/failure writes
+ // no-op'd on the `deleted` guard and any GLB the render produced is orphaned —
+ // remove it now that the child has fully settled (no further writes can race us).
+ const record = await store.getModel(id, { includeDeleted: true }).catch(() => null);
+ if (record?.deleted) await cleanupRenderDir(id);
}
}
export const listModels = store.listModels;
export const getModel = store.getModel;
-export const deleteModel = store.deleteModel;
+
+/**
+ * Delete a record and, if a render is in flight, kill its subprocess so it stops
+ * burning GPU the moment the user walks away. The soft-delete write itself stays a
+ * clean no-op on the record. When a live render exists we SIGTERM it and let
+ * executeRender's `finally` remove the orphaned GLB once the child settles (avoids a
+ * delete-then-rewrite race); with no live render (e.g. a stale `generating` row that
+ * survived a restart) we clean any orphaned mesh directly.
+ */
+export async function deleteModel(id) {
+ const current = await store.getModel(id, { includeDeleted: true });
+ const result = await store.deleteModel(id);
+ if (current?.status === 'generating' && current.generationOperationId) {
+ const kill = activeRenders.get(current.generationOperationId);
+ if (kill) {
+ kill();
+ } else {
+ await cleanupRenderDir(id);
+ }
+ }
+ return result;
+}
export async function createModel(input, { caps = detectHostCapabilities() } = {}) {
const sourcePath = resolveGalleryImage(input.filename);
diff --git a/server/services/imageTo3d/models.test.js b/server/services/imageTo3d/models.test.js
index b8d0daef19..3b1e7593fa 100644
--- a/server/services/imageTo3d/models.test.js
+++ b/server/services/imageTo3d/models.test.js
@@ -1,5 +1,10 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
+vi.mock('node:fs/promises', async (importOriginal) => ({
+ ...(await importOriginal()),
+ rm: vi.fn(() => Promise.resolve()),
+}));
+
vi.mock('../../lib/fileUtils.js', () => ({
PATHS: { imageTo3d: '/mock/data/image-to-3d' },
resolveGalleryImage: vi.fn((filename) => (
@@ -20,7 +25,11 @@ vi.mock('./targets.js', () => ({
vi.mock('./trellis2.js', () => ({
isTrellis2Installed: vi.fn(() => true),
- runTrellis2Generate: vi.fn(() => Promise.resolve({ assetPath: '/mock/data/image-to-3d/x/model.glb' })),
+ // The runner returns a { promise, kill } pair (see runTrellis2Generate).
+ runTrellis2Generate: vi.fn(() => ({
+ promise: Promise.resolve({ assetPath: '/mock/data/image-to-3d/x/model.glb' }),
+ kill: vi.fn(),
+ })),
}));
vi.mock('./db.js', () => ({
@@ -32,10 +41,13 @@ vi.mock('./db.js', () => ({
recoverInterruptedModels: vi.fn(),
}));
+import { rm } from 'node:fs/promises';
import { resolveTarget } from './targets.js';
import { isTrellis2Installed, runTrellis2Generate } from './trellis2.js';
import * as store from './db.js';
-import { createModel, startGeneration, getModelAsset, recoverInterruptedModels } from './models.js';
+import {
+ createModel, startGeneration, getModelAsset, recoverInterruptedModels, deleteModel,
+} from './models.js';
const draftRecord = () => ({
id: 'image3d-example',
@@ -57,7 +69,10 @@ describe('image-to-3D model orchestration', () => {
? { 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' });
+ runTrellis2Generate.mockReturnValue({
+ promise: Promise.resolve({ assetPath: '/mock/data/image-to-3d/x/model.glb' }),
+ kill: vi.fn(),
+ });
});
it('rejects a source that is no longer in the gallery', async () => {
@@ -125,7 +140,10 @@ describe('image-to-3D model orchestration', () => {
if (next) current = next;
return current;
});
- runTrellis2Generate.mockRejectedValue(new Error('TRELLIS.2 generate exited 1'));
+ runTrellis2Generate.mockImplementation(() => ({
+ promise: Promise.reject(new Error('TRELLIS.2 generate exited 1')),
+ kill: vi.fn(),
+ }));
await createModel({ name: 'Beacon', filename: 'example.png' });
await vi.waitFor(() => expect(current.status).toBe('failed'));
@@ -142,6 +160,49 @@ describe('image-to-3D model orchestration', () => {
expect(runTrellis2Generate).not.toHaveBeenCalled();
});
+ it('deleting a record mid-render kills the child and leaves no orphaned GLB', async () => {
+ let current = draftRecord();
+ const killSpy = vi.fn();
+ let rejectRender;
+ runTrellis2Generate.mockReturnValue({
+ promise: new Promise((_, reject) => { rejectRender = reject; }),
+ kill: killSpy,
+ });
+ 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;
+ });
+ store.deleteModel.mockImplementation(async () => {
+ current = {
+ ...current,
+ status: current.status === 'generating' ? 'canceled' : current.status,
+ deleted: true,
+ };
+ return { ok: true };
+ });
+
+ await createModel({ name: 'Beacon', filename: 'example.png' });
+ // The render subprocess spawns inside executeRender (setImmediate) — wait until the
+ // kill handle is registered before deleting.
+ await vi.waitFor(() => expect(runTrellis2Generate).toHaveBeenCalled());
+ expect(current.status).toBe('generating');
+
+ await deleteModel('image3d-example');
+ // The in-flight subprocess is SIGTERM'd promptly.
+ expect(killSpy).toHaveBeenCalled();
+ expect(current.deleted).toBe(true);
+
+ // The killed child settles; executeRender's finally then removes the orphaned dir.
+ rejectRender(Object.assign(new Error('killed'), { code: 'TRELLIS2_GENERATE_FAILED' }));
+ await vi.waitFor(() => expect(rm).toHaveBeenCalledWith(
+ '/mock/data/image-to-3d/image3d-example',
+ expect.objectContaining({ recursive: true, force: true }),
+ ));
+ });
+
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'))
diff --git a/server/services/imageTo3d/trellis2.js b/server/services/imageTo3d/trellis2.js
index b2af05eb22..a894b1d368 100644
--- a/server/services/imageTo3d/trellis2.js
+++ b/server/services/imageTo3d/trellis2.js
@@ -22,6 +22,7 @@ import { existsSync } from 'node:fs';
import { homedir, platform } from 'node:os';
import { join } from 'node:path';
import { spawn } from 'node:child_process';
+import { killWithEscalation } from '../../lib/killWithEscalation.js';
const HOME = homedir();
const IS_WIN = platform() === 'win32';
@@ -278,10 +279,16 @@ export function installTrellis2({
* from a cold boot. `spawnImpl`/`exists` are injectable so the wiring (right command,
* progress streaming, resolve-with-asset) is unit-testable without a real render.
*
+ * Returns `{ promise, kill }` (mirroring `installTrellis2`) so a caller can
+ * terminate the render mid-flight — e.g. when the user deletes the record while
+ * its GLB is still rendering. `kill` routes through the shared
+ * `killWithEscalation` (SIGTERM, then SIGKILL after a grace window if the child
+ * ignored it), the same cancel convention every other spawn-based media job uses.
+ *
* @param {{imagePath: string, outputPath?: string, base?: string,
* onProgress?: (frame: object) => void,
* spawnImpl?: Function, exists?: (p: string) => boolean}} opts
- * @returns {Promise<{assetPath: string}>}
+ * @returns {{promise: Promise<{assetPath: string}>, kill: () => void}}
*/
export function runTrellis2Generate({
imagePath,
@@ -294,14 +301,14 @@ export function runTrellis2Generate({
if (!isTrellis2Installed({ base, exists })) {
const err = new Error('TRELLIS.2 is not installed — install it before generating.');
err.code = 'TRELLIS2_NOT_INSTALLED';
- return Promise.reject(err);
+ return { promise: Promise.reject(err), kill: () => {} };
}
const { command, args } = buildGenerateArgs({ imagePath, outputPath, base });
- return new Promise((resolve, reject) => {
- // Child-process boundary — errors surface via the 'error'/'close' events, not a
- // throw into the request lifecycle (CLAUDE.md child-process exception).
- const child = spawnImpl(command, args, { cwd: trellis2Root(base) });
- let assetPath = outputPath || null;
+ // Child-process boundary — errors surface via the 'error'/'close' events, not a
+ // throw into the request lifecycle (CLAUDE.md child-process exception).
+ const child = spawnImpl(command, args, { cwd: trellis2Root(base) });
+ let assetPath = outputPath || null;
+ const promise = new Promise((resolve, reject) => {
const ingest = (buf) => {
for (const line of String(buf).split('\n')) {
const frame = parseGenerateProgress(line);
@@ -325,4 +332,8 @@ export function runTrellis2Generate({
reject(err);
});
});
+ // Single captured child, never replaced — the helper's own exit check gates the
+ // SIGKILL escalation, so `stillRunning` is unconditionally true here.
+ const kill = () => killWithEscalation(child, { label: 'trellis2 generate', stillRunning: () => true });
+ return { promise, kill };
}
diff --git a/server/services/imageTo3d/trellis2.test.js b/server/services/imageTo3d/trellis2.test.js
index abce673f51..8e67a88ccb 100644
--- a/server/services/imageTo3d/trellis2.test.js
+++ b/server/services/imageTo3d/trellis2.test.js
@@ -115,14 +115,14 @@ describe('runTrellis2Generate', () => {
const child = new EventEmitter();
child.stdout = new EventEmitter();
child.stderr = new EventEmitter();
+ child.kill = vi.fn();
return child;
};
it('rejects without spawning when the model is not installed', async () => {
const spawnImpl = vi.fn();
- await expect(
- runTrellis2Generate({ imagePath: 'a.png', base: BASE, exists: () => false, spawnImpl }),
- ).rejects.toMatchObject({ code: 'TRELLIS2_NOT_INSTALLED' });
+ const { promise } = runTrellis2Generate({ imagePath: 'a.png', base: BASE, exists: () => false, spawnImpl });
+ await expect(promise).rejects.toMatchObject({ code: 'TRELLIS2_NOT_INSTALLED' });
expect(spawnImpl).not.toHaveBeenCalled();
});
@@ -130,7 +130,7 @@ describe('runTrellis2Generate', () => {
const child = makeChild();
const spawnImpl = vi.fn(() => child);
const frames = [];
- const promise = runTrellis2Generate({
+ const { promise } = runTrellis2Generate({
imagePath: 'a.png',
base: BASE,
exists: installed,
@@ -154,7 +154,7 @@ describe('runTrellis2Generate', () => {
it('rejects on a non-zero exit', async () => {
const child = makeChild();
- const promise = runTrellis2Generate({
+ const { promise } = runTrellis2Generate({
imagePath: 'a.png',
outputPath: '/out/a.glb',
base: BASE,
@@ -167,7 +167,7 @@ describe('runTrellis2Generate', () => {
it('rejects when it exits 0 but never reported a .glb', async () => {
const child = makeChild();
- const promise = runTrellis2Generate({
+ const { promise } = runTrellis2Generate({
imagePath: 'a.png',
base: BASE,
exists: installed,
@@ -176,6 +176,20 @@ describe('runTrellis2Generate', () => {
child.emit('close', 0);
await expect(promise).rejects.toMatchObject({ code: 'TRELLIS2_GENERATE_FAILED' });
});
+
+ it('kill() SIGTERMs the running child so a deleted render terminates promptly', async () => {
+ const child = makeChild();
+ const { promise, kill } = runTrellis2Generate({
+ imagePath: 'a.png',
+ base: BASE,
+ exists: installed,
+ spawnImpl: () => child,
+ });
+ kill();
+ expect(child.kill).toHaveBeenCalledWith('SIGTERM');
+ child.emit('close', null); // SIGTERM lands as a non-zero/null exit
+ await expect(promise).rejects.toMatchObject({ code: 'TRELLIS2_GENERATE_FAILED' });
+ });
});
describe('isTransientInstallError', () => {