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
address review (codex): four ways the single-file/bounds contract could still be bypassed
[._.]/ Adam Eivy138603a7dfb7
diff --git a/scripts/generate_ltx2.py b/scripts/generate_ltx2.pyindex ab95ab883a..9b5209c481 100644--- a/scripts/generate_ltx2.py+++ b/scripts/generate_ltx2.py@@ -387,11 +387,18 @@ def parse_args() -> argparse.Namespace:p.add_argument("--ic-reference", action="append", default=None, metavar="PATH",help="Reference clip for the IC-LoRA video-conditioning channel. Repeatable; ""how many the fused weight expects is set by --ic-min/max-references.")- p.add_argument("--ic-min-references", type=int, default=1,+ # NO DEFAULTS. A 1/1 default would silently green-light a direct+ # `--ic-mode ingredients --ic-reference one.mp4` invocation that omitted the+ # flags: the wrong reference count for a weight yields plausible-looking+ # garbage rather than an error, so "caller forgot the bounds" must fail loudly+ # instead of falling back to some other weight's contract. Required together.+ p.add_argument("--ic-min-references", type=int, default=None,help="Fewest --ic-reference entries the fused weight accepts (from PortOS' "- "icLoraWeights registry, which owns the per-weight contract).")- p.add_argument("--ic-max-references", type=int, default=1,- help="Most --ic-reference entries the fused weight accepts.")+ "icLoraWeights registry, which owns the per-weight contract). REQUIRED "+ "for --mode ic, alongside --ic-max-references.")+ p.add_argument("--ic-max-references", type=int, default=None,+ help="Most --ic-reference entries the fused weight accepts. REQUIRED for "+ "--mode ic, alongside --ic-min-references.")p.add_argument("--ic-strength", type=float, default=1.0,help="Per-reference conditioning strength (0.0-1.0+) applied to every ""--ic-reference entry.")@@ -855,6 +862,12 @@ def run_ic_lora(args: argparse.Namespace) -> str:# a weight fed the wrong reference count produces plausible-looking garbage# rather than an error, so a direct/script caller needs the guard too.lo, hi = args.ic_min_references, args.ic_max_references+ if lo is None or hi is None:+ raise SystemExit(+ "--ic-min-references and --ic-max-references are both required for ic mode "+ "(they carry the fused weight's reference contract; guessing them would let a "+ "wrong reference count render plausible-looking garbage)"+ )if lo < 1 or hi < lo:raise SystemExit(f"--ic-min-references/--ic-max-references must satisfy 1 <= min <= max; got {lo}/{hi}"diff --git a/scripts/generate_ltx2_ic_lora_test.py b/scripts/generate_ltx2_ic_lora_test.pyindex 57764f28df..86048917ad 100644--- a/scripts/generate_ltx2_ic_lora_test.py+++ b/scripts/generate_ltx2_ic_lora_test.py@@ -179,6 +179,34 @@ class RunIcLoraBoundsTest(unittest.TestCase):self.helper.run_ic_lora(self._args(references=self.refs[:2], lo=0, hi=8))self.assertIn("1 <= min <= max", str(ctx.exception))+ def test_requires_both_bounds_rather_than_defaulting_them(self):+ # A 1/1 default would silently green-light a direct+ # `--ic-mode ingredients --ic-reference one.mp4` that omitted the flags —+ # rendering plausible-looking garbage instead of erroring. Omitting either+ # bound must fail loudly.+ for lo, hi in ((None, 8), (2, None), (None, None)):+ with self.subTest(lo=lo, hi=hi):+ with self.assertRaises(SystemExit) as ctx:+ self.helper.run_ic_lora(+ self._args(references=self.refs[:1], lo=lo, hi=hi)+ )+ self.assertIn("both required", str(ctx.exception))++ def test_argparse_leaves_the_bounds_unset_by_default(self):+ # The flags carry no default at all — a default is exactly what would let a+ # caller bypass the registry-derived contract.+ argv = sys.argv+ sys.argv = [+ "generate_ltx2.py", "--mode", "ic",+ "--prompt", "x", "--output", "/tmp/x.mp4", "--model", "/m",+ ]+ try:+ args = self.helper.parse_args()+ finally:+ sys.argv = argv+ self.assertIsNone(args.ic_min_references)+ self.assertIsNone(args.ic_max_references)+def test_rejects_a_reference_missing_from_disk(self):with self.assertRaises(SystemExit) as ctx:self.helper.run_ic_lora(diff --git a/server/lib/README.md b/server/lib/README.mdindex 7dc4533355..d992617820 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -115,7 +115,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `ansiStrip.js` | Streaming ANSI / control-byte stripper. || `hfToken.js` | HuggingFace token resolution (settings > env > CLI): `getHfToken` / `getHfTokenInfo` / `hfTokenEnv`, plus `hfChildEnv(extra?)` for a complete Malloc-stripped child environment that preserves inherited variables while injecting the resolved token. || `hfErrors.js` | Parse huggingface_hub gated-access errors: `isGatedRepoError(text)` classifies a failure as gated (403/restricted), `extractGatedRepo(text)` → `owner/name` (or null) for the UI's license deep-link. Shared by the image runner and MIDI transcription (LoRA trainer keeps its own regex to also match bare 401). 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. Also `verifyModelCache(repoId,{deep})` (structural safetensors-header + optional sha256 integrity check) and `repairModelCache(repoId,{deep})` (delete corrupt weight files so the download path re-fetches them) — power the "Repair model" banner. `repairCachedFile(path)` is the single-file counterpart (unlinks one snapshot entry AND the blob behind its symlink) for a weight inside an aggregate repo, where a whole-snapshot walk would be prohibitive. `verifySafetensorsStructure(path,size)` is the reusable header/size structural check (reads only the header region) — also used by the Civitai/HF LoRA install path to reject truncated downloads. |+| `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. Also `verifyModelCache(repoId,{deep})` (structural safetensors-header + optional sha256 integrity check) and `repairModelCache(repoId,{deep})` (delete corrupt weight files so the download path re-fetches them) — power the "Repair model" banner. `findCachedRepoFile(repoId,filename)` resolves ONE known file in the newest snapshot **without walking it** (the whole-snapshot stat in `inspectModelCache` is prohibitive for an aggregate repo that hosts hundreds of GB of unrelated weights), and `repairCachedFile(path)` is the matching single-file repair (unlinks one snapshot entry AND the blob behind its symlink). `verifySafetensorsStructure(path,size)` is the reusable header/size structural check (reads only the header region) — also used by the Civitai/HF LoRA install path to reject truncated downloads. || `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. || `icLoraWeights.js` | IC-LoRA weight registry for the local LTX-2 remix modes (`IC_LORA_MODES`, `IC_LORA_MODE_VALUES`, `listIcLoraWeights()`, `isIcLoraMode(mode)`, `icLoraSpecForMode(mode)`, `icLoraRepos()`, `icLoraWeightCandidates(spec)`, `findCachedIcLoraWeight(spec)`, `resolveIcLoraWeight(mode)` → `{path,cached,spec}`). Single source of truth mapping each remix mode (`ic-control`, `ic-colorize`, `ic-ingredients`) → its HF repo/filename, reference-count rule, per-weight `referenceDownscaleFactor` (read from the weight's safetensors metadata, never assumed), and input surface (`referenceKind: 'video' | 'image'`). A `requiresPreDownload` spec (Ingredients) suppresses `resolveIcLoraWeight`'s bare-repo-id fallback — the pipeline would `snapshot_download` it, and its candidates are a gated first-party repo plus a ~708 GB aggregate mirror, so the weight must be pre-fetched single-file instead. Also owns the two rules derived from that data: `assertIcReferenceCount(spec,count,fail)` / `describeIcReferenceRange(spec)` and `icResolutionIssue(spec,w,h)` (the output-resolution divisibility its reference encoder imposes). Mirrored to `client/src/lib/videoGenParams.js`; `icLoraWeights.parity.test.js` diffs the two. || `sseHeaders.js` | `SSE_HEADERS` — the canonical SSE response headers (incl. `X-Accel-Buffering:no`) in a dependency-free module so any producer (`sseDownload.js`, `sseUtils.js`) can share them without pulling in a heavier module's transitive imports. |diff --git a/server/lib/hfCache.js b/server/lib/hfCache.jsindex aba16b0755..25f982b1c1 100644--- a/server/lib/hfCache.js+++ b/server/lib/hfCache.js@@ -129,6 +129,28 @@ export async function inspectModelCache(repoId) {export const isModelCached = async (repoId) => (await inspectModelCache(repoId)).cached;+// Resolve ONE known file inside a repo's newest snapshot, without walking the+// snapshot at all. `inspectModelCache` recursively collects and stats every+// weight in the snapshot — correct when the question is "is this whole model+// downloaded?", but wrong (and expensive) for an aggregate repo where we only+// ever care about a single file: `DeepBeepMeep/LTX-2` hosts every LTX weight in+// one ~708 GB repo, so walking a populated snapshot there stats hundreds of GB+// of files that have nothing to do with the one we asked for.+//+// Returns the absolute path, or null when the repo has no snapshot or the file+// isn't resident. The `stat` FOLLOWS the symlink, so a dangling snapshot link+// left by an interrupted download reports null rather than a plausible path+// that fails on open — the same non-zero test inspectModelCache applies.+export async function findCachedRepoFile(repoId, filename) {+ if (!repoId || typeof repoId !== 'string') return null;+ if (!filename || typeof filename !== 'string') return null;+ const snapshotPath = await latestSnapshotDir(join(getHfCacheRoot(), repoToDirName(repoId)));+ if (!snapshotPath) return null;+ const candidate = join(snapshotPath, filename);+ const stat = await fs.stat(candidate).catch(() => null);+ return stat && stat.size > 0 ? candidate : null;+}+// ---------------------------------------------------------------------------// Weight-integrity verification (issue #1324)//diff --git a/server/lib/hfCache.test.js b/server/lib/hfCache.test.jsindex f6830fc931..4cb5610d8d 100644--- a/server/lib/hfCache.test.js+++ b/server/lib/hfCache.test.js@@ -5,7 +5,7 @@ import { tmpdir } from 'node:os';import { join } from 'node:path';import {inspectModelCache, getHfCacheRoot, isModelCached,- verifyModelCache, repairModelCache,+ verifyModelCache, repairModelCache, findCachedRepoFile, repairCachedFile,} from './hfCache.js';// Build a minimal *valid* .safetensors buffer: 8-byte LE header length, a JSON@@ -332,3 +332,106 @@ describe('repairModelCache', () => {expect(result.deleted).toEqual([]);});});++// ── Single-file probe + repair (#3112) ─────────────────────────────────────+// A weight can live inside an AGGREGATE repo: `DeepBeepMeep/LTX-2` mirrors every+// LTX weight in one ~708 GB repo. `inspectModelCache` recursively stats every+// weight in the snapshot, which there means hundreds of GB of files that have+// nothing to do with the one we asked for — so these two helpers answer the+// single-file questions without ever walking the snapshot.+describe('findCachedRepoFile', () => {+ let originalEnv;+ const cleanup = [];++ beforeEach(() => { originalEnv = process.env.HF_HUB_CACHE; });+ afterEach(() => {+ if (originalEnv === undefined) delete process.env.HF_HUB_CACHE;+ else process.env.HF_HUB_CACHE = originalEnv;+ for (const dir of cleanup.splice(0)) rmSync(dir, { recursive: true, force: true });+ });++ const aggregateCache = ({ partial = false } = {}) => {+ const { root } = buildFakeCache({+ repoId: 'org/aggregate',+ snapshots: {+ sha1: {+ 'wanted.safetensors': 1024,+ 'unrelated-a.safetensors': 2048,+ 'unrelated-b.safetensors': 4096,+ },+ },+ partial,+ });+ cleanup.push(root);+ process.env.HF_HUB_CACHE = root;+ return root;+ };++ it('resolves the requested file out of an aggregate repo', async () => {+ aggregateCache();+ const found = await findCachedRepoFile('org/aggregate', 'wanted.safetensors');+ expect(found).toMatch(/snapshots\/sha1\/wanted\.safetensors$/);+ });++ it('returns null for a file the repo has not fetched, even though siblings exist', async () => {+ // The precise failure this exists to prevent: inspectModelCache would report+ // the repo `cached` off the unrelated siblings and the caller would skip a+ // download for a weight the user does NOT have.+ aggregateCache();+ expect(await findCachedRepoFile('org/aggregate', 'never-fetched.safetensors')).toBeNull();+ expect((await inspectModelCache('org/aggregate')).cached).toBe(true);+ });++ it('returns null for a dangling snapshot symlink (interrupted download)', async () => {+ // The stat FOLLOWS the link, so a link with no blob behind it reports null+ // rather than a plausible path that fails on open inside the render.+ aggregateCache({ partial: true });+ expect(await findCachedRepoFile('org/aggregate', 'wanted.safetensors')).toBeNull();+ });++ it('returns null when the repo has no snapshot at all', async () => {+ aggregateCache();+ expect(await findCachedRepoFile('org/never-downloaded', 'wanted.safetensors')).toBeNull();+ });++ it('returns null for a missing repo id or filename', async () => {+ aggregateCache();+ expect(await findCachedRepoFile('', 'wanted.safetensors')).toBeNull();+ expect(await findCachedRepoFile(null, 'wanted.safetensors')).toBeNull();+ expect(await findCachedRepoFile('org/aggregate', '')).toBeNull();+ expect(await findCachedRepoFile('org/aggregate', null)).toBeNull();+ });+});++describe('repairCachedFile', () => {+ const cleanup = [];+ afterEach(() => {+ for (const dir of cleanup.splice(0)) rmSync(dir, { recursive: true, force: true });+ });++ it('unlinks the snapshot entry AND the blob behind it, leaving siblings alone', async () => {+ // Deleting only the symlink is not enough: `hf_hub_download` keys on the+ // cached etag rather than the content, so a stale blob with the right name+ // would be trusted and never re-fetched.+ const { root, repoDir } = buildFakeCache({+ repoId: 'org/aggregate',+ snapshots: { sha1: { 'wanted.safetensors': 1024, 'keep.safetensors': 2048 } },+ });+ cleanup.push(root);+ const target = join(repoDir, 'snapshots', 'sha1', 'wanted.safetensors');+ const blob = readlinkSync(target);+ const keep = join(repoDir, 'snapshots', 'sha1', 'keep.safetensors');++ expect(await repairCachedFile(target)).toBe(true);+ expect(existsSync(target)).toBe(false);+ expect(existsSync(blob)).toBe(false);+ // The aggregate repo's other weights are untouched — that's the whole point+ // of not routing through repairModelCache here.+ expect(existsSync(keep)).toBe(true);+ });++ it('reports false for a path that is not there', async () => {+ expect(await repairCachedFile('/nope/missing.safetensors')).toBe(false);+ expect(await repairCachedFile(null)).toBe(false);+ });+});diff --git a/server/lib/icLoraWeights.js b/server/lib/icLoraWeights.jsindex 6199669b26..1ebe0fdedf 100644--- a/server/lib/icLoraWeights.js+++ b/server/lib/icLoraWeights.js@@ -28,9 +28,7 @@// so `gated: true` marks it and the mirror provides an un-gated path for users// without an HF token.-import { join } from 'node:path';-import { existsSync } from 'node:fs';-import { inspectModelCache } from './hfCache.js';+import { findCachedRepoFile } from './hfCache.js';// One entry per shipped remix mode. `minReferences`/`maxReferences` are the// weight's contract: the Python helper receives them as flags (never a second@@ -213,13 +211,11 @@ export const icResolutionIssue = (spec, width, height) => {// (`{ path, repo, filename, mirror }`) or null when nothing is cached.export const findCachedIcLoraWeight = async (spec) => {for (const candidate of icLoraWeightCandidates(spec)) {- const { snapshotPath } = await inspectModelCache(candidate.repo);- if (!snapshotPath) continue;- const exact = join(snapshotPath, candidate.filename);- // `existsSync` FOLLOWS symlinks, so a dangling snapshot link left by an- // interrupted download reports false here — the same "is it really resident?"- // question inspectModelCache asks of a whole snapshot.- if (existsSync(exact)) return { ...candidate, path: exact };+ // findCachedRepoFile, NOT inspectModelCache: the latter recursively walks and+ // stats every weight in the snapshot, which for the aggregate mirror means+ // hundreds of GB of unrelated files. This resolves the one filename directly.+ const path = await findCachedRepoFile(candidate.repo, candidate.filename);+ if (path) return { ...candidate, path };}return null;};diff --git a/server/lib/icLoraWeights.test.js b/server/lib/icLoraWeights.test.jsindex 89947575f6..2f4f511e12 100644--- a/server/lib/icLoraWeights.test.js+++ b/server/lib/icLoraWeights.test.js@@ -5,12 +5,8 @@ import { join } from 'node:path';// cache and existsSync probes the pinned weight file. Mock them so these tests// cover the registry + resolution logic rather than the user's ~/.cache layout// (hfCache.test.js already covers the cache walk).-const { mockInspectModelCache, mockExistsSync } = vi.hoisted(() => ({- mockInspectModelCache: vi.fn(),- mockExistsSync: vi.fn(),-}));-vi.mock('./hfCache.js', () => ({ inspectModelCache: mockInspectModelCache }));-vi.mock('node:fs', () => ({ existsSync: mockExistsSync }));+const { mockFindCachedRepoFile } = vi.hoisted(() => ({ mockFindCachedRepoFile: vi.fn() }));+vi.mock('./hfCache.js', () => ({ findCachedRepoFile: mockFindCachedRepoFile }));const {IC_LORA_MODES, IC_LORA_MODE_VALUES, isIcLoraMode, icLoraSpecForMode,@@ -19,8 +15,7 @@ const {} = await import('./icLoraWeights.js');beforeEach(() => {- mockInspectModelCache.mockReset();- mockExistsSync.mockReset();+ mockFindCachedRepoFile.mockReset();});describe('IC-LoRA registry', () => {@@ -98,9 +93,18 @@ describe('IC-LoRA registry', () => {});describe('resolveIcLoraWeight', () => {+ // `findCachedRepoFile(repo, filename)` returns the absolute path or null. It is+ // deliberately NOT inspectModelCache: that walks + stats the whole snapshot,+ // which for an aggregate mirror means hundreds of GB of unrelated weights.+ const cacheHas = (...pairs) => mockFindCachedRepoFile.mockImplementation(+ async (repo, filename) => {+ const hit = pairs.find((p) => p.repo === repo && p.filename === filename);+ return hit ? join(hit.snapshot, filename) : null;+ },+ );+it('pins the exact filename inside the cached snapshot', async () => {- mockInspectModelCache.mockResolvedValue({ cached: true, sizeBytes: 1, snapshotPath: '/hf/snap' });- mockExistsSync.mockReturnValue(true);+ cacheHas({ repo: IC_LORA_MODES.control.repo, filename: IC_LORA_MODES.control.filename, snapshot: '/hf/snap' });const resolved = await resolveIcLoraWeight('ic-control');// Pinning the filename (rather than returning the snapshot dir or the repo@@ -111,29 +115,31 @@ describe('resolveIcLoraWeight', () => {});it('pins each mode to its OWN filename, not the first registry entry', async () => {- mockInspectModelCache.mockResolvedValue({ cached: true, sizeBytes: 1, snapshotPath: '/hf/snap' });- mockExistsSync.mockReturnValue(true);+ cacheHas({ repo: IC_LORA_MODES.colorize.repo, filename: IC_LORA_MODES.colorize.filename, snapshot: '/hf/snap' });const resolved = await resolveIcLoraWeight('ic-colorize');expect(resolved.path).toBe(join('/hf/snap', IC_LORA_MODES.colorize.filename));expect(resolved.spec).toBe(IC_LORA_MODES.colorize);- expect(mockInspectModelCache).toHaveBeenCalledWith(IC_LORA_MODES.colorize.repo);- });-- it('falls back to the repo id when no snapshot exists', async () => {- mockInspectModelCache.mockResolvedValue({ cached: false, sizeBytes: 0, snapshotPath: null });-- const resolved = await resolveIcLoraWeight('ic-control');- expect(resolved.path).toBe(IC_LORA_MODES.control.repo);- expect(resolved.cached).toBe(false);+ expect(mockFindCachedRepoFile).toHaveBeenCalledWith(+ IC_LORA_MODES.colorize.repo, IC_LORA_MODES.colorize.filename,+ );+ });++ it('never asks for a whole-snapshot walk, only exact filenames (#3112)', async () => {+ // The single-file invariant at the resolution layer: every probe names a file.+ cacheHas();+ await resolveIcLoraWeight('ic-ingredients');+ expect(mockFindCachedRepoFile).toHaveBeenCalledTimes(2);+ for (const [, filename] of mockFindCachedRepoFile.mock.calls) {+ expect(filename).toMatch(/\.safetensors$/);+ }});- it('falls back to the repo id when the snapshot lacks the pinned file', async () => {- // A partial download leaves the snapshot dir present but the weight absent —- // returning the dir-joined path would hand the pipeline a missing file, so- // the repo-id fallback (which re-downloads) is the correct degrade.- mockInspectModelCache.mockResolvedValue({ cached: true, sizeBytes: 1, snapshotPath: '/hf/snap' });- mockExistsSync.mockReturnValue(false);+ it('falls back to the repo id when the weight is not resident', async () => {+ // Covers both "no snapshot at all" and "snapshot present but the pinned file+ // missing / a dangling symlink" — findCachedRepoFile collapses them to null,+ // and the repo-id fallback (which re-downloads) is the correct degrade.+ cacheHas();const resolved = await resolveIcLoraWeight('ic-control');expect(resolved.path).toBe(IC_LORA_MODES.control.repo);@@ -142,7 +148,7 @@ describe('resolveIcLoraWeight', () => {it('returns null for an unknown mode without touching the cache', async () => {expect(await resolveIcLoraWeight('ic-nope')).toBeNull();- expect(mockInspectModelCache).not.toHaveBeenCalled();+ expect(mockFindCachedRepoFile).not.toHaveBeenCalled();});it('SUPPRESSES the repo-id fallback for a requiresPreDownload weight (#3112)', async () => {@@ -152,7 +158,7 @@ describe('resolveIcLoraWeight', () => {// DeepBeepMeep/LTX-2 aggregate, which would fill the user's disk. Neither id// may ever reach the pipeline — path must be null so icLoraArgs 400s with// "download the weight first".- mockInspectModelCache.mockResolvedValue({ cached: false, sizeBytes: 0, snapshotPath: null });+ cacheHas();const resolved = await resolveIcLoraWeight('ic-ingredients');expect(resolved.path).toBeNull();@@ -162,16 +168,15 @@ describe('resolveIcLoraWeight', () => {expect(resolved.path).not.toBe(IC_LORA_MODES.ingredients.mirrorRepo);});- it('still resolves a requiresPreDownload weight from the mirror snapshot', async () => {- // Official repo has no snapshot; the mirror does. The candidate walk must find- // it there rather than giving up (that's what makes the un-gated path work for- // a user with no HF token).- mockInspectModelCache.mockImplementation(async (repo) => (- repo === IC_LORA_MODES.ingredients.mirrorRepo- ? { cached: true, sizeBytes: 1, snapshotPath: '/hf/mirror-snap' }- : { cached: false, sizeBytes: 0, snapshotPath: null }- ));- mockExistsSync.mockReturnValue(true);+ it('still resolves a requiresPreDownload weight from the mirror', async () => {+ // Official repo doesn't have it; the mirror does. The candidate walk must find+ // it there rather than giving up — that's what makes the un-gated path work+ // for a user with no HF token.+ cacheHas({+ repo: IC_LORA_MODES.ingredients.mirrorRepo,+ filename: IC_LORA_MODES.ingredients.mirrorFilename,+ snapshot: '/hf/mirror-snap',+ });const resolved = await resolveIcLoraWeight('ic-ingredients');expect(resolved.path).toBe(join('/hf/mirror-snap', IC_LORA_MODES.ingredients.mirrorFilename));@@ -179,17 +184,17 @@ describe('resolveIcLoraWeight', () => {expect(resolved.repo).toBe(IC_LORA_MODES.ingredients.mirrorRepo);});- it('prefers the official repo over the mirror when both are cached', async () => {- mockInspectModelCache.mockImplementation(async (repo) => ({- cached: true,- sizeBytes: 1,- snapshotPath: repo === IC_LORA_MODES.ingredients.repo ? '/hf/official' : '/hf/mirror',- }));- mockExistsSync.mockReturnValue(true);+ it('prefers the official repo over the mirror when both have it', async () => {+ cacheHas(+ { repo: IC_LORA_MODES.ingredients.repo, filename: IC_LORA_MODES.ingredients.filename, snapshot: '/hf/official' },+ { repo: IC_LORA_MODES.ingredients.mirrorRepo, filename: IC_LORA_MODES.ingredients.mirrorFilename, snapshot: '/hf/mirror' },+ );const resolved = await resolveIcLoraWeight('ic-ingredients');expect(resolved.repo).toBe(IC_LORA_MODES.ingredients.repo);expect(resolved.path).toBe(join('/hf/official', IC_LORA_MODES.ingredients.filename));+ // Short-circuits: the mirror is never even probed once the official hit lands.+ expect(mockFindCachedRepoFile).toHaveBeenCalledTimes(1);});});@@ -215,12 +220,16 @@ describe('icLoraWeightCandidates', () => {});describe('findCachedIcLoraWeight', () => {- it('treats a dangling snapshot symlink as not cached', async () => {- // existsSync FOLLOWS symlinks, so an interrupted download (link present, blob- // gone) must NOT count as resident — otherwise the render hands the pipeline a- // path that fails on open.- mockInspectModelCache.mockResolvedValue({ cached: true, sizeBytes: 1, snapshotPath: '/hf/snap' });- mockExistsSync.mockReturnValue(false);+ it('returns null when no candidate has the file resident', async () => {+ // findCachedRepoFile already collapses "no snapshot", "file absent" and+ // "dangling symlink / zero bytes" into null (hfCache.test.js covers those);+ // this asserts the candidate walk gives up rather than returning a bad path.+ mockFindCachedRepoFile.mockResolvedValue(null);expect(await findCachedIcLoraWeight(IC_LORA_MODES.ingredients)).toBeNull();});++ it('returns nothing for a null spec without probing the cache', async () => {+ expect(await findCachedIcLoraWeight(null)).toBeNull();+ expect(mockFindCachedRepoFile).not.toHaveBeenCalled();+ });});diff --git a/server/lib/sseDownload.js b/server/lib/sseDownload.jsindex b734796925..2baabd11aa 100644--- a/server/lib/sseDownload.js+++ b/server/lib/sseDownload.js@@ -93,14 +93,19 @@ export async function startHfDownloadStream({ req, res, repo, repos, fallbacks,const { repo: r, only: onlyFiles } = targets[i];const isLastTarget = i === targets.length - 1;if (aborted) return;- const existing = await inspectModelCache(r);+ // For a single-file pull the repo-wide cache verdict is both the wrong+ // question AND too expensive to ask: `inspectModelCache` recursively stats+ // every weight in the snapshot, and an aggregate mirror reports `cached` off+ // any unrelated resident file — so it would skip the file the user actually+ // asked for after walking hundreds of GB to get there. Skip the walk entirely+ // and defer to the caller's per-file predicate.+ const singleFile = onlyFiles.length > 0;+ const existing = singleFile+ ? { cached: false, sizeBytes: 0 }+ : await inspectModelCache(r);if (aborted) return;- // For a single-file pull the repo-wide cache verdict is the wrong question:- // an aggregate mirror reports `cached` the moment any unrelated weight is- // resident, which would skip the file the user actually asked for. Defer to- // the caller's per-file predicate when one is supplied.- const alreadyHave = onlyFiles.length && typeof cachedFile === 'function'- ? await cachedFile()+ const alreadyHave = singleFile+ ? (typeof cachedFile === 'function' ? await cachedFile() : false): existing.cached;if (aborted) return;// `force` is set by a repair-initiated re-download: repairModelCache()@@ -110,11 +115,11 @@ export async function startHfDownloadStream({ req, res, repo, repos, fallbacks,// re-runs the HF fetch, which is a cheap no-op for files already present// (etag match) and pulls only what's gone.if (alreadyHave && !force) {- // A single-file pull must NOT claim the repo's resident total: for the- // aggregate mirror that's every unrelated weight the user has (hundreds of- // GB), which would be a wildly wrong number on the badge. Report 0 there- // and let the badge fall back to the registry's size estimate.- if (onlyFiles.length) {+ // A single-file pull has no repo-wide total to report (we deliberately+ // never computed one) — and claiming the aggregate mirror's resident bytes+ // would be a wildly wrong number on the badge anyway. Report 0 and let the+ // badge fall back to the registry's size estimate.+ if (singleFile) {console.log(`📦 HuggingFace weight already cached: ${onlyFiles.join(', ')} (${r})`);send({ type: 'log', message: `${onlyFiles.join(', ')} already cached.`, repo: r, sizeBytes: 0 });} else {@@ -130,7 +135,7 @@ export async function startHfDownloadStream({ req, res, repo, repos, fallbacks,// Dedupe key includes the filenames: an aggregate repo hosts many unrelated// weights, so two single-file pulls of DIFFERENT files from the same repo are// not duplicates and must not block each other.- const flightKey = onlyFiles.length ? `${r}::${onlyFiles.join(',')}` : r;+ const flightKey = singleFile ? `${r}::${onlyFiles.join(',')}` : r;if (inFlight.has(flightKey)) {console.log(`⏭️ HuggingFace download already running for ${flightKey} — refusing duplicate`);send({ type: 'error', message: `Another download for ${r} is already running.`, kind: 'already_running', repo: r });@@ -139,10 +144,10 @@ export async function startHfDownloadStream({ req, res, repo, repos, fallbacks,// Server-side visibility for a pull that used to surface only on the SSE// stream (the browser) — a headless/PM2 log had no record the multi-GB// fetch ever ran. Log the start, each file as it streams, and the outcome.- console.log(`⬇️ Downloading HuggingFace repo: ${r}${onlyFiles.length ? ` (${onlyFiles.length} file(s) only)` : ''}${force ? ' (forced re-fetch)' : ''}`);+ console.log(`⬇️ Downloading HuggingFace repo: ${r}${singleFile ? ` (${onlyFiles.length} file(s) only)` : ''}${force ? ' (forced re-fetch)' : ''}`);const handle = downloadHfRepo({repo: r,- only: onlyFiles.length ? onlyFiles : null,+ only: singleFile ? onlyFiles : null,onEvent: (ev) => {if (ev.type === 'progress' && ev.file) {console.log(`⬇️ ${r}: ${ev.file} (${ev.step}/${ev.total})`);diff --git a/server/lib/sseDownload.test.js b/server/lib/sseDownload.test.jsindex 0f20abb88f..028b67ca42 100644--- a/server/lib/sseDownload.test.js+++ b/server/lib/sseDownload.test.js@@ -296,6 +296,26 @@ describe('startHfDownloadStream single-file + fallbacks (#3112)', () => {expect(parseFrames(frames).at(-1).sizeBytes).toBe(0);});+ it('never inspects the whole repo for a single-file pull (#3112)', async () => {+ // inspectModelCache recursively stats EVERY weight in the snapshot. Against a+ // populated 708 GB mirror that's the expensive walk the single-file path+ // exists to avoid — and its verdict would be wrong anyway (cached off any+ // unrelated resident file). It must not be called at all.+ const { req, res } = makeReqRes();+ await startHfDownloadStream({ req, res, fallbacks: CANDIDATES, cachedFile: async () => false });+ expect(inspectModelCache).not.toHaveBeenCalled();+ });++ it('does NOT treat a single-file pull as cached when no predicate is supplied', async () => {+ // Fail-safe direction: a caller that forgot `cachedFile` must re-fetch (cheap,+ // etag no-op) rather than inherit the repo-wide `cached: true` and skip a+ // weight the user doesn't have.+ inspectModelCache.mockResolvedValue({ cached: true, sizeBytes: 700e9, snapshotPath: '/snap' });+ const { req, res } = makeReqRes();+ await startHfDownloadStream({ req, res, fallbacks: [CANDIDATES[0]] });+ expect(downloadHfRepo).toHaveBeenCalledTimes(1);+ });+it('rejects an empty fallbacks list rather than silently completing', async () => {const { req, res, frames } = makeReqRes();await startHfDownloadStream({ req, res, fallbacks: [] });diff --git a/server/routes/videoGen.js b/server/routes/videoGen.jsindex ec427c85b3..7feb3888fd 100644--- a/server/routes/videoGen.js+++ b/server/routes/videoGen.js@@ -118,6 +118,12 @@ const optionalInt = (min, max, label) => z.preprocess((v) => v == null || v === '' ? undefined : Number(v),z.number().int().refine((n) => n >= min && n <= max, `${label} ${min}..${max}`).optional(),);+// Coarse upper bound for any IC reference array, derived from the registry so a+// weight raising its own maxReferences doesn't get rejected by a stale literal in+// the schema before the per-mode assertion below can speak. Per-weight bounds are+// still enforced against the mode's own spec (assertIcReferenceCount).+const MAX_IC_REFERENCES = Math.max(...listIcLoraWeights().map((s) => s.maxReferences));+const generateBodySchema = z.object({// Render backend: the local runtimes (default) or the Grok Build CLI's// image-first image_to_video flow (#2859 phase 2). Grok ignores the@@ -180,7 +186,7 @@ const generateBodySchema = z.object({}return v;},- z.array(z.string().guid()).min(1).max(8).optional(),+ z.array(z.string().guid()).min(1).max(MAX_IC_REFERENCES).optional(),),// Ingredients-style IC references: 2-8 gallery STILLS, not clips. A separate// field from icReference / icReferenceVideoIds on purpose — those are@@ -199,7 +205,12 @@ const generateBodySchema = z.object({}return v;},- z.array(z.string().min(1).max(512)).min(1).max(8).optional(),+ // Ceiling derived from the registry (the largest maxReferences any weight+ // declares), NOT a hardcoded 8 — a second literal here would silently+ // pre-empt the per-mode registry check with a 422 the moment a weight raised+ // its own maximum. This is only a coarse sanity bound; the real per-weight+ // rule is asserted below against the mode's own spec.+ z.array(z.string().min(1).max(512)).min(1).max(MAX_IC_REFERENCES).optional(),),// Reference-video conditioning strength for the IC-LoRA channel. Distinct// from the IC-LoRA's own fusion strength (fixed at 1.0 server-side) and fromdiff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.jsindex 4a53a0e085..89bf2e4d4d 100644--- a/server/routes/videoGen.test.js+++ b/server/routes/videoGen.test.js@@ -122,6 +122,7 @@ vi.mock('fs/promises', () => ({import * as videoGenService from '../services/videoGen/local.js';import * as mediaJobQueue from '../services/mediaJobQueue/index.js';import { resolveGalleryImage } from '../lib/fileUtils.js';+import { listIcLoraWeights } from '../lib/icLoraWeights.js';import videoGenRoutes, { isAudioMime } from './videoGen.js';// isAudioMime is the gating function inside the fileFilter callback. The@@ -1025,14 +1026,29 @@ describe('videoGen routes', () => {expect(mediaJobQueue.enqueueJob).not.toHaveBeenCalled();});- it('rejects more than 8 references at the schema boundary', async () => {+ it('rejects more references than any registered weight accepts', async () => {+ // The schema ceiling is DERIVED from the registry (the largest+ // maxReferences declared), not a second hardcoded 8 that would pre-empt+ // the per-weight check with a 422 the moment a weight raised its limit.+ const ceiling = Math.max(...listIcLoraWeights().map((w) => w.maxReferences));const r = await request(app).post('/api/video-gen/').send({- prompt: 'recompose', mode: 'ic-ingredients', icReferenceImageFiles: stills(9),+ prompt: 'recompose', mode: 'ic-ingredients', icReferenceImageFiles: stills(ceiling + 1),});expect(r.status).toBe(400);expect(mediaJobQueue.enqueueJob).not.toHaveBeenCalled();});+ it('lets the registry bound speak at the ceiling rather than the schema', async () => {+ // At exactly the registry maximum the request must reach the per-mode+ // assertion (and pass), proving the coarse schema bound isn't the one+ // enforcing the weight contract.+ const ceiling = Math.max(...listIcLoraWeights().map((w) => w.maxReferences));+ const r = await request(app).post('/api/video-gen/').send({+ prompt: 'recompose', mode: 'ic-ingredients', icReferenceImageFiles: stills(ceiling),+ });+ expect(r.status).toBe(200);+ });+it('rejects no references with an actionable message', async () => {const r = await request(app).post('/api/video-gen/').send({prompt: 'recompose', mode: 'ic-ingredients',diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.jsindex cff96f5449..5de503253f 100644--- a/server/services/videoGen/local.js+++ b/server/services/videoGen/local.js@@ -919,33 +919,34 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m{ status: 400, code: 'IC_LORA_STILL_NEEDS_FFMPEG' },);}- resolvedIcReferencePaths = await Promise.all(icReferencePaths.map(async (stillPath, i) => {- const clipPath = join(tmpdir(), `ic-still-${i}-${jobId}.mp4`);- const result = await execFileAsync(stillFfmpeg, [- '-loop', '1', '-i', stillPath,- '-vf', `scale=${w}:${h}:force_original_aspect_ratio=increase,crop=${w}:${h}`,- '-frames:v', String(IC_STILL_REFERENCE_FRAMES),- '-r', String(parsedFps),- '-pix_fmt', 'yuv420p', '-an',- '-y', clipPath,- ], { env: safeChildProcessEnv(), timeout: 30000 }).catch((err) => ({ error: err }));- if (result.error) {- // Unlike the resizeImage fallback (which degrades to the original), there- // is no usable degradation here — a still handed straight to the pipeline- // fails deep inside the VAE reshape. Fail loudly with the ffmpeg reason.- throw new ServerError(- `Failed to prepare Ingredients reference ${basename(stillPath)}: ${result.error.message}`,- { status: 400, code: 'IC_LORA_STILL_PREP_FAILED' },- );- }- icReferenceTempPaths.push(clipPath);- return clipPath;- })).catch(async (err) => {- // Partial success leaks the clips already written — one still failing- // aborts the render, so drop them before rethrowing.- for (const p of icReferenceTempPaths) await unlink(p).catch(() => {});- throw err;- });+ // Register EVERY target path up-front, before any encode starts, and settle+ // all of them before deciding. `Promise.all` + push-on-success would reject+ // at the first failure while sibling encodes were still in flight, so their+ // files would land after cleanup already ran and leak. Registering the paths+ // eagerly also means the outer error/close handlers can clean up regardless+ // of which encodes finished.+ const clipPaths = icReferencePaths.map((_, i) => join(tmpdir(), `ic-still-${i}-${jobId}.mp4`));+ icReferenceTempPaths.push(...clipPaths);+ const encodes = await Promise.all(icReferencePaths.map((stillPath, i) => execFileAsync(stillFfmpeg, [+ '-loop', '1', '-i', stillPath,+ '-vf', `scale=${w}:${h}:force_original_aspect_ratio=increase,crop=${w}:${h}`,+ '-frames:v', String(IC_STILL_REFERENCE_FRAMES),+ '-r', String(parsedFps),+ '-pix_fmt', 'yuv420p', '-an',+ '-y', clipPaths[i],+ ], { env: safeChildProcessEnv(), timeout: 30000 }).catch((err) => ({ error: err }))));+ const failedAt = encodes.findIndex((r) => r?.error);+ if (failedAt !== -1) {+ // Unlike the resizeImage fallback (which degrades to the original), there is+ // no usable degradation here — a still handed straight to the pipeline fails+ // deep inside the VAE reshape. Fail loudly with the ffmpeg reason.+ for (const p of clipPaths) await unlink(p).catch(() => {});+ throw new ServerError(+ `Failed to prepare Ingredients reference ${basename(icReferencePaths[failedAt])}: ${encodes[failedAt].error.message}`,+ { status: 400, code: 'IC_LORA_STILL_PREP_FAILED' },+ );+ }+ resolvedIcReferencePaths = clipPaths;}const meta = {diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.jsindex e54f6e7b5a..2d36f11a64 100644--- a/server/services/videoGen/local.test.js+++ b/server/services/videoGen/local.test.js@@ -77,11 +77,16 @@ vi.mock('../../lib/hfToken.js', () => ({// cache walk (which hfCache.test.js covers). `snapshotPath` non-null + the// always-true existsSync mock below means the weight resolves to its exact// pinned filename; a test that wants the un-cached fallback overrides this.-const { mockInspectModelCache } = vi.hoisted(() => ({+const { mockInspectModelCache, mockFindCachedRepoFile } = vi.hoisted(() => ({mockInspectModelCache: vi.fn(async () => ({ cached: true, sizeBytes: 1000, snapshotPath: '/mock/hf/snap' })),+ // icLoraWeights resolves an IC weight via the exact-file probe (NOT the+ // snapshot walk) so an aggregate mirror is never enumerated. Default to+ // "resident", derived from the same mocked snapshot path the tests assert on.+ mockFindCachedRepoFile: vi.fn(async (_repo, filename) => join('/mock/hf/snap', filename)),}));vi.mock('../../lib/hfCache.js', () => ({inspectModelCache: mockInspectModelCache,+ findCachedRepoFile: mockFindCachedRepoFile,}));vi.mock('fs', () => ({@@ -1757,7 +1762,9 @@ describe('generateVideo — IC-LoRA remix arg threading (#3100)', () => {);beforeEach(() => {- mockInspectModelCache.mockResolvedValue({ cached: true, sizeBytes: 1000, snapshotPath: '/mock/hf/snap' });+ // Every weight resident. The probe is per-FILE (findCachedRepoFile) rather+ // than a snapshot walk, so an aggregate mirror is never enumerated.+ mockFindCachedRepoFile.mockImplementation(async (_repo, filename) => join('/mock/hf/snap', filename));});it('routes ic-control to --mode ic with the pinned weight, reference, and strength', async () => {@@ -1812,7 +1819,7 @@ describe('generateVideo — IC-LoRA remix arg threading (#3100)', () => {const { spawnDetached } = await import('../../lib/detachedSpawn.js');const spawnMock = vi.mocked(spawnDetached);spawnMock.mockClear();- mockInspectModelCache.mockResolvedValue({ cached: false, sizeBytes: 0, snapshotPath: null });+ mockFindCachedRepoFile.mockResolvedValue(null);await generateVideo({ ...baseIcRender, jobId: 'ic-uncached' });@@ -1825,7 +1832,7 @@ describe('generateVideo — IC-LoRA remix arg threading (#3100)', () => {const { spawnDetached } = await import('../../lib/detachedSpawn.js');const spawnMock = vi.mocked(spawnDetached);spawnMock.mockClear();- mockInspectModelCache.mockResolvedValue({ cached: false, sizeBytes: 0, snapshotPath: null });+ mockFindCachedRepoFile.mockResolvedValue(null);await generateVideo({ ...baseIcRender, jobId: 'ic-colorize-uncached', mode: 'ic-colorize' });@@ -1988,7 +1995,7 @@ describe('generateVideo — IC-LoRA remix arg threading (#3100)', () => {// `_resolve_lora_path` would `snapshot_download` a gated repo / a ~708 GB// mirror. So an uncached Ingredients render must 400 rather than silently// starting an unbounded pull.- mockInspectModelCache.mockResolvedValue({ cached: false, sizeBytes: 0, snapshotPath: null });+ mockFindCachedRepoFile.mockResolvedValue(null);await expect(generateVideo({ ...baseIngredients, jobId: 'ing-uncached' })).rejects.toThrow(/is not downloaded — download Ingredients/);});@@ -2015,6 +2022,62 @@ describe('generateVideo — IC-LoRA remix arg threading (#3100)', () => {]);});+ it('cleans up EVERY temp clip when one still fails to encode', async () => {+ // Promise.all rejects at the first failure while siblings are still in+ // flight, so a push-on-success registry would miss the ones that landed+ // afterwards. Every target path is registered before any encode starts.+ const { execFile } = await import('child_process');+ const { unlink } = await import('fs/promises');+ const execFileMock = vi.mocked(execFile);+ const unlinkMock = vi.mocked(unlink);+ execFileMock.mockClear();+ unlinkMock.mockClear();++ // Fail the SECOND still; the first and third still succeed.+ let stillIndex = 0;+ execFileMock.mockImplementation((_bin, args, _opts, cb) => {+ if (args.includes('-loop')) {+ const mine = stillIndex++;+ if (mine === 1) return cb?.(new Error('ffmpeg exploded'));+ }+ return cb?.(null, '', '');+ });++ await expect(generateVideo({+ ...baseIngredients, jobId: 'ing-partial-fail',+ icReferencePaths: ['/mock/images/a.png', '/mock/images/b.png', '/mock/images/c.png'],+ })).rejects.toThrow(/Failed to prepare Ingredients reference b\.png/);++ // All three temp paths unlinked, not just the ones that had resolved when+ // the rejection fired.+ const unlinked = unlinkMock.mock.calls.map(([p]) => String(p));+ for (const i of [0, 1, 2]) {+ expect(unlinked.some((p) => p.includes(`ic-still-${i}-ing-partial-fail.mp4`))).toBe(true);+ }+ // The ORIGINAL gallery stills are the user's files and must survive.+ for (const f of ['/mock/images/a.png', '/mock/images/b.png', '/mock/images/c.png']) {+ expect(unlinked).not.toContain(f);+ }+ execFileMock.mockImplementation((_bin, _args, _opts, cb) => cb?.(null, '', ''));+ });++ it('cleans up the temp clips after a successful render', async () => {+ const { unlink } = await import('fs/promises');+ const unlinkMock = vi.mocked(unlink);+ unlinkMock.mockClear();++ await generateVideo({ ...baseIngredients, jobId: 'ing-cleanup' });+ // Success-path cleanup runs in the child's async close handler, which fires+ // after generateVideo resolves.+ await vi.waitFor(() => expect(unlinkMock).toHaveBeenCalled());++ const unlinked = unlinkMock.mock.calls.map(([p]) => String(p));+ for (const i of [0, 1]) {+ expect(unlinked.some((p) => p.includes(`ic-still-${i}-ing-cleanup.mp4`))).toBe(true);+ }+ expect(unlinked).not.toContain('/mock/images/owl.png');+ });+it('stamps the gallery basenames (not the temp clip paths) onto history', async () => {const started = [];const onStarted = (p) => started.push(p);