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
Clarify local LLM backend migration
Adam Eivyefa8c28e5464
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 5a658e83e8..5c25372c9b 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, **one-click installs a missing backend** (Homebrew on macOS for both; the official script for Ollama on Linux; a download link elsewhere — with live installer output over the socket), 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.+- **[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, **one-click installs a missing backend** (Homebrew on macOS for both; the official script for Ollama on Linux; a download link elsewhere — with live installer output over the socket), makes clear **both backends can run at the same time** — the **Default** marker (formerly the misleading "Active" badge, which read as a running-state indicator) just picks which one PortOS routes local runs to, and **Set as Default** changes it without moving anything — and lets you **move models between the two in either direction, independently of the default**: 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 each backend card's **Import from…** action offers **Link** (hardlink the GGUF so both backends share one file on disk — zero extra space, falling back to a copy across filesystems) or **Copy** (an independent duplicate), with **no re-download** either way; models that can't be shared/copied — LM Studio MLX-format, sharded, or (when targeting Ollama) multimodal — re-pull the cross-backend catalog equivalent. It also 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`, with link mode pre-placing a content-addressed `blobs/sha256-…` hardlink so create dedups against it), `server/services/lmStudioManager.js` (hardlink-or-copy GGUF into LM Studio's model tree), `server/services/localLlm.js` (unified orchestration + `.env` default marker + provider enabling + bidirectional link/copy migrate, decoupled from the default), `server/lib/localLlmCatalog.js` (pure catalog + install-id mapping), `server/lib/localLlmDisk.js` (pure on-disk GGUF/manifest reasoning for the local-share/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.jsxindex 540f6869e2..55badf9763 100644--- a/client/src/components/settings/LocalLlmTab.jsx+++ b/client/src/components/settings/LocalLlmTab.jsx@@ -1,5 +1,5 @@import { useState, useEffect, useRef, useCallback } from 'react';-import { Cpu, Box, ArrowRightLeft, Download, Trash2, RefreshCw, Search, Plus, ExternalLink } from 'lucide-react';+import { Cpu, Box, ArrowRightLeft, Download, Trash2, RefreshCw, Search, Plus, ExternalLink, Star, Link2, Copy } from 'lucide-react';import toast from '../ui/Toast';import BrailleSpinner from '../BrailleSpinner';import { formatBytes } from '../../utils/formatters';@@ -17,10 +17,29 @@ const labelFor = (id) => BACKENDS.find((b) => b.id === id)?.label || id;const btnClass = 'flex items-center gap-1.5 px-2 py-1 text-xs font-medium rounded transition-colors disabled:opacity-50';-function BackendCard({ backend, status, isActive, busy, actionInProgress, runAction, setConfirmAction }) {+// Summarize a migrate result for the success toast (per-model statuses → counts).+function summarizeMigrate(r) {+ const c = { linked: 0, copied: 0, installed: 0, started: 0, failed: 0, skipped: 0 };+ for (const x of r?.results || []) {+ if (x.status === 'imported') c[x.linked ? 'linked' : 'copied']++;+ else if (c[x.status] != null) c[x.status]++;+ }+ const parts = [+ c.linked && `${c.linked} linked`,+ c.copied && `${c.copied} copied`,+ c.installed && `${c.installed} downloaded`,+ c.started && `${c.started} downloading`,+ c.failed && `${c.failed} failed`,+ c.skipped && `${c.skipped} skipped`+ ].filter(Boolean);+ return `${labelFor(r.from)} → ${labelFor(r.to)}: ${parts.join(', ') || 'nothing to move'}`;+}++function BackendCard({ backend, status, isDefault, busy, actionInProgress, runAction, setConfirmAction }) {const data = status?.[backend.id];const Icon = backend.icon;const other = backend.id === 'ollama' ? 'lmstudio' : 'ollama';+ const otherData = status?.[other];const statusLabel = data?.available ? 'Running' : data?.installed ? 'Installed (stopped)' : 'Not installed';const statusColor = data?.available ? 'bg-port-success' : data?.installed ? 'bg-port-warning' : 'bg-gray-600';@@ -32,8 +51,15 @@ function BackendCard({ backend, status, isActive, busy, actionInProgress, runAct{backend.label}</div><div className="flex items-center gap-1.5">- {isActive && <span className="text-xs px-1.5 py-0.5 bg-port-accent/20 text-port-accent rounded">Active</span>}- <span className={`w-2 h-2 rounded-full ${statusColor}`} />+ {isDefault && (+ <span+ className="text-xs px-1.5 py-0.5 bg-port-accent/20 text-port-accent rounded"+ title="PortOS routes local-LLM runs here by default. This is independent of whether the server is running (see the status dot)."+ >+ Default+ </span>+ )}+ <span className={`w-2 h-2 rounded-full ${statusColor}`} title={statusLabel} /></div></div>@@ -73,30 +99,36 @@ function BackendCard({ backend, status, isActive, busy, actionInProgress, runAct</div>)}- {data?.installed && !isActive && (+ {data?.installed && (<div className="flex flex-wrap gap-1.5 pt-1 border-t border-port-border/50">- <button- onClick={() => setConfirmAction({- type: 'migrate',- label: `Migrate to ${backend.label}?`,- 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}- className={`${btnClass} bg-port-accent/20 hover:bg-port-accent/30 text-port-accent`}- >- <ArrowRightLeft size={12} />- Migrate to {backend.label}- </button>- <button- onClick={() => runAction(`switch-${backend.id}`, () => switchLocalLlmBackend(backend.id), `Switched to ${backend.label}`)}- disabled={busy}- className={`${btnClass} bg-port-border hover:bg-port-border/70 text-white`}- title="Make this the active backend without moving any models"- >- {actionInProgress === `switch-${backend.id}` ? <BrailleSpinner /> : <ArrowRightLeft size={12} />}- Switch- </button>+ {!isDefault && (+ <button+ onClick={() => runAction(`switch-${backend.id}`, () => switchLocalLlmBackend(backend.id), `${backend.label} is now the default backend`)}+ disabled={busy}+ className={`${btnClass} bg-port-border hover:bg-port-border/70 text-white`}+ title="Route PortOS local-LLM runs here by default — doesn't move any models or stop the other backend"+ >+ {actionInProgress === `switch-${backend.id}` ? <BrailleSpinner /> : <Star size={12} />}+ Set as Default+ </button>+ )}+ {otherData?.available && (+ <button+ onClick={() => setConfirmAction({+ type: 'migrate',+ to: backend.id,+ from: other,+ label: `Bring ${labelFor(other)}'s models onto ${backend.label}?`,+ detail: `Provisions the ${otherData.modelCount ?? 0} model${(otherData.modelCount ?? 0) === 1 ? '' : 's'} on ${labelFor(other)} onto ${backend.label} — your default backend is unchanged. Link shares each GGUF on disk (no extra space, falls back to a copy across filesystems); Copy makes an independent duplicate. Portable single-file GGUF models move with no re-download; MLX-format, sharded, or multimodal models that can't be shared/copied are re-pulled.`+ })}+ disabled={busy}+ className={`${btnClass} bg-port-accent/20 hover:bg-port-accent/30 text-port-accent`}+ title={`Copy or link the models installed on ${labelFor(other)} onto ${backend.label}`}+ >+ <ArrowRightLeft size={12} />+ Import from {labelFor(other)}+ </button>+ )}</div>)}</div>@@ -197,6 +229,9 @@ export function LocalLlmTab() {<RefreshCw size={14} className={loading ? 'animate-spin' : ''} /></button></div>+ <p className="text-xs text-gray-500">+ Both backends can be installed and running at the same time — <span className="text-gray-400">Default</span> just sets which one PortOS routes local-LLM runs to. Use <span className="text-gray-400">Import from…</span> to copy or link models between them without re-downloading.+ </p>{loading && !status ? (<BrailleSpinner text="Loading local LLM status" />@@ -205,7 +240,7 @@ export function LocalLlmTab() {<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">{BACKENDS.map((b) => (<BackendCard- key={b.id} backend={b} status={status} isActive={status.backend === b.id}+ key={b.id} backend={b} status={status} isDefault={status.backend === b.id}busy={busy} actionInProgress={actionInProgress}runAction={runAction} setConfirmAction={setConfirmAction}/>@@ -223,14 +258,24 @@ export function LocalLlmTab() {<div className="bg-port-bg border border-port-warning/30 rounded-lg p-4 space-y-3"><p className="text-sm text-white">{confirmAction.label}</p>{confirmAction.detail && <p className="text-xs text-gray-400">{confirmAction.detail}</p>}- <div className="flex items-center gap-2">+ <div className="flex items-center gap-2 flex-wrap">+ <button+ onClick={() => runAction(`migrate-${confirmAction.to}-link`, () => migrateLocalLlmBackend(confirmAction.to, 'link'), summarizeMigrate)}+ disabled={busy}+ className="flex items-center gap-2 px-3 py-1.5 text-sm font-medium rounded-lg transition-colors disabled:opacity-50 bg-port-accent/20 hover:bg-port-accent/30 text-port-accent"+ title="Hardlink each GGUF so both backends share one file on disk (no extra space; falls back to a copy across filesystems)"+ >+ {actionInProgress === `migrate-${confirmAction.to}-link` ? <BrailleSpinner /> : <Link2 size={14} />}+ Link (share disk)+ </button><button- onClick={confirmAction.action}+ onClick={() => runAction(`migrate-${confirmAction.to}-copy`, () => migrateLocalLlmBackend(confirmAction.to, 'copy'), summarizeMigrate)}disabled={busy}- className="flex items-center gap-2 px-3 py-1.5 text-sm font-medium rounded-lg transition-colors disabled:opacity-50 bg-port-warning/20 hover:bg-port-warning/30 text-port-warning"+ className="flex items-center gap-2 px-3 py-1.5 text-sm font-medium rounded-lg transition-colors disabled:opacity-50 bg-port-border hover:bg-port-border/70 text-white"+ title="Make an independent duplicate on the target (uses extra disk; survives deleting the source backend's copy)">- {busy ? <BrailleSpinner /> : <ArrowRightLeft size={14} />}- Confirm+ {actionInProgress === `migrate-${confirmAction.to}-copy` ? <BrailleSpinner /> : <Copy size={14} />}+ Copy (independent)</button><button onClick={() => setConfirmAction(null)} className="px-3 py-1.5 text-sm text-gray-400 hover:text-white transition-colors">Canceldiff --git a/client/src/services/apiLocalLlm.js b/client/src/services/apiLocalLlm.jsindex c365634c00..802c69d5a2 100644--- a/client/src/services/apiLocalLlm.js+++ b/client/src/services/apiLocalLlm.js@@ -16,8 +16,12 @@ export const deleteLocalLlmModel = (backend, modelId) =>export const installLocalLlmBackend = (backend) =>request('/local-llm/install-backend', { method: 'POST', body: JSON.stringify({ backend }) });+// Set the default backend (which one PortOS routes local runs to) — does not move models.export const switchLocalLlmBackend = (to) =>request('/local-llm/switch', { method: 'POST', body: JSON.stringify({ to }) });-export const migrateLocalLlmBackend = (to) =>- request('/local-llm/migrate', { method: 'POST', body: JSON.stringify({ to }) });+// Move the OTHER backend's models onto `to`. mode: 'link' shares GGUF weights on+// disk (default, zero extra space, falls back to copy across filesystems);+// 'copy' makes an independent duplicate. Never changes the default backend.+export const migrateLocalLlmBackend = (to, mode = 'link') =>+ request('/local-llm/migrate', { method: 'POST', body: JSON.stringify({ to, mode }) });diff --git a/server/lib/validation.js b/server/lib/validation.jsindex b6a00d6536..6b92206342 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -1054,6 +1054,13 @@ export const localLlmInstallSchema = z.object({});export const localLlmDeleteSchema = localLlmInstallSchema;export const localLlmSwitchSchema = z.object({ to: localLlmBackendSchema });+// Migrate moves models from the OTHER backend onto `to` (bidirectional, never+// flips the default marker). `mode` picks how the GGUF lands on disk: 'link'+// hardlinks/shares it (default), 'copy' duplicates it.+export const localLlmMigrateSchema = z.object({+ to: localLlmBackendSchema,+ mode: z.enum(['link', 'copy']).optional().default('link'),+});export const localLlmInstallBackendSchema = z.object({ backend: localLlmBackendSchema });/**diff --git a/server/routes/localLlm.js b/server/routes/localLlm.jsindex 2c5a5d5f9a..bee65ede97 100644--- a/server/routes/localLlm.js+++ b/server/routes/localLlm.js@@ -15,6 +15,7 @@ import {localLlmInstallSchema,localLlmDeleteSchema,localLlmSwitchSchema,+ localLlmMigrateSchema,localLlmInstallBackendSchema} from '../lib/validation.js'import { getCatalog, searchCatalog, isBackend } from '../lib/localLlmCatalog.js'@@ -93,26 +94,27 @@ router.post('/delete', asyncHandler(async (req, res) => {res.json({ success: true, ...result })}))-// POST /api/local-llm/switch — flip active backend without moving models+// POST /api/local-llm/switch — set the default backend without moving modelsrouter.post('/switch', asyncHandler(async (req, res) => {const { to } = validateRequest(localLlmSwitchSchema, req.body)const emit = emitter(req)- emit('start', `Switching to ${to}…`)+ emit('start', `Setting ${to} as default…`)const result = await switchBackend(to)if (!result.success) {emit('error', result.error || 'Switch failed')return res.status(500).json({ error: result.error || 'Switch failed' })}- emit('complete', `Switched to ${to}`)+ emit('complete', `${to} is now the default backend`)res.json(result)}))-// POST /api/local-llm/migrate — provision models on target (copy GGUF locally-// where possible, else re-pull), then switch the active backend+// POST /api/local-llm/migrate — move the OTHER backend's models onto `to`+// (bidirectional; link/share or copy GGUF locally where possible, else re-pull).+// Does NOT change the default backend — use /switch for that.router.post('/migrate', asyncHandler(async (req, res) => {- const { to } = validateRequest(localLlmSwitchSchema, req.body)+ const { to, mode } = validateRequest(localLlmMigrateSchema, req.body)const emit = emitter(req)- const result = await migrateBackend(to, ({ event, message }) => emit(event, message))+ const result = await migrateBackend(to, { mode, onProgress: ({ event, message }) => emit(event, message) })if (!result.success) {emit('error', result.error || 'Migration failed')return res.status(500).json({ error: result.error || 'Migration failed' })diff --git a/server/services/lmStudioManager.js b/server/services/lmStudioManager.jsindex 0302289e11..d6ddff7519 100644--- a/server/services/lmStudioManager.js+++ b/server/services/lmStudioManager.js@@ -8,7 +8,7 @@import { homedir } from 'os'import { join, basename } from 'path'import { existsSync } from 'fs'-import { readdir, stat, mkdir, copyFile } from 'fs/promises'+import { readdir, stat, mkdir, copyFile, link } from 'fs/promises'import { cosEvents } from './cosEvents.js'import { fetchWithTimeout } from '../lib/fetchWithTimeout.js'import {@@ -513,34 +513,45 @@ async function resolveLocalModel(modelId) {}/**- * 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 }>}+ * Place 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. In `link`+ * mode the file is hardlinked (shared on disk with the source backend's copy);+ * `copy` mode duplicates it. Link falls back to copy on any error (notably EXDEV+ * across filesystems).+ * @param {{ lmstudioId: string, ggufPath: string, projectorPath?: string|null, mode?: 'link'|'copy' }} args+ * @returns {Promise<{ success: boolean, modelId?: string, linked?: boolean, error?: string }>}*/-async function importModelFromGguf({ lmstudioId, ggufPath, projectorPath }) {+async function importModelFromGguf({ lmstudioId, ggufPath, projectorPath, mode = 'copy' }) {const modelsDir = await getModelsDir()const { publisher, repo } = lmStudioPublisherRepo(lmstudioId)const destDir = join(modelsDir, publisher, repo)// Report the actual on-disk id (sanitized) rather than the raw input, so// migrate results / follow-up ops match where the file really landed.const resolvedId = `${publisher}/${repo}`+ // Hardlink when asked; fall back to copy on any link error. Returns whether+ // the file ended up hardlinked (so the caller can report disk-sharing).+ const place = async (src, dest) => {+ if (mode === 'link' && await link(src, dest).then(() => true).catch(() => false)) return true+ await copyFile(src, dest)+ return false+ }+ let linked = falseconst r = await mkdir(destDir, { recursive: true }).then(async () => {const base = basename(ggufPath)const destName = /\.gguf$/i.test(base) ? base : `${repo}.gguf`- await copyFile(ggufPath, join(destDir, destName))+ linked = await place(ggufPath, join(destDir, destName))if (projectorPath) {const projBase = basename(projectorPath)- await copyFile(projectorPath, join(destDir, /\.gguf$/i.test(projBase) ? projBase : `${repo}-mmproj.gguf`))+ await place(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: resolvedId }resetCache()- console.log(`📦 LM Studio import (local): ${resolvedId} ← ${ggufPath}`)- return { success: true, modelId: resolvedId }+ console.log(`📦 LM Studio import (${linked ? 'hardlink' : 'copy'}): ${resolvedId} ← ${ggufPath}`)+ return { success: true, modelId: resolvedId, linked }}export {diff --git a/server/services/localLlm.js b/server/services/localLlm.jsindex 22bf71ee9a..8c08d3f414 100644--- a/server/services/localLlm.js+++ b/server/services/localLlm.js@@ -1,19 +1,23 @@/*** Local LLM orchestration — unifies the Ollama and LM Studio backends behind- * one shape so the UI can list / search / install / delete models and migrate- * or switch the active backend (mirroring the Docker↔native Postgres flow).+ * one shape so the UI can list / search / install / delete models, move models+ * between backends, and pick the default backend. Both backends can be installed+ * and running at the same time; the "default" is just which one PortOS routes+ * local runs to.*- * The active backend is recorded in `.env` as `LLM_BACKEND` (parallel to+ * The default backend is recorded in `.env` as `LLM_BACKEND` (parallel to* `PGMODE`), so it survives restarts and is readable by the setup script. The* matching aiToolkit provider (`ollama` / `lmstudio`) is enabled whenever a- * backend becomes active.+ * backend becomes the default (each provider stays independently enabled — we+ * never disable the other, so both remain usable concurrently).** 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.+ * file tree). So `migrateBackend` (bidirectional, independent of the default+ * marker) hardlinks each model's GGUF across — sharing it on disk with zero+ * extra space — or copies it, and re-pulls the cross-backend catalog equivalent+ * only for models it can't share/copy (LM Studio MLX-format, sharded, or+ * multimodal). See `server/lib/localLlmDisk.js` for the disk logic.*/import { execFile, spawn } from 'child_process'@@ -355,7 +359,7 @@ export async function switchBackend(to) {* 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) {+async function tryLocalImport(to, model, targetId, resolved, mode, 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.@@ -365,48 +369,63 @@ async function tryLocalImport(to, model, targetId, resolved, onProgress) {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 verb = mode === 'link' ? 'Linking' : 'Copying'+ onProgress({ event: 'start', message: `${verb} ${name} onto ${to} (no download)…` })const r = to === 'ollama'- ? await ollamaManager.importModelFromGguf({ name, ggufPath: resolved.ggufPath })- : await lmStudioManager.importModelFromGguf({ lmstudioId: name, ggufPath: resolved.ggufPath, projectorPath: resolved.projectorPath })+ ? await ollamaManager.importModelFromGguf({ name, ggufPath: resolved.ggufPath, mode })+ : await lmStudioManager.importModelFromGguf({ lmstudioId: name, ggufPath: resolved.ggufPath, projectorPath: resolved.projectorPath, mode })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 }+ // `linked` reflects what actually happened on disk — link mode falls back to a+ // copy across filesystems, so report the real outcome, not the requested mode.+ onProgress({ event: 'start', message: `${r.linked ? 'Linked' : 'Copied'} ${r.modelId} onto ${to} (no download)` })+ return { source: model.id, target: r.modelId, status: 'imported', linked: !!r.linked, reason: null }}+/** The other of the two backends (migration source for a given target). */+const otherBackend = (backend) => (backend === 'ollama' ? 'lmstudio' : 'ollama')+/**- * 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.+ * Provision the OTHER backend's installed models onto `to`. This is bidirectional+ * (source is simply the opposite backend, NOT the active one) and decoupled from+ * the default-backend marker — it never flips it. Use `switchBackend` ("Set as+ * Default") for routing. The underlying GGUF weights ARE portable across backends:+ *+ * • `mode: 'link'` (default) — hardlink the GGUF so both backends share one file+ * on disk (zero extra space), falling back to a copy where a hardlink isn't+ * possible (different filesystem).+ * • `mode: 'copy'` — make an independent duplicate.+ *+ * Either way there's no re-download for portable single-file GGUFs; models that+ * can't be shared/copied (LM Studio MLX-format, sharded, or with a separate+ * projector when targeting Ollama) fall back to re-pulling the catalog+ * equivalent. Per-model results are reported; an individual failure doesn't abort.** @param {string} to - target backend- * @param {(p: { event: string, message: string }) => void} [onProgress]+ * @param {{ mode?: 'link'|'copy', onProgress?: (p: { event: string, message: string }) => void }} [opts]*/-export async function migrateBackend(to, onProgress = () => {}) {+export async function migrateBackend(to, { mode = 'link', onProgress = () => {} } = {}) {if (!isBackend(to)) return { success: false, error: `Unknown backend: ${to}` }- // Source is whatever's active now — we're moving away from it. Migrating to- // the already-active backend is a no-op, not "re-provision from the other".- const from = getBackend()- if (from === to) {- return { success: false, error: `${to} is already the active backend — nothing to migrate.` }- }+ if (mode !== 'link' && mode !== 'copy') mode = 'link'+ const from = otherBackend(to)onProgress({ event: 'start', message: `Reading models installed on ${from}…` })const sourceModels = await listModels(from, true) // fresh source list for an accurate migration+ if (sourceModels.length === 0) {+ const message = `No models installed on ${from} to move.`+ onProgress({ event: 'complete', message })+ return { success: true, from, to, mode, results: [] }+ }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)+ // 1) Fast path — link/copy the GGUF locally (no download) when we can.+ const imported = await tryLocalImport(to, model, targetId, resolved, mode, onProgress)if (imported) { results.push(imported); continue }// 2) Fallback — re-pull the catalog equivalent.@@ -426,35 +445,33 @@ export async function migrateBackend(to, onProgress = () => {}) {results.push({ source: model.id, target: targetId, status, reason: r.error })}- const imported = results.filter((r) => r.status === 'imported').length+ const linked = results.filter((r) => r.status === 'imported' && r.linked).length+ const copied = results.filter((r) => r.status === 'imported' && !r.linked).lengthconst installed = results.filter((r) => r.status === 'installed').lengthconst started = results.filter((r) => r.status === 'started').lengthconst failed = results.filter((r) => r.status === 'failed').length- const skipped = results.length - imported - installed - started - failed- const succeeded = imported + installed + started+ const skipped = results.filter((r) => r.status === 'skipped').length+ const succeeded = linked + copied + installed + started- // Don't flip the active marker onto a backend we couldn't provision anything- // on — if every attempt failed (target not installed/running), switching would- // leave PortOS pointed at an unusable backend. All-skipped is fine (the target- // itself works; we just had no equivalent to move).+ // Surface a hard failure when nothing could be provisioned (e.g. target not+ // installed/running). All-skipped is fine — the target works, we just had no+ // equivalent to move.if (failed > 0 && succeeded === 0) {- const error = `Migration to ${to} failed — no models could be provisioned (is ${to} installed and running?). Active backend left unchanged.`+ const error = `Migration ${from} → ${to} failed — no models could be provisioned (is ${to} installed and running?).`onProgress({ event: 'error', message: error })- console.error(`⚠️ Migration to ${to} aborted: ${failed} failed, 0 succeeded — marker unchanged`)- return { success: false, error, results }+ console.error(`⚠️ Migration ${from} → ${to} aborted: ${failed} failed, 0 succeeded`)+ return { success: false, from, to, mode, error, results }}- writeBackend(to)- await ensureBackendProvider(to)-const parts = [- imported ? `${imported} copied locally` : null,+ linked ? `${linked} linked (shared on disk)` : null,+ copied ? `${copied} copied` : 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 }+ onProgress({ event: 'complete', message: `Moved ${from} → ${to} — ${parts.join(', ') || 'no models to move'}` })+ console.log(`🔀 Moved models ${from} → ${to} (${linked} linked, ${copied} copied, ${installed} downloaded, ${failed} failed)`)+ return { success: true, from, to, mode, results }}diff --git a/server/services/localLlm.test.js b/server/services/localLlm.test.jsindex 5ecb0593c7..dabc98382e 100644--- a/server/services/localLlm.test.js+++ b/server/services/localLlm.test.js@@ -18,7 +18,8 @@ const mocks = vi.hoisted(() => ({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 }))+ // Echo the requested mode as the real outcome (link mode "succeeds" in tests).+ importModelFromGguf: vi.fn(async ({ name, mode }) => ({ success: true, modelId: name, linked: mode === 'link' }))},lmstudio: {getAvailableModels: vi.fn(async () => []),@@ -28,7 +29,7 @@ const mocks = vi.hoisted(() => ({isAppInstalled: vi.fn(() => false),getLastListError: vi.fn(() => null),resolveLocalModel: vi.fn(async () => null),- importModelFromGguf: vi.fn(async ({ lmstudioId }) => ({ success: true, modelId: lmstudioId }))+ importModelFromGguf: vi.fn(async ({ lmstudioId, mode }) => ({ success: true, modelId: lmstudioId, linked: mode === 'link' }))},providers: {getProviderById: vi.fn(async () => ({ id: 'ollama', enabled: false })),@@ -111,37 +112,51 @@ describe('localLlm', () => {});describe('migrateBackend', () => {- it('re-provisions known source models on the target and flips the marker', async () => {- writeEnv('LLM_BACKEND=lmstudio\n');+ it('moves the OTHER backend\'s known models onto the target WITHOUT changing the default', async () => {+ writeEnv('LLM_BACKEND=lmstudio\n'); // default stays lmstudio throughout+ // Source is always the opposite of the target — here ollama is the target,+ // so lmstudio is the source regardless of which is the default.mocks.lmstudio.getAvailableModels.mockResolvedValueOnce([{ id: 'lmstudio-community/Llama-3.2-3B-Instruct-GGUF' },{ id: 'someorg/Totally-Unknown-GGUF' } // best-effort → ollama bare name]);const events = [];- const r = await svc.migrateBackend('ollama', (e) => events.push(e));+ const r = await svc.migrateBackend('ollama', { onProgress: (e) => events.push(e) });expect(r.success).toBe(true);- expect(r.backend).toBe('ollama');+ expect(r.from).toBe('lmstudio');+ expect(r.to).toBe('ollama');expect(mocks.ollama.pullModel).toHaveBeenCalledWith('llama3.2', expect.any(Function));expect(r.results.find((x) => x.target === 'llama3.2').status).toBe('installed');- expect(svc.getBackend()).toBe('ollama');+ expect(svc.getBackend()).toBe('lmstudio'); // default marker untouched+ expect(mocks.providers.updateProvider).not.toHaveBeenCalled(); // providers untouchedexpect(events.at(-1).event).toBe('complete');});+ it('returns success with no results when the source backend has no models', async () => {+ // Target ollama → source lmstudio (empty).+ mocks.lmstudio.getAvailableModels.mockResolvedValueOnce([]);+ const r = await svc.migrateBackend('ollama');+ expect(r.success).toBe(true);+ expect(r.results).toEqual([]);+ expect(mocks.ollama.pullModel).not.toHaveBeenCalled();+ expect(mocks.ollama.importModelFromGguf).not.toHaveBeenCalled();+ });+it('skips a model with no known target equivalent (→ LM Studio)', async () => {- writeEnv('LLM_BACKEND=ollama\n');+ // Target lmstudio → source ollama.mocks.ollama.getInstalledModels.mockResolvedValueOnce([{ id: 'custom-unlisted:latest', name: 'custom-unlisted:latest' }]);const r = await svc.migrateBackend('lmstudio');+ expect(r.from).toBe('ollama');expect(r.results.find((x) => x.source === 'custom-unlisted:latest').status).toBe('skipped');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');+ it('links a local GGUF to the target instead of downloading (default link mode)', async () => {mocks.lmstudio.getAvailableModels.mockResolvedValueOnce([{ id: 'lmstudio-community/Llama-3.2-3B-Instruct-GGUF' }]);@@ -149,18 +164,33 @@ describe('localLlm', () => {ggufPath: '/models/llama-3.2-3b.gguf', projectorPath: null, isMlx: false, isSharded: false});- const r = await svc.migrateBackend('ollama');+ const r = await svc.migrateBackend('ollama'); // mode defaults to 'link'expect(r.results[0].status).toBe('imported');- expect(mocks.ollama.importModelFromGguf).toHaveBeenCalledWith({ name: 'llama3.2', ggufPath: '/models/llama-3.2-3b.gguf' });+ expect(r.results[0].linked).toBe(true);+ expect(mocks.ollama.importModelFromGguf).toHaveBeenCalledWith({ name: 'llama3.2', ggufPath: '/models/llama-3.2-3b.gguf', mode: 'link' });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');+ it('copies (not links) the local GGUF when mode is "copy"', async () => {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: '/models/llama-3.2-3b.gguf', projectorPath: null, isMlx: false, isSharded: false+ });++ const r = await svc.migrateBackend('ollama', { mode: 'copy' });+ expect(r.mode).toBe('copy');+ expect(r.results[0].status).toBe('imported');+ expect(r.results[0].linked).toBe(false);+ expect(mocks.ollama.importModelFromGguf).toHaveBeenCalledWith({ name: 'llama3.2', ggufPath: '/models/llama-3.2-3b.gguf', mode: 'copy' });+ });++ it('does not local-import an MLX model — falls back to re-pull', async () => {+ mocks.lmstudio.getAvailableModels.mockResolvedValueOnce([+ { id: 'lmstudio-community/Llama-3.2-3B-Instruct-GGUF' }+ ]);+ // MLX dir has no GGUF to link/copy → must re-pull the catalog equivalent.mocks.lmstudio.resolveLocalModel.mockResolvedValueOnce({ggufPath: null, projectorPath: null, isMlx: true, isSharded: false});@@ -172,7 +202,6 @@ describe('localLlm', () => {});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' }]);@@ -186,7 +215,7 @@ describe('localLlm', () => {expect(r.results[0].status).toBe('installed');});- it('does not flip the marker when every provision fails (target unusable)', async () => {+ it('fails (without touching the default or providers) when every provision fails', async () => {writeEnv('LLM_BACKEND=lmstudio\n');mocks.lmstudio.getAvailableModels.mockResolvedValueOnce([{ id: 'lmstudio-community/Llama-3.2-3B-Instruct-GGUF' }@@ -197,18 +226,8 @@ describe('localLlm', () => {const r = await svc.migrateBackend('ollama');expect(r.success).toBe(false);expect(r.error).toMatch(/no models could be provisioned/);- expect(svc.getBackend()).toBe('lmstudio'); // marker left unchanged- expect(mocks.providers.updateProvider).not.toHaveBeenCalled(); // provider not flipped either- });-- it('rejects migrating to the already-active backend (no-op)', async () => {- writeEnv('LLM_BACKEND=ollama\n');- const r = await svc.migrateBackend('ollama');- expect(r.success).toBe(false);- expect(r.error).toMatch(/already the active backend/);- // No source read, no installs attempted.- expect(mocks.ollama.getInstalledModels).not.toHaveBeenCalled();- expect(mocks.lmstudio.getAvailableModels).not.toHaveBeenCalled();+ expect(svc.getBackend()).toBe('lmstudio'); // default left unchanged+ expect(mocks.providers.updateProvider).not.toHaveBeenCalled(); // providers untouched});});diff --git a/server/services/ollamaManager.js b/server/services/ollamaManager.jsindex 1866ce9609..0691d0e0ce 100644--- a/server/services/ollamaManager.js+++ b/server/services/ollamaManager.js@@ -15,10 +15,10 @@*/import { homedir } from 'os'-import { join } from 'path'-import { readdir, stat } from 'fs/promises'+import { join, dirname } from 'path'+import { readdir, stat, link, mkdir } from 'fs/promises'import { fetchWithTimeout } from '../lib/fetchWithTimeout.js'-import { readJSONFile } from '../lib/fileUtils.js'+import { readJSONFile, sha256File } from '../lib/fileUtils.js'import {parseOllamaManifest, parseOllamaModelRef, ollamaManifestRelPath, digestToBlobFilename, buildModelfile} from '../lib/localLlmDisk.js'@@ -284,17 +284,38 @@ async function resolveLocalModel(modelId) {return { ggufPath, projectorPath, isMlx: false, isSharded: false }}+/**+ * Pre-place the source GGUF as a hardlink at `blobs/sha256-<hash>` so the+ * subsequent `/api/create` reuses the existing (content-addressed) blob instead+ * of copying the multi-GB weights — zero extra disk, the file is shared with the+ * source backend's copy. Best-effort: a cross-filesystem hardlink (EXDEV) or any+ * error returns false and the caller's `/api/create` just copies as usual.+ * @returns {Promise<boolean>} whether the blob is now hardlinked+ */+async function prelinkBlob(ggufPath) {+ const hex = await sha256File(ggufPath)+ const blobPath = join(getModelsDir(), 'blobs', digestToBlobFilename(`sha256:${hex}`))+ if (await fileExists(blobPath)) return true // already present (content-addressed dedup)+ await mkdir(dirname(blobPath), { recursive: true })+ await link(ggufPath, blobPath)+ return true+}+/*** 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 }>}+ * In `link` mode the blob is hardlinked into Ollama's store first so create+ * dedups against it (shared on disk); `copy` mode lets create copy the blob.+ * @param {{ name: string, ggufPath: string, mode?: 'link'|'copy' }} args+ * @returns {Promise<{ success: boolean, modelId?: string, linked?: boolean, error?: string }>}*/-async function importModelFromGguf({ name, ggufPath }) {+async function importModelFromGguf({ name, ggufPath, mode = 'copy' }) {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 linked = mode === 'link' ? await prelinkBlob(ggufPath).catch(() => false) : false+ console.log(`📦 Ollama import (${linked ? 'hardlink' : 'copy'}): ${name} ← ${ggufPath}`)+ // No timeout — create may copy the (multi-GB) blob into the store (skipped+ // when we pre-hardlinked a matching blob above).const response = await fetchWithTimeout(`${config.baseUrl}/api/create`, {method: 'POST',headers: { 'Content-Type': 'application/json' },@@ -308,8 +329,8 @@ async function importModelFromGguf({ name, ggufPath }) {const lastError = await streamNdjson(response)if (lastError) return { success: false, error: lastError }installedModels = null- console.log(`✅ Ollama import complete: ${name}`)- return { success: true, modelId: name }+ console.log(`✅ Ollama import complete: ${name}${linked ? ' (hardlinked blob — no extra disk)' : ''}`)+ return { success: true, modelId: name, linked }}/**