Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat([issue-1324]): verify downloaded model weights and offer one-click repair

[._.]/ Adam Eivy7cd202a03e77
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index aea1f5f9ce..967bc1de55 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,8 @@
## Added
+- **[issue-1324] Catch corrupt model weights and repair them in one click.** A download that finished with the *right file size but wrong bytes* (an interrupted resumable fetch, bit-rot) silently decodes to garbled "mosaic" renders that a clean re-download fixes — a leading non-hardware cause of bad output. PortOS now checks downloaded model weights for integrity: a fast structural scan of each `.safetensors` header (catches truncation without loading any tensors) runs automatically and is surfaced on the image- and video-gen model status, plus an optional deep per-file checksum scan on demand. When the Video Gen model you've selected has damaged weight files, a **Repair model** banner appears that deletes the bad files and re-downloads clean copies with progress — no need to wipe and re-fetch the whole multi-GB model by hand. (#1324)
+
- **[issue-1305] Continuity bible — an established-facts ledger for your series.** A new **Series Continuity** view (linked from the series page) builds a ledger of the concrete, *checkable* facts your story has committed to — the kind a later scene could contradict. Facts are **auto-seeded from universe canon** (each character's physical description, each place/object's description; **locked** canon is flagged as ground truth) and then **learned from the drafted prose** via an LLM extraction pass, sorted into seven buckets: physical traits, ages & birthdays, dates & elapsed time, locations & geography, possessions & wardrobe, world rules, and **who-knows-what-when**. Each fact shows its subject, the assertion, a canon/prose badge, and — for prose facts — a verbatim anchor quote and a deep-link to the issue where it was established. Generation streams live progress; the ledger flags itself **stale** when the manuscript or canon changes so you know to rebuild. This ledger is the substrate the upcoming contradiction checks (canon-contradiction, timeline, knowledge-leak, wardrobe/prop/injury) will read rather than re-deriving. New endpoints: `GET /api/pipeline/series/:id/continuity-bible` + `POST …/generate` (with SSE progress + cancel); one new stage prompt (`pipeline-continuity-bible`) shipped + migrated for existing installs. (#1305)
- **[issue-1304] Read aloud — proof a manuscript section by ear with synced karaoke highlighting.** Reading prose aloud is one of the most effective proofing techniques: clunky rhythm, tongue-twisters, repeated words, and unnatural sentences are obvious to the ear and invisible to the eye. The Manuscript Editor gets a **Read aloud** button (in the header, next to Impact preview) that opens a read-along panel for the active section. It synthesizes the section's prose with the same local TTS engines that already voice storyboard dialogue (Kokoro/Piper — no new dependency, no network), splitting the text into sentence segments so it can **highlight each sentence as it's spoken** (karaoke-style) and let you click any sentence to jump there. Sync needs no word-level timestamps: the server measures each sentence's WAV duration and the client plays the segments back-to-back, driving the highlight + a progress bar from those durations. A pick-a-narrator-voice control (remembered across sessions) reuses the shared VoicePicker. Each sentence also carries a lightweight **"hard to say" scan** — over-long sentences, hard consonant clusters, alliteration runs, and a word repeated in close proximity get a wavy underline + hover tooltip so likely trouble-spots are visible before and while you listen. Narration is strictly **non-destructive** — it only reads the section's current text and never mutates the manuscript. New endpoint: `POST /api/pipeline/tts/narrate` (text → per-segment audio + duration + readability). (`server/services/pipeline/manuscriptNarration.js`, `server/services/pipeline/audio.js`, `server/routes/pipeline/audio.js`, `client/src/components/pipeline/manuscript/ManuscriptReadAloud.jsx`, `client/src/pages/PipelineManuscriptEditor.jsx`, `client/src/services/apiPipeline.js`) (#1304)
diff --git a/client/src/hooks/useModelDownloadStatus.js b/client/src/hooks/useModelDownloadStatus.js
index 51772511a4..cb512c8bc5 100644
--- a/client/src/hooks/useModelDownloadStatus.js
+++ b/client/src/hooks/useModelDownloadStatus.js
@@ -1,7 +1,10 @@
import { useEffect, useState, useCallback, useMemo } from 'react';
import { useSseProgress } from './useSseProgress.js';
import toast from '../components/ui/Toast';
-import { getImageModelStatuses, getVideoModelStatuses } from '../services/apiImageVideo.js';
+import {
+ getImageModelStatuses, getVideoModelStatuses,
+ verifyImageModels, verifyVideoModels, repairImageModel, repairVideoModel,
+} from '../services/apiImageVideo.js';
// Sentinel `modelId` used to drive a text-encoder download instead of a model
// download. The video form passes this to `start()`; the URL builder below
@@ -77,6 +80,40 @@ export function useModelDownloadStatus({ kind = 'image' } = {}) {
setActiveModelId(modelId);
}, []);
+ // Force a deep integrity re-scan (per-file sha256). Returns the server's
+ // result and refreshes the status list so the structural badge stays current.
+ // `verifying` flips while in flight so the caller can disable the button.
+ const [verifying, setVerifying] = useState(false);
+ const verify = useCallback(async ({ modelId, deep = true } = {}) => {
+ setVerifying(true);
+ const fn = kind === 'video' ? verifyVideoModels : verifyImageModels;
+ const result = await fn({ modelId, deep }).catch((err) => {
+ toast.error(err?.message || 'Integrity scan failed');
+ return null;
+ });
+ await fetchStatuses();
+ setVerifying(false);
+ return result;
+ }, [kind, fetchStatuses]);
+
+ // Repair = delete the flagged corrupt files, then re-download them through
+ // the same SSE path the Download button uses (progress + auto status-refresh
+ // on completion come for free). `repairing` gates the button while the
+ // deletion request is in flight.
+ const [repairing, setRepairing] = useState(false);
+ const repair = useCallback(async (modelId, { deep = false } = {}) => {
+ if (!modelId) return;
+ setRepairing(true);
+ const fn = kind === 'video' ? repairVideoModel : repairImageModel;
+ const result = await fn(modelId, { deep }).catch((err) => {
+ toast.error(err?.message || 'Repair failed');
+ return null;
+ });
+ setRepairing(false);
+ if (result) start(modelId); // re-download clean copies via the existing SSE
+ return result;
+ }, [kind, start]);
+
// Manual cancel: refetch directly because `sse.close()` followed by
// setActiveModelId(null) clears the URL, which causes useSseProgress to
// reset `closed → false` before the close-effect can observe `true`.
@@ -113,6 +150,10 @@ export function useModelDownloadStatus({ kind = 'image' } = {}) {
refresh: fetchStatuses,
start,
cancel,
+ verify,
+ verifying,
+ repair,
+ repairing,
getStatus,
activeModelId,
progress: sse.latest,
diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsx
index 3dda1d65e5..64ea6297f0 100644
--- a/client/src/pages/VideoGen.jsx
+++ b/client/src/pages/VideoGen.jsx
@@ -874,6 +874,16 @@ export default function VideoGen() {
: textEncoderInfo)
: null;
+ // Weight-integrity (issue #1324). A corrupt/truncated model decodes to
+ // garbled "mosaic" video that a clean re-download fixes; surface a Repair
+ // banner keyed on the cheap structural check the status poll already ran so
+ // the user can delete + re-fetch the bad files instead of debugging a render.
+ const modelIntegrity = modelStatus && !modelStatus.downloading ? modelStatus.integrity : null;
+ const integrityBad = modelIntegrity?.status === 'bad';
+ const integrityKey = integrityBad ? `${modelId}:${(modelIntegrity.badFiles || []).map((f) => f.name).join(',')}` : null;
+ const [dismissedIntegrityKey, setDismissedIntegrityKey] = useState(null);
+ const showIntegrityBanner = integrityBad && dismissedIntegrityKey !== integrityKey && !modelDownload.downloading;
+
const { matched: matchedResolution, label: resolutionLabel } = resolveResolutionLabel(VIDEO_RESOLUTIONS, width, height);
const progressPct = progress?.progress != null ? Math.round(progress.progress * 100) : null;
@@ -1404,6 +1414,35 @@ export default function VideoGen() {
</button>
</div>
)}
+ {showIntegrityBanner && (
+ <div className="rounded-lg border border-port-error/40 bg-port-error/10 px-3 py-3 text-xs text-port-error flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2">
+ <div className="flex items-start gap-2">
+ <AlertTriangle className="w-4 h-4 shrink-0 mt-0.5" />
+ <div>
+ <strong className="font-semibold">{currentModel?.name || modelId}</strong> has {(modelIntegrity.badFiles || []).length || 'corrupt'} damaged weight file{(modelIntegrity.badFiles || []).length === 1 ? '' : 's'} — renders may come out garbled.
+ Repair deletes the bad file{(modelIntegrity.badFiles || []).length === 1 ? '' : 's'} and re-downloads clean copies.
+ </div>
+ </div>
+ <div className="flex items-center gap-2 self-start sm:self-auto">
+ <button
+ type="button"
+ onClick={() => { setDismissedIntegrityKey(integrityKey); modelDownload.repair(modelId); }}
+ disabled={modelDownload.repairing || modelDownload.downloading}
+ className="whitespace-nowrap inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-port-error text-white text-xs font-medium hover:bg-port-error/80 disabled:opacity-50"
+ >
+ <RefreshCw className={`w-3.5 h-3.5 ${modelDownload.repairing ? 'animate-spin' : ''}`} />
+ Repair model
+ </button>
+ <button
+ type="button"
+ onClick={() => setDismissedIntegrityKey(integrityKey)}
+ className="text-gray-400 hover:text-gray-200 text-xs"
+ >
+ Dismiss
+ </button>
+ </div>
+ </div>
+ )}
<StylePresetPicker
value={stylePreset?.id || ''}
onChange={setStylePreset}
diff --git a/client/src/services/apiImageVideo.js b/client/src/services/apiImageVideo.js
index 87dc109bd3..ee37ee7ac4 100644
--- a/client/src/services/apiImageVideo.js
+++ b/client/src/services/apiImageVideo.js
@@ -7,6 +7,21 @@ export const listImageModels = () => request('/image-gen/models');
// Per-model download status: `[{ id, repo, cached, sizeBytes }]`. Drives the
// inline Available/Download badge on the image gen form.
export const getImageModelStatuses = () => request('/image-gen/models/status', { silent: true });
+// Force an integrity re-scan of downloaded models. `deep:true` adds the
+// per-file sha256 comparison (slower) on top of the cheap structural check the
+// status poll already runs. Silent — callers own their own error UI.
+export const verifyImageModels = ({ modelId, deep = false } = {}) => request('/image-gen/models/verify', {
+ method: 'POST',
+ body: JSON.stringify({ ...(modelId ? { modelId } : {}), deep }),
+ silent: true,
+});
+// Delete the corrupt/truncated weight files for a model so the existing
+// download path re-fetches clean copies. Returns `{ deleted, repos }`.
+export const repairImageModel = (modelId, { deep = false } = {}) => request(`/image-gen/models/${encodeURIComponent(modelId)}/repair`, {
+ method: 'POST',
+ body: JSON.stringify({ deep }),
+ silent: true,
+});
export const listLoras = () => request('/image-gen/loras');
export const listImageGallery = () => request('/image-gen/gallery');
export const getActiveImageJob = () => request('/image-gen/active');
@@ -77,6 +92,17 @@ export const listVideoModels = (options) => request('/video-gen/models', options
// contract as the image variant + a text-encoder block since the active
// encoder is a separate multi-GB pull.
export const getVideoModelStatuses = () => request('/video-gen/models/status', { silent: true });
+// Integrity re-scan / repair — mirrors the image-gen helpers above.
+export const verifyVideoModels = ({ modelId, deep = false } = {}) => request('/video-gen/models/verify', {
+ method: 'POST',
+ body: JSON.stringify({ ...(modelId ? { modelId } : {}), deep }),
+ silent: true,
+});
+export const repairVideoModel = (modelId, { deep = false } = {}) => request(`/video-gen/models/${encodeURIComponent(modelId)}/repair`, {
+ method: 'POST',
+ body: JSON.stringify({ deep }),
+ silent: true,
+});
export const cancelVideoGen = () => request('/video-gen/cancel', { method: 'POST' });
// Currently-running (or next-queued) video job — used on VideoGen mount to
// resume progress display after a page reload. Silent so a 5xx during status
diff --git a/server/lib/README.md b/server/lib/README.md
index 6f8a79105d..94f97f29b0 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -93,7 +93,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). |
| `hfErrors.js` | Parse huggingface_hub gated-access errors: `extractGatedRepo(text)` → `owner/name` (or null) for the UI's license deep-link. Shared by the image runner and LoRA trainer. Pure. |
-| `hfCache.js` | HuggingFace Hub cache inspection (`inspectModelCache(repoId)` → `{cached,sizeBytes,snapshotPath}`, `isModelCached`, `getHfCacheRoot`). Drives the inline "Available / Download" badge on the image + video gen forms. |
+| `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. |
| `hfDownload.js` | `downloadHfRepo({repo,onEvent})` returning `{promise,kill}` — spawns `scripts/hf_download_repo.py` in the FLUX.2 venv (fallback: mflux pythonPath) and emits SSE-friendly stage/progress/complete events. Powers the inline "Download" button next to the model picker. |
| `sseDownload.js` | `startHfDownloadStream({req,res,repo,alreadyDownloadedMessage})`, `openSseStream(res)` (`{send,safeEnd}` SSE boilerplate), `SSE_HEADERS` — shared SSE driver used by both image and video gen `/models/:id/download` routes. Owns the cross-route in-flight Map so a double-click (or both pages running) can't spawn two python children against the same repo. |
diff --git a/server/lib/hfCache.js b/server/lib/hfCache.js
index d8da3c0275..2e3456d983 100644
--- a/server/lib/hfCache.js
+++ b/server/lib/hfCache.js
@@ -20,9 +20,10 @@
// route — which inspects every registered model — doesn't block the Node
// event loop while walking large snapshot directories.
-import { promises as fs } from 'node:fs';
+import { promises as fs, createReadStream } from 'node:fs';
import { homedir } from 'node:os';
-import { join } from 'node:path';
+import { join, dirname, resolve as resolvePath } from 'node:path';
+import { createHash } from 'node:crypto';
// HF cache root resolution mirrors huggingface_hub's own precedence:
// HF_HUB_CACHE > HF_HOME/hub > $XDG_CACHE_HOME/huggingface/hub
@@ -127,3 +128,200 @@ export async function inspectModelCache(repoId) {
}
export const isModelCached = async (repoId) => (await inspectModelCache(repoId)).cached;
+
+// ---------------------------------------------------------------------------
+// Weight-integrity verification (issue #1324)
+//
+// `inspectModelCache` only confirms each weight blob *exists* and is non-zero.
+// That misses the failure mode upstream proved out: a corrupt/partial download
+// with the *right size but wrong bytes* (e.g. an interrupted resumable fetch
+// that left a truncated tensor region, or bit-rot) decodes to garbled "mosaic"
+// renders that a clean re-download fixes. `verifyModelCache` adds two cheap,
+// no-tensor-load integrity checks on top of the existence check:
+//
+// structural — for every `.safetensors` file, read the 8-byte little-endian
+// header-length prefix + the JSON header and confirm the file is at least
+// `8 + headerLen + max(data_offsets.end)` bytes long. Catches truncation
+// and corrupt headers without loading a single tensor.
+// deep (opt-in) — hash each weight file and compare against HuggingFace's
+// published content hash. We get that hash for free, *with no network*:
+// HF names each cache blob by its etag, which for LFS weight files IS the
+// sha256 of the content. The snapshot file is a symlink into
+// `../../blobs/<sha256>`, so the symlink target's basename is the expected
+// digest. (Non-LFS files are named by a git sha1 — skipped, they're tiny
+// config/tokenizer files we don't treat as weights anyway.)
+// ---------------------------------------------------------------------------
+
+const SAFETENSORS_MAX_HEADER_BYTES = 100_000_000; // 100MB — far above any real header
+const SHA256_RE = /^[0-9a-f]{64}$/;
+
+// Cheap structural check for a single .safetensors file. Reads only the header
+// region (a few KB), never the tensor payload. Returns { ok, reason, ... }.
+async function verifySafetensorsStructure(path, size) {
+ if (size < 8) return { ok: false, reason: 'truncated-header' };
+ let fd;
+ try {
+ fd = await fs.open(path, 'r');
+ } catch {
+ return { ok: false, reason: 'unreadable' };
+ }
+ try {
+ const head = Buffer.alloc(8);
+ await fd.read(head, 0, 8, 0);
+ const headerLen = Number(head.readBigUInt64LE(0));
+ if (!Number.isSafeInteger(headerLen) || headerLen <= 0
+ || headerLen > SAFETENSORS_MAX_HEADER_BYTES || 8 + headerLen > size) {
+ return { ok: false, reason: 'bad-header-length' };
+ }
+ const jsonBuf = Buffer.alloc(headerLen);
+ await fd.read(jsonBuf, 0, headerLen, 8);
+ let header;
+ try {
+ header = JSON.parse(jsonBuf.toString('utf8'));
+ } catch {
+ return { ok: false, reason: 'unparseable-header' };
+ }
+ // The largest tensor end-offset (relative to the byte buffer after the
+ // header) is the minimum payload length the file must contain.
+ let maxEnd = 0;
+ for (const [name, tensor] of Object.entries(header)) {
+ if (name === '__metadata__') continue;
+ const off = tensor?.data_offsets;
+ if (Array.isArray(off) && off.length === 2 && Number.isFinite(off[1]) && off[1] > maxEnd) {
+ maxEnd = off[1];
+ }
+ }
+ const expectedBytes = 8 + headerLen + maxEnd;
+ if (size < expectedBytes) {
+ return { ok: false, reason: 'truncated-data', expectedBytes, actualBytes: size };
+ }
+ return { ok: true, reason: 'structural-ok' };
+ } finally {
+ await fd.close().catch(() => {});
+ }
+}
+
+// The expected sha256 for a cache blob is the symlink target's basename (HF
+// names LFS blobs by their sha256 etag). Returns null when the snapshot entry
+// is a real file (local_dir copy) or a git-sha1-named non-LFS blob — both
+// cases have no usable sha256 to compare against.
+async function expectedBlobSha256(path) {
+ const lst = await fs.lstat(path).catch(() => null);
+ if (!lst || !lst.isSymbolicLink()) return null;
+ const target = await fs.readlink(path).catch(() => null);
+ if (!target) return null;
+ const base = target.split('/').pop();
+ return SHA256_RE.test(base) ? base : null;
+}
+
+async function sha256OfFile(path) {
+ return new Promise((resolve, reject) => {
+ const hash = createHash('sha256');
+ const stream = createReadStream(path);
+ stream.on('error', reject);
+ stream.on('data', (chunk) => hash.update(chunk));
+ stream.on('end', () => resolve(hash.digest('hex')));
+ });
+}
+
+// Verify a single weight file. `deep` adds the sha256 comparison on top of the
+// structural check.
+async function verifyWeightFile(file, { deep }) {
+ const stat = await fs.stat(file.path).catch(() => null); // follows symlink
+ if (!stat) return { name: file.name, ok: false, reason: 'missing-blob', sizeBytes: 0 };
+ if (stat.size === 0) return { name: file.name, ok: false, reason: 'empty', sizeBytes: 0 };
+
+ const entry = { name: file.name, ok: true, reason: 'size-only', sizeBytes: stat.size };
+ if (file.name.endsWith('.safetensors')) {
+ const structural = await verifySafetensorsStructure(file.path, stat.size);
+ if (!structural.ok) {
+ return { ...entry, ok: false, reason: structural.reason, expectedBytes: structural.expectedBytes };
+ }
+ entry.reason = 'structural-ok';
+ }
+ if (deep) {
+ const expectedSha = await expectedBlobSha256(file.path);
+ if (expectedSha) {
+ const actualSha = await sha256OfFile(file.path).catch(() => null);
+ if (actualSha && actualSha !== expectedSha) {
+ return { ...entry, ok: false, reason: 'sha256-mismatch' };
+ }
+ if (actualSha) entry.reason = 'sha256-ok';
+ }
+ }
+ return entry;
+}
+
+// Returns `{ repoId, status, cached, sizeBytes, snapshotPath, checkedDeep, files }`.
+// `status` is one of:
+// 'missing' — no snapshot / no weight files (nothing downloaded to verify)
+// 'ok' — every weight file passed its checks
+// 'bad' — at least one weight file is corrupt/truncated/missing-blob
+// `files` carries a per-file `{ name, ok, reason, sizeBytes }` breakdown so the
+// repair path knows exactly which files to delete and the UI can explain why.
+export async function verifyModelCache(repoId, { deep = false } = {}) {
+ const base = {
+ repoId, status: 'missing', cached: false, sizeBytes: 0,
+ snapshotPath: null, checkedDeep: deep, files: [],
+ };
+ if (!repoId || typeof repoId !== 'string') return base;
+ const root = getHfCacheRoot();
+ const repoDir = join(root, repoToDirName(repoId));
+ const snapshotPath = await latestSnapshotDir(repoDir);
+ if (!snapshotPath) return base;
+ const weights = [];
+ await collectWeightFiles(snapshotPath, weights);
+ if (weights.length === 0) return { ...base, snapshotPath };
+
+ const files = await Promise.all(weights.map((w) => verifyWeightFile(w, { deep })));
+ let sizeBytes = 0;
+ let anyBad = false;
+ for (const f of files) {
+ if (f.ok) sizeBytes += f.sizeBytes || 0;
+ else anyBad = true;
+ }
+ return {
+ repoId,
+ status: anyBad ? 'bad' : 'ok',
+ cached: !anyBad,
+ sizeBytes,
+ snapshotPath,
+ checkedDeep: deep,
+ files,
+ };
+}
+
+// Delete the flagged (corrupt/truncated/missing-blob) weight files so the
+// existing resumable HF fetch path re-downloads them. For symlinked cache
+// entries we unlink BOTH the snapshot symlink and the blob it points at — a
+// stale blob with the right name but wrong bytes would otherwise be trusted by
+// `hf_hub_download` (it keys on the cached etag, not the content) and never
+// re-fetched. Returns `{ repoId, status, deleted: [names] }`; an 'ok' or
+// 'missing' status deletes nothing (caller just re-downloads from scratch).
+export async function repairModelCache(repoId, { deep = false } = {}) {
+ const verify = await verifyModelCache(repoId, { deep });
+ if (verify.status !== 'bad') {
+ return { repoId, status: verify.status, deleted: [] };
+ }
+ const snapshotPath = verify.snapshotPath;
+ const weights = [];
+ await collectWeightFiles(snapshotPath, weights);
+ const byName = new Map(weights.map((w) => [w.name, w.path]));
+ const badNames = verify.files.filter((f) => !f.ok).map((f) => f.name);
+ const deleted = [];
+ for (const name of badNames) {
+ const path = byName.get(name);
+ if (!path) continue;
+ const lst = await fs.lstat(path).catch(() => null);
+ if (lst?.isSymbolicLink()) {
+ const target = await fs.readlink(path).catch(() => null);
+ if (target) {
+ const blobPath = resolvePath(dirname(path), target);
+ await fs.unlink(blobPath).catch(() => {});
+ }
+ }
+ await fs.unlink(path).catch(() => {});
+ deleted.push(name);
+ }
+ return { repoId, status: 'bad', deleted };
+}
diff --git a/server/lib/hfCache.test.js b/server/lib/hfCache.test.js
index 650ce71a79..e66cc50d71 100644
--- a/server/lib/hfCache.test.js
+++ b/server/lib/hfCache.test.js
@@ -1,8 +1,48 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
-import { mkdtempSync, mkdirSync, writeFileSync, symlinkSync, rmSync } from 'node:fs';
+import { mkdtempSync, mkdirSync, writeFileSync, symlinkSync, rmSync, existsSync, readlinkSync } from 'node:fs';
+import { createHash } from 'node:crypto';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
-import { inspectModelCache, getHfCacheRoot, isModelCached } from './hfCache.js';
+import {
+ inspectModelCache, getHfCacheRoot, isModelCached,
+ verifyModelCache, repairModelCache,
+} from './hfCache.js';
+
+// Build a minimal *valid* .safetensors buffer: 8-byte LE header length, a JSON
+// header declaring one tensor whose data_offsets span `dataLen` bytes, then the
+// data region. `truncateBy` lops bytes off the end to simulate a partial fetch.
+function buildSafetensors({ dataLen = 16, truncateBy = 0 } = {}) {
+ const header = JSON.stringify({ t: { dtype: 'F32', shape: [dataLen / 4], data_offsets: [0, dataLen] } });
+ const headerBuf = Buffer.from(header, 'utf8');
+ const lenBuf = Buffer.alloc(8);
+ lenBuf.writeBigUInt64LE(BigInt(headerBuf.length), 0);
+ const data = Buffer.alloc(dataLen, 7);
+ const full = Buffer.concat([lenBuf, headerBuf, data]);
+ return truncateBy > 0 ? full.subarray(0, full.length - truncateBy) : full;
+}
+
+// Build a fake HF cache with real file contents (vs. the zero-filled blobs the
+// inspect tests use). Each file is symlinked into the snapshot from a blob
+// named by its sha256 — matching how HF names LFS blobs, which is what the deep
+// sha256 check relies on. `blobName` overrides the blob name to force a
+// sha256 mismatch.
+function buildContentCache({ repoId, files }) {
+ const root = mkdtempSync(join(tmpdir(), 'hfverify-test-'));
+ const repoDir = join(root, `models--${repoId.replace(/\//g, '--')}`);
+ const blobsDir = join(repoDir, 'blobs');
+ const snapDir = join(repoDir, 'snapshots', 'sha');
+ mkdirSync(blobsDir, { recursive: true });
+ mkdirSync(snapDir, { recursive: true });
+ for (const [filename, spec] of Object.entries(files)) {
+ const content = spec.content;
+ const sha = spec.blobName || createHash('sha256').update(content).digest('hex');
+ const blobPath = join(blobsDir, sha);
+ writeFileSync(blobPath, content);
+ // Relative symlink mirrors HF's `../../blobs/<sha>` layout.
+ symlinkSync(join('..', '..', 'blobs', sha), join(snapDir, filename));
+ }
+ return { root, repoDir, snapDir, blobsDir };
+}
// Build a fake HF cache layout under tmp so we can assert the inspector
// without touching the user's real ~/.cache/huggingface/hub. Snapshot files
@@ -140,3 +180,137 @@ describe('hfCache', () => {
expect((await inspectModelCache(undefined)).cached).toBe(false);
});
});
+
+describe('verifyModelCache', () => {
+ let originalEnv;
+ const roots = [];
+ 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 r of roots.splice(0)) rmSync(r, { recursive: true, force: true });
+ });
+
+ it('returns status "missing" for a repo with no snapshot', async () => {
+ process.env.HF_HUB_CACHE = mkdtempSync(join(tmpdir(), 'hfverify-empty-'));
+ roots.push(process.env.HF_HUB_CACHE);
+ const r = await verifyModelCache('foo/bar');
+ expect(r.status).toBe('missing');
+ expect(r.cached).toBe(false);
+ });
+
+ it('returns status "ok" for a structurally valid safetensors', async () => {
+ const { root } = buildContentCache({
+ repoId: 'org/good',
+ files: { 'model.safetensors': { content: buildSafetensors({ dataLen: 32 }) } },
+ });
+ roots.push(root);
+ process.env.HF_HUB_CACHE = root;
+ const r = await verifyModelCache('org/good');
+ expect(r.status).toBe('ok');
+ expect(r.cached).toBe(true);
+ expect(r.files).toHaveLength(1);
+ expect(r.files[0].ok).toBe(true);
+ });
+
+ it('flags a truncated safetensors (right header, missing tail bytes) as bad', async () => {
+ const { root } = buildContentCache({
+ repoId: 'org/truncated',
+ files: { 'model.safetensors': { content: buildSafetensors({ dataLen: 64, truncateBy: 16 }) } },
+ });
+ roots.push(root);
+ process.env.HF_HUB_CACHE = root;
+ const r = await verifyModelCache('org/truncated');
+ expect(r.status).toBe('bad');
+ expect(r.files[0].ok).toBe(false);
+ expect(r.files[0].reason).toBe('truncated-data');
+ });
+
+ it('flags a garbage (non-safetensors) header as bad', async () => {
+ const { root } = buildContentCache({
+ repoId: 'org/garbage',
+ files: { 'model.safetensors': { content: Buffer.alloc(4096, 0) } }, // header length 0
+ });
+ roots.push(root);
+ process.env.HF_HUB_CACHE = root;
+ const r = await verifyModelCache('org/garbage');
+ expect(r.status).toBe('bad');
+ expect(r.files[0].reason).toBe('bad-header-length');
+ });
+
+ it('deep check passes when content sha256 matches the blob name', async () => {
+ const { root } = buildContentCache({
+ repoId: 'org/deepok',
+ files: { 'model.safetensors': { content: buildSafetensors({ dataLen: 16 }) } },
+ });
+ roots.push(root);
+ process.env.HF_HUB_CACHE = root;
+ const r = await verifyModelCache('org/deepok', { deep: true });
+ expect(r.status).toBe('ok');
+ expect(r.checkedDeep).toBe(true);
+ expect(r.files[0].reason).toBe('sha256-ok');
+ });
+
+ it('deep check flags content whose sha256 differs from the blob name', async () => {
+ const { root } = buildContentCache({
+ repoId: 'org/deepbad',
+ files: {
+ // structurally valid, but stored under a wrong (mismatched) blob name
+ 'model.safetensors': { content: buildSafetensors({ dataLen: 16 }), blobName: 'a'.repeat(64) },
+ },
+ });
+ roots.push(root);
+ process.env.HF_HUB_CACHE = root;
+ const structural = await verifyModelCache('org/deepbad');
+ expect(structural.status).toBe('ok'); // structural alone can't catch wrong-bytes
+ const deep = await verifyModelCache('org/deepbad', { deep: true });
+ expect(deep.status).toBe('bad');
+ expect(deep.files[0].reason).toBe('sha256-mismatch');
+ });
+});
+
+describe('repairModelCache', () => {
+ let originalEnv;
+ const roots = [];
+ 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 r of roots.splice(0)) rmSync(r, { recursive: true, force: true });
+ });
+
+ it('deletes the corrupt file (symlink + blob) and leaves good files alone', async () => {
+ const { root, snapDir, blobsDir } = buildContentCache({
+ repoId: 'org/mixed',
+ files: {
+ 'good.safetensors': { content: buildSafetensors({ dataLen: 32 }) },
+ 'bad.safetensors': { content: buildSafetensors({ dataLen: 64, truncateBy: 16 }) },
+ },
+ });
+ roots.push(root);
+ process.env.HF_HUB_CACHE = root;
+
+ const badBlob = join(blobsDir, readlinkSync(join(snapDir, 'bad.safetensors')).split('/').pop());
+ expect(existsSync(badBlob)).toBe(true);
+
+ const result = await repairModelCache('org/mixed');
+ expect(result.status).toBe('bad');
+ expect(result.deleted).toEqual(['bad.safetensors']);
+ // The bad symlink + blob are gone; the good file is untouched.
+ expect(existsSync(join(snapDir, 'bad.safetensors'))).toBe(false);
+ expect(existsSync(badBlob)).toBe(false);
+ expect(existsSync(join(snapDir, 'good.safetensors'))).toBe(true);
+ });
+
+ it('is a no-op when integrity is already ok', async () => {
+ const { root } = buildContentCache({
+ repoId: 'org/clean',
+ files: { 'model.safetensors': { content: buildSafetensors({ dataLen: 32 }) } },
+ });
+ roots.push(root);
+ process.env.HF_HUB_CACHE = root;
+ const result = await repairModelCache('org/clean');
+ expect(result.status).toBe('ok');
+ expect(result.deleted).toEqual([]);
+ });
+});
diff --git a/server/routes/imageGen.integrity.test.js b/server/routes/imageGen.integrity.test.js
new file mode 100644
index 0000000000..e1950a938f
--- /dev/null
+++ b/server/routes/imageGen.integrity.test.js
@@ -0,0 +1,101 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+
+// Integrity / repair routes (issue #1324). Mocks mediaModels + hfCache so the
+// thin route glue is exercised in isolation; the real structural/sha256 logic
+// is covered in lib/hfCache.test.js. The remaining mock set mirrors
+// imageGen.test.js so the route's import graph links under vitest.
+
+vi.mock('../lib/mediaModels.js', () => ({
+ getImageModels: vi.fn(() => [{ id: 'flux2', name: 'FLUX.2' }]),
+ isFlux2: vi.fn(() => true),
+ isEditOnly: vi.fn(() => false),
+ repoForModel: vi.fn((m) => `org/${m.id}`),
+ requiredReposForModel: vi.fn((m) => [`org/${m.id}`]),
+}));
+
+vi.mock('../lib/hfCache.js', () => ({
+ inspectModelCache: vi.fn(async () => ({ cached: true, sizeBytes: 100, snapshotPath: '/snap' })),
+ verifyModelCache: vi.fn(async (repoId, opts) => ({
+ repoId, status: 'bad', cached: false, sizeBytes: 0, snapshotPath: '/snap',
+ checkedDeep: !!opts?.deep,
+ files: [{ name: 'model.safetensors', ok: false, reason: 'truncated-data', sizeBytes: 10 }],
+ })),
+ repairModelCache: vi.fn(async (repoId) => ({ repoId, status: 'bad', deleted: ['model.safetensors'] })),
+}));
+
+vi.mock('../services/imageGen/index.js', () => ({
+ checkConnection: vi.fn(),
+ generateImage: vi.fn(),
+ generateAvatar: vi.fn(),
+ attachSseClient: vi.fn(() => false),
+ cancel: vi.fn(() => false),
+ IMAGE_GEN_MODE: { EXTERNAL: 'external', LOCAL: 'local', CODEX: 'codex' },
+ IMAGE_GEN_MODES: ['external', 'local', 'codex'],
+ resolveImageCleaners: () => ({ cleanC2PA: true, denoise: false }),
+ local: { listImageModels: vi.fn(() => []) },
+}));
+
+vi.mock('../services/settings.js', () => ({
+ getSettings: vi.fn(async () => ({ imageGen: { mode: 'external' } })),
+ updateSettingsWith: vi.fn(async () => {}),
+}));
+
+vi.mock('../services/mediaJobQueue/index.js', () => ({
+ enqueueJob: vi.fn(() => ({ jobId: 'mock', position: 1, status: 'queued' })),
+ attachSseClient: vi.fn(() => false),
+ cancelJob: vi.fn(async () => ({ ok: true })),
+ listJobs: vi.fn(() => []),
+}));
+
+vi.mock('../lib/pythonSetup.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ isFlux2VenvHealthy: vi.fn(async () => true),
+ resolveFlux2Python: vi.fn(() => null),
+}));
+
+import imageGenRoutes from './imageGen.js';
+import { verifyModelCache, repairModelCache } from '../lib/hfCache.js';
+
+describe('Image Gen integrity routes', () => {
+ let app;
+ beforeEach(() => {
+ app = express();
+ app.use(express.json());
+ app.use('/api/image-gen', imageGenRoutes);
+ app.use(errorMiddleware);
+ vi.clearAllMocks();
+ });
+
+ it('GET /models/status surfaces an integrity block for cached models', async () => {
+ const res = await request(app).get('/api/image-gen/models/status');
+ expect(res.status).toBe(200);
+ const entry = res.body.find((m) => m.id === 'flux2');
+ expect(entry.cached).toBe(true);
+ expect(entry.integrity.status).toBe('bad');
+ expect(entry.integrity.badFiles[0].name).toBe('model.safetensors');
+ });
+
+ it('POST /models/verify runs a deep scan and returns per-model status', async () => {
+ const res = await request(app).post('/api/image-gen/models/verify').send({ deep: true });
+ expect(res.status).toBe(200);
+ expect(res.body.deep).toBe(true);
+ expect(res.body.models[0].status).toBe('bad');
+ // deep:true must reach verifyModelCache
+ expect(verifyModelCache).toHaveBeenCalledWith('org/flux2', { deep: true });
+ });
+
+ it('POST /models/:id/repair deletes flagged files and reports them', async () => {
+ const res = await request(app).post('/api/image-gen/models/flux2/repair').send({});
+ expect(res.status).toBe(200);
+ expect(res.body.deleted).toEqual([{ repo: 'org/flux2', name: 'model.safetensors' }]);
+ expect(repairModelCache).toHaveBeenCalledWith('org/flux2', { deep: false });
+ });
+
+ it('POST /models/:id/repair 404s for an unknown model', async () => {
+ const res = await request(app).post('/api/image-gen/models/nope/repair').send({});
+ expect(res.status).toBe(404);
+ });
+});
diff --git a/server/routes/imageGen.js b/server/routes/imageGen.js
index ed56037a40..e530d6da27 100644
--- a/server/routes/imageGen.js
+++ b/server/routes/imageGen.js
@@ -12,7 +12,7 @@
import { Router } from 'express';
import { z } from 'zod';
import { unlink, stat } from 'fs/promises';
-import { asyncHandler, ServerError } from '../lib/errorHandler.js';
+import { asyncHandler, ServerError, failValidation } from '../lib/errorHandler.js';
import {
validateRequest, imageEdgeSchema, refineImagePixelCap, PIXEL_CAP_MESSAGE,
} from '../lib/validation.js';
@@ -24,7 +24,7 @@ import { getSettings, updateSettingsWith } from '../services/settings.js';
import { getHfToken, getHfTokenInfo, HF_TOKEN_REGEX } from '../lib/hfToken.js';
import { getImageModels, isFlux2, isEditOnly, repoForModel, requiredReposForModel } from '../lib/mediaModels.js';
import { usesDiffusersRunner } from '../lib/runners.js';
-import { inspectModelCache } from '../lib/hfCache.js';
+import { inspectModelCache, verifyModelCache, repairModelCache } from '../lib/hfCache.js';
import { startHfDownloadStream, openSseStream } from '../lib/sseDownload.js';
import {
REQUIRED_PACKAGES, detectPython, installPackages,
@@ -375,11 +375,70 @@ router.get('/models/status', asyncHandler(async (_req, res) => {
const cached = inspections.every((i) => i.cached);
const sizeBytes = inspections.reduce((sum, i) => sum + (i.sizeBytes || 0), 0);
const pendingRepos = required.filter((_, i) => !inspections[i].cached);
- return { id: m.id, repo: required[0], cached, sizeBytes, requiredRepos: required, pendingRepos };
+ // Integrity is only meaningful for repos that finished downloading — run
+ // the cheap structural check across every cached required repo and report
+ // the worst result, so a corrupt aux encoder still surfaces a Repair state.
+ const integrity = cached ? aggregateIntegrity(await Promise.all(required.map((r) => verifyModelCache(r)))) : null;
+ return { id: m.id, repo: required[0], cached, sizeBytes, requiredRepos: required, pendingRepos, integrity };
}));
res.json(statuses);
}));
+// Condense one-or-more verifyModelCache() results into the UI-facing shape
+// `{ status, badFiles }`. 'bad' wins over 'ok' wins over 'missing' so a model
+// whose main weights verify but whose aux encoder is corrupt still reports bad.
+function aggregateIntegrity(verifies) {
+ const list = verifies.filter(Boolean);
+ if (list.length === 0) return null;
+ const status = list.some((v) => v.status === 'bad') ? 'bad'
+ : list.every((v) => v.status === 'ok') ? 'ok'
+ : 'missing';
+ const badFiles = list.flatMap((v) => v.files.filter((f) => !f.ok).map((f) => ({ repo: v.repoId, name: f.name, reason: f.reason })));
+ return { status, checkedDeep: list.every((v) => v.checkedDeep), badFiles };
+}
+
+// POST /models/verify — on-demand integrity re-scan. `deep:true` adds the
+// per-file sha256 comparison on top of the structural check. With no `modelId`
+// it scans every model.
+const verifyImageBodySchema = z.object({
+ modelId: z.string().min(1).optional(),
+ deep: z.boolean().optional(),
+});
+router.post('/models/verify', asyncHandler(async (req, res) => {
+ const parsed = verifyImageBodySchema.safeParse(req.body || {});
+ if (!parsed.success) failValidation(parsed);
+ const { modelId, deep = false } = parsed.data;
+ const models = getImageModels().filter((m) => (modelId ? m.id === modelId : true));
+ if (modelId && models.length === 0) {
+ throw new ServerError(`Unknown model id: ${modelId}`, { status: 404, code: 'UNKNOWN_MODEL' });
+ }
+ const results = await Promise.all(models.map(async (m) => {
+ const required = requiredReposForModel(m) || [];
+ const verifies = await Promise.all(required.map((r) => verifyModelCache(r, { deep })));
+ return { id: m.id, ...(aggregateIntegrity(verifies) || { status: 'missing', badFiles: [] }) };
+ }));
+ res.json({ deep, models: results });
+}));
+
+// POST /models/:modelId/repair — delete the flagged weight files across the
+// model's required repos so the existing resumable HF fetch path re-downloads
+// them. Returns the deleted-file list; the client then re-triggers the normal
+// download SSE to pull clean copies with progress.
+router.post('/models/:modelId/repair', asyncHandler(async (req, res) => {
+ const model = getImageModels().find((m) => m.id === req.params.modelId);
+ if (!model) throw new ServerError(`Unknown model id: ${req.params.modelId}`, { status: 404, code: 'UNKNOWN_MODEL' });
+ const parsed = z.object({ deep: z.boolean().optional() }).safeParse(req.body || {});
+ if (!parsed.success) failValidation(parsed);
+ const deep = parsed.data.deep || false;
+ const required = requiredReposForModel(model);
+ if (!required) {
+ throw new ServerError(`Model "${model.id}" has no HuggingFace repo on file.`, { status: 400, code: 'NO_REPO_FOR_MODEL' });
+ }
+ const repaired = await Promise.all(required.map((repo) => repairModelCache(repo, { deep })));
+ const deleted = repaired.flatMap((r) => r.deleted.map((name) => ({ repo: r.repoId, name })));
+ res.json({ deep, deleted, repos: required });
+}));
+
// SSE-driven model download. Cancels the python child if the client
// disconnects mid-download; cross-route in-flight dedupe lives in
// startHfDownloadStream so a FLUX repo shared with video gen can't spawn
diff --git a/server/routes/videoGen.integrity.test.js b/server/routes/videoGen.integrity.test.js
new file mode 100644
index 0000000000..79470b9129
--- /dev/null
+++ b/server/routes/videoGen.integrity.test.js
@@ -0,0 +1,114 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+
+// Integrity / repair routes (issue #1324). Mocks mediaModels + hfCache so the
+// thin route glue is exercised in isolation; the real structural/sha256 logic
+// is covered in lib/hfCache.test.js. The remaining mock set mirrors
+// videoGen.test.js so the route's import graph links under vitest.
+
+vi.mock('../lib/mediaModels.js', () => ({
+ repoForModel: vi.fn((m) => `org/${m.id}`),
+ getTextEncoderRepo: vi.fn(() => 'org/text-encoder'),
+ isHfRepoId: vi.fn(() => true),
+}));
+
+vi.mock('../lib/hfCache.js', () => ({
+ inspectModelCache: vi.fn(async () => ({ cached: true, sizeBytes: 100, snapshotPath: '/snap' })),
+ verifyModelCache: vi.fn(async (repoId, opts) => ({
+ repoId, status: 'bad', cached: false, sizeBytes: 0, snapshotPath: '/snap',
+ checkedDeep: !!opts?.deep,
+ files: [{ name: 'model.safetensors', ok: false, reason: 'truncated-data', sizeBytes: 10 }],
+ })),
+ repairModelCache: vi.fn(async (repoId) => ({ repoId, status: 'bad', deleted: ['model.safetensors'] })),
+}));
+
+vi.mock('../services/settings.js', () => ({
+ getSettings: vi.fn(async () => ({ imageGen: { local: { pythonPath: '/usr/bin/python3' } } })),
+}));
+
+vi.mock('../lib/pythonSetup.js', () => ({
+ checkPackages: vi.fn(async () => ({ installed: [], missing: [], missingPip: [] })),
+ isAllowedPython: vi.fn(() => true),
+}));
+
+vi.mock('../services/videoGen/local.js', () => ({
+ listVideoModels: vi.fn(() => [{ id: 'ltx2_unified', name: 'LTX-2 Unified', runtime: 'ltx2' }]),
+ defaultVideoModelId: vi.fn(() => 'ltx2_unified'),
+ loadHistory: vi.fn(async () => []),
+ deleteHistoryItem: vi.fn(),
+ setHistoryItemHidden: vi.fn(),
+ extractLastFrame: vi.fn(),
+ stitchVideos: vi.fn(),
+ upscaleHistoryItem: vi.fn(),
+ DEFAULT_NUM_FRAMES: 121,
+ resolveFflfLtx2PixelBudget: vi.fn(() => 1000),
+ BYOV_VIDEO_RUNTIMES: new Set(['ltx2']),
+ BYOV_RUNTIME_INFO: { ltx2: { id: 'ltx2', label: 'LTX-2 MLX', venvPython: '/tmp/x.py', installEnvVar: 'X', repoUrl: 'x', repoDir: '/tmp' } },
+ isByovRuntimeInstalled: vi.fn(() => false),
+ isByovRuntimeReady: vi.fn(async () => false),
+ invalidateByovReadyCache: vi.fn(),
+}));
+
+vi.mock('../services/mediaJobQueue/index.js', () => ({
+ enqueueJob: vi.fn(() => ({ jobId: 'mock', position: 1, status: 'queued' })),
+ attachSseClient: vi.fn(() => false),
+ cancelJob: vi.fn(async () => ({ ok: true })),
+ listJobs: vi.fn(() => []),
+}));
+
+vi.mock('../lib/multipart.js', () => ({
+ uploadFields: () => (_req, _res, next) => next(),
+}));
+
+vi.mock('../lib/fileUtils.js', () => ({
+ tryReadFile: vi.fn().mockResolvedValue(null),
+ PATHS: { root: '/mock', data: '/mock/data', images: '/mock/images', videos: '/mock/videos', uploads: '/mock/uploads' },
+ ensureDir: vi.fn(async () => {}),
+ resolveGalleryImage: vi.fn((name) => `/mock/images/${name}`),
+}));
+
+vi.mock('fs', () => ({ existsSync: vi.fn(() => true) }));
+vi.mock('fs/promises', () => ({ unlink: vi.fn(async () => {}), copyFile: vi.fn(async () => {}) }));
+
+import videoGenRoutes from './videoGen.js';
+import { verifyModelCache, repairModelCache } from '../lib/hfCache.js';
+
+describe('Video Gen integrity routes', () => {
+ let app;
+ beforeEach(() => {
+ app = express();
+ app.use(express.json());
+ app.use('/api/video-gen', videoGenRoutes);
+ app.use(errorMiddleware);
+ vi.clearAllMocks();
+ });
+
+ it('GET /models/status surfaces integrity for cached models + text encoder', async () => {
+ const res = await request(app).get('/api/video-gen/models/status');
+ expect(res.status).toBe(200);
+ expect(res.body.models[0].integrity.status).toBe('bad');
+ expect(res.body.textEncoder.integrity.status).toBe('bad');
+ });
+
+ it('POST /models/verify deep-scans every model + the encoder', async () => {
+ const res = await request(app).post('/api/video-gen/models/verify').send({ deep: true });
+ expect(res.status).toBe(200);
+ expect(res.body.deep).toBe(true);
+ expect(res.body.models.length).toBeGreaterThanOrEqual(2); // model + encoder
+ expect(verifyModelCache).toHaveBeenCalledWith('org/ltx2_unified', { deep: true });
+ });
+
+ it('POST /models/:id/repair deletes flagged files and reports them', async () => {
+ const res = await request(app).post('/api/video-gen/models/ltx2_unified/repair').send({});
+ expect(res.status).toBe(200);
+ expect(res.body.deleted).toEqual([{ repo: 'org/ltx2_unified', name: 'model.safetensors' }]);
+ expect(repairModelCache).toHaveBeenCalledWith('org/ltx2_unified', { deep: false });
+ });
+
+ it('POST /models/:id/repair 404s for an unknown model', async () => {
+ const res = await request(app).post('/api/video-gen/models/nope/repair').send({});
+ expect(res.status).toBe(404);
+ });
+});
diff --git a/server/routes/videoGen.js b/server/routes/videoGen.js
index bddcd1765c..07539d86d5 100644
--- a/server/routes/videoGen.js
+++ b/server/routes/videoGen.js
@@ -41,7 +41,7 @@ import {
import { enqueueJob, attachSseClient, cancelJob, listJobs } from '../services/mediaJobQueue/index.js';
import { repoForModel, getTextEncoderRepo, isHfRepoId } from '../lib/mediaModels.js';
import { videoLoraFamily } from '../lib/runners.js';
-import { inspectModelCache } from '../lib/hfCache.js';
+import { inspectModelCache, verifyModelCache, repairModelCache } from '../lib/hfCache.js';
import { startHfDownloadStream, openSseStream } from '../lib/sseDownload.js';
const router = Router();
@@ -371,6 +371,34 @@ router.get('/models', (_req, res) => {
res.json(listVideoModels());
});
+// Condense a verifyModelCache() result down to the UI-facing integrity shape:
+// `{ status, badFiles: [{ name, reason }] }`. The full per-file list is kept
+// out of the polled payload — the banner only needs the status + which files
+// to name.
+const summarizeIntegrity = (verify) => {
+ if (!verify) return null;
+ return {
+ status: verify.status,
+ checkedDeep: verify.checkedDeep,
+ badFiles: verify.files.filter((f) => !f.ok).map((f) => ({ name: f.name, reason: f.reason })),
+ };
+};
+
+// Resolve the repo set an integrity scan should cover. A specific `modelId`
+// scopes to that model's repo; no modelId scans every model repo plus the
+// shared text encoder.
+const reposToVerify = (modelId) => {
+ if (modelId) {
+ const m = listVideoModels().find((x) => x.id === modelId);
+ const repo = m ? repoForModel(m) : null;
+ return repo ? [repo] : [];
+ }
+ const repos = listVideoModels().map(repoForModel).filter(Boolean);
+ const enc = getTextEncoderRepo();
+ if (isHfRepoId(enc)) repos.push(enc);
+ return [...new Set(repos)];
+};
+
// Per-model download status — see /api/image-gen/models/status for the
// shape contract. We also surface the active text-encoder repo so the
// video form can warn when the Gemma encoder isn't downloaded yet (a
@@ -381,21 +409,66 @@ router.get('/models/status', asyncHandler(async (_req, res) => {
// surface both the repo-cache status and the resolved local path so the UI
// can distinguish "not downloaded" from "served from LM Studio".
const encoderRepo = getTextEncoderRepo();
- const [models, encoderInspection] = await Promise.all([
+ const [models, encoderInspection, encoderIntegrity] = await Promise.all([
Promise.all(listVideoModels().map(async (m) => {
const repo = repoForModel(m);
- if (!repo) return { id: m.id, repo: null, cached: null, sizeBytes: 0 };
+ if (!repo) return { id: m.id, repo: null, cached: null, sizeBytes: 0, integrity: null };
const { cached, sizeBytes } = await inspectModelCache(repo);
- return { id: m.id, repo, cached, sizeBytes };
+ // Only run the (header-reading) integrity check for repos that are
+ // actually downloaded — a not-yet-cached model gets the Download badge,
+ // not a Repair banner.
+ const integrity = cached ? summarizeIntegrity(await verifyModelCache(repo)) : null;
+ return { id: m.id, repo, cached, sizeBytes, integrity };
})),
isHfRepoId(encoderRepo) ? inspectModelCache(encoderRepo) : Promise.resolve(null),
+ isHfRepoId(encoderRepo) ? verifyModelCache(encoderRepo) : Promise.resolve(null),
]);
const textEncoder = encoderInspection
- ? { repo: encoderRepo, ...encoderInspection }
- : { repo: encoderRepo, cached: true, sizeBytes: 0 };
+ ? { repo: encoderRepo, ...encoderInspection, integrity: encoderInspection.cached ? summarizeIntegrity(encoderIntegrity) : null }
+ : { repo: encoderRepo, cached: true, sizeBytes: 0, integrity: null };
res.json({ models, textEncoder });
}));
+// POST /models/verify — force an integrity re-scan on demand. `deep:true` adds
+// the per-file sha256 comparison (slower; reads every weight byte) on top of
+// the cheap structural check the status poll already runs. With no `modelId`
+// it scans every cached model + the text encoder.
+const verifyBodySchema = z.object({
+ modelId: z.string().min(1).optional(),
+ deep: z.boolean().optional(),
+});
+router.post('/models/verify', asyncHandler(async (req, res) => {
+ const parsed = verifyBodySchema.safeParse(req.body || {});
+ if (!parsed.success) failValidation(parsed);
+ const { modelId, deep = false } = parsed.data;
+ const repos = reposToVerify(modelId);
+ if (modelId && repos.length === 0) {
+ throw new ServerError(`Unknown video model: ${modelId}`, { status: 404, code: 'UNKNOWN_MODEL' });
+ }
+ const results = await Promise.all(repos.map(async (repo) => verifyModelCache(repo, { deep })));
+ res.json({ deep, models: results.map((r) => ({ repo: r.repoId, ...summarizeIntegrity(r) })) });
+}));
+
+// POST /models/:modelId/repair — delete the flagged (corrupt/truncated) weight
+// files for the model's repo(s) so the existing resumable HF fetch path
+// re-downloads them. Returns the deleted-file list; the client then re-triggers
+// the normal `/models/:id/download` SSE stream to pull clean copies with
+// progress. `deep:true` uses the sha256 comparison to decide what's corrupt.
+router.post('/models/:modelId/repair', asyncHandler(async (req, res) => {
+ const model = listVideoModels().find((m) => m.id === req.params.modelId);
+ if (!model) throw new ServerError(`Unknown video model: ${req.params.modelId}`, { status: 404, code: 'UNKNOWN_MODEL' });
+ const parsed = z.object({ deep: z.boolean().optional() }).safeParse(req.body || {});
+ if (!parsed.success) failValidation(parsed);
+ const deep = parsed.data.deep || false;
+ const repos = reposToVerify(model.id);
+ if (repos.length === 0) {
+ throw new ServerError(`Model "${model.id}" has no HuggingFace repo on file.`, { status: 400, code: 'NO_REPO_FOR_MODEL' });
+ }
+ const repaired = await Promise.all(repos.map((repo) => repairModelCache(repo, { deep })));
+ const deleted = repaired.flatMap((r) => r.deleted.map((name) => ({ repo: r.repoId, name })));
+ res.json({ deep, deleted, repos });
+}));
+
router.get('/models/:modelId/download', asyncHandler(async (req, res) => {
const model = listVideoModels().find((m) => m.id === req.params.modelId);
if (!model) throw new ServerError(`Unknown video model: ${req.params.modelId}`, { status: 404 });