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

fix: recover from stale launchd bootstrap when enabling Ollama at startup

Ilya Eivy5b9da76d3ff4
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 86b18e0c93..b0e2da85a6 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -23,6 +23,7 @@
- **Hugging Face search results now rank by downloads and recency more strongly.** A model's download count and how recently it was updated now dominate the result ordering (recency is graduated — a model updated this week outranks an equivalent one from months or years ago, and stale models are demoted), so popular, actively-maintained models surface first instead of being outweighed by publisher/format bonuses.
- **[issue-1488] Pinning a small-context local model to a heavy analysis stage no longer overflows its window.** The reverse-outline, continuity-bible, comic-script verification, alternate-POV rewrite, and per-issue editorial-analysis stages used to size the manuscript they send to a fixed 48–60K-character floor regardless of the model — fine on a big-context provider, but on a genuinely small-window local model (e.g. an 8K-context model) that floor plus the prompt could exceed the window. These stages now scale the manuscript to the model's actual window, trimming it to fit a small one (never down to empty — a usable minimum is always kept) while still feeding the whole manuscript to a large-context model exactly as before.
- **Installing Ollama (or LM Studio) via Homebrew no longer reports a false "install failed."** `brew install` routinely exits non-zero *after* a successful pour — a failed `brew cleanup`, a dependency's post-install caveats, or env-hint noise (notably Ollama's new `mlx`/`mlx-c` dependencies) all bubble up as exit 1 even though the formula/cask is fully installed on disk. PortOS treated that exit code as a hard failure and told you the install didn't work, when in fact it did. The install path now verifies presence-on-disk via `brew list` after a non-zero exit and treats the package being installed as the source of truth — so a successful-but-noisy Homebrew install is reported as success and proceeds to start the backend, instead of surfacing a misleading error. (`server/services/localLlm.js`)
+- **Clicking "Run at Startup" for Ollama no longer fails with `Bootstrap failed: 5: Input/output error`.** Registering Ollama as a login service runs `brew services start ollama`, which shells out to `launchctl bootstrap` — and that fails with launchd error 5 (EIO) when a stale service registration is already loaded (left over from a prior `ollama serve`, an interrupted start, or a Homebrew upgrade). PortOS now detects that specific bootstrap conflict, boots out the stale registration (`brew services stop`), and retries the start once — so the toggle succeeds instead of surfacing the raw launchctl error. Unrelated start failures (e.g. permission errors) are not retried. (`server/services/ollamaManager.js`)
## Comic pages
diff --git a/server/services/ollamaManager.js b/server/services/ollamaManager.js
index 2e71d2e22d..a2cfb35149 100644
--- a/server/services/ollamaManager.js
+++ b/server/services/ollamaManager.js
@@ -253,17 +253,57 @@ async function startServer() {
}
}
+/**
+ * `brew services start` shells out to `launchctl bootstrap gui/<uid> …plist`,
+ * which fails with `Bootstrap failed: 5: Input/output error` when a service is
+ * already bootstrapped in that domain — a stale launchd registration left over
+ * from a prior `ollama serve`, an interrupted start, or a Homebrew upgrade. The
+ * job is loaded but `start` refuses to re-bootstrap it. Booting it out
+ * (`brew services stop`, i.e. `launchctl bootout`) clears the registration so
+ * the retry can bootstrap cleanly.
+ */
+function isBootstrapConflictError(message) {
+ const m = String(message || '').toLowerCase()
+ // "already loaded/bootstrapped" unambiguously means a stale registration.
+ if (/already (?:loaded|bootstrapped)/.test(m)) return true
+ // Otherwise require the failure to actually be about a launchctl *bootstrap*
+ // before trusting the EIO / exit-5 signal — so an unrelated brew failure that
+ // merely mentions "input/output error" (a disk EIO, a permissions error)
+ // can't trip the bootout-and-retry recovery. The two real-world shapes both
+ // name bootstrap: launchctl's own "Bootstrap failed: 5: Input/output error"
+ // and brew's wrapper "…launchctl bootstrap … exited with 5".
+ if (!/bootstrap/.test(m)) return false
+ return /bootstrap failed: 5\b/.test(m) ||
+ /\binput\/output error\b/.test(m) ||
+ /exited with 5\b/.test(m) ||
+ /\bbootstrap failed\b/.test(m)
+}
+
+async function runServiceStart(controller) {
+ const [cmd, args] = controller.start
+ return execFileAsync(cmd, args, { timeout: SERVICE_COMMAND_TIMEOUT_MS })
+ .then(() => ({ success: true }))
+ .catch((err) => ({ success: false, error: err.stderr?.trim() || err.stdout?.trim() || err.message }))
+}
+
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 }))
+ let result = await runServiceStart(controller)
+
+ // Recover from a stale launchd registration: bootstrap reported the job is
+ // already loaded, so boot it out and retry once. systemd's `enable --now` is
+ // idempotent and never hits this, so the recovery is homebrew-only.
+ if (!result.success && controller.manager === 'homebrew' && isBootstrapConflictError(result.error)) {
+ console.warn(`♻️ Ollama service start hit a stale launchd registration (${result.error}); booting out and retrying`)
+ const [stopCmd, stopArgs] = controller.stop
+ await execFileAsync(stopCmd, stopArgs, { timeout: SERVICE_COMMAND_TIMEOUT_MS }).catch(() => {})
+ result = await runServiceStart(controller)
+ }
const running = await waitForAvailability(true, START_TIMEOUT_MS)
const service = await getServiceStatus().catch(() => ({
@@ -966,5 +1006,6 @@ export {
ensureProviderReady,
isOllamaProvider,
getServiceStatus,
- getEmbeddings
+ getEmbeddings,
+ isBootstrapConflictError
}
diff --git a/server/services/ollamaManager.test.js b/server/services/ollamaManager.test.js
index 47f1d71e61..ddd1a47463 100644
--- a/server/services/ollamaManager.test.js
+++ b/server/services/ollamaManager.test.js
@@ -1,5 +1,15 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+// startPersistentService / getServiceStatus shell out via promisify(execFile).
+// Route every exec call through a per-test impl so the homebrew service flow can
+// be scripted (brew --version, services start/stop/list). `spawn` is referenced
+// at module import (startServer) but never invoked by these tests.
+const execMock = { impl: () => {} }
+vi.mock('child_process', () => ({
+ execFile: (cmd, args, opts, cb) => execMock.impl(cmd, args, opts, cb),
+ spawn: vi.fn()
+}))
+
// pullModel talks to Ollama over its native HTTP API via the global `fetch`
// (through fetchWithTimeout). We stub `fetch` so each test scripts the
// `/api/version` probe and a sequence of per-attempt `/api/pull` streams.
@@ -186,3 +196,138 @@ describe('ollamaManager.pullModel transient-error retry', () => {
expect(pullUrls).toHaveLength(1) // not retried — sharding won't resolve on retry
})
})
+
+describe('ollamaManager.isBootstrapConflictError', () => {
+ it('matches the launchctl bootstrap-5 / EIO failures brew surfaces', async () => {
+ const { isBootstrapConflictError } = await import('./ollamaManager.js')
+ expect(isBootstrapConflictError('Bootstrap failed: 5: Input/output error')).toBe(true)
+ expect(isBootstrapConflictError('Error: Failure while executing; `/bin/launchctl bootstrap gui/501 …` exited with 5.')).toBe(true)
+ expect(isBootstrapConflictError('service already loaded')).toBe(true)
+ })
+
+ it('does NOT match unrelated failures (no false bootout/retry)', async () => {
+ const { isBootstrapConflictError } = await import('./ollamaManager.js')
+ expect(isBootstrapConflictError('Permission denied')).toBe(false)
+ expect(isBootstrapConflictError('ollama: command not found')).toBe(false)
+ expect(isBootstrapConflictError('')).toBe(false)
+ expect(isBootstrapConflictError(undefined)).toBe(false)
+ })
+
+ it('requires bootstrap context — a bare EIO / exit-5 unrelated to bootstrap is not a conflict', async () => {
+ const { isBootstrapConflictError } = await import('./ollamaManager.js')
+ // A generic disk EIO during an unrelated brew step must not trip the bootout.
+ expect(isBootstrapConflictError('Error: write failed: Input/output error')).toBe(false)
+ // Some other command exiting 5 with no bootstrap involved.
+ expect(isBootstrapConflictError('Error: `brew cleanup` exited with 5.')).toBe(false)
+ })
+})
+
+describe('ollamaManager.startPersistentService bootstrap recovery (homebrew)', () => {
+ let originalPlatform
+ beforeEach(() => {
+ // Force the homebrew controller branch regardless of CI host OS.
+ originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform')
+ Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true })
+ })
+ afterEach(() => {
+ Object.defineProperty(process, 'platform', originalPlatform)
+ vi.unstubAllGlobals()
+ execMock.impl = () => {}
+ })
+
+ // Reachable /api/version so waitForAvailability resolves true on first probe.
+ function stubReachable() {
+ const body = { version: '0.24.0' }
+ vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, status: 200, json: async () => body, text: async () => JSON.stringify(body) })))
+ }
+
+ async function loadManager() {
+ vi.resetModules()
+ return import('./ollamaManager.js')
+ }
+
+ it('boots out a stale launchd registration and retries when start fails with bootstrap-5', async () => {
+ stubReachable()
+ const calls = []
+ let startAttempts = 0
+ execMock.impl = (cmd, args, opts, cb) => {
+ const a = (args || []).join(' ')
+ calls.push(`${cmd} ${a}`)
+ if (cmd === 'brew' && a === '--version') return cb(null, { stdout: 'Homebrew 4.0.0', stderr: '' })
+ if (cmd === 'brew' && a === 'services start ollama') {
+ startAttempts++
+ if (startAttempts === 1) {
+ const e = new Error('Bootstrap failed: 5: Input/output error')
+ e.stderr = 'Bootstrap failed: 5: Input/output error'
+ return cb(e)
+ }
+ return cb(null, { stdout: '', stderr: '' })
+ }
+ if (cmd === 'brew' && a === 'services stop ollama') return cb(null, { stdout: '', stderr: '' })
+ if (cmd === 'brew' && a === 'services list') return cb(null, { stdout: 'ollama started ilyaeivy ~/Library/LaunchAgents/homebrew.mxcl.ollama.plist\n', stderr: '' })
+ return cb(new Error(`unexpected exec: ${cmd} ${a}`))
+ }
+
+ const { startPersistentService } = await loadManager()
+ const result = await startPersistentService()
+
+ expect(result.success).toBe(true)
+ expect(result.persistent).toBe(true)
+ expect(startAttempts).toBe(2) // recovered: bootout then retried
+ expect(calls).toContain('brew services stop ollama')
+ })
+
+ it('does NOT bootout/retry when start fails for an unrelated reason', async () => {
+ stubReachable()
+ let startAttempts = 0
+ let stopCalled = false
+ execMock.impl = (cmd, args, opts, cb) => {
+ const a = (args || []).join(' ')
+ if (cmd === 'brew' && a === '--version') return cb(null, { stdout: 'Homebrew 4.0.0', stderr: '' })
+ if (cmd === 'brew' && a === 'services start ollama') {
+ startAttempts++
+ const e = new Error('Permission denied')
+ e.stderr = 'Permission denied'
+ return cb(e)
+ }
+ if (cmd === 'brew' && a === 'services stop ollama') { stopCalled = true; return cb(null, { stdout: '', stderr: '' }) }
+ if (cmd === 'brew' && a === 'services list') return cb(null, { stdout: 'ollama started ilyaeivy ~/Library/LaunchAgents/homebrew.mxcl.ollama.plist\n', stderr: '' })
+ return cb(new Error(`unexpected exec: ${cmd} ${a}`))
+ }
+
+ const { startPersistentService } = await loadManager()
+ // The API is still reachable here (stubReachable), but the failed start with a
+ // non-bootstrap error must not trigger the bootout-and-retry recovery path.
+ await startPersistentService()
+
+ expect(startAttempts).toBe(1)
+ expect(stopCalled).toBe(false)
+ })
+
+ it('surfaces the retry error (not the stale first error) when bootout+retry still fails', async () => {
+ // A non-successful start falls to the failure branch and reports result.error
+ // regardless of reachability; keep the API reachable so the probe returns fast.
+ stubReachable()
+ let startAttempts = 0
+ execMock.impl = (cmd, args, opts, cb) => {
+ const a = (args || []).join(' ')
+ if (cmd === 'brew' && a === '--version') return cb(null, { stdout: 'Homebrew 4.0.0', stderr: '' })
+ if (cmd === 'brew' && a === 'services start ollama') {
+ startAttempts++
+ const e = new Error(startAttempts === 1 ? 'Bootstrap failed: 5: Input/output error' : 'launchctl bootstrap gui/501 still wedged')
+ e.stderr = e.message
+ return cb(e)
+ }
+ if (cmd === 'brew' && a === 'services stop ollama') return cb(null, { stdout: '', stderr: '' })
+ if (cmd === 'brew' && a === 'services list') return cb(null, { stdout: 'ollama none\n', stderr: '' })
+ return cb(new Error(`unexpected exec: ${cmd} ${a}`))
+ }
+
+ const { startPersistentService } = await loadManager()
+ const result = await startPersistentService()
+
+ expect(startAttempts).toBe(2) // recovery was attempted
+ expect(result.success).toBe(false)
+ expect(result.error).toContain('still wedged') // retry's error, not the first
+ })
+})