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

Add Ollama service controls

Adam Eivye97cf18dc141
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 5c25372c9b..169325e606 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -1,7 +1,7 @@
# Unreleased Changes
## Added
-- **[local-llm-backend-management] Local LLMs — pick a backend at setup, manage models, and migrate between Ollama and LM Studio.** Setup now asks whether you want **Ollama** or **LM Studio** for local on-device models and installs the chosen one if it's missing (`scripts/setup-llm.js`, wired into `npm run setup`; `npm run setup:llm` to run it standalone). The choice is recorded as `LLM_BACKEND` in `.env`, and the matching AI provider is auto-enabled on boot. A new **Settings → Local LLMs** tab (reachable from the sidebar, ⌘K, and voice) shows both backends' status, **one-click installs a missing backend** (Homebrew on macOS for both; the official script for Ollama on Linux; a download link elsewhere — with live installer output over the socket), makes clear **both backends can run at the same time** — the **Default** marker (formerly the misleading "Active" badge, which read as a running-state indicator) just picks which one PortOS routes local runs to, and **Set as Default** changes it without moving anything — and lets you **move models between the two in either direction, independently of the default**: the GGUF weights are portable (only the on-disk *layout* differs — Ollama's content-addressed blob store vs LM Studio's plain file tree), so each backend card's **Import from…** action offers **Link** (hardlink the GGUF so both backends share one file on disk — zero extra space, falling back to a copy across filesystems) or **Copy** (an independent duplicate), with **no re-download** either way; models that can't be shared/copied — LM Studio MLX-format, sharded, or (when targeting Ollama) multimodal — re-pull the cross-backend catalog equivalent. It also manages models like the LoRA/Media-Models pages do: a curated cross-backend catalog with search, one-click install, free-text "pull by name", and delete — with live pull progress over the `localLlm:progress` socket. Server side: `server/services/ollamaManager.js` (native Ollama HTTP API + local GGUF import via `/api/create`, with link mode pre-placing a content-addressed `blobs/sha256-…` hardlink so create dedups against it), `server/services/lmStudioManager.js` (hardlink-or-copy GGUF into LM Studio's model tree), `server/services/localLlm.js` (unified orchestration + `.env` default marker + provider enabling + bidirectional link/copy migrate, decoupled from the default), `server/lib/localLlmCatalog.js` (pure catalog + install-id mapping), `server/lib/localLlmDisk.js` (pure on-disk GGUF/manifest reasoning for the local-share/copy fast-path), and `/api/local-llm/*` routes.
+- **[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), can **start or stop Ollama directly** when the local server is installed but not running, makes clear **both backends can run at the same time** — the **Default** marker (formerly the misleading "Active" badge, which read as a running-state indicator) just picks which one PortOS routes local runs to, and **Set as Default** changes it without moving anything — and lets you **move models between the two in either direction, independently of the default**: the GGUF weights are portable (only the on-disk *layout* differs — Ollama's content-addressed blob store vs LM Studio's plain file tree), so each backend card's **Import from…** action offers **Link** (hardlink the GGUF so both backends share one file on disk — zero extra space, falling back to a copy across filesystems) or **Copy** (an independent duplicate), with **no re-download** either way; models that can't be shared/copied — LM Studio MLX-format, sharded, or (when targeting Ollama) multimodal — re-pull the cross-backend catalog equivalent. It also manages models like the LoRA/Media-Models pages do: a curated cross-backend catalog with search, one-click install, free-text "pull by name", and delete — with live pull progress over the `localLlm:progress` socket. Server side: `server/services/ollamaManager.js` (native Ollama HTTP API + local GGUF import via `/api/create`, with link mode pre-placing a content-addressed `blobs/sha256-…` hardlink so create dedups against it), `server/services/lmStudioManager.js` (hardlink-or-copy GGUF into LM Studio's model tree), `server/services/localLlm.js` (unified orchestration + `.env` default marker + provider enabling + bidirectional link/copy migrate, decoupled from the default), `server/lib/localLlmCatalog.js` (pure catalog + install-id mapping), `server/lib/localLlmDisk.js` (pure on-disk GGUF/manifest reasoning for the local-share/copy fast-path), and `/api/local-llm/*` routes.
- **[codex5-onboarding-capability-map] Capabilities page — every connected system at a glance.** A new Capabilities page (under System) shows the status of each integration on one screen: AI Providers, Calendar, Brain & Memory, Voice, Tailscale & HTTPS, Genome & Health, Telegram, Messages, and Apps & Processes. Every row says whether it's set up and healthy — Ready, Degraded, Error, or Not set up — and links straight to its settings, so the page works as both a first-run setup checklist and a quick runtime health overview. Reachable from the sidebar, ⌘K, and voice.
- **Federated media collections + per-category sync integrity.** Media collections are now a first-class peer-sync record kind (`mediaCollection` in `PEER_SUBSCRIBABLE_KINDS`, schema-version-gated at `mediaCollections: 1`): they auto-subscribe on create, push per-record on edit, and propagate deletes via tombstones — collections now reach parity between federated machines the way universes/series already did, instead of only riding along as `linkedCollection` cargo or the opt-in 60s snapshot. Required adding soft-delete to collections (`deleted`/`deletedAt`; `deleteCollection` marks instead of splicing; `listCollections({ includeDeleted })`; tombstone-aware LWW merge; tombstone GC), so a delete on one node can't be resurrected by a reverse-subscribed peer. Synced images now carry their **generation prompts**: the peer asset manifest advertises a canonical gen-params-only `sidecarSha256` (machine-local hash-cache stripped so it converges across peers), and the asset-pull worker fetches each image's `.metadata.json` sidecar alongside the bytes — fixing images that previously landed in "Unsorted" with no prompts. A new per-category **sync integrity** surface (`GET /api/peer-sync/manifest`, `GET /api/peer-sync/integrity`, pure `computeRecordIntegrity` diff) drives a `SyncBadge` on every Universe / Series / Media-Collection row (in-sync / diverged / assets-missing / local-only / on-peer-only / "not syncing — enable?") plus a deep-linkable `SyncDetailDrawer` (`/…/:id/sync`) showing the per-peer breakdown, previews, and manual actions: **Sync to peer** (`POST /sync-record`, force-push bypassing the unchanged-hash short-circuit), **Sync now** (`POST /sync-now`, backfill-subscribe + retry a peer's pending pushes), and **Pull missing prompts** (`POST /pull-metadata` + a button on the Unsorted view that backfills sidecars from online peers). `mediaCollections` sync stays **opt-in** per peer (default off); the badge surfaces a clear "enable?" state rather than flipping the default.
- **Manual tombstone GC trigger.** The 60s `syncOrchestrator` sweep buffers tombstones for 24h to give every peer time to ack a deletion before the bytes leave disk — fine for normal use, painful right after a mass-delete. New `POST /api/sync/tombstones/sweep` (Zod-validated optional `{ graceMs }` clamped to `[0, 24h]`) calls `sweepTombstones({ graceMs })` so callers can shrink the buffer; the per-kind null-cutoff refusal (snapshot-mode peer with no per-record subscription) still fires independently of `graceMs` to preserve resurrection safety. Companion `GET /api/sync/tombstones/status` returns the dry-run refusal status without invoking the prune helpers. A new "GC tombstones now" section on the Instances page (between SelfCard/AddPeer and the peers list) POSTs `graceMs: 0` and surfaces per-kind prune counts + any refusals in a toast; the button is disabled only when every kind is refused. `scripts/gc-tombstones-now.js` is the equivalent CLI path (dry-run by default; `--apply` to prune) for headless cleanups — uses the same "stop the server first, single-process write-tail isn't cross-process safe" wording as `cleanup-test-data.js`. `sweepTombstones` now returns `{ universes, series, issues, refused }` so the manual trigger can explain why a kind didn't shrink. The orchestrator path keeps the 24h default behavior unchanged.
diff --git a/client/src/components/settings/LocalLlmTab.jsx b/client/src/components/settings/LocalLlmTab.jsx
index 55badf9763..d4df515b77 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, ExternalLink, Star, Link2, Copy } from 'lucide-react';
+import { Cpu, Box, ArrowRightLeft, Download, Trash2, RefreshCw, Search, Plus, ExternalLink, Star, Link2, Copy, Play, Square } from 'lucide-react';
import toast from '../ui/Toast';
import BrailleSpinner from '../BrailleSpinner';
import { formatBytes } from '../../utils/formatters';
import {
getLocalLlmStatus, getLocalLlmCatalog, installLocalLlmModel,
- deleteLocalLlmModel, switchLocalLlmBackend, migrateLocalLlmBackend, installLocalLlmBackend
+ deleteLocalLlmModel, switchLocalLlmBackend, migrateLocalLlmBackend, installLocalLlmBackend, controlOllamaService
} from '../../services/api';
import socket from '../../services/socket';
@@ -101,6 +101,23 @@ function BackendCard({ backend, status, isDefault, busy, actionInProgress, runAc
{data?.installed && (
<div className="flex flex-wrap gap-1.5 pt-1 border-t border-port-border/50">
+ {backend.id === 'ollama' && data?.canControl && (
+ <button
+ onClick={() => runAction(
+ `ollama-service-${data.available ? 'stop' : 'start'}`,
+ () => controlOllamaService(data.available ? 'stop' : 'start'),
+ data.available ? 'Ollama stopped' : 'Ollama is running'
+ )}
+ disabled={busy}
+ className={`${btnClass} ${data.available ? 'bg-port-warning/20 hover:bg-port-warning/30 text-port-warning' : 'bg-port-accent/20 hover:bg-port-accent/30 text-port-accent'}`}
+ title={data.available ? 'Stop the local Ollama server' : 'Start the local Ollama server'}
+ >
+ {actionInProgress === `ollama-service-${data.available ? 'stop' : 'start'}`
+ ? <BrailleSpinner />
+ : data.available ? <Square size={12} /> : <Play size={12} />}
+ {data.available ? 'Stop' : 'Start'} Ollama
+ </button>
+ )}
{!isDefault && (
<button
onClick={() => runAction(`switch-${backend.id}`, () => switchLocalLlmBackend(backend.id), `${backend.label} is now the default backend`)}
@@ -307,11 +324,23 @@ export function LocalLlmTab() {
</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>
+ <div className="flex items-center gap-2 flex-wrap text-xs text-port-warning">
+ <span>
+ {labelFor(selected)} isn't running — {selectedData.installed
+ ? (selected === 'ollama' ? 'start it to install or manage models.' : 'launch the app and enable the local server.')
+ : 'install it first (Settings → Local LLMs prompts at setup, or run `npm run setup:llm`).'}
+ </span>
+ {selected === 'ollama' && selectedData.installed && selectedData.canControl && (
+ <button
+ onClick={() => runAction('ollama-service-start-models', () => controlOllamaService('start'), 'Ollama is running')}
+ disabled={busy}
+ className={`${btnClass} bg-port-accent/20 hover:bg-port-accent/30 text-port-accent`}
+ >
+ {actionInProgress === 'ollama-service-start-models' ? <BrailleSpinner /> : <Play size={12} />}
+ Start Ollama
+ </button>
+ )}
+ </div>
)}
{selectedData?.available && selectedData?.modelsError && (
<p className="text-xs text-port-warning">
diff --git a/client/src/services/apiLocalLlm.js b/client/src/services/apiLocalLlm.js
index 802c69d5a2..376ca993e8 100644
--- a/client/src/services/apiLocalLlm.js
+++ b/client/src/services/apiLocalLlm.js
@@ -16,6 +16,9 @@ export const deleteLocalLlmModel = (backend, modelId) =>
export const installLocalLlmBackend = (backend) =>
request('/local-llm/install-backend', { method: 'POST', body: JSON.stringify({ backend }) });
+export const controlOllamaService = (action) =>
+ request('/local-llm/ollama-service', { method: 'POST', body: JSON.stringify({ action }) });
+
// Set the default backend (which one PortOS routes local runs to) — does not move models.
export const switchLocalLlmBackend = (to) =>
request('/local-llm/switch', { method: 'POST', body: JSON.stringify({ to }) });
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 6b92206342..77c82702a9 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -1062,6 +1062,7 @@ export const localLlmMigrateSchema = z.object({
mode: z.enum(['link', 'copy']).optional().default('link'),
});
export const localLlmInstallBackendSchema = z.object({ backend: localLlmBackendSchema });
+export const localLlmOllamaServiceSchema = z.object({ action: z.enum(['start', 'stop']) });
/**
* Validate data against a Zod schema, throwing on failure.
diff --git a/server/routes/localLlm.js b/server/routes/localLlm.js
index bee65ede97..434d6f9fcb 100644
--- a/server/routes/localLlm.js
+++ b/server/routes/localLlm.js
@@ -16,11 +16,12 @@ import {
localLlmDeleteSchema,
localLlmSwitchSchema,
localLlmMigrateSchema,
- localLlmInstallBackendSchema
+ localLlmInstallBackendSchema,
+ localLlmOllamaServiceSchema
} from '../lib/validation.js'
import { getCatalog, searchCatalog, isBackend } from '../lib/localLlmCatalog.js'
import {
- getStatus, listModels, installModel, deleteModel, switchBackend, migrateBackend, installBackend
+ getStatus, listModels, installModel, deleteModel, switchBackend, migrateBackend, installBackend, controlOllamaServer
} from '../services/localLlm.js'
const router = Router()
@@ -62,6 +63,23 @@ router.post('/install-backend', asyncHandler(async (req, res) => {
res.json(result)
}))
+// POST /api/local-llm/ollama-service — start/stop the local Ollama server
+router.post('/ollama-service', asyncHandler(async (req, res) => {
+ const { action } = validateRequest(localLlmOllamaServiceSchema, req.body)
+ const emit = emitter(req)
+ emit('start', `${action === 'start' ? 'Starting' : 'Stopping'} Ollama…`)
+ const result = await controlOllamaServer(action).catch((err) => {
+ emit('error', `Ollama ${action} failed: ${err.message}`)
+ throw err
+ })
+ if (!result.success) {
+ emit('error', result.error || `Ollama ${action} failed`)
+ return res.status(502).json({ error: result.error || `Ollama ${action} failed` })
+ }
+ emit('complete', action === 'start' ? 'Ollama is running' : 'Ollama stopped')
+ 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.js
index 8c08d3f414..b4dc8447d1 100644
--- a/server/services/localLlm.js
+++ b/server/services/localLlm.js
@@ -218,6 +218,17 @@ export async function installBackend(backend, onProgress = () => {}) {
}
}
+/**
+ * Start/stop the Ollama HTTP server from the UI. LM Studio is app-controlled,
+ * so keep this intentionally narrow instead of inventing unreliable app-launch
+ * behavior for every platform.
+ */
+export async function controlOllamaServer(action) {
+ if (action === 'start') return ollamaManager.startServer()
+ if (action === 'stop') return ollamaManager.stopServer()
+ return { success: false, error: `Unknown Ollama action: ${action}` }
+}
+
/** Normalize each backend's installed-model shape into one card shape. */
function normalizeModels(backend, models) {
if (backend === 'ollama') {
@@ -269,6 +280,7 @@ export async function getStatus() {
baseUrl: ollamaStatus.baseUrl,
modelCount: ollamaStatus.modelCount,
models: normalizeModels('ollama', ollamaStatus.models),
+ canControl: ollamaCli || ollamaStatus.available,
canAutoInstall: canAutoInstall('ollama'),
downloadUrl: DOWNLOAD_URL.ollama
},
diff --git a/server/services/localLlm.test.js b/server/services/localLlm.test.js
index dabc98382e..9d515f19fd 100644
--- a/server/services/localLlm.test.js
+++ b/server/services/localLlm.test.js
@@ -16,6 +16,8 @@ const mocks = vi.hoisted(() => ({
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: [] })),
+ startServer: vi.fn(async () => ({ success: true, running: true })),
+ stopServer: vi.fn(async () => ({ success: true, running: false })),
// No local GGUF found by default → migrate falls back to re-pull.
resolveLocalModel: vi.fn(async () => null),
// Echo the requested mode as the real outcome (link mode "succeeds" in tests).
@@ -111,6 +113,22 @@ describe('localLlm', () => {
});
});
+ describe('controlOllamaServer', () => {
+ it('starts and stops Ollama through the Ollama manager', async () => {
+ expect(await svc.controlOllamaServer('start')).toEqual({ success: true, running: true });
+ expect(await svc.controlOllamaServer('stop')).toEqual({ success: true, running: false });
+ expect(mocks.ollama.startServer).toHaveBeenCalledTimes(1);
+ expect(mocks.ollama.stopServer).toHaveBeenCalledTimes(1);
+ });
+
+ it('rejects unknown Ollama service actions', async () => {
+ const r = await svc.controlOllamaServer('restart');
+ expect(r.success).toBe(false);
+ expect(mocks.ollama.startServer).not.toHaveBeenCalled();
+ expect(mocks.ollama.stopServer).not.toHaveBeenCalled();
+ });
+ });
+
describe('migrateBackend', () => {
it('moves the OTHER backend\'s known models onto the target WITHOUT changing the default', async () => {
writeEnv('LLM_BACKEND=lmstudio\n'); // default stays lmstudio throughout
diff --git a/server/services/ollamaManager.js b/server/services/ollamaManager.js
index 0691d0e0ce..5d134c89df 100644
--- a/server/services/ollamaManager.js
+++ b/server/services/ollamaManager.js
@@ -17,16 +17,21 @@
import { homedir } from 'os'
import { join, dirname } from 'path'
import { readdir, stat, link, mkdir } from 'fs/promises'
+import { execFile, spawn } from 'child_process'
+import { promisify } from 'util'
import { fetchWithTimeout } from '../lib/fetchWithTimeout.js'
import { readJSONFile, sha256File } from '../lib/fileUtils.js'
import {
parseOllamaManifest, parseOllamaModelRef, ollamaManifestRelPath, digestToBlobFilename, buildModelfile
} from '../lib/localLlmDisk.js'
+const execFileAsync = promisify(execFile)
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 START_TIMEOUT_MS = 12_000
+const STOP_TIMEOUT_MS = 8_000
const DEFAULT_CONFIG = {
// Ollama uses OLLAMA_HOST (host:port, no scheme) by convention; also accept
@@ -48,6 +53,8 @@ let isAvailable = null
// too — otherwise the catalog-overlay path re-hits /api/tags on every keystroke.
let installedModels = null
let lastCheckAt = null
+let managedProcess = null
+let managedProcessPid = null
const status = { lastError: null, lastSuccessAt: null, consecutiveErrors: 0 }
@@ -67,9 +74,9 @@ async function ollamaRequest(endpoint, options = {}) {
/**
* Check if Ollama is reachable (cached for AVAILABILITY_CACHE_TTL_MS).
*/
-async function checkOllamaAvailable() {
+async function checkOllamaAvailable(forceRefresh = false) {
const now = Date.now()
- if (lastCheckAt && now - lastCheckAt < AVAILABILITY_CACHE_TTL_MS && isAvailable !== null) {
+ if (!forceRefresh && lastCheckAt && now - lastCheckAt < AVAILABILITY_CACHE_TTL_MS && isAvailable !== null) {
return isAvailable
}
try {
@@ -89,6 +96,115 @@ async function checkOllamaAvailable() {
}
}
+function resetAvailabilityCache() {
+ isAvailable = null
+ lastCheckAt = null
+ installedModels = null
+}
+
+async function waitForAvailability(expected, timeoutMs) {
+ const deadline = Date.now() + timeoutMs
+ while (Date.now() < deadline) {
+ if ((await checkOllamaAvailable(true)) === expected) return true
+ await new Promise((resolve) => setTimeout(resolve, 400))
+ }
+ return (await checkOllamaAvailable(true)) === expected
+}
+
+function rememberManagedProcess(child) {
+ managedProcess = child
+ managedProcessPid = child.pid
+ child.on('exit', () => {
+ if (managedProcessPid === child.pid) {
+ managedProcess = null
+ managedProcessPid = null
+ }
+ })
+}
+
+async function terminateManagedProcess() {
+ const pid = managedProcessPid
+ if (!pid) return false
+ try {
+ process.kill(-pid, 'SIGTERM')
+ } catch {
+ try { process.kill(pid, 'SIGTERM') } catch { return false }
+ }
+ return true
+}
+
+/**
+ * Start the Ollama HTTP server via the local CLI.
+ * @returns {Promise<{ success: boolean, running?: boolean, alreadyRunning?: boolean, pid?: number, error?: string }>}
+ */
+async function startServer() {
+ if (await checkOllamaAvailable(true)) {
+ return { success: true, running: true, alreadyRunning: true }
+ }
+
+ let spawnError = null
+ const stderr = []
+ const child = spawn('ollama', ['serve'], {
+ detached: true,
+ stdio: ['ignore', 'ignore', 'pipe'],
+ env: process.env
+ })
+ rememberManagedProcess(child)
+ child.stderr?.on('data', (chunk) => {
+ stderr.push(chunk.toString())
+ if (stderr.join('').length > 2000) stderr.shift()
+ })
+ child.on('error', (err) => { spawnError = err })
+ child.unref()
+
+ const running = await waitForAvailability(true, START_TIMEOUT_MS)
+ if (running) {
+ console.log(`▶️ Started Ollama server (pid ${child.pid})`)
+ return { success: true, running: true, pid: child.pid }
+ }
+
+ const detail = spawnError?.message || stderr.join('').trim()
+ return {
+ success: false,
+ running: false,
+ error: `Ollama did not become reachable${detail ? `: ${detail}` : ''}`
+ }
+}
+
+/**
+ * Stop the Ollama HTTP server. Prefer the PortOS-managed process when we
+ * started it; otherwise terminate the local `ollama` process by executable name.
+ */
+async function stopServer() {
+ if (!(await checkOllamaAvailable(true))) {
+ return { success: true, running: false, alreadyStopped: true }
+ }
+
+ await terminateManagedProcess()
+ if (await waitForAvailability(false, STOP_TIMEOUT_MS)) {
+ resetAvailabilityCache()
+ console.log('⏹️ Stopped PortOS-managed Ollama server')
+ return { success: true, running: false }
+ }
+
+ if (process.platform === 'darwin' || process.platform === 'linux') {
+ const killed = await execFileAsync('pkill', ['-TERM', '-x', 'ollama'], { timeout: 5_000 })
+ .then(() => true)
+ .catch(() => false)
+ if (killed && await waitForAvailability(false, STOP_TIMEOUT_MS)) {
+ resetAvailabilityCache()
+ console.log('⏹️ Stopped Ollama server')
+ return { success: true, running: false }
+ }
+ }
+
+ return {
+ success: false,
+ running: true,
+ error: 'Ollama is running, but PortOS could not stop the local process automatically.'
+ }
+}
+
/**
* List installed models from /api/tags.
* @returns {Promise<Array<{ id, name, size, family, params, quantization, modifiedAt }>>}
@@ -356,5 +472,7 @@ export {
deleteModel,
getStatus,
resolveLocalModel,
- importModelFromGguf
+ importModelFromGguf,
+ startServer,
+ stopServer
}