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
feat: import curated MLX models into Ollama (#4518)
[._.]/ Adam Eivy42bac53fc349
diff --git a/docs/research/2026-08-16-qwen38-mlx-macos.md b/docs/research/2026-08-16-qwen38-mlx-macos.mdindex 51c7ffd700..e9e15d2b92 100644--- a/docs/research/2026-08-16-qwen38-mlx-macos.md+++ b/docs/research/2026-08-16-qwen38-mlx-macos.md@@ -25,8 +25,8 @@ LM Studio from its JavaScript server and does not own an MLX Python inferenceloop where replacing operators would have an effect.There is therefore no useful PortOS feature to add for `mlx.fast` itself. The-native MLX model is the correct integration boundary; MLX/LM Studio own the-operator implementation and can update it independently.+native MLX model is the correct integration boundary; Ollama or LM Studio owns+the operator implementation and can update it independently.## Why the linked MTP repos are not catalog installs@@ -58,15 +58,19 @@ operator choice.PortOS also catalogs `orcarouter/Qwen3.8-27B-Uncensored-MLX` for explicitred-team and unrestricted local evaluation. The repository is gated on Hugging-Face and publishes several quantizations under one repository, so it is an-Apple-Silicon LM Studio entry rather than an Ollama pull target. Users must-accept the repository terms and authenticate in LM Studio before installing;-LM Studio resolves the appropriate available quantization.+Face and publishes several quantizations under one repository. The shared+catalog recommends it on both Apple-Silicon backends: PortOS downloads the+self-contained 15.0 GB `4-bit/` checkpoint and imports it with `ollama create`,+while LM Studio can select another available quantization. Users must accept+the repository terms and configure a Hugging Face token before installing.## PortOS behavior- Ollama on Apple Silicon: recommends and pulls the packaged- `qwen3.8:27b-mlx` model through Ollama's native MLX engine.+ `qwen3.8:27b-mlx` model through Ollama's native MLX engine. It also offers the+ curated OrcaRouter uncensored build, downloading its gated 4-bit Safetensors+ directory and importing it under+ `orcarouter/qwen3.8-27b-uncensored-mlx:4bit` with Ollama 0.19 or newer.- LM Studio on Apple Silicon: recommends and installs the complete 4-bit MLXtarget through the existing model-install endpoint.- LM Studio on Intel macOS and non-macOS hosts: hides the MLX recommendation;@@ -74,13 +78,14 @@ LM Studio resolves the appropriate available quantization.- Ollama on non-Apple hosts: hides the MLX recommendation; the existing GGUFentry remains available.- Migration: the known backend-specific MLX ids map exactly so switching- backends re-pulls the equivalent package instead of guessing a model name.+ backends installs the equivalent package instead of guessing a model name.## Sources- [`mlx.core.fast` documentation](https://ml-explore.github.io/mlx/build/html/python/fast.html)- [MLX-LM](https://github.com/ml-explore/mlx-lm)- [Ollama's MLX engine announcement](https://ollama.com/blog/mlx)+- [Ollama Safetensors import](https://docs.ollama.com/import)- [Complete Qwen3.8 27B MLX 4-bit checkpoint](https://huggingface.co/mlx-community/Qwen3.8-27B-4bit)- [OrcaRouter Qwen3.8 27B Uncensored MLX](https://huggingface.co/orcarouter/Qwen3.8-27B-Uncensored-MLX)- [Qwen3.8 27B MTP 4-bit drafter](https://huggingface.co/mlx-community/Qwen3.8-27B-MTP-4bit)diff --git a/server/lib/localLlmCatalog.js b/server/lib/localLlmCatalog.jsindex 5f50ab7ee7..199e9e698b 100644--- a/server/lib/localLlmCatalog.js+++ b/server/lib/localLlmCatalog.js@@ -39,7 +39,7 @@ export const LOCAL_LLM_CATEGORIES = [// Each entry: { key, name, category, recommendedFor?, featured?, params, size,// family, description, note?, capabilities, context?, format?,-// appleSiliconOnly?, ollama?, lmstudio?, ollamaAliases?,+// appleSiliconOnly?, ollama?, lmstudio?, ollamaImport?, ollamaAliases?,// lmstudioAliases? }//// `category` is the one primary lane that groups a model in the unfiltered@@ -49,6 +49,8 @@ export const LOCAL_LLM_CATEGORIES = [// It must include the primary category. `featured` is reserved for a deliberate// first-choice recommendation, not a measure of raw benchmark scores.// `ollama` / `lmstudio` are the exact pull/download ids for that backend.+// `ollamaImport` marks a curated Hugging Face Safetensors directory that PortOS+// imports with `ollama create` instead of trying to pull from Ollama's registry.// A missing id means there is no well-known build of that model for that// backend (the user can still free-text install one).// `ollamaAliases` / `lmstudioAliases` preserve recognized ids retired by an@@ -308,14 +310,20 @@ export const LOCAL_LLM_CATALOG = [category: 'general',recommendedFor: ['general', 'coding', 'reasoning', 'vision', 'multilingual'],params: '27B',- size: 'varies',+ size: '15.0 GB',family: 'qwen',description: 'OrcaRouter’s abliterated Qwen3.8 variant for red-team and unrestricted local evaluation, with 2-, 4-, 6-, and 8-bit MLX builds plus vision, tools, reasoning, and multilingual support.',- note: 'Gated on Hugging Face — accept the repository terms and authenticate in LM Studio before installing; LM Studio selects the quantization for this machine.',+ note: 'Gated on Hugging Face — accept the repository terms and configure a Hugging Face token in Settings. Ollama imports the 4-bit build; LM Studio can select another quantization.',capabilities: ['chat', 'code', 'reasoning', 'tools', 'vision', 'multilingual'],context: 262144,format: 'mlx',appleSiliconOnly: true,+ ollama: 'orcarouter/qwen3.8-27b-uncensored-mlx:4bit',+ ollamaImport: {+ repo: 'orcarouter/Qwen3.8-27B-Uncensored-MLX',+ subdir: '4-bit',+ minVersion: '0.19.0'+ },lmstudio: 'https://huggingface.co/orcarouter/Qwen3.8-27B-Uncensored-MLX',lmstudioAliases: ['orcarouter/Qwen3.8-27B-Uncensored-MLX']},@@ -698,6 +706,18 @@ const entryIdsForBackend = (entry, backend) => [const entryMatchesBackendId = (entry, backend, normalizedId) =>entryIdsForBackend(entry, backend).some((id) => normalizeFor(backend, id) === normalizedId);+/**+ * Return the trusted local-Safetensors import recipe for a curated Ollama id.+ * Unknown/free-text ids return null and continue through the normal pull path.+ */+export function getOllamaImportSpec(modelId) {+ const normalizedId = normalizeOllamaId(modelId);+ const entry = LOCAL_LLM_CATALOG.find((candidate) => (+ candidate.ollamaImport && entryMatchesBackendId(candidate, 'ollama', normalizedId)+ ));+ return entry ? { modelId: entry.ollama, ...entry.ollamaImport } : null;+}+/*** Return the catalog projected onto a single backend: only entries that ship* a known build for `backend`, each with the backend-specific install iddiff --git a/server/lib/localLlmCatalog.test.js b/server/lib/localLlmCatalog.test.jsindex 5025f47807..04085c231e 100644--- a/server/lib/localLlmCatalog.test.js+++ b/server/lib/localLlmCatalog.test.js@@ -1,6 +1,7 @@import { describe, it, expect } from 'vitest';import {- BACKENDS, isBackend, LOCAL_LLM_CATALOG, LOCAL_LLM_CATEGORIES, getCatalog, searchCatalog, mapModelToBackend+ BACKENDS, isBackend, LOCAL_LLM_CATALOG, LOCAL_LLM_CATEGORIES, getCatalog, searchCatalog,+ mapModelToBackend, getOllamaImportSpec} from './localLlmCatalog.js';describe('localLlmCatalog', () => {@@ -76,7 +77,14 @@ describe('localLlmCatalog', () => {expect(getCatalog('lmstudio', ['orcarouter/Qwen3.8-27B-Uncensored-MLX'], { appleSilicon: true }).find((m) => m.key === uncensoredKey)?.installed).toBe(true);expect(getCatalog('lmstudio', [], { appleSilicon: false }).some((m) => m.key === uncensoredKey)).toBe(false);- expect(getCatalog('ollama', [], { appleSilicon: true }).some((m) => m.key === uncensoredKey)).toBe(false);+ expect(getCatalog('ollama', [], { appleSilicon: true }).find((m) => m.key === uncensoredKey)).toMatchObject({+ format: 'mlx',+ id: 'orcarouter/qwen3.8-27b-uncensored-mlx:4bit',+ size: '15.0 GB'+ });+ expect(getCatalog('ollama', ['orcarouter/qwen3.8-27b-uncensored-mlx:4bit'], { appleSilicon: true })+ .find((m) => m.key === uncensoredKey)?.installed).toBe(true);+ expect(getCatalog('ollama', [], { appleSilicon: false }).some((m) => m.key === uncensoredKey)).toBe(false);});it('returns [] for an unknown backend', () => {@@ -177,9 +185,11 @@ describe('localLlmCatalog', () => {.toEqual({ targetId: 'mlx-community/Qwen3.8-27B-4bit', exact: true });});- it('does not invent an Ollama target for the LM Studio-only uncensored MLX build', () => {+ it('maps the uncensored MLX build to its curated local Ollama import name', () => {expect(mapModelToBackend('lmstudio', 'orcarouter/Qwen3.8-27B-Uncensored-MLX', 'ollama'))- .toEqual({ targetId: null, exact: false });+ .toEqual({ targetId: 'orcarouter/qwen3.8-27b-uncensored-mlx:4bit', exact: true });+ expect(mapModelToBackend('ollama', 'orcarouter/qwen3.8-27b-uncensored-mlx:4bit', 'lmstudio'))+ .toEqual({ targetId: 'https://huggingface.co/orcarouter/Qwen3.8-27B-Uncensored-MLX', exact: true });});it('returns null (skip) when mapping an unknown model TO LM Studio', () => {@@ -192,4 +202,17 @@ describe('localLlmCatalog', () => {expect(mapModelToBackend('ollama', 'llama3.2', 'nope')).toEqual({ targetId: null, exact: false });});});++ describe('getOllamaImportSpec', () => {+ it('returns only the trusted recipe attached to the curated install id', () => {+ expect(getOllamaImportSpec('orcarouter/qwen3.8-27b-uncensored-mlx:4bit')).toEqual({+ modelId: 'orcarouter/qwen3.8-27b-uncensored-mlx:4bit',+ repo: 'orcarouter/Qwen3.8-27B-Uncensored-MLX',+ subdir: '4-bit',+ minVersion: '0.19.0'+ });+ expect(getOllamaImportSpec('ORCAROUTER/QWEN3.8-27B-UNCENSORED-MLX:4BIT')).not.toBeNull();+ expect(getOllamaImportSpec('someone/untrusted-model:latest')).toBeNull();+ });+ });});diff --git a/server/services/huggingFaceCatalog.js b/server/services/huggingFaceCatalog.jsindex 24aeb5ae44..a576540eef 100644--- a/server/services/huggingFaceCatalog.js+++ b/server/services/huggingFaceCatalog.js@@ -530,10 +530,11 @@ function isInstalled(backend, result, installedIds) {// ---- MLX (Apple Silicon) ----------------------------------------------------// MLX is Apple's native ML format. It ships sharded `.safetensors` + a config-// (no single GGUF), and is installable ONLY via LM Studio (`lms get <repo>`) on-// Apple Silicon — Ollama packages supported native MLX builds through its own-// registry and can't pull arbitrary HF safetensors repos, so MLX is never surfaced-// for the Ollama backend (the search gates the whole MLX query on LM Studio + Apple Silicon).+// (no single GGUF). Live Hub discovery remains LM Studio-only: `lms get <repo>`+// understands an arbitrary result, whereas Ollama requires a supported local+// Safetensors import and a deliberate local model name. Curated Ollama imports+// are declared in localLlmCatalog.js instead of making every search result look+// one-click compatible.const MLX_PUBLISHER = 'mlx-community'const SAFETENSORS_RE = /\.safetensors$/i@@ -1006,10 +1007,11 @@ export async function searchHuggingFaceModels({ backend, query = '', category =// surfaces MLX repos, not just hand-typed queries that happen to match one.const mlxSearch = normalizeText(query) || CATEGORY_SEARCH[requestedCategory]?.replace(/\bgguf\b/gi, 'mlx') || 'mlx'const fetchLimit = Math.max(limit * 3, 30)- // MLX is only installable via LM Studio on Apple Silicon (see toMlxResult), so- // run the extra MLX query only there — never for Ollama, non-Apple hosts, or- // the audio category. `appleSilicon` is injected by the route (default false),- // keeping the service deterministic for tests regardless of the test host.+ // Arbitrary live MLX results are installable only through LM Studio (see+ // toMlxResult); trusted Ollama imports come from the curated catalog. Run this+ // discovery query only for LM Studio on Apple Silicon, never for Ollama,+ // non-Apple hosts, or audio. `appleSilicon` is route-injected (default false),+ // keeping tests deterministic regardless of their host.const wantMlx = appleSilicon && backend === 'lmstudio' && requestedCategory !== 'audio'const [ggufModelsRaw, mlxModelsRaw] = await Promise.all([fetchModels(search, fetchLimit, ggufOnly ? 'gguf' : null),diff --git a/server/services/localLlm.js b/server/services/localLlm.jsindex f1792b6704..93a9b3536c 100644--- a/server/services/localLlm.js+++ b/server/services/localLlm.js@@ -29,7 +29,7 @@ import { pipeline } from 'stream/promises'import { Readable } from 'stream'import { PATHS, atomicWrite, ensureDir, pathExists, sleep } from '../lib/fileUtils.js'import { compareSemver } from '../lib/versionUtils.js'-import { isBackend, mapModelToBackend } from '../lib/localLlmCatalog.js'+import { isBackend, mapModelToBackend, getOllamaImportSpec } from '../lib/localLlmCatalog.js'import { sanitizeOllamaName } from '../lib/localLlmDisk.js'import { recommendEditorialModel, isVisionModel, isVisionCapableCliProvider, isToolUseModel } from '../lib/localModelHeuristics.js'import { commandExists } from '../lib/commandExists.js'@@ -924,7 +924,10 @@ export function describeInstallProgress(p) {export async function installModel(backend, modelId, onProgress) {if (!isBackend(backend)) return { success: false, error: `Unknown backend: ${backend}` }if (backend === 'ollama') {- const result = await ollamaManager.pullModel(modelId, onProgress)+ const importSpec = getOllamaImportSpec(modelId)+ const result = importSpec+ ? await ollamaManager.importModelFromHfSafetensors(importSpec, onProgress)+ : await ollamaManager.pullModel(modelId, onProgress)if (result.success) refreshOllamaBackedProviders()return result}diff --git a/server/services/localLlm.test.js b/server/services/localLlm.test.jsindex d5db46f2cb..c7c46ed24c 100644--- a/server/services/localLlm.test.js+++ b/server/services/localLlm.test.js@@ -24,6 +24,7 @@ const mocks = vi.hoisted(() => ({getInstalledModels: vi.fn(async () => []),getModelCapabilities: vi.fn(async () => []),pullModel: vi.fn(async (id) => ({ success: true, modelId: id })),+ importModelFromHfSafetensors: vi.fn(async ({ modelId }) => ({ success: true, modelId })),deleteModel: vi.fn(async (id) => ({ success: true, modelId: id })),getLoadedModels: vi.fn(async () => []),getLastLoadedModelsError: vi.fn(() => null),@@ -224,6 +225,17 @@ describe('localLlm', () => {await svc.installModel('ollama', 'llama3.2');expect(mocks.ollama.pullModel).toHaveBeenCalledWith('llama3.2', undefined);});+ it('routes a curated Safetensors model through Ollama create instead of registry pull', async () => {+ const onProgress = vi.fn();+ await svc.installModel('ollama', 'orcarouter/qwen3.8-27b-uncensored-mlx:4bit', onProgress);+ expect(mocks.ollama.importModelFromHfSafetensors).toHaveBeenCalledWith({+ modelId: 'orcarouter/qwen3.8-27b-uncensored-mlx:4bit',+ repo: 'orcarouter/Qwen3.8-27B-Uncensored-MLX',+ subdir: '4-bit',+ minVersion: '0.19.0'+ }, onProgress);+ expect(mocks.ollama.pullModel).not.toHaveBeenCalled();+ });it('routes Ollama delete to deleteModel', async () => {await svc.deleteModel('ollama', 'llama3.2');expect(mocks.ollama.deleteModel).toHaveBeenCalledWith('llama3.2');diff --git a/server/services/ollamaManager.js b/server/services/ollamaManager.jsindex cc41cb26b0..4c1ea45be2 100644--- a/server/services/ollamaManager.js+++ b/server/services/ollamaManager.js@@ -14,10 +14,13 @@* DELETE /api/delete → { name }*/-import { homedir } from 'os'+import { homedir, tmpdir } from 'os'import { join, dirname } from 'path'-import { readdir, stat, link, unlink } from 'fs/promises'+import { createWriteStream } from 'fs'+import { readdir, stat, link, unlink, mkdtemp, rm } from 'fs/promises'import { createHash } from 'crypto'+import { Readable, Transform } from 'stream'+import { pipeline } from 'stream/promises'import { execFile, spawn } from '../lib/childProcess.js';import { promisify } from 'util'import { fetchWithTimeout } from '../lib/fetchWithTimeout.js'import { readResponseJson } from '../lib/readResponseJson.js'@@ -27,10 +30,12 @@ import {parseOllamaManifest, parseOllamaModelRef, ollamaManifestRelPath, digestToBlobFilename, buildModelfile,manifestBlobRefs, huggingFaceRegistryBase} from '../lib/localLlmDisk.js'-import { buildHfAuthHeaders } from '../lib/huggingfaceLora.js'+import { buildHfAuthHeaders, buildHfResolveUrl, HF_API } from '../lib/huggingfaceLora.js'import { isEmbeddingModel } from '../lib/localModelHeuristics.js'import { commandExists } from '../lib/commandExists.js'import { OLLAMA_AGENT_MIN_CONTEXT, OLLAMA_CONTEXT_ENV_VAR, withOllamaContextEnv } from '../lib/ollamaContext.js'+import { compareSemver } from '../lib/versionUtils.js'+import { isSafeHfRepoRelativePath } from '../lib/hfCache.js'const execFileAsync = promisify(execFile)const AVAILABILITY_CACHE_TTL_MS = 30_000@@ -63,6 +68,7 @@ const START_TIMEOUT_MS = 12_000const STOP_TIMEOUT_MS = 8_000const SERVICE_COMMAND_TIMEOUT_MS = 20_000const PROCESS_IDENTITY_TIMEOUT_MS = 2_000+const HF_IMPORT_METADATA_TIMEOUT_MS = 180_000const DEFAULT_CONFIG = {// Ollama uses OLLAMA_HOST (host:port, no scheme) by convention; also accept@@ -970,6 +976,124 @@ async function pullModel(modelId, onProgress) {return { success: false, error: lastError, modelId, ...(code ? { code } : {}) }}+function hfImportError(status, statusText) {+ if (status === 401 || status === 403) {+ return 'Hugging Face denied access. Accept the repository terms, then configure a Hugging Face token in Settings.'+ }+ return `Hugging Face request failed: ${status} ${statusText}`+}++async function downloadHfImportFile({ repo, remotePath, destination, headers, progress }) {+ const url = buildHfResolveUrl(repo, 'main', remotePath)+ const response = await fetchWithTimeout(url, { headers }, 0)+ if (!response.ok || !response.body) throw new Error(hfImportError(response.status, response.statusText))+ await ensureDir(dirname(destination))+ const tracker = new Transform({+ transform(chunk, _encoding, callback) {+ progress(chunk.length)+ callback(null, chunk)+ }+ })+ await pipeline(Readable.fromWeb(response.body), tracker, createWriteStream(destination))+}++/**+ * Download a curated Hugging Face Safetensors subdirectory and import it through+ * Ollama's supported `ollama create` path. The caller supplies only catalog-owned+ * recipes; arbitrary free-text ids continue through pullModel instead.+ *+ * @param {{ modelId: string, repo: string, subdir: string, minVersion?: string }} spec+ * @param {(p: { status: string, percent: number|null, completed?: number, total?: number, importing?: boolean }) => void} [onProgress]+ */+async function importModelFromHfSafetensors(spec, onProgress) {+ const { modelId, repo, subdir, minVersion = '0.19.0' } = spec+ if (!(await checkOllamaAvailable())) {+ return { success: false, error: 'Ollama not available', modelId }+ }+ const version = await getVersion()+ if (!version || compareSemver(version.replace(/^v/, ''), minVersion.replace(/^v/, '')) < 0) {+ return {+ success: false,+ error: `This MLX import requires Ollama ${minVersion} or newer${version ? ` (installed: ${version})` : ''}.`,+ modelId,+ code: 'OLLAMA_OUTDATED'+ }+ }+ const { getHfToken } = await import('../lib/hfToken.js')+ const token = await getHfToken()+ if (!token) {+ return {+ success: false,+ error: 'This gated model requires a Hugging Face token. Accept the repository terms, then configure a token in Settings.',+ modelId,+ code: 'HF_TOKEN_REQUIRED'+ }+ }+ if (!(await commandExists('ollama', ['--version']))) {+ return { success: false, error: 'The Ollama CLI is required to import Safetensors models.', modelId }+ }++ const headers = buildHfAuthHeaders(token)+ const metadataUrl = `${HF_API}/${repo}?blobs=true`+ const metadataResponse = await fetchWithTimeout(metadataUrl, { headers }, HF_IMPORT_METADATA_TIMEOUT_MS)+ .catch((err) => ({ _err: describeFetchError(err) }))+ if (metadataResponse._err) return { success: false, error: metadataResponse._err, modelId }+ if (!metadataResponse.ok) {+ return { success: false, error: hfImportError(metadataResponse.status, metadataResponse.statusText), modelId }+ }+ const metadata = await metadataResponse.json().catch(() => null)+ const prefix = `${subdir.replace(/\/+$/, '')}/`+ const files = (metadata?.siblings || [])+ .filter((file) => typeof file.rfilename === 'string' && file.rfilename.startsWith(prefix))+ .map((file) => ({+ remotePath: file.rfilename,+ relativePath: file.rfilename.slice(prefix.length),+ size: Number(file.lfs?.size ?? file.size) || 0+ }))+ .filter((file) => isSafeHfRepoRelativePath(file.relativePath))+ if (!files.some((file) => file.relativePath.endsWith('.safetensors')) || !files.some((file) => file.relativePath === 'config.json')) {+ return { success: false, error: `The ${subdir} checkpoint is incomplete or unavailable on Hugging Face.`, modelId }+ }++ 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 = 0+ let lastPercent = -1+ const reportBytes = (bytes) => {+ completed += bytes+ const percent = total > 0 ? Math.min(100, Math.floor((completed / total) * 100)) : null+ if (percent === lastPercent) return+ lastPercent = percent+ if (typeof onProgress === 'function') onProgress({ status: 'downloading MLX checkpoint', percent, completed, total })+ }+ const performImport = async () => {+ for (const file of files) {+ await downloadHfImportFile({+ repo,+ remotePath: file.remotePath,+ destination: join(modelDir, ...file.relativePath.split('/')),+ headers,+ progress: reportBytes+ })+ }+ const modelfile = join(tempRoot, 'Modelfile')+ await atomicWrite(modelfile, `FROM ${modelDir}\n`)+ if (typeof onProgress === 'function') {+ onProgress({ status: 'importing checkpoint into Ollama', percent: null, importing: true })+ }+ await execFileAsync('ollama', ['create', modelId, '-f', modelfile], { timeout: 0, maxBuffer: 64 * 1024 * 1024 })+ installedModels = null+ console.log(`✅ Ollama Safetensors import complete: ${modelId}`)+ return { success: true, modelId }+ }+ return performImport()+ .catch((err) => ({ success: false, error: err.stderr || err.message, modelId }))+ .finally(() => rm(tempRoot, { recursive: true, force: true }).catch((err) => {+ console.error(`⚠️ Ollama Safetensors import cleanup failed: ${err.message}`)+ }))+}+/*** Detect the Go-runtime deadline Ollama reports when a registry request outlives* its internal per-request budget: `context deadline exceeded`. Distinctive@@ -1418,6 +1542,7 @@ export {getLastLoadedModelsError,unloadModel,pullModel,+ importModelFromHfSafetensors,deleteModel,getStatus,getBaseUrl,diff --git a/server/services/ollamaManager.test.js b/server/services/ollamaManager.test.jsindex 1577c7e7c2..e7d2e9a0fd 100644--- a/server/services/ollamaManager.test.js+++ b/server/services/ollamaManager.test.js@@ -560,6 +560,98 @@ describe('ollamaManager.isBootstrapConflictError', () => {})})+describe('ollamaManager curated Hugging Face Safetensors import', () => {+ const spec = {+ modelId: 'example/qwen-mlx:4bit',+ repo: 'example/Qwen-MLX',+ subdir: '4-bit',+ minVersion: '0.19.0'+ }++ afterEach(() => {+ hfTokenMock.token = null+ execMock.impl = () => {}+ vi.unstubAllGlobals()+ })++ it('downloads the selected checkpoint and creates a local Ollama model', async () => {+ hfTokenMock.token = 'hf_example_token'+ const config = Buffer.from('{"model_type":"qwen3_8"}')+ const weights = Buffer.from('example safetensors bytes')+ const requested = []+ vi.stubGlobal('fetch', vi.fn(async (url, init) => {+ const href = String(url)+ requested.push({ href, init })+ 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: config.length },+ { rfilename: '4-bit/model.safetensors', lfs: { size: weights.length } },+ { rfilename: '4-bit/../outside.safetensors', lfs: { size: 10 } },+ { rfilename: '4-bit/..\\outside.safetensors', lfs: { size: 10 } },+ { rfilename: '8-bit/model.safetensors', lfs: { size: 999 } }+ ] }), { status: 200, headers: { 'Content-Type': 'application/json' } })+ }+ if (href.includes('/resolve/main/4-bit/config.json')) return new Response(config)+ if (href.includes('/resolve/main/4-bit/model.safetensors')) return new Response(weights)+ throw new Error(`unexpected fetch: ${href}`)+ }))+ let createCall+ execMock.impl = (cmd, args, _opts, cb) => {+ if (cmd === 'ollama' && args.join(' ') === '--version') return cb(null, { stdout: 'ollama 0.31.0', stderr: '' })+ if (cmd === 'ollama' && args[0] === 'create') {+ createCall = { cmd, args }+ readFile(args[3], 'utf8').then((modelfile) => {+ createCall.modelfile = modelfile+ cb(null, { stdout: '', stderr: '' })+ }, cb)+ return undefined+ }+ return cb(new Error(`unexpected exec: ${cmd} ${args.join(' ')}`))+ }+ const onProgress = vi.fn()+ const { importModelFromHfSafetensors } = await loadManager()++ const result = await importModelFromHfSafetensors(spec, onProgress)++ expect(result).toEqual({ success: true, modelId: spec.modelId })+ expect(createCall.args.slice(0, 2)).toEqual(['create', spec.modelId])+ expect(createCall.modelfile.replace(/\\/g, '/')).toMatch(/^FROM .*\/model\n$/)+ await expect(stat(createCall.args[3])).rejects.toMatchObject({ code: 'ENOENT' })+ expect(requested.some(({ href }) => href.includes('8-bit/model.safetensors'))).toBe(false)+ expect(requested.some(({ href }) => href.includes('outside.safetensors'))).toBe(false)+ expect(requested.filter(({ href }) => href.includes('huggingface.co'))+ .every(({ init }) => init?.headers?.Authorization === 'Bearer hf_example_token')).toBe(true)+ expect(onProgress).toHaveBeenCalledWith(expect.objectContaining({ status: 'downloading MLX checkpoint', percent: 100 }))+ expect(onProgress).toHaveBeenCalledWith(expect.objectContaining({ importing: true }))+ })++ it('fails before downloading when the gated repository has no token', async () => {+ stubFetch([])+ const { importModelFromHfSafetensors } = await loadManager()++ const result = await importModelFromHfSafetensors(spec)++ expect(result).toMatchObject({ success: false, code: 'HF_TOKEN_REQUIRED' })+ expect(globalThis.fetch).toHaveBeenCalledTimes(2) // availability + installed-version probes only+ })++ it('requires an Ollama release with Safetensors create support', async () => {+ vi.stubGlobal('fetch', vi.fn(async (url) => {+ if (String(url).endsWith('/api/version')) {+ const body = { version: '0.18.9' }+ return { ok: true, status: 200, json: async () => body, text: async () => JSON.stringify(body) }+ }+ throw new Error(`unexpected fetch: ${url}`)+ }))+ const { importModelFromHfSafetensors } = await loadManager()++ const result = await importModelFromHfSafetensors(spec)++ expect(result).toMatchObject({ success: false, code: 'OLLAMA_OUTDATED' })+ })+})+describe('ollamaManager.startPersistentService bootstrap recovery (homebrew)', () => {let restorePlatform = () => {}beforeEach(() => {