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
review: job-aware temp GC, completed-gate on result-fetch, oriented sourceDims, explicit GPU run trigger (#2264)
Adam Eivy410c754f448e
diff --git a/client/src/pages/ImageClean.jsx b/client/src/pages/ImageClean.jsxindex 7a75ff9bba..c530bb0ed3 100644--- a/client/src/pages/ImageClean.jsx+++ b/client/src/pages/ImageClean.jsx@@ -247,7 +247,31 @@ export default function ImageClean() {width: dims?.width || null,height: dims?.height || null,});- runClean(file, steps, diffusionMode);+ // Auto-run the sync pipeline on select. If the GPU sub-mode is active it's+ // NOT auto-enqueued (see `autoRun`) — the user tunes strength/max-MP then+ // clicks "Run GPU clean", so the render reads the settings they see.+ autoRun(file, steps, diffusionMode);+ };++ // A GPU diffusion run is expensive (GPU-serialized, queued) and has tunable+ // params (strength / max-MP) — so it only fires from an explicit button, never+ // as a side effect of toggling a step or switching mode (which would enqueue+ // with stale params, then silently ignore later slider moves). Sync pipelines+ // (metadata / denoise / CPU light) stay auto-run for instant feedback.+ const willUseGpu = (selectedSteps, mode) => !!selectedSteps.diffusion && mode === 'gpu';+ const autoRun = (file, selectedSteps, mode, opts) => {+ if (!file) return;+ if (willUseGpu(selectedSteps, mode)) {+ // Clear a stale sync result so the After panel shows the "run GPU" prompt+ // rather than a now-inconsistent preview.+ if (resultUrlRef.current) { URL.revokeObjectURL(resultUrlRef.current); resultUrlRef.current = null; }+ setResult(null);+ setGpuJobId(null);+ setGpuJob(null);+ setBusy(false);+ return;+ }+ runClean(file, selectedSteps, mode, opts);};const toggleStep = (key) => {@@ -255,13 +279,13 @@ export default function ImageClean() {const next = { ...steps, [key]: !steps[key] };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, diffusionMode);+ // reflects the current steps (GPU is gated behind the explicit button).+ if (original?.file) autoRun(original.file, next, diffusionMode);};const changeDiffusionMode = (mode) => {setDiffusionMode(mode);- if (original?.file && steps.diffusion) runClean(original.file, steps, mode);+ if (original?.file && steps.diffusion) autoRun(original.file, steps, mode);};const handleDrag = (e) => {@@ -538,6 +562,17 @@ export default function ImageClean() {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>)}+ {/* Explicit run trigger — GPU never auto-enqueues, so the+ render always reads the strength/max-MP shown here. */}+ <button+ type="button"+ onClick={() => { if (original?.file) runClean(original.file, steps, 'gpu'); }}+ disabled={busy || !regen?.available}+ className="px-4 py-2 rounded-lg text-sm bg-port-accent hover:bg-port-accent/80 disabled:opacity-40 disabled:cursor-not-allowed text-white transition-colors flex items-center gap-2 w-full sm:w-auto"+ >+ <Zap size={16} />+ {busy && gpuJobId ? 'Rendering…' : 'Run GPU clean'}+ </button></div>)}</div>@@ -571,7 +606,7 @@ export default function ImageClean() {<Undo2 size={12} /> Undo</button><button- onClick={() => { painterRef.current?.clear(); if (original?.file) runClean(original.file, steps, diffusionMode, { skipMask: true }); }}+ onClick={() => { painterRef.current?.clear(); if (original?.file) autoRun(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} /> Cleardiff --git a/server/routes/imageClean.js b/server/routes/imageClean.jsindex 207212c74a..49eeacc9cb 100644--- a/server/routes/imageClean.js+++ b/server/routes/imageClean.js@@ -147,11 +147,20 @@ router.post(// in visual space) aligns with the render.let gpuInit = result.data;let gpuOriginal = maskBuffer ? originalBuffer : null;+ // Dimensions the render + upscale-back target. `result.width/height` are+ // the (metadata-step) cleaned dims; but when a mask forces the oriented+ // re-encode below, the oriented buffer's dims can differ (EXIF 6/8 swaps+ // W/H) — so read them off the ORIENTED buffer, or FLUX renders at the+ // wrong aspect and the composite misaligns.+ let sourceDims = result.width && result.height ? { width: result.width, height: result.height } : null;if (maskBuffer) {- const orientedPng = await sharp(result.data).rotate().png().toBuffer().catch(() => null);- if (orientedPng) { gpuInit = orientedPng; gpuOriginal = orientedPng; }+ const oriented = await sharp(result.data).rotate().png().toBuffer({ resolveWithObject: true }).catch(() => null);+ if (oriented) {+ gpuInit = oriented.data;+ gpuOriginal = oriented.data;+ sourceDims = { width: oriented.info.width, height: oriented.info.height };+ }}- const sourceDims = result.width && result.height ? { width: result.width, height: result.height } : null;const queued = await enqueueGpuClean({initBuffer: gpuInit,sourceDims,@@ -307,15 +316,21 @@ router.get(if (status.status === 'failed' || status.status === 'canceled') {throw new ServerError(status.error || `Clean job ${status.status}`, { status: 409, code: 'JOB_FAILED' });}+ // Never read bytes off disk while the job is still queued/running: the+ // runner writes the render mid-flight (and the completion path upscales it+ // back to source dims AFTER the initial write), so a read before the+ // terminal `completed` state could return a partial or pre-upscale frame.+ // 409 keeps the client polling. (A job that vanished from the queue's 24h+ // archive reads as `unknown` — fall through and let the disk decide 200 vs+ // 404, so a completed-then-forgotten render is still fetchable.)+ if (status.status === 'queued' || status.status === 'running') {+ throw new ServerError('Clean result not ready yet', { status: 409, code: 'RESULT_NOT_READY', severity: 'warning' });+ }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' },- );+ // Completed/unknown but no bytes on disk → gone (past the temp GC or an+ // unknown id). A true miss so the client stops polling.+ throw new ServerError('Clean result not found', { status: 404, code: 'NOT_FOUND', severity: 'warning' });}res.setHeader('Access-Control-Expose-Headers', 'X-Clean-Report');res.setHeader('X-Clean-Report', JSON.stringify({diff --git a/server/services/imageCleanTmpGc.js b/server/services/imageCleanTmpGc.jsindex a84c91b87b..f5668fdf17 100644--- a/server/services/imageCleanTmpGc.js+++ b/server/services/imageCleanTmpGc.js@@ -17,12 +17,45 @@import { readdir, stat, unlink } from 'node:fs/promises';import { join } from 'node:path';import { PATHS } from '../lib/fileUtils.js';+import { listJobs } from './mediaJobQueue/index.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.+// takes, while sparing an un-fetched result. The age-gate is a BACKSTOP — the+// primary safety is the active-job guard below (a queued job stuck behind a+// long render / first-run model download can sit well past an hour, and its+// init/mask/original must survive until it runs).export const CLEAN_TMP_MAX_AGE_MS = 60 * 60 * 1000; // 1 hour+// Collect the temp-file basenames any queued/running media job still depends on+// so the sweep never deletes a not-yet-run job's init image, or the mask/+// original a completed-but-not-yet-fetched masked render needs to composite.+// A job's `initImagePath` names `image-clean-tmp/init-<uuid>.png`, and its id+// keys the `<jobId>-{mask,original,clean.json}` + `<jobId>.png` side files.+// Pure over its arg (the job list) so it's testable without the real queue.+export function collectActiveCleanBasenames(jobs = []) {+ const keep = new Set();+ for (const job of Array.isArray(jobs) ? jobs : []) {+ if (job?.kind !== 'image') continue;+ // Only in-flight jobs pin files; a terminal job's render is either already+ // fetched or up for age-gated collection.+ if (job.status !== 'queued' && job.status !== 'running') continue;+ const init = job.params?.initImagePath;+ if (typeof init === 'string' && init) {+ const base = init.split(/[/\\]/).pop();+ if (base) keep.add(base);+ }+ const id = typeof job.id === 'string' ? job.id : null;+ if (id) {+ keep.add(`${id}.png`);+ keep.add(`${id}-mask.png`);+ keep.add(`${id}-original.png`);+ keep.add(`${id}-clean.json`);+ }+ }+ return keep;+}+// 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@@ -39,14 +72,22 @@ export async function sweepImageCleanTmp({now = Date.now(),maxAgeMs = CLEAN_TMP_MAX_AGE_MS,tmpDir = PATHS.imageCleanTmp,+ activeJobs = null,} = {}) {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 };+ if (files.length === 0) return { deleted: 0, keptYoung: 0, keptActive: 0 };++ // Files pinned by a still-queued/running job are never swept, regardless of+ // age — a job stuck behind a long render can outlive the grace window.+ const jobs = activeJobs || listJobs({ kind: 'image' });+ const active = collectActiveCleanBasenames(jobs);let deleted = 0;let keptYoung = 0;+ let keptActive = 0;for (const name of files) {+ if (active.has(name)) { keptActive += 1; continue; }const info = await stat(join(tmpDir, name)).catch(() => null);if (!info) continue; // vanished under us — nothing to doif (now - info.mtimeMs < maxAgeMs) {@@ -56,7 +97,7 @@ export async function sweepImageCleanTmp({const removed = await unlink(join(tmpDir, name)).then(() => true).catch(() => false);if (removed) deleted += 1;}- return { deleted, keptYoung };+ return { deleted, keptYoung, keptActive };}/**diff --git a/server/services/imageCleanTmpGc.test.js b/server/services/imageCleanTmpGc.test.jsindex d74ad7d845..86898219a2 100644--- a/server/services/imageCleanTmpGc.test.js+++ b/server/services/imageCleanTmpGc.test.js@@ -2,7 +2,7 @@ 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';+import { sweepImageCleanTmp, collectActiveCleanBasenames, CLEAN_TMP_MAX_AGE_MS } from './imageCleanTmpGc.js';let dir;@@ -28,20 +28,21 @@ const writeAged = (name, ageMs) => {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 });+ const res = await sweepImageCleanTmp({ tmpDir: join(dir, 'nope'), activeJobs: [] });+ expect(res.deleted).toBe(0);+ expect(res.keptYoung).toBe(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 });+ const res = await sweepImageCleanTmp({ tmpDir: dir, activeJobs: [] });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 });+ const res = await sweepImageCleanTmp({ tmpDir: dir, activeJobs: [] });expect(res.deleted).toBe(0);expect(res.keptYoung).toBe(1);expect(existsSync(fresh)).toBe(true);@@ -57,7 +58,54 @@ describe('sweepImageCleanTmp', () => {'22222222-2222-4222-8222-222222222222-clean.json',];names.forEach((n) => writeAged(n, age));- const res = await sweepImageCleanTmp({ tmpDir: dir });+ const res = await sweepImageCleanTmp({ tmpDir: dir, activeJobs: [] });expect(res.deleted).toBe(names.length);});++ it('never sweeps files pinned by a still-queued job, even past the grace window', async () => {+ const age = CLEAN_TMP_MAX_AGE_MS + 60_000;+ const jobId = '33333333-3333-4333-8333-333333333333';+ const init = 'init-pinned.png';+ // Old files, but a queued job still depends on its init + side files.+ writeAged(init, age);+ writeAged(`${jobId}-mask.png`, age);+ writeAged(`${jobId}-clean.json`, age);+ // An unrelated old file should still be swept.+ const stray = writeAged('44444444-4444-4444-8444-444444444444.png', age);+ const jobs = [{+ id: jobId,+ kind: 'image',+ status: 'queued',+ params: { initImagePath: `/data/image-clean-tmp/${init}` },+ }];+ const res = await sweepImageCleanTmp({ tmpDir: dir, activeJobs: jobs });+ expect(res.keptActive).toBe(3);+ expect(res.deleted).toBe(1);+ expect(existsSync(join(dir, init))).toBe(true);+ expect(existsSync(stray)).toBe(false);+ });+});++describe('collectActiveCleanBasenames', () => {+ it('keeps init + jobId side files for queued/running jobs only', () => {+ const jobs = [+ { id: 'a', kind: 'image', status: 'queued', params: { initImagePath: '/x/image-clean-tmp/init-a.png' } },+ { id: 'b', kind: 'image', status: 'running', params: {} },+ { id: 'c', kind: 'image', status: 'completed', params: { initImagePath: '/x/init-c.png' } },+ { id: 'd', kind: 'video', status: 'queued', params: {} },+ ];+ const keep = collectActiveCleanBasenames(jobs);+ expect(keep.has('init-a.png')).toBe(true);+ expect(keep.has('a.png')).toBe(true);+ expect(keep.has('b-mask.png')).toBe(true);+ // Completed + non-image jobs pin nothing.+ expect(keep.has('init-c.png')).toBe(false);+ expect(keep.has('c.png')).toBe(false);+ expect(keep.has('d.png')).toBe(false);+ });++ it('tolerates a non-array / empty input', () => {+ expect(collectActiveCleanBasenames(null).size).toBe(0);+ expect(collectActiveCleanBasenames([]).size).toBe(0);+ });});