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): setup backend choice, model management UI, and Ollama↔LM Studio migrate

Adam Eivyaf691fa4aa0c
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 3e7206a322..f09a65feea 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -1,6 +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.
- **[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/.env.example b/.env.example
index af34d22845..6173114c1d 100644
--- a/.env.example
+++ b/.env.example
@@ -27,9 +27,15 @@ PGPASSWORD=portos
# Chief of Staff runner endpoint (used when CoS runs as a separate process)
# COS_RUNNER_URL=http://localhost:5558
+# Active local LLM backend: "ollama" or "lmstudio" (chosen at setup time; managed in Settings → Local LLMs)
+# LLM_BACKEND=ollama
+
# LM Studio local inference server URL
# LM_STUDIO_URL=http://localhost:1234
+# Ollama local inference server URL (defaults to http://localhost:11434)
+# OLLAMA_URL=http://localhost:11434
+
# Path to the Claude CLI binary (defaults to system PATH)
# CLAUDE_PATH=/usr/local/bin/claude
diff --git a/PLAN.md b/PLAN.md
index e54e9a56dc..539224f2af 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -2,8 +2,14 @@
For project goals, see [GOALS.md](./GOALS.md). For completed work, see [.changelog/](./.changelog/) and `git log`.
+## In Progress
+
+- [x] [local-llm-backend-management] **Local LLM backend (Ollama / LM Studio) setup + model management + migrate.** (1) `scripts/setup-llm.js` prompts at setup time for Ollama vs LM Studio, installs the chosen one if missing, writes `LLM_BACKEND` to `.env`; (2) unified model management UI (list/search/install/delete) mirroring the LoRA/MediaModels pattern, with a curated cross-backend catalog (`server/lib/localLlmCatalog.js`); (3) migrate/switch between Ollama and LM Studio mirroring the Docker↔native Postgres `DatabaseTab`. Server: `server/services/ollamaManager.js`, `server/services/localLlm.js`, `server/routes/localLlm.js`. Client: `client/src/services/apiLocalLlm.js`, `client/src/components/settings/LocalLlmTab.jsx` (Settings tab `local-llm`).
+
## Next Up
+- [ ] [extract-shared-env-file-helper] **Extract a shared `.env` parse/set-key helper.** `parseEnvFile()` + single-key upsert logic is now duplicated three ways: `scripts/setup-db.js` (`setPgMode`), `scripts/setup-llm.js` (`parseEnvFile`/`setBackend`), and `server/services/localLlm.js` (`readEnv`/`writeBackend`). Deferred from the `[local-llm-backend-management]` simplify pass because the two setup scripts are intentionally dependency-light/standalone (run before/around `npm install`) and shouldn't import from `server/lib`. Cleanest fix: a tiny `scripts/lib/envFile.js` shared only between the setup scripts (parse + `upsertEnvKey(path, key, value)`); leave `localLlm.js`'s copy or have it import the same helper if the script→server boundary is acceptable. ~15 lines each.
+
- [ ] [migrate-taskitem-formatattachmentsize-to-formatbytes] **Migrate `TaskItem.jsx`'s local `formatAttachmentSize` to shared `formatBytes`.** `client/src/components/cos/tabs/TaskItem.jsx` still defines a local `formatAttachmentSize(bytes)` (B/KB/MB with `.toFixed(1)`) that duplicates `formatBytes` in `client/src/utils/formatters.js`. Surfaced by gemini review during the `[migrate-two-remaining-local-formatters]` claim 2026-05-24; deferred as out-of-scope for that item (which named only `formatDateTime` + `formatDurationMin`). Note the edge-case semantics differ: the local helper returns `''` for falsy/0 size (used inside an attachment `title` like `(1.5 KB)`), while `formatBytes(0)` returns `'0 B'` — preserve the empty-on-missing behavior with a guard (`att.size ? formatBytes(att.size) : ''`) so the title doesn't render `(0 B)` for sizeless attachments.
- [ ] [optimize-voice-ui-index-text-payload-lazy-only-run] **Optimize `voice:ui:index` text payload.** Lazy: only run `extractVisibleText` when server requests via `voice:ui:read-request`. Keep current behavior as fallback.
- [ ] [voice-agent-explicit-long-term-memory-routing-on] **Voice agent — explicit long-term memory routing.** On retrieval-shaped voice turns, inject top-N relevant memories into the system prompt via `brain_search`.
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsx
index 42f5a0ad74..28af6475e2 100644
--- a/client/src/components/Layout.jsx
+++ b/client/src/components/Layout.jsx
@@ -284,6 +284,7 @@ const navItems = [
{ to: '/settings/backup', label: 'Backup', icon: Download },
{ to: '/settings/database', label: 'Database', icon: Database },
{ to: '/settings/general', label: 'General', icon: Settings },
+ { to: '/settings/local-llm', label: 'Local LLMs', icon: Cpu },
{ to: '/settings/mortalloom', label: 'MortalLoom', icon: Activity },
{ to: '/prompts', label: 'Prompts', icon: FileText },
{ to: '/ai', label: 'Providers', icon: Bot },
diff --git a/client/src/components/settings/LocalLlmTab.jsx b/client/src/components/settings/LocalLlmTab.jsx
new file mode 100644
index 0000000000..9b5a6a6dba
--- /dev/null
+++ b/client/src/components/settings/LocalLlmTab.jsx
@@ -0,0 +1,326 @@
+import { useState, useEffect, useRef, useCallback } from 'react';
+import { Cpu, Box, ArrowRightLeft, Download, Trash2, RefreshCw, Search, Plus } from 'lucide-react';
+import toast from '../ui/Toast';
+import BrailleSpinner from '../BrailleSpinner';
+import { formatBytes } from '../../utils/formatters';
+import {
+ getLocalLlmStatus, getLocalLlmCatalog, installLocalLlmModel,
+ deleteLocalLlmModel, switchLocalLlmBackend, migrateLocalLlmBackend
+} from '../../services/api';
+import socket from '../../services/socket';
+
+const BACKENDS = [
+ { id: 'ollama', label: 'Ollama', icon: Cpu },
+ { id: 'lmstudio', label: 'LM Studio', icon: Box }
+];
+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 }) {
+ const data = status?.[backend.id];
+ const Icon = backend.icon;
+ const other = backend.id === 'ollama' ? 'lmstudio' : 'ollama';
+ 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';
+
+ return (
+ <div className="bg-port-bg border border-port-border rounded-lg p-3 space-y-2">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2 text-sm text-gray-400">
+ <Icon size={14} />
+ {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}`} />
+ </div>
+ </div>
+
+ <div className="text-sm text-white">{statusLabel}</div>
+ <div className="text-xs text-gray-400">
+ {data?.modelCount ?? 0} model{(data?.modelCount ?? 0) === 1 ? '' : 's'} installed
+ {data?.version && <> · v{data.version}</>}
+ </div>
+
+ {!isActive && (
+ <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: `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.`,
+ 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>
+ </div>
+ )}
+ </div>
+ );
+}
+
+export function LocalLlmTab() {
+ const [status, setStatus] = useState(null);
+ const [loading, setLoading] = useState(true);
+ const [selected, setSelected] = useState('ollama');
+ const [catalog, setCatalog] = useState([]);
+ const [query, setQuery] = useState('');
+ const [manualId, setManualId] = useState('');
+ const [actionInProgress, setActionInProgress] = useState(null);
+ const [progressMsg, setProgressMsg] = useState('');
+ const [confirmAction, setConfirmAction] = useState(null);
+ const progressTimer = useRef(null);
+ const selectedInitialized = useRef(false);
+
+ const loadStatus = useCallback(() => {
+ setLoading(true);
+ return getLocalLlmStatus()
+ .then((s) => {
+ setStatus(s);
+ // Default the model-management view to the active backend on first load.
+ if (!selectedInitialized.current && s?.backend) {
+ setSelected(s.backend);
+ selectedInitialized.current = true;
+ }
+ })
+ .catch(() => toast.error('Failed to load local LLM status'))
+ .finally(() => setLoading(false));
+ }, []);
+
+ const loadCatalog = useCallback((backend, q) => {
+ getLocalLlmCatalog(backend, q)
+ .then((r) => setCatalog(r.models || []))
+ .catch(() => setCatalog([]));
+ }, []);
+
+ useEffect(() => { loadStatus(); }, [loadStatus]);
+ // Debounce so typing in the search box doesn't fire a request per keystroke.
+ useEffect(() => {
+ const t = setTimeout(() => loadCatalog(selected, query), 250);
+ return () => clearTimeout(t);
+ }, [selected, query, loadCatalog]);
+
+ useEffect(() => {
+ const handleProgress = (data) => {
+ clearTimeout(progressTimer.current);
+ setProgressMsg(data.message || '');
+ if (data.event === 'complete') {
+ progressTimer.current = setTimeout(() => setProgressMsg(''), 3000);
+ loadStatus();
+ loadCatalog(selected, query);
+ }
+ if (data.event === 'error') {
+ progressTimer.current = setTimeout(() => setProgressMsg(''), 5000);
+ }
+ };
+ socket.on('localLlm:progress', handleProgress);
+ return () => {
+ socket.off('localLlm:progress', handleProgress);
+ clearTimeout(progressTimer.current);
+ };
+ }, [loadStatus, loadCatalog, selected, query]);
+
+ const runAction = useCallback((key, fn, successMsg) => {
+ setConfirmAction(null);
+ setActionInProgress(key);
+ return fn()
+ .then((result) => {
+ if (successMsg) toast.success(typeof successMsg === 'function' ? successMsg(result) : successMsg);
+ loadStatus();
+ loadCatalog(selected, query);
+ })
+ .catch(() => { /* request() surfaces API errors as a toast */ })
+ .finally(() => setActionInProgress(null));
+ }, [loadStatus, loadCatalog, selected, query]);
+
+ const busy = actionInProgress != null;
+ const selectedData = status?.[selected];
+ const installedModels = selectedData?.models || [];
+
+ const install = (modelId) => runAction(`install-${modelId}`, () => installLocalLlmModel(selected, modelId), `${modelId} installed`);
+ const remove = (modelId) => runAction(`delete-${modelId}`, () => deleteLocalLlmModel(selected, modelId), `${modelId} deleted`);
+
+ return (
+ <div className="space-y-4">
+ {/* Backends — status + switch/migrate */}
+ <div className="bg-port-card border border-port-border rounded-xl p-4 sm:p-6 space-y-4">
+ <div className="flex items-center justify-between">
+ <h2 className="text-sm font-medium text-gray-300">Local LLM Backends</h2>
+ <button onClick={loadStatus} disabled={loading} className="p-1.5 text-gray-400 hover:text-white transition-colors" title="Refresh">
+ <RefreshCw size={14} className={loading ? 'animate-spin' : ''} />
+ </button>
+ </div>
+
+ {loading && !status ? (
+ <BrailleSpinner text="Loading local LLM status" />
+ ) : status ? (
+ <>
+ <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}
+ busy={busy} actionInProgress={actionInProgress}
+ runAction={runAction} setConfirmAction={setConfirmAction}
+ />
+ ))}
+ </div>
+
+ {progressMsg && (
+ <div className="flex items-center gap-2 text-sm text-port-accent bg-port-accent/10 border border-port-accent/20 rounded-lg px-3 py-2">
+ <BrailleSpinner />
+ {progressMsg}
+ </div>
+ )}
+
+ {confirmAction && (
+ <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">
+ <button
+ onClick={confirmAction.action}
+ 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"
+ >
+ {busy ? <BrailleSpinner /> : <ArrowRightLeft size={14} />}
+ Confirm
+ </button>
+ <button onClick={() => setConfirmAction(null)} className="px-3 py-1.5 text-sm text-gray-400 hover:text-white transition-colors">
+ Cancel
+ </button>
+ </div>
+ </div>
+ )}
+ </>
+ ) : (
+ <p className="text-sm text-gray-500">Unable to load local LLM status</p>
+ )}
+ </div>
+
+ {/* Models — backend picker + catalog/install + installed list */}
+ <div className="bg-port-card border border-port-border rounded-xl p-4 sm:p-6 space-y-4">
+ <div className="flex items-center justify-between gap-3 flex-wrap">
+ <h2 className="text-sm font-medium text-gray-300">Models</h2>
+ <div className="flex items-center gap-1.5">
+ {BACKENDS.map((b) => (
+ <button
+ key={b.id}
+ onClick={() => setSelected(b.id)}
+ className={`px-2.5 py-1 text-xs rounded transition-colors ${selected === b.id ? 'bg-port-accent/20 text-port-accent' : 'bg-port-bg text-gray-400 hover:text-white'}`}
+ >
+ {b.label}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ {selectedData && !selectedData.available && (
+ <p className="text-xs text-port-warning">
+ {labelFor(selected)} isn't running — {selectedData.installed
+ ? `start it to install or manage models${selected === 'ollama' ? ' (run \`ollama serve\`)' : ' (launch the app and enable the local server)'}.`
+ : 'install it first (Settings → Local LLMs prompts at setup, or run `npm run setup:llm`).'}
+ </p>
+ )}
+
+ {/* Free-text install + search */}
+ <div className="flex flex-col sm:flex-row gap-2">
+ <div className="flex-1 flex items-center gap-2 bg-port-bg border border-port-border rounded-lg px-3">
+ <Search size={14} className="text-gray-500" />
+ <input
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ placeholder={`Search the ${labelFor(selected)} catalog…`}
+ className="flex-1 bg-transparent py-2 text-sm text-white placeholder-gray-600 focus:outline-none"
+ />
+ </div>
+ <div className="flex items-center gap-2">
+ <input
+ value={manualId}
+ onChange={(e) => setManualId(e.target.value)}
+ placeholder={selected === 'ollama' ? 'pull by name e.g. llama3.2' : 'publisher/Model-GGUF'}
+ className="flex-1 sm:w-56 bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white placeholder-gray-600 focus:outline-none focus:border-port-accent"
+ />
+ <button
+ onClick={() => { const id = manualId.trim(); if (id) { install(id); setManualId(''); } }}
+ disabled={busy || !manualId.trim()}
+ className="flex items-center gap-1.5 px-3 py-2 bg-port-accent/20 hover:bg-port-accent/30 text-port-accent text-sm font-medium rounded-lg disabled:opacity-50"
+ >
+ <Plus size={14} /> Install
+ </button>
+ </div>
+ </div>
+
+ {/* Catalog cards */}
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-2">
+ {catalog.map((m) => (
+ <div key={m.id} className="flex items-start gap-3 bg-port-bg border border-port-border rounded-lg p-3">
+ <div className="flex-1 min-w-0">
+ <div className="text-sm text-white truncate">{m.name} <span className="text-xs text-gray-500">· {m.params}</span></div>
+ <div className="text-xs text-gray-500 truncate">{m.id}</div>
+ <div className="text-xs text-gray-500 mt-0.5">{m.description}</div>
+ <div className="text-[11px] text-gray-600 mt-0.5">{m.size} · {(m.capabilities || []).join(', ')}</div>
+ </div>
+ {m.installed ? (
+ <span className="text-xs px-2 py-1 text-port-success shrink-0">Installed</span>
+ ) : (
+ <button
+ onClick={() => install(m.id)}
+ disabled={busy}
+ className="px-2.5 py-1 text-xs bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded disabled:opacity-50 flex items-center gap-1 shrink-0"
+ >
+ {actionInProgress === `install-${m.id}` ? <BrailleSpinner /> : <Download size={12} />}
+ Install
+ </button>
+ )}
+ </div>
+ ))}
+ {catalog.length === 0 && (
+ <p className="text-xs text-gray-500">No catalog matches{query ? ` for "${query}"` : ''}.</p>
+ )}
+ </div>
+
+ {/* Installed models */}
+ <div className="space-y-2 pt-2 border-t border-port-border/50">
+ <h3 className="text-xs font-medium text-gray-400">Installed on {labelFor(selected)} ({installedModels.length})</h3>
+ {installedModels.length === 0 ? (
+ <p className="text-xs text-gray-500">No models installed yet.</p>
+ ) : installedModels.map((m) => (
+ <div key={m.id} className="flex items-center gap-3 bg-port-bg border border-port-border rounded-lg p-3">
+ <div className="flex-1 min-w-0">
+ <div className="text-sm text-white truncate">{m.name}</div>
+ <div className="text-xs text-gray-500 truncate">
+ {[m.params, m.quantization, m.family].filter(Boolean).join(' · ')}
+ </div>
+ </div>
+ {m.size != null && <span className="text-xs text-gray-400 shrink-0">{formatBytes(m.size)}</span>}
+ <button
+ onClick={() => remove(m.id)}
+ disabled={busy}
+ className="px-2.5 py-1 text-xs bg-port-error/20 hover:bg-port-error/40 text-port-error rounded disabled:opacity-50 flex items-center gap-1 shrink-0"
+ >
+ {actionInProgress === `delete-${m.id}` ? <BrailleSpinner /> : <Trash2 size={12} />}
+ Delete
+ </button>
+ </div>
+ ))}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+export default LocalLlmTab;
diff --git a/client/src/components/settings/SettingsTabsHeader.jsx b/client/src/components/settings/SettingsTabsHeader.jsx
index f40440f4ce..c9e274182b 100644
--- a/client/src/components/settings/SettingsTabsHeader.jsx
+++ b/client/src/components/settings/SettingsTabsHeader.jsx
@@ -13,6 +13,7 @@ const TABS = [
{ id: 'backup', label: 'Backup', to: '/settings/backup' },
{ id: 'database', label: 'Database', to: '/settings/database' },
{ id: 'general', label: 'General', to: '/settings/general' },
+ { id: 'local-llm', label: 'Local LLMs', to: '/settings/local-llm' },
{ id: 'mortalloom', label: 'MortalLoom', to: '/settings/mortalloom' },
{ id: 'prompts', label: 'Prompts', to: '/prompts' },
{ id: 'providers', label: 'Providers', to: '/ai' },
diff --git a/client/src/pages/Settings.jsx b/client/src/pages/Settings.jsx
index dee0bdf4dd..d0964ad69b 100644
--- a/client/src/pages/Settings.jsx
+++ b/client/src/pages/Settings.jsx
@@ -1,6 +1,7 @@
import { useParams, Navigate } from 'react-router-dom';
import { BackupTab } from '../components/settings/BackupTab';
import { DatabaseTab } from '../components/settings/DatabaseTab';
+import { LocalLlmTab } from '../components/settings/LocalLlmTab';
import { TelegramTab } from '../components/settings/TelegramTab';
import { GeneralTab } from '../components/settings/GeneralTab';
import { MortalLoomTab } from '../components/settings/MortalLoomTab';
@@ -28,6 +29,7 @@ export default function Settings() {
case 'general': return <GeneralTab />;
case 'backup': return <BackupTab />;
case 'database': return <DatabaseTab />;
+ case 'local-llm': return <LocalLlmTab />;
case 'sharing': return <SharingTab />;
case 'voice': return <VoiceTab />;
case 'telegram': return <TelegramTab />;
diff --git a/client/src/services/README.md b/client/src/services/README.md
index a7f771be67..c7e2aef251 100644
--- a/client/src/services/README.md
+++ b/client/src/services/README.md
@@ -42,6 +42,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire
| `apiCommands.js` | CLI command dispatch. |
| `apiDashboard.js` | Dashboard state. |
| `apiDatabase.js` | Database introspection. |
+| `apiLocalLlm.js` | Local LLM backends (Ollama / LM Studio): status, model list/catalog/install/delete, switch/migrate. |
| `apiGit.js` | Git operations. |
| `apiGithub.js` | GitHub repo metadata. |
| `apiHistory.js` | Historical logs / runs. |
diff --git a/client/src/services/api.js b/client/src/services/api.js
index 655619a83b..7fd02f3486 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -23,6 +23,7 @@ export * from './apiCalendar.js';
export * from './apiGoals.js';
export * from './apiReview.js';
export * from './apiDatabase.js';
+export * from './apiLocalLlm.js';
export * from './apiGSD.js';
export * from './apiGithub.js';
export * from './apiLoops.js';
diff --git a/client/src/services/apiLocalLlm.js b/client/src/services/apiLocalLlm.js
new file mode 100644
index 0000000000..d2aee7df79
--- /dev/null
+++ b/client/src/services/apiLocalLlm.js
@@ -0,0 +1,22 @@
+import { request } from './apiCore.js';
+
+// Local LLM backends (Ollama / LM Studio) — status, model management, migrate.
+export const getLocalLlmStatus = () => request('/local-llm/status');
+
+export const getLocalLlmModels = (backend) =>
+ request(`/local-llm/models?backend=${encodeURIComponent(backend)}`);
+
+export const getLocalLlmCatalog = (backend, q = '') =>
+ request(`/local-llm/catalog?backend=${encodeURIComponent(backend)}${q ? `&q=${encodeURIComponent(q)}` : ''}`);
+
+export const installLocalLlmModel = (backend, modelId) =>
+ request('/local-llm/install', { method: 'POST', body: JSON.stringify({ backend, modelId }) });
+
+export const deleteLocalLlmModel = (backend, modelId) =>
+ request('/local-llm/delete', { method: 'POST', body: JSON.stringify({ backend, modelId }) });
+
+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 }) });
diff --git a/package.json b/package.json
index 443dc837a5..d0accb58e6 100644
--- a/package.json
+++ b/package.json
@@ -20,9 +20,10 @@
"pm2:startup": "node ./node_modules/pm2/bin/pm2 startup",
"install:all": "npm run setup",
"migrations": "node scripts/run-migrations.js",
- "setup": "git submodule update --init --recursive && npm install && npm install --prefix client && npm install --prefix server && npm install --prefix autofixer && node client/node_modules/esbuild/install.js && node server/node_modules/esbuild/install.js && npm rebuild node-pty sharp --prefix server && node scripts/setup-data.js && node scripts/setup-db.js && node scripts/setup-browser.js",
+ "setup": "git submodule update --init --recursive && npm install && npm install --prefix client && npm install --prefix server && npm install --prefix autofixer && node client/node_modules/esbuild/install.js && node server/node_modules/esbuild/install.js && npm rebuild node-pty sharp --prefix server && node scripts/setup-data.js && node scripts/setup-db.js && node scripts/setup-llm.js && node scripts/setup-browser.js",
"setup:data": "node scripts/setup-data.js",
"setup:db": "node scripts/setup-db.js",
+ "setup:llm": "node scripts/setup-llm.js",
"setup:browser": "node scripts/setup-browser.js",
"setup:cert": "node scripts/setup-cert.js",
"setup:ghostty": "node scripts/setup-ghostty.js",
diff --git a/scripts/setup-llm.js b/scripts/setup-llm.js
new file mode 100644
index 0000000000..612e64c261
--- /dev/null
+++ b/scripts/setup-llm.js
@@ -0,0 +1,158 @@
+#!/usr/bin/env node
+
+/**
+ * Local LLM Setup Script
+ *
+ * Lets the user pick a local-LLM backend (Ollama or LM Studio) and installs
+ * the chosen one if it isn't present. The choice is recorded in `.env` as
+ * `LLM_BACKEND`; the server enables the matching provider on boot.
+ *
+ * Idempotent: if `LLM_BACKEND` is already set, this reports status and exits
+ * without re-prompting. Non-interactive (CI / piped) runs skip silently.
+ *
+ * Called by: npm run setup (and `npm run setup:llm` directly).
+ */
+
+import { execFileSync } from 'child_process';
+import { createInterface } from 'readline';
+import { dirname, join } from 'path';
+import { fileURLToPath } from 'url';
+import { existsSync, readFileSync, writeFileSync } from 'fs';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const rootDir = join(__dirname, '..');
+const envPath = join(rootDir, '.env');
+
+function parseEnvFile() {
+ const result = {};
+ let content = '';
+ try { content = readFileSync(envPath, 'utf8'); } catch { return result; }
+ for (const line of content.split('\n')) {
+ const trimmed = line.trim();
+ if (!trimmed || trimmed.startsWith('#')) continue;
+ const idx = trimmed.indexOf('=');
+ if (idx === -1) continue;
+ result[trimmed.slice(0, idx).trim()] = trimmed.slice(idx + 1).trim();
+ }
+ return result;
+}
+
+function setBackend(backend) {
+ let content = '';
+ try { content = readFileSync(envPath, 'utf8'); } catch { /* no .env yet */ }
+ if (/^LLM_BACKEND=/m.test(content)) {
+ content = content.replace(/^LLM_BACKEND=.*/m, `LLM_BACKEND=${backend}`);
+ } else {
+ content = `LLM_BACKEND=${backend}\n${content}`;
+ }
+ writeFileSync(envPath, content);
+ console.log(`✅ Local LLM backend set to ${backend} (LLM_BACKEND in .env)`);
+}
+
+function hasCommand(cmd, args) {
+ try { execFileSync(cmd, args, { stdio: 'pipe' }); return true; } catch { return false; }
+}
+
+const hasBrew = () => hasCommand('brew', ['--version']);
+const hasOllama = () => hasCommand('ollama', ['--version']);
+const hasLmStudio = () =>
+ hasCommand('lms', ['version']) ||
+ (process.platform === 'darwin' && existsSync('/Applications/LM Studio.app'));
+
+function installOllama() {
+ const platform = process.platform;
+ try {
+ if (platform === 'darwin' && hasBrew()) {
+ console.log('🍺 Installing Ollama via Homebrew...');
+ execFileSync('brew', ['install', 'ollama'], { stdio: 'inherit' });
+ console.log(' Start it with: ollama serve (or `brew services start ollama`)');
+ return true;
+ }
+ if (platform === 'linux') {
+ console.log('⬇️ Installing Ollama via official script...');
+ execFileSync('bash', ['-c', 'curl -fsSL https://ollama.com/install.sh | sh'], { stdio: 'inherit' });
+ return true;
+ }
+ } catch (err) {
+ console.error(`⚠️ Ollama install failed: ${err.message}`);
+ }
+ console.log(' Download Ollama manually: https://ollama.com/download');
+ return false;
+}
+
+function installLmStudio() {
+ try {
+ if (process.platform === 'darwin' && hasBrew()) {
+ console.log('🍺 Installing LM Studio via Homebrew...');
+ execFileSync('brew', ['install', '--cask', 'lm-studio'], { stdio: 'inherit' });
+ console.log(' Launch LM Studio, then enable the local server (Developer tab) and run: lms bootstrap');
+ return true;
+ }
+ } catch (err) {
+ console.error(`⚠️ LM Studio install failed: ${err.message}`);
+ }
+ console.log(' Download LM Studio manually: https://lmstudio.ai/download');
+ return false;
+}
+
+function promptChoice() {
+ return new Promise((resolve) => {
+ console.log('🧠 Choose a local LLM backend (for free, on-device models):');
+ console.log('');
+ console.log(' 1) Ollama (CLI-first, simple `ollama pull`, great default)');
+ console.log(' 2) LM Studio (GUI app with a built-in model browser)');
+ console.log(' 3) Skip (configure later in Settings → Local LLMs)');
+ console.log('');
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
+ rl.question(' Enter choice [1/2/3]: ', (answer) => {
+ rl.close();
+ const t = answer.trim();
+ resolve(t === '1' ? 'ollama' : t === '2' ? 'lmstudio' : 'skip');
+ });
+ });
+}
+
+function promptYesNo(question) {
+ return new Promise((resolve) => {
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
+ rl.question(` ${question} [y/N]: `, (answer) => {
+ rl.close();
+ resolve(/^y(es)?$/i.test(answer.trim()));
+ });
+ });
+}
+
+const env = parseEnvFile();
+const existing = env.LLM_BACKEND || process.env.LLM_BACKEND;
+
+if (existing === 'ollama' || existing === 'lmstudio') {
+ const installed = existing === 'ollama' ? hasOllama() : hasLmStudio();
+ console.log(`🧠 Local LLM backend: ${existing}${installed ? ' (installed)' : ' — not detected, install it to use local models'}`);
+ process.exit(0);
+}
+
+// Non-interactive: don't block setup / CI. Leave LLM_BACKEND unset.
+if (!process.stdin.isTTY || !process.stdout.isTTY) {
+ console.log('🧠 No local LLM backend selected — set one later in Settings → Local LLMs (or `npm run setup:llm`).');
+ process.exit(0);
+}
+
+const choice = await promptChoice();
+
+if (choice === 'skip') {
+ console.log(' Skipped — pick a backend later in Settings → Local LLMs.');
+ process.exit(0);
+}
+
+const alreadyInstalled = choice === 'ollama' ? hasOllama() : hasLmStudio();
+if (!alreadyInstalled) {
+ const label = choice === 'ollama' ? 'Ollama' : 'LM Studio';
+ const yes = await promptYesNo(`${label} is not installed. Install it now?`);
+ if (yes) {
+ (choice === 'ollama' ? installOllama : installLmStudio)();
+ } else {
+ console.log(` Skipping install — you can install ${label} later, the choice is still saved.`);
+ }
+}
+
+setBackend(choice);
diff --git a/server/index.js b/server/index.js
index 512edbaff5..f5c9dd6534 100644
--- a/server/index.js
+++ b/server/index.js
@@ -68,6 +68,7 @@ import jiraRoutes from './routes/jira.js';
import autobiographyRoutes from './routes/autobiography.js';
import backupRoutes from './routes/backup.js';
import databaseRoutes from './routes/database.js';
+import localLlmRoutes from './routes/localLlm.js';
import searchRoutes from './routes/search.js';
import paletteRoutes from './routes/palette.js';
import dashboardLayoutsRoutes from './routes/dashboardLayouts.js';
@@ -269,6 +270,13 @@ try {
console.error(`❌ Failed to load providers at startup: ${err.message}`);
}
+// Ensure the provider paired with the active local-LLM backend (LLM_BACKEND in
+// .env, chosen at setup time) is enabled, so a fresh install can use Ollama /
+// LM Studio for runs without hand-toggling it in the Providers UI.
+import { ensureBackendProvider, getBackend as getLocalLlmBackend } from './services/localLlm.js';
+ensureBackendProvider(getLocalLlmBackend()).catch((err) =>
+ console.error(`⚠️ Failed to enable local LLM backend provider: ${err.message}`));
+
// Swap the toolkit's generic executeCliRun for PortOS's variant that adds
// CLI-provider-specific args building (Codex `exec -`, Gemini stdin piping,
// Claude Code `-p -`). The toolkit's in-tree implementation is also safe
@@ -404,6 +412,7 @@ app.use('/api/digital-twin/identity', identityRoutes);
app.use('/api/digital-twin/autobiography', autobiographyRoutes);
app.use('/api/digital-twin', digitalTwinRoutes);
app.use('/api/lmstudio', lmstudioRoutes);
+app.use('/api/local-llm', localLlmRoutes);
app.use('/api/voice', voiceRoutes);
app.use('/api/browser', browserRoutes);
app.use('/api/data', dataManagerRoutes);
diff --git a/server/lib/README.md b/server/lib/README.md
index 1aa502e3e5..5fdb3c3ee0 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -143,6 +143,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. |
| `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 0e28c766a4..b9ff629507 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -113,6 +113,7 @@ export * from './curatedGenomeMarkers.js';
// === Domain utilities ===
export * from './capabilityMap.js';
export * from './civitai.js';
+export * from './localLlmCatalog.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
new file mode 100644
index 0000000000..9a2f664d1f
--- /dev/null
+++ b/server/lib/localLlmCatalog.js
@@ -0,0 +1,260 @@
+// 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.
+//
+// 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
+// (server/services/localLlm.js) which knows what's actually on disk.
+
+export const BACKENDS = ['ollama', 'lmstudio'];
+
+export const isBackend = (b) => BACKENDS.includes(b);
+
+// Each entry: { key, name, params, size, family, description, capabilities,
+// ollama?, lmstudio? }
+// `ollama` / `lmstudio` are the exact pull/download ids for that backend.
+// A missing id means there is no well-known build of that model for that
+// backend (the user can still free-text install one).
+export const LOCAL_LLM_CATALOG = [
+ {
+ key: 'llama3.2',
+ name: 'Llama 3.2 3B',
+ params: '3B',
+ size: '2.0 GB',
+ family: 'llama',
+ description: "Meta's compact general-purpose chat model. Fast on most machines.",
+ capabilities: ['chat', 'tools'],
+ ollama: 'llama3.2',
+ lmstudio: 'lmstudio-community/Llama-3.2-3B-Instruct-GGUF'
+ },
+ {
+ key: 'llama3.1',
+ name: 'Llama 3.1 8B',
+ params: '8B',
+ size: '4.7 GB',
+ family: 'llama',
+ description: "Meta's mid-size instruct model — a solid general default.",
+ capabilities: ['chat', 'tools'],
+ ollama: 'llama3.1',
+ lmstudio: 'lmstudio-community/Meta-Llama-3.1-8B-Instruct-GGUF'
+ },
+ {
+ key: 'qwen2.5',
+ name: 'Qwen2.5 7B',
+ params: '7B',
+ size: '4.7 GB',
+ family: 'qwen',
+ description: "Alibaba's strong multilingual instruct model with good tool use.",
+ capabilities: ['chat', 'tools'],
+ ollama: 'qwen2.5',
+ lmstudio: 'lmstudio-community/Qwen2.5-7B-Instruct-GGUF'
+ },
+ {
+ key: 'qwen2.5-coder',
+ name: 'Qwen2.5 Coder 7B',
+ params: '7B',
+ size: '4.7 GB',
+ family: 'qwen',
+ description: 'Code-specialised Qwen2.5 — strong at completion and refactors.',
+ capabilities: ['chat', 'code'],
+ ollama: 'qwen2.5-coder',
+ lmstudio: 'lmstudio-community/Qwen2.5-Coder-7B-Instruct-GGUF'
+ },
+ {
+ key: 'mistral',
+ name: 'Mistral 7B',
+ params: '7B',
+ size: '4.1 GB',
+ family: 'mistral',
+ description: 'Fast, capable 7B instruct model that runs well on modest GPUs.',
+ capabilities: ['chat'],
+ ollama: 'mistral',
+ lmstudio: 'lmstudio-community/Mistral-7B-Instruct-v0.3-GGUF'
+ },
+ {
+ key: 'gemma2',
+ name: 'Gemma 2 9B',
+ params: '9B',
+ size: '5.4 GB',
+ family: 'gemma',
+ description: "Google's Gemma 2 instruct model — strong reasoning for its size.",
+ capabilities: ['chat'],
+ ollama: 'gemma2',
+ lmstudio: 'lmstudio-community/gemma-2-9b-it-GGUF'
+ },
+ {
+ key: 'phi3',
+ name: 'Phi-3 Mini',
+ params: '3.8B',
+ size: '2.3 GB',
+ family: 'phi',
+ description: "Microsoft's small-but-capable model with a long context window.",
+ capabilities: ['chat'],
+ ollama: 'phi3',
+ lmstudio: 'lmstudio-community/Phi-3.1-mini-128k-instruct-GGUF'
+ },
+ {
+ key: 'deepseek-r1',
+ name: 'DeepSeek-R1 Distill 7B',
+ params: '7B',
+ size: '4.7 GB',
+ family: 'deepseek',
+ description: 'Reasoning-tuned distill — good local "thinking" model.',
+ capabilities: ['chat', 'reasoning'],
+ ollama: 'deepseek-r1',
+ lmstudio: 'lmstudio-community/DeepSeek-R1-Distill-Qwen-7B-GGUF'
+ },
+ {
+ key: 'gpt-oss-20b',
+ name: 'GPT-OSS 20B',
+ params: '20B',
+ size: '12 GB',
+ family: 'gpt-oss',
+ description: 'Open-weights 20B model — the default local thinking model.',
+ capabilities: ['chat', 'reasoning'],
+ ollama: 'gpt-oss:20b',
+ lmstudio: 'lmstudio-community/gpt-oss-20b-GGUF'
+ },
+ {
+ key: 'llava',
+ name: 'LLaVA 7B (vision)',
+ params: '7B',
+ size: '4.5 GB',
+ family: 'llava',
+ description: 'Vision-language model — answers questions about images.',
+ capabilities: ['chat', 'vision'],
+ ollama: 'llava',
+ lmstudio: 'lmstudio-community/llava-v1.5-7b-GGUF'
+ },
+ {
+ key: 'codellama',
+ name: 'Code Llama 7B',
+ params: '7B',
+ size: '3.8 GB',
+ family: 'llama',
+ description: "Meta's code-specialised Llama for completion and infilling.",
+ capabilities: ['chat', 'code'],
+ ollama: 'codellama',
+ lmstudio: 'lmstudio-community/CodeLlama-7b-Instruct-GGUF'
+ },
+ {
+ key: 'smollm2',
+ name: 'SmolLM2 1.7B',
+ params: '1.7B',
+ size: '1.1 GB',
+ family: 'smollm',
+ description: 'Tiny, fast model for quick classification and routing tasks.',
+ capabilities: ['chat'],
+ ollama: 'smollm2',
+ lmstudio: 'lmstudio-community/SmolLM2-1.7B-Instruct-GGUF'
+ },
+ {
+ key: 'nomic-embed-text',
+ name: 'Nomic Embed Text',
+ params: '137M',
+ size: '274 MB',
+ family: 'embedding',
+ description: 'Text embedding model for semantic search / memory recall.',
+ capabilities: ['embeddings'],
+ ollama: 'nomic-embed-text',
+ lmstudio: 'nomic-ai/nomic-embed-text-v1.5-GGUF'
+ }
+];
+
+// Strip an Ollama tag suffix (`llama3.2:latest` → `llama3.2`) and lowercase.
+const normalizeOllamaId = (id) => String(id || '').split(':')[0].trim().toLowerCase();
+
+// Reduce an LM Studio / HuggingFace id to a comparable stem:
+// `lmstudio-community/Llama-3.2-3B-Instruct-GGUF` → `llama-3.2-3b-instruct`.
+const normalizeLmStudioId = (id) => String(id || '')
+ .split('/').pop()
+ .trim()
+ .toLowerCase()
+ .replace(/[-.]gguf$/i, '')
+ .replace(/-gguf$/i, '');
+
+const normalizeFor = (backend, id) =>
+ backend === 'ollama' ? normalizeOllamaId(id) : normalizeLmStudioId(id);
+
+/**
+ * Return the catalog projected onto a single backend: only entries that ship
+ * a known build for `backend`, each with the backend-specific install id
+ * surfaced as `id`. Pure — pass installed ids to overlay an `installed` flag.
+ *
+ * @param {string} backend - 'ollama' | 'lmstudio'
+ * @param {string[]} [installedIds] - ids currently installed on that backend
+ * @returns {Array<{ id, key, name, params, size, family, description, capabilities, installed }>}
+ */
+export function getCatalog(backend, installedIds = []) {
+ if (!isBackend(backend)) return [];
+ const installedNorm = new Set(installedIds.map((id) => normalizeFor(backend, id)));
+ return LOCAL_LLM_CATALOG
+ .filter((entry) => entry[backend])
+ .map((entry) => ({
+ id: entry[backend],
+ key: entry.key,
+ name: entry.name,
+ params: entry.params,
+ size: entry.size,
+ family: entry.family,
+ description: entry.description,
+ capabilities: entry.capabilities,
+ installed: installedNorm.has(normalizeFor(backend, entry[backend]))
+ }));
+}
+
+/**
+ * Filter the per-backend catalog by a free-text query against name, id,
+ * family, and description. Empty query returns the full catalog.
+ */
+export function searchCatalog(backend, query, installedIds = []) {
+ const all = getCatalog(backend, installedIds);
+ const q = String(query || '').trim().toLowerCase();
+ if (!q) return all;
+ return all.filter((m) =>
+ m.name.toLowerCase().includes(q) ||
+ m.id.toLowerCase().includes(q) ||
+ m.family.toLowerCase().includes(q) ||
+ m.description.toLowerCase().includes(q));
+}
+
+/**
+ * Map an installed model id on `fromBackend` to the equivalent install id on
+ * `toBackend`, used by the migrate flow.
+ *
+ * Returns `{ targetId, exact }`:
+ * - `exact: true` — a curated catalog entry matched and the target build is known.
+ * - `exact: false` — best-effort derived name (only when the target is Ollama,
+ * which can pull bare model names); `targetId` is null when no reasonable
+ * guess exists (e.g. mapping an unknown model TO LM Studio needs a HF repo).
+ */
+export function mapModelToBackend(fromBackend, modelId, toBackend) {
+ if (!isBackend(fromBackend) || !isBackend(toBackend) || fromBackend === toBackend) {
+ return { targetId: null, exact: false };
+ }
+ const fromNorm = normalizeFor(fromBackend, modelId);
+ const entry = LOCAL_LLM_CATALOG.find(
+ (e) => e[fromBackend] && normalizeFor(fromBackend, e[fromBackend]) === fromNorm
+ );
+ if (entry && entry[toBackend]) {
+ return { targetId: entry[toBackend], exact: true };
+ }
+
+ // No catalog match. Ollama can pull bare model names, so derive a stem and
+ // try it best-effort. There's no safe way to guess a HuggingFace repo for
+ // LM Studio, so bail with null and let the caller report the skip.
+ if (toBackend === 'ollama') {
+ const stem = fromBackend === 'lmstudio'
+ ? normalizeLmStudioId(modelId).replace(/-instruct.*$/i, '').replace(/-\d+b.*$/i, '')
+ : normalizeOllamaId(modelId);
+ return { targetId: stem || null, exact: false };
+ }
+ return { targetId: null, exact: false };
+}
diff --git a/server/lib/localLlmCatalog.test.js b/server/lib/localLlmCatalog.test.js
new file mode 100644
index 0000000000..218e685760
--- /dev/null
+++ b/server/lib/localLlmCatalog.test.js
@@ -0,0 +1,83 @@
+import { describe, it, expect } from 'vitest';
+import {
+ BACKENDS, isBackend, LOCAL_LLM_CATALOG, getCatalog, searchCatalog, mapModelToBackend
+} from './localLlmCatalog.js';
+
+describe('localLlmCatalog', () => {
+ describe('isBackend', () => {
+ it('accepts the two known backends and rejects everything else', () => {
+ expect(BACKENDS).toEqual(['ollama', 'lmstudio']);
+ expect(isBackend('ollama')).toBe(true);
+ expect(isBackend('lmstudio')).toBe(true);
+ expect(isBackend('file')).toBe(false);
+ expect(isBackend(undefined)).toBe(false);
+ });
+ });
+
+ describe('getCatalog', () => {
+ it('projects entries onto the backend-specific install id', () => {
+ const ollama = getCatalog('ollama');
+ const llama = ollama.find((m) => m.key === 'llama3.2');
+ expect(llama.id).toBe('llama3.2');
+ const lms = getCatalog('lmstudio');
+ const llamaLms = lms.find((m) => m.key === 'llama3.2');
+ expect(llamaLms.id).toBe('lmstudio-community/Llama-3.2-3B-Instruct-GGUF');
+ });
+
+ it('only includes entries that ship a build for the backend', () => {
+ // Every catalog entry currently has both ids, so counts match the catalog.
+ expect(getCatalog('ollama').length).toBe(LOCAL_LLM_CATALOG.filter((e) => e.ollama).length);
+ });
+
+ it('marks installed models (tag-insensitive for Ollama)', () => {
+ const list = getCatalog('ollama', ['llama3.2:latest']);
+ expect(list.find((m) => m.id === 'llama3.2').installed).toBe(true);
+ expect(list.find((m) => m.id === 'mistral').installed).toBe(false);
+ });
+
+ it('matches LM Studio installed ids despite the -GGUF suffix / publisher prefix', () => {
+ const list = getCatalog('lmstudio', ['lmstudio-community/Llama-3.2-3B-Instruct-GGUF']);
+ expect(list.find((m) => m.key === 'llama3.2').installed).toBe(true);
+ });
+
+ it('returns [] for an unknown backend', () => {
+ expect(getCatalog('nope')).toEqual([]);
+ });
+ });
+
+ describe('searchCatalog', () => {
+ it('returns everything for an empty query', () => {
+ expect(searchCatalog('ollama', '').length).toBe(getCatalog('ollama').length);
+ });
+ it('filters by name, family, and description', () => {
+ expect(searchCatalog('ollama', 'coder').some((m) => m.key === 'qwen2.5-coder')).toBe(true);
+ expect(searchCatalog('ollama', 'vision').some((m) => m.key === 'llava')).toBe(true);
+ expect(searchCatalog('ollama', 'zzzznotamodel')).toEqual([]);
+ });
+ });
+
+ describe('mapModelToBackend', () => {
+ it('maps a known model exactly across backends', () => {
+ expect(mapModelToBackend('ollama', 'llama3.2:latest', 'lmstudio'))
+ .toEqual({ targetId: 'lmstudio-community/Llama-3.2-3B-Instruct-GGUF', exact: true });
+ expect(mapModelToBackend('lmstudio', 'lmstudio-community/Llama-3.2-3B-Instruct-GGUF', 'ollama'))
+ .toEqual({ targetId: 'llama3.2', exact: true });
+ });
+
+ it('best-effort derives an Ollama name for an unknown LM Studio model', () => {
+ const r = mapModelToBackend('lmstudio', 'someorg/Mystery-Model-7B-Instruct-GGUF', 'ollama');
+ expect(r.exact).toBe(false);
+ expect(r.targetId).toBe('mystery-model');
+ });
+
+ it('returns null (skip) when mapping an unknown model TO LM Studio', () => {
+ expect(mapModelToBackend('ollama', 'custom-unlisted', 'lmstudio'))
+ .toEqual({ targetId: null, exact: false });
+ });
+
+ it('refuses same-backend or unknown-backend mappings', () => {
+ expect(mapModelToBackend('ollama', 'llama3.2', 'ollama')).toEqual({ targetId: null, exact: false });
+ expect(mapModelToBackend('ollama', 'llama3.2', 'nope')).toEqual({ targetId: null, exact: false });
+ });
+ });
+});
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index 3cb224fba3..45d1051fd1 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -127,6 +127,7 @@ export const NAV_COMMANDS = [
{ id: 'nav.settings.backup', path: '/settings/backup', label: 'Backup', section: 'Settings', aliases: ['backup', 'settings-backup'] },
{ id: 'nav.settings.database', path: '/settings/database', label: 'Database', section: 'Settings', aliases: ['settings-database', 'database'] },
{ id: 'nav.settings.general', path: '/settings/general', label: 'General', section: 'Settings', aliases: ['settings', 'settings-general', 'general'] },
+ { id: 'nav.settings.local-llm', path: '/settings/local-llm', label: 'Local LLMs', section: 'Settings', aliases: ['local-llm', 'local-llms', 'ollama', 'lm-studio', 'lmstudio'], keywords: ['ollama', 'lm studio', 'local model', 'local llm', 'gguf', 'pull model', 'install model', 'migrate', 'switch backend'] },
{ id: 'nav.settings.mortalloom', path: '/settings/mortalloom', label: 'MortalLoom', section: 'Settings', aliases: ['settings-mortalloom', 'mortalloom'] },
{ id: 'nav.settings.sharing', path: '/settings/sharing', label: 'Sharing', section: 'Settings', aliases: ['settings-sharing', 'sharing-settings'], keywords: ['display name', 'bio', 'attribution', 'identity', 'source'] },
{ id: 'nav.settings.telegram', path: '/settings/telegram', label: 'Telegram', section: 'Settings', aliases: ['settings-telegram', 'telegram'] },
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 9fb36d333c..8bb4aa76c5 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -1041,6 +1041,15 @@ export const stageConfigUpdateSchema = z.object({
// sends an unmodelled field. If a future stage field is added, extend the
// schema rather than reintroducing `.passthrough()`.
+// === Local LLM backends (Ollama / LM Studio) ===
+export const localLlmBackendSchema = z.enum(['ollama', 'lmstudio']);
+export const localLlmInstallSchema = z.object({
+ backend: localLlmBackendSchema,
+ modelId: z.string().min(1).max(256),
+});
+export const localLlmDeleteSchema = localLlmInstallSchema;
+export const localLlmSwitchSchema = z.object({ to: localLlmBackendSchema });
+
/**
* Validate data against a Zod schema, throwing on failure.
* Returns parsed data on success, throws ServerError on failure.
diff --git a/server/routes/localLlm.js b/server/routes/localLlm.js
new file mode 100644
index 0000000000..ecf31adc30
--- /dev/null
+++ b/server/routes/localLlm.js
@@ -0,0 +1,102 @@
+/**
+ * Local LLM Routes
+ *
+ * REST endpoints for managing local LLM backends (Ollama / LM Studio):
+ * backend status, installed-model listing, a curated install catalog,
+ * install/delete, and switch/migrate between backends. Long-running pulls and
+ * migrations stream progress over the `localLlm:progress` socket event (same
+ * contract the Database tab uses).
+ */
+
+import { Router } from 'express'
+import { asyncHandler } from '../lib/errorHandler.js'
+import {
+ validateRequest,
+ localLlmInstallSchema,
+ localLlmDeleteSchema,
+ localLlmSwitchSchema
+} from '../lib/validation.js'
+import { getCatalog, searchCatalog, isBackend } from '../lib/localLlmCatalog.js'
+import {
+ getStatus, listModels, installModel, deleteModel, switchBackend, migrateBackend
+} from '../services/localLlm.js'
+
+const router = Router()
+
+const emitter = (req) => {
+ const io = req.app.get('io')
+ return (event, message) => io?.emit('localLlm:progress', { event, message })
+}
+
+// GET /api/local-llm/status — both backends + active marker
+router.get('/status', asyncHandler(async (req, res) => {
+ res.json(await getStatus())
+}))
+
+// GET /api/local-llm/models?backend=ollama — installed models for a backend
+router.get('/models', asyncHandler(async (req, res) => {
+ const { backend } = req.query
+ if (!isBackend(backend)) return res.status(400).json({ error: 'backend must be "ollama" or "lmstudio"' })
+ res.json({ backend, models: await listModels(backend) })
+}))
+
+// GET /api/local-llm/catalog?backend=ollama&q=llama — curated install picker
+router.get('/catalog', asyncHandler(async (req, res) => {
+ const { backend, q } = req.query
+ if (!isBackend(backend)) return res.status(400).json({ error: 'backend must be "ollama" or "lmstudio"' })
+ const installed = (await listModels(backend)).map((m) => m.id)
+ const models = q ? searchCatalog(backend, q, installed) : getCatalog(backend, installed)
+ res.json({ backend, models })
+}))
+
+// POST /api/local-llm/install — pull/download a model (streams progress)
+router.post('/install', asyncHandler(async (req, res) => {
+ const { backend, modelId } = validateRequest(localLlmInstallSchema, req.body)
+ const emit = emitter(req)
+ emit('start', `Installing ${modelId} on ${backend}…`)
+ const result = await installModel(backend, modelId, (p) => {
+ if (p?.percent != null) emit('start', `${modelId}: ${p.status || 'downloading'} ${p.percent}%`)
+ })
+ if (!result.success) {
+ emit('error', result.error || 'Install failed')
+ return res.status(502).json({ error: result.error || 'Install failed', modelId })
+ }
+ emit('complete', `${modelId} installed on ${backend}`)
+ res.json({ success: true, ...result })
+}))
+
+// POST /api/local-llm/delete — remove an installed model
+router.post('/delete', asyncHandler(async (req, res) => {
+ const { backend, modelId } = validateRequest(localLlmDeleteSchema, req.body)
+ const result = await deleteModel(backend, modelId)
+ if (!result.success) return res.status(502).json({ error: result.error || 'Delete failed', modelId })
+ res.json({ success: true, ...result })
+}))
+
+// POST /api/local-llm/switch — flip active backend without moving models
+router.post('/switch', asyncHandler(async (req, res) => {
+ const { to } = validateRequest(localLlmSwitchSchema, req.body)
+ const emit = emitter(req)
+ emit('start', `Switching to ${to}…`)
+ 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}`)
+ res.json(result)
+}))
+
+// POST /api/local-llm/migrate — re-provision models on target, then switch
+router.post('/migrate', asyncHandler(async (req, res) => {
+ const { to } = validateRequest(localLlmSwitchSchema, req.body)
+ const emit = emitter(req)
+ const result = await migrateBackend(to, ({ event, message }) => emit(event, message))
+ if (!result.success) {
+ emit('error', result.error || 'Migration failed')
+ return res.status(500).json({ error: result.error || 'Migration failed' })
+ }
+ res.json(result)
+}))
+
+export default router
diff --git a/server/services/localLlm.js b/server/services/localLlm.js
new file mode 100644
index 0000000000..9cea4aa6da
--- /dev/null
+++ b/server/services/localLlm.js
@@ -0,0 +1,242 @@
+/**
+ * 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).
+ *
+ * The active 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.
+ *
+ * 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.
+ */
+
+import { execFile } from 'child_process'
+import { promisify } from 'util'
+import { readFileSync, writeFileSync } from 'fs'
+import { join } from 'path'
+import { PATHS } from '../lib/fileUtils.js'
+import { isBackend, mapModelToBackend } from '../lib/localLlmCatalog.js'
+import * as ollamaManager from './ollamaManager.js'
+import * as lmStudioManager from './lmStudioManager.js'
+import { getProviderById, updateProvider } from './providers.js'
+
+const execFileAsync = promisify(execFile)
+const ENV_PATH = join(PATHS.root, '.env')
+const DEFAULT_BACKEND = 'ollama'
+
+// aiToolkit provider id that pairs with each backend.
+const PROVIDER_ID = { ollama: 'ollama', lmstudio: 'lmstudio' }
+
+// ---- active-backend marker (.env LLM_BACKEND) --------------------------------
+
+function readEnv() {
+ const result = {}
+ let content = ''
+ try { content = readFileSync(ENV_PATH, 'utf8') } catch { return result }
+ for (const line of content.split('\n')) {
+ const trimmed = line.trim()
+ if (!trimmed || trimmed.startsWith('#')) continue
+ const idx = trimmed.indexOf('=')
+ if (idx === -1) continue
+ let value = trimmed.slice(idx + 1).trim()
+ if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
+ value = value.slice(1, -1)
+ }
+ result[trimmed.slice(0, idx).trim()] = value
+ }
+ return result
+}
+
+/** The active local-LLM backend, read fresh from `.env` each call. */
+export function getBackend() {
+ const fromEnv = readEnv().LLM_BACKEND || process.env.LLM_BACKEND
+ return isBackend(fromEnv) ? fromEnv : DEFAULT_BACKEND
+}
+
+function writeBackend(backend) {
+ let content = ''
+ try { content = readFileSync(ENV_PATH, 'utf8') } catch { /* no .env yet */ }
+ if (/^LLM_BACKEND=/m.test(content)) {
+ content = content.replace(/^LLM_BACKEND=.*/m, `LLM_BACKEND=${backend}`)
+ } else {
+ content = `LLM_BACKEND=${backend}\n${content}`
+ }
+ writeFileSync(ENV_PATH, content)
+}
+
+/**
+ * Enable the aiToolkit provider that pairs with `backend`, so the active local
+ * backend is actually usable for runs. Best-effort: a misconfigured provider
+ * store must not crash a boot-time or migrate call.
+ */
+export async function ensureBackendProvider(backend) {
+ const id = PROVIDER_ID[backend]
+ if (!id) return
+ const provider = await getProviderById(id).catch(() => null)
+ if (provider && !provider.enabled) {
+ await updateProvider(id, { enabled: true }).catch((err) =>
+ console.error(`⚠️ Failed to enable ${id} provider: ${err.message}`))
+ console.log(`🔌 Enabled ${id} provider for active local LLM backend`)
+ }
+}
+
+// ---- backend capability probes ----------------------------------------------
+
+async function commandExists(cmd, args) {
+ return execFileAsync(cmd, args, { timeout: 5_000 }).then(() => true).catch(() => false)
+}
+
+const manager = (backend) => (backend === 'ollama' ? ollamaManager : lmStudioManager)
+
+/** Normalize each backend's installed-model shape into one card shape. */
+function normalizeModels(backend, models) {
+ if (backend === 'ollama') {
+ return models.map((m) => ({
+ id: m.id, name: m.name, size: m.size ?? null,
+ params: m.params || null, quantization: m.quantization || null, family: m.family || null
+ }))
+ }
+ return models.map((m) => ({
+ id: m.id, name: m.id, size: null,
+ params: null, quantization: m.quantization || null, family: m.arch || null
+ }))
+}
+
+/** Installed models for a backend, normalized. */
+export async function listModels(backend) {
+ if (!isBackend(backend)) return []
+ const raw = backend === 'ollama'
+ ? await ollamaManager.getInstalledModels(true)
+ : await lmStudioManager.getAvailableModels()
+ return normalizeModels(backend, raw)
+}
+
+/**
+ * Combined status for both backends plus the active marker.
+ */
+export async function getStatus() {
+ const [ollamaStatus, ollamaCli, lmStudioStatus, lmsCli, lmStudioModels] = await Promise.all([
+ ollamaManager.getStatus(),
+ commandExists('ollama', ['--version']),
+ lmStudioManager.getStatus(),
+ commandExists('lms', ['version']),
+ listModels('lmstudio').catch(() => []) // already normalized
+ ])
+
+ return {
+ backend: getBackend(),
+ ollama: {
+ installed: ollamaCli || ollamaStatus.available,
+ available: ollamaStatus.available,
+ version: ollamaStatus.version,
+ baseUrl: ollamaStatus.baseUrl,
+ modelCount: ollamaStatus.modelCount,
+ models: normalizeModels('ollama', ollamaStatus.models)
+ },
+ lmstudio: {
+ installed: lmsCli || lmStudioStatus.available,
+ available: lmStudioStatus.available,
+ hasCli: lmsCli,
+ baseUrl: lmStudioStatus.baseUrl,
+ modelCount: lmStudioModels.length,
+ models: lmStudioModels
+ }
+ }
+}
+
+// ---- install / delete --------------------------------------------------------
+
+/**
+ * Install (pull/download) a model on a backend.
+ * @param {(p) => void} [onProgress] - streaming progress (Ollama only)
+ */
+export async function installModel(backend, modelId, onProgress) {
+ if (!isBackend(backend)) return { success: false, error: `Unknown backend: ${backend}` }
+ if (backend === 'ollama') {
+ return ollamaManager.pullModel(modelId, onProgress)
+ }
+ // LM Studio: prefer the `lms` CLI (real download), fall back to the REST hook.
+ if (await commandExists('lms', ['version'])) {
+ const r = await execFileAsync('lms', ['get', modelId, '--yes'], { timeout: 0 })
+ .then(() => ({ ok: true })).catch((err) => ({ _err: err.stderr || err.message }))
+ if (r._err) return { success: false, error: r._err, modelId }
+ lmStudioManager.resetCache()
+ return { success: true, modelId }
+ }
+ return lmStudioManager.downloadModel(modelId)
+}
+
+/**
+ * Delete an installed model from a backend.
+ */
+export async function deleteModel(backend, modelId) {
+ if (!isBackend(backend)) return { success: false, error: `Unknown backend: ${backend}` }
+ if (backend === 'ollama') {
+ return ollamaManager.deleteModel(modelId)
+ }
+ // LM Studio has no delete in its REST API — use the `lms` CLI if present.
+ if (await commandExists('lms', ['version'])) {
+ const r = await execFileAsync('lms', ['rm', modelId, '--yes'], { timeout: 30_000 })
+ .then(() => ({ ok: true })).catch((err) => ({ _err: err.stderr || err.message }))
+ if (r._err) return { success: false, error: r._err, modelId }
+ lmStudioManager.resetCache()
+ return { success: true, modelId }
+ }
+ return { success: false, error: 'Deleting LM Studio models requires the `lms` CLI. Remove it from the LM Studio app instead.', modelId }
+}
+
+// ---- switch / migrate --------------------------------------------------------
+
+/**
+ * Flip the active backend without moving any models.
+ */
+export async function switchBackend(to) {
+ if (!isBackend(to)) return { success: false, error: `Unknown backend: ${to}` }
+ writeBackend(to)
+ await ensureBackendProvider(to)
+ console.log(`🔀 Active local LLM backend → ${to}`)
+ return { success: true, backend: 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.
+ *
+ * @param {string} to - target backend
+ * @param {(p: { event: string, message: string }) => void} [onProgress]
+ */
+export async function migrateBackend(to, onProgress = () => {}) {
+ if (!isBackend(to)) return { success: false, error: `Unknown backend: ${to}` }
+ const from = to === 'ollama' ? 'lmstudio' : 'ollama'
+
+ onProgress({ event: 'start', message: `Reading models installed on ${from}…` })
+ const sourceModels = await listModels(from)
+
+ const results = []
+ for (const model of sourceModels) {
+ const { targetId, exact } = mapModelToBackend(from, model.id, to)
+ 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` })
+ continue
+ }
+ onProgress({ event: 'start', message: `Installing ${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}%` })
+ })
+ results.push({ source: model.id, target: targetId, status: r.success ? 'installed' : 'failed', reason: r.error })
+ }
+
+ writeBackend(to)
+ await ensureBackendProvider(to)
+
+ const installed = results.filter((r) => r.status === 'installed').length
+ const failed = results.filter((r) => r.status === 'failed').length
+ onProgress({ event: 'complete', message: `Migrated to ${to} — ${installed} installed, ${failed} failed, ${results.length - installed - failed} skipped` })
+ console.log(`🔀 Migrated local LLM backend → ${to} (${installed} installed, ${failed} failed)`)
+ return { success: true, backend: to, results }
+}
diff --git a/server/services/localLlm.test.js b/server/services/localLlm.test.js
new file mode 100644
index 0000000000..e32f44d834
--- /dev/null
+++ b/server/services/localLlm.test.js
@@ -0,0 +1,126 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import os from 'os';
+import path from 'path';
+import fs from 'fs';
+
+// vi.mock factories are hoisted above the module body, so the mutable holder
+// and the mock objects must come from vi.hoisted (which runs first). The
+// service captures ENV_PATH = join(PATHS.root, '.env') at import time, so each
+// test sets `state.root` to a fresh temp dir and re-imports under resetModules.
+const state = vi.hoisted(() => ({ root: '' }));
+vi.mock('../lib/fileUtils.js', () => ({ PATHS: state }));
+
+const mocks = vi.hoisted(() => ({
+ ollama: {
+ 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: [] }))
+ },
+ 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()
+ },
+ providers: {
+ getProviderById: vi.fn(async () => ({ id: 'ollama', enabled: false })),
+ updateProvider: vi.fn(async () => ({}))
+ }
+}));
+vi.mock('./ollamaManager.js', () => mocks.ollama);
+vi.mock('./lmStudioManager.js', () => mocks.lmstudio);
+vi.mock('./providers.js', () => mocks.providers);
+
+const writeEnv = (content) => fs.writeFileSync(path.join(state.root, '.env'), content);
+
+let svc;
+beforeEach(async () => {
+ vi.clearAllMocks(); // clears calls, keeps the default impls defined above
+ delete process.env.LLM_BACKEND;
+ state.root = fs.mkdtempSync(path.join(os.tmpdir(), 'portos-llm-svc-'));
+ vi.resetModules();
+ svc = await import('./localLlm.js');
+});
+
+describe('localLlm', () => {
+ describe('getBackend', () => {
+ it('defaults to ollama when .env has no marker', () => {
+ expect(svc.getBackend()).toBe('ollama');
+ });
+ it('reads LLM_BACKEND fresh from .env', () => {
+ writeEnv('LLM_BACKEND=lmstudio\nPGMODE=docker\n');
+ expect(svc.getBackend()).toBe('lmstudio');
+ });
+ it('ignores an invalid marker', () => {
+ writeEnv('LLM_BACKEND=garbage\n');
+ expect(svc.getBackend()).toBe('ollama');
+ });
+ });
+
+ describe('switchBackend', () => {
+ it('writes the marker and enables the paired (disabled) provider', async () => {
+ const r = await svc.switchBackend('lmstudio');
+ expect(r).toEqual({ success: true, backend: 'lmstudio' });
+ expect(svc.getBackend()).toBe('lmstudio');
+ expect(mocks.providers.updateProvider).toHaveBeenCalledWith('lmstudio', { enabled: true });
+ });
+ it('rejects an unknown backend', async () => {
+ const r = await svc.switchBackend('nope');
+ expect(r.success).toBe(false);
+ });
+ });
+
+ describe('ensureBackendProvider', () => {
+ it('does not re-enable an already-enabled provider', async () => {
+ mocks.providers.getProviderById.mockResolvedValueOnce({ id: 'ollama', enabled: true });
+ await svc.ensureBackendProvider('ollama');
+ expect(mocks.providers.updateProvider).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('installModel / deleteModel dispatch', () => {
+ it('routes Ollama install to pullModel', async () => {
+ await svc.installModel('ollama', 'llama3.2');
+ expect(mocks.ollama.pullModel).toHaveBeenCalledWith('llama3.2', undefined);
+ });
+ it('routes Ollama delete to deleteModel', async () => {
+ await svc.deleteModel('ollama', 'llama3.2');
+ expect(mocks.ollama.deleteModel).toHaveBeenCalledWith('llama3.2');
+ });
+ it('rejects an unknown backend', async () => {
+ expect((await svc.installModel('nope', 'x')).success).toBe(false);
+ });
+ });
+
+ describe('migrateBackend', () => {
+ it('re-provisions known source models on the target and flips the marker', async () => {
+ writeEnv('LLM_BACKEND=lmstudio\n');
+ 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));
+
+ expect(r.success).toBe(true);
+ expect(r.backend).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(events.at(-1).event).toBe('complete');
+ });
+
+ it('skips a model with no known target equivalent (→ LM Studio)', async () => {
+ writeEnv('LLM_BACKEND=ollama\n');
+ mocks.ollama.getInstalledModels.mockResolvedValueOnce([
+ { id: 'custom-unlisted:latest', name: 'custom-unlisted:latest' }
+ ]);
+
+ const r = await svc.migrateBackend('lmstudio');
+ expect(r.results.find((x) => x.source === 'custom-unlisted:latest').status).toBe('skipped');
+ expect(mocks.lmstudio.downloadModel).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/server/services/ollamaManager.js b/server/services/ollamaManager.js
new file mode 100644
index 0000000000..0d7cbbdabd
--- /dev/null
+++ b/server/services/ollamaManager.js
@@ -0,0 +1,218 @@
+/**
+ * Ollama Manager Service
+ *
+ * Manages a local Ollama install over its native HTTP API (default
+ * http://localhost:11434). Mirrors lmStudioManager.js so server/services/
+ * localLlm.js can treat both backends through one shape: availability probe,
+ * installed-model listing, streaming pulls, and deletes.
+ *
+ * Ollama's REST surface (not OpenAI-compatible):
+ * GET /api/version → { version }
+ * GET /api/tags → { models: [{ name, size, details, modified_at }] }
+ * GET /api/ps → { models: [...] } (loaded into memory)
+ * POST /api/pull → NDJSON stream { status, total?, completed? }
+ * DELETE /api/delete → { name }
+ */
+
+import { fetchWithTimeout } from '../lib/fetchWithTimeout.js'
+
+const AVAILABILITY_CACHE_TTL_MS = 30_000
+const DEFAULT_REQUEST_TIMEOUT_MS = 10_000
+// Short probe — degrade to "no Ollama" fast rather than block on a cold check.
+const AVAILABILITY_PROBE_TIMEOUT_MS = 5_000
+
+const DEFAULT_CONFIG = {
+ // Ollama uses OLLAMA_HOST (host:port, no scheme) by convention; also accept
+ // an explicit OLLAMA_URL. Normalize to a scheme + no trailing slash + no /v1.
+ baseUrl: normalizeBaseUrl(process.env.OLLAMA_URL || process.env.OLLAMA_HOST || 'http://localhost:11434'),
+ timeout: DEFAULT_REQUEST_TIMEOUT_MS
+}
+
+function normalizeBaseUrl(raw) {
+ let url = String(raw || '').trim().replace(/\/+$/, '').replace(/\/v1$/, '')
+ if (url && !/^https?:\/\//i.test(url)) url = `http://${url}`
+ return url || 'http://localhost:11434'
+}
+
+let config = { ...DEFAULT_CONFIG }
+let isAvailable = null
+let installedModels = []
+let lastCheckAt = null
+
+const status = { lastError: null, lastSuccessAt: null, consecutiveErrors: 0 }
+
+async function ollamaRequest(endpoint, options = {}) {
+ const { timeout, headers, ...rest } = options
+ const response = await fetchWithTimeout(`${config.baseUrl}${endpoint}`, {
+ ...rest,
+ headers: { 'Content-Type': 'application/json', ...headers }
+ }, timeout ?? config.timeout)
+ if (!response.ok) {
+ const body = await response.text().catch(() => '')
+ throw new Error(`Ollama API error: ${response.status} ${response.statusText}${body ? ` — ${body.slice(0, 200)}` : ''}`)
+ }
+ return response.json()
+}
+
+/**
+ * Check if Ollama is reachable (cached for AVAILABILITY_CACHE_TTL_MS).
+ */
+async function checkOllamaAvailable() {
+ const now = Date.now()
+ if (lastCheckAt && now - lastCheckAt < AVAILABILITY_CACHE_TTL_MS && isAvailable !== null) {
+ return isAvailable
+ }
+ try {
+ await ollamaRequest('/api/version', { timeout: AVAILABILITY_PROBE_TIMEOUT_MS })
+ isAvailable = true
+ status.lastSuccessAt = now
+ status.consecutiveErrors = 0
+ status.lastError = null
+ lastCheckAt = now
+ return true
+ } catch (err) {
+ isAvailable = false
+ status.lastError = err.message
+ status.consecutiveErrors++
+ lastCheckAt = now
+ return false
+ }
+}
+
+/**
+ * List installed models from /api/tags.
+ * @returns {Promise<Array<{ id, name, size, family, params, quantization, modifiedAt }>>}
+ */
+async function getInstalledModels(forceRefresh = false) {
+ if (!forceRefresh && installedModels.length > 0) return installedModels
+ if (!(await checkOllamaAvailable())) return []
+
+ const data = await ollamaRequest('/api/tags').catch(() => null)
+ if (!data?.models) return []
+
+ installedModels = data.models.map((m) => ({
+ id: m.name || m.model,
+ name: m.name || m.model,
+ size: m.size ?? null,
+ family: m.details?.family || null,
+ params: m.details?.parameter_size || null,
+ quantization: m.details?.quantization_level || null,
+ modifiedAt: m.modified_at || null
+ }))
+ return installedModels
+}
+
+async function getVersion() {
+ const data = await ollamaRequest('/api/version', { timeout: AVAILABILITY_PROBE_TIMEOUT_MS }).catch(() => null)
+ return data?.version || null
+}
+
+/**
+ * Pull a model, streaming progress. Resolves once the pull finishes.
+ * @param {string} modelId
+ * @param {(p: { status: string, percent: number|null, completed?: number, total?: number }) => void} [onProgress]
+ * @returns {Promise<{ success: boolean, modelId: string, error?: string }>}
+ */
+async function pullModel(modelId, onProgress) {
+ if (!(await checkOllamaAvailable())) {
+ return { success: false, error: 'Ollama not available', modelId }
+ }
+ console.log(`📥 Ollama pull: ${modelId}`)
+
+ // No timeout — multi-GB pulls take minutes; the stream is the lifecycle.
+ const response = await fetchWithTimeout(`${config.baseUrl}/api/pull`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name: modelId, stream: true })
+ }, 0).catch((err) => ({ _err: err.message }))
+
+ if (response._err || !response.ok || !response.body) {
+ const error = response._err || `pull failed: ${response.status} ${response.statusText}`
+ console.error(`⚠️ Ollama pull failed for ${modelId}: ${error}`)
+ return { success: false, error, modelId }
+ }
+
+ const reader = response.body.getReader()
+ const decoder = new TextDecoder()
+ let buffer = ''
+ let lastError = null
+
+ // Ollama streams newline-delimited JSON progress frames. Read via getReader()
+ // to match the rest of the codebase's streaming-fetch convention.
+ while (true) {
+ const { value, done } = await reader.read()
+ if (done) break
+ buffer += decoder.decode(value, { stream: true })
+ let nl
+ while ((nl = buffer.indexOf('\n')) !== -1) {
+ const line = buffer.slice(0, nl).trim()
+ buffer = buffer.slice(nl + 1)
+ if (!line) continue
+ const frame = safeParse(line)
+ if (!frame) continue
+ 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 (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 }
+}
+
+function safeParse(line) {
+ try { return JSON.parse(line) } catch { return null }
+}
+
+/**
+ * Delete an installed model (DELETE /api/delete).
+ */
+async function deleteModel(modelId) {
+ if (!(await checkOllamaAvailable())) {
+ return { success: false, error: 'Ollama not available', modelId }
+ }
+ const result = await ollamaRequest('/api/delete', {
+ method: 'DELETE',
+ body: JSON.stringify({ name: modelId }),
+ timeout: 15_000
+ }).then(() => ({ ok: true })).catch((err) => ({ _err: err.message }))
+
+ if (result._err) {
+ return { success: false, error: result._err, modelId }
+ }
+ installedModels = []
+ console.log(`🗑️ Ollama deleted: ${modelId}`)
+ return { success: true, modelId }
+}
+
+/**
+ * Aggregate status for the unified local-LLM UI.
+ */
+async function getStatus() {
+ const available = await checkOllamaAvailable()
+ const models = available ? await getInstalledModels(true) : []
+ return {
+ available,
+ baseUrl: config.baseUrl,
+ version: available ? await getVersion() : null,
+ modelCount: models.length,
+ models,
+ lastError: status.lastError,
+ consecutiveErrors: status.consecutiveErrors
+ }
+}
+
+export {
+ getInstalledModels,
+ pullModel,
+ deleteModel,
+ getStatus
+}