Skip to content

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

surface gated-repo HuggingFace failures in LoRA training UI with a license deep-link

[._.]/ Adam Eivyd7d863125d33
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 874a28cf54..a41ffcdeda 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -32,6 +32,8 @@
## Fixed
+- **A gated-model LoRA training failure now shows a one-click "Request access" link, like image rendering already does** — Training a FLUX.2 Klein LoRA pulls a *different, separately-gated* HuggingFace repo than rendering does (the mflux trainer resolves `flux2-klein-9b` → `black-forest-labs/FLUX.2-klein-base-9B`, whereas inference uses `FLUX.2-klein-9B`). So a user who'd accepted the inference model's license — and whose stored token is otherwise valid, with `canReadGatedRepos` — still hit a `GatedRepoError` the instant training started, with no obvious next step. Image rendering already turns this into an actionable banner with a deep link to the license page; training now does the same. The failure classifier extracts the gated `owner/repo` from the trainer's stderr (both the `Access to model … is restricted` and `Cannot access gated repo for url …` forms), persists it on the run record as `errorRepo`, and the training panel renders a **"Request access to `<repo>` ↗"** button that opens the exact license page — accept it there with the token's account and retry, no token change needed. The repo-extraction the image runner already did inline is now a shared `extractGatedRepo()` helper (`server/lib/hfErrors.js`) both subsystems consume. (`server/lib/hfErrors.js`, `server/services/loraTraining/failure.js`, `server/services/loraTraining/index.js`, `server/services/imageGen/local.js`, `client/src/components/loraTraining/TrainingPanel.jsx`)
+
- **mflux-trained FLUX.2 LoRAs now load into diffusers (double-block `to_out` key mismatch)** — Even on the bf16 base, an mflux-trained adapter failed to load with `Target module ModuleList(...) is not supported`, so the whole LoRA was dropped and the render fell back to base. Cause: mflux targets a double transformer block's `attn.to_out` as a bare Linear and exports the key `transformer_blocks.N.attn.to_out.lora_*`, but diffusers' `Flux2Attention` wraps that projection in `ModuleList([Linear, Dropout])` — PEFT needs the inner `.0`. The shared LoRA loader (`scripts/lora_utils.py`) now normalizes mflux adapters on load: it inserts the `.0` for double-block `to_out` only (single-block `to_out` is a bare Linear in diffusers and is left alone), then hands diffusers the remapped state dict. Verified against the real diffusers Flux2 structure — all 100 of the adapter's target modules resolve to `nn.Linear` after the fix. Self-healing: existing trained LoRAs are fixed at load time with no re-training or migration. Every other mflux target already matched diffusers naming. (`scripts/lora_utils.py`)
- **Trained character LoRAs now actually apply at render time (were silently ignored on quantized FLUX.2)** — A trained LoRA attached to a FLUX.2 Klein render did *nothing*: the default inference model is the **SDNQ 4-bit quantized** Klein, and PEFT can't inject an adapter into SDNQ-quantized `Linear` layers (`Target module SDNQLinear … is not supported`). The runner's LoRA loader is best-effort, so it logged the failure and rendered the **base model anyway** — every "LoRA" render was the plain base, which looked like a broken LoRA. Since a trained adapter is trained against the bf16 base, the image runner now **auto-routes any LoRA render off the quantized repo onto the gated bf16 base** (`black-forest-labs/FLUX.2-klein-{4B,9B}`, resolved from the model's size variant) with `quantization=none`; non-LoRA renders stay on the fast SDNQ/Int8 path. The bf16 base repos are now a single source of truth in `lib/runners.js` that LoRA training reuses, so the train-against and render-against repos can't drift. (`server/lib/runners.js`, `server/services/imageGen/local.js`, `server/services/loraTraining/runtimes.js`)
diff --git a/client/src/components/loraTraining/TrainingPanel.jsx b/client/src/components/loraTraining/TrainingPanel.jsx
index 830c2fdab5..e1e338b5b9 100644
--- a/client/src/components/loraTraining/TrainingPanel.jsx
+++ b/client/src/components/loraTraining/TrainingPanel.jsx
@@ -155,6 +155,25 @@ export default function TrainingPanel({ dataset, readiness, triggerSaving, onRun
)}
</div>
)}
+ {lastRun?.status === 'failed' && lastRun.errorCode === 'HF_AUTH' && (
+ <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 className="font-semibold text-sm">Model access required</div>
+ <div className="text-port-warning/90">
+ The training base model is gated on HuggingFace. Accept its license with the account
+ that owns your stored token, then retry — no token change needed.
+ </div>
+ {lastRun.errorRepo && (
+ <a
+ href={`https://huggingface.co/${lastRun.errorRepo}`}
+ 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 {lastRun.errorRepo} ↗
+ </a>
+ )}
+ </div>
+ )}
{lastRun?.status === 'completed' && (
<CheckpointPicker run={lastRun} onPromoted={refreshRuns} />
)}
diff --git a/server/lib/README.md b/server/lib/README.md
index ce2c107f00..65f6a9931a 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -90,6 +90,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `contextBudget.js` | Context-window budgeter for editorial passes. `estimateTokens` (chars/4), `usableInputTokens`, `planManuscriptPass({ contextWindow, sections })` → `{ mode: 'whole' \| 'chunked', chunks }`. Decides whole-manuscript vs chunked given a model's window. |
| `ansiStrip.js` | Streaming ANSI / control-byte stripper. |
| `hfToken.js` | HuggingFace token resolution (settings > env > CLI). |
+| `hfErrors.js` | Parse huggingface_hub gated-access errors: `extractGatedRepo(text)` → `owner/name` (or null) for the UI's license deep-link. Shared by the image runner and LoRA trainer. Pure. |
| `hfCache.js` | HuggingFace Hub cache inspection (`inspectModelCache(repoId)` → `{cached,sizeBytes,snapshotPath}`, `isModelCached`, `getHfCacheRoot`). Drives the inline "Available / Download" badge on the image + video gen forms. |
| `hfDownload.js` | `downloadHfRepo({repo,onEvent})` returning `{promise,kill}` — spawns `scripts/hf_download_repo.py` in the FLUX.2 venv (fallback: mflux pythonPath) and emits SSE-friendly stage/progress/complete events. Powers the inline "Download" button next to the model picker. |
| `sseDownload.js` | `startHfDownloadStream({req,res,repo,alreadyDownloadedMessage})`, `openSseStream(res)` (`{send,safeEnd}` SSE boilerplate), `SSE_HEADERS` — shared SSE driver used by both image and video gen `/models/:id/download` routes. Owns the cross-route in-flight Map so a double-click (or both pages running) can't spawn two python children against the same repo. |
diff --git a/server/lib/hfErrors.js b/server/lib/hfErrors.js
new file mode 100644
index 0000000000..9e7d8da544
--- /dev/null
+++ b/server/lib/hfErrors.js
@@ -0,0 +1,19 @@
+// Shared parsing of huggingface_hub gated-access error text. Both the image
+// runner (server/services/imageGen/local.js) and the LoRA trainer
+// (server/services/loraTraining/failure.js) hit gated-repo failures and want
+// to deep-link the user to the model's license page — so the `owner/name`
+// extraction lives here once instead of being re-regexed per subsystem.
+//
+// Pure, no side effects.
+
+// Matches both huggingface_hub gated-access message shapes:
+// "Access to model <repo> is restricted …" (GatedRepoError prose)
+// "Cannot access gated repo for url https://huggingface.co/<repo>/…"
+// The optional backtick tolerates markdown-wrapped repo ids; the trailing
+// `.git` strip normalizes clone-style refs.
+export const GATED_REPO_RE = /(?:Access to model|Cannot access gated repo for url https?:\/\/huggingface\.co\/)\s*`?([\w.-]+\/[\w.-]+)/i;
+
+export function extractGatedRepo(text = '') {
+ const match = String(text).match(GATED_REPO_RE);
+ return match ? match[1].replace(/\.git$/, '') : null;
+}
diff --git a/server/lib/hfErrors.test.js b/server/lib/hfErrors.test.js
new file mode 100644
index 0000000000..9b337736e5
--- /dev/null
+++ b/server/lib/hfErrors.test.js
@@ -0,0 +1,28 @@
+import { describe, it, expect } from 'vitest';
+import { extractGatedRepo } from './hfErrors.js';
+
+describe('extractGatedRepo', () => {
+ it('pulls the repo from the GatedRepoError prose', () => {
+ expect(extractGatedRepo('Access to model black-forest-labs/FLUX.2-klein-base-9B is restricted and you are not in the authorized list.'))
+ .toBe('black-forest-labs/FLUX.2-klein-base-9B');
+ expect(extractGatedRepo('Access to model meta-llama/Meta-Llama-3.1-8B-Instruct is restricted'))
+ .toBe('meta-llama/Meta-Llama-3.1-8B-Instruct');
+ });
+
+ it('pulls the repo from the "Cannot access gated repo for url" form', () => {
+ expect(extractGatedRepo('Cannot access gated repo for url https://huggingface.co/foo/bar/resolve/main/x.json'))
+ .toBe('foo/bar');
+ });
+
+ it('tolerates a markdown backtick and strips a trailing .git', () => {
+ expect(extractGatedRepo('Access to model `owner/name`')).toBe('owner/name');
+ expect(extractGatedRepo('Cannot access gated repo for url https://huggingface.co/owner/name.git/'))
+ .toBe('owner/name');
+ });
+
+ it('returns null for unrelated text and non-strings', () => {
+ expect(extractGatedRepo('some unrelated traceback line')).toBeNull();
+ expect(extractGatedRepo()).toBeNull();
+ expect(extractGatedRepo(null)).toBeNull();
+ });
+});
diff --git a/server/lib/index.js b/server/lib/index.js
index 69b1a09c98..6c25c85302 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -72,6 +72,7 @@ export * from './codexAssistantExtract.js';
export * from './codexCliOutput.js';
export * from './contextBudget.js';
export * from './hfToken.js';
+export * from './hfErrors.js';
export * from './hfCache.js';
export * from './hfDownload.js';
export * from './sseDownload.js';
diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.js
index 6d16290100..1535830907 100644
--- a/server/services/imageGen/local.js
+++ b/server/services/imageGen/local.js
@@ -26,6 +26,7 @@ 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';
+import { extractGatedRepo } from '../../lib/hfErrors.js';
import { safeChildProcessEnv } from '../../lib/processEnv.js';
import { IMAGE_GEN_MODE } from './modes.js';
import { computePixelDelta } from './regen.js';
@@ -714,13 +715,12 @@ export async function generateImage({ pythonPath, prompt = '', negativePrompt =
// 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) {
+ const gatedText = lines.join('\n');
+ const gatedRepo = extractGatedRepo(gatedText);
+ const hasGatedError = /GatedRepoError|Access to model .* is restricted/.test(gatedText);
+ if (gatedRepo || hasGatedError) {
userKind = 'gated_repo';
- userRepo = gatedUrlMatch ? gatedUrlMatch[1] : null;
+ userRepo = gatedRepo;
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.`;
}
diff --git a/server/services/loraTraining/failure.js b/server/services/loraTraining/failure.js
index f6617fa1b5..d61f12fdfb 100644
--- a/server/services/loraTraining/failure.js
+++ b/server/services/loraTraining/failure.js
@@ -4,9 +4,11 @@
* stable `{ code, message }` the run record and SSE error frame carry.
*/
+import { extractGatedRepo } from '../../lib/hfErrors.js';
+
const OOM_RE = /MPS backend out of memory|CUDA out of memory|Insufficient Memory|Metal.*out of memory|std::bad_alloc/i;
const MODULE_NOT_FOUND_RE = /ModuleNotFoundError|No module named/i;
-const HF_AUTH_RE = /GatedRepoError|401 Client Error|Repo.*is gated|Access to model .* is restricted/i;
+const HF_AUTH_RE = /GatedRepoError|401 Client Error|Repo.*is gated|Access to model .* is restricted|Cannot access gated repo/i;
// argparse rejecting the trainer's flags / model choice → the installed mflux
// predates FLUX.2 LoRA training (0.12.x wants `--train-config`, has no flux2
// base models). This is the failure that surfaced as a bare "exited with code 2".
@@ -17,10 +19,15 @@ const HF_AUTH_RE = /GatedRepoError|401 Client Error|Repo.*is gated|Access to mod
const CLI_MISMATCH_RE = /unrecognized arguments|invalid choice|the following arguments are required|mflux-train: error/i;
export function classifyTrainingFailure({ stderrTail = [], exitCode = null, signal = null, userError = null } = {}) {
+ const tail = stderrTail.join('\n');
if (userError?.message) {
- return { code: userError.kind || 'DATASET_ERROR', message: userError.message };
+ const code = userError.kind || 'DATASET_ERROR';
+ const result = { code, message: userError.message };
+ // The trainer re-emits the raw gated-repo stderr line as USER_ERROR:HF_AUTH:…,
+ // so the repo is usually already in userError.message; fall back to the tail.
+ if (code === 'HF_AUTH') result.repo = extractGatedRepo(userError.message) || extractGatedRepo(tail);
+ return result;
}
- const tail = stderrTail.join('\n');
if (OOM_RE.test(tail)) {
return {
code: 'OOM',
@@ -34,9 +41,13 @@ export function classifyTrainingFailure({ stderrTail = [], exitCode = null, sign
};
}
if (HF_AUTH_RE.test(tail)) {
+ const repo = extractGatedRepo(tail);
return {
code: 'HF_AUTH',
- message: 'Hugging Face rejected the model download — set HUGGINGFACE_API_KEY and accept the model license on huggingface.co.',
+ message: repo
+ ? `Hugging Face denied access to ${repo} — accept its license at huggingface.co, then retry.`
+ : 'Hugging Face rejected the model download — set your HuggingFace token and accept the model license on huggingface.co.',
+ repo,
};
}
if (CLI_MISMATCH_RE.test(tail)) {
diff --git a/server/services/loraTraining/failure.test.js b/server/services/loraTraining/failure.test.js
index 0bdaf304e6..8bfac9ae30 100644
--- a/server/services/loraTraining/failure.test.js
+++ b/server/services/loraTraining/failure.test.js
@@ -22,6 +22,34 @@ describe('classifyTrainingFailure', () => {
expect(classifyTrainingFailure({ stderrTail: ['GatedRepoError: 403'] }).code).toBe('HF_AUTH');
});
+ it('extracts the gated repo for the UI deep-link (USER_ERROR path)', () => {
+ // The real production path: the trainer re-emits the raw gated stderr line
+ // as USER_ERROR:HF_AUTH:<line>, so the repo rides in userError.message.
+ const out = classifyTrainingFailure({
+ userError: {
+ kind: 'HF_AUTH',
+ message: 'Access to model black-forest-labs/FLUX.2-klein-base-9B is restricted and you are not in the authorized list. Visit https://huggingface.co/black-forest-labs/FLUX.2-klein-base-9B to ask for access.',
+ },
+ });
+ expect(out.code).toBe('HF_AUTH');
+ expect(out.repo).toBe('black-forest-labs/FLUX.2-klein-base-9B');
+ });
+
+ it('extracts the gated repo from a raw stderr tail and rewrites the message', () => {
+ const out = classifyTrainingFailure({
+ stderrTail: ['Cannot access gated repo for url https://huggingface.co/black-forest-labs/FLUX.2-klein-base-9B/resolve/main/config.json.'],
+ });
+ expect(out.code).toBe('HF_AUTH');
+ expect(out.repo).toBe('black-forest-labs/FLUX.2-klein-base-9B');
+ expect(out.message).toContain('black-forest-labs/FLUX.2-klein-base-9B');
+ });
+
+ it('falls back to a null repo when no repo is parseable from an HF auth failure', () => {
+ const out = classifyTrainingFailure({ stderrTail: ['GatedRepoError: 403'] });
+ expect(out.code).toBe('HF_AUTH');
+ expect(out.repo).toBeNull();
+ });
+
it('classifies argparse CLI mismatch as a stale-mflux upgrade hint', () => {
// The exact tail the wrapper replays when mflux 0.12.x rejects --config.
// This is the REAL production path: the wrapper intentionally does NOT emit
diff --git a/server/services/loraTraining/index.js b/server/services/loraTraining/index.js
index 957e091eda..1cd4f083d4 100644
--- a/server/services/loraTraining/index.js
+++ b/server/services/loraTraining/index.js
@@ -514,15 +514,17 @@ async function finalizeTraining({ jobId, runId, code, signal, state }) {
return;
}
- const { code: failCode, message } = classifyTrainingFailure({
+ const { code: failCode, message, repo: failRepo = null } = classifyTrainingFailure({
stderrTail: state.stderrTail, exitCode: code, signal, userError: state.userError,
});
await runsDb.updateRun(runId, {
status: 'failed', completedAt: new Date().toISOString(), error: message, errorCode: failCode,
+ // Gated-repo deep-link target for the UI banner (HF_AUTH only); null otherwise.
+ errorRepo: failRepo,
}).catch(() => {});
await flipDatasetAfterRun(run?.datasetId, { trained: false });
console.error(`❌ training [${shortId(jobId)}] ${failCode}: ${message}`);
- trainingEvents.emit('failed', { generationId: jobId, error: message });
+ trainingEvents.emit('failed', { generationId: jobId, error: message, code: failCode, repo: failRepo });
}
/**