Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
address review (codex): keep a tuning's identity, and never file it as evidence it isn't
Adam Eivyfcf3faa6d8f1
diff --git a/client/src/components/settings/LocalModelAssessments.jsx b/client/src/components/settings/LocalModelAssessments.jsxindex 461de6d43c..dae8b5fc33 100644--- a/client/src/components/settings/LocalModelAssessments.jsx+++ b/client/src/components/settings/LocalModelAssessments.jsx@@ -76,6 +76,11 @@ const compactTuning = (draft) => Object.fromEntries(Object.entries(draft || {}).filter(([, v]) => v !== '' && v !== null && v !== undefined));+// A model can hold several measurements, one per launch tuning, so the tuning is+// part of a row's identity — not decoration. Keying on model alone gave two+// variants the same React key and made "discard" target the wrong record.+const entryKey = (entry) => `${entry.backend}:${entry.modelId}@${entry.tuningKey || ''}`;+// `null` is NOT MEASURED and must render as such — never as 0, and never as a// dash the reader could mistake for "measured, none".const Measured = ({ value, suffix = '', digits = 0 }) =>@@ -405,7 +410,7 @@ function TuningComparison({ rows, runtimeLabelFor }) {<span className="text-[10px] text-gray-500">{runtimeLabelFor(row.backend)}</span></div>{row.variants.map((variant, index) => (- <div key={variant.label} className="grid grid-cols-[1fr_auto] gap-2 items-center text-[11px]">+ <div key={`${row.backend}:${row.modelId}@${variant.label}`} className="grid grid-cols-[1fr_auto] gap-2 items-center text-[11px]"><div className="min-w-0"><div className="flex items-center gap-1.5"><span className={index === 0 ? 'text-emerald-400' : 'text-gray-300'}>{variant.label}</span>@@ -675,7 +680,7 @@ export function LocalModelAssessments() {<div className="space-y-2">{report.ranked.map((entry) => (<RankedRow- key={`${entry.backend}:${entry.modelId}`}+ key={entryKey(entry)}entry={entry}runtimeLabel={backendLabel(report, entry.backend)}busy={busy}@@ -695,8 +700,13 @@ export function LocalModelAssessments() {<div className="space-y-1"><h3 className="text-xs font-medium text-gray-400">Measured, but not recommended</h3>{report.excluded.map((entry) => (- <div key={`${entry.backend}:${entry.modelId}`} className="flex items-center gap-2 text-xs flex-wrap">+ <div key={entryKey(entry)} className="flex items-center gap-2 text-xs flex-wrap"><span className="text-gray-300 font-mono break-all">{entry.modelId}</span>+ {/* Several rows can name the same model — one per tuning — so+ the configuration is what tells them apart. */}+ <span className="px-1.5 py-0.5 text-[10px] rounded border border-port-border text-gray-500">+ {entry.tuningLabel || 'backend defaults'}+ </span><VerdictPill verdict={entry.verdict} />{entry.reason && <span className="text-gray-500">{entry.reason}</span>}</div>diff --git a/client/src/components/settings/LocalModelAssessments.test.jsx b/client/src/components/settings/LocalModelAssessments.test.jsxindex 0c31f4e7e8..412d539e6d 100644--- a/client/src/components/settings/LocalModelAssessments.test.jsx+++ b/client/src/components/settings/LocalModelAssessments.test.jsx@@ -472,3 +472,71 @@ describe('LocalModelAssessments — tuning comparison', () => {expect(await screen.findByText('backend defaults')).toBeInTheDocument();});});++// A model can hold several measurements, one per launch tuning. Every action on+// a row therefore has to target THAT measurement — keying on the model alone+// gave two variants the same React key and pointed discard/re-measure at the+// backend-defaults record.+describe('LocalModelAssessments — one row per tuning', () => {+ const tunedEntry = () => rankedEntry({+ backend: 'llama',+ modelId: 'dflash',+ tuningKey: 'ubatchSize=512',+ tuning: { ubatchSize: 512 },+ tuningLabel: 'Micro-batch size 512',+ });++ beforeEach(() => {+ vi.clearAllMocks();+ getLocalLlmAssessments.mockResolvedValue(report({+ ranked: [rankedEntry({ backend: 'llama', modelId: 'dflash', tuningKey: '' }), tunedEntry()],+ assessments: [{ backend: 'llama', modelId: 'dflash', tuningKey: '' }, { backend: 'llama', modelId: 'dflash', tuningKey: 'ubatchSize=512' }],+ }));+ });++ it('labels each variant by its own tuning, not all as backend defaults', async () => {+ render(<LocalModelAssessments />);+ expect(await screen.findByText('Micro-batch size 512')).toBeInTheDocument();+ expect(screen.getByText('backend defaults')).toBeInTheDocument();+ });++ it('discards the tuning the row names, not the backend-defaults record', async () => {+ deleteLocalLlmAssessment.mockResolvedValue({ success: true });+ const user = userEvent.setup();+ render(<LocalModelAssessments />);+ const buttons = await screen.findAllByRole('button', { name: /Discard the measurement for dflash/ });+ // Ranked order puts the tuned row second (both score alike, tie broken on+ // tuning signature: '' sorts before 'ubatchSize=512').+ await user.click(buttons[1]);+ await waitFor(() => expect(deleteLocalLlmAssessment)+ .toHaveBeenCalledWith('llama', 'dflash', 'ubatchSize=512', { silent: true }));+ });++ // Re-measure should reproduce the configuration that produced the row, so+ // adjusting one knob is a one-field edit rather than re-entering the set.+ it('pre-fills a re-measure from the row\'s own tuning', async () => {+ runLocalLlmAssessment.mockResolvedValue({ verdict: 'fits', tuningApplied: true });+ const user = userEvent.setup();+ render(<LocalModelAssessments />);+ const remeasure = await screen.findAllByRole('button', { name: /Measure dflash again/ });+ await user.click(remeasure[1]);+ await user.click(await screen.findByRole('button', { name: 'Run assessment' }));+ await waitFor(() => expect(runLocalLlmAssessment).toHaveBeenCalledWith(+ expect.objectContaining({ tuning: { ubatchSize: 512 } }),+ expect.anything(),+ ));+ });++ it('warns on a ranked row whose tuning never reached the daemon', async () => {+ getLocalLlmAssessments.mockResolvedValue(report({+ ranked: [rankedEntry({+ tuningKey: 'ubatchSize=512',+ tuningLabel: 'Micro-batch size 512',+ tuningApplied: false,+ tuningNotApplied: 'llama-server is not running',+ })],+ }));+ render(<LocalModelAssessments />);+ expect(await screen.findByText(/Tuning was not applied/)).toBeInTheDocument();+ });+});diff --git a/server/lib/localModelAssessment.js b/server/lib/localModelAssessment.jsindex 9d9bacadbe..ec0777396f 100644--- a/server/lib/localModelAssessment.js+++ b/server/lib/localModelAssessment.js@@ -308,6 +308,8 @@ export function rankByIntent(assessments, intent = 'balanced') {excluded.push({backend: assessment?.backend || null,modelId: assessment?.modelId || null,+ tuningKey: assessment?.tuningKey || '',+ tuningLabel: assessment?.tuningLabel || null,verdict,reason: assessment?.verdictReason || null,});@@ -319,6 +321,8 @@ export function rankByIntent(assessments, intent = 'balanced') {excluded.push({backend: assessment?.backend || null,modelId: assessment?.modelId || null,+ tuningKey: assessment?.tuningKey || '',+ tuningLabel: assessment?.tuningLabel || null,verdict,reason: 'ran, but no axis of this intent was measured',});@@ -343,6 +347,19 @@ export function rankByIntent(assessments, intent = 'balanced') {// `null` = the caller did not annotate staleness, which is not the same as// "compared and current".staleness: assessment?.staleness || null,+ // The tuning IS part of this row's identity, not decoration. A model can+ // hold several measurements, one per launch configuration, and the+ // consumer uses these to key the row, to delete THIS measurement rather+ // than the backend-defaults one, and to pre-fill a re-measure with the+ // configuration that produced it. Dropping them collapsed every variant+ // onto the default record.+ tuningKey: assessment?.tuningKey || '',+ tuning: assessment?.tuning || {},+ tuningLabel: assessment?.tuningLabel || null,+ // `null` = nothing was settable (see runAssessment); `false` means these+ // numbers describe some OTHER configuration, which the row has to say.+ tuningApplied: assessment?.tuningApplied ?? null,+ tuningNotApplied: assessment?.tuningNotApplied || null,explanation: explainAssessment(assessment, resolvedIntent),});}@@ -361,7 +378,10 @@ export function rankByIntent(assessments, intent = 'balanced') {(isStale(a) - isStale(b))|| (b.score - a.score)|| (b.coverage - a.coverage)- || String(a.modelId).localeCompare(String(b.modelId)));+ || String(a.modelId).localeCompare(String(b.modelId))+ // Two tunings of ONE model tie on model id, so the signature is what makes+ // their order stable across reloads.+ || String(a.tuningKey).localeCompare(String(b.tuningKey)));return { intent: resolvedIntent, ranked, excluded };}diff --git a/server/lib/localModelAssessment.test.js b/server/lib/localModelAssessment.test.jsindex 2ab3baea4e..7d5fd97658 100644--- a/server/lib/localModelAssessment.test.js+++ b/server/lib/localModelAssessment.test.js@@ -228,6 +228,72 @@ describe('explainAssessment', () => {});});+// The tuning IS the row's identity when a model holds several measurements. The+// consumer keys the row on it, deletes THIS measurement with it, and pre-fills a+// re-measure from it — so a projection that drops it collapses every variant+// onto the backend-defaults record (wrong row deleted, re-measure loses its+// settings, duplicate React keys).+describe('rankByIntent — tuning identity', () => {+ const tuned = (tuningKey, tuning, tuningLabel, charsPerSecond) => ({+ backend: 'llama',+ modelId: 'example-7b',+ verdict: 'fits',+ params: '7B',+ tuningKey,+ tuning,+ tuningLabel,+ performance: { meanCharsPerSecond: charsPerSecond, contextDegradation: 0.9, maxWorkingContextTokens: 16384 },+ environment: { memoryBudgetGb: 64 },+ residentGb: 5,+ });++ it('carries the tuning through to every ranked row', () => {+ const { ranked } = rankByIntent([+ tuned('', {}, null, 90),+ tuned('ubatchSize=512', { ubatchSize: 512 }, 'Micro-batch size 512', 120),+ ], 'fastest');+ expect(ranked).toHaveLength(2);+ expect(ranked.map((r) => r.tuningKey).sort()).toEqual(['', 'ubatchSize=512']);+ const fastest = ranked[0];+ expect(fastest.tuningKey).toBe('ubatchSize=512');+ expect(fastest.tuning).toEqual({ ubatchSize: 512 });+ expect(fastest.tuningLabel).toBe('Micro-batch size 512');+ });++ it('gives two tunings of one model distinct identities, not one collapsed row', () => {+ const { ranked } = rankByIntent([+ tuned('', {}, null, 90),+ tuned('ubatchSize=512', { ubatchSize: 512 }, 'Micro-batch size 512', 120),+ ], 'fastest');+ const keys = ranked.map((r) => `${r.backend}:${r.modelId}@${r.tuningKey}`);+ expect(new Set(keys).size).toBe(2);+ });++ it('reports that a tuning was not applied so the row can say the numbers are another config', () => {+ const entry = tuned('ubatchSize=512', { ubatchSize: 512 }, 'Micro-batch size 512', 120);+ const { ranked } = rankByIntent([+ { ...entry, tuningApplied: false, tuningNotApplied: 'llama-server is not running' },+ ], 'fastest');+ expect(ranked[0].tuningApplied).toBe(false);+ expect(ranked[0].tuningNotApplied).toBe('llama-server is not running');+ });++ it('breaks a model-id tie on the tuning so the order is stable across reloads', () => {+ const a = tuned('a=1', {}, 'A', 100);+ const b = tuned('b=2', { }, 'B', 100);+ expect(rankByIntent([b, a], 'fastest').ranked.map((r) => r.tuningKey)).toEqual(['a=1', 'b=2']);+ expect(rankByIntent([a, b], 'fastest').ranked.map((r) => r.tuningKey)).toEqual(['a=1', 'b=2']);+ });++ it('carries the tuning onto an excluded row too, so variants stay distinguishable there', () => {+ const { excluded } = rankByIntent([+ { ...tuned('ubatchSize=512', { ubatchSize: 512 }, 'Micro-batch size 512', 120), verdict: 'does-not-fit' },+ ], 'fastest');+ expect(excluded[0].tuningKey).toBe('ubatchSize=512');+ expect(excluded[0].tuningLabel).toBe('Micro-batch size 512');+ });+});+describe('rankByIntent', () => {const assessment = (modelId, verdict, performance, extra = {}) => ({backend: 'ollama',@@ -263,7 +329,7 @@ describe('rankByIntent', () => {const { ranked, excluded } = rankByIntent(models, 'balanced');expect(ranked.map((r) => r.modelId)).toEqual(['example-model:7b']);expect(excluded).toEqual([- { backend: 'ollama', modelId: 'example-model:70b', verdict: 'does-not-fit', reason: 'out of memory' },+ { backend: 'ollama', modelId: 'example-model:70b', tuningKey: '', tuningLabel: null, verdict: 'does-not-fit', reason: 'out of memory' },]);});diff --git a/server/services/llamaServerManager.js b/server/services/llamaServerManager.jsindex 77daa0880d..1d9ab7291e 100644--- a/server/services/llamaServerManager.js+++ b/server/services/llamaServerManager.js@@ -26,6 +26,12 @@ const PROBE_TIMEOUT_MS = 1500;const STARTUP_WAIT_TIMEOUT_MS = 4000;// How long a relaunch waits for the kernel to release the old listener.const PORT_RELEASE_TIMEOUT_MS = 5000;+// How long a relaunch waits for the new process to answer. `startLlamaServer`+// polls for only STARTUP_WAIT_TIMEOUT_MS, which a large GGUF routinely exceeds+// while loading — so a relaunch must not read "not ready yet" as "wedged".+// Mutable only through the test seam below: a suite asserting the give-up path+// cannot sit through two real minutes of polling.+let relaunchReadyTimeoutMs = 120000;let currentConfig = null;let recentLogs = [];@@ -460,6 +466,19 @@ async function waitForPortRelease(port) {while (Date.now() < deadline && await isPortInUse(port)) await sleep(200);}+/**+ * Block until the endpoint answers, or the readiness budget elapses.+ * `false` means it never answered — which is a wedged process, not a slow one.+ */+async function waitForEndpoint(endpoint) {+ const deadline = Date.now() + relaunchReadyTimeoutMs;+ while (Date.now() < deadline) {+ if (await probeEndpoint(endpoint)) return true;+ await sleep(1000);+ }+ return false;+}+/*** Relaunch llama-server with a different tuning, keeping the model/drafter it is* already serving.@@ -529,12 +548,28 @@ export async function relaunchLlamaServerWithTuning(tuning = {}) {return { applied: false, reason: `llama-server rejected that tuning: ${started.failure}`, config: started.config };}- // PM2 reporting `online` is not the same as the server answering. A daemon- // that never opened its port has not had the tuning applied in any sense a- // measurement could rest on, so say so rather than filing the samples that- // follow under a configuration nothing could reach.- if (!started.online) {- return { applied: false, reason: 'llama-server relaunched but never answered on its port', config: started.config };+ // PM2 reporting `online` is not the same as the server answering. But+ // `startLlamaServer` only polls for four seconds, and a large GGUF routinely+ // takes longer than that to load — so `online: false` is "not ready YET",+ // not "wedged". Give it a real readiness budget before judging.+ const ready = started.online || await waitForEndpoint(started.endpoint);+ if (!ready) {+ // Still silent. Treat it exactly like a rejected launch line: put the+ // previous configuration back, so the install's llama provider is not left+ // pointing at a process that never serves. Without this the caller would go+ // on to measure a dead endpoint and record the timeouts as evidence.+ console.error('❌ llama-server: relaunched process never answered — restoring the previous configuration');+ await stopLlamaServer().catch(() => {});+ await waitForPortRelease(previous.port ?? PORTS.LLAMA_SERVER);+ const restored = await startLlamaServer(previous).catch((err) => {+ console.error(`❌ llama-server: could not restore the previous configuration: ${err.message}`);+ return null;+ });+ 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 };}@@ -654,9 +689,11 @@ export async function installLlamaServer({ onProgress = () => {} } = {}) {/*** Clears in-memory test state (used by test suites).*/-export function _resetLlamaServerStateForTests() {+export function _resetLlamaServerStateForTests({ relaunchReadyTimeout } = {}) {currentConfig = null;recentLogs = [];lastExitError = null;+ // Restored to the production budget unless a suite asks for a shorter one.+ relaunchReadyTimeoutMs = Number.isFinite(relaunchReadyTimeout) ? relaunchReadyTimeout : 120000;}diff --git a/server/services/llamaServerManager.test.js b/server/services/llamaServerManager.test.jsindex f56d7c6ec2..f55c99f821 100644--- a/server/services/llamaServerManager.test.js+++ b/server/services/llamaServerManager.test.js@@ -531,14 +531,44 @@ describe('llamaServerManager', () => {// PM2 reporting `online` is not the same as the server answering. A daemon// that never opened its port has not had the tuning applied in any sense a// measurement could rest on.+ // `startLlamaServer` polls for only four seconds, and a large GGUF routinely+ // takes longer than that to load. Treating "not ready yet" as "wedged" would+ // tear down a launch that was about to succeed.+ it('waits past the start probe for a slow load rather than calling it wedged', async () => {+ await started();+ let answerAfter = 3;+ vi.spyOn(openAiModelsProbe, 'probeOpenAiModels').mockImplementation(async () => {+ if (pm2State?.status !== 'online') return { reachable: false };+ return { reachable: answerAfter-- <= 0 };+ });+ execPm2Calls = [];+ const result = await relaunchLlamaServerWithTuning({ ubatchSize: 512 });+ expect(result.applied).toBe(true);+ // One start only — the slow load was waited out, not restarted.+ expect(execPm2Calls.filter((c) => c[0] === 'start')).toHaveLength(1);+ });+it('reports not-applied when the relaunched server never answers', async () => {await started();// PM2 keeps reporting `online` while the endpoint stays silent — the exact// split the check exists for.vi.spyOn(openAiModelsProbe, 'probeOpenAiModels').mockResolvedValue({ reachable: false });+ // Shrink the readiness budget: the give-up path is what's under test, and+ // the production two minutes would just be two minutes of sleeping.+ _resetLlamaServerStateForTests({ relaunchReadyTimeout: 1500 });+ execPm2Calls = [];const result = await relaunchLlamaServerWithTuning({ ubatchSize: 512 });expect(result.applied).toBe(false);expect(result.reason).toMatch(/never answered/);- });+ // A silent process must not be LEFT running: this daemon fronts the llama+ // provider for the whole install, so the previous configuration goes back+ // exactly as it does for a launch line llama.cpp rejects outright.+ const restore = execPm2Calls.filter((c) => c[0] === 'start').at(-1);+ expect(restore).not.toContain('-ub');+ expect(restore[restore.indexOf('-m') + 1]).toBe(modelPath);+ // Two full start cycles (each polling `STARTUP_WAIT_TIMEOUT_MS` against a+ // deliberately-silent probe) plus the readiness budget — slow by design,+ // not by accident, so this one test buys the room rather than the suite.+ }, 30000);});});diff --git a/server/services/localLlmPlayground.js b/server/services/localLlmPlayground.jsindex 218c0baa4e..f1f98565e8 100644--- a/server/services/localLlmPlayground.js+++ b/server/services/localLlmPlayground.js@@ -218,6 +218,9 @@ export async function runLocalLlmTest({export async function runEndpointLlmTest({runtime,endpoint,+ // Empty for the usual unauthenticated loopback daemon; set for a vLLM+ // container started behind `VLLM_API_KEY`, which 401s without it.+ apiKey = '',modelId,prompt,systemPrompt = '',@@ -237,6 +240,7 @@ export async function runEndpointLlmTest({try {const text = await streamOpenAiChat({endpoint,+ apiKey,model: modelId,messages: buildMessages({ systemPrompt, prompt }),temperature,diff --git a/server/services/localModelAssessments.js b/server/services/localModelAssessments.jsindex 960505a486..1ba31a6e09 100644--- a/server/services/localModelAssessments.js+++ b/server/services/localModelAssessments.js@@ -62,6 +62,7 @@ import {LOCAL_RUNTIMES,MANAGED_ASSESSMENT_BACKENDS,isEndpointRuntime,+ localRuntimeKind,} from '../lib/localProviderRuntime.js';import {compareTunings,@@ -73,6 +74,7 @@ import {tuningSpecsFor,} from '../lib/localModelTuning.js';import { probeOpenAiModels } from '../lib/openAiModelsProbe.js';+import { getAllProviders } from './providers.js';import { runEndpointLlmTest, runLocalLlmTest } from './localLlmPlayground.js';import { getLlamaServerEndpoint, relaunchLlamaServerWithTuning } from './llamaServerManager.js';import { listModels } from './localLlm.js';@@ -156,6 +158,25 @@ export async function runtimeEndpoint(runtime) {return LOCAL_RUNTIMES[runtime]?.defaultBaseUrl || null;}+/**+ * The API key a bare endpoint runtime is served behind, or `''` for the usual+ * unauthenticated loopback daemon.+ *+ * A vLLM container started from the shipped compose stack sets `VLLM_API_KEY`+ * and answers 401 to an unauthenticated request — which `probeOpenAiModels`+ * correctly reports as "reachable, listing unreadable" and a measurement would+ * hit on every sample. `providerReadiness.js` already solves this by reading the+ * key off the matching provider record; this resolves it the same way, keyed on+ * the same `localRuntimeKind` classifier so the two can't disagree about which+ * provider backs which runtime.+ */+export async function runtimeApiKey(runtime) {+ const providers = await getAllProviders().catch(() => []);+ const match = (Array.isArray(providers) ? providers : [])+ .find((p) => localRuntimeKind(p) === runtime && typeof p?.apiKey === 'string' && p.apiKey !== '');+ return match?.apiKey || '';+}+/*** Models this runtime can be measured against, plus why the list failed when it* did.@@ -184,7 +205,7 @@ export async function listRuntimeModels(runtime) {const endpoint = await runtimeEndpoint(runtime);if (!endpoint) return { models: null, error: 'no endpoint is configured for this runtime' };- const probe = await probeOpenAiModels(endpoint, { timeoutMs: 2500 });+ const probe = await probeOpenAiModels(endpoint, { timeoutMs: 2500, apiKey: await runtimeApiKey(runtime) });if (!probe.reachable) return { models: null, error: `not reachable at ${endpoint} (${probe.error})` };if (!probe.models) return { models: null, error: probe.error || 'model listing was not readable' };// An endpoint runtime reports ids only — no params, no quantization. `null`@@ -302,6 +323,9 @@ export async function runAssessment({ backend, modelId, contextTokens = DEFAULT_if (isEndpointRuntime(backend) && !endpoint) {throw new Error(`No endpoint is configured for the ${backend} runtime`);}+ // Same key the listing probe used — a key-gated vLLM 401s every sample+ // otherwise, and the run would record "does-not-fit" for an auth failure.+ const apiKey = endpoint ? await runtimeApiKey(backend) : '';const environment = await captureEnvironment({ backend });const { models: installed } = await listRuntimeModels(backend);@@ -343,7 +367,7 @@ export async function runAssessment({ backend, modelId, contextTokens = DEFAULT_signal,};const result = await (endpoint- ? runEndpointLlmTest({ ...shared, runtime: backend, endpoint })+ ? runEndpointLlmTest({ ...shared, runtime: backend, endpoint, apiKey }): runLocalLlmTest({ ...shared, backend })).catch((err) => ({ backend, modelId, text: '', error: err?.message || 'assessment run failed' }));@@ -479,7 +503,26 @@ export async function getAssessmentReport({ intent = 'balanced' } = {}) {.filter((a) => !isStillInstalled(a)).map((a) => ({ backend: a?.backend || null, modelId: a?.modelId || null, tuningLabel: a?.tuningLabel || null }));- const { ranked, excluded } = rankByIntent(stillInstalled, resolvedIntent);+ // A reading taken under a tuning PortOS could NOT apply describes some other+ // configuration entirely. It is kept on disk (the run cost real minutes, and+ // the failed attempt plus its reason is what tells the user why) but it must+ // never be scored AS that tuning: ranking it would recommend a configuration+ // nobody measured, and comparing it would credit the previous config's+ // throughput to the knobs that never reached the daemon.+ const unappliedTuning = stillInstalled.filter((a) => a?.tuningApplied === false);+ const scorable = stillInstalled.filter((a) => a?.tuningApplied !== false);++ const { ranked, excluded } = rankByIntent(scorable, resolvedIntent);+ for (const a of unappliedTuning) {+ excluded.push({+ backend: a?.backend || null,+ modelId: a?.modelId || null,+ 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'}`,+ });+ }// "Not yet measured" is keyed on the model, NOT on the model+tuning: once one// tuning has been measured the model is no longer an unanswered question, and@@ -504,7 +547,7 @@ export async function getAssessmentReport({ intent = 'balanced' } = {}) {// so the UI renders one source of truth instead of a hardcoded backend list.runtimes,// Which tuning won, per model, for models measured under two or more.- tuningComparison: compareTunings(stillInstalled),+ tuningComparison: compareTunings(scorable),// Runtimes whose model list could not be trusted — distinct from "listed,// and legitimately empty".listErrors,diff --git a/server/services/localModelAssessments.test.js b/server/services/localModelAssessments.test.jsindex 5511e256a7..7ab570a446 100644--- a/server/services/localModelAssessments.test.js+++ b/server/services/localModelAssessments.test.js@@ -31,6 +31,11 @@ vi.mock('./localLlmPlayground.js', () => ({const probeOpenAiModels = vi.fn();vi.mock('../lib/openAiModelsProbe.js', () => ({ probeOpenAiModels: (...args) => probeOpenAiModels(...args) }));+// `runtimeApiKey` reads the provider registry to authenticate a key-gated+// runtime (a vLLM container started behind VLLM_API_KEY).+const getAllProviders = vi.fn();+vi.mock('./providers.js', () => ({ getAllProviders: (...args) => getAllProviders(...args) }));+const getLlamaServerEndpoint = vi.fn();const relaunchLlamaServerWithTuning = vi.fn();vi.mock('./llamaServerManager.js', () => ({@@ -82,6 +87,7 @@ beforeEach(() => {runEndpointLlmTest.mockReset();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 });});@@ -716,3 +722,85 @@ describe('runtime roster', () => {expect(report.runtimes.find((r) => r.id === 'ollama').modelCount).toBe(1);});});+++// ---------------------------------------------------------------------------+// Key-gated runtimes, and evidence hygiene for a tuning that never landed+// ---------------------------------------------------------------------------++describe('key-gated runtimes', () => {+ // `vllmBacked` is the structural marker `localRuntimeKind` keys on — it+ // deliberately does NOT derive the backend from an editable name or endpoint.+ const vllmProvider = { id: 'vllm', name: 'vLLM', vllmBacked: true, endpoint: 'http://127.0.0.1:18020/v1', apiKey: 'secret-key' };++ // A vLLM container from the shipped compose stack sets VLLM_API_KEY and 401s+ // an unauthenticated request. Without the key the listing reads as+ // "unreadable" and every sample fails auth — recorded as a fit verdict.+ it('authenticates the model listing with the provider record\'s key', async () => {+ getAllProviders.mockResolvedValue([vllmProvider]);+ probeOpenAiModels.mockResolvedValue({ reachable: true, models: ['qwen'], error: null });+ await svc.listRuntimeModels('vllm');+ expect(probeOpenAiModels).toHaveBeenCalledWith(expect.any(String), expect.objectContaining({ apiKey: 'secret-key' }));+ });++ it('authenticates the measurement with the same key', async () => {+ getAllProviders.mockResolvedValue([vllmProvider]);+ probeOpenAiModels.mockResolvedValue({ reachable: true, models: ['qwen'], error: null });+ runEndpointLlmTest.mockResolvedValue(okRun());+ await svc.runAssessment({ backend: 'vllm', modelId: 'qwen', contextTokens: [512] });+ expect(runEndpointLlmTest).toHaveBeenCalledWith(expect.objectContaining({ apiKey: 'secret-key' }));+ });++ // The usual loopback daemon is unauthenticated; attaching a key from an+ // unrelated provider would be worse than sending none.+ it('sends no key when no provider for that runtime carries one', async () => {+ getAllProviders.mockResolvedValue([{ id: 'ollama', ollamaBacked: true, endpoint: 'http://localhost:11434/v1', apiKey: 'not-mine' }]);+ probeOpenAiModels.mockResolvedValue({ reachable: true, models: [], error: null });+ await svc.listRuntimeModels('mtplx');+ expect(probeOpenAiModels).toHaveBeenCalledWith(expect.any(String), expect.objectContaining({ apiKey: '' }));+ });+});++describe('unapplied tuning is not evidence', () => {+ const measureWithUnappliedTuning = async () => {+ probeOpenAiModels.mockResolvedValue({ reachable: true, models: ['dflash'], error: null });+ runEndpointLlmTest.mockResolvedValue(okRun(40, 150));+ relaunchLlamaServerWithTuning.mockResolvedValue({ applied: false, reason: 'llama-server is not running', config: null });+ await svc.runAssessment({ backend: 'llama', modelId: 'dflash', contextTokens: [512], tuning: { ubatchSize: 512 } });+ };++ // The numbers describe the configuration that was ACTUALLY running. Ranking+ // them would recommend a tuning nobody measured.+ it('keeps the record but never ranks it', async () => {+ await measureWithUnappliedTuning();+ const report = await svc.getAssessmentReport();+ expect(report.assessments).toHaveLength(1);+ expect(report.ranked).toEqual([]);+ expect(report.excluded[0].reason).toMatch(/tuning was not applied/);+ expect(report.excluded[0].tuningKey).toBe('ubatchSize=512');+ });++ // Comparing it would credit the previous config's throughput to knobs that+ // never reached the daemon.+ it('never lets it win a tuning comparison', async () => {+ // A real, applied backend-defaults reading first — llama is an endpoint+ // runtime, so it measures through runEndpointLlmTest either way.+ probeOpenAiModels.mockResolvedValue({ reachable: true, models: ['dflash'], error: null });+ runEndpointLlmTest.mockResolvedValue(okRun(40, 90));+ await svc.runAssessment({ backend: 'llama', modelId: 'dflash', contextTokens: [512] });+ // …then a faster one whose tuning never reached the daemon. Two records+ // exist, so the only thing stopping a comparison is the exclusion itself.+ await measureWithUnappliedTuning();+ expect(await svc.loadAssessments()).toHaveLength(2);+ const report = await svc.getAssessmentReport();+ expect(report.tuningComparison).toEqual([]);+ });++ it('still ranks a tuning that WAS applied', async () => {+ probeOpenAiModels.mockResolvedValue({ reachable: true, models: ['dflash'], error: null });+ runEndpointLlmTest.mockResolvedValue(okRun(40, 150));+ await svc.runAssessment({ backend: 'llama', modelId: 'dflash', contextTokens: [512], tuning: { ubatchSize: 512 } });+ const report = await svc.getAssessmentReport();+ expect(report.ranked.map((r) => r.tuningKey)).toEqual(['ubatchSize=512']);+ });+});