Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat(local-llm): one-click install a missing backend from the model manager
Adam Eivy08581fba7bbe
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex de07285108..ae5ccc62ba 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -1,7 +1,7 @@# Unreleased Changes## Added-- **[local-llm-backend-management] Local LLMs — pick a backend at setup, manage models, and migrate between Ollama and LM Studio.** Setup now asks whether you want **Ollama** or **LM Studio** for local on-device models and installs the chosen one if it's missing (`scripts/setup-llm.js`, wired into `npm run setup`; `npm run setup:llm` to run it standalone). The choice is recorded as `LLM_BACKEND` in `.env`, and the matching AI provider is auto-enabled on boot. A new **Settings → Local LLMs** tab (reachable from the sidebar, ⌘K, and voice) shows both backends' status, lets you **switch** the active backend or **migrate** to the other (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), lets you **switch** the active backend or **migrate** to the other (the GGUF weights are portable — only the on-disk *layout* differs (Ollama's content-addressed blob store vs LM Studio's plain file tree), so migrate **copies each model's GGUF across locally with no re-download** where it can, and re-pulls the cross-backend catalog equivalent only for models it can't copy — LM Studio MLX-format, sharded, or multimodal — mirrors the Docker↔native Postgres flow), and manages models like the LoRA/Media-Models pages do: a curated cross-backend catalog with search, one-click install, free-text "pull by name", and delete — with live pull progress over the `localLlm:progress` socket. Server side: `server/services/ollamaManager.js` (native Ollama HTTP API + local GGUF import via `/api/create`), `server/services/localLlm.js` (unified orchestration + `.env` marker + provider enabling + migrate), `server/lib/localLlmCatalog.js` (pure catalog + install-id mapping), `server/lib/localLlmDisk.js` (pure on-disk GGUF/manifest reasoning for the local-copy fast-path), and `/api/local-llm/*` routes.- **[codex5-onboarding-capability-map] Capabilities page — every connected system at a glance.** A new Capabilities page (under System) shows the status of each integration on one screen: AI Providers, Calendar, Brain & Memory, Voice, Tailscale & HTTPS, Genome & Health, Telegram, Messages, and Apps & Processes. Every row says whether it's set up and healthy — Ready, Degraded, Error, or Not set up — and links straight to its settings, so the page works as both a first-run setup checklist and a quick runtime health overview. Reachable from the sidebar, ⌘K, and voice.- **Federated media collections + per-category sync integrity.** Media collections are now a first-class peer-sync record kind (`mediaCollection` in `PEER_SUBSCRIBABLE_KINDS`, schema-version-gated at `mediaCollections: 1`): they auto-subscribe on create, push per-record on edit, and propagate deletes via tombstones — collections now reach parity between federated machines the way universes/series already did, instead of only riding along as `linkedCollection` cargo or the opt-in 60s snapshot. Required adding soft-delete to collections (`deleted`/`deletedAt`; `deleteCollection` marks instead of splicing; `listCollections({ includeDeleted })`; tombstone-aware LWW merge; tombstone GC), so a delete on one node can't be resurrected by a reverse-subscribed peer. Synced images now carry their **generation prompts**: the peer asset manifest advertises a canonical gen-params-only `sidecarSha256` (machine-local hash-cache stripped so it converges across peers), and the asset-pull worker fetches each image's `.metadata.json` sidecar alongside the bytes — fixing images that previously landed in "Unsorted" with no prompts. A new per-category **sync integrity** surface (`GET /api/peer-sync/manifest`, `GET /api/peer-sync/integrity`, pure `computeRecordIntegrity` diff) drives a `SyncBadge` on every Universe / Series / Media-Collection row (in-sync / diverged / assets-missing / local-only / on-peer-only / "not syncing — enable?") plus a deep-linkable `SyncDetailDrawer` (`/…/:id/sync`) showing the per-peer breakdown, previews, and manual actions: **Sync to peer** (`POST /sync-record`, force-push bypassing the unchanged-hash short-circuit), **Sync now** (`POST /sync-now`, backfill-subscribe + retry a peer's pending pushes), and **Pull missing prompts** (`POST /pull-metadata` + a button on the Unsorted view that backfills sidecars from online peers). `mediaCollections` sync stays **opt-in** per peer (default off); the badge surfaces a clear "enable?" state rather than flipping the default.- **Manual tombstone GC trigger.** The 60s `syncOrchestrator` sweep buffers tombstones for 24h to give every peer time to ack a deletion before the bytes leave disk — fine for normal use, painful right after a mass-delete. New `POST /api/sync/tombstones/sweep` (Zod-validated optional `{ graceMs }` clamped to `[0, 24h]`) calls `sweepTombstones({ graceMs })` so callers can shrink the buffer; the per-kind null-cutoff refusal (snapshot-mode peer with no per-record subscription) still fires independently of `graceMs` to preserve resurrection safety. Companion `GET /api/sync/tombstones/status` returns the dry-run refusal status without invoking the prune helpers. A new "GC tombstones now" section on the Instances page (between SelfCard/AddPeer and the peers list) POSTs `graceMs: 0` and surfaces per-kind prune counts + any refusals in a toast; the button is disabled only when every kind is refused. `scripts/gc-tombstones-now.js` is the equivalent CLI path (dry-run by default; `--apply` to prune) for headless cleanups — uses the same "stop the server first, single-process write-tail isn't cross-process safe" wording as `cleanup-test-data.js`. `sweepTombstones` now returns `{ universes, series, issues, refused }` so the manual trigger can explain why a kind didn't shrink. The orchestrator path keeps the 24h default behavior unchanged.diff --git a/client/src/components/settings/LocalLlmTab.jsx b/client/src/components/settings/LocalLlmTab.jsxindex d69a49f737..0d14a65a1e 100644--- a/client/src/components/settings/LocalLlmTab.jsx+++ b/client/src/components/settings/LocalLlmTab.jsx@@ -1,11 +1,11 @@import { useState, useEffect, useRef, useCallback } from 'react';-import { Cpu, Box, ArrowRightLeft, Download, Trash2, RefreshCw, Search, Plus } from 'lucide-react';+import { Cpu, Box, ArrowRightLeft, Download, Trash2, RefreshCw, Search, Plus, ExternalLink } from 'lucide-react';import toast from '../ui/Toast';import BrailleSpinner from '../BrailleSpinner';import { formatBytes } from '../../utils/formatters';import {getLocalLlmStatus, getLocalLlmCatalog, installLocalLlmModel,- deleteLocalLlmModel, switchLocalLlmBackend, migrateLocalLlmBackend+ deleteLocalLlmModel, switchLocalLlmBackend, migrateLocalLlmBackend, installLocalLlmBackend} from '../../services/api';import socket from '../../services/socket';@@ -43,7 +43,37 @@ function BackendCard({ backend, status, isActive, busy, actionInProgress, runAct{data?.version && <> · v{data.version}</>}</div>- {!isActive && (+ {!data?.installed && (+ <div className="flex flex-wrap gap-1.5 pt-1 border-t border-port-border/50">+ {data?.canAutoInstall ? (+ <button+ onClick={() => runAction(+ `install-backend-${backend.id}`,+ () => installLocalLlmBackend(backend.id),+ (r) => r?.note ? `Installed ${backend.label} — ${r.note}` : `Installed ${backend.label}`+ )}+ disabled={busy}+ className={`${btnClass} bg-port-accent/20 hover:bg-port-accent/30 text-port-accent`}+ title="Install via Homebrew (macOS) / official installer (Linux)"+ >+ {actionInProgress === `install-backend-${backend.id}` ? <BrailleSpinner /> : <Download size={12} />}+ Install {backend.label}+ </button>+ ) : (+ <a+ href={data?.downloadUrl}+ target="_blank"+ rel="noreferrer"+ className={`${btnClass} bg-port-border hover:bg-port-border/70 text-white no-underline`}+ >+ <ExternalLink size={12} />+ Get {backend.label}+ </a>+ )}+ </div>+ )}++ {data?.installed && !isActive && (<div className="flex flex-wrap gap-1.5 pt-1 border-t border-port-border/50"><buttononClick={() => setConfirmAction({diff --git a/client/src/services/README.md b/client/src/services/README.mdindex c7e2aef251..5fb8f5e750 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -42,7 +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. |+| `apiLocalLlm.js` | Local LLM backends (Ollama / LM Studio): status, model list/catalog/install/delete, backend install (Homebrew/script), switch/migrate. || `apiGit.js` | Git operations. || `apiGithub.js` | GitHub repo metadata. || `apiHistory.js` | Historical logs / runs. |diff --git a/client/src/services/apiLocalLlm.js b/client/src/services/apiLocalLlm.jsindex d2aee7df79..10bda56747 100644--- a/client/src/services/apiLocalLlm.js+++ b/client/src/services/apiLocalLlm.js@@ -15,6 +15,9 @@ export const installLocalLlmModel = (backend, modelId) =>export const deleteLocalLlmModel = (backend, modelId) =>request('/local-llm/delete', { method: 'POST', body: JSON.stringify({ backend, modelId }) });+export const installLocalLlmBackend = (backend) =>+ request('/local-llm/install-backend', { method: 'POST', body: JSON.stringify({ backend }) });+export const switchLocalLlmBackend = (to) =>request('/local-llm/switch', { method: 'POST', body: JSON.stringify({ to }) });diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 1ba00a262a..b6a00d6536 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -1054,6 +1054,7 @@ export const localLlmInstallSchema = z.object({});export const localLlmDeleteSchema = localLlmInstallSchema;export const localLlmSwitchSchema = z.object({ to: localLlmBackendSchema });+export const localLlmInstallBackendSchema = z.object({ backend: localLlmBackendSchema });/*** Validate data against a Zod schema, throwing on failure.diff --git a/server/routes/localLlm.js b/server/routes/localLlm.jsindex 8346243585..8b46aa7031 100644--- a/server/routes/localLlm.js+++ b/server/routes/localLlm.js@@ -14,11 +14,12 @@ import {validateRequest,localLlmInstallSchema,localLlmDeleteSchema,- localLlmSwitchSchema+ localLlmSwitchSchema,+ localLlmInstallBackendSchema} from '../lib/validation.js'import { getCatalog, searchCatalog, isBackend } from '../lib/localLlmCatalog.js'import {- getStatus, listModels, installModel, deleteModel, switchBackend, migrateBackend+ getStatus, listModels, installModel, deleteModel, switchBackend, migrateBackend, installBackend} from '../services/localLlm.js'const router = Router()@@ -49,6 +50,24 @@ router.get('/catalog', asyncHandler(async (req, res) => {res.json({ backend, models })}))+// POST /api/local-llm/install-backend — install the backend app/binary itself+// (Homebrew on macOS, official script for Ollama on Linux). Streams progress.+router.post('/install-backend', asyncHandler(async (req, res) => {+ const { backend } = validateRequest(localLlmInstallBackendSchema, req.body)+ const emit = emitter(req)+ const result = await installBackend(backend, ({ event, message }) => emit(event, message))+ .catch((err) => {+ emit('error', `Install failed: ${err.message}`)+ throw err+ })+ if (!result.success) {+ emit('error', result.error || 'Install failed')+ return res.status(502).json({ error: result.error || 'Install failed', backend })+ }+ emit('complete', `${backend === 'ollama' ? 'Ollama' : 'LM Studio'} installed${result.note ? ` — ${result.note}` : ''}`)+ res.json(result)+}))+// 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)diff --git a/server/services/localLlm.js b/server/services/localLlm.jsindex 045c13c4db..5282f2ad5b 100644--- a/server/services/localLlm.js+++ b/server/services/localLlm.js@@ -16,7 +16,7 @@* flips the active marker. See `server/lib/localLlmDisk.js` for the disk logic.*/-import { execFile } from 'child_process'+import { execFile, spawn } from 'child_process'import { promisify } from 'util'import { readFileSync, writeFileSync } from 'fs'import { join } from 'path'@@ -36,6 +36,21 @@ const DEFAULT_BACKEND = 'ollama'// request forever. Large models on a slow link still fit comfortably.const LMS_INSTALL_TIMEOUT_MS = 60 * 60 * 1000+// Backend (app/binary) installs go through a package manager and can pull a+// large cask; bound them so a wedged installer can't hang the request forever.+const BACKEND_INSTALL_TIMEOUT_MS = 30 * 60 * 1000++const DOWNLOAD_URL = { ollama: 'https://ollama.com/download', lmstudio: 'https://lmstudio.ai/download' }++// Which (platform, backend) pairs PortOS can install automatically. macOS uses+// Homebrew for both; Linux has an official Ollama script but no clean LM Studio+// CLI install; Windows is download-only.+function canAutoInstall(backend) {+ if (process.platform === 'darwin') return true+ if (process.platform === 'linux') return backend === 'ollama'+ return false+}+// aiToolkit provider id that pairs with each backend.const PROVIDER_ID = { ollama: 'ollama', lmstudio: 'lmstudio' }@@ -104,6 +119,94 @@ async function commandExists(cmd, args) {const manager = (backend) => (backend === 'ollama' ? ollamaManager : lmStudioManager)+/**+ * Spawn a command and stream its stdout/stderr lines to `onLine`, resolving+ * `{ success }` on exit. Used for package-manager installs where live output is+ * the only progress signal. Never rejects (errors resolve as `{ success:false }`)+ * and guards the `onLine` hook — this runs outside the request lifecycle.+ */+function runStreaming(cmd, args, onLine, timeoutMs = 0) {+ return new Promise((resolve) => {+ const child = spawn(cmd, args, { stdio: ['ignore', 'pipe', 'pipe'] })+ let buffer = ''+ let settled = false+ const safeLine = (line) => {+ if (!line || typeof onLine !== 'function') return+ try { onLine(line) } catch (err) { console.error(`⚠️ install progress hook failed: ${err.message}`) }+ }+ const finish = (result) => {+ if (settled) return+ settled = true+ if (timer) clearTimeout(timer)+ resolve(result)+ }+ const timer = timeoutMs > 0+ ? setTimeout(() => { child.kill('SIGKILL'); finish({ success: false, error: `timed out after ${Math.round(timeoutMs / 1000)}s` }) }, timeoutMs)+ : null+ const onData = (chunk) => {+ buffer += chunk.toString()+ let nl+ while ((nl = buffer.indexOf('\n')) !== -1) {+ safeLine(buffer.slice(0, nl).trim())+ buffer = buffer.slice(nl + 1)+ }+ }+ child.stdout.on('data', onData)+ child.stderr.on('data', onData)+ child.on('error', (err) => finish({ success: false, error: err.message }))+ child.on('close', (code) => {+ safeLine(buffer.trim())+ finish(code === 0 ? { success: true } : { success: false, error: `exited with code ${code}` })+ })+ })+}++/**+ * Install a backend's app/binary via the platform package manager (Homebrew on+ * macOS for both; the official script for Ollama on Linux). Streams installer+ * output via `onProgress`. Returns `{ success, note? }` — `note` tells the user+ * how to start it (installing the binary doesn't start the server/app).+ *+ * @param {string} backend - 'ollama' | 'lmstudio'+ * @param {(p: { event: string, message: string }) => void} [onProgress]+ */+export async function installBackend(backend, onProgress = () => {}) {+ if (!isBackend(backend)) return { success: false, error: `Unknown backend: ${backend}` }+ const emit = (message) => onProgress({ event: 'start', message })+ const downloadHint = `Download it from ${DOWNLOAD_URL[backend]}.`++ if (!canAutoInstall(backend)) {+ return { success: false, error: `Automatic install isn't supported on this platform. ${downloadHint}` }+ }++ // Linux Ollama: official install script.+ if (process.platform === 'linux') {+ emit('Installing Ollama via the official install script…')+ const r = await runStreaming('bash', ['-c', 'curl -fsSL https://ollama.com/install.sh | sh'], emit, BACKEND_INSTALL_TIMEOUT_MS)+ if (!r.success) return { success: false, error: `Ollama install failed: ${r.error}. ${downloadHint}` }+ console.log('⬇️ Installed Ollama (linux script)')+ return { success: true, backend }+ }++ // macOS: Homebrew (formula for Ollama, cask for LM Studio).+ if (!(await commandExists('brew', ['--version']))) {+ return { success: false, error: `Homebrew not found — install it from https://brew.sh first, or download the app: ${DOWNLOAD_URL[backend]}` }+ }+ const label = backend === 'ollama' ? 'Ollama' : 'LM Studio'+ const args = backend === 'ollama' ? ['install', 'ollama'] : ['install', '--cask', 'lm-studio']+ emit(`Installing ${label} via Homebrew (this can take a few minutes)…`)+ const r = await runStreaming('brew', args, emit, BACKEND_INSTALL_TIMEOUT_MS)+ if (!r.success) return { success: false, error: `Homebrew install failed: ${r.error}` }+ console.log(`🍺 Installed ${label} via Homebrew`)+ return {+ success: true,+ backend,+ note: backend === 'ollama'+ ? 'Start it with `ollama serve` (or `brew services start ollama`), then refresh.'+ : 'Launch LM Studio, enable the local server (Developer tab), then run `lms bootstrap`.'+ }+}+/** Normalize each backend's installed-model shape into one card shape. */function normalizeModels(backend, models) {if (backend === 'ollama') {@@ -155,7 +258,9 @@ export async function getStatus() {version: ollamaStatus.version,baseUrl: ollamaStatus.baseUrl,modelCount: ollamaStatus.modelCount,- models: normalizeModels('ollama', ollamaStatus.models)+ models: normalizeModels('ollama', ollamaStatus.models),+ canAutoInstall: canAutoInstall('ollama'),+ downloadUrl: DOWNLOAD_URL.ollama},lmstudio: {installed: lmsCli || lmStudioStatus.available,@@ -164,7 +269,9 @@ export async function getStatus() {baseUrl: lmStudioStatus.baseUrl,modelCount: lmStudioModels.models.length,models: lmStudioModels.models,- modelsError: lmStudioModels.error+ modelsError: lmStudioModels.error,+ canAutoInstall: canAutoInstall('lmstudio'),+ downloadUrl: DOWNLOAD_URL.lmstudio}}}diff --git a/server/services/localLlm.test.js b/server/services/localLlm.test.jsindex fab4a39f4b..7ab2c89a2e 100644--- a/server/services/localLlm.test.js+++ b/server/services/localLlm.test.js@@ -184,4 +184,22 @@ describe('localLlm', () => {expect(mocks.lmstudio.getAvailableModels).not.toHaveBeenCalled();});});++ describe('installBackend', () => {+ it('rejects an unknown backend', async () => {+ expect((await svc.installBackend('nope')).success).toBe(false);+ });++ it('returns a download hint on an unsupported platform (no install attempted)', async () => {+ const orig = Object.getOwnPropertyDescriptor(process, 'platform');+ Object.defineProperty(process, 'platform', { value: 'win32', configurable: true });+ try {+ const r = await svc.installBackend('lmstudio');+ expect(r.success).toBe(false);+ expect(r.error).toMatch(/lmstudio\.ai/); // surfaces the manual download link+ } finally {+ Object.defineProperty(process, 'platform', orig);+ }+ });+ });});