Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: eight more findings from claude's second review pass, mostly in the ETag mechanism
[._.]/ Adam Eivyc0720f233599
diff --git a/client/src/services/apiLocalLlm.js b/client/src/services/apiLocalLlm.jsindex 6f8ab494b0..c30eb7fce5 100644--- a/client/src/services/apiLocalLlm.js+++ b/client/src/services/apiLocalLlm.js@@ -153,10 +153,9 @@ export const installLlamaServer = () =>export const upgradeLlamaServer = () =>request('/local-llm/llama-server/upgrade', { method: 'POST' });-// Fetch one speculative-decoding preset's GGUF (role: 'model' | 'draftModel')-// from Hugging Face into the path the launcher passes llama.cpp. Byte progress-// arrives on the `llamaServer:download` socket event, not in this response —-// a multi-GB transfer resolves only when the file is on disk.+// Size/destination/free-disk numbers for the confirm step, before any+// transfer starts. `body.kind` picks which download this previews+// ('spec-decode' | 'mtplx' | 'install') — see localLlmDownloadPreflightSchema.export const previewLocalLlmDownload = (body, options) =>request('/local-llm/download-preflight', {method: 'POST',@@ -164,6 +163,10 @@ export const previewLocalLlmDownload = (body, options) =>...options,});+// Fetch one speculative-decoding preset's GGUF (role: 'model' | 'draftModel')+// from Hugging Face into the path the launcher passes llama.cpp. Byte progress+// arrives on the `llamaServer:download` socket event, not in this response —+// a multi-GB transfer resolves only when the file is on disk.export const downloadSpecDecodeModel = (presetId, role, options) =>request('/local-llm/llama-server/download-model', {method: 'POST',diff --git a/server/lib/downloadPreflight.js b/server/lib/downloadPreflight.jsindex 4ea18421ca..c2f8d488f1 100644--- a/server/lib/downloadPreflight.js+++ b/server/lib/downloadPreflight.js@@ -40,7 +40,7 @@ export const partialPathFor = (destPath) => `${destPath}${PARTIAL_SUFFIX}`;// Sidecar recording the ETag of the object that produced a `.partial`, so a// later resume can send `If-Range` and detect a same-length replacement// object instead of silently splicing its bytes onto our stale prefix.-const etagPathFor = (destPath) => `${partialPathFor(destPath)}.etag`;+export const etagPathFor = (destPath) => `${partialPathFor(destPath)}.etag`;export function normalizeSha256(value) {if (typeof value !== 'string') return null;@@ -60,6 +60,11 @@ const parseContentRangeTotal = (header) => {return match ? Number(match[1]) : 0;};+const parseContentRangeStart = (header) => {+ const match = String(header || '').match(/bytes\s+(\d+)-/i);+ return match ? Number(match[1]) : null;+};+async function freeBytesForPath(destPath, statfsImpl) {let probe = destPath || '/';for (let i = 0; i < 8; i += 1) {@@ -275,31 +280,41 @@ export async function streamResumableDownload({idleTimer.unref?.();};+ // Evict a partial this attempt can no longer trust (the resume point moved+ // or the object changed) and recheck capacity against whatever real total+ // the triggering response reports — the original preflight only reserved+ // the bytes THIS discarded partial was short by, not the full payload a+ // clean restart now needs.+ const evictPartialForRestart = async (expectedBytes) => {+ await rm(tmpPath, { force: true }).catch(() => {});+ await rm(etagPath, { force: true }).catch(() => {});+ resumeFrom = 0;+ delete reqHeaders.Range;+ delete reqHeaders['If-Range'];+ if (expectedBytes > 0) {+ assertDownloadFits(await assessDownloadPreflight({ destPath, expectedBytes }));+ }+ };++ // For a response this attempt can't use AT ALL (416, or a 206 that resumed+ // from the wrong offset) — drop its body and recurse into a fresh request.+ const discardAndRefetch = async (res) => {+ await res.body?.cancel?.().catch(() => {});+ await evictPartialForRestart(parseContentRangeTotal(res.headers?.get?.('content-range')));+ return streamResumableDownload({+ url, destPath, headers, fetchImpl, onBytes, signal, onIdleStall,+ idleStallTimeoutMs, isCancelled, expectedSha256, finalize, onHttpError,+ });+ };+resetIdleTimer();try {const res = await fetchImpl(url, { headers: reqHeaders, redirect: 'follow', signal });if (!res.ok && res.status !== 206) {- if (res.status === 416 && resumeFrom > 0) {- // Partial is past what the server has (or the object changed) —- // start clean. A 416 conventionally reports the real size as- // `Content-Range: bytes */<total>`; recheck capacity against it- // before the restart, same as the Range-ignored (200) branch below —- // the original preflight only reserved the bytes this discarded- // partial was short by, not the full payload the restart now needs.- await rm(tmpPath, { force: true }).catch(() => {});- await rm(etagPath, { force: true }).catch(() => {});- resumeFrom = 0;- delete reqHeaders.Range;- delete reqHeaders['If-Range'];- const totalFromRange = parseContentRangeTotal(res.headers?.get?.('content-range'));- if (totalFromRange > 0) {- assertDownloadFits(await assessDownloadPreflight({ destPath, expectedBytes: totalFromRange }));- }- return streamResumableDownload({- url, destPath, headers, fetchImpl, onBytes, signal, onIdleStall,- idleStallTimeoutMs, isCancelled, expectedSha256, finalize, onHttpError,- });- }+ // Partial is past what the server has (or the object changed) — 416+ // conventionally reports the real size as `Content-Range: bytes+ // */<total>`, which discardAndRefetch uses for its capacity recheck.+ if (res.status === 416 && resumeFrom > 0) return discardAndRefetch(res);if (onHttpError) onHttpError(res);return rejectDownloadStatus(res);}@@ -308,19 +323,19 @@ export async function streamResumableDownload({}// Server ignored Range (or If-Range caught the object changing under us)- // and sent the whole file — discard the leftover prefix. The preflight- // the caller ran before starting only reserved the REMAINING bytes- // (crediting the partial already on disk); now the FULL payload is- // about to land instead, so recheck capacity against this response's- // own Content-Length before writing over the freed space.+ // and sent the whole file in THIS response — no need to re-fetch, just+ // stop treating it as a resume and consume the body already in hand.if (resumeFrom > 0 && res.status === 200) {- await rm(tmpPath, { force: true }).catch(() => {});- await rm(etagPath, { force: true }).catch(() => {});- resumeFrom = 0;- const freshLength = Number(res.headers?.get?.('content-length')) || 0;- if (freshLength > 0) {- assertDownloadFits(await assessDownloadPreflight({ destPath, expectedBytes: freshLength }));- }+ await evictPartialForRestart(Number(res.headers?.get?.('content-length')) || 0);+ }++ // A 206 that resumed from somewhere OTHER than we asked (a proxy that+ // normalizes/ignores the exact offset) would otherwise get appended onto+ // our existing prefix at the wrong point, corrupting the file — this+ // response's body starts at the wrong offset, so it can't be reused.+ if (resumeFrom > 0 && res.status === 206) {+ const rangeStart = parseContentRangeStart(res.headers?.get?.('content-range'));+ if (rangeStart != null && rangeStart !== resumeFrom) return discardAndRefetch(res);}const rangeTotal = parseContentRangeTotal(res.headers?.get?.('content-range'));@@ -333,8 +348,13 @@ export async function streamResumableDownload({// record this response's ETag so a LATER resume of it can send// If-Range. Best-effort: no ETag, or a write failure, just means the// next resume attempt has nothing to validate against (today's behavior).+ // A WEAK etag (`W/"…"`) is explicitly excluded from If-Range use by RFC+ // 9110 §13.1.5 — a conforming origin always treats it as non-matching+ // and answers 200, so saving/sending one would silently turn every+ // resume of this object into a full restart.if (flags === 'w') {- const etag = res.headers?.get?.('etag') || null;+ const rawEtag = res.headers?.get?.('etag') || null;+ const etag = rawEtag && !/^\s*W\//i.test(rawEtag) ? rawEtag : null;if (etag) await writeFile(etagPath, etag).catch(() => {});else await rm(etagPath, { force: true }).catch(() => {});}@@ -356,6 +376,18 @@ export async function streamResumableDownload({throw err;});+ // A body that ends cleanly (no stream error) short of the advertised+ // total is a truncation, not a success — without a published digest to+ // catch it (the HF LoRA path has none), a short file would otherwise be+ // renamed into place and treated as a complete, selectable model. Keep+ // the partial (and its etag) so the next attempt can still resume it.+ if (total > 0 && received !== total) {+ throw new ServerError(+ `Download ended early: got ${received} of ${total} expected bytes for ${destPath}`,+ { status: 502, code: 'DOWNLOAD_TRUNCATED', context: { destPath, received, total } },+ );+ }+const check = await verifyDownloadHash(tmpPath, expectedSha256);if (!check.ok) {await rm(tmpPath, { force: true }).catch(() => {});diff --git a/server/lib/downloadPreflight.test.js b/server/lib/downloadPreflight.test.jsindex e194ccdeb2..abd6a32896 100644--- a/server/lib/downloadPreflight.test.js+++ b/server/lib/downloadPreflight.test.js@@ -366,6 +366,97 @@ describe('streamResumableDownload', () => {expect(secondCallHeaders['If-Range']).toBe('"abc123"');});+ // RFC 9110 §13.1.5 excludes WEAK etags (`W/"…"`) from If-Range use — a+ // conforming origin always evaluates a weak If-Range as non-matching and+ // answers 200, so saving/sending one would turn every resume into a full+ // restart instead of the intended change-detection guard.+ it('never records or sends a weak ETag as If-Range', async () => {+ const destPath = await makeDir();+ await streamResumableDownload({+ url: 'https://example.com/w.gguf',+ destPath,+ finalize: false,+ fetchImpl: async () => ({+ ok: true,+ status: 200,+ headers: { get: (name) => ({ 'content-length': '6', etag: 'W/"abc123"' }[name] || null) },+ body: webBody('gg', 'ufgg'),+ }),+ });+ expect(await readFile(`${partialPathFor(destPath)}.etag`, 'utf8').catch(() => null)).toBeNull();++ await writeFile(partialPathFor(destPath), 'gg');+ let secondCallHeaders;+ await streamResumableDownload({+ url: 'https://example.com/w.gguf',+ destPath,+ fetchImpl: async (_url, opts) => {+ secondCallHeaders = opts.headers;+ return {+ ok: true,+ status: 206,+ headers: { get: (name) => ({ 'content-length': '4', 'content-range': 'bytes 2-5/6' }[name] || null) },+ body: webBody('ufgg'),+ };+ },+ });+ expect(secondCallHeaders['If-Range']).toBeUndefined();+ });++ // A proxy that normalizes/ignores the exact byte offset can answer 206+ // starting somewhere OTHER than requested — appending that onto our+ // existing prefix at `flags: 'a'` would corrupt the file, so this must be+ // treated the same as a Range-ignored 200: discard and restart clean.+ it('discards and restarts when a 206 resumes from the wrong offset', async () => {+ const destPath = await makeDir();+ await writeFile(partialPathFor(destPath), 'gg');+ let callCount = 0;+ const fetchImpl = async (_url, opts) => {+ callCount += 1;+ if (callCount === 1) {+ expect(opts.headers.Range).toBe('bytes=2-');+ return {+ ok: true,+ status: 206,+ // Resumed from byte 0, not the byte 2 we asked for.+ headers: { get: (name) => ({ 'content-length': '6', 'content-range': 'bytes 0-5/6' }[name] || null) },+ body: webBody('ggufgg'),+ };+ }+ expect(opts.headers.Range).toBeUndefined();+ return {+ ok: true,+ status: 200,+ headers: { get: (name) => (name === 'content-length' ? '6' : null) },+ body: webBody('ggufgg'),+ };+ };+ const result = await streamResumableDownload({ url: 'https://example.com/w.gguf', destPath, fetchImpl });+ expect(callCount).toBe(2);+ expect(result.resumed).toBe(false);+ expect(await readFile(destPath, 'utf8')).toBe('ggufgg');+ });++ // A body that ends cleanly (no stream error) short of the advertised total+ // is a truncation — without a published digest to catch it (the HF LoRA+ // path has none), a short file would otherwise be renamed into place and+ // treated as a complete, selectable model.+ it('refuses a cleanly-closed response that fell short of Content-Length', async () => {+ const destPath = await makeDir();+ const fetchImpl = async () => ({+ ok: true,+ status: 200,+ headers: { get: (name) => (name === 'content-length' ? '10' : null) },+ body: webBody('short'), // 5 bytes, advertised 10+ });+ await expect(streamResumableDownload({+ url: 'https://example.com/w.gguf', destPath, fetchImpl,+ })).rejects.toMatchObject({ code: 'DOWNLOAD_TRUNCATED' });+ // Kept for a future resume, exactly like a transport-error partial.+ expect(await readFile(partialPathFor(destPath), 'utf8')).toBe('short');+ expect(await readFile(destPath).catch(() => null)).toBeNull();+ });+// The 416 restart path deletes the partial and recurses with resumeFrom// reset to 0 — the recursive call's own "Range ignored" recheck never// fires (resumeFrom is already 0 there), so without an explicit recheckdiff --git a/server/lib/huggingfaceLora.js b/server/lib/huggingfaceLora.jsindex 06d61e00ef..362946bc55 100644--- a/server/lib/huggingfaceLora.js+++ b/server/lib/huggingfaceLora.js@@ -118,15 +118,24 @@ export const buildHfResolveUrl = (repo, revision, file) =>// Fetch model metadata from the public HF API. Returns the parsed JSON with// `siblings` (file list), `tags`, and `cardData` (carries `base_model`).// fetchImpl is injectable for tests.-export const fetchHuggingfaceModel = async (repo, { token, revision, fetchImpl = fetch, signal } = {}) => {+//+// `expand` (string | string[]) requests extra fields the API omits by+// default — e.g. `usedStorage` (total repo size in bytes), which callers+// that need a real byte count for a WHOLE repo (no single file to HEAD/+// range-probe) can't get any other way. The default call — no `expand` —+// is unaffected: siblings still carry only `rfilename`, and we size-rank+// via the resolve HEAD only if multiple LoRA files tie.+export const fetchHuggingfaceModel = async (repo, { token, revision, fetchImpl = fetch, signal, expand } = {}) => {if (!/^[^/\s]+\/[^/\s]+$/.test(String(repo))) {throw new ServerError(`Invalid HuggingFace repo id: ${repo}`, { status: 400, code: 'HF_BAD_URL' });}- // The `blobs=true` expand isn't needed — siblings carry rfilename, and we- // size-rank via the resolve HEAD only if multiple LoRA files tie.- const url = revision+ const base = revision? `${HF_API}/${repo}/revision/${encodeURIComponent(revision)}`: `${HF_API}/${repo}`;+ const expandFields = expand ? (Array.isArray(expand) ? expand : [expand]) : [];+ const url = expandFields.length+ ? `${base}?${expandFields.map((field) => `expand[]=${encodeURIComponent(field)}`).join('&')}`+ : base;const res = await fetchImpl(url, { headers: { Accept: 'application/json', ...buildHfAuthHeaders(token) }, signal });if (!res.ok) {if (res.status === 404) {diff --git a/server/services/localLlm.js b/server/services/localLlm.jsindex 5e8616ae2d..d0dfafe2ac 100644--- a/server/services/localLlm.js+++ b/server/services/localLlm.js@@ -34,7 +34,7 @@ import { pipeline } from 'stream/promises'import { Readable } from 'stream'import { PATHS, atomicWrite, ensureDir, pathExists, sleep } from '../lib/fileUtils.js'import { ServerError } from '../lib/errorHandler.js'-import { assessDownloadPreflight, assertDownloadFits } from '../lib/downloadPreflight.js'+import { assessDownloadPreflight, diskInsufficientError, DOWNLOAD_VERDICTS } from '../lib/downloadPreflight.js'import { compareSemver } from '../lib/versionUtils.js'import { getCatalog, isBackend, mapModelToBackend, getOllamaImportSpec, catalogSizeBytes } from '../lib/localLlmCatalog.js'import { sanitizeOllamaName } from '../lib/localLlmDisk.js'@@ -933,10 +933,18 @@ export async function previewInstallModel(backend, modelId) {export async function installModel(backend, modelId, onProgress, { force = false } = {}) {if (!isBackend(backend)) return { success: false, error: `Unknown backend: ${backend}` }- assertDownloadFits(await assessDownloadPreflight({+ // Resolve-not-throw: every other failure this function can hit (unknown+ // backend, OLLAMA_OUTDATED, ...) resolves `{ success: false, error }` —+ // migrateBackend's per-model loop is written against that contract with no+ // try/catch of its own, so a throw here would abort the whole migration on+ // model N instead of recording one more `status: 'failed'` row and moving on.+ const preflight = await assessDownloadPreflight({destPath: await localInstallDest(backend),expectedBytes: catalogSizeBytes(backend, modelId),- }))+ })+ if (preflight.verdict === DOWNLOAD_VERDICTS.INSUFFICIENT) {+ return { success: false, error: diskInsufficientError(preflight).message, code: 'DISK_INSUFFICIENT' }+ }if (backend === 'ollama') {const importSpec = getOllamaImportSpec(modelId)const result = importSpecdiff --git a/server/services/localLlm.test.js b/server/services/localLlm.test.jsindex 7101c26cd9..8b8e4ad385 100644--- a/server/services/localLlm.test.js+++ b/server/services/localLlm.test.js@@ -18,6 +18,25 @@ const measured = vi.hoisted(() => ({ ollama: {}, lmstudio: {} }));vi.mock('./localModelAssessmentStore.js', () => ({getMeasuredFits: async (backend) => measured[backend] || {},}));+// Forces assessDownloadPreflight's verdict on its NEXT call only, then+// reverts to real behavior (real statfs) — so a two-model migrateBackend+// test can make model #1's preflight fail without also failing model #2's,+// and the other ~14 installModel/migrateBackend call sites in this file+// that never set `once` are unaffected.+const preflightOverride = vi.hoisted(() => ({ once: null }));+vi.mock('../lib/downloadPreflight.js', async (importOriginal) => {+ const actual = await importOriginal();+ return {+ ...actual,+ assessDownloadPreflight: async (opts) => {+ const real = await actual.assessDownloadPreflight(opts);+ if (!preflightOverride.once) return real;+ const verdict = preflightOverride.once;+ preflightOverride.once = null;+ return { ...real, verdict };+ },+ };+});vi.mock('../lib/fileUtils.js', async () => {const fsMod = await import('fs');return {@@ -136,6 +155,7 @@ const flushMicrotasks = () => new Promise((resolve) => setTimeout(resolve, 0));let svc;beforeEach(async () => {vi.clearAllMocks(); // clears calls, keeps the default impls defined above+ preflightOverride.once = null;// `clearAllMocks` clears recorded CALLS but not queued `…Once` values, and the// provider fan-out is fire-and-forget: a test where it correctly never runs// (a failed pull) leaves its `getAllProviders` answer queued and the NEXT test@@ -316,6 +336,17 @@ describe('localLlm', () => {it('rejects an unknown backend', async () => {expect((await svc.installModel('nope', 'x')).success).toBe(false);});+ // installModel must resolve `{success:false}` for a disk-insufficient+ // preflight, not throw — migrateBackend's per-model loop has no+ // try/catch of its own and is written against that resolve-not-throw+ // contract (matching every other anticipated failure this function+ // already handles, e.g. the "unknown backend" case above).+ it('resolves DISK_INSUFFICIENT rather than throwing', async () => {+ preflightOverride.once = 'insufficient';+ const result = await svc.installModel('ollama', 'llama3.2');+ expect(result).toMatchObject({ success: false, code: 'DISK_INSUFFICIENT' });+ expect(mocks.ollama.pullModel).not.toHaveBeenCalled();+ });it('refreshes Ollama-backed providers after a successful install', async () => {mocks.providers.getAllProviders.mockResolvedValueOnce({providers: [@@ -478,6 +509,24 @@ describe('localLlm', () => {expect(events.at(-1).event).toBe('complete');});+ // A thrown DISK_INSUFFICIENT out of installModel would escape this loop+ // (no try/catch here) and abort the whole migration on whichever model+ // hits it, losing every result gathered for the models before it.+ it('records one model as failed on DISK_INSUFFICIENT and still installs the next one', async () => {+ mocks.lmstudio.getAvailableModels.mockResolvedValueOnce([+ { id: 'lmstudio-community/Llama-3.2-3B-Instruct-GGUF' },+ { id: 'someorg/Totally-Unknown-GGUF' }, // best-effort → ollama bare name+ ]);+ preflightOverride.once = 'insufficient'; // hits the FIRST model's preflight only++ const r = await svc.migrateBackend('ollama');++ expect(r.success).toBe(true); // model #2 still succeeded+ expect(r.results.find((x) => x.target === 'llama3.2')).toMatchObject({ status: 'failed' });+ expect(r.results.find((x) => x.target !== 'llama3.2').status).toBe('installed');+ expect(r.results).toHaveLength(2);+ });+it('returns success with no results when the source backend has no models', async () => {// Target ollama → source lmstudio (empty).mocks.lmstudio.getAvailableModels.mockResolvedValueOnce([]);diff --git a/server/services/loras.js b/server/services/loras.jsindex 69c47b9ec7..6bd6945fa5 100644--- a/server/services/loras.js+++ b/server/services/loras.js@@ -23,6 +23,7 @@ import { ServerError } from '../lib/errorHandler.js';import {assessDownloadPreflight,assertDownloadFits,+ etagPathFor,probeRemoteSize,siblingDownloadMeta,streamResumableDownload,@@ -465,6 +466,12 @@ const downloadToFile = async (url, destPath, { fetchImpl = fetch, headers = {} ,}: undefined,});+ // `finalize: false` means streamResumableDownload never had a chance to+ // clean up its own etag sidecar (that only happens on ITS finalize path).+ // Reaching here means the stream completed successfully — every branch+ // below either moves or deletes tmpPath outright, never leaves it for a+ // future resume, so the sidecar describing it is equally done.+ await rm(etagPathFor(destPath), { force: true }).catch(() => {});if (onProgress) onProgress(lastTick);// Atomic no-clobber finalize: `link` is POSIX-atomic and fails with EEXIST// when destPath already exists (concurrent install that snuck past our@@ -658,12 +665,20 @@ const HF_LORA_FAMILY_VALUES = new Set(HF_LORA_FAMILIES);// generated filename depends only on `repo` + the picked `file`. Preview// therefore never throws HF_UNKNOWN_FAMILY: that check belongs to the actual// install, which needs a concrete family for the sidecar metadata.+// Neither caller threads a cancellation signal into this metadata lookup+// (only the actual byte-stream download gets one) — a stalled-but-reachable+// HF would otherwise hang a preview, or an install, indefinitely on this+// call alone.+const METADATA_FETCH_TIMEOUT_MS = 10_000;+const resolveHfLoraInstallPlan = async (input, { fetchImpl = fetch } = {}) => {const { repo, revision, file: parsedFile } = parseHuggingfaceLoraRef(input?.url);// Stored/env/CLI HF token — only needed for gated repos, but harmless to// send on public ones (HF ignores a bearer it doesn't require).const token = (typeof input?.token === 'string' && input.token.trim()) || (await getHfToken()) || '';- const model = await fetchHuggingfaceModel(repo, { token, revision, fetchImpl });+ const model = await fetchHuggingfaceModel(repo, {+ token, revision, fetchImpl, signal: AbortSignal.timeout(METADATA_FETCH_TIMEOUT_MS),+ });const preferredFile = input?.file || parsedFile || null;const detected = detectHfLoraFamily({ repo, model, file: preferredFile });@@ -707,6 +722,7 @@ const resolveHfLoraInstallPlan = async (input, { fetchImpl = fetch } = {}) => {const probed = await probeRemoteSize(buildHfResolveUrl(repo, revision, file), {headers: buildHfAuthHeaders(token),fetchImpl,+ signal: AbortSignal.timeout(METADATA_FETCH_TIMEOUT_MS),});expectedBytes = probed.bytes;}diff --git a/server/services/loras.test.js b/server/services/loras.test.jsindex 1e658f071b..2d26c10ef1 100644--- a/server/services/loras.test.js+++ b/server/services/loras.test.js@@ -835,7 +835,7 @@ describe('installFromHuggingface', () => {const stream = new ReadableStream({start(c) { c.enqueue(new Uint8Array(validSafetensors())); c.close(); },});- return { ok: true, status: 200, body: stream };+ return { ok: true, status: 200, headers: { get: (name) => (name === 'etag' ? '"lora-etag"' : null) }, body: stream };}throw new Error(`unexpected fetch: ${url}`);};@@ -850,6 +850,10 @@ describe('installFromHuggingface', () => {expect(sidecar.triggerWords).toEqual(['audio reactive']);// The picked file is the canonical diffusers weights, not the README.expect(calls.some((u) => u.includes('/resolve/main/pytorch_lora_weights.safetensors'))).toBe(true);+ // downloadToFile's `finalize: false` means streamResumableDownload never+ // runs its own etag-sidecar cleanup — a successful install must still+ // remove it (nothing left it there for a future resume to use).+ expect(existsSync(join(tmpLoras, `${sidecar.filename}.partial.etag`))).toBe(false);});// HF's model-metadata response never carries per-sibling sizes (thediff --git a/server/services/mtplxModelManager.js b/server/services/mtplxModelManager.jsindex 075485ee93..5470d857d3 100644--- a/server/services/mtplxModelManager.js+++ b/server/services/mtplxModelManager.js@@ -72,7 +72,17 @@ const mtplxCachePath = () => getHfCacheRoot();async function expectedMtplxBytes(repo) {if (!repo) return 0;const token = await getHfToken();- const model = await fetchHuggingfaceModel(repo, { token }).catch(() => null);+ // `usedStorage` (total repo size) is an EXPANDED field — the default model+ // response omits it, same as siblings omitting per-file sizes — and an MTPLX+ // pull grabs the whole repo, so there's no single resolve URL to HEAD/probe+ // the way the other download paths do. A stalled-but-reachable HF gets a+ // real timeout rather than blocking the preflight (and the pull behind it)+ // indefinitely — this call sits in front of the actual download now.+ const model = await fetchHuggingfaceModel(repo, {+ token,+ expand: 'usedStorage',+ signal: AbortSignal.timeout(SEARCH_TIMEOUT_MS),+ }).catch(() => null);return Number(model?.usedStorage) || 0;}diff --git a/server/services/specDecodeModels.js b/server/services/specDecodeModels.jsindex 32b6da1ab7..3474609afa 100644--- a/server/services/specDecodeModels.js+++ b/server/services/specDecodeModels.js@@ -192,14 +192,21 @@ const siblingFor = (model, filename) => {return siblings.find((row) => row?.rfilename === filename) || null;};+// The preview path (previewSpecDecodeDownload) calls this with no signal —+// a real download's own abort chain covers the actual transfer, but a+// metadata/size lookup that just blocks the confirm modal needs its own+// bound, or a stalled-but-reachable HF hangs the preview indefinitely.+const METADATA_FETCH_TIMEOUT_MS = 10_000;+const resolveSpecDownloadPlan = async ({ source, destPath, token, signal }) => {+ const boundedSignal = signal || AbortSignal.timeout(METADATA_FETCH_TIMEOUT_MS);const headers = buildHfAuthHeaders(token);- const model = await fetchHuggingfaceModel(source.repo, { token, signal });+ const model = await fetchHuggingfaceModel(source.repo, { token, signal: boundedSignal });const file = pickGgufSibling(model, { file: source.file, quant: source.quant, repo: source.repo });const url = buildHfResolveUrl(source.repo, 'main', file);let meta = siblingDownloadMeta(siblingFor(model, file));if (!meta.bytes) {- const probed = await probeRemoteSize(url, { headers, signal });+ const probed = await probeRemoteSize(url, { headers, signal: boundedSignal });meta = { bytes: probed.bytes || meta.bytes, sha256: meta.sha256 || probed.sha256 };}const preflight = await assessDownloadPreflight({ destPath, expectedBytes: meta.bytes });