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
fix: manage Ollama context windows per model (#4366)
[._.]/ Adam Eivy76872060a25a
diff --git a/.changelog/next/fixed-issue-4366.md b/.changelog/next/fixed-issue-4366.mdnew file mode 100644index 0000000000..b7a76c924c--- /dev/null+++ b/.changelog/next/fixed-issue-4366.md@@ -0,0 +1 @@+- Ollama context-window management now canonicalizes loopback aliases, respects the selected model's runtime limit, and recovers after daemon restarts.diff --git a/server/lib/ollamaContext.js b/server/lib/ollamaContext.jsindex dcdd0f3785..5fed740663 100644--- a/server/lib/ollamaContext.js+++ b/server/lib/ollamaContext.js@@ -63,11 +63,24 @@ function hostOf(baseUrl) {if (!raw) return null// A bare `host:port` (the OLLAMA_HOST convention) is not a valid URL, so give// it a scheme before parsing rather than string-comparing the two spellings.- const withScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(raw) ? raw : `http://${raw}`+ const withScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(raw)+ ? raw.replace(/^(https?:\/\/):(?=\d|$)/i, '$1localhost:')+ : /^:\d+(?:\/.*)?$/.test(raw)+ ? `http://localhost${raw}`+ : `http://${raw}`// `URL.parse` returns null on invalid input instead of throwing (Node ≥22.1;// the repo's engine floor is 22.12), so no try/catch is needed here.const url = URL.parse(withScheme)- return url ? url.host.toLowerCase() : null+ if (!url) return null++ // Ollama treats loopback aliases as the same local daemon. Compare a+ // canonical hostname plus the parsed port so 127.0.0.1, [::1], and an empty+ // OLLAMA_HOST hostname cannot make a local provider look remote.+ const hostname = url.hostname.replace(/^\[|\]$/g, '').toLowerCase()+ const canonicalHostname = ['127.0.0.1', '::1', 'localhost'].includes(hostname)+ ? 'localhost'+ : hostname+ return `${canonicalHostname}${url.port ? `:${url.port}` : ''}`}/**diff --git a/server/lib/ollamaContext.test.js b/server/lib/ollamaContext.test.jsindex b1c7ddc6c6..3bca2d8a17 100644--- a/server/lib/ollamaContext.test.js+++ b/server/lib/ollamaContext.test.js@@ -115,6 +115,13 @@ describe('isSameOllamaDaemon', () => {expect(isSameOllamaDaemon('https://LOCALHOST:11434/', 'http://localhost:11434')).toBe(true)})+ it('matches loopback aliases, including IPv6 and an empty OLLAMA_HOST hostname', () => {+ expect(isSameOllamaDaemon('http://127.0.0.1:11434', 'http://localhost:11434')).toBe(true)+ expect(isSameOllamaDaemon('http://[::1]:11434/v1', 'http://localhost:11434')).toBe(true)+ expect(isSameOllamaDaemon(':11434', 'http://localhost:11434')).toBe(true)+ expect(isSameOllamaDaemon('http://:11434', 'http://127.0.0.1:11434')).toBe(true)+ })+it('rejects a different host or port — PortOS only manages the daemon it points at', () => {expect(isSameOllamaDaemon('http://192.0.2.10:11434', 'http://localhost:11434')).toBe(false)expect(isSameOllamaDaemon('http://localhost:11435', 'http://localhost:11434')).toBe(false)diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.jsindex 49847eb296..054cb9e336 100644--- a/server/services/agentCliSpawning.js+++ b/server/services/agentCliSpawning.js@@ -347,7 +347,9 @@ export async function spawnDirectly({// the same daemon context preparation as runner and TUI launches. This is// deliberately before spawn: a per-request window cannot reach a CLI that// talks to Ollama on its own.- const ollamaContext = isOllamaBackedProvider(provider) ? await ensureOllamaAgentContext(provider) : null;+ const ollamaContext = isOllamaBackedProvider(provider)+ ? await ensureOllamaAgentContext(provider, { model })+ : null;if (ollamaContext?.warning) {emitLog('warn', `Agent ${agentId} Ollama context preparation: ${ollamaContext.warning}`, {agentId,diff --git a/server/services/agentCliSpawning.test.js b/server/services/agentCliSpawning.test.jsindex 6f1ddc048c..a04e95489d 100644--- a/server/services/agentCliSpawning.test.js+++ b/server/services/agentCliSpawning.test.js@@ -610,7 +610,10 @@ describe('stream error containment', () => {});await new Promise((r) => setTimeout(r, 10));- expect(ensureOllamaAgentContext).toHaveBeenCalledWith(expect.objectContaining({ id: 'claude-ollama' }));+ expect(ensureOllamaAgentContext).toHaveBeenCalledWith(+ expect.objectContaining({ id: 'claude-ollama' }),+ { model: 'claude-3' },+ );expect(ensureOllamaAgentContext.mock.invocationCallOrder[0]).toBeLessThan(spawn.mock.invocationCallOrder[0]);fakeProcess.emit('close', 0);diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex 505df41e3f..eb956f2e51 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -1125,7 +1125,9 @@ export async function spawnTuiAgent({// failure mode otherwise is an hour of work lost to a 400 at 100% context.// Gated on the predicate here (not just inside the helper) so a cloud-provider// spawn — the overwhelmingly common case — takes no async hop at all.- const ollamaContext = isOllamaBackedProvider(provider) ? await ensureOllamaAgentContext(provider) : null;+ const ollamaContext = isOllamaBackedProvider(provider)+ ? await ensureOllamaAgentContext(provider, { model })+ : null;if (ollamaContext?.warning) appendLine(ollamaContext.warning);if (ollamaContext?.applied) appendLine(`🪟 Reloaded Ollama at a ${ollamaContext.contextLength}-token context window`);diff --git a/server/services/ollamaAgentContext.js b/server/services/ollamaAgentContext.jsindex 59d11af7fd..b14efbd40e 100644--- a/server/services/ollamaAgentContext.js+++ b/server/services/ollamaAgentContext.js@@ -39,11 +39,11 @@ import { ensureContextWindow, getBaseUrl, getRuntimeContextLength } from './olla* `isOllamaBackedProvider` too, so a cloud run takes no async hop at all; this* guard is the module's own contract, not the hot path.*- * @param {{id?:string, name?:string, numCtx?:number|null, envVars?:object, endpoint?:string, ollamaBacked?:boolean}|null} provider- * @param {{ env?: Record<string, string|undefined> }} [options]+ * @param {{id?:string, name?:string, defaultModel?:string|null, numCtx?:number|null, envVars?:object, endpoint?:string, ollamaBacked?:boolean}|null} provider+ * @param {{ env?: Record<string, string|undefined>, model?: string|null }} [options]* @returns {Promise<{ skipped: boolean, contextLength?: number|null, applied?: boolean, warning?: string|null }>}*/-export async function ensureOllamaAgentContext(provider, { env = process.env } = {}) {+export async function ensureOllamaAgentContext(provider, { env = process.env, model = provider?.defaultModel ?? null } = {}) {if (!provider || !isOllamaBackedProvider(provider)) return { skipped: true }// A provider can point at a REMOTE Ollama host. `ollamaManager` only ever// starts, stops, and inspects the local daemon, so acting on one of those@@ -57,7 +57,7 @@ export async function ensureOllamaAgentContext(provider, { env = process.env } =const providerName = provider.name || provider.id || nullif (!contextLength) {- const runtime = await getRuntimeContextLength().catch(() => null)+ const runtime = await (model ? getRuntimeContextLength(model) : getRuntimeContextLength()).catch(() => null)const warning = runtime != null && runtime < OLLAMA_AGENT_MIN_CONTEXT? describeOllamaContextTooSmall(runtime, { providerName }): null@@ -65,7 +65,10 @@ export async function ensureOllamaAgentContext(provider, { env = process.env } =return { skipped: false, contextLength: null, applied: false, warning }}- const result = await ensureContextWindow(contextLength).catch((err) => ({+ const result = await (model+ ? ensureContextWindow(contextLength, model)+ : ensureContextWindow(contextLength)+ ).catch((err) => ({applied: false, reason: 'error', error: err.message}))const warning = result.errordiff --git a/server/services/ollamaAgentContext.test.js b/server/services/ollamaAgentContext.test.jsindex 2ff78421d3..ccab857f8a 100644--- a/server/services/ollamaAgentContext.test.js+++ b/server/services/ollamaAgentContext.test.js@@ -51,6 +51,12 @@ describe('ensureOllamaAgentContext', () => {expect(result).toMatchObject({ skipped: false, contextLength: 131072, applied: true, warning: null })})+ it('passes the selected model through to runtime context management', async () => {+ ensureContextWindow.mockResolvedValue({ applied: true, reason: 'restarted' })+ await ensureOllamaAgentContext({ ...claudeOllamaTui, numCtx: 131072 }, { env: {}, model: 'small-model' })+ expect(ensureContextWindow).toHaveBeenCalledWith(131072, 'small-model')+ })+it('warns but does not block the spawn when the reload fails', async () => {ensureContextWindow.mockResolvedValue({ applied: false, reason: 'stop-failed', error: 'still reachable' })const result = await ensureOllamaAgentContext({ ...claudeOllamaTui, numCtx: 131072 }, { env: {} })diff --git a/server/services/ollamaManager.js b/server/services/ollamaManager.jsindex 694dac49ea..9082a7ac52 100644--- a/server/services/ollamaManager.js+++ b/server/services/ollamaManager.js@@ -96,6 +96,11 @@ let managedProcessPid = null// bounce the daemon before every single agent spawn. Once a window has been// handed over, that request is done.let appliedContextLength = null+// When the latch was established while a model was resident, an empty /api/ps+// response is evidence that the daemon was replaced behind PortOS's back. An+// idle daemon has no such evidence, so preserve its latch to avoid restarting+// on every pre-spawn while no model is loaded.+let appliedWhileModelResident = falseconst status = { lastError: null, lastSuccessAt: null, consecutiveErrors: 0 }@@ -202,6 +207,7 @@ async function checkOllamaAvailable(forceRefresh = false) {// The daemon we handed a window to is gone; whatever comes up next has to// be re-checked rather than credited with that window.appliedContextLength = null+ appliedWhileModelResident = falsestatus.lastError = err.messagestatus.consecutiveErrors++lastCheckAt = now@@ -427,23 +433,40 @@ async function ensureRunning({ preferPersistent = false } = {}) {return startServer()}+async function getRuntimeModels() {+ if (!(await checkOllamaAvailable())) return null+ const data = await ollamaRequest('/api/ps').catch(() => null)+ return Array.isArray(data?.models) ? data.models : []+}++const modelNames = (model) => [model?.name, model?.model]+ .filter((name) => typeof name === 'string' && name.trim())+ .map((name) => name.trim())+/**- * The context window the daemon actually loaded models at, read from `/api/ps`.- * Ollama reports it per resident model; we take the largest, since that is the- * window a request routed to an already-resident model will get.+ * The context window the daemon actually loaded at, read from `/api/ps`.+ * Ollama reports it per resident model. When a model is selected, only that+ * model is considered; without a selection, the smallest resident window is+ * used so a large sibling model cannot hide a smaller model's limit.*- * `null` means unknowable right now — no model is resident, so Ollama has not- * yet committed to a window. Callers must treat that as "no evidence", never as- * "too small": the daemon's own default may well be generous.+ * If a selected model is not resident yet, the fallback is the smallest window+ * among all resident models: every relevant resident model must meet the target+ * before the daemon can be treated as safe. `null` means no model is resident.+ * @param {string|null} [selectedModel]* @returns {Promise<number|null>}*/-async function getRuntimeContextLength() {- if (!(await checkOllamaAvailable())) return null- const data = await ollamaRequest('/api/ps').catch(() => null)- const windows = (Array.isArray(data?.models) ? data.models : [])- .map((m) => Number(m?.context_length))+async function getRuntimeContextLength(selectedModel = null) {+ const models = await getRuntimeModels()+ if (models == null) return null+ const wanted = typeof selectedModel === 'string' ? selectedModel.trim() : ''+ const selected = wanted+ ? models.filter((model) => modelNames(model).includes(wanted))+ : []+ const resident = selected.length ? selected : models+ const windows = resident+ .map((model) => Number(model?.context_length)).filter((n) => Number.isFinite(n) && n > 0)- return windows.length ? Math.max(...windows) : null+ return windows.length ? Math.min(...windows) : null}/**@@ -457,9 +480,10 @@ async function getRuntimeContextLength() {* the VRAM-based default `numCtx` exists to override.** @param {number|null} contextLength+ * @param {string|null} [selectedModel] - model the next request will use* @returns {Promise<{ applied: boolean, reason: string, contextLength: number|null, runtimeContextLength?: number|null, error?: string }>}*/-async function ensureContextWindow(contextLength) {+async function ensureContextWindow(contextLength, selectedModel = null) {const target = Number(contextLength) > 0 ? Math.floor(Number(contextLength)) : nullif (!target) return { applied: false, reason: 'not-configured', contextLength: null }if (!(await checkOllamaAvailable(true))) {@@ -470,7 +494,17 @@ async function ensureContextWindow(contextLength) {}if (Number(appliedContextLength) >= target) {- return { applied: false, reason: 'already-applied', contextLength: target, runtimeContextLength: appliedContextLength }+ // Availability alone cannot identify an Ollama process: an external+ // restart can become reachable before PortOS observes a failed probe. A+ // daemon that had a resident model and now has none is the positive live+ // evidence needed to invalidate the old process's latch. Keep the latch+ // for an idle daemon, because /api/ps is normally empty between runs.+ const residentRuntime = await getRuntimeContextLength()+ if (residentRuntime != null || !appliedWhileModelResident) {+ return { applied: false, reason: 'already-applied', contextLength: target, runtimeContextLength: appliedContextLength }+ }+ appliedContextLength = null+ appliedWhileModelResident = false}// `runtime == null` means nothing is resident, which is the NORMAL idle state@@ -479,7 +513,7 @@ async function ensureContextWindow(contextLength) {// user set `numCtx` to override, so leaving it alone here would make the// setting a no-op in the common case. Apply it; the `appliedContextLength`// latch keeps this to one reload per daemon.- const runtime = await getRuntimeContextLength()+ const runtime = await getRuntimeContextLength(selectedModel)if (runtime != null && runtime >= target) {return { applied: false, reason: 'already-large-enough', contextLength: target, runtimeContextLength: runtime }}@@ -492,6 +526,7 @@ async function ensureContextWindow(contextLength) {const service = await getServiceStatus().catch(() => null)if (service?.runAtStartup) {const viaService = await restartServiceWithContext(service, target)+ if (viaService.applied) appliedWhileModelResident = runtime != nullreturn { ...viaService, contextLength: target, runtimeContextLength: runtime }}@@ -500,6 +535,7 @@ async function ensureContextWindow(contextLength) {return { applied: false, reason: 'stop-failed', contextLength: target, runtimeContextLength: runtime, error: stopped.error }}const started = await startServer({ contextLength: target })+ if (started.success) appliedWhileModelResident = runtime != nullreturn started.success? { applied: true, reason: 'restarted', contextLength: target, runtimeContextLength: runtime }: { applied: false, reason: 'start-failed', contextLength: target, runtimeContextLength: runtime, error: started.error }diff --git a/server/services/ollamaManager.test.js b/server/services/ollamaManager.test.jsindex c8850d3148..65d1584584 100644--- a/server/services/ollamaManager.test.js+++ b/server/services/ollamaManager.test.js@@ -676,10 +676,18 @@ describe('ollamaManager context window', () => {}))}- it('reports the largest window across resident models', async () => {+ it('reports the smallest window across resident models when no model is selected', async () => {stubPs([{ name: 'a', context_length: 32768 }, { name: 'b', context_length: 131072 }])const { getRuntimeContextLength } = await loadManager()- expect(await getRuntimeContextLength()).toBe(131072)+ expect(await getRuntimeContextLength()).toBe(32768)+ })++ it('reports the selected model window instead of a larger resident sibling', async () => {+ stubPs([{ name: 'a', context_length: 32768 }, { name: 'b', context_length: 131072 }])+ const { getRuntimeContextLength } = await loadManager()+ expect(await getRuntimeContextLength('a')).toBe(32768)+ expect(await getRuntimeContextLength('b')).toBe(131072)+ expect(await getRuntimeContextLength('not-resident')).toBe(32768)})it('reports null when nothing is resident — Ollama has not committed to a window yet', async () => {@@ -746,6 +754,27 @@ describe('ollamaManager context window — launch-at-login daemons', () => {expect(calls.some((c) => c.includes('services stop'))).toBe(false)})+ it('reloads when the selected model is small even if another resident model is large', async () => {+ restorePlatform = pinPlatform('darwin')+ stubPs([{ name: 'small', context_length: 32768 }, { name: 'large', context_length: 131072 }])+ const calls = []+ 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 list') return cb(null, { stdout: 'ollama started testuser plist\n', stderr: '' })+ if (cmd === 'launchctl') return cb(null, { stdout: '', stderr: '' })+ if (cmd === 'brew' && a === 'services restart ollama') return cb(null, { stdout: '', stderr: '' })+ return cb(new Error(`unexpected exec: ${cmd} ${a}`))+ }++ const { ensureContextWindow } = await loadManager()+ const result = await ensureContextWindow(65536, 'small')++ expect(result).toMatchObject({ applied: true, reason: 'service-restarted', contextLength: 65536, runtimeContextLength: 32768 })+ expect(calls).toContain('launchctl setenv OLLAMA_CONTEXT_LENGTH 65536')+ })+// An idle daemon (nothing resident) is the NORMAL state between runs. Skipping// it would make `numCtx` a no-op exactly when it matters: the window Ollama// picks when the harness loads its model is the VRAM-based default the setting@@ -795,6 +824,32 @@ describe('ollamaManager context window — launch-at-login daemons', () => {expect(second).toMatchObject({ applied: false, reason: 'already-applied' })})+ it('reapplies the window when a resident daemon is externally replaced', async () => {+ restorePlatform = pinPlatform('darwin')+ let models = [{ name: 'a', context_length: 32768 }]+ vi.stubGlobal('fetch', vi.fn(async (url) => {+ const body = String(url).endsWith('/api/ps') ? { models } : { version: '0.32.13' }+ return { ok: true, status: 200, json: async () => body, text: async () => JSON.stringify(body) }+ }))+ let restarts = 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 list') return cb(null, { stdout: 'ollama started testuser plist\n', stderr: '' })+ if (cmd === 'launchctl') return cb(null, { stdout: '', stderr: '' })+ if (cmd === 'brew' && a === 'services restart ollama') { restarts++; return cb(null, { stdout: '', stderr: '' }) }+ return cb(new Error(`unexpected exec: ${cmd} ${a}`))+ }++ const { ensureContextWindow } = await loadManager()+ await ensureContextWindow(131072, 'a')+ models = []+ const result = await ensureContextWindow(131072, 'a')++ expect(restarts).toBe(2)+ expect(result).toMatchObject({ applied: true, reason: 'service-restarted' })+ })+it('reports the systemd drop-in instead of tearing the unit down', async () => {restorePlatform = pinPlatform('linux')stubPs([{ name: 'a', context_length: 32768 }])diff --git a/server/services/runner.js b/server/services/runner.jsindex 1b87280fc7..011c278618 100644--- a/server/services/runner.js+++ b/server/services/runner.js@@ -293,7 +293,9 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, on// services/ollamaAgentContext.js.// Gated on the predicate here (not just inside the helper) so a cloud-provider// run — the overwhelmingly common case — takes no async hop at all.- const ollamaContext = isOllamaBackedProvider(provider) ? await ensureOllamaAgentContext(provider) : null;+ const ollamaContext = isOllamaBackedProvider(provider)+ ? await ensureOllamaAgentContext(provider, { model: provider.defaultModel ?? null })+ : null;if (ollamaContext?.warning) onData?.(`${ollamaContext.warning}\n`);// Shared composition (provider.envVars + OpenCode models map + PWD pin +