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-gen): queueable renders, FLUX.2 stage UI + typed errors, stepwise unpack fix
Adam Eivye991401285cf
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 16b49a803f..81139e8736 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,10 @@## Added+- **Queue additional renders while one is in flight.** Image Gen form fields stay editable during a render and the Generate button becomes a "Queue" button — submissions land in `mediaJobQueue` (server FIFO) without taking over the active SSE/preview, so the user can stack multiple prompts without waiting. A "+N queued" badge surfaces queue depth, and a 4 s `/api/media-jobs` poll syncs it against the server's truth and refreshes the gallery the moment a queued render completes (only on busy-count drop — no per-tick refresh churn). The poll's effect deps key on a `queueActive` boolean so the interval clock doesn't tear down on every count change. A separate "Cancel current" button lets the user kill the active render without losing the form's content. Mirrors the form-editable-during-render policy already in place for video gen.+- **STAGE pipeline for FLUX.2 model loading + downloads.** `flux2_macos.py` now emits `STAGE:download-tokenizer:<repo>` / `STAGE:download-pipeline:<repo>` / `STAGE:move-to-device` / `STAGE:inference` markers; `server/services/imageGen/local.js#handleLine` parses them and broadcasts a typed `{type:'stage', stage, detail}` SSE event. The Image Gen page maps each marker to a friendly label via a `STAGE_LABELS` lookup ("Downloading model weights (~8 GB on first run)…", "Moving model to GPU…", etc.) so the multi-minute first-run HF weight download no longer looks like a frozen "step 0/8". Inference progress events also carry the active phase so the step counter only ticks during real diffusion, not during download `tqdm` bars (which count safetensors files, not steps).+- **Friendly typed errors for HuggingFace failures.** Top-level exception handler in `flux2_macos.py` walks the exception cause chain (diffusers wraps HF errors in `OSError`) to detect `GatedRepoError` / `HfHubHTTPError(401)` / `RepositoryNotFoundError`, then emits a structured `USER_ERROR:<kind>:<repo>` line plus a friendly `❌ <prose>` line — including a `_repo_from_hf_error()` URL parser that reconstructs `owner/name` from the failing request URL because `huggingface_hub` doesn't always populate `error.repo_id`. `local.js` parses the `USER_ERROR:` line out of the stderr buffer (single `findIndex` pass — no nested `indexOf` O(n²)) and propagates `kind` + `repo` through both the per-job SSE error event and the `imageGenEvents.emit('failed', ...)` payload, so the queue's downstream broadcast inherits the friendly message instead of "Exit code 1". The Image Gen page renders a typed error card with an `ERROR_HEADINGS` lookup ("Model access required" / "HuggingFace token rejected" / "Model repo not found") and a one-click "Request access to <repo> ↗" button that deep-links to the HF page — replacing the previous behavior where a 9B gated-access failure surfaced as bare "Exit code 1" with a wall of Python tracebacks in `pm2 logs`.+- **Python child stderr/stdout echoed to pm2 logs.** `local.js` now logs `🐍 [<jobId>] <line>` / `🐍-out [<jobId>] <line>` for every non-progress, non-noise line from `flux2_macos.py` (and any future image runner). Lines that drove a `progress` or `stage` SSE event are intentionally excluded so the log stream isn't drowned by tqdm bars. Mirrors the existing video-gen logging pattern — without it, model-load lifecycle (`🔧 sdnq: pipeline ← …`) was only visible in the SSE channel the browser saw and never landed in server logs, making "stuck on step 0/8 for 8 minutes" indistinguishable from a hang.- **In-app HuggingFace token entry.** The "FLUX.2-klein is gated, export HF_TOKEN before running PortOS" banner now has a paste-and-save form: enter your `hf_…` token, click Save, and PortOS persists it to `settings.imageGen.hfToken`. The local-image worker (`server/services/imageGen/local.js`) injects it into the spawn env (`HF_TOKEN`, `HUGGINGFACE_HUB_TOKEN`, `HUGGINGFACEHUB_API_TOKEN` — `huggingface_hub` reads any of the three) so `flux2_macos.py` can pull gated repos like `black-forest-labs/FLUX.2-klein-4B` without the user having to drop to a shell. New helper `server/lib/hfToken.js` (`getHfToken()` / `hfTokenEnv()` / `isPlausibleHfToken()`) — stored token wins over env-var fallback so the user can update without restarting PortOS. New route `POST /api/image-gen/setup/flux2-token` validates the `hf_…` prefix before persisting. Same security trade-off as other PortOS settings: plaintext in `data/settings.json`, justified by the single-user Tailscale deployment model documented in CLAUDE.md.- **In-app FLUX.2 venv installer.** Selecting a FLUX.2 model when the venv isn't bootstrapped now surfaces an "Install FLUX.2" button on the Image Gen page instead of telling the user to drop to a shell and run `INSTALL_FLUX2=1 bash scripts/setup-image-video.sh`. Clicking it opens a modal that streams real-time progress over a new SSE endpoint (`GET /api/image-gen/setup/flux2-install`) — a 5-stage pipeline (detect Python → create venv → upgrade pip → install packages → verify `Flux2KleinPipeline` import) animates with check-marks/spinners while pip output scrolls in a live log pane below. Closing the modal mid-install SIGTERMs pip so a multi-GB torch download doesn't keep going invisibly. Server-side logic lives in `installFlux2Venv()` in `server/lib/pythonSetup.js`, mirroring the bash script's package list (`FLUX2_PIP_SPECS`) so both paths stay in sync. The status cache (`resolveFlux2Python`) busts on completion so the banner clears without a server restart.- **FLUX.2-klein image generation on macOS (Apple Silicon).** Three quantized variants ship: 4B SDNQ-4bit (~8 GB @ 512px, recommended), 9B SDNQ-4bit (~12 GB, needs 32+ GB RAM), and 4B Int8 (~16 GB). Runs through PyTorch + diffusers + MPS in a separate `~/.portos/venv-flux2` to avoid colliding with mflux's older torch. `INSTALL_FLUX2=1 bash scripts/setup-image-video.sh` bootstraps the venv (idempotent — skips re-install when `Flux2KleinPipeline` already imports). The runner (`scripts/flux2_macos.py`) mirrors `mflux-generate`'s CLI surface so the existing local-image dispatcher just swaps the binary path; live preview frames, metadata sidecar, gallery, and Remix all work unchanged. Stepwise preview decodes latents on a `@torch.no_grad()` callback and writes capped 512-px PNGs so fs.watch + base64 stays cheap. Models are gated on HuggingFace — accept the license at https://huggingface.co/black-forest-labs/FLUX.2-klein-4B and export `HF_TOKEN`; the Image Gen page surfaces a yellow banner when the venv is missing or the token isn't set. The legacy `flux2-klein-{4b,9b}` registry entries (which had `broken: 'macos'`) auto-upgrade in place — user customizations like a custom name or steps are preserved.@@ -26,6 +30,7 @@## Fixed+- **FLUX.2 stepwise previews now actually render.** The callback's `vae.decode(latents)` was silently failing every step with `IndexError: tuple index out of range` because `Flux2KleinPipeline` hands the callback latents in transformer-packed shape `(B, num_patches, C·P²)` (e.g. `(1, 2304, 128)` for 1024×576) but the VAE expects unpacked `(B, C, H, W)`. New `_unpack_flux2_latents()` does the patch unpack (2×2 patches × 8× VAE downsample) before the decode call. `make_stepwise_callback()` now takes `height`/`width` and short-circuits the unpack if a future pipeline version hands us an already-4-D tensor.- **FLUX.2 install detection now checks functional health, not just file existence.** Previously `resolveFlux2Python()` returned the venv binary path as long as the file existed — but a venv whose install was killed mid-pip leaves the python binary behind with an empty site-packages, so the status endpoint reported `venvInstalled: true`, the install banner cleared, and rendering crashed with `Exit code 1` in 100ms when `flux2_macos.py` failed to `import diffusers`. New helper `isFlux2VenvHealthy()` (cached) probes `from diffusers import Flux2KleinPipeline` once. `/setup/flux2-status` and `/setup/flux2-install`'s early-return both use it, so a half-broken venv now reports as not-installed and the user can retry the install from the UI without manual cleanup.- **PM2 watcher debounce reduced from 5 min → 1 min** and `ignore_watch` hardened with `data/`, `logs/`, `.cache/`, and `portos-stepwise-*` patterns. `watch: ['server']` already scopes the watcher correctly, but the long debounce meant a server-file edit + start-render-now sequence could cleanly kick off a render and then have PM2 restart 5 minutes in, killing the Python child with SIGINT halfway through. Tighter debounce + explicit defense-in-depth ignore patterns make the failure mode less catastrophic and easier to predict during dev.- **FLUX.2 stepwise preview diagnostic.** Added a one-time `🖼️ stepwise: callback live, latents.shape=…` log on the first callback fire, and a post-run `🖼️ stepwise summary: callback fired N times, saved M previews` so when previews don't show up the cause (callback never attached, latents missing, VAE decode failing) shows up in `pm2 logs`. The existing per-step `⚠️ stepwise preview failed` line now also includes the exception type for triage.diff --git a/PLAN.md b/PLAN.mdindex cf54599328..1c6ae90d30 100644--- a/PLAN.md+++ b/PLAN.md@@ -33,6 +33,7 @@ The PR landed with full pipeline mechanics + auto-recovery + smoke-test fixture,- [ ] **M50 P9 — CoS Automation & Rules** — Automated email classification, rule-based pre-filtering, email-to-task pipeline.- [ ] **M50 P10 — Auto-Send with AI Review Gate** — Per-account/per-recipient trust level + dual-LLM review (drafter + reviewer). Only auto-send when both approve or trust ≥ 0.9. See [Messages Security](./docs/features/messages-security.md).- [ ] **M34 P5-P7 — Digital Twin** — Multi-modal capture (voice/video/image identity sources), advanced testing, personas. Ties to GOALS.md secondary "Multi-Modal Identity Capture".+- [ ] **Multi-reference image editing for FLUX.2** — Add a UI on the Image Gen page that accepts 2+ reference images plus an edit prompt (e.g. "put the subject from image A into the scene from image B"). When this lands, swap the model registry's 9B entry to [`black-forest-labs/FLUX.2-klein-9B-kv`](https://huggingface.co/black-forest-labs/FLUX.2-klein-9B-kv) — KV-cache optimization computes reference-image KV pairs once and reuses them across edits, giving up to 2.5× speedup on multi-reference workflows. Single-prompt / single-init paths see no benefit, which is why standard 9B is fine until then. Work involves: schema for multi-image payload (`referenceImages: [...]`), client multi-uploader, server FormData parsing, and adapting `flux2_macos.py` to call the multi-reference pipeline API. Separately-gated repo on HF — user must request access.### Depfree Audit — 2026-04-28diff --git a/client/src/pages/ImageGen.jsx b/client/src/pages/ImageGen.jsxindex 1a751e6839..2517620536 100644--- a/client/src/pages/ImageGen.jsx+++ b/client/src/pages/ImageGen.jsx@@ -27,7 +27,7 @@ import { useImageGenProgress } from '../hooks/useImageGenProgress';import {getImageGenStatus, generateImage, listImageModels, listLoras, listImageGallery,cancelImageGen, deleteImage, setImageHidden, getActiveImageJob, getSettings,- buildFormData,+ buildFormData, listMediaJobs,} from '../services/api';import { randomSeed, safeParseJSON } from '../lib/genUtils';@@ -45,6 +45,31 @@ const RESOLUTIONS = [const DEFAULT_NEGATIVE = 'blurry, low quality, distorted, deformed, ugly, watermark, text, signature';+// User-facing labels for STAGE markers emitted by FLUX.2 (and any future+// runner). The keys match what `flux2_macos.py` prints; unknown stages fall+// through to the prettified id so adding a new STAGE in Python doesn't+// require a client change to be at least readable.+const STAGE_LABELS = {+ 'starting': 'Starting…',+ 'download-tokenizer': 'Loading tokenizer…',+ 'download-pipeline': 'Downloading model weights (~8 GB on first run)…',+ 'download-snapshot': 'Downloading model weights…',+ 'download-int8-snapshot': 'Downloading model weights (~16 GB on first run)…',+ 'load-transformer': 'Loading transformer…',+ 'load-text-encoder': 'Loading text encoder…',+ 'move-to-device': 'Moving model to GPU…',+ 'inference': 'Running diffusion…',+};++// Headings for typed errors emitted via USER_ERROR: lines. Keys match `kind`+// from the SSE error event. Unknown/missing kinds fall through to the+// generic 'Generation failed' heading.+const ERROR_HEADINGS = {+ gated_repo: 'Model access required',+ hf_unauthorized: 'HuggingFace token rejected',+ repo_not_found: 'Model repo not found',+};+export default function ImageGen() {const navigate = useNavigate();const [searchParams, setSearchParams] = useSearchParams();@@ -87,7 +112,18 @@ export default function ImageGen() {const [generating, setGenerating] = useState(false);const [statusMsg, setStatusMsg] = useState('');+ const [errorMeta, setErrorMeta] = useState(null); // { kind, repo } for typed-error guidanceconst [localProgress, setLocalProgress] = useState(null); // local mode SSE-driven 0..1+ // Count of additional submits stacked behind the in-flight render. Drains+ // back to 0 every time the active render completes (refreshGallery picks+ // up everything finished server-side). Just a visual signal for the user;+ // the real queue lives in mediaJobQueue on the server.+ const [pendingQueued, setPendingQueued] = useState(0);+ // FLUX.2 (and any future runner that emits `STAGE:` markers) flips this+ // through phases like 'download-pipeline' → 'move-to-device' → 'inference'.+ // Drives the loading-card label so a multi-minute first-run model download+ // doesn't look like a frozen "step 0/8".+ const [stage, setStage] = useState(null);const [result, setResult] = useState(null);const [error, setError] = useState(null);const eventSourceRef = useRef(null);@@ -307,6 +343,39 @@ export default function ImageGen() {return () => controller.abort();}, [isFlux2Model, modelId, refreshFlux2Status]);+ // While the user has additional renders queued behind the active one, poll+ // `/api/media-jobs` to keep `pendingQueued` in sync with the server's+ // actual queue depth and refresh the gallery when a job transitions+ // running → done. The effect intentionally depends only on `pendingQueued+ // > 0` (a boolean) — using `pendingQueued` directly would tear down and+ // recreate the interval every tick the count changes, never letting the+ // 4s clock settle.+ const queueActive = pendingQueued > 0;+ const lastBusyRef = useRef(0);+ useEffect(() => {+ if (!queueActive) return;+ let cancelled = false;+ const tick = async () => {+ const jobs = await listMediaJobs({ kind: 'image' }).catch(() => null);+ if (cancelled || !jobs) return;+ const stillBusy = jobs.filter((j) => j.status === 'queued' || j.status === 'running').length;+ // Subtract 1 for the actively-tracked render (when generating). Floor+ // at 0 so a transient counting glitch doesn't show "−1 queued".+ const next = Math.max(0, stillBusy - (generating ? 1 : 0));+ // Only refresh gallery on a busy-count drop — that's the signal a+ // queued job just completed. Otherwise polling re-fetches the gallery+ // every 4s for nothing.+ if (stillBusy < lastBusyRef.current) refreshGallery();+ lastBusyRef.current = stillBusy;+ // No-op guard: same value setState would still trigger a render, so+ // explicitly skip when nothing changed.+ setPendingQueued((prev) => (prev === next ? prev : next));+ };+ tick();+ const interval = setInterval(tick, 4000);+ return () => { cancelled = true; clearInterval(interval); };+ }, [queueActive, generating]); // eslint-disable-line react-hooks/exhaustive-deps+const flux2Issue = isFlux2Model && flux2Status? (!flux2Status.venvInstalled ? 'venv' : !flux2Status.hfTokenPresent ? 'token' : null): null;@@ -322,12 +391,13 @@ export default function ImageGen() {const handleRandomSeed = () => setSeed(randomSeed());- const startLocalGeneration = async () => {- setLocalProgress({ progress: 0 });- // Codex shares the SSE-driven async pipeline with local. The codex- // payload below intentionally omits local-only knobs (model, LoRAs,- // quantize, guidance, steps, seed) — the codex provider only consumes- // prompt/negative/width/height, so we don't bother sending the rest.+ // Snapshots current form state into a server payload + POSTs it to the+ // mediaJobQueue. Returns the queue's response ({ jobId, position, ... }).+ // Shared between startLocalGeneration (which then opens SSE for the job)+ // and the "queue another while one is running" path which only needs the+ // POST — the user keeps watching the active render and the new submission+ // sits in the server queue until the active one finishes.+ const submitGenerationPayload = async () => {const payload = isCodexMode ? {prompt: prompt.trim(),negativePrompt: negativePrompt.trim() || undefined,@@ -346,11 +416,7 @@ export default function ImageGen() {loraScales: selectedLoras.map((l) => l.scale),mode: 'local',};- // i2i (local Flux): switch to multipart so the init image travels with- // the prompt payload. The route's optional-multipart middleware accepts- // both shapes against the same endpoint.const hasInitImage = isLocalMode && initImage.source != null;- let data;if (hasInitImage) {const fd = buildFormData({...payload,@@ -362,11 +428,14 @@ export default function ImageGen() {const body = await res.json().catch(() => ({ error: `HTTP ${res.status}` }));throw new Error(body.error || `HTTP ${res.status}`);}- data = await res.json();- } else {- data = await generateImage(payload);+ return { payload, data: await res.json() };}+ return { payload, data: await generateImage(payload) };+ };+ const startLocalGeneration = async () => {+ setLocalProgress({ progress: 0 });+ const { payload, data } = await submitGenerationPayload();return new Promise((resolve, reject) => {const jobId = data.jobId || data.generationId;const es = new EventSource(`/api/image-gen/${jobId}/events`);@@ -375,9 +444,10 @@ export default function ImageGen() {es.onmessage = (ev) => {const msg = safeParseJSON(ev.data);if (!msg) return;+ if (msg.type === 'stage') setStage({ name: msg.stage, detail: msg.detail });if (msg.type === 'status') setStatusMsg(msg.message);if (msg.type === 'progress') {- setLocalProgress({ progress: msg.progress });+ setLocalProgress({ progress: msg.progress, phase: msg.phase });setStatusMsg(msg.message);}if (msg.type === 'complete') {@@ -404,7 +474,13 @@ export default function ImageGen() {}if (msg.type === 'error') {es.close();- reject(new Error(msg.error));+ // The server may attach `kind` (e.g. 'gated_repo', 'hf_unauthorized')+ // and `repo` for the UI to deep-link to the HF access page. Carry+ // them on the Error so handleGenerate's catch can render guidance.+ const err = new Error(msg.error);+ if (msg.kind) err.kind = msg.kind;+ if (msg.repo) err.repo = msg.repo;+ reject(err);}if (msg.type === 'canceled') {es.close();@@ -418,13 +494,33 @@ export default function ImageGen() {});};+ // Queue a render without taking over the active SSE/preview. Used when the+ // user submits while one is already rendering — they get to keep watching+ // the in-flight render, and the new payload lands in mediaJobQueue (server+ // FIFO). When the active render finishes, refreshGallery() pulls all+ // completed images so the queued ones become visible as they land.+ const handleQueueAdditional = async () => {+ if (!prompt.trim()) return;+ const { data } = await submitGenerationPayload().catch((err) => {+ toast.error(err.message || 'Failed to queue render');+ return {};+ });+ if (!data) return;+ setPendingQueued((n) => n + 1);+ const pos = typeof data.position === 'number' ? data.position : null;+ toast.success(pos ? `Queued (${pos} ahead in queue)` : 'Queued');+ };+const handleGenerate = async (e) => {e?.preventDefault?.();- if (!prompt.trim() || generating) return;+ if (!prompt.trim()) return;+ if (generating) return handleQueueAdditional();setGenerating(true);setStatusMsg('Starting...');setError(null);+ setErrorMeta(null);setResult(null);+ setStage(null);// Both modes go through the socket-driven progress hook now — local mflux// emits stepwise frames via the imageGenEvents bus the same way external// SD API does, so the same hook drives the live preview for both.@@ -450,11 +546,20 @@ export default function ImageGen() {refreshGallery();} catch (err) {setError(err.message || 'Image generation failed');- toast.error(err.message || 'Image generation failed');+ // Typed kind from a USER_ERROR: line lets the UI render guidance+ // (request access link, re-paste token CTA) instead of just the prose.+ if (err.kind) setErrorMeta({ kind: err.kind, repo: err.repo });+ // Toast a one-line summary; the inline error card carries full prose.+ const firstLine = String(err.message || 'Image generation failed').split('\n')[0];+ toast.error(firstLine);} finally {setGenerating(false);setLocalProgress(null);+ setStage(null);endGenerate();+ // pendingQueued is reconciled by the polling effect (source of truth+ // is /api/media-jobs). Decrementing here would briefly undercount+ // before the next 4s tick reconciles.}};@@ -550,7 +655,7 @@ export default function ImageGen() {key={id}type="button"onClick={() => setSelectedMode(id)}- disabled={generating}+ disabled={statusLoading}className={`inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs transition-colors disabled:opacity-50 ${effectiveMode === id ? 'bg-port-accent text-white' : 'text-gray-400 hover:text-white hover:bg-port-border/40'}`}title={`Use ${label} for the next render`}>@@ -590,7 +695,7 @@ export default function ImageGen() {value={prompt}onChange={(e) => setPrompt(e.target.value)}rows={3}- disabled={generating}+ disabled={statusLoading}className="w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50 resize-y"placeholder="Describe the image you want to generate..."/>@@ -601,7 +706,7 @@ export default function ImageGen() {value={negativePrompt}onChange={(e) => setNegativePrompt(e.target.value)}rows={3}- disabled={generating}+ disabled={statusLoading}className="w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50 resize-y"placeholder="What to avoid..."/>@@ -617,7 +722,7 @@ export default function ImageGen() {<buttontype="button"onClick={() => setFlux2InstallOpen(true)}- disabled={generating}+ disabled={statusLoading}className="self-start sm:self-auto whitespace-nowrap inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-port-accent text-white text-xs font-medium hover:bg-port-accent/80 disabled:opacity-50"><Sparkles size={14} />@@ -639,7 +744,7 @@ export default function ImageGen() {<selectvalue={modelId}onChange={(e) => { setModelId(e.target.value); setSteps(''); setGuidance(''); }}- disabled={generating}+ disabled={statusLoading}className="w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50">{models.map((m) => <option key={m.id} value={m.id}>{m.name}</option>)}@@ -652,7 +757,7 @@ export default function ImageGen() {<selectvalue={resolutionLabel}onChange={handleResolutionChange}- disabled={generating}+ disabled={statusLoading}className="w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50">{RESOLUTIONS.map((r) => <option key={r.label} value={r.label}>{r.label}</option>)}@@ -671,14 +776,14 @@ export default function ImageGen() {type="number"value={seed}onChange={(e) => setSeed(e.target.value)}- disabled={generating}+ disabled={statusLoading}placeholder="Random"className="flex-1 bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50"/><buttontype="button"onClick={handleRandomSeed}- disabled={generating}+ disabled={statusLoading}className="p-2 text-gray-400 hover:text-white border border-port-border rounded-lg hover:bg-port-border/50 disabled:opacity-50 min-h-[40px] min-w-[40px] flex items-center justify-center"title="Randomize seed">@@ -698,7 +803,7 @@ export default function ImageGen() {value={steps}onChange={(e) => setSteps(e.target.value)}placeholder={String(currentModel?.steps || 25)}- disabled={generating}+ disabled={statusLoading}className="w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50"/></div>@@ -715,7 +820,7 @@ export default function ImageGen() {value={guidance}onChange={(e) => setGuidance(e.target.value)}placeholder={String(currentModel?.guidance ?? '')}- disabled={generating}+ disabled={statusLoading}className="w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50"/></div>@@ -725,7 +830,7 @@ export default function ImageGen() {<selectvalue={quantize}onChange={(e) => setQuantize(e.target.value)}- disabled={generating}+ disabled={statusLoading}className="w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50">{['3', '4', '5', '6', '8'].map((q) => <option key={q} value={q}>{q}-bit{q === '8' ? ' (default)' : q === '4' ? ' (fast)' : ''}</option>)}@@ -739,7 +844,7 @@ export default function ImageGen() {<inputtype="range" min={1} max={20} step={0.5}value={cfgScale}- disabled={generating}+ disabled={statusLoading}onChange={(e) => setCfgScale(Number(e.target.value))}className="w-full accent-port-accent"/>@@ -759,7 +864,7 @@ export default function ImageGen() {<inputtype="checkbox"checked={!!selected}- disabled={generating}+ disabled={statusLoading}onChange={(e) => {if (e.target.checked) setSelectedLoras((p) => [...p, { filename: lora.filename, name: lora.name, scale: 1.0 }]);else setSelectedLoras((p) => p.filter((s) => s.filename !== lora.filename));@@ -774,7 +879,7 @@ export default function ImageGen() {<inputtype="number" min={0} max={2} step={0.1}value={selected.scale}- disabled={generating}+ disabled={statusLoading}onChange={(e) => {const scale = parseFloat(e.target.value) || 0;setSelectedLoras((p) => p.map((s) => s.filename === lora.filename ? { ...s, scale } : s));@@ -806,7 +911,7 @@ export default function ImageGen() {<buttontype="button"onClick={handleClearInitImage}- disabled={generating}+ disabled={statusLoading}className="absolute -top-2 -right-2 w-5 h-5 rounded-full bg-port-card border border-port-border text-gray-300 hover:text-white hover:bg-port-error/40 flex items-center justify-center disabled:opacity-50"title="Remove init image">@@ -820,7 +925,7 @@ export default function ImageGen() {<inputtype="range" min={0} max={1} step={0.05}value={initImageStrength}- disabled={generating}+ disabled={statusLoading}onChange={(e) => setInitImageStrength(Number(e.target.value))}className="w-full accent-port-accent mt-1"/>@@ -831,37 +936,67 @@ export default function ImageGen() {<label className="flex items-center justify-center gap-2 w-full px-3 py-2 border border-dashed border-port-border rounded-lg text-xs text-gray-400 hover:text-white hover:border-port-accent cursor-pointer transition-colors"><ImageIcon className="w-4 h-4" />Upload image to remix (PNG/JPG/WebP)- <input type="file" accept="image/png,image/jpeg,image/webp" className="hidden" onChange={handlePickInitImage} disabled={generating} />+ <input type="file" accept="image/png,image/jpeg,image/webp" className="hidden" onChange={handlePickInitImage} disabled={statusLoading} /></label>)}</div>)}- <div className="flex items-center gap-2 pt-1">- {generating ? (+ <div className="flex items-center gap-2 pt-1 flex-wrap">+ <button+ type="submit"+ disabled={!prompt.trim() || notConnected}+ className="flex items-center gap-2 px-4 py-2 bg-port-accent hover:bg-port-accent/80 disabled:opacity-50 disabled:cursor-not-allowed text-white text-sm font-medium rounded-lg min-h-[40px]"+ >+ <Sparkles className="w-4 h-4" /> {generating ? 'Queue' : 'Generate'}+ </button>+ {generating && (<buttontype="button"onClick={handleCancel}- className="flex items-center gap-2 px-4 py-2 bg-port-error hover:bg-port-error/80 text-white text-sm font-medium rounded-lg min-h-[40px]"+ className="flex items-center gap-2 px-3 py-2 bg-port-error hover:bg-port-error/80 text-white text-sm font-medium rounded-lg min-h-[40px]">- <X className="w-4 h-4" /> Cancel- </button>- ) : (- <button- type="submit"- disabled={!prompt.trim() || notConnected}- className="flex items-center gap-2 px-4 py-2 bg-port-accent hover:bg-port-accent/80 disabled:opacity-50 disabled:cursor-not-allowed text-white text-sm font-medium rounded-lg min-h-[40px]"- >- <Sparkles className="w-4 h-4" /> Generate+ <X className="w-4 h-4" /> Cancel current</button>)}+ {pendingQueued > 0 && (+ <span className="text-xs px-2 py-1 rounded bg-port-accent/20 text-port-accent border border-port-accent/30">+ +{pendingQueued} queued+ </span>+ )}{progressPct != null && <span className="text-xs text-port-accent">{progressPct}%</span>}{(generating || error) && (<span className={`text-xs truncate ${error ? 'text-port-error' : 'text-gray-400'}`}>- {error || statusMsg || 'Working...'}+ {error ? String(error).split('\n')[0] : (stage ? (STAGE_LABELS[stage.name] || stage.name) : statusMsg) || 'Working...'}</span>)}</div>++ {error && (+ <div className="rounded-lg border border-port-error/40 bg-port-error/10 px-3 py-3 text-xs text-port-error space-y-2">+ <div className="font-semibold text-sm">+ {ERROR_HEADINGS[errorMeta?.kind] || 'Generation failed'}+ </div>+ <div className="whitespace-pre-wrap break-words text-port-warning/90">+ {String(error)}+ </div>+ {errorMeta?.kind === 'gated_repo' && errorMeta?.repo && (+ <a+ href={`https://huggingface.co/${errorMeta.repo}`}+ target="_blank"+ rel="noreferrer"+ className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-port-accent text-white text-xs font-medium hover:bg-port-accent/80"+ >+ Request access to {errorMeta.repo} ↗+ </a>+ )}+ {errorMeta?.kind === 'hf_unauthorized' && (+ <div className="text-port-warning/80">+ Paste a fresh token in the FLUX.2 banner above (it appears when the model needs one).+ </div>+ )}+ </div>+ )}</div><div className="bg-port-card border border-port-border rounded-xl p-4 space-y-2">@@ -880,9 +1015,14 @@ export default function ImageGen() {) : result ? (<img src={result.path} alt={result.prompt} decoding="async" className="w-full h-full object-contain" />) : generating ? (- <div className="text-gray-500 text-sm flex flex-col items-center gap-2">+ <div className="text-gray-500 text-sm flex flex-col items-center gap-2 px-4 text-center"><BrailleSpinner />- <span>{statusMsg || 'Starting diffusion...'}</span>+ <span className="font-medium text-gray-300">+ {stage ? (STAGE_LABELS[stage.name] || stage.name) : (statusMsg || 'Starting diffusion…')}+ </span>+ {stage?.detail && (+ <span className="text-[10px] text-gray-500 truncate max-w-[280px]">{stage.detail}</span>+ )}</div>) : (<div className="text-gray-600 text-xs flex flex-col items-center gap-1.5">diff --git a/client/src/services/api.js b/client/src/services/api.jsindex ebf5c18eb7..f826973a9a 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -36,6 +36,7 @@ export * from './apiPalette.js';export * from './apiDashboard.js';export * from './apiAsk.js';export * from './apiImageVideo.js';+export * from './apiMediaJobs.js';// Default export for simplified imports (get/post/put/delete helpers)export { default } from './apiCore.js';diff --git a/scripts/flux2_macos.py b/scripts/flux2_macos.pyindex f027754600..5a178d9285 100755--- a/scripts/flux2_macos.py+++ b/scripts/flux2_macos.py@@ -96,8 +96,15 @@ def load_pipeline_sdnq(repo: str, tokenizer_repo: str, device: str, dtype):from diffusers import Flux2KleinPipelinefrom transformers import AutoTokenizer+ # STAGE markers are parsed by server/services/imageGen/local.js#handleLine+ # and emitted as `stage` SSE events so the UI can show "Downloading model+ # weights (~8 GB on first run)" instead of a misleading "step 0/8". The+ # tokenizer is small (a few MB), the pipeline + transformer is the big+ # ~8 GB SDNQ-quantized weights download — flagged as `download-pipeline`.+ print(f"STAGE:download-tokenizer:{tokenizer_repo}", file=sys.stderr, flush=True)print(f"🔧 sdnq: tokenizer ← {tokenizer_repo}", file=sys.stderr)tokenizer = AutoTokenizer.from_pretrained(tokenizer_repo, subfolder="tokenizer", use_fast=False)+ print(f"STAGE:download-pipeline:{repo}", file=sys.stderr, flush=True)print(f"🔧 sdnq: pipeline ← {repo}", file=sys.stderr)pipe = Flux2KleinPipeline.from_pretrained(repo,@@ -105,6 +112,7 @@ def load_pipeline_sdnq(repo: str, tokenizer_repo: str, device: str, dtype):torch_dtype=dtype,low_cpu_mem_usage=True,)+ print("STAGE:move-to-device", file=sys.stderr, flush=True)pipe.to(device)return pipe@@ -120,13 +128,16 @@ def load_pipeline_int8(repo: str, base_repo: str, device: str, dtype):sys.path.insert(0, str(Path(__file__).resolve().parent))from flux2_quantized import QuantizedFlux2Transformer2DModel+ print(f"STAGE:download-int8-snapshot:{repo}", file=sys.stderr, flush=True)print(f"🔧 int8: snapshot ← {repo}", file=sys.stderr)model_path = snapshot_download(repo)+ print("STAGE:load-transformer", file=sys.stderr, flush=True)print("🔧 int8: transformer …", file=sys.stderr)qtransformer = QuantizedFlux2Transformer2DModel.from_pretrained(model_path)qtransformer.to(device=device, dtype=dtype)+ print("STAGE:load-text-encoder", file=sys.stderr, flush=True)print("🔧 int8: text encoder …", file=sys.stderr)# AutoModelForCausalLM picks the right class from the config# (Qwen3ForCausalLM here). transformers>=4.51 ships Qwen3 in-tree so we@@ -171,12 +182,33 @@ def apply_memory_optimizations(pipe) -> None:vae.enable_tiling()-def make_stepwise_callback(stepwise_dir: str, pipe):+def _unpack_flux2_latents(latents, height: int, width: int, vae_scale: int = 8, patch: int = 2):+ """Convert Flux2 transformer-packed latents `(B, num_patches, C*P*P)` back+ to the VAE-friendly `(B, C, H_lat, W_lat)` layout.++ For 1024×576 with vae_scale=8 patch=2: `(1, 2304, 128)` → `(1, 16, 72, 128)`+ (2304 = 36×64 patches, 128 = 16 channels × 2×2 patch). diffusers' own+ `_unpack_latents_with_ids` requires an `x_ids` tensor not exposed to the+ callback, so we do the math ourselves.+ """+ bsz, num_patches, ch_packed = latents.shape+ h = height // vae_scale // patch+ w = width // vae_scale // patch+ c = ch_packed // (patch * patch)+ if h * w != num_patches or c * patch * patch != ch_packed:+ raise ValueError(+ f"unpack mismatch: latents={tuple(latents.shape)} expected "+ f"num_patches={h*w} channels_packed={c*patch*patch} for {height}x{width}"+ )+ latents = latents.view(bsz, h, w, c, patch, patch)+ latents = latents.permute(0, 3, 1, 4, 2, 5)+ return latents.reshape(bsz, c, h * patch, w * patch)+++def make_stepwise_callback(stepwise_dir: str, pipe, height: int, width: int):"""Return a `callback_on_step_end` that decodes the running latent into asmall preview PNG. local.js's `processLatestFrame` watches this dir and- streams the freshest frame to the SSE client. Match mflux's filename- shape (`step_<N>.png`, no zero padding) so the existing parser sorts- by mtime and picks the latest correctly."""+ streams the freshest frame to the SSE client."""if not stepwise_dir:return None@@ -205,12 +237,14 @@ def make_stepwise_callback(stepwise_dir: str, pipe):# Best-effort decode. Errors here must not abort generation — the# final image is still produced after the last step.try:+ # Flux2 latents arrive packed (B, num_patches, C*p*p). VAE expects+ # (B, C, H, W). Skip unpack if it's already 4-D (future-proof).+ if latents.dim() == 3:+ latents = _unpack_flux2_latents(latents, height, width)decoded = vae.decode(latents / scaling + shift, return_dict=False)[0]decoded = (decoded.clamp(-1, 1) + 1) / 2arr = (decoded[0].float().cpu().permute(1, 2, 0).numpy() * 255).astype("uint8")img = Image.fromarray(arr)- # Cap preview size — fs.watch + base64 encode every step is fine- # for 256px thumbnails but wasteful at 1024px.img.thumbnail((512, 512), Image.LANCZOS)img.save(out / f"step_{step_index + 1}.png", "PNG", optimize=False)fired["saved"] += 1@@ -283,7 +317,7 @@ def main() -> None:(int(args.width), int(args.height)), Image.LANCZOS)- callback = make_stepwise_callback(args.stepwise_image_output_dir, pipe)+ callback = make_stepwise_callback(args.stepwise_image_output_dir, pipe, int(args.height), int(args.width))# Flux2KleinPipeline.__call__ doesn't always accept negative_prompt or# strength — passing an unsupported kwarg raises TypeError. Filter to# what the live signature actually accepts.@@ -314,6 +348,7 @@ def main() -> None:if args.image_strength is not None and "strength" in accepted:pipe_kwargs["strength"] = float(args.image_strength)+ print("STAGE:inference", file=sys.stderr, flush=True)print(f"🎨 flux2 generate seed={seed} {args.width}x{args.height} steps={args.steps} "f"guidance={args.guidance} device={device}",@@ -362,5 +397,84 @@ def main() -> None:print(f"✅ flux2 saved {args.output} (seed={seed})", file=sys.stderr)+def _emit_user_error(kind: str, message: str, repo: str = "") -> None:+ """Emit a structured single-line error the server's stderr parser picks up+ for the SSE error event. `kind` is a stable identifier the UI maps to a+ friendly heading; `message` is the human prose; `repo` (optional) is the+ HF repo to deep-link the user to so they can request access / check token."""+ line = f"USER_ERROR:{kind}"+ if repo:+ line += f":{repo}"+ print(line, file=sys.stderr, flush=True)+ print(f"❌ {message}", file=sys.stderr, flush=True)++if __name__ == "__main__":- main()+ try:+ main()+ except KeyboardInterrupt:+ sys.exit(130)+ except SystemExit:+ raise+ except Exception as err:+ # Top-level safety net — every error type we recognise gets a friendly+ # USER_ERROR: line so the UI can surface "request access at <link>"+ # instead of bare "Exit code 1". Anything we don't recognise still+ # falls through to a printed traceback above + a generic USER_ERROR+ # below, so the user sees *something* actionable.+ from huggingface_hub.errors import GatedRepoError, RepositoryNotFoundError, HfHubHTTPError+ # Walk the cause chain — diffusers wraps HF errors in OSError, so the+ # innermost exception is what tells us the real story.+ chain = []+ cur = err+ while cur is not None:+ chain.append(cur)+ cur = cur.__cause__ or cur.__context__+ def _repo_from_hf_error(hf_err):+ """huggingface_hub doesn't always populate `repo_id` on the error.+ Fall back to parsing the failing URL — `/<owner>/<repo>/resolve/...`+ for file downloads or `/api/models/<owner>/<repo>` for API hits."""+ repo = getattr(hf_err, "repo_id", None) or ""+ if repo:+ return repo+ url = getattr(getattr(hf_err, "response", None), "url", None) or \+ getattr(getattr(hf_err, "request", None), "url", None)+ if url is None:+ return ""+ path = str(url).split("huggingface.co", 1)[-1].lstrip("/")+ parts = path.split("/")+ if parts[:1] == ["api"] and len(parts) >= 4 and parts[1] in {"models", "datasets", "spaces"}:+ return f"{parts[2]}/{parts[3]}"+ if len(parts) >= 2 and parts[0] not in {"api", "settings", "join"}:+ return f"{parts[0]}/{parts[1]}"+ return ""++ gated = next((e for e in chain if isinstance(e, GatedRepoError)), None)+ notfound = next((e for e in chain if isinstance(e, RepositoryNotFoundError)), None)+ http = next((e for e in chain if isinstance(e, HfHubHTTPError)), None)+ if gated is not None:+ repo = _repo_from_hf_error(gated)+ url = f"https://huggingface.co/{repo}" if repo else "https://huggingface.co/"+ _emit_user_error(+ "gated_repo",+ f"Access to {repo or 'the model repo'} is restricted. Visit {url} "+ f"to request access, then make sure your HF token is set in PortOS.",+ repo,+ )+ sys.exit(2)+ status = getattr(getattr(http, "response", None), "status_code", None) if http else None+ if status == 401:+ _emit_user_error(+ "hf_unauthorized",+ "HuggingFace rejected the token (401). Check that the token is valid "+ "and has read access, then re-paste it in PortOS.",+ )+ sys.exit(2)+ if notfound is not None:+ repo = _repo_from_hf_error(notfound)+ _emit_user_error("repo_not_found", f"HF repo not found: {repo or '(unknown)'}", repo)+ sys.exit(2)+ # Unknown failure — emit the original traceback (already printed above)+ # plus a generic structured marker so the UI shows something useful.+ _emit_user_error("unknown", f"{type(err).__name__}: {err}")+ raisediff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.jsindex 43341a4485..421eadce7a 100644--- a/server/services/imageGen/local.js+++ b/server/services/imageGen/local.js@@ -305,35 +305,70 @@ export async function generateImage({ pythonPath, prompt, negativePrompt = '', m// would grow this buffer for the full duration of a long render.const STDERR_TAIL_BYTES = 64 * 1024;let stderrBuffer = '';+ // Returns true when the line drove a progress event (so the pm2-log echo+ // below skips it — progress bars are spammy and already visible in the UI).+ // Status / debug / error lines fall through to console.log so a stuck render+ // (model download, HF auth probe, weight load) shows up in pm2 logs instead+ // of vanishing into the SSE channel only the browser ever sees.+ // Phase tracking. Lifecycle events from the runner (STAGE:download-pipeline,+ // STAGE:inference, etc.) flip the phase so the UI can show "Downloading+ // model weights" instead of misleading "step 0/8" while HF pulls multi-GB+ // shards. Inference progress events also tag themselves with the current+ // phase so the client knows whether `step/total` reflects download chunks+ // (out of N safetensors files) or actual generation steps.+ let currentPhase = 'starting';const handleLine = (line) => {const trimmed = line.trim();- if (!trimmed || PYTHON_NOISE_RE.test(trimmed)) return;- // mflux progress: "100%|████| 8/8 [00:05<00:00, 1.43it/s]"+ if (!trimmed || PYTHON_NOISE_RE.test(trimmed)) return true;++ if (trimmed.startsWith('STAGE:')) {+ const rest = trimmed.slice(6); // strip 'STAGE:'+ const colon = rest.indexOf(':');+ const stage = colon === -1 ? rest : rest.slice(0, colon);+ const detail = colon === -1 ? '' : rest.slice(colon + 1);+ currentPhase = stage;+ broadcastSse(job, { type: 'stage', stage, detail });+ return true;+ }+const m = trimmed.match(/(\d+)%\|.*?(\d+)\/(\d+)/);if (m) {const pct = parseInt(m[1], 10) / 100;const step = parseInt(m[2], 10);const total = parseInt(m[3], 10);- broadcastSse(job, { type: 'progress', progress: pct, message: trimmed });- imageGenEvents.emit('progress', { generationId: jobId, progress: pct, step, totalSteps: total });- if (activeJob && activeJob.generationId === jobId) {- activeJob.progress = pct; activeJob.step = step; activeJob.totalSteps = total;+ broadcastSse(job, { type: 'progress', progress: pct, message: trimmed, phase: currentPhase });+ // Only forward to imageGenEvents (which drives the UI step counter)+ // when we're actually in the inference phase — download tqdm bars+ // count safetensors files, not diffusion steps.+ if (currentPhase === 'inference') {+ imageGenEvents.emit('progress', { generationId: jobId, progress: pct, step, totalSteps: total });+ if (activeJob && activeJob.generationId === jobId) {+ activeJob.progress = pct; activeJob.step = step; activeJob.totalSteps = total;+ }}- } else {- broadcastSse(job, { type: 'status', message: trimmed });+ return true;}+ broadcastSse(job, { type: 'status', message: trimmed });+ return false;};+ const shortId = jobId.slice(0, 8);proc.stderr.on('data', (chunk) => {const text = chunk.toString();stderrBuffer += text;if (stderrBuffer.length > STDERR_TAIL_BYTES) {stderrBuffer = stderrBuffer.slice(-STDERR_TAIL_BYTES);}- for (const line of text.split(/[\n\r]+/)) handleLine(line);+ for (const line of text.split(/[\n\r]+/)) {+ const trimmed = line.trim();+ if (!handleLine(line) && trimmed) console.log(`🐍 [${shortId}] ${trimmed}`);+ }});proc.stdout.on('data', (chunk) => {- for (const line of chunk.toString().split(/[\n\r]+/)) handleLine(line);+ for (const line of chunk.toString().split(/[\n\r]+/)) {+ const trimmed = line.trim();+ if (!handleLine(line) && trimmed) console.log(`🐍-out [${shortId}] ${trimmed}`);+ }});proc.on('close', async (code, signal) => {@@ -344,10 +379,35 @@ export async function generateImage({ pythonPath, prompt, negativePrompt = '', mif (code !== 0) {job.status = 'error';const reason = signal ? `Killed by signal ${signal}` : `Exit code ${code}`;- const tail = stderrBuffer.trim().split('\n').slice(-10).join('\n');- console.log(`❌ Image generation failed [${jobId.slice(0, 8)}]: ${reason}`);- broadcastSse(job, { type: 'error', error: `Generation failed: ${reason}\n${tail}` });- imageGenEvents.emit('failed', { generationId: jobId, error: reason });+ // Extract a structured user-error if the runner emitted one+ // (USER_ERROR:gated_repo:black-forest-labs/FLUX.2-klein-9B), and find+ // the matching `❌ …` prose line that follows it. Fall back to the last+ // 10 stderr lines if no structured error was emitted (unknown crash).+ const lines = stderrBuffer.split('\n').map((l) => l.trim()).filter(Boolean);+ const structIdx = lines.findIndex((l) => l.startsWith('USER_ERROR:'));+ let userMessage = null;+ let userKind = null;+ let userRepo = null;+ if (structIdx >= 0) {+ // Split with limit=2 so a kind containing colons can't shred the repo.+ const [kind, ...rest] = lines[structIdx].slice('USER_ERROR:'.length).split(':');+ userKind = kind;+ userRepo = rest.join(':') || null;+ const proseIdx = lines.findIndex((l, i) => i > structIdx && l.startsWith('❌'));+ userMessage = proseIdx >= 0 ? lines[proseIdx].replace(/^❌\s*/, '') : null;+ }+ const tail = lines.slice(-10).join('\n');+ const errorText = userMessage+ ? `${userMessage}\n\n(diagnostic) ${reason}`+ : `Generation failed: ${reason}\n${tail}`;+ console.log(`❌ Image generation failed [${jobId.slice(0, 8)}]: ${userMessage || reason}`);+ job.error = userMessage || reason;+ job.errorKind = userKind;+ job.errorRepo = userRepo;+ broadcastSse(job, { type: 'error', error: errorText, kind: userKind, repo: userRepo });+ // Propagate the friendly message (not the raw "Exit code 1") to the+ // job queue so its `failed` log line and future SSE replays carry it.+ imageGenEvents.emit('failed', { generationId: jobId, error: userMessage || reason });} else {job.status = 'complete';// Sidecar: persist a metadata record next to the PNG so the gallery