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

fix: unwind a failed local image launch fully — clear active job, reap child, close watcher, reject NUL prompts (#11862)

Adam Eivy8776f65a174f
diff --git a/server/routes/imageGen.js b/server/routes/imageGen.js
index fc84951705..689e146e89 100644
--- a/server/routes/imageGen.js
+++ b/server/routes/imageGen.js
@@ -106,13 +106,17 @@ const galleryImageFilenameSchema = (label) => z.string().max(256)
router.get('/style-presets', (_req, res) => res.json(STYLE_PRESETS));
+// Rejected, never stripped: model input is not silently modified. spawn() also throws on NUL.
+const noNulPrompt = z.string().max(MAX_PROMPT_LENGTH)
+ .refine((v) => !v.includes('\0'), { message: 'Prompt may not contain a NUL character' });
+
const generateSchema = z.object({
promptAdditions: promptAdditionsSchema,
// Empty prompt allowed — i2i / edit / unconditional generation don't require
// one. The multipart FormData builder drops empty-string fields, so an empty
// prompt arrives as `undefined`; default it to '' rather than rejecting.
- prompt: z.string().max(MAX_PROMPT_LENGTH).optional().default(''),
- negativePrompt: z.string().max(MAX_PROMPT_LENGTH).optional(),
+ prompt: noNulPrompt.optional().default(''),
+ negativePrompt: noNulPrompt.optional(),
// Per-request backend override. If omitted, the dispatcher uses
// `imageGen.mode` from settings.json.
mode: z.enum(IMAGE_GEN_MODES).optional(),
diff --git a/server/routes/imageGen.test.js b/server/routes/imageGen.test.js
index 1c695b7848..43cd2a2ec6 100644
--- a/server/routes/imageGen.test.js
+++ b/server/routes/imageGen.test.js
@@ -496,6 +496,15 @@ describe('Image Gen Routes', () => {
expect(response.status).toBe(400);
});
+ it('rejects a NUL character in the prompt or negative prompt with 400 (#11862)', async () => {
+ imageGen.generateImage.mockClear();
+ for (const body of [{ prompt: 'a\u0000b' }, { prompt: 'ok', negativePrompt: 'x\u0000' }]) {
+ const response = await request(app).post('/api/image-gen/generate').send(body);
+ expect(response.status).toBe(400);
+ }
+ expect(imageGen.generateImage).not.toHaveBeenCalled();
+ });
+
it('should pass optional parameters', async () => {
imageGen.generateImage.mockResolvedValue({ generationId: 'gen-002', filename: 'test2.png', path: '/data/images/test2.png' });
diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.js
index 5ed85631ce..f29d9d273a 100644
--- a/server/services/imageGen/local.js
+++ b/server/services/imageGen/local.js
@@ -742,6 +742,7 @@ export async function generateImage({ pythonPath, prompt = '', negativePrompt =
let proc;
let claimHandedOff = false;
let takeEarlyExit = null;
+ let startedEmitted = false;
try {
// `renderPrompt` — the user's prompt plus any LoRA activation tokens it was
// missing (#4665). Identical to `prompt` when nothing was woven.
@@ -768,6 +769,7 @@ export async function generateImage({ pythonPath, prompt = '', negativePrompt =
console.log(`🎨 Generating image [${jobId.slice(0, 8)}] local: ${modelId} ${width}x${height} steps=${actualSteps} references=${validReferenceImagePaths.length}`);
imageGenEvents.emit('started', { generationId: jobId, totalSteps: actualSteps });
+ startedEmitted = true;
activeJob = { ...meta, generationId: jobId, totalSteps: actualSteps, step: 0, progress: 0, currentImage: null, mode: IMAGE_GEN_MODE.LOCAL };
proc = spawn(bin, args, safeChildProcessOptions({ env: childEnv, stdio: ['ignore', 'pipe', 'pipe'] }));
@@ -785,7 +787,20 @@ export async function generateImage({ pythonPath, prompt = '', negativePrompt =
// event — unwind it exactly the way the busy branch above does, or a refusal
// strands a `running` entry and its stepwise dir every time.
if (!claimHandedOff) {
- if (proc?.pid) maintenance.markCurrentUnsettled();
+ if (proc?.pid) {
+ maintenance.markCurrentUnsettled();
+ // No close handler is wired yet, so nothing else will ever reap this child.
+ try {
+ killWithEscalation(proc, { label: 'abandoned image child', stillRunning: () => true });
+ } catch (killErr) {
+ console.error(`❌ Abandoned image child would not stop [${jobId.slice(0, 8)}]: ${killErr.message}`);
+ }
+ }
+ if (activeProcess === proc) activeProcess = null;
+ if (activeJob?.generationId === jobId) activeJob = null;
+ if (startedEmitted) {
+ imageGenEvents.emit('failed', { mode: IMAGE_GEN_MODE.LOCAL, generationId: jobId, error: err.message });
+ }
await releaseHeavyClaim();
jobs.delete(jobId);
await removeStepwise();
@@ -809,6 +824,8 @@ export async function generateImage({ pythonPath, prompt = '', negativePrompt =
const reason = `Failed to spawn ${bin}: ${err.message}`;
console.error(`❌ Image generation spawn error [${jobId.slice(0, 8)}]: ${reason}`);
void releaseHeavyClaim();
+ // The close handler skips its own watcher.close() once finalized.
+ if (watcher) { try { watcher.close(); } catch { /* ignore */ } }
void removeStepwise();
dispatchTerminalEvent(
jobId,
@@ -863,6 +880,11 @@ export async function generateImage({ pythonPath, prompt = '', negativePrompt =
watcher = fsWatch(stepwiseDir, (event) => {
if (event === 'rename') processLatestFrame();
});
+ // Windows raises EPERM here when the watched dir is deleted; with no listener
+ // that is an uncaught exception and the server exits.
+ watcher.on?.('error', (err) => {
+ console.warn(`⚠️ Stepwise watcher error [${jobId.slice(0, 8)}]: ${err?.message}`);
+ });
} catch { /* if watch fails, we still get final image — degrade gracefully */ }
// Bounded tail of recent stderr — only the last ~64KB is kept, since the
diff --git a/server/services/imageGen/local.test.js b/server/services/imageGen/local.test.js
index 6fea9e923c..cd3c4ba483 100644
--- a/server/services/imageGen/local.test.js
+++ b/server/services/imageGen/local.test.js
@@ -1401,3 +1401,65 @@ it('drives a child that dies during the heavy-claim handoff to a terminal state
expect(releaseClaim.mock.calls.length).toBe(releasedBefore + 1);
} finally { claimSpy.mockRestore(); }
});
+
+describe('local render launch unwind (#11862)', () => {
+ const setup = () => {
+ mockResolveFlux2Python.mockReturnValue('/fake/venv-flux2/bin/python3');
+ mockIsFlux2VenvHealthy.mockResolvedValue(true);
+ const child = new EventEmitter();
+ child.stdout = new EventEmitter(); child.stderr = new EventEmitter();
+ child.kill = vi.fn();
+ return child;
+ };
+
+ it('a synchronous spawn throw clears the active job and emits a terminal failure', async () => {
+ setup();
+ mockSpawn.mockImplementationOnce(() => { throw new Error('ERR_INVALID_ARG_VALUE: NUL'); });
+ const { imageGenEvents } = await import('../imageGenEvents.js');
+ const { getActiveJob } = await import('./local.js');
+ const failed = new Promise((resolve) => imageGenEvents.once('failed', resolve));
+ await expect(generateImage({ modelId: 'qwen-image-2.1', prompt: 'spawn throws' })).rejects.toThrow('NUL');
+ expect((await failed).error).toContain('NUL');
+ expect(getActiveJob()).toBeNull();
+ });
+
+ it('a rejected claim handoff kills the spawned child and clears the active process', async () => {
+ const child = setup();
+ child.pid = 5151;
+ mockSpawn.mockReturnValue(child);
+ const heavyJobClaim = await import('../../lib/heavyJobClaim.js');
+ const claimSpy = vi.spyOn(heavyJobClaim, 'claimHeavyLocalJob').mockResolvedValueOnce({
+ ok: true,
+ release: releaseClaim,
+ handoffTo: async () => { throw new Error('ENOSPC: no space left'); },
+ });
+ const { getActiveJob } = await import('./local.js');
+ try {
+ await expect(generateImage({ modelId: 'qwen-image-2.1', prompt: 'handoff fails' })).rejects.toThrow('ENOSPC');
+ expect(child.kill).toHaveBeenCalledWith('SIGTERM');
+ expect(getActiveJob()).toBeNull();
+ } finally { claimSpy.mockRestore(); }
+ });
+
+ it('a spawn ENOENT closes the stepwise watcher, which carries an error listener', async () => {
+ const child = setup();
+ const fsMod = await import('fs');
+ const watcher = Object.assign(new EventEmitter(), { close: vi.fn() });
+ fsMod.watch.mockReturnValueOnce(watcher);
+ mockSpawn.mockReturnValue(child);
+ const heavyJobClaim = await import('../../lib/heavyJobClaim.js');
+ const claimSpy = vi.spyOn(heavyJobClaim, 'claimHeavyLocalJob').mockResolvedValueOnce({
+ ok: true,
+ release: releaseClaim,
+ handoffTo: async () => { child.emit('error', Object.assign(new Error('spawn ENOENT'), { code: 'ENOENT' })); },
+ });
+ const { imageGenEvents } = await import('../imageGenEvents.js');
+ const failed = new Promise((resolve) => imageGenEvents.once('failed', resolve));
+ try {
+ await generateImage({ modelId: 'qwen-image-2.1', prompt: 'enoent' });
+ await failed;
+ expect(watcher.close).toHaveBeenCalled();
+ expect(watcher.listenerCount('error')).toBeGreaterThan(0);
+ } finally { claimSpy.mockRestore(); }
+ });
+});