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

budget Ollama against OLLAMA_CONTEXT_LENGTH, not just the provider's numCtx (#7472)

[._.]/ Adam Eivy8cf47711fe18
diff --git a/client/src/components/providers/ProviderCard.jsx b/client/src/components/providers/ProviderCard.jsx
index 84fec0e9f6..3276319f98 100644
--- a/client/src/components/providers/ProviderCard.jsx
+++ b/client/src/components/providers/ProviderCard.jsx
@@ -34,6 +34,7 @@ import {
providerTypeClass,
resolveModelContextWindow,
supportsModelRefresh,
+ withRuntimeContextWindow,
} from '../../utils/providers';
import { formatContextLength, formatDateTime } from '../../utils/formatters';
import { isHttpsUrl } from '../../utils/urlNormalize';
@@ -513,9 +514,15 @@ export default function ProviderCard({
// first, so the meter agrees with what the dispatch gate enforces —
// a card reading 128K beside an endpoint serving 32K promised a
// budget no run could ever spend. Down or silent → `null`, and the
- // ladder resolves exactly as it did before.
+ // ladder resolves exactly as it did before. The window PortOS
+ // LAUNCHED that daemon at rides the same payload — it is resolved
+ // server-side because its second rung is the ambient
+ // `OLLAMA_CONTEXT_LENGTH` the browser cannot read (#7472).
const { tokens, source } = resolveModelContextWindow(
- mergeObservedContextWindows(provider, daemonReadiness?.contextWindows),
+ withRuntimeContextWindow(
+ mergeObservedContextWindows(provider, daemonReadiness?.contextWindows),
+ daemonReadiness?.runtimeContextWindow,
+ ),
provider.defaultModel
);
const windowLabel = formatContextLength(tokens);
diff --git a/client/src/components/providers/ProviderForm.jsx b/client/src/components/providers/ProviderForm.jsx
index 5e16c0cce6..9bebf9d71d 100644
--- a/client/src/components/providers/ProviderForm.jsx
+++ b/client/src/components/providers/ProviderForm.jsx
@@ -3,7 +3,7 @@ import { useState } from 'react';
import { AlertTriangle, Braces, Cpu, Plug, SlidersHorizontal } from 'lucide-react';
import toast from '../ui/Toast';
import * as api from '../../services/api';
-import { filterHardwareCompatibleProviderModels, filterGenerationModels, isEmbeddingModel, isProviderHardwareCompatible, isProviderModelHardwareCompatible, mergeModelLists, configuredDefaultIn, localBackendForProvider, mergeObservedContextWindows, modelOptionLabel, isProcessProvider, isLocalEndpoint, effectiveModelContextWindow, isRunnerAllowedCommand, effortLevelsForProvider, isOllamaBackedProvider, gatewayForProvider, isClaudeCommandProvider, generationControlsFor, isCodexProvider } from '../../utils/providers';
+import { filterHardwareCompatibleProviderModels, filterGenerationModels, isEmbeddingModel, isProviderHardwareCompatible, isProviderModelHardwareCompatible, mergeModelLists, configuredDefaultIn, localBackendForProvider, mergeObservedContextWindows, withRuntimeContextWindow, modelOptionLabel, isProcessProvider, isLocalEndpoint, effectiveModelContextWindow, isRunnerAllowedCommand, effortLevelsForProvider, isOllamaBackedProvider, gatewayForProvider, isClaudeCommandProvider, generationControlsFor, isCodexProvider } from '../../utils/providers';
import Banner from '../ui/Banner';
import {
formatDurationMs,
@@ -120,7 +120,11 @@ export default function ProviderForm({ provider, daemonReadiness = null, onClose
// never saved — `modelContextWindows` is not a form field, so an observation
// can reach "Budgeter uses …" and the model-option labels without any risk of
// a Save writing a running process's window into the record (#7441).
- const capabilityProvider = mergeObservedContextWindows({
+ // The daemon's LAUNCH ceiling folds in the same way and for the same reason
+ // (#7472): it is resolved server-side from the ambient `OLLAMA_CONTEXT_LENGTH`
+ // the browser cannot read, and a typed-but-unsaved `numCtx` still outranks it
+ // — the clamp reads the record's own rung first.
+ const capabilityProvider = withRuntimeContextWindow(mergeObservedContextWindows({
...provider,
...formData,
id: provider?.id,
@@ -129,7 +133,7 @@ export default function ProviderForm({ provider, daemonReadiness = null, onClose
...provider?.modelHardwareCompatibility,
...liveHardwareFor(formData),
},
- }, daemonReadiness?.contextWindows);
+ }, daemonReadiness?.contextWindows), daemonReadiness?.runtimeContextWindow);
const availableModels = filterHardwareCompatibleProviderModels(
filterGenerationModels(mergedModels),
capabilityProvider,
diff --git a/client/src/utils/README.md b/client/src/utils/README.md
index c12b332495..2db0298032 100644
--- a/client/src/utils/README.md
+++ b/client/src/utils/README.md
@@ -61,7 +61,7 @@ is where each shared table is re-exported from its `server/lib` leaf.
| `providerModels` | Which MODEL and EFFORT a run resolves to, and what a picker may list. The configured-default sentinels (`CODEX_CONFIGURED_DEFAULT` …, `isConfiguredDefaultModel`, `configuredDefaultIn` — so a picker can render an option matching a sentinel-valued tier instead of a blank select) and `filterSelectableModels`; the per-CLI effort ladders, `effortLevelsForProvider`, `resolveCliEffort` (what a stored effort actually runs as, so the picker can name a clamped level), `effortSurvivingModel` and `seedModelEffort`; the Antigravity base-model ↔ effort-suffix split (`splitAntigravityModel`, `antigravityBaseModels`, `antigravityModelEffortLevels`, `withStaleAntigravityPin`); the account-aware option list (`providerModelList`, `resolveProviderModelOptions`, `effortAwareModelOptions`, `MODEL_SOURCE` — the one place a Codex-subscription account catalog enters a picker); `effectiveModelFor`; `mergeModelLists` / `mergeProviderUpdate`; and `generationControlsFor` (which temperature / top-p / thinking controls a provider forwards at all). The sentinels, effort ladders and the Antigravity split are re-exported from the pure leaf `server/lib/providerModels.js`; `effortLevelsForProvider` / `resolveCliEffort` delegate to the server's and add the ladder a sanitized provider inventory publishes, clamped through the server's `clampEffortToLadder`. The generation-control tables still mirror `server/lib/opencodeConfig.js`. |
| `providerSelection` | Which providers and models a picker may OFFER on this install: `isProviderHardwareCompatible` / `isProviderModelHardwareCompatible` / `filterHardwareCompatibleProviderModels` (server-annotated, fail-open), `selectableProviders` (the single rule `ProviderModelSelector` renders from), `filterRunnableProviders` (agent jobs need a CLI/TUI harness), the fail-closed tool-free local policy (`TOOL_FREE_LOCAL_PROVIDER_IDS`, `TOOL_FREE_LOCAL_TEXT_CAPABILITIES`, `isToolFreeLocalProvider`, `isToolFreeLocalModel`, `toolFreeLocalSelectionPolicy`) used by security-sensitive pickers, and the pr-reviewer postures (`PUBLIC_REVIEW_NO_TOOL_POSTURE` / `PUBLIC_REVIEW_ACTIONS_POSTURE`, `supportsPublicReviewPosture`, `enforcesPublicReviewPosture`, `publicReviewSelectionPolicy` — mirror of `server/lib/agentExecutionProfiles.js`: a pipeline stage names a POSTURE, the server publishes each provider's `publicReviewPostures` and `publicReviewEnforcedPostures` on `GET /api/providers`, and the picker offers exactly the providers this install can run the stage on, so no vendor is named on either side). Also the caller EXECUTION-MODE picker rule (`callerModeList`, `providerModeSelectionPolicy`) over `server/lib/callerModePolicy.js` — the server enforces the policy on the pin, on `activeProvider` inheritance and on every fallback candidate; this only lets a picker SHOW the rule, keeping an ineligible saved value visible-but-disabled instead of hidden or silently replaced — read off `CALLER_MODE_POLICIES` in that pure leaf, so it cannot drift). |
| `localModelHeuristics` | What an untyped LOCAL model can do, judged from its id: `isEmbeddingModel` / `isVisionModel` / `isToolUseModel` (re-exported from the pure leaf `server/lib/localModelHeuristics.js` — one regex per family; a model card's explicit capability metadata outranks the id regex), `isVisionCapableCliProvider`, `filterGenerationModels` (sentinels and embedding-only models dropped), `visionLocalModelFilter` and `localToolUseHint` / `withToolUseOptionLabel` (unioned with the server's authoritative per-provider capability maps from `useVisionModelIds` / `useToolUseModelIds`; tool-use is an annotation plus warning, never a filter), and `modelCapabilityInfo` (capability badges for a selected model without over-sharing a local runtime's answer with another provider). |
-| `providerContextWindows` | How large a context window a provider/model gets for planning and where the number came from: the vendor constants and the `KNOWN_MODEL_CONTEXT_WINDOWS` ladder (`knownModelContextWindow`, `knownProviderContextWindow`), `catalogModelContextWindow` (the window the provider's own `/models` catalog reported), `resolveModelContextWindow` → `{ tokens, source }` with `CONTEXT_WINDOW_SOURCE` (`override` / `reported` / `assumed` — the state a card has to label rather than print as fact), `effectiveModelContextWindow`, and `modelOptionLabel` ("id (32K ctx)"). The constants and the known-model / known-provider / catalog rungs are re-exported from the pure leaf `server/lib/providerContextWindows.js`, the same rungs the server's `effectiveContextWindow` budgets with — including `mergeObservedContextWindows`, which folds a local daemon's live window (off the readiness payload) onto the catalog rung so the card shows what the dispatch gate enforces, and holds every resolved window down to an Ollama daemon's launch `num_ctx` through `clampToRuntimeContextWindow` (applied internally, from `server/lib/aiToolkit/internal/ollamaBacked.js` — the same module the server's budgeter and pre-dispatch gate use), so the meter can't promise a budget a run would be refused for (#7466). |
+| `providerContextWindows` | How large a context window a provider/model gets for planning and where the number came from: the vendor constants and the `KNOWN_MODEL_CONTEXT_WINDOWS` ladder (`knownModelContextWindow`, `knownProviderContextWindow`), `catalogModelContextWindow` (the window the provider's own `/models` catalog reported), `resolveModelContextWindow` → `{ tokens, source }` with `CONTEXT_WINDOW_SOURCE` (`override` / `reported` / `assumed` — the state a card has to label rather than print as fact), `effectiveModelContextWindow`, and `modelOptionLabel` ("id (32K ctx)"). The constants and the known-model / known-provider / catalog rungs are re-exported from the pure leaf `server/lib/providerContextWindows.js`, the same rungs the server's `effectiveContextWindow` budgets with — including `mergeObservedContextWindows`, which folds a local daemon's live window (off the readiness payload) onto the catalog rung so the card shows what the dispatch gate enforces, and holds every resolved window down to an Ollama daemon's launch `num_ctx` through `clampToRuntimeContextWindow` (applied internally, from `server/lib/aiToolkit/internal/ollamaBacked.js` — the same module the server's budgeter and pre-dispatch gate use), so the meter can't promise a budget a run would be refused for (#7466). `withRuntimeContextWindow(provider, ceiling)` stamps that ceiling's second rung — the ambient `OLLAMA_CONTEXT_LENGTH` the server launched the daemon with, which the browser cannot read and so takes off the readiness payload as `runtimeContextWindow` (#7472). |
| `providerReadiness` | Is a provider READY to run on this install, and why not. `credentialSource` (stored / inherited / env / subscription / none) and `providerCardState(provider, { runtime, status, keySetFor, envVarSet, codexAccount })` + `PROVIDER_CARD_STATE` — ready, benched, blocked on a missing prerequisite (CLI not installed / API key absent / empty credential env var / signed-out ChatGPT account), unknown, or simply switched off. Reads the SERVER's `missingPrerequisites` (published per provider on `GET /api/providers` from `server/lib/providerPrerequisites.js`, the same computation `getFallbackProvider` routes on) and adds only what the browser can see; unknown lookup values mean "not probed", never "missing". Distinct from `ProviderReadiness` / `GET /api/providers/readiness`, which probes the local daemon behind a provider. Also `isRunnerAllowedCommand(command, allowedCommands)` — would the CoS Agent Runner accept this command? Mirrors only the normalization in `server/cos-runner/allowedCommands.js` (the list arrives as `runnerAllowedCommands` on `GET /api/providers`); returns `null` for "list not fetched" so a failed fetch never renders a warning; pinned by `server/cos-runner/allowedCommands.parity.test.js`. `resolvesOutsidePortosPath` / `providerRuntimeKey` (the key a CLI runtime is published under by `GET /api/providers/runtimes`), `supportsModelRefresh` (`canRefreshModels === true`, the server's own answer) and `codexRoutingAdvisory` (the non-blocking "your `~/.codex/config.toml` re-points Codex" notice — server-only and machine-local, rendered in the UI and nowhere else). |
| `providerAssignments` | Which provider/model a RECORD resolves to, and the option helpers the assignment editors share: `resolveEffectiveProvider` (its pin, else the active provider, plus whether it fell back so a "Default" option can name what it resolves to), `resolveSeriesRunLlm` (mirror of `server/lib/seriesLlmOverride.js`: per-run override → `series.llm` → active provider), `getProviderTimeout`, `providerDisplayName` and `providerModelLabel` (the one "Provider / model" phrasing), and `assignmentProviderOptions` / `assignmentModelOptions` / `assignmentDefaultModel` / `assignmentToolUseState` over the `getAiAssignments` payload shape — shared by the global AI Assignments table and every per-record override drawer so none of them derives the rule differently. |
diff --git a/client/src/utils/providerContextWindows.js b/client/src/utils/providerContextWindows.js
index afd360c369..558e1f7f3f 100644
--- a/client/src/utils/providerContextWindows.js
+++ b/client/src/utils/providerContextWindows.js
@@ -14,6 +14,10 @@
*
* The Ollama `num_ctx` ceiling is shared with the SERVER's dispatch gate too,
* so the meter cannot promise a window a run would then be refused for (#7466).
+ * Its second rung — the ambient `OLLAMA_CONTEXT_LENGTH` the server launched the
+ * daemon with — is server env the browser cannot read, so it arrives as
+ * `runtimeContextWindow` on the readiness payload and is folded in with
+ * `withRuntimeContextWindow` at the two call sites that budget (#7472).
*
* Re-exported by `./providers.js` for existing `utils/providers` imports.
*/
@@ -33,6 +37,15 @@ import {
// already takes `isOllamaBackedProvider` from there.
import { clampToRuntimeContextWindow } from '../../../server/lib/aiToolkit/internal/ollamaBacked.js';
+export {
+ // Stamps the window PortOS holds a local Ollama daemon at onto a provider
+ // projection, so the clamp above sees the rung the browser cannot resolve for
+ // itself: the ambient `OLLAMA_CONTEXT_LENGTH` this install launched the daemon
+ // with. The number arrives as `runtimeContextWindow` on the readiness payload,
+ // beside the served windows `mergeObservedContextWindows` folds in (#7472).
+ withRuntimeContextWindow,
+} from '../../../server/lib/aiToolkit/internal/ollamaBacked.js';
+
export {
DEFAULT_LARGE_CONTEXT_WINDOW,
CODEX_CONTEXT_WINDOW,
diff --git a/server/lib/README.md b/server/lib/README.md
index fb1d4d5c0c..fdd8506b7a 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -479,7 +479,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
| `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. |
| `specDecodePresets.js` | Curated llama-server speculative-decoding presets (target + drafter GGUF paths, `--spec-type`, and the Hugging Face repo/quant each file comes from) plus `findSpecDecodePreset` / `specDecodeSource` / `hfSearchUrl`. Also owns the `--spec-type` vocabulary: `SPEC_TYPE_SUGGESTIONS` (published to the launcher card), `parseSpecTypes` (the flag is a comma-separated list) and `isDraftSpecType` (the `draft-` prefix is what needs a drafter GGUF — every `ngram-*` type runs without one). Server-owned so the launcher card can offer a Download button per file. Pure. |
| `llamaCppInstall.js` | Where a llama.cpp install comes from on this host, for `services/llamaServerManager.js`. `llamaCppInstallPlan(platform)` → the frozen descriptor for that platform's package manager — Homebrew on macOS/Linux (`brew install llama.cpp`), winget on Windows (`winget install ggml.llamacpp`) — carrying `manager`, `managerLabel`, `packageId`, `installCommand`, the install/upgrade (and, for winget, list/upgrade-check) argv, and the three refusal strings a caller would otherwise hardcode: `missingManagerError`, `notInstalledError`, `pathRepairHint`. The LLMs page renders `installCommand` out of the llama-server status payload, which is what stopped a Windows install prompt from telling the user to run Homebrew. Also the winget-side readers Homebrew needs no equivalent for: `parseWingetPackageFields(stdout, id)` (winget has NO machine-readable output mode and LOCALIZED table headers, so fields are read positionally from the tokens after the id token — `Version [Available] [Source]`; `null` = not installed), `wingetLinkDirs(env)` (the portable-shim directories winget adds to the USER PATH, which an already-running server has not inherited) and `isWingetManagedPath` (counterpart of the manager's `isHomebrewLlamaServer`: a source build earlier on PATH must not be offered a `winget upgrade`). Every WinGet path is reasoned about with `path.win32` regardless of host, so both branches are coverable from a macOS/Linux checkout. Pure. |
-| `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`. |
+| `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, with `managedOllamaBaseUrl(env)` supplying the managed side (`OLLAMA_URL` → `OLLAMA_HOST` → the stock local daemon); `managedOllamaContextLength(provider, env)` is `resolveOllamaContextLength` gated on that comparison, and `withOllamaRuntimeContextWindow(provider, env)` stamps it onto an in-memory provider projection as `runtimeContextWindow` — how the env rung reaches the vendored toolkit’s `clampToRuntimeContextWindow`, which may not import out here (#7472); `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, { measured })` ranks installed models for editorial review/editing, dropping any a fresh measurement proved cannot run here. Pure — `client/src/utils/localModelHeuristics.js` re-exports `isEmbeddingModel`/`isVisionModel`/`isToolUseModel` from here. |
| `localModelAssessment.js` | Scoring for MEASURED local-model assessments (recorded by `services/localModelAssessments.js`): `classifyFitVerdict` (`fits`/`does-not-fit`/`incompatible`/`unknown`), `summarizePerformance` (mean/peak chars-per-second AND tokens-per-second, prefill rate, TTFT, max working context, cross-context degradation), `scoreAssessment` + `scoreForIntent` + `rankByIntent` for the balanced/smartest/fastest/lightweight pickers, `explainAssessment`, `compareEnvironments`/`describeStaleness` (is a stored reading still valid for THIS machine?), `buildThroughputReport` (every measurement as one tokens/s table, fastest first, per-context readings intact), `selectSweepTargets`/`summarizeSweepScopes`/`SWEEP_SCOPES` (which measurements a "measure everything" run covers, and how many), and `measuredFitVerdict`/`reconcileFit` (fold a measurement into the catalog's size-estimate fit badge, keeping the disagreement). Pure. `null` strictly means NOT MEASURED — never 0, never "failed". |
| `localModelTuning.js` | Launch/runtime tuning knobs for the measurable local runtimes — ONLY knobs PortOS can actually apply. A knob is defined by its transport, and `applies` + the user-facing `note` are DERIVED from it: `config` (llama.cpp's `-b`/`-ub`/`-t`/`--parallel`/`--flash-attn`/`--cache-type-k\|v`/`--spec-draft-n-max`, via `launchConfig`), `env` (Ollama's `OLLAMA_CONTEXT_LENGTH`/`_FLASH_ATTENTION`/`_KV_CACHE_TYPE`/`_NUM_PARALLEL`, via `launchEnv`), `cli` (a flag on the launch line of a daemon PortOS re-runs — LM Studio's `lms load --context-length`/`--gpu`/`--parallel`, and MTPLX's `mtplx serve --context-window`/`--depth`/`--generation-mode`/`--kv-quant`/`--batching-preset`/`--profile` — via `launchArgs`), or `wire` (a request-body field, via `requestBody` — currently no members). vLLM declares none: PortOS does not start it, so there is no launch line to put a flag on. Read the MTPLX verification note in the module before adding an `mtplx serve` flag — it exits before it binds on one it does not recognize. Also `normalizeTuning` (coerce + clamp + drop unknown keys), `tuningSignature` (stable identity — `''` for backend defaults, so pre-tuning store keys keep resolving), `describeTuning`, `launchTuning`, and `compareTunings` (which tuning won per model using exact tokens/s when all variants have tokenizer counts and chars/s otherwise, labelled from each record's persisted `tuningLabel`, with a `deltaPercent` against the winner), and `tuningGridFor` (the candidate grid a tuning sweep runs — backend defaults plus one variant per knob declaring a `sweep` value, capped by `maxVariants`; `sweepWith` carries a knob's documented prerequisite). Pure. || `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`. |
diff --git a/server/lib/aiToolkit/AGENTS.md b/server/lib/aiToolkit/AGENTS.md
index b87e542ec5..b9ce32f224 100644
--- a/server/lib/aiToolkit/AGENTS.md
+++ b/server/lib/aiToolkit/AGENTS.md
@@ -5,6 +5,7 @@ The AI provider/runner/prompt toolkit is vendored in-tree here. (It was previous
**Key points:**
- `index.js` exports `createAIToolkit`, `createProviderStatusService`, the four Router factories (providers / runs / prompts / providerStatus), and the context-fit pair `knownContextWindow` / `contextWindowRejection` — the host applies the same rule to the EXPLICITLY requested provider, which `getFallbackProvider` never sees. Both answer `null` for an unknown window, which every caller must keep reading as "no constraint"; nothing infers a window from a model id.
- **The Ollama `num_ctx` ceiling is declared ONCE, in `internal/ollamaBacked.js`** (`clampToRuntimeContextWindow`), beside the predicate that gates it. `knownContextWindow` applies it through that helper and must never restate the `Math.min` inline — the host's prompt budgeter (`server/services/stageRunner.js#effectiveContextWindow`) and the browser's provider-card meter call the same function, and when the rule was stated twice they drifted (#7466). It is an upper BOUND over every planning rung, a user's explicit `contextWindow` included, and the answer outright when nothing else declared one. Host callers import the `internal/` leaf directly: the public barrel reaches `fs` and `child_process`, and `stageRunner.js` sits inside the server suite's import budget.
+ - **A rung of that ceiling this directory cannot resolve arrives as DATA, never as an import out.** PortOS also sets the daemon-wide window through the ambient `OLLAMA_CONTEXT_LENGTH` (`server/lib/ollamaContext.js#resolveOllamaContextLength`), which the toolkit may not reach and the browser cannot read at all — so the host resolves it and stamps it onto an in-memory provider projection with `withRuntimeContextWindow`, declared in the same file as the clamp that reads it. `runtimeContextWindow` ranks BELOW `provider.numCtx`, exactly as `resolveOllamaContextLength` ranks the two, and is never persisted to `providers.json` (it describes the process running right now). Adding another host-resolved rung follows the same shape: stamp a field beside the reader, do not import out. Precedent: #7472.
- Provider configuration (models, tiers, fallbacks) lives in `providers.js`
- `loadProviders()` auto-migrates legacy codex configs to the `codex-configured-default` sentinel; `server/index.js` warms it at startup so the rewrite happens before any request
- PortOS extends toolkit routes in `server/routes/providers.js` for vision testing and provider status (status routes live in PortOS, not the toolkit, because they call PortOS-side socket helpers)
diff --git a/server/lib/aiToolkit/internal/ollamaBacked.js b/server/lib/aiToolkit/internal/ollamaBacked.js
index 0982ad89b9..4afd240078 100644
--- a/server/lib/aiToolkit/internal/ollamaBacked.js
+++ b/server/lib/aiToolkit/internal/ollamaBacked.js
@@ -58,31 +58,91 @@ export function ollamaBaseFromProvider(provider) {
* declared window and then refused before it dispatched. The gate, the budgeter
* and the browser's provider-card meter now all call this.
*
- * Two deliberate limits, both conservative (they can only under-plan):
- * - Only Ollama honors the runner's top-level `num_ctx`; every other
- * OpenAI-compatible endpoint ignores it, so there the field describes a
- * window nothing enforces and must never refuse a request. Hence the
- * `isOllamaBackedProvider` gate — and why this lives beside that predicate
- * rather than in its own module, which would add a module to the import
- * closure of every suite reaching either end of one rule.
- * - It reads `provider.numCtx` only. The ambient `OLLAMA_CONTEXT_LENGTH` rung
- * that `server/lib/ollamaContext.js#resolveOllamaContextLength` adds is not
- * visible here (the toolkit may not import out, and the browser cannot see
- * server env); and for an Ollama-backed CLI/TUI harness `numCtx` is the
- * window the daemon is reloaded UP TO, so a daemon already running wider
- * keeps its wider window.
+ * The ceiling itself walks TWO rungs, in the same order
+ * `server/lib/ollamaContext.js#resolveOllamaContextLength` walks to decide what
+ * to launch the daemon with — so the budgeter and the launcher answer the same
+ * question the same way:
+ *
+ * 1. `provider.numCtx` — the window this provider's own record asks for.
+ * 2. `provider.runtimeContextWindow` — the window the daemon is ACTUALLY
+ * running at, stamped by the host (see {@link withRuntimeContextWindow}).
+ * This is the ambient `OLLAMA_CONTEXT_LENGTH` rung, which this directory
+ * cannot resolve for itself, and it ranks BELOW `numCtx` for the same
+ * reason `resolveOllamaContextLength` does: explicit provider config wins,
+ * and an unsaved `numCtx` being edited in the provider form must not be
+ * overruled by the window the daemon happens to be serving right now.
+ *
+ * Each rung is validated independently: a zero / negative / non-numeric
+ * `numCtx` falls THROUGH to the runtime rung rather than collapsing the whole
+ * ceiling to "none", so a malformed record cannot silently widen the budget.
+ *
+ * One deliberate limit, conservative (it can only under-plan): only Ollama
+ * honors the runner's top-level `num_ctx`; every other OpenAI-compatible
+ * endpoint ignores it, so there the field describes a window nothing enforces
+ * and must never refuse a request. Hence the `isOllamaBackedProvider` gate —
+ * and why this lives beside that predicate rather than in its own module, which
+ * would add a module to the import closure of every suite reaching either end
+ * of one rule.
+ *
+ * For an Ollama-backed CLI/TUI harness `numCtx` is the window the daemon is
+ * reloaded UP TO, so a daemon already running wider keeps its wider window.
*
* @param {object|null|undefined} provider
* @param {number|null|undefined} planned — whatever the caller's ladder resolved
* @returns {number|null}
*/
export function clampToRuntimeContextWindow(provider, planned) {
- const positive = (value) => {
- const n = Number(value);
- return Number.isFinite(n) && n > 0 ? Math.floor(n) : null;
- };
- const ceiling = isOllamaBackedProvider(provider) ? positive(provider?.numCtx) : null;
- const usable = positive(planned);
+ const ceiling = isOllamaBackedProvider(provider)
+ ? (positiveTokens(provider?.numCtx) ?? positiveTokens(provider?.runtimeContextWindow))
+ : null;
+ const usable = positiveTokens(planned);
if (!ceiling) return usable;
return usable ? Math.min(usable, ceiling) : ceiling;
}
+
+/**
+ * `provider` carrying the window its Ollama daemon is ACTUALLY running at —
+ * the write side of the `runtimeContextWindow` rung
+ * {@link clampToRuntimeContextWindow} reads.
+ *
+ * Declared here beside its reader, for the same reason the ceiling itself is
+ * declared once: a field whose meaning is stated in two modules is a field the
+ * two will eventually disagree about (#7466).
+ *
+ * It exists because the ceiling has a rung this directory cannot resolve. PortOS
+ * also sets the daemon-wide window through the ambient `OLLAMA_CONTEXT_LENGTH`
+ * env var (`server/lib/ollamaContext.js#resolveOllamaContextLength`), and on an
+ * install that uses that rung with `numCtx` unset, the budgeter planned at the
+ * model's catalog window, the gate admitted it, and the call died at dispatch
+ * with `exceed_context_size_error` (#7472). The toolkit may not import out to
+ * where that lives, and the browser cannot read server env at all — so the HOST
+ * resolves it and hands it in as data on the provider projection, rather than
+ * the clamp reaching out for it. Server side that is
+ * `ollamaContext.js#withOllamaRuntimeContextWindow`; the browser takes the same
+ * number off the provider-readiness payload.
+ *
+ * In-memory ONLY. `runtimeContextWindow` describes the process running right
+ * now — relaunch the daemon at another window and a stored copy would be a lie
+ * — so it must never reach `providers.json`, exactly like the observed windows
+ * `mergeObservedContextWindows` folds onto the same projection.
+ *
+ * Returns the SAME object when there is nothing to add, so a host with no
+ * ambient window allocates nothing and compares identically. `null` in must
+ * stay `null` out: "PortOS did not set a window" is not a window.
+ *
+ * @param {object|null|undefined} provider
+ * @param {number|null|undefined} ceiling — the window the daemon is held at
+ * @returns {object|null|undefined}
+ */
+export function withRuntimeContextWindow(provider, ceiling) {
+ const runtime = positiveTokens(ceiling);
+ if (!provider || !runtime) return provider;
+ if (positiveTokens(provider.runtimeContextWindow) === runtime) return provider;
+ return { ...provider, runtimeContextWindow: runtime };
+}
+
+/** A context-window field as a positive integer token count, or `null`. */
+function positiveTokens(value) {
+ const n = Number(value);
+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : null;
+}
diff --git a/server/lib/ollamaContext.js b/server/lib/ollamaContext.js
index 5fed740663..5df05c60e7 100644
--- a/server/lib/ollamaContext.js
+++ b/server/lib/ollamaContext.js
@@ -20,6 +20,12 @@
* `server/services/ollamaAgentContext.js` owns the pre-spawn enforcement.
*/
+// The `internal/` leaf on purpose: the toolkit's public barrel reaches `fs` and
+// `child_process`, and this module sits in the closure of the prompt budgeter
+// and the dispatch gate, both inside the server suite's import budget. The leaf
+// imports nothing.
+import { isOllamaBackedProvider, ollamaBaseFromProvider, withRuntimeContextWindow } from './aiToolkit/internal/ollamaBacked.js'
+
/**
* Smallest runtime window an Ollama-backed *agent harness* can realistically
* finish a task in. Not a hard requirement — it is the threshold below which
@@ -57,6 +63,67 @@ export function resolveOllamaContextLength(provider, env = process.env) {
return positiveInt(provider?.numCtx) ?? positiveInt(env?.[OLLAMA_CONTEXT_ENV_VAR])
}
+/**
+ * The base URL of the Ollama daemon THIS install manages — `OLLAMA_URL`, then
+ * the `OLLAMA_HOST` (`host:port`) convention, then the stock local daemon.
+ *
+ * Declared here rather than restated at each reader because it is half of the
+ * `isSameOllamaDaemon` comparison below, and a second spelling of it is a second
+ * answer to "is this provider's daemon the one PortOS launched?".
+ * `services/ollamaManager.js` normalizes the result into its own config.
+ *
+ * @param {Record<string, string|undefined>} [env]
+ * @returns {string}
+ */
+export function managedOllamaBaseUrl(env = process.env) {
+ const raw = String(env?.OLLAMA_URL || env?.OLLAMA_HOST || '').trim()
+ return raw || 'http://localhost:11434'
+}
+
+/**
+ * The window PortOS holds `provider`'s daemon at, or `null` when it holds it at
+ * none (Ollama's VRAM auto-pick stands).
+ *
+ * {@link resolveOllamaContextLength} gated on the daemon being the one this
+ * install manages. The gate matters because the ambient `OLLAMA_CONTEXT_LENGTH`
+ * only ever reaches the daemon PortOS launches (`withOllamaContextEnv`): applied
+ * to a provider pointed at a REMOTE Ollama it would describe a window nobody
+ * set, and budget that remote daemon down to a local machine's VRAM headroom.
+ * The same gate `services/ollamaAgentContext.js` puts on the reload.
+ *
+ * `numCtx` is deliberately NOT gated with it — an `api`-type provider's
+ * `numCtx` rides the request as `num_ctx` and binds a remote daemon just as
+ * well, which is why the clamp reads that rung straight off the record.
+ *
+ * @param {object|null|undefined} provider
+ * @param {Record<string, string|undefined>} [env]
+ * @returns {number|null}
+ */
+export function managedOllamaContextLength(provider, env = process.env) {
+ if (!isOllamaBackedProvider(provider)) return null
+ if (!isSameOllamaDaemon(ollamaBaseFromProvider(provider), managedOllamaBaseUrl(env))) return null
+ return resolveOllamaContextLength(provider, env)
+}
+
+/**
+ * `provider` with that window stamped on for a caller about to ask a context
+ * question about it — the ONE operation the prompt budgeter
+ * (`services/stageRunner.js#effectiveContextWindow`) and the pre-dispatch gate
+ * (`services/promptRunner.js#assertRequestFitsContext`) both want.
+ *
+ * This is how the env rung reaches the vendored toolkit, which may not import
+ * out to this module: as data on an in-memory projection, never persisted. See
+ * `aiToolkit/internal/ollamaBacked.js#withRuntimeContextWindow` for the field's
+ * contract and #7472 for the failure it closes.
+ *
+ * @param {object|null|undefined} provider
+ * @param {Record<string, string|undefined>} [env]
+ * @returns {object|null|undefined}
+ */
+export function withOllamaRuntimeContextWindow(provider, env = process.env) {
+ return withRuntimeContextWindow(provider, managedOllamaContextLength(provider, env))
+}
+
/** `host:port` for comparing two Ollama base URLs, or null when unparseable. */
function hostOf(baseUrl) {
const raw = String(baseUrl || '').trim()
diff --git a/server/services/ollamaManager.js b/server/services/ollamaManager.js
index 71e5d82666..07a4ad99f8 100644
--- a/server/services/ollamaManager.js
+++ b/server/services/ollamaManager.js
@@ -34,7 +34,7 @@ import { buildHfAuthHeaders, buildHfResolveUrl, HF_API } from '../lib/huggingfac
import { isEmbeddingModel } from '../lib/localModelHeuristics.js'
import { commandExists } from '../lib/commandExists.js'
import {
- OLLAMA_AGENT_MIN_CONTEXT, OLLAMA_CONTEXT_ENV_VAR, resolveOllamaContextLength, withOllamaContextEnv
+ OLLAMA_AGENT_MIN_CONTEXT, OLLAMA_CONTEXT_ENV_VAR, managedOllamaBaseUrl, resolveOllamaContextLength, withOllamaContextEnv
} from '../lib/ollamaContext.js'
import { compareSemver } from '../lib/versionUtils.js'
import { isSafeHfRepoRelativePath } from '../lib/hfCache.js'
@@ -76,7 +76,7 @@ const HF_IMPORT_METADATA_TIMEOUT_MS = 180_000
const DEFAULT_CONFIG = {
// Ollama uses OLLAMA_HOST (host:port, no scheme) by convention; also accept
// an explicit OLLAMA_URL. Normalize to a scheme + no trailing slash + no /v1.
- baseUrl: normalizeBaseUrl(process.env.OLLAMA_URL || process.env.OLLAMA_HOST || 'http://localhost:11434'),
+ baseUrl: normalizeBaseUrl(managedOllamaBaseUrl()),
timeout: DEFAULT_REQUEST_TIMEOUT_MS
}
diff --git a/server/services/promptRunner.js b/server/services/promptRunner.js
index 29e0841ab3..d4a103a7d7 100644
--- a/server/services/promptRunner.js
+++ b/server/services/promptRunner.js
@@ -40,6 +40,7 @@ import { analyzeError, ERROR_CATEGORIES, isRunCanceledError } from '../lib/aiToo
import { isSchemaTypeCategory, resolveProviderBench } from '../lib/providerCooldown.js';
import { isGenerationModel, isVisionCapableCliProvider } from '../lib/localModelHeuristics.js';
import { contextWindowRejection } from '../lib/aiToolkit/providerStatus.js';
+import { withOllamaRuntimeContextWindow } from '../lib/ollamaContext.js';
import { getAIToolkitInstance } from '../lib/aiToolkitState.js';
import { createSingleFlight } from '../lib/singleFlight.js';
import { extractJson } from '../lib/jsonExtract.js';
@@ -1318,7 +1319,11 @@ async function assertRequestFitsContext(provider, model, requestCapabilities, {
const required = Number(requestCapabilities?.requiredContextTokens);
if (!Number.isFinite(required) || required <= 0) return;
- const observed = await withObservedContextWindowsLazy(provider);
+ // Two in-memory projections, both describing what the daemon is doing RIGHT
+ // NOW rather than what the record remembers: the windows it is serving, and
+ // the ceiling PortOS launched it at — including the ambient
+ // `OLLAMA_CONTEXT_LENGTH` rung the toolkit cannot reach for itself (#7472).
+ const observed = withOllamaRuntimeContextWindow(await withObservedContextWindowsLazy(provider));
// `reason` already names both numbers, which is what the operator needs to
// decide between a smaller prompt and a wider provider — so it IS the
// message rather than being re-worded beside it.
diff --git a/server/services/providerReadiness.js b/server/services/providerReadiness.js
index f6a84ed334..2aac75359d 100644
--- a/server/services/providerReadiness.js
+++ b/server/services/providerReadiness.js
@@ -41,6 +41,7 @@ import { expandPageToken, getNavPageForPath } from '../lib/navManifest.js';
import { bareLocalModelId } from '../lib/providerModels.js';
import { probeOpenAiModelsCached, resetOpenAiModelsProbeCache } from '../lib/openAiModelsProbeCache.js';
import { aliasServedContextWindows } from '../lib/providerContextWindows.js';
+import { managedOllamaContextLength } from '../lib/ollamaContext.js';
import { findCommandOnPath } from '../lib/processEnv.js';
import { actionCovers, describeRuntimeSetup, readRuntimeWeights, weightsBlockStart } from './localRuntimeSetup.js';
import { isAppInstalled as isLmStudioAppInstalled } from './lmStudioManager.js';
@@ -444,6 +445,14 @@ export async function getProviderReadiness(provider, deps = {}) {
// (#7441) — this is the channel the provider card budgets its meter from, so
// the card shows the window the dispatch gate would actually enforce.
contextWindows: aliasServedContextWindows(provider, runtime, result.contextWindows),
+ // The window PortOS holds this daemon at, resolved from BOTH rungs — the
+ // provider's `numCtx` and the ambient `OLLAMA_CONTEXT_LENGTH` this install
+ // launches Ollama with. It rides the same payload for the same reason the
+ // served windows do: it is runtime state, not configuration, and the card's
+ // meter must show the ceiling the dispatch gate enforces. The browser cannot
+ // read server env, so without this the card stayed on the `numCtx`-only rung
+ // and promised a window a run would then be refused for (#7472).
+ runtimeContextWindow: managedOllamaContextLength(provider),
// What a one-click "set this up for me" button can do about the unmet
// checks, or `null` when nothing here is auto-fixable (see
// `localRuntimeSetup.js`). Carried on the readiness payload so the card
diff --git a/server/services/stageRunner.js b/server/services/stageRunner.js
index 0955ea1cfd..7695075757 100644
--- a/server/services/stageRunner.js
+++ b/server/services/stageRunner.js
@@ -34,6 +34,9 @@ import {
// dependency-free `internal/` leaf, not the toolkit barrel: that reaches `fs`
// and `child_process`, and this module is inside the server suite's import budget.
import { clampToRuntimeContextWindow } from '../lib/aiToolkit/internal/ollamaBacked.js';
+// …and the rung of that ceiling the toolkit cannot resolve for itself: the
+// ambient `OLLAMA_CONTEXT_LENGTH` PortOS launches the daemon with (#7472).
+import { withOllamaRuntimeContextWindow } from '../lib/ollamaContext.js';
import { createRun, patchRunMetadata } from './runner.js';
import { resolveProviderModelTier, MIN_TIMEOUT as STAGE_TIMEOUT_MIN_MS, MAX_TIMEOUT as STAGE_TIMEOUT_MAX_MS } from '../lib/aiToolkit/constants.js';
@@ -233,9 +236,18 @@ function claimedContextWindow(provider, model) {
* actually serve. The ceiling bounds every rung, an explicit override included
* (a user preference the daemon cannot honor past its launch window). See
* {@link clampToRuntimeContextWindow} for the rule and why it is shared.
+ *
+ * The provider is projected through `withOllamaRuntimeContextWindow` first so
+ * the ceiling sees BOTH rungs the daemon was launched from — `numCtx` and the
+ * ambient `OLLAMA_CONTEXT_LENGTH`. Without it an install that configures the
+ * window through the env var alone budgeted at the model's catalog window and
+ * the call died at dispatch (#7472). The projection is in-memory and never
+ * persisted; `resolveStageContext` deliberately does NOT do it for us, because
+ * both of its branches (probe and no-probe) must get the same ceiling.
*/
export function effectiveContextWindow(provider, model) {
- return clampToRuntimeContextWindow(provider, claimedContextWindow(provider, model));
+ const runtime = withOllamaRuntimeContextWindow(provider);
+ return clampToRuntimeContextWindow(runtime, claimedContextWindow(runtime, model));
}
/**
diff --git a/server/services/stageRunner.test.js b/server/services/stageRunner.test.js
index f93108e8b6..7f8908a8f0 100644
--- a/server/services/stageRunner.test.js
+++ b/server/services/stageRunner.test.js
@@ -53,6 +53,11 @@ const { CODEX_CONTEXT_WINDOW, DEFAULT_LARGE_CONTEXT_WINDOW } = await import('../
// `fs`/`child_process`-reaching barrel: the contract test below asserts the
// budgeter and the gate agree, so it has to ask the real gate.
const { contextWindowRejection, knownContextWindow } = await import('../lib/aiToolkit/providerStatus.js');
+// The host's projection of a provider for a context question, and the resolver
+// the DAEMON LAUNCHER reads. The contract test below pins the budget against
+// what the launcher actually holds Ollama at — budgeter/gate agreement alone
+// cannot catch a rung they are both blind to (#7472).
+const { withOllamaRuntimeContextWindow, resolveOllamaContextLength } = await import('../lib/ollamaContext.js');
const apiProvider = (extra = {}) => ({
id: 'mock-api', name: 'Mock', type: 'api', enabled: true, defaultModel: 'm-default', ...extra,
@@ -353,9 +358,18 @@ describe('stageRunner — the budget never exceeds what the dispatch gate allows
{ ...ollama, modelContextWindows: undefined, contextWindow: 64_000 },
{ id: 'ollama', type: 'api', enabled: true, numCtx: 16_000, contextWindow: 128_000 },
{ type: 'tui', command: 'opencode', modelContextWindows: { 'qwen3:32b': 40_960 } },
+ // The env rung: no `numCtx`, so the ceiling exists only in the window
+ // PortOS launched the daemon at. Before #7472 this shape was COMPARED and
+ // still passed — budgeter and gate agreed on 40,960, the wrong answer —
+ // which is why the assertion below it is what proves the fix.
+ { ...ollama, numCtx: undefined, runtimeContextWindow: 16_384 },
];
const compared = shapes.filter((provider) => {
- const admitted = knownContextWindow(provider, 'qwen3:32b');
+ // Projected exactly as the host projects it before asking the gate
+ // (`promptRunner.js#assertRequestFitsContext`): the toolkit cannot resolve
+ // the ambient rung itself, so a gate asked about the RAW record is not the
+ // gate any request meets.
+ const admitted = knownContextWindow(withOllamaRuntimeContextWindow(provider), 'qwen3:32b');
expect(admitted, `the gate declares no window for ${JSON.stringify(provider)}`).toBeGreaterThan(0);
expect(effectiveContextWindow(provider, 'qwen3:32b'),
`budgeted wider than the gate admits for ${JSON.stringify(provider)}`)
@@ -364,6 +378,54 @@ describe('stageRunner — the budget never exceeds what the dispatch gate allows
});
expect(compared).toHaveLength(shapes.length);
});
+
+ // #7472 — the rung #7466 left open. Budgeter/gate agreement cannot catch this
+ // one: with no `numCtx` both ends read no ceiling and agree on the model's
+ // catalog window, while the daemon is running at the env-configured one and
+ // rejects the prompt with `exceed_context_size_error`. So this pins the budget
+ // against what the LAUNCHER holds the daemon at, not against the gate.
+ describe('an env-configured daemon (OLLAMA_CONTEXT_LENGTH, no numCtx)', () => {
+ const envOllama = { ...ollama, numCtx: undefined };
+
+ beforeEach(() => {
+ // Pinned rather than inherited: this machine may have either set already,
+ // and `OLLAMA_HOST` decides whether the provider counts as the daemon
+ // PortOS manages at all.
+ vi.stubEnv('OLLAMA_CONTEXT_LENGTH', '16384');
+ vi.stubEnv('OLLAMA_HOST', '');
+ vi.stubEnv('OLLAMA_URL', '');
+ });
+
+ afterEach(() => { vi.unstubAllEnvs(); });
+
+ it('budgets to the window the daemon was launched at, not the catalog window', async () => {
+ providers.getActiveProvider.mockResolvedValue(envOllama);
+ serving({ 'qwen3:32b': 40_960 });
+
+ const { contextWindow, model } = await resolveStageContext('any-stage');
+ // The daemon's ACTUAL window — the same number `ollamaAgentContext.js`
+ // hands `ensureContextWindow` and `withOllamaContextEnv` puts on
+ // `ollama serve`. Asserting against the resolver rather than the literal
+ // is the point: budget and launch must not be able to diverge.
+ expect(contextWindow).toBe(resolveOllamaContextLength(envOllama));
+ expect(contextWindow).toBe(16_384);
+ // …and the gate the host actually asks agrees, in both directions.
+ const gated = withOllamaRuntimeContextWindow(envOllama);
+ expect(contextWindowRejection(gated, model, { requiredContextTokens: contextWindow })).toBeNull();
+ expect(contextWindowRejection(gated, model, { requiredContextTokens: 40_960 })).toMatch(/16384/);
+ });
+
+ it('lets an explicit numCtx outrank it, and leaves a REMOTE daemon alone', async () => {
+ // `numCtx` first, exactly as `resolveOllamaContextLength` ranks the two —
+ // so a provider form's unsaved edit is not overruled by the ambient value.
+ expect(effectiveContextWindow({ ...envOllama, numCtx: 8_192 }, 'qwen3:32b')).toBe(8_192);
+ // The env var only ever reaches the daemon THIS install launches. Applied
+ // to a provider pointed at another host it would budget someone else's
+ // daemon down to this machine's VRAM headroom.
+ const remote = { ...envOllama, endpoint: 'http://192.0.2.10:11434/v1' };
+ expect(effectiveContextWindow(remote, 'qwen3:32b')).toBe(40_960);
+ });
+ });
});
describe('stageRunner — extractJson', () => {