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: refuse video LoRAs whose safetensors key layout the LTX-2 loader can't fuse (#3799)
[._.]/ Adam Eivy05cf6c6a70db
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 3e2d8200b6..46fbfa6a5a 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -91,3 +91,4 @@- **A URL that doesn't match a page now says so instead of quietly depositing you on the Dashboard.** Every unmatched route — a stale bookmark, a typo, or a half-remembered path like `/annotate` (the annotator actually lives at `/media/annotate`) — hit a blanket redirect to `/`, so the user saw the page-loading spinner, then the Dashboard's skeleton widgets, then the Dashboard: indistinguishable from the app losing their navigation, with no account of what happened. Unknown routes now render a 404 page that names the path that didn't match and offers Go back, Dashboard, and a reminder that ⌘K searches every page by name. `/annotate` and `/annotate/:mediaKey` are redirected to their real `/media/annotate` home rather than being swallowed, and the annotator's own keyless state stopped reading like a loading screen: it now distinguishes "nothing selected" from "that media is no longer available" and offers **Choose media** and **Blank canvas** — the latter being the first way to start a free-standing sketch from the UI at all.- **A character repair that objectively filled the blank cast fields is no longer thrown away because the judge scored it a tie.** The foundation gate holds each repair provisional until an independent re-judge proves it helped the dimension it was asked to fix, and reverts it otherwise — the right rule for editorial work that can only be assessed by reading it. But the character dimension's core complaint is frequently a countable one ("every core character has blank physicalDescription, visualNotes, silhouetteNotes, visualIdentity and colorPalette"), and answering it is a countable act. On the observed run the repair authored all five visual fields for all five leads — roughly five minutes of a max-effort ensemble pass — the judge came back holding character at the same 5 while unrelated worldbuilding drifted 8 → 7, and the gate reverted every sheet and paused the run for review with the cast blank again. The gate now takes a second, LLM-free opinion before it reverts a *tied* character repair: it counts the blank framework and visual fields across the exact cast the repair is allowed to write (the series roster, minus locked members) before and after, and keeps the work when that count went down. A repair whose target regressed is still reverted, every other dimension is unaffected, and a repair that changed nothing measurable is still rejected — what changed is that a fact on disk now outranks a tied score.- **A local video render now tells you how long it has left, once your machine has rendered something comparable.** Local renders run 15–40+ minutes and the only progress the UI could show was a step counter — "20%" on a job that might finish in four minutes or forty, with no way to tell which. Each completed render now records its wall-clock time alongside the shape it rendered (model, resolution, frames, steps), and a new job estimates itself from that history: a run of the same shape uses the median of your own measured runs outright, a different shape is placed on a least-squares fit of cost against pixels × frames × steps, and the fit's intercept — the fixed per-render cost of loading weights and decoding — is what lets a chained multi-chunk render be estimated as N renders rather than one long one. The estimate rides the render's started/progress events through to the client, where the progress bar reads "20% · ~18m 30s left". An install that has never measured a comparable render reports no estimate at all rather than a fabricated one, and the progress bar simply shows the percentage as before.+- **A video LoRA in the wrong key layout is now refused with the reason instead of quietly rendering an un-LoRA'd clip.** Downloaded LoRAs ship in several incompatible safetensors key conventions, and the LTX-2 loader fuses exactly one of them: `lora_A`/`lora_B` rank pairs, optionally under a `diffusion_model.` prefix. A kohya/LyCORIS file (`lora_down`/`lora_up` + `alpha`) or a diffusers/PEFT-prefixed file matches nothing in the transformer — so the render burned its full GPU time and came back looking like the LoRA had never been selected, with no error anywhere to explain it. Confusingly, kohya files are commonly published *with* the ComfyUI `diffusion_model.` prefix, so the prefix alone was never a reliable signal. PortOS now classifies the layout from the safetensors header (`bare` / `comfyui` / `diffusers` / `kohya` / `not_a_lora`) at install time, records it in the LoRA's sidecar, and backfills it on the next listing for LoRAs installed earlier. A render that selects an un-fusable one fails up front with a 400 naming the layout and what to use instead. A file whose header can't be read stays "undetermined" and is still allowed through — unreadable is not the same as unusable.diff --git a/server/lib/README.md b/server/lib/README.mdindex 8419c274be..8b1c07c568 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -164,7 +164,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `threejsModelRig.js` | `evaluateThreejsRigReadiness(spec)` — honest rig-readiness report over an already-validated Three.js spec: `{ articulationReady, reasons, jointCount, socketCount, attachmentCount, rootJointId, subjectType }`. The schema proves the optional `articulation` graph is well *formed* (one root, no cycles or forward refs, joints and pivots pointed at real parts/sockets); this reports whether it is *useful* (more than a lone root, every child joint carrying a pivot axis) and names the reason when it is not. It reports rather than rejects, and never claims skinning: PortOS generates static assemblies and declared articulation intent, not skeletons or bind poses. || `pgFileFacade.js` | Shared PG/file store-backend backbone for the six storage dispatchers (pipeline series/issues, story builder, universe builder, catalog user-types, writers room). `isFileBackend()` (dev/test escape-hatch predicate) · `resolvePgBackend({ requirement, migrate?, loadDb, makePg })` (health-check → `ensureSchema` → one-time migration → import `db.js` → build the PG backend) · `createPgFileFacade({ makeFile, makePg })` (promise-memoized lazy selection so concurrent first calls don't run the migration twice; returns `{ getBackend, getBackendName, reset }`). Each store keeps its own `makeFile`/`makePg` factories + public surface. `createRecordStoreBackendSelector({ label, loadFileBackend, loadDbBackend, requireDbMessage?, isTestMode?, onDbReady? })` wraps the same backbone for the stores whose backends are whole MODULES rather than built objects (Creative Director, Music Video, Sprites) → `{ selectBackend, getBackendName }` where the name is `'file'`/`'postgres'`; `isTestMode` lets a store use the stronger `isTestRunner()` signal (Sprites). || `multipart.js` | Streaming multipart/form-data parser. |-| `safetensors.js` | `readSafetensorsHeader(path)` reads only the JSON header of a `.safetensors` file (never the tensor payload). `detectFlux2VariantFromHeader(header)` / `detectFlux2Variant(path)` classify a LoRA as FLUX.2 Klein `'4b'` (hidden dim 3072) vs `'9b'` (4096) by transformer-block tensor shapes, so the LoRA picker can hide off-variant weights that would silently fail to load. |+| `safetensors.js` | `readSafetensorsHeader(path)` reads only the JSON header of a `.safetensors` file (never the tensor payload). `detectFlux2VariantFromHeader(header)` / `detectFlux2Variant(path)` classify a LoRA as FLUX.2 Klein `'4b'` (hidden dim 3072) vs `'9b'` (4096) by transformer-block tensor shapes, so the LoRA picker can hide off-variant weights that would silently fail to load. `classifyLoraKeyLayoutFromHeader(header)` / `classifyLoraKeyLayout(path)` classify the key layout as `LORA_KEY_LAYOUTS` (`bare` / `comfyui` / `diffusers` / `kohya` / `not_a_lora`, `null` = unreadable), and `videoLoraLayoutIssue(layout)` returns the user-facing reason a layout can't fuse into the LTX-2 video transformer (or `null` when it can). || `pdfImageEmbed.js` | PDF image embed helpers for comic / volume PDFs. || `zipStream.js` | Streaming ZIP parser (`parseZip`, unzipper-style); `collectZipEntry(entry, maxBytes?)` buffers one `parseZip` entry into a Buffer (size-capped); `collectZipEntries(path, { match, onMatch, maxBytes? })` owns the multi-entry import lifecycle (teardown, autodrain, per-entry await) leaving callers only match/parse; `isZipUpload(file)` predicate for an uploaded ZIP; `extractZipEntryToBuffer(path, match)` cracks one member out to a Buffer. || `zipWriter.js` | Minimal ZIP writer — `createZip(entries)` builds a stored (uncompressed) archive Buffer that round-trips through `parseZip`; `crc32(buf)` is the dependency-free checksum it uses. |diff --git a/server/lib/safetensors.js b/server/lib/safetensors.jsindex 1121bbc644..ca71701824 100644--- a/server/lib/safetensors.js+++ b/server/lib/safetensors.js@@ -95,3 +95,125 @@ export const detectFlux2VariantFromHeader = (header) => {*/export const detectFlux2Variant = async (path) =>detectFlux2VariantFromHeader(await readSafetensorsHeader(path));++/**+ * LoRA safetensors key layouts.+ *+ * Downloaded LoRAs ship in several mutually incompatible key conventions, and+ * a runtime that fuses one layout silently no-ops (or renders noise) on+ * another. The layout is fully determined by the tensor names in the header,+ * so we classify it once at install time instead of discovering it as an+ * opaque failure deep inside a Python render.+ *+ * - `bare` — module paths with no wrapper prefix:+ * `transformer_blocks.0.attn1.to_k.lora_A.weight`+ * - `comfyui` — the same paths under a `diffusion_model.` prefix (what+ * ComfyUI-targeted LTX-2 / WAN LoRAs ship as). The LTX-2 MLX+ * loader strips that prefix itself, so it is fusable.+ * - `diffusers` — PEFT/diffusers wrapper prefixes (`transformer.`,+ * `base_model.model.`, `unet.`, `text_encoder…`). Fusable for+ * diffusers-based image runners, NOT for the LTX-2 video+ * loader (whose keys carry no such prefix).+ * - `kohya` — kohya_ss / LyCORIS training output: `lora_down.weight` ++ * `lora_up.weight` pairs (usually with `lora_unet_…`+ * underscore-flattened module names and per-module `alpha`+ * scalars). Never fusable by an `lora_A`/`lora_B` reader.+ * - `not_a_lora`— header parsed fine but holds no LoRA tensors at all (a full+ * checkpoint, a VAE, an embedding).+ *+ * `null` (rather than a member of this map) is the "couldn't determine"+ * sentinel — an unreadable/corrupt/non-safetensors file. Callers must NOT+ * treat it as `not_a_lora`.+ */+export const LORA_KEY_LAYOUTS = Object.freeze({+ BARE: 'bare',+ COMFYUI: 'comfyui',+ DIFFUSERS: 'diffusers',+ KOHYA: 'kohya',+ NOT_A_LORA: 'not_a_lora',+});++export const LORA_KEY_LAYOUT_VALUES = Object.freeze(Object.values(LORA_KEY_LAYOUTS));++// `lora_A` / `lora_B` (diffusers/PEFT rank pair) anywhere in a dotted key.+const LORA_AB_RE = /(^|\.)lora_(A|B)(\.|$)/;+// kohya/LyCORIS rank pair. Also matched under a `diffusion_model.` prefix —+// real-world LTX-2 LoRAs ship `diffusion_model.<path>.lora_down.weight`, which+// looks ComfyUI-shaped but is NOT fusable by an lora_A/lora_B reader.+const LORA_DOWN_UP_RE = /(^|\.)lora_(down|up)(\.|$)/;+// kohya's underscore-flattened module namespace (`lora_unet_…`, `lora_te1_…`).+const KOHYA_PREFIX_RE = /^lora_(unet|te\d*)_/;+// diffusers / PEFT wrapper prefixes.+const DIFFUSERS_PREFIX_RE = /^(transformer|base_model|unet|text_encoder\w*)\./;++/**+ * Classify the LoRA key layout of a parsed safetensors header. Returns one of+ * `LORA_KEY_LAYOUTS`, or `null` when the header is missing/unparsable.+ *+ * Mixed files exist (a kohya LoRA that also ships a `diffusion_model.`-prefixed+ * copy of the same deltas), so each tensor votes and the winner is the most+ * common layout. Ties resolve toward the least-fusable layout — refusing a+ * render with a clear reason beats emitting noise.+ */+export const classifyLoraKeyLayoutFromHeader = (header) => {+ if (!header || typeof header !== 'object') return null;+ const counts = {+ [LORA_KEY_LAYOUTS.KOHYA]: 0,+ [LORA_KEY_LAYOUTS.DIFFUSERS]: 0,+ [LORA_KEY_LAYOUTS.COMFYUI]: 0,+ [LORA_KEY_LAYOUTS.BARE]: 0,+ };+ for (const name of Object.keys(header)) {+ if (name === '__metadata__') continue;+ if (KOHYA_PREFIX_RE.test(name) || LORA_DOWN_UP_RE.test(name)) {+ counts[LORA_KEY_LAYOUTS.KOHYA] += 1;+ continue;+ }+ // Everything below needs an actual rank tensor — bare `alpha` scalars and+ // non-LoRA tensors carry no layout signal of their own.+ if (!LORA_AB_RE.test(name)) continue;+ if (name.startsWith('diffusion_model.')) counts[LORA_KEY_LAYOUTS.COMFYUI] += 1;+ else if (DIFFUSERS_PREFIX_RE.test(name)) counts[LORA_KEY_LAYOUTS.DIFFUSERS] += 1;+ else counts[LORA_KEY_LAYOUTS.BARE] += 1;+ }+ // Object.keys order here is the tie-break order (least fusable first).+ let winner = null;+ let best = 0;+ for (const [layout, n] of Object.entries(counts)) {+ if (n > best) {+ best = n;+ winner = layout;+ }+ }+ return winner || LORA_KEY_LAYOUTS.NOT_A_LORA;+};++/**+ * Convenience: read a file and classify its LoRA key layout in one call.+ * Returns a `LORA_KEY_LAYOUTS` value, or `null` when the file can't be read.+ */+export const classifyLoraKeyLayout = async (path) =>+ classifyLoraKeyLayoutFromHeader(await readSafetensorsHeader(path));++// Layouts the LTX-2 MLX loader can actually fuse. Its fuser pairs+// `<module>.lora_A.weight` with `<module>.lora_B.weight` after stripping a+// leading `diffusion_model.` — so bare and ComfyUI-prefixed files work, and+// nothing else does.+const VIDEO_FUSABLE_LAYOUTS = new Set([LORA_KEY_LAYOUTS.BARE, LORA_KEY_LAYOUTS.COMFYUI]);++/**+ * Why a layout can't be fused into the LTX-2 video transformer, as a+ * user-facing phrase — or `null` when it is fusable. `null` layout (couldn't+ * classify) is deliberately permissive: an unreadable header is not evidence+ * of an unusable file, and the caller already checked the file exists.+ */+export const videoLoraLayoutIssue = (layout) => {+ if (layout == null || VIDEO_FUSABLE_LAYOUTS.has(layout)) return null;+ if (layout === LORA_KEY_LAYOUTS.KOHYA) {+ return 'it uses the kohya/LyCORIS key layout (lora_down/lora_up + alpha), which the LTX-2 loader cannot fuse — it only reads lora_A/lora_B pairs. Re-export it in the ComfyUI (diffusion_model.*) layout, or pick a LoRA published for ComfyUI';+ }+ if (layout === LORA_KEY_LAYOUTS.DIFFUSERS) {+ return 'it uses the diffusers/PEFT key layout, whose alpha/rank scale is not stored in the file — applying it to the video transformer would be guesswork. Use a LoRA published for ComfyUI (diffusion_model.*) instead';+ }+ return 'it contains no LoRA tensors at all — this looks like a checkpoint or embedding, not a LoRA';+};diff --git a/server/lib/safetensors.test.js b/server/lib/safetensors.test.jsindex 1b77fd99f0..751e900815 100644--- a/server/lib/safetensors.test.js+++ b/server/lib/safetensors.test.js@@ -7,6 +7,10 @@ import {readSafetensorsHeader,detectFlux2VariantFromHeader,detectFlux2Variant,+ classifyLoraKeyLayoutFromHeader,+ classifyLoraKeyLayout,+ videoLoraLayoutIssue,+ LORA_KEY_LAYOUTS,} from './safetensors.js';// Build a valid safetensors file buffer from a header object: 8-byte LE u64@@ -113,3 +117,102 @@ describe('detectFlux2Variant (file)', () => {expect(await detectFlux2Variant(p)).toBeNull();});});++describe('classifyLoraKeyLayoutFromHeader', () => {+ it('classifies bare module-path lora_A/lora_B keys', () => {+ expect(classifyLoraKeyLayoutFromHeader({+ 'transformer_blocks.0.attn1.to_k.lora_A.weight': { shape: [32, 2048] },+ 'transformer_blocks.0.attn1.to_k.lora_B.weight': { shape: [2048, 32] },+ })).toBe(LORA_KEY_LAYOUTS.BARE);+ });++ it('classifies ComfyUI diffusion_model.-prefixed keys', () => {+ expect(classifyLoraKeyLayoutFromHeader({+ 'diffusion_model.transformer_blocks.0.attn1.to_k.lora_A.weight': { shape: [32, 2048] },+ 'diffusion_model.transformer_blocks.0.attn1.to_k.lora_B.weight': { shape: [2048, 32] },+ })).toBe(LORA_KEY_LAYOUTS.COMFYUI);+ });++ it('classifies diffusers/PEFT wrapper prefixes', () => {+ expect(classifyLoraKeyLayoutFromHeader({+ 'transformer.single_transformer_blocks.0.attn.to_out.lora_A.weight': { shape: [32, 3072] },+ 'transformer.single_transformer_blocks.0.attn.to_out.lora_B.weight': { shape: [3072, 32] },+ })).toBe(LORA_KEY_LAYOUTS.DIFFUSERS);+ expect(classifyLoraKeyLayoutFromHeader({+ 'base_model.model.blocks.0.attn.q.lora_A.weight': { shape: [16, 1024] },+ })).toBe(LORA_KEY_LAYOUTS.DIFFUSERS);+ });++ it('classifies kohya lora_unet_ + lora_down/lora_up keys', () => {+ expect(classifyLoraKeyLayoutFromHeader({+ 'lora_unet_transformer_blocks_0_attn1_to_k.alpha': { shape: [] },+ 'lora_unet_transformer_blocks_0_attn1_to_k.lora_down.weight': { shape: [32, 2048] },+ 'lora_unet_transformer_blocks_0_attn1_to_k.lora_up.weight': { shape: [2048, 32] },+ })).toBe(LORA_KEY_LAYOUTS.KOHYA);+ });++ it('calls a diffusion_model.-prefixed lora_down/lora_up file kohya, not comfyui', () => {+ // Real-world shape: the ComfyUI prefix is present but the rank pair is+ // kohya's, so an lora_A/lora_B fuser matches nothing.+ expect(classifyLoraKeyLayoutFromHeader({+ 'diffusion_model.transformer_blocks.0.attn1.to_k.alpha': { shape: [] },+ 'diffusion_model.transformer_blocks.0.attn1.to_k.lora_down.weight': { shape: [32, 2048] },+ 'diffusion_model.transformer_blocks.0.attn1.to_k.lora_up.weight': { shape: [2048, 32] },+ })).toBe(LORA_KEY_LAYOUTS.KOHYA);+ });++ it('picks the dominant layout in a mixed-layout file', () => {+ const header = {+ 'diffusion_model.transformer_blocks.0.attn1.to_k.lora_down.weight': { shape: [32, 2048] },+ 'diffusion_model.transformer_blocks.0.attn1.to_k.lora_up.weight': { shape: [2048, 32] },+ 'lora_unet_transformer_blocks_0_attn1_to_k.lora_down.weight': { shape: [32, 2048] },+ 'lora_unet_transformer_blocks_0_attn1_to_k.lora_up.weight': { shape: [2048, 32] },+ 'diffusion_model.transformer_blocks.1.attn1.to_k.lora_A.weight': { shape: [32, 2048] },+ };+ expect(classifyLoraKeyLayoutFromHeader(header)).toBe(LORA_KEY_LAYOUTS.KOHYA);+ });++ it('returns not_a_lora for a header with no LoRA tensors', () => {+ expect(classifyLoraKeyLayoutFromHeader({+ 'transformer_blocks.0.attn1.to_k.weight': { shape: [2048, 2048] },+ __metadata__: { format: 'pt' },+ })).toBe(LORA_KEY_LAYOUTS.NOT_A_LORA);+ });++ it('returns null (undetermined, NOT not_a_lora) for an unparsable header', () => {+ expect(classifyLoraKeyLayoutFromHeader(null)).toBeNull();+ expect(classifyLoraKeyLayoutFromHeader('nope')).toBeNull();+ });+});++describe('classifyLoraKeyLayout (file)', () => {+ it('reads + classifies in one call', async () => {+ const p = writeTmp('comfy.safetensors', makeFile({+ 'diffusion_model.transformer_blocks.0.attn1.to_k.lora_A.weight': { shape: [32, 2048] },+ }));+ expect(await classifyLoraKeyLayout(p)).toBe(LORA_KEY_LAYOUTS.COMFYUI);+ });++ it('returns null for a non-safetensors file', async () => {+ const p = writeTmp('garbage.safetensors', Buffer.from('garbage'));+ expect(await classifyLoraKeyLayout(p)).toBeNull();+ });+});++describe('videoLoraLayoutIssue', () => {+ it('passes the two fusable layouts', () => {+ expect(videoLoraLayoutIssue(LORA_KEY_LAYOUTS.BARE)).toBeNull();+ expect(videoLoraLayoutIssue(LORA_KEY_LAYOUTS.COMFYUI)).toBeNull();+ });++ it('is permissive when the layout is undetermined', () => {+ expect(videoLoraLayoutIssue(null)).toBeNull();+ expect(videoLoraLayoutIssue(undefined)).toBeNull();+ });++ it('names the layout and the reason for un-fusable files', () => {+ expect(videoLoraLayoutIssue(LORA_KEY_LAYOUTS.KOHYA)).toMatch(/kohya/i);+ expect(videoLoraLayoutIssue(LORA_KEY_LAYOUTS.DIFFUSERS)).toMatch(/diffusers/i);+ expect(videoLoraLayoutIssue(LORA_KEY_LAYOUTS.NOT_A_LORA)).toMatch(/no LoRA tensors/i);+ });+});diff --git a/server/services/loras.js b/server/services/loras.jsindex 0103dbe8ec..16860f73c6 100644--- a/server/services/loras.js+++ b/server/services/loras.js@@ -52,7 +52,12 @@ import {pickHfLoraFile,} from '../lib/huggingfaceLora.js';import { RUNNER_FAMILIES, VIDEO_LORA_FAMILIES, composeCompatKey } from '../lib/runners.js';-import { detectFlux2Variant } from '../lib/safetensors.js';+import {+ classifyLoraKeyLayout,+ classifyLoraKeyLayoutFromHeader,+ detectFlux2VariantFromHeader,+ readSafetensorsHeader,+} from '../lib/safetensors.js';import { getHfToken } from '../lib/hfToken.js';import { getSettings } from './settings.js';@@ -128,17 +133,36 @@ export const listLoras = async () => {// Civitai metadata). Persist a header-detected value back so the header// is read at most once per LoRA. Mirrors the "re-derive runnerFamily on// read" healing above.+ //+ // Both header-derived fields below share ONE lazy header read (a LoRA+ // whose sidecar already answers never opens the file), and they heal the+ // sidecar through a SINGLE patch — two fire-and-forget patches would+ // read-modify-write the same sidecar concurrently and drop one field.+ let headerPromise = null;+ const readHeaderOnce = () => {+ if (!headerPromise) headerPromise = readSafetensorsHeader(_fullPath);+ return headerPromise;+ };+ const backfill = {};let fluxVariant = null;if (runnerFamily === RUNNER_FAMILIES.FLUX2) {fluxVariant = sidecar?.fluxVariant || flux2VariantFromBaseModel(baseModel);if (!fluxVariant) {- fluxVariant = await detectFlux2Variant(_fullPath);- if (fluxVariant) {- // Best-effort cache — never block or fail the list on a write error.- patchLoraSidecar(filename, { fluxVariant }).catch(() => {});- }+ fluxVariant = detectFlux2VariantFromHeader(await readHeaderOnce());+ if (fluxVariant) backfill.fluxVariant = fluxVariant;}}+ // Safetensors key layout ('bare'/'comfyui'/'diffusers'/'kohya'/+ // 'not_a_lora'). Backfilled for LoRAs installed before installs recorded+ // it. `null` means "couldn't read the header", which we deliberately+ // don't persist: it's not a classification, and a later read may succeed.+ let keyLayout = sidecar?.keyLayout || null;+ if (!keyLayout) {+ keyLayout = classifyLoraKeyLayoutFromHeader(await readHeaderOnce());+ if (keyLayout) backfill.keyLayout = keyLayout;+ }+ // Best-effort cache — never block or fail the list on a write error.+ if (Object.keys(backfill).length > 0) patchLoraSidecar(filename, backfill).catch(() => {});// The picker matches this against the selected model's `loraCompatKey`.// FLUX.2 → size-specific (or bare 'flux2' when size is unknown, so it// still shows for both sizes); every other family → its runner id.@@ -156,6 +180,7 @@ export const listLoras = async () => {huggingface: sidecar?.huggingface || null,runnerFamily,fluxVariant,+ keyLayout,loraCompatKey,triggerWords: sidecar?.triggerWords || [],// Coerce non-finite values (NaN, Infinity, missing/malformed sidecar@@ -243,6 +268,30 @@ export const patchLoraSidecar = async (filename, patch) => {return next;};+// Stamp the classified safetensors key layout onto a freshly-built sidecar so+// consumers (the video-LoRA fusion gate) never have to re-read the header.+// Omits the field entirely when classification fails — a `null` there would be+// indistinguishable from "already classified as nothing" and would defeat the+// heal-on-read backfill in listLoras().+const withKeyLayout = async (sidecar, destPath) => {+ const keyLayout = await classifyLoraKeyLayout(destPath);+ return keyLayout ? { ...sidecar, keyLayout } : sidecar;+};++/**+ * Resolve one LoRA's safetensors key layout: the sidecar value when present,+ * else classified from the file header. Returns `null` when the header can't+ * be read (the "couldn't determine" sentinel — NOT `'not_a_lora'`).+ *+ * Deliberately does not persist a header-derived value: the callers are render+ * hot paths, and listLoras() already owns the backfill-and-cache duty.+ */+export const getLoraKeyLayout = async (filename) => {+ const sidecar = await readSidecar(filename);+ if (sidecar?.keyLayout) return sidecar.keyLayout;+ return classifyLoraKeyLayout(join(PATHS.loras, filename));+};+// Resolve the active Civitai API key — either from settings (`civitai.apiKey`)// or the CIVITAI_API_KEY env var. Settings wins so a user can override the// env without restarting. Returns empty string for "no key", which the@@ -478,9 +527,9 @@ export const installFromCivitai = async (input, { fetchImpl = fetch } = {}) => {});await verifyDownloadedLora(destPath, { expectedSha256: file?.hashes?.SHA256 || null, source: 'civitai' });- const sidecar = buildSidecar({ model, version, file, filename });+ const sidecar = await withKeyLayout(buildSidecar({ model, version, file, filename }), destPath);await atomicWrite(sidecarPath(filename), JSON.stringify(sidecar, null, 2) + '\n');- console.log(`✅ Installed Civitai LoRA: ${filename}`);+ console.log(`✅ Installed Civitai LoRA: ${filename} [layout=${sidecar.keyLayout || 'unknown'}]`);return sidecar;};@@ -561,8 +610,11 @@ export const installFromHuggingface = async (input, { fetchImpl = fetch, onProgr// sha256 compare available for this path).await verifyDownloadedLora(destPath, { source: 'huggingface' });- const sidecar = buildHfLoraSidecar({ repo, revision, file, model, family, filename });+ const sidecar = await withKeyLayout(+ buildHfLoraSidecar({ repo, revision, file, model, family, filename }),+ destPath,+ );await atomicWrite(sidecarPath(filename), JSON.stringify(sidecar, null, 2) + '\n');- console.log(`✅ Installed HuggingFace LoRA: ${filename}`);+ console.log(`✅ Installed HuggingFace LoRA: ${filename} [layout=${sidecar.keyLayout || 'unknown'}]`);return sidecar;};diff --git a/server/services/loras.test.js b/server/services/loras.test.jsindex 9ea1b82acd..100906bc99 100644--- a/server/services/loras.test.js+++ b/server/services/loras.test.js@@ -657,3 +657,57 @@ describe('installFromHuggingface', () => {expect(existsSync(join(tmpLoras, 'lora-fal-ltx2.3-audio-reactive-lora-hf.safetensors'))).toBe(false);});});++describe('LoRA key layout', () => {+ const writeLora = async (name, header) => {+ const fs = await import('fs/promises');+ await fs.mkdir(tmpLoras, { recursive: true });+ await fs.writeFile(join(tmpLoras, name), validSafetensors(header));+ };++ it('classifies and backfills keyLayout into the sidecar on list', async () => {+ const fs = await import('fs/promises');+ await writeLora('lora-comfy.safetensors', {+ 'diffusion_model.transformer_blocks.0.attn1.to_k.lora_A.weight': { dtype: 'F16', shape: [32, 2048], data_offsets: [0, 1] },+ });+ const list = await lorasService.listLoras();+ expect(list.find((l) => l.filename === 'lora-comfy.safetensors').keyLayout).toBe('comfyui');+ // Sidecar write is fire-and-forget; let the microtask queue drain.+ await new Promise((r) => setTimeout(r, 10));+ const sidecar = JSON.parse(await fs.readFile(join(tmpLoras, 'lora-comfy.safetensors.metadata.json'), 'utf-8'));+ expect(sidecar.keyLayout).toBe('comfyui');+ });++ it('prefers the stored sidecar layout over re-reading the header', async () => {+ const fs = await import('fs/promises');+ await fs.mkdir(tmpLoras, { recursive: true });+ // Unreadable file — a header read would yield null, so a 'comfyui' result+ // can only have come from the sidecar.+ await fs.writeFile(join(tmpLoras, 'lora-stored.safetensors'), 'garbage');+ await fs.writeFile(join(tmpLoras, 'lora-stored.safetensors.metadata.json'), JSON.stringify({+ filename: 'lora-stored.safetensors', keyLayout: 'comfyui',+ }));+ const list = await lorasService.listLoras();+ expect(list.find((l) => l.filename === 'lora-stored.safetensors').keyLayout).toBe('comfyui');+ expect(await lorasService.getLoraKeyLayout('lora-stored.safetensors')).toBe('comfyui');+ });++ it('reports null (not not_a_lora) when the header is unreadable', async () => {+ const fs = await import('fs/promises');+ await fs.mkdir(tmpLoras, { recursive: true });+ await fs.writeFile(join(tmpLoras, 'lora-corrupt.safetensors'), 'garbage');+ const list = await lorasService.listLoras();+ expect(list.find((l) => l.filename === 'lora-corrupt.safetensors').keyLayout).toBe(null);+ expect(await lorasService.getLoraKeyLayout('lora-corrupt.safetensors')).toBe(null);+ // Nothing persisted — a later read may succeed.+ expect(existsSync(join(tmpLoras, 'lora-corrupt.safetensors.metadata.json'))).toBe(false);+ });++ it('getLoraKeyLayout classifies from the header when no sidecar exists', async () => {+ await writeLora('lora-kohya.safetensors', {+ 'lora_unet_transformer_blocks_0_attn1_to_k.lora_down.weight': { dtype: 'F16', shape: [32, 2048], data_offsets: [0, 1] },+ 'lora_unet_transformer_blocks_0_attn1_to_k.lora_up.weight': { dtype: 'F16', shape: [2048, 32], data_offsets: [1, 2] },+ });+ expect(await lorasService.getLoraKeyLayout('lora-kohya.safetensors')).toBe('kohya');+ });+});diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.jsindex d5c521a9dc..3f5a0a9434 100644--- a/server/services/videoGen/local.js+++ b/server/services/videoGen/local.js@@ -22,6 +22,7 @@ import { spawnDetached } from '../../lib/detachedSpawn.js';import { killWithEscalation } from '../../lib/killWithEscalation.js';import { createLineReader } from '../../lib/streamLines.js';import { ServerError } from '../../lib/errorHandler.js';+import { videoLoraLayoutIssue } from '../../lib/safetensors.js';import { videoGenEvents } from './events.js';import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay, PYTHON_NOISE_RE } from '../../lib/sseUtils.js';import { getVideoModels, getDefaultVideoModelId, getTextEncoderRepo } from '../../lib/mediaModels.js';@@ -38,7 +39,7 @@ import { hfChildEnv } from '../../lib/hfToken.js';import { inspectModelCache, findCachedRepoFile } from '../../lib/hfCache.js';import { safeChildProcessEnv } from '../../lib/processEnv.js';import { makeVideoGenLineHandler, finalizeGeneratedVideo, isWatchdogSuccess, describeSignalDeath, describeRenderConditioning, RENDER_INPUTS_VERSION } from './generateVideoHelpers.js';-import { assertSafeLoraFilename } from '../loras.js';+import { assertSafeLoraFilename, getLoraKeyLayout } from '../loras.js';import { isMlxVideoLtxLoraCapable } from '../../lib/runners.js';import {isVideoModelTermsAccepted, acceptedVideoModelTerms, videoModelTermsGateId, videoModelTermsError,@@ -296,17 +297,36 @@ export const resolveT2vTwoStageOverride = ({// Python FileNotFoundError deep inside the render. Returns [] for no LoRAs.// Only the ltx2 runtime consumes the result; buildArgs rejects LoRAs on the// other runtimes before this is even reached for a doomed job.-export const resolveVideoLoras = (loras) => {+//+// Also gates on the safetensors KEY LAYOUT. The loader fuses `lora_A`/`lora_B`+// pairs after stripping a leading `diffusion_model.`, so a kohya (lora_down/+// lora_up) or diffusers/PEFT-prefixed file matches nothing: the render burns+// minutes of GPU time and comes back as an un-LoRA'd (or noisy) clip with no+// error anywhere. Refuse it up front with the layout named.+export const resolveVideoLoras = async (loras) => {if (!Array.isArray(loras) || loras.length === 0) return [];- return loras.map((l) => {+ const out = [];+ for (const l of loras) {assertSafeLoraFilename(l?.filename);const path = join(PATHS.loras, l.filename);if (!existsSync(path)) {throw new ServerError(`LoRA not found: ${l.filename}`, { status: 400, code: 'LORA_NOT_FOUND' });}+ const layout = await getLoraKeyLayout(l.filename);+ const issue = videoLoraLayoutIssue(layout);+ if (issue) {+ throw new ServerError(+ `LoRA "${l.filename}" can't be used for video: ${issue}.`,+ { status: 400, code: 'LORA_LAYOUT_UNSUPPORTED' },+ );+ }+ if (layout == null) {+ console.log(`⚠️ LoRA key layout undetermined for ${l.filename} — fusing anyway`);+ }const strength = Number.isFinite(l?.scale) ? l.scale : 1.0;- return { path, strength, filename: l.filename };- });+ out.push({ path, strength, filename: l.filename });+ }+ return out;};// Build the spawn args for dgrauet's ltx-2-mlx runtime via our Python helper.@@ -960,7 +980,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m// missing/typo'd LoRA fails with a clean 400 before any GPU work. buildArgs// rejects LoRAs on non-ltx2 runtimes (the route also guards), so this is a// no-op there.- const resolvedLoras = resolveVideoLoras(loras);+ const resolvedLoras = await resolveVideoLoras(loras);// IC-LoRA remix: resolve the per-mode weight before any GPU work. A cached// weight resolves to the exact file inside the HF snapshot; an un-cached onediff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.jsindex 179f3590eb..65e0e52e09 100644--- a/server/services/videoGen/local.test.js+++ b/server/services/videoGen/local.test.js@@ -166,6 +166,15 @@ vi.mock('fs', () => ({statSync: vi.fn(() => ({ size: 1000 })),}));+// LoRA key-layout gate (resolveVideoLoras). `null` = undetermined, which is+// the permissive default so the pre-existing LoRA-threading tests below still+// reach the spawn path; the gate's own tests set a layout explicitly.+const loraLayoutState = vi.hoisted(() => ({ layout: null }));+vi.mock('../loras.js', () => ({+ assertSafeLoraFilename: vi.fn(),+ getLoraKeyLayout: vi.fn(async () => loraLayoutState.layout),+}));+vi.mock('fs/promises', () => ({unlink: vi.fn(async () => {}),writeFile: vi.fn(async () => {}),@@ -3076,3 +3085,62 @@ describe('generateVideo — history-calibrated ETA (#3801)', () => {expect(started.etaBasis).toBe('proportional');});});++describe('resolveVideoLoras — safetensors key-layout gate', () => {+ let resolveVideoLoras;+ beforeEach(async () => {+ vi.resetModules();+ loraLayoutState.layout = null;+ ({ resolveVideoLoras } = await import('./local.js'));+ });+ afterEach(() => { loraLayoutState.layout = null; });++ it('resolves bare and ComfyUI layouts (the two the loader can fuse)', async () => {+ for (const layout of ['bare', 'comfyui']) {+ loraLayoutState.layout = layout;+ expect(await resolveVideoLoras([{ filename: 'style.safetensors', scale: 0.7 }])).toEqual([+ { path: join(MOCK_PATHS.loras, 'style.safetensors'), strength: 0.7, filename: 'style.safetensors' },+ ]);+ }+ });++ it('rejects a kohya-layout LoRA with an actionable 400 naming the layout', async () => {+ loraLayoutState.layout = 'kohya';+ await expect(resolveVideoLoras([{ filename: 'style.safetensors', scale: 1.0 }]))+ .rejects.toMatchObject({ status: 400, code: 'LORA_LAYOUT_UNSUPPORTED' });+ await expect(resolveVideoLoras([{ filename: 'style.safetensors' }]))+ .rejects.toThrow(/kohya/i);+ });++ it('rejects diffusers/PEFT and non-LoRA files too', async () => {+ loraLayoutState.layout = 'diffusers';+ await expect(resolveVideoLoras([{ filename: 'style.safetensors' }])).rejects.toThrow(/diffusers/i);+ loraLayoutState.layout = 'not_a_lora';+ await expect(resolveVideoLoras([{ filename: 'ckpt.safetensors' }])).rejects.toThrow(/no LoRA tensors/i);+ });++ it('rejects the whole render when ANY selected LoRA is un-fusable', async () => {+ const layouts = { 'ok.safetensors': 'comfyui', 'bad.safetensors': 'kohya' };+ const { getLoraKeyLayout } = await import('../loras.js');+ vi.mocked(getLoraKeyLayout).mockImplementation(async (f) => layouts[f] ?? null);+ await expect(resolveVideoLoras([+ { filename: 'ok.safetensors' }, { filename: 'bad.safetensors' },+ ])).rejects.toThrow(/bad\.safetensors/);+ vi.mocked(getLoraKeyLayout).mockImplementation(async () => loraLayoutState.layout);+ });++ it('passes an undetermined layout through rather than blocking the render', async () => {+ loraLayoutState.layout = null;+ const resolved = await resolveVideoLoras([{ filename: 'mystery.safetensors' }]);+ expect(resolved).toHaveLength(1);+ expect(resolved[0].strength).toBe(1.0);+ });++ it('returns [] for no LoRAs without consulting the layout', async () => {+ const { getLoraKeyLayout } = await import('../loras.js');+ vi.mocked(getLoraKeyLayout).mockClear();+ expect(await resolveVideoLoras([])).toEqual([]);+ expect(await resolveVideoLoras(undefined)).toEqual([]);+ expect(getLoraKeyLayout).not.toHaveBeenCalled();+ });+});