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

address review (codex): apply the window when idle, skip remote daemons

Adam Eivy65ee1541f25f
diff --git a/server/lib/README.md b/server/lib/README.md
index 22683f8d26..1b731c2114 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -286,7 +286,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `huggingfaceModel.js` | HuggingFace base-model (image/video) classifier for the self-service "add a model" flow (#2124): inspect repo siblings + card → decide the loadable runtime/runner, STRICTLY refuse GGUF-only / wan / hunyuan / unclassifiable repos (so a bad add can't wedge the picker), build the `media-models.json` entry (`source:'user'`), + a `searchHuggingfaceModels` Hub-search helper. Pure. |
| `localLlmCatalog.js` | Curated cross-backend (Ollama↔LM Studio) local-LLM catalog + install-id mapping for the migrate flow. Pure. |
| `localLlmDisk.js` | Pure on-disk reasoning for the migrate "copy GGUF locally instead of re-downloading" fast-path (Ollama manifest/blob parsing, LM Studio path layout, MLX/projector/shard detection) plus the Hugging Face registry addressing used to finish an abandoned Ollama pull. |
-| `ollamaContext.js` | Ollama runtime context-window reasoning. `resolveOllamaContextLength(provider, env)` → the window PortOS should hold the daemon at (`provider.numCtx`, then `OLLAMA_CONTEXT_LENGTH`, then `null` = leave Ollama's VRAM-based auto-pick alone); `withOllamaContextEnv(env, n)` builds the `ollama serve` child env; `parseOllamaContextOverflow(text)` recognizes the `exceed_context_size_error` rejection and pulls `{ promptTokens, contextLength }` out of either the JSON body or the human message; `describeOllamaContextOverflow` / `describeOllamaContextTooSmall` render the actionable one-liners; `OLLAMA_AGENT_MIN_CONTEXT` is the window below which an agent harness is warned. Pure — the daemon side lives in `services/ollamaManager.js` (`ensureContextWindow`), the pre-spawn enforcement in `services/ollamaAgentContext.js`. |
+| `ollamaContext.js` | Ollama runtime context-window reasoning. `resolveOllamaContextLength(provider, env)` → the window PortOS should hold the daemon at (`provider.numCtx`, then `OLLAMA_CONTEXT_LENGTH`, then `null` = leave Ollama's VRAM-based auto-pick alone); `withOllamaContextEnv(env, n)` builds the `ollama serve` child env; `parseOllamaContextOverflow(text)` recognizes the `exceed_context_size_error` rejection and pulls `{ promptTokens, contextLength }` out of either the JSON body or the human message; `describeOllamaContextOverflow` / `describeOllamaContextTooSmall` render the actionable one-liners; `isSameOllamaDaemon(providerBase, managedBase)` compares host+port so a provider pointed at a *remote* Ollama never triggers a local-daemon reload; `OLLAMA_AGENT_MIN_CONTEXT` is the window below which an agent harness is warned. Pure — the daemon side lives in `services/ollamaManager.js` (`ensureContextWindow`), the pre-spawn enforcement in `services/ollamaAgentContext.js`. |
| `localModelHeuristics.js` | Capability heuristics for untyped local (Ollama/LM Studio) models. `isEmbeddingModel`/`isGenerationModel` (so a generation/fallback run never picks an embedding model like `nomic-embed-text`); `isVisionModel(model)` (string id or model card — prefers explicit `type:'vlm'`/`capabilities:['vision']` metadata, falls back to id regex; used by the LoRA captioner); `recommendEditorialModel(models)` ranks installed models for editorial review/editing. Pure. Mirror `isEmbeddingModel`/`isVisionModel` in `client/src/utils/providers.js`. |
| `loraDataset.js` | Pure helpers for character LoRA training datasets (`data/lora-datasets/`): `sanitizeLoraDataset` (collectionStore sanitizer), `deriveTriggerWord` (name → single-token slug with collision suffix), `prefixCaption` (idempotent trigger-word prefixing), `buildVariationMatrix` (deterministic view/pose/expression/outfit tuples for batch generation), `computeDatasetReadiness` (trainable gate: ≥`MIN_TRAINING_IMAGES` ready+captioned images, plus an advisory `recommended`/`quality` tier via `datasetQualityTier` nudging toward `RECOMMENDED_TRAINING_IMAGES`), `analyzeCaptionInvariants` (flags identity fragments repeated across ≥`INVARIANT_SHARE_THRESHOLD` of captions — those bind to the caption phrases instead of the trigger token, issue #1320) + `stripSharedFragments` (rewrite one caption with those fragments removed, trigger preserved). Prompt building + I/O live in `services/loraDatasetGenerate.js` / `services/loraDatasets.js`. |
| `issueLength.js` | Per-issue size targets fed into text stages. |
diff --git a/server/lib/ollamaContext.js b/server/lib/ollamaContext.js
index 01368b32fc..dcdd0f3785 100644
--- a/server/lib/ollamaContext.js
+++ b/server/lib/ollamaContext.js
@@ -57,6 +57,43 @@ export function resolveOllamaContextLength(provider, env = process.env) {
return positiveInt(provider?.numCtx) ?? positiveInt(env?.[OLLAMA_CONTEXT_ENV_VAR])
}
+/** `host:port` for comparing two Ollama base URLs, or null when unparseable. */
+function hostOf(baseUrl) {
+ const raw = String(baseUrl || '').trim()
+ 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}`
+ // `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
+}
+
+/**
+ * Whether `providerBaseUrl` names the same Ollama daemon as `managedBaseUrl`.
+ *
+ * `isOllamaBackedProvider` matches any provider whose tokens come from Ollama,
+ * including one pointed at a *remote* daemon — but PortOS can only start, stop,
+ * or hand a context window to the local one it manages. Reloading the local
+ * daemon for a provider served by another host would disrupt unrelated local
+ * work AND leave the provider's real daemon untouched, so the daemon-management
+ * path gates on this.
+ *
+ * Compares host + port only: scheme and `/v1` suffix vary between how a provider
+ * spells the endpoint and how `ollamaManager` normalizes it. Unparseable on
+ * either side → false, so an ambiguous value never authorizes a restart.
+ *
+ * @param {string|null|undefined} providerBaseUrl
+ * @param {string|null|undefined} managedBaseUrl
+ * @returns {boolean}
+ */
+export function isSameOllamaDaemon(providerBaseUrl, managedBaseUrl) {
+ const a = hostOf(providerBaseUrl)
+ const b = hostOf(managedBaseUrl)
+ return !!a && !!b && a === b
+}
+
/**
* Child env for `ollama serve`, carrying the resolved window. Returns `env`
* untouched when `contextLength` is null so a PortOS-started daemon keeps
diff --git a/server/lib/ollamaContext.test.js b/server/lib/ollamaContext.test.js
index c1461065ba..b1c7ddc6c6 100644
--- a/server/lib/ollamaContext.test.js
+++ b/server/lib/ollamaContext.test.js
@@ -4,6 +4,7 @@ import {
OLLAMA_CONTEXT_ENV_VAR,
describeOllamaContextOverflow,
describeOllamaContextTooSmall,
+ isSameOllamaDaemon,
parseOllamaContextOverflow,
resolveOllamaContextLength,
withOllamaContextEnv
@@ -106,3 +107,22 @@ describe('overflow descriptions', () => {
expect(text).toContain(`${OLLAMA_AGENT_MIN_CONTEXT / 1024}K`)
})
})
+
+describe('isSameOllamaDaemon', () => {
+ it('matches across scheme and /v1 spelling differences', () => {
+ expect(isSameOllamaDaemon('http://localhost:11434/v1', 'http://localhost:11434')).toBe(true)
+ expect(isSameOllamaDaemon('localhost:11434', 'http://localhost:11434')).toBe(true)
+ expect(isSameOllamaDaemon('https://LOCALHOST:11434/', 'http://localhost: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)
+ })
+
+ it('is false when either side is missing or unparseable, so nothing ambiguous authorizes a restart', () => {
+ expect(isSameOllamaDaemon('', 'http://localhost:11434')).toBe(false)
+ expect(isSameOllamaDaemon('http://localhost:11434', null)).toBe(false)
+ expect(isSameOllamaDaemon('http://', 'http://localhost:11434')).toBe(false)
+ })
+})
diff --git a/server/services/ollamaAgentContext.js b/server/services/ollamaAgentContext.js
index 18e6c51310..59d11af7fd 100644
--- a/server/services/ollamaAgentContext.js
+++ b/server/services/ollamaAgentContext.js
@@ -16,12 +16,17 @@
*/
import { isOllamaBackedProvider } from './providers.js'
+// Straight from `internal/` on purpose: it is deliberately NOT re-exported from
+// providers.js, and re-deriving the normalization here is exactly the drift that
+// exclusion exists to prevent.
+import { ollamaBaseFromProvider } from '../lib/aiToolkit/internal/ollamaBacked.js'
import {
OLLAMA_AGENT_MIN_CONTEXT,
describeOllamaContextTooSmall,
+ isSameOllamaDaemon,
resolveOllamaContextLength
} from '../lib/ollamaContext.js'
-import { ensureContextWindow, getRuntimeContextLength } from './ollamaManager.js'
+import { ensureContextWindow, getBaseUrl, getRuntimeContextLength } from './ollamaManager.js'
/**
* Prepare the Ollama daemon for an agent harness run.
@@ -40,6 +45,13 @@ import { ensureContextWindow, getRuntimeContextLength } from './ollamaManager.js
*/
export async function ensureOllamaAgentContext(provider, { env = process.env } = {}) {
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
+ // would reload an unrelated local daemon and still leave the provider's real
+ // daemon at its old window.
+ if (!isSameOllamaDaemon(ollamaBaseFromProvider(provider), getBaseUrl())) {
+ return { skipped: true, reason: 'remote-daemon' }
+ }
const contextLength = resolveOllamaContextLength(provider, env)
const providerName = provider.name || provider.id || null
diff --git a/server/services/ollamaAgentContext.test.js b/server/services/ollamaAgentContext.test.js
index 8ef1630b7f..2ff78421d3 100644
--- a/server/services/ollamaAgentContext.test.js
+++ b/server/services/ollamaAgentContext.test.js
@@ -2,7 +2,8 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'
vi.mock('./ollamaManager.js', () => ({
ensureContextWindow: vi.fn(),
- getRuntimeContextLength: vi.fn()
+ getRuntimeContextLength: vi.fn(),
+ getBaseUrl: vi.fn(() => 'http://localhost:11434')
}))
import { ensureContextWindow, getRuntimeContextLength } from './ollamaManager.js'
@@ -33,6 +34,16 @@ describe('ensureOllamaAgentContext', () => {
expect(await ensureOllamaAgentContext(null, { env: {} })).toEqual({ skipped: true })
})
+ // ollamaManager only ever manages the LOCAL daemon, so reloading it for a
+ // provider served by another host would disrupt unrelated local work and still
+ // leave that provider's real daemon at its old window.
+ it('skips a provider pointed at a remote Ollama host', async () => {
+ const remote = { ...claudeOllamaTui, numCtx: 131072, envVars: { ANTHROPIC_BASE_URL: 'http://192.0.2.10:11434' } }
+ expect(await ensureOllamaAgentContext(remote, { env: {} })).toEqual({ skipped: true, reason: 'remote-daemon' })
+ expect(ensureContextWindow).not.toHaveBeenCalled()
+ expect(getRuntimeContextLength).not.toHaveBeenCalled()
+ })
+
it('holds the daemon at the provider window', async () => {
ensureContextWindow.mockResolvedValue({ applied: true, reason: 'restarted' })
const result = await ensureOllamaAgentContext({ ...claudeOllamaTui, numCtx: 131072 }, { env: {} })
diff --git a/server/services/ollamaManager.js b/server/services/ollamaManager.js
index 718135f791..7177dc7df6 100644
--- a/server/services/ollamaManager.js
+++ b/server/services/ollamaManager.js
@@ -448,11 +448,11 @@ async function getRuntimeContextLength() {
* Hold the Ollama daemon at (at least) `contextLength` tokens, reloading it with
* that window when it is running at a smaller one.
*
- * Reloading a daemon is disruptive, so it happens only on positive evidence:
- * `/api/ps` reports a resident model below the target and this daemon has not
- * already been handed that window. An unmanaged daemon with nothing resident is
- * left alone — see {@link getRuntimeContextLength}, an unknown window is not a
- * small one — and the pre-spawn warning covers that case instead.
+ * Reloading a daemon is disruptive, so it happens at most once per daemon per
+ * window (the `appliedContextLength` latch) and never when a resident model is
+ * already at or above the target. It DOES happen when nothing is resident: an
+ * idle daemon has not committed to a window yet, and the one it will pick is
+ * the VRAM-based default `numCtx` exists to override.
*
* @param {number|null} contextLength
* @returns {Promise<{ applied: boolean, reason: string, contextLength: number|null, runtimeContextLength?: number|null, error?: string }>}
@@ -471,13 +471,18 @@ async function ensureContextWindow(contextLength) {
return { applied: false, reason: 'already-applied', contextLength: target, runtimeContextLength: appliedContextLength }
}
+ // `runtime == null` means nothing is resident, which is the NORMAL idle state
+ // between runs — not a reason to skip. The window Ollama will pick when the
+ // harness loads its model is its VRAM-based default, i.e. exactly the one the
+ // 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()
- if (runtime == null) return { applied: false, reason: 'unknown-window', contextLength: target, runtimeContextLength: null }
- if (runtime >= target) {
+ if (runtime != null && runtime >= target) {
return { applied: false, reason: 'already-large-enough', contextLength: target, runtimeContextLength: runtime }
}
- console.log(`🪟 Reloading Ollama at a ${target}-token context window (was ${runtime})`)
+ console.log(`🪟 Reloading Ollama at a ${target}-token context window (was ${runtime ?? 'unknown'})`)
// A daemon the user registered to launch at login must keep that registration:
// `stopServer` would route through `brew services stop` / `systemctl disable`,
diff --git a/server/services/ollamaManager.test.js b/server/services/ollamaManager.test.js
index 92d6d36eb0..0b812e6bb5 100644
--- a/server/services/ollamaManager.test.js
+++ b/server/services/ollamaManager.test.js
@@ -561,7 +561,7 @@ describe('ollamaManager.startPersistentService bootstrap recovery (homebrew)', (
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: '' })
+ if (cmd === 'brew' && a === 'services list') return cb(null, { stdout: 'ollama started testuser ~/Library/LaunchAgents/homebrew.mxcl.ollama.plist\n', stderr: '' })
return cb(new Error(`unexpected exec: ${cmd} ${a}`))
}
@@ -588,7 +588,7 @@ describe('ollamaManager.startPersistentService bootstrap recovery (homebrew)', (
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: '' })
+ if (cmd === 'brew' && a === 'services list') return cb(null, { stdout: 'ollama started testuser ~/Library/LaunchAgents/homebrew.mxcl.ollama.plist\n', stderr: '' })
return cb(new Error(`unexpected exec: ${cmd} ${a}`))
}
@@ -671,11 +671,6 @@ describe('ollamaManager context window', () => {
expect(await ensureContextWindow(65536)).toMatchObject({ applied: false, reason: 'already-large-enough' })
})
- it('leaves an unmanaged daemon with nothing resident alone — an unknown window is not evidence', async () => {
- stubPs([])
- const { ensureContextWindow } = await loadManager()
- expect(await ensureContextWindow(65536)).toMatchObject({ applied: false, reason: 'unknown-window' })
- })
})
describe('ollamaManager context window — launch-at-login daemons', () => {
@@ -701,7 +696,7 @@ describe('ollamaManager context window — launch-at-login daemons', () => {
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 antic plist\n', stderr: '' })
+ if (cmd === 'brew' && a === 'services list') return cb(null, { stdout: 'ollama started testuser plist\n', stderr: '' })
if (cmd === 'launchctl' && a.startsWith('setenv OLLAMA_CONTEXT_LENGTH')) 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}`))
@@ -716,6 +711,31 @@ describe('ollamaManager context window — launch-at-login daemons', () => {
expect(calls.some((c) => c.includes('services stop'))).toBe(false)
})
+ // 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
+ // exists to override.
+ it('applies the window to an idle daemon rather than waiting for a model to be resident', async () => {
+ restorePlatform = pinPlatform('darwin')
+ stubPs([])
+ 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(131072)
+
+ expect(result).toMatchObject({ applied: true, reason: 'service-restarted' })
+ expect(calls).toContain('launchctl setenv OLLAMA_CONTEXT_LENGTH 131072')
+ })
+
it('does not reload twice for the same window once it has been handed over', async () => {
restorePlatform = pinPlatform('darwin')
stubPs([{ name: 'a', context_length: 32768 }])
@@ -723,7 +743,7 @@ describe('ollamaManager context window — launch-at-login daemons', () => {
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 antic plist\n', 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}`))