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

address review (codex): force re-download after repair so a deleted shard isn't skipped

[._.]/ Adam Eivy4058c7126aa3
diff --git a/client/src/hooks/useModelDownloadStatus.js b/client/src/hooks/useModelDownloadStatus.js
index 7b2f63be62..5c3bcb5f6d 100644
--- a/client/src/hooks/useModelDownloadStatus.js
+++ b/client/src/hooks/useModelDownloadStatus.js
@@ -13,12 +13,17 @@ import {
// callers and the hook agree on the magic string.
export const TEXT_ENCODER_DOWNLOAD_ID = '__text_encoder__';
-const buildDownloadUrl = (kind, modelId) => {
+const buildDownloadUrl = (kind, modelId, force = false) => {
if (!modelId) return null;
+ // A repair-initiated re-download appends `?force=1` so the server re-fetches
+ // even when the repo still looks cached — repairModelCache() deleted the bad
+ // file(s), but a multi-shard repo's surviving shards otherwise mask the gap
+ // and the deleted shard would never be pulled back.
+ const q = force ? '?force=1' : '';
if (kind === 'video' && modelId === TEXT_ENCODER_DOWNLOAD_ID) {
- return '/api/video-gen/text-encoder/download';
+ return `/api/video-gen/text-encoder/download${q}`;
}
- return `/api/${kind}-gen/models/${encodeURIComponent(modelId)}/download`;
+ return `/api/${kind}-gen/models/${encodeURIComponent(modelId)}/download${q}`;
};
// Model download-status hook. Drives the inline "Available · 7.8 GB" /
@@ -33,6 +38,9 @@ export function useModelDownloadStatus({ kind = 'image' } = {}) {
const [extra, setExtra] = useState({}); // video: { textEncoder: {...} }
const [loading, setLoading] = useState(false);
const [activeModelId, setActiveModelId] = useState(null);
+ // True only for a repair-initiated re-download — appends `?force=1` so the
+ // server re-fetches a repo whose surviving shards still read as cached.
+ const [forceDownload, setForceDownload] = useState(false);
const fetchStatuses = useCallback(async () => {
setLoading(true);
@@ -57,7 +65,7 @@ export function useModelDownloadStatus({ kind = 'image' } = {}) {
// EventSource for the active download. `null` URL = idle (useSseProgress's
// `enabled: false` cleanup tears the connection down on cancel).
- const downloadUrl = buildDownloadUrl(kind, activeModelId);
+ const downloadUrl = buildDownloadUrl(kind, activeModelId, forceDownload);
const sse = useSseProgress(downloadUrl, { enabled: !!downloadUrl });
// Refetch on natural stream close. useSseProgress flips `closed:true` once
@@ -74,10 +82,12 @@ export function useModelDownloadStatus({ kind = 'image' } = {}) {
}
fetchStatuses();
setActiveModelId(null);
+ setForceDownload(false);
}
}, [sse.closed, sse.latest, fetchStatuses]);
- const start = useCallback((modelId) => {
+ const start = useCallback((modelId, { force = false } = {}) => {
+ setForceDownload(force);
setActiveModelId(modelId);
}, []);
@@ -117,7 +127,10 @@ export function useModelDownloadStatus({ kind = 'image' } = {}) {
return null;
});
setRepairing(false);
- if (result) start(modelId); // re-download clean copies via the existing SSE
+ // Force the re-download: repair deleted the bad file(s), but a multi-shard
+ // repo's surviving shards keep it reading as cached, so a non-forced pull
+ // would skip the deleted shard.
+ if (result) start(modelId, { force: true });
return result;
}, [kind, start]);
@@ -129,6 +142,7 @@ export function useModelDownloadStatus({ kind = 'image' } = {}) {
const cancel = useCallback(() => {
sse.close();
setActiveModelId(null);
+ setForceDownload(false);
fetchStatuses();
}, [sse, fetchStatuses]);
diff --git a/server/lib/sseDownload.js b/server/lib/sseDownload.js
index ec12b14b67..257a406fc9 100644
--- a/server/lib/sseDownload.js
+++ b/server/lib/sseDownload.js
@@ -34,7 +34,7 @@ export function openSseStream(res) {
return { send, safeEnd };
}
-export async function startHfDownloadStream({ req, res, repo, repos, alreadyDownloadedMessage }) {
+export async function startHfDownloadStream({ req, res, repo, repos, alreadyDownloadedMessage, force = false }) {
// Caller passes either `repo` (single string, legacy callers) OR `repos`
// (ordered array, used when a model has auxiliary repos that must be
// present alongside the main weights — e.g. HiDream's separate Llama-3.1
@@ -68,7 +68,13 @@ export async function startHfDownloadStream({ req, res, repo, repos, alreadyDown
if (aborted) return;
const existing = await inspectModelCache(r);
if (aborted) return;
- if (existing.cached) {
+ // `force` is set by a repair-initiated re-download: repairModelCache()
+ // deleted the corrupt file(s), but for a multi-shard repo the remaining
+ // shards still make inspectModelCache() report `cached` — so skipping here
+ // would leave the just-deleted shard missing and never re-fetched. Forcing
+ // re-runs the HF fetch, which is a cheap no-op for files already present
+ // (etag match) and pulls only what's gone.
+ if (existing.cached && !force) {
totalSize += existing.sizeBytes || 0;
send({ type: 'log', message: `${r} already cached (${existing.sizeBytes} bytes).`, repo: r, sizeBytes: existing.sizeBytes });
continue;
diff --git a/server/lib/sseDownload.test.js b/server/lib/sseDownload.test.js
new file mode 100644
index 0000000000..9111923e87
--- /dev/null
+++ b/server/lib/sseDownload.test.js
@@ -0,0 +1,64 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// startHfDownloadStream's cache short-circuit (`if (existing.cached) continue`)
+// must be bypassable via `force` — otherwise a repair that deleted one shard of
+// a multi-file repo (leaving the rest cached) would skip the re-download and
+// never pull the deleted shard back. Mock the IO-bound cache inspect + HF fetch
+// so the pure stream-control logic is exercised in isolation.
+
+vi.mock('./hfCache.js', () => ({
+ inspectModelCache: vi.fn(async () => ({ cached: true, sizeBytes: 100, snapshotPath: '/snap' })),
+}));
+
+vi.mock('./hfDownload.js', () => ({
+ downloadHfRepo: vi.fn(() => ({ promise: Promise.resolve(), kill: vi.fn() })),
+}));
+
+import { startHfDownloadStream } from './sseDownload.js';
+import { inspectModelCache } from './hfCache.js';
+import { downloadHfRepo } from './hfDownload.js';
+
+// Minimal req/res doubles — req only needs `.on('close')`; res captures the
+// SSE frames written so we can assert the terminal `complete` message.
+const makeReqRes = () => {
+ const frames = [];
+ const req = { on: vi.fn() };
+ const res = {
+ writableEnded: false,
+ writeHead: vi.fn(),
+ write: vi.fn((chunk) => { frames.push(chunk); }),
+ end: vi.fn(function end() { res.writableEnded = true; }),
+ };
+ return { req, res, frames };
+};
+
+const parseFrames = (frames) => frames
+ .map((f) => f.replace(/^data: /, '').trim())
+ .filter(Boolean)
+ .map((f) => JSON.parse(f));
+
+describe('startHfDownloadStream force', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ inspectModelCache.mockResolvedValue({ cached: true, sizeBytes: 100, snapshotPath: '/snap' });
+ });
+
+ it('skips the HF fetch for a cached repo when force is unset (Download button)', async () => {
+ const { req, res, frames } = makeReqRes();
+ await startHfDownloadStream({ req, res, repo: 'org/encoder' });
+ expect(downloadHfRepo).not.toHaveBeenCalled();
+ const events = parseFrames(frames);
+ expect(events.some((e) => e.type === 'log' && /already cached/.test(e.message))).toBe(true);
+ expect(events.at(-1)).toMatchObject({ type: 'complete' });
+ });
+
+ it('re-fetches a cached repo when force is set (repair re-download)', async () => {
+ const { req, res, frames } = makeReqRes();
+ await startHfDownloadStream({ req, res, repo: 'org/encoder', force: true });
+ // The whole point of the fix: a still-cached repo (surviving shards) is
+ // re-downloaded instead of skipped, so a deleted shard is pulled back.
+ expect(downloadHfRepo).toHaveBeenCalledWith(expect.objectContaining({ repo: 'org/encoder' }));
+ const events = parseFrames(frames);
+ expect(events.at(-1)).toMatchObject({ type: 'complete', message: 'org/encoder downloaded.' });
+ });
+});
diff --git a/server/routes/imageGen.js b/server/routes/imageGen.js
index 3fa84302c9..ca3ee24631 100644
--- a/server/routes/imageGen.js
+++ b/server/routes/imageGen.js
@@ -504,8 +504,9 @@ router.get('/models/:modelId/download', asyncHandler(async (req, res) => {
}
// Sequentially fetch every required repo (main + aux text encoders for
// HiDream). The SSE stream tags each event with `repo` so the client can
- // show per-repo progress / log lines.
- await startHfDownloadStream({ req, res, repos });
+ // show per-repo progress / log lines. `?force=1` (repair-initiated) re-fetches
+ // even when the repo still looks cached, so a deleted shard isn't skipped.
+ await startHfDownloadStream({ req, res, repos, force: req.query.force === '1' });
}));
router.get('/loras', asyncHandler(async (_req, res) => {
diff --git a/server/routes/videoGen.js b/server/routes/videoGen.js
index 03b816290e..9d76ad1355 100644
--- a/server/routes/videoGen.js
+++ b/server/routes/videoGen.js
@@ -475,7 +475,7 @@ router.get('/models/:modelId/download', asyncHandler(async (req, res) => {
if (!model) throw new ServerError(`Unknown video model: ${req.params.modelId}`, { status: 404 });
const repo = repoForModel(model);
if (!repo) throw new ServerError(`Model "${model.id}" has no HuggingFace repo on file.`, { status: 400, code: 'NO_REPO_FOR_MODEL' });
- await startHfDownloadStream({ req, res, repo });
+ await startHfDownloadStream({ req, res, repo, force: req.query.force === '1' });
}));
// POST /text-encoder/repair — delete the flagged (corrupt/truncated) weight
@@ -506,7 +506,10 @@ router.get('/text-encoder/download', asyncHandler(async (req, res) => {
if (!isHfRepoId(repo)) {
throw new ServerError('Active text encoder is a local-path entry, not an HF repo.', { status: 400, code: 'NOT_DOWNLOADABLE' });
}
- await startHfDownloadStream({ req, res, repo });
+ // `?force=1` (sent by the repair-initiated re-download) re-fetches even when
+ // the repo still looks cached — a deleted shard from a multi-file encoder
+ // would otherwise be skipped.
+ await startHfDownloadStream({ req, res, repo, force: req.query.force === '1' });
}));
router.post('/', frameImageUpload, asyncHandler(async (req, res) => {