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
fix(imagegen): surface HuggingFace token prompt for gated FLUX.1-dev
Ilya Eivy040ae06d3cce
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 9b678250df..076ae3a603 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -72,6 +72,30 @@## Fixed+- **Missing HuggingFace token prompt for FLUX.1-dev (gated repo).** Generating+ with FLUX.1-dev failed with a raw `huggingface_hub.errors.GatedRepoError:+ 401 Client Error` stack trace and no UI affordance — the existing inline+ HF-token banner only triggered for FLUX.2-klein. Two fixes: (1) Model+ registry now drives gating — `data/media-models.json` entries can carry+ `requiresHfToken: true` + `licenseUrl`, and `dev` (FLUX.1-dev) is marked+ accordingly. A new `GET /api/image-gen/setup/hf-token-status` endpoint+ reports token presence for any gated legacy mflux model (FLUX.2's combined+ status endpoint stays for its venv check). The component is renamed+ `Flux2TokenBanner → HfTokenBanner` and takes a `modelLabel` + `licenseUrl`+ prop so the gated-model copy/link adapts to the selected model. The POST+ endpoint is renamed `/setup/flux2-token → /setup/hf-token` to match its+ generic role.+ (2) `server/services/imageGen/local.js` now detects gated-repo failures+ from mflux's pre-built binary (which doesn't emit PortOS's structured+ `USER_ERROR:` markers) by matching `GatedRepoError` / `Cannot access gated+ repo for url …/<owner>/<name>/…` in stderr, extracting the repo, and+ surfacing an actionable `kind=gated_repo` failure with the license URL —+ same path used by the existing `mflux_install_corrupted` heuristic.+ Touches: `data/media-models.json`, `server/routes/imageGen.js`,+ `server/services/imageGen/local.js`, `client/src/pages/ImageGen.jsx`,+ `client/src/components/imageGen/HfTokenBanner.jsx` (renamed from+ `Flux2TokenBanner.jsx`).+- **Visual Style Preset dropdown clipped inside the bible sidebar.** Theprior z-30 → z-50 bump was a no-op for the real problem: the dropdownlives inside the Pipeline Series bible `<aside class="lg:overflow-y-auto">`,diff --git a/client/src/components/imageGen/Flux2TokenBanner.jsx b/client/src/components/imageGen/HfTokenBanner.jsxsimilarity index 79%rename from client/src/components/imageGen/Flux2TokenBanner.jsxrename to client/src/components/imageGen/HfTokenBanner.jsxindex 6eb5a720f7..007dafcf05 100644--- a/client/src/components/imageGen/Flux2TokenBanner.jsx+++ b/client/src/components/imageGen/HfTokenBanner.jsx@@ -1,8 +1,9 @@/**- * 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).+ * Inline HF_TOKEN entry for any gated HuggingFace image model (FLUX.1-dev,+ * FLUX.2-klein, etc.). 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 mflux /+ * 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@@ -14,7 +15,7 @@ import { Key, Loader2 } from 'lucide-react';import toast from '../ui/Toast';import apiCore from '../../services/apiCore';-export default function Flux2TokenBanner({ licenseUrl, onSaved }) {+export default function HfTokenBanner({ modelLabel, licenseUrl, onSaved }) {const [token, setToken] = useState('');const [saving, setSaving] = useState(false);@@ -24,7 +25,7 @@ export default function Flux2TokenBanner({ licenseUrl, onSaved }) {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);+ const result = await apiCore.post('/image-gen/setup/hf-token', { token: trimmed }).catch(() => null);setSaving(false);if (!result?.ok) return;setToken('');@@ -32,12 +33,14 @@ export default function Flux2TokenBanner({ licenseUrl, onSaved }) {onSaved?.();};+ const licenseLinkText = licenseUrl?.replace(/^https?:\/\//, '');+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{' '}+ {modelLabel} 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+ {licenseLinkText}</a>, then create a read token at{' '}<a href="https://huggingface.co/settings/tokens" target="_blank" rel="noreferrer" className="underline text-white">diff --git a/client/src/pages/ImageGen.jsx b/client/src/pages/ImageGen.jsxindex 16dde178ce..5f2a04ff75 100644--- a/client/src/pages/ImageGen.jsx+++ b/client/src/pages/ImageGen.jsx@@ -20,7 +20,7 @@ import BackendChipStrip from '../components/media/BackendChipStrip';import { normalizeImage } from '../components/media/normalize';import { RUNNER_FAMILIES } from '../lib/runnerFamilies';import Flux2InstallModal from '../components/imageGen/Flux2InstallModal';-import Flux2TokenBanner from '../components/imageGen/Flux2TokenBanner';+import HfTokenBanner from '../components/imageGen/HfTokenBanner';import ImageGenControls from '../components/imageGen/ImageGenControls';import MediaJobsQueue from '../components/media/MediaJobsQueue';import { useMediaCompletionRefresh } from '../hooks/useMediaCompletionRefresh';@@ -109,6 +109,9 @@ export default function ImageGen() {// user is only using mflux/external/codex.const [flux2Status, setFlux2Status] = useState(null);const [flux2InstallOpen, setFlux2InstallOpen] = useState(false);+ // Generic HF-token presence for legacy mflux gated models (FLUX.1-dev).+ // Lazy-fetched when a model with `requiresHfToken: true` is selected.+ const [hfTokenPresent, setHfTokenPresent] = useState(null);const [selectedMode, setSelectedMode] = useState(null);const [availableBackends, setAvailableBackends] = useState([]);@@ -398,6 +401,13 @@ export default function ImageGen() {.catch(() => {});}, []);+ const refreshHfTokenStatus = useCallback((signal) => {+ return fetch('/api/image-gen/setup/hf-token-status', { signal })+ .then((r) => r.ok ? r.json() : null)+ .then((s) => { if (s) setHfTokenPresent(!!s.hfTokenPresent); })+ .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).@@ -417,6 +427,17 @@ export default function ImageGen() {return () => controller.abort();}, [isFlux2Model, modelId, refreshFlux2Status]);+ // Lazy-fetch HF token presence for legacy mflux gated models (FLUX.1-dev).+ // FLUX.2 has its own combined status fetch above (which also covers the+ // venv install), so skip the duplicate request when isFlux2Model.+ const needsHfTokenGate = !!currentModel?.requiresHfToken && !isFlux2Model;+ useEffect(() => {+ if (!needsHfTokenGate) { setHfTokenPresent(null); return; }+ const controller = new AbortController();+ refreshHfTokenStatus(controller.signal);+ return () => controller.abort();+ }, [needsHfTokenGate, modelId, refreshHfTokenStatus]);+// 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@@ -832,11 +853,19 @@ export default function ImageGen() {</div>)}{flux2Issue === 'token' && (- <Flux2TokenBanner+ <HfTokenBanner+ modelLabel={currentModel?.name || 'FLUX.2-klein'}licenseUrl={flux2Status.licenseUrl}onSaved={refreshFlux2Status}/>)}+ {needsHfTokenGate && hfTokenPresent === false && (+ <HfTokenBanner+ modelLabel={currentModel?.name || modelId}+ licenseUrl={currentModel?.licenseUrl}+ onSaved={refreshHfTokenStatus}+ />+ )}<ImageGenControlsmode={effectiveMode}@@ -1043,7 +1072,7 @@ export default function ImageGen() {)}{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).+ Paste a fresh token in the HF token banner above (it appears when the model needs one).</div>)}</div>diff --git a/data.sample/media-models.json b/data.sample/media-models.jsonindex 4b4be64b3f..e3e0047849 100644--- a/data.sample/media-models.json+++ b/data.sample/media-models.json@@ -63,7 +63,9 @@"id": "dev","name": "Flux 1 Dev","steps": 20,- "guidance": 3.5+ "guidance": 3.5,+ "requiresHfToken": true,+ "licenseUrl": "https://huggingface.co/black-forest-labs/FLUX.1-dev"},{"id": "schnell",diff --git a/scripts/migrations/010-mark-flux1-dev-gated.js b/scripts/migrations/010-mark-flux1-dev-gated.jsnew file mode 100644index 0000000000..8877905ce0--- /dev/null+++ b/scripts/migrations/010-mark-flux1-dev-gated.js@@ -0,0 +1,70 @@+/**+ * Mark FLUX.1-dev as a gated HuggingFace model in existing installs.+ *+ * `data.sample/media-models.json` now carries `requiresHfToken: true` ++ * `licenseUrl` on the `dev` entry so the Image Gen page can surface the+ * inline HF-token banner (same pattern FLUX.2-klein already used). Fresh+ * installs pick this up via the data.sample → data copy in setup-data.js,+ * but `media-models.json` is not in JSON_MERGE_TARGETS so existing installs+ * keep their pre-flip entry. This migration patches the two fields onto an+ * unmodified `dev` entry without touching anything else.+ *+ * Idempotent: a second run finds either both fields already present, or a+ * user who customized/renamed the entry, and exits without writing.+ */++import { readFile, writeFile } from 'fs/promises';+import { join } from 'path';++const REL_PATH = 'data/media-models.json';++export default {+ async up({ rootDir }) {+ const path = join(rootDir, REL_PATH);+ const raw = await readFile(path, 'utf-8').catch((err) => {+ if (err.code === 'ENOENT') return null;+ throw err;+ });+ if (raw == null) {+ console.log(`📄 ${REL_PATH} not present — skipping (fresh install will copy from data.sample)`);+ return;+ }++ let config;+ try {+ config = JSON.parse(raw);+ } catch (err) {+ console.log(`⚠️ ${REL_PATH}: invalid JSON, skipping (${err.message})`);+ return;+ }++ const images = Array.isArray(config?.image) ? config.image : null;+ if (!images) {+ console.log(`⚠️ ${REL_PATH}: no image[] array — skipping`);+ return;+ }++ const dev = images.find((m) => m?.id === 'dev');+ if (!dev) {+ console.log(`✅ ${REL_PATH}: no 'dev' entry — user removed it, nothing to migrate`);+ return;+ }++ let changed = false;+ if (dev.requiresHfToken !== true) {+ dev.requiresHfToken = true;+ changed = true;+ }+ if (!dev.licenseUrl) {+ dev.licenseUrl = 'https://huggingface.co/black-forest-labs/FLUX.1-dev';+ changed = true;+ }++ if (changed) {+ await writeFile(path, `${JSON.stringify(config, null, 2)}\n`);+ console.log(`📝 ${REL_PATH}: marked FLUX.1-dev as gated (requiresHfToken + licenseUrl)`);+ } else {+ console.log(`✅ ${REL_PATH}: FLUX.1-dev already marked as gated, no changes`);+ }+ },+};diff --git a/server/routes/imageGen.js b/server/routes/imageGen.jsindex aef6c5bccf..dde933b11f 100644--- a/server/routes/imageGen.js+++ b/server/routes/imageGen.js@@ -487,13 +487,23 @@ router.get('/setup/flux2-status', asyncHandler(async (_req, res) => {});}));+// Generic HF-token presence check for legacy mflux runners that don't need+// the FLUX.2 venv. Any model entry with `requiresHfToken: true` in+// data/media-models.json drives the banner through this endpoint.+router.get('/setup/hf-token-status', asyncHandler(async (_req, res) => {+ const token = await getHfToken();+ res.json({ hfTokenPresent: !!token });+}));+// 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({+// Same endpoint serves FLUX.2 and legacy mflux gated models — the token is+// global (HF_TOKEN env in spawn).+const hfTokenSchema = 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 || {});+router.post('/setup/hf-token', asyncHandler(async (req, res) => {+ const { token } = validateRequest(hfTokenSchema, req.body || {});const settings = await getSettings();await saveSettings({...settings,diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.jsindex 0613945f81..b5661a0a81 100644--- a/server/services/imageGen/local.js+++ b/server/services/imageGen/local.js@@ -479,6 +479,25 @@ export async function generateImage({ pythonPath, prompt, negativePrompt = '', muserMessage = 'Your mflux install is corrupted (entry-point shim and package layout out of sync). Repair with: `pip uninstall -y mflux && pip install --user --force-reinstall --no-cache-dir --no-deps mflux`. If you use conda, run the same in your conda env\'s pip.';}}+ // Legacy mflux-generate is a pre-built binary, so it doesn't emit the+ // structured USER_ERROR markers the flux2/z-image Python runners use.+ // Match the raw huggingface_hub stack instead — `GatedRepoError` or the+ // "Cannot access gated repo for url …/<owner>/<name>/…" prose. Extract+ // the repo so the UI banner can link the user straight to the license+ // page (and we set kind=gated_repo so the client knows to surface the+ // token-entry form).+ if (!userMessage) {+ const gatedUrlMatch = lines+ .map((l) => l.match(/Cannot access gated repo for url https?:\/\/huggingface\.co\/([^/\s]+\/[^/\s]+)\//))+ .find(Boolean);+ const hasGatedError = lines.some((l) => /GatedRepoError|Access to model .* is restricted/.test(l));+ if (gatedUrlMatch || hasGatedError) {+ userKind = 'gated_repo';+ userRepo = gatedUrlMatch ? gatedUrlMatch[1] : null;+ const repoText = userRepo || 'the model';+ userMessage = `Access to ${repoText} is gated. Accept the license at https://huggingface.co/${userRepo || '<repo>'} and paste your HuggingFace token into Image Gen settings, then retry.`;+ }+ }const tail = lines.slice(-10).join('\n');const errorText = userMessage? `${userMessage}\n\n(diagnostic) ${reason}`