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: finish an Ollama HF pull that died on "context deadline exceeded" at 100%
[._.]/ Adam Eivy5b2780bf16d5
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 7db539626e..42df380844 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -4,6 +4,10 @@- **[issue-3168] Music Video projects now have a Concept and Visual style field.** Set them before clicking "AI Plan" to steer the proposed scenes toward a story or theme, and every generated frame and shot prompt now carries your chosen visual style automatically.+## Local LLM installs++- **A large Hugging Face model that failed with "context deadline exceeded" at 100% now finishes installing.** Ollama downloads the multi-gigabyte weights first and fetches the model's tiny metadata blob last; when Hugging Face's CDN takes a minute to serve that few-hundred-byte file, Ollama's internal request deadline expires and it abandons the install without writing the manifest — so tens of gigabytes of verified weights sit on disk and the model looks like it was never installed, and every retry loses the same race. PortOS now recognizes that specific failure and completes the install itself: it re-fetches the manifest and any missing *small* metadata blobs with a generous timeout, verifies every blob's SHA-256 against the manifest, clears leftover partial files, and only then writes the manifest. A missing multi-gigabyte layer, an unknown blob size, or a checksum mismatch is refused instead of papered over, so a genuinely incomplete download still reports as failed. The progress banner now says "finishing install from downloaded files…" instead of sitting at 100%.+## Usage cost reporting- **[issue-3156] Historical usage estimates can now be reconciled against provider transcripts.** The Usage page offers an explicit, progress-reporting repair that matches transcripts only to PortOS run windows, preserves configured provider IDs, replaces each old estimate once, and rebuilds corrected totals without inventing legacy cost.diff --git a/server/lib/README.md b/server/lib/README.mdindex 0c547c7144..1d530311dc 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -232,7 +232,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `huggingfaceLora.js` | HuggingFace LoRA import helpers: parse HF ref → `{repo,revision}`, fetch `/api/models` metadata, pick the `.safetensors`, detect the video-LoRA family (`ltx-video`), build the sidecar + `resolve` download URL. The HF analogue of `civitai.js` for video LoRAs. Pure. || `huggingfaceModel.js` | HuggingFace base-model (image/video) classifier for the self-service "add a model" flow (#2124): inspect repo siblings + card → decide the loadable runtime/runner, STRICTLY refuse GGUF-only / wan / hunyuan / unclassifiable repos (so a bad add can't wedge the picker), build the `media-models.json` entry (`source:'user'`), + a `searchHuggingfaceModels` Hub-search helper. Pure. || `localLlmCatalog.js` | Curated cross-backend (Ollama↔LM Studio) local-LLM catalog + install-id mapping for the migrate flow. Pure. |-| `localLlmDisk.js` | Pure on-disk reasoning for the migrate "copy GGUF locally instead of re-downloading" fast-path (Ollama manifest/blob parsing, LM Studio path layout, MLX/projector/shard detection). |+| `localLlmDisk.js` | Pure on-disk reasoning for the migrate "copy GGUF locally instead of re-downloading" fast-path (Ollama manifest/blob parsing, LM Studio path layout, MLX/projector/shard detection) plus the Hugging Face registry addressing used to finish an abandoned Ollama pull. || `localModelHeuristics.js` | Capability heuristics for untyped local (Ollama/LM Studio) models. `isEmbeddingModel`/`isGenerationModel` (so a generation/fallback run never picks an embedding model like `nomic-embed-text`); `isVisionModel(model)` (string id or model card — prefers explicit `type:'vlm'`/`capabilities:['vision']` metadata, falls back to id regex; used by the LoRA captioner); `recommendEditorialModel(models)` ranks installed models for editorial review/editing. Pure. Mirror `isEmbeddingModel`/`isVisionModel` in `client/src/utils/providers.js`. || `loraDataset.js` | Pure helpers for character LoRA training datasets (`data/lora-datasets/`): `sanitizeLoraDataset` (collectionStore sanitizer), `deriveTriggerWord` (name → single-token slug with collision suffix), `prefixCaption` (idempotent trigger-word prefixing), `buildVariationMatrix` (deterministic view/pose/expression/outfit tuples for batch generation), `computeDatasetReadiness` (trainable gate: ≥`MIN_TRAINING_IMAGES` ready+captioned images, plus an advisory `recommended`/`quality` tier via `datasetQualityTier` nudging toward `RECOMMENDED_TRAINING_IMAGES`), `analyzeCaptionInvariants` (flags identity fragments repeated across ≥`INVARIANT_SHARE_THRESHOLD` of captions — those bind to the caption phrases instead of the trigger token, issue #1320) + `stripSharedFragments` (rewrite one caption with those fragments removed, trigger preserved). Prompt building + I/O live in `services/loraDatasetGenerate.js` / `services/loraDatasets.js`. || `issueLength.js` | Per-issue size targets fed into text stages. |diff --git a/server/lib/localLlmDisk.js b/server/lib/localLlmDisk.jsindex 29a325339e..8cf3e589fa 100644--- a/server/lib/localLlmDisk.js+++ b/server/lib/localLlmDisk.js@@ -36,6 +36,45 @@ export function digestToBlobFilename(digest) {return String(digest || '').replace(':', '-');}+/**+ * Every blob a manifest needs on disk: the tiny config blob plus each layer, as+ * `{ digest, size, filename, hex }`. Ollama verifies ALL of them before writing+ * the manifest, so a pull that "reached 100%" can still be missing the config.+ * `size` is null (never 0) when the manifest doesn't declare one — absent and+ * legitimately-empty must not collapse. `hex` is the bare digest for comparing+ * against a locally computed hash.+ * @param {object} manifest a parsed Ollama/OCI manifest+ * @returns {Array<{ digest: string, size: number|null, filename: string, hex: string }>}+ */+export function manifestBlobRefs(manifest) {+ return [manifest?.config, ...(Array.isArray(manifest?.layers) ? manifest.layers : [])]+ .filter((entry) => entry?.digest)+ .map((entry) => ({+ digest: entry.digest,+ size: Number.isFinite(entry.size) ? entry.size : null,+ filename: digestToBlobFilename(entry.digest),+ hex: String(entry.digest).split(':').pop() || ''+ }));+}++/**+ * The Hugging Face OCI registry base URL for a passthrough pull ref+ * (`hf.co/<owner>/<repo>:<quant>`), or null when the ref isn't one — those are+ * the only refs whose manifest + blobs PortOS can fetch itself to finish a pull+ * Ollama abandoned, since HF exposes the OCI registry API at+ * `https://huggingface.co/v2/<owner>/<repo>/…`.+ *+ * Always addresses the canonical `huggingface.co` host: `hf.co` only+ * 307-redirects there, and the redirect costs a round trip on every blob.+ * @param {{ registry?: string, namespace?: string, name?: string, tag?: string }} ref+ * @returns {string|null}+ */+export function huggingFaceRegistryBase(ref) {+ const isHf = /^(hf\.co|huggingface\.co)$/i.test(String(ref?.registry || ''))+ && Boolean(ref?.namespace) && Boolean(ref?.name) && Boolean(ref?.tag);+ return isHf ? `https://huggingface.co/v2/${ref.namespace}/${ref.name}` : null;+}+/*** Parse an Ollama model ref into registry/namespace/name/tag, mirroring how* Ollama lays manifests out on disk. Bare names default to thediff --git a/server/lib/localLlmDisk.test.js b/server/lib/localLlmDisk.test.jsindex 252643fca9..e27b663dfb 100644--- a/server/lib/localLlmDisk.test.js+++ b/server/lib/localLlmDisk.test.js@@ -2,7 +2,7 @@ import { describe, it, expect } from 'vitest';import {parseOllamaManifest, digestToBlobFilename, parseOllamaModelRef, ollamaManifestRelPath,sanitizeOllamaName, dirIsMlx, selectPrimaryGguf, selectProjectorGguf, isShardedGguf,- lmStudioPublisherRepo, buildModelfile,+ lmStudioPublisherRepo, buildModelfile, manifestBlobRefs, huggingFaceRegistryBase,OLLAMA_MODEL_MEDIATYPE, OLLAMA_PROJECTOR_MEDIATYPE} from './localLlmDisk.js';@@ -110,4 +110,49 @@ describe('localLlmDisk', () => {expect(buildModelfile('/abs/path/model.gguf')).toBe('FROM /abs/path/model.gguf\n');});});++ describe('manifestBlobRefs', () => {+ it('lists the config blob FIRST plus every layer, with sizes, filenames and bare hexes', () => {+ const manifest = {+ config: { digest: 'sha256:cfg', size: 481 },+ layers: [+ { mediaType: OLLAMA_MODEL_MEDIATYPE, digest: 'sha256:weights', size: 29787701792 },+ { mediaType: OLLAMA_PROJECTOR_MEDIATYPE, digest: 'sha256:proj', size: 927607360 }+ ]+ };+ expect(manifestBlobRefs(manifest)).toEqual([+ { digest: 'sha256:cfg', size: 481, filename: 'sha256-cfg', hex: 'cfg' },+ { digest: 'sha256:weights', size: 29787701792, filename: 'sha256-weights', hex: 'weights' },+ { digest: 'sha256:proj', size: 927607360, filename: 'sha256-proj', hex: 'proj' }+ ]);+ });+ it('reports a null size (not 0) when the manifest omits or mistypes it', () => {+ // A missing size must NOT read as "0 bytes" — the caller treats null as+ // "unknown, refuse to recover" rather than "empty file, nothing to fetch".+ const refs = manifestBlobRefs({ config: { digest: 'sha256:cfg' }, layers: [{ digest: 'sha256:w', size: '900' }] });+ expect(refs.map((r) => r.size)).toEqual([null, null]);+ });+ it('skips entries with no digest and tolerates a malformed manifest', () => {+ expect(manifestBlobRefs({ config: { size: 5 }, layers: [{ size: 9 }] })).toEqual([]);+ expect(manifestBlobRefs(null)).toEqual([]);+ expect(manifestBlobRefs({})).toEqual([]);+ });+ });++ describe('huggingFaceRegistryBase', () => {+ it('builds the canonical huggingface.co OCI base (never the redirecting hf.co)', () => {+ expect(huggingFaceRegistryBase(parseOllamaModelRef('hf.co/example-org/Some-Model-GGUF:Q8_0')))+ .toBe('https://huggingface.co/v2/example-org/Some-Model-GGUF');+ expect(huggingFaceRegistryBase(parseOllamaModelRef('huggingface.co/owner/repo:Q4_K_M')))+ .toBe('https://huggingface.co/v2/owner/repo');+ expect(huggingFaceRegistryBase(parseOllamaModelRef('HF.CO/owner/repo:Q4_K_M')))+ .toBe('https://huggingface.co/v2/owner/repo');+ });+ it('returns null for the ollama.ai registry and other hosts (no HF OCI API to recover from)', () => {+ expect(huggingFaceRegistryBase(parseOllamaModelRef('gpt-oss:20b'))).toBe(null);+ expect(huggingFaceRegistryBase(parseOllamaModelRef('myorg/mymodel:v2'))).toBe(null);+ expect(huggingFaceRegistryBase(parseOllamaModelRef('localhost:5000/team/m'))).toBe(null);+ expect(huggingFaceRegistryBase(null)).toBe(null);+ });+ });});diff --git a/server/routes/localLlm.js b/server/routes/localLlm.jsindex abe85945aa..e5a412996c 100644--- a/server/routes/localLlm.js+++ b/server/routes/localLlm.js@@ -28,7 +28,8 @@ import { getCatalog, searchCatalog, isBackend } from '../lib/localLlmCatalog.js'import { isAppleSilicon } from '../lib/platform.js'import { searchHuggingFaceModels, enrichCatalogWithVariants } from '../services/huggingFaceCatalog.js'import {- getStatus, listModels, listVisionModels, installModel, deleteModel, switchBackend, migrateBackend, installBackend, upgradeBackend, controlOllamaServer+ getStatus, listModels, listVisionModels, installModel, deleteModel, switchBackend, migrateBackend, installBackend, upgradeBackend, controlOllamaServer,+ describeInstallProgress} from '../services/localLlm.js'import { runLocalLlmTest, compareLocalLlmModels } from '../services/localLlmPlayground.js'import { listUserModels } from '../services/audioModels.js'@@ -174,9 +175,12 @@ router.post('/install', asyncHandler(async (req, res) => {// A thrown rejection (e.g. the pull stream dropping mid-download) would 500// via asyncHandler but never emit a terminal progress frame, leaving the// client's progress banner stuck on the last 'start'. Surface it as 'error'.+ // Any statused frame renders — percent progress, a transient-error retry, or+ // the `finalizing` pass where PortOS completes an install Ollama abandoned+ // (without which the banner would sit at "100%" through the whole recovery).const result = await installModel(backend, modelId, (p) => {- if (p?.percent != null) emit('start', `${modelId}: ${p.status || 'downloading'} ${p.percent}%`)- else if (p?.retrying) emit('start', `${modelId}: ${p.status || 'retrying…'}`)+ const label = describeInstallProgress(p)+ if (label) emit('start', `${modelId}: ${label}`)}).catch((err) => {emit('error', `Install failed: ${err.message}`)throw errdiff --git a/server/services/localLlm.js b/server/services/localLlm.jsindex 32745db877..f1ac48727b 100644--- a/server/services/localLlm.js+++ b/server/services/localLlm.js@@ -829,6 +829,19 @@ function refreshOllamaBackedProviders() {})}+/**+ * One-line label for an install progress frame, or null for a frame with nothing+ * to say. Shared by every consumer of `installModel`'s `onProgress` (the install+ * route and `migrateBackend`) so a new frame kind — `retrying`, `finalizing`, or+ * whatever comes next — reaches all of them without another per-call-site edit.+ * @param {{ status?: string, percent?: number|null }} [p]+ * @returns {string|null}+ */+export function describeInstallProgress(p) {+ if (p?.percent != null) return `${p.status || 'downloading'} ${p.percent}%`+ return p?.status || null+}+/*** Install (pull/download) a model on a backend.* @param {(p) => void} [onProgress] - streaming progress (Ollama only)@@ -973,7 +986,8 @@ export async function migrateBackend(to, { mode = 'link', onProgress = () => {}}onProgress({ event: 'start', message: `Downloading ${targetId} on ${to}${exact ? '' : ' (best-effort)'}…` })const r = await installModel(to, targetId, (p) => {- if (p?.percent != null) onProgress({ event: 'start', message: `Pulling ${targetId}: ${p.percent}%` })+ const label = describeInstallProgress(p)+ if (label) onProgress({ event: 'start', message: `Pulling ${targetId}: ${label}` })})// `pending` (LM Studio REST fallback) means the download was queued, not// finished — don't report it as a completed install.diff --git a/server/services/localLlm.test.js b/server/services/localLlm.test.jsindex 9e938280cb..cce2666eb4 100644--- a/server/services/localLlm.test.js+++ b/server/services/localLlm.test.js@@ -148,6 +148,24 @@ describe('localLlm', () => {});});+ describe('describeInstallProgress', () => {+ it('labels percent frames and every statused non-percent frame', () => {+ expect(svc.describeInstallProgress({ status: 'downloading', percent: 42 })).toBe('downloading 42%');+ expect(svc.describeInstallProgress({ percent: 0 })).toBe('downloading 0%');+ // Retry + finalize frames carry no percent — they must still render, or the+ // banner freezes at the last percentage for the whole pause.+ expect(svc.describeInstallProgress({ status: 'retrying after network error', percent: null }))+ .toBe('retrying after network error');+ expect(svc.describeInstallProgress({ status: 'finishing install from downloaded files…', percent: null, finalizing: true }))+ .toBe('finishing install from downloaded files…');+ });+ it('returns null for a frame with nothing to say', () => {+ expect(svc.describeInstallProgress({ percent: null })).toBe(null);+ expect(svc.describeInstallProgress({})).toBe(null);+ expect(svc.describeInstallProgress(null)).toBe(null);+ });+ });+describe('switchBackend', () => {it('writes the marker and enables the paired (disabled) provider', async () => {const r = await svc.switchBackend('lmstudio');diff --git a/server/services/ollamaManager.js b/server/services/ollamaManager.jsindex 00f85fc58e..2bfbb633f7 100644--- a/server/services/ollamaManager.js+++ b/server/services/ollamaManager.js@@ -16,15 +16,19 @@import { homedir } from 'os'import { join, dirname } from 'path'-import { readdir, stat, link } from 'fs/promises'+import { readdir, stat, link, unlink } from 'fs/promises'+import { createHash } from 'crypto'import { execFile, spawn } from 'child_process'import { promisify } from 'util'import { fetchWithTimeout } from '../lib/fetchWithTimeout.js'import { readResponseJson } from '../lib/readResponseJson.js'-import { readJSONFile, sha256File, safeJSONParse, ensureDir, sleep } from '../lib/fileUtils.js'+import { readJSONFile, sha256File, safeJSONParse, ensureDir, atomicWrite, sleep } from '../lib/fileUtils.js'import {- parseOllamaManifest, parseOllamaModelRef, ollamaManifestRelPath, digestToBlobFilename, buildModelfile+ parseOllamaManifest, parseOllamaModelRef, ollamaManifestRelPath, digestToBlobFilename, buildModelfile,+ manifestBlobRefs, huggingFaceRegistryBase} from '../lib/localLlmDisk.js'+import { buildHfAuthHeaders } from '../lib/huggingfaceLora.js'+import { getHfToken } from '../lib/hfToken.js'import { isEmbeddingModel } from '../lib/localModelHeuristics.js'const execFileAsync = promisify(execFile)@@ -37,6 +41,21 @@ const DEFAULT_REQUEST_TIMEOUT_MS = 10_000// than restarts. Total attempts (1 initial + retries) and a linear backoff base.const PULL_MAX_ATTEMPTS = 3const PULL_RETRY_BASE_DELAY_MS = 1_000+// Hugging Face can be pathologically slow serving the tiny (≈500 byte) *config*+// blob of a large GGUF repo — a cold CDN miss regularly takes 50-60s, well past+// Ollama's internal per-request deadline. The weight layers all reach 100%, then+// the pull dies with "context deadline exceeded" and no manifest is written, so+// the model vanishes even though ~30GB of verified blobs are on disk. Ollama+// itself doesn't resume that step, and every retry re-races the same deadline.+// So when a pull fails that way we finish it ourselves: fetch the manifest ++// missing blobs with a generous timeout, verify each digest, and write the+// manifest Ollama would have written. See isPullDeadlineError().+const HF_FINALIZE_TIMEOUT_MS = 180_000+// Only complete blobs small enough to hold in memory and hash in one shot — the+// config/params/template layers this recovery exists for are bytes-to-kilobytes.+// A missing multi-GB weight layer is a real download, not a stalled hiccup, so+// we bail and let the error surface rather than silently re-downloading it here.+const HF_FINALIZE_MAX_BLOB_BYTES = 4 * 1024 * 1024// Short probe — degrade to "no Ollama" fast rather than block on a cold check.const AVAILABILITY_PROBE_TIMEOUT_MS = 5_000const START_TIMEOUT_MS = 12_000@@ -645,11 +664,14 @@ async function unloadModel(modelName) {/*** Pull a model, streaming progress. Resolves once the pull finishes.- * During a transient-error backoff the callback fires with `retrying: true`- * (and `percent: null`) so the UI can show a "retrying" banner instead of stalling.+ * Non-percent frames carry a reason flag so the UI can show why the banner is+ * paused instead of stalling: `retrying: true` during a transient-error backoff,+ * `finalizing: true` while PortOS completes an install Ollama abandoned (see+ * finalizeHuggingFacePull). A success that went through that recovery is flagged+ * `recovered: true`.* @param {string} modelId- * @param {(p: { status: string, percent: number|null, completed?: number, total?: number, retrying?: boolean }) => void} [onProgress]- * @returns {Promise<{ success: boolean, modelId: string, error?: string }>}+ * @param {(p: { status: string, percent: number|null, completed?: number, total?: number, retrying?: boolean, finalizing?: boolean }) => void} [onProgress]+ * @returns {Promise<{ success: boolean, modelId: string, error?: string, recovered?: boolean }>}*/async function pullModel(modelId, onProgress) {if (!(await checkOllamaAvailable())) {@@ -675,6 +697,20 @@ async function pullModel(modelId, onProgress) {await sleep(delayMs)}+ // The weights may all be on disk and only Ollama's manifest write missing —+ // retrying just re-races the same deadline, so finish the pull ourselves.+ if (isPullDeadlineError(lastError)) {+ if (typeof onProgress === 'function') {+ onProgress({ status: 'finishing install from downloaded files…', percent: null, finalizing: true })+ }+ const recovered = await finalizeHuggingFacePull(modelId).catch((err) => ({ success: false, error: err.message }))+ if (recovered.success) {+ installedModels = null // bust cache so the recovered model shows on next list+ return { success: true, modelId, recovered: true }+ }+ console.warn(`⚠️ Ollama pull recovery declined for ${modelId}: ${recovered.error}`)+ }+console.error(`⚠️ Ollama pull failed for ${modelId}: ${lastError}`)const code = isShardedGgufError(lastError) ? 'SHARDED_GGUF': isOllamaOutdatedError(lastError) ? 'OLLAMA_OUTDATED'@@ -682,6 +718,21 @@ async function pullModel(modelId, onProgress) {return { success: false, error: lastError, modelId, ...(code ? { code } : {}) }}+/**+ * Detect the Go-runtime deadline Ollama reports when a registry request outlives+ * its internal per-request budget: `context deadline exceeded`. Distinctive+ * because it lands AFTER the weight layers hit 100% — the blobs are downloaded+ * and verified, only the manifest write is missing — which is what makes the+ * local-completion recovery in finalizeHuggingFacePull() safe to attempt.+ *+ * Deliberately NOT part of isTransientPullError: retrying re-races the same slow+ * endpoint against the same deadline and fails identically every time.+ * @param {string|null|undefined} error+ */+function isPullDeadlineError(error) {+ return /context deadline exceeded/i.test(String(error ?? ''))+}+/*** Detect Ollama's refusal to pull a multi-part (sharded) GGUF. The HF passthrough* registry returns a 400 whose message names "sharded GGUF" and links the tracking@@ -866,12 +917,15 @@ function getModelsDir() {const fileExists = (p) => stat(p).then((s) => s.isFile()).catch(() => false)const readManifest = (p) => readJSONFile(p, null, { logError: false })+// One expression for the canonical manifest path, so the recovery writer and+// findManifest's reader can't drift apart.+const manifestPathFor = (modelsDir, ref) => join(modelsDir, ...ollamaManifestRelPath(ref).split('/'))// The canonical manifest path covers registry-pulled models; fall back to a// shallow scan of manifests/<registry>/<namespace>/<name>/<tag> for custom// registries/namespaces we didn't guess.async function findManifest(modelsDir, ref) {- const direct = await readManifest(join(modelsDir, ...ollamaManifestRelPath(ref).split('/')))+ const direct = await readManifest(manifestPathFor(modelsDir, ref))if (direct) return directconst manifestsDir = join(modelsDir, 'manifests')const registries = await readdir(manifestsDir).catch(() => [])@@ -886,6 +940,86 @@ async function findManifest(modelsDir, ref) {return null}+/**+ * Fetch a Hugging Face registry document (manifest or blob) as a Buffer, with a+ * timeout generous enough for HF's slow cold-CDN small-blob path (the very thing+ * Ollama's own deadline gives up on). Carries the user's HF token when they have+ * one, so a gated repo Ollama could pull is recoverable too.+ * @returns {Promise<{ buffer: Buffer }|{ error: string }>}+ */+async function fetchHuggingFaceDocument(url, headers) {+ return fetchWithTimeout(url, { headers }, HF_FINALIZE_TIMEOUT_MS)+ .then(async (response) => (response.ok+ ? { buffer: Buffer.from(await response.arrayBuffer()) }+ : { error: `${response.status} ${response.statusText}` }))+ .catch((err) => ({ error: describeFetchError(err) }))+}++/**+ * Finish a Hugging Face pull that downloaded its weights but died before Ollama+ * wrote the manifest (see HF_FINALIZE_TIMEOUT_MS). Re-fetches the manifest, then+ * for each blob it references: keeps an on-disk blob whose size already matches,+ * and downloads + digest-verifies any small missing one. Only when EVERY blob is+ * present and correct does it write the manifest — a half-written manifest would+ * leave `ollama run` failing on a missing blob, which is worse than no model.+ *+ * Digest verification is the whole safety story here: we are hand-placing files+ * into Ollama's content-addressed store, so a byte we didn't verify is a corrupt+ * model that reports as installed.+ *+ * Pure disk + network: the caller owns the `installedModels` cache bust, so this+ * stays safe to call from a future "repair this install" action.+ *+ * @param {string} modelId e.g. `hf.co/<owner>/<repo>:Q8_0`+ * @returns {Promise<{ success: boolean, error?: string }>}+ */+async function finalizeHuggingFacePull(modelId) {+ const ref = parseOllamaModelRef(modelId)+ const base = huggingFaceRegistryBase(ref)+ if (!base) return { success: false, error: 'not a Hugging Face model ref' }++ const modelsDir = getModelsDir()+ const blobsDir = join(modelsDir, 'blobs')+ const headers = buildHfAuthHeaders(await getHfToken())+ const fetched = await fetchHuggingFaceDocument(`${base}/manifests/${ref.tag}`, headers)+ if (fetched.error) return { success: false, error: `manifest fetch failed: ${fetched.error}` }++ const manifestText = fetched.buffer.toString('utf8')+ const refs = manifestBlobRefs(safeJSONParse(manifestText, null))+ if (refs.length === 0) return { success: false, error: 'manifest listed no blobs' }++ for (const blob of refs) {+ const blobPath = join(blobsDir, blob.filename)+ const existing = await stat(blobPath).then((s) => s.size, () => null)+ // Ollama already verified anything it finished writing, so a size match is+ // enough to accept it — re-hashing a 30GB weight layer would take minutes.+ if (existing !== null && existing === blob.size) continue+ if (blob.size === null || blob.size > HF_FINALIZE_MAX_BLOB_BYTES) {+ return { success: false, error: `blob ${blob.filename} (${blob.size ?? 'unknown'} bytes) is missing and too large to recover` }+ }+ const got = await fetchHuggingFaceDocument(`${base}/blobs/${blob.digest}`, headers)+ if (got.error) return { success: false, error: `blob ${blob.filename} fetch failed: ${got.error}` }+ const hex = createHash('sha256').update(got.buffer).digest('hex')+ if (hex !== blob.hex) return { success: false, error: `blob ${blob.filename} failed digest verification` }+ await atomicWrite(blobPath, got.buffer)+ console.log(`🧩 Ollama pull recovery: restored blob ${blob.filename.slice(0, 19)} (${got.buffer.length}B) for ${modelId}`)+ }++ // Ollama leaves `<blob>-partial*` scratch files behind for the download it+ // abandoned; they'd shadow the completed blobs on a future resume attempt. One+ // pass over the (potentially large) blobs dir clears every blob's leftovers.+ const scratch = await readdir(blobsDir).catch(() => [])+ await Promise.all(scratch+ .filter((name) => refs.some((blob) => name.startsWith(`${blob.filename}-partial`)))+ .map((name) => unlink(join(blobsDir, name)).catch(() => {})))++ // Write the manifest byte-for-byte as the registry served it so the digest+ // Ollama derives from it matches the registry's.+ await atomicWrite(manifestPathFor(modelsDir, ref), manifestText)+ console.log(`✅ Ollama pull recovery: wrote manifest for ${modelId} (${refs.length} blobs verified)`)+ return { success: true }+}+/*** Locate an installed Ollama model's weight files on disk (no network).* @returns {Promise<{ ggufPath: string, projectorPath: string|null, isMlx: false, isSharded: false }|null>}@@ -1007,5 +1141,7 @@ export {isOllamaProvider,getServiceStatus,getEmbeddings,- isBootstrapConflictError+ isBootstrapConflictError,+ isPullDeadlineError,+ finalizeHuggingFacePull}diff --git a/server/services/ollamaManager.test.js b/server/services/ollamaManager.test.jsindex ddd1a47463..32791e683b 100644--- a/server/services/ollamaManager.test.js+++ b/server/services/ollamaManager.test.js@@ -1,4 +1,8 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import { mkdtemp, mkdir, rm, readFile, writeFile, stat } from 'fs/promises'+import { createHash } from 'crypto'+import { tmpdir } from 'os'+import { join } from 'path'// startPersistentService / getServiceStatus shell out via promisify(execFile).// Route every exec call through a per-test impl so the homebrew service flow can@@ -10,6 +14,11 @@ vi.mock('child_process', () => ({spawn: vi.fn()}))+// The HF pull recovery attaches the user's HF token (so a gated repo Ollama could+// pull is recoverable too). Stub the resolver rather than reading real settings.+const hfTokenMock = { token: null }+vi.mock('../lib/hfToken.js', () => ({ getHfToken: async () => hfTokenMock.token }))+// pullModel talks to Ollama over its native HTTP API via the global `fetch`// (through fetchWithTimeout). We stub `fetch` so each test scripts the// `/api/version` probe and a sequence of per-attempt `/api/pull` streams.@@ -70,12 +79,13 @@ function stubFetch(pullResponses) {}// Fresh module per test → fresh availability cache so the version probe runs.-async function loadPullModel() {+async function loadManager() {vi.resetModules()- const mod = await import('./ollamaManager.js')- return mod.pullModel+ return import('./ollamaManager.js')}+const loadPullModel = () => loadManager().then((mod) => mod.pullModel)+describe('ollamaManager.pullModel transient-error retry', () => {beforeEach(() => { vi.useFakeTimers() })afterEach(() => { vi.useRealTimers(); vi.unstubAllGlobals() })@@ -197,6 +207,283 @@ describe('ollamaManager.pullModel transient-error retry', () => {})})+// ---- HF pull recovery ("context deadline exceeded" after 100%) --------------+//+// finalizeHuggingFacePull touches the real filesystem, so these tests point+// OLLAMA_MODELS at a temp dir and pre-place the layer blobs Ollama had already+// finished downloading — the exact on-disk state the bug leaves behind.++// Serve a Buffer the way fetch does, for the HF registry stub.+const bufferResponse = (buf) => ({ ok: true, status: 200, arrayBuffer: async () => buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength) })++describe('ollamaManager HF pull recovery', () => {+ const HF_ID = 'hf.co/example-org/Example-Model-GGUF:Q8_0'+ const HF_BASE = 'https://huggingface.co/v2/example-org/Example-Model-GGUF'+ let modelsDir+ let originalModelsEnv++ // Real content so digests are genuine — the recovery verifies every blob it+ // writes, and a fake digest must be able to fail that check.+ const configBody = Buffer.from(JSON.stringify({ model_format: 'gguf', model_family: 'qwen35' }))+ const configDigest = `sha256:${createHash('sha256').update(configBody).digest('hex')}`+ const weightsBody = Buffer.from('pretend 30GB of GGUF weights')+ const weightsDigest = `sha256:${createHash('sha256').update(weightsBody).digest('hex')}`++ const manifest = () => ({+ schemaVersion: 2,+ config: { digest: configDigest, mediaType: 'application/vnd.docker.container.image.v1+json', size: configBody.length },+ layers: [{ digest: weightsDigest, mediaType: 'application/vnd.ollama.image.model', size: weightsBody.length }]+ })++ beforeEach(async () => {+ originalModelsEnv = process.env.OLLAMA_MODELS+ modelsDir = await mkdtemp(join(tmpdir(), 'portos-ollama-models-'))+ process.env.OLLAMA_MODELS = modelsDir+ await mkdir(join(modelsDir, 'blobs'), { recursive: true })+ })++ afterEach(async () => {+ if (originalModelsEnv === undefined) delete process.env.OLLAMA_MODELS+ else process.env.OLLAMA_MODELS = originalModelsEnv+ await rm(modelsDir, { recursive: true, force: true })+ vi.unstubAllGlobals()+ })++ const blobPath = (digest) => join(modelsDir, 'blobs', digest.replace(':', '-'))+ const manifestPath = () => join(modelsDir, 'manifests', 'hf.co', 'example-org', 'Example-Model-GGUF', 'Q8_0')++ // Pre-place the weight layer Ollama finished before it died.+ const placeWeights = () => writeFile(blobPath(weightsDigest), weightsBody)++ // Stub the HF OCI registry. `blobBody` overrides what the config blob serves+ // (to simulate corruption); `failBlob` makes the blob request fail outright.+ // The returned array of requested URLs also carries the per-request `init`+ // objects on `.inits`, so header propagation is assertable.+ function stubRegistry({ blobBody = configBody, failBlob = false, manifestDoc = manifest() } = {}) {+ const urls = []+ urls.inits = []+ vi.stubGlobal('fetch', vi.fn(async (url, init) => {+ const u = String(url)+ urls.push(u)+ urls.inits.push(init)+ if (u.endsWith('/api/version')) return versionResponse()+ if (u === `${HF_BASE}/manifests/Q8_0`) return bufferResponse(Buffer.from(JSON.stringify(manifestDoc)))+ if (u === `${HF_BASE}/blobs/${configDigest}`) {+ if (failBlob) return { ok: false, status: 504, statusText: 'Gateway Timeout' }+ return bufferResponse(blobBody)+ }+ throw new Error(`unexpected fetch: ${u}`)+ }))+ return urls+ }++ const exists = (p) => stat(p).then(() => true, () => false)++ describe('isPullDeadlineError', () => {+ it('matches Ollama’s Go deadline error', async () => {+ const { isPullDeadlineError } = await loadManager()+ expect(isPullDeadlineError('context deadline exceeded')).toBe(true)+ expect(isPullDeadlineError('Post "https://…": context deadline exceeded')).toBe(true)+ })+ it('does NOT match the transient class or unrelated errors', async () => {+ const { isPullDeadlineError } = await loadManager()+ // Must stay disjoint from isTransientPullError — a plain retry can't fix a+ // deadline, and the recovery path must not swallow real network blips.+ expect(isPullDeadlineError('EOF')).toBe(false)+ expect(isPullDeadlineError('read ECONNRESET')).toBe(false)+ expect(isPullDeadlineError('pull model manifest: file does not exist')).toBe(false)+ expect(isPullDeadlineError(null)).toBe(false)+ })+ })++ describe('finalizeHuggingFacePull', () => {+ it('fetches the missing config blob and writes the manifest Ollama never wrote', async () => {+ await placeWeights()+ stubRegistry()+ const { finalizeHuggingFacePull } = await loadManager()++ expect(await finalizeHuggingFacePull(HF_ID)).toEqual({ success: true })+ expect(await readFile(blobPath(configDigest))).toEqual(configBody)+ // Byte-identical to what the registry served, so Ollama derives the same digest.+ expect(await readFile(manifestPath(), 'utf8')).toBe(JSON.stringify(manifest()))+ })++ it('carries the user’s HF token so a gated repo is recoverable too', async () => {+ hfTokenMock.token = 'hf_example_token'+ await placeWeights()+ const urls = stubRegistry()+ const { finalizeHuggingFacePull } = await loadManager()++ await finalizeHuggingFacePull(HF_ID)++ // Both the manifest and the blob request need the bearer — a 401 on either+ // would make the recovery decline every time for a gated model.+ expect(urls.inits.every((init) => init?.headers?.Authorization === 'Bearer hf_example_token')).toBe(true)+ hfTokenMock.token = null+ })++ it('keeps the already-downloaded weight layer instead of re-fetching 30GB', async () => {+ await placeWeights()+ const urls = stubRegistry()+ const { finalizeHuggingFacePull } = await loadManager()++ await finalizeHuggingFacePull(HF_ID)++ expect(urls).not.toContain(`${HF_BASE}/blobs/${weightsDigest}`)+ expect(await readFile(blobPath(weightsDigest))).toEqual(weightsBody) // untouched+ })++ it('clears the `-partial` scratch files Ollama abandoned for the recovered blob', async () => {+ await placeWeights()+ const partial = `${blobPath(configDigest)}-partial`+ const partialPart = `${blobPath(configDigest)}-partial-0`+ await writeFile(partial, Buffer.alloc(481))+ await writeFile(partialPart, '{"N":0,"Offset":0,"Size":481,"Completed":0}\n')+ stubRegistry()+ const { finalizeHuggingFacePull } = await loadManager()++ await finalizeHuggingFacePull(HF_ID)++ // Left in place they'd shadow the completed blob on a later resume attempt.+ expect(await exists(partial)).toBe(false)+ expect(await exists(partialPart)).toBe(false)+ })++ it('refuses to write the manifest when a downloaded blob fails digest verification', async () => {+ await placeWeights()+ stubRegistry({ blobBody: Buffer.from('corrupted bytes from a bad CDN edge') })+ const { finalizeHuggingFacePull } = await loadManager()++ const result = await finalizeHuggingFacePull(HF_ID)++ expect(result.success).toBe(false)+ expect(result.error).toMatch(/digest verification/)+ // No manifest AND no bogus blob — a corrupt model that reports installed is+ // worse than a failed install.+ expect(await exists(manifestPath())).toBe(false)+ expect(await exists(blobPath(configDigest))).toBe(false)+ })++ it('refuses when a multi-GB weight layer is the missing blob (that is a real download)', async () => {+ // No placeWeights(), and the layer declares its true multi-GB size — so+ // this was never a "finished downloading, only the manifest is missing"+ // failure and must not turn into a silent 30GB re-download here.+ const big = manifest()+ big.layers[0].size = 29_787_701_792+ stubRegistry({ manifestDoc: big })+ const { finalizeHuggingFacePull } = await loadManager()++ const result = await finalizeHuggingFacePull(HF_ID)++ expect(result.success).toBe(false)+ expect(result.error).toMatch(/too large to recover/)+ expect(await exists(manifestPath())).toBe(false)+ })++ it('refuses a blob whose manifest size is missing rather than guessing', async () => {+ // Unknown size must not read as "0 bytes, nothing to fetch" — absent and+ // legitimately-empty are different, and only one is safe to accept.+ const noSize = manifest()+ delete noSize.layers[0].size+ stubRegistry({ manifestDoc: noSize })+ const { finalizeHuggingFacePull } = await loadManager()++ const result = await finalizeHuggingFacePull(HF_ID)++ expect(result.success).toBe(false)+ expect(result.error).toMatch(/unknown bytes/)+ expect(await exists(manifestPath())).toBe(false)+ })++ it('treats a size-mismatched on-disk blob as missing and re-fetches it', async () => {+ await placeWeights()+ await writeFile(blobPath(configDigest), Buffer.from('truncated')) // wrong size+ const urls = stubRegistry()+ const { finalizeHuggingFacePull } = await loadManager()++ expect(await finalizeHuggingFacePull(HF_ID)).toEqual({ success: true })+ expect(urls).toContain(`${HF_BASE}/blobs/${configDigest}`)+ expect(await readFile(blobPath(configDigest))).toEqual(configBody)+ })++ it('surfaces a failed blob fetch without writing a partial manifest', async () => {+ await placeWeights()+ stubRegistry({ failBlob: true })+ const { finalizeHuggingFacePull } = await loadManager()++ const result = await finalizeHuggingFacePull(HF_ID)++ expect(result.success).toBe(false)+ expect(result.error).toMatch(/504/)+ expect(await exists(manifestPath())).toBe(false)+ })++ it('declines a non-Hugging-Face ref (no OCI registry to fetch from)', async () => {+ const { finalizeHuggingFacePull } = await loadManager()+ const result = await finalizeHuggingFacePull('gpt-oss:20b')+ expect(result).toEqual({ success: false, error: 'not a Hugging Face model ref' })+ })++ it('declines a manifest that lists no blobs', async () => {+ stubRegistry({ manifestDoc: { schemaVersion: 2 } })+ const { finalizeHuggingFacePull } = await loadManager()+ const result = await finalizeHuggingFacePull(HF_ID)+ expect(result.success).toBe(false)+ expect(result.error).toMatch(/no blobs/)+ })+ })++ describe('pullModel deadline recovery', () => {+ // Script /api/pull to fail with the deadline error, then let the recovery run.+ function stubPullThenRegistry(registryOpts) {+ const inner = stubRegistry(registryOpts)+ const registryFetch = globalThis.fetch+ let pulls = 0+ vi.stubGlobal('fetch', vi.fn(async (url, ...rest) => {+ if (String(url).endsWith('/api/pull')) {+ pulls+++ return makeStreamResponse([+ { status: 'pulling manifest' },+ { status: 'pulling', total: 100, completed: 100 },+ { error: 'context deadline exceeded' }+ ])+ }+ return registryFetch(url, ...rest)+ }))+ return { urls: inner, pullCount: () => pulls }+ }++ it('completes the install locally instead of failing at 100%', async () => {+ await placeWeights()+ const { pullCount } = stubPullThenRegistry()+ const { pullModel } = await loadManager()+ const onProgress = vi.fn()++ const result = await pullModel(HF_ID, onProgress)++ expect(result).toEqual({ success: true, modelId: HF_ID, recovered: true })+ expect(pullCount()).toBe(1) // NOT retried — a retry re-races the same deadline+ // The banner must move off "100%" while the recovery runs.+ expect(onProgress).toHaveBeenCalledWith(expect.objectContaining({ finalizing: true }))+ expect(await exists(manifestPath())).toBe(true)+ })++ it('reports the original deadline error when recovery cannot finish the install', async () => {+ // Multi-GB weight layer absent → recovery declines → the user sees Ollama's+ // real error rather than a confusing recovery-internal message.+ const big = manifest()+ big.layers[0].size = 29_787_701_792+ const { pullModel } = await loadManager()+ stubPullThenRegistry({ manifestDoc: big })++ const result = await pullModel(HF_ID)++ expect(result.success).toBe(false)+ expect(result.error).toBe('context deadline exceeded')+ })+ })+})+describe('ollamaManager.isBootstrapConflictError', () => {it('matches the launchctl bootstrap-5 / EIO failures brew surfaces', async () => {const { isBootstrapConflictError } = await import('./ollamaManager.js')@@ -241,11 +528,6 @@ describe('ollamaManager.startPersistentService bootstrap recovery (homebrew)', (vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, status: 200, json: async () => body, text: async () => JSON.stringify(body) })))}- async function loadManager() {- vi.resetModules()- return import('./ollamaManager.js')- }-it('boots out a stale launchd registration and retries when start fails with bootstrap-5', async () => {stubReachable()const calls = []