Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

refactor([imagegen-autoclean-bundle]): consolidate per-mode auto-clean state + dedup route/dispatcher resolution

[._.]/ Adam Eivyfddac1af7fc3
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index bf7c65ceb4..8d0ab63a59 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -4,6 +4,8 @@
- **[med-ai-dispatch-server-services-aidetect-js-242] `aiDetect.js` migrated to `runPromptThroughProvider` — TUI providers now work on Settings → Detect App.** `server/services/aiDetect.js` had a legacy `if (provider.type === 'cli') … else if ('api') … else 'Unknown provider type'` dispatch that rejected TUI providers outright and duplicated spawn/fetch logic the central handler already covers. The two inline functions (`executeCliDetection`, `executeApiDetection`) and the local `spawn`/`fetch` machinery are gone; detection now flows through `runPromptThroughProvider` from `server/lib/promptRunner.js` with `source: 'ai-app-detect'`, `cwd: dirPath` (so a spawned CLI/TUI runs against the analyzed repo, not PortOS's own cwd), and a 60s default timeout. `parseAiResponse` also moved to the shared `extractJson` helper from `server/lib/jsonExtract.js`, which strips CLI banner text and repairs trailing-comma JSON — relevant for TUI providers that emit banner output around the JSON payload. New `server/services/aiDetect.test.js` locks in the dispatch behavior (regression test ensures TUI no longer fails with "Unknown provider type") plus directory + provider-disabled error paths and the banner-stripping JSON case.
+- **[imagegen-autoclean-bundle] Image-gen auto-clean code-quality cleanup (4 items).** Bundled deferrals from the per-render auto-clean PR's `/simplify` pass. (1) [imagegen-autoclean-double-resolution] Extract `resolveAutoClean(body, settings, mode)` from `server/services/imageGen/index.js` and share it with `server/routes/imageGen.js` so the precedence resolution lives in one place — the route stamps the resolved value onto the request body and the dispatcher still resolves as a safety net for direct callers like `generateAvatar`. (2) [imagegentab-triplicate-autoclean-state-collapse] Collapse three `autoCleanCodex/Local/External` state vars in `client/src/components/settings/ImageGenTab.jsx` into one `autoCleanByMode` object with a curried `setAutoCleanFor(mode)` setter, dropping ~15 LOC of triplicated isDirty / saved-snapshot / patch / reload code. (3) [imagegen-savedautocleanbymode-derive] Drop the re-seed `useEffect` in `client/src/pages/ImageGen.jsx` and re-seed `autoClean` explicitly at the two mode-change points (`reloadBackends` + new `handleSelectMode`); `selectedModeRef` mirrors the latest value so `reloadBackends`'s `useCallback` stays stable. (4) [autoclean-sidecar-read-parallelize] Kick off the sidecar `tryReadFile` immediately after `cleanImageBuffer` returns so the disk read overlaps the PNG atomic-write window in `server/lib/imageClean.js#autoCleanGeneratedImage`. Added a `resolveAutoClean` shim to the imageGen-route test mock to mirror real precedence. All 5958 server + 163 client tests pass.
+
- **Retire `DONE.md` — the audit trail for completed work is now `git log` + `.changelog/`.** Slashdo v2.18.0 dropped DONE.md handling from `/do:replan` and friends; PortOS follows suit. Bumped the slashdo submodule to `v2.18.0`, deleted the repo-root `DONE.md`, and updated PLAN.md's preamble to point at the changelog and `git log` instead. `/claim` (`.claude/commands/claim.md`) now removes the picked item from PLAN.md outright and appends an entry to `.changelog/NEXT.md`. Server prompts retire DONE.md too: `feature-ideas` (PROMPT_VERSIONS v8→v9) and `plan-task` (v5→v6) no longer read DONE.md or write archive entries — they scan `.changelog/` + `git log` for completed-work signal and remove items from PLAN.md outright. Old v8/v5 bodies are captured in `PREVIOUS_DEFAULT_PROMPTS` so existing schedules on stock prompts auto-upgrade on next read. Also stripped DONE.md mentions from `documentation`, `do-replan`, `code-reviewer-review`, and `code-reviewer-implement` task prompts (unversioned — stock copies behave like custom and stick until the user resets, which is fine). `server/routes/apps.js#ALLOWED_DOCUMENTS` no longer lists DONE.md so the Documents tab won't surface it for managed apps. `server/services/cos.js#applyPlanIdMetadata` stopped reading DONE.md for slug-uniqueness (PLAN.md is now the only source). `server/lib/planIds.js` comments/tests updated. Client copy in `SlashDoPanel.jsx` (`/do:replan` button) + `TaskItem.jsx` reflect the new replan behavior. Existing repos with a DONE.md on disk are left untouched — slashdo simply no longer reads or writes them.
## Added
diff --git a/PLAN.md b/PLAN.md
index 84083c3a11..1d1d7dc18c 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -26,11 +26,7 @@ _Nothing currently parked — pick the next item from the Backlog._
- [ ] [cleanplateprompt-migrate-to-rich-canon-fragments] **Migrate `client/src/lib/cleanPlatePrompt.js#composeCleanPlatePrompt` to `richCanonDescriptorFragments('place', setting)`.** Clean-plate prompt builder (Cluster A — A4 setting reference renders) hand-rolls `description + Palette + recurringDetails` extraction at `cleanPlatePrompt.js:26-30` and is missing `era` / `weather` for the same reason `[pipeline-visual-stages-setting-field-injection]` was missing them — both are visual prompts that benefit from period/atmosphere cues. Tightly scoped sibling change (one client file + one test file). Deferred from that PR because the PLAN item targeted storyboard+comic-panel specifically; clean plates are setting-reference renders, adjacent but distinct.
- [ ] [extract-readcertmeta-helper] **Extract a shared `readCertMeta()` helper from `data/certs/meta.json` readers.** Three independent readers exist: `server/lib/peerSelfHost.js:13-18` (hostname only), `server/services/certRenewer.js:30-31` (mode + hostname), `server/lib/networkExposure.js:25-29` (mode + hostname + ips). Each does its own `statSync({ throwIfNoEntry: false }) + readFileSync + safeJSONParse`. Consolidate into `server/lib/certMeta.js` exporting `readCertMeta() → { mode, hostname, ips } | null`. Surfaced by /simplify during `[codex5-network-exposure-ui]`; deferred to keep that PR scoped. Note `peerSelfHost.js` is in a hot path — verify perf when consolidating.
- [ ] [hoist-loopback-host-helper-to-client-lib] **Hoist `isLoopbackHost` to `client/src/lib/loopbackHost.js`.** `server/lib/networkExposure.js` exports `isLoopbackHost`, but `client/src/components/NetworkExposureWidget.jsx:22-30` re-declares the same `LOOPBACK_HOSTS` Set and `describeMicAvailability()` helper inline (server export isn't reachable from browser). Move the client copy into `client/src/lib/loopbackHost.js` + add a barrel entry so future secure-context callers (voiceClient, etc.) can reuse it. When hoisting, broaden the IPv4 check from a single literal `127.0.0.1` to the full `127.0.0.0/8` loopback range to match browser secure-context behavior — easy `/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/` regex. Surfaced by /simplify and the codex review during `[codex5-network-exposure-ui]`.
-- [ ] [imagegen-autoclean-double-resolution] **Deduplicate `autoClean` resolution across route + dispatcher.** `server/routes/imageGen.js:204-206` and `server/services/imageGen/index.js:73-79` both compute the same `body.autoClean ?? settings.imageGen[mode].autoClean === true` precedence. The route's resolution is the one that matters in practice (it's the single path that feeds both the synchronous external dispatch AND the codex/local job queue, which bypasses the dispatcher); the dispatcher's resolution is only a safety net for direct callers like `generateAvatar`. Either extract `resolveAutoClean(body, settings, mode)` into one helper and call from both, or thread the resolved value through `params` and have the dispatcher trust it. Cosmetic dup; works correctly today. Settings is cache-backed so the double `getSettings()` call is sub-ms. Surfaced by /simplify after the per-render checkbox PR.
-- [ ] [imagegentab-triplicate-autoclean-state-collapse] **Collapse triplicate auto-clean state in `ImageGenTab.jsx`.** Three near-identical state vars (`autoCleanCodex/Local/External` at `client/src/components/settings/ImageGenTab.jsx:56-58`), three `saved` snapshot fields (`:73-77`), three isDirty comparisons (`:191-193`), three save-patch entries (`:204-209`), three reload assignments (`:149-169`). Collapse to one object: `const [autoCleanByMode, setAutoCleanByMode] = useState({ codex: false, local: false, external: false })` with checkbox `onChange={(v) => setAutoCleanByMode(p => ({ ...p, codex: v }))}`. Cuts ~15 LOC. Surfaced by /simplify after the per-render checkbox PR.
-- [ ] [imagegen-savedautocleanbymode-derive] **Derive `savedAutoCleanByMode` instead of holding it as state.** `client/src/pages/ImageGen.jsx:161,245-249,256-259` keeps a `savedAutoCleanByMode` map + a re-seed `useEffect` that fires on every `effectiveMode` change. Could be a single inline computation in `reloadBackends` + the chip `onChange`: `setAutoClean(s.imageGen?.[mode]?.autoClean === true)`. Kills one state var and one effect. Surfaced by /simplify after the per-render checkbox PR.
-- [ ] [image-gen-mode-enum-unify] **Unify image-gen mode enum across server + client.** Server has `IMAGE_GEN_MODES = ['external','local','codex']` (a Zod-validator alphabet) at `server/services/imageGen/index.js:21`; client has `IMAGE_GEN_MODE` constants at `client/src/utils/imageGenBackends.js:3`. Code reads strings (`'codex'`, `'local'`, `'external'`) inline at ~10 sites across `server/services/imageGen/{codex,local,external}.js`, `server/routes/imageGen.js`, and several client pages. Either export a typed enum object on the server (`IMAGE_GEN_MODE = Object.freeze({ CODEX: 'codex', ... })`) and use throughout, or accept the string-soup and drop the unused `IMAGE_GEN_MODES` array. Surfaced by /simplify after the per-render checkbox PR.
-- [ ] [autoclean-sidecar-read-parallelize] **Parallelize sidecar read with PNG write in `autoCleanGeneratedImage`.** `server/lib/imageClean.js#autoCleanGeneratedImage` awaits the cleaned-PNG `atomicWrite` before kicking off `tryReadFile(sidecarPath)`, even though the sidecar read has no data dependency on the PNG write. Start `tryReadFile(sidecarPath)` immediately after `cleanImageBuffer` returns and `await` both. Saves ~1ms per auto-clean. Marginal — only matters under sustained parallel codex/local generation. Surfaced by /simplify after the per-render checkbox PR.
+- [ ] [image-gen-mode-enum-unify] **Unify image-gen mode enum across server + client.** Server has `IMAGE_GEN_MODES = ['external','local','codex']` (a Zod-validator alphabet) at `server/services/imageGen/index.js:21`; client has `IMAGE_GEN_MODE` constants at `client/src/lib/imageGenBackends.js:3`. Code reads strings (`'codex'`, `'local'`, `'external'`) inline at ~10 sites across `server/services/imageGen/{codex,local,external}.js`, `server/routes/imageGen.js`, and several client pages. `IMAGE_GEN_MODES` is actively used (Zod enum + voice tool enum), so the choice is "export a typed enum object on the server (`IMAGE_GEN_MODE = Object.freeze({ CODEX: 'codex', ... })`) alongside `IMAGE_GEN_MODES` and adopt it at dispatch sites" — not "drop `IMAGE_GEN_MODES`". Surfaced by /simplify after the per-render checkbox PR.
### v2.1.0 pre-release review residue (deferred from main→release multi-agent review, 2026-05-16)
diff --git a/client/src/components/settings/ImageGenTab.jsx b/client/src/components/settings/ImageGenTab.jsx
index d579293025..832d2d930b 100644
--- a/client/src/components/settings/ImageGenTab.jsx
+++ b/client/src/components/settings/ImageGenTab.jsx
@@ -53,9 +53,8 @@ export function ImageGenTab() {
// (when present) and reduces visible AI-generation artifacts via a median
// pass + sharpen. Does NOT defeat SynthID — gpt-image embeds SynthID and our
// median+sharpen+re-encode falls inside Google's stated robustness envelope.
- const [autoCleanCodex, setAutoCleanCodex] = useState(false);
- const [autoCleanLocal, setAutoCleanLocal] = useState(false);
- const [autoCleanExternal, setAutoCleanExternal] = useState(false);
+ const [autoCleanByMode, setAutoCleanByMode] = useState({ external: false, local: false, codex: false });
+ const setAutoCleanFor = (m) => (v) => setAutoCleanByMode((p) => ({ ...p, [m]: v }));
// Raw string held while the user is typing in the parallel-limit input.
// Clamping is deferred to onBlur so multi-digit entry isn't blocked.
const [parallelLimitDraft, setParallelLimitDraft] = useState('1');
@@ -73,7 +72,7 @@ export function ImageGenTab() {
const [saved, setSaved] = useState({
mode: 'external', sdapiUrl: '', pythonPath: '', exposeA1111: false,
codexEnabled: false, codexPath: '', codexModel: '', codexParallelLimit: 1,
- autoCleanCodex: false, autoCleanLocal: false, autoCleanExternal: false,
+ autoCleanByMode: { external: false, local: false, codex: false },
});
const [status, setStatus] = useState(null);
@@ -146,9 +145,11 @@ export function ImageGenTab() {
: PARALLEL_FALLBACK;
setParallelBounds(bounds);
const cxParallel = clampParallel(cx.parallelLimit, bounds);
- const acCodex = cx.autoClean === true;
- const acLocal = ig.local?.autoClean === true;
- const acExternal = ig.external?.autoClean === true;
+ const ac = {
+ codex: cx.autoClean === true,
+ local: ig.local?.autoClean === true,
+ external: ig.external?.autoClean === true,
+ };
setMode(m);
setSdapiUrl(url);
setPythonPath(py);
@@ -158,14 +159,12 @@ export function ImageGenTab() {
setCodexModel(cxModel);
setCodexParallelLimit(cxParallel);
setParallelLimitDraft(String(cxParallel));
- setAutoCleanCodex(acCodex);
- setAutoCleanLocal(acLocal);
- setAutoCleanExternal(acExternal);
+ setAutoCleanByMode(ac);
setSaved({
mode: m, sdapiUrl: url, pythonPath: py, exposeA1111: expose,
codexEnabled: cxEnabled, codexPath: cxPath, codexModel: cxModel,
codexParallelLimit: cxParallel,
- autoCleanCodex: acCodex, autoCleanLocal: acLocal, autoCleanExternal: acExternal,
+ autoCleanByMode: ac,
});
setToolRegistered(tools.some((t) => t.id === SDAPI_TOOL_ID));
setCodexToolRegistered(tools.some((t) => t.id === CODEX_TOOL_ID));
@@ -190,9 +189,9 @@ export function ImageGenTab() {
|| codexPath !== saved.codexPath
|| codexModel !== saved.codexModel
|| codexParallelLimit !== saved.codexParallelLimit
- || autoCleanCodex !== saved.autoCleanCodex
- || autoCleanLocal !== saved.autoCleanLocal
- || autoCleanExternal !== saved.autoCleanExternal;
+ || autoCleanByMode.codex !== saved.autoCleanByMode.codex
+ || autoCleanByMode.local !== saved.autoCleanByMode.local
+ || autoCleanByMode.external !== saved.autoCleanByMode.external;
const handleSave = async () => {
setSaving(true);
@@ -203,11 +202,11 @@ export function ImageGenTab() {
const patch = {
imageGen: {
mode,
- external: { sdapiUrl: url, autoClean: autoCleanExternal },
- local: { pythonPath: pythonPath || undefined, autoClean: autoCleanLocal },
+ external: { sdapiUrl: url, autoClean: autoCleanByMode.external },
+ local: { pythonPath: pythonPath || undefined, autoClean: autoCleanByMode.local },
codex: {
enabled: codexEnabled, codexPath: cxPath, model: cxModel, parallelLimit: cxParallel,
- autoClean: autoCleanCodex,
+ autoClean: autoCleanByMode.codex,
},
expose: { a1111: exposeA1111 },
// Keep the legacy field populated so anything still reading
@@ -225,7 +224,7 @@ export function ImageGenTab() {
mode, sdapiUrl: url || '', pythonPath, exposeA1111,
codexEnabled, codexPath: cxPath || '', codexModel: cxModel || '',
codexParallelLimit: cxParallel,
- autoCleanCodex, autoCleanLocal, autoCleanExternal,
+ autoCleanByMode,
});
if (cxParallel !== codexParallelLimit) {
setCodexParallelLimit(cxParallel);
@@ -426,7 +425,7 @@ export function ImageGenTab() {
placeholder="http://localhost:7860"
/>
<p className="text-xs text-gray-500">Base URL for the SD WebUI server PortOS should send generation requests to.</p>
- <AutoCleanToggle checked={autoCleanExternal} onChange={setAutoCleanExternal} />
+ <AutoCleanToggle checked={autoCleanByMode.external} onChange={setAutoCleanFor('external')} />
</div>
)}
@@ -440,7 +439,7 @@ export function ImageGenTab() {
and are surfaced in <a href="/media/models" className="text-port-accent hover:underline">Media → Models</a>.
</p>
<LocalSetupPanel pythonPath={pythonPath} onPythonPathChange={setPythonPath} />
- <AutoCleanToggle checked={autoCleanLocal} onChange={setAutoCleanLocal} />
+ <AutoCleanToggle checked={autoCleanByMode.local} onChange={setAutoCleanFor('local')} />
</div>
)}
@@ -536,7 +535,7 @@ export function ImageGenTab() {
)}
</p>
</div>
- <AutoCleanToggle checked={autoCleanCodex} onChange={setAutoCleanCodex} />
+ <AutoCleanToggle checked={autoCleanByMode.codex} onChange={setAutoCleanFor('codex')} />
</div>
)}
</div>
diff --git a/client/src/pages/ImageGen.jsx b/client/src/pages/ImageGen.jsx
index e179c9f33e..7ca83d0349 100644
--- a/client/src/pages/ImageGen.jsx
+++ b/client/src/pages/ImageGen.jsx
@@ -123,6 +123,10 @@ export default function ImageGen() {
const [hfTokenPresent, setHfTokenPresent] = useState(null);
const [selectedMode, setSelectedMode] = useState(null);
+ // Mirror selectedMode in a ref so callbacks (reloadBackends) can read the
+ // latest value without re-creating themselves on every mode flip.
+ const selectedModeRef = useRef(null);
+ selectedModeRef.current = selectedMode;
const [availableBackends, setAvailableBackends] = useState([]);
const [prompt, setPrompt] = useState('');
@@ -158,6 +162,10 @@ export default function ImageGen() {
// payload so all three dispatch paths (external sync, codex queue, local
// queue) see the same boolean.
const [autoClean, setAutoClean] = useState(false);
+ // Saved per-mode default — keeps the "(overrides saved default)" hint
+ // reactive to settings reloads. Held as state (not a ref) so when the user
+ // edits a saved default in the Settings drawer and closes it, the hint
+ // re-evaluates even if `autoClean` happens to match the new saved value.
const [savedAutoCleanByMode, setSavedAutoCleanByMode] = useState({});
const [generating, setGenerating] = useState(false);
@@ -231,32 +239,36 @@ export default function ImageGen() {
const reloadBackends = useCallback(() => {
return getSettings().then((s) => {
const backends = deriveAvailableBackends(s);
- setAvailableBackends(backends);
- const saved = s?.imageGen?.mode || IMAGE_GEN_MODE.EXTERNAL;
- // If the user just disabled the currently-selected backend, fall
- // through to the first viable one — a just-toggled provider should
- // Just Work without a page reload.
- setSelectedMode((prev) => {
- if (prev && backends.find((b) => b.id === prev)) return prev;
- if (backends.find((b) => b.id === saved)) return saved;
- if (backends.length) return backends[0].id;
- return saved;
- });
- setSavedAutoCleanByMode({
+ const savedMap = {
external: s?.imageGen?.external?.autoClean === true,
local: s?.imageGen?.local?.autoClean === true,
codex: s?.imageGen?.codex?.autoClean === true,
- });
+ };
+ const saved = s?.imageGen?.mode || IMAGE_GEN_MODE.EXTERNAL;
+ // If the user just disabled the currently-selected backend, fall
+ // through to the first viable one — a just-toggled provider should
+ // Just Work without a page reload. Reading `selectedMode` here instead
+ // of inside a setSelectedMode updater keeps the state update pure
+ // (React updaters must not call other setters).
+ const prev = selectedModeRef.current;
+ const next = (prev && backends.find((b) => b.id === prev)) ? prev
+ : backends.find((b) => b.id === saved) ? saved
+ : backends.length ? backends[0].id
+ : saved;
+ setAvailableBackends(backends);
+ setSavedAutoCleanByMode(savedMap);
+ setSelectedMode(next);
+ setAutoClean(savedMap[next] === true);
}).catch(() => {});
}, []);
- // Re-seed the autoClean checkbox whenever the effective mode changes (mode
- // switch OR settings refresh). Without this, a user who flips from external
- // to local would still see the external autoClean value in the form.
- useEffect(() => {
- if (Object.keys(savedAutoCleanByMode).length === 0) return;
- setAutoClean(savedAutoCleanByMode[effectiveMode] === true);
- }, [effectiveMode, savedAutoCleanByMode]);
+ // Re-seed the autoClean checkbox when the user manually picks a different
+ // backend chip — without this, switching external→local would leave the
+ // external autoClean value in the form.
+ const handleSelectMode = useCallback((next) => {
+ setSelectedMode(next);
+ setAutoClean(savedAutoCleanByMode[next] === true);
+ }, [savedAutoCleanByMode]);
useEffect(() => {
listImageModels().then((m) => {
@@ -869,7 +881,7 @@ export default function ImageGen() {
<BackendChipStrip
availableBackends={availableBackends}
value={effectiveMode}
- onChange={setSelectedMode}
+ onChange={handleSelectMode}
disabled={statusLoading}
loadingId={statusLoading ? effectiveMode : null}
titlePrefix="Use"
diff --git a/server/lib/imageClean.js b/server/lib/imageClean.js
index 8ba75cdf73..2fa5f0a1a3 100644
--- a/server/lib/imageClean.js
+++ b/server/lib/imageClean.js
@@ -186,6 +186,9 @@ export async function autoCleanGeneratedImage({ enabled, pngPath, sidecarPath, m
});
if (!result || result.format !== 'png') return { cleaned: false };
+ // Sidecar read has no data dependency on the PNG write — kick it off in
+ // parallel so the disk-read latency overlaps the encode/write window.
+ const sidecarReadP = sidecarPath ? tryReadFile(sidecarPath) : Promise.resolve(null);
const replaced = await atomicWrite(pngPath, result.data)
.then(() => true)
.catch((err) => {
@@ -197,7 +200,7 @@ export async function autoCleanGeneratedImage({ enabled, pngPath, sidecarPath, m
// Best-effort sidecar patch — a missing sidecar is fine, the clean still
// happened. Merge so other fields aren't dropped.
if (sidecarPath) {
- const raw = await tryReadFile(sidecarPath);
+ const raw = await sidecarReadP;
const patched = {
...safeJSONParse(raw, {}),
autoCleaned: true,
diff --git a/server/routes/imageGen.js b/server/routes/imageGen.js
index aea4572311..1f444e4d58 100644
--- a/server/routes/imageGen.js
+++ b/server/routes/imageGen.js
@@ -19,7 +19,7 @@ import {
} from '../lib/validation.js';
import { optionalUploadFields } from '../lib/multipart.js';
import * as imageGen from '../services/imageGen/index.js';
-import { local, IMAGE_GEN_MODES } from '../services/imageGen/index.js';
+import { local, IMAGE_GEN_MODES, resolveAutoClean } from '../services/imageGen/index.js';
import { enqueueJob, attachSseClient as attachQueueSseClient, cancelJob, listJobs } from '../services/mediaJobQueue/index.js';
import { getSettings, saveSettings } from '../services/settings.js';
import { getHfToken, getHfTokenInfo, HF_TOKEN_REGEX } from '../lib/hfToken.js';
@@ -198,12 +198,9 @@ router.post('/generate', imageGenUploads, asyncHandler(async (req, res) => {
const mode = data.mode || settings.imageGen?.mode || 'external';
// Resolve autoClean ONCE at the route layer so all three dispatch paths
// (synchronous external, codex queue, local queue) see the same value.
- // Body wins when explicit (the per-render checkbox); otherwise inherit the
- // saved per-mode setting. Stamp onto `data` so the value flows through
- // the spread-into-params calls below verbatim.
- data.autoClean = (typeof data.autoClean === 'boolean')
- ? data.autoClean
- : (settings.imageGen?.[mode]?.autoClean === true);
+ // Stamp onto `data` so the value flows through the spread-into-params
+ // calls below verbatim.
+ data.autoClean = resolveAutoClean(data.autoClean, settings, mode);
// Multi-reference is a FLUX.2-only, local-backend-only feature — local.js's
// buildArgs only emits --reference-images/--reference-strengths inside the
diff --git a/server/routes/imageGen.test.js b/server/routes/imageGen.test.js
index eebc5858d6..13cbb03eb0 100644
--- a/server/routes/imageGen.test.js
+++ b/server/routes/imageGen.test.js
@@ -10,6 +10,11 @@ vi.mock('../services/imageGen/index.js', () => ({
attachSseClient: vi.fn(() => false),
cancel: vi.fn(() => false),
IMAGE_GEN_MODES: ['external', 'local', 'codex'],
+ // Mirror the real precedence so route-level resolution behaves correctly
+ // under test: explicit body bool wins, otherwise fall back to settings.
+ resolveAutoClean: (bodyValue, settings, mode) => (typeof bodyValue === 'boolean'
+ ? bodyValue
+ : settings?.imageGen?.[mode]?.autoClean === true),
local: {
listImageModels: vi.fn(() => []),
listLoraFilenames: vi.fn(async () => []),
diff --git a/server/services/imageGen/index.js b/server/services/imageGen/index.js
index 6cd478a5f4..07de1d671e 100644
--- a/server/services/imageGen/index.js
+++ b/server/services/imageGen/index.js
@@ -26,6 +26,15 @@ const sdapiUrl = (s) => cfg(s).external?.sdapiUrl || cfg(s).sdapiUrl || null;
const pythonPath = (s) => cfg(s).local?.pythonPath || null;
const codexCfg = (s) => cfg(s).codex || {};
+// Body wins when explicit (per-render checkbox); otherwise inherit the saved
+// per-mode default. Shared by `/generate` (stamps the resolved value onto the
+// request so all three dispatch paths agree) and `generateImage()` (safety net
+// for direct callers like `generateAvatar`).
+export function resolveAutoClean(bodyValue, settings, mode) {
+ if (typeof bodyValue === 'boolean') return bodyValue;
+ return cfg(settings)[mode]?.autoClean === true;
+}
+
export async function getMode() {
const s = await getSettings();
return cfg(s).mode || DEFAULT_MODE;
@@ -69,13 +78,12 @@ export async function generateImage(params) {
delete normalized.initImagePath;
delete normalized.initImageStrength;
}
- // Auto-clean is per-provider-mode, opt-in. Precedence: caller-supplied
- // boolean (the `/generate` route's per-render checkbox) wins; otherwise
- // inherit the saved per-mode setting. Strip from `normalized` so the
- // explicit arg on each provider call isn't shadowed by the spread.
- const autoClean = (typeof normalized.autoClean === 'boolean')
- ? normalized.autoClean
- : (cfg(s)[mode]?.autoClean === true);
+ // Auto-clean is per-provider-mode, opt-in. The route layer already resolves
+ // this so the queue/route paths agree, but resolve here too for direct
+ // callers (e.g. `generateAvatar`) that skip the route. Strip from
+ // `normalized` so the explicit arg on each provider call isn't shadowed by
+ // the spread.
+ const autoClean = resolveAutoClean(normalized.autoClean, s, mode);
delete normalized.autoClean;
if (mode === 'codex') {
const c = codexCfg(s);