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: stage uploaded init images into image-refs so they stop duplicating into the gallery
[._.]/ Adam Eivyc07df7918b68
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 1fbe7b9b53..88c5b816d0 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -18,6 +18,8 @@## Fixed+- **Uploaded init/reference images stop duplicating into the gallery on every render** — an uploaded init image (i2i / edit renders) was staged into `data/images`, the very directory the gallery enumerates, so each render dropped a fresh `init-<uuid>.png` copy there and it surfaced as a duplicate "(no prompt)" card alongside the actual output. Init uploads now stage into `data/image-refs` (the sibling dir multi-reference uploads already use — served statically but excluded from the gallery listing), and the Codex i2i path re-anchors through `resolveImageInputPath` so it still finds them. A migration relocates the orphaned staged-upload files prior renders already left in the gallery (moved, not deleted, so they stay reachable as inputs). (`server/services/imageGen/prepareParams.js`, `server/services/imageGen/codex.js`, `scripts/migrations/085-relocate-staged-upload-images-out-of-gallery.js`)+- **Multi-reference FLUX.2 renders no longer crash on `guidance_scale`** — generating with reference images on a FLUX.2-klein model loads the guidance-distilled `Flux2KleinKVPipeline`, whose `__call__()` doesn't accept `guidance_scale`. The runner passed it unconditionally in the base kwargs (only the optional kwargs were signature-filtered), so every multi-reference render died with `TypeError: …got an unexpected keyword argument 'guidance_scale'`. `guidance_scale` is now gated on the live pipeline signature like `negative_prompt`/`strength`/`image`. The same run also silently dropped its LoRA — `set_adapters` raised `'tuple' / int` because `zip(*loaded)` hands diffusers tuples where it does arithmetic over the weights; the adapter names/scales are now passed as lists. (`scripts/flux2_macos.py`, `scripts/lora_utils.py`)- **Single LoRA + init/reference image no longer fails validation** — submitting a local FLUX render with exactly one LoRA selected *and* an init or reference image attached used to 400 with "expected array, received string." The multipart path sends one LoRA as a bare repeated field (the parser only builds an array for two or more), and the route never wrapped it before Zod validation. Single-LoRA submissions over multipart now coerce correctly (matching the existing reference-strengths handling). Two-or-more LoRAs and the JSON path were always fine. (`server/routes/imageGen.js`)diff --git a/scripts/migrations/085-relocate-staged-upload-images-out-of-gallery.js b/scripts/migrations/085-relocate-staged-upload-images-out-of-gallery.jsnew file mode 100644index 0000000000..42f0bd8a52--- /dev/null+++ b/scripts/migrations/085-relocate-staged-upload-images-out-of-gallery.js@@ -0,0 +1,118 @@+/**+ * Relocate staged init/reference upload images out of the gallery directory.+ *+ * Why:+ * Before this change, `prepareGenerateParams` staged uploaded INIT images into+ * `data/images` — the same directory `listGallery()` enumerates. Every i2i /+ * edit render therefore dropped a fresh `init-<uuid>.png` into the gallery dir,+ * and since the gallery lists every `.png` under `data/images`, each staged+ * copy surfaced as a duplicate "(no prompt)" card (the original bug report:+ * the reference/init image duplicated into the gallery on every render).+ *+ * The code fix routes new init uploads into `data/image-refs` (the sibling dir+ * that is served statically but NOT enumerated by the gallery — where multi-+ * reference uploads already land). This migration cleans up the orphans that+ * prior renders already left behind in `data/images` on existing installs.+ *+ * What it does:+ * For each file in `data/images` whose name matches a staged-upload pattern+ * (`init-<uuid>` or `ref-<uuid>` with an image extension) AND has NO sidecar+ * metadata, MOVE it to `data/image-refs`. The two conditions together are the+ * safe discriminator: a genuinely generated gallery image is named+ * `<jobId>.png` (no `init-`/`ref-` prefix) and ALWAYS carries a+ * `<jobId>.metadata.json` sidecar. A staged input upload has the prefix and+ * never gets a sidecar. We require both so a user who happened to import a file+ * literally named `init-….png` WITH a sidecar (treating it as a real gallery+ * entry) is left untouched.+ *+ * Files are MOVED, not deleted — they remain reachable as init/reference+ * inputs from `data/image-refs` (resolveImageInputPath accepts that root), and+ * metadata sidecars on generated images reference them by basename only, which+ * keeps resolving. Lineage is preserved; nothing is destroyed.+ *+ * Dependency-light (fs + path only), per the migration convention.+ *+ * Idempotent: a second run finds no matching files in `data/images` (they were+ * already moved) → no-op. A collision in the target dir (a same-named file+ * already in image-refs — effectively impossible with UUIDs) is left in place+ * and logged, never overwritten.+ */++import { mkdir, readdir, rename, stat } from 'fs/promises';+import { join } from 'path';++const IMAGES_DIR = 'images';+const IMAGE_REFS_DIR = 'image-refs';++// `init-<uuid>` / `ref-<uuid>` with a decodable image extension. The UUID shape+// is loose on purpose (any hex/dash run) so we still catch files staged by older+// builds; the no-sidecar requirement below is what makes the match safe.+const STAGED_UPLOAD_RE = /^(?:init|ref)-[0-9a-f-]+\.(?:png|jpe?g|webp)$/i;++const fileExists = (p) => stat(p).then(() => true).catch(() => false);++// Generated gallery images carry a sidecar at `<name-without-ext>.metadata.json`+// OR the alternate `<name>.metadata.json` shape (see readImageSidecar). A staged+// input upload has neither.+async function hasSidecar(dir, filename) {+ const base = filename.replace(/\.[^.]+$/, '');+ return (+ (await fileExists(join(dir, `${base}.metadata.json`))) ||+ (await fileExists(join(dir, `${filename}.metadata.json`)))+ );+}++export default {+ async up({ rootDir }) {+ const dataDir = join(rootDir, 'data');+ const imagesDir = join(dataDir, IMAGES_DIR);+ const refsDir = join(dataDir, IMAGE_REFS_DIR);++ if (!(await fileExists(imagesDir))) {+ console.log('🖼️ migration 085: no data/images dir — fresh install, no-op');+ return { ok: true, reason: 'no-images-dir' };+ }++ const entries = await readdir(imagesDir, { withFileTypes: true }).catch(() => []);+ const candidates = entries+ .filter((e) => e.isFile() && STAGED_UPLOAD_RE.test(e.name))+ .map((e) => e.name);++ if (candidates.length === 0) {+ console.log('🖼️ migration 085: no staged-upload files in gallery dir — no-op');+ return { ok: true, reason: 'none' };+ }++ let moved = 0;+ let skippedSidecar = 0;+ let skippedCollision = 0;+ // We have candidates, so the refs dir will be needed; mkdir is idempotent.+ await mkdir(refsDir, { recursive: true });++ for (const filename of candidates) {+ // A staged input upload never has a sidecar — a same-named file WITH a+ // sidecar is a real gallery entry the user imported; leave it alone.+ if (await hasSidecar(imagesDir, filename)) {+ skippedSidecar += 1;+ continue;+ }+ const dest = join(refsDir, filename);+ if (await fileExists(dest)) {+ // UUID collision is effectively impossible; never clobber the existing+ // refs file — leave the gallery copy in place and surface it.+ skippedCollision += 1;+ console.log(`🖼️ migration 085: ${filename} already exists in image-refs — left in gallery dir`);+ continue;+ }+ await rename(join(imagesDir, filename), dest);+ moved += 1;+ }++ console.log(+ `🖼️ migration 085: moved ${moved} staged-upload image(s) out of the gallery into image-refs` ++ (skippedSidecar ? `, kept ${skippedSidecar} with sidecars` : '') ++ (skippedCollision ? `, ${skippedCollision} collision(s) left in place` : ''),+ );+ return { ok: true, reason: 'relocated', moved, skippedSidecar, skippedCollision };+ },+};diff --git a/scripts/migrations/085-relocate-staged-upload-images-out-of-gallery.test.js b/scripts/migrations/085-relocate-staged-upload-images-out-of-gallery.test.jsnew file mode 100644index 0000000000..c4c54e6bbb--- /dev/null+++ b/scripts/migrations/085-relocate-staged-upload-images-out-of-gallery.test.js@@ -0,0 +1,89 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync, mkdirSync, writeFileSync, existsSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++import migration from './085-relocate-staged-upload-images-out-of-gallery.js';++describe('migration 085 — relocate staged-upload images out of gallery', () => {+ let rootDir;+ let imagesDir;+ let refsDir;++ const write = (dir, name, body = 'x') => writeFileSync(join(dir, name), body);++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-085-'));+ imagesDir = join(rootDir, 'data', 'images');+ refsDir = join(rootDir, 'data', 'image-refs');+ mkdirSync(imagesDir, { recursive: true });+ });++ afterEach(() => rmSync(rootDir, { recursive: true, force: true }));++ it('moves sidecar-less init-/ref- uploads into image-refs', async () => {+ write(imagesDir, 'init-299d377d-0f13-465c-9e3c-a91860836416.png');+ write(imagesDir, 'ref-2ccd8f2f-f781-4626-a4af-b6da3b4a27da.jpg');++ const res = await migration.up({ rootDir });+ expect(res).toMatchObject({ ok: true, reason: 'relocated', moved: 2 });++ expect(existsSync(join(imagesDir, 'init-299d377d-0f13-465c-9e3c-a91860836416.png'))).toBe(false);+ expect(existsSync(join(refsDir, 'init-299d377d-0f13-465c-9e3c-a91860836416.png'))).toBe(true);+ expect(existsSync(join(refsDir, 'ref-2ccd8f2f-f781-4626-a4af-b6da3b4a27da.jpg'))).toBe(true);+ });++ it('leaves real generated gallery images untouched', async () => {+ write(imagesDir, 'job-abc.png');+ write(imagesDir, 'job-abc.metadata.json', '{}');++ const res = await migration.up({ rootDir });+ expect(res.reason).toBe('none');+ expect(existsSync(join(imagesDir, 'job-abc.png'))).toBe(true);+ });++ it('keeps a prefixed file that has a sidecar (user-imported as a real entry)', async () => {+ write(imagesDir, 'init-deadbeef-0000.png');+ write(imagesDir, 'init-deadbeef-0000.metadata.json', '{}');++ const res = await migration.up({ rootDir });+ expect(res).toMatchObject({ moved: 0, skippedSidecar: 1 });+ expect(existsSync(join(imagesDir, 'init-deadbeef-0000.png'))).toBe(true);+ expect(existsSync(join(refsDir, 'init-deadbeef-0000.png'))).toBe(false);+ });++ it('also recognizes the alternate <name>.metadata.json sidecar shape', async () => {+ write(imagesDir, 'ref-cafe-1111.png');+ write(imagesDir, 'ref-cafe-1111.png.metadata.json', '{}');++ const res = await migration.up({ rootDir });+ expect(res.skippedSidecar).toBe(1);+ expect(existsSync(join(imagesDir, 'ref-cafe-1111.png'))).toBe(true);+ });++ it('never clobbers an existing refs file with the same name', async () => {+ mkdirSync(refsDir, { recursive: true });+ write(imagesDir, 'init-c0111510.png', 'gallery-copy');+ write(refsDir, 'init-c0111510.png', 'refs-copy');++ const res = await migration.up({ rootDir });+ expect(res).toMatchObject({ moved: 0, skippedCollision: 1 });+ // Both copies survive; the refs original is not overwritten.+ expect(existsSync(join(imagesDir, 'init-c0111510.png'))).toBe(true);+ expect(existsSync(join(refsDir, 'init-c0111510.png'))).toBe(true);+ });++ it('is idempotent — a second run is a no-op', async () => {+ write(imagesDir, 'init-abcd-2222.png');+ const first = await migration.up({ rootDir });+ expect(first).toMatchObject({ moved: 1 });+ const second = await migration.up({ rootDir });+ expect(second.reason).toBe('none');+ });++ it('no-op on a fresh install with no images dir', async () => {+ rmSync(imagesDir, { recursive: true, force: true });+ const res = await migration.up({ rootDir });+ expect(res.reason).toBe('no-images-dir');+ });+});diff --git a/server/routes/imageGen.multipart.test.js b/server/routes/imageGen.multipart.test.jsindex 78f6e6fd16..a277e86a0b 100644--- a/server/routes/imageGen.multipart.test.js+++ b/server/routes/imageGen.multipart.test.js@@ -233,9 +233,15 @@ describe('POST /api/image-gen/generate — multipart reference-image packing', (expect(enqueueJob).toHaveBeenCalledTimes(1);const params = enqueueJob.mock.calls[0][0].params;const { dir, name, ext } = parsePath(params.initImagePath);- expect(dir).toBe(imagesSandbox);+ // Init uploads stage into PATHS.imageRefs (sibling of the gallery), NOT+ // PATHS.images — landing in the gallery dir surfaces them as duplicate+ // "(no prompt)" cards because listGallery() enumerates every .png there.+ expect(dir).toBe(refsSandbox);expect(name.startsWith('init-')).toBe(true);expect(ext).toBe('.png');+ // And no file leaked into the gallery dir.+ const imagesDirContents = await readdir(imagesSandbox);+ expect(imagesDirContents).toHaveLength(0);});// The editOnly gate must fire for a text-only submission to an edit-onlydiff --git a/server/services/imageGen/codex.js b/server/services/imageGen/codex.jsindex f028c59027..fecbd1db84 100644--- a/server/services/imageGen/codex.js+++ b/server/services/imageGen/codex.js@@ -24,7 +24,7 @@ import { existsSync } from 'fs';import { join } from 'path';import { homedir } from 'os';import { randomUUID } from 'crypto';-import { ensureDir, PATHS, resolveGalleryImage } from '../../lib/fileUtils.js';+import { ensureDir, PATHS, resolveImageInputPath } from '../../lib/fileUtils.js';import { ServerError } from '../../lib/errorHandler.js';import { autoCleanGeneratedImage } from '../../lib/imageClean.js';import { imageGenEvents } from '../imageGenEvents.js';@@ -149,9 +149,11 @@ export async function generateImage({// Defense-in-depth: HTTP routes already resolve basenames to absolute paths,// but re-anchor here so any future caller can't attach an arbitrary local- // file via the codex CLI's `-i` flag. Mirrors imageGen/local.js.+ // file via the codex CLI's `-i` flag. Mirrors imageGen/local.js — accepts+ // the gallery, the image-refs upload dir (where init uploads are staged), and+ // shipped visual templates.const validInitImagePath = (initImagePath && typeof initImagePath === 'string')- ? resolveGalleryImage(initImagePath)+ ? resolveImageInputPath(initImagePath): null;// An empty prompt is fine when editing an init image (the attached image isdiff --git a/server/services/imageGen/prepareParams.js b/server/services/imageGen/prepareParams.jsindex 94394c87da..14c07e6238 100644--- a/server/services/imageGen/prepareParams.js+++ b/server/services/imageGen/prepareParams.js@@ -114,15 +114,19 @@ export async function prepareGenerateParams({ data, files, referenceImageFields}}- if (initUpload) await ensureDir(PATHS.images);- if (referenceUploads.length) await ensureDir(PATHS.imageRefs);+ if (initUpload || referenceUploads.length) await ensureDir(PATHS.imageRefs);if (initUpload) {// Trust the validated mimetype from the fileFilter — picking the ext// off the original filename can mismatch the bytes (e.g. HEIC saved// as .jpg). MIME_TO_EXT only contains formats the fileFilter accepts.const ext = MIME_TO_EXT[(initUpload.mimetype || '').toLowerCase()] || '.png';const initFilename = `init-${randomUUID()}${ext}`;- initImagePath = join(PATHS.images, initFilename);+ // Stage into PATHS.imageRefs (sibling of the gallery), NOT PATHS.images —+ // listGallery() enumerates every .png in PATHS.images, so an init upload+ // landing there surfaces as a duplicate "(no prompt)" card in the gallery+ // on every i2i/edit render. The runner re-anchors init paths through+ // resolveImageInputPath, which accepts the refs dir.+ initImagePath = join(PATHS.imageRefs, initFilename);await copyFile(initUpload.path, initImagePath);uploadedTempPaths.push(initUpload.path);} else if (data.initImageFile) {