Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat(local-llm): migrate copies GGUF weights locally instead of re-downloading

Adam Eivya4a63d18eb38
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index f09a65feea..de07285108 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -1,7 +1,7 @@
# Unreleased Changes
## Added
-- **[local-llm-backend-management] Local LLMs — pick a backend at setup, manage models, and migrate between Ollama and LM Studio.** Setup now asks whether you want **Ollama** or **LM Studio** for local on-device models and installs the chosen one if it's missing (`scripts/setup-llm.js`, wired into `npm run setup`; `npm run setup:llm` to run it standalone). The choice is recorded as `LLM_BACKEND` in `.env`, and the matching AI provider is auto-enabled on boot. A new **Settings → Local LLMs** tab (reachable from the sidebar, ⌘K, and voice) shows both backends' status, lets you **switch** the active backend or **migrate** to the other (re-provisioning your installed models on the target, since Ollama/LM Studio weights aren't portable on disk — mirrors the Docker↔native Postgres flow), and manages models like the LoRA/Media-Models pages do: a curated cross-backend catalog with search, one-click install, free-text "pull by name", and delete — with live pull progress over the `localLlm:progress` socket. Server side: `server/services/ollamaManager.js` (native Ollama HTTP API), `server/services/localLlm.js` (unified orchestration + `.env` marker + provider enabling + migrate), `server/lib/localLlmCatalog.js` (pure catalog + install-id mapping), and `/api/local-llm/*` routes.
+- **[local-llm-backend-management] Local LLMs — pick a backend at setup, manage models, and migrate between Ollama and LM Studio.** Setup now asks whether you want **Ollama** or **LM Studio** for local on-device models and installs the chosen one if it's missing (`scripts/setup-llm.js`, wired into `npm run setup`; `npm run setup:llm` to run it standalone). The choice is recorded as `LLM_BACKEND` in `.env`, and the matching AI provider is auto-enabled on boot. A new **Settings → Local LLMs** tab (reachable from the sidebar, ⌘K, and voice) shows both backends' status, lets you **switch** the active backend or **migrate** to the other (the GGUF weights are portable — only the on-disk *layout* differs (Ollama's content-addressed blob store vs LM Studio's plain file tree), so migrate **copies each model's GGUF across locally with no re-download** where it can, and re-pulls the cross-backend catalog equivalent only for models it can't copy — LM Studio MLX-format, sharded, or multimodal — mirrors the Docker↔native Postgres flow), and manages models like the LoRA/Media-Models pages do: a curated cross-backend catalog with search, one-click install, free-text "pull by name", and delete — with live pull progress over the `localLlm:progress` socket. Server side: `server/services/ollamaManager.js` (native Ollama HTTP API + local GGUF import via `/api/create`), `server/services/localLlm.js` (unified orchestration + `.env` marker + provider enabling + migrate), `server/lib/localLlmCatalog.js` (pure catalog + install-id mapping), `server/lib/localLlmDisk.js` (pure on-disk GGUF/manifest reasoning for the local-copy fast-path), and `/api/local-llm/*` routes.
- **[codex5-onboarding-capability-map] Capabilities page — every connected system at a glance.** A new Capabilities page (under System) shows the status of each integration on one screen: AI Providers, Calendar, Brain & Memory, Voice, Tailscale & HTTPS, Genome & Health, Telegram, Messages, and Apps & Processes. Every row says whether it's set up and healthy — Ready, Degraded, Error, or Not set up — and links straight to its settings, so the page works as both a first-run setup checklist and a quick runtime health overview. Reachable from the sidebar, ⌘K, and voice.
- **Federated media collections + per-category sync integrity.** Media collections are now a first-class peer-sync record kind (`mediaCollection` in `PEER_SUBSCRIBABLE_KINDS`, schema-version-gated at `mediaCollections: 1`): they auto-subscribe on create, push per-record on edit, and propagate deletes via tombstones — collections now reach parity between federated machines the way universes/series already did, instead of only riding along as `linkedCollection` cargo or the opt-in 60s snapshot. Required adding soft-delete to collections (`deleted`/`deletedAt`; `deleteCollection` marks instead of splicing; `listCollections({ includeDeleted })`; tombstone-aware LWW merge; tombstone GC), so a delete on one node can't be resurrected by a reverse-subscribed peer. Synced images now carry their **generation prompts**: the peer asset manifest advertises a canonical gen-params-only `sidecarSha256` (machine-local hash-cache stripped so it converges across peers), and the asset-pull worker fetches each image's `.metadata.json` sidecar alongside the bytes — fixing images that previously landed in "Unsorted" with no prompts. A new per-category **sync integrity** surface (`GET /api/peer-sync/manifest`, `GET /api/peer-sync/integrity`, pure `computeRecordIntegrity` diff) drives a `SyncBadge` on every Universe / Series / Media-Collection row (in-sync / diverged / assets-missing / local-only / on-peer-only / "not syncing — enable?") plus a deep-linkable `SyncDetailDrawer` (`/…/:id/sync`) showing the per-peer breakdown, previews, and manual actions: **Sync to peer** (`POST /sync-record`, force-push bypassing the unchanged-hash short-circuit), **Sync now** (`POST /sync-now`, backfill-subscribe + retry a peer's pending pushes), and **Pull missing prompts** (`POST /pull-metadata` + a button on the Unsorted view that backfills sidecars from online peers). `mediaCollections` sync stays **opt-in** per peer (default off); the badge surfaces a clear "enable?" state rather than flipping the default.
- **Manual tombstone GC trigger.** The 60s `syncOrchestrator` sweep buffers tombstones for 24h to give every peer time to ack a deletion before the bytes leave disk — fine for normal use, painful right after a mass-delete. New `POST /api/sync/tombstones/sweep` (Zod-validated optional `{ graceMs }` clamped to `[0, 24h]`) calls `sweepTombstones({ graceMs })` so callers can shrink the buffer; the per-kind null-cutoff refusal (snapshot-mode peer with no per-record subscription) still fires independently of `graceMs` to preserve resurrection safety. Companion `GET /api/sync/tombstones/status` returns the dry-run refusal status without invoking the prune helpers. A new "GC tombstones now" section on the Instances page (between SelfCard/AddPeer and the peers list) POSTs `graceMs: 0` and surfaces per-kind prune counts + any refusals in a toast; the button is disabled only when every kind is refused. `scripts/gc-tombstones-now.js` is the equivalent CLI path (dry-run by default; `--apply` to prune) for headless cleanups — uses the same "stop the server first, single-process write-tail isn't cross-process safe" wording as `cleanup-test-data.js`. `sweepTombstones` now returns `{ universes, series, issues, refused }` so the manual trigger can explain why a kind didn't shrink. The orchestrator path keeps the 24h default behavior unchanged.
diff --git a/client/src/components/settings/LocalLlmTab.jsx b/client/src/components/settings/LocalLlmTab.jsx
index c9c7d9eceb..d69a49f737 100644
--- a/client/src/components/settings/LocalLlmTab.jsx
+++ b/client/src/components/settings/LocalLlmTab.jsx
@@ -49,7 +49,7 @@ function BackendCard({ backend, status, isActive, busy, actionInProgress, runAct
onClick={() => setConfirmAction({
type: 'migrate',
label: `Migrate to ${backend.label}?`,
- detail: `Re-installs the models you have on ${labelFor(other)} onto ${backend.label} (local model weights aren't portable between backends), then makes ${backend.label} the active backend. Large pulls can take a while.`,
+ detail: `Provisions the models you have on ${labelFor(other)} onto ${backend.label}, then makes ${backend.label} the active backend. GGUF weights are copied locally (no re-download) where possible; anything that can't be copied (LM Studio MLX-format, sharded, or multimodal models) is re-pulled, which can take a while.`,
action: () => runAction(`migrate-${backend.id}`, () => migrateLocalLlmBackend(backend.id), `Migrated to ${backend.label}`)
})}
disabled={busy}
diff --git a/server/lib/README.md b/server/lib/README.md
index 5fdb3c3ee0..ddbf25ae42 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -144,6 +144,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `capabilityMap.js` | Pure row builders for the Capability Map (per-integration status tiers + rollup); fed by `routes/capabilities.js`. |
| `civitai.js` | Civitai URL parsing + API client. |
| `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). |
| `issueLength.js` | Per-issue size targets fed into text stages. |
| `mediaItemKey.js` | `<kind>:<ref>` key vocabulary for media items. |
| `navManifest.js` | Single source of truth for nav (`⌘K` palette + voice). Add an entry when you add a page. |
diff --git a/server/lib/index.js b/server/lib/index.js
index b9ff629507..13c7034322 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -114,6 +114,7 @@ export * from './curatedGenomeMarkers.js';
export * from './capabilityMap.js';
export * from './civitai.js';
export * from './localLlmCatalog.js';
+export * from './localLlmDisk.js';
export * from './issueLength.js';
export * from './mediaItemKey.js';
export * from './navManifest.js';
diff --git a/server/lib/localLlmCatalog.js b/server/lib/localLlmCatalog.js
index f4c5b35f73..373bf54476 100644
--- a/server/lib/localLlmCatalog.js
+++ b/server/lib/localLlmCatalog.js
@@ -1,13 +1,14 @@
// Curated cross-backend catalog of popular local LLMs.
//
-// PortOS supports two local-LLM backends — Ollama (native blob format) and
-// LM Studio (raw GGUF). Their model identifiers differ (`llama3.2` vs
-// `lmstudio-community/Llama-3.2-3B-Instruct-GGUF`) and the weights are NOT
-// interchangeable on disk, so "migrating" between them means re-provisioning
-// the equivalent model on the other backend. This catalog is the mapping
-// table that makes both the in-UI install picker and the migrate flow work
-// without guessing: each entry carries the canonical id for whichever
-// backend(s) ship a well-known build of that model.
+// PortOS supports two local-LLM backends — Ollama (content-addressed blob
+// store) and LM Studio (plain GGUF files). Their model identifiers differ
+// (`llama3.2` vs `lmstudio-community/Llama-3.2-3B-Instruct-GGUF`). The GGUF
+// weights themselves ARE portable; only the on-disk layout differs, so the
+// migrate flow copies the weights across locally when it can (see
+// `localLlmDisk.js`) and re-pulls the equivalent only when it can't. This
+// catalog is the mapping table that makes both the in-UI install picker and
+// the migrate re-pull fallback work without guessing: each entry carries the
+// canonical id for whichever backend(s) ship a well-known build of that model.
//
// This module is pure (no I/O, no network) so it can be unit-tested and
// imported anywhere. The installed-state overlay is applied by the caller
diff --git a/server/lib/localLlmDisk.js b/server/lib/localLlmDisk.js
new file mode 100644
index 0000000000..1310efab82
--- /dev/null
+++ b/server/lib/localLlmDisk.js
@@ -0,0 +1,133 @@
+// Pure on-disk reasoning for the Ollama↔LM Studio "copy weights locally instead
+// of re-downloading" migrate fast-path.
+//
+// Both backends store the SAME GGUF weights — only the on-disk *layout* differs:
+// • LM Studio: plain files at <models>/<publisher>/<repo>/<file>.gguf
+// (and Apple **MLX** models, which are NOT GGUF and have no
+// Ollama equivalent)
+// • Ollama: a content-addressed blob store —
+// <models>/blobs/sha256-<hash> referenced by a JSON manifest at
+// <models>/manifests/<registry>/<namespace>/<name>/<tag>
+//
+// So a single-file GGUF text model can be imported across backends with no
+// network pull. Multimodal (separate mmproj projector), sharded (`-00001-of-`),
+// and MLX models are the exceptions the caller routes to re-pull / skip.
+//
+// This module is pure (no fs, no network) so it is unit-testable; the managers
+// do the actual reads/copies using these helpers.
+
+// Ollama manifest layer media types.
+export const OLLAMA_MODEL_MEDIATYPE = 'application/vnd.ollama.image.model';
+export const OLLAMA_PROJECTOR_MEDIATYPE = 'application/vnd.ollama.image.projector';
+
+/**
+ * Extract the weight + projector blob digests from a parsed Ollama manifest.
+ * @param {object} manifest
+ * @returns {{ modelDigest: string|null, projectorDigest: string|null }}
+ */
+export function parseOllamaManifest(manifest) {
+ const layers = Array.isArray(manifest?.layers) ? manifest.layers : [];
+ const find = (mt) => layers.find((l) => l?.mediaType === mt)?.digest || null;
+ return { modelDigest: find(OLLAMA_MODEL_MEDIATYPE), projectorDigest: find(OLLAMA_PROJECTOR_MEDIATYPE) };
+}
+
+/** `sha256:abc123` → `sha256-abc123` (Ollama's blob filename form). */
+export function digestToBlobFilename(digest) {
+ return String(digest || '').replace(':', '-');
+}
+
+/**
+ * Parse an Ollama model ref into registry/namespace/name/tag, mirroring how
+ * Ollama lays manifests out on disk. Bare names default to the
+ * `registry.ollama.ai/library/<name>:latest` form.
+ * @param {string} id e.g. `llama3.2:latest`, `gpt-oss:20b`, `myorg/m:tag`
+ */
+export function parseOllamaModelRef(id) {
+ let rest = String(id || '').trim();
+ if (!rest) return { registry: 'registry.ollama.ai', namespace: 'library', name: '', tag: 'latest' };
+
+ // Split off the tag: the LAST `:` only when what follows has no `/` (so a
+ // `host:port/...` registry prefix isn't mistaken for a tag).
+ let tag = 'latest';
+ const colon = rest.lastIndexOf(':');
+ if (colon !== -1 && !rest.slice(colon + 1).includes('/')) {
+ tag = rest.slice(colon + 1) || 'latest';
+ rest = rest.slice(0, colon);
+ }
+
+ const parts = rest.split('/').filter(Boolean);
+ let registry = 'registry.ollama.ai';
+ let namespace = 'library';
+ let name = rest;
+ if (parts.length === 1) {
+ name = parts[0];
+ } else if (parts.length === 2) {
+ [namespace, name] = parts;
+ } else {
+ // registry / namespace / name (extra path segments fold into the namespace)
+ registry = parts[0];
+ name = parts[parts.length - 1];
+ namespace = parts.slice(1, -1).join('/');
+ }
+ return { registry, namespace, name, tag };
+}
+
+/** Relative manifest path (POSIX-joined) for a parsed ref. */
+export function ollamaManifestRelPath({ registry, namespace, name, tag }) {
+ return ['manifests', registry, namespace, name, tag].join('/');
+}
+
+/** A filesystem-safe Ollama model name for `ollama create` / `/api/create`. */
+export function sanitizeOllamaName(id) {
+ const base = String(id || '').split('/').pop() || '';
+ const cleaned = base.trim().toLowerCase().replace(/[^a-z0-9._:-]/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '');
+ return cleaned || 'imported-model';
+}
+
+/** Is this directory an MLX model (safetensors, no GGUF)? MLX ≠ GGUF. */
+export function dirIsMlx(filenames = []) {
+ const lower = filenames.map((f) => String(f).toLowerCase());
+ const hasGguf = lower.some((f) => f.endsWith('.gguf'));
+ const hasSafetensors = lower.some((f) => f.endsWith('.safetensors'));
+ return hasSafetensors && !hasGguf;
+}
+
+const isProjectorName = (f) => /(^|[-_./])(mmproj|projector)/i.test(f);
+const isShardName = (f) => /-\d{5}-of-\d{5}\.gguf$/i.test(f);
+
+/**
+ * Pick the primary weights GGUF from a directory listing: skip projector files,
+ * prefer the first shard of a sharded model, otherwise the first `.gguf`.
+ * @returns {string|null} the chosen basename
+ */
+export function selectPrimaryGguf(filenames = []) {
+ const ggufs = filenames.filter((f) => /\.gguf$/i.test(f) && !isProjectorName(f));
+ if (ggufs.length === 0) return null;
+ const firstShard = ggufs.find((f) => /-00001-of-\d{5}\.gguf$/i.test(f));
+ return firstShard || ggufs[0];
+}
+
+/** Find the multimodal projector GGUF in a listing, if any. */
+export function selectProjectorGguf(filenames = []) {
+ return filenames.find((f) => /\.gguf$/i.test(f) && isProjectorName(f)) || null;
+}
+
+/** True when the chosen GGUF is one part of a multi-file (sharded) model. */
+export function isShardedGguf(basename) {
+ return isShardName(String(basename || ''));
+}
+
+/**
+ * Split an LM Studio model id into its on-disk `<publisher>/<repo>` parts.
+ * Bare ids (no `/`) land under an `imported` publisher.
+ */
+export function lmStudioPublisherRepo(lmstudioId) {
+ const parts = String(lmstudioId || '').split('/').filter(Boolean);
+ if (parts.length >= 2) return { publisher: parts[0], repo: parts.slice(1).join('-') };
+ return { publisher: 'imported', repo: parts[0] || 'model' };
+}
+
+/** A `FROM <gguf>` Modelfile body for importing a local GGUF into Ollama. */
+export function buildModelfile(ggufPath) {
+ return `FROM ${ggufPath}\n`;
+}
diff --git a/server/lib/localLlmDisk.test.js b/server/lib/localLlmDisk.test.js
new file mode 100644
index 0000000000..0232ccd0ca
--- /dev/null
+++ b/server/lib/localLlmDisk.test.js
@@ -0,0 +1,108 @@
+import { describe, it, expect } from 'vitest';
+import {
+ parseOllamaManifest, digestToBlobFilename, parseOllamaModelRef, ollamaManifestRelPath,
+ sanitizeOllamaName, dirIsMlx, selectPrimaryGguf, selectProjectorGguf, isShardedGguf,
+ lmStudioPublisherRepo, buildModelfile,
+ OLLAMA_MODEL_MEDIATYPE, OLLAMA_PROJECTOR_MEDIATYPE
+} from './localLlmDisk.js';
+
+describe('localLlmDisk', () => {
+ describe('parseOllamaManifest', () => {
+ it('extracts the model + projector digests by media type', () => {
+ const manifest = {
+ layers: [
+ { mediaType: 'application/vnd.ollama.image.template', digest: 'sha256:tpl' },
+ { mediaType: OLLAMA_MODEL_MEDIATYPE, digest: 'sha256:weights' },
+ { mediaType: OLLAMA_PROJECTOR_MEDIATYPE, digest: 'sha256:proj' }
+ ]
+ };
+ expect(parseOllamaManifest(manifest)).toEqual({ modelDigest: 'sha256:weights', projectorDigest: 'sha256:proj' });
+ });
+ it('returns nulls for a text-only model and a malformed manifest', () => {
+ expect(parseOllamaManifest({ layers: [{ mediaType: OLLAMA_MODEL_MEDIATYPE, digest: 'sha256:w' }] }))
+ .toEqual({ modelDigest: 'sha256:w', projectorDigest: null });
+ expect(parseOllamaManifest(null)).toEqual({ modelDigest: null, projectorDigest: null });
+ expect(parseOllamaManifest({})).toEqual({ modelDigest: null, projectorDigest: null });
+ });
+ });
+
+ describe('digestToBlobFilename', () => {
+ it('rewrites the sha256 separator', () => {
+ expect(digestToBlobFilename('sha256:abc123')).toBe('sha256-abc123');
+ expect(digestToBlobFilename(null)).toBe('');
+ });
+ });
+
+ describe('parseOllamaModelRef', () => {
+ it('defaults a bare name to library/<name>:latest', () => {
+ expect(parseOllamaModelRef('llama3.2')).toEqual({ registry: 'registry.ollama.ai', namespace: 'library', name: 'llama3.2', tag: 'latest' });
+ });
+ it('keeps a meaningful tag like 20b', () => {
+ expect(parseOllamaModelRef('gpt-oss:20b')).toEqual({ registry: 'registry.ollama.ai', namespace: 'library', name: 'gpt-oss', tag: '20b' });
+ });
+ it('handles namespace/name:tag', () => {
+ expect(parseOllamaModelRef('myorg/mymodel:v2')).toEqual({ registry: 'registry.ollama.ai', namespace: 'myorg', name: 'mymodel', tag: 'v2' });
+ });
+ it('does not mistake a registry host:port for a tag', () => {
+ expect(parseOllamaModelRef('localhost:5000/team/m')).toEqual({ registry: 'localhost:5000', namespace: 'team', name: 'm', tag: 'latest' });
+ });
+ });
+
+ describe('ollamaManifestRelPath', () => {
+ it('joins the manifest path the way Ollama lays it out', () => {
+ expect(ollamaManifestRelPath(parseOllamaModelRef('llama3.2:latest')))
+ .toBe('manifests/registry.ollama.ai/library/llama3.2/latest');
+ });
+ });
+
+ describe('sanitizeOllamaName', () => {
+ it('lowercases and strips path + bad chars', () => {
+ expect(sanitizeOllamaName('lmstudio-community/Llama-3.2-3B-Instruct-GGUF')).toBe('llama-3.2-3b-instruct-gguf');
+ expect(sanitizeOllamaName('My Model!!')).toBe('my-model');
+ expect(sanitizeOllamaName('')).toBe('imported-model');
+ });
+ });
+
+ describe('dirIsMlx', () => {
+ it('flags safetensors-only dirs and clears GGUF dirs', () => {
+ expect(dirIsMlx(['model.safetensors', 'config.json', 'tokenizer.json'])).toBe(true);
+ expect(dirIsMlx(['gpt-oss-20b-MXFP4.gguf'])).toBe(false);
+ expect(dirIsMlx(['model.safetensors', 'extra.gguf'])).toBe(false); // has a gguf → usable
+ expect(dirIsMlx([])).toBe(false);
+ });
+ });
+
+ describe('selectPrimaryGguf / selectProjectorGguf', () => {
+ it('picks the weights gguf and skips the projector', () => {
+ const files = ['llava-v1.5-7b-mmproj-f16.gguf', 'llava-v1.5-7b-Q4_K_M.gguf', 'README.md'];
+ expect(selectPrimaryGguf(files)).toBe('llava-v1.5-7b-Q4_K_M.gguf');
+ expect(selectProjectorGguf(files)).toBe('llava-v1.5-7b-mmproj-f16.gguf');
+ });
+ it('prefers the first shard of a sharded model', () => {
+ const files = ['model-00002-of-00003.gguf', 'model-00001-of-00003.gguf', 'model-00003-of-00003.gguf'];
+ expect(selectPrimaryGguf(files)).toBe('model-00001-of-00003.gguf');
+ expect(isShardedGguf(selectPrimaryGguf(files))).toBe(true);
+ });
+ it('returns null when there is no weights gguf', () => {
+ expect(selectPrimaryGguf(['only-mmproj.gguf', 'notes.txt'])).toBe(null);
+ expect(selectProjectorGguf(['weights.gguf'])).toBe(null);
+ });
+ it('single plain gguf is not flagged sharded', () => {
+ expect(isShardedGguf('mistral-7b-instruct-Q4_K_M.gguf')).toBe(false);
+ });
+ });
+
+ describe('lmStudioPublisherRepo', () => {
+ it('splits publisher/repo and falls back for bare ids', () => {
+ expect(lmStudioPublisherRepo('lmstudio-community/Llama-3.2-3B-Instruct-GGUF'))
+ .toEqual({ publisher: 'lmstudio-community', repo: 'Llama-3.2-3B-Instruct-GGUF' });
+ expect(lmStudioPublisherRepo('justaname')).toEqual({ publisher: 'imported', repo: 'justaname' });
+ });
+ });
+
+ describe('buildModelfile', () => {
+ it('emits a FROM line for a local gguf path', () => {
+ expect(buildModelfile('/abs/path/model.gguf')).toBe('FROM /abs/path/model.gguf\n');
+ });
+ });
+});
diff --git a/server/routes/localLlm.js b/server/routes/localLlm.js
index ab4630a0c5..8346243585 100644
--- a/server/routes/localLlm.js
+++ b/server/routes/localLlm.js
@@ -95,7 +95,8 @@ router.post('/switch', asyncHandler(async (req, res) => {
res.json(result)
}))
-// POST /api/local-llm/migrate — re-provision models on target, then switch
+// POST /api/local-llm/migrate — provision models on target (copy GGUF locally
+// where possible, else re-pull), then switch the active backend
router.post('/migrate', asyncHandler(async (req, res) => {
const { to } = validateRequest(localLlmSwitchSchema, req.body)
const emit = emitter(req)
diff --git a/server/services/lmStudioManager.js b/server/services/lmStudioManager.js
index fe815e4fdf..b1508cb8ae 100644
--- a/server/services/lmStudioManager.js
+++ b/server/services/lmStudioManager.js
@@ -5,8 +5,14 @@
* Provides model discovery, loading, unloading, and downloading.
*/
+import { homedir } from 'os'
+import { join } from 'path'
+import { readdir, stat, mkdir, copyFile } from 'fs/promises'
import { cosEvents } from './cosEvents.js'
import { fetchWithTimeout } from '../lib/fetchWithTimeout.js'
+import {
+ dirIsMlx, selectPrimaryGguf, selectProjectorGguf, isShardedGguf, lmStudioPublisherRepo
+} from '../lib/localLlmDisk.js'
const AVAILABILITY_CACHE_TTL_MS = 30_000
const DEFAULT_REQUEST_TIMEOUT_MS = 30_000
@@ -435,6 +441,75 @@ function resetCache() {
lastCheckAt = null
}
+// ---- local-disk introspection / import (migrate fast-path) ------------------
+
+const dirExists = (p) => stat(p).then((s) => s.isDirectory()).catch(() => false)
+
+/** LM Studio's models root — first of the two known locations that exists. */
+async function getModelsDir() {
+ const candidates = [
+ process.env.LM_STUDIO_MODELS_DIR,
+ join(homedir(), '.lmstudio', 'models'),
+ join(homedir(), '.cache', 'lm-studio', 'models')
+ ].filter(Boolean)
+ for (const dir of candidates) {
+ if (await dirExists(dir)) return dir
+ }
+ return candidates[1] // sensible default even if it doesn't exist yet
+}
+
+/**
+ * Locate an installed LM Studio model's files on disk (no network). The model
+ * id maps directly onto the `<publisher>/<repo>` folder. MLX models (safetensors,
+ * no GGUF) return `{ isMlx: true, ggufPath: null }` so the caller routes them to
+ * re-pull instead of a (impossible) file copy.
+ * @returns {Promise<{ ggufPath: string|null, projectorPath: string|null, isMlx: boolean, isSharded: boolean }|null>}
+ */
+async function resolveLocalModel(modelId) {
+ const modelsDir = await getModelsDir()
+ const dir = join(modelsDir, ...String(modelId || '').split('/'))
+ if (!(await dirExists(dir))) return null
+ const files = await readdir(dir).catch(() => [])
+ if (dirIsMlx(files)) return { ggufPath: null, projectorPath: null, isMlx: true, isSharded: false }
+ const primary = selectPrimaryGguf(files)
+ if (!primary) return null
+ const projector = selectProjectorGguf(files)
+ return {
+ ggufPath: join(dir, primary),
+ projectorPath: projector ? join(dir, projector) : null,
+ isMlx: false,
+ isSharded: isShardedGguf(primary)
+ }
+}
+
+/**
+ * Copy a local GGUF into LM Studio's model tree (no download). LM Studio indexes
+ * loose GGUF files dropped under `<publisher>/<repo>/` on its next scan.
+ * @param {{ lmstudioId: string, ggufPath: string, projectorPath?: string|null }} args
+ * @returns {Promise<{ success: boolean, modelId?: string, error?: string }>}
+ */
+async function importModelFromGguf({ lmstudioId, ggufPath, projectorPath }) {
+ const modelsDir = await getModelsDir()
+ const { publisher, repo } = lmStudioPublisherRepo(lmstudioId)
+ const destDir = join(modelsDir, publisher, repo)
+ const r = await mkdir(destDir, { recursive: true })
+ .then(async () => {
+ const base = ggufPath.split('/').pop()
+ const destName = /\.gguf$/i.test(base) ? base : `${repo}.gguf`
+ await copyFile(ggufPath, join(destDir, destName))
+ if (projectorPath) {
+ const projBase = projectorPath.split('/').pop()
+ await copyFile(projectorPath, join(destDir, /\.gguf$/i.test(projBase) ? projBase : `${repo}-mmproj.gguf`))
+ }
+ })
+ .then(() => ({ ok: true }))
+ .catch((err) => ({ _err: err.message }))
+ if (r._err) return { success: false, error: r._err, modelId: lmstudioId }
+ resetCache()
+ console.log(`📦 LM Studio import (local): ${lmstudioId} ← ${ggufPath}`)
+ return { success: true, modelId: lmstudioId }
+}
+
export {
checkLMStudioAvailable,
getLoadedModels,
@@ -448,5 +523,8 @@ export {
getStatus,
updateConfig,
resetCache,
+ getModelsDir,
+ resolveLocalModel,
+ importModelFromGguf,
DEFAULT_CONFIG
}
diff --git a/server/services/localLlm.js b/server/services/localLlm.js
index 309e8d8d37..045c13c4db 100644
--- a/server/services/localLlm.js
+++ b/server/services/localLlm.js
@@ -8,9 +8,12 @@
* matching aiToolkit provider (`ollama` / `lmstudio`) is enabled whenever a
* backend becomes active.
*
- * Weights are NOT interchangeable on disk between the two backends, so
- * "migrate" re-provisions the equivalent model on the target backend (via the
- * cross-backend catalog) and then flips the active marker.
+ * The GGUF weights ARE portable between the two backends — only the on-disk
+ * layout differs (Ollama's content-addressed blob store vs LM Studio's plain
+ * file tree). So "migrate" copies each model's GGUF across locally (no
+ * download) when it can, and re-pulls the cross-backend catalog equivalent only
+ * for models it can't copy (LM Studio MLX-format, sharded, or multimodal), then
+ * flips the active marker. See `server/lib/localLlmDisk.js` for the disk logic.
*/
import { execFile } from 'child_process'
@@ -19,6 +22,7 @@ import { readFileSync, writeFileSync } from 'fs'
import { join } from 'path'
import { PATHS } from '../lib/fileUtils.js'
import { isBackend, mapModelToBackend } from '../lib/localLlmCatalog.js'
+import { sanitizeOllamaName } from '../lib/localLlmDisk.js'
import * as ollamaManager from './ollamaManager.js'
import * as lmStudioManager from './lmStudioManager.js'
import { getProviderById, updateProvider } from './providers.js'
@@ -228,9 +232,42 @@ export async function switchBackend(to) {
}
/**
- * Migrate to a backend: re-provision the source backend's installed models on
- * the target (weights aren't portable), then flip the active marker. Per-model
- * results are reported; an individual failure doesn't abort the switch.
+ * Try to provision a single source model on the target WITHOUT downloading, by
+ * copying its GGUF weights across the two on-disk layouts (the underlying GGUF
+ * is the same; only Ollama's content-addressed blob store vs LM Studio's plain
+ * file tree differ). Returns a per-model result on success, or `null` to tell
+ * the caller to fall back to a re-pull (no local file, MLX-only, multi-file
+ * sharded, a multimodal projector we can't carry into Ollama, or a copy error).
+ */
+async function tryLocalImport(to, model, targetId, resolved, onProgress) {
+ // Fast path requires a single-file GGUF on disk. MLX (no GGUF) and sharded
+ // models fall through; a separate projector can be copied to LM Studio but
+ // not cleanly imported into Ollama, so that case re-pulls too.
+ if (!resolved?.ggufPath || resolved.isSharded) return null
+ if (to === 'ollama' && resolved.projectorPath) return null
+
+ const name = to === 'ollama'
+ ? sanitizeOllamaName(targetId || model.id)
+ : (targetId || `imported/${model.id.split('/').pop()}`)
+ onProgress({ event: 'start', message: `Importing ${name} on ${to} (local copy, no download)…` })
+ const r = to === 'ollama'
+ ? await ollamaManager.importModelFromGguf({ name, ggufPath: resolved.ggufPath })
+ : await lmStudioManager.importModelFromGguf({ lmstudioId: name, ggufPath: resolved.ggufPath, projectorPath: resolved.projectorPath })
+ if (!r.success) {
+ onProgress({ event: 'start', message: `Local import of ${model.id} failed (${r.error}); re-pulling…` })
+ return null
+ }
+ onProgress({ event: 'start', message: `Imported ${r.modelId} on ${to} (no download)` })
+ return { source: model.id, target: r.modelId, status: 'imported', reason: null }
+}
+
+/**
+ * Migrate to a backend: provision the active backend's installed models on the
+ * target, then flip the active marker. The underlying GGUF weights ARE portable
+ * across backends, so each model is first copied locally (no download) when it's
+ * a single-file GGUF; models that can't be copied (LM Studio MLX-format, sharded,
+ * or with a separate projector) fall back to re-pulling the catalog equivalent.
+ * Per-model results are reported; an individual failure doesn't abort the switch.
*
* @param {string} to - target backend
* @param {(p: { event: string, message: string }) => void} [onProgress]
@@ -250,12 +287,20 @@ export async function migrateBackend(to, onProgress = () => {}) {
const results = []
for (const model of sourceModels) {
const { targetId, exact } = mapModelToBackend(from, model.id, to)
+ const resolved = await manager(from).resolveLocalModel(model.id).catch(() => null)
+
+ // 1) Fast path — copy the GGUF locally (no download) when we can.
+ const imported = await tryLocalImport(to, model, targetId, resolved, onProgress)
+ if (imported) { results.push(imported); continue }
+
+ // 2) Fallback — re-pull the catalog equivalent.
if (!targetId) {
- results.push({ source: model.id, target: null, status: 'skipped', reason: 'no known equivalent' })
- onProgress({ event: 'start', message: `Skipped ${model.id} — no known ${to} equivalent` })
+ const reason = resolved?.isMlx ? 'MLX format — no GGUF equivalent to re-pull' : 'no known equivalent'
+ results.push({ source: model.id, target: null, status: 'skipped', reason })
+ onProgress({ event: 'start', message: `Skipped ${model.id} — ${reason}` })
continue
}
- onProgress({ event: 'start', message: `Installing ${targetId} on ${to}${exact ? '' : ' (best-effort)'}…` })
+ 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}%` })
})
@@ -268,12 +313,19 @@ export async function migrateBackend(to, onProgress = () => {}) {
writeBackend(to)
await ensureBackendProvider(to)
+ const imported = results.filter((r) => r.status === 'imported').length
const installed = results.filter((r) => r.status === 'installed').length
const started = results.filter((r) => r.status === 'started').length
const failed = results.filter((r) => r.status === 'failed').length
- const skipped = results.length - installed - started - failed
- const startedNote = started ? `, ${started} downloading` : ''
- onProgress({ event: 'complete', message: `Migrated to ${to} — ${installed} installed${startedNote}, ${failed} failed, ${skipped} skipped` })
- console.log(`🔀 Migrated local LLM backend → ${to} (${installed} installed, ${failed} failed)`)
+ const skipped = results.length - imported - installed - started - failed
+ const parts = [
+ imported ? `${imported} copied locally` : null,
+ installed ? `${installed} downloaded` : null,
+ started ? `${started} downloading` : null,
+ failed ? `${failed} failed` : null,
+ skipped ? `${skipped} skipped` : null
+ ].filter(Boolean)
+ onProgress({ event: 'complete', message: `Migrated to ${to} — ${parts.join(', ') || 'no models to move'}` })
+ console.log(`🔀 Migrated local LLM backend → ${to} (${imported} copied, ${installed} downloaded, ${failed} failed)`)
return { success: true, backend: to, results }
}
diff --git a/server/services/localLlm.test.js b/server/services/localLlm.test.js
index b60ce81edc..fab4a39f4b 100644
--- a/server/services/localLlm.test.js
+++ b/server/services/localLlm.test.js
@@ -15,13 +15,18 @@ const mocks = vi.hoisted(() => ({
getInstalledModels: vi.fn(async () => []),
pullModel: vi.fn(async (id) => ({ success: true, modelId: id })),
deleteModel: vi.fn(async (id) => ({ success: true, modelId: id })),
- getStatus: vi.fn(async () => ({ available: true, baseUrl: 'x', version: '1', modelCount: 0, models: [] }))
+ getStatus: vi.fn(async () => ({ available: true, baseUrl: 'x', version: '1', modelCount: 0, models: [] })),
+ // No local GGUF found by default → migrate falls back to re-pull.
+ resolveLocalModel: vi.fn(async () => null),
+ importModelFromGguf: vi.fn(async ({ name }) => ({ success: true, modelId: name }))
},
lmstudio: {
getAvailableModels: vi.fn(async () => []),
downloadModel: vi.fn(async (id) => ({ success: true, modelId: id })),
getStatus: vi.fn(async () => ({ available: false, baseUrl: 'y', loadedModels: 0 })),
- resetCache: vi.fn()
+ resetCache: vi.fn(),
+ resolveLocalModel: vi.fn(async () => null),
+ importModelFromGguf: vi.fn(async ({ lmstudioId }) => ({ success: true, modelId: lmstudioId }))
},
providers: {
getProviderById: vi.fn(async () => ({ id: 'ollama', enabled: false })),
@@ -123,6 +128,52 @@ describe('localLlm', () => {
expect(mocks.lmstudio.downloadModel).not.toHaveBeenCalled();
});
+ it('copies a local GGUF to the target instead of downloading (fast path)', async () => {
+ writeEnv('LLM_BACKEND=lmstudio\n');
+ mocks.lmstudio.getAvailableModels.mockResolvedValueOnce([
+ { id: 'lmstudio-community/Llama-3.2-3B-Instruct-GGUF' }
+ ]);
+ mocks.lmstudio.resolveLocalModel.mockResolvedValueOnce({
+ ggufPath: '/models/llama-3.2-3b.gguf', projectorPath: null, isMlx: false, isSharded: false
+ });
+
+ const r = await svc.migrateBackend('ollama');
+ expect(r.results[0].status).toBe('imported');
+ expect(mocks.ollama.importModelFromGguf).toHaveBeenCalledWith({ name: 'llama3.2', ggufPath: '/models/llama-3.2-3b.gguf' });
+ expect(mocks.ollama.pullModel).not.toHaveBeenCalled(); // no network download
+ });
+
+ it('does not local-copy an MLX model — falls back to re-pull', async () => {
+ writeEnv('LLM_BACKEND=lmstudio\n');
+ mocks.lmstudio.getAvailableModels.mockResolvedValueOnce([
+ { id: 'lmstudio-community/Llama-3.2-3B-Instruct-GGUF' }
+ ]);
+ // MLX dir has no GGUF to copy → must re-pull the catalog equivalent.
+ mocks.lmstudio.resolveLocalModel.mockResolvedValueOnce({
+ ggufPath: null, projectorPath: null, isMlx: true, isSharded: false
+ });
+
+ const r = await svc.migrateBackend('ollama');
+ expect(mocks.ollama.importModelFromGguf).not.toHaveBeenCalled();
+ expect(mocks.ollama.pullModel).toHaveBeenCalledWith('llama3.2', expect.any(Function));
+ expect(r.results[0].status).toBe('installed');
+ });
+
+ it('re-pulls when an Ollama-target import would drop a separate projector', async () => {
+ writeEnv('LLM_BACKEND=lmstudio\n');
+ mocks.lmstudio.getAvailableModels.mockResolvedValueOnce([
+ { id: 'lmstudio-community/Llama-3.2-3B-Instruct-GGUF' }
+ ]);
+ mocks.lmstudio.resolveLocalModel.mockResolvedValueOnce({
+ ggufPath: '/m/w.gguf', projectorPath: '/m/mmproj.gguf', isMlx: false, isSharded: false
+ });
+
+ const r = await svc.migrateBackend('ollama');
+ expect(mocks.ollama.importModelFromGguf).not.toHaveBeenCalled();
+ expect(mocks.ollama.pullModel).toHaveBeenCalled();
+ expect(r.results[0].status).toBe('installed');
+ });
+
it('rejects migrating to the already-active backend (no-op)', async () => {
writeEnv('LLM_BACKEND=ollama\n');
const r = await svc.migrateBackend('ollama');
diff --git a/server/services/ollamaManager.js b/server/services/ollamaManager.js
index c336fcf021..01f653fcd0 100644
--- a/server/services/ollamaManager.js
+++ b/server/services/ollamaManager.js
@@ -14,7 +14,13 @@
* DELETE /api/delete → { name }
*/
+import { homedir } from 'os'
+import { join } from 'path'
+import { readFile, readdir, stat } from 'fs/promises'
import { fetchWithTimeout } from '../lib/fetchWithTimeout.js'
+import {
+ parseOllamaManifest, parseOllamaModelRef, ollamaManifestRelPath, digestToBlobFilename, buildModelfile
+} from '../lib/localLlmDisk.js'
const AVAILABILITY_CACHE_TTL_MS = 30_000
const DEFAULT_REQUEST_TIMEOUT_MS = 10_000
@@ -132,6 +138,35 @@ async function pullModel(modelId, onProgress) {
return { success: false, error, modelId }
}
+ const lastError = await streamNdjson(response, (frame) => {
+ if (typeof onProgress === 'function') {
+ const percent = frame.total > 0 && frame.completed >= 0
+ ? Math.round((frame.completed / frame.total) * 100)
+ : null
+ onProgress({ status: frame.status || '', percent, completed: frame.completed, total: frame.total })
+ }
+ })
+
+ if (lastError) {
+ return { success: false, error: lastError, modelId }
+ }
+ installedModels = [] // bust cache so the new model shows on next list
+ console.log(`✅ Ollama pull complete: ${modelId}`)
+ return { success: true, modelId }
+}
+
+/**
+ * Consume an Ollama NDJSON progress stream (used by /api/pull and /api/create).
+ * Returns the last `{ error }` seen, or null on a clean stream. Reads via
+ * getReader() to match the codebase's streaming convention; try/finally releases
+ * the reader even if a read rejects mid-stream (avoids leaking the connection).
+ * Flushes the decoder + trailing buffer so a final frame that wasn't newline-
+ * terminated (notably a terminal `{"error":...}`) isn't silently dropped.
+ * @param {Response} response - a fetch Response with a readable body
+ * @param {(frame: object) => void} [onFrame]
+ * @returns {Promise<string|null>} last error message, or null
+ */
+async function streamNdjson(response, onFrame) {
const reader = response.body.getReader()
const decoder = new TextDecoder()
let buffer = ''
@@ -143,18 +178,9 @@ async function pullModel(modelId, onProgress) {
const frame = safeParse(trimmed)
if (!frame) return
if (frame.error) lastError = frame.error
- if (typeof onProgress === 'function') {
- const percent = frame.total > 0 && frame.completed >= 0
- ? Math.round((frame.completed / frame.total) * 100)
- : null
- onProgress({ status: frame.status || '', percent, completed: frame.completed, total: frame.total })
- }
+ if (typeof onFrame === 'function') onFrame(frame)
}
- // Ollama streams newline-delimited JSON progress frames. Read via getReader()
- // to match the rest of the codebase's streaming-fetch convention. try/finally
- // releases the reader even if a read rejects mid-pull (avoids leaking the
- // underlying connection).
try {
while (true) {
const { value, done } = await reader.read()
@@ -166,21 +192,12 @@ async function pullModel(modelId, onProgress) {
buffer = buffer.slice(nl + 1)
}
}
- // Flush the decoder and process any final frame that wasn't newline-
- // terminated — otherwise a terminal `{"error":...}` (or "success") frame
- // would be dropped and a failed pull silently reported as success.
buffer += decoder.decode()
handleFrame(buffer)
} finally {
reader.releaseLock()
}
-
- if (lastError) {
- return { success: false, error: lastError, modelId }
- }
- installedModels = [] // bust cache so the new model shows on next list
- console.log(`✅ Ollama pull complete: ${modelId}`)
- return { success: true, modelId }
+ return lastError
}
function safeParse(line) {
@@ -208,6 +225,83 @@ async function deleteModel(modelId) {
return { success: true, modelId }
}
+// ---- local-disk introspection / import (migrate fast-path) ------------------
+
+/** Ollama's models root: `$OLLAMA_MODELS` or `~/.ollama/models`. */
+function getModelsDir() {
+ return process.env.OLLAMA_MODELS || join(homedir(), '.ollama', 'models')
+}
+
+const fileExists = (p) => stat(p).then((s) => s.isFile()).catch(() => false)
+const readJson = (p) => readFile(p, 'utf8').then((t) => JSON.parse(t)).catch(() => null)
+
+// 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 readJson(join(modelsDir, ...ollamaManifestRelPath(ref).split('/')))
+ if (direct) return direct
+ const manifestsDir = join(modelsDir, 'manifests')
+ const registries = await readdir(manifestsDir).catch(() => [])
+ for (const registry of registries) {
+ const namespaces = await readdir(join(manifestsDir, registry)).catch(() => [])
+ for (const ns of namespaces) {
+ const candidate = join(manifestsDir, registry, ns, ref.name, ref.tag)
+ const m = await readJson(candidate)
+ if (m) return m
+ }
+ }
+ return null
+}
+
+/**
+ * Locate an installed Ollama model's weight files on disk (no network).
+ * @returns {Promise<{ ggufPath: string, projectorPath: string|null, isMlx: false, isSharded: false }|null>}
+ */
+async function resolveLocalModel(modelId) {
+ const modelsDir = getModelsDir()
+ const manifest = await findManifest(modelsDir, parseOllamaModelRef(modelId))
+ if (!manifest) return null
+ const { modelDigest, projectorDigest } = parseOllamaManifest(manifest)
+ if (!modelDigest) return null
+ const ggufPath = join(modelsDir, 'blobs', digestToBlobFilename(modelDigest))
+ if (!(await fileExists(ggufPath))) return null
+ return {
+ ggufPath,
+ projectorPath: projectorDigest ? join(modelsDir, 'blobs', digestToBlobFilename(projectorDigest)) : null,
+ isMlx: false,
+ isSharded: false
+ }
+}
+
+/**
+ * Register a local GGUF file as an Ollama model via `/api/create` (no download).
+ * @param {{ name: string, ggufPath: string }} args
+ * @returns {Promise<{ success: boolean, modelId?: string, error?: string }>}
+ */
+async function importModelFromGguf({ name, ggufPath }) {
+ if (!(await checkOllamaAvailable())) {
+ return { success: false, error: 'Ollama not available' }
+ }
+ console.log(`📦 Ollama import (local): ${name} ← ${ggufPath}`)
+ // No timeout — create copies the (multi-GB) blob into the store.
+ const response = await fetchWithTimeout(`${config.baseUrl}/api/create`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name, modelfile: buildModelfile(ggufPath), stream: true })
+ }, 0).catch((err) => ({ _err: err.message }))
+
+ if (response._err || !response.ok || !response.body) {
+ const error = response._err || `create failed: ${response.status} ${response.statusText}`
+ return { success: false, error }
+ }
+ const lastError = await streamNdjson(response)
+ if (lastError) return { success: false, error: lastError }
+ installedModels = []
+ console.log(`✅ Ollama import complete: ${name}`)
+ return { success: true, modelId: name }
+}
+
/**
* Aggregate status for the unified local-LLM UI.
*/
@@ -229,5 +323,8 @@ export {
getInstalledModels,
pullModel,
deleteModel,
- getStatus
+ getStatus,
+ getModelsDir,
+ resolveLocalModel,
+ importModelFromGguf
}