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 findings from claude's third and final review pass
[._.]/ Adam Eivy40b7cdc688a0
diff --git a/client/src/services/apiImageVideo.js b/client/src/services/apiImageVideo.jsindex 83c399a25a..6dd2bc59ba 100644--- a/client/src/services/apiImageVideo.js+++ b/client/src/services/apiImageVideo.js@@ -432,10 +432,13 @@ export const installLoraFromCivitai = ({ url, silent = false } = {}) => request(// `family`/`file` are optional overrides — pass them when the caller already// knows the exact target (a curated video suggestion card) so the previewed-// file matches what the HF install will actually pick.+// file matches what the HF install will actually pick. A curated card+// without one (buildCard's `file: entry.file || null`) must not serialize a+// literal `null` — the route schema's `.optional()` accepts an ABSENT key,+// not `null`.export const previewLoraInstall = ({ url, source = 'civitai', family, file, silent = false } = {}) => request('/loras/install/preflight', {method: 'POST',- body: JSON.stringify({ url, source, family, file }),+ body: JSON.stringify({ url, source, ...(family ? { family } : {}), ...(file ? { file } : {}) }),silent,});diff --git a/client/src/services/apiImageVideo.test.js b/client/src/services/apiImageVideo.test.jsnew file mode 100644index 0000000000..7a523326ee--- /dev/null+++ b/client/src/services/apiImageVideo.test.js@@ -0,0 +1,50 @@+// @vitest-environment node+/**+ * previewLoraInstall's body-serialization boundary — a curated video LoRA+ * card without a `file` (buildCard's `file: entry.file || null`) must not+ * serialize a literal `null`: the route schema's `.optional()` accepts an+ * ABSENT key, not `null`, and JSON.stringify keeps `null` while it drops+ * `undefined`.+ */++import { describe, it, expect, vi, beforeEach } from 'vitest';++vi.mock('./apiCore.js', async (importOriginal) => ({+ ...(await importOriginal()),+ request: vi.fn(),+}));++let request;+let previewLoraInstall;++beforeEach(async () => {+ vi.resetModules();+ ({ request } = await import('./apiCore.js'));+ ({ previewLoraInstall } = await import('./apiImageVideo.js'));+ request.mockReset();+});++describe('previewLoraInstall', () => {+ it('omits family/file from the body when the card carries them as null', async () => {+ request.mockResolvedValue({ verdict: 'ok' });+ await previewLoraInstall({ url: 'https://huggingface.co/org/repo', source: 'huggingface', family: null, file: null });++ const body = JSON.parse(request.mock.calls[0][1].body);+ expect(body).toEqual({ url: 'https://huggingface.co/org/repo', source: 'huggingface' });+ expect(body).not.toHaveProperty('family');+ expect(body).not.toHaveProperty('file');+ });++ it('includes family/file when the caller provides them', async () => {+ request.mockResolvedValue({ verdict: 'ok' });+ await previewLoraInstall({ url: 'https://huggingface.co/org/repo', source: 'huggingface', family: 'ltx-video', file: 'weights.safetensors' });++ const body = JSON.parse(request.mock.calls[0][1].body);+ expect(body).toEqual({+ url: 'https://huggingface.co/org/repo',+ source: 'huggingface',+ family: 'ltx-video',+ file: 'weights.safetensors',+ });+ });+});diff --git a/server/lib/downloadPreflight.js b/server/lib/downloadPreflight.jsindex c2f8d488f1..1ae2cf26ac 100644--- a/server/lib/downloadPreflight.js+++ b/server/lib/downloadPreflight.js@@ -246,7 +246,13 @@ export async function streamResumableDownload({const existing = await stat(tmpPath).catch(() => null);let resumeFrom = existing?.isFile() ? existing.size : 0;- const reqHeaders = { ...headers };+ // Force an uncompressed transport. A proxy/mirror that gzips the response+ // still reports Content-Length for the ENCODED size while the bytes we+ // actually count and write are decoded — the truncation check below (and+ // Range math on a resume) would otherwise compare/offset in the wrong+ // units. Weight files are already-compressed binary blobs, so this costs+ // nothing on an origin that would have sent them uncompressed anyway.+ const reqHeaders = { 'Accept-Encoding': 'identity', ...headers };if (resumeFrom > 0) {reqHeaders.Range = `bytes=${resumeFrom}-`;// Makes the resume conditional on the remote object being UNCHANGEDdiff --git a/server/lib/huggingfaceLora.js b/server/lib/huggingfaceLora.jsindex 362946bc55..70a16dab64 100644--- a/server/lib/huggingfaceLora.js+++ b/server/lib/huggingfaceLora.js@@ -118,24 +118,15 @@ 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.-//-// `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 } = {}) => {+// The `blobs=true` expand isn't needed — siblings carry 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 } = {}) => {if (!/^[^/\s]+\/[^/\s]+$/.test(String(repo))) {throw new ServerError(`Invalid HuggingFace repo id: ${repo}`, { status: 400, code: 'HF_BAD_URL' });}- const base = revision+ const url = 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 d0dfafe2ac..4b68759552 100644--- a/server/services/localLlm.js+++ b/server/services/localLlm.js@@ -913,21 +913,39 @@ async function localInstallDest(backend) {return backend === 'ollama' ? ollamaManager.getModelsDir() : lmStudioManager.getModelsDir()}+// A "Redownload" of a model already on disk transfers little to nothing in+// practice — Ollama's pull re-checks the registry digest and dedupes+// unchanged layers, and LM Studio's own `lms get` skips files already+// present — so sizing it against the FULL catalog size (like a genuine+// net-new install) can refuse a redownload the real transfer would have+// completed in seconds. `expectedBytes: 0` matches this feature's existing+// "can't size it, don't block it" convention for that case.+async function expectedInstallBytes(backend, modelId) {+ const installed = await listModels(backend).catch(() => [])+ if (installed.some((m) => m.id === modelId)) return 0+ return catalogSizeBytes(backend, modelId)+}+export async function previewInstallModel(backend, modelId) {if (!isBackend(backend)) {throw new ServerError(`Unknown backend: ${backend}`, { status: 400 })}const destPath = await localInstallDest(backend)+ const installed = await listModels(backend).catch(() => [])+ const alreadyDownloaded = installed.some((m) => m.id === modelId)// 0 for a free-text/uncurated model id (e.g. a bare Ollama tag the user// typed) — the preflight already treats that as "unknown, never refuse."- const preflight = await assessDownloadPreflight({ destPath, expectedBytes: catalogSizeBytes(backend, modelId) })+ const preflight = await assessDownloadPreflight({+ destPath,+ expectedBytes: alreadyDownloaded ? 0 : catalogSizeBytes(backend, modelId),+ })return {kind: 'install',backend,modelId,...preflight,destPath,- alreadyDownloaded: false,+ alreadyDownloaded,}}@@ -940,7 +958,7 @@ export async function installModel(backend, modelId, onProgress, { force = false// 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),+ expectedBytes: await expectedInstallBytes(backend, modelId),})if (preflight.verdict === DOWNLOAD_VERDICTS.INSUFFICIENT) {return { success: false, error: diskInsufficientError(preflight).message, code: 'DISK_INSUFFICIENT' }diff --git a/server/services/localLlm.test.js b/server/services/localLlm.test.jsindex 8b8e4ad385..7acfdab58d 100644--- a/server/services/localLlm.test.js+++ b/server/services/localLlm.test.js@@ -23,12 +23,13 @@ vi.mock('./localModelAssessmentStore.js', () => ({// 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 }));+const preflightOverride = vi.hoisted(() => ({ once: null, lastCall: null }));vi.mock('../lib/downloadPreflight.js', async (importOriginal) => {const actual = await importOriginal();return {...actual,assessDownloadPreflight: async (opts) => {+ preflightOverride.lastCall = opts;const real = await actual.assessDownloadPreflight(opts);if (!preflightOverride.once) return real;const verdict = preflightOverride.once;@@ -156,6 +157,7 @@ let svc;beforeEach(async () => {vi.clearAllMocks(); // clears calls, keeps the default impls defined abovepreflightOverride.once = null;+ preflightOverride.lastCall = 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@@ -347,6 +349,22 @@ describe('localLlm', () => {expect(result).toMatchObject({ success: false, code: 'DISK_INSUFFICIENT' });expect(mocks.ollama.pullModel).not.toHaveBeenCalled();});+ // A pull of a model already on disk transfers little to nothing (Ollama+ // dedupes unchanged registry layers) — sizing it against the full+ // catalog entry like a genuine net-new install can refuse a+ // "Redownload" the real transfer would finish in seconds.+ it('does not size an already-installed model against its full catalog size', async () => {+ mocks.ollama.getInstalledModels.mockResolvedValueOnce([{ id: 'llama3.2', name: 'llama3.2' }]);+ await svc.installModel('ollama', 'llama3.2', undefined, { force: true });+ expect(preflightOverride.lastCall).toMatchObject({ expectedBytes: 0 });+ expect(mocks.ollama.pullModel).toHaveBeenCalled();+ });+ it('previewInstallModel reports alreadyDownloaded for an installed model', async () => {+ mocks.ollama.getInstalledModels.mockResolvedValueOnce([{ id: 'llama3.2', name: 'llama3.2' }]);+ const preview = await svc.previewInstallModel('ollama', 'llama3.2');+ expect(preview.alreadyDownloaded).toBe(true);+ expect(preview.expectedBytes).toBe(0);+ });it('refreshes Ollama-backed providers after a successful install', async () => {mocks.providers.getAllProviders.mockResolvedValueOnce({providers: [diff --git a/server/services/loras.js b/server/services/loras.jsindex 6bd6945fa5..99b2da462c 100644--- a/server/services/loras.js+++ b/server/services/loras.js@@ -550,7 +550,16 @@ const verifyDownloadedLora = async (destPath, { expectedSha256 = null, source =// Install a LoRA from a Civitai URL. Returns the new sidecar JSON so the// client can render it immediately without a second list round-trip.-const performCivitaiInstall = async (input, { modelId, versionId, fetchImpl }) => {+// Civitai's `type` casing varies in the wild (LORA / Lora / lora) and the+// family includes LoCon / LyCORIS / DoRA / LoHA — all of which load through+// diffusers' lora pipeline. Refuse only true non-LoRA checkpoints.+const ALLOWED_CIVITAI_LORA_TYPES = new Set(['lora', 'locon', 'lycoris', 'dora', 'loha']);++// Shared by performCivitaiInstall and previewCivitaiInstall so a preview can+// never promise a download the install would actually refuse — early-access+// gating, the LoRA-type check, and the missing-downloadUrl guard all throw+// from here now, instead of only guarding the real transfer.+const resolveCivitaiInstallPlan = async (input, { modelId, versionId, fetchImpl }) => {const apiKey = (typeof input?.apiKey === 'string' && input.apiKey.trim()) || (await resolveCivitaiKey());const model = await fetchCivitaiModel(modelId, { apiKey, fetchImpl });const version = pickVersion(model, versionId);@@ -577,11 +586,7 @@ const performCivitaiInstall = async (input, { modelId, versionId, fetchImpl }) ={ status: 422, code: 'CIVITAI_NO_DOWNLOAD' },);}- // Civitai's `type` casing varies in the wild (LORA / Lora / lora) and the- // family includes LoCon / LyCORIS / DoRA / LoHA — all of which load- // through diffusers' lora pipeline. Refuse only true non-LoRA checkpoints.- const ALLOWED_LORA_TYPES = new Set(['lora', 'locon', 'lycoris', 'dora', 'loha']);- if (model?.type && !ALLOWED_LORA_TYPES.has(String(model.type).toLowerCase())) {+ if (model?.type && !ALLOWED_CIVITAI_LORA_TYPES.has(String(model.type).toLowerCase())) {throw new ServerError(`Civitai model "${model.name}" is type "${model.type}", not a LoRA — refusing to install`,{ status: 400, code: 'CIVITAI_NOT_A_LORA' },@@ -595,33 +600,42 @@ const performCivitaiInstall = async (input, { modelId, versionId, fetchImpl }) =const slug = slugifyForFilename(model.name || file.name?.replace(/\.safetensors$/i, ''));const filename = `lora-${slug}-v${version.id}.safetensors`;const destPath = join(PATHS.loras, filename);- if (existsSync(destPath)) {+ const expectedBytes = Number(file.sizeKB) > 0 ? Number(file.sizeKB) * 1024 : 0;++ return { apiKey, model, version, file, filename, destPath, expectedBytes };+};++const performCivitaiInstall = async (input, { modelId, versionId, fetchImpl }) => {+ const plan = await resolveCivitaiInstallPlan(input, { modelId, versionId, fetchImpl });+ if (existsSync(plan.destPath)) {throw new ServerError(- `Already installed: ${filename}. Delete it first or pick a different version.`,+ `Already installed: ${plan.filename}. Delete it first or pick a different version.`,{ status: 409, code: 'CIVITAI_ALREADY_INSTALLED' },);}await ensureDir(PATHS.loras);- const expectedBytes = Number(file.sizeKB) > 0 ? Number(file.sizeKB) * 1024 : 0;- assertDownloadFits(await assessDownloadPreflight({ destPath, expectedBytes }));+ assertDownloadFits(await assessDownloadPreflight({ destPath: plan.destPath, expectedBytes: plan.expectedBytes }));- console.log(`📥 Installing Civitai LoRA: ${model.name} v${version.id} → ${filename} (${file.sizeKB ? Math.round(file.sizeKB / 1024) + ' MB' : 'size unknown'})`);+ console.log(`📥 Installing Civitai LoRA: ${plan.model.name} v${plan.version.id} → ${plan.filename} (${plan.file.sizeKB ? Math.round(plan.file.sizeKB / 1024) + ' MB' : 'size unknown'})`);// Authenticate downloads via `?token=` only — the Authorization header// doesn't survive the 302 to CDN, AND sending both means the token also// ends up in CDN access logs. The metadata fetch (fetchCivitaiModel)// still uses the header since /api/v1/* doesn't redirect.- const tokenized = applyDownloadToken(file.downloadUrl, apiKey);- await downloadToFile(tokenized, destPath, {+ const tokenized = applyDownloadToken(plan.file.downloadUrl, plan.apiKey);+ await downloadToFile(tokenized, plan.destPath, {fetchImpl,headers: { 'User-Agent': 'PortOS/civitai-installer' },- hasApiKey: !!apiKey,+ hasApiKey: !!plan.apiKey,});- await verifyDownloadedLora(destPath, { expectedSha256: file?.hashes?.SHA256 || null, source: 'civitai' });+ await verifyDownloadedLora(plan.destPath, { expectedSha256: plan.file?.hashes?.SHA256 || null, source: 'civitai' });- const sidecar = await withKeyLayout(buildSidecar({ model, version, file, filename }), destPath);- await writeLoraSidecar(filename, sidecar);- console.log(`✅ Installed Civitai LoRA: ${filename} [layout=${sidecar.keyLayout || 'unknown'}]`);+ const sidecar = await withKeyLayout(+ buildSidecar({ model: plan.model, version: plan.version, file: plan.file, filename: plan.filename }),+ plan.destPath,+ );+ await writeLoraSidecar(plan.filename, sidecar);+ console.log(`✅ Installed Civitai LoRA: ${plan.filename} [layout=${sidecar.keyLayout || 'unknown'}]`);return sidecar;};@@ -637,20 +651,13 @@ export const installFromCivitai = async (input, { fetchImpl = fetch } = {}) => {/** Size / dest / free-disk numbers for the LoRA confirm step — no transfer. */export const previewCivitaiInstall = async (input, { fetchImpl = fetch } = {}) => {const { modelId, versionId } = parseCivitaiUrl(input?.url);- const apiKey = (typeof input?.apiKey === 'string' && input.apiKey.trim()) || (await resolveCivitaiKey());- const model = await fetchCivitaiModel(modelId, { apiKey, fetchImpl });- const version = pickVersion(model, versionId);- const file = pickPrimaryFile(version);- const slug = slugifyForFilename(model.name || file.name?.replace(/\.safetensors$/i, ''));- const filename = `lora-${slug}-v${version.id}.safetensors`;- const destPath = join(PATHS.loras, filename);- const expectedBytes = Number(file.sizeKB) > 0 ? Number(file.sizeKB) * 1024 : 0;- const preflight = await assessDownloadPreflight({ destPath, expectedBytes });+ const plan = await resolveCivitaiInstallPlan(input, { modelId, versionId, fetchImpl });+ const preflight = await assessDownloadPreflight({ destPath: plan.destPath, expectedBytes: plan.expectedBytes });return {kind: 'civitai',...preflight,- destPath: filename,- alreadyDownloaded: existsSync(destPath),+ destPath: plan.filename,+ alreadyDownloaded: existsSync(plan.destPath),};};diff --git a/server/services/loras.test.js b/server/services/loras.test.jsindex 2d26c10ef1..8591f8c01f 100644--- a/server/services/loras.test.js+++ b/server/services/loras.test.js@@ -683,6 +683,17 @@ describe('installFromCivitai', () => {).rejects.toThrow(/not a LoRA/);});+ // previewCivitaiInstall shares its filename/guard logic with the real+ // install (resolveCivitaiInstallPlan) — a preview that didn't share it+ // would show a normal confirm dialog (size, destination, enabled Confirm)+ // for a download that could never actually start.+ it('previewCivitaiInstall refuses a non-LoRA model type, same as the real install', async () => {+ const fetchImpl = async () => (mockJsonResponse({ ...FAKE_MODEL, type: 'Checkpoint' }));+ await expect(+ lorasService.previewCivitaiInstall({ url: 'https://civitai.com/models/2600698' }, { fetchImpl }),+ ).rejects.toThrow(/not a LoRA/);+ });+it('accepts LoRA-family types case-insensitively (DoRA, Lora, lycoris)', async () => {// Civitai's `type` casing isn't stable in the wild — DoRA / LoHA / Lora// / lower-case variants are all the same family from diffusers' POV.diff --git a/server/services/mtplxModelManager.js b/server/services/mtplxModelManager.jsindex 5470d857d3..fddb0104f3 100644--- a/server/services/mtplxModelManager.js+++ b/server/services/mtplxModelManager.js@@ -26,11 +26,9 @@ import { ServerError } from '../lib/errorHandler.js';import { assessDownloadPreflight, assertDownloadFits } from '../lib/downloadPreflight.js';import { safeJSONParse } from '../lib/fileUtils.js';import { getHfCacheRoot } from '../lib/hfCache.js';-import { fetchHuggingfaceModel } from '../lib/huggingfaceLora.js';import { listMtplxCachedModels } from '../lib/mtplxModels.js';import { findCommandOnPath } from '../lib/processEnv.js';import { fetchRepoPublishedDates } from './huggingFaceCatalog.js';-import { getHfToken } from './hfToken.js';import { runStreamingCommand } from '../lib/streamingSpawn.js';/** A Hugging Face search is one API call — short, and worth failing fast. */@@ -69,28 +67,22 @@ export const isMtplxRepoId = (value) => typeof value === 'string' && REPO_ID_RE.// the pull actually lands on.const mtplxCachePath = () => getHfCacheRoot();-async function expectedMtplxBytes(repo) {- if (!repo) return 0;- const token = await getHfToken();- // `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;-}+// No reliable byte count exists for what an MTPLX pull actually transfers.+// `usedStorage` (an `expand[]` field fetchHuggingfaceModel can request)+// looks like a fix, but it's the WHOLE repo's total across EVERY format+// variant hosted there — pytorch + tf + jax + tflite + onnx + safetensors,+// etc. — not just what MTPLX downloads, and a multi-format repo can+// over-report by 2-3x. Refusing a valid pull over files it WON'T fetch is+// worse than the status quo, so expectedBytes stays 0 (never refuse when+// the size is unknown) rather than trading an under-protective gap for an+// over-refusing one.+const UNKNOWN_MTPLX_BYTES = 0;export async function previewMtplxPull({ model = null } = {}) {const repo = model ? requireRepoId(model) : null;const preflight = await assessDownloadPreflight({destPath: mtplxCachePath(),- expectedBytes: await expectedMtplxBytes(repo),+ expectedBytes: UNKNOWN_MTPLX_BYTES,});return { kind: 'mtplx', ...preflight, destPath: repo || 'MTPLX cache', alreadyDownloaded: false };}@@ -219,7 +211,7 @@ export async function pullMtplxModel({ model = null, onProgress = () => {} } = {const label = repo || 'MTPLX\'s default verified checkpoint';assertDownloadFits(await assessDownloadPreflight({destPath: mtplxCachePath(),- expectedBytes: await expectedMtplxBytes(repo),+ expectedBytes: UNKNOWN_MTPLX_BYTES,}));onProgress({ event: 'start', model: repo, message: `Downloading ${label}. This is a multi-gigabyte download and can take a while.` });diff --git a/server/services/ollamaManager.js b/server/services/ollamaManager.jsindex d9673c91d8..0a038b61f9 100644--- a/server/services/ollamaManager.js+++ b/server/services/ollamaManager.js@@ -38,6 +38,7 @@ import {} from '../lib/ollamaContext.js'import { compareSemver } from '../lib/versionUtils.js'import { isSafeHfRepoRelativePath } from '../lib/hfCache.js'+import { assessDownloadPreflight, diskInsufficientError, DOWNLOAD_VERDICTS } from '../lib/downloadPreflight.js'const execFileAsync = promisify(execFile)const AVAILABILITY_CACHE_TTL_MS = 30_000@@ -1441,9 +1442,24 @@ async function importModelFromHfSafetensors(spec, onProgress) {return { success: false, error: `The ${subdir} checkpoint is incomplete or unavailable on Hugging Face.`, modelId }}+ // This import writes the checkpoint TWICE — once staged under `tmpdir()`,+ // once more when `ollama create` below lands it in the models dir — on+ // volumes that can differ (a temp partition, or OLLAMA_MODELS pointed at+ // external storage). The outer installModel() preflight only checked one+ // copy against one of those volumes using a catalog-string size estimate;+ // this uses the real per-file bytes this import already fetched from HF.+ const total = files.reduce((sum, file) => sum + file.size, 0)+ const stagingPreflight = await assessDownloadPreflight({ destPath: tmpdir(), expectedBytes: total })+ if (stagingPreflight.verdict === DOWNLOAD_VERDICTS.INSUFFICIENT) {+ return { success: false, error: diskInsufficientError(stagingPreflight).message, modelId, code: 'DISK_INSUFFICIENT' }+ }+ const modelsDirPreflight = await assessDownloadPreflight({ destPath: getModelsDir(), expectedBytes: total })+ if (modelsDirPreflight.verdict === DOWNLOAD_VERDICTS.INSUFFICIENT) {+ return { success: false, error: diskInsufficientError(modelsDirPreflight).message, modelId, code: 'DISK_INSUFFICIENT' }+ }+const tempRoot = await mkdtemp(join(tmpdir(), 'portos-ollama-hf-import-'))const modelDir = join(tempRoot, 'model')- const total = files.reduce((sum, file) => sum + file.size, 0)let completed = 0let lastPercent = -1const reportBytes = (bytes) => {diff --git a/server/services/ollamaManager.test.js b/server/services/ollamaManager.test.jsindex 2b84a89837..d3d99163c8 100644--- a/server/services/ollamaManager.test.js+++ b/server/services/ollamaManager.test.js@@ -700,6 +700,37 @@ describe('ollamaManager curated Hugging Face Safetensors import', () => {expect(globalThis.fetch).toHaveBeenCalledTimes(2) // availability + installed-version probes only})+ // This import writes the checkpoint TWICE — staged under a temp dir, then+ // again when `ollama create` lands it in the models dir — so a disk+ // refusal must happen BEFORE either copy starts, using the real per-file+ // bytes this import already fetched from HF (not a coarse catalog+ // estimate the caller passed in, which the outer installModel() preflight+ // already checked separately).+ it('refuses before downloading or creating when the real checkpoint size will not fit', async () => {+ hfTokenMock.token = 'hf_example_token'+ vi.stubGlobal('fetch', vi.fn(async (url) => {+ const href = String(url)+ if (href.endsWith('/api/version')) return versionResponse()+ if (href.includes('/api/models/example/Qwen-MLX')) {+ return new Response(JSON.stringify({ siblings: [+ { rfilename: '4-bit/config.json', size: 10 },+ // No real disk holds this many bytes.+ { rfilename: '4-bit/model.safetensors', lfs: { size: Number.MAX_SAFE_INTEGER } }+ ] }), { status: 200, headers: { 'Content-Type': 'application/json' } })+ }+ throw new Error(`unexpected fetch: ${href} — the size refusal should have happened first`)+ }))+ execMock.impl = (cmd, args, _opts, cb) => {+ if (cmd === 'ollama' && args.join(' ') === '--version') return cb(null, { stdout: 'ollama 0.31.0', stderr: '' })+ throw new Error(`unexpected exec: ${cmd} ${args.join(' ')} — the size refusal should have happened first`)+ }+ const { importModelFromHfSafetensors } = await loadManager()++ const result = await importModelFromHfSafetensors(spec)++ expect(result).toMatchObject({ success: false, code: 'DISK_INSUFFICIENT' })+ })+it('requires an Ollama release with Safetensors create support', async () => {vi.stubGlobal('fetch', vi.fn(async (url) => {if (String(url).endsWith('/api/version')) {