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: validate stored LoRA layouts and match lowercase lora_a/lora_b keys (#3799)
[._.]/ Adam Eivy3a28510b9014
diff --git a/.gitignore b/.gitignoreindex bdcc3d67b0..f2b8b32acd 100644--- a/.gitignore+++ b/.gitignore@@ -15,6 +15,10 @@ build/data/*!data/.gitkeep+# Scratch dir the provider-status suite writes under server/ while it runs —+# transient, but long-lived enough for a concurrent `git add -A` to catch it.+server/test-data-status/+# Environment files.env.env.localdiff --git a/server/lib/README.md b/server/lib/README.mdindex 8b1c07c568..d38c391a07 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. `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). |+| `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), `isKnownLoraKeyLayout(layout)` validates a layout read back out of persisted state, 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 ca71701824..87dd6439f1 100644--- a/server/lib/safetensors.js+++ b/server/lib/safetensors.js@@ -135,14 +135,25 @@ export const LORA_KEY_LAYOUTS = Object.freeze({export const LORA_KEY_LAYOUT_VALUES = Object.freeze(Object.values(LORA_KEY_LAYOUTS));+/**+ * Is `layout` one of the layouts this module actually knows? Callers that read+ * a layout back out of persisted state (a LoRA sidecar) must validate before+ * trusting it — an unrecognized string would otherwise fall through+ * `videoLoraLayoutIssue`'s known cases and get reported as "no LoRA tensors".+ */+export const isKnownLoraKeyLayout = (layout) => LORA_KEY_LAYOUT_VALUES.includes(layout);+// `lora_A` / `lora_B` (diffusers/PEFT rank pair) anywhere in a dotted key.-const LORA_AB_RE = /(^|\.)lora_(A|B)(\.|$)/;+// Case-insensitive: some trainers emit lowercase `lora_a`/`lora_b` (upstream's+// own LTX trainer normalizes exactly that spelling on export), and treating+// those as "no rank tensors" would misreport a usable LoRA as `not_a_lora`.+const LORA_AB_RE = /(^|\.)lora_(A|B)(\.|$)/i;// 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)(\.|$)/;+const LORA_DOWN_UP_RE = /(^|\.)lora_(down|up)(\.|$)/i;// kohya's underscore-flattened module namespace (`lora_unet_…`, `lora_te1_…`).-const KOHYA_PREFIX_RE = /^lora_(unet|te\d*)_/;+const KOHYA_PREFIX_RE = /^lora_(unet|te\d*)_/i;// diffusers / PEFT wrapper prefixes.const DIFFUSERS_PREFIX_RE = /^(transformer|base_model|unet|text_encoder\w*)\./;diff --git a/server/lib/safetensors.test.js b/server/lib/safetensors.test.jsindex 751e900815..847c59601c 100644--- a/server/lib/safetensors.test.js+++ b/server/lib/safetensors.test.js@@ -10,7 +10,9 @@ import {classifyLoraKeyLayoutFromHeader,classifyLoraKeyLayout,videoLoraLayoutIssue,+ isKnownLoraKeyLayout,LORA_KEY_LAYOUTS,+ LORA_KEY_LAYOUT_VALUES,} from './safetensors.js';// Build a valid safetensors file buffer from a header object: 8-byte LE u64@@ -216,3 +218,21 @@ describe('videoLoraLayoutIssue', () => {expect(videoLoraLayoutIssue(LORA_KEY_LAYOUTS.NOT_A_LORA)).toMatch(/no LoRA tensors/i);});});++describe('classifyLoraKeyLayoutFromHeader — casing', () => {+ it('recognizes lowercase lora_a/lora_b rank tensors', () => {+ 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);+ });+});++describe('isKnownLoraKeyLayout', () => {+ it('accepts every declared layout and rejects anything else', () => {+ for (const layout of LORA_KEY_LAYOUT_VALUES) expect(isKnownLoraKeyLayout(layout)).toBe(true);+ expect(isKnownLoraKeyLayout('peft')).toBe(false);+ expect(isKnownLoraKeyLayout(null)).toBe(false);+ expect(isKnownLoraKeyLayout(undefined)).toBe(false);+ });+});diff --git a/server/services/loras.js b/server/services/loras.jsindex 16860f73c6..4f77c503d2 100644--- a/server/services/loras.js+++ b/server/services/loras.js@@ -56,6 +56,7 @@ import {classifyLoraKeyLayout,classifyLoraKeyLayoutFromHeader,detectFlux2VariantFromHeader,+ isKnownLoraKeyLayout,readSafetensorsHeader,} from '../lib/safetensors.js';import { getHfToken } from '../lib/hfToken.js';@@ -156,7 +157,10 @@ export const listLoras = async () => {// '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;+ // Validate the stored value: a sidecar hand-edited (or written by a+ // future version that knows a layout this one doesn't) must fall back to+ // re-classifying, not propagate a string nothing downstream understands.+ let keyLayout = isKnownLoraKeyLayout(sidecar?.keyLayout) ? sidecar.keyLayout : null;if (!keyLayout) {keyLayout = classifyLoraKeyLayoutFromHeader(await readHeaderOnce());if (keyLayout) backfill.keyLayout = keyLayout;@@ -288,7 +292,7 @@ const withKeyLayout = async (sidecar, destPath) => {*/export const getLoraKeyLayout = async (filename) => {const sidecar = await readSidecar(filename);- if (sidecar?.keyLayout) return sidecar.keyLayout;+ if (isKnownLoraKeyLayout(sidecar?.keyLayout)) return sidecar.keyLayout;return classifyLoraKeyLayout(join(PATHS.loras, filename));};diff --git a/server/services/loras.test.js b/server/services/loras.test.jsindex 100906bc99..2a5ec05c6b 100644--- a/server/services/loras.test.js+++ b/server/services/loras.test.js@@ -711,3 +711,19 @@ describe('LoRA key layout', () => {expect(await lorasService.getLoraKeyLayout('lora-kohya.safetensors')).toBe('kohya');});});++describe('LoRA key layout — stored value validation', () => {+ it('re-classifies when the sidecar holds an unrecognized layout string', async () => {+ const fs = await import('fs/promises');+ await fs.mkdir(tmpLoras, { recursive: true });+ await fs.writeFile(join(tmpLoras, 'lora-bogus.safetensors'), validSafetensors({+ 'diffusion_model.transformer_blocks.0.attn1.to_k.lora_A.weight': { dtype: 'F16', shape: [32, 2048], data_offsets: [0, 1] },+ }));+ await fs.writeFile(join(tmpLoras, 'lora-bogus.safetensors.metadata.json'), JSON.stringify({+ filename: 'lora-bogus.safetensors', keyLayout: 'peft-ish',+ }));+ expect(await lorasService.getLoraKeyLayout('lora-bogus.safetensors')).toBe('comfyui');+ const list = await lorasService.listLoras();+ expect(list.find((l) => l.filename === 'lora-bogus.safetensors').keyLayout).toBe('comfyui');+ });+});diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.jsindex 65e0e52e09..16c5fd161f 100644--- a/server/services/videoGen/local.test.js+++ b/server/services/videoGen/local.test.js@@ -3093,7 +3093,13 @@ describe('resolveVideoLoras — safetensors key-layout gate', () => {loraLayoutState.layout = null;({ resolveVideoLoras } = await import('./local.js'));});- afterEach(() => { loraLayoutState.layout = null; });+ afterEach(async () => {+ loraLayoutState.layout = null;+ // Restore the shared mock here rather than inline, so a failing assertion+ // in a per-filename test can't leak its implementation into the next one.+ const { getLoraKeyLayout } = await import('../loras.js');+ vi.mocked(getLoraKeyLayout).mockImplementation(async () => loraLayoutState.layout);+ });it('resolves bare and ComfyUI layouts (the two the loader can fuse)', async () => {for (const layout of ['bare', 'comfyui']) {@@ -3126,7 +3132,6 @@ describe('resolveVideoLoras — safetensors key-layout gate', () => {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 () => {