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

refactor([flux2-runner-sidecar-tests]): extract testable buildSidecarMeta from generateImage

[._.]/ Adam Eivy5ba265ac0f86
diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.js
index 200d778e2b..648f48508d 100644
--- a/server/services/imageGen/local.js
+++ b/server/services/imageGen/local.js
@@ -234,38 +234,59 @@ export const buildArgs = ({ pythonPath, model, prompt, negativePrompt, width, he
return { bin, args };
};
-export async function generateImage({ pythonPath, prompt, negativePrompt = '', modelId = 'dev', width = 1024, height = 1024, steps, guidance, seed, quantize = '8', loraFilenames = [], loraPaths = [], loraScales = [], initImagePath = null, initImageStrength = null, referenceImagePaths = [], referenceImageStrengths = [], jobId: providedJobId = null, cleanC2PA = false, denoise = false }) {
- if (!prompt?.trim()) throw new ServerError('Prompt is required', { status: 400, code: 'VALIDATION_ERROR' });
- // Single-flight is enforced by the mediaJobQueue worker upstream. Direct
- // callers that bypass the queue must not run two concurrent renders — the
- // activeProcess handle below would be clobbered and cancel() would orphan
- // the first child.
- // loadMediaModels memoizes — on-disk edits to data/media-models.json still
- // need a server restart to apply. Don't re-check model.broken here:
- // getImageModels() already filtered current-platform entries; an extra
- // check would also reject entries broken on the OTHER platform (e.g.
- // 'windows' on a macOS box).
- const model = getImageModels().find((m) => m.id === modelId);
- if (!model) throw new ServerError(`Unknown or unsupported model: ${modelId}`, { status: 400, code: 'VALIDATION_ERROR' });
- // Both flux2 and z-image runners resolve their own Python via the FLUX.2
- // venv — only the legacy mflux/imagine_win path needs the user-configured
- // Settings > Image Gen pythonPath.
- if (!isFlux2(model) && !usesDiffusersRunner(model) && !pythonPath) {
- throw new ServerError('Python path not configured — set it in Settings > Image Gen', { status: 400, code: 'IMAGE_GEN_NOT_CONFIGURED' });
- }
- // FLUX.2 and Z-Image runners now load LoRAs via diffusers'
- // pipe.load_lora_weights — but only LoRAs trained against the matching
- // base model will produce sensible output. The LoRA picker UI uses the
- // sidecar's `runnerFamily` field to filter; we don't enforce here so a
- // user can deliberately experiment with off-family weights and see what
- // happens (the runner will surface a shape-mismatch error from diffusers).
-
- await ensureDir(PATHS.images);
- await ensureDir(PATHS.loras);
+// Clamp 0..1 with a finite-fallback — Math.max/min preserve NaN, so a
+// corrupt sidecar value like Number('bad') would slip through and end up
+// serialized into metadata / the CLI flag. `null` here means "no strength
+// sent" (init-image), which the args builder already gates on; for refs
+// we fall back to 1.0 (full influence).
+const clampStrength01 = (raw, fallback) => {
+ const n = Number(raw);
+ if (!Number.isFinite(n)) return fallback;
+ return Math.max(0, Math.min(1, n));
+};
- const jobId = providedJobId || randomUUID();
+/**
+ * Build the resolved/validated render parameters + sidecar `meta` object for a
+ * generation job. Factored out of `generateImage` so the resolution rules
+ * (seed/steps/guidance defaults, LoRA prefix-check, init/reference path
+ * re-anchoring, strength clamping) are unit-testable without spawning Python
+ * or touching the gallery filesystem.
+ *
+ * Filesystem touch-points are injected so the function stays pure:
+ * - `resolveInputPath(rawPath)` — re-anchors an init/reference path against the
+ * approved image roots; returns the validated absolute path or `null`
+ * (production passes `resolveImageInputPath`).
+ * - `loraExists(absPath)` — whether a prefix-checked LoRA path exists on disk
+ * (production passes `existsSync`).
+ *
+ * `meta` is the exact object `generateImage` persists as the `<jobId>.metadata.json`
+ * sidecar AND spreads into the in-memory job + activeJob snapshots, so the
+ * shape returned here is the contract the gallery/Remix flow reads back.
+ */
+export function buildSidecarMeta({
+ jobId,
+ model,
+ prompt,
+ negativePrompt = '',
+ modelId,
+ width,
+ height,
+ steps,
+ guidance,
+ seed,
+ quantize,
+ loraFilenames = [],
+ loraPaths = [],
+ loraScales = [],
+ initImagePath = null,
+ initImageStrength = null,
+ referenceImagePaths = [],
+ referenceImageStrengths = [],
+ resolveInputPath,
+ loraExists,
+ now = () => new Date().toISOString(),
+}) {
const filename = `${jobId}.png`;
- const outputPath = join(PATHS.images, filename);
const actualSeed = seed != null && seed !== '' ? Number(seed) : Math.floor(Math.random() * 2147483647);
const actualSteps = steps ? Number(steps) : model.steps;
// Step-wise distilled models (Schnell / FLUX.2 Klein / Z-Image-Turbo) ignore
@@ -293,7 +314,7 @@ export async function generateImage({ pythonPath, prompt, negativePrompt = '', m
if (!p || typeof p !== 'string') return false;
const resolved = resolvePath(p);
if (!resolved.startsWith(lorasRoot)) return false;
- return existsSync(resolved);
+ return loraExists(resolved);
});
// Store loraFilenames (basenames) in the sidecar going forward — that's
@@ -302,26 +323,16 @@ export async function generateImage({ pythonPath, prompt, negativePrompt = '', m
const validLoraFilenames = validLoras.map((p) => basename(p));
// i2i: defense in depth — the route already validated a fresh request,
// but an old sidecar replay can carry a stale absolute path outside the
- // approved image roots. resolveImageInputPath accepts gallery + image-refs
+ // approved image roots. resolveInputPath accepts gallery + image-refs
// + visual templates — the latter so the universe-builder reference-sheet
// renderer can use a shipped layout template as the init-image anchor.
const validInitImagePath = (initImagePath && typeof initImagePath === 'string')
- ? resolveImageInputPath(initImagePath)
+ ? resolveInputPath(initImagePath)
: null;
- // Clamp 0..1 with a finite-fallback — Math.max/min preserve NaN, so a
- // corrupt sidecar value like Number('bad') would slip through and end up
- // serialized into metadata / the CLI flag. `null` here means "no strength
- // sent" (init-image), which the args builder already gates on; for refs
- // (below) we fall back to 1.0 (full influence).
- const clampStrength01 = (raw, fallback) => {
- const n = Number(raw);
- if (!Number.isFinite(n)) return fallback;
- return Math.max(0, Math.min(1, n));
- };
const validInitImageStrength = validInitImagePath && initImageStrength != null
? clampStrength01(initImageStrength, null)
: null;
- // Multi-reference: re-anchor each path through resolveImageInputPath so a
+ // Multi-reference: re-anchor each path through resolveInputPath so a
// sidecar replay can't sneak a path outside the approved image roots into
// the runner. Accepts gallery + image-refs + visual templates — the gallery
// path lets a canon portrait (e.g. character.primaryImageRef) flow in as a
@@ -331,7 +342,7 @@ export async function generateImage({ pythonPath, prompt, negativePrompt = '', m
const rawRefPaths = Array.isArray(referenceImagePaths) ? referenceImagePaths : [];
const validReferences = rawRefPaths
.map((p, i) => {
- const resolved = typeof p === 'string' ? resolveImageInputPath(p) : null;
+ const resolved = typeof p === 'string' ? resolveInputPath(p) : null;
if (!resolved) return null;
const rawStrength = referenceImageStrengths?.[i];
const strength = rawStrength != null ? clampStrength01(rawStrength, 1.0) : 1.0;
@@ -344,7 +355,84 @@ export async function generateImage({ pythonPath, prompt, negativePrompt = '', m
// a Flux2KVLayerCache.store + _flux2_kv_causal_attention patch that scales
// each reference's V slice by the corresponding strength (1.0 = upstream
// baseline, 0.0 = ignored). Mirrors the Python sidecar's `referenceStrengths`.
- const meta = { id: jobId, prompt, negativePrompt, modelId, seed: actualSeed, width: Number(width), height: Number(height), steps: actualSteps, guidance: actualGuidance, quantize, filename, loraFilenames: validLoraFilenames, loraPaths: validLoras, loraScales, initImageFilename: validInitImagePath ? basename(validInitImagePath) : null, initImageStrength: validInitImageStrength, referenceImageFilenames: validReferenceImagePaths.map((p) => basename(p)), referenceImageStrengths: validReferenceImageStrengths, createdAt: new Date().toISOString() };
+ const meta = { id: jobId, prompt, negativePrompt, modelId, seed: actualSeed, width: Number(width), height: Number(height), steps: actualSteps, guidance: actualGuidance, quantize, filename, loraFilenames: validLoraFilenames, loraPaths: validLoras, loraScales, initImageFilename: validInitImagePath ? basename(validInitImagePath) : null, initImageStrength: validInitImageStrength, referenceImageFilenames: validReferenceImagePaths.map((p) => basename(p)), referenceImageStrengths: validReferenceImageStrengths, createdAt: now() };
+ return {
+ meta,
+ actualSeed,
+ actualSteps,
+ actualGuidance,
+ validLoras,
+ validInitImagePath,
+ validInitImageStrength,
+ validReferenceImagePaths,
+ validReferenceImageStrengths,
+ };
+}
+
+export async function generateImage({ pythonPath, prompt, negativePrompt = '', modelId = 'dev', width = 1024, height = 1024, steps, guidance, seed, quantize = '8', loraFilenames = [], loraPaths = [], loraScales = [], initImagePath = null, initImageStrength = null, referenceImagePaths = [], referenceImageStrengths = [], jobId: providedJobId = null, cleanC2PA = false, denoise = false }) {
+ if (!prompt?.trim()) throw new ServerError('Prompt is required', { status: 400, code: 'VALIDATION_ERROR' });
+ // Single-flight is enforced by the mediaJobQueue worker upstream. Direct
+ // callers that bypass the queue must not run two concurrent renders — the
+ // activeProcess handle below would be clobbered and cancel() would orphan
+ // the first child.
+ // loadMediaModels memoizes — on-disk edits to data/media-models.json still
+ // need a server restart to apply. Don't re-check model.broken here:
+ // getImageModels() already filtered current-platform entries; an extra
+ // check would also reject entries broken on the OTHER platform (e.g.
+ // 'windows' on a macOS box).
+ const model = getImageModels().find((m) => m.id === modelId);
+ if (!model) throw new ServerError(`Unknown or unsupported model: ${modelId}`, { status: 400, code: 'VALIDATION_ERROR' });
+ // Both flux2 and z-image runners resolve their own Python via the FLUX.2
+ // venv — only the legacy mflux/imagine_win path needs the user-configured
+ // Settings > Image Gen pythonPath.
+ if (!isFlux2(model) && !usesDiffusersRunner(model) && !pythonPath) {
+ throw new ServerError('Python path not configured — set it in Settings > Image Gen', { status: 400, code: 'IMAGE_GEN_NOT_CONFIGURED' });
+ }
+ // FLUX.2 and Z-Image runners now load LoRAs via diffusers'
+ // pipe.load_lora_weights — but only LoRAs trained against the matching
+ // base model will produce sensible output. The LoRA picker UI uses the
+ // sidecar's `runnerFamily` field to filter; we don't enforce here so a
+ // user can deliberately experiment with off-family weights and see what
+ // happens (the runner will surface a shape-mismatch error from diffusers).
+
+ await ensureDir(PATHS.images);
+ await ensureDir(PATHS.loras);
+
+ const jobId = providedJobId || randomUUID();
+ const filename = `${jobId}.png`;
+ const outputPath = join(PATHS.images, filename);
+ const {
+ meta,
+ actualSeed,
+ actualSteps,
+ actualGuidance,
+ validLoras,
+ validInitImagePath,
+ validInitImageStrength,
+ validReferenceImagePaths,
+ validReferenceImageStrengths,
+ } = buildSidecarMeta({
+ jobId,
+ model,
+ prompt,
+ negativePrompt,
+ modelId,
+ width,
+ height,
+ steps,
+ guidance,
+ seed,
+ quantize,
+ loraFilenames,
+ loraPaths,
+ loraScales,
+ initImagePath,
+ initImageStrength,
+ referenceImagePaths,
+ referenceImageStrengths,
+ resolveInputPath: resolveImageInputPath,
+ loraExists: existsSync,
+ });
const job = { ...meta, clients: [], status: 'running' };
jobs.set(jobId, job);
diff --git a/server/services/imageGen/local.test.js b/server/services/imageGen/local.test.js
index 88687a820e..79263e4ee7 100644
--- a/server/services/imageGen/local.test.js
+++ b/server/services/imageGen/local.test.js
@@ -21,13 +21,14 @@ vi.mock('../../lib/pythonSetup.js', () => ({
let tmpRegistryDir;
let priorRegistryEnv;
let buildArgs;
+let buildSidecarMeta;
beforeAll(async () => {
tmpRegistryDir = mkdtempSync(join(tmpdir(), 'portos-imagegen-local-test-'));
priorRegistryEnv = process.env.PORTOS_MEDIA_MODELS_FILE;
process.env.PORTOS_MEDIA_MODELS_FILE = join(tmpRegistryDir, 'media-models.json');
vi.resetModules();
- ({ buildArgs } = await import('./local.js'));
+ ({ buildArgs, buildSidecarMeta } = await import('./local.js'));
});
afterAll(() => {
@@ -420,3 +421,195 @@ describe('imageGen local.buildArgs z-image dispatch', () => {
expect(args).not.toContain('--use-pe');
});
});
+
+describe('imageGen local.buildSidecarMeta', () => {
+ // Pull the real PATHS.loras prefix so LoRA candidates the meta-builder joins
+ // against it pass its resolve+prefix check. Existence is faked via the
+ // injected `loraExists` so the test never touches the filesystem.
+ let LORAS_ROOT;
+ let join_;
+ beforeAll(async () => {
+ ({ PATHS: { loras: LORAS_ROOT } } = await import('../../lib/fileUtils.js'));
+ ({ join: join_ } = await import('path'));
+ });
+
+ // Default injectable deps: resolveInputPath echoes any path it's given (i.e.
+ // every supplied path is "valid"), loraExists always true, fixed timestamp.
+ const ECHO = (p) => p;
+ const ALWAYS = () => true;
+ const FIXED_NOW = () => '2024-01-01T00:00:00.000Z';
+
+ const baseMetaInput = {
+ jobId: 'job-1234-5678',
+ model: { id: 'flux2-klein-9b', steps: 8, guidance: 0 },
+ prompt: 'a red cube',
+ negativePrompt: '',
+ modelId: 'flux2-klein-9b',
+ width: 1024,
+ height: 768,
+ steps: 8,
+ guidance: 0,
+ seed: 42,
+ quantize: 'sdnq',
+ resolveInputPath: ECHO,
+ loraExists: ALWAYS,
+ now: FIXED_NOW,
+ };
+
+ it('builds the canonical sidecar meta shape with reference fields populated', () => {
+ const refA = '/data/images/ref-a.png';
+ const refB = '/data/image-refs/ref-b.jpg';
+ const { meta } = buildSidecarMeta({
+ ...baseMetaInput,
+ referenceImagePaths: [refA, refB],
+ referenceImageStrengths: [0.85, 0.5],
+ });
+ expect(meta).toMatchObject({
+ id: 'job-1234-5678',
+ prompt: 'a red cube',
+ negativePrompt: '',
+ modelId: 'flux2-klein-9b',
+ seed: 42,
+ width: 1024,
+ height: 768,
+ steps: 8,
+ guidance: 0,
+ quantize: 'sdnq',
+ filename: 'job-1234-5678.png',
+ createdAt: '2024-01-01T00:00:00.000Z',
+ });
+ // referenceImageFilenames stores basenames, parallel to the strengths array.
+ expect(meta.referenceImageFilenames).toEqual(['ref-a.png', 'ref-b.jpg']);
+ expect(meta.referenceImageStrengths).toEqual([0.85, 0.5]);
+ });
+
+ it('defaults each missing reference strength to 1.0 (full influence)', () => {
+ const { meta } = buildSidecarMeta({
+ ...baseMetaInput,
+ referenceImagePaths: ['/data/images/r1.png', '/data/images/r2.png'],
+ referenceImageStrengths: [0.3], // only the first supplied
+ });
+ expect(meta.referenceImageFilenames).toEqual(['r1.png', 'r2.png']);
+ expect(meta.referenceImageStrengths).toEqual([0.3, 1.0]);
+ });
+
+ it('clamps reference strengths to 0..1 and falls back to 1.0 on non-finite', () => {
+ const { meta } = buildSidecarMeta({
+ ...baseMetaInput,
+ referenceImagePaths: ['/data/images/lo.png', '/data/images/hi.png', '/data/images/bad.png'],
+ referenceImageStrengths: [-2, 5, Number('nope')],
+ });
+ expect(meta.referenceImageStrengths).toEqual([0, 1, 1.0]);
+ });
+
+ it('drops a rejected reference path WITHOUT shifting the surviving strength', () => {
+ // resolveInputPath rejects the second path; the third must keep ITS own
+ // strength (0.9), not inherit the dropped slot's (0.2). This pins the
+ // "pair before filter" invariant the meta-builder relies on.
+ const resolveInputPath = (p) => (p.includes('reject') ? null : p);
+ const { meta, validReferenceImagePaths } = buildSidecarMeta({
+ ...baseMetaInput,
+ resolveInputPath,
+ referenceImagePaths: ['/data/images/keep.png', '/data/images/reject.png', '/data/images/also-keep.png'],
+ referenceImageStrengths: [0.4, 0.2, 0.9],
+ });
+ expect(validReferenceImagePaths).toEqual(['/data/images/keep.png', '/data/images/also-keep.png']);
+ expect(meta.referenceImageFilenames).toEqual(['keep.png', 'also-keep.png']);
+ expect(meta.referenceImageStrengths).toEqual([0.4, 0.9]);
+ });
+
+ it('emits empty reference arrays when no references are supplied', () => {
+ const { meta } = buildSidecarMeta({ ...baseMetaInput });
+ expect(meta.referenceImageFilenames).toEqual([]);
+ expect(meta.referenceImageStrengths).toEqual([]);
+ });
+
+ it('tolerates a non-array referenceImagePaths (sidecar replay corruption)', () => {
+ const { meta } = buildSidecarMeta({
+ ...baseMetaInput,
+ referenceImagePaths: null,
+ referenceImageStrengths: null,
+ });
+ expect(meta.referenceImageFilenames).toEqual([]);
+ expect(meta.referenceImageStrengths).toEqual([]);
+ });
+
+ it('records initImageFilename + clamped strength for i2i', () => {
+ const { meta } = buildSidecarMeta({
+ ...baseMetaInput,
+ initImagePath: '/data/images/init.png',
+ initImageStrength: 0.7,
+ });
+ expect(meta.initImageFilename).toBe('init.png');
+ expect(meta.initImageStrength).toBe(0.7);
+ });
+
+ it('leaves init strength null when no init image survives resolution', () => {
+ const { meta } = buildSidecarMeta({
+ ...baseMetaInput,
+ resolveInputPath: () => null, // init path rejected
+ initImagePath: '/somewhere/outside.png',
+ initImageStrength: 0.7,
+ });
+ expect(meta.initImageFilename).toBeNull();
+ expect(meta.initImageStrength).toBeNull();
+ });
+
+ it('keeps only LoRA basenames that exist, storing both filenames + paths', () => {
+ const loraFilenames = ['lora-good.safetensors', 'lora-missing.safetensors'];
+ const loraExists = (abs) => abs.endsWith('lora-good.safetensors');
+ const { meta } = buildSidecarMeta({
+ ...baseMetaInput,
+ loraFilenames,
+ loraScales: [1.0],
+ loraExists,
+ });
+ expect(meta.loraFilenames).toEqual(['lora-good.safetensors']);
+ expect(meta.loraPaths).toEqual([join_(LORAS_ROOT, 'lora-good.safetensors')]);
+ // loraScales passes through verbatim (the runner pairs them positionally).
+ expect(meta.loraScales).toEqual([1.0]);
+ });
+
+ it('rejects a LoRA path outside the loras root (sidecar replay traversal)', () => {
+ const { meta } = buildSidecarMeta({
+ ...baseMetaInput,
+ loraPaths: ['/etc/evil.safetensors'],
+ loraExists: ALWAYS, // would exist, but prefix-check must reject it first
+ });
+ expect(meta.loraFilenames).toEqual([]);
+ expect(meta.loraPaths).toEqual([]);
+ });
+
+ it('falls back to model defaults for steps and guidance when unset', () => {
+ const { meta } = buildSidecarMeta({
+ ...baseMetaInput,
+ model: { id: 'm', steps: 28, guidance: 3.5 },
+ steps: undefined,
+ guidance: undefined,
+ });
+ expect(meta.steps).toBe(28);
+ expect(meta.guidance).toBe(3.5);
+ });
+
+ it('clamps guidance to <=1.0 for cfgDisabled models, leaving sub-1.0 untouched', () => {
+ const high = buildSidecarMeta({
+ ...baseMetaInput,
+ model: { id: 'm', steps: 8, cfgDisabled: true },
+ guidance: 7.5,
+ }).meta;
+ expect(high.guidance).toBe(1.0);
+ const low = buildSidecarMeta({
+ ...baseMetaInput,
+ model: { id: 'm', steps: 8, cfgDisabled: true },
+ guidance: 0,
+ }).meta;
+ expect(low.guidance).toBe(0);
+ });
+
+ it('generates a random seed in range when none is supplied', () => {
+ const { meta } = buildSidecarMeta({ ...baseMetaInput, seed: undefined });
+ expect(Number.isInteger(meta.seed)).toBe(true);
+ expect(meta.seed).toBeGreaterThanOrEqual(0);
+ expect(meta.seed).toBeLessThan(2147483647);
+ });
+});