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: use prior FableLoom shots as references

Adam Eivy6f02ada5df12
diff --git a/client/src/components/fableloom/sceneMediaRequests.js b/client/src/components/fableloom/sceneMediaRequests.js
index 4a40d42be3..ae51d48cd1 100644
--- a/client/src/components/fableloom/sceneMediaRequests.js
+++ b/client/src/components/fableloom/sceneMediaRequests.js
@@ -17,8 +17,8 @@ const withLoomStyle = (prompt, styleNotes) => {
return notes ? `${prompt}\n\nStyle: ${notes}` : prompt;
};
-// Match Image Gen's established i2i default: strong enough to carry likeness
-// and environment forward without pinning the next shot to the same pose.
+// Keep enough reference influence to carry likeness and environment forward
+// without asking the model to preserve the prior shot's composition.
export const FABLELOOM_CONTINUITY_STRENGTH = 0.4;
/**
@@ -48,8 +48,8 @@ export function buildFableLoomImageRequest({ loom, episode, episodeId, node, sty
prompt: styled.prompt,
...(styled.negativePrompt ? { negativePrompt: styled.negativePrompt } : {}),
...(priorImage ? {
- initImageFile: priorImage,
- initImageStrength: FABLELOOM_CONTINUITY_STRENGTH,
+ referenceImageFiles: [priorImage],
+ referenceStrengths: [FABLELOOM_CONTINUITY_STRENGTH],
} : {}),
fableLoom: { loomId: loom.id, episodeId, nodeId: node.id },
};
diff --git a/client/src/components/fableloom/sceneMediaRequests.test.js b/client/src/components/fableloom/sceneMediaRequests.test.js
index 477e0b2625..79afd3ca7e 100644
--- a/client/src/components/fableloom/sceneMediaRequests.test.js
+++ b/client/src/components/fableloom/sceneMediaRequests.test.js
@@ -33,8 +33,8 @@ describe('FableLoom scene media request composition', () => {
expect(buildFableLoomImageRequest({ loom, episode, episodeId: 'ep-1', node: target }))
.toMatchObject({
- initImageFile: 'prior-shot.png',
- initImageStrength: 0.4,
+ referenceImageFiles: ['prior-shot.png'],
+ referenceStrengths: [0.4],
});
});
diff --git a/client/src/pages/FableLoomStory.jsx b/client/src/pages/FableLoomStory.jsx
index 4ba7ba4f28..04569ccee2 100644
--- a/client/src/pages/FableLoomStory.jsx
+++ b/client/src/pages/FableLoomStory.jsx
@@ -47,7 +47,8 @@ import {
const CONTINUITY_FALLBACK_CODES = new Set([
'IMAGE_EDIT_UNSUPPORTED_MODE',
- 'INIT_IMAGE_NOT_FOUND',
+ 'REFERENCE_IMAGE_NOT_FOUND',
+ 'REFERENCE_IMAGES_FLUX2_ONLY',
]);
export default function FableLoomStory({ view = 'graph' }) {
@@ -249,7 +250,7 @@ export default function FableLoomStory({ view = 'graph' }) {
});
if (!queued) return null;
if (continuityFallbackCode) {
- toast.warning(continuityFallbackCode === 'INIT_IMAGE_NOT_FOUND'
+ toast.warning(continuityFallbackCode === 'REFERENCE_IMAGE_NOT_FOUND'
? 'The prior shot image is missing — rendering this scene without continuity conditioning'
: 'The current image backend cannot use the prior shot — rendering this scene without continuity conditioning');
}
diff --git a/client/src/pages/FableLoomStory.test.jsx b/client/src/pages/FableLoomStory.test.jsx
index 70e8df125a..4a49bb8809 100644
--- a/client/src/pages/FableLoomStory.test.jsx
+++ b/client/src/pages/FableLoomStory.test.jsx
@@ -292,8 +292,8 @@ describe('FableLoomStory scene media lifecycle', () => {
await waitFor(() => expect(api.generateImage).toHaveBeenCalledWith({
prompt: 'the same scout crosses into the observatory',
- initImageFile: 'threshold.png',
- initImageStrength: 0.4,
+ referenceImageFiles: ['threshold.png'],
+ referenceStrengths: [0.4],
fableLoom: { loomId: 'loom-1', episodeId: 'ep-1', nodeId: 'node-2' },
}, { silent: true }));
});
@@ -326,7 +326,7 @@ describe('FableLoomStory scene media lifecycle', () => {
await user.click(await screen.findByRole('button', { name: 'Canvas generate second image' }));
await waitFor(() => expect(api.generateImage).toHaveBeenCalledTimes(2));
- expect(api.generateImage.mock.calls[0][0]).toMatchObject({ initImageFile: 'threshold.png' });
+ expect(api.generateImage.mock.calls[0][0]).toMatchObject({ referenceImageFiles: ['threshold.png'] });
expect(api.generateImage.mock.calls[1]).toEqual([{
prompt: 'the scout enters the observatory',
fableLoom: { loomId: 'loom-1', episodeId: 'ep-1', nodeId: 'node-2' },
diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.json
index 6482867cb9..f7406b2691 100644
--- a/server/lib/apiRouteCatalog.generated.json
+++ b/server/lib/apiRouteCatalog.generated.json
@@ -10011,7 +10011,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 746
+ "line": 750
}
]
},
@@ -10022,7 +10022,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 770
+ "line": 774
}
]
},
@@ -10033,7 +10033,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 765
+ "line": 769
}
]
},
@@ -10044,7 +10044,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 799
+ "line": 803
}
]
},
@@ -10055,7 +10055,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 784
+ "line": 788
}
]
},
@@ -10066,7 +10066,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 761
+ "line": 765
}
]
},
@@ -10077,7 +10077,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 689
+ "line": 693
}
]
},
@@ -10088,7 +10088,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 331
+ "line": 335
}
]
},
@@ -10099,7 +10099,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 335
+ "line": 339
}
]
},
@@ -10110,7 +10110,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 557
+ "line": 561
}
]
},
@@ -10121,7 +10121,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 695
+ "line": 699
}
]
},
@@ -10132,7 +10132,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 680
+ "line": 684
}
]
},
@@ -10143,7 +10143,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 381
+ "line": 385
}
]
},
@@ -10154,7 +10154,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 676
+ "line": 680
}
]
},
@@ -10165,7 +10165,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 579
+ "line": 583
}
]
},
@@ -10176,7 +10176,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 657
+ "line": 661
}
]
},
@@ -10187,7 +10187,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 638
+ "line": 642
}
]
},
@@ -10198,7 +10198,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 590
+ "line": 594
}
]
},
@@ -10209,7 +10209,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 618
+ "line": 622
}
]
},
@@ -10220,7 +10220,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 348
+ "line": 352
}
]
},
@@ -10330,7 +10330,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 317
+ "line": 321
}
]
},
@@ -10341,7 +10341,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 60
+ "line": 62
}
]
},
@@ -10352,7 +10352,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 573
+ "line": 577
}
]
},
diff --git a/server/routes/imageGen.js b/server/routes/imageGen.js
index a946f9c6cb..109e667287 100644
--- a/server/routes/imageGen.js
+++ b/server/routes/imageGen.js
@@ -56,6 +56,8 @@ const MAX_LORAS = 8;
const MAX_REFERENCE_IMAGES = 4;
const MAX_IMAGE_UPLOAD_BYTES = 20 * 1024 * 1024;
const updatePromptSchema = z.object({ prompt: z.string().max(MAX_PROMPT_LENGTH) });
+const galleryImageFilenameSchema = (label) => z.string().max(256)
+ .regex(/^[^/\\]+\.(png|jpg|jpeg|webp)$/i, `${label} must be a basename ending in png/jpg/jpeg/webp`);
router.get('/style-presets', (_req, res) => res.json(STYLE_PRESETS));
@@ -94,16 +96,18 @@ const generateSchema = z.object({
// i2i: pick an existing gallery image (basename) as the init image. If
// initImage was uploaded via multipart, this is ignored in favor of the
// upload. Strength: 0.0 = ignore source, 1.0 = max influence.
- initImageFile: z.string().max(256).regex(/^[^/\\]+\.(png|jpg|jpeg|webp)$/i, 'init image must be a basename ending in png/jpg/jpeg/webp').optional(),
+ initImageFile: galleryImageFilenameSchema('init image').optional(),
initImageStrength: z.number().min(0).max(1).optional(),
// Multi-reference image conditioning. Up to 4 reference images are uploaded
- // as separate multipart fields `referenceImage1` … `referenceImage4`;
+ // as separate multipart fields `referenceImage1` … `referenceImage4`, or
+ // named from the existing gallery through JSON `referenceImageFiles`;
// `referenceStrengths` is a parallel array of weights (0.0 = ignore the
- // reference, 1.0 = full influence). The schema only constrains the strengths
- // array — file presence is enforced at the upload layer, and the route
- // pairs filled slots with their strengths positionally. Strengths are honored
+ // reference, 1.0 = full influence), ordered as named files then uploads.
+ // Uploaded file presence is enforced at the upload layer, and the route
+ // pairs all surviving slots with their strengths positionally. Strengths are honored
// numerically only by local FLUX.2; the cloud CLIs expose no per-reference
// weight, so they receive the paths alone.
+ referenceImageFiles: z.array(galleryImageFilenameSchema('reference image')).max(MAX_REFERENCE_IMAGES).optional(),
referenceStrengths: z.array(z.number().min(0).max(1)).max(MAX_REFERENCE_IMAGES).optional(),
// Per-render override of the cleaners. When omitted, the route inherits
// from `settings.imageGen.{mode}.{cleanC2PA,denoise}`. Explicit booleans
diff --git a/server/routes/imageGen.multipart.test.js b/server/routes/imageGen.multipart.test.js
index a2a708a38c..1badf6c592 100644
--- a/server/routes/imageGen.multipart.test.js
+++ b/server/routes/imageGen.multipart.test.js
@@ -1,7 +1,7 @@
import { describe, it, expect, beforeEach, beforeAll, afterAll, vi } from 'vitest';
import express from 'express';
import { createServer } from 'http';
-import { mkdtemp, rm, readdir, readFile, unlink } from 'fs/promises';
+import { mkdtemp, rm, readdir, readFile, unlink, writeFile } from 'fs/promises';
import { join, parse as parsePath } from 'path';
import { tmpdir } from 'os';
import { errorMiddleware } from '../lib/errorHandler.js';
@@ -14,12 +14,11 @@ let refsSandbox;
vi.mock('../lib/fileUtils.js', async () => {
const actual = await vi.importActual('../lib/fileUtils.js');
- return {
- ...actual,
- get PATHS() {
- return { ...actual.PATHS, images: imagesSandbox, imageRefs: refsSandbox };
- },
- };
+ // Mutate the shared PATHS object so both direct route reads and helper
+ // closures such as resolveGalleryImage use the sandbox roots.
+ actual.PATHS.images = imagesSandbox;
+ actual.PATHS.imageRefs = refsSandbox;
+ return { ...actual };
});
// These tests exercise multipart packing and edit-only validation, not host
@@ -125,8 +124,7 @@ function buildMultipart(parts) {
};
}
-async function postMultipart(app, path, parts) {
- const { body, contentType } = buildMultipart(parts);
+async function postBody(app, path, body, contentType) {
const server = createServer(app);
await new Promise((resolve, reject) => {
server.listen(0, '127.0.0.1', resolve);
@@ -150,6 +148,18 @@ async function postMultipart(app, path, parts) {
}
}
+async function postMultipart(app, path, parts) {
+ const { body, contentType } = buildMultipart(parts);
+ return postBody(app, path, body, contentType);
+}
+
+const postJson = (app, path, body) => postBody(
+ app,
+ path,
+ JSON.stringify(body),
+ 'application/json',
+);
+
describe('POST /api/image-gen/generate — multipart reference-image packing', () => {
let app;
@@ -212,6 +222,24 @@ describe('POST /api/image-gen/generate — multipart reference-image packing', (
expect(imagesDirContents.filter((f) => f.startsWith('ref-'))).toHaveLength(0);
});
+ it('resolves a gallery image as a reference for a new conditioned render, not an init edit', async () => {
+ mockedSettings = { imageGen: { mode: 'codex', codex: { enabled: true } } };
+ await writeFile(join(imagesSandbox, 'prior-shot.png'), PNG_FIXTURE);
+
+ const res = await postJson(app, '/api/image-gen/generate', {
+ prompt: 'the same scout from a new camera angle',
+ referenceImageFiles: ['prior-shot.png'],
+ referenceStrengths: [0.4],
+ });
+
+ expect(res.status).toBe(200);
+ const { params } = enqueueJob.mock.calls.at(-1)[0];
+ expect(params.referenceImagePaths).toEqual([join(imagesSandbox, 'prior-shot.png')]);
+ expect(params.referenceImageStrengths).toEqual([0.4]);
+ expect(params.initImagePath).toBeUndefined();
+ expect(params.referenceImageFiles).toBeUndefined();
+ });
+
it('packs only the filled slots (gaps in the slot numbering collapse to a packed array)', async () => {
const res = await postMultipart(app, '/api/image-gen/generate', [
{ name: 'prompt', value: 'sparse multi-ref' },
diff --git a/server/services/imageGen/prepareParams.js b/server/services/imageGen/prepareParams.js
index c9c5867884..2ed6cf307b 100644
--- a/server/services/imageGen/prepareParams.js
+++ b/server/services/imageGen/prepareParams.js
@@ -6,12 +6,12 @@
* - gate input-image uploads to backends that can consume them, are enabled,
* and can take that many — all BEFORE anything is staged to disk
* - stage multer temp uploads into PATHS.images / PATHS.imageRefs
- * - resolve initImagePath from upload or gallery filename
+ * - resolve initImagePath and referenceImagePaths from uploads or gallery filenames
* - enforce each cloud CLI's prompt requirement
*
* Returns:
* {
- * data - mutated validated body (initImageFile/referenceStrengths
+ * data - mutated validated body (gallery filenames/referenceStrengths
* stripped; initImagePath/referenceImagePaths/Strengths added)
* mode - resolved IMAGE_GEN_MODE string
* settings - raw settings object (caller reuses for dispatch)
@@ -100,6 +100,7 @@ export async function prepareGenerateParams({ data, files, referenceImageFields
const initUpload = files?.initImage;
const referenceImagePaths = [];
const referenceImageStrengths = [];
+ const namedReferenceFiles = Array.isArray(data.referenceImageFiles) ? data.referenceImageFiles : [];
// Pair strengths by PACK position (post-filter), not slot position — the
// client renumbers populated slots into `referenceImage1..N` and sends a
@@ -109,7 +110,10 @@ export async function prepareGenerateParams({ data, files, referenceImageFields
const referenceUploads = referenceImageFields
.map((field) => files?.[field])
.filter(Boolean)
- .map((upload, packedIndex) => ({ upload, strength: data.referenceStrengths?.[packedIndex] }));
+ .map((upload, packedIndex) => ({
+ upload,
+ strength: data.referenceStrengths?.[namedReferenceFiles.length + packedIndex],
+ }));
// Best-effort cleanup of every multer-staged file currently on `files`.
// The multipart parser writes uploads to `os.tmpdir()` as they stream in,
@@ -173,7 +177,16 @@ export async function prepareGenerateParams({ data, files, referenceImageFields
// request or named by an earlier one) plus every reference slot. Every gate
// below keys off these two, rather than respelling "carries input images"
// per gate and having to keep the spellings in sync.
- const inputImageCount = (initUpload || data.initImageFile ? 1 : 0) + referenceUploads.length;
+ const referenceImageCount = namedReferenceFiles.length + referenceUploads.length;
+ const inputImageCount = (initUpload || data.initImageFile ? 1 : 0) + referenceImageCount;
+
+ if (referenceImageCount > referenceImageFields.length) {
+ cleanupReqFilesTemp();
+ throw new ServerError(
+ `Image generation accepts at most ${referenceImageFields.length} reference images; received ${referenceImageCount}`,
+ { status: 400, code: 'TOO_MANY_REFERENCE_IMAGES' },
+ );
+ }
if (!isEditCapableMode(mode) && inputImageCount) {
cleanupReqFilesTemp();
@@ -209,7 +222,7 @@ export async function prepareGenerateParams({ data, files, referenceImageFields
// copying the uploads to PATHS.imageRefs and silently dropping them
// downstream — that would orphan files on disk and produce metadata sidecars
// that lie about how the render was conditioned.
- if (referenceUploads.length && mode === IMAGE_GEN_MODE.LOCAL) {
+ if (referenceImageCount && mode === IMAGE_GEN_MODE.LOCAL) {
const candidate = selectLocalImageModel(data.modelId);
if (!isFlux2(candidate)) {
cleanupReqFilesTemp();
@@ -262,6 +275,23 @@ export async function prepareGenerateParams({ data, files, referenceImageFields
initImagePath = resolved;
}
+ // JSON callers can condition a new render on existing gallery images
+ // without mislabeling them as an init/edit source. Keep these first so their
+ // strengths align with `referenceStrengths`, followed by multipart uploads.
+ for (const [index, filename] of namedReferenceFiles.entries()) {
+ const resolved = resolveGalleryImage(filename);
+ if (!resolved) {
+ cleanupStagedAndTemp();
+ throw new ServerError(
+ 'Reference image not found in gallery',
+ { status: 400, code: 'REFERENCE_IMAGE_NOT_FOUND' },
+ );
+ }
+ referenceImagePaths.push(resolved);
+ const strength = data.referenceStrengths?.[index];
+ referenceImageStrengths.push(typeof strength === 'number' ? strength : 1.0);
+ }
+
// Multi-reference editing (FLUX.2). Walk packed slot entries in submit
// order — each contributes a path + its parallel strength. Empty slots
// are filtered out above so the runner sees `referenceImagePaths: [p1, ...]`
@@ -281,6 +311,7 @@ export async function prepareGenerateParams({ data, files, referenceImageFields
// Strip the route-only fields — providers expect normalized `…Path(s)`.
delete data.initImageFile;
+ delete data.referenceImageFiles;
delete data.referenceStrengths;
if (initImagePath) data.initImagePath = initImagePath;
if (referenceImagePaths.length) {