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(settings): expose HuggingFace token in Image Gen settings
[._.]/ Adam Eivyd6f50f6cace8
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 993b4ebae2..de58a19a0b 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,7 @@## Added+- **Settings → Image Gen → HuggingFace Token panel.** Adds a first-class place to paste, view, and clear the HuggingFace token used by gated local image models (FLUX.1-dev, FLUX.2-klein). The panel shows live status with source attribution (stored in `settings.json` vs `HF_TOKEN` env var vs `~/.cache/huggingface/token` from `hf auth login`) so it's clear which slot a token lives in; the Clear button only appears for stored tokens (env/CLI come from outside settings). The runner-side `GatedRepoError` message already pointed at "Image Gen settings" — that destination now exists. Backed by `GET /api/image-gen/setup/hf-token-status` (now returns `source`), the existing `POST` for save, and a new `DELETE /api/image-gen/setup/hf-token` for clear. Also: migration `012-mark-flux1-dev-gated.js` retrofits `requiresHfToken: true` + `licenseUrl` onto the FLUX.1-dev entry in existing installs' `data/media-models.json` (fresh installs were already covered via `data.sample`), so the inline banner on the Image Gen page surfaces for that model too — same flow that previously only worked for FLUX.2-klein.- **Pipeline — issue back covers + volume (trade-paperback) covers + volume PDF.** Every comic issue now generates both a front and a back cover concept as part of the LLM comic-script pass (new `## Back cover concept` section, parsed alongside the existing `## Cover concept`). Both renders use the proof/final workflow and ship in the issue PDF as `cover → pages → back → colophon`. Each volume (season) gets its own front + back cover concepts via a new per-season LLM step (`POST /series/:id/seasons/:seasonId/cover-concepts/generate`) that seeds `season.cover.script` / `season.backCover.script` when blank (never clobbers user edits). The new `GET /series/:id/seasons/:seasonId/volume.pdf` compiles a full trade paperback: `[vol front] → [issue1 front → issue1 pages → issue1 back] → [issue2 …] → [vol back] → colophon`, sorted by `arcPosition ?? number`. Existing seasons get a "Generate cover concepts (LLM)" + "Compile volume PDF" button on each Arc canvas row to backfill. Migration `011-comic-script-back-cover.js` adds the back-cover section to the installed comic-script prompt for unmodified installs.- **Universe Builder — per-category "Generate N more" variations.** Each category card now has a Generate dropdown (3 / 5 / 10 / custom up to 50) next to the existing Render / + Add buttons. The LLM is given the universe's bible context (logline, premise, style notes, influences) plus the list of existing labels to skip, and returns N additional variations that get appended to the category. Locked items are unaffected — Generate is purely additive. Auto-saves when the universe is already persisted; otherwise hands you a "review then Save" toast. New endpoint: `POST /api/universe-builder/generate-variations`.diff --git a/client/src/components/settings/ImageGenTab.jsx b/client/src/components/settings/ImageGenTab.jsxindex f73b08f63b..f51c7645ce 100644--- a/client/src/components/settings/ImageGenTab.jsx+++ b/client/src/components/settings/ImageGenTab.jsx@@ -9,7 +9,7 @@import { useState, useEffect, useCallback, useRef } from 'react';import {Save, Image as ImageIcon, Zap, Wrench, Cloud, Cpu, Globe, AlertTriangle,- Sparkles, Terminal+ Sparkles, Terminal, Key, Check, Trash2} from 'lucide-react';import toast from '../ui/Toast';import BrailleSpinner from '../BrailleSpinner';@@ -17,6 +17,7 @@ import LocalSetupPanel from './LocalSetupPanel';import {getSettings, updateSettings, getImageGenStatus, generateImage,registerTool, updateTool, getToolsList,+ getHfTokenStatus, saveHfToken, clearHfToken,} from '../../services/api';const SDAPI_TOOL_ID = 'sdapi';@@ -67,6 +68,45 @@ export function ImageGenTab() {const [renderResult, setRenderResult] = useState(null);const renderEsRef = useRef(null);+ // HuggingFace token state — separate from the main settings save flow because+ // it has its own validated endpoints (POST /setup/hf-token + DELETE) and+ // applies to local Flux models regardless of which backend is active.+ // `source` is 'stored' | 'env' | 'cli' | 'none'; only 'stored' tokens can be+ // cleared from the UI (env/CLI come from outside settings.json).+ const [hfTokenInfo, setHfTokenInfo] = useState({ hfTokenPresent: null, source: null });+ const [hfTokenInput, setHfTokenInput] = useState('');+ // One busy flag covers both save and clear since they're mutually exclusive+ // (both disable the form + buttons). `busy` is the in-flight verb so the+ // Clear button can still show a Trash icon while the spinner is on Save.+ const [hfTokenBusy, setHfTokenBusy] = useState(null); // null | 'saving' | 'clearing'++ useEffect(() => {+ getHfTokenStatus()+ .then((s) => { if (s) setHfTokenInfo({ hfTokenPresent: !!s.hfTokenPresent, source: s.source || null }); })+ .catch(() => {});+ }, []);++ const handleSaveHfToken = async () => {+ const trimmed = hfTokenInput.trim();+ if (!trimmed) return;+ setHfTokenBusy('saving');+ const result = await saveHfToken(trimmed).catch(() => null);+ setHfTokenBusy(null);+ if (!result?.ok) return;+ setHfTokenInput('');+ setHfTokenInfo({ hfTokenPresent: true, source: result.source || 'stored' });+ toast.success('HuggingFace token saved');+ };++ const handleClearHfToken = async () => {+ setHfTokenBusy('clearing');+ const result = await clearHfToken().catch(() => null);+ setHfTokenBusy(null);+ if (!result?.ok) return;+ setHfTokenInfo({ hfTokenPresent: !!result.hfTokenPresent, source: result.source || 'none' });+ toast.success(result.hfTokenPresent ? 'Stored token cleared (env / CLI token still active)' : 'HuggingFace token cleared');+ };+// Close any in-flight test-render SSE on unmount so we don't fire setState// on a torn-down component if the user navigates away mid-render.useEffect(() => () => renderEsRef.current?.close(), []);@@ -454,6 +494,84 @@ export function ImageGenTab() {)}</div>+ {/* HuggingFace token — used by local Flux models (FLUX.1-dev, FLUX.2-klein).+ Independent of the mode picker because the token persists in settings+ and applies whenever local image gen runs. */}+ <div className="bg-port-card border border-port-border rounded-xl p-6 space-y-4">+ <div className="flex items-center gap-2 text-white">+ <Key size={18} />+ <h2 className="text-lg font-semibold">HuggingFace Token</h2>+ </div>+ <p className="text-xs text-gray-500">+ Required for gated local models — currently <code className="text-gray-400">FLUX.1-dev</code> and the{' '}+ <code className="text-gray-400">FLUX.2-klein</code> family. Accept each model's license on HuggingFace, then create a read token at{' '}+ <a href="https://huggingface.co/settings/tokens" target="_blank" rel="noreferrer" className="text-port-accent hover:underline">+ huggingface.co/settings/tokens+ </a>{' '}and paste it below. PortOS reads stored tokens first, then falls back to the{' '}+ <code className="text-gray-400">HF_TOKEN</code> env var or <code className="text-gray-400">~/.cache/huggingface/token</code>.+ </p>++ {hfTokenInfo.hfTokenPresent === null ? (+ <div className="text-xs text-gray-500"><BrailleSpinner text="Checking token status" /></div>+ ) : hfTokenInfo.hfTokenPresent ? (+ <div className="flex items-center gap-2 text-xs text-port-success">+ <Check size={14} />+ <span>+ Token configured+ {hfTokenInfo.source === 'env' && ' (from HF_TOKEN environment variable)'}+ {hfTokenInfo.source === 'cli' && ' (from ~/.cache/huggingface/token — set via `hf auth login`)'}+ {hfTokenInfo.source === 'stored' && ' (stored in settings.json)'}+ </span>+ </div>+ ) : (+ <div className="flex items-center gap-2 text-xs text-port-warning">+ <AlertTriangle size={14} />+ <span>No HuggingFace token configured — gated models will fail to download.</span>+ </div>+ )}++ <div>+ <label htmlFor="hf-token-input" className="block text-xs font-medium text-gray-400 mb-1">+ {hfTokenInfo.source === 'stored' ? 'Replace stored token' : 'Paste a token'}+ </label>+ <div className="flex flex-col sm:flex-row gap-2">+ <input+ id="hf-token-input"+ type="password"+ value={hfTokenInput}+ onChange={(e) => setHfTokenInput(e.target.value)}+ onKeyDown={(e) => { if (e.key === 'Enter') handleSaveHfToken(); }}+ disabled={hfTokenBusy !== null}+ placeholder="hf_…"+ autoComplete="off"+ spellCheck={false}+ className="flex-1 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"+ />+ <button+ type="button"+ onClick={handleSaveHfToken}+ disabled={hfTokenBusy !== null || !hfTokenInput.trim()}+ className="whitespace-nowrap inline-flex items-center justify-center gap-2 px-4 py-2 rounded-lg bg-port-accent text-white text-sm font-medium hover:bg-port-accent/80 disabled:opacity-50 min-h-[40px]"+ >+ {hfTokenBusy === 'saving' ? <BrailleSpinner /> : <Save size={14} />}+ Save token+ </button>+ </div>+ </div>++ {hfTokenInfo.source === 'stored' && (+ <button+ type="button"+ onClick={handleClearHfToken}+ disabled={hfTokenBusy !== null}+ className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-border text-gray-300 text-xs font-medium hover:bg-port-error/20 hover:text-port-error disabled:opacity-50"+ >+ {hfTokenBusy === 'clearing' ? <BrailleSpinner /> : <Trash2 size={12} />}+ Clear stored token+ </button>+ )}+ </div>+{/* Save + status */}<div className="flex items-center gap-3"><buttondiff --git a/client/src/services/apiImageVideo.js b/client/src/services/apiImageVideo.jsindex c7c79985b2..67e384484f 100644--- a/client/src/services/apiImageVideo.js+++ b/client/src/services/apiImageVideo.js@@ -24,6 +24,15 @@ export const cleanGalleryImage = (filename, level = 'light') => request(`/image-body: JSON.stringify({ level }),});+// HuggingFace token (gated local Flux models). Stored in settings.imageGen.hfToken;+// reads fall back to HF_TOKEN env var and then ~/.cache/huggingface/token.+export const getHfTokenStatus = () => request('/image-gen/setup/hf-token-status', { silent: true });+export const saveHfToken = (token) => request('/image-gen/setup/hf-token', {+ method: 'POST',+ body: JSON.stringify({ token }),+});+export const clearHfToken = () => request('/image-gen/setup/hf-token', { method: 'DELETE' });+// Video genexport const getVideoGenStatus = () => request('/video-gen/status');export const listVideoModels = () => request('/video-gen/models');diff --git a/scripts/migrations/009-simplify-cos-agent-briefing.js b/scripts/migrations/010-simplify-cos-agent-briefing.jssimilarity index 100%rename from scripts/migrations/009-simplify-cos-agent-briefing.jsrename to scripts/migrations/010-simplify-cos-agent-briefing.jsdiff --git a/scripts/migrations/010-renumber-pipeline-issues-by-volume.js b/scripts/migrations/011-renumber-pipeline-issues-by-volume.jssimilarity index 100%rename from scripts/migrations/010-renumber-pipeline-issues-by-volume.jsrename to scripts/migrations/011-renumber-pipeline-issues-by-volume.jsdiff --git a/scripts/migrations/010-mark-flux1-dev-gated.js b/scripts/migrations/012-mark-flux1-dev-gated.jssimilarity index 100%rename from scripts/migrations/010-mark-flux1-dev-gated.jsrename to scripts/migrations/012-mark-flux1-dev-gated.jsdiff --git a/scripts/migrations/011-comic-script-back-cover.js b/scripts/migrations/013-comic-script-back-cover.jssimilarity index 100%rename from scripts/migrations/011-comic-script-back-cover.jsrename to scripts/migrations/013-comic-script-back-cover.jsdiff --git a/scripts/migrations/012-attribute-existing-annotations.js b/scripts/migrations/014-attribute-existing-annotations.jssimilarity index 100%rename from scripts/migrations/012-attribute-existing-annotations.jsrename to scripts/migrations/014-attribute-existing-annotations.jsdiff --git a/server/lib/hfToken.js b/server/lib/hfToken.jsindex 9b97bd2631..fa94f89266 100644--- a/server/lib/hfToken.js+++ b/server/lib/hfToken.js@@ -19,17 +19,28 @@ async function readHfCliToken() {}export async function getHfToken() {+ const { token } = await getHfTokenInfo();+ return token;+}++// Same lookup as `getHfToken()` but also surfaces *where* the token came from+// so the Settings UI can show "Stored token configured" vs "Using env var+// HF_TOKEN" — and so the Clear button only appears when the stored entry is+// the one being used. `source` is one of: 'stored' | 'env' | 'cli' | 'none'.+export async function getHfTokenInfo() {const settings = await getSettings();const stored = settings?.imageGen?.hfToken?.trim?.();- if (stored) return stored;+ if (stored) return { token: stored, source: 'stored' };const envToken = (process.env.HF_TOKEN ||process.env.HUGGINGFACE_HUB_TOKEN ||process.env.HUGGINGFACEHUB_API_TOKEN ||null);- if (envToken) return envToken;- return await readHfCliToken();+ if (envToken) return { token: envToken, source: 'env' };+ const cliToken = await readHfCliToken();+ if (cliToken) return { token: cliToken, source: 'cli' };+ return { token: null, source: 'none' };}// Spread into a child_process spawn `env` to give the Python child whicheverdiff --git a/server/routes/imageGen.js b/server/routes/imageGen.jsindex dde933b11f..a80ae64295 100644--- a/server/routes/imageGen.js+++ b/server/routes/imageGen.js@@ -23,7 +23,7 @@ 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, saveSettings } from '../services/settings.js';-import { getHfToken, HF_TOKEN_REGEX } from '../lib/hfToken.js';+import { getHfToken, getHfTokenInfo, HF_TOKEN_REGEX } from '../lib/hfToken.js';import { getImageModels, isFlux2, isZImage, isErnie } from '../lib/mediaModels.js';import {REQUIRED_PACKAGES, detectPython, checkPackages, installPackages,@@ -491,8 +491,8 @@ router.get('/setup/flux2-status', asyncHandler(async (_req, res) => {// 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 });+ const { token, source } = await getHfTokenInfo();+ res.json({ hfTokenPresent: !!token, source });}));// Save the HF token from the inline form on the Image Gen page. settings.json@@ -509,7 +509,17 @@ router.post('/setup/hf-token', asyncHandler(async (req, res) => {...settings,imageGen: { ...(settings.imageGen || {}), hfToken: token.trim() },});- res.json({ ok: true, hfTokenPresent: true });+ res.json({ ok: true, hfTokenPresent: true, source: 'stored' });+}));++// Clear the stored HF token. Falls back to env / CLI tokens if present —+// callers should re-fetch /setup/hf-token-status to see the post-clear state.+router.delete('/setup/hf-token', asyncHandler(async (_req, res) => {+ const settings = await getSettings();+ const { hfToken: _drop, ...restImageGen } = settings.imageGen || {};+ await saveSettings({ ...settings, imageGen: restImageGen });+ const { token, source } = await getHfTokenInfo();+ res.json({ ok: true, hfTokenPresent: !!token, source });}));const checkSchema = z.object({ pythonPath: z.string().min(1) });