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: retry transient EOF errors during Ollama model pulls (#491)

[._.]/ Adam Eivydc72b64b4037
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 1ca6c2b151..f369da1b34 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -22,6 +22,7 @@ TBD
## Fixed
+- **Ollama model installs no longer die on a transient "EOF".** Pulling a model from the Local LLMs page could fail with a bare `EOF` status and leave the model uninstalled. Ollama streams pull progress as NDJSON, and a transient network hiccup between Ollama and the model registry/CDN surfaces mid-stream as an `{"error":"EOF"}` frame (or the response read dropping outright). PortOS gave up on the first occurrence — even though the `ollama` CLI silently retries these and the pull is resumable (partial blobs are kept). `pullModel` now retries the transient/EOF class up to 3 attempts with a linear backoff, continuing from the partial download rather than restarting; non-transient errors (bad model name, missing manifest) still fail fast. The install banner shows a "retrying after network error" notice during the backoff instead of stalling.
- **TUI agents no longer try (and fail) to `/quit` at the end of a run.** The spawned-agent completion workflow used to tell the agent to write its `.agent-done` sentinel and then run `/quit`. In current Claude Code, `/quit` is a UI command that can't be invoked programmatically — so the agent attempted `Skill(quit)`, hit an error, and printed a confusing "please run /quit yourself" message before idling. The prompt now treats the sentinel as the sole done signal (PortOS finalizes the run within 2s of seeing it and closes the session itself) and explicitly tells the agent not to run `/quit`.
- **Tabbed sub-nav strips no longer drift vertically on mobile.** The horizontally-scrolling sub-nav tabs (Media Gen and every other page that uses the shared `TabPills` primitive) could be dragged diagonally/vertically on iOS, producing an uneven, wonky scroll. Both `TabPills` scroll containers now set `touch-action: pan-x` so touch gestures pan the strip horizontally while vertical drags pass through to normal page scrolling.
- **Chief of Staff pane overflow** — content panel collapses to a single `flex-1 min-h-0 min-w-0 overflow-y-auto overflow-x-hidden` div so tall tab content scrolls inside the panel instead of expanding it. Event log rows in both `EventLog` and `TerminalCoSPanel` get `break-all` so long unbreakable tokens (URLs, hashes, paths) wrap inside the 320px sidebar instead of pushing the column wider visually.
diff --git a/server/routes/localLlm.js b/server/routes/localLlm.js
index 61eb236ba1..509cfe34c1 100644
--- a/server/routes/localLlm.js
+++ b/server/routes/localLlm.js
@@ -113,6 +113,7 @@ router.post('/install', asyncHandler(async (req, res) => {
// client's progress banner stuck on the last 'start'. Surface it as 'error'.
const result = await installModel(backend, modelId, (p) => {
if (p?.percent != null) emit('start', `${modelId}: ${p.status || 'downloading'} ${p.percent}%`)
+ else if (p?.retrying) emit('start', `${modelId}: ${p.status || 'retrying…'}`)
}).catch((err) => {
emit('error', `Install failed: ${err.message}`)
throw err
diff --git a/server/services/ollamaManager.js b/server/services/ollamaManager.js
index bc05d98770..5f9b237d42 100644
--- a/server/services/ollamaManager.js
+++ b/server/services/ollamaManager.js
@@ -28,6 +28,13 @@ import {
const execFileAsync = promisify(execFile)
const AVAILABILITY_CACHE_TTL_MS = 30_000
const DEFAULT_REQUEST_TIMEOUT_MS = 10_000
+// A pull streams progress as NDJSON; a transient network failure between Ollama
+// and the registry/CDN surfaces mid-stream as an `{"error":"EOF"}` frame (or the
+// response read rejecting outright). The `ollama` CLI silently retries these and
+// the pull is resumable — partial blobs are kept — so a retry continues rather
+// than restarts. Total attempts (1 initial + retries) and a linear backoff base.
+const PULL_MAX_ATTEMPTS = 3
+const PULL_RETRY_BASE_DELAY_MS = 1_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
@@ -406,8 +413,10 @@ async function getVersion() {
/**
* Pull a model, streaming progress. Resolves once the pull finishes.
+ * During a transient-error backoff the callback fires with `retrying: true`
+ * (and `percent: null`) so the UI can show a "retrying" banner instead of stalling.
* @param {string} modelId
- * @param {(p: { status: string, percent: number|null, completed?: number, total?: number }) => void} [onProgress]
+ * @param {(p: { status: string, percent: number|null, completed?: number, total?: number, retrying?: boolean }) => void} [onProgress]
* @returns {Promise<{ success: boolean, modelId: string, error?: string }>}
*/
async function pullModel(modelId, onProgress) {
@@ -416,17 +425,47 @@ async function pullModel(modelId, onProgress) {
}
console.log(`📥 Ollama pull: ${modelId}`)
+ let lastError = null
+ for (let attempt = 1; attempt <= PULL_MAX_ATTEMPTS; attempt++) {
+ const result = await attemptOllamaPull(modelId, onProgress)
+ if (result.success) {
+ installedModels = null // bust cache so the new model shows on next list
+ console.log(`✅ Ollama pull complete: ${modelId}${attempt > 1 ? ` (after ${attempt} attempts)` : ''}`)
+ return { success: true, modelId }
+ }
+ lastError = result.error
+ // Bad model name / missing manifest etc. won't fix themselves — only retry
+ // the transient network class, and only while attempts remain.
+ if (attempt >= PULL_MAX_ATTEMPTS || !isTransientPullError(lastError)) break
+ const delayMs = PULL_RETRY_BASE_DELAY_MS * attempt
+ console.warn(`🔁 Ollama pull ${modelId} hit transient error "${lastError}" (attempt ${attempt}/${PULL_MAX_ATTEMPTS}); retrying in ${delayMs}ms`)
+ if (typeof onProgress === 'function') onProgress({ status: 'retrying after network error', percent: null, retrying: true })
+ await new Promise((resolve) => setTimeout(resolve, delayMs))
+ }
+
+ console.error(`⚠️ Ollama pull failed for ${modelId}: ${lastError}`)
+ return { success: false, error: lastError, modelId }
+}
+
+/**
+ * A single pull attempt. Returns `{ success }` or `{ success: false, error }`.
+ * A read that rejects mid-stream (dropped connection) is caught and returned as
+ * an error string so the caller's retry loop can classify it like an `{error}`
+ * frame rather than letting it throw out of the request lifecycle.
+ * @param {string} modelId
+ * @param {(p: object) => void} [onProgress]
+ * @returns {Promise<{ success: boolean, error?: string }>}
+ */
+async function attemptOllamaPull(modelId, onProgress) {
// 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 }))
+ }, 0).catch((err) => ({ _err: describeFetchError(err) }))
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 }
+ return { success: false, error: response._err || `pull failed: ${response.status} ${response.statusText}` }
}
const lastError = await streamNdjson(response, (frame) => {
@@ -436,14 +475,48 @@ async function pullModel(modelId, onProgress) {
: null
onProgress({ status: frame.status || '', percent, completed: frame.completed, total: frame.total })
}
- })
+ }).catch((err) => err?.message || String(err))
- if (lastError) {
- return { success: false, error: lastError, modelId }
- }
- installedModels = null // bust cache so the new model shows on next list
- console.log(`✅ Ollama pull complete: ${modelId}`)
- return { success: true, modelId }
+ return lastError ? { success: false, error: lastError } : { success: true }
+}
+
+/**
+ * Flatten a thrown fetch error into a single descriptive string, walking the
+ * `cause` chain. Node/undici reports network failures as `TypeError: fetch
+ * failed` with the real reason (ECONNRESET, ETIMEDOUT, ...) tucked into
+ * `err.cause` (and sometimes nested deeper). Without this, the transient
+ * classifier only sees "fetch failed" and misclassifies retryable failures as
+ * fatal. Includes each level's `.code` so `isTransientPullError()` can match.
+ * @param {unknown} err
+ * @returns {string}
+ */
+function describeFetchError(err) {
+ const parts = []
+ let node = err
+ const seen = new Set()
+ // Bound the walk in case of a self-referential cause chain.
+ for (let depth = 0; node && typeof node === 'object' && depth < 5; depth++) {
+ if (seen.has(node)) break
+ seen.add(node)
+ if (node.code) parts.push(String(node.code))
+ if (node.message) parts.push(String(node.message))
+ node = node.cause
+ }
+ if (typeof node === 'string') parts.push(node)
+ return parts.join(': ') || String(err)
+}
+
+/**
+ * Classify a pull/stream error string as a transient network failure worth
+ * retrying (Ollama↔registry EOF, connection reset, undici "terminated", etc.).
+ * Non-transient errors — invalid model name, "file does not exist" — return
+ * false so the retry loop gives up immediately.
+ * @param {string|null|undefined} error
+ * @returns {boolean}
+ */
+function isTransientPullError(error) {
+ if (!error) return false
+ return /\beof\b|connection reset|reset by peer|broken pipe|socket hang up|other side closed|terminated|i\/o timeout|\btimeout\b|tls handshake|temporary failure|network is unreachable|connection refused|econnreset|etimedout|epipe/i.test(String(error))
}
/**
@@ -601,7 +674,7 @@ async function importModelFromGguf({ name, ggufPath, mode = 'copy' }) {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name, modelfile: buildModelfile(ggufPath), stream: true })
- }, 0).catch((err) => ({ _err: err.message }))
+ }, 0).catch((err) => ({ _err: describeFetchError(err) }))
if (response._err || !response.ok || !response.body) {
const error = response._err || `create failed: ${response.status} ${response.statusText}`
diff --git a/server/services/ollamaManager.test.js b/server/services/ollamaManager.test.js
new file mode 100644
index 0000000000..dfbb3568a3
--- /dev/null
+++ b/server/services/ollamaManager.test.js
@@ -0,0 +1,157 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+
+// 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.
+
+const encoder = new TextEncoder()
+
+// Build a fake streaming Response from a list of NDJSON frame objects. If
+// `rejectAt` is set, the reader throws on that read index (simulating a dropped
+// connection mid-stream — undici surfaces this as `TypeError: terminated`).
+function makeStreamResponse(frames, { rejectAt } = {}) {
+ const lines = frames.map((f) => encoder.encode(`${JSON.stringify(f)}\n`))
+ let i = 0
+ return {
+ ok: true,
+ status: 200,
+ body: {
+ getReader() {
+ return {
+ read: async () => {
+ if (rejectAt != null && i === rejectAt) { i++; throw new Error('terminated') }
+ if (i >= lines.length) return { value: undefined, done: true }
+ return { value: lines[i++], done: false }
+ },
+ releaseLock() {}
+ }
+ }
+ }
+ }
+}
+
+const versionResponse = () => ({ ok: true, status: 200, json: async () => ({ version: '0.24.0' }) })
+
+// Install a fetch stub that answers /api/version and dispenses one scripted
+// /api/pull response per call from the given queue.
+function stubFetch(pullResponses) {
+ const queue = [...pullResponses]
+ const pullUrls = []
+ const fn = vi.fn(async (url) => {
+ if (String(url).endsWith('/api/version')) return versionResponse()
+ if (String(url).endsWith('/api/pull')) {
+ pullUrls.push(url)
+ const next = queue.shift()
+ if (!next) throw new Error('pull called more times than scripted')
+ // A queued Error simulates fetch itself rejecting (request-level failure,
+ // e.g. undici `TypeError: fetch failed` with the real reason in .cause).
+ if (next instanceof Error) throw next
+ return next
+ }
+ throw new Error(`unexpected fetch: ${url}`)
+ })
+ vi.stubGlobal('fetch', fn)
+ return { fn, pullUrls }
+}
+
+// Fresh module per test → fresh availability cache so the version probe runs.
+async function loadPullModel() {
+ vi.resetModules()
+ const mod = await import('./ollamaManager.js')
+ return mod.pullModel
+}
+
+describe('ollamaManager.pullModel transient-error retry', () => {
+ beforeEach(() => { vi.useFakeTimers() })
+ afterEach(() => { vi.useRealTimers(); vi.unstubAllGlobals() })
+
+ // Drive a pull to completion while advancing the backoff timers.
+ async function runPull(pullModel, id) {
+ const onProgress = vi.fn()
+ const promise = pullModel(id, onProgress)
+ await vi.runAllTimersAsync()
+ return { result: await promise, onProgress }
+ }
+
+ it('retries a mid-stream {"error":"EOF"} frame and succeeds on a later attempt', async () => {
+ const pullModel = await loadPullModel()
+ const { pullUrls } = stubFetch([
+ makeStreamResponse([{ status: 'pulling manifest' }, { status: 'downloading', total: 100, completed: 40 }, { error: 'EOF' }]),
+ makeStreamResponse([{ status: 'downloading', total: 100, completed: 100 }, { status: 'success' }])
+ ])
+
+ const { result } = await runPull(pullModel, 'smollm:135m')
+
+ expect(result).toEqual({ success: true, modelId: 'smollm:135m' })
+ expect(pullUrls).toHaveLength(2) // one retry
+ })
+
+ it('retries a dropped-connection read rejection (undici "terminated")', async () => {
+ const pullModel = await loadPullModel()
+ const { pullUrls } = stubFetch([
+ makeStreamResponse([{ status: 'downloading', total: 100, completed: 10 }], { rejectAt: 1 }),
+ makeStreamResponse([{ status: 'success' }])
+ ])
+
+ const { result } = await runPull(pullModel, 'qwen2.5:0.5b')
+
+ expect(result.success).toBe(true)
+ expect(pullUrls).toHaveLength(2)
+ })
+
+ it('retries a request-level "fetch failed" whose real reason lives in err.cause (ECONNRESET)', async () => {
+ const pullModel = await loadPullModel()
+ // undici surfaces a dropped connection as `TypeError: fetch failed` with the
+ // actual ECONNRESET buried in `.cause` — the classifier must see the cause.
+ const fetchFailed = new TypeError('fetch failed')
+ fetchFailed.cause = Object.assign(new Error('read ECONNRESET'), { code: 'ECONNRESET' })
+ const { pullUrls } = stubFetch([
+ fetchFailed,
+ makeStreamResponse([{ status: 'success' }])
+ ])
+
+ const { result } = await runPull(pullModel, 'smollm:135m')
+
+ expect(result.success).toBe(true)
+ expect(pullUrls).toHaveLength(2) // classified transient via cause, retried
+ })
+
+ it('does NOT retry a non-transient error (bad model / missing manifest)', async () => {
+ const pullModel = await loadPullModel()
+ const { pullUrls } = stubFetch([
+ makeStreamResponse([{ status: 'pulling manifest' }, { error: 'pull model manifest: file does not exist' }])
+ ])
+
+ const { result } = await runPull(pullModel, 'does-not-exist')
+
+ expect(result.success).toBe(false)
+ expect(result.error).toContain('file does not exist')
+ expect(pullUrls).toHaveLength(1) // gave up immediately, no retry
+ })
+
+ it('gives up after the attempt ceiling and returns the last transient error', async () => {
+ const pullModel = await loadPullModel()
+ const { pullUrls } = stubFetch([
+ makeStreamResponse([{ error: 'EOF' }]),
+ makeStreamResponse([{ error: 'EOF' }]),
+ makeStreamResponse([{ error: 'EOF' }])
+ ])
+
+ const { result } = await runPull(pullModel, 'smollm:135m')
+
+ expect(result).toEqual({ success: false, error: 'EOF', modelId: 'smollm:135m' })
+ expect(pullUrls).toHaveLength(3) // PULL_MAX_ATTEMPTS
+ })
+
+ it('signals a retry to onProgress so the UI banner does not stall during backoff', async () => {
+ const pullModel = await loadPullModel()
+ stubFetch([
+ makeStreamResponse([{ error: 'EOF' }]),
+ makeStreamResponse([{ status: 'success' }])
+ ])
+
+ const { onProgress } = await runPull(pullModel, 'smollm:135m')
+
+ expect(onProgress).toHaveBeenCalledWith(expect.objectContaining({ retrying: true }))
+ })
+})