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
Run Ollama as a startup service
Adam Eivy9f157d1c8a11
diff --git a/client/src/components/settings/LocalLlmTab.jsx b/client/src/components/settings/LocalLlmTab.jsxindex eb55bc2fe0..e9fec080cb 100644--- a/client/src/components/settings/LocalLlmTab.jsx+++ b/client/src/components/settings/LocalLlmTab.jsx@@ -1,5 +1,5 @@import { useState, useEffect, useRef, useCallback, useMemo } from 'react';-import { Cpu, Box, ArrowRightLeft, Download, Trash2, RefreshCw, Search, Plus, ExternalLink, Star, Link2, Copy, Play, Square } from 'lucide-react';+import { Cpu, Box, ArrowRightLeft, Download, Trash2, RefreshCw, Search, Plus, ExternalLink, Star, Link2, Copy, Play, Square, Power, PowerOff } from 'lucide-react';import toast from '../ui/Toast';import BrailleSpinner from '../BrailleSpinner';import { formatBytes } from '../../utils/formatters';@@ -54,6 +54,8 @@ function BackendCard({ backend, status, isDefault, busy, actionInProgress, runAcconst otherData = status?.[other];const statusLabel = data?.available ? 'Running' : data?.installed ? 'Installed (stopped)' : 'Not installed';const statusColor = data?.available ? 'bg-port-success' : data?.installed ? 'bg-port-warning' : 'bg-gray-600';+ const startupService = backend.id === 'ollama' ? data?.service : null;+ const runsAtStartup = Boolean(startupService?.runAtStartup);return (<div className="bg-port-bg border border-port-border rounded-lg p-3 space-y-2">@@ -79,6 +81,7 @@ function BackendCard({ backend, status, isDefault, busy, actionInProgress, runAc<div className="text-xs text-gray-400">{data?.modelCount ?? 0} model{(data?.modelCount ?? 0) === 1 ? '' : 's'} installed{data?.version && <> · v{data.version}</>}+ {startupService?.supported && <> · {runsAtStartup ? 'runs at login' : 'startup off'}</>}</div>{!data?.installed && (@@ -130,6 +133,23 @@ function BackendCard({ backend, status, isDefault, busy, actionInProgress, runAc{data.available ? 'Stop' : 'Start'} Ollama</button>)}+ {backend.id === 'ollama' && startupService?.supported && (+ <button+ onClick={() => runAction(+ `ollama-service-${runsAtStartup ? 'disable' : 'enable'}`,+ () => controlOllamaService(runsAtStartup ? 'disable' : 'enable'),+ runsAtStartup ? 'Ollama background service disabled' : 'Ollama will run at login'+ )}+ disabled={busy}+ className={`${btnClass} ${runsAtStartup ? '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={runsAtStartup ? 'Stop the Homebrew service and remove the launch-at-login registration' : 'Start Ollama with Homebrew services so it runs in the background at login'}+ >+ {actionInProgress === `ollama-service-${runsAtStartup ? 'disable' : 'enable'}`+ ? <BrailleSpinner />+ : runsAtStartup ? <PowerOff size={12} /> : <Power size={12} />}+ {runsAtStartup ? 'Disable Startup' : 'Run at Startup'}+ </button>+ )}{!isDefault && (<buttononClick={() => runAction(`switch-${backend.id}`, () => switchLocalLlmBackend(backend.id), `${backend.label} is now the default backend`)}@@ -258,6 +278,8 @@ export function LocalLlmTab() {const busy = actionInProgress != null;const selectedData = status?.[selected];+ const selectedOllamaStartupAction = selectedData?.service?.supported ? 'enable' : 'start';+ const selectedOllamaStartupLabel = selectedData?.service?.supported ? 'Run at Startup' : 'Start Ollama';const installedModels = selectedData?.models || [];const catalogCategories = useMemo(() => {const counts = new Map();@@ -376,17 +398,21 @@ export function LocalLlmTab() {<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.')+ ? (selected === 'ollama' ? 'use the controls to start it or keep it running at login.' : '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')}+ onClick={() => runAction(+ `ollama-service-${selectedOllamaStartupAction}-models`,+ () => controlOllamaService(selectedOllamaStartupAction),+ selectedOllamaStartupAction === 'enable' ? 'Ollama will run at login' : '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+ {actionInProgress === `ollama-service-${selectedOllamaStartupAction}-models` ? <BrailleSpinner /> : <Play size={12} />}+ {selectedOllamaStartupLabel}</button>)}</div>diff --git a/server/index.js b/server/index.jsindex 16f570d258..9e3d51bbeb 100644--- a/server/index.js+++ b/server/index.js@@ -70,6 +70,7 @@ import backupRoutes from './routes/backup.js';import databaseRoutes from './routes/database.js';import localLlmRoutes from './routes/localLlm.js';import { ensureBackendProvider, getBackend as getLocalLlmBackend } from './services/localLlm.js';+import { ensureRunning as ensureOllamaRunning } from './services/ollamaManager.js';import searchRoutes from './routes/search.js';import paletteRoutes from './routes/palette.js';import dashboardLayoutsRoutes from './routes/dashboardLayouts.js';@@ -274,8 +275,13 @@ try {// 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.-ensureBackendProvider(getLocalLlmBackend()).catch((err) =>+const activeLocalLlmBackend = getLocalLlmBackend();+ensureBackendProvider(activeLocalLlmBackend).catch((err) =>console.error(`⚠️ Failed to enable local LLM backend provider: ${err.message}`));+if (activeLocalLlmBackend === 'ollama') {+ ensureOllamaRunning({ preferPersistent: true }).catch((err) =>+ console.error(`⚠️ Failed to start Ollama for active local LLM backend: ${err.message}`));+}// Swap the toolkit's generic executeCliRun for PortOS's variant that adds// CLI-provider-specific args building (Codex `exec -`, Gemini stdin piping,diff --git a/server/lib/aiProvider.js b/server/lib/aiProvider.jsindex e9f7c7f57c..c4a2df2bf2 100644--- a/server/lib/aiProvider.js+++ b/server/lib/aiProvider.js@@ -5,6 +5,7 @@import { getAllProviders } from '../services/providers.js';import { startAIOp } from '../services/aiStatusEvents.js';+import { ensureProviderReady as ensureOllamaProviderReady, isOllamaProvider } from '../services/ollamaManager.js';const isAPI = (p) => p && p.type === 'api' && p.enabled !== false;@@ -185,6 +186,16 @@ export async function callProviderAISimple(provider, model, prompt, options = {}const startMs = Date.now();const elapsedSec = () => ((Date.now() - startMs) / 1000).toFixed(1);+ if (isOllamaProvider(provider)) {+ statusOp.update('provider:starting', 'Starting Ollama if needed…', { providerId: provider.id });+ const ready = await ensureOllamaProviderReady(provider).catch((err) => ({ success: false, error: err.message }));+ if (!ready.success) {+ const error = `Ollama is not running and PortOS could not start it: ${ready.error || 'unknown error'}`;+ statusOp.error(error);+ return { error };+ }+ }+const first = await postChatCompletion(provider, model, prompt, opts);if (!first.error) {statusOp.complete(`${doneLabel} done (${elapsedSec()}s)`);diff --git a/server/lib/aiToolkit/runner.js b/server/lib/aiToolkit/runner.jsindex f4dee70919..73b7d0f5af 100644--- a/server/lib/aiToolkit/runner.js+++ b/server/lib/aiToolkit/runner.js@@ -5,6 +5,7 @@ import { join, extname } from 'path';import { spawn } from 'child_process';import { randomUUID } from 'crypto';import { analyzeError, analyzeHttpError, ERROR_CATEGORIES } from './errorDetection.js';+import { ensureProviderReady as ensureOllamaProviderReady } from '../../services/ollamaManager.js';export function createRunnerService(config = {}) {const {@@ -309,16 +310,19 @@ export function createRunnerService(config = {}) {messageContent = prompt;}- const response = await fetch(`${provider.endpoint}/chat/completions`, {- method: 'POST',- headers,- signal: controller.signal,- body: JSON.stringify({- model: model || provider.defaultModel,- messages: [{ role: 'user', content: messageContent }],- stream: true- })- }).catch(err => ({ ok: false, error: err.message, status: 0 }));+ const ready = await ensureOllamaProviderReady(provider).catch((err) => ({ success: false, error: err.message }));+ const response = ready.success+ ? await fetch(`${provider.endpoint}/chat/completions`, {+ method: 'POST',+ headers,+ signal: controller.signal,+ body: JSON.stringify({+ model: model || provider.defaultModel,+ messages: [{ role: 'user', content: messageContent }],+ stream: true+ })+ }).catch(err => ({ ok: false, error: err.message, status: 0 }))+ : { ok: false, error: `Ollama is not running and PortOS could not start it: ${ready.error || 'unknown error'}`, status: 0 };if (!response.ok) {activeRuns.delete(runId);diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 77c82702a9..914aca0704 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -1062,7 +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']) });+export const localLlmOllamaServiceSchema = z.object({ action: z.enum(['start', 'stop', 'enable', 'disable']) });/*** Validate data against a Zod schema, throwing on failure.diff --git a/server/routes/localLlm.js b/server/routes/localLlm.jsindex 434d6f9fcb..d8ba7c08c3 100644--- a/server/routes/localLlm.js+++ b/server/routes/localLlm.js@@ -67,7 +67,13 @@ router.post('/install-backend', asyncHandler(async (req, res) => {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 actionLabel = {+ start: 'Starting Ollama…',+ stop: 'Stopping Ollama…',+ enable: 'Registering Ollama as a background service…',+ disable: 'Disabling Ollama background service…'+ }[action]+ emit('start', actionLabel)const result = await controlOllamaServer(action).catch((err) => {emit('error', `Ollama ${action} failed: ${err.message}`)throw err@@ -76,7 +82,13 @@ router.post('/ollama-service', asyncHandler(async (req, res) => {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')+ const completeLabel = {+ start: 'Ollama is running',+ stop: 'Ollama stopped',+ enable: 'Ollama will run in the background at login',+ disable: 'Ollama background service disabled'+ }[action]+ emit('complete', completeLabel)res.json(result)}))diff --git a/server/services/askService.js b/server/services/askService.jsindex a9f57e94ba..2c960a11af 100644--- a/server/services/askService.js+++ b/server/services/askService.js@@ -30,6 +30,7 @@ import { getEvents as getCalendarEvents } from './calendarSync.js';import { tokenize as bm25Tokenize, STOP_WORDS } from '../lib/bm25.js';import { VALID_MODES as STORAGE_VALID_MODES } from './askConversations.js';import { resolveCliModel } from '../lib/providerModels.js';+import { ensureProviderReady as ensureOllamaProviderReady } from './ollamaManager.js';// Re-export so the route can keep importing modes via askService — but// askConversations is the source of truth (it owns the persistence schema).@@ -426,6 +427,10 @@ async function* streamCompletion(provider, model, prompt, signal) {};let response;try {+ const ready = await ensureOllamaProviderReady(provider);+ if (!ready.success) {+ throw new Error(`Ollama is not running and PortOS could not start it: ${ready.error || 'unknown error'}`);+ }response = await fetch(`${provider.endpoint}/chat/completions`, {method: 'POST',headers,diff --git a/server/services/insightsService.js b/server/services/insightsService.jsindex 47d82a0883..84e5a4c5bc 100644--- a/server/services/insightsService.js+++ b/server/services/insightsService.js@@ -22,6 +22,7 @@ import { getActiveProvider, getProviderById } from './providers.js';import { getCorrelationData } from './appleHealthQuery.js';import { stripCodeFences, parseLLMJSON } from '../lib/aiProvider.js';import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';+import { ensureProviderReady as ensureOllamaProviderReady } from './ollamaManager.js';const DEFAULT_AI_TIMEOUT_MS = 300000;@@ -169,6 +170,11 @@ async function callProviderAISimple(provider, model, prompt, { temperature = 0.3const timeout = provider.timeout || DEFAULT_AI_TIMEOUT_MS;if (provider.type === 'api') {+ const ready = await ensureOllamaProviderReady(provider).catch((err) => ({ success: false, error: err.message }));+ if (!ready.success) {+ return { error: `Ollama is not running and PortOS could not start it: ${ready.error || 'unknown error'}` };+ }+const headers = { 'Content-Type': 'application/json' };if (provider.apiKey) headers['Authorization'] = `Bearer ${provider.apiKey}`;diff --git a/server/services/localLlm.js b/server/services/localLlm.jsindex 3b0e0a2189..ef32c2f091 100644--- a/server/services/localLlm.js+++ b/server/services/localLlm.js@@ -209,12 +209,31 @@ export async function installBackend(backend, onProgress = () => {}) {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`)+ if (backend === 'ollama') {+ emit('Starting Ollama as a Homebrew service…')+ const service = await ollamaManager.startPersistentService().catch((err) => ({ success: false, error: err.message }))+ if (service.success) {+ return {+ success: true,+ backend,+ service: service.service,+ note: 'Started as a Homebrew service; it will run in the background at login.'+ }+ }+ const fallback = await ollamaManager.startServer().catch((err) => ({ success: false, error: err.message }))+ return {+ success: true,+ backend,+ service: service.service,+ note: fallback.success+ ? `Installed, but Homebrew services could not register Ollama (${service.error}). Started it for this session.`+ : `Installed, but PortOS could not start Ollama automatically (${service.error || fallback.error}). Use Run at Startup from this screen.`+ }+ }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`.'+ note: 'Launch LM Studio, enable the local server (Developer tab), then run `lms bootstrap`.'}}@@ -226,6 +245,8 @@ export async function installBackend(backend, onProgress = () => {}) {export async function controlOllamaServer(action) {if (action === 'start') return ollamaManager.startServer()if (action === 'stop') return ollamaManager.stopServer()+ if (action === 'enable') return ollamaManager.startPersistentService()+ if (action === 'disable') return ollamaManager.stopPersistentService()return { success: false, error: `Unknown Ollama action: ${action}` }}@@ -281,6 +302,7 @@ export async function getStatus() {modelCount: ollamaStatus.modelCount,models: normalizeModels('ollama', ollamaStatus.models),canControl: ollamaCli || ollamaStatus.available,+ service: ollamaStatus.service,canAutoInstall: canAutoInstall('ollama'),downloadUrl: DOWNLOAD_URL.ollama},diff --git a/server/services/localLlm.test.js b/server/services/localLlm.test.jsindex 9d515f19fd..0fb2d491a8 100644--- a/server/services/localLlm.test.js+++ b/server/services/localLlm.test.js@@ -18,6 +18,8 @@ const mocks = vi.hoisted(() => ({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 })),+ startPersistentService: vi.fn(async () => ({ success: true, running: true, persistent: true })),+ stopPersistentService: vi.fn(async () => ({ success: true, running: false, persistent: 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).@@ -121,11 +123,20 @@ describe('localLlm', () => {expect(mocks.ollama.stopServer).toHaveBeenCalledTimes(1);});+ it('enables and disables Ollama as a persistent service', async () => {+ expect(await svc.controlOllamaServer('enable')).toEqual({ success: true, running: true, persistent: true });+ expect(await svc.controlOllamaServer('disable')).toEqual({ success: true, running: false, persistent: false });+ expect(mocks.ollama.startPersistentService).toHaveBeenCalledTimes(1);+ expect(mocks.ollama.stopPersistentService).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();+ expect(mocks.ollama.startPersistentService).not.toHaveBeenCalled();+ expect(mocks.ollama.stopPersistentService).not.toHaveBeenCalled();});});diff --git a/server/services/ollamaManager.js b/server/services/ollamaManager.jsindex 8fcd62f517..bc05d98770 100644--- a/server/services/ollamaManager.js+++ b/server/services/ollamaManager.js@@ -32,6 +32,7 @@ const DEFAULT_REQUEST_TIMEOUT_MS = 10_000const AVAILABILITY_PROBE_TIMEOUT_MS = 5_000const START_TIMEOUT_MS = 12_000const STOP_TIMEOUT_MS = 8_000+const SERVICE_COMMAND_TIMEOUT_MS = 20_000const DEFAULT_CONFIG = {// Ollama uses OLLAMA_HOST (host:port, no scheme) by convention; also accept@@ -58,6 +59,70 @@ let managedProcessPid = nullconst status = { lastError: null, lastSuccessAt: null, consecutiveErrors: 0 }+async function commandExists(cmd, args = ['--version']) {+ return execFileAsync(cmd, args, { timeout: 5_000 }).then(() => true).catch(() => false)+}++async function getServiceController() {+ if (process.platform === 'darwin' && await commandExists('brew', ['--version'])) {+ return {+ supported: true,+ manager: 'homebrew',+ start: ['brew', ['services', 'start', 'ollama']],+ stop: ['brew', ['services', 'stop', 'ollama']],+ list: ['brew', ['services', 'list']]+ }+ }+ if (process.platform === 'linux' && await commandExists('systemctl', ['--version'])) {+ return {+ supported: true,+ manager: 'systemd',+ start: ['systemctl', ['start', 'ollama']],+ stop: ['systemctl', ['stop', 'ollama']],+ list: ['systemctl', ['is-active', 'ollama']]+ }+ }+ return { supported: false, manager: null }+}++async function getServiceStatus() {+ const controller = await getServiceController()+ if (!controller.supported) {+ return { supported: false, manager: null, running: false, runAtStartup: false, status: null }+ }++ if (controller.manager === 'homebrew') {+ const [cmd, args] = controller.list+ const { stdout } = await execFileAsync(cmd, args, { timeout: SERVICE_COMMAND_TIMEOUT_MS }).catch(() => ({ stdout: '' }))+ const line = stdout.split('\n').find((entry) => entry.trim().startsWith('ollama '))+ const serviceStatus = line?.trim().split(/\s+/)[1] || 'none'+ const running = serviceStatus === 'started'+ return {+ supported: true,+ manager: 'homebrew',+ running,+ runAtStartup: running,+ status: serviceStatus+ }+ }++ if (controller.manager === 'systemd') {+ const [cmd, args] = controller.list+ const { stdout } = await execFileAsync(cmd, args, { timeout: SERVICE_COMMAND_TIMEOUT_MS }).catch(() => ({ stdout: '' }))+ const serviceStatus = stdout.trim() || 'inactive'+ const running = serviceStatus === 'active'+ return {+ supported: true,+ manager: 'systemd',+ running,+ runAtStartup: running,+ status: serviceStatus+ }+ }++ return { supported: false, manager: null, running: false, runAtStartup: false, status: null }+}+async function ollamaRequest(endpoint, options = {}) {const { timeout, headers, ...rest } = optionsconst response = await fetchWithTimeout(`${config.baseUrl}${endpoint}`, {@@ -171,6 +236,100 @@ async function startServer() {}}+async function startPersistentService() {+ const controller = await getServiceController()+ if (!controller.supported) {+ return { success: false, running: await checkOllamaAvailable(true), error: 'No supported Ollama background service manager found.' }+ }++ const [cmd, args] = controller.start+ resetAvailabilityCache()+ const result = await execFileAsync(cmd, args, { timeout: SERVICE_COMMAND_TIMEOUT_MS })+ .then(() => ({ success: true }))+ .catch((err) => ({ success: false, error: err.stderr?.trim() || err.stdout?.trim() || err.message }))++ const running = await waitForAvailability(true, START_TIMEOUT_MS)+ const service = await getServiceStatus().catch(() => ({+ supported: true,+ manager: controller.manager,+ running,+ runAtStartup: running,+ status: running ? 'started' : 'unknown'+ }))++ if (result.success && running) {+ console.log(`▶️ Started Ollama via ${controller.manager} service`)+ return { success: true, running: true, persistent: true, service }+ }++ return {+ success: false,+ running,+ persistent: false,+ service,+ error: result.error || 'Ollama service started, but the API did not become reachable.'+ }+}++async function stopPersistentService() {+ const controller = await getServiceController()+ if (!controller.supported) {+ return { success: false, running: await checkOllamaAvailable(true), error: 'No supported Ollama background service manager found.' }+ }++ const [cmd, args] = controller.stop+ const result = await execFileAsync(cmd, args, { timeout: SERVICE_COMMAND_TIMEOUT_MS })+ .then(() => ({ success: true }))+ .catch((err) => ({ success: false, error: err.stderr?.trim() || err.stdout?.trim() || err.message }))++ const stopped = await waitForAvailability(false, STOP_TIMEOUT_MS)+ if (stopped) resetAvailabilityCache()+ const service = await getServiceStatus().catch(() => ({+ supported: true,+ manager: controller.manager,+ running: !stopped,+ runAtStartup: !stopped,+ status: stopped ? 'stopped' : 'unknown'+ }))++ if (result.success && stopped) {+ console.log(`⏹️ Stopped Ollama ${controller.manager} service`)+ return { success: true, running: false, persistent: false, service }+ }++ return {+ success: false,+ running: !stopped,+ persistent: service.runAtStartup,+ service,+ error: result.error || 'Ollama service stopped, but the API still appears reachable.'+ }+}++async function ensureRunning({ preferPersistent = false } = {}) {+ if (await checkOllamaAvailable(true)) {+ return { success: true, running: true, alreadyRunning: true, service: await getServiceStatus().catch(() => null) }+ }+ if (preferPersistent) {+ const serviceResult = await startPersistentService()+ if (serviceResult.success) return serviceResult+ console.warn(`⚠️ Failed to start Ollama as a background service: ${serviceResult.error}`)+ }+ return startServer()+}++function isOllamaProvider(provider) {+ const endpoint = String(provider?.endpoint || '')+ return provider?.id === 'ollama' ||+ /ollama/i.test(provider?.name || '') ||+ /(^|[/:])(?:localhost|127\.0\.0\.1|\[::1\]):11434\b/i.test(endpoint)+}++async function ensureProviderReady(provider, options = {}) {+ if (!isOllamaProvider(provider)) return { success: true, skipped: true }+ return ensureRunning({ preferPersistent: options.preferPersistent !== false })+}+/*** Stop the Ollama HTTP server. Prefer the PortOS-managed process when we* started it; otherwise terminate the local `ollama` process by executable name.@@ -180,6 +339,12 @@ async function stopServer() {return { success: true, running: false, alreadyStopped: true }}+ const service = await getServiceStatus().catch(() => null)+ if (service?.runAtStartup) {+ const stoppedService = await stopPersistentService()+ if (stoppedService.success || !(await checkOllamaAvailable(true))) return stoppedService+ }+await terminateManagedProcess()if (await waitForAvailability(false, STOP_TIMEOUT_MS)) {resetAvailabilityCache()@@ -455,12 +620,14 @@ async function importModelFromGguf({ name, ggufPath, mode = 'copy' }) {async function getStatus(forceRefresh = false) {const available = await checkOllamaAvailable(forceRefresh)const models = available ? await getInstalledModels(true) : []+ const service = await getServiceStatus().catch(() => ({ supported: false, manager: null, running: false, runAtStartup: false, status: null }))return {available,baseUrl: config.baseUrl,version: available ? await getVersion() : null,modelCount: models.length,models,+ service,lastError: status.lastError,consecutiveErrors: status.consecutiveErrors}@@ -474,5 +641,11 @@ export {resolveLocalModel,importModelFromGguf,startServer,- stopServer+ stopServer,+ startPersistentService,+ stopPersistentService,+ ensureRunning,+ ensureProviderReady,+ isOllamaProvider,+ getServiceStatus}diff --git a/server/services/visionTest.js b/server/services/visionTest.jsindex 252695bef6..31a627eb5a 100644--- a/server/services/visionTest.js+++ b/server/services/visionTest.js@@ -11,6 +11,7 @@ import { join, extname } from 'path';import { getProviderById } from './providers.js';import { PATHS } from '../lib/fileUtils.js';import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';+import { ensureProviderReady as ensureOllamaProviderReady } from './ollamaManager.js';const SCREENSHOTS_DIR = PATHS.screenshots;const DEFAULT_VISION_TIMEOUT_MS = 60000;@@ -62,6 +63,10 @@ async function loadImageAsBase64(imagePath) {* @returns {Promise<Object>} - API response*/async function callVisionAPI({ endpoint, apiKey, model, imageDataUrl, prompt, timeout = DEFAULT_VISION_TIMEOUT_MS }) {+ await ensureOllamaProviderReady({ endpoint }).then((ready) => {+ if (!ready.success) throw new Error(`Ollama is not running and PortOS could not start it: ${ready.error || 'unknown error'}`);+ });+const response = await fetchWithTimeout(`${endpoint}/chat/completions`, {method: 'POST',headers: {