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

address review round 5: 4 Copilot findings on PR #181

Adam Eivybb828bd8f787
diff --git a/server/routes/imageGen.test.js b/server/routes/imageGen.test.js
index 78b94ccf84..b9ab198ce9 100644
--- a/server/routes/imageGen.test.js
+++ b/server/routes/imageGen.test.js
@@ -49,6 +49,20 @@ describe('Image Gen Routes', () => {
expect(response.status).toBe(200);
expect(response.body.connected).toBe(false);
});
+
+ it('forwards a valid ?mode= query into checkConnection', async () => {
+ imageGen.checkConnection.mockResolvedValue({ connected: true, mode: 'codex' });
+ const response = await request(app).get('/api/image-gen/status?mode=codex');
+ expect(response.status).toBe(200);
+ expect(imageGen.checkConnection).toHaveBeenCalledWith({ mode: 'codex' });
+ });
+
+ it('ignores an invalid ?mode= query and uses the saved default', async () => {
+ imageGen.checkConnection.mockResolvedValue({ connected: true, mode: 'external' });
+ const response = await request(app).get('/api/image-gen/status?mode=bogus');
+ expect(response.status).toBe(200);
+ expect(imageGen.checkConnection).toHaveBeenCalledWith({ mode: undefined });
+ });
});
describe('POST /api/image-gen/generate', () => {
@@ -128,4 +142,31 @@ describe('Image Gen Routes', () => {
expect(response.status).toBe(200);
});
});
+
+ // GET /:jobId/events and POST /cancel both go through the dispatcher's
+ // attachSseClient/cancel — these tests lock in that contract so a future
+ // refactor can't accidentally re-couple them to the local provider.
+ describe('SSE attach + cancel via dispatcher', () => {
+ it('GET /:jobId/events returns 404 when no provider owns the job', async () => {
+ imageGen.attachSseClient.mockReturnValueOnce(false);
+ const response = await request(app).get('/api/image-gen/missing-job/events');
+ expect(response.status).toBe(404);
+ expect(imageGen.attachSseClient).toHaveBeenCalledWith('missing-job', expect.anything());
+ });
+
+ it('POST /cancel returns ok=false when no provider had a job', async () => {
+ imageGen.cancel.mockReturnValueOnce(false);
+ const response = await request(app).post('/api/image-gen/cancel');
+ expect(response.status).toBe(200);
+ expect(response.body.ok).toBe(false);
+ expect(imageGen.cancel).toHaveBeenCalled();
+ });
+
+ it('POST /cancel returns ok=true when a provider cancelled', async () => {
+ imageGen.cancel.mockReturnValueOnce(true);
+ const response = await request(app).post('/api/image-gen/cancel');
+ expect(response.status).toBe(200);
+ expect(response.body.ok).toBe(true);
+ });
+ });
});
diff --git a/server/services/imageGen/codex.js b/server/services/imageGen/codex.js
index 97ab883e18..75279732b4 100644
--- a/server/services/imageGen/codex.js
+++ b/server/services/imageGen/codex.js
@@ -155,11 +155,20 @@ async function runCodex(job, jobId, bin, args, outputPath, filename, meta) {
}
}, CODEX_TIMEOUT_MS);
+ // Banner is roughly 12 lines / ~500 bytes — keep a small rolling
+ // buffer so a session-id line that gets split across chunk boundaries
+ // (Node streams can land each pipe write as its own 'data' event)
+ // still matches. Trim aggressively after a match to keep this tiny.
+ let bannerBuf = '';
+ const BANNER_BUF_MAX = 4 * 1024;
const captureSession = (text) => {
if (sessionId) return;
- const m = text.match(SESSION_ID_RE);
+ bannerBuf += text;
+ if (bannerBuf.length > BANNER_BUF_MAX) bannerBuf = bannerBuf.slice(-BANNER_BUF_MAX);
+ const m = bannerBuf.match(SESSION_ID_RE);
if (m) {
sessionId = m[1];
+ bannerBuf = '';
broadcastSse(job, { type: 'status', message: `Codex session ${sessionId.slice(0, 8)}…` });
}
};
diff --git a/server/services/voice/tools.js b/server/services/voice/tools.js
index 207feed0ea..bf3bd9e365 100644
--- a/server/services/voice/tools.js
+++ b/server/services/voice/tools.js
@@ -14,6 +14,7 @@ import * as journal from '../brainJournal.js';
import { resolveNavCommand, normalizeLabel } from '../../lib/navManifest.js';
import { runAsk, VALID_MODES as ASK_VALID_MODES } from '../askService.js';
import * as imageGen from '../imageGen/index.js';
+import { imageGenEvents } from '../imageGenEvents.js';
import { getSettings } from '../settings.js';
const DAILY_LOG_PATH = '/brain/daily-log';
@@ -1118,20 +1119,74 @@ const TOOLS = [
if (!w.ok) return w;
const h = normalizeDimension(height, 'height');
if (!h.ok) return h;
- const result = await imageGen.generateImage({
- prompt: prompt.trim(),
- negativePrompt: negativePrompt?.trim() || undefined,
- width: w.value,
- height: h.value,
- mode: requestedMode,
- });
+ // Local + codex backends return a job descriptor synchronously and
+ // emit 'completed'/'failed' on imageGenEvents when the file actually
+ // lands. Subscribe BEFORE calling generateImage so a fast job can't
+ // emit 'completed' before we attach. External backends await the
+ // upstream HTTP call internally and the file is on disk by the time
+ // generateImage resolves — wait() is a no-op there.
+ let resolveDone, rejectDone;
+ const completionPromise = new Promise((res, rej) => { resolveDone = res; rejectDone = rej; });
+ let registeredId = null;
+ const onCompleted = (ev) => { if (ev.generationId === registeredId) cleanup(resolveDone, ev); };
+ const onFailed = (ev) => { if (ev.generationId === registeredId) cleanup(rejectDone, ev); };
+ const cleanup = (fn, ev) => {
+ clearTimeout(timeout);
+ imageGenEvents.off('completed', onCompleted);
+ imageGenEvents.off('failed', onFailed);
+ fn(ev);
+ };
+ // 5-min cap mirrors the codex provider's own timeout — a stuck job
+ // shouldn't leak listeners into the voice/palette dispatcher forever.
+ const timeout = setTimeout(() => cleanup(rejectDone, { error: 'image generation timed out' }), 5 * 60 * 1000);
+ imageGenEvents.on('completed', onCompleted);
+ imageGenEvents.on('failed', onFailed);
+ // Swallow unhandled rejection if generateImage throws before we
+ // register; the catch block below handles it.
+ completionPromise.catch(() => {});
+
+ let result;
+ try {
+ result = await imageGen.generateImage({
+ prompt: prompt.trim(),
+ negativePrompt: negativePrompt?.trim() || undefined,
+ width: w.value,
+ height: h.value,
+ mode: requestedMode,
+ });
+ } catch (err) {
+ cleanup(() => {}, null);
+ return { ok: false, summary: `Image generation failed: ${err?.message || err}` };
+ }
+
const usedMode = result?.mode || requestedMode || 'default';
+ const isAsync = usedMode === 'local' || usedMode === 'codex';
+ // External resolves with the file already on disk — short-circuit.
+ if (!isAsync) {
+ cleanup(() => {}, null);
+ return {
+ ok: true,
+ path: result?.path,
+ filename: result?.filename,
+ mode: usedMode,
+ summary: `Generated image (${usedMode}): ${result?.filename || 'pending'}`,
+ };
+ }
+
+ registeredId = result.generationId;
+ const ev = await completionPromise.catch((errEv) => ({ __failed: true, ...errEv }));
+ if (ev?.__failed) {
+ return { ok: false, summary: `Image generation failed: ${ev.error || 'unknown'}` };
+ }
+ // The 'completed' event carries the canonical path/filename — prefer
+ // it over the descriptor returned by generateImage (which may not
+ // have the final filename in some providers).
return {
ok: true,
- path: result?.path,
- filename: result?.filename,
+ path: ev?.path || result?.path,
+ filename: ev?.filename || result?.filename,
mode: usedMode,
- summary: `Generating image (${usedMode}): ${result?.filename || 'pending'}`,
+ summary: `Generated image (${usedMode}): ${ev?.filename || result?.filename}`,
};
},
},
diff --git a/server/services/voice/tools.test.js b/server/services/voice/tools.test.js
index b4b1ca904a..a78560ae64 100644
--- a/server/services/voice/tools.test.js
+++ b/server/services/voice/tools.test.js
@@ -34,10 +34,34 @@ vi.mock('../feeds.js', () => ({
}));
// imageGen dispatcher — tests pin the dispatch and let us assert what mode
// the voice tool forwards. The settings mock controls the codex-enabled gate.
-const generateImageMock = vi.fn(async (params) => ({
- filename: 'mock.png', path: '/data/images/mock.png', mode: params?.mode || 'external',
-}));
+// For async modes (local/codex) the mock also simulates the per-provider
+// 'completed' event the real providers emit on imageGenEvents — without
+// that, the tool's await would hang for 5 minutes.
const codexEnabledRef = { value: false };
+
+// Hoisting note: vi.mock factories run before the module under test loads,
+// so we can't import imageGenEvents up here. Instead, do the import lazily
+// inside the mock factory using vi.importActual.
+let _imageGenEvents = null;
+const getEvents = async () => {
+ if (!_imageGenEvents) _imageGenEvents = (await vi.importActual('../imageGenEvents.js')).imageGenEvents;
+ return _imageGenEvents;
+};
+
+const generateImageMock = vi.fn(async (params) => {
+ const mode = params?.mode || 'external';
+ const generationId = `mock-${Math.random().toString(36).slice(2, 10)}`;
+ const result = { generationId, filename: 'mock.png', path: '/data/images/mock.png', mode };
+ if (mode === 'local' || mode === 'codex') {
+ // Fire the completion event after generateImage resolves so the tool
+ // has time to register its listener with the captured generationId.
+ setImmediate(async () => {
+ const events = await getEvents();
+ events.emit('completed', { generationId, path: result.path, filename: result.filename });
+ });
+ }
+ return result;
+});
vi.mock('../imageGen/index.js', () => ({
generateImage: (...args) => generateImageMock(...args),
IMAGE_GEN_MODES: ['external', 'local', 'codex'],
@@ -514,4 +538,34 @@ describe("image_generate", () => {
expect(r.ok).toBe(false);
expect(r.summary).toMatch(/height must be an integer between 64 and 2048/);
});
+
+ // The tool returns synchronously for external (file is already on disk)
+ // but for local/codex it must await the imageGenEvents 'completed' event
+ // — otherwise the palette toast says "image generated" before the file
+ // actually exists.
+ it("waits for imageGenEvents 'completed' on async modes (local) before resolving", async () => {
+ generateImageMock.mockClear();
+ const r = await dispatchTool("image_generate", { prompt: "a fox", provider: "local" });
+ expect(r.ok).toBe(true);
+ expect(r.mode).toBe("local");
+ expect(r.summary).toMatch(/^Generated image \(local\)/);
+ });
+
+ it("returns ok:false when imageGenEvents emits 'failed' for async modes", async () => {
+ codexEnabledRef.value = true;
+ generateImageMock.mockClear();
+ // Override the default mock to emit 'failed' instead of 'completed'.
+ generateImageMock.mockImplementationOnce(async (params) => {
+ const generationId = `mockfail-${Math.random().toString(36).slice(2, 8)}`;
+ setImmediate(async () => {
+ const events = await getEvents();
+ events.emit('failed', { generationId, error: 'mock provider failure' });
+ });
+ return { generationId, filename: 'mock.png', path: '/data/images/mock.png', mode: params.mode };
+ });
+ const r = await dispatchTool("image_generate", { prompt: "a fox", provider: "codex" });
+ expect(r.ok).toBe(false);
+ expect(r.summary).toMatch(/mock provider failure/);
+ codexEnabledRef.value = false;
+ });
});