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
fix([issue-4916]): clear external image jobs on terminal states
[._.]/ Adam Eivyd6b1655654b6
diff --git a/server/services/imageGen/external.js b/server/services/imageGen/external.jsindex 51550013e7..cf0bc0b046 100644--- a/server/services/imageGen/external.js+++ b/server/services/imageGen/external.js@@ -62,7 +62,8 @@ function startProgressPolling(baseUrl, generationId) {let lastProgress = -1;let lastImageEmit = 0;let inFlight = false;- const interval = setInterval(async () => {+ let interval;+ const poll = async () => {if (inFlight) return;inFlight = true;try {@@ -93,10 +94,14 @@ function startProgressPolling(baseUrl, generationId) {activeJob.totalSteps = data.state?.sampling_steps ?? activeJob.totalSteps;if (includeImage) activeJob.currentImage = data.current_image;}+ } catch (err) {+ clearInterval(interval);+ console.error(`❌ External image generation progress polling failed: ${err.message}`);} finally {inFlight = false;}- }, PROGRESS_POLL_INTERVAL);+ };+ interval = setInterval(() => { void poll(); }, PROGRESS_POLL_INTERVAL);return () => clearInterval(interval);}@@ -135,47 +140,43 @@ export async function generateImage({ sdapiUrl, prompt, negativePrompt, width, h};const stopPolling = startProgressPolling(baseUrl, generationId);-- let res;try {- res = await fetchWithTimeout(+ const res = await fetchWithTimeout(`${baseUrl}/sdapi/v1/txt2img`,{ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) },300000);- } catch (err) {- stopPolling();- activeJob = null;- imageGenEvents.emit('failed', { mode: IMAGE_GEN_MODE.EXTERNAL, generationId, error: 'Network error contacting image generation service' });- throw err;- }- stopPolling();-- if (!res.ok) {- const errBody = await res.text().catch(() => '');- activeJob = null;- imageGenEvents.emit('failed', { mode: IMAGE_GEN_MODE.EXTERNAL, generationId, error: `SD API error ${res.status}` });- throw new Error(`SD API error ${res.status}: ${errBody.slice(0, 200)}`);- }+ if (!res.ok) {+ const errBody = await res.text().catch(() => '');+ throw new Error(`SD API error ${res.status}: ${errBody.slice(0, 200)}`);+ }- const data = await res.json();- if (!data.images?.length) {+ const data = await res.json();+ if (!data.images?.length) throw new Error('SD API returned no images');++ await ensureDir(PATHS.images);+ const filename = `${randomUUID()}.png`;+ const pngPath = join(PATHS.images, filename);+ await writeFile(pngPath, Buffer.from(data.images[0], 'base64'));+ // Auto-clean BEFORE the SSE complete fires so the URL the client opens+ // serves the cleaned bytes. External mode has no sidecar — pass null so+ // the helper just patches the PNG in place.+ await autoCleanGeneratedImage({ cleanC2PA, denoise, pngPath, sidecarPath: null, mode: IMAGE_GEN_MODE.EXTERNAL });+ const path = `/data/images/${filename}`;+ console.log(`🖼️ Image saved: ${filename}`);activeJob = null;- imageGenEvents.emit('failed', { mode: IMAGE_GEN_MODE.EXTERNAL, generationId, error: 'No images returned' });- throw new Error('SD API returned no images');+ imageGenEvents.emit('completed', { mode: IMAGE_GEN_MODE.EXTERNAL, generationId, path, filename });+ return { generationId, filename, path, mode: IMAGE_GEN_MODE.EXTERNAL, model };+ } catch (err) {+ if (activeJob?.generationId === generationId) activeJob = null;+ imageGenEvents.emit('failed', {+ mode: IMAGE_GEN_MODE.EXTERNAL,+ generationId,+ error: err.message === 'fetch failed' ? 'Network error contacting image generation service' : err.message,+ });+ throw err;+ } finally {+ stopPolling();+ if (activeJob?.generationId === generationId) activeJob = null;}-- await ensureDir(PATHS.images);- const filename = `${randomUUID()}.png`;- const pngPath = join(PATHS.images, filename);- await writeFile(pngPath, Buffer.from(data.images[0], 'base64'));- // Auto-clean BEFORE the SSE complete fires so the URL the client opens- // serves the cleaned bytes. External mode has no sidecar — pass null so- // the helper just patches the PNG in place.- await autoCleanGeneratedImage({ cleanC2PA, denoise, pngPath, sidecarPath: null, mode: IMAGE_GEN_MODE.EXTERNAL });- const path = `/data/images/${filename}`;- console.log(`🖼️ Image saved: ${filename}`);- activeJob = null;- imageGenEvents.emit('completed', { mode: IMAGE_GEN_MODE.EXTERNAL, generationId, path, filename });- return { generationId, filename, path, mode: IMAGE_GEN_MODE.EXTERNAL, model };}diff --git a/server/services/imageGen/external.test.js b/server/services/imageGen/external.test.jsnew file mode 100644index 0000000000..8290988b2a--- /dev/null+++ b/server/services/imageGen/external.test.js@@ -0,0 +1,67 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const { fetchWithTimeout, imageGenEvents } = vi.hoisted(() => ({+ fetchWithTimeout: vi.fn(),+ imageGenEvents: { emit: vi.fn() },+}));++vi.mock('../../lib/fetchWithTimeout.js', () => ({ fetchWithTimeout }));+vi.mock('fs/promises', () => ({ writeFile: vi.fn() }));+vi.mock('../../lib/fileUtils.js', () => ({+ ensureDir: vi.fn(),+ PATHS: { images: '/tmp/portos-external-image-test' },+}));+vi.mock('../../lib/imageClean.js', () => ({ autoCleanGeneratedImage: vi.fn() }));+vi.mock('../imageGenEvents.js', () => ({ imageGenEvents }));++import { generateImage, getActiveJob } from './external.js';++const response = (json) => ({ ok: true, json: vi.fn().mockResolvedValue(json) });++beforeEach(() => {+ fetchWithTimeout.mockReset();+ imageGenEvents.emit.mockReset();+ vi.spyOn(console, 'error').mockImplementation(() => {});+});++describe('external image generation lifecycle', () => {+ it('clears activeJob and emits a failure when a terminal response cannot be read', async () => {+ fetchWithTimeout+ .mockResolvedValueOnce(response({ sd_model_checkpoint: 'example-model' }))+ .mockResolvedValueOnce({ ok: true, json: vi.fn().mockRejectedValue(new Error('malformed response')) });++ await expect(generateImage({ sdapiUrl: 'http://example.com', prompt: 'a test image' }))+ .rejects.toThrow('malformed response');++ expect(getActiveJob()).toBeNull();+ expect(imageGenEvents.emit).toHaveBeenCalledWith('failed', expect.objectContaining({ error: 'malformed response' }));+ });++ it('clears the polling interval when an unexpected progress handler error occurs', async () => {+ vi.useFakeTimers();+ const progressError = new Error('progress handler failed');+ imageGenEvents.emit.mockImplementation((event) => {+ if (event === 'progress') throw progressError;+ });+ let resolveGeneration;+ const generation = new Promise((resolve) => { resolveGeneration = resolve; });+ fetchWithTimeout+ .mockResolvedValueOnce(response({ sd_model_checkpoint: 'example-model' }))+ .mockReturnValueOnce(generation)+ .mockResolvedValueOnce(response({ progress: 0.5, state: {} }));++ const pending = generateImage({ sdapiUrl: 'http://example.test', prompt: 'a test image' });+ await Promise.resolve();+ await Promise.resolve();+ await vi.advanceTimersByTimeAsync(500);+ expect(console.error).toHaveBeenCalledWith(expect.stringContaining('progress handler failed'));+ expect(fetchWithTimeout).toHaveBeenCalledTimes(3);++ await vi.advanceTimersByTimeAsync(1_000);+ expect(fetchWithTimeout).toHaveBeenCalledTimes(3);+ resolveGeneration(response({ images: ['aW1hZ2U='] }));+ await pending;+ vi.useRealTimers();+ });++});