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

feat([issue-912]): add local-FLUX regenerate action to defeat SynthID watermarks

[._.]/ Adam Eivyb591fd93ee89
diff --git a/client/src/components/media/MediaLightbox.jsx b/client/src/components/media/MediaLightbox.jsx
index af63702a58..6cade48e9b 100644
--- a/client/src/components/media/MediaLightbox.jsx
+++ b/client/src/components/media/MediaLightbox.jsx
@@ -1,6 +1,6 @@
import { useEffect, useRef, useState } from 'react';
import {
- X, Copy, Sparkles, Film, Image as ImageIcon, Download, Eraser,
+ X, Copy, Sparkles, Film, Image as ImageIcon, Download, Eraser, Wand2,
ChevronLeft, ChevronRight, Maximize2, Minimize2, Star,
} from 'lucide-react';
import PromptRefineModal from './PromptRefineModal';
@@ -72,6 +72,8 @@ export default function MediaLightbox({
onSendToVideo,
onContinue,
onClean,
+ onRegenerate,
+ regenAvailable = false,
onPrevious,
onNext,
hasPrevious = false,
@@ -313,6 +315,8 @@ export default function MediaLightbox({
onSendToVideo={onSendToVideo}
onContinue={onContinue}
onClean={onClean}
+ onRegenerate={onRegenerate}
+ regenAvailable={regenAvailable}
copy={copy}
onRefine={() => setRefineOpen(true)}
annotation={annotation}
@@ -354,13 +358,14 @@ function PeerNotes({ others }) {
function SettingsPane({
item, meta, isVideo,
- onClose, onRemix, onSendToVideo, onContinue, onClean,
+ onClose, onRemix, onSendToVideo, onContinue, onClean, onRegenerate, regenAvailable,
copy, onRefine,
annotation, onAnnotationChange,
variantGroup, onSelectVariant,
}) {
const asideClasses = 'md:w-80 lg:w-96 shrink-0 flex flex-col border-t md:border-t-0 md:border-l border-port-border max-h-[40vh] md:max-h-[92vh]';
const [cleaning, setCleaning] = useState(false);
+ const [regenerating, setRegenerating] = useState(false);
const starred = !!annotation?.starred;
const closeThenRun = (handler) => {
onClose?.();
@@ -607,6 +612,31 @@ function SettingsPane({
<Eraser className="w-3.5 h-3.5" /> {cleaning ? 'Cleaning…' : 'Clean'}
</button>
)}
+ {!isVideo && onRegenerate && regenAvailable && (
+ <button
+ type="button"
+ disabled={regenerating}
+ onClick={async () => {
+ if (regenerating) return;
+ setRegenerating(true);
+ let ok = false;
+ try {
+ await onRegenerate(item);
+ ok = true;
+ } catch {
+ // Caller toasts its own error; stay open so the user can retry.
+ } finally {
+ setRegenerating(false);
+ }
+ if (ok) onClose();
+ }}
+ title="Regenerate through a local FLUX model (img2img) to overwrite SynthID watermarking. Creates a new variant; the original is kept."
+ aria-label="Regenerate image to defeat SynthID watermark"
+ className="flex-1 flex items-center justify-center gap-1.5 px-2 py-1.5 text-xs bg-port-accent/80 text-white hover:opacity-90 rounded disabled:opacity-50 disabled:cursor-not-allowed"
+ >
+ <Wand2 className="w-3.5 h-3.5" /> {regenerating ? 'Queuing…' : 'Regenerate'}
+ </button>
+ )}
{isVideo && onContinue && (
<button
type="button"
diff --git a/client/src/components/media/variants.js b/client/src/components/media/variants.js
index e50ea7b889..80281e3cc0 100644
--- a/client/src/components/media/variants.js
+++ b/client/src/components/media/variants.js
@@ -46,6 +46,13 @@ export function computeImageVariantGroup(item, items) {
const group = [];
if (original) group.push({ label: 'Original', item: original });
for (const c of cleaned) {
+ // SynthID-defeat regens (issue #912) reuse `cleanedFrom` for grouping but
+ // are a different operation than the lossless/denoise clean — label them
+ // distinctly so the toggle reads "Regenerated" instead of "Cleaned".
+ if (c.regenerated) {
+ group.push({ label: 'Regenerated', item: c });
+ continue;
+ }
const levelTag = c.cleanLevel ? ` (${c.cleanLevel})` : '';
group.push({ label: `Cleaned${levelTag}`, item: c });
}
diff --git a/client/src/components/media/variants.test.js b/client/src/components/media/variants.test.js
index 97079d7760..8c8d0aa50f 100644
--- a/client/src/components/media/variants.test.js
+++ b/client/src/components/media/variants.test.js
@@ -62,6 +62,22 @@ describe('computeImageVariantGroup', () => {
]);
});
+ it('labels a SynthID-defeat regen variant "Regenerated" (grouped via cleanedFrom)', () => {
+ const orig = img('a.png');
+ const regen = img('regen-uuid.png', { cleanedFrom: 'a.png', regenerated: true, regenStrength: 0.4 });
+ const result = computeImageVariantGroup(orig, [orig, regen]);
+ expect(result.group.map((g) => g.label)).toEqual(['Original', 'Regenerated']);
+ });
+
+ it('mixes cleaned and regenerated variants under one source with distinct labels', () => {
+ const orig = img('a.png');
+ const cleaned = img('a_clean-aggressive.png', { cleanedFrom: 'a.png', cleanLevel: 'aggressive', createdAt: '2024-01-01' });
+ const regen = img('regen-uuid.png', { cleanedFrom: 'a.png', regenerated: true, createdAt: '2024-01-02' });
+ const result = computeImageVariantGroup(regen, [orig, cleaned, regen]);
+ expect(result.group.map((g) => g.label)).toEqual(['Original', 'Cleaned (aggressive)', 'Regenerated']);
+ expect(result.active.label).toBe('Regenerated');
+ });
+
it('returns null when only the original exists (no clean siblings yet — no toggle needed)', () => {
const orig = img('a.png');
const unrelated = img('b.png');
diff --git a/client/src/pages/ImageGen.jsx b/client/src/pages/ImageGen.jsx
index 2b08ced675..de7eec7710 100644
--- a/client/src/pages/ImageGen.jsx
+++ b/client/src/pages/ImageGen.jsx
@@ -46,7 +46,7 @@ import { useModelDownloadStatus } from '../hooks/useModelDownloadStatus';
import {
getImageGenStatus, generateImage, listImageModels, listLorasFull, listImageGallery,
cancelImageGen, deleteImage, setImageHidden, cleanGalleryImage, getActiveImageJob, getSettings,
- buildFormData, listMediaJobs,
+ buildFormData, listMediaJobs, regenerateGalleryImage, getRegenAvailability,
} from '../services/api';
// Multi-reference editing (FLUX.2 only) — 4 fixed slots, each carrying an
@@ -245,6 +245,13 @@ export default function ImageGen() {
}, []);
useMediaCompletionRefresh({ onImageCompleted: refreshGallery });
+ // SynthID-defeat regen (issue #912) is hardware-gated on a local FLUX
+ // runner — only surface the lightbox action when the backend is installed.
+ const [regenAvailable, setRegenAvailable] = useState(false);
+ useEffect(() => {
+ getRegenAvailability().then((r) => setRegenAvailable(!!r?.available)).catch(() => {});
+ }, []);
+
// Re-runnable so the Settings drawer can trigger a refresh on close
// without forcing a full page reload.
const reloadBackends = useCallback(() => {
@@ -815,6 +822,20 @@ export default function ImageGen() {
toast.success(`Cleaned → ${cleaned.filename}`);
};
+ // SynthID-defeat regen (issue #912) — unlike clean, this is a queued local
+ // FLUX render: it returns a job ack, and the finished variant lands in the
+ // gallery via the queue-completion refresh (useMediaCompletionRefresh /
+ // pollQueue). Bump pendingQueued so the queue indicator + 4s poll engage.
+ const handleRegenerate = async (img) => {
+ if (!img?.filename) throw new Error('Missing filename');
+ await regenerateGalleryImage(img.filename).catch((err) => {
+ toast.error(err.message || 'Failed to start regeneration');
+ throw err;
+ });
+ setPendingQueued((n) => n + 1);
+ toast.success('Regenerating — the new image will appear when it finishes');
+ };
+
const sendToVideo = (img) => {
if (!img?.filename) return;
const params = new URLSearchParams({ sourceImageFile: img.filename });
@@ -1288,6 +1309,8 @@ export default function ImageGen() {
onRemix={(item) => item?.raw && handleRemix(item.raw)}
onSendToVideo={(item) => item?.raw?.filename && sendToVideo(item.raw)}
onClean={(item) => handleClean(item?.raw)}
+ onRegenerate={(item) => handleRegenerate(item?.raw)}
+ regenAvailable={regenAvailable}
/>
diff --git a/client/src/services/apiImageVideo.js b/client/src/services/apiImageVideo.js
index 8917ece067..8821ee6a2f 100644
--- a/client/src/services/apiImageVideo.js
+++ b/client/src/services/apiImageVideo.js
@@ -26,6 +26,18 @@ export const cleanGalleryImage = (filename) => request(`/image-gen/${encodeURICo
method: 'POST',
body: JSON.stringify({}),
});
+// SynthID-defeat regen (issue #912). Enqueues a local-FLUX img2img round-trip
+// of a gallery image; returns the queue ack ({ jobId, position, ... }) — the
+// finished render lands in the gallery via the normal queue-completion refresh.
+// `silent` so the lightbox owns its own error toast (single-layer rule).
+export const regenerateGalleryImage = (filename, { strength, steps } = {}) =>
+ request(`/image-gen/${encodeURIComponent(filename)}/regenerate`, {
+ method: 'POST',
+ body: JSON.stringify({ ...(strength != null ? { strength } : {}), ...(steps != null ? { steps } : {}) }),
+ silent: true,
+ });
+// Whether the local FLUX regen backend is installed (hardware gate). `{ available, modelId, reason }`.
+export const getRegenAvailability = () => request('/image-gen/regen/availability', { silent: true });
// HuggingFace token (gated local Flux models). Stored in settings.imageGen.hfToken;
// reads fall back to HF_TOKEN env var and then ~/.cache/huggingface/token.
diff --git a/server/routes/imageGen.js b/server/routes/imageGen.js
index fabd089460..bb55ce8fe9 100644
--- a/server/routes/imageGen.js
+++ b/server/routes/imageGen.js
@@ -38,6 +38,10 @@ import { join } from 'node:path';
import { readFile, writeFile, stat } from 'fs/promises';
import { STYLE_PRESETS } from '../lib/writersRoomStylePresets.js';
import { cleanImageBuffer } from '../lib/imageClean.js';
+import {
+ resolveRegenBackend, getRegenAvailability, readImageDimensions, buildRegenParams,
+ DEFAULT_REGEN_STRENGTH, REGEN_STRENGTH_MIN, REGEN_STRENGTH_MAX,
+} from '../services/imageGen/regen.js';
import { purgeImageRefFromAllUniverses } from '../services/universeCanon.js';
import { listCollections, addItem, ERR_DUPLICATE } from '../services/mediaCollections.js';
import { itemKey } from '../lib/mediaItemKey.js';
@@ -144,6 +148,13 @@ const avatarSchema = z.object({
prompt: z.string().max(2000).optional(),
});
+// SynthID-defeat regen (issue #912). Body is optional — both fields default
+// server-side (strength → DEFAULT_REGEN_STRENGTH, steps → the model default).
+const regenerateSchema = z.object({
+ strength: z.number().min(REGEN_STRENGTH_MIN).max(REGEN_STRENGTH_MAX).optional(),
+ steps: z.number().int().min(1).max(50).optional(),
+});
+
router.get('/status', asyncHandler(async (req, res) => {
// Optional ?mode= override lets the Image Gen page probe a specific
// backend (e.g. when the user flips the per-render chip to Codex but
@@ -160,6 +171,12 @@ router.get('/active', asyncHandler(async (_req, res) => {
res.json({ activeJob: await imageGen.getActiveJob() });
}));
+// SynthID-defeat regen availability (issue #912). Drives whether the lightbox
+// shows the "Regenerate" action — it's hardware-gated on a local FLUX runner.
+router.get('/regen/availability', asyncHandler(async (_req, res) => {
+ res.json(await getRegenAvailability());
+}));
+
// Shape returned for any image-gen job that goes through the mediaJobQueue
// (local + codex). Kept in one place so the two enqueue branches below stay
// in sync — the client's polling/SSE hooks key off these fields.
@@ -605,6 +622,46 @@ router.post('/:filename/clean', asyncHandler(async (req, res) => {
});
}));
+// SynthID-defeat regeneration (issue #912). Round-trips an existing gallery
+// image through local FLUX img2img at low–moderate denoise so the per-pixel
+// watermark is overwritten by fresh sampling — the only honest defeat path
+// (the lossless clean above can't touch SynthID). Post-hoc + history-only:
+// enqueues a normal local image job (GPU lane) using the source's own prompt;
+// the new render lands in the gallery as a variant of the source. Hardware-
+// gated — 400s with an actionable message when no local FLUX runner exists.
+router.post('/:filename/regenerate', asyncHandler(async (req, res) => {
+ const filename = req.params.filename;
+ local.assertGalleryFilename(filename);
+ const body = validateRequest(regenerateSchema, req.body || {});
+
+ const sourceAbsPath = resolveGalleryImage(filename);
+ if (!sourceAbsPath) {
+ throw new ServerError('Image not found', { status: 404, code: 'NOT_FOUND' });
+ }
+ const { metadata: sourceMeta } = await local.readImageSidecar(filename);
+
+ const backend = await resolveRegenBackend({ sourceModelId: sourceMeta.modelId });
+ if (!backend.available) {
+ throw new ServerError(backend.reason, { status: 400, code: 'REGEN_BACKEND_UNAVAILABLE' });
+ }
+
+ const sourceDims = await readImageDimensions(sourceAbsPath);
+ const strength = body.strength ?? DEFAULT_REGEN_STRENGTH;
+ const params = buildRegenParams({
+ filename,
+ sourceAbsPath,
+ sourceMeta,
+ sourceDims,
+ model: backend.model,
+ pythonPath: backend.pythonPath,
+ strength,
+ steps: body.steps,
+ });
+ const queued = enqueueJob({ kind: 'image', params });
+ console.log(`♻️ Regenerating ${filename} via ${backend.model.id} (strength=${strength}) → job ${queued.jobId.slice(0, 8)}`);
+ return res.json(queuedImageResponse({ ...queued, mode: IMAGE_GEN_MODE.LOCAL, model: backend.model.id }));
+}));
+
// Add the cleaned-image filename to every collection that already contains
// the source filename. Returns the ids of the collections that received the
// new entry (excluding ones that already contained the cleaned filename).
diff --git a/server/routes/imageGen.test.js b/server/routes/imageGen.test.js
index d25bd202fe..7ef341dd5d 100644
--- a/server/routes/imageGen.test.js
+++ b/server/routes/imageGen.test.js
@@ -31,6 +31,8 @@ vi.mock('../services/imageGen/index.js', () => ({
listLoraFilenames: vi.fn(async () => []),
listGallery: vi.fn(async () => []),
deleteImage: vi.fn(async () => ({ ok: true })),
+ assertGalleryFilename: vi.fn(),
+ readImageSidecar: vi.fn(async () => ({ path: '', metadata: {} })),
},
}));
@@ -789,4 +791,34 @@ describe('Image Gen Routes', () => {
expect(detectArm64Python).not.toHaveBeenCalled();
});
});
+
+ // SynthID-defeat regen (issue #912).
+ describe('GET /api/image-gen/regen/availability', () => {
+ it('reports the local FLUX backend as available when the venv is healthy', async () => {
+ // isFlux2VenvHealthy is mocked to true and the real model registry
+ // carries FLUX.2 models, so a flux-venv model resolves.
+ const response = await request(app).get('/api/image-gen/regen/availability');
+ expect(response.status).toBe(200);
+ expect(response.body.available).toBe(true);
+ expect(typeof response.body.modelId).toBe('string');
+ });
+ });
+
+ describe('POST /api/image-gen/:filename/regenerate', () => {
+ it('rejects an out-of-range strength before touching the filesystem (400)', async () => {
+ const response = await request(app)
+ .post('/api/image-gen/whatever.png/regenerate')
+ .send({ strength: 0.95 }); // max is 0.6
+ expect(response.status).toBe(400);
+ expect(mediaJobQueue.enqueueJob).not.toHaveBeenCalled();
+ });
+
+ it('404s when the source image is not in the gallery', async () => {
+ const response = await request(app)
+ .post('/api/image-gen/does-not-exist.png/regenerate')
+ .send({});
+ expect(response.status).toBe(404);
+ expect(mediaJobQueue.enqueueJob).not.toHaveBeenCalled();
+ });
+ });
});
diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.js
index 12ee3b3f92..698c532d66 100644
--- a/server/services/imageGen/local.js
+++ b/server/services/imageGen/local.js
@@ -287,6 +287,13 @@ export function buildSidecarMeta({
initImageStrength = null,
referenceImagePaths = [],
referenceImageStrengths = [],
+ // SynthID-defeat regen lineage. When `regenOf` is set, this render is a
+ // post-hoc round-trip of an existing gallery image through local FLUX
+ // img2img (issue #912) — stamp the source filename as `cleanedFrom` (so the
+ // lightbox variant toggle groups the regen under its source the same way a
+ // cleaned copy is) plus explicit `regenerated`/`regenSteps`/`regenStrength`/
+ // `regenModelId` so the sidecar lineage stays honest about how it was made.
+ regenOf = null,
resolveInputPath,
loraExists,
now = () => new Date().toISOString(),
@@ -361,6 +368,21 @@ export function buildSidecarMeta({
// 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: now() };
+ // Regen lineage (issue #912). `regenOf` is the source gallery filename this
+ // render was generated from. We reuse the existing `cleanedFrom` field so the
+ // lightbox's `computeImageVariantGroup` groups the regen under its source with
+ // zero changes to the grouping key, and add explicit regen* fields so the
+ // sidecar honestly records that the per-pixel watermark was overwritten by a
+ // fresh sampling pass rather than stripped. `regenStrength`/`regenSteps`/
+ // `regenModelId` mirror the resolved render params (not the raw inputs) so a
+ // replayed/clamped value is what's recorded.
+ if (typeof regenOf === 'string' && regenOf) {
+ meta.cleanedFrom = regenOf;
+ meta.regenerated = true;
+ meta.regenStrength = validInitImageStrength;
+ meta.regenSteps = actualSteps;
+ meta.regenModelId = modelId;
+ }
return {
meta,
actualSeed,
@@ -374,7 +396,7 @@ export function buildSidecarMeta({
};
}
-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 }) {
+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, regenOf = null }) {
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
@@ -435,6 +457,7 @@ export async function generateImage({ pythonPath, prompt, negativePrompt = '', m
initImageStrength,
referenceImagePaths,
referenceImageStrengths,
+ regenOf,
resolveInputPath: resolveImageInputPath,
loraExists: existsSync,
});
diff --git a/server/services/imageGen/local.test.js b/server/services/imageGen/local.test.js
index 990d175592..b403a73b1e 100644
--- a/server/services/imageGen/local.test.js
+++ b/server/services/imageGen/local.test.js
@@ -520,6 +520,29 @@ describe('imageGen local.buildSidecarMeta', () => {
expect(meta.referenceImageStrengths).toEqual([0.85, 0.5]);
});
+ it('stamps regen lineage (cleanedFrom + regen* fields) when regenOf is set', () => {
+ const { meta } = buildSidecarMeta({
+ ...baseMetaInput,
+ initImagePath: '/data/images/source.png',
+ initImageStrength: 0.4,
+ regenOf: 'source.png',
+ });
+ // cleanedFrom mirrors the source so computeImageVariantGroup groups it.
+ expect(meta.cleanedFrom).toBe('source.png');
+ expect(meta.regenerated).toBe(true);
+ // regen* mirror the RESOLVED render params, not the raw inputs.
+ expect(meta.regenStrength).toBe(0.4);
+ expect(meta.regenSteps).toBe(8);
+ expect(meta.regenModelId).toBe('flux2-klein-9b');
+ });
+
+ it('omits regen lineage entirely for a normal (non-regen) render', () => {
+ const { meta } = buildSidecarMeta({ ...baseMetaInput });
+ expect(meta.cleanedFrom).toBeUndefined();
+ expect(meta.regenerated).toBeUndefined();
+ expect(meta.regenStrength).toBeUndefined();
+ });
+
it('defaults each missing reference strength to 1.0 (full influence)', () => {
const { meta } = buildSidecarMeta({
...baseMetaInput,
diff --git a/server/services/imageGen/regen.js b/server/services/imageGen/regen.js
new file mode 100644
index 0000000000..38c98d892f
--- /dev/null
+++ b/server/services/imageGen/regen.js
@@ -0,0 +1,158 @@
+/**
+ * Image Gen — SynthID-defeat regeneration (issue #912).
+ *
+ * The plain cleaner (`server/lib/imageClean.js`) only strips the C2PA `caBX`
+ * chunk and runs median+sharpen — SynthID survives that by design. The only
+ * honest defeat path is to round-trip the pixels through a generative model:
+ * a short-step img2img pass on a LOCAL FLUX runner at low–moderate denoise
+ * (~0.4) so composition holds but the per-pixel watermark signal is overwritten
+ * by fresh sampling.
+ *
+ * Scope (per the issue): post-hoc, history-only — a second action next to
+ * "Clean (aggressive)" in the lightbox, never auto-applied and never wired into
+ * the active generation flow. Hardware-gated: it only runs when a local FLUX
+ * runner is actually installed, so the UI hides the action otherwise.
+ *
+ * This module owns the backend-availability gate + the pure param assembly.
+ * The render itself reuses the existing local img2img path — the route enqueues
+ * a normal `kind: 'image'` job through `mediaJobQueue` (the GPU lane already
+ * serializes MLX work; a separate "regen lane" would just contend for the same
+ * runtime and OOM the box, so reusing the GPU lane is the correct shape). The
+ * `regenOf` param threaded into `generateImage` stamps the lineage onto the
+ * resulting sidecar (`regenerated`/`regenSteps`/`regenStrength`/`regenModelId`
+ * + `cleanedFrom` for variant grouping).
+ */
+
+import { existsSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import sharp from 'sharp';
+import { getSettings } from '../settings.js';
+import { getImageModels, isFlux2 } from '../../lib/mediaModels.js';
+import { usesDiffusersRunner } from '../../lib/runners.js';
+import { isFlux2VenvHealthy } from '../../lib/pythonSetup.js';
+import { IMAGE_GEN_MODE } from './modes.js';
+
+const IS_WIN = process.platform === 'win32';
+
+// img2img denoise strength: lower = closer to the source (less watermark
+// overwrite), higher = more of the image resampled. 0.4 is the issue's
+// recommended midpoint — enough fresh sampling to overwrite the per-pixel
+// signal while composition holds.
+export const DEFAULT_REGEN_STRENGTH = 0.4;
+export const REGEN_STRENGTH_MIN = 0.2;
+export const REGEN_STRENGTH_MAX = 0.6;
+
+// FLUX.2 + the diffusers-family runners (Z-Image / ERNIE / HiDream / Qwen) all
+// share the FLUX.2 venv and implement img2img via `--image-path`.
+export const modelUsesFluxVenv = (model) => isFlux2(model) || usesDiffusersRunner(model);
+
+// Whether a model can do the img2img round-trip regen needs. FLUX.2/diffusers
+// runners do i2i on every platform. The legacy mflux path does i2i on macOS
+// (`mflux-generate --image-path`), but on Windows `imagine_win.py` silently
+// drops the init-image args — a regen there would degrade to txt2img and
+// produce an unrelated image, so it's excluded.
+export function modelSupportsRegen(model) {
+ if (!model) return false;
+ if (modelUsesFluxVenv(model)) return true;
+ return !IS_WIN;
+}
+
+function mfluxBinaryPresent(pythonPath) {
+ if (!pythonPath) return false;
+ return existsSync(join(dirname(pythonPath), IS_WIN ? 'mflux-generate.exe' : 'mflux-generate'));
+}
+
+// Order regen candidates: the source's own model first (style continuity on
+// the round-trip), then prefer fast distilled models (`cfgDisabled` —
+// Schnell / Klein / Turbo) for a snappy ~5–15s pass, then everything else.
+// Pure — `models`/`sourceModelId` in, ordered list out.
+export function orderRegenCandidates(models, sourceModelId) {
+ const list = Array.isArray(models) ? models.filter(Boolean) : [];
+ return [...list].sort((a, b) => {
+ const aSrc = a.id === sourceModelId ? 0 : 1;
+ const bSrc = b.id === sourceModelId ? 0 : 1;
+ if (aSrc !== bSrc) return aSrc - bSrc;
+ const aFast = a.cfgDisabled ? 0 : 1;
+ const bFast = b.cfgDisabled ? 0 : 1;
+ return aFast - bFast;
+ });
+}
+
+// Resolve the local FLUX backend regen should use. Returns
+// `{ available, model, pythonPath }` on success, or `{ available: false, reason }`
+// with an actionable message when nothing runnable is installed (the hardware
+// gate). Async because the FLUX.2 venv health probe spawns a process (cached).
+export async function resolveRegenBackend({ sourceModelId } = {}) {
+ const models = getImageModels();
+ if (!models.length) {
+ return { available: false, reason: 'No local image models are configured on this machine.' };
+ }
+ const settings = await getSettings().catch(() => null);
+ const pythonPath = settings?.imageGen?.local?.pythonPath || null;
+ const fluxVenvHealthy = await isFlux2VenvHealthy().catch(() => false);
+ const mfluxReady = mfluxBinaryPresent(pythonPath);
+ const candidates = orderRegenCandidates(models, sourceModelId).filter(modelSupportsRegen);
+ for (const model of candidates) {
+ if (modelUsesFluxVenv(model)) {
+ if (fluxVenvHealthy) return { available: true, model, pythonPath };
+ } else if (mfluxReady) {
+ return { available: true, model, pythonPath };
+ }
+ }
+ const reason = !fluxVenvHealthy && !mfluxReady
+ ? 'No local FLUX runner is installed. Set up the FLUX.2 venv in Settings → Image Gen to enable image regeneration.'
+ : 'No local FLUX model on this machine supports image-to-image regeneration.';
+ return { available: false, reason };
+}
+
+// Slim shape for the UI gate — drives whether the lightbox shows the
+// Regenerate action at all.
+export async function getRegenAvailability() {
+ const resolved = await resolveRegenBackend();
+ return {
+ available: resolved.available,
+ modelId: resolved.model?.id || null,
+ reason: resolved.available ? null : resolved.reason,
+ };
+}
+
+// Read an image's pixel dimensions off disk. Used to size the regen render to
+// match the source (img2img resizes the init image to width/height; a mismatch
+// would distort composition). Returns null on a read/decode failure so the
+// caller can fall back to the sidecar's recorded dimensions.
+export async function readImageDimensions(absPath) {
+ const meta = await sharp(absPath).metadata().catch(() => null);
+ if (meta?.width && meta?.height) return { width: meta.width, height: meta.height };
+ return null;
+}
+
+// Pure: assemble the mediaJobQueue params for a regen render. Reuses the source
+// image's own prompt (falling back to a generic quality prompt when the source
+// has no recorded prompt — e.g. an upload or an already-cleaned copy) so the
+// round-trip preserves intent. `regenOf` is what stamps the sidecar lineage in
+// `generateImage`. The validated `strength` is the img2img denoise; `steps`
+// (optional) lets the caller pin a low count, otherwise the model default is
+// used. Actual dimensions match the source.
+export function buildRegenParams({ filename, sourceAbsPath, sourceMeta = {}, sourceDims = null, model, pythonPath, strength, steps }) {
+ const dims = sourceDims
+ || (sourceMeta.width && sourceMeta.height ? { width: sourceMeta.width, height: sourceMeta.height } : null);
+ const prompt = typeof sourceMeta.prompt === 'string' && sourceMeta.prompt.trim()
+ ? sourceMeta.prompt
+ : 'high quality, highly detailed';
+ const params = {
+ mode: IMAGE_GEN_MODE.LOCAL,
+ pythonPath,
+ modelId: model.id,
+ prompt,
+ negativePrompt: typeof sourceMeta.negativePrompt === 'string' ? sourceMeta.negativePrompt : '',
+ initImagePath: sourceAbsPath,
+ initImageStrength: strength,
+ regenOf: filename,
+ };
+ if (dims) {
+ params.width = dims.width;
+ params.height = dims.height;
+ }
+ if (steps != null) params.steps = steps;
+ return params;
+}
diff --git a/server/services/imageGen/regen.test.js b/server/services/imageGen/regen.test.js
new file mode 100644
index 0000000000..95f1ed1d33
--- /dev/null
+++ b/server/services/imageGen/regen.test.js
@@ -0,0 +1,165 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// Mock the dependencies resolveRegenBackend composes so the tests stay pure
+// (no filesystem, no settings store, no Python probe).
+vi.mock('../../lib/mediaModels.js', () => ({
+ getImageModels: vi.fn(() => []),
+ isFlux2: (m) => m?.runner === 'flux2',
+}));
+vi.mock('../../lib/runners.js', () => ({
+ usesDiffusersRunner: (m) => m?.runner === 'z-image',
+}));
+vi.mock('../settings.js', () => ({
+ getSettings: vi.fn(async () => ({})),
+}));
+vi.mock('../../lib/pythonSetup.js', () => ({
+ isFlux2VenvHealthy: vi.fn(async () => false),
+}));
+vi.mock('node:fs', () => ({ existsSync: vi.fn(() => false) }));
+vi.mock('sharp', () => ({ default: () => ({ metadata: async () => ({}) }) }));
+
+import { getImageModels } from '../../lib/mediaModels.js';
+import { getSettings } from '../settings.js';
+import { isFlux2VenvHealthy } from '../../lib/pythonSetup.js';
+import { existsSync } from 'node:fs';
+import {
+ orderRegenCandidates, modelSupportsRegen, modelUsesFluxVenv,
+ resolveRegenBackend, buildRegenParams, DEFAULT_REGEN_STRENGTH,
+} from './regen.js';
+
+const FLUX2 = { id: 'flux2-klein-9b', runner: 'flux2', cfgDisabled: true };
+const ZIMAGE = { id: 'z-image-turbo', runner: 'z-image', cfgDisabled: true };
+const MFLUX_DEV = { id: 'dev', runner: 'mflux', steps: 20 };
+
+beforeEach(() => {
+ vi.mocked(getImageModels).mockReturnValue([]);
+ vi.mocked(getSettings).mockResolvedValue({});
+ vi.mocked(isFlux2VenvHealthy).mockResolvedValue(false);
+ vi.mocked(existsSync).mockReturnValue(false);
+});
+
+describe('orderRegenCandidates', () => {
+ it('puts the source model first, then prefers fast (cfgDisabled) models', () => {
+ const models = [MFLUX_DEV, FLUX2, ZIMAGE];
+ const ordered = orderRegenCandidates(models, 'dev');
+ expect(ordered[0].id).toBe('dev'); // source wins regardless of speed
+ // remaining ordered fast-first
+ expect(ordered.slice(1).map((m) => m.id)).toEqual(['flux2-klein-9b', 'z-image-turbo']);
+ });
+
+ it('with no source match, fast models lead', () => {
+ const ordered = orderRegenCandidates([MFLUX_DEV, FLUX2], 'nonexistent');
+ expect(ordered[0].id).toBe('flux2-klein-9b');
+ });
+
+ it('tolerates non-array / empty input', () => {
+ expect(orderRegenCandidates(null, 'x')).toEqual([]);
+ expect(orderRegenCandidates(undefined, 'x')).toEqual([]);
+ });
+});
+
+describe('modelSupportsRegen / modelUsesFluxVenv', () => {
+ it('flux2 + diffusers models use the flux venv and support regen', () => {
+ expect(modelUsesFluxVenv(FLUX2)).toBe(true);
+ expect(modelUsesFluxVenv(ZIMAGE)).toBe(true);
+ expect(modelSupportsRegen(FLUX2)).toBe(true);
+ expect(modelSupportsRegen(ZIMAGE)).toBe(true);
+ });
+
+ it('legacy mflux is not a flux-venv model', () => {
+ expect(modelUsesFluxVenv(MFLUX_DEV)).toBe(false);
+ });
+
+ it('null model never supports regen', () => {
+ expect(modelSupportsRegen(null)).toBe(false);
+ });
+});
+
+describe('resolveRegenBackend', () => {
+ it('reports unavailable when no local models are configured', async () => {
+ vi.mocked(getImageModels).mockReturnValue([]);
+ const r = await resolveRegenBackend();
+ expect(r.available).toBe(false);
+ expect(r.reason).toMatch(/no local image models/i);
+ });
+
+ it('selects a flux2 model when the FLUX.2 venv is healthy', async () => {
+ vi.mocked(getImageModels).mockReturnValue([FLUX2]);
+ vi.mocked(isFlux2VenvHealthy).mockResolvedValue(true);
+ const r = await resolveRegenBackend();
+ expect(r.available).toBe(true);
+ expect(r.model.id).toBe('flux2-klein-9b');
+ });
+
+ it('reports unavailable with an install hint when no runner is installed', async () => {
+ vi.mocked(getImageModels).mockReturnValue([FLUX2]);
+ vi.mocked(isFlux2VenvHealthy).mockResolvedValue(false);
+ vi.mocked(existsSync).mockReturnValue(false);
+ const r = await resolveRegenBackend();
+ expect(r.available).toBe(false);
+ expect(r.reason).toMatch(/no local flux runner is installed/i);
+ });
+
+ it('prefers the source model when it is runnable', async () => {
+ vi.mocked(getImageModels).mockReturnValue([FLUX2, ZIMAGE]);
+ vi.mocked(isFlux2VenvHealthy).mockResolvedValue(true);
+ const r = await resolveRegenBackend({ sourceModelId: 'z-image-turbo' });
+ expect(r.available).toBe(true);
+ expect(r.model.id).toBe('z-image-turbo');
+ });
+});
+
+describe('buildRegenParams', () => {
+ const base = {
+ filename: 'source.png',
+ sourceAbsPath: '/data/images/source.png',
+ model: FLUX2,
+ pythonPath: null,
+ strength: DEFAULT_REGEN_STRENGTH,
+ };
+
+ it('assembles a local img2img job from the source prompt + dims + regenOf', () => {
+ const params = buildRegenParams({
+ ...base,
+ sourceMeta: { prompt: 'a neon city', negativePrompt: 'blurry', width: 1024, height: 768, modelId: 'flux2-klein-9b' },
+ });
+ expect(params).toMatchObject({
+ mode: 'local',
+ modelId: 'flux2-klein-9b',
+ prompt: 'a neon city',
+ negativePrompt: 'blurry',
+ initImagePath: '/data/images/source.png',
+ initImageStrength: 0.4,
+ regenOf: 'source.png',
+ width: 1024,
+ height: 768,
+ });
+ });
+
+ it('prefers measured sourceDims over the sidecar dimensions', () => {
+ const params = buildRegenParams({
+ ...base,
+ sourceMeta: { prompt: 'x', width: 100, height: 100 },
+ sourceDims: { width: 1280, height: 720 },
+ });
+ expect(params.width).toBe(1280);
+ expect(params.height).toBe(720);
+ });
+
+ it('falls back to a generic prompt when the source has none', () => {
+ const params = buildRegenParams({ ...base, sourceMeta: {} });
+ expect(params.prompt).toMatch(/high quality/i);
+ expect(params.negativePrompt).toBe('');
+ });
+
+ it('omits width/height when neither dims source is available', () => {
+ const params = buildRegenParams({ ...base, sourceMeta: { prompt: 'x' } });
+ expect(params.width).toBeUndefined();
+ expect(params.height).toBeUndefined();
+ });
+
+ it('includes steps only when provided', () => {
+ expect(buildRegenParams({ ...base, sourceMeta: { prompt: 'x' } }).steps).toBeUndefined();
+ expect(buildRegenParams({ ...base, sourceMeta: { prompt: 'x' }, steps: 6 }).steps).toBe(6);
+ });
+});