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
Offer only model-tuning knobs PortOS can actually apply, and apply them
[._.]/ Adam Eivy895e152aeae9
diff --git a/client/src/components/settings/LocalModelAssessments.jsx b/client/src/components/settings/LocalModelAssessments.jsxindex 91c91c69e6..d9838b9ae3 100644--- a/client/src/components/settings/LocalModelAssessments.jsx+++ b/client/src/components/settings/LocalModelAssessments.jsx@@ -51,14 +51,6 @@ const BACKEND_LABEL = {ollama: 'Ollama', lmstudio: 'LM Studio', llama: 'llama.cpp', mtplx: 'MTPLX', vllm: 'vLLM',};-// What PortOS can actually DO with a knob, spelled out next to it. A knob it-// cannot set must never look like one it did.-const APPLIES_NOTE = {- launch: 'PortOS puts this on the launch line and relaunches the server.',- request: 'Sent with each measurement request.',- record: 'PortOS cannot set this — recorded so two readings stay comparable.',-};-const VERDICT_META = {fits: { label: 'Fits', cls: 'text-emerald-400 border-emerald-400/50' },'does-not-fit': { label: 'Does not fit', cls: 'text-port-warning border-port-warning/50' },@@ -133,7 +125,12 @@ function TuningFields({ specs, draft, onChange, disabled }) {<div className="min-w-0"><label htmlFor={fieldId} className="text-xs text-gray-300">{spec.label}</label><p className="text-[10px] text-gray-500 leading-snug">{spec.hint}</p>- <p className="text-[10px] text-gray-600 leading-snug">{APPLIES_NOTE[spec.applies]}</p>+ {/* What PortOS will DO with the knob, naming the flag or variable+ it becomes. Derived server-side from the knob's transport+ (server/lib/localModelTuning.js) and shipped on the spec, so+ the UI cannot describe a transport differently from the code+ that applies it. */}+ <p className="text-[10px] text-gray-600 leading-snug">{spec.note}</p></div>{spec.type === 'boolean' ? (<input@@ -229,6 +226,8 @@ function AssessmentConsentModal({<p className="text-[10px] text-gray-500">Leave a field empty to use the runtime's own default. A tuned run is recordedseparately, so you can compare it against the untuned one instead of replacing it.+ Setting a launch knob restarts that runtime's server before measuring, which+ interrupts anything else using it.</p><TuningFields specs={tuningSpecs} draft={tuning} onChange={onTuningChange} disabled={running} /></div>diff --git a/client/src/components/settings/LocalModelAssessments.test.jsx b/client/src/components/settings/LocalModelAssessments.test.jsxindex 518564dbaf..4bd9ada099 100644--- a/client/src/components/settings/LocalModelAssessments.test.jsx+++ b/client/src/components/settings/LocalModelAssessments.test.jsx@@ -52,11 +52,11 @@ const report = (overrides = {}) => ({// drift from.const RUNTIMES = [{ id: 'ollama', label: 'Ollama', managed: true, modelCount: 1, error: null, tuningSpecs: [- { id: 'numCtx', label: 'Context size', type: 'number', applies: 'request', min: 512, max: 1048576, unit: 'tokens', hint: 'Sent with the request.' },+ { id: 'numCtx', label: 'Context size', type: 'number', applies: 'launch', env: 'OLLAMA_CONTEXT_LENGTH', min: 512, max: 1048576, unit: 'tokens', hint: 'The window every model loads with.', note: 'PortOS restarts the server with OLLAMA_CONTEXT_LENGTH set.' },] },{ id: 'llama', label: 'llama.cpp', managed: false, modelCount: 3, error: null, tuningSpecs: [- { id: 'ubatchSize', label: 'Micro-batch size', type: 'number', applies: 'launch', min: 1, max: 8192, hint: 'Physical micro-batch.' },- { id: 'flashAttn', label: 'Flash attention', type: 'boolean', applies: 'launch', hint: 'Fused attention kernel.' },+ { id: 'ubatchSize', label: 'Micro-batch size', type: 'number', applies: 'launch', config: true, min: 1, max: 8192, hint: 'Physical micro-batch.', note: "PortOS puts this on the server's launch line and relaunches it." },+ { id: 'flashAttn', label: 'Flash attention', type: 'boolean', applies: 'launch', config: true, hint: 'Fused attention kernel.', note: "PortOS puts this on the server's launch line and relaunches it." },] },{ id: 'mtplx', label: 'MTPLX', managed: false, modelCount: null, error: 'not reachable at http://127.0.0.1:8000/v1 (ECONNREFUSED)', tuningSpecs: [] },];@@ -473,12 +473,26 @@ describe('LocalModelAssessments — tuning', () => {));});- it('says what PortOS can and cannot set for each knob', async () => {+ // Naming the transport, not just "applied": the user is choosing flags to+ // pass a model, so the form has to say which flag each knob becomes. The+ // sentence is derived server-side and rides on the spec.+ it('names the transport that carries each knob to the daemon', async () => {const user = userEvent.setup();render(<LocalModelAssessments />);await user.click(await screen.findByRole('button', { name: 'Measure' }));await user.click(await screen.findByRole('button', { name: /Tuning/ }));- expect(screen.getAllByText(/puts this on the launch line/).length).toBe(2);+ expect(screen.getAllByText(/puts this on the server's launch line/).length).toBe(2);+ });++ it('names the environment variable an Ollama knob is applied through', async () => {+ getLocalLlmAssessments.mockResolvedValue(report({+ unassessed: [{ backend: 'ollama', modelId: 'example-model:7b', params: null }],+ }));+ const user = userEvent.setup();+ render(<LocalModelAssessments />);+ await user.click(await screen.findByRole('button', { name: 'Measure' }));+ await user.click(await screen.findByRole('button', { name: /Tuning/ }));+ expect(screen.getByText(/restarts the server with OLLAMA_CONTEXT_LENGTH set/)).toBeInTheDocument();});it('warns instead of celebrating when the tuning never reached the daemon', async () => {diff --git a/server/lib/README.md b/server/lib/README.mdindex 44aac2404a..e8be11794e 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -315,7 +315,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `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, { measured })` ranks installed models for editorial review/editing, dropping any a fresh measurement proved cannot run here. Pure. Mirror `isEmbeddingModel`/`isVisionModel` in `client/src/utils/providers.js`. || `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: `TUNING_SPECS` (per runtime — llama.cpp's `-b`/`-ub`/`-t`/`--flash-attn`/`--cache-type-k|v`/`--draft-max`, Ollama's `num_ctx`, plus the record-only knobs for LM Studio / MTPLX / vLLM), each declaring `applies: 'launch' \| 'request' \| 'record'` so the UI can never claim PortOS set something it cannot. `normalizeTuning` (coerce + clamp + drop unknown keys), `tuningSignature` (stable identity — `''` for backend defaults, so pre-tuning store keys keep resolving), `describeTuning`, `launchTuning`, `requestBody` (request knobs under their wire names), and `compareTunings` (which tuning won per model, with a `deltaPercent` against the winner). Pure. |+| `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`/`--flash-attn`/`--cache-type-k\|v`/`--draft-max`, via `launchConfig`), `env` (Ollama's `OLLAMA_CONTEXT_LENGTH`/`_FLASH_ATTENTION`/`_KV_CACHE_TYPE`/`_NUM_PARALLEL`, via `launchEnv`), `cli` (LM Studio's `lms load --context-length`/`--gpu`/`--parallel`, via `launchArgs`), or `wire` (a request-body field, via `requestBody` — currently no members). MTPLX/vLLM declare none: PortOS has no launch path into them. 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, labelled from each record's persisted `tuningLabel`, with a `deltaPercent` against the winner). 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`. || `issueLength.js` | Per-issue size targets fed into text stages. || `musicDuration.js` | Lyric-aware MiniMax Music 3 duration analysis and ending-cushioned auto-duration recommendation; mirrors `client/src/lib/musicDuration.js`. |diff --git a/server/lib/localModelTuning.js b/server/lib/localModelTuning.jsindex 91704cdff6..f0b188519a 100644--- a/server/lib/localModelTuning.js+++ b/server/lib/localModelTuning.js@@ -13,19 +13,45 @@* that lets several tunings of ONE model coexist in the store and be ranked* against each other.*- * ## `applies` — the honesty axis (read before adding a knob)+ * ## Only knobs PortOS can actually SET (read before adding a knob)*- * Every knob declares what PortOS can actually DO with it:+ * The point of a tuning sweep is to learn what flags this install should pass a+ * given model. A knob PortOS cannot apply teaches nothing: the user types a+ * number, the daemon runs exactly as it did before, and the reading is filed+ * under a configuration that never existed. So the catalog holds ONLY knobs with+ * a code path that reaches the daemon, and a knob is DEFINED by the transport+ * that carries it — exactly one of:*- * - `'launch'` — PortOS starts this daemon, so it puts the knob on the- * command line (llama.cpp only today, via `llamaServerManager`).- * - `'request'` — PortOS sends it with each measurement request.- * - `'record'` — PortOS cannot set it. The user states how the daemon was- * launched so two readings are comparable.+ * - `config: true` — a `llamaServerManager` config key PortOS puts on the+ * llama-server command line and relaunches. → `launchConfig`+ * - `env: 'NAME'` — an environment variable PortOS hands `ollama serve`+ * when it restarts the daemon. → `launchEnv`+ * - `cli: '--flag'` — an `lms load` flag PortOS passes when it reloads the+ * LM Studio model. → `launchArgs`+ * - `wire: 'field'` — a field PortOS merges into each measurement request+ * body. → `requestBody`*- * A `'record'` knob is NOT a lie by omission — it changes nothing about the run- * and the UI says so. What it must never do is claim to have been applied. Do- * not promote a knob to `'launch'`/`'request'` without a code path that sends it.+ * The transport is the ONLY thing a spec literal declares about application:+ * `applies` ('launch' vs 'request') and the user-facing `note` are DERIVED from+ * it by `decorate` below, so the two can never disagree and a new knob has one+ * field to get right. A knob declared without a transport renders through+ * nothing — which `localModelTuning.test.js` fails on. Do NOT add a knob just to+ * document how a daemon was started; that dresses an unapplied setting up as an+ * applied one. (An older revision had an `applies: 'record'` tier for exactly+ * that, covering LM Studio, MTPLX, vLLM and half of Ollama. It was removed+ * because "PortOS cannot set this" knobs are not testable and crowded out the+ * ones that are. A reading taken under one still describes itself: the store+ * persists each record's `tuningLabel` at measure time — see `compareTunings`.)+ *+ * The `wire` tier is currently EMPTY and that is deliberate, not an oversight:+ * llama.cpp, Ollama, and LM Studio all pick these settings when the model loads,+ * and Ollama's OpenAI-compatible endpoint silently drops unknown body fields. It+ * is kept because a runtime that does honour per-request knobs (vLLM) is the+ * likely next entry.+ *+ * MTPLX and vLLM therefore declare no knobs: PortOS starts MTPLX under PM2 but+ * passes only `--port`/`--model`, and it does not start vLLM at all. Add knobs+ * there once there is a launch path that carries them.** ## The sentinel contract*@@ -40,10 +66,33 @@* KV-cache quantization types llama.cpp accepts for `--cache-type-k/-v`. Kept to* the three that are universally compiled in; an exotic type the local build* lacks would make the server exit on launch, which reads to the user as "this- * model does not fit".+ * model does not fit". Ollama's `OLLAMA_KV_CACHE_TYPE` takes the same spellings.*/const CACHE_TYPES = ['f16', 'q8_0', 'q4_0'];+/**+ * The user-facing sentence for a knob: what PortOS will DO with it, naming the+ * flag or variable it becomes. Derived from the transport so the form, the+ * catalog, and the code that applies it cannot drift — and shipped to the client+ * on the spec, so the note lives with the module that owns the transport rather+ * than being re-derived in the UI.+ */+const noteFor = (spec) => {+ if (spec.wire) return `Sent with each measurement request as \`${spec.wire}\`.`;+ if (spec.env) return `PortOS restarts the server with ${spec.env} set.`;+ if (spec.cli) return `PortOS reloads the model with \`lms load ${spec.cli}\`.`;+ return "PortOS puts this on the server's launch line and relaunches it.";+};++// `applies` and `note` are computed, never written by hand — see the transport+// rule above. A spec with no transport gets `applies: 'launch'` and a note it+// cannot honour, which is what the catalog guard test exists to catch.+const decorate = (spec) => Object.freeze({+ ...spec,+ applies: spec.wire ? 'request' : 'launch',+ note: noteFor(spec),+});+/*** Tuning knobs per runtime, in the order a UI should render them.*@@ -51,42 +100,46 @@ const CACHE_TYPES = ['f16', 'q8_0', 'q4_0'];* a tuning sweep is finding the trade that suits this machine, not maximizing* any single number.*/-export const TUNING_SPECS = Object.freeze({- llama: Object.freeze([- { id: 'ctxSize', label: 'Context size', type: 'number', applies: 'launch', min: 512, max: 1048576, unit: 'tokens', hint: 'KV cache is allocated for the whole window up front — a larger one costs memory even when prompts are short.' },- { id: 'nGpuLayers', label: 'GPU layers', type: 'number', applies: 'launch', min: 0, max: 999, hint: 'Layers offloaded to the GPU. Fewer layers frees VRAM for a bigger context at the cost of throughput.' },- { id: 'batchSize', label: 'Batch size', type: 'number', applies: 'launch', min: 1, max: 8192, hint: 'Logical prompt batch (-b). Raising it speeds up prefill on long prompts and raises peak memory.' },- { id: 'ubatchSize', label: 'Micro-batch size', type: 'number', applies: 'launch', min: 1, max: 8192, hint: 'Physical micro-batch (-ub). The single knob that most often moves long-context throughput.' },- { id: 'threads', label: 'CPU threads', type: 'number', applies: 'launch', min: 1, max: 256, hint: 'Threads for the CPU-resident layers. More is not always faster once you pass the physical core count.' },- { id: 'flashAttn', label: 'Flash attention', type: 'boolean', applies: 'launch', hint: 'Fused attention kernel. Usually faster and lighter on memory, but not every build/GPU supports it.' },- { id: 'cacheTypeK', label: 'KV cache type (K)', type: 'enum', applies: 'launch', options: CACHE_TYPES, hint: 'Quantizing the key cache buys context length with a little quality.' },- { id: 'cacheTypeV', label: 'KV cache type (V)', type: 'enum', applies: 'launch', options: CACHE_TYPES, hint: 'Quantizing the value cache buys context length with a little quality.' },- { id: 'draftMax', label: 'Draft tokens', type: 'number', applies: 'launch', min: 0, max: 64, hint: 'Speculative-decoding lookahead. Only does anything when a drafter model is loaded.' },- ]),- ollama: Object.freeze([- { id: 'numCtx', label: 'Context size', type: 'number', applies: 'request', wire: 'num_ctx', min: 512, max: 1048576, unit: 'tokens', hint: 'Sent with the measurement request as `num_ctx`.' },- { id: 'numGpu', label: 'GPU layers', type: 'number', applies: 'record', min: 0, max: 999, hint: 'Set via the model\'s Modelfile or OLLAMA_NUM_GPU — recorded here so two readings are comparable.' },- { id: 'numThread', label: 'CPU threads', type: 'number', applies: 'record', min: 1, max: 256, hint: 'Set outside PortOS; recorded so a thread-count change does not read as noise.' },- { id: 'flashAttention', label: 'Flash attention', type: 'boolean', applies: 'record', hint: 'OLLAMA_FLASH_ATTENTION in the daemon\'s environment.' },- { id: 'kvCacheType', label: 'KV cache type', type: 'enum', applies: 'record', options: CACHE_TYPES, hint: 'OLLAMA_KV_CACHE_TYPE in the daemon\'s environment.' },- ]),- lmstudio: Object.freeze([- { id: 'contextLength', label: 'Context length', type: 'number', applies: 'record', min: 512, max: 1048576, unit: 'tokens', hint: 'Chosen in LM Studio when the model is loaded.' },- { id: 'gpuOffloadLayers', label: 'GPU offload layers', type: 'number', applies: 'record', min: 0, max: 999, hint: 'LM Studio\'s GPU offload slider.' },- { id: 'evalBatchSize', label: 'Eval batch size', type: 'number', applies: 'record', min: 1, max: 8192, hint: 'LM Studio\'s evaluation batch size.' },- { id: 'flashAttention', label: 'Flash attention', type: 'boolean', applies: 'record', hint: 'LM Studio\'s flash-attention toggle.' },- ]),- mtplx: Object.freeze([- { id: 'numDraftTokens', label: 'MTP draft tokens', type: 'number', applies: 'record', min: 0, max: 64, hint: 'Multi-token-prediction lookahead the server was started with.' },- { id: 'maxKvSize', label: 'Max KV size', type: 'number', applies: 'record', min: 512, max: 1048576, unit: 'tokens', hint: 'KV cache ceiling on the launch line.' },- { id: 'kvBits', label: 'KV cache bits', type: 'enum', applies: 'record', options: ['4', '8', '16'], hint: 'MLX KV-cache quantization width.' },- ]),- vllm: Object.freeze([- { id: 'maxModelLen', label: 'Max model length', type: 'number', applies: 'record', min: 512, max: 1048576, unit: 'tokens', hint: '--max-model-len on the container launch line.' },- { id: 'gpuMemoryUtilization', label: 'GPU memory utilization', type: 'number', applies: 'record', min: 0.1, max: 1, step: 0.05, hint: '--gpu-memory-utilization: the fraction of VRAM vLLM is allowed to claim.' },- { id: 'maxNumSeqs', label: 'Max concurrent sequences', type: 'number', applies: 'record', min: 1, max: 1024, hint: '--max-num-seqs: batching width, which trades single-stream latency for throughput.' },- ]),-});+const RAW_SPECS = {+ llama: [+ { id: 'ctxSize', label: 'Context size', type: 'number', config: true, min: 512, max: 1048576, unit: 'tokens', hint: 'KV cache is allocated for the whole window up front — a larger one costs memory even when prompts are short.' },+ { id: 'nGpuLayers', label: 'GPU layers', type: 'number', config: true, min: 0, max: 999, hint: 'Layers offloaded to the GPU. Fewer layers frees VRAM for a bigger context at the cost of throughput.' },+ { id: 'batchSize', label: 'Batch size', type: 'number', config: true, min: 1, max: 8192, hint: 'Logical prompt batch (-b). Raising it speeds up prefill on long prompts and raises peak memory.' },+ { id: 'ubatchSize', label: 'Micro-batch size', type: 'number', config: true, min: 1, max: 8192, hint: 'Physical micro-batch (-ub). The single knob that most often moves long-context throughput.' },+ { id: 'threads', label: 'CPU threads', type: 'number', config: true, min: 1, max: 256, hint: 'Threads for the CPU-resident layers. More is not always faster once you pass the physical core count.' },+ { id: 'flashAttn', label: 'Flash attention', type: 'boolean', config: true, hint: 'Fused attention kernel. Usually faster and lighter on memory, but not every build/GPU supports it.' },+ { id: 'cacheTypeK', label: 'KV cache type (K)', type: 'enum', config: true, options: CACHE_TYPES, hint: 'Quantizing the key cache buys context length with a little quality.' },+ { id: 'cacheTypeV', label: 'KV cache type (V)', type: 'enum', config: true, options: CACHE_TYPES, hint: 'Quantizing the value cache buys context length with a little quality.' },+ { id: 'draftMax', label: 'Draft tokens', type: 'number', config: true, min: 0, max: 64, hint: 'Speculative-decoding lookahead. Only does anything when a drafter model is loaded.' },+ ],+ // Every Ollama knob is daemon-wide environment, applied by restarting+ // `ollama serve` — including the context window. A `num_ctx` in the request+ // body is NOT an alternative: Ollama's OpenAI-compatible endpoint drops+ // unknown fields, and the model still loads at the daemon default.+ ollama: [+ { id: 'numCtx', label: 'Context size', type: 'number', env: 'OLLAMA_CONTEXT_LENGTH', min: 512, max: 1048576, unit: 'tokens', hint: 'The window every model loads with. Larger costs VRAM up front, and past what fits Ollama offloads to CPU instead of failing.' },+ { id: 'flashAttention', label: 'Flash attention', type: 'boolean', env: 'OLLAMA_FLASH_ATTENTION', hint: 'Fused attention kernel. Usually faster and lighter on memory, and a prerequisite for a quantized KV cache.' },+ { id: 'kvCacheType', label: 'KV cache type', type: 'enum', env: 'OLLAMA_KV_CACHE_TYPE', options: CACHE_TYPES, hint: 'Quantizing the KV cache buys context length with a little quality. Ollama honours it only with flash attention on.' },+ { id: 'numParallel', label: 'Parallel requests', type: 'number', env: 'OLLAMA_NUM_PARALLEL', min: 1, max: 16, hint: 'Request slots the daemon serves at once. Each slot claims its own share of the context window, so raising it shrinks the window per request.' },+ ],+ // LM Studio's load-time settings, applied by reloading the model through+ // `lms load`. The app's other toggles (eval batch size, flash attention) have+ // no CLI flag, so they are not offered — see the transport rule above.+ lmstudio: [+ { id: 'contextLength', label: 'Context length', type: 'number', cli: '--context-length', min: 512, max: 1048576, unit: 'tokens', hint: 'The window the model is loaded with. LM Studio refuses a load that does not fit rather than silently shrinking it.' },+ { id: 'gpuOffload', label: 'GPU offload', type: 'number', cli: '--gpu', min: 0, max: 1, step: 0.05, hint: 'Fraction of layers on the GPU (0 = CPU only, 1 = full offload). Lower frees VRAM for a bigger context at the cost of throughput.' },+ { id: 'parallel', label: 'Parallel requests', type: 'number', cli: '--parallel', min: 1, max: 16, hint: 'Predictions the model runs at once. Higher total throughput, slower per prediction.' },+ ],+ // PortOS starts MTPLX under PM2 but passes only `--port` and `--model`, and it+ // does not start vLLM at all — so neither has a knob it could apply. Left+ // present-and-empty rather than absent so the runtime still enumerates.+ mtplx: [],+ vllm: [],+};++export const TUNING_SPECS = Object.freeze(Object.fromEntries(+ Object.entries(RAW_SPECS).map(([runtime, specs]) => [runtime, Object.freeze(specs.map(decorate))])+));/** Knob specs for one runtime, or `[]` for a runtime with none declared. */export const tuningSpecsFor = (runtimeId) => TUNING_SPECS[runtimeId] || [];@@ -163,6 +216,11 @@ const formatValue = (spec, value) => {* Human label for a tuning set, e.g. `Context size 32k · Micro-batch size 512`.* `null` when nothing was tuned — the caller renders "backend defaults" rather* than an empty string that reads like a missing value.+ *+ * Describes the tuning as the CURRENT catalog understands it, which is right for+ * the run being measured. It is NOT how a stored reading describes itself: each+ * record persists the `tuningLabel` it was measured under, so a knob that later+ * leaves the catalog cannot silently relabel an old measurement.*/export function describeTuning(runtimeId, tuning) {const parts = tuningSpecsFor(runtimeId)@@ -172,13 +230,75 @@ export function describeTuning(runtimeId, tuning) {}/**- * The subset of a tuning set PortOS puts on the daemon's command line. Empty for- * every runtime PortOS does not start itself.+ * The subset of a tuning set PortOS applies at LAUNCH — the daemon has to be+ * (re)started for these to take effect, whatever the transport.+ *+ * All four renderers below walk the CATALOG rather than the tuning, so a knob+ * the runtime does not declare cannot reach a launch line, and the rendered+ * order is the order the form showed.*/export function launchTuning(runtimeId, tuning) {const out = {};- for (const [id, value] of Object.entries(tuning || {})) {- if (specById(runtimeId, id)?.applies === 'launch') out[id] = value;+ for (const spec of tuningSpecsFor(runtimeId)) {+ if (spec.applies !== 'launch') continue;+ const value = tuning?.[spec.id];+ if (value !== undefined && value !== null && value !== '') out[spec.id] = value;+ }+ return out;+}++/**+ * Launch knobs rendered as a llama-server CONFIG object — knob id to value,+ * which is the shape `llamaServerManager.startLlamaServer` takes.+ */+export function launchConfig(runtimeId, tuning) {+ const out = {};+ for (const spec of tuningSpecsFor(runtimeId)) {+ if (!spec.config) continue;+ const value = tuning?.[spec.id];+ if (value !== undefined && value !== null && value !== '') out[spec.id] = value;+ }+ return out;+}++/**+ * Launch knobs rendered as the daemon's ENVIRONMENT (Ollama), e.g.+ * `{ OLLAMA_FLASH_ATTENTION: '1' }`.+ *+ * Booleans render as `1`/`0` because that is what Ollama parses, and an+ * explicitly-off toggle has to survive as an override of a daemon default that+ * may be on. Every value is a string, since that is what a child process+ * environment holds.+ */+export function launchEnv(runtimeId, tuning) {+ const out = {};+ for (const spec of tuningSpecsFor(runtimeId)) {+ if (!spec.env) continue;+ const value = tuning?.[spec.id];+ if (value === undefined || value === null || value === '') continue;+ out[spec.env] = spec.type === 'boolean' ? (value ? '1' : '0') : String(value);+ }+ return out;+}++/**+ * Launch knobs rendered as COMMAND-LINE arguments (`lms load`), flattened to the+ * `['--context-length', '8192']` shape `spawn` takes.+ *+ * A boolean renders as a bare flag when on and is omitted when off — a CLI has+ * no spelling for "explicitly off" that is not just the default.+ */+export function launchArgs(runtimeId, tuning) {+ const out = [];+ for (const spec of tuningSpecsFor(runtimeId)) {+ if (!spec.cli) continue;+ const value = tuning?.[spec.id];+ if (value === undefined || value === null || value === '') continue;+ if (spec.type === 'boolean') {+ if (value) out.push(spec.cli);+ continue;+ }+ out.push(spec.cli, String(value));}return out;}@@ -187,20 +307,27 @@ export function launchTuning(runtimeId, tuning) {* The request-applied knobs, rendered under their WIRE names, ready to merge* into a chat-completions body.*- * The wire name lives on the spec rather than in a lookup table here so a knob- * cannot be declared `applies: 'request'` without also declaring the field the- * daemon reads — which would produce a knob that silently does nothing while the- * UI reports it as applied.+ * Empty for every runtime today — see the note on the `wire` tier at the top of+ * this file. The wire name lives on the spec rather than in a lookup table here+ * so a knob cannot declare itself request-applied without also naming the field+ * the daemon reads.*/export function requestBody(runtimeId, tuning) {const out = {};- for (const [id, value] of Object.entries(tuning || {})) {- const spec = specById(runtimeId, id);- if (spec?.applies === 'request' && spec.wire) out[spec.wire] = value;+ for (const spec of tuningSpecsFor(runtimeId)) {+ if (!spec.wire) continue;+ const value = tuning?.[spec.id];+ if (value !== undefined && value !== null && value !== '') out[spec.wire] = value;}return out;}+// The label the record was MEASURED under, which is what a comparison table has+// to show. Re-deriving it from the raw tuning would silently relabel a reading+// whose knob has since left the catalog — the record is the authority on the+// configuration it describes, not today's catalog.+const labelOf = (a) => a?.tuningLabel || describeTuning(a?.backend, a?.tuning) || 'Backend defaults';+const throughputOf = (a) => {const value = a?.performance?.meanCharsPerSecond;return Number.isFinite(value) ? value : null;@@ -239,12 +366,12 @@ export function compareTunings(assessments) {modelId: sorted[0].modelId,best: {tuning: sorted[0].tuning || {},- label: describeTuning(sorted[0].backend, sorted[0].tuning) || 'Backend defaults',+ label: labelOf(sorted[0]),charsPerSecond: winner,},variants: sorted.map((a) => ({tuning: a.tuning || {},- label: describeTuning(a.backend, a.tuning) || 'Backend defaults',+ label: labelOf(a),charsPerSecond: throughputOf(a),maxWorkingContextTokens: Number.isFinite(a.performance?.maxWorkingContextTokens)? a.performance.maxWorkingContextTokensdiff --git a/server/lib/localModelTuning.test.js b/server/lib/localModelTuning.test.jsindex 4ae3c6c14d..53656051f8 100644--- a/server/lib/localModelTuning.test.js+++ b/server/lib/localModelTuning.test.js@@ -3,6 +3,9 @@ import {TUNING_SPECS,compareTunings,describeTuning,+ launchArgs,+ launchConfig,+ launchEnv,launchTuning,normalizeTuning,requestBody,@@ -11,31 +14,58 @@ import {} from './localModelTuning.js';describe('TUNING_SPECS', () => {- it('declares an applies mode for every knob', () => {+ // The whole point of the catalog is learning which flags to pass a model, so a+ // knob PortOS cannot send teaches nothing. Every knob must name EXACTLY ONE+ // transport — none means it renders in the form, changes nothing, and the+ // reading is filed under a configuration that never existed; two means the+ // derived `applies` picks a winner nobody declared.+ it('gives every knob exactly one transport that reaches the daemon', () => {for (const [runtime, specs] of Object.entries(TUNING_SPECS)) {for (const spec of specs) {- expect(['launch', 'request', 'record'], `${runtime}/${spec.id}`).toContain(spec.applies);+ const transports = [spec.wire, spec.env, spec.cli, spec.config].filter(Boolean);+ expect(transports, `${runtime}/${spec.id}`).toHaveLength(1);}}});- // A `request` knob with no wire name would be reported to the user as applied- // while `requestBody` silently dropped it.- it('gives every request-applied knob the field name the daemon reads', () => {+ // Derived, not declared — so a spec literal cannot disagree with itself.+ it('derives applies and the user-facing note from that transport', () => {for (const [runtime, specs] of Object.entries(TUNING_SPECS)) {- for (const spec of specs.filter((s) => s.applies === 'request')) {- expect(spec.wire, `${runtime}/${spec.id}`).toBeTruthy();+ for (const spec of specs) {+ expect(spec.applies, `${runtime}/${spec.id}`).toBe(spec.wire ? 'request' : 'launch');+ expect(spec.note, `${runtime}/${spec.id}`).toBeTruthy();}}});- it('only puts launch knobs on runtimes PortOS actually starts', () => {+ it('names the flag or variable the knob becomes, not just that it is applied', () => {+ const byId = (runtime, id) => tuningSpecsFor(runtime).find((s) => s.id === id);+ expect(byId('ollama', 'flashAttention').note).toContain('OLLAMA_FLASH_ATTENTION');+ expect(byId('lmstudio', 'contextLength').note).toContain('lms load --context-length');+ expect(byId('llama', 'ubatchSize').note).toContain('launch line');+ });++ // Guard against a transport that is declared but renders nothing — the failure+ // a hand-maintained renderer switch would reintroduce.+ it('renders every knob through the renderer its transport names', () => {for (const [runtime, specs] of Object.entries(TUNING_SPECS)) {- if (runtime === 'llama') continue;- expect(specs.some((s) => s.applies === 'launch'), runtime).toBe(false);+ for (const spec of specs) {+ const sample = { [spec.id]: spec.type === 'boolean' ? true : spec.type === 'enum' ? spec.options[0] : 1 };+ const rendered = Object.keys(launchEnv(runtime, sample)).length+ + launchArgs(runtime, sample).length+ + Object.keys(launchConfig(runtime, sample)).length+ + Object.keys(requestBody(runtime, sample)).length;+ expect(rendered, `${runtime}/${spec.id}`).toBeGreaterThan(0);+ }}});+ // PortOS passes MTPLX only --port/--model and does not start vLLM at all.+ it('offers no knob for a runtime PortOS has no launch path into', () => {+ expect(tuningSpecsFor('mtplx')).toEqual([]);+ expect(tuningSpecsFor('vllm')).toEqual([]);+ });+it('returns an empty list for an unknown runtime rather than throwing', () => {expect(tuningSpecsFor('not-a-runtime')).toEqual([]);});@@ -56,7 +86,7 @@ describe('normalizeTuning', () => {});it('keeps a fractional knob fractional when the spec declares a step', () => {- expect(normalizeTuning('vllm', { gpuMemoryUtilization: 0.85 })).toEqual({ gpuMemoryUtilization: 0.85 });+ expect(normalizeTuning('lmstudio', { gpuOffload: 0.85 })).toEqual({ gpuOffload: 0.85 });});it('coerces the string booleans a form posts', () => {@@ -109,23 +139,62 @@ describe('describeTuning', () => {it('renders a false boolean as off, not as absent', () => {expect(describeTuning('llama', { flashAttn: false })).toBe('Flash attention off');});++ it('ignores a key the runtime does not declare rather than inventing a label', () => {+ expect(describeTuning('llama', { somethingElse: 4 })).toBeNull();+ });});-describe('launchTuning / requestBody', () => {+describe('launchTuning / launchConfig / launchEnv / launchArgs / requestBody', () => {it('keeps only the knobs that reach the llama.cpp command line', () => {expect(launchTuning('llama', { ubatchSize: 512, cacheTypeK: 'q8_0' })).toEqual({ ubatchSize: 512, cacheTypeK: 'q8_0' });});- it('finds no launch knobs on a runtime PortOS does not start', () => {- expect(launchTuning('ollama', { numCtx: 8192, numGpu: 40 })).toEqual({});+ it('renders llama.cpp knobs as the config object its manager relaunches with', () => {+ expect(launchConfig('llama', { ubatchSize: 512, cacheTypeK: 'q8_0' }))+ .toEqual({ ubatchSize: 512, cacheTypeK: 'q8_0' });+ });++ // A key no spec declares must never reach a launch line, whichever renderer+ // it is handed to.+ it('drops an undeclared key from every launch renderer', () => {+ expect(launchConfig('llama', { rmRf: '/' })).toEqual({});+ expect(launchEnv('ollama', { rmRf: '/' })).toEqual({});+ expect(launchArgs('lmstudio', { rmRf: '/' })).toEqual([]);});- it('renders request knobs under the wire name the daemon reads', () => {- expect(requestBody('ollama', { numCtx: 8192, numGpu: 40 })).toEqual({ num_ctx: 8192 });+ it('renders Ollama knobs as the daemon environment they only reach it through', () => {+ expect(launchEnv('ollama', { numCtx: 8192, flashAttention: true, kvCacheType: 'q8_0' })).toEqual({+ OLLAMA_CONTEXT_LENGTH: '8192',+ OLLAMA_FLASH_ATTENTION: '1',+ OLLAMA_KV_CACHE_TYPE: 'q8_0',+ });});- it('sends nothing for a record-only runtime', () => {+ // Ollama parses 0/1, not JS `false` — and an explicitly-off toggle has to+ // survive as an override of a daemon default that may be on.+ it('renders a false toggle as 0 rather than dropping it', () => {+ expect(launchEnv('ollama', { flashAttention: false })).toEqual({ OLLAMA_FLASH_ATTENTION: '0' });+ });++ it('renders LM Studio knobs as the lms load flags that carry them', () => {+ expect(launchArgs('lmstudio', { contextLength: 8192, gpuOffload: 0.5 }))+ .toEqual(['--context-length', '8192', '--gpu', '0.5']);+ });++ it('renders lms flags in catalog order, whatever order the knobs were set in', () => {+ expect(launchArgs('lmstudio', { parallel: 2, contextLength: 8192 }))+ .toEqual(['--context-length', '8192', '--parallel', '2']);+ });++ it('renders nothing for a runtime whose knobs travel by another transport', () => {+ expect(launchArgs('ollama', { numCtx: 8192 })).toEqual([]);+ expect(launchEnv('lmstudio', { contextLength: 8192 })).toEqual({});+ });++ it('sends no request body for a runtime whose knobs are all launch-time', () => {+ expect(requestBody('ollama', { numCtx: 8192 })).toEqual({});expect(requestBody('lmstudio', { contextLength: 8192 })).toEqual({});});});@@ -156,6 +225,17 @@ describe('compareTunings', () => {expect(row.best.label).toBe('Backend defaults');});+ // The record is the authority on the configuration it was measured under. A+ // knob that has since left the catalog would otherwise re-derive to "Backend+ // defaults", silently changing what a stored reading claims to be.+ it('shows the label the reading was measured under, not one re-derived today', () => {+ const [row] = compareTunings([+ measured({ someRetiredKnob: 8192 }, 120, { tuningLabel: 'Max KV size 8k' }),+ measured({ ubatchSize: 512 }, 90),+ ]);+ expect(row.best.label).toBe('Max KV size 8k');+ });+// One reading is not a comparison. Presenting it as "the best tuning" would// dress a single measurement up as a conclusion.it('omits a model measured under only one tuning', () => {diff --git a/server/services/lmStudioManager.js b/server/services/lmStudioManager.jsindex 12add98fb1..0e91b43668 100644--- a/server/services/lmStudioManager.js+++ b/server/services/lmStudioManager.js@@ -26,6 +26,9 @@ const AVAILABILITY_PROBE_TIMEOUT_MS = 5_000// `lms server start|stop` only asks the already-installed app to flip its// listener — it never downloads anything, so a minute is generous.const LMS_CONTROL_TIMEOUT_MS = 60_000+// `lms load` reads a multi-gigabyte GGUF off disk and allocates its KV cache;+// on a cold page cache that is minutes, not seconds.+const LMS_LOAD_TIMEOUT_MS = 300_000// Default LM Studio configurationconst DEFAULT_CONFIG = {@@ -275,6 +278,45 @@ async function loadModel(modelId) {return { success: true, modelId, ...response }}+/**+ * Reload a model through the `lms` CLI with explicit load-time settings.+ *+ * LM Studio's context length, GPU offload, and parallelism are chosen when a+ * model is LOADED — no request field changes them, and the REST load endpoint+ * takes only a model id. `lms load` is the one path that carries them, so a+ * tuned measurement of an LM Studio model goes through here or it is measuring+ * whatever the app happened to be holding.+ *+ * The model is unloaded first: `lms load` on an already-resident model returns+ * the existing instance rather than re-loading it at the new settings, which+ * would report success for a tuning that never applied.+ *+ * Resolves rather than throws (mirrors `controlServer`) so a caller can record+ * the refusal alongside the reading it describes.+ *+ * @param {string} modelId+ * @param {string[]} args - rendered flags, e.g. `['--context-length', '8192']`+ * @returns {Promise<{ success: boolean, error?: string }>}+ */+async function loadModelWithArgs(modelId, args = []) {+ if (!modelId) return { success: false, error: 'No model was named to load.' }++ if (await checkLMStudioAvailable()) await unloadModel(modelId).catch(() => {})++ // `-y` because there is no one at a terminal to answer the model-picker prompt+ // `lms load` opens when a key matches more than one download.+ //+ // `runLms` resets the model caches, so the next reader refetches lazily —+ // forcing a refresh here would pay two loopback round trips for a value+ // nothing reads between the load and the first sample.+ const result = await runLms(['load', modelId, '-y', ...args], { timeoutMs: LMS_LOAD_TIMEOUT_MS })+ if (!result.success) return result++ console.log(`📦 LM Studio loaded ${modelId}${args.length ? ` (${args.join(' ')})` : ''}`)+ cosEvents.emit('lmstudio:modelLoaded', { modelId })+ return { success: true }+}+/*** Unload a model from LM Studio memory* @param {string} modelId - Model identifier to unload@@ -506,6 +548,41 @@ function isAppInstalled() {return process.platform === 'darwin' && existsSync('/Applications/LM Studio.app')}+/**+ * Run one `lms` subcommand, resolving to `{ success }` or `{ success: false, error }`.+ *+ * Every `lms` call shares the same three failure shapes — the CLI is not on+ * PATH, the process timed out, or it exited non-zero — and the same rule for+ * pulling a human line out of the result (last line of stderr, else stdout).+ * They live here once so the "run \`lms bootstrap\`" instruction and the+ * error-line rule cannot be fixed for one caller and not the other.+ *+ * Resolves rather than throws (mirrors `controlOllamaServer`) so a route can+ * turn a refusal into a 502, and a measurement can record it, with the reason+ * intact.+ *+ * @param {string[]} args+ * @param {{ timeoutMs: number }} options+ */+async function runLms(args, { timeoutMs }) {+ const binary = findCommandOnPath('lms')+ if (!binary) {+ return {+ success: false,+ error: "LM Studio's \`lms\` CLI is not on PortOS's PATH. Open LM Studio once and run \`lms bootstrap\`, or use the app's Developer tab."+ }+ }+ const label = `\`lms ${args.filter((a) => !a.startsWith('-')).join(' ')}\``+ const result = await bufferedSpawn(binary, args, { timeoutMs, shell: false })+ resetCache()+ if (result.timedOut) return { success: false, error: `${label} timed out after ${Math.round(timeoutMs / 1000)}s` }+ if (!result.success) {+ const detail = result.error?.message || String(result.stderr || result.stdout || '').trim().split(/\r?\n/).pop()+ return { success: false, error: detail || `${label} exited with code ${result.code}` }+ }+ return { success: true }+}+/*** Start or stop LM Studio's local OpenAI-compatible server via its own `lms` CLI.*@@ -523,20 +600,8 @@ async function controlServer(action) {if (action !== 'start' && action !== 'stop') {return { success: false, error: `Unknown LM Studio action: ${action}` }}- const binary = findCommandOnPath('lms')- if (!binary) {- return {- success: false,- error: "LM Studio's `lms` CLI is not on PortOS's PATH. Open LM Studio once and run `lms bootstrap`, or use the app's Developer tab."- }- }- const result = await bufferedSpawn(binary, ['server', action], { timeoutMs: LMS_CONTROL_TIMEOUT_MS, shell: false })- resetCache()- if (result.timedOut) return { success: false, error: `\`lms server ${action}\` timed out` }- if (!result.success) {- const detail = result.error?.message || String(result.stderr || result.stdout || '').trim().split(/\r?\n/).pop()- return { success: false, error: detail || `\`lms server ${action}\` exited with code ${result.code}` }- }+ const result = await runLms(['server', action], { timeoutMs: LMS_CONTROL_TIMEOUT_MS })+ if (!result.success) return resultconsole.log(`📦 LM Studio server ${action === 'start' ? 'started' : 'stopped'}`)return { success: true }}@@ -862,6 +927,7 @@ export {getAvailableModels,downloadModel,loadModel,+ loadModelWithArgs,unloadModel,getRecommendedThinkingModel,quickCompletion,diff --git a/server/services/lmStudioManager.test.js b/server/services/lmStudioManager.test.jsindex 4f38fb833a..3673d2af02 100644--- a/server/services/lmStudioManager.test.js+++ b/server/services/lmStudioManager.test.js@@ -3,6 +3,17 @@ import os from 'os';import path from 'path';import fs from 'fs';+// `lms` drives the tuned load. Stubbed rather than shelled out to: the tests must+// stay hermetic, and a real `lms load` would page a multi-gigabyte GGUF into the+// developer's LM Studio.+const lmsSpawn = vi.fn();+vi.mock('../lib/bufferedSpawn.js', () => ({ bufferedSpawn: (...args) => lmsSpawn(...args) }));+const lmsBinary = { path: '/usr/local/bin/lms' };+vi.mock('../lib/processEnv.js', async (importOriginal) => ({+ ...(await importOriginal()),+ findCommandOnPath: (cmd) => (cmd === 'lms' ? lmsBinary.path : null),+}));+let tempDir;let originalModelsDir;let originalUrl;@@ -16,6 +27,8 @@ beforeEach(() => {// network-free and deterministic regardless of whether LM Studio is running.originalUrl = process.env.LM_STUDIO_URL;process.env.LM_STUDIO_URL = 'http://127.0.0.1:1';+ lmsSpawn.mockReset().mockResolvedValue({ success: true, code: 0, stdout: '', stderr: '' });+ lmsBinary.path = '/usr/local/bin/lms';vi.resetModules();});@@ -244,3 +257,50 @@ describe('lmStudioManager evictDownloadedQuant', () => {.toMatchObject({ success: true, missing: true });});});++// LM Studio picks context length, GPU offload, and parallelism when a model is+// LOADED. No request field moves them and the REST load endpoint takes only a+// model id, so `lms load` is the only transport a tuned measurement has.+describe('lmStudioManager.loadModelWithArgs', () => {+ it('passes the tuning flags to lms load, auto-approving the model picker', async () => {+ const { loadModelWithArgs } = await import('./lmStudioManager.js');+ const result = await loadModelWithArgs('publisher/model', ['--context-length', '8192']);++ expect(result).toEqual({ success: true });+ const [binary, args] = lmsSpawn.mock.calls[0];+ expect(binary).toBe('/usr/local/bin/lms');+ expect(args).toEqual(['load', 'publisher/model', '-y', '--context-length', '8192']);+ });++ // Reporting success for a load that never happened would file the reading+ // under a tuning the model was not running.+ it('surfaces the CLI failure line rather than a generic error', async () => {+ lmsSpawn.mockResolvedValue({ success: false, code: 1, stdout: '', stderr: 'Model does not fit at that context length\n' });+ const { loadModelWithArgs } = await import('./lmStudioManager.js');+ expect(await loadModelWithArgs('publisher/model', ['--context-length', '1048576']))+ .toEqual({ success: false, error: 'Model does not fit at that context length' });+ });++ it('reports the timeout instead of hanging the measurement', async () => {+ lmsSpawn.mockResolvedValue({ timedOut: true });+ const { loadModelWithArgs } = await import('./lmStudioManager.js');+ const result = await loadModelWithArgs('publisher/model', []);+ expect(result.success).toBe(false);+ expect(result.error).toContain('timed out');+ });++ it('refuses when the lms CLI is not installed, naming the command that fixes it', async () => {+ lmsBinary.path = null;+ const { loadModelWithArgs } = await import('./lmStudioManager.js');+ const result = await loadModelWithArgs('publisher/model', []);+ expect(result.success).toBe(false);+ expect(result.error).toContain('lms bootstrap');+ expect(lmsSpawn).not.toHaveBeenCalled();+ });++ it('refuses without shelling out when no model was named', async () => {+ const { loadModelWithArgs } = await import('./lmStudioManager.js');+ expect(await loadModelWithArgs('', [])).toEqual({ success: false, error: 'No model was named to load.' });+ expect(lmsSpawn).not.toHaveBeenCalled();+ });+});diff --git a/server/services/localLlmPlayground.js b/server/services/localLlmPlayground.jsindex 40e66594b3..de6e9f532e 100644--- a/server/services/localLlmPlayground.js+++ b/server/services/localLlmPlayground.js@@ -122,8 +122,11 @@ async function streamChatCompletion({ provider, backend, modelId, prompt, systemmessages: buildMessages({ systemPrompt, prompt }),temperature,maxTokens,- // The caller's knobs win over the provider default: an assessment measuring- // a specific `num_ctx` must not silently be run at the provider's.+ // The caller's knobs win over the provider default, so a caller measuring a+ // specific value is never silently run at the provider's. (Ollama is not one+ // of those callers: its OpenAI-compatible endpoint drops unknown body fields,+ // so its context window is a daemon-restart knob — see the transport rule in+ // `lib/localModelTuning.js` and `ollamaManager.ensureContextWindow`.)extraBody: { ...(Number(provider.numCtx) > 0 ? { num_ctx: Number(provider.numCtx) } : {}), ...extraBody },signal,onChunk,diff --git a/server/services/localModelAssessments.js b/server/services/localModelAssessments.jsindex 565be9ebf9..5debaae25f 100644--- a/server/services/localModelAssessments.js+++ b/server/services/localModelAssessments.js@@ -73,6 +73,9 @@ import {import {compareTunings,describeTuning,+ launchArgs,+ launchConfig,+ launchEnv,launchTuning,normalizeTuning,requestBody,@@ -90,8 +93,12 @@ import { listModels } from './localLlm.js';import {getLoadedModels as getLoadedOllamaModels,getLastInstalledModelsError as getOllamaListError,+ restartWithEnv as restartOllamaWithEnv,} from './ollamaManager.js';-import { getLastListError as getLmStudioListError } from './lmStudioManager.js';+import {+ getLastListError as getLmStudioListError,+ loadModelWithArgs as loadLmStudioModelWithArgs,+} from './lmStudioManager.js';// Re-exported so the store split stays an implementation detail for callers that// only ever wanted "the assessments feature".@@ -361,6 +368,46 @@ export async function runAssessment({ backend, modelId, contextTokens = DEFAULT_}}+// Every applier reports the same three things — did it take effect, why not,+// and what the daemon is running now — out of a manager result that spells+// success differently (`applied` vs `success`). Normalizing here keeps each+// entry below to the one line that is actually runtime-specific.+const toApplication = (ok, error, fallbackReason) => ({+ applied: ok === true,+ reason: ok === true ? null : (error || fallbackReason),+ config: null,+});++/**+ * Put a runtime's launch knobs into effect, each by the only transport that+ * reaches it: llama.cpp relaunches with a new command line, Ollama restarts+ * carrying new environment, LM Studio reloads the model through `lms load`.+ *+ * Keyed by BACKEND rather than by transport because the applier is "who owns+ * this daemon" — the manager that knows how to stop it, what to put back if the+ * new configuration will not start, and whether the user registered it to launch+ * at login. A runtime with no entry has no launch path, which is why+ * `lib/localModelTuning.js` declares no launch knob for one; this refusal is the+ * backstop for a knob added without one, so the reading is filed as "not+ * applied" instead of silently attributed to a tuning that never ran.+ */+const LAUNCH_APPLIERS = {+ llama: ({ launch }) => relaunchLlamaServerWithTuning(launchConfig('llama', launch)),+ ollama: ({ launch }) => restartOllamaWithEnv(launchEnv('ollama', launch))+ .then((r) => toApplication(r.applied, r.error, `Ollama could not be restarted with that tuning (${r.reason})`)),+ lmstudio: ({ modelId, launch }) => loadLmStudioModelWithArgs(modelId, launchArgs('lmstudio', launch))+ .then((r) => toApplication(r.success, r.error, 'LM Studio could not reload the model with that tuning')),+};++async function applyLaunchTuning({ backend, modelId, launch }) {+ const applier = LAUNCH_APPLIERS[backend];+ if (!applier) {+ return { applied: false, reason: `PortOS does not start the ${backend} runtime, so it cannot apply launch tuning`, config: null };+ }+ return applier({ backend, modelId, launch })+ .catch((err) => ({ applied: false, reason: err?.message || 'relaunch failed', config: null }));+}+// The measurement itself, with the accelerator already claimed by the caller// above. Split out so the claim's release is one `finally` around one call// rather than wrapped around a 100-line body.@@ -369,20 +416,17 @@ async function measureModel({ backend, modelId, contexts, tuning, signal, emit }const tuningKey = tuningSignature(normalizedTuning);const tuningLabel = describeTuning(backend, normalizedTuning);- // Launch knobs go on the daemon's command line BEFORE the first sample, or- // the measurement would describe the previous configuration while claiming- // the new one. `applied: false` is recorded rather than swallowed — a reading- // taken under a tuning PortOS could not apply must not be filed as evidence- // for that tuning.+ // Launch knobs reach the daemon BEFORE the first sample, or the measurement+ // would describe the previous configuration while claiming the new one.+ // `applied: false` is recorded rather than swallowed — a reading taken under a+ // tuning PortOS could not apply must not be filed as evidence for that tuning.const launch = launchTuning(backend, normalizedTuning);- const applicable = { ...launch, ...requestBody(backend, normalizedTuning) };+ const request = requestBody(backend, normalizedTuning);const tuningApplication = Object.keys(launch).length > 0- ? await relaunchLlamaServerWithTuning(launch).catch((err) => ({ applied: false, reason: err?.message || 'relaunch failed', config: null }))- // `null`, NOT `true`, when nothing here is settable: an all-`record` tuning- // (LM Studio, MTPLX, vLLM) was never applied by PortOS in any sense, and- // reporting it as applied is the exact claim `lib/localModelTuning.js`- // forbids. `true` is reserved for knobs that actually reached the daemon.- : { applied: Object.keys(applicable).length > 0 ? true : null, reason: null, config: null };+ ? await applyLaunchTuning({ backend, modelId, launch })+ // `null`, NOT `true`, when nothing was tuned. `true` when the only knobs set+ // ride on the request body, which needs no daemon restart to take effect.+ : { applied: Object.keys(request).length > 0 ? true : null, reason: null, config: null };const endpoint = isEndpointRuntime(backend) ? await runtimeEndpoint(backend) : null;if (isEndpointRuntime(backend) && !endpoint) {@@ -428,7 +472,7 @@ async function measureModel({ backend, modelId, contexts, tuning, signal, emit }temperature: 0,maxTokens: SAMPLE_MAX_TOKENS,timeoutMs: SAMPLE_TIMEOUT_MS,- extraBody: requestBody(backend, normalizedTuning),+ extraBody: request,signal,};const result = await (endpointdiff --git a/server/services/localModelAssessments.test.js b/server/services/localModelAssessments.test.jsindex e5e6782fc7..a1b07fced7 100644--- a/server/services/localModelAssessments.test.js+++ b/server/services/localModelAssessments.test.js@@ -49,16 +49,25 @@ vi.mock('./localLlm.js', () => ({ listModels: (...args) => listModels(...args) }const getLoadedModels = vi.fn();const getOllamaListError = vi.fn();const ollamaVersion = vi.fn(async () => '0.0.0-test');+// Ollama's tuning knobs are daemon environment, so applying one restarts the+// daemon. Default to "it worked" and let a test override to assert the refusal path.+const restartOllamaWithEnv = vi.fn(async () => ({ applied: true, reason: 'restarted' }));vi.mock('./ollamaManager.js', () => ({getLoadedModels: (...args) => getLoadedModels(...args),getLastInstalledModelsError: () => getOllamaListError(),// Recorded with each assessment so a backend UPDATE can later be detected as// staleness — see localModelAssessmentStore.captureEnvironment.getVersion: (...args) => ollamaVersion(...args),+ restartWithEnv: (...args) => restartOllamaWithEnv(...args),}));const getLmStudioListError = vi.fn();-vi.mock('./lmStudioManager.js', () => ({ getLastListError: () => getLmStudioListError() }));+// LM Studio's knobs are load-time, so applying one reloads the model via `lms load`.+const loadLmStudioModelWithArgs = vi.fn(async () => ({ success: true }));+vi.mock('./lmStudioManager.js', () => ({+ getLastListError: () => getLmStudioListError(),+ loadModelWithArgs: (...args) => loadLmStudioModelWithArgs(...args),+}));// A fixed, generous memory budget so the memory axis is deterministic.vi.mock('../lib/localMemory.js', () => ({ getAvailableMemoryGb: async () => 64 }));@@ -92,6 +101,8 @@ beforeEach(() => {getLlamaServerEndpoint.mockReset().mockResolvedValue('http://127.0.0.1:5568/v1');getAllProviders.mockReset().mockResolvedValue([]);relaunchLlamaServerWithTuning.mockReset().mockResolvedValue({ applied: true, reason: null, config: null });+ restartOllamaWithEnv.mockReset().mockResolvedValue({ applied: true, reason: 'restarted' });+ loadLmStudioModelWithArgs.mockReset().mockResolvedValue({ success: true });});describe('buildSamplePrompt', () => {@@ -691,10 +702,49 @@ describe('tuning', () => {expect(await svc.loadAssessments()).toHaveLength(2);});- it('sends a request-applied knob with the measurement', async () => {+ // Ollama's OpenAI-compatible endpoint drops unknown body fields, so the only+ // spelling of a context window is the daemon's environment. Sending one in the+ // body would look applied and change nothing.+ it('restarts Ollama with the tuning env instead of putting it in the request body', async () => {runLocalLlmTest.mockResolvedValue(okRun());- await svc.runAssessment({ backend: 'ollama', modelId: 'example-model:7b', contextTokens: [512], tuning: { numCtx: 8192 } });- expect(runLocalLlmTest).toHaveBeenCalledWith(expect.objectContaining({ extraBody: { num_ctx: 8192 } }));+ const result = await svc.runAssessment({+ backend: 'ollama', modelId: 'example-model:7b', contextTokens: [512], tuning: { numCtx: 8192, flashAttention: true },+ });+ expect(restartOllamaWithEnv).toHaveBeenCalledWith({ OLLAMA_CONTEXT_LENGTH: '8192', OLLAMA_FLASH_ATTENTION: '1' });+ expect(runLocalLlmTest).toHaveBeenCalledWith(expect.objectContaining({ extraBody: {} }));+ expect(result.tuningApplied).toBe(true);+ });++ it('records the reason when Ollama could not be restarted with the tuning', async () => {+ runLocalLlmTest.mockResolvedValue(okRun());+ restartOllamaWithEnv.mockResolvedValueOnce({ applied: false, reason: 'stop-failed', error: 'Ollama would not stop' });+ const result = await svc.runAssessment({+ backend: 'ollama', modelId: 'example-model:7b', contextTokens: [512], tuning: { numCtx: 8192 },+ });+ expect(result.tuningApplied).toBe(false);+ expect(result.tuningNotApplied).toBe('Ollama would not stop');+ });++ // LM Studio picks context/offload/parallelism when the model LOADS, so a tuned+ // reading has to reload it through `lms load` first.+ it('reloads the LM Studio model with the tuning flags', async () => {+ runLocalLlmTest.mockResolvedValue(okRun());+ const result = await svc.runAssessment({+ backend: 'lmstudio', modelId: 'example-model:7b', contextTokens: [512], tuning: { contextLength: 8192, gpuOffload: 0.5 },+ });+ expect(loadLmStudioModelWithArgs).toHaveBeenCalledWith('example-model:7b', ['--context-length', '8192', '--gpu', '0.5']);+ expect(result.tuningApplied).toBe(true);+ expect(result.tuningLabel).toBe('Context length 8k · GPU offload 0.5');+ });++ it('records the reason when LM Studio refused the tuned load', async () => {+ runLocalLlmTest.mockResolvedValue(okRun());+ loadLmStudioModelWithArgs.mockResolvedValueOnce({ success: false, error: 'Model does not fit at that context length' });+ const result = await svc.runAssessment({+ backend: 'lmstudio', modelId: 'example-model:7b', contextTokens: [512], tuning: { contextLength: 1048576 },+ });+ expect(result.tuningApplied).toBe(false);+ expect(result.tuningNotApplied).toBe('Model does not fit at that context length');});it('puts llama.cpp launch knobs on the command line before the first sample', async () => {@@ -722,18 +772,28 @@ describe('tuning', () => {expect(result.tuningNotApplied).toBe('llama-server is not running');});- // A tuning made entirely of `record` knobs was never applied by PortOS in any- // sense — `true` there is the exact claim lib/localModelTuning.js forbids, and- // `false` would imply something went wrong. `null` is the honest answer.- it('records tuningApplied as null when there is nothing for PortOS to apply', async () => {+ // An untuned run applied nothing — `true` there is the exact claim+ // lib/localModelTuning.js forbids, and `false` would imply something went+ // wrong. `null` is the honest answer.+ it('records tuningApplied as null when there was nothing to apply', async () => {runLocalLlmTest.mockResolvedValue(okRun());const untuned = await svc.runAssessment({ backend: 'ollama', modelId: 'example-model:7b', contextTokens: [512] });expect(untuned.tuningApplied).toBeNull();- const recordOnly = await svc.runAssessment({- backend: 'lmstudio', modelId: 'example-model:7b', contextTokens: [512], tuning: { contextLength: 8192 },+ expect(restartOllamaWithEnv).not.toHaveBeenCalled();+ });++ // A runtime with no launch path must not silently swallow a knob: the catalog+ // offers none for MTPLX/vLLM today, and if one is ever added without a+ // transport the reading has to say it was not applied.+ it('refuses launch tuning for a runtime PortOS does not start', async () => {+ probeOpenAiModels.mockResolvedValue({ reachable: true, models: ['a-model'], error: null });+ runEndpointLlmTest.mockResolvedValue(okRun());+ const result = await svc.runAssessment({+ backend: 'mtplx', modelId: 'a-model', contextTokens: [512], tuning: { maxKvSize: 8192 },});- expect(recordOnly.tuningApplied).toBeNull();- expect(recordOnly.tuningLabel).toBe('Context length 8k');+ // Retired from the catalog, so it normalizes away entirely — no claim made.+ expect(result.tuningApplied).toBeNull();+ expect(result.tuningKey).toBe('');});it('never relaunches llama-server for an untuned run', async () => {diff --git a/server/services/ollamaManager.js b/server/services/ollamaManager.jsindex db196bb17f..7cad9dcdb1 100644--- a/server/services/ollamaManager.js+++ b/server/services/ollamaManager.js@@ -33,7 +33,9 @@ import {import { buildHfAuthHeaders, buildHfResolveUrl, HF_API } from '../lib/huggingfaceLora.js'import { isEmbeddingModel } from '../lib/localModelHeuristics.js'import { commandExists } from '../lib/commandExists.js'-import { OLLAMA_AGENT_MIN_CONTEXT, OLLAMA_CONTEXT_ENV_VAR, withOllamaContextEnv } from '../lib/ollamaContext.js'+import {+ OLLAMA_AGENT_MIN_CONTEXT, resolveOllamaContextLength, withOllamaContextEnv+} from '../lib/ollamaContext.js'import { compareSemver } from '../lib/versionUtils.js'import { isSafeHfRepoRelativePath } from '../lib/hfCache.js'@@ -117,6 +119,34 @@ let appliedContextLength = null// treated as "no evidence" so an unavailable process probe cannot create a// restart loop.let appliedDaemonIdentity = null+// Signature of the FULL launch env the live daemon was started with, so a second+// request for the same tuning is a no-op instead of another restart. A sweep+// measures every model under one tuning; without this it would stop, start, and+// cold-load the daemon once per model, and every first sample would be timing a+// fresh page-in rather than the model.+let appliedLaunchEnv = null++const envSignature = (env) => Object.entries(env || {})+ .sort(([a], [b]) => a.localeCompare(b))+ .map(([k, v]) => `${k}=${v}`)+ .join(',')++/**+ * Record the launch env the daemon that is up right now was started with.+ *+ * `identity` is the process identity to latch against — a spawned child's PID,+ * or the probed identity of a service PortOS restarted. Both latches are set+ * together and cleared together, so "which env" and "which process" can never+ * describe two different daemons.+ */+function rememberAppliedEnv(env, identity) {+ appliedLaunchEnv = envSignature(env)+ // A restart that named no window leaves Ollama on its VRAM-based auto-pick,+ // which is not a window PortOS can claim — so the context latch is cleared+ // rather than crediting the new process with the old one's window.+ appliedContextLength = resolveOllamaContextLength(null, env || {})+ appliedDaemonIdentity = identity || null+}const status = { lastError: null, lastSuccessAt: null, consecutiveErrors: 0 }@@ -221,9 +251,10 @@ async function checkOllamaAvailable(forceRefresh = false) {} catch (err) {isAvailable = 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.+ // be re-checked rather than credited with that window or that launch env.appliedContextLength = nullappliedDaemonIdentity = null+ appliedLaunchEnv = nullstatus.lastError = err.messagestatus.consecutiveErrors++lastCheckAt = now@@ -272,24 +303,30 @@ async function terminateManagedProcess() {/*** Start the Ollama HTTP server via the local CLI.*- * `contextLength` (when set) becomes the daemon-wide `OLLAMA_CONTEXT_LENGTH`.- * This is the only lever that reaches Ollama-backed *agent harnesses* — Claude- * Code and OpenCode talk to Ollama directly, so PortOS can't attach a- * per-request `num_ctx` the way the toolkit runner does for `api` providers.- * @param {{ contextLength?: number|null }} [options]+ * `env` carries every launch-time knob PortOS can hand the daemon —+ * `OLLAMA_CONTEXT_LENGTH`, `OLLAMA_FLASH_ATTENTION`, `OLLAMA_KV_CACHE_TYPE`, … —+ * because the process environment is the ONLY lever that reaches them. Claude+ * Code and OpenCode talk to Ollama directly, and its OpenAI-compatible endpoint+ * drops unknown body fields, so PortOS cannot attach a per-request `num_ctx` the+ * way the toolkit runner does for `api` providers. There is deliberately no+ * second, context-only parameter: two spellings of one variable would need a+ * precedence rule, and the latches below would have to read both.+ *+ * @param {{ env?: Record<string, string> }} [options]* @returns {Promise<{ success: boolean, running?: boolean, alreadyRunning?: boolean, pid?: number, error?: string }>}*/-async function startServer({ contextLength = null } = {}) {+async function startServer({ env = null } = {}) {if (await checkOllamaAvailable(true)) {return { success: true, running: true, alreadyRunning: true }}+ const contextLength = resolveOllamaContextLength(null, env || {})let spawnError = nullconst stderr = []const child = spawn('ollama', ['serve'], {detached: true,stdio: ['ignore', 'ignore', 'pipe'],- env: withOllamaContextEnv(process.env, contextLength)+ env: { ...process.env, ...(env || {}) }})rememberManagedProcess(child)child.stderr?.on('data', (chunk) => {@@ -301,8 +338,7 @@ async function startServer({ contextLength = null } = {}) {const running = await waitForAvailability(true, START_TIMEOUT_MS)if (running) {- appliedContextLength = contextLength || null- appliedDaemonIdentity = contextLength ? String(child.pid) : null+ rememberAppliedEnv(env, String(child.pid))const window = contextLength ? ` (context ${contextLength})` : ''console.log(`▶️ Started Ollama server (pid ${child.pid})${window}`)return { success: true, running: true, pid: child.pid }@@ -541,11 +577,9 @@ async function getRuntimeContextLength(selectedModel = null) {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 }+ const env = withOllamaContextEnv({}, target)if (!(await checkOllamaAvailable(true))) {- const started = await startServer({ contextLength: target })- return started.success- ? { applied: true, reason: 'started', contextLength: target }- : { applied: false, reason: 'start-failed', contextLength: target, error: started.error }+ return { ...(await restartWithEnv(env)), contextLength: target }}if (Number(appliedContextLength) >= target) {@@ -559,8 +593,7 @@ async function ensureContextWindow(contextLength, selectedModel = null) {if (!appliedDaemonIdentity || !currentIdentity || currentIdentity === appliedDaemonIdentity) {return { applied: false, reason: 'already-applied', contextLength: target, runtimeContextLength: appliedContextLength }}- appliedContextLength = null- appliedDaemonIdentity = null+ rememberAppliedEnv(null, null)}// `runtime == null` means nothing is resident, which is the NORMAL idle state@@ -576,53 +609,51 @@ async function ensureContextWindow(contextLength, selectedModel = null) {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`,- // which un-registers it. Restart it in place instead (see restartServiceWithContext).- const service = await getServiceStatus().catch(() => null)- if (service?.runAtStartup) {- const viaService = await restartServiceWithContext(service, target)- return { ...viaService, contextLength: target, runtimeContextLength: runtime }- }-- const stopped = await stopServer()- if (!stopped.success) {- return { applied: false, reason: 'stop-failed', contextLength: target, runtimeContextLength: runtime, error: stopped.error }- }- const started = await startServer({ contextLength: target })- return started.success- ? { applied: true, reason: 'restarted', contextLength: target, runtimeContextLength: runtime }- : { applied: false, reason: 'start-failed', contextLength: target, runtimeContextLength: runtime, error: started.error }+ // The restart ladder itself — including the rule that a launch-at-login daemon+ // is restarted in place rather than un-registered — lives in `restartWithEnv`.+ // The checks ABOVE are what is specific to a context window: a resident model+ // already big enough, and the >= latch that keeps an agent spawn from bouncing+ // the daemon. Everything below was the same ladder written twice.+ return { ...(await restartWithEnv(env)), contextLength: target, runtimeContextLength: runtime }}/**- * Restart a launch-at-login-registered Ollama at `contextLength`, WITHOUT+ * Restart a launch-at-login-registered Ollama carrying `env`, WITHOUT* un-registering it.** macOS: `launchctl setenv` writes into the user's launchd domain, which every- * job launched afterwards inherits — so setting it and then- * `brew services restart ollama` carries the window into a plist PortOS cannot- * edit (Homebrew regenerates it from the formula on every start). The variable- * is scoped to Ollama's behavior, so exporting it session-wide is harmless.+ * job launched afterwards inherits — so setting the variables and then+ * `brew services restart ollama` carries them into a plist PortOS cannot edit+ * (Homebrew regenerates it from the formula on every start). The variables are+ * scoped to Ollama's behavior, so exporting them session-wide is harmless.** Linux: the equivalent is a `systemctl edit ollama` drop-in, which needs root.* PortOS reports what to do rather than tearing the unit down to work around it.+ *+ * @param {{ manager: string }} service+ * @param {Record<string, string>} env*/-async function restartServiceWithContext(service, contextLength) {+async function restartServiceWithEnv(service, env) {+ const entries = Object.entries(env || {})+ if (entries.length === 0) return { applied: false, reason: 'nothing-to-apply' }+if (service.manager !== 'homebrew') {+ const lines = entries.map(([k, v]) => `Environment="${k}=${v}"`).join(' ')return {applied: false,reason: 'service-managed',- error: `Ollama runs as a ${service.manager} service, which PortOS can't hand a context window. ` +- `Add one with: sudo systemctl edit ollama → [Service] Environment="${OLLAMA_CONTEXT_ENV_VAR}=${contextLength}", then restart it.`+ error: `Ollama runs as a ${service.manager} service, which PortOS can't hand launch settings. ` ++ `Add them with: sudo systemctl edit ollama → [Service] ${lines}, then restart it.`}}const controller = await getServiceController()- const setenv = await execFileAsync('launchctl', ['setenv', OLLAMA_CONTEXT_ENV_VAR, String(contextLength)], { timeout: SERVICE_COMMAND_TIMEOUT_MS })- .then(() => ({ success: true }))- .catch((err) => ({ success: false, error: err.stderr?.trim() || err.message }))- if (!setenv.success) return { applied: false, reason: 'setenv-failed', error: setenv.error }+ for (const [key, value] of entries) {+ const setenv = await execFileAsync('launchctl', ['setenv', key, String(value)], { timeout: SERVICE_COMMAND_TIMEOUT_MS })+ .then(() => ({ success: true }))+ .catch((err) => ({ success: false, error: err.stderr?.trim() || err.message }))+ if (!setenv.success) return { applied: false, reason: 'setenv-failed', error: setenv.error }+ }resetAvailabilityCache()const [cmd, args] = controller.restart@@ -634,12 +665,66 @@ async function restartServiceWithContext(service, contextLength) {if (!(await waitForAvailability(true, START_TIMEOUT_MS))) {return { applied: false, reason: 'restart-unreachable', error: 'Ollama restarted, but the API did not become reachable.' }}- appliedContextLength = contextLength- appliedDaemonIdentity = await getOllamaProcessIdentity()- console.log(`▶️ Restarted the Ollama ${service.manager} service at a ${contextLength}-token context window`)+ rememberAppliedEnv(env, await getOllamaProcessIdentity())+ console.log(`▶️ Restarted the Ollama ${service.manager} service with ${entries.map(([k, v]) => `${k}=${v}`).join(', ')}`)return { applied: true, reason: 'service-restarted' }}+/**+ * Restart the local Ollama daemon so it picks up `env` — the launch-time knobs+ * (`OLLAMA_FLASH_ATTENTION`, `OLLAMA_KV_CACHE_TYPE`, `OLLAMA_CONTEXT_LENGTH`, …)+ * that reach Ollama ONLY through its process environment.+ *+ * Ollama's OpenAI-compatible endpoint silently drops unknown body fields, so+ * there is no per-request spelling of any of these: a tuned measurement either+ * restarts the daemon or is measuring the previous configuration. This resolves+ * rather than throws, and reports `applied: false` with a reason when it could+ * not — the caller records that instead of filing the reading under a tuning+ * that never took effect.+ *+ * @param {Record<string, string>} env+ * @returns {Promise<{ applied: boolean, reason: string, error?: string }>}+ */+async function restartWithEnv(env) {+ const entries = Object.entries(env || {})+ if (entries.length === 0) return { applied: false, reason: 'nothing-to-apply' }++ // The daemon that is up may already BE this tuning — a sweep measures every+ // model under one knob set, and restarting per model would cold-load each one+ // and time the page-in as if it were the model's throughput. Same evidence+ // rule as the context latch: only a CHANGED process identity invalidates it,+ // because an unreadable identity is not evidence of replacement.+ if (appliedLaunchEnv !== null && appliedLaunchEnv === envSignature(env) && await checkOllamaAvailable(true)) {+ const currentIdentity = await getOllamaProcessIdentity()+ if (!appliedDaemonIdentity || !currentIdentity || currentIdentity === appliedDaemonIdentity) {+ return { applied: true, reason: 'already-applied' }+ }+ rememberAppliedEnv(null, null)+ }++ console.log(`🔧 Restarting Ollama with ${entries.map(([k, v]) => `${k}=${v}`).join(', ')}`)++ if (!(await checkOllamaAvailable(true))) {+ const started = await startServer({ env })+ return started.success+ ? { applied: true, reason: 'started' }+ : { applied: false, reason: 'start-failed', error: started.error }+ }++ // A daemon the user registered to launch at login must keep that registration:+ // `stopServer` would route through `brew services stop` / `systemctl disable`,+ // which un-registers it. Restart it in place instead.+ const service = await getServiceStatus().catch(() => null)+ if (service?.runAtStartup) return restartServiceWithEnv(service, env)++ const stopped = await stopServer()+ if (!stopped.success) return { applied: false, reason: 'stop-failed', error: stopped.error }+ const started = await startServer({ env })+ return started.success+ ? { applied: true, reason: 'restarted' }+ : { applied: false, reason: 'start-failed', error: started.error }+}+function isOllamaProvider(provider) {const endpoint = String(provider?.endpoint || '')return provider?.id === 'ollama' ||@@ -1574,6 +1659,7 @@ export {startServer,stopServer,ensureContextWindow,+ restartWithEnv,getRuntimeContextLength,startPersistentService,stopPersistentService,diff --git a/server/services/ollamaManager.test.js b/server/services/ollamaManager.test.jsindex e7d2e9a0fd..67a451f203 100644--- a/server/services/ollamaManager.test.js+++ b/server/services/ollamaManager.test.js@@ -810,6 +810,166 @@ describe('ollamaManager context window', () => {})+describe('ollamaManager.restartWithEnv', () => {+ let restorePlatform = null+ afterEach(() => { vi.unstubAllGlobals(); restorePlatform?.(); restorePlatform = null })++ // Reachability is a mutable flag so a test can model the daemon going down and+ // coming back — `restartWithEnv` reads it before and after every step.+ function stubReachable(state) {+ vi.stubGlobal('fetch', vi.fn(async (url) => {+ if (!state.reachable) throw new Error('ECONNREFUSED')+ 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) }+ }))+ }++ it('does nothing when the tuning names no environment', async () => {+ stubReachable({ reachable: true })+ const { restartWithEnv } = await loadManager()+ expect(await restartWithEnv({})).toEqual({ applied: false, reason: 'nothing-to-apply' })+ })++ // The knobs only reach Ollama through the process environment, so the whole+ // point is that they land on the child `ollama serve` — not merely that the+ // daemon came back up.+ it('hands the knobs to the daemon it starts when Ollama is down', async () => {+ const state = { reachable: false }+ stubReachable(state)+ const { spawn } = await import('../lib/childProcess.js')+ spawn.mockReset().mockImplementation(() => {+ state.reachable = true+ return { pid: 4242, stderr: { on: () => {} }, on: () => {}, unref: () => {} }+ })++ const { restartWithEnv } = await loadManager()+ const result = await restartWithEnv({ OLLAMA_FLASH_ATTENTION: '1', OLLAMA_KV_CACHE_TYPE: 'q8_0' })++ expect(result).toEqual({ applied: true, reason: 'started' })+ const [, args, options] = spawn.mock.calls[0]+ expect(args).toEqual(['serve'])+ expect(options.env).toMatchObject({ OLLAMA_FLASH_ATTENTION: '1', OLLAMA_KV_CACHE_TYPE: 'q8_0' })+ })++ // Same rule as the context-window path: raising a knob must never cost the+ // user their launch-at-login registration.+ it('restarts a homebrew service in place rather than un-registering it', async () => {+ restorePlatform = pinPlatform('darwin')+ stubReachable({ reachable: true })+ 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 { restartWithEnv } = await loadManager()+ const result = await restartWithEnv({ OLLAMA_FLASH_ATTENTION: '1', OLLAMA_KV_CACHE_TYPE: 'q4_0' })++ expect(result).toMatchObject({ applied: true, reason: 'service-restarted' })+ expect(calls).toContain('launchctl setenv OLLAMA_FLASH_ATTENTION 1')+ expect(calls).toContain('launchctl setenv OLLAMA_KV_CACHE_TYPE q4_0')+ expect(calls).toContain('brew services restart ollama')+ expect(calls.some((c) => c.includes('services stop'))).toBe(false)+ })++ // A restart that named no window leaves the daemon on its VRAM auto-pick. The+ // latch has to forget the old process's window, or the next agent spawn is+ // credited with a window nothing is holding.+ it('clears the context latch when the restart did not name a window', async () => {+ restorePlatform = pinPlatform('darwin')+ stubReachable({ reachable: true })+ 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 === 'ps') return cb(null, { stdout: '101 /usr/local/bin/ollama serve\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, restartWithEnv } = await loadManager()+ await ensureContextWindow(131072)+ await restartWithEnv({ OLLAMA_FLASH_ATTENTION: '1' })+ // Without the latch clear this returns 'already-applied' and never restarts.+ expect(await ensureContextWindow(131072)).toMatchObject({ applied: true, reason: 'service-restarted' })+ expect(restarts).toBe(3)+ })++ // A sweep measures every model under ONE tuning. Restarting per model would+ // cold-load each one and time the page-in as the model's throughput.+ it('does not restart again for a tuning the live daemon already holds', async () => {+ restorePlatform = pinPlatform('darwin')+ stubReachable({ reachable: true })+ 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 === 'ps') return cb(null, { stdout: '101 /usr/local/bin/ollama serve\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 { restartWithEnv } = await loadManager()+ const env = { OLLAMA_FLASH_ATTENTION: '1', OLLAMA_KV_CACHE_TYPE: 'q8_0' }+ await restartWithEnv(env)+ const second = await restartWithEnv({ OLLAMA_KV_CACHE_TYPE: 'q8_0', OLLAMA_FLASH_ATTENTION: '1' })++ // `applied: true` — the tuning IS in effect, which is what the caller records.+ expect(second).toEqual({ applied: true, reason: 'already-applied' })+ expect(restarts).toBe(1)+ })++ it('restarts again when the tuning differs by a single knob', async () => {+ restorePlatform = pinPlatform('darwin')+ stubReachable({ reachable: true })+ 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 === 'ps') return cb(null, { stdout: '101 /usr/local/bin/ollama serve\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 { restartWithEnv } = await loadManager()+ await restartWithEnv({ OLLAMA_KV_CACHE_TYPE: 'q8_0' })+ await restartWithEnv({ OLLAMA_KV_CACHE_TYPE: 'q4_0' })+ expect(restarts).toBe(2)+ })++ // systemd needs root for the equivalent drop-in. Reporting the exact edit beats+ // tearing the unit down to work around it.+ it('refuses a service manager it cannot hand environment to, naming the fix', async () => {+ restorePlatform = pinPlatform('linux')+ stubReachable({ reachable: true })+ execMock.impl = (cmd, args, opts, cb) => {+ const a = (args || []).join(' ')+ if (cmd === 'systemctl' && a === '--version') return cb(null, { stdout: 'systemd 250', stderr: '' })+ if (cmd === 'systemctl' && a.startsWith('is-enabled')) return cb(null, { stdout: 'enabled\n', stderr: '' })+ if (cmd === 'systemctl' && a.startsWith('is-active')) return cb(null, { stdout: 'active\n', stderr: '' })+ return cb(new Error(`unexpected exec: ${cmd} ${a}`))+ }++ const { restartWithEnv } = await loadManager()+ const result = await restartWithEnv({ OLLAMA_FLASH_ATTENTION: '1' })++ expect(result.applied).toBe(false)+ expect(result.reason).toBe('service-managed')+ expect(result.error).toContain('Environment="OLLAMA_FLASH_ATTENTION=1"')+ })+})+describe('ollamaManager context window — launch-at-login daemons', () => {let restorePlatform = nullafterEach(() => { vi.unstubAllGlobals(); restorePlatform?.(); restorePlatform = null })