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
feat: Image Cleaner GPU FLUX diffusion round-trip + resolution-aware options + save-to-gallery (#2264)
Adam Eivy0065d2447b0c
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 7dc84e8312..f882095628 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -153,3 +153,5 @@- **[issue-2175] Generation-side character framework + structure doctrine (CWQE Phase 10 remainder).** Following the worldbuilding-doctrine slice (#2219), the character-generation and structure-planning prompts now teach the craft up front. The character bible gains the Ghost → Wound → Lie → Want → Need chain (with interlock checks: state the Lie in one sentence; the Need/Truth is its direct opposite; the Ghost causally explains the Lie), a declared arc type (positive/negative/flat), the Three Sliders (proactivity/likability/competence 1–10, rule: HIGH on ≥2 or one-with-growth; all-low = boring, all-high = Mary Sue), and a secrets list — all OPTIONAL so pre-#2175 records round-trip unchanged (`server/lib/storyBible.js` sanitizer + Zod-shape parity via the existing `canonArrayField` sanitize-on-write, client mirror in `client/src/lib/bibleLimits.js`, character-sheet UI in `CharacterDetailEditor.jsx` with `htmlFor`/`id` pairing, and no-clobber merge in `universeCharacterExpand.js` for the AI-expand path). The `character.consistency` / `arc.*` editorial checks now receive the authored Lie/Want/Need/arc-type when present (via `canonCharacterTraitsSummary`) so they reconcile plan-vs-delivery instead of inferring both. Structure prompts gain lean doctrine: `pipeline-season-episodes.md` a try-fail mandate (60%+ of middle episodes end "Yes, but"/"No, and"), beat rules (Catalyst external; Break Into Two a protagonist choice; All Is Lost includes a death — literal or of a hope/relationship/identity) and an active-climax rule; `pipeline-arc-overview.md` MICE-style thread nesting (threads close in reverse order of opening; name the opening/closing thread per season). Shipped-template edits ship to existing installs via hash-keyed migrations 171/172/173 (with the drift-cross-sync of prior owners 003/005/019/027/166). Remaining Phase 10 items (Le Guin style doctrine into the style-guide flow) stay tracked on #2175.- **[issue-2160] Bulk-history importer for Spotify extended streaming history + shared import seam.** The `/timeline` page gains a collapsible "Import Spotify history" panel: upload the privacy-download ZIP (or a single `Streaming_History_Audio_*.json`) → preview parsed counts/date-range/top-artists → confirm, and every play lands as an idempotent `media.listen` event via the existing `recordEvents()` infra (dedupe on track-uri + played-at, so re-imports and overlapping exports never double-count). Both the modern extended-history shape (`ts`/`ms_played`/`master_metadata_*`) and the legacy `StreamingHistory*.json` shape (`endTime`/`artistName`/`trackName`/`msPlayed`) are parsed; legacy offset-less UTC timestamps are anchored to UTC so a server west of UTC can't shift the listen into the wrong day. The route reuses the streaming `multipart.js` parser + `zipStream.js` (no new deps; the JSON parser is hand-written), Zod-validates the `preview` flag, and always unlinks the temp upload. This is one slice of the larger backfill issue. (`server/services/spotifyImport.js`, `server/routes/timeline.js`, `client/src/services/apiTimeline.js`, `client/src/components/timeline/SpotifyImportPanel.jsx`, `client/src/pages/Timeline.jsx`)++- **[issue-2264] Image Cleaner GPU FLUX diffusion round-trip + resolution-aware options + save-to-gallery.** Completes the composable Image Cleaner (predecessor #1763): the `/devtools/image-clean` page can now run the higher-reliability GPU FLUX img2img round-trip, not just the CPU light pass. The GPU render is GPU-serialized through `mediaJobQueue` (two concurrent FLUX renders OOM the box), so for `?diffusion=gpu` the route stages the already-sync-cleaned bytes to a non-gallery temp dir, enqueues a job through the SAME regen seam the lightbox `/regenerate` flow uses (`resolveRegenBackend` / `buildRegenParams` / `clampRegenDimensions` / `enqueueJob`), and returns HTTP 202 + a `jobId`; the client tracks progress via the existing media-job channel (`useMediaJobProgress`), then GETs the finished bytes from a result endpoint. A non-gallery render seam was factored out of `generateImage` (`resolveOutputPlacement` + an `outputTarget` param): the cleaner renders to `data/image-clean-tmp/` with **no sidecar** and the gallery `completed` index/federate hooks suppressed, so a clean pass never pollutes the gallery by default — the lightbox gallery-write + lineage/variant behavior is untouched. The finished result is ephemeral; an explicit "Save to gallery" action promotes it via `saveUploadedGalleryImage`. Resolution-aware diffusion options land in the page: a GPU/CPU sub-mode selector auto-picked by hardware (`getRegenAvailability()`), a strength slider bounded by the server's `strengthMin`/`strengthMax`, an optional max-render-MP override, a render-budget warning when the source exceeds the FLUX attention budget, and a resolution-squeeze note. The ignore-zone preserve-region mask (#1763) applies to the GPU sub-mode too — the original (oriented) pixels are composited back over the diffused frame after the render. A short-grace age-gated GC (`imageCleanTmpGc.js`) sweeps the temp working files. (`server/routes/imageClean.js`, `server/services/imageGen/cleanGpu.js`, `server/services/imageGen/local.js`, `server/services/imageGen/regen.js`, `server/services/imageCleanTmpGc.js`, `server/lib/fileUtils.js`, `client/src/pages/ImageClean.jsx`, `client/src/services/apiMedia.js`)diff --git a/client/src/pages/ImageClean.jsx b/client/src/pages/ImageClean.jsxindex 207d409777..7a75ff9bba 100644--- a/client/src/pages/ImageClean.jsx+++ b/client/src/pages/ImageClean.jsx@@ -1,9 +1,10 @@import { useState, useRef, useCallback, useEffect } from 'react';-import { Eraser, Upload, Download, ShieldCheck, Sparkles, Brush, Square, Undo2, X } from 'lucide-react';+import { Eraser, Upload, Download, ShieldCheck, Sparkles, Brush, Square, Undo2, X, Cpu, Zap, Save } from 'lucide-react';import toast from '../components/ui/Toast';import BrailleSpinner from '../components/BrailleSpinner';import IgnoreZonePainter from '../components/media/IgnoreZonePainter';import * as api from '../services/api';+import useMediaJobProgress from '../hooks/useMediaJobProgress';import { formatBytes } from '../utils/formatters';const ALLOWED_EXT = /\.(png|jpe?g|webp)$/i;@@ -30,8 +31,25 @@ export default function ImageClean() {const [busy, setBusy] = useState(false);const [dragActive, setDragActive] = useState(false);// Opt-in pipeline steps. metadata defaults ON (lossless), denoise OFF (lossy),- // diffusion OFF (lossy — CPU light pass, the only step that touches SynthID).+ // diffusion OFF (lossy — CPU light pass or GPU FLUX round-trip).const [steps, setSteps] = useState({ metadata: true, denoise: false, diffusion: false });+ // Diffusion sub-mode: 'gpu' (FLUX round-trip, hardware-gated) or 'cpu' (light+ // spatial pass, always available). Auto-selected by hardware once availability+ // loads; the user can override. `regen` carries the availability payload+ // (strength bounds, model id, reason) so the strength slider stays in lock-step+ // with server validation. null until the probe returns.+ const [diffusionMode, setDiffusionMode] = useState('cpu');+ const [regen, setRegen] = useState(null);+ const [strength, setStrength] = useState(0.25);+ const [maxMp, setMaxMp] = useState(''); // '' = use server default budget+ // GPU job tracking (issue #2264). When a GPU clean is enqueued the server+ // returns a jobId; we track it via the media-job channel, then fetch the+ // finished bytes. `gpuJobId` drives the progress hook; `gpuResult` holds the+ // fetched render + whether it was saved to the gallery.+ const [gpuJobId, setGpuJobId] = useState(null);+ const [gpuJob, setGpuJob] = useState(null); // enqueue descriptor (modelId, strength, ...)+ const [savedFilename, setSavedFilename] = useState(null);+ const [saving, setSaving] = useState(false);// Ignore-zone (preserve-region) mask state — only relevant when the diffusion// step is on. `maskTool`/`brushSize`/`feather` drive the painter; `hasMask`// reflects whether any region is painted so the re-clean knows to send it.@@ -45,33 +63,120 @@ export default function ImageClean() {const previewUrlRef = useRef(null);const resultUrlRef = useRef(null);+ // Live progress for the GPU clean job (no-op when gpuJobId is null).+ const jobProgress = useMediaJobProgress(gpuJobId, { kind: 'image' });++ // Probe local FLUX availability once on mount — auto-select GPU when a runner+ // is installed, else fall back to the always-available CPU light pass. Also+ // seeds the strength slider bounds/default so it matches server validation.+ useEffect(() => {+ let alive = true;+ api.getRegenAvailability().then((info) => {+ if (!alive || !info) return;+ setRegen(info);+ setStrength(typeof info.strengthDefault === 'number' ? info.strengthDefault : 0.25);+ setDiffusionMode(info.available ? 'gpu' : 'cpu');+ }).catch(() => {+ // Availability is best-effort — if it fails, stay on the CPU light pass+ // (always available) with the conservative defaults already set.+ });+ return () => { alive = false; };+ }, []);+// Revoke any outstanding blob URL on unmount so we don't leak.useEffect(() => () => {if (previewUrlRef.current) URL.revokeObjectURL(previewUrlRef.current);if (resultUrlRef.current) URL.revokeObjectURL(resultUrlRef.current);}, []);+ // Once the tracked GPU job completes, fetch the finished bytes and show them+ // in the After preview. Gated on the jobId so a stale completion (user moved+ // on) can't overwrite a newer render.+ useEffect(() => {+ if (!gpuJobId || jobProgress.status !== 'completed') return;+ let alive = true;+ const myJob = gpuJobId;+ // The socket `completed` event can (rarely) beat the render's final disk+ // write, so a `pending` (409) result gets a few bounded retries rather than+ // stranding the spinner. The server writes the PNG before emitting the+ // event, so in practice the first attempt succeeds.+ const attempt = (tries) => {+ api.fetchCleanResult(myJob).then((res) => {+ if (!alive || myJob !== gpuJobId) return;+ if (res.pending) {+ if (tries > 0) setTimeout(() => { if (alive && myJob === gpuJobId) attempt(tries - 1); }, 600);+ else { setBusy(false); toast.error('GPU clean result never became available'); }+ return;+ }+ if (resultUrlRef.current) { URL.revokeObjectURL(resultUrlRef.current); resultUrlRef.current = null; }+ const objectUrl = URL.createObjectURL(res.blob);+ resultUrlRef.current = objectUrl;+ const report = res.report || {};+ setResult({+ format: 'png',+ width: report.width,+ height: report.height,+ sizeAfter: res.blob.size,+ sizeBefore: original?.size || res.blob.size,+ mimeType: res.mimeType,+ objectUrl,+ steps: gpuJob?.steps || [],+ c2paStripped: !!gpuJob?.c2paStripped,+ c2paPresent: !!gpuJob?.c2paPresent,+ gpu: true,+ });+ setBusy(false);+ toast.success('GPU clean complete');+ }).catch((err) => {+ if (!alive) return;+ setBusy(false);+ toast.error(err.message || 'Failed to fetch clean result');+ });+ };+ attempt(5);+ return () => { alive = false; };+ }, [gpuJobId, jobProgress.status, original, gpuJob]);++ // A failed/canceled GPU job clears the spinner and surfaces the error.+ useEffect(() => {+ if (!gpuJobId) return;+ if (jobProgress.status === 'failed' || jobProgress.status === 'canceled') {+ setBusy(false);+ toast.error(jobProgress.error || `GPU clean ${jobProgress.status}`);+ }+ }, [gpuJobId, jobProgress.status, jobProgress.error]);+// `skipMask` lets a caller (e.g. Clear) force a mask-free re-clean without// depending on the painter ref having flushed its React state yet — clear()// only schedules state, so reading painterRef.hasMask in the same tick would// still see the stale mask. The Clear path passes skipMask:true explicitly.- const runClean = useCallback(async (file, selectedSteps, { skipMask = false } = {}) => {+ const runClean = useCallback(async (file, selectedSteps, mode, opts = {}) => {+ const { skipMask = false } = opts;if (!file) return;const myRequestId = ++requestIdRef.current;setBusy(true);+ // Reset any prior GPU job/result state on a fresh run.+ setGpuJobId(null);+ setGpuJob(null);+ setSavedFilename(null);if (resultUrlRef.current) {URL.revokeObjectURL(resultUrlRef.current);resultUrlRef.current = null;}setResult(null);- // Map the boolean diffusion toggle to the server's mode enum. Only the CPU- // light pass is wired on this route today; the GPU FLUX round-trip is a- // deferred follow-up (server returns 501 for diffusion=gpu).+ // Map the diffusion toggle + sub-mode to the server's mode enum.+ const diffusion = selectedSteps.diffusion ? (mode === 'gpu' ? 'gpu' : 'light') : 'off';const payload = {metadata: selectedSteps.metadata,denoise: selectedSteps.denoise,- diffusion: selectedSteps.diffusion ? 'light' : 'off',+ diffusion,};+ // GPU-only diffusion knobs.+ if (diffusion === 'gpu') {+ payload.strength = strength;+ const mp = Number(maxMp);+ if (maxMp !== '' && Number.isFinite(mp) && mp > 0) payload.maxMp = mp;+ }// Ignore-zone mask only matters when a diffusion pass runs — export the// painted preserve-region as a PNG Blob and ride it in the request envelope// so the server composites original pixels back into the masked regions.@@ -92,13 +197,25 @@ export default function ImageClean() {setBusy(false);return;}+ // GPU path: the server enqueued a job. Track it — the progress effect fetches+ // the bytes on completion. Keep `busy` true (the spinner shows job progress).+ if (cleaned.gpu) {+ if (!cleaned.job?.jobId) {+ setBusy(false);+ toast.error('GPU clean did not return a job id');+ return;+ }+ setGpuJob(cleaned.job);+ setGpuJobId(cleaned.job.jobId);+ return;+ }setBusy(false);const objectUrl = URL.createObjectURL(cleaned.blob);resultUrlRef.current = objectUrl;const report = cleaned.report || {};setResult({ ...report, mimeType: cleaned.mimeType, objectUrl });toast.success(report.c2paStripped ? 'C2PA chunk removed' : 'Image cleaned');- }, [feather]);+ }, [feather, strength, maxMp]);const handleFile = async (file) => {if (!file) return;@@ -130,7 +247,7 @@ export default function ImageClean() {width: dims?.width || null,height: dims?.height || null,});- runClean(file, steps);+ runClean(file, steps, diffusionMode);};const toggleStep = (key) => {@@ -139,7 +256,12 @@ export default function ImageClean() {setSteps(next);// Re-run immediately against the new selection so the After preview always// reflects the current steps.- if (original?.file) runClean(original.file, next);+ if (original?.file) runClean(original.file, next, diffusionMode);+ };++ const changeDiffusionMode = (mode) => {+ setDiffusionMode(mode);+ if (original?.file && steps.diffusion) runClean(original.file, steps, mode);};const handleDrag = (e) => {@@ -173,6 +295,23 @@ export default function ImageClean() {setOriginal(null);setResult(null);setBusy(false);+ setGpuJobId(null);+ setGpuJob(null);+ setSavedFilename(null);+ };++ const saveToGallery = async () => {+ if (!gpuJobId || saving) return;+ setSaving(true);+ const saved = await api.saveCleanResult(gpuJobId, { silent: true }).catch((err) => {+ toast.error(err.message || 'Failed to save to gallery');+ return null;+ });+ setSaving(false);+ if (saved?.filename) {+ setSavedFilename(saved.filename);+ toast.success('Saved to gallery');+ }};const downloadName = (() => {@@ -188,6 +327,16 @@ export default function ImageClean() {? ((sizeDelta / result.sizeBefore) * 100).toFixed(1): '0.0';+ // Render-budget analysis for the GPU path (issue #2264). The GPU render+ // downscales to fit FLUX's O(tokens²) attention budget, then upscales back —+ // so a source over the budget takes a fidelity hit worth warning about.+ const srcMp = megapixels(original?.width, original?.height);+ const budgetMp = (() => {+ const n = Number(maxMp);+ return maxMp !== '' && Number.isFinite(n) && n > 0 ? n : 2.0; // DEFAULT_MAX_REGEN_MEGAPIXELS+ })();+ const overBudget = srcMp > budgetMp;+const STEP_DEFS = [{key: 'metadata',@@ -201,8 +350,8 @@ export default function ImageClean() {},{key: 'diffusion',- label: 'Diffusion pass — disrupt SynthID (CPU)',- hint: 'Lossy, best-effort — a CPU spatial round-trip (resize-squeeze + color/high-frequency nudge) that perturbs SynthID\'s watermark carriers. Blurs fine text. This is the only step that touches SynthID, and it disrupts — never guarantees removal. GPU FLUX round-trip coming later.',+ label: 'Diffusion pass — disrupt SynthID',+ hint: 'Lossy, best-effort — round-trips the pixels to perturb SynthID\'s watermark carriers. This is the only step that touches SynthID, and it disrupts — never guarantees removal. Blurs fine text (use the ignore-zone mask to preserve regions).',},];@@ -225,8 +374,8 @@ export default function ImageClean() {openai.com/synthid</a>), since SynthID is embedded in pixel values and was designed to survive median + sharpen + re-encode. The <strong>diffusion pass</strong>{' '}- (CPU) is the only step that perturbs SynthID's carriers — best-effort, and it <em>disrupts</em> rather than guarantees removal (never verified against- Google's detector). The higher-reliability GPU FLUX round-trip is a follow-up.+ is the only step that perturbs SynthID's carriers — best-effort, and it <em>disrupts</em> rather than guarantees removal (never verified against+ Google's detector).</p></div></div>@@ -303,6 +452,97 @@ export default function ImageClean() {</div></div>+ {/* Diffusion options — sub-mode + resolution-aware controls (issue #2264) */}+ {steps.diffusion && (+ <div className="bg-port-card border border-port-border rounded-lg p-4 space-y-4">+ <div className="flex items-center gap-2">+ <Zap size={16} className="text-port-accent" />+ <span className="text-sm font-medium text-white">Diffusion sub-mode</span>+ </div>+ {/* Sub-mode selector — GPU (hardware-gated) vs CPU light pass. */}+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">+ <button+ type="button"+ onClick={() => changeDiffusionMode('gpu')}+ disabled={busy || !regen?.available}+ className={`text-left p-3 rounded-lg border transition-colors ${+ diffusionMode === 'gpu'+ ? 'border-port-accent bg-port-accent/10'+ : 'border-port-border hover:border-port-accent/50'+ } ${!regen?.available ? 'opacity-40 cursor-not-allowed' : ''}`}+ >+ <span className="flex items-center gap-2 text-sm text-white"><Zap size={14} /> GPU FLUX round-trip</span>+ <span className="block text-xs text-gray-500 mt-1">+ {regen?.available+ ? `Higher reliability. Model: ${regen.modelId || 'local FLUX'}. GPU-serialized (queued).`+ : (regen?.reason || 'No local FLUX runner installed.')}+ </span>+ </button>+ <button+ type="button"+ onClick={() => changeDiffusionMode('cpu')}+ disabled={busy}+ className={`text-left p-3 rounded-lg border transition-colors ${+ diffusionMode === 'cpu'+ ? 'border-port-accent bg-port-accent/10'+ : 'border-port-border hover:border-port-accent/50'+ }`}+ >+ <span className="flex items-center gap-2 text-sm text-white"><Cpu size={14} /> CPU light pass</span>+ <span className="block text-xs text-gray-500 mt-1">+ Always available, synchronous. Best-effort spatial round-trip — lower reliability than the GPU pass.+ </span>+ </button>+ </div>++ {/* GPU-only resolution-aware options. */}+ {diffusionMode === 'gpu' && (+ <div className="space-y-3 border-t border-port-border pt-3">+ <div className="flex flex-col sm:flex-row sm:items-center gap-4">+ <div className="flex items-center gap-2 flex-1">+ <label htmlFor="strength" className="text-xs text-gray-500 whitespace-nowrap">Denoise strength</label>+ <input+ id="strength"+ type="range"+ min={regen?.strengthMin ?? 0.02}+ max={regen?.strengthMax ?? 0.6}+ step="0.01"+ value={strength}+ onChange={(e) => setStrength(Number(e.target.value))}+ disabled={busy}+ className="flex-1 accent-port-accent"+ />+ <span className="text-xs text-gray-400 w-10 text-right">{strength.toFixed(2)}</span>+ </div>+ <div className="flex items-center gap-2 flex-1">+ <label htmlFor="max-mp" className="text-xs text-gray-500 whitespace-nowrap">Max render MP</label>+ <input+ id="max-mp"+ type="number"+ min="0.25"+ max="16"+ step="0.25"+ value={maxMp}+ placeholder="2.0 (default)"+ onChange={(e) => setMaxMp(e.target.value)}+ disabled={busy}+ className="flex-1 bg-port-bg border border-port-border rounded px-2 py-1 text-sm text-white"+ />+ </div>+ </div>+ <p className="text-xs text-gray-500">+ A universal resolution-squeeze (~0.9×) is applied automatically as a second disruption vector, then the render is upscaled back to source dimensions.+ </p>+ {overBudget && (+ <p className="text-xs text-port-warning">+ Source is {srcMp.toFixed(1)}MP, above the {budgetMp.toFixed(1)}MP render budget — the render downscales to fit FLUX's attention budget, then upscales back to {original.width}×{original.height}. Expect some fidelity loss.+ </p>+ )}+ </div>+ )}+ </div>+ )}+{/* Ignore-zone (preserve-region) mask painter — only when diffusion is on */}{steps.diffusion && (<div className="bg-port-card border border-port-border rounded-lg p-4 space-y-3">@@ -331,7 +571,7 @@ export default function ImageClean() {<Undo2 size={12} /> Undo</button><button- onClick={() => { painterRef.current?.clear(); if (original?.file) runClean(original.file, steps, { skipMask: true }); }}+ onClick={() => { painterRef.current?.clear(); if (original?.file) runClean(original.file, steps, diffusionMode, { skipMask: true }); }}className="px-2 py-1 rounded text-xs flex items-center gap-1 border border-port-border text-gray-400 hover:text-white transition-colors"><X size={12} /> Clear@@ -380,7 +620,7 @@ export default function ImageClean() {<span className="text-xs text-gray-400 w-10 text-right">{feather}px</span></div><button- onClick={() => { if (original?.file) runClean(original.file, steps); }}+ onClick={() => { if (original?.file) runClean(original.file, steps, diffusionMode); }}disabled={busy || !hasMask}className="px-3 py-1.5 rounded text-sm bg-port-accent hover:bg-port-accent/80 disabled:opacity-40 disabled:cursor-not-allowed text-white transition-colors whitespace-nowrap">@@ -412,7 +652,14 @@ export default function ImageClean() {{result && <span className="text-xs text-gray-500">{formatBytes(result.sizeAfter)}</span>}</div><div className="p-4 flex items-center justify-center bg-port-bg/50 min-h-[200px]">- {busy && <BrailleSpinner text="Cleaning" />}+ {busy && gpuJobId && (+ <BrailleSpinner text={+ jobProgress.status === 'queued' ? 'Queued (GPU)'+ : jobProgress.status === 'running' ? `Rendering${typeof jobProgress.progress === 'number' && jobProgress.progress > 0 ? ` ${Math.round(jobProgress.progress * 100)}%` : ''}`+ : 'Cleaning'+ } />+ )}+ {busy && !gpuJobId && <BrailleSpinner text="Cleaning" />}{!busy && result && (<imgsrc={result.objectUrl}@@ -489,6 +736,18 @@ export default function ImageClean() {Download</a>)}+ {/* Save-to-gallery — only for a finished GPU render (the temp result+ is discarded by default; this promotes it to a gallery citizen). */}+ {result?.gpu && gpuJobId && (+ <button+ onClick={saveToGallery}+ disabled={saving || !!savedFilename}+ className="px-4 py-2 bg-port-card border border-port-border hover:border-port-accent/50 text-gray-300 rounded-lg transition-colors flex items-center gap-2 disabled:opacity-40 disabled:cursor-not-allowed"+ >+ <Save size={16} />+ {savedFilename ? 'Saved to gallery' : saving ? 'Saving…' : 'Save to gallery'}+ </button>+ )}<buttononClick={handleReset}className="px-4 py-2 bg-port-card border border-port-border hover:border-port-accent/50 text-gray-300 rounded-lg transition-colors"diff --git a/client/src/services/apiMedia.js b/client/src/services/apiMedia.jsindex f9fca420dc..0fcba2632f 100644--- a/client/src/services/apiMedia.js+++ b/client/src/services/apiMedia.js@@ -35,10 +35,15 @@ export const deleteAllUploads = (options = {}) => request('/uploads?confirm=true// page's own catch can toast (no silent flag needed — this never double-toasts).//// `steps` is `{ metadata?: boolean, denoise?: boolean, diffusion?: 'off'|'light'|'gpu',-// mask?: Blob, feather?: number }`.+// mask?: Blob, feather?: number, strength?: number, maxMp?: number }`.// metadata/denoise default on the server (metadata ON, denoise OFF); diffusion// defaults to 'off'. 'light' runs the CPU spatial SynthID-disruption pass;-// 'gpu' (the FLUX round-trip) is not yet wired here and returns a 501.+// 'gpu' (the FLUX round-trip) is GPU-serialized: the server returns HTTP 202+// with a `{ mode:'gpu', jobId, ... }` JSON body instead of image bytes. This+// wrapper detects that and returns `{ gpu: true, job }` so the caller can track+// progress via the media-job channel and then fetch the result (see+// `fetchCleanResult` / `saveCleanResult` below). `strength`/`maxMp` are+// GPU-only diffusion knobs, ignored by the sync passes.//// When a `mask` Blob (a painted preserve-region PNG) is supplied AND a diffusion// step runs, the body is framed as an ignore-zone envelope@@ -50,6 +55,8 @@ export const cleanImage = async (file, steps = {}) => {if (typeof steps.metadata === 'boolean') params.set('metadata', steps.metadata ? '1' : '0');if (typeof steps.denoise === 'boolean') params.set('denoise', steps.denoise ? '1' : '0');if (typeof steps.diffusion === 'string' && steps.diffusion !== 'off') params.set('diffusion', steps.diffusion);+ if (typeof steps.strength === 'number') params.set('strength', String(steps.strength));+ if (typeof steps.maxMp === 'number') params.set('maxMp', String(steps.maxMp));// Build the request body. With a mask + a diffusion step, prefix the raw image// bytes with the length-framed mask; otherwise send the file directly.@@ -92,9 +99,52 @@ export const cleanImage = async (file, steps = {}) => {throw err;}+ // GPU FLUX round-trip: the server enqueued a job and returned 202 + JSON+ // (no image bytes). Hand the job descriptor back so the caller tracks progress+ // and fetches the result when it completes.+ if (response.status === 202) {+ const job = await response.json().catch(() => null);+ return { gpu: true, job };+ }+const reportHeader = response.headers.get('X-Clean-Report');let report = null;if (reportHeader) { try { report = JSON.parse(reportHeader); } catch { report = null; } }const blob = await response.blob();return { blob, mimeType: blob.type || report?.format || 'application/octet-stream', report };};++// Fetch the finished bytes for a GPU FLUX clean job (issue #2264). Returns+// `{ blob, mimeType, report }` on 200, `{ pending: true }` while the job is+// still rendering (409 RESULT_NOT_READY — the caller keeps polling the+// media-job channel), or throws on a hard failure (404/JOB_FAILED). The result+// is ephemeral; call `saveCleanResult` to keep it in the gallery.+export const fetchCleanResult = async (jobId) => {+ const response = await fetch(`${API_BASE}/image-clean/result/${encodeURIComponent(jobId)}`).catch(() => null);+ if (!response) throw new Error('Server unreachable — check your connection and try again');+ if (response.status === 409) {+ const err = await response.json().catch(() => ({}));+ if (err?.code === 'RESULT_NOT_READY') return { pending: true };+ const e = new Error(err.error || 'Clean job failed');+ e.code = err.code; e.status = 409;+ throw e;+ }+ if (!response.ok) {+ const err = await response.json().catch(() => ({ error: 'Failed to fetch clean result' }));+ maybeRedirectToLogin(response, err);+ const e = new Error(err.error || `HTTP ${response.status}`);+ e.code = err?.code; e.status = response.status;+ throw e;+ }+ const reportHeader = response.headers.get('X-Clean-Report');+ let report = null;+ if (reportHeader) { try { report = JSON.parse(reportHeader); } catch { report = null; } }+ const blob = await response.blob();+ return { blob, mimeType: blob.type || 'image/png', report };+};++// Explicit save-to-gallery for a finished GPU clean result (the default is NOT+// to keep it). Returns the new gallery `{ filename, path }`. Silent so the+// page's own useAsyncAction/catch owns the error toast.+export const saveCleanResult = (jobId, options = {}) =>+ request(`/image-clean/result/${encodeURIComponent(jobId)}/save`, { method: 'POST', ...options });diff --git a/client/src/services/apiMedia.test.js b/client/src/services/apiMedia.test.jsnew file mode 100644index 0000000000..e23a6e7808--- /dev/null+++ b/client/src/services/apiMedia.test.js@@ -0,0 +1,103 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';++// cleanImage / fetchCleanResult call global fetch() directly (Blob body + custom+// header, which the JSON-oriented request() helper can't surface). saveCleanResult+// goes through request(). Mock both layers.+const request = vi.fn();+vi.mock('./apiCore.js', () => ({+ request: (...a) => request(...a),+ API_BASE: '/api',+ maybeRedirectToLogin: vi.fn(),+}));++let cleanImage;+let fetchCleanResult;+let saveCleanResult;++beforeEach(async () => {+ vi.resetModules();+ request.mockReset();+ ({ cleanImage, fetchCleanResult, saveCleanResult } = await import('./apiMedia.js'));+ global.fetch = vi.fn();+});++afterEach(() => {+ vi.restoreAllMocks();+});++// Minimal fetch Response stub. `blob()` returns a Blob-like with a `.type`.+const makeResponse = ({ status = 200, ok = status < 400, headers = {}, json = null, blobType = 'image/png' } = {}) => ({+ status,+ ok,+ headers: { get: (k) => headers[k] ?? headers[k.toLowerCase()] ?? null },+ json: async () => json,+ blob: async () => ({ type: blobType, size: 123 }),+});++const fakeFile = { arrayBuffer: async () => new Uint8Array([1, 2, 3]).buffer, type: 'image/png', name: 'x.png' };++describe('cleanImage', () => {+ it('threads GPU-only strength + maxMp into the query string', async () => {+ global.fetch.mockResolvedValue(makeResponse({ status: 200, headers: { 'X-Clean-Report': '{"format":"png"}' } }));+ await cleanImage(fakeFile, { metadata: true, diffusion: 'gpu', strength: 0.35, maxMp: 1.5 });+ const url = global.fetch.mock.calls[0][0];+ expect(url).toContain('diffusion=gpu');+ expect(url).toContain('strength=0.35');+ expect(url).toContain('maxMp=1.5');+ });++ it('returns { gpu:true, job } on a 202 enqueue response', async () => {+ const job = { mode: 'gpu', jobId: 'j1', modelId: 'flux2-klein-4b', strength: 0.25 };+ global.fetch.mockResolvedValue(makeResponse({ status: 202, json: job }));+ const out = await cleanImage(fakeFile, { diffusion: 'gpu' });+ expect(out.gpu).toBe(true);+ expect(out.job.jobId).toBe('j1');+ });++ it('returns the blob + parsed report on a 200 sync response', async () => {+ global.fetch.mockResolvedValue(makeResponse({ status: 200, headers: { 'X-Clean-Report': '{"format":"png","c2paStripped":true}' } }));+ const out = await cleanImage(fakeFile, { metadata: true });+ expect(out.gpu).toBeUndefined();+ expect(out.report.c2paStripped).toBe(true);+ expect(out.mimeType).toBe('image/png');+ });++ it('throws with the server code on an error response', async () => {+ global.fetch.mockResolvedValue(makeResponse({ status: 400, ok: false, json: { error: 'No FLUX', code: 'REGEN_BACKEND_UNAVAILABLE' } }));+ await expect(cleanImage(fakeFile, { diffusion: 'gpu' })).rejects.toMatchObject({ code: 'REGEN_BACKEND_UNAVAILABLE' });+ });+});++describe('fetchCleanResult', () => {+ it('returns { pending:true } while the job is still rendering (409 RESULT_NOT_READY)', async () => {+ global.fetch.mockResolvedValue(makeResponse({ status: 409, ok: false, json: { code: 'RESULT_NOT_READY' } }));+ const out = await fetchCleanResult('j1');+ expect(out.pending).toBe(true);+ });++ it('returns the finished blob + report on 200', async () => {+ global.fetch.mockResolvedValue(makeResponse({ status: 200, headers: { 'X-Clean-Report': '{"mode":"gpu","width":8}' } }));+ const out = await fetchCleanResult('j1');+ expect(out.report.mode).toBe('gpu');+ expect(out.mimeType).toBe('image/png');+ });++ it('throws on a hard failure (JOB_FAILED)', async () => {+ global.fetch.mockResolvedValue(makeResponse({ status: 409, ok: false, json: { error: 'runner OOM', code: 'JOB_FAILED' } }));+ await expect(fetchCleanResult('j1')).rejects.toMatchObject({ code: 'JOB_FAILED' });+ });++ it('throws on a 404 (result gone / unknown id)', async () => {+ global.fetch.mockResolvedValue(makeResponse({ status: 404, ok: false, json: { error: 'not found', code: 'NOT_FOUND' } }));+ await expect(fetchCleanResult('j1')).rejects.toMatchObject({ status: 404 });+ });+});++describe('saveCleanResult', () => {+ it('POSTs to the save endpoint (silent) and returns the gallery record', async () => {+ request.mockResolvedValue({ filename: 'upload-abc.png', path: '/data/images/upload-abc.png' });+ const out = await saveCleanResult('j1');+ expect(request).toHaveBeenCalledWith('/image-clean/result/j1/save', expect.objectContaining({ method: 'POST' }));+ expect(out.filename).toBe('upload-abc.png');+ });+});diff --git a/server/index.js b/server/index.jsindex 0a5d1db426..76bbbc10c7 100644--- a/server/index.js+++ b/server/index.js@@ -185,6 +185,7 @@ import { recoverStuckAutoRuns } from './services/pipeline/autoRunner.js';import { recoverStuckAutopilots } from './services/pipeline/seriesAutopilot.js';import { startOrphanShellGc } from './services/importerOrphanGc.js';import { startImageRefsGc } from './services/imageRefsGc.js';+import { startImageCleanTmpGc } from './services/imageCleanTmpGc.js';import { initBridge as initBrainMemoryBridge } from './services/brainMemoryBridge.js';import { initDrillCache } from './services/meatspacePostDrillCache.js';import { registerPostReminderSchedule } from './services/meatspacePostReminder.js';@@ -609,6 +610,10 @@ startOrphanShellGc();// Periodically GC orphan staged init/reference upload images that pile up in// data/image-refs on every i2i/edit render and are never cleaned up (issue #1214).startImageRefsGc();+// Periodically GC the Image Cleaner's GPU-clean temp working files (init/render/+// mask/original) that land in data/image-clean-tmp and are never long-lived+// (issue #2264). Age-gate only — nothing here is referenced after the fetch.+startImageCleanTmpGc();// Warm the catalog user-type registry from the user-type store (Postgres as of// #1001; the settings.json slice under the escape hatch) before any catalog// request can land, so user-defined types validate + mint ids immediately ondiff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.jsindex 33f2c46cec..5873a50412 100644--- a/server/lib/fileUtils.js+++ b/server/lib/fileUtils.js@@ -95,6 +95,13 @@ export const PATHS = {// never surfaces them, and so a future per-render cleanup pass can drop// the whole dir without touching the gallery.imageRefs: join(INSTALL_ROOT, 'data/image-refs'),+ // Ephemeral working dir for the Image Cleaner's GPU FLUX round-trip (issue+ // #2264). The sync-cleaned init bytes and the finished render land here as+ // `<jobId>-init.png` / `<jobId>-result.png` so the cleaner can render WITHOUT+ // writing a gallery file + sidecar (the default is not to keep the result).+ // A sibling of `images/` — never surfaced by the gallery's flat `.png`+ // enumeration; swept by imageCleanTmpGc.js on an age gate. Not federated.+ imageCleanTmp: join(INSTALL_ROOT, 'data/image-clean-tmp'),loras: join(INSTALL_ROOT, 'data/loras'),// Per-character LoRA training datasets (collectionStore layout:// lora-datasets/<id>/index.json + lora-datasets/<id>/images/*.png).@@ -1095,6 +1102,15 @@ export const resolveGalleryImage = makePathResolver(() => PATHS.images);*/export const resolveImageRef = makePathResolver(() => PATHS.imageRefs);+/**+ * Resolve an Image Cleaner temp init/result filename to an absolute path under+ * `PATHS.imageCleanTmp` (issue #2264). The GPU FLUX round-trip stages the+ * sync-cleaned init bytes here and renders the result back here, so the runner+ * must accept this root as a valid `initImagePath` source. Same defense-in-depth+ * as the gallery/refs resolvers, anchored at the temp root.+ */+export const resolveImageCleanTmp = makePathResolver(() => PATHS.imageCleanTmp);+/*** Resolve a shipped visual template filename (e.g. character reference-sheet* layout PNG) to an absolute path under `PATHS.visualTemplates`. Caches@@ -1145,6 +1161,9 @@ const IMAGE_INPUT_RESOLVERS = [['images', resolveGalleryImage],['imageRefs', resolveImageRef],['visualTemplates', resolveTemplateAsset],+ // Image Cleaner temp init images (issue #2264) — the GPU FLUX round-trip+ // stages sync-cleaned bytes here as the img2img init.+ ['imageCleanTmp', resolveImageCleanTmp],];export function resolveImageInputPath(rawPath) {diff --git a/server/routes/imageClean.js b/server/routes/imageClean.jsindex 02c036dcbc..207212c74a 100644--- a/server/routes/imageClean.js+++ b/server/routes/imageClean.js@@ -14,7 +14,8 @@ import sharp from 'sharp';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { validateRequest } from '../lib/validation.js';import { cleanImageBuffer, CLEAN_LEVELS, compositeIgnoreZone, IGNORE_ZONE_FEATHER_DEFAULT } from '../lib/imageClean.js';-import { applyLightRegen, computePixelDelta } from '../services/imageGen/regen.js';+import { applyLightRegen, computePixelDelta, REGEN_STRENGTH_MIN, REGEN_STRENGTH_MAX } from '../services/imageGen/regen.js';+import { enqueueGpuClean, readGpuCleanResult, getGpuCleanStatus, saveGpuCleanToGallery } from '../services/imageGen/cleanGpu.js';const router = Router();@@ -38,11 +39,11 @@ const queryFlag = (def) => z.preprocess(// Diffusion sub-mode. `off` (default) skips it entirely; `light` runs the// CPU-only spatial pass (`applyLightRegen`) that actually perturbs SynthID's// resolution-dependent carriers — the no-GPU fallback, always available since-// sharp is a hard dependency. `gpu` (the FLUX img2img round-trip) is NOT wired-// on this route yet: it needs the non-gallery render seam factored out of the-// lightbox `/regenerate` flow (async job queue + progress channel), deferred to-// a follow-up. Accepting the token but rejecting it with a clear 501 keeps the-// client contract stable for when that lands. Anything else → the `off` default.+// sharp is a hard dependency. `gpu` (the FLUX img2img round-trip) is+// GPU-serialized via mediaJobQueue: the route stages the sync-cleaned bytes,+// enqueues a job through the shared regen seam, and returns a `jobId` the+// client tracks via the media-job progress channel (issue #2264). Anything+// else → the `off` default.const diffusionMode = z.preprocess((v) => {if (v === undefined || v === '' || v === '0' || v === 'false' || v === 'off') return 'off';@@ -67,6 +68,18 @@ const cleanQuerySchema = z.object({(v) => (v === undefined || v === '' ? IGNORE_ZONE_FEATHER_DEFAULT : Number(v)),z.number().min(0).max(50),),+ // GPU-diffusion-only knobs (issue #2264), ignored by the sync passes.+ // `strength` is the img2img denoise, clamped to the same [MIN, MAX] the+ // lightbox slider is bound to; absent → the conservative arbitrary-upload+ // default. `maxMp` is the optional per-run render-megapixel budget override.+ strength: z.preprocess(+ (v) => (v === undefined || v === '' ? undefined : Number(v)),+ z.number().min(REGEN_STRENGTH_MIN).max(REGEN_STRENGTH_MAX).optional(),+ ),+ maxMp: z.preprocess(+ (v) => (v === undefined || v === '' ? undefined : Number(v)),+ z.number().min(0.25).max(16).optional(),+ ),});// Decode the optional ignore-zone envelope. When `?mask=1`, the body is@@ -103,18 +116,7 @@ router.post('/',raw({ type: RAW_TYPES, limit: RAW_LIMIT }),asyncHandler(async (req, res) => {- const { metadata, denoise, diffusion, mask: hasMask, feather } = validateRequest(cleanQuerySchema, req.query);-- // The GPU FLUX round-trip needs the non-gallery render seam factored out of- // the lightbox `/regenerate` flow (async job queue + media-job progress),- // which this slice defers to a follow-up. Reject it explicitly so a client- // that asked for it gets an actionable message rather than a silent CPU pass.- if (diffusion === 'gpu') {- throw new ServerError('GPU FLUX diffusion is not yet available on the Image Cleaner. Use the CPU light pass (diffusion=light) or run a regeneration from the ImageGen lightbox.', {- status: 501,- code: 'NOT_IMPLEMENTED',- });- }+ const { metadata, denoise, diffusion, mask: hasMask, feather, strength, maxMp } = validateRequest(cleanQuerySchema, req.query);const rawBody = Buffer.isBuffer(req.body) ? req.body : null;const { image: buffer, mask: maskBuffer } = splitMaskEnvelope(rawBody, hasMask);@@ -132,6 +134,43 @@ router.post(const result = await cleanImageBuffer(buffer, { metadata, denoise });+ // GPU FLUX round-trip (issue #2264). Unlike the sync passes, the GPU render+ // is GPU-serialized through mediaJobQueue and can't run inline — so hand the+ // already-sync-cleaned bytes to the shared regen seam, enqueue a job, and+ // return a `jobId` (HTTP 202). The client tracks progress via the media-job+ // channel, then GETs the finished bytes from the result endpoint. The mask,+ // when present, is staged with the (oriented) original so the result-fetch+ // composites the preserved region back over the diffused frame.+ if (diffusion === 'gpu') {+ // Orientation parity (same rationale as the light-pass block below): bake+ // EXIF orientation into the init + preserved-original so the mask (painted+ // in visual space) aligns with the render.+ let gpuInit = result.data;+ let gpuOriginal = maskBuffer ? originalBuffer : null;+ if (maskBuffer) {+ const orientedPng = await sharp(result.data).rotate().png().toBuffer().catch(() => null);+ if (orientedPng) { gpuInit = orientedPng; gpuOriginal = orientedPng; }+ }+ const sourceDims = result.width && result.height ? { width: result.width, height: result.height } : null;+ const queued = await enqueueGpuClean({+ initBuffer: gpuInit,+ sourceDims,+ strength,+ maxMegapixels: maxMp,+ originalBuffer: maskBuffer ? gpuOriginal : null,+ maskBuffer: maskBuffer || null,+ feather,+ });+ console.log(`🧼 Image clean GPU job queued: ${queued.modelId} (strength=${queued.strength}) → job ${queued.jobId.slice(0, 8)}`);+ return res.status(202).json({+ mode: 'gpu',+ ...queued,+ c2paStripped: result.c2paStripped,+ c2paPresent: result.c2paPresent,+ steps: result.steps,+ });+ }+// Diffusion (CPU light pass) runs LAST in the pipeline order (metadata →// denoise → diffusion), on the already-cleaned bytes. `applyLightRegen` is a// pure sharp round-trip (resize-squeeze + micro color nudge + high-freq@@ -247,4 +286,61 @@ router.post(}),);+// Validate a clean job id — the mediaJobQueue mints v4 UUIDs, so anything that+// isn't UUID-shaped can't be a real job (and keeps the temp-path resolution+// safe). Reused by the result-fetch + save-to-gallery routes below.+const jobIdSchema = z.object({+ jobId: z.string().uuid('Invalid job id'),+});++// Result-fetch for a GPU FLUX clean job (issue #2264). Returns the finished+// temp render bytes (with any pending ignore-zone composite applied) as the+// response body — the default is NOT to keep them in the gallery. 409 while the+// job is still queued/running (the client keeps polling the media-job channel);+// 404 once past the temp GC / never produced. The result stays ephemeral: the+// caller saves it explicitly via POST below if they want to keep it.+router.get(+ '/result/:jobId',+ asyncHandler(async (req, res) => {+ const { jobId } = validateRequest(jobIdSchema, req.params);+ const status = getGpuCleanStatus(jobId);+ if (status.status === 'failed' || status.status === 'canceled') {+ throw new ServerError(status.error || `Clean job ${status.status}`, { status: 409, code: 'JOB_FAILED' });+ }+ const result = await readGpuCleanResult(jobId);+ if (!result) {+ // Distinguish "still rendering" (keep polling) from "gone" (past the temp+ // GC or an unknown id) so the client can stop polling on a true miss.+ const inFlight = status.status === 'queued' || status.status === 'running';+ throw new ServerError(+ inFlight ? 'Clean result not ready yet' : 'Clean result not found',+ { status: inFlight ? 409 : 404, code: inFlight ? 'RESULT_NOT_READY' : 'NOT_FOUND', severity: 'warning' },+ );+ }+ res.setHeader('Access-Control-Expose-Headers', 'X-Clean-Report');+ res.setHeader('X-Clean-Report', JSON.stringify({+ format: 'png',+ width: result.width,+ height: result.height,+ composited: result.composited,+ mode: 'gpu',+ }));+ res.setHeader('Content-Type', 'image/png');+ res.send(result.data);+ }),+);++// Explicit save-to-gallery for a GPU FLUX clean result (issue #2264). The+// default clean flow never touches the gallery; this promotes the finished+// temp render to a first-class gallery citizen (reusing saveUploadedGalleryImage+// so it lists/deletes like any other). Returns the new gallery `{ filename, path }`.+router.post(+ '/result/:jobId/save',+ asyncHandler(async (req, res) => {+ const { jobId } = validateRequest(jobIdSchema, req.params);+ const saved = await saveGpuCleanToGallery(jobId);+ res.status(201).json(saved);+ }),+);+export default router;diff --git a/server/routes/imageClean.test.js b/server/routes/imageClean.test.jsindex ddbe45ac3e..a115d70723 100644--- a/server/routes/imageClean.test.js+++ b/server/routes/imageClean.test.js@@ -1,9 +1,24 @@-import { describe, it, expect, beforeAll } from 'vitest';+import { describe, it, expect, beforeAll, vi, beforeEach } from 'vitest';import { randomBytes } from 'node:crypto';import express from 'express';import sharp from 'sharp';import { request } from '../lib/testHelper.js';import { errorMiddleware } from '../lib/errorHandler.js';++// Mock the GPU-clean orchestration so the route's ?diffusion=gpu path never+// touches the REAL mediaJobQueue / FLUX runner (which would enqueue a live job+// against the shared install — and would OOM/spawn Python on a machine that has+// a runner installed). The route contract (stage → enqueue → 202 with jobId,+// result-fetch, save-to-gallery) is what's under test here; the seam's own+// behavior (temp staging, param assembly) is covered in cleanGpu.test.js.+vi.mock('../services/imageGen/cleanGpu.js', () => ({+ enqueueGpuClean: vi.fn(),+ readGpuCleanResult: vi.fn(),+ getGpuCleanStatus: vi.fn(),+ saveGpuCleanToGallery: vi.fn(),+}));++import { enqueueGpuClean, readGpuCleanResult, getGpuCleanStatus, saveGpuCleanToGallery } from '../services/imageGen/cleanGpu.js';import imageCleanRoutes from './imageClean.js';// Mirror server/index.js: the global express.json() runs first but is a no-op@@ -64,6 +79,13 @@ const postImage = (query, buffer, contentType = 'image/png') =>.set('Content-Type', contentType).send(buffer);+beforeEach(() => {+ vi.mocked(enqueueGpuClean).mockReset();+ vi.mocked(readGpuCleanResult).mockReset();+ vi.mocked(getGpuCleanStatus).mockReset();+ vi.mocked(saveGpuCleanToGallery).mockReset();+});+describe('POST /api/image-clean (raw transport)', () => {it('cleans a PNG and returns the bytes + report header', async () => {const res = await postImage('', pngFixture);@@ -142,10 +164,75 @@ describe('POST /api/image-clean (raw transport)', () => {expect(report.steps.map((s) => s.step)).toEqual(['metadata', 'denoise', 'diffusion']);});- it('rejects GPU diffusion with 501 NOT_IMPLEMENTED (deferred to a follow-up)', async () => {+ it('enqueues a GPU FLUX clean job and returns 202 + jobId (issue #2264)', async () => {+ vi.mocked(enqueueGpuClean).mockResolvedValue({+ jobId: '11111111-1111-4111-8111-111111111111',+ position: 1,+ status: 'queued',+ modelId: 'flux2-klein-4b',+ strength: 0.25,+ width: 16,+ height: 16,+ scaled: true,+ });+ const res = await postImage('?diffusion=gpu', pngFixture);+ expect(res.status).toBe(202);+ expect(res.body.mode).toBe('gpu');+ expect(res.body.jobId).toBe('11111111-1111-4111-8111-111111111111');+ expect(res.body.modelId).toBe('flux2-klein-4b');+ // The sync-clean report rides along so the client can show what already ran.+ expect(Array.isArray(res.body.steps)).toBe(true);+ // The already-sync-cleaned bytes were handed to the seam, not the raw upload.+ expect(vi.mocked(enqueueGpuClean)).toHaveBeenCalledTimes(1);+ const arg = vi.mocked(enqueueGpuClean).mock.calls[0][0];+ expect(Buffer.isBuffer(arg.initBuffer)).toBe(true);+ });++ it('surfaces the no-FLUX-runner gate as a 400 on the GPU path', async () => {+ vi.mocked(enqueueGpuClean).mockRejectedValue(+ Object.assign(new Error('No local FLUX runner is installed.'), { status: 400, code: 'REGEN_BACKEND_UNAVAILABLE' }),+ );const res = await postImage('?diffusion=gpu', pngFixture);- expect(res.status).toBe(501);- expect(res.body.code).toBe('NOT_IMPLEMENTED');+ expect(res.status).toBe(400);+ expect(res.body.code).toBe('REGEN_BACKEND_UNAVAILABLE');+ });++ it('passes a validated strength + max-MP override through to the GPU seam', async () => {+ vi.mocked(enqueueGpuClean).mockResolvedValue({+ jobId: '22222222-2222-4222-8222-222222222222', position: 1, status: 'queued',+ modelId: 'flux2-klein-4b', strength: 0.4, width: 16, height: 16, scaled: false,+ });+ const res = await postImage('?diffusion=gpu&strength=0.4&maxMp=1.5', pngFixture);+ expect(res.status).toBe(202);+ const arg = vi.mocked(enqueueGpuClean).mock.calls[0][0];+ expect(arg.strength).toBe(0.4);+ expect(arg.maxMegapixels).toBe(1.5);+ });++ it('rejects an out-of-range strength on the GPU path with VALIDATION_ERROR', async () => {+ const res = await postImage('?diffusion=gpu&strength=5', pngFixture);+ expect(res.status).toBe(400);+ expect(res.body.code).toBe('VALIDATION_ERROR');+ // The seam was never reached — validation short-circuits.+ expect(vi.mocked(enqueueGpuClean)).not.toHaveBeenCalled();+ });++ it('stages the oriented original + mask for the GPU composite when a mask rides along', async () => {+ vi.mocked(enqueueGpuClean).mockResolvedValue({+ jobId: '33333333-3333-4333-8333-333333333333', position: 1, status: 'queued',+ modelId: 'flux2-klein-4b', strength: 0.25, width: 4, height: 4, scaled: false,+ });+ const maskRaw = Buffer.alloc(4 * 4, 255);+ const maskPng = await sharp(maskRaw, { raw: { width: 4, height: 4, channels: 1 } }).png().toBuffer();+ const lenPrefix = Buffer.alloc(4);+ lenPrefix.writeUInt32BE(maskPng.length, 0);+ const envelope = Buffer.concat([lenPrefix, maskPng, pngFixture]);+ const res = await postImage('?diffusion=gpu&mask=1&feather=2', envelope);+ expect(res.status).toBe(202);+ const arg = vi.mocked(enqueueGpuClean).mock.calls[0][0];+ expect(Buffer.isBuffer(arg.originalBuffer)).toBe(true);+ expect(Buffer.isBuffer(arg.maskBuffer)).toBe(true);+ expect(arg.feather).toBe(2);});it('treats an unknown diffusion value as off (no diffusion step)', async () => {@@ -310,3 +397,59 @@ describe('POST /api/image-clean (raw transport)', () => {expect(report.height).toBe(4);});});++describe('GPU clean result-fetch + save-to-gallery (issue #2264)', () => {+ const JOB = '44444444-4444-4444-8444-444444444444';+ const getResult = (jobId) => request(buildApp()).get(`/api/image-clean/result/${jobId}`);+ const postSave = (jobId) => request(buildApp()).post(`/api/image-clean/result/${jobId}/save`);++ it('returns the finished render bytes as image/png with a report header', async () => {+ const png = await sharp({ create: { width: 8, height: 8, channels: 3, background: { r: 10, g: 20, b: 30 } } }).png().toBuffer();+ vi.mocked(getGpuCleanStatus).mockReturnValue({ status: 'completed', error: null });+ vi.mocked(readGpuCleanResult).mockResolvedValue({ data: png, width: 8, height: 8, composited: false });+ const res = await getResult(JOB);+ expect(res.status).toBe(200);+ expect(res.headers['content-type']).toBe('image/png');+ const report = JSON.parse(res.headers['x-clean-report']);+ expect(report.mode).toBe('gpu');+ expect(report.width).toBe(8);+ });++ it('409s (keep polling) while the job is still running', async () => {+ vi.mocked(getGpuCleanStatus).mockReturnValue({ status: 'running', error: null });+ vi.mocked(readGpuCleanResult).mockResolvedValue(null);+ const res = await getResult(JOB);+ expect(res.status).toBe(409);+ expect(res.body.code).toBe('RESULT_NOT_READY');+ });++ it('404s once the render is gone (past temp GC / unknown id)', async () => {+ vi.mocked(getGpuCleanStatus).mockReturnValue({ status: 'unknown', error: null });+ vi.mocked(readGpuCleanResult).mockResolvedValue(null);+ const res = await getResult(JOB);+ expect(res.status).toBe(404);+ expect(res.body.code).toBe('NOT_FOUND');+ });++ it('409s with the failure reason when the job failed', async () => {+ vi.mocked(getGpuCleanStatus).mockReturnValue({ status: 'failed', error: 'runner OOM' });+ const res = await getResult(JOB);+ expect(res.status).toBe(409);+ expect(res.body.code).toBe('JOB_FAILED');+ });++ it('rejects a non-UUID job id with VALIDATION_ERROR', async () => {+ const res = await getResult('not-a-uuid');+ expect(res.status).toBe(400);+ expect(res.body.code).toBe('VALIDATION_ERROR');+ expect(vi.mocked(readGpuCleanResult)).not.toHaveBeenCalled();+ });++ it('saves a finished result to the gallery on the explicit save action (201)', async () => {+ vi.mocked(saveGpuCleanToGallery).mockResolvedValue({ filename: 'upload-abcd1234.png', path: '/data/images/upload-abcd1234.png' });+ const res = await postSave(JOB);+ expect(res.status).toBe(201);+ expect(res.body.filename).toBe('upload-abcd1234.png');+ expect(vi.mocked(saveGpuCleanToGallery)).toHaveBeenCalledWith(JOB);+ });+});diff --git a/server/services/imageCleanTmpGc.js b/server/services/imageCleanTmpGc.jsnew file mode 100644index 0000000000..a84c91b87b--- /dev/null+++ b/server/services/imageCleanTmpGc.js@@ -0,0 +1,93 @@+/**+ * Image Cleaner temp GC (issue #2264).+ *+ * The GPU FLUX clean round-trip stages ephemeral working files under+ * `PATHS.imageCleanTmp` — the sync-cleaned init (`init-<uuid>.png`), the render+ * (`<jobId>.png`), the preserve-region inputs (`<jobId>-original.png` /+ * `<jobId>-mask.png`), and a small `<jobId>-clean.json`. Unlike the gallery,+ * nothing here is ever referenced long-term: the client fetches the result once+ * (and optionally saves it to the gallery, which re-encodes a fresh copy). So a+ * plain mtime age-gate is enough — no reference tracking like imageRefsGc.+ *+ * The whole dir is fair game; the grace window just spares files from an+ * in-flight render or a result the user hasn't fetched yet. Kept short (an hour)+ * because a GPU clean completes and is fetched in seconds-to-minutes.+ */++import { readdir, stat, unlink } from 'node:fs/promises';+import { join } from 'node:path';+import { PATHS } from '../lib/fileUtils.js';++// Grace window before a temp clean file is eligible for deletion, measured+// against mtime. An hour is generous next to the seconds-to-minutes a GPU clean+// takes, while sparing an in-flight render or an un-fetched result.+export const CLEAN_TMP_MAX_AGE_MS = 60 * 60 * 1000; // 1 hour++// How often the sweep runs once started. Cheap files, low churn — hourly keeps+// the dir bounded without busywork.+const SWEEP_INTERVAL_MS = 60 * 60 * 1000; // 1 hour++let sweepTimer = null;+let initialSweepTimer = null;++/**+ * Delete every file under `tmpDir` older than `maxAgeMs`. Returns+ * `{ deleted, keptYoung }`. A missing dir yields all-zero. Pure over its args so+ * tests can point it at a temp dir and pin `now`.+ */+export async function sweepImageCleanTmp({+ now = Date.now(),+ maxAgeMs = CLEAN_TMP_MAX_AGE_MS,+ tmpDir = PATHS.imageCleanTmp,+} = {}) {+ const entries = await readdir(tmpDir, { withFileTypes: true }).catch(() => []);+ const files = entries.filter((e) => e.isFile()).map((e) => e.name);+ if (files.length === 0) return { deleted: 0, keptYoung: 0 };++ let deleted = 0;+ let keptYoung = 0;+ for (const name of files) {+ const info = await stat(join(tmpDir, name)).catch(() => null);+ if (!info) continue; // vanished under us — nothing to do+ if (now - info.mtimeMs < maxAgeMs) {+ keptYoung += 1;+ continue;+ }+ const removed = await unlink(join(tmpDir, name)).then(() => true).catch(() => false);+ if (removed) deleted += 1;+ }+ return { deleted, keptYoung };+}++/**+ * Start the periodic sweep. Fires once ~5 min after boot (off the startup hot+ * path) then hourly. Idempotent — a second call is a no-op.+ */+export function startImageCleanTmpGc() {+ if (sweepTimer) return;++ const runSweep = () => {+ sweepImageCleanTmp()+ .then(({ deleted }) => {+ if (deleted > 0) console.log(`🧹 Image-clean temp GC: removed ${deleted} stale file(s)`);+ })+ .catch((err) => console.error(`❌ Image-clean temp GC sweep failed: ${err.message}`));+ };++ initialSweepTimer = setTimeout(() => { initialSweepTimer = null; runSweep(); }, 5 * 60 * 1000);+ initialSweepTimer.unref?.();+ sweepTimer = setInterval(runSweep, SWEEP_INTERVAL_MS);+ sweepTimer.unref?.();+}++/** Stop the periodic sweep (used by tests / graceful shutdown). */+export function stopImageCleanTmpGc() {+ if (initialSweepTimer) {+ clearTimeout(initialSweepTimer);+ initialSweepTimer = null;+ }+ if (sweepTimer) {+ clearInterval(sweepTimer);+ sweepTimer = null;+ }+}diff --git a/server/services/imageCleanTmpGc.test.js b/server/services/imageCleanTmpGc.test.jsnew file mode 100644index 0000000000..d74ad7d845--- /dev/null+++ b/server/services/imageCleanTmpGc.test.js@@ -0,0 +1,63 @@+import { describe, it, expect, beforeEach, afterAll } from 'vitest';+import { mkdtempSync, rmSync, writeFileSync, existsSync, utimesSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import { sweepImageCleanTmp, CLEAN_TMP_MAX_AGE_MS } from './imageCleanTmpGc.js';++let dir;++beforeEach(() => {+ dir = mkdtempSync(join(tmpdir(), 'portos-cleantmp-gc-test-'));+});++afterAll(() => {+ // beforeEach makes a fresh dir per test; clean the last one.+ if (dir) rmSync(dir, { recursive: true, force: true });+});++// Write a file and backdate its mtime by `ageMs` so the age-gate sees it as old.+const writeAged = (name, ageMs) => {+ const p = join(dir, name);+ writeFileSync(p, 'x');+ if (ageMs > 0) {+ const when = new Date(Date.now() - ageMs);+ utimesSync(p, when, when);+ }+ return p;+};++describe('sweepImageCleanTmp', () => {+ it('all-zero on a missing dir', async () => {+ const res = await sweepImageCleanTmp({ tmpDir: join(dir, 'nope') });+ expect(res).toEqual({ deleted: 0, keptYoung: 0 });+ });++ it('deletes files older than the grace window', async () => {+ const old = writeAged('11111111-1111-4111-8111-111111111111.png', CLEAN_TMP_MAX_AGE_MS + 60_000);+ const res = await sweepImageCleanTmp({ tmpDir: dir });+ expect(res.deleted).toBe(1);+ expect(existsSync(old)).toBe(false);+ });++ it('spares files younger than the grace window (an in-flight render)', async () => {+ const fresh = writeAged('init-abc.png', 0);+ const res = await sweepImageCleanTmp({ tmpDir: dir });+ expect(res.deleted).toBe(0);+ expect(res.keptYoung).toBe(1);+ expect(existsSync(fresh)).toBe(true);+ });++ it('sweeps every kind of temp working file (init/render/mask/original/json)', async () => {+ const age = CLEAN_TMP_MAX_AGE_MS + 60_000;+ const names = [+ 'init-xyz.png',+ '22222222-2222-4222-8222-222222222222.png',+ '22222222-2222-4222-8222-222222222222-mask.png',+ '22222222-2222-4222-8222-222222222222-original.png',+ '22222222-2222-4222-8222-222222222222-clean.json',+ ];+ names.forEach((n) => writeAged(n, age));+ const res = await sweepImageCleanTmp({ tmpDir: dir });+ expect(res.deleted).toBe(names.length);+ });+});diff --git a/server/services/imageGen/cleanGpu.js b/server/services/imageGen/cleanGpu.jsnew file mode 100644index 0000000000..11e51fdd52--- /dev/null+++ b/server/services/imageGen/cleanGpu.js@@ -0,0 +1,193 @@+/**+ * Image Cleaner — GPU FLUX round-trip orchestration (issue #2264).+ *+ * The synchronous Image Cleaner route (`server/routes/imageClean.js`) runs the+ * metadata / median-sharpen / CPU-light passes inline and returns the bytes.+ * The GPU FLUX img2img round-trip can't run inline: it's GPU-serialized through+ * `mediaJobQueue` (two concurrent FLUX renders OOM the box). So for+ * `?diffusion=gpu` the route hands the (already sync-cleaned) bytes to this+ * service, which:+ *+ * 1. Stages the init bytes to `PATHS.imageCleanTmp` (a non-gallery temp dir).+ * 2. Resolves the local FLUX backend + assembles the img2img params, reusing+ * `resolveRegenBackend` / `buildRegenParams` / `clampRegenDimensions` from+ * `regen.js` — the SAME seam the lightbox `/regenerate` flow uses.+ * 3. Enqueues a `kind: 'image'` job with a NON-GALLERY `outputTarget`+ * (`generateImage` writes the render to the temp dir with NO sidecar, so+ * the gallery is never polluted by default).+ * 4. Returns a `jobId` the client tracks via the existing media-job progress+ * channel (`useMediaJobProgress`), then fetches the finished bytes.+ *+ * When an ignore-zone mask rode along, the original (pre-diffusion, oriented)+ * bytes + the mask are staged next to the render so the result-fetch can+ * composite the ORIGINAL pixels back into the masked regions (feathered) after+ * the GPU redraws the frame — the same preserve-region behavior the CPU light+ * pass applies inline.+ *+ * The finished bytes are consumed by an explicit result-fetch; the default is+ * NOT to keep them. An optional save-to-gallery action promotes the result to a+ * first-class gallery citizen (reusing `saveUploadedGalleryImage`).+ */++import { randomUUID } from 'node:crypto';+import { join } from 'node:path';+import sharp from 'sharp';+import { PATHS, ensureDir, atomicWrite, tryReadFile, resolveImageCleanTmp } from '../../lib/fileUtils.js';+import { ServerError } from '../../lib/errorHandler.js';+import { compositeIgnoreZone, IGNORE_ZONE_FEATHER_DEFAULT } from '../../lib/imageClean.js';+import { resolveRegenBackend, buildRegenParams, resolveRegenStrengthDefault } from './regen.js';+import { enqueueJob, getJob } from '../mediaJobQueue/index.js';++// Small JSON sidecar written next to the temp render so the result-fetch knows+// whether an ignore-zone composite is pending (and the feather sigma). Kept out+// of the gallery sidecar shape on purpose — this is ephemeral working state,+// not a gallery record.+const cleanMetaPath = (jobId) => join(PATHS.imageCleanTmp, `${jobId}-clean.json`);++/**+ * Enqueue a GPU FLUX clean round-trip. `initBuffer` is the already-sync-cleaned+ * image bytes; `originalBuffer`/`maskBuffer` (optional) drive the post-render+ * ignore-zone composite. Returns `{ jobId, position, status, modelId, strength,+ * width, height, scaled }` on success. Throws a 400 ServerError with an+ * actionable message when no local FLUX runner is available (the hardware gate).+ */+export async function enqueueGpuClean({+ initBuffer,+ sourceDims = null,+ strength = null,+ maxMegapixels,+ originalBuffer = null,+ maskBuffer = null,+ feather = IGNORE_ZONE_FEATHER_DEFAULT,+}) {+ if (!Buffer.isBuffer(initBuffer) || initBuffer.length === 0) {+ throw new ServerError('No image bytes to render', { status: 400, code: 'VALIDATION_ERROR' });+ }++ // Hardware gate — no source model to bias the pick (an arbitrary upload has+ // no lineage), so resolveRegenBackend chooses the best installed FLUX runner.+ const backend = await resolveRegenBackend({});+ if (!backend.available) {+ throw new ServerError(backend.reason, { status: 400, code: 'REGEN_BACKEND_UNAVAILABLE' });+ }++ await ensureDir(PATHS.imageCleanTmp);+ // Stage the init bytes under an `init-<uuid>` name so the shared image-input+ // resolver accepts them and the tmp GC can sweep them. The render itself+ // lands at `<jobId>.png` (jobId is assigned by enqueueJob below).+ const initName = `init-${randomUUID()}.png`;+ const initAbsPath = join(PATHS.imageCleanTmp, initName);+ // Normalize to PNG so the runner's init-image decode is stable regardless of+ // the source format, then write the raw bytes (atomicWrite is JSON-only).+ const initPng = await sharp(initBuffer).png().toBuffer();+ const { writeFile } = await import('node:fs/promises');+ await writeFile(initAbsPath, initPng);++ // Conservative default for an arbitrary upload (no SynthID-bearing lineage+ // to key on) — mirrors the lightbox's resolveRegenStrengthDefault({}).+ const useStrength = typeof strength === 'number' && Number.isFinite(strength)+ ? strength+ : resolveRegenStrengthDefault({});++ const params = buildRegenParams({+ // No gallery filename — this render has no gallery lineage. `regenOf` stays+ // absent so `generateImage` writes no `cleanedFrom`/variant lineage.+ filename: initName,+ sourceAbsPath: initAbsPath,+ sourceDims,+ model: backend.model,+ pythonPath: backend.pythonPath,+ strength: useStrength,+ initImageAbsPath: initAbsPath,+ ...(typeof maxMegapixels === 'number' && maxMegapixels > 0 ? { maxMegapixels } : {}),+ });+ // Strip the regen lineage stamp — a clean render is NOT a gallery variant of+ // anything, and there's no source gallery filename to anchor a group at.+ delete params.regenOf;+ // Render to the temp dir with no sidecar so the gallery stays clean.+ params.outputTarget = { dir: PATHS.imageCleanTmp, skipSidecar: true };++ const queued = enqueueJob({ kind: 'image', params });+ const jobId = queued.jobId;++ // Stage the preserve-region inputs (only when a mask rode along) so the+ // result-fetch can composite the ORIGINAL pixels back over the diffused+ // render. Named by the (now-known) jobId. Best-effort — a failed stage just+ // means the composite is skipped, never a failed enqueue.+ let hasMask = false;+ if (Buffer.isBuffer(originalBuffer) && Buffer.isBuffer(maskBuffer)) {+ await writeFile(join(PATHS.imageCleanTmp, `${jobId}-original.png`), originalBuffer).catch(() => {});+ await writeFile(join(PATHS.imageCleanTmp, `${jobId}-mask.png`), maskBuffer).catch(() => {});+ hasMask = true;+ }+ await atomicWrite(cleanMetaPath(jobId), { hasMask, feather, initName }).catch(() => {});++ console.log(`🧪 GPU clean enqueued via ${backend.model.id} (strength=${useStrength}${hasMask ? ', ignore-zone mask' : ''}) → job ${jobId.slice(0, 8)}`);+ return {+ jobId,+ position: queued.position,+ status: queued.status,+ modelId: backend.model.id,+ strength: useStrength,+ width: params.width,+ height: params.height,+ scaled: !!params.upscaleTo,+ };+}++// Resolve the finished temp render for a clean job. Returns `null` when the job+// hasn't completed (or produced no output) yet — the caller maps that to a 409+// so the client keeps polling. On success returns `{ data, width, height }`+// with any pending ignore-zone composite applied.+export async function readGpuCleanResult(jobId) {+ const resultPath = resolveImageCleanTmp(`${jobId}.png`);+ if (!resultPath) return null;+ const rendered = await tryReadFile(resultPath, null);+ if (!rendered || rendered.length === 0) return null;++ // Apply the deferred ignore-zone composite, if one was staged. The mask+ // restores the ORIGINAL pixels into the painted regions over the diffused+ // frame — the GPU redrew the whole image, garbling any text/faces the user+ // wanted preserved. Missing/failed composite falls back to the raw render.+ const meta = await tryReadFile(cleanMetaPath(jobId), null);+ let cleanMeta = null;+ if (meta) { try { cleanMeta = JSON.parse(meta); } catch { cleanMeta = null; } }+ if (cleanMeta?.hasMask) {+ const [original, mask] = await Promise.all([+ tryReadFile(join(PATHS.imageCleanTmp, `${jobId}-original.png`), null),+ tryReadFile(join(PATHS.imageCleanTmp, `${jobId}-mask.png`), null),+ ]);+ if (Buffer.isBuffer(original) && Buffer.isBuffer(mask)) {+ const composited = await compositeIgnoreZone(rendered, original, mask, {+ feather: typeof cleanMeta.feather === 'number' ? cleanMeta.feather : IGNORE_ZONE_FEATHER_DEFAULT,+ });+ if (composited) return { data: composited.data, width: composited.width, height: composited.height, composited: true };+ }+ }++ const dims = await sharp(rendered).metadata().catch(() => ({}));+ return { data: rendered, width: dims.width || null, height: dims.height || null, composited: false };+}++// Whether a clean job is finished (its render is on disk). Distinguishes+// "not done yet" (keep polling) from "done" for the result-fetch route.+export function getGpuCleanStatus(jobId) {+ const job = getJob(jobId);+ if (!job) return { status: 'unknown' };+ return { status: job.status, error: job.error || null };+}++// Save a finished clean result to the gallery (the explicit opt-in — the+// default is NOT to keep it). Reuses `saveUploadedGalleryImage` so the saved+// file is a first-class gallery citizen (lists/deletes like any other). Returns+// the new gallery `{ filename, path }`.+export async function saveGpuCleanToGallery(jobId) {+ const result = await readGpuCleanResult(jobId);+ if (!result) {+ throw new ServerError('Clean result not ready or not found', { status: 409, code: 'RESULT_NOT_READY' });+ }+ const { saveUploadedGalleryImage } = await import('./local.js');+ const saved = await saveUploadedGalleryImage(result.data.toString('base64'));+ console.log(`💾 Saved GPU clean result to gallery: ${saved.filename} (from job ${jobId.slice(0, 8)})`);+ return saved;+}diff --git a/server/services/imageGen/cleanGpu.test.js b/server/services/imageGen/cleanGpu.test.jsnew file mode 100644index 0000000000..9e74e33310--- /dev/null+++ b/server/services/imageGen/cleanGpu.test.js@@ -0,0 +1,173 @@+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';+import { mkdirSync, rmSync, existsSync, readdirSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import sharp from 'sharp';++// Point PATHS.imageCleanTmp at a throwaway dir so the seam's temp staging never+// touches the real data tree, and mock the queue + backend so nothing spawns a+// FLUX runner or enqueues a live job on the shared install. `vi.hoisted` gives+// the hoisted vi.mock factory a stable path; the seam's `ensureDir` creates it.+const { TMP } = vi.hoisted(() => ({+ TMP: `/tmp/portos-cleangpu-test-${Date.now()}-${Math.random().toString(36).slice(2)}`,+}));++vi.mock('../../lib/fileUtils.js', async (importOriginal) => {+ const actual = await importOriginal();+ return {+ ...actual,+ PATHS: { ...actual.PATHS, imageCleanTmp: TMP },+ // Re-anchor the resolver at the test dir so result-fetch resolves there.+ resolveImageCleanTmp: (name) => {+ if (typeof name !== 'string' || !name || name.includes('/') || name.includes('..')) return null;+ return join(TMP, name);+ },+ };+});++const enqueueJob = vi.fn();+const getJob = vi.fn();+vi.mock('../mediaJobQueue/index.js', () => ({+ enqueueJob: (...a) => enqueueJob(...a),+ getJob: (...a) => getJob(...a),+}));++const resolveRegenBackend = vi.fn();+vi.mock('./regen.js', async (importOriginal) => {+ const actual = await importOriginal();+ return {+ ...actual,+ resolveRegenBackend: (...a) => resolveRegenBackend(...a),+ };+});++import { enqueueGpuClean, readGpuCleanResult, getGpuCleanStatus } from './cleanGpu.js';++const AVAILABLE = { available: true, model: { id: 'flux2-klein-4b' }, pythonPath: null };++beforeEach(() => {+ enqueueJob.mockReset();+ getJob.mockReset();+ resolveRegenBackend.mockReset();+ mkdirSync(TMP, { recursive: true });+});++afterAll(() => rmSync(TMP, { recursive: true, force: true }));++const makePng = (w = 8, h = 8) => sharp({ create: { width: w, height: h, channels: 3, background: { r: 5, g: 10, b: 15 } } }).png().toBuffer();++describe('enqueueGpuClean', () => {+ it('stages the init bytes to the temp dir and enqueues a non-gallery job', async () => {+ resolveRegenBackend.mockResolvedValue(AVAILABLE);+ enqueueJob.mockReturnValue({ jobId: 'aaaaaaaa-0000-4000-8000-000000000000', position: 1, status: 'queued' });+ const init = await makePng(8, 8);++ const out = await enqueueGpuClean({ initBuffer: init, sourceDims: { width: 8, height: 8 } });++ expect(out.jobId).toBe('aaaaaaaa-0000-4000-8000-000000000000');+ expect(out.modelId).toBe('flux2-klein-4b');+ // A job was enqueued with a NON-GALLERY output target + skipSidecar.+ expect(enqueueJob).toHaveBeenCalledTimes(1);+ const { kind, params } = enqueueJob.mock.calls[0][0];+ expect(kind).toBe('image');+ expect(params.outputTarget.dir).toBe(TMP);+ expect(params.outputTarget.skipSidecar).toBe(true);+ // No regen lineage — a clean render is not a gallery variant of anything.+ expect(params.regenOf).toBeUndefined();+ // The init image is staged on disk and pointed at by the params.+ expect(params.initImagePath.startsWith(TMP)).toBe(true);+ expect(existsSync(params.initImagePath)).toBe(true);+ // A clean-meta sidecar records that no mask was staged.+ const clean = readdirSync(TMP).find((f) => f.endsWith('-clean.json'));+ expect(clean).toBeTruthy();+ });++ it('honors an explicit strength + max-MP override', async () => {+ resolveRegenBackend.mockResolvedValue(AVAILABLE);+ enqueueJob.mockReturnValue({ jobId: 'bbbbbbbb-0000-4000-8000-000000000000', position: 1, status: 'queued' });+ const init = await makePng(2000, 2000);++ const out = await enqueueGpuClean({ initBuffer: init, sourceDims: { width: 2000, height: 2000 }, strength: 0.4, maxMegapixels: 1.0 });++ expect(out.strength).toBe(0.4);+ const { params } = enqueueJob.mock.calls[0][0];+ expect(params.initImageStrength).toBe(0.4);+ // A 1.0-MP budget on a 4-MP source clamps the render below source dims.+ expect(params.width * params.height).toBeLessThanOrEqual(1.05 * 1_000_000);+ // Clamped → upscale-back to source dims is stamped.+ expect(params.upscaleTo).toEqual({ width: 2000, height: 2000 });+ });++ it('stages the mask + original when an ignore-zone rides along', async () => {+ resolveRegenBackend.mockResolvedValue(AVAILABLE);+ enqueueJob.mockReturnValue({ jobId: 'cccccccc-0000-4000-8000-000000000000', position: 1, status: 'queued' });+ const init = await makePng(8, 8);+ const original = await makePng(8, 8);+ const mask = await sharp(Buffer.alloc(8 * 8, 255), { raw: { width: 8, height: 8, channels: 1 } }).png().toBuffer();++ await enqueueGpuClean({ initBuffer: init, sourceDims: { width: 8, height: 8 }, originalBuffer: original, maskBuffer: mask, feather: 4 });++ const files = readdirSync(TMP);+ expect(files.some((f) => f.endsWith('-original.png'))).toBe(true);+ expect(files.some((f) => f.endsWith('-mask.png'))).toBe(true);+ });++ it('throws a 400 when no local FLUX runner is available (hardware gate)', async () => {+ resolveRegenBackend.mockResolvedValue({ available: false, reason: 'No local FLUX runner is installed.' });+ const init = await makePng();+ await expect(enqueueGpuClean({ initBuffer: init })).rejects.toMatchObject({ status: 400, code: 'REGEN_BACKEND_UNAVAILABLE' });+ expect(enqueueJob).not.toHaveBeenCalled();+ });++ it('rejects an empty init buffer', async () => {+ await expect(enqueueGpuClean({ initBuffer: Buffer.alloc(0) })).rejects.toMatchObject({ status: 400 });+ });+});++describe('readGpuCleanResult', () => {+ it('returns the finished render bytes when present', async () => {+ const jobId = 'dddddddd-0000-4000-8000-000000000000';+ const render = await makePng(12, 12);+ writeFileSync(join(TMP, `${jobId}.png`), render);+ const out = await readGpuCleanResult(jobId);+ expect(out).toBeTruthy();+ expect(out.width).toBe(12);+ expect(out.composited).toBe(false);+ });++ it('returns null when the render is not on disk yet', async () => {+ const out = await readGpuCleanResult('eeeeeeee-0000-4000-8000-000000000000');+ expect(out).toBeNull();+ });++ it('composites the ignore-zone mask back over the render when one was staged', async () => {+ const jobId = 'ffffffff-0000-4000-8000-000000000000';+ // Render = solid black; original = solid white; full-white mask → the whole+ // frame is restored to the original (white) after the composite.+ const render = await sharp({ create: { width: 8, height: 8, channels: 3, background: { r: 0, g: 0, b: 0 } } }).png().toBuffer();+ const original = await sharp({ create: { width: 8, height: 8, channels: 3, background: { r: 255, g: 255, b: 255 } } }).png().toBuffer();+ const mask = await sharp(Buffer.alloc(8 * 8, 255), { raw: { width: 8, height: 8, channels: 1 } }).png().toBuffer();+ writeFileSync(join(TMP, `${jobId}.png`), render);+ writeFileSync(join(TMP, `${jobId}-original.png`), original);+ writeFileSync(join(TMP, `${jobId}-mask.png`), mask);+ writeFileSync(join(TMP, `${jobId}-clean.json`), JSON.stringify({ hasMask: true, feather: 0 }));++ const out = await readGpuCleanResult(jobId);+ expect(out.composited).toBe(true);+ // Center pixel should now be white (the original), not the rendered black.+ const { data } = await sharp(out.data).raw().toBuffer({ resolveWithObject: true });+ const mid = (4 * 8 + 4) * (data.length / (8 * 8));+ expect(data[Math.floor(mid)]).toBeGreaterThan(200);+ });+});++describe('getGpuCleanStatus', () => {+ it('reports unknown for a missing job', () => {+ getJob.mockReturnValue(null);+ expect(getGpuCleanStatus('x')).toEqual({ status: 'unknown' });+ });++ it('surfaces the queue job status + error', () => {+ getJob.mockReturnValue({ status: 'failed', error: 'boom' });+ expect(getGpuCleanStatus('x')).toEqual({ status: 'failed', error: 'boom' });+ });+});diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.jsindex 03526acef0..6bc7fb11bf 100644--- a/server/services/imageGen/local.js+++ b/server/services/imageGen/local.js@@ -433,7 +433,29 @@ 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, regenOf = null, upscaleTo = null }) {+/**+ * Resolve where a render's PNG + sidecar go (issue #2264). Pure so the+ * gallery-vs-temp branch is unit-testable without spawning a render.+ *+ * - No `outputTarget` (the default, every existing caller) → the gallery dir+ * with a sidecar written — the lightbox/regenerate/gen behavior, untouched.+ * - `outputTarget.dir` (the Image Cleaner's temp render) → that dir, and+ * `skipSidecar` (defaulting true for a non-gallery dir) suppresses the+ * `<jobId>.metadata.json` write + the gallery `completed` index/federate hooks.+ *+ * A gallery-dir target always keeps its sidecar even if `skipSidecar` was+ * passed — a gallery citizen without a sidecar would be an un-remixable orphan.+ */+export function resolveOutputPlacement(outputTarget) {+ const target = outputTarget && typeof outputTarget === 'object' ? outputTarget : null;+ const outputDir = target?.dir && typeof target.dir === 'string' ? target.dir : PATHS.images;+ const isGallery = outputDir === PATHS.images;+ // Non-gallery renders default to no sidecar; a gallery render always writes one.+ const skipSidecar = isGallery ? false : (target?.skipSidecar !== false);+ return { outputDir, skipSidecar, isGallery };+}++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, upscaleTo = null, outputTarget = null }) {// Empty prompt is allowed: img2img / edit / unconditional renders are driven// by the init image (or run unconditionally), so text isn't required. The// mflux/diffusers runners accept an empty `--prompt` — the regen pass (#912)@@ -462,12 +484,22 @@ export async function generateImage({ pythonPath, prompt = '', negativePrompt =// 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);+ // Non-gallery render target (issue #2264): the Image Cleaner's GPU FLUX+ // round-trip renders to a temp dir with NO sidecar, so a clean pass never+ // pollutes the gallery by default. See `resolveOutputPlacement` for the exact+ // branch logic (unit-tested in local.test.js).+ const { outputDir, skipSidecar } = resolveOutputPlacement(outputTarget);++ await ensureDir(outputDir);await ensureDir(PATHS.loras);const jobId = providedJobId || randomUUID();const filename = `${jobId}.png`;- const outputPath = join(PATHS.images, filename);+ const outputPath = join(outputDir, filename);+ // The public path a gallery render mounts at (`/data/images/<f>`). A+ // non-gallery render has no static mount, so the queue reads the finished+ // bytes off `outputPath` directly (surfaced as `outputPath` in the result).+ const publicPath = outputDir === PATHS.images ? `/data/images/${filename}` : null;const {meta,actualSeed,@@ -804,19 +836,37 @@ export async function generateImage({ pythonPath, prompt = '', negativePrompt =// Sidecar: persist a metadata record next to the PNG so the gallery// and Remix flow can recover prompt/seed/steps even if mflux's own// --metadata sidecar lives at a slightly different filename shape.- const sidecar = join(PATHS.images, `${jobId}.metadata.json`);- await atomicWrite(sidecar, meta).catch(() => {});- // Cleaners run BEFORE the SSE complete + completed events so subscribers- // see the cleaned bytes. Local FLUX renders never carry C2PA chunks so- // cleanC2PA is a no-op on local — denoise is the only mode that does- // anything here.- await autoCleanGeneratedImage({ cleanC2PA, denoise, pngPath: outputPath, sidecarPath: sidecar, mode: IMAGE_GEN_MODE.LOCAL });- console.log(`✅ Image generated [${jobId.slice(0, 8)}]: ${filename}`);- const result = { filename, seed: actualSeed, path: `/data/images/${filename}` };+ // A non-gallery target (issue #2264, the Image Cleaner's temp render)+ // skips this write entirely — the temp bytes are consumed by an explicit+ // result-fetch, so there's no gallery record to hydrate.+ const sidecar = join(outputDir, `${jobId}.metadata.json`);+ if (!skipSidecar) {+ await atomicWrite(sidecar, meta).catch(() => {});+ // Cleaners run BEFORE the SSE complete + completed events so subscribers+ // see the cleaned bytes. Local FLUX renders never carry C2PA chunks so+ // cleanC2PA is a no-op on local — denoise is the only mode that does+ // anything here.+ await autoCleanGeneratedImage({ cleanC2PA, denoise, pngPath: outputPath, sidecarPath: sidecar, mode: IMAGE_GEN_MODE.LOCAL });+ }+ console.log(`✅ Image generated [${jobId.slice(0, 8)}]: ${filename}${skipSidecar ? ' (temp, no sidecar)' : ''}`);+ // A non-gallery render has no `/data/images` mount — carry the absolute+ // `outputPath` so the queue/route can read the finished bytes; `path`+ // stays null so nothing treats it as a gallery URL.+ const result = { filename, seed: actualSeed, path: publicPath, outputPath };broadcastSse(job, { type: 'complete', result });// Include `seed` so /sdapi/v1/txt2img can surface the actual seed used- // (mflux generates a random one if the client didn't pass one).- imageGenEvents.emit('completed', { generationId: jobId, path: `/data/images/${filename}`, filename, seed: actualSeed });+ // (mflux generates a random one if the client didn't pass one). Emit the+ // gallery `completed` (which drives the media-asset index + peer-sync+ // hooks) ONLY for a gallery target — a temp render must not be indexed or+ // federated. The queue's own `completed` handler still fires off the+ // return value below, so the job settles either way.+ if (!skipSidecar) {+ imageGenEvents.emit('completed', { generationId: jobId, path: publicPath, filename, seed: actualSeed });+ } else {+ // `temp: true` tells the media-asset-index + peer-sync hooks to ignore+ // this render — there's no gallery file or sidecar to index/federate.+ imageGenEvents.emit('completed', { generationId: jobId, path: null, filename, seed: actualSeed, outputPath, temp: true });+ }}closeJobAfterDelay(jobs, jobId);});diff --git a/server/services/imageGen/local.test.js b/server/services/imageGen/local.test.jsindex 5074de7224..45ec80d063 100644--- a/server/services/imageGen/local.test.js+++ b/server/services/imageGen/local.test.js@@ -22,13 +22,16 @@ let tmpRegistryDir;let priorRegistryEnv;let buildArgs;let buildSidecarMeta;+let resolveOutputPlacement;+let PATHS;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, buildSidecarMeta } = await import('./local.js'));+ ({ buildArgs, buildSidecarMeta, resolveOutputPlacement } = await import('./local.js'));+ ({ PATHS } = await import('../../lib/fileUtils.js'));});afterAll(() => {@@ -769,3 +772,38 @@ describe('imageGen local.buildSidecarMeta', () => {expect(meta.seed).toBeLessThan(2147483647);});});++describe('imageGen local.resolveOutputPlacement (issue #2264 non-gallery render seam)', () => {+ it('defaults to the gallery dir WITH a sidecar when no outputTarget is given', () => {+ // The lightbox/regenerate/generate path — must be untouched.+ const p = resolveOutputPlacement(null);+ expect(p.outputDir).toBe(PATHS.images);+ expect(p.isGallery).toBe(true);+ expect(p.skipSidecar).toBe(false);+ });++ it('renders to a temp dir with NO sidecar when a non-gallery target is given', () => {+ const p = resolveOutputPlacement({ dir: PATHS.imageCleanTmp, skipSidecar: true });+ expect(p.outputDir).toBe(PATHS.imageCleanTmp);+ expect(p.isGallery).toBe(false);+ expect(p.skipSidecar).toBe(true);+ });++ it('defaults a non-gallery target to skipSidecar even when the flag is omitted', () => {+ const p = resolveOutputPlacement({ dir: PATHS.imageCleanTmp });+ expect(p.skipSidecar).toBe(true);+ });++ it('always writes a sidecar for a gallery-dir target, even if skipSidecar was passed', () => {+ // A gallery citizen without a sidecar would be an un-remixable orphan.+ const p = resolveOutputPlacement({ dir: PATHS.images, skipSidecar: true });+ expect(p.outputDir).toBe(PATHS.images);+ expect(p.skipSidecar).toBe(false);+ });++ it('ignores a malformed outputTarget (non-object / missing dir) → gallery default', () => {+ expect(resolveOutputPlacement('nope').outputDir).toBe(PATHS.images);+ expect(resolveOutputPlacement({}).outputDir).toBe(PATHS.images);+ expect(resolveOutputPlacement({ dir: 123 }).outputDir).toBe(PATHS.images);+ });+});diff --git a/server/services/imageGen/regen.js b/server/services/imageGen/regen.jsindex 32a766f50b..f6f54e64cb 100644--- a/server/services/imageGen/regen.js+++ b/server/services/imageGen/regen.js@@ -275,7 +275,7 @@ export async function readImageDimensions(absPath) {// clamping changes the dims, `upscaleTo` carries the source's exact dimensions// so `generateImage` resizes the result back up, delivering a watermark-free// copy at the original resolution.-export function buildRegenParams({ filename, sourceAbsPath, sourceMeta = {}, sourceDims = null, model, pythonPath, strength, steps, promptOverride, initImageAbsPath, annotated = false }) {+export function buildRegenParams({ filename, sourceAbsPath, sourceMeta = {}, sourceDims = null, model, pythonPath, strength, steps, promptOverride, initImageAbsPath, annotated = false, maxMegapixels = DEFAULT_MAX_REGEN_MEGAPIXELS }) {// The img2img base pixels normally come from the clicked source, but an// annotation re-render (issue #2036 phase 2) points the init image at the// flattened source+strokes PNG while STILL reading dimensions/metadata/lineage@@ -305,7 +305,10 @@ export function buildRegenParams({ filename, sourceAbsPath, sourceMeta = {}, sou...(annotated ? { annotatedRegen: true } : {}),};if (src) {- const render = clampRegenDimensions(src.width, src.height);+ // `maxMegapixels` lets a caller (e.g. the Image Cleaner's optional+ // max-render-MP override) push or pull the render budget per-run; defaults+ // to the env-tunable DEFAULT_MAX_REGEN_MEGAPIXELS the lightbox uses.+ const render = clampRegenDimensions(src.width, src.height, maxMegapixels);params.width = render.width;params.height = render.height;// Clamped or /16-rounded → deliver the cleaned copy at the source's exactdiff --git a/server/services/mediaAssetIndex/index.js b/server/services/mediaAssetIndex/index.jsindex 66ea19e525..5a9030b071 100644--- a/server/services/mediaAssetIndex/index.js+++ b/server/services/mediaAssetIndex/index.js@@ -34,8 +34,12 @@ function isEscapeHatch() {// Index a single just-generated image. The 'completed' event carries the// filename; the full metadata is in the sidecar the generator just wrote.-async function onImageCompleted({ filename } = {}) {+async function onImageCompleted({ filename, temp } = {}) {if (typeof filename !== 'string' || !filename) return;+ // A non-gallery temp render (issue #2264, Image Cleaner GPU pass) has no+ // gallery file or sidecar — skip indexing it. It lives in imageCleanTmp and+ // is consumed by an explicit result-fetch, never listed in the gallery.+ if (temp) return;const { readImageSidecar } = await import('../imageGen/local.js');const { metadata } = await readImageSidecar(filename);// Mirror listGallery's entry shape (filename + path + spread sidecar). One