Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: put the daemon back on its defaults for an untuned assessment (#4759, #4763)

[._.]/ Adam Eivyc485bd9f7c40
diff --git a/client/src/components/settings/LocalModelAssessments.jsx b/client/src/components/settings/LocalModelAssessments.jsx
index d2ed65c152..6ce491bdde 100644
--- a/client/src/components/settings/LocalModelAssessments.jsx
+++ b/client/src/components/settings/LocalModelAssessments.jsx
@@ -33,6 +33,7 @@ import useMounted from '../../hooks/useMounted';
import AssessmentSweepPanel from './AssessmentSweepPanel';
import ModelThroughputReport from './ModelThroughputReport';
import { formatContextTokens, formatDurationMs, throughputLabel } from '../../utils/formatters';
+import { tuningNoticeChip } from '../../lib/assessmentTuningNotice';
import {
getLocalLlmAssessments, runLocalLlmAssessment, deleteLocalLlmAssessment,
} from '../../services/api';
@@ -299,14 +300,10 @@ function RankedRow({ entry, runtimeLabel, onRemeasure, onDelete, onSweepTunings,
{entry.tuningLabel || 'backend defaults'}
</span>
</div>
- {/* The numbers below describe SOME OTHER configuration when the launch
- knobs never reached the daemon — say so rather than filing them
- under the tuning that was asked for. */}
- {entry.tuningApplied === false && entry.tuningNotApplied && (
- <p className="text-[11px] text-port-warning mt-0.5">
- Tuning was not applied — {entry.tuningNotApplied}. These numbers describe the configuration that was actually running.
- </p>
- )}
+ {/* No `tuningApplied === false` caveat here on purpose: a reading whose
+ configuration never reached the daemon is never RANKED. The server
+ pulls it out of `scorable` and into `excluded`, which renders the
+ reason below — see `getAssessmentReport`. */}
<p className="text-xs text-gray-400 mt-1">{entry.explanation}</p>
{entry.staleness?.stale && (
<p className="text-[11px] text-port-warning mt-0.5">
@@ -606,8 +603,8 @@ export function LocalModelAssessments() {
// A tuning that could not be applied means the verdict describes a
// different configuration — surface that at the point of the result
// rather than only in the row the user has to go find.
- if (result.tuningApplied === false && result.tuningNotApplied) {
- toast.warning(`${target.modelId}: ${verdict} — tuning not applied (${result.tuningNotApplied})`);
+ if (tuningNoticeChip(result)) {
+ toast.warning(`${target.modelId}: ${verdict} — ${tuningNoticeChip(result)} (${result.tuningNotApplied || 'reason not recorded'})`);
return;
}
toast.success(`${target.modelId}: ${verdict}`);
diff --git a/client/src/components/settings/LocalModelAssessments.test.jsx b/client/src/components/settings/LocalModelAssessments.test.jsx
index 8d8abe395b..9761b41479 100644
--- a/client/src/components/settings/LocalModelAssessments.test.jsx
+++ b/client/src/components/settings/LocalModelAssessments.test.jsx
@@ -508,7 +508,7 @@ describe('LocalModelAssessments — tuning', () => {
it('warns instead of celebrating when the tuning never reached the daemon', async () => {
runLocalLlmAssessment.mockResolvedValue({
- verdict: 'fits', tuningApplied: false, tuningNotApplied: 'llama-server is not running',
+ verdict: 'fits', tuningKey: 'ubatchSize=512', tuningApplied: false, tuningNotApplied: 'llama-server is not running',
});
const user = userEvent.setup();
render(<LocalModelAssessments />);
@@ -609,17 +609,40 @@ describe('LocalModelAssessments — one row per tuning', () => {
));
});
- it('warns on a ranked row whose tuning never reached the daemon', async () => {
+ // A reading whose configuration never reached the daemon is never RANKED —
+ // the server pulls it into `excluded` (`getAssessmentReport`), which is where
+ // the sentence has to land. Asserting it on a ranked row would pass against a
+ // hand-built fixture the server can never produce.
+ it('explains an excluded row whose tuning never reached the daemon', async () => {
getLocalLlmAssessments.mockResolvedValue(report({
- ranked: [rankedEntry({
+ excluded: [{
+ backend: 'llama',
+ modelId: 'dflash',
tuningKey: 'ubatchSize=512',
tuningLabel: 'Micro-batch size 512',
- tuningApplied: false,
- tuningNotApplied: 'llama-server is not running',
- })],
+ verdict: 'fits',
+ reason: 'measured, but the requested tuning was not applied — llama-server is not running',
+ }],
+ }));
+ render(<LocalModelAssessments />);
+ expect(await screen.findByText(/requested tuning was not applied/)).toBeInTheDocument();
+ });
+
+ // The untuned counterpart: its chip reads "backend defaults", so the sentence
+ // beside it has to name what actually failed rather than contradict the chip.
+ it('explains an excluded row the daemon could not be returned to defaults for', async () => {
+ getLocalLlmAssessments.mockResolvedValue(report({
+ excluded: [{
+ backend: 'ollama',
+ modelId: 'example-model:7b',
+ tuningKey: '',
+ tuningLabel: null,
+ verdict: 'fits',
+ reason: 'measured, but the daemon still carried an earlier tuning — Ollama would not stop',
+ }],
}));
render(<LocalModelAssessments />);
- expect(await screen.findByText(/Tuning was not applied/)).toBeInTheDocument();
+ expect(await screen.findByText(/daemon still carried an earlier tuning/)).toBeInTheDocument();
});
});
diff --git a/client/src/components/settings/ModelThroughputReport.jsx b/client/src/components/settings/ModelThroughputReport.jsx
index 4721fd750f..e35a4e6700 100644
--- a/client/src/components/settings/ModelThroughputReport.jsx
+++ b/client/src/components/settings/ModelThroughputReport.jsx
@@ -20,6 +20,7 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { Timer, Copy, Check } from 'lucide-react';
import { copyToClipboard } from '../../lib/clipboard';
+import { tuningNoticeChip } from '../../lib/assessmentTuningNotice';
import { formatContextTokens, formatDurationMs } from '../../utils/formatters';
// One rate, as text. `null` is not measured and renders as an em dash — never a
@@ -138,7 +139,7 @@ export default function ModelThroughputReport({ report, runtimeLabelFor }) {
{row.staleness?.stale && <span className="ml-1 text-port-warning">stale</span>}
{/* The numbers are real but describe a configuration nobody
asked for — say so here too, not only in the ranked list. */}
- {row.tuningApplied === false && <span className="ml-1 text-port-warning">tuning not applied</span>}
+ {tuningNoticeChip(row) && <span className="ml-1 text-port-warning">{tuningNoticeChip(row)}</span>}
</div>
</td>
<td className="px-2 py-1.5 text-right"><Rate value={row.meanTokensPerSecond} estimated={row.tokensEstimated} /></td>
diff --git a/client/src/components/settings/ModelThroughputReport.test.jsx b/client/src/components/settings/ModelThroughputReport.test.jsx
index f4ca5db9d3..48350eb81d 100644
--- a/client/src/components/settings/ModelThroughputReport.test.jsx
+++ b/client/src/components/settings/ModelThroughputReport.test.jsx
@@ -82,12 +82,24 @@ describe('ModelThroughputReport', () => {
it('flags a reading whose tuning never reached the daemon', () => {
const unapplied = row('tuned-model', {
- tuningLabel: '8k context', tuningApplied: false, tuningNotApplied: 'llama-server is not running',
+ tuningKey: 'ctxSize=8192', tuningLabel: '8k context', tuningApplied: false, tuningNotApplied: 'llama-server is not running',
});
render(<ModelThroughputReport report={report([unapplied])} />);
expect(screen.getByText('tuning not applied')).toBeInTheDocument();
});
+ // An UNTUNED reading already renders as "backend defaults", so the same
+ // warning has to say the opposite thing: the daemon could not be put BACK on
+ // defaults, and this row is not the baseline it claims to be.
+ it('flags an untuned reading the daemon could not be returned to defaults for', () => {
+ const stillTuned = row('baseline-model', {
+ tuningKey: '', tuningApplied: false, tuningNotApplied: 'Ollama would not stop',
+ });
+ render(<ModelThroughputReport report={report([stillTuned])} />);
+ expect(screen.getByText('not at defaults')).toBeInTheDocument();
+ expect(screen.queryByText('tuning not applied')).not.toBeInTheDocument();
+ });
+
it('renders nothing at all when no model has been measured', () => {
const { container } = render(<ModelThroughputReport report={report([])} />);
expect(container).toBeEmptyDOMElement();
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index c292273b51..4ba5094e27 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -94,6 +94,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `a11yKeyboard.js` | `clickableProps(handler, { role?, disabled? })` → `{ role, tabIndex, onKeyDown }` and `onActivateKeyDown(handler)` — make a non-`<button>` element with an `onClick` keyboard-accessible (Enter/Space activation, focusable, `role="button"`). Spread `clickableProps` next to the existing `onClick`. Use instead of hand-rolling `role`/`tabIndex`/`onKeyDown` on clickable `<div>`/`<span>`/`<li>`. Also the shared predicate every app-global key handler consults: `shouldIgnoreGlobalKey(event, { enabledInDialog?, ignoreRepeat?, allowChords? })` — the single "must this handler stand down?" answer (editable target, native Space button activation, ⌘/Ctrl/Alt chord, OS auto-repeat, open `aria-modal` dialog), used by `useKeyboardShortcuts`, `useKeyCapture` AND the voice widget's push-to-talk hotkey so their guard lists can't drift. Add a new guard there, not at one caller. Its parts are exported too: `isEditableTarget(el)`, `isButtonActivation(event)` (true when Space would natively activate the focused button) and `isPressKey(event)` (Enter or Space by either `key` or `code`). Plus `noPointerFocusSurfaceProps` — spread on the ROOT of a surface that owns a key globally (a Space-scored drill, the Morse keyer, RapidReader, the OpenWorld HUD); one capture-phase handler stops a mouse click anywhere inside from parking focus on a button and taking that key over via native activation, covering controls added later too. |
| `appIdentity.js` | `PORTOS_APP_ID` — stable id of the baseline PortOS app (mirrors `server/lib/appIdentity.js`). Dependency-free so a module reachable from a node-env server test (e.g. `components/apps/constants.js`) can identify PortOS without importing `services/apiCore.js`, which pulls in React via `ui/Toast`. `apiCore.js` re-exports it, so `import { PORTOS_APP_ID } from '../services/api'` still works. |
| `applyManuscriptEdits.js` | `applyEditsToContent(content, edits, anchorQuote)` — PREVIEW-ONLY client mirror of the server's accept splice (`server/services/pipeline/manuscriptFix.js`): locate each `find` (nearest the anchor when recurring), drop overlaps, replace bottom-up. Powers the Manuscript editor's whole-manuscript impact preview. |
+| `assessmentTuningNotice.js` | `tuningNoticeChip(entry)` — the short form of how a measured local-model assessment says its launch configuration did NOT take effect. `tuningApplied === false` covers two opposite cases and `tuningKey` separates them: a TUNED run whose knobs never reached the daemon (`tuning not applied`), versus an UNTUNED run PortOS could not put back on backend defaults (`not at defaults`) — #4759. Shared by `ModelThroughputReport.jsx`'s table cell and `LocalModelAssessments.jsx`'s result toast; the long form is the server's exclusion reason in `getAssessmentReport`. |
| `audioRecorder.js` | `startMemoRecording()` → `{ stream, stop, cancel }` handle whose `stop()` resolves to `{ audioBase64, mimeType, peak, durationMs }` (16 kHz mono WAV, base64); the live `stream` lets a tuner tap the same mic. `createStreamAnalyser(stream, { fftSize })` → `{ analyser, context, close }` taps an `AnalyserNode` off an existing stream (no second getUserMedia). Plus `blobToWav16k`, `encodePcmToWav`, `pickRecordingMimeType`, `arrayBufferToBase64`. Standalone one-shot memo capture for catalog voice ingest — NOT the live voice-agent recorder in `services/voiceClient.js`. |
| `bareUrl.js` | `parseBareUrl(text)` — the normalized URL when a capture's entire text is a URL, else null. Client mirror of the authoritative `server/lib/bareUrl.js` (parity enforced by `server/lib/bareUrl.mirror.test.js`), so the brain capture boxes preview the exact filing decision the server will make. Use this — not the looser `utils/urlNormalize.js` `isUrl` — anywhere the answer must match the server. |
| `youtubeUrl.js` | `isYoutubeVideoUrl(text)` / `youtubeVideoId(url)` — single-video YouTube URL detection. Client mirror of `YOUTUBE_INGEST_URL_RE` in `server/services/youtubeIngest.js` (behavioral parity pinned by `server/lib/youtubeUrl.mirror.test.js`); deliberately excludes playlists and channels. Quick Capture uses it to swap to the ingest submit path and reveal the ingest options panel. Also `INGEST_OPTIONS` — the single table of the three ingest artifacts (`key` / `settingKey` / `fallback` / `label` / `hint`) — plus `defaultIngestOptions()` and `ingestOptionsFromSettings(settings)`. Everything that enumerates the switches derives from that table; add an artifact there, not at each call site. |
diff --git a/client/src/lib/assessmentTuningNotice.js b/client/src/lib/assessmentTuningNotice.js
new file mode 100644
index 0000000000..0bb8438605
--- /dev/null
+++ b/client/src/lib/assessmentTuningNotice.js
@@ -0,0 +1,26 @@
+/**
+ * How a measured local-model assessment describes a launch configuration that
+ * did NOT take effect.
+ *
+ * `tuningApplied === false` covers two different failures, and they read as
+ * opposite things to the person looking at the row:
+ *
+ * - a TUNED run whose knobs never reached the daemon — the numbers describe
+ * some other configuration, not the one in the label;
+ * - an UNTUNED run PortOS could not put back on backend defaults, because the
+ * daemon was still carrying the previous run's tuning. Its label already
+ * says "backend defaults", so "tuning was not applied" reads as a
+ * contradiction unless the copy names what actually happened.
+ *
+ * `tuningKey` is what separates them: `''` is the untuned run.
+ *
+ * This is the SHORT form, for a dense table cell or a toast suffix. The full
+ * sentence for a surface with room to say it is the server-side exclusion reason
+ * in `getAssessmentReport` — keep the two in step.
+ *
+ * @returns {string|null} `null` when nothing is wrong with the reading.
+ */
+export function tuningNoticeChip(entry) {
+ if (entry?.tuningApplied !== false) return null;
+ return entry?.tuningKey ? 'tuning not applied' : 'not at defaults';
+}
diff --git a/client/src/lib/assessmentTuningNotice.test.js b/client/src/lib/assessmentTuningNotice.test.js
new file mode 100644
index 0000000000..a970ed28e6
--- /dev/null
+++ b/client/src/lib/assessmentTuningNotice.test.js
@@ -0,0 +1,31 @@
+import { describe, it, expect } from 'vitest';
+import { tuningNoticeChip } from './assessmentTuningNotice';
+
+describe('tuningNoticeChip', () => {
+ it('says nothing for a reading whose configuration took effect', () => {
+ expect(tuningNoticeChip({ tuningApplied: true, tuningKey: 'ubatchSize=512' })).toBeNull();
+ });
+
+ // `null` is "there was nothing to apply" — the daemon is at backend defaults
+ // and the row is accurate, so a warning here would be noise.
+ it('says nothing when there was nothing to apply', () => {
+ expect(tuningNoticeChip({ tuningApplied: null, tuningKey: '' })).toBeNull();
+ });
+
+ it('names the requested tuning as unapplied for a tuned run', () => {
+ expect(tuningNoticeChip({ tuningApplied: false, tuningKey: 'ubatchSize=512' })).toBe('tuning not applied');
+ });
+
+ // The untuned row already reads "backend defaults". "Tuning was not applied"
+ // there contradicts the label instead of explaining it — the failure is that
+ // the daemon could not be put BACK on defaults.
+ it('names the leftover tuning for an untuned run that could not be cleared', () => {
+ expect(tuningNoticeChip({ tuningApplied: false, tuningKey: '' })).toBe('not at defaults');
+ });
+
+ // The chip is a table's only room, so it must appear even when the manager
+ // gave no reason — otherwise a suspect row reads as a clean one.
+ it('still chips a failed application that recorded no reason', () => {
+ expect(tuningNoticeChip({ tuningApplied: false, tuningKey: '', tuningNotApplied: null })).toBe('not at defaults');
+ });
+});
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index 1936c2fa3d..c3e4e302b5 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -68,6 +68,7 @@ export * from './goalFeatureMap.js';
export * from './a11yKeyboard.js';
export * from './appIdentity.js';
export * from './applyManuscriptEdits.js';
+export * from './assessmentTuningNotice.js';
export * from './audioRecorder.js';
export * from './bareUrl.js';
export * from './boundedMap.js';
diff --git a/server/lib/localModelTuning.js b/server/lib/localModelTuning.js
index 0fc5dbba05..c23a8e463d 100644
--- a/server/lib/localModelTuning.js
+++ b/server/lib/localModelTuning.js
@@ -89,6 +89,23 @@
* why `normalizeTuning` drops empty input instead of filling it in, and why the
* signature of an untuned run is `''` (so its store key is byte-identical to the
* pre-tuning key, and existing records keep resolving).
+ *
+ * `''` is a CLAIM, not merely an absence: the record says the reading was taken
+ * at backend defaults. So an EMPTY launch set is a request in its own right —
+ * `localModelAssessments` hands it to the runtime's applier wherever that
+ * applier can honour it (`resetsOnEmpty`), and the daemon is relaunched WITHOUT
+ * the tuning it is currently carrying. Skipping that for an untuned run is what
+ * filed a still-tuned daemon as "Backend defaults" and let `compareTunings` rank
+ * every real tuning against a configuration that never ran (#4759, #4763).
+ *
+ * **Adding the first `wire` knob breaks an assumption two call sites make.**
+ * While that tier is empty, a non-empty `tuningKey` implies a non-empty LAUNCH
+ * set, so `getAssessmentReport` and the client's `tuningNoticeChip` both read
+ * `tuningKey` as "did this run request launch tuning?" when wording a
+ * `tuningApplied: false` row. A request-only tuning would have a non-empty key
+ * and an empty launch set, so a failed reset on that run would be described as
+ * "the requested tuning was not applied". Split those two on
+ * `launchTuning(backend, tuning)` rather than on the key when that day comes.
*/
/**
diff --git a/server/services/llamaServerManager.js b/server/services/llamaServerManager.js
index 98dad90b5d..28db4f9936 100644
--- a/server/services/llamaServerManager.js
+++ b/server/services/llamaServerManager.js
@@ -35,6 +35,23 @@ const PORT_RELEASE_TIMEOUT_MS = 5000;
let relaunchReadyTimeoutMs = 120000;
let currentConfig = null;
+// The launch line the daemon was serving BEFORE PortOS put an assessment tuning
+// on it. `null` means no PortOS-applied tuning is in effect — either none was
+// ever applied, or it has since been cleared — and is what makes an UNTUNED
+// assessment honest: without it a baseline run would sample whatever the
+// previous measurement left running and file the numbers as "Backend defaults".
+//
+// Deliberately NOT the same thing as `CLEARED_TUNING`. That renders the launch
+// line with every sweepable knob off, which also wipes flags the USER set on the
+// LLMs page — correct for a sweep, which captured them and will put them back,
+// and wrong for an ordinary measurement, which did not. Restoring the captured
+// line undoes only what PortOS itself applied.
+//
+// Module state, so it does not survive a PortOS restart that re-adopts a still
+// -tuned PM2 process. That case degrades to today's behaviour (the untuned run
+// no-ops) rather than to a wrong relaunch, and the reconstructed launch line
+// cannot tell a PortOS tuning apart from the same flags typed by the user.
+let preTuningConfig = null;
let lastExitError = null;
const logs = createDaemonLogBuffer();
const appendLog = logs.append;
@@ -318,6 +335,11 @@ export async function startLlamaServer(options = {}) {
}
appendLog(`Starting: llama-server ${args.join(' ')}`);
+ // A fresh launch line supersedes any baseline: whatever PortOS tuned is gone
+ // with the process it tuned, and restoring the old daemon's configuration over
+ // this one would undo a start the user just asked for. A relaunch re-arms this
+ // AFTER the start returns, from the baseline it captured itself.
+ preTuningConfig = null;
currentConfig = {
model,
// The drafter actually on the launch line, so the status card reports what
@@ -429,6 +451,10 @@ export async function stopLlamaServer() {
throw new ServerError(`Failed to stop llama-server: ${err.message}`, { status: 500 });
}
currentConfig = null;
+ // The tuning died with the process, so there is no longer anything to clear.
+ // A relaunch that stops the daemon itself re-establishes this from its own
+ // captured baseline — see `relaunchLlamaServerWithTuning`.
+ preTuningConfig = null;
return { success: true, message: 'llama-server stopped' };
}
@@ -505,10 +531,20 @@ async function waitForEndpoint(endpoint) {
* silently resize the window (or the slot count) out from under a running
* server.
*
+ * An EMPTY tuning WITHOUT `reset` is the third request: an untuned measurement
+ * asking to be taken at backend defaults. It restores the launch line PortOS
+ * displaced when it first tuned this daemon — which undoes what PortOS applied
+ * and leaves the user's own flags exactly where they were, so it needs none of
+ * the capture/restore ceremony a `reset` does. When PortOS has tuned nothing,
+ * nothing is relaunched.
+ *
* @param {object} tuning launch knobs from `lib/localModelTuning.js`
* @param {{reset?: boolean}} [options] `reset` clears every sweepable knob the
* tuning does not name. Never pass it from an ordinary measurement.
- * @returns {Promise<{applied: boolean, reason: string|null, config: object|null}>}
+ * @returns {Promise<{applied: boolean|null, reason: string|null, config: object|null}>}
+ * `applied: null` means nothing needed to change — the daemon already serves
+ * the requested configuration, which is not a refusal and must not be recorded
+ * as one.
*/
const LAUNCHER_OWNED_KNOBS = new Set(['ctxSize', 'nGpuLayers', 'parallel']);
@@ -582,27 +618,48 @@ export async function restoreLlamaServerConfig(config) {
}
export async function relaunchLlamaServerWithTuning(tuning = {}, { reset = false } = {}) {
- // Without a reset an empty tuning asks for nothing, so there is nothing to do
- // — and answering before touching PM2 keeps an ordinary untuned measurement
- // free of a status round trip.
- if (!reset && Object.values(tuning).every((v) => v === null || v === undefined)) {
- return { applied: false, reason: 'no launch knobs were requested', config: currentConfig };
+ const empty = Object.values(tuning).every((v) => v === null || v === undefined);
+ // An empty tuning with no `reset` is an UNTUNED measurement asking to be taken
+ // at backend defaults. If PortOS put a tuning on this daemon, it has to come
+ // back off — the reading is stored as "Backend defaults" either way, and
+ // `compareTunings` ranks every real tuning against it. Restoring the captured
+ // pre-tuning line, NOT `CLEARED_TUNING`: the reset clears sweepable knobs the
+ // user may have set themselves, which only a sweep is entitled to do.
+ const clearing = empty && !reset && Boolean(preTuningConfig);
+ // Nothing PortOS applied is outstanding, so an empty tuning asks for nothing —
+ // and answering before touching PM2 keeps an ordinary untuned measurement free
+ // of a status round trip.
+ if (!reset && empty && !clearing) {
+ return { applied: null, reason: null, config: currentConfig };
}
const status = await getLlamaServerStatus();
if (!status.running) {
+ // Whatever carried the tuning is gone; the next start is untuned by
+ // construction, so there is nothing left to undo.
+ preTuningConfig = null;
+ if (clearing) return { applied: null, reason: null, config: null };
return { applied: false, reason: 'llama-server is not running, so PortOS has no model path to relaunch with', config: null };
}
if (!status.managed || !status.config?.model) {
return {
applied: false,
- reason: 'llama-server was started outside PortOS — start it from the LLMs page to let PortOS apply tuning',
+ // Worded for the direction it was asked in. A clearing run requested NO
+ // tuning, and its row already reads "backend defaults" — telling that user
+ // their tuning could not be applied contradicts what they are looking at.
+ reason: clearing
+ ? 'llama-server was started outside PortOS, so PortOS cannot relaunch it without the tuning it is carrying'
+ : 'llama-server was started outside PortOS — start it from the LLMs page to let PortOS apply tuning',
config: status.config || null,
};
}
const previous = status.config;
- const next = { ...previous, ...(reset ? CLEARED_TUNING : {}), ...tuning };
+ // Captured before `stopLlamaServer` clears it, and put back explicitly on
+ // every exit below — the stop is part of this relaunch, not the user ending
+ // the tuning session.
+ const baseline = preTuningConfig;
+ const next = clearing ? baseline : { ...previous, ...(reset ? CLEARED_TUNING : {}), ...tuning };
// Nothing to do when the daemon is ALREADY running this exact tuning — the
// common case for an untuned measurement on an untuned server, and the reason
// making an empty tuning meaningful costs a plain assessment nothing.
@@ -612,12 +669,24 @@ export async function relaunchLlamaServerWithTuning(tuning = {}, { reset = false
// `nGpuLayers`) changes nothing in the cleared set, and judging on that would
// report a context-size change as applied while the server kept serving the
// old window.
- const compared = new Set([...Object.keys(CLEARED_TUNING), ...Object.keys(tuning || {})]);
+ //
+ // A CLEARING run compares the whole captured line, not just the knob set: the
+ // baseline is a complete configuration, and any field of it that drifted is a
+ // difference this relaunch exists to undo.
+ const compared = clearing
+ ? new Set([...Object.keys(baseline), ...Object.keys(previous)])
+ : new Set([...Object.keys(CLEARED_TUNING), ...Object.keys(tuning || {})]);
const changed = [...compared].some((id) => asLaunched(next[id]) !== asLaunched(previous[id]));
- if (!changed) return { applied: true, reason: null, config: previous };
+ if (!changed) {
+ // The daemon already serves the pre-tuning line, so the tuning is gone.
+ if (clearing) preTuningConfig = null;
+ return { applied: clearing ? null : true, reason: null, config: previous };
+ }
const knobs = Object.entries(tuning).filter(([, v]) => v !== null && v !== undefined);
- console.log(`🦙 llama-server: relaunching to apply tuning (${knobs.length ? knobs.map(([k, v]) => `${k}=${v}`).join(', ') : 'backend defaults'})`);
+ console.log(clearing
+ ? '🦙 llama-server: relaunching without the tuning PortOS applied'
+ : `🦙 llama-server: relaunching to apply tuning (${knobs.length ? knobs.map(([k, v]) => `${k}=${v}`).join(', ') : 'backend defaults'})`);
await stopLlamaServer();
await waitForPortRelease(next.port ?? PORTS.LLAMA_SERVER);
@@ -637,7 +706,16 @@ export async function relaunchLlamaServerWithTuning(tuning = {}, { reset = false
return { failure: err.message, config: restored?.config || null };
});
if (started.failure) {
- return { applied: false, reason: `llama-server rejected that tuning: ${started.failure}`, config: started.config };
+ // `previous` is back on the port, so whatever tuning it carried is still in
+ // effect and still needs undoing later.
+ preTuningConfig = baseline;
+ return {
+ applied: false,
+ reason: clearing
+ ? `llama-server rejected its pre-tuning launch line: ${started.failure}`
+ : `llama-server rejected that tuning: ${started.failure}`,
+ config: started.config,
+ };
}
// PM2 reporting `online` is not the same as the server answering. But
@@ -657,13 +735,20 @@ export async function relaunchLlamaServerWithTuning(tuning = {}, { reset = false
console.error(`❌ llama-server: could not restore the previous configuration: ${err.message}`);
return null;
});
+ preTuningConfig = baseline;
return {
applied: false,
reason: 'llama-server relaunched but never answered on its port',
config: restored?.config || null,
};
}
- return { applied: true, reason: null, config: started.config };
+ // The daemon now serves `next`. Clearing leaves it untuned, so there is
+ // nothing left to undo; a first tuning records the line it displaced, and a
+ // second must NOT overwrite that with the line the first one left.
+ preTuningConfig = clearing ? null : (baseline || previous);
+ // `null`, not `true`, for a clear: there was no tuning to apply, and the
+ // reading that follows describes backend defaults truthfully.
+ return { applied: clearing ? null : true, reason: null, config: started.config };
}
/**
@@ -783,6 +868,7 @@ export async function installLlamaServer({ onProgress = () => {} } = {}) {
*/
export function _resetLlamaServerStateForTests({ relaunchReadyTimeout } = {}) {
currentConfig = null;
+ preTuningConfig = null;
logs.reset();
lastExitError = null;
// Restored to the production budget unless a suite asks for a shorter one.
diff --git a/server/services/llamaServerManager.test.js b/server/services/llamaServerManager.test.js
index 90c6d5dc5d..068fe2bb3b 100644
--- a/server/services/llamaServerManager.test.js
+++ b/server/services/llamaServerManager.test.js
@@ -509,11 +509,87 @@ describe('llamaServerManager', () => {
// The user's launch flags live only in the running process, so an ordinary
// measurement must never reset them. Without `reset` an empty tuning asks
// for nothing and is answered before PM2 is touched at all.
- it('refuses an empty tuning rather than restarting for no reason', async () => {
+ // `null`, not `false`: nothing was refused. The daemon already serves the
+ // configuration the caller asked for, so an untuned assessment's "Backend
+ // defaults" label is accurate as it stands.
+ it('relaunches nothing for an empty tuning on a daemon it never tuned', async () => {
await started();
execPm2Calls = [];
const result = await relaunchLlamaServerWithTuning({});
- expect(result.applied).toBe(false);
+ expect(result.applied).toBeNull();
+ expect(result.reason).toBeNull();
+ expect(restarted()).toBe(false);
+ });
+
+ // The bug this pair exists for: an untuned run that followed a tuned one was
+ // sampling a daemon still carrying the tuned launch line, then filing the
+ // reading as "Backend defaults" — a record describing a configuration that
+ // never ran, which `compareTunings` ranks every real tuning against.
+ it('puts the pre-tuning launch line back for an empty tuning after a tuned one', async () => {
+ await started();
+ await relaunchLlamaServerWithTuning({ ubatchSize: 512, flashAttn: true });
+ execPm2Calls = [];
+
+ const result = await relaunchLlamaServerWithTuning({});
+
+ expect(result.applied).toBeNull();
+ const start = execPm2Calls.find((c) => c[0] === 'start');
+ expect(start).not.toContain('-ub');
+ expect(start).not.toContain('--flash-attn');
+ expect(start[start.indexOf('-m') + 1]).toBe(modelPath);
+ });
+
+ // The baseline is the line the FIRST tuning displaced. Crediting the second
+ // tuning's `previous` would make "untuned" mean "whatever the first sweep
+ // left running" — the same lie, one step removed.
+ it('keeps the original baseline across successive tunings', async () => {
+ await started();
+ await relaunchLlamaServerWithTuning({ ubatchSize: 512 });
+ await relaunchLlamaServerWithTuning({ ubatchSize: 1024, flashAttn: true });
+ execPm2Calls = [];
+
+ await relaunchLlamaServerWithTuning({});
+
+ const start = execPm2Calls.find((c) => c[0] === 'start');
+ expect(start).not.toContain('-ub');
+ expect(start).not.toContain('--flash-attn');
+ });
+
+ it('relaunches nothing for a second empty tuning once the daemon is back at its baseline', async () => {
+ await started();
+ await relaunchLlamaServerWithTuning({ ubatchSize: 512 });
+ await relaunchLlamaServerWithTuning({});
+ execPm2Calls = [];
+
+ expect(await relaunchLlamaServerWithTuning({})).toMatchObject({ applied: null });
+ expect(restarted()).toBe(false);
+ });
+
+ // A user-stopped daemon takes its tuning with it, so a later untuned run has
+ // nothing to undo — and must not resurrect the process to prove it.
+ it('drops the baseline when the daemon is stopped outside a relaunch', async () => {
+ await started();
+ await relaunchLlamaServerWithTuning({ ubatchSize: 512 });
+ await stopLlamaServer();
+ execPm2Calls = [];
+
+ expect(await relaunchLlamaServerWithTuning({})).toMatchObject({ applied: null });
+ expect(restarted()).toBe(false);
+ });
+
+ // A start the user asked for supersedes the baseline. Restoring the old
+ // daemon's launch line over a configuration just chosen on the LLMs page
+ // would undo their change in the name of measuring defaults.
+ it('drops the baseline when a fresh server is started over a crashed one', async () => {
+ await started();
+ await relaunchLlamaServerWithTuning({ ubatchSize: 512 });
+ // The daemon dies outside PortOS — nothing called stopLlamaServer, so
+ // nothing cleared the baseline — and the user starts a new one.
+ pm2State = null;
+ await startLlamaServer({ model: modelPath, port: PORTS.LLAMA_SERVER, ctxSize: 65536 });
+ execPm2Calls = [];
+
+ expect(await relaunchLlamaServerWithTuning({})).toMatchObject({ applied: null });
expect(restarted()).toBe(false);
});
diff --git a/server/services/lmStudioManager.js b/server/services/lmStudioManager.js
index 706b985b67..956dbae617 100644
--- a/server/services/lmStudioManager.js
+++ b/server/services/lmStudioManager.js
@@ -54,6 +54,19 @@ let availableModels = null
// list, so this lets callers tell "0 models" from "couldn't list models".
let lastListError = null
let lastCheckAt = null
+// Model id → the `lms load` flags PortOS loaded it with. An entry means that
+// model is resident under a PortOS tuning; its absence means it is not, which is
+// what lets an UNTUNED assessment tell "already at defaults, relaunch nothing"
+// from "still carrying the last sweep's flags, reload without them". Without it
+// a baseline reading is filed as "Backend defaults" while the model is loaded at
+// the previous run's context length.
+//
+// Deliberately NOT cleared by `resetCache` (`runLms` resets the model caches
+// after every command, including the load that just set this) and not by a
+// failed availability probe either. A stale entry costs one reload nobody needed
+// and still leaves the model untuned; a wrongly-dropped one silently restores
+// the mislabeling this record exists to prevent. Only an unload clears it.
+const tunedLoads = new Map()
// Status tracking
const status = {
@@ -291,17 +304,65 @@ async function loadModel(modelId) {
* the existing instance rather than re-loading it at the new settings, which
* would report success for a tuning that never applied.
*
+ * An EMPTY `args` is the opposite request: reload the model with no tuning flags
+ * at all, so an untuned assessment measures a model that is actually untuned
+ * rather than whatever the previous sweep loaded. It is a no-op when PortOS did
+ * not load this model with flags — reloading anyway would cold-load the weights
+ * and the first sample would time the page-in.
+ *
* 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 }>}
+ * @returns {Promise<{ success: boolean, unchanged?: boolean, error?: string }>}
+ * `unchanged: true` means nothing needed reloading — not a refusal.
*/
async function loadModelWithArgs(modelId, args = []) {
if (!modelId) return { success: false, error: 'No model was named to load.' }
- if (await checkLMStudioAvailable()) await unloadModel(modelId).catch(() => {})
+ const signature = args.join(' ')
+ const carried = tunedLoads.get(modelId) || null
+ if (!signature && !carried) return { success: true, unchanged: true }
+
+ // `lms load` on an already-RESIDENT model returns the existing instance rather
+ // than re-loading it at the new settings, so the model has to be out of memory
+ // before the load or the call reports success for a configuration that never
+ // applied. That makes a refused unload fatal in both directions: a tuned load
+ // would file the previous configuration's throughput under the requested
+ // tuning, and a clear would file it as backend defaults.
+ //
+ // Gated on residency, not merely on availability. `unloadModel` also resolves
+ // `{ success: false }` for a model that simply is not loaded — the ordinary
+ // state before a first assessment — and reading that as a refusal would fail
+ // every first run and never record its tuning. Both probes are FORCED: a
+ // cached `false` availability, or a stale loaded-models list, would skip the
+ // unload and hand back exactly the stale instance this guards against.
+ if (await checkLMStudioAvailable(true)) {
+ const resident = await getLoadedModels(true).catch(() => [])
+ // `[]` from `getLoadedModels` means "nothing is loaded" OR "both list
+ // endpoints failed" — the null-vs-empty sentinel trap in root CLAUDE.md, and
+ // `getLastLoadedModelsError` is the module's own way out of it. An
+ // untrustworthy list must not read as "not resident": that skips the unload,
+ // `lms load` hands back the existing instance, and the previous
+ // configuration's throughput is filed under this call's. Assume resident and
+ // try — a wasted unload attempt is recoverable, a stale instance is not.
+ const listTrusted = getLastLoadedModelsError() === null
+ const loaded = !listTrusted
+ || resident.some((m) => m?.id === modelId || modelIdsReferToSameRepo(m?.id, modelId))
+ const unloaded = loaded
+ ? await unloadModel(modelId).catch((err) => ({ success: false, error: err?.message }))
+ : { success: true }
+ // Checked BEFORE the load: once `lms load` has run, a refusal is no longer
+ // the whole story — the flags may genuinely be in effect.
+ if (!unloaded.success) {
+ return {
+ success: false,
+ error: unloaded.error
+ || `LM Studio would not unload ${modelId}, so it is still loaded with ${carried || 'its previous settings'}`,
+ }
+ }
+ }
// `-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.
@@ -312,7 +373,9 @@ async function loadModelWithArgs(modelId, args = []) {
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(' ')})` : ''}`)
+ if (signature) tunedLoads.set(modelId, signature)
+ else tunedLoads.delete(modelId)
+ console.log(`📦 LM Studio loaded ${modelId}${signature ? ` (${signature})` : ` without ${carried}`}`)
cosEvents.emit('lmstudio:modelLoaded', { modelId })
return { success: true }
}
@@ -342,6 +405,8 @@ async function unloadModel(modelId) {
// Refresh loaded models
await getLoadedModels(true)
+ // Whatever flags it was loaded with left with it.
+ tunedLoads.delete(modelId)
console.log(`📤 Model unloaded: ${modelId}`)
cosEvents.emit('lmstudio:modelUnloaded', { modelId })
diff --git a/server/services/lmStudioManager.test.js b/server/services/lmStudioManager.test.js
index 3673d2af02..3b3bfd3988 100644
--- a/server/services/lmStudioManager.test.js
+++ b/server/services/lmStudioManager.test.js
@@ -284,7 +284,7 @@ describe('lmStudioManager.loadModelWithArgs', () => {
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', []);
+ const result = await loadModelWithArgs('publisher/model', ['--context-length', '8192']);
expect(result.success).toBe(false);
expect(result.error).toContain('timed out');
});
@@ -292,12 +292,136 @@ describe('lmStudioManager.loadModelWithArgs', () => {
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', []);
+ const result = await loadModelWithArgs('publisher/model', ['--context-length', '8192']);
expect(result.success).toBe(false);
expect(result.error).toContain('lms bootstrap');
expect(lmsSpawn).not.toHaveBeenCalled();
});
+ // The bug: an untuned assessment following a tuned one left the model resident
+ // at the previous run's context length, then stored the reading as
+ // `tuningKey: ''` — "Backend defaults" describing a load that never happened.
+ it('reloads without flags when PortOS loaded the model with some', async () => {
+ const { loadModelWithArgs } = await import('./lmStudioManager.js');
+ await loadModelWithArgs('publisher/model', ['--context-length', '8192']);
+ lmsSpawn.mockClear();
+
+ expect(await loadModelWithArgs('publisher/model', [])).toEqual({ success: true });
+ const [, args] = lmsSpawn.mock.calls[0];
+ expect(args).toEqual(['load', 'publisher/model', '-y']);
+ });
+
+ // Reloading a model that is already untuned would cold-load the weights, and
+ // the first sample would time the page-in as the model's throughput.
+ it('reloads nothing when PortOS never loaded the model with flags', async () => {
+ const { loadModelWithArgs } = await import('./lmStudioManager.js');
+ expect(await loadModelWithArgs('publisher/model', [])).toEqual({ success: true, unchanged: true });
+ expect(lmsSpawn).not.toHaveBeenCalled();
+ });
+
+ it('reloads nothing for a second clear once the model is back at defaults', async () => {
+ const { loadModelWithArgs } = await import('./lmStudioManager.js');
+ await loadModelWithArgs('publisher/model', ['--context-length', '8192']);
+ await loadModelWithArgs('publisher/model', []);
+ lmsSpawn.mockClear();
+
+ expect(await loadModelWithArgs('publisher/model', [])).toEqual({ success: true, unchanged: true });
+ expect(lmsSpawn).not.toHaveBeenCalled();
+ });
+
+ // `lms load` on a resident model returns the EXISTING instance and reports
+ // success, so an unload that failed means the model serving before the call is
+ // still what is serving — in EITHER direction. Reporting success would file
+ // the previous configuration's throughput under the one that was asked for.
+ // A reachable LM Studio whose `/api/v0/models` reports `resident` loaded, and
+ // whose unload succeeds unless `state.fails`.
+ const stubLmStudio = (state) => vi.stubGlobal('fetch', vi.fn(async (url) => {
+ const href = String(url);
+ if (href.includes('/models/unload')) {
+ return state.fails
+ ? { ok: false, status: 500, text: async () => 'busy', json: async () => ({}) }
+ : { ok: true, status: 200, json: async () => ({}), text: async () => '{}' };
+ }
+ const data = (state.resident || []).map((id) => ({ id, state: 'loaded', type: 'llm' }));
+ return { ok: true, status: 200, json: async () => ({ data }), text: async () => JSON.stringify({ data }) };
+ }));
+
+ // The ordinary state before a FIRST assessment: LM Studio up, model not
+ // resident. `unloadModel` reports failure for a model that was never loaded,
+ // and reading that as a refusal would fail every first run — and then leave
+ // the tuning unrecorded, so the follow-up untuned run no-ops and files a
+ // still-tuned model as backend defaults.
+ it('loads a model that is not resident without treating the unload as a refusal', async () => {
+ stubLmStudio({ resident: [], fails: true });
+ const { loadModelWithArgs } = await import('./lmStudioManager.js');
+
+ expect(await loadModelWithArgs('publisher/model', ['--context-length', '8192'])).toEqual({ success: true });
+ // The tuning was recorded, so the clear that follows knows to reload.
+ lmsSpawn.mockClear();
+ expect(await loadModelWithArgs('publisher/model', [])).toEqual({ success: true });
+ expect(lmsSpawn).toHaveBeenCalled();
+ });
+
+ // `getLoadedModels` returns `[]` for "nothing loaded" AND for "both list
+ // endpoints failed". Reading the second as "not resident" skips the unload,
+ // and `lms load` then hands back the resident instance while reporting
+ // success — the previous configuration's throughput filed under this tuning.
+ it('attempts the unload when the loaded-model list could not be trusted', async () => {
+ vi.stubGlobal('fetch', vi.fn(async (url) => {
+ const href = String(url);
+ if (href.includes('/models/unload')) {
+ return { ok: false, status: 500, text: async () => 'busy', json: async () => ({}) };
+ }
+ // Reachable enough for the availability probe, but neither list endpoint
+ // returns a `data` array — so the list is an error, not an empty result.
+ return { ok: true, status: 200, json: async () => ({}), text: async () => '{}' };
+ }));
+ const { loadModelWithArgs } = await import('./lmStudioManager.js');
+
+ expect(await loadModelWithArgs('publisher/model', ['--context-length', '8192'])).toMatchObject({ success: false });
+ expect(lmsSpawn).not.toHaveBeenCalled();
+ });
+
+ it('refuses a tuned load when a RESIDENT model would not unload', async () => {
+ stubLmStudio({ resident: ['publisher/model'], fails: true });
+ const { loadModelWithArgs } = await import('./lmStudioManager.js');
+
+ expect(await loadModelWithArgs('publisher/model', ['--context-length', '8192'])).toMatchObject({ success: false });
+ // Refused BEFORE the load — once `lms load` has run the flags may really be
+ // in effect, and the refusal would no longer be the whole story.
+ expect(lmsSpawn).not.toHaveBeenCalled();
+ });
+
+ it('refuses a clear whose unload failed, keeping the record for a retry', async () => {
+ const state = { resident: [], fails: false };
+ stubLmStudio(state);
+ const { loadModelWithArgs } = await import('./lmStudioManager.js');
+ await loadModelWithArgs('publisher/model', ['--context-length', '8192']);
+
+ state.resident = ['publisher/model'];
+ state.fails = true;
+ expect(await loadModelWithArgs('publisher/model', [])).toMatchObject({ success: false });
+
+ // The entry survived, so the next attempt still knows the model is tuned
+ // rather than no-opping and recording it as backend defaults.
+ state.fails = false;
+ lmsSpawn.mockClear();
+ expect(await loadModelWithArgs('publisher/model', [])).toEqual({ success: true });
+ expect(lmsSpawn).toHaveBeenCalled();
+ });
+
+ // A failed tuned load leaves the model at whatever it was, so the flags were
+ // never applied and there is nothing for a later untuned run to clear.
+ it('does not record flags from a load the CLI refused', async () => {
+ lmsSpawn.mockResolvedValue({ success: false, code: 1, stdout: '', stderr: 'Model does not fit\n' });
+ const { loadModelWithArgs } = await import('./lmStudioManager.js');
+ await loadModelWithArgs('publisher/model', ['--context-length', '1048576']);
+ lmsSpawn.mockClear();
+
+ expect(await loadModelWithArgs('publisher/model', [])).toEqual({ success: true, unchanged: true });
+ 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.' });
diff --git a/server/services/localModelAssessments.js b/server/services/localModelAssessments.js
index 29b56fe2c6..21b5a9cea7 100644
--- a/server/services/localModelAssessments.js
+++ b/server/services/localModelAssessments.js
@@ -378,9 +378,14 @@ export async function runAssessment({ backend, modelId, contextTokens = DEFAULT_
// 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.
+//
+// `null` is the third state and means "nothing needed to change": the daemon
+// already serves the requested configuration. That is NOT a refusal, so it
+// carries no reason — recording one would put a "tuning not applied" warning on
+// a reading that is perfectly accurate.
const toApplication = (ok, error, fallbackReason) => ({
- applied: ok === true,
- reason: ok === true ? null : (error || fallbackReason),
+ applied: ok === null ? null : ok === true,
+ reason: ok === true || ok === null ? null : (error || fallbackReason),
config: null,
});
@@ -431,6 +436,7 @@ const LAUNCH_APPLIERS = {
llama: {
transport: 'config',
sweepable: true,
+ resetsOnEmpty: true,
apply: ({ launch, reset }) => relaunchLlamaServerWithTuning(launchConfig('llama', launch), { reset }),
capture: captureLlamaServerConfig,
restore: restoreLlamaServerConfig,
@@ -438,18 +444,24 @@ const LAUNCH_APPLIERS = {
ollama: {
transport: 'env',
sweepable: false,
+ resetsOnEmpty: true,
apply: ({ launch }) => restartOllamaWithEnv(launchEnv('ollama', launch))
.then((r) => toApplication(r.applied, r.error, `Ollama could not be restarted with that tuning (${r.reason})`)),
},
lmstudio: {
transport: 'cli',
sweepable: false,
+ resetsOnEmpty: true,
apply: ({ modelId, launch }) => loadLmStudioModelWithArgs(modelId, launchArgs('lmstudio', launch))
- .then((r) => toApplication(r.success, r.error, 'LM Studio could not reload the model with that tuning')),
+ .then((r) => toApplication(r.unchanged ? null : r.success, r.error, 'LM Studio could not reload the model with that tuning')),
},
mtplx: {
transport: 'cli',
sweepable: false,
+ // `relaunchMtplxServerWithTuning` refuses an empty knob set rather than
+ // relaunching without flags, so PortOS cannot put this daemon back on its
+ // defaults and an untuned run must not claim it did.
+ resetsOnEmpty: false,
// Takes the knob set as-is rather than rendered flags: `mtplxServerManager`
// renders it with the same catalog on the way to the launch line, and keeps
// the ids so it can report back which tuning the daemon came up under.
@@ -469,6 +481,24 @@ export const LAUNCH_TRANSPORTS = Object.freeze(Object.fromEntries(
/** Whether a TUNING SWEEP may drive this runtime — see `sweepable` above. */
export const isTuningSweepable = (backend) => LAUNCH_APPLIERS[backend]?.sweepable === true;
+/**
+ * Whether an EMPTY knob set is a real "run at backend defaults" instruction this
+ * manager honours, rather than a request for nothing.
+ *
+ * This is what makes an UNTUNED assessment honest. Such a run records
+ * `tuningKey: ''` and renders as **Backend defaults**, so the daemon has to
+ * actually BE at them — but if the previous run tuned it, it is still serving
+ * under that tuning and the reading is filed under a configuration that never
+ * ran. `compareTunings` then ranks every real tuning against it, making the one
+ * row a user reads as the baseline the least trustworthy row in the table
+ * (#4759, and the same failure #4763 describes for a sweep's baseline variant).
+ *
+ * Distinct from `sweepable`: this is only the RESET half. A sweep additionally
+ * needs `capture`/`restore` so it can put the user's own launch flags back after
+ * driving the daemon through a grid — which llama.cpp alone has today.
+ */
+const resetsOnEmpty = (backend) => LAUNCH_APPLIERS[backend]?.resetsOnEmpty === true;
+
/**
* Remember a runtime's launch configuration so a sweep can put it back.
* `null` for a runtime with nothing to capture — restoring it is then a no-op.
@@ -482,7 +512,12 @@ export const restoreLaunchState = (backend, state) =>
async function applyLaunchTuning({ backend, modelId, launch, reset }) {
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 };
+ // No launch path at all. A requested tuning is genuinely not applied; an
+ // empty set has nothing to undo, because PortOS never put a tuning on this
+ // daemon in the first place.
+ return Object.keys(launch).length > 0
+ ? { applied: false, reason: `PortOS does not start the ${backend} runtime, so it cannot apply launch tuning`, config: null }
+ : { applied: null, reason: null, config: null };
}
return applier.apply({ backend, modelId, launch, reset })
.catch((err) => ({ applied: false, reason: err?.message || 'relaunch failed', config: null }));
@@ -502,14 +537,23 @@ async function measureModel({ backend, modelId, contexts, tuning, resetTuning, s
// tuning PortOS could not apply must not be filed as evidence for that tuning.
const launch = launchTuning(backend, normalizedTuning);
const request = requestBody(backend, normalizedTuning);
- // `resetTuning` (a SWEEP, never an ordinary Measure) makes an empty launch
- // tuning meaningful: "no knobs" is the baseline every variant is compared
- // against, so it has to be applied rather than assumed. Without it an empty
- // tuning stays what it has always been — nothing was asked for, nothing is
- // touched — which is what keeps a plain measurement from relaunching, and from
- // recording `tuningApplied: false` for a run that requested no tuning at all.
+ // An empty launch tuning is a real instruction — "run at backend defaults" —
+ // wherever the runtime can honour it (`resetsOnEmpty`). A sweep needs that for
+ // its baseline variant, and so does an ORDINARY untuned Measure: it records
+ // `tuningKey: ''` and renders as "Backend defaults", so a daemon the previous
+ // run tuned has to be put back or the reading describes a configuration that
+ // never ran (#4759 / #4763).
+ //
+ // This costs a plain measurement nothing when the daemon is already at
+ // defaults — every applier compares against what is running and relaunches
+ // only on a real difference. A runtime that CANNOT reset keeps the old
+ // behaviour: nothing was asked for, nothing is touched, and `tuningApplied`
+ // stays `null` rather than becoming a `false` that would drop every untuned
+ // reading out of the recommendations.
+ const clearing = Object.keys(launch).length === 0;
+ const resetting = clearing && (resetTuning || resetsOnEmpty(backend));
let tuningApplication;
- if (Object.keys(launch).length > 0 || resetTuning) {
+ if (!clearing || resetting) {
// Announced BEFORE the await, because applying a launch tuning stops and
// restarts a daemon — and a cold MLX or GGUF checkpoint can take minutes to
// load again. Without this the progress stream is silent for that whole
@@ -522,7 +566,17 @@ async function measureModel({ backend, modelId, contexts, tuning, resetTuning, s
// not a sentence. It is a real configuration — say which one.
message: `Restarting ${backend} with ${tuningLabel || 'backend defaults'} before measuring…`,
});
- tuningApplication = await applyLaunchTuning({ backend, modelId, launch, reset: resetTuning });
+ // `reset` stays SWEEP-only. It renders the cleared launch line, which wipes
+ // sweepable knobs the USER may have set on the LLMs page — safe only for a
+ // caller that captured them and will put them back. An ordinary untuned run
+ // asks its manager to undo what PORTOS applied and nothing else.
+ const application = await applyLaunchTuning({ backend, modelId, launch, reset: resetTuning });
+ // A tuning made only of request-body knobs rides on each sample and needs no
+ // daemon restart, so the applier's "nothing to apply" is `true` there — it
+ // did take effect, just not through the launch line.
+ tuningApplication = application.applied === null && Object.keys(request).length > 0
+ ? { ...application, applied: true }
+ : application;
} else {
// `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.
@@ -740,7 +794,14 @@ export async function getAssessmentReport({ intent = 'balanced' } = {}) {
tuningKey: a?.tuningKey || '',
tuningLabel: a?.tuningLabel || null,
verdict: a?.verdict || 'unknown',
- reason: `measured, but the requested tuning was not applied — ${a?.tuningNotApplied || 'reason not recorded'}`,
+ // `tuningApplied: false` covers two opposite failures, and the row shows a
+ // configuration chip beside this sentence. An UNTUNED run's chip already
+ // reads "backend defaults", so "the requested tuning was not applied"
+ // contradicts it — that run's failure is that the daemon could not be put
+ // BACK on defaults. Mirrors `tuningNoticeChip` on the client.
+ reason: a?.tuningKey
+ ? `measured, but the requested tuning was not applied — ${a?.tuningNotApplied || 'reason not recorded'}`
+ : `measured, but the daemon still carried an earlier tuning — ${a?.tuningNotApplied || 'reason not recorded'}`,
});
}
diff --git a/server/services/localModelAssessments.test.js b/server/services/localModelAssessments.test.js
index 53e0809460..3d2546d10a 100644
--- a/server/services/localModelAssessments.test.js
+++ b/server/services/localModelAssessments.test.js
@@ -115,9 +115,20 @@ beforeEach(() => {
probeOpenAiModels.mockReset().mockResolvedValue({ reachable: true, models: [], error: null });
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 });
+ // Mirrors each manager's real contract: an EMPTY request asks the daemon to
+ // drop a tuning PortOS applied, and reports "nothing needed to change" when it
+ // is already untuned. A flat `applied: true` here would let an untuned run
+ // record the very claim `lib/localModelTuning.js` forbids.
+ const empty = (v) => !v || (Array.isArray(v) ? v.length === 0 : Object.keys(v).length === 0);
+ relaunchLlamaServerWithTuning.mockReset().mockImplementation(async (tuning) => (empty(tuning)
+ ? { applied: null, reason: null, config: null }
+ : { applied: true, reason: null, config: null }));
+ restartOllamaWithEnv.mockReset().mockImplementation(async (env) => (empty(env)
+ ? { applied: null, reason: 'already-untuned' }
+ : { applied: true, reason: 'restarted' }));
+ loadLmStudioModelWithArgs.mockReset().mockImplementation(async (_modelId, args) => (empty(args)
+ ? { success: true, unchanged: true }
+ : { success: true }));
getMtplxServerEndpoint.mockReset().mockResolvedValue('http://127.0.0.1:8000/v1');
relaunchMtplxServerWithTuning.mockReset().mockResolvedValue({ applied: true, reason: null, config: null });
});
@@ -823,7 +834,39 @@ describe('tuning', () => {
runLocalLlmTest.mockResolvedValue(okRun());
const untuned = await svc.runAssessment({ backend: 'ollama', modelId: 'example-model:7b', contextTokens: [512] });
expect(untuned.tuningApplied).toBeNull();
- expect(restartOllamaWithEnv).not.toHaveBeenCalled();
+ expect(untuned.tuningNotApplied).toBeNull();
+ });
+
+ // The bug this covers: an untuned run took the no-applier branch, so a daemon
+ // the PREVIOUS run tuned kept serving under that tuning while the reading was
+ // stored with `tuningKey: ''` and rendered as "Backend defaults". Every applier
+ // that CAN reset has to be asked to.
+ it.each([
+ ['ollama', () => restartOllamaWithEnv, (m) => expect(m).toHaveBeenCalledWith({})],
+ ['llama', () => relaunchLlamaServerWithTuning, (m) => expect(m).toHaveBeenCalledWith({}, { reset: false })],
+ ['lmstudio', () => loadLmStudioModelWithArgs, (m) => expect(m).toHaveBeenCalledWith('a-model', [])],
+ ])('asks the %s applier to drop any tuning still on the daemon for an untuned run', async (backend, getMock, assertCall) => {
+ probeOpenAiModels.mockResolvedValue({ reachable: true, models: ['a-model'], error: null });
+ runEndpointLlmTest.mockResolvedValue(okRun());
+ runLocalLlmTest.mockResolvedValue(okRun());
+
+ const result = await svc.runAssessment({ backend, modelId: 'a-model', contextTokens: [512] });
+
+ assertCall(getMock());
+ expect(result.tuningKey).toBe('');
+ });
+
+ // A daemon that could NOT be put back on its defaults is measuring some other
+ // configuration, and the record has to say so rather than call it a baseline.
+ it('records that an untuned run could not clear the tuning still on the daemon', async () => {
+ runLocalLlmTest.mockResolvedValue(okRun());
+ restartOllamaWithEnv.mockResolvedValue({ applied: false, reason: 'stop-failed', error: 'Ollama would not stop' });
+
+ const result = await svc.runAssessment({ backend: 'ollama', modelId: 'example-model:7b', contextTokens: [512] });
+
+ expect(result.tuningKey).toBe('');
+ expect(result.tuningApplied).toBe(false);
+ expect(result.tuningNotApplied).toBe('Ollama would not stop');
});
// A runtime with no launch path must not silently swallow a knob: the catalog
@@ -870,11 +913,12 @@ describe('tuning', () => {
// The user's launch flags live only in the running llama-server process, so an
// ordinary measurement must never touch them. A reset is something a SWEEP
// asks for, and only a sweep, because only a sweep puts the configuration back.
- it('never relaunches llama-server for an untuned run', async () => {
+ it('never RESETS llama-server for an untuned run', async () => {
probeOpenAiModels.mockResolvedValue({ reachable: true, models: ['dflash'], error: null });
runEndpointLlmTest.mockResolvedValue(okRun());
await svc.runAssessment({ backend: 'llama', modelId: 'dflash', contextTokens: [512] });
- expect(relaunchLlamaServerWithTuning).not.toHaveBeenCalled();
+ // Asked to undo what PortOS applied, never to clear the user's own flags.
+ expect(relaunchLlamaServerWithTuning).toHaveBeenCalledWith({}, { reset: false });
});
// The baseline variant of a tuning sweep: no knobs, which only means something
diff --git a/server/services/ollamaManager.js b/server/services/ollamaManager.js
index abd9c59200..0519a4f4bb 100644
--- a/server/services/ollamaManager.js
+++ b/server/services/ollamaManager.js
@@ -125,6 +125,32 @@ let appliedDaemonIdentity = null
// 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
+// The variable NAMES behind `appliedLaunchEnv`, kept alongside the signature
+// rather than re-derived from a string. Longer-lived than `appliedLaunchEnv` on
+// purpose: that latch answers "does the daemon that is up right now hold this
+// env?", so losing sight of the daemon clears it. This answers "what has PortOS
+// put in front of Ollama that has not been cleared yet?", which a clear needs
+// even when the daemon it was applied to is gone.
+let appliedLaunchEnvKeys = []
+// The subset of those that went into the launchd DOMAIN via `launchctl setenv`
+// (the homebrew launch-at-login path). Tracked separately because a domain
+// variable outlives every daemon: every job started afterwards inherits it, so
+// clearing means unsetting it BY NAME. Omitting it from the next start does
+// nothing. Emptied only by a successful unset.
+let launchdExportedKeys = []
+// The env object behind `appliedLaunchEnv`, kept so a tuning can capture the
+// configuration it displaces rather than only its signature.
+let appliedLaunchEnvValues = null
+// The launch env the daemon carried BEFORE an assessment tuning went on it.
+// `null` means no tuning is outstanding.
+//
+// The baseline an untuned assessment restores is what THIS INSTALL runs by
+// default, not an empty environment — `ensureContextWindow` puts the user's
+// configured agent context window on the same `OLLAMA_CONTEXT_LENGTH` a tuning
+// uses, and stripping it in the name of measuring "backend defaults" would
+// silently undo a setting the user chose on the LLMs page. Same rule as
+// `llamaServerManager`'s `preTuningConfig`, for the same reason.
+let preTuningEnv = null
const envSignature = (env) => Object.entries(env || {})
.sort(([a], [b]) => a.localeCompare(b))
@@ -144,6 +170,14 @@ function rememberAppliedEnv(env, identity) {
// `appliedLaunchEnv !== null` to mean "we know what this daemon holds", and an
// empty-string stand-in for "unknown" would claim knowledge we do not have.
appliedLaunchEnv = env ? envSignature(env) : null
+ // Only a NAMED env updates the key record. `null` means "we no longer know
+ // which daemon is up", which says nothing about whether the variables PortOS
+ // exported are still in the launchd domain — and forgetting them there would
+ // strand a tuning nothing can clear.
+ if (env) {
+ appliedLaunchEnvKeys = Object.keys(env)
+ appliedLaunchEnvValues = { ...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.
@@ -341,6 +375,11 @@ async function startServer({ env = null } = {}) {
const running = await waitForAvailability(true, START_TIMEOUT_MS)
if (running) {
+ // A daemon PortOS just started carries exactly `env` and nothing else, so
+ // there is no earlier tuning left to undo. `restartWithEnv` re-asserts its
+ // own baseline after this returns — see the note there. Mirrors
+ // `llamaServerManager`'s `startLlamaServer`.
+ preTuningEnv = null
rememberAppliedEnv(env, String(child.pid))
const window = contextLength ? ` (context ${contextLength})` : ''
console.log(`▶️ Started Ollama server (pid ${child.pid})${window}`)
@@ -582,7 +621,7 @@ async function ensureContextWindow(contextLength, selectedModel = null) {
if (!target) return { applied: false, reason: 'not-configured', contextLength: null }
const env = withOllamaContextEnv({}, target)
if (!(await checkOllamaAvailable(true))) {
- return { ...(await restartWithEnv(env)), contextLength: target }
+ return { ...(await restartWithEnv(env, { tuning: false })), contextLength: target }
}
if (Number(appliedContextLength) >= target) {
@@ -617,7 +656,7 @@ async function ensureContextWindow(contextLength, selectedModel = null) {
// 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 }
+ return { ...(await restartWithEnv(env, { tuning: false })), contextLength: target, runtimeContextLength: runtime }
}
/**
@@ -634,11 +673,11 @@ async function ensureContextWindow(contextLength, selectedModel = null) {
* PortOS reports what to do rather than tearing the unit down to work around it.
*
* @param {{ manager: string }} service
- * @param {Record<string, string>} env
+ * @param {Record<string, string>} env - never empty; `restartWithEnv` routes an
+ * empty env to `clearLaunchEnv` instead, which UNSETS what was set.
*/
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(' ')
@@ -650,27 +689,63 @@ async function restartServiceWithEnv(service, env) {
}
}
- const controller = await getServiceController()
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 }))
+ const setenv = await runLaunchctl(['setenv', key, String(value)])
+ // A key PortOS did NOT manage to set is not PortOS's to unset — the name may
+ // belong to a variable the user exported themselves. Only a successful
+ // setenv makes it ours.
if (!setenv.success) return { applied: false, reason: 'setenv-failed', error: setenv.error }
+ // Recorded as we go, not after the restart: it is already in the domain, and
+ // a bounce that fails later must not leave it untracked and unclearable.
+ if (!launchdExportedKeys.includes(key)) launchdExportedKeys.push(key)
}
+ const bounced = await bounceService()
+ if (!bounced.ok) return bounced.failure
+ 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' }
+}
+
+const runLaunchctl = (args) => execFileAsync('launchctl', args, { timeout: SERVICE_COMMAND_TIMEOUT_MS })
+ .then(() => ({ success: true }))
+ .catch((err) => ({ success: false, error: err.stderr?.trim() || err.message }))
+
+/**
+ * Take variables back OUT of the launchd domain, by name.
+ *
+ * Reached only for keys `restartServiceWithEnv` put there, so `launchctl` is
+ * always the right tool — the domain exists on macOS and nowhere else.
+ */
+async function unsetLaunchdKeys(keys) {
+ for (const key of keys) {
+ const unsetenv = await runLaunchctl(['unsetenv', key])
+ if (!unsetenv.success) return { success: false, error: unsetenv.error }
+ }
+ return { success: true }
+}
+
+/**
+ * Restart the service controller's Ollama and wait for the API to come back.
+ * `{ ok: false, failure }` carries the caller's return value verbatim, so the
+ * set and clear paths above cannot drift on how a bounce failure is reported.
+ */
+async function bounceService() {
+ const controller = await getServiceController()
resetAvailabilityCache()
const [cmd, args] = controller.restart
const restarted = await execFileAsync(cmd, args, { timeout: SERVICE_COMMAND_TIMEOUT_MS })
.then(() => ({ success: true }))
.catch((err) => ({ success: false, error: err.stderr?.trim() || err.stdout?.trim() || err.message }))
- if (!restarted.success) return { applied: false, reason: 'restart-failed', error: restarted.error }
+ if (!restarted.success) return { ok: false, failure: { applied: false, reason: 'restart-failed', error: restarted.error } }
if (!(await waitForAvailability(true, START_TIMEOUT_MS))) {
- return { applied: false, reason: 'restart-unreachable', error: 'Ollama restarted, but the API did not become reachable.' }
+ return {
+ ok: false,
+ failure: { applied: false, reason: 'restart-unreachable', error: 'Ollama restarted, but the API did not become reachable.' }
+ }
}
- 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' }
+ return { ok: true }
}
/**
@@ -685,13 +760,52 @@ async function restartServiceWithEnv(service, env) {
* not — the caller records that instead of filing the reading under a tuning
* that never took effect.
*
+ * An EMPTY `env` is the opposite request: drop a tuning PortOS applied earlier
+ * and put the daemon back on the env it had before. An untuned assessment needs
+ * that — otherwise it samples the previous sweep's tuning and the reading is
+ * filed as "Backend defaults". When no tuning is outstanding, nothing restarts.
+ *
* @param {Record<string, string>} env
- * @returns {Promise<{ applied: boolean, reason: string, error?: string }>}
+ * @param {{ tuning?: boolean }} [options] `tuning: false` marks a restart that
+ * changes the install's REAL configuration (`ensureContextWindow` handing the
+ * daemon the user's agent context window) rather than a temporary assessment
+ * tuning. It is not undoable, and it becomes the baseline a later clear
+ * restores — without it, measuring "backend defaults" would strip a setting
+ * the user chose on the LLMs page.
+ * @returns {Promise<{ applied: boolean|null, reason: string, error?: string }>}
+ * `applied: null` means nothing needed to change — not a refusal.
*/
-async function restartWithEnv(env) {
+async function restartWithEnv(env, { tuning = true } = {}) {
const entries = Object.entries(env || {})
- if (entries.length === 0) return { applied: false, reason: 'nothing-to-apply' }
+ if (entries.length === 0) {
+ return tuning ? clearLaunchEnv() : { applied: false, reason: 'nothing-to-apply' }
+ }
+
+ // A TUNING is temporary and has to be undoable, so the first one records the
+ // env it displaces; a second must not overwrite that with the first one's.
+ // `appliedLaunchEnv === null` is the module's "we do not know what this daemon
+ // holds" sentinel — an unknown baseline is `{}` (PortOS knows of no env to put
+ // back), never a stale record of some earlier daemon's.
+ const before = preTuningEnv
+ const captured = preTuningEnv
+ ?? (appliedLaunchEnv !== null && appliedLaunchEnvValues ? { ...appliedLaunchEnvValues } : {})
+
+ const result = await applyLaunchEnv(env, entries)
+ // Asserted AFTER the restart, never before: `startServer`/`stopServer` drop
+ // the baseline as a matter of course (a daemon PortOS just started is untuned
+ // by construction), so anything written up front would be wiped mid-call.
+ //
+ // A restart that did not happen changed nothing, so the bookkeeping must not
+ // move either. A non-tuning restart that DID happen is the install's real
+ // configuration changing, which leaves nothing to undo.
+ if (result.applied === false) preTuningEnv = before
+ else preTuningEnv = tuning ? captured : null
+ return result
+}
+// The restart itself, with `restartWithEnv` owning the baseline bookkeeping
+// around it so no exit below has to remember to unwind it.
+async function applyLaunchEnv(env, entries) {
// 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
@@ -705,6 +819,19 @@ async function restartWithEnv(env) {
rememberAppliedEnv(null, null)
}
+ // A key the PREVIOUS env exported into the launchd domain and this one does
+ // not name is STILL set, and every job started afterwards inherits it — so the
+ // daemon would come back carrying half the old configuration. Omitting a
+ // variable is not clearing it. Done here rather than in the service path
+ // alone, because a spawned daemon started while a service is registered
+ // inherits the same domain.
+ const stale = launchdExportedKeys.filter((key) => !(key in env))
+ if (stale.length) {
+ const cleared = await unsetLaunchdKeys(stale)
+ if (!cleared.success) return { applied: false, reason: 'unsetenv-failed', error: cleared.error }
+ launchdExportedKeys = launchdExportedKeys.filter((key) => key in env)
+ }
+
console.log(`🔧 Restarting Ollama with ${entries.map(([k, v]) => `${k}=${v}`).join(', ')}`)
if (!(await checkOllamaAvailable(true))) {
@@ -728,6 +855,109 @@ async function restartWithEnv(env) {
: { applied: false, reason: 'start-failed', error: started.error }
}
+/**
+ * Put the daemon back on the env it carried before PortOS tuned it.
+ *
+ * This is the half of the tuning contract that keeps a BASELINE measurement
+ * honest. An untuned assessment records `tuningKey: ''` and renders as "Backend
+ * defaults"; if the daemon is still carrying the last sweep's
+ * `OLLAMA_FLASH_ATTENTION=1`, that label describes a configuration that never
+ * ran, and `compareTunings` then ranks every real tuning against it.
+ *
+ * "Before PortOS tuned it" is `preTuningEnv`, NOT an empty environment — see the
+ * note there. Only when that baseline is itself empty does this tear the launch
+ * env down to nothing.
+ */
+async function clearLaunchEnv() {
+ // Variables PortOS exported are outstanding even when no tuning reached the
+ // daemon — a `setenv` that landed before its restart failed. They sit in the
+ // launchd domain, so the daemon that came up NEXT inherited them and is tuned
+ // however this record reads. Taking them out is not enough: that daemon holds
+ // them in its own process environment and has to be restarted too, which is
+ // exactly what an empty baseline already means here.
+ const baseline = preTuningEnv ?? (launchdExportedKeys.length ? {} : null)
+ // Nothing outstanding at all. `null` — not `false` — because no request was
+ // refused: the daemon already serves the configuration being asked for.
+ if (baseline === null) return { applied: null, reason: 'already-untuned' }
+
+ const keys = [...new Set([...appliedLaunchEnvKeys, ...launchdExportedKeys])]
+ console.log(`🔧 Clearing the Ollama tuning PortOS applied (${keys.join(', ')})`)
+ preTuningEnv = null
+
+ // A non-empty baseline is just "restart under this env", which the normal
+ // path already does — including taking the tuning's leftover launchd
+ // variables back out of the domain. It is not an APPLICATION though: the run
+ // asked for no tuning, so a success records `null`.
+ if (Object.keys(baseline).length > 0) {
+ const restored = await restartWithEnv(baseline, { tuning: false })
+ if (restored.applied === false) {
+ preTuningEnv = baseline
+ return restored
+ }
+ return { ...restored, applied: null }
+ }
+
+ const exported = launchdExportedKeys
+ // Domain variables come out FIRST, and regardless of whether a daemon is up:
+ // they outlive the process that read them, so a login-launched Ollama would
+ // otherwise come back tuned long after this run recorded "backend defaults".
+ if (exported.length) {
+ const unset = await unsetLaunchdKeys(exported)
+ if (!unset.success) {
+ preTuningEnv = baseline
+ return { applied: false, reason: 'unsetenv-failed', error: unset.error }
+ }
+ launchdExportedKeys = []
+ }
+
+ const running = await checkOllamaAvailable(true)
+ const service = await getServiceStatus().catch(() => null)
+
+ // Nothing to restart. The domain is already clear and a daemon PortOS spawns
+ // inherits the PortOS process environment, so whatever comes up next is
+ // untuned either way.
+ if (!running) {
+ rememberAppliedEnv({}, null)
+ return { applied: null, reason: 'not-running' }
+ }
+
+ // Every failure below leaves the daemon still tuned, so the baseline goes back
+ // on the books for a later run to retry.
+ const failed = (result) => {
+ preTuningEnv = baseline
+ return result
+ }
+
+ // A daemon the user registered to launch at login must keep that
+ // registration: `stopServer` would un-register it. Restart it in place.
+ if (service?.runAtStartup) {
+ if (service.manager !== 'homebrew') {
+ return failed({
+ applied: false,
+ reason: 'service-managed',
+ error: `Ollama runs as a ${service.manager} service, which PortOS can't hand launch settings. ` +
+ `Remove them with: sudo systemctl edit ollama → delete the Environment= lines for ${keys.join(', ')}, then restart it.`
+ })
+ }
+ const bounced = await bounceService()
+ if (!bounced.ok) return failed(bounced.failure)
+ rememberAppliedEnv({}, await getOllamaProcessIdentity())
+ console.log(`▶️ Ollama no longer carries ${keys.join(', ')}`)
+ return { applied: null, reason: 'service-restarted-untuned' }
+ }
+
+ const stopped = await stopServer()
+ if (!stopped.success) return failed({ applied: false, reason: 'stop-failed', error: stopped.error })
+ // `env: {}`, not an omitted `env` — `startServer` records the env it launched
+ // with, and an empty object is the positive statement "this daemon holds no
+ // PortOS tuning". Omitting it records nothing, and the NEXT untuned run would
+ // bounce the daemon again to clear a tuning that is already gone.
+ const started = await startServer({ env: {} })
+ return started.success
+ ? { applied: null, reason: 'restarted-untuned' }
+ : failed({ applied: false, reason: 'start-failed', error: started.error })
+}
+
function isOllamaProvider(provider) {
const endpoint = String(provider?.endpoint || '')
return provider?.id === 'ollama' ||
@@ -745,6 +975,17 @@ async function ensureProviderReady(provider, options = {}) {
* started it; otherwise terminate the local `ollama` process by executable name.
*/
async function stopServer() {
+ const stopped = await stopOllamaProcess()
+ // Whatever spawn-time env the daemon carried left with it, whichever of the
+ // three ways it went down — so there is no longer a tuning to undo. (Anything
+ // PortOS put in the launchd DOMAIN outlives the process and is tracked
+ // separately, by `launchdExportedKeys`.) Done in one place rather than at each
+ // success return, where a fourth stop path would silently miss it.
+ if (stopped.success) preTuningEnv = null
+ return stopped
+}
+
+async function stopOllamaProcess() {
if (!(await checkOllamaAvailable(true))) {
return { success: true, running: false, alreadyStopped: true }
}
diff --git a/server/services/ollamaManager.test.js b/server/services/ollamaManager.test.js
index 67a451f203..0d2149386a 100644
--- a/server/services/ollamaManager.test.js
+++ b/server/services/ollamaManager.test.js
@@ -816,6 +816,19 @@ describe('ollamaManager.restartWithEnv', () => {
// 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.
+ // A homebrew-managed, launch-at-login Ollama that answers every command the
+ // set and clear paths issue. `calls` collects the command lines for assertion.
+ const brewServiceImpl = (calls) => (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 === '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') return cb(null, { stdout: '', stderr: '' })
+ return cb(new Error(`unexpected exec: ${cmd} ${a}`))
+ }
+
function stubReachable(state) {
vi.stubGlobal('fetch', vi.fn(async (url) => {
if (!state.reachable) throw new Error('ECONNREFUSED')
@@ -824,10 +837,255 @@ describe('ollamaManager.restartWithEnv', () => {
}))
}
- it('does nothing when the tuning names no environment', async () => {
+ // `null`, not `false`: nothing was refused. The daemon already runs on its
+ // ambient environment, which is exactly what an untuned assessment claims to
+ // be measuring.
+ it('does nothing when the tuning names no environment and PortOS applied none', async () => {
+ stubReachable({ reachable: true })
+ const { restartWithEnv } = await loadManager()
+ expect(await restartWithEnv({})).toEqual({ applied: null, reason: 'already-untuned' })
+ })
+
+ // The bug: an untuned run following a tuned one sampled a daemon still
+ // carrying `OLLAMA_FLASH_ATTENTION=1` and filed the reading as "Backend
+ // defaults" — a record describing a configuration that never ran.
+ // A stop-then-start clear, with no launch-at-login service in the way. The
+ // daemon has to go DOWN between the two, so reachability is scripted: the
+ // clear's own probe and stopServer's see it up, the stop's wait sees it gone,
+ // and the fresh spawn brings it back. `pid: null` keeps
+ // `terminateManagedProcess` from signalling a real process id.
+ function stubSpawnRestart(state) {
+ execMock.impl = (cmd, args, opts, cb) => cb(new Error(`no service manager: ${cmd}`))
+ return import('../lib/childProcess.js').then(({ spawn }) => {
+ spawn.mockReset().mockImplementation(() => {
+ state.up = true
+ return { pid: null, stderr: { on: () => {} }, on: () => {}, unref: () => {} }
+ })
+ return spawn
+ })
+ }
+
+ it('restarts without the launch env it applied earlier', async () => {
+ const state = { up: false, probesBeforeStop: 0 }
+ stubReachable({ get reachable() { return state.up || state.probesBeforeStop-- > 0 } })
+ const spawn = await stubSpawnRestart(state)
+ const { restartWithEnv } = await loadManager()
+ await restartWithEnv({ OLLAMA_FLASH_ATTENTION: '1' })
+
+ // Model the daemon the tuned start left running, then let the stop take it
+ // down: two probes answer "up" (the clear's check and stopServer's), the
+ // third answers "gone".
+ state.up = false
+ state.probesBeforeStop = 2
+ const cleared = await restartWithEnv({})
+
+ expect(cleared).toMatchObject({ applied: null, reason: 'restarted-untuned' })
+ const [, , options] = spawn.mock.calls[spawn.mock.calls.length - 1]
+ expect(options.env.OLLAMA_FLASH_ATTENTION).toBeUndefined()
+ })
+
+ it('restarts nothing for a second clear once the daemon is already untuned', async () => {
+ const state = { up: false, probesBeforeStop: 0 }
+ stubReachable({ get reachable() { return state.up || state.probesBeforeStop-- > 0 } })
+ const spawn = await stubSpawnRestart(state)
+ const { restartWithEnv } = await loadManager()
+ await restartWithEnv({ OLLAMA_FLASH_ATTENTION: '1' })
+ state.up = false
+ state.probesBeforeStop = 2
+ await restartWithEnv({})
+ const spawnsBefore = spawn.mock.calls.length
+
+ expect(await restartWithEnv({})).toEqual({ applied: null, reason: 'already-untuned' })
+ expect(spawn.mock.calls.length).toBe(spawnsBefore)
+ })
+
+ // `launchctl setenv` writes into the launchd domain, which outlives the daemon
+ // that read it. Omitting the variable from the next restart is NOT clearing
+ // it — every job launched afterwards would still inherit the tuning.
+ it('unsets the launchd variables it exported before bouncing a homebrew service', 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 === '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') return cb(null, { stdout: '', stderr: '' })
+ return cb(new Error(`unexpected exec: ${cmd} ${a}`))
+ }
+
+ const { restartWithEnv } = await loadManager()
+ await restartWithEnv({ OLLAMA_FLASH_ATTENTION: '1', OLLAMA_KV_CACHE_TYPE: 'q4_0' })
+ const cleared = await restartWithEnv({})
+
+ expect(cleared).toMatchObject({ applied: null, reason: 'service-restarted-untuned' })
+ expect(calls).toContain('launchctl unsetenv OLLAMA_FLASH_ATTENTION')
+ expect(calls).toContain('launchctl unsetenv OLLAMA_KV_CACHE_TYPE')
+ expect(calls.filter((c) => c === 'brew services restart ollama')).toHaveLength(2)
+ })
+
+ // `launchctl setenv` is domain-wide, so a key the previous tuning exported and
+ // this one does not name is STILL set. Leaving it there measures the second
+ // tuning against half of the first one.
+ it('unsets a launchd variable the next tuning stops naming', async () => {
+ restorePlatform = pinPlatform('darwin')
stubReachable({ reachable: true })
+ const calls = []
+ execMock.impl = brewServiceImpl(calls)
+
const { restartWithEnv } = await loadManager()
- expect(await restartWithEnv({})).toEqual({ applied: false, reason: 'nothing-to-apply' })
+ await restartWithEnv({ OLLAMA_FLASH_ATTENTION: '1', OLLAMA_KV_CACHE_TYPE: 'q4_0' })
+ calls.length = 0
+ await restartWithEnv({ OLLAMA_FLASH_ATTENTION: '1' })
+
+ expect(calls).toContain('launchctl unsetenv OLLAMA_KV_CACHE_TYPE')
+ expect(calls).not.toContain('launchctl unsetenv OLLAMA_FLASH_ATTENTION')
+ })
+
+ // The variables are in the domain the moment `setenv` returns. Recording them
+ // only after a successful bounce leaves a failed restart with exported
+ // variables nothing knows to clear — and the next untuned run reports
+ // "backend defaults" over them.
+ it('still clears variables it exported before a failed restart', async () => {
+ restorePlatform = pinPlatform('darwin')
+ stubReachable({ reachable: true })
+ const calls = []
+ let restartFails = true
+ execMock.impl = (cmd, args, opts, cb) => {
+ const a = (args || []).join(' ')
+ calls.push(`${cmd} ${a}`)
+ if (cmd === 'brew' && a === 'services restart ollama' && restartFails) {
+ return cb(Object.assign(new Error('restart failed'), { stderr: 'brew: restart failed' }))
+ }
+ return brewServiceImpl([])(cmd, args, opts, cb)
+ }
+
+ const { restartWithEnv } = await loadManager()
+ expect(await restartWithEnv({ OLLAMA_FLASH_ATTENTION: '1' })).toMatchObject({ reason: 'restart-failed' })
+ restartFails = false
+ calls.length = 0
+
+ expect(await restartWithEnv({})).toMatchObject({ applied: null })
+ expect(calls).toContain('launchctl unsetenv OLLAMA_FLASH_ATTENTION')
+ // Unsetting the domain is not enough. The variable was in it, so whatever
+ // daemon is up inherited it and holds it in its OWN process environment —
+ // that one has to be restarted too, or this run measures a tuned daemon and
+ // records it as backend defaults.
+ expect(calls).toContain('brew services restart ollama')
+ })
+
+ // A key PortOS could not set is not PortOS's to unset: the name may belong to
+ // a variable the user exported themselves.
+ it('does not claim a launchd variable whose setenv failed', 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 === 'launchctl' && a.startsWith('setenv')) return cb(new Error('setenv refused'))
+ return brewServiceImpl([])(cmd, args, opts, cb)
+ }
+
+ const { restartWithEnv } = await loadManager()
+ expect(await restartWithEnv({ OLLAMA_FLASH_ATTENTION: '1' })).toMatchObject({ reason: 'setenv-failed' })
+ calls.length = 0
+
+ expect(await restartWithEnv({})).toEqual({ applied: null, reason: 'already-untuned' })
+ expect(calls).toEqual([])
+ })
+
+ // A daemon PortOS just started carries exactly what it was handed, so a later
+ // untuned run has nothing to undo — and must not bounce it (and cold-load the
+ // model) to prove it. Same guarantee `llamaServerManager` gives.
+ it('drops the baseline when a fresh daemon is started over a tuned one', async () => {
+ const state = { up: false, probesBeforeStop: 0 }
+ stubReachable({ get reachable() { return state.up || state.probesBeforeStop-- > 0 } })
+ const spawn = await stubSpawnRestart(state)
+ const { restartWithEnv, startServer, stopServer } = await loadManager()
+ await restartWithEnv({ OLLAMA_FLASH_ATTENTION: '1' })
+
+ // The user stops and restarts Ollama themselves — the daemon that comes back
+ // was never handed a tuning.
+ state.up = false
+ state.probesBeforeStop = 1
+ await stopServer()
+ state.up = false
+ await startServer()
+ const spawnsBefore = spawn.mock.calls.length
+
+ expect(await restartWithEnv({})).toEqual({ applied: null, reason: 'already-untuned' })
+ expect(spawn.mock.calls.length).toBe(spawnsBefore)
+ })
+
+ // `stopServer` has three ways to bring the daemon down. A tuning outstanding
+ // when it goes down the `pkill` fallback (the daemon was not PortOS-spawned)
+ // must drop the baseline just the same, or the next untuned run kills the
+ // user's daemon and cold-loads the model to "restore" a tuning already gone.
+ it('drops the baseline however the daemon was stopped', async () => {
+ const state = { up: false, probesBeforeStop: 0 }
+ stubReachable({ get reachable() { return state.up || state.probesBeforeStop-- > 0 } })
+ const spawn = await stubSpawnRestart(state)
+ const { restartWithEnv, stopServer } = await loadManager()
+ await restartWithEnv({ OLLAMA_FLASH_ATTENTION: '1' })
+
+ // The managed-process path fails to take it down, so the pkill fallback does.
+ execMock.impl = (cmd, args, opts, cb) => (cmd === 'pkill'
+ ? cb(null, { stdout: '', stderr: '' })
+ : cb(new Error(`no service manager: ${cmd}`)))
+ state.up = false
+ state.probesBeforeStop = 1
+ expect(await stopServer()).toMatchObject({ success: true })
+ const spawnsBefore = spawn.mock.calls.length
+
+ expect(await restartWithEnv({})).toEqual({ applied: null, reason: 'already-untuned' })
+ expect(spawn.mock.calls.length).toBe(spawnsBefore)
+ })
+
+ // `ensureContextWindow` puts the user's configured agent window on the same
+ // OLLAMA_CONTEXT_LENGTH a tuning uses. Tearing the launch env down to nothing
+ // in the name of measuring "backend defaults" would silently undo a setting
+ // they chose on the LLMs page — the baseline is what the install runs by
+ // default, not an empty environment.
+ it('restores the pre-tuning env rather than stripping it', async () => {
+ const state = { up: false, probesBeforeStop: 0 }
+ stubReachable({ get reachable() { return state.up || state.probesBeforeStop-- > 0 } })
+ const spawn = await stubSpawnRestart(state)
+ const { ensureContextWindow, restartWithEnv } = await loadManager()
+ await ensureContextWindow(131072)
+ state.up = false
+ state.probesBeforeStop = 2
+ await restartWithEnv({ OLLAMA_CONTEXT_LENGTH: '131072', OLLAMA_FLASH_ATTENTION: '1' })
+ state.up = false
+ state.probesBeforeStop = 2
+
+ expect(await restartWithEnv({})).toMatchObject({ applied: null })
+
+ const [, , options] = spawn.mock.calls[spawn.mock.calls.length - 1]
+ expect(options.env.OLLAMA_FLASH_ATTENTION).toBeUndefined()
+ expect(options.env.OLLAMA_CONTEXT_LENGTH).toBe('131072')
+ })
+
+ // The domain outlives the daemon, so a stopped Ollama is no reason to leave
+ // the variables in it — the next login-launched one would inherit them.
+ it('unsets exported variables even when Ollama is already down', async () => {
+ restorePlatform = pinPlatform('darwin')
+ const state = { reachable: true }
+ stubReachable(state)
+ const calls = []
+ execMock.impl = brewServiceImpl(calls)
+
+ const { restartWithEnv } = await loadManager()
+ await restartWithEnv({ OLLAMA_FLASH_ATTENTION: '1' })
+ state.reachable = false
+ calls.length = 0
+
+ expect(await restartWithEnv({})).toMatchObject({ applied: null, reason: 'not-running' })
+ expect(calls).toContain('launchctl unsetenv OLLAMA_FLASH_ATTENTION')
+ expect(calls).not.toContain('brew services restart ollama')
})
// The knobs only reach Ollama through the process environment, so the whole