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): in-app FLUX.2 venv installer + HF token entry
Adam Eivyc9f7f1a248db
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex f7bb5b1ba4..16b49a803f 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,8 @@## Added+- **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.- **Creative Director — autonomous long-form video projects** (`/media/creative-director`). Configure a project with a fixed aspect ratio, quality, model, target duration (up to 10 min), style spec, and optional starting image or user-supplied story. A CoS-driven agent writes a scene-by-scene treatment, kicks off 1–10s segment renders one at a time (continuing from each prior segment's last frame or starting fresh from a new image), evaluates output thumbnails against the style spec via its own multimodal review, and self-perpetuates until the episode is complete. On completion the server auto-creates a video-timeline project and renders the final concat into a single mp4. All segments + the final cut are grouped in an auto-created media collection. New routes (`/api/creative-director/*`), data file (`data/creative-director-projects.json`), preset tables (`server/lib/creativeDirectorPresets.js`), agent prompts (`server/lib/creativeDirectorPrompts.js`), and UI tabs (Overview / Treatment / Segments / Runs).- **Unified media job queue** (`server/services/mediaJobQueue/`) for image and video gen. Replaces the per-provider 409 BUSY error with a FIFO that accepts every submission immediately and returns `{ jobId, status: 'queued', position }`. A single worker drains serially (image and video share Metal/MLX runtime, so parallelism would OOM anyway). Persists to `data/media-jobs.json`; on boot any job stuck in `running` is reclassified `failed (interrupted by restart)`. SSE on `/api/{video,image}-gen/:jobId/events` covers the full `queued → started → progress → complete/failed` lifecycle so existing UIs keep working without changes. New `/api/media-jobs` lets the UI inspect and cancel queued/running renders.@@ -24,9 +26,12 @@## Fixed-- **`scripts/setup-data.js` now merges missing keys into known structured JSON seeds.** File-level copy-if-missing didn't help when the destination JSON already existed but was missing newly-added entries — so adding a new prompt stage to `data.sample/prompts/stage-config.json` never reached existing installs (their `data/prompts/stage-config.json` already existed, got skipped, agent task threw "Stage X not found" at runtime). The setup script now also walks two known structured JSONs (`prompts/stage-config.json` under `stages`, `prompts/variables.json` under `variables`) and merges any missing top-level entries from `data.sample/` into the user's copy without overwriting customizations. Caveat: if a user deliberately deleted a starter entry it'll come back on the next run — accepted trade-off vs. silent drift on upgrade. Future structured seeds opt in by adding an entry to `JSON_MERGE_TARGETS`.+- **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.+- **Creative Director smoke-test fixture is ~2× faster.** Drops scene `durationSeconds` from 3s → 2s and switches `aspectRatio` from `1:1` (512×512) to a new hidden `1:1-small` preset (384×384, ~44% fewer pixels) — total compute budget goes from `3 × 3s × 512²` to `3 × 2s × 384²`, roughly a 63% pixel-frame reduction. The smaller preset is registered in `ASPECT_PRESETS` only (not `ASPECT_RATIOS`), so the user-facing dropdown and route validation surface stay unchanged; the smoke route bypasses validation by constructing the project internally. `targetDurationSeconds` updated to 6 to match (3 × 2s). Lets the post-pipeline-change health check finish in render time only without waiting on full-resolution clips.-- **Creative Director agent prompts moved into the Prompts Manager.** `buildTreatmentPrompt` and `buildEvaluatePrompt` (in `server/lib/creativeDirectorPrompts.js`) now compute a flat view object and delegate to `buildPrompt('cd-treatment', view)` / `buildPrompt('cd-evaluate', view)`. The actual prompt text lives in `data/prompts/stages/cd-treatment.md` and `cd-evaluate.md` — editable from the Prompts Manager UI without code changes. The view object precomputes everything the template engine can't (aspect dims, render params, multi-frame list with timeline-position labels, scene strategy line, retry budget delta), so authors can rearrange wording and sections freely. `agentBridge.js` updated to await the now-async builders. The two new stages ship as starters under `data.sample/prompts/stages/cd-{treatment,evaluate}.md` plus `cd-*` entries in `data.sample/prompts/stage-config.json` — `npm run setup` / `npm run setup:data` copies them into `data/prompts/` on fresh installs (and fills in any missing files on existing installs without overwriting user customizations).+- **Creative Director agent prompts moved into the Prompts Manager.** `buildTreatmentPrompt` and `buildEvaluatePrompt` (in `server/lib/creativeDirectorPrompts.js`) now compute a flat view object and delegate to `buildPrompt('cd-treatment', view)` / `buildPrompt('cd-evaluate', view)`. The actual prompt text lives in `data/prompts/stages/cd-treatment.md` and `cd-evaluate.md` — editable from the Prompts Manager UI without code changes. The view object precomputes everything the template engine can't (aspect dims, render params, multi-frame list with timeline-position labels, scene strategy line, retry budget delta), so authors can rearrange wording and sections freely. `agentBridge.js` updated to await the now-async builders. The two new stages plus their templates ship as starters in `data.sample/prompts/stages/cd-treatment.md`, `cd-evaluate.md`, and the `cd-*` entries in `data.sample/prompts/stage-config.json` — `npm run setup` / `npm run setup:data` copies them into `data/prompts/` on fresh installs (and fills in any missing files on existing installs without overwriting user customizations).- **Prompt template engine upgraded to support dot notation.** `server/lib/promptTemplate.js` ships an enhanced Mustache-flavored renderer that handles `{{a.b.c}}` lookups, object section scopes (`{{#user}}{{first}}{{/user}}`), array iteration with parent-scope fall-through (so `{{project.id}}` still resolves inside `{{#frames}}`), `{{.}}` for primitive iteration items, inverted sections (`{{^x}}`), and triple-mustache (`{{{x}}}`). Routed through `server/services/promptService.js#buildPrompt` so every PortOS template (including legacy ones like `cos-evaluate.md` that were silently leaving `{{metadata.context}}` literals in the output because the upstream toolkit's `\w+`-only regex doesn't match dots) now renders correctly. Storage stays in the toolkit (`stage-config.json`, `variables.json`, `.md` files); only the templating step is local. 17 engine tests + 12 CD prompt-rendering tests cover the surface.- **Creative Director multi-frame evaluator sampling.** The cognitive evaluator previously only Read the rendered video's frame-0 thumbnail, so 5s i2v scenes whose intent develops mid- or late-clip (archway appearing, light bloom, particles converging) were getting rejected even when the render delivered. The server now samples 5 evenly-spaced frames at render-completion time via a new `extractEvaluationFrames()` helper in `server/lib/ffmpeg.js` (probes total frames with `ffprobe`, then uses `ffmpeg -vf "select='eq(n,0)+eq(n,N/4)+eq(n,N/2)+eq(n,3*N/4)+eq(n,N-1)'" -vsync vfr`), writes them as `<jobId>-f1.jpg ... -f5.jpg` in `data/video-thumbnails/`, persists the basenames to `scene.evaluationFrames`, and `buildEvaluatePrompt` now lists every frame with timeline position tags ("start (0%)", "~50% through", "end (~100%)") and instructs the agent to Read each one. Includes explicit "intent that arrives late still counts as delivered" guidance to fix the false-reject pattern observed on the first real E2E run. Falls back to single-thumbnail Read when extraction fails (ffmpeg/ffprobe missing, probe returns 0 frames).- **Creative Director stuck projects now self-recover** — `completionHook` always re-evaluates project state after any CD task completes (regardless of task kind), so legacy `scene`-kind tasks from before the treatment/evaluate split no longer leave a project frozen. PATCHing a scene to a terminal status (`accepted` or `failed`) also nudges the orchestrator to start the next scene immediately.diff --git a/client/src/components/imageGen/Flux2InstallModal.jsx b/client/src/components/imageGen/Flux2InstallModal.jsxnew file mode 100644index 0000000000..96b7419dfd--- /dev/null+++ b/client/src/components/imageGen/Flux2InstallModal.jsx@@ -0,0 +1,289 @@+/**+ * FLUX.2 venv installer modal. Streams progress from+ * GET /api/image-gen/setup/flux2-install (SSE) and animates a 5-stage pipeline+ * so the user sees something is happening during the multi-GB torch download.+ *+ * Stages match the events emitted by installFlux2Venv() in pythonSetup.js:+ * detect → venv → upgrade-pip → install → verify → complete+ *+ * Closing the modal mid-install (X button or backdrop click) terminates the+ * EventSource, which the server interprets as a cancel and SIGTERMs pip.+ */++import { useEffect, useRef, useState } from 'react';+import { CheckCircle2, Loader2, AlertCircle, Download, X } from 'lucide-react';+import { safeParseJSON } from '../../lib/genUtils';++// Cap on retained log lines. A torch install can emit hundreds of pip output+// lines; without this the array grows unbounded and re-renders cost more per+// append (slice copy is O(n) but n is bounded).+const MAX_LOG_LINES = 500;++const STAGES = [+ { id: 'detect', label: 'Detect Python' },+ { id: 'venv', label: 'Create venv' },+ { id: 'upgrade-pip', label: 'Upgrade pip' },+ { id: 'install', label: 'Install packages' },+ { id: 'verify', label: 'Verify' },+];++const STAGE_INDEX = Object.fromEntries(STAGES.map((s, i) => [s.id, i]));++export default function Flux2InstallModal({ open, onClose, onComplete }) {+ const [currentStage, setCurrentStage] = useState(null);+ const [logs, setLogs] = useState([]);+ const [done, setDone] = useState(false);+ const [error, setError] = useState(null);+ const [confirmingCancel, setConfirmingCancel] = useState(false);+ const logsEndRef = useRef(null);+ const esRef = useRef(null);+ // Stash onComplete in a ref so the EventSource effect doesn't re-run (and+ // tear down the SSE connection) every time the parent re-renders with a+ // fresh inline arrow. Without this, ImageGen's frequent state churn+ // (gallery, generating, localProgress) would kill the install mid-stream.+ const onCompleteRef = useRef(onComplete);+ useEffect(() => { onCompleteRef.current = onComplete; }, [onComplete]);++ const appendLog = (entry) => setLogs((prev) => {+ const next = prev.length >= MAX_LOG_LINES ? [...prev.slice(-(MAX_LOG_LINES - 1)), entry] : [...prev, entry];+ return next;+ });++ useEffect(() => {+ if (!open) {+ setCurrentStage(null);+ setLogs([]);+ setDone(false);+ setError(null);+ setConfirmingCancel(false);+ if (esRef.current) { esRef.current.close(); esRef.current = null; }+ return;+ }++ const es = new EventSource('/api/image-gen/setup/flux2-install');+ esRef.current = es;++ es.onmessage = (ev) => {+ const msg = safeParseJSON(ev.data);+ if (!msg) return;+ if (msg.type === 'stage') {+ setCurrentStage(msg.stage);+ appendLog({ kind: 'stage', text: msg.message || msg.stage });+ } else if (msg.type === 'log') {+ appendLog({ kind: 'log', text: msg.message });+ } else if (msg.type === 'complete') {+ setDone(true);+ appendLog({ kind: 'success', text: msg.message });+ es.close();+ esRef.current = null;+ onCompleteRef.current?.();+ } else if (msg.type === 'error') {+ setError(msg.message);+ appendLog({ kind: 'error', text: msg.message });+ es.close();+ esRef.current = null;+ }+ };++ es.onerror = () => {+ // Network drop or server killed the stream. If we already saw `complete`+ // this is harmless; otherwise surface it so the user isn't stuck on a+ // forever-spinning modal.+ setError((prev) => prev ?? (done ? null : 'Connection to installer lost. Restart PortOS or try again.'));+ es.close();+ esRef.current = null;+ };++ return () => {+ if (esRef.current) { esRef.current.close(); esRef.current = null; }+ };+ // onComplete intentionally excluded — it lives in onCompleteRef.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [open]);++ // Auto-scroll on every log line. `behavior: 'auto'` (instant) avoids+ // queueing hundreds of smooth-scroll animations during a chatty pip install.+ useEffect(() => {+ if (logsEndRef.current) {+ logsEndRef.current.scrollIntoView({ behavior: 'auto', block: 'end' });+ }+ }, [logs.length]);++ if (!open) return null;++ const installRunning = !done && !error && currentStage && currentStage !== 'verify';++ const performClose = () => {+ if (esRef.current) { esRef.current.close(); esRef.current = null; }+ onClose();+ };++ const handleClose = () => {+ if (installRunning) { setConfirmingCancel(true); return; }+ performClose();+ };++ const stageIdx = currentStage ? STAGE_INDEX[currentStage] ?? -1 : -1;++ return (+ <div className="fixed inset-0 z-[9999] flex items-start justify-center pt-[8vh]">+ <div+ className="absolute inset-0 bg-black/70 backdrop-blur-sm"+ onClick={handleClose}+ aria-hidden="true"+ />+ <div+ role="dialog"+ aria-modal="true"+ aria-labelledby="flux2-install-title"+ className="relative w-full max-w-2xl mx-4 bg-port-card rounded-xl border border-port-border shadow-2xl overflow-hidden flex flex-col max-h-[80vh]"+ >+ {/* Header */}+ <div className="flex items-center justify-between px-5 py-4 border-b border-port-border">+ <div className="flex items-center gap-2.5">+ <Download size={18} className="text-port-accent" />+ <h2 id="flux2-install-title" className="text-sm font-semibold text-white">+ Installing FLUX.2 Runtime+ </h2>+ </div>+ <button+ onClick={handleClose}+ className="text-gray-400 hover:text-white p-1"+ aria-label="Close installer"+ >+ <X size={18} />+ </button>+ </div>++ {/* Stage pipeline */}+ <div className="px-5 py-4 border-b border-port-border bg-port-bg/40">+ <div className="flex items-center justify-between gap-2">+ {STAGES.map((s, i) => {+ const isDone = done || stageIdx > i;+ const isCurrent = !done && stageIdx === i && !error;+ const isFailed = error && stageIdx === i;+ return (+ <div key={s.id} className="flex-1 flex flex-col items-center">+ <div className="flex items-center w-full">+ <div+ className={`flex items-center justify-center w-8 h-8 rounded-full border-2 transition-colors ${+ isFailed+ ? 'border-port-error bg-port-error/20 text-port-error'+ : isDone+ ? 'border-port-success bg-port-success/20 text-port-success'+ : isCurrent+ ? 'border-port-accent bg-port-accent/20 text-port-accent'+ : 'border-port-border bg-port-bg text-gray-500'+ }`}+ >+ {isFailed ? (+ <AlertCircle size={16} />+ ) : isDone ? (+ <CheckCircle2 size={16} />+ ) : isCurrent ? (+ <Loader2 size={16} className="animate-spin" />+ ) : (+ <span className="text-[10px] font-bold">{i + 1}</span>+ )}+ </div>+ {i < STAGES.length - 1 && (+ <div+ className={`flex-1 h-0.5 mx-1 transition-colors ${+ isDone ? 'bg-port-success' : 'bg-port-border'+ }`}+ />+ )}+ </div>+ <span+ className={`mt-2 text-[10px] text-center leading-tight ${+ isCurrent ? 'text-port-accent font-medium' : 'text-gray-400'+ }`}+ >+ {s.label}+ </span>+ </div>+ );+ })}+ </div>+ </div>++ {/* Live log */}+ <div className="flex-1 overflow-auto bg-port-bg px-4 py-3 font-mono text-[11px] leading-relaxed">+ {logs.length === 0 ? (+ <div className="text-gray-500 italic flex items-center gap-2">+ <Loader2 size={12} className="animate-spin" />+ Connecting to installer…+ </div>+ ) : (+ logs.map((entry, i) => (+ <div+ key={i}+ className={+ entry.kind === 'stage'+ ? 'text-port-accent font-semibold mt-1'+ : entry.kind === 'success'+ ? 'text-port-success font-semibold'+ : entry.kind === 'error'+ ? 'text-port-error'+ : 'text-gray-400'+ }+ >+ {entry.kind === 'stage' && '▸ '}+ {entry.text}+ </div>+ ))+ )}+ <div ref={logsEndRef} />+ </div>++ {/* Footer */}+ <div className="px-5 py-3 border-t border-port-border flex items-center justify-between gap-3">+ {confirmingCancel ? (+ <>+ <span className="text-xs text-port-warning">+ Cancel the install? In-progress downloads will stop.+ </span>+ <div className="flex gap-2">+ <button+ onClick={() => setConfirmingCancel(false)}+ className="px-3 py-1.5 rounded-lg text-xs font-medium bg-port-border text-gray-300 hover:bg-port-border/70"+ >+ Keep installing+ </button>+ <button+ onClick={performClose}+ className="px-3 py-1.5 rounded-lg text-xs font-medium bg-port-error text-white hover:bg-port-error/80"+ >+ Yes, cancel+ </button>+ </div>+ </>+ ) : (+ <>+ <span className="text-xs text-gray-400">+ {done+ ? '✅ FLUX.2 is ready. You can close this window.'+ : error+ ? '⚠️ Installer hit an error — see logs above.'+ : 'Downloading torch + diffusers from PyPI/git. ~3-10 minutes on first run.'}+ </span>+ <button+ onClick={handleClose}+ disabled={!done && !error && !currentStage}+ className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${+ done+ ? 'bg-port-success text-white hover:bg-port-success/80'+ : error+ ? 'bg-port-border text-white hover:bg-port-border/70'+ : 'bg-port-border text-gray-300 hover:bg-port-border/70 disabled:opacity-50'+ }`}+ >+ {done ? 'Done' : error ? 'Close' : 'Cancel'}+ </button>+ </>+ )}+ </div>+ </div>+ </div>+ );+}diff --git a/client/src/components/imageGen/Flux2TokenBanner.jsx b/client/src/components/imageGen/Flux2TokenBanner.jsxnew file mode 100644index 0000000000..6eb5a720f7--- /dev/null+++ b/client/src/components/imageGen/Flux2TokenBanner.jsx@@ -0,0 +1,75 @@+/**+ * Inline HF_TOKEN entry for the Image Gen page. Replaces the static+ * "export HF_TOKEN=… before running PortOS" instruction with a paste-and-save+ * form that stores the token in settings.json (which the local-image worker+ * reads when spawning flux2_macos.py).+ *+ * Single-user app behind Tailscale — see CLAUDE.md security model — so a+ * plaintext settings entry is the appropriate trade-off vs. a separate+ * keystore.+ */++import { useState } from 'react';+import { Key, Loader2 } from 'lucide-react';+import toast from '../ui/Toast';+import apiCore from '../../services/apiCore';++export default function Flux2TokenBanner({ licenseUrl, onSaved }) {+ const [token, setToken] = useState('');+ const [saving, setSaving] = useState(false);++ const handleSave = async () => {+ const trimmed = token.trim();+ if (!trimmed) return;+ setSaving(true);+ // apiCore.post toasts the error itself on non-2xx; swallow the throw so+ // we leave saving=false either way and don't double-toast.+ const result = await apiCore.post('/image-gen/setup/flux2-token', { token: trimmed }).catch(() => null);+ setSaving(false);+ if (!result?.ok) return;+ setToken('');+ toast.success('HuggingFace token saved');+ onSaved?.();+ };++ return (+ <div className="rounded-lg border border-port-warning/40 bg-port-warning/10 px-3 py-3 text-xs text-port-warning space-y-2">+ <div>+ FLUX.2-klein is a gated model. Accept the license at{' '}+ <a href={licenseUrl} target="_blank" rel="noreferrer" className="underline text-white">+ huggingface.co/black-forest-labs/FLUX.2-klein-4B+ </a>+ , then create a read token at{' '}+ <a href="https://huggingface.co/settings/tokens" target="_blank" rel="noreferrer" className="underline text-white">+ huggingface.co/settings/tokens+ </a>{' '}+ and paste it below.+ </div>+ <div className="flex flex-col sm:flex-row gap-2 items-stretch sm:items-center">+ <div className="flex items-center gap-1.5 flex-1 bg-port-bg border border-port-border rounded-lg px-2 py-1.5">+ <Key size={14} className="text-gray-400 flex-shrink-0" />+ <input+ type="password"+ value={token}+ onChange={(e) => setToken(e.target.value)}+ onKeyDown={(e) => { if (e.key === 'Enter') handleSave(); }}+ disabled={saving}+ placeholder="hf_…"+ autoComplete="off"+ spellCheck={false}+ className="flex-1 bg-transparent text-white text-xs focus:outline-none disabled:opacity-50"+ />+ </div>+ <button+ type="button"+ onClick={handleSave}+ disabled={saving || !token.trim()}+ className="whitespace-nowrap inline-flex items-center justify-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"+ >+ {saving ? <Loader2 size={14} className="animate-spin" /> : <Key size={14} />}+ {saving ? 'Saving…' : 'Save token'}+ </button>+ </div>+ </div>+ );+}diff --git a/client/src/pages/ImageGen.jsx b/client/src/pages/ImageGen.jsxindex 4eace0daf2..1a751e6839 100644--- a/client/src/pages/ImageGen.jsx+++ b/client/src/pages/ImageGen.jsx@@ -15,6 +15,8 @@ import { ImageGenTab } from '../components/settings/ImageGenTab';import MediaCard from '../components/media/MediaCard';import MediaLightbox from '../components/media/MediaLightbox';import { normalizeImage } from '../components/media/normalize';+import Flux2InstallModal from '../components/imageGen/Flux2InstallModal';+import Flux2TokenBanner from '../components/imageGen/Flux2TokenBanner';import {Image as ImageIcon, Sparkles, Download, RefreshCw, Settings as SettingsIcon,Dice5, AlertTriangle, X, Film, Cloud, Cpu, Terminal@@ -60,6 +62,7 @@ export default function ImageGen() {// selection of a flux2 model so we don't make an extra request when the// user is only using mflux/external/codex.const [flux2Status, setFlux2Status] = useState(null);+ const [flux2InstallOpen, setFlux2InstallOpen] = useState(false);const [selectedMode, setSelectedMode] = useState(null);const [availableBackends, setAvailableBackends] = useState([]);@@ -278,18 +281,31 @@ export default function ImageGen() {const resolutionLabel = matchedResolution?.label || `${width}×${height}`;const isFlux2Model = currentModel?.runner === 'flux2';+ const refreshFlux2Status = useCallback((signal) => {+ return fetch('/api/image-gen/setup/flux2-status', { signal })+ .then((r) => r.ok ? r.json() : null)+ .then((s) => { if (s) setFlux2Status(s); })+ .catch(() => {});+ }, []);++ // Memoized so Flux2InstallModal's EventSource effect doesn't re-fire on+ // every parent re-render (gallery / generating / progress state churn+ // would otherwise tear down the SSE connection mid-install).+ const handleFlux2ModalClose = useCallback(() => setFlux2InstallOpen(false), []);+ const handleFlux2InstallComplete = useCallback(() => {+ refreshFlux2Status();+ toast.success('FLUX.2 runtime installed');+ }, [refreshFlux2Status]);+useEffect(() => {if (!isFlux2Model) { setFlux2Status(null); return; }// Abort the in-flight request when the user switches models before it// resolves — otherwise a stale response could re-show the banner for// a non-flux2 selection.const controller = new AbortController();- fetch('/api/image-gen/setup/flux2-status', { signal: controller.signal })- .then((r) => r.ok ? r.json() : null)- .then((s) => { if (s) setFlux2Status(s); })- .catch(() => {});+ refreshFlux2Status(controller.signal);return () => controller.abort();- }, [isFlux2Model, modelId]);+ }, [isFlux2Model, modelId, refreshFlux2Status]);const flux2Issue = isFlux2Model && flux2Status? (!flux2Status.venvInstalled ? 'venv' : !flux2Status.hfTokenPresent ? 'token' : null)@@ -593,19 +609,27 @@ export default function ImageGen() {</div>{flux2Issue === 'venv' && (- <div className="rounded-lg border border-port-warning/40 bg-port-warning/10 px-3 py-2 text-xs text-port-warning">- FLUX.2 venv not found at <code className="text-white">{flux2Status.expectedVenvPath}</code>.- Run <code className="text-white">INSTALL_FLUX2=1 bash scripts/setup-image-video.sh</code> to bootstrap it.+ <div className="rounded-lg border border-port-warning/40 bg-port-warning/10 px-3 py-3 text-xs text-port-warning flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2">+ <div>+ FLUX.2 runtime isn't installed yet. PortOS can set it up automatically+ — torch + diffusers download, ~3-10 min on first run.+ </div>+ <button+ type="button"+ onClick={() => setFlux2InstallOpen(true)}+ disabled={generating}+ 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} />+ Install FLUX.2+ </button></div>)}{flux2Issue === 'token' && (- <div className="rounded-lg border border-port-warning/40 bg-port-warning/10 px-3 py-2 text-xs text-port-warning">- FLUX.2-klein is gated. Accept the license at{' '}- <a href={flux2Status.licenseUrl} target="_blank" rel="noreferrer" className="underline text-white">- huggingface.co/black-forest-labs/FLUX.2-klein-4B- </a>{' '}- and export <code className="text-white">HF_TOKEN=…</code> before running PortOS.- </div>+ <Flux2TokenBanner+ licenseUrl={flux2Status.licenseUrl}+ onSaved={refreshFlux2Status}+ />)}<div className="grid grid-cols-2 sm:grid-cols-3 gap-3">@@ -963,6 +987,12 @@ export default function ImageGen() {<Drawer open={settingsOpen} onClose={closeSettings} title="Media Generation Settings"><ImageGenTab /></Drawer>++ <Flux2InstallModal+ open={flux2InstallOpen}+ onClose={handleFlux2ModalClose}+ onComplete={handleFlux2InstallComplete}+ /></div>);}diff --git a/ecosystem.config.cjs b/ecosystem.config.cjsindex f4784675d9..eb6be2f7ca 100644--- a/ecosystem.config.cjs+++ b/ecosystem.config.cjs@@ -57,8 +57,20 @@ module.exports = {PATH: process.env.PATH // Inherit PATH for git/node access in child processes},watch: ['server'],- watch_delay: 300000, // 5 min delay before restarting on file changes- ignore_watch: ['**/node_modules', '**/*.test.js', '**/*package-lock*'],+ watch_delay: 60000, // 1 min debounce before restarting on file changes+ // Defense in depth — `watch: ['server']` already scopes the watcher to+ // the server/ subtree, so writes to data/ at repo root don't fire it.+ // Belt + suspenders: explicitly ignore runtime data, logs, and the+ // tmpdir-style scratch paths a render might (mis)route into the tree.+ ignore_watch: [+ '**/node_modules',+ '**/*.test.js',+ '**/*package-lock*',+ '**/data/**',+ '**/logs/**',+ '**/.cache/**',+ '**/portos-stepwise-*/**',+ ],max_memory_restart: '2G'},{diff --git a/scripts/flux2_macos.py b/scripts/flux2_macos.pyindex 5677bf49d0..f027754600 100755--- a/scripts/flux2_macos.py+++ b/scripts/flux2_macos.py@@ -190,11 +190,18 @@ def make_stepwise_callback(stepwise_dir: str, pipe):if shift is None:shift = 0.0+ fired = {"count": 0, "saved": 0}+@torch.no_grad()def cb(pipe, step_index, _timestep, callback_kwargs):+ fired["count"] += 1latents = callback_kwargs.get("latents")if latents is None:+ if step_index == 0:+ print("⚠️ stepwise: latents missing from callback_kwargs", file=sys.stderr)return callback_kwargs+ if step_index == 0:+ print(f"🖼️ stepwise: callback live, latents.shape={tuple(latents.shape)}", file=sys.stderr)# Best-effort decode. Errors here must not abort generation — the# final image is still produced after the last step.try:@@ -206,10 +213,12 @@ def make_stepwise_callback(stepwise_dir: str, pipe):# 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"] += 1except Exception as err:- print(f"⚠️ stepwise preview failed at step {step_index}: {err}", file=sys.stderr)+ print(f"⚠️ stepwise preview failed at step {step_index}: {type(err).__name__}: {err}", file=sys.stderr)return callback_kwargs+ cb._stats = firedreturn cb@@ -316,6 +325,10 @@ def main() -> None:image = result.images[0]image.save(args.output)+ if callback is not None and hasattr(callback, "_stats"):+ s = callback._stats+ print(f"🖼️ stepwise summary: callback fired {s['count']} times, saved {s['saved']} previews", file=sys.stderr)+if args.metadata:write_sidecar(args.output,diff --git a/server/lib/hfToken.js b/server/lib/hfToken.jsnew file mode 100644index 0000000000..0af63157a5--- /dev/null+++ b/server/lib/hfToken.js@@ -0,0 +1,34 @@+// HuggingFace token resolution. Stored token (settings.imageGen.hfToken) wins+// over env vars so the user can update from the UI without restarting PortOS.+// huggingface_hub reads HF_TOKEN / HUGGINGFACE_HUB_TOKEN /+// HUGGINGFACEHUB_API_TOKEN — surface all three when injecting into spawn env.++import { getSettings } from '../services/settings.js';++export async function getHfToken() {+ const settings = await getSettings();+ const stored = settings?.imageGen?.hfToken?.trim?.();+ if (stored) return stored;+ return (+ process.env.HF_TOKEN ||+ process.env.HUGGINGFACE_HUB_TOKEN ||+ process.env.HUGGINGFACEHUB_API_TOKEN ||+ null+ );+}++// Spread into a child_process spawn `env` to give the Python child whichever+// token variable name its code reads.+export async function hfTokenEnv() {+ const token = await getHfToken();+ if (!token) return {};+ return {+ HF_TOKEN: token,+ HUGGINGFACE_HUB_TOKEN: token,+ HUGGINGFACEHUB_API_TOKEN: token,+ };+}++// HF tokens are `hf_` + ~36 alphanumeric chars. Exported as a Zod-friendly+// regex so route schemas validate at the boundary instead of post-parse.+export const HF_TOKEN_REGEX = /^hf_[A-Za-z0-9_-]+$/;diff --git a/server/lib/pythonSetup.js b/server/lib/pythonSetup.jsindex 80efafc909..c69d37cb64 100644--- a/server/lib/pythonSetup.js+++ b/server/lib/pythonSetup.js@@ -93,6 +93,27 @@ export function resolveFlux2Python() {return null;}+// Whether the venv can actually run the FLUX.2 pipeline. Distinct from+// resolveFlux2Python() which only confirms the python binary exists — a+// killed-mid-install run leaves the binary but no packages, and we'd+// otherwise report that broken state as "ready" forever. Cached because the+// import probe spawns a process; bust via invalidateFlux2Health().+let cachedFlux2Healthy = null;+export async function isFlux2VenvHealthy() {+ if (cachedFlux2Healthy !== null) return cachedFlux2Healthy;+ const py = resolveFlux2Python();+ if (!py) { cachedFlux2Healthy = false; return false; }+ const ok = await execFileAsync(py, ['-c', 'from diffusers import Flux2KleinPipeline'], { timeout: 30_000 })+ .then(() => true)+ .catch(() => false);+ cachedFlux2Healthy = ok;+ return ok;+}+export function invalidateFlux2Health() {+ cachedFlux2Python = null;+ cachedFlux2Healthy = null;+}+// Used by /api/image-gen/setup/* routes to validate user-supplied pythonPath// before exec. Single-user / Tailnet model means we trust the operator, but// "you can shell out to anything" is still too sharp — restrict to actual@@ -197,3 +218,100 @@ export function installPackages(pythonPath, importNames, onLog) {return { promise, kill: () => { if (!proc.killed) proc.kill('SIGTERM'); } };}++// Pip specs for the FLUX.2 venv. Mirrors scripts/setup-image-video.sh so the+// shell path and the in-app installer stay in sync. diffusers + sdnq are+// git-only because Flux2KleinPipeline isn't in any tagged release yet.+export const FLUX2_PIP_SPECS = [+ 'torch>=2.5',+ 'torchvision',+ 'accelerate',+ 'transformers>=4.51',+ 'sentencepiece',+ 'protobuf',+ 'safetensors',+ 'huggingface_hub[hf_xet]',+ 'diffusers @ git+https://github.com/huggingface/diffusers',+ 'sdnq @ git+https://github.com/Disty0/sdnq.git',+ 'peft>=0.17',+ 'optimum-quanto>=0.2.7',+ 'pillow',+];++// Bootstrap the FLUX.2 venv from inside the app so users don't have to drop to+// a shell. Drives staged SSE progress: detect → venv → upgrade-pip → install+// → verify. onLog gets `{ type: 'log' | 'stage' | 'error' | 'complete', stage?, message }`.+// Returns `{ promise, kill }` like installPackages so the route can SIGTERM+// pip if the EventSource is closed mid-install.+export function installFlux2Venv(onLog) {+ let currentProc = null;+ let killed = false;++ const stage = (name, message) => onLog({ type: 'stage', stage: name, message });+ const log = (message) => onLog({ type: 'log', message });++ const runPython = (args) => new Promise((resolve) => {+ const proc = spawn(args[0], args.slice(1), { stdio: ['ignore', 'pipe', 'pipe'] });+ currentProc = proc;+ const onChunk = (chunk) => {+ for (const line of chunk.toString().split(/[\r\n]+/)) {+ const t = line.trim();+ if (t) log(t);+ }+ };+ proc.stdout.on('data', onChunk);+ proc.stderr.on('data', onChunk);+ proc.on('close', (code) => { currentProc = null; resolve(code === 0); });+ proc.on('error', (err) => { onLog({ type: 'error', message: err.message }); currentProc = null; resolve(false); });+ });++ const promise = (async () => {+ stage('detect', 'Looking for system Python…');+ const basePython = await detectPython();+ if (!basePython) {+ onLog({ type: 'error', message: 'No system Python 3 found. Install Python 3.10+ and try again.' });+ return { ok: false, stage: 'detect' };+ }+ log(`Using base Python: ${basePython}`);++ stage('venv', `Creating FLUX.2 venv at ${FLUX2_VENV_DEFAULT}…`);+ const targetDir = FLUX2_VENV_DEFAULT.replace(IS_WIN ? /\\Scripts\\python\.exe$/ : /\/bin\/python3$/, '');+ const venvPython = await createVenv(basePython, targetDir).catch((err) => {+ onLog({ type: 'error', message: `venv creation failed: ${err.message}` });+ return null;+ });+ if (!venvPython) return { ok: false, stage: 'venv' };+ if (killed) return { ok: false, stage: 'venv', cancelled: true };++ stage('upgrade-pip', 'Upgrading pip + wheel + setuptools…');+ if (!await runPython([venvPython, '-m', 'pip', 'install', '--upgrade', 'pip', 'wheel', 'setuptools'])) {+ return { ok: false, stage: 'upgrade-pip' };+ }+ if (killed) return { ok: false, stage: 'upgrade-pip', cancelled: true };++ stage('install', 'Installing torch + diffusers + sdnq + transformers (~6-10 min — large download)…');+ if (!await runPython([venvPython, '-m', 'pip', 'install', '--upgrade', '--progress-bar', 'on', ...FLUX2_PIP_SPECS])) {+ return { ok: false, stage: 'install' };+ }+ if (killed) return { ok: false, stage: 'install', cancelled: true };++ stage('verify', 'Verifying Flux2KleinPipeline import…');+ if (!await runPython([venvPython, '-c', 'from diffusers import Flux2KleinPipeline; print("ok")'])) {+ onLog({ type: 'error', message: 'Verification failed: Flux2KleinPipeline did not import. Try INSTALL_FLUX2=1 FLUX2_FORCE_REINSTALL=1 bash scripts/setup-image-video.sh' });+ return { ok: false, stage: 'verify' };+ }++ invalidateFlux2Health();++ onLog({ type: 'complete', message: `FLUX.2 venv ready: ${venvPython}` });+ return { ok: true, pythonPath: venvPython };+ })();++ return {+ promise,+ kill: () => {+ killed = true;+ if (currentProc && !currentProc.killed) currentProc.kill('SIGTERM');+ },+ };+}diff --git a/server/routes/imageGen.js b/server/routes/imageGen.jsindex 28260d6560..95c6fb94fe 100644--- a/server/routes/imageGen.js+++ b/server/routes/imageGen.js@@ -20,12 +20,13 @@ import { optionalUpload } from '../lib/multipart.js';import * as imageGen from '../services/imageGen/index.js';import { local, IMAGE_GEN_MODES } from '../services/imageGen/index.js';import { enqueueJob, attachSseClient as attachQueueSseClient, cancelJob, listJobs } from '../services/mediaJobQueue/index.js';-import { getSettings } from '../services/settings.js';+import { getSettings, saveSettings } from '../services/settings.js';+import { getHfToken, HF_TOKEN_REGEX } from '../lib/hfToken.js';import { getImageModels, isFlux2 } from '../lib/mediaModels.js';import {REQUIRED_PACKAGES, detectPython, checkPackages, installPackages,isExternallyManaged, createVenv, isAllowedPython, pipNameFor,- resolveFlux2Python, FLUX2_VENV_DEFAULT,+ resolveFlux2Python, FLUX2_VENV_DEFAULT, installFlux2Venv, isFlux2VenvHealthy,} from '../lib/pythonSetup.js';import { PATHS, ensureDir } from '../lib/fileUtils.js';import { join, basename, resolve as resolvePath, sep as PATH_SEP } from 'node:path';@@ -262,27 +263,87 @@ router.get('/setup/python', asyncHandler(async (_req, res) => {res.json({ path });}));+// SSE-driven FLUX.2 venv bootstrap. Replaces the "drop to a shell and run+// INSTALL_FLUX2=1 bash scripts/setup-image-video.sh" friction with an in-app+// install: the client opens an EventSource, gets staged progress events+// (detect → venv → upgrade-pip → install → verify), and either finishes or+// surfaces a clear error. Runs the install logic in-process via+// installFlux2Venv() so we get structured `stage` events the UI can animate+// against, instead of having to parse bash output.+//+// In-flight singleton: a rapid double-click would otherwise race two pip+// processes against the same venv directory. resolveFlux2Python() can't+// gate the second click — the first install hasn't created the python yet.+let flux2InstallInFlight = null;++router.get('/setup/flux2-install', asyncHandler(async (req, res) => {+ res.writeHead(200, {+ 'Content-Type': 'text/event-stream',+ 'Cache-Control': 'no-cache',+ Connection: 'keep-alive',+ });+ const send = (event) => {+ if (!res.writableEnded) res.write(`data: ${JSON.stringify(event)}\n\n`);+ };+ const safeEnd = () => { if (!res.writableEnded) res.end(); };++ // Skip only when the venv binary AND the import work — a half-broken venv+ // (binary present, packages missing from a killed mid-install) needs to+ // re-run the install, not be reported as ready.+ if (await isFlux2VenvHealthy()) {+ send({ type: 'stage', stage: 'verify', message: 'FLUX.2 venv already installed.' });+ send({ type: 'complete', message: 'Already installed — nothing to do.' });+ return safeEnd();+ }+ if (flux2InstallInFlight) {+ send({ type: 'error', message: 'Another FLUX.2 install is already running. Wait for it to finish or restart PortOS.' });+ return safeEnd();+ }++ const { promise, kill } = installFlux2Venv(send);+ flux2InstallInFlight = promise;+ promise+ .catch((err) => send({ type: 'error', message: err?.message || 'Unknown installer failure' }))+ .finally(() => {+ flux2InstallInFlight = null;+ safeEnd();+ });++ // Cancel the install if the client navigates away mid-bootstrap. A torch+ // install is a multi-GB download and would otherwise keep running invisibly.+ req.on('close', () => { kill(); safeEnd(); });+}));+// Used by the FLUX.2 model picker: surface a banner when the gated repo's// license hasn't been accepted (HF_TOKEN missing) and the runner is set up.-router.get('/setup/flux2-status', (_req, res) => {- // huggingface_hub reads HF_TOKEN (preferred) and the legacy- // HUGGINGFACEHUB_API_TOKEN / HUGGINGFACE_HUB_TOKEN names. Earlier rev of- // this code used HUGGING_FACE_HUB_TOKEN (extra underscore) which doesn't- // match what the library actually checks.- const hasToken = !!(- process.env.HF_TOKEN ||- process.env.HUGGINGFACE_HUB_TOKEN ||- process.env.HUGGINGFACEHUB_API_TOKEN- );+// `venvInstalled` reflects functional health (binary AND packages import) —+// a half-broken venv would otherwise hide the install banner forever.+router.get('/setup/flux2-status', asyncHandler(async (_req, res) => {+ const [token, healthy] = await Promise.all([getHfToken(), isFlux2VenvHealthy()]);const venvPython = resolveFlux2Python();res.json({- hfTokenPresent: hasToken,- venvInstalled: !!venvPython,+ hfTokenPresent: !!token,+ venvInstalled: healthy,venvPath: venvPython,expectedVenvPath: FLUX2_VENV_DEFAULT,licenseUrl: 'https://huggingface.co/black-forest-labs/FLUX.2-klein-4B',});+}));++// Save the HF token from the inline form on the Image Gen page. settings.json+// is the canonical location (single-user app behind Tailscale — see CLAUDE.md).+const flux2TokenSchema = z.object({+ token: z.string().regex(HF_TOKEN_REGEX, 'Token must look like `hf_…`').max(200),});+router.post('/setup/flux2-token', asyncHandler(async (req, res) => {+ const { token } = validateRequest(flux2TokenSchema, req.body || {});+ const settings = await getSettings();+ await saveSettings({+ ...settings,+ imageGen: { ...(settings.imageGen || {}), hfToken: token.trim() },+ });+ res.json({ ok: true, hfTokenPresent: true });+}));const checkSchema = z.object({ pythonPath: z.string().min(1) });diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.jsindex 764538b5af..43341a4485 100644--- a/server/services/imageGen/local.js+++ b/server/services/imageGen/local.js@@ -23,6 +23,7 @@ import { ServerError } from '../../lib/errorHandler.js';import { imageGenEvents } from '../imageGenEvents.js';import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay, PYTHON_NOISE_RE } from '../../lib/sseUtils.js';import { resolveFlux2Python, FLUX2_VENV_DEFAULT } from '../../lib/pythonSetup.js';+import { hfTokenEnv } from '../../lib/hfToken.js';const IS_WIN = process.platform === 'win32';@@ -241,7 +242,7 @@ export async function generateImage({ pythonPath, prompt, negativePrompt = '', mimageGenEvents.emit('started', { generationId: jobId, totalSteps: actualSteps });activeJob = { ...meta, generationId: jobId, totalSteps: actualSteps, step: 0, progress: 0, currentImage: null, mode: 'local' };- const proc = spawn(bin, args, { env: { ...process.env }, stdio: ['ignore', 'pipe', 'pipe'] });+ const proc = spawn(bin, args, { env: { ...process.env, ...(await hfTokenEnv()) }, stdio: ['ignore', 'pipe', 'pipe'] });activeProcess = proc;// Without an 'error' handler, a missing/non-executable pythonPath would// crash the server with an unhandled error event.diff --git a/server/services/settings.js b/server/services/settings.jsindex 05d9997cb2..620035307a 100644--- a/server/services/settings.js+++ b/server/services/settings.js@@ -14,6 +14,7 @@ const save = async (settings) => {};export const getSettings = load;+export const saveSettings = save;export const updateSettings = async (patch) => {const current = await load();