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

refactor([issue-1324]): reuse sha256File, share integrity-summary helpers, drop redundant walks

[._.]/ Adam Eivy1b059824b3c2
diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsx
index 64ea6297f0..743f974150 100644
--- a/client/src/pages/VideoGen.jsx
+++ b/client/src/pages/VideoGen.jsx
@@ -880,6 +880,7 @@ export default function VideoGen() {
// 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 integrityBadCount = integrityBad ? (modelIntegrity.badFiles || []).length : 0;
const integrityKey = integrityBad ? `${modelId}:${(modelIntegrity.badFiles || []).map((f) => f.name).join(',')}` : null;
const [dismissedIntegrityKey, setDismissedIntegrityKey] = useState(null);
const showIntegrityBanner = integrityBad && dismissedIntegrityKey !== integrityKey && !modelDownload.downloading;
@@ -1419,8 +1420,8 @@ export default function VideoGen() {
<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.
+ <strong className="font-semibold">{currentModel?.name || modelId}</strong> has {integrityBadCount || 'corrupt'} damaged weight file{integrityBadCount === 1 ? '' : 's'} — renders may come out garbled.
+ Repair deletes the bad file{integrityBadCount === 1 ? '' : 's'} and re-downloads clean copies.
</div>
</div>
<div className="flex items-center gap-2 self-start sm:self-auto">
diff --git a/server/lib/hfCache.js b/server/lib/hfCache.js
index 2e3456d983..cc5f025b2f 100644
--- a/server/lib/hfCache.js
+++ b/server/lib/hfCache.js
@@ -20,10 +20,10 @@
// route — which inspects every registered model — doesn't block the Node
// event loop while walking large snapshot directories.
-import { promises as fs, createReadStream } from 'node:fs';
+import { promises as fs } from 'node:fs';
import { homedir } from 'node:os';
import { join, dirname, resolve as resolvePath } from 'node:path';
-import { createHash } from 'node:crypto';
+import { sha256File } from './fileUtils.js';
// HF cache root resolution mirrors huggingface_hub's own precedence:
// HF_HUB_CACHE > HF_HOME/hub > $XDG_CACHE_HOME/huggingface/hub
@@ -214,24 +214,15 @@ async function expectedBlobSha256(path) {
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.
+// structural check. The returned entry keeps the resolved `path` so the repair
+// path can delete the file without re-walking the snapshot.
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 };
+ if (!stat) return { name: file.name, path: file.path, ok: false, reason: 'missing-blob', sizeBytes: 0 };
+ if (stat.size === 0) return { name: file.name, path: file.path, ok: false, reason: 'empty', sizeBytes: 0 };
- const entry = { name: file.name, ok: true, reason: 'size-only', sizeBytes: stat.size };
+ const entry = { name: file.name, path: file.path, ok: true, reason: 'size-only', sizeBytes: stat.size };
if (file.name.endsWith('.safetensors')) {
const structural = await verifySafetensorsStructure(file.path, stat.size);
if (!structural.ok) {
@@ -242,7 +233,7 @@ async function verifyWeightFile(file, { deep }) {
if (deep) {
const expectedSha = await expectedBlobSha256(file.path);
if (expectedSha) {
- const actualSha = await sha256OfFile(file.path).catch(() => null);
+ const actualSha = await sha256File(file.path).catch(() => null);
if (actualSha && actualSha !== expectedSha) {
return { ...entry, ok: false, reason: 'sha256-mismatch' };
}
@@ -303,25 +294,47 @@ export async function repairModelCache(repoId, { deep = false } = {}) {
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);
+ for (const file of verify.files.filter((f) => !f.ok)) {
+ const lst = await fs.lstat(file.path).catch(() => null);
if (lst?.isSymbolicLink()) {
- const target = await fs.readlink(path).catch(() => null);
+ const target = await fs.readlink(file.path).catch(() => null);
if (target) {
- const blobPath = resolvePath(dirname(path), target);
+ const blobPath = resolvePath(dirname(file.path), target);
await fs.unlink(blobPath).catch(() => {});
}
}
- await fs.unlink(path).catch(() => {});
- deleted.push(name);
+ await fs.unlink(file.path).catch(() => {});
+ deleted.push(file.name);
}
return { repoId, status: 'bad', deleted };
}
+
+// Condense a verifyModelCache() result to the UI-facing shape `{ status,
+// checkedDeep, badFiles: [{ name, reason }] }`. Drops the internal file paths
+// and per-tensor details — the banner only needs which files are bad and why.
+// Single-repo form, used for video models + the text encoder.
+export function summarizeVerify(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 })),
+ };
+}
+
+// Multi-repo condensation for models with a primary + aux repos (image gen):
+// 'bad' wins over 'ok' wins over 'missing' so a corrupt aux encoder still
+// reports bad, and each bad file carries its repo so the UI can name it.
+export function aggregateVerifies(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';
+ return {
+ status,
+ checkedDeep: list.every((v) => v.checkedDeep),
+ badFiles: list.flatMap((v) => v.files.filter((f) => !f.ok).map((f) => ({ repo: v.repoId, name: f.name, reason: f.reason }))),
+ };
+}
diff --git a/server/routes/imageGen.integrity.test.js b/server/routes/imageGen.integrity.test.js
index e1950a938f..2657db2f84 100644
--- a/server/routes/imageGen.integrity.test.js
+++ b/server/routes/imageGen.integrity.test.js
@@ -16,12 +16,15 @@ vi.mock('../lib/mediaModels.js', () => ({
requiredReposForModel: vi.fn((m) => [`org/${m.id}`]),
}));
-vi.mock('../lib/hfCache.js', () => ({
+// Keep the real pure helpers (summarizeVerify/aggregateVerifies); only stub the
+// IO-bound inspect/verify/repair so we don't touch a real HF cache.
+vi.mock('../lib/hfCache.js', async (importOriginal) => ({
+ ...(await importOriginal()),
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 }],
+ files: [{ name: 'model.safetensors', path: '/snap/model.safetensors', ok: false, reason: 'truncated-data', sizeBytes: 10 }],
})),
repairModelCache: vi.fn(async (repoId) => ({ repoId, status: 'bad', deleted: ['model.safetensors'] })),
}));
diff --git a/server/routes/imageGen.js b/server/routes/imageGen.js
index e530d6da27..c0a20cdb9c 100644
--- a/server/routes/imageGen.js
+++ b/server/routes/imageGen.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, verifyModelCache, repairModelCache } from '../lib/hfCache.js';
+import { inspectModelCache, verifyModelCache, repairModelCache, aggregateVerifies } from '../lib/hfCache.js';
import { startHfDownloadStream, openSseStream } from '../lib/sseDownload.js';
import {
REQUIRED_PACKAGES, detectPython, installPackages,
@@ -378,25 +378,12 @@ router.get('/models/status', asyncHandler(async (_req, res) => {
// 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;
+ const integrity = cached ? aggregateVerifies(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.
@@ -415,7 +402,7 @@ router.post('/models/verify', asyncHandler(async (req, res) => {
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: [] }) };
+ return { id: m.id, ...(aggregateVerifies(verifies) || { status: 'missing', badFiles: [] }) };
}));
res.json({ deep, models: results });
}));
diff --git a/server/routes/videoGen.integrity.test.js b/server/routes/videoGen.integrity.test.js
index 79470b9129..1bf17b70e6 100644
--- a/server/routes/videoGen.integrity.test.js
+++ b/server/routes/videoGen.integrity.test.js
@@ -14,12 +14,15 @@ vi.mock('../lib/mediaModels.js', () => ({
isHfRepoId: vi.fn(() => true),
}));
-vi.mock('../lib/hfCache.js', () => ({
+// Keep the real pure helpers (summarizeVerify/aggregateVerifies); only stub the
+// IO-bound inspect/verify/repair so we don't touch a real HF cache.
+vi.mock('../lib/hfCache.js', async (importOriginal) => ({
+ ...(await importOriginal()),
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 }],
+ files: [{ name: 'model.safetensors', path: '/snap/model.safetensors', ok: false, reason: 'truncated-data', sizeBytes: 10 }],
})),
repairModelCache: vi.fn(async (repoId) => ({ repoId, status: 'bad', deleted: ['model.safetensors'] })),
}));
diff --git a/server/routes/videoGen.js b/server/routes/videoGen.js
index 07539d86d5..4c02e755ea 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, verifyModelCache, repairModelCache } from '../lib/hfCache.js';
+import { inspectModelCache, verifyModelCache, repairModelCache, summarizeVerify } from '../lib/hfCache.js';
import { startHfDownloadStream, openSseStream } from '../lib/sseDownload.js';
const router = Router();
@@ -371,19 +371,6 @@ 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.
@@ -409,7 +396,7 @@ 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, encoderIntegrity] = await Promise.all([
+ const [models, textEncoder] = 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, integrity: null };
@@ -417,15 +404,16 @@ router.get('/models/status', asyncHandler(async (_req, res) => {
// 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;
+ const integrity = cached ? summarizeVerify(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),
+ (async () => {
+ if (!isHfRepoId(encoderRepo)) return { repo: encoderRepo, cached: true, sizeBytes: 0, integrity: null };
+ const enc = await inspectModelCache(encoderRepo);
+ const integrity = enc.cached ? summarizeVerify(await verifyModelCache(encoderRepo)) : null;
+ return { repo: encoderRepo, ...enc, integrity };
+ })(),
]);
- const textEncoder = encoderInspection
- ? { repo: encoderRepo, ...encoderInspection, integrity: encoderInspection.cached ? summarizeIntegrity(encoderIntegrity) : null }
- : { repo: encoderRepo, cached: true, sizeBytes: 0, integrity: null };
res.json({ models, textEncoder });
}));
@@ -446,7 +434,7 @@ router.post('/models/verify', asyncHandler(async (req, res) => {
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) })) });
+ res.json({ deep, models: results.map((r) => ({ repo: r.repoId, ...summarizeVerify(r) })) });
}));
// POST /models/:modelId/repair — delete the flagged (corrupt/truncated) weight