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
feat: give MTPLX real launch-tuning knobs on its mtplx serve command line (#4746)
[._.]/ Adam Eivy10055e674bfa
diff --git a/client/src/components/settings/LocalModelAssessments.test.jsx b/client/src/components/settings/LocalModelAssessments.test.jsxindex 4bd9ada099..0b27cec5f2 100644--- a/client/src/components/settings/LocalModelAssessments.test.jsx+++ b/client/src/components/settings/LocalModelAssessments.test.jsx@@ -58,7 +58,10 @@ const RUNTIMES = [{ id: 'ubatchSize', label: 'Micro-batch size', type: 'number', applies: 'launch', config: true, min: 1, max: 8192, hint: 'Physical micro-batch.', note: "PortOS puts this on the server's launch line and relaunches it." },{ id: 'flashAttn', label: 'Flash attention', type: 'boolean', applies: 'launch', config: true, hint: 'Fused attention kernel.', note: "PortOS puts this on the server's launch line and relaunches it." },] },- { id: 'mtplx', label: 'MTPLX', managed: false, modelCount: null, error: 'not reachable at http://127.0.0.1:8000/v1 (ECONNREFUSED)', tuningSpecs: [] },+ { id: 'mtplx', label: 'MTPLX', managed: false, modelCount: null, error: 'not reachable at http://127.0.0.1:8000/v1 (ECONNREFUSED)', tuningSpecs: [+ { id: 'depth', label: 'MTP depth', type: 'number', applies: 'launch', cli: '--depth', min: 1, max: 8, hint: 'Draft lookahead.', note: 'PortOS relaunches `mtplx serve` with `--depth` on its command line.' },+ { id: 'kvQuant', label: 'KV cache quantization', type: 'enum', applies: 'launch', cli: '--kv-quant', options: ['off', 'q8', 'q4'], hint: 'Context length for a little quality.', note: 'PortOS relaunches `mtplx serve` with `--kv-quant` on its command line.' },+ ] },];// The sweep queue is server state the panel reads on mount. Every suite herediff --git a/docs/features/mtplx.md b/docs/features/mtplx.mdindex 31b90da4bd..d2f862de38 100644--- a/docs/features/mtplx.md+++ b/docs/features/mtplx.md@@ -144,7 +144,40 @@ not offer to stop a process it did not start.All presets are disabled by default. Merely updating PortOS does not make anetwork request, invoke a model, tune speculative decoding, alter the activeprovider, or install anything — the setup above runs only from that explicit-click. MTPLX tuning remains an explicit operator action outside PortOS.+click. Nothing relaunches `mtplx serve` on its own either; the tuning below runs+only from an assessment you start.++## Tuning the launch line++**Models → LLMs → measured assessments** can relaunch `mtplx serve` with+different flags between runs, so "how fast is this checkpoint here?" can be+answered per configuration rather than once. The knobs PortOS offers are the ones+it can actually put on the launch line:++| Knob | Flag | What it trades |+| --- | --- | --- |+| Context window | `--context-window` | Prompt length against unified memory |+| MTP depth | `--depth` | Draft lookahead — deeper wins more when accepted, costs more when rejected |+| Decode mode | `--generation-mode` | Native multi-token speculative decode vs plain autoregressive |+| KV cache quantization | `--kv-quant` | Context length against a little quality |+| Batching preset | `--batching-preset` | Per-request latency against total throughput |+| Runtime profile | `--profile` | MTPLX's own bundle: peak rate vs holding up over a long run |++Each measurement is stored under the tuning it ran with, so several tunings of+one checkpoint coexist and can be ranked against each other.++Two things worth knowing:++- **A launch line MTPLX rejects does not leave the daemon down.** `mtplx serve`+ exits before it binds on a flag or value it will not accept, so PortOS puts the+ previous configuration back up and records the reading as *not* applied, naming+ the reason. A sweep is expected to produce launch lines that do not work.+- **The knobs come from MTPLX's own argument parser**, not from its feature docs,+ and only flags stable across MTPLX releases are offered. If your MTPLX is old+ enough to reject one, you get the refusal above rather than a dead provider.++`mtplx tune` — upstream's own depth auto-tuner, which writes a saved winner into+MTPLX's config — stays an explicit operator action outside PortOS.## Startup at bootdiff --git a/server/lib/localModelTuning.js b/server/lib/localModelTuning.jsindex 78810febf4..538e7475b0 100644--- a/server/lib/localModelTuning.js+++ b/server/lib/localModelTuning.js@@ -26,8 +26,9 @@* llama-server command line and relaunches. → `launchConfig`* - `env: 'NAME'` — an environment variable PortOS hands `ollama serve`* when it restarts the daemon. → `launchEnv`- * - `cli: '--flag'` — an `lms load` flag PortOS passes when it reloads the- * LM Studio model. → `launchArgs`+ * - `cli: '--flag'` — a launch flag PortOS puts on the command line of a+ * daemon it re-runs: `lms load` for LM Studio, `mtplx+ * serve` for MTPLX. → `launchArgs`* - `wire: 'field'` — a field PortOS merges into each measurement request* body. → `requestBody`*@@ -49,9 +50,21 @@* is kept because a runtime that does honour per-request knobs (vLLM) is the* likely next entry.*- * MTPLX and vLLM therefore declare no knobs: PortOS starts MTPLX under PM2 but- * passes only `--port`/`--model`, and it does not start vLLM at all. Add knobs- * there once there is a launch path that carries them.+ * vLLM therefore declares no knobs: PortOS does not start it — it is a container+ * from the shipped compose stack, so there is no launch line to put a flag on.+ * Add knobs there once PortOS manages that container's lifecycle.+ *+ * ## Verifying an `mtplx serve` flag before declaring it+ *+ * MTPLX's knobs were read off its own `serve` argument parser (upstream+ * `mtplx/cli.py`), not off its feature docs, and every one below was checked to+ * exist unchanged from MTPLX v1.0.0 through v2.9.0 — including the enum SPELLINGS,+ * since argparse rejects an unlisted choice exactly as it rejects an unknown+ * flag. That matters more here than for the other runtimes: `mtplx serve` exits+ * before it binds on a flag it does not recognize, which the LLMs page reports as+ * "the server would not start". Verify the same way (`mtplx serve --help`, or the+ * upstream parser) before adding one, and prefer a flag with a long history over+ * one that appeared in the current release.** ## The sentinel contract*@@ -70,6 +83,17 @@*/const CACHE_TYPES = ['f16', 'q8_0', 'q4_0'];+/**+ * The command a `cli` knob's flag lands on, per runtime. Two runtimes now share+ * the `cli` transport but re-run different binaries, and the note has to name the+ * one the user would see in `ps` — "PortOS reloads the model with `lms load …`"+ * on an MTPLX knob would describe a command that never runs.+ */+const CLI_COMMAND = {+ lmstudio: (flag) => `PortOS reloads the model with \`lms load ${flag}\`.`,+ mtplx: (flag) => `PortOS relaunches \`mtplx serve\` with \`${flag}\` on its command line.`,+};+/*** The user-facing sentence for a knob: what PortOS will DO with it, naming the* flag or variable it becomes. Derived from the transport so the form, the@@ -77,20 +101,25 @@ const CACHE_TYPES = ['f16', 'q8_0', 'q4_0'];* on the spec, so the note lives with the module that owns the transport rather* than being re-derived in the UI.*/-const noteFor = (spec) => {+const noteFor = (runtimeId, spec) => {if (spec.wire) return `Sent with each measurement request as \`${spec.wire}\`.`;if (spec.env) return `PortOS restarts the server with ${spec.env} set.`;- if (spec.cli) return `PortOS reloads the model with \`lms load ${spec.cli}\`.`;+ // A `cli` runtime with no entry above falls back to naming the flag alone+ // rather than borrowing another runtime's command — vague, but never wrong.+ if (spec.cli) {+ const describe = CLI_COMMAND[runtimeId];+ return describe ? describe(spec.cli) : `PortOS puts \`${spec.cli}\` on the server's launch line and relaunches it.`;+ }return "PortOS puts this on the server's launch line and relaunches it.";};// `applies` and `note` are computed, never written by hand — see the transport// rule above. A spec with no transport gets `applies: 'launch'` and a note it// cannot honour, which is what the catalog guard test exists to catch.-const decorate = (spec) => Object.freeze({+const decorate = (runtimeId, spec) => Object.freeze({...spec,applies: spec.wire ? 'request' : 'launch',- note: noteFor(spec),+ note: noteFor(runtimeId, spec),});/**@@ -131,15 +160,30 @@ const RAW_SPECS = {{ id: 'gpuOffload', label: 'GPU offload', type: 'number', cli: '--gpu', min: 0, max: 1, step: 0.05, hint: 'Fraction of layers on the GPU (0 = CPU only, 1 = full offload). Lower frees VRAM for a bigger context at the cost of throughput.' },{ id: 'parallel', label: 'Parallel requests', type: 'number', cli: '--parallel', min: 1, max: 16, hint: 'Predictions the model runs at once. Higher total throughput, slower per prediction.' },],- // PortOS starts MTPLX under PM2 but passes only `--port` and `--model`, and it- // does not start vLLM at all — so neither has a knob it could apply. Left+ // `mtplx serve` flags, applied by relaunching the PM2 daemon on a new command+ // line. Ordered context → decode → memory → preset, so the form reads from the+ // knob that decides whether a prompt fits down to the ones that trade latency+ // for throughput. Every flag verified against upstream's own argument parser —+ // see the verification note at the top of this file before adding another.+ mtplx: [+ { id: 'contextWindow', label: 'Context window', type: 'number', cli: '--context-window', min: 512, max: 1048576, unit: 'tokens', hint: 'Overrides the window MTPLX reads from the model config. Larger costs unified memory up front, and past what fits the server will not load.' },+ { id: 'depth', label: 'MTP depth', type: 'number', cli: '--depth', min: 1, max: 8, hint: 'Tokens the MTP sidecar drafts per verify step. Deeper wins more when the draft is accepted and costs more when it is rejected — the knob MTPLX\'s own `mtplx tune` sweeps.' },+ { id: 'generationMode', label: 'Decode mode', type: 'enum', cli: '--generation-mode', options: ['mtp', 'ar'], hint: 'Native multi-token speculative decode, or plain target-only autoregressive. The comparison that answers whether MTP is actually paying off for this model here.' },+ { id: 'kvQuant', label: 'KV cache quantization', type: 'enum', cli: '--kv-quant', options: ['off', 'q8', 'q4'], hint: 'Quantizing the paged KV cache buys context length with a little quality. q4 is the smallest at every length but re-dequantizes each decode step, so long-context decode gets slower.' },+ { id: 'batchingPreset', label: 'Batching preset', type: 'enum', cli: '--batching-preset', options: ['solo', 'latency', 'agent', 'throughput'], hint: 'How the server trades per-request latency against total throughput. `solo` is the cleanest baseline for a single-stream measurement.' },+ { id: 'profile', label: 'Runtime profile', type: 'enum', cli: '--profile', options: ['sustained', 'turbo', 'performance-cold', 'stable'], hint: 'MTPLX\'s own bundle of runtime settings. `turbo` targets peak rate on the quantized flagships; `sustained` holds up over a long run. Diagnostic profiles are deliberately not offered.' },+ ],+ // PortOS does not start vLLM at all — it is a container from the shipped+ // compose stack — so it has no launch line to put a flag on. Left// present-and-empty rather than absent so the runtime still enumerates.- mtplx: [],vllm: [],};export const TUNING_SPECS = Object.freeze(Object.fromEntries(- Object.entries(RAW_SPECS).map(([runtime, specs]) => [runtime, Object.freeze(specs.map(decorate))])+ Object.entries(RAW_SPECS).map(([runtime, specs]) => [+ runtime,+ Object.freeze(specs.map((spec) => decorate(runtime, spec))),+ ])));/** Knob specs for one runtime, or `[]` for a runtime with none declared. */diff --git a/server/lib/localModelTuning.test.js b/server/lib/localModelTuning.test.jsindex 58ff49a830..51102de880 100644--- a/server/lib/localModelTuning.test.js+++ b/server/lib/localModelTuning.test.js@@ -43,6 +43,17 @@ describe('TUNING_SPECS', () => {expect(byId('ollama', 'flashAttention').note).toContain('OLLAMA_FLASH_ATTENTION');expect(byId('lmstudio', 'contextLength').note).toContain('lms load --context-length');expect(byId('llama', 'ubatchSize').note).toContain('launch line');+ expect(byId('mtplx', 'depth').note).toContain('mtplx serve');+ });++ // LM Studio and MTPLX both ride the `cli` transport but re-run different+ // binaries. A note derived from the transport alone would tell an MTPLX user+ // PortOS runs `lms load`, which is a command that never executes here.+ it('names the right binary when two runtimes share the cli transport', () => {+ const noteFor = (runtime, id) => tuningSpecsFor(runtime).find((s) => s.id === id).note;+ expect(noteFor('mtplx', 'kvQuant')).toContain('mtplx serve');+ expect(noteFor('mtplx', 'kvQuant')).not.toContain('lms load');+ expect(noteFor('lmstudio', 'gpuOffload')).not.toContain('mtplx');});// Guard against a transport that is declared but renders nothing — the failure@@ -60,12 +71,46 @@ describe('TUNING_SPECS', () => {}});- // PortOS passes MTPLX only --port/--model and does not start vLLM at all.+ // PortOS does not start vLLM at all — it is a container from the shipped+ // compose stack, so there is no launch line to put a flag on.it('offers no knob for a runtime PortOS has no launch path into', () => {- expect(tuningSpecsFor('mtplx')).toEqual([]);expect(tuningSpecsFor('vllm')).toEqual([]);});+ // `mtplx serve` exits before it binds on an unrecognized flag, which the LLMs+ // page reports as "the server would not start". These spellings were read off+ // upstream's own argument parser and are checked here so a future edit cannot+ // quietly reword one into a flag MTPLX has never accepted.+ it('renders MTPLX knobs as the flags mtplx serve actually accepts', () => {+ expect(launchArgs('mtplx', {+ contextWindow: 32768,+ depth: 4,+ generationMode: 'mtp',+ kvQuant: 'q8',+ batchingPreset: 'solo',+ profile: 'turbo',+ })).toEqual([+ '--context-window', '32768',+ '--depth', '4',+ '--generation-mode', 'mtp',+ '--kv-quant', 'q8',+ '--batching-preset', 'solo',+ '--profile', 'turbo',+ ]);+ });++ // argparse rejects an unlisted choice exactly as it rejects an unknown flag,+ // so an enum option is as load-bearing as the flag name itself.+ it('offers MTPLX only enum values its parser lists', () => {+ const options = (id) => tuningSpecsFor('mtplx').find((s) => s.id === id).options;+ expect(options('kvQuant')).toEqual(['off', 'q8', 'q4']);+ expect(options('generationMode')).toEqual(['mtp', 'ar']);+ expect(options('batchingPreset')).toEqual(['solo', 'latency', 'agent', 'throughput']);+ // A subset of MTPLX's PROFILE_CHOICES: the diagnostic profiles ('exact',+ // 'max-diagnostic') are valid but are not what a throughput sweep is asking.+ expect(options('profile')).toEqual(['sustained', 'turbo', 'performance-cold', 'stable']);+ });+it('returns an empty list for an unknown runtime rather than throwing', () => {expect(tuningSpecsFor('not-a-runtime')).toEqual([]);});diff --git a/server/services/localModelAssessments.js b/server/services/localModelAssessments.jsindex 5debaae25f..6e7a3eb49d 100644--- a/server/services/localModelAssessments.js+++ b/server/services/localModelAssessments.js@@ -88,7 +88,7 @@ import { probeOpenAiModels } from '../lib/openAiModelsProbe.js';import { getAllProviders } from './providers.js';import { runEndpointLlmTest, runLocalLlmTest } from './localLlmPlayground.js';import { getLlamaServerEndpoint, relaunchLlamaServerWithTuning } from './llamaServerManager.js';-import { getMtplxServerEndpoint } from './mtplxServerManager.js';+import { getMtplxServerEndpoint, relaunchMtplxServerWithTuning } from './mtplxServerManager.js';import { listModels } from './localLlm.js';import {getLoadedModels as getLoadedOllamaModels,@@ -381,7 +381,8 @@ const toApplication = (ok, error, fallbackReason) => ({/*** Put a runtime's launch knobs into effect, each by the only transport that* reaches it: llama.cpp relaunches with a new command line, Ollama restarts- * carrying new environment, LM Studio reloads the model through `lms load`.+ * carrying new environment, LM Studio reloads the model through `lms load`,+ * MTPLX relaunches `mtplx serve` with the flags on its command line.** Keyed by BACKEND rather than by transport because the applier is "who owns* this daemon" — the manager that knows how to stop it, what to put back if the@@ -390,21 +391,53 @@ const toApplication = (ok, error, fallbackReason) => ({* `lib/localModelTuning.js` declares no launch knob for one; this refusal is the* backstop for a knob added without one, so the reading is filed as "not* applied" instead of silently attributed to a tuning that never ran.+ *+ * Each entry also names the ONE knob transport its path can carry. That is the+ * sharper trap than a missing applier: add an `env:` knob to MTPLX and the+ * applier still runs, the assessment still records `tuningApplied: true`, and+ * the flag is silently dropped on the way to a launch line that renders only+ * `cli`. Nothing fails at runtime, so `LAUNCH_TRANSPORTS` below is exported and+ * `localModelAssessments.test.js` asserts the catalog against it.*/const LAUNCH_APPLIERS = {- llama: ({ launch }) => relaunchLlamaServerWithTuning(launchConfig('llama', launch)),- ollama: ({ launch }) => restartOllamaWithEnv(launchEnv('ollama', launch))- .then((r) => toApplication(r.applied, r.error, `Ollama could not be restarted with that tuning (${r.reason})`)),- lmstudio: ({ modelId, launch }) => loadLmStudioModelWithArgs(modelId, launchArgs('lmstudio', launch))- .then((r) => toApplication(r.success, r.error, 'LM Studio could not reload the model with that tuning')),+ llama: {+ transport: 'config',+ apply: ({ launch }) => relaunchLlamaServerWithTuning(launchConfig('llama', launch)),+ },+ ollama: {+ transport: 'env',+ 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',+ 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')),+ },+ mtplx: {+ transport: 'cli',+ // 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 needs+ // the ids to merge this tuning onto what the daemon is already running with.+ apply: ({ launch }) => relaunchMtplxServerWithTuning(launch),+ },};+/**+ * Runtime id → the knob transport its applier carries. Derived rather than+ * written twice, so an applier added without declaring one lands here as+ * `undefined` and fails the guard instead of quietly opting out of it.+ */+export const LAUNCH_TRANSPORTS = Object.freeze(Object.fromEntries(+ Object.entries(LAUNCH_APPLIERS).map(([runtime, { transport }]) => [runtime, transport])+));+async function applyLaunchTuning({ backend, modelId, launch }) {const applier = LAUNCH_APPLIERS[backend];if (!applier) {return { applied: false, reason: `PortOS does not start the ${backend} runtime, so it cannot apply launch tuning`, config: null };}- return applier({ backend, modelId, launch })+ return applier.apply({ backend, modelId, launch }).catch((err) => ({ applied: false, reason: err?.message || 'relaunch failed', config: null }));}diff --git a/server/services/localModelAssessments.test.js b/server/services/localModelAssessments.test.jsindex a1b07fced7..1697608378 100644--- a/server/services/localModelAssessments.test.js+++ b/server/services/localModelAssessments.test.js@@ -43,6 +43,16 @@ vi.mock('./llamaServerManager.js', () => ({relaunchLlamaServerWithTuning: (...args) => relaunchLlamaServerWithTuning(...args),}));+// MTPLX's knobs are `mtplx serve` flags, so applying one relaunches the PM2+// daemon. Left unmocked this suite would shell out to the developer's real PM2+// and probe their real :8000 — the same reason llama-server is mocked above.+const getMtplxServerEndpoint = vi.fn(async () => 'http://127.0.0.1:8000/v1');+const relaunchMtplxServerWithTuning = vi.fn(async () => ({ applied: true, reason: null, config: null }));+vi.mock('./mtplxServerManager.js', () => ({+ getMtplxServerEndpoint: (...args) => getMtplxServerEndpoint(...args),+ relaunchMtplxServerWithTuning: (...args) => relaunchMtplxServerWithTuning(...args),+}));+const listModels = vi.fn();vi.mock('./localLlm.js', () => ({ listModels: (...args) => listModels(...args) }));@@ -79,6 +89,7 @@ const store = await import('./localModelAssessmentStore.js');// Dynamic, like the two above: a static import hoists ABOVE the fileUtils mock,// and this module resolves its claim path from `PATHS.data` at load time.const { claimHeavyLocalJob } = await import('../lib/heavyJobClaim.js');+const { TUNING_SPECS, tuningSpecsFor } = await import('../lib/localModelTuning.js');const STORE = join(tempRoot, 'local-llm', 'assessments.json');@@ -103,6 +114,8 @@ beforeEach(() => {relaunchLlamaServerWithTuning.mockReset().mockResolvedValue({ applied: true, reason: null, config: null });restartOllamaWithEnv.mockReset().mockResolvedValue({ applied: true, reason: 'restarted' });loadLmStudioModelWithArgs.mockReset().mockResolvedValue({ success: true });+ getMtplxServerEndpoint.mockReset().mockResolvedValue('http://127.0.0.1:8000/v1');+ relaunchMtplxServerWithTuning.mockReset().mockResolvedValue({ applied: true, reason: null, config: null });});describe('buildSamplePrompt', () => {@@ -684,6 +697,33 @@ describe('endpoint runtimes', () => {});});+// The refusal in `applyLaunchTuning` catches a runtime with NO applier. This+// catches the sharper case: a runtime WITH one, whose catalog declares a knob+// that applier's transport cannot carry. Nothing fails at runtime there — the+// relaunch runs, `tuningApplied: true` is recorded, and the knob is dropped on+// the way to the launch line, which is exactly the un-applied-but-claimed+// reading the catalog exists to prevent.+describe('launch transports', () => {+ it('carries every launch knob each runtime with an applier declares', () => {+ for (const [runtime, transport] of Object.entries(svc.LAUNCH_TRANSPORTS)) {+ expect(transport, `${runtime} applier declares no transport`).toBeTruthy();+ for (const spec of tuningSpecsFor(runtime)) {+ if (spec.applies !== 'launch') continue;+ expect(spec[transport], `${runtime}/${spec.id} is not a \`${transport}\` knob`).toBeTruthy();+ }+ }+ });++ // The mirror: a runtime that declares launch knobs but has no applier would+ // offer a form whose every field is refused at run time.+ it('gives every runtime that declares a launch knob an applier to apply it', () => {+ for (const [runtime, specs] of Object.entries(TUNING_SPECS)) {+ if (!specs.some((spec) => spec.applies === 'launch')) continue;+ expect(svc.LAUNCH_TRANSPORTS, `${runtime} declares launch knobs`).toHaveProperty(runtime);+ }+ });+});+describe('tuning', () => {it('keeps two tunings of one model as two records rather than overwriting', async () => {runLocalLlmTest.mockResolvedValue(okRun(40, 120));@@ -783,19 +823,46 @@ describe('tuning', () => {});// A runtime with no launch path must not silently swallow a knob: the catalog- // offers none for MTPLX/vLLM today, and if one is ever added without a- // transport the reading has to say it was not applied.+ // offers none for vLLM (a container from the shipped compose stack), and if+ // one is ever added without a transport the reading has to say so.it('refuses launch tuning for a runtime PortOS does not start', async () => {probeOpenAiModels.mockResolvedValue({ reachable: true, models: ['a-model'], error: null });runEndpointLlmTest.mockResolvedValue(okRun());const result = await svc.runAssessment({- backend: 'mtplx', modelId: 'a-model', contextTokens: [512], tuning: { maxKvSize: 8192 },+ backend: 'vllm', modelId: 'a-model', contextTokens: [512], tuning: { maxKvSize: 8192 },});- // Retired from the catalog, so it normalizes away entirely — no claim made.+ // Not in the catalog, so it normalizes away entirely — no claim made.expect(result.tuningApplied).toBeNull();expect(result.tuningKey).toBe('');});+ it('relaunches `mtplx serve` to apply an MTPLX tuning', async () => {+ probeOpenAiModels.mockResolvedValue({ reachable: true, models: ['a-model'], error: null });+ runEndpointLlmTest.mockResolvedValue(okRun());+ const result = await svc.runAssessment({+ backend: 'mtplx', modelId: 'a-model', contextTokens: [512], tuning: { depth: 5, kvQuant: 'q8' },+ });+ expect(relaunchMtplxServerWithTuning).toHaveBeenCalledWith({ depth: 5, kvQuant: 'q8' });+ expect(result.tuningApplied).toBe(true);+ expect(result.tuningKey).toBe('depth=5,kvQuant=q8');+ });++ // A launch line MTPLX rejects must not be filed as evidence FOR that tuning —+ // the manager puts the previous configuration back and says why, and the+ // reading has to carry the refusal rather than the claim.+ it('records an MTPLX tuning the daemon refused as not applied', async () => {+ probeOpenAiModels.mockResolvedValue({ reachable: true, models: ['a-model'], error: null });+ runEndpointLlmTest.mockResolvedValue(okRun());+ relaunchMtplxServerWithTuning.mockResolvedValueOnce({+ applied: false, reason: 'MTPLX rejected that tuning: unrecognized arguments', config: null,+ });+ const result = await svc.runAssessment({+ backend: 'mtplx', modelId: 'a-model', contextTokens: [512], tuning: { contextWindow: 1048576 },+ });+ expect(result.tuningApplied).toBe(false);+ expect(result.tuningNotApplied).toMatch(/unrecognized arguments/);+ });+it('never relaunches llama-server for an untuned run', async () => {probeOpenAiModels.mockResolvedValue({ reachable: true, models: ['dflash'], error: null });runEndpointLlmTest.mockResolvedValue(okRun());diff --git a/server/services/mtplxServerManager.js b/server/services/mtplxServerManager.jsindex 85188b3266..024e11b0fd 100644--- a/server/services/mtplxServerManager.js+++ b/server/services/mtplxServerManager.js@@ -25,6 +25,7 @@import { commandExists } from '../lib/commandExists.js';import { sleep } from '../lib/fileUtils.js';import { ServerError } from '../lib/errorHandler.js';+import { launchArgs, normalizeTuning, tuningSpecsFor } from '../lib/localModelTuning.js';import { LOCAL_RUNTIMES, localEndpointPort } from '../lib/localProviderRuntime.js';import { listMtplxCachedModels, pickMtplxCachedModel } from '../lib/mtplxModels.js';import { probeOpenAiModels } from '../lib/openAiModelsProbe.js';@@ -51,7 +52,27 @@ const PROBE_TIMEOUT_MS = 1500;* still-loading path doesn't have to sit through the real budget.*/let startupWaitMs = 8_000;-const STARTUP_POLL_MS = 1500;+/**+ * Beat between startup polls. Mutable through the same test seam as the budget+ * above: a suite that pins the endpoint probe unreachable pays this delay in+ * FULL on every lifecycle test, which is what made this file the slowest server+ * suite — a 1.5s floor per start, several starts per relaunch case, close enough+ * to the 10s per-test timeout to flake under CI load.+ */+let startupPollMs = 1500;+const PORT_RELEASE_TIMEOUT_MS = 5000;+/**+ * How long a TUNING relaunch waits for the new launch line to answer before+ * calling it wedged and putting the previous configuration back.+ *+ * Far longer than `startupWaitMs`, and deliberately longer than llama.cpp's+ * equivalent: `startMtplxServer` only proves the process survived its first+ * seconds, and a cold multi-gigabyte MLX checkpoint routinely takes minutes to+ * load. Judging it at eight seconds would restore the previous configuration+ * over a server that was merely still loading. Mutable through the test seam so+ * a suite asserting the never-answered path doesn't sit through the real budget.+ */+let relaunchReadyTimeoutMs = 300_000;/** Package-manager installs routinely run for minutes. */const INSTALL_TIMEOUT_MS = 20 * 60 * 1000;@@ -100,9 +121,48 @@ function parseConfigFromArgs(args) {// Absent means MTPLX was started on its OWN default checkpoint — don't// invent a repo id the launch line never carried.model: pm2ArgValue(list, '--model'),+ tuning: parseTuningFromArgs(list),};}+/**+ * Recover the tuning knobs from a launch line PortOS is re-adopting.+ *+ * Walks the CATALOG rather than the argv, so a flag PortOS no longer declares+ * cannot come back as a knob, and every value goes through `normalizeTuning` —+ * argv holds strings, and the rest of the manager expects the coerced shape a+ * relaunch would merge onto. Empty when nothing was tuned, which reads the same+ * as a server started before tuning existed.+ */+function parseTuningFromArgs(list) {+ const raw = {};+ for (const spec of tuningSpecsFor('mtplx')) {+ if (!spec.cli) continue;+ const value = pm2ArgValue(list, spec.cli);+ if (value !== null) raw[spec.id] = value;+ }+ return normalizeTuning('mtplx', raw);+}++/** Block until the port is free, or the release budget elapses. */+async function waitForPortRelease(port) {+ const deadline = Date.now() + PORT_RELEASE_TIMEOUT_MS;+ 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 — a wedged process, not a slow-loading 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;+}+/** Resolve the `mtplx` executable on the child-process PATH. */const resolveMtplxBinary = () => findCommandOnPath('mtplx');@@ -250,10 +310,18 @@ async function resolveStartModel(requested, emit) {* 127.0.0.1, and accepting a host PortOS never puts on the launch line would* report an endpoint the server is not bound to.*- * @param {{port?: number, model?: string, waitMs?: number, onProgress?: (line: string) => void}} options+ * `tuning` is a knob set from `lib/localModelTuning.js` (`TUNING_SPECS.mtplx`),+ * rendered to `mtplx serve` flags by the catalog rather than by a flag map here,+ * so a knob cannot reach the launch line without also being declared, described,+ * and offered in the form. It is kept on `currentConfig` so a later relaunch —+ * for a different port, or for one more knob — re-applies what is already set+ * instead of quietly dropping it.+ *+ * @param {{port?: number, model?: string, tuning?: object, waitMs?: number, onProgress?: (line: string) => void}} options*/export async function startMtplxServer(options = {}) {- const { port = DEFAULT_PORT, model: requestedModel = null, waitMs, onProgress = () => {} } = options;+ const { port = DEFAULT_PORT, model: requestedModel = null, tuning = null, waitMs, onProgress = () => {} } = options;+ const normalizedTuning = normalizeTuning('mtplx', tuning);const emit = (line) => { appendLog(line); onProgress(line); };const binaryPath = resolveMtplxBinary();@@ -292,15 +360,16 @@ export async function startMtplxServer(options = {}) {// API-only server, which is the half PortOS talks to. The daemon must bind// where the PROVIDER points — a user who moved MTPLX to 8010 would otherwise// get a second server on 8000 that nothing talks to.- const args = ['serve', '--port', String(port), ...(model ? ['--model', model] : [])];- currentConfig = { port, model };+ const tuningArgs = launchArgs('mtplx', normalizedTuning);+ const args = ['serve', '--port', String(port), ...(model ? ['--model', model] : []), ...tuningArgs];+ currentConfig = { port, model, tuning: normalizedTuning };appendLog(`Starting: mtplx ${args.join(' ')}`);// Delete any stale PM2 entry so our own previous instance doesn't count as a collision.await execPm2(['delete', MTPLX_APP]).catch(() => {});clearJlistCache();- console.log(`🚄 MTPLX starting on ${DEFAULT_HOST}:${port}${model ? ` (model ${model})` : ' (MTPLX default model)'}`);+ console.log(`🚄 MTPLX starting on ${DEFAULT_HOST}:${port}${model ? ` (model ${model})` : ' (MTPLX default model)'}${tuningArgs.length ? ` with ${tuningArgs.join(' ')}` : ''}`);await execPm2(['start', binaryPath,'--name', MTPLX_APP,@@ -315,7 +384,7 @@ export async function startMtplxServer(options = {}) {let online = false;let currentProc = null;while (Date.now() < deadline) {- await sleep(STARTUP_POLL_MS);+ await sleep(startupPollMs);clearJlistCache();currentProc = await getAppStatusStrict(MTPLX_APP);if (currentProc && ['errored', 'stopped', 'not_found'].includes(currentProc.status)) break;@@ -376,11 +445,110 @@ export async function stopMtplxServer() {return { success: true, message: 'MTPLX stopped' };}+/**+ * Relaunch `mtplx serve` with a different tuning, keeping the checkpoint and+ * port it is already serving.+ *+ * This is MTPLX's half of the measured-assessment feature: a sweep across MTP+ * depths or KV-quantization modes is only possible if something can put those+ * flags on the launch line between runs. It mirrors+ * `llamaServerManager.relaunchLlamaServerWithTuning` — same result shape, same+ * two refusals, same restore-on-failure — because the assessment runner treats+ * every runtime's applier identically.+ *+ * It refuses rather than guesses in the two cases where it cannot know what to+ * relaunch:+ * - nothing is running, so there is no checkpoint to reuse;+ * - something IS listening but PortOS did not start it, so stopping it would+ * kill a process the user owns.+ *+ * Every one of those returns `{ applied: false, reason }` instead of throwing:+ * the caller can still measure whatever is actually serving and record that the+ * tuning was NOT applied, which is far more useful than failing the whole run.+ *+ * The restore path is not optional. A tuning sweep EXPECTS launch lines that do+ * not work — a `--context-window` past what unified memory holds, a `--depth`+ * the checkpoint's MTP sidecar will not draft. `mtplx serve` exits before it+ * binds and `startMtplxServer` throws; leaving the daemon down would break the+ * whole install's `mtplx` provider, not just the measurement. So the previous+ * configuration goes back up before the failure is reported.+ *+ * @param {object} tuning launch knobs from `lib/localModelTuning.js`+ * @returns {Promise<{applied: boolean, reason: string|null, config: object|null}>}+ */+export async function relaunchMtplxServerWithTuning(tuning = {}) {+ const knobs = Object.entries(normalizeTuning('mtplx', tuning)).filter(([, v]) => v !== null && v !== undefined);+ if (knobs.length === 0) {+ return { applied: false, reason: 'no launch knobs were requested', config: currentConfig };+ }++ const status = await getMtplxServerStatus();+ if (!status.running) {+ return { applied: false, reason: 'MTPLX is not running, so PortOS has no checkpoint to relaunch with', config: null };+ }+ if (!status.managed) {+ return {+ applied: false,+ reason: 'MTPLX was started outside PortOS — start it from the LLMs page to let PortOS apply tuning',+ config: status.config || null,+ };+ }++ const previous = status.config || { port: status.port, model: null, tuning: {} };+ // Merged onto what is already on the launch line, not replacing it: a sweep+ // that varies one knob must not silently drop the ones already set.+ const next = { ...previous, tuning: { ...(previous.tuning || {}), ...Object.fromEntries(knobs) } };+ const port = next.port ?? DEFAULT_PORT;+ console.log(`🚄 MTPLX: relaunching to apply tuning (${knobs.map(([k, v]) => `${k}=${v}`).join(', ')})`);++ await stopMtplxServer();+ await waitForPortRelease(port);++ const started = await startMtplxServer(next).catch(async (err) => {+ console.error(`❌ MTPLX: tuning launch failed (${err.message}) — restoring the previous configuration`);+ await waitForPortRelease(previous.port ?? DEFAULT_PORT);+ const restored = await startMtplxServer(previous).catch((restoreErr) => {+ console.error(`❌ MTPLX: could not restore the previous configuration: ${restoreErr.message}`);+ return null;+ });+ return { failure: err.message, config: restored?.config || null };+ });+ if (started.failure) {+ return { applied: false, reason: `MTPLX rejected that tuning: ${started.failure}`, config: started.config };+ }++ // `startMtplxServer` returning is not the same as the endpoint answering — it+ // waits only long enough to catch a server that dies immediately, and a cold+ // MLX checkpoint takes far longer than that to load. So `online: false` here+ // is "not ready YET", not "wedged"; give it the real readiness budget first.+ const ready = started.online || await waitForEndpoint(started.endpoint);+ if (ready) return { applied: true, reason: null, config: started.config };++ // Still silent. Treat it exactly like a rejected launch line: put the previous+ // configuration back, so the install's mtplx 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 for this tuning.+ console.error('❌ MTPLX: relaunched process never answered — restoring the previous configuration');+ await stopMtplxServer().catch(() => {});+ await waitForPortRelease(previous.port ?? DEFAULT_PORT);+ const restored = await startMtplxServer(previous).catch((err) => {+ console.error(`❌ MTPLX: could not restore the previous configuration: ${err.message}`);+ return null;+ });+ return {+ applied: false,+ reason: 'MTPLX relaunched but never answered on its port',+ config: restored?.config || null,+ };+}+/** Clears in-memory state (used by test suites). */-export function _resetMtplxServerStateForTests({ startupWait } = {}) {+export function _resetMtplxServerStateForTests({ startupWait, startupPoll, relaunchReadyTimeout } = {}) {currentConfig = null;logs.reset();lastExitError = null;// Restored to the production budget unless a suite asks for a shorter one.startupWaitMs = Number.isFinite(startupWait) ? startupWait : 8_000;+ startupPollMs = Number.isFinite(startupPoll) ? startupPoll : 1500;+ relaunchReadyTimeoutMs = Number.isFinite(relaunchReadyTimeout) ? relaunchReadyTimeout : 300_000;}diff --git a/server/services/mtplxServerManager.test.js b/server/services/mtplxServerManager.test.jsindex d50ed6576d..32f0c50150 100644--- a/server/services/mtplxServerManager.test.js+++ b/server/services/mtplxServerManager.test.js@@ -3,6 +3,7 @@ import {getMtplxServerStatus,startMtplxServer,stopMtplxServer,+ relaunchMtplxServerWithTuning,installMtplx,_resetMtplxServerStateForTests,MTPLX_APP,@@ -24,9 +25,9 @@ describe('mtplxServerManager', () => {beforeEach(() => {// A start that never answers on its port is the NORMAL path here (the probe- // is pinned unreachable) — shorten the beat so the suite doesn't sit- // through the production budget on every lifecycle test.- _resetMtplxServerStateForTests({ startupWait: 50 });+ // is pinned unreachable), so every lifecycle test pays the startup budget AND+ // its poll beat in full — shorten both rather than sitting through them.+ _resetMtplxServerStateForTests({ startupWait: 50, startupPoll: 5 });vi.restoreAllMocks();pm2State = null;execPm2Calls = [];@@ -198,6 +199,147 @@ describe('mtplxServerManager', () => {vi.spyOn(platform, 'isPortInUse').mockResolvedValue(true);await expect(startMtplxServer()).rejects.toThrow(/already in use/);});++ it('puts the tuning knobs on the launch line as mtplx serve flags', async () => {+ const result = await startMtplxServer({ tuning: { depth: 5, kvQuant: 'q4' } });+ const launch = execPm2Calls.find((a) => a[0] === 'start');+ expect(launch[launch.indexOf('--depth') + 1]).toBe('5');+ expect(launch[launch.indexOf('--kv-quant') + 1]).toBe('q4');+ // Carried on the config so a later relaunch re-applies it rather than+ // silently dropping back to MTPLX's defaults.+ expect(result.config.tuning).toEqual({ depth: 5, kvQuant: 'q4' });+ });++ it('drops a knob the catalog does not declare instead of inventing a flag', async () => {+ // The retired `maxKvSize` knob was never an `mtplx serve` flag; passing+ // one through unchecked is exactly the exit-before-bind failure.+ await startMtplxServer({ tuning: { maxKvSize: 8192, depth: 2 } });+ const launch = execPm2Calls.find((a) => a[0] === 'start');+ expect(launch).not.toContain('--max-kv-size');+ expect(launch).toContain('--depth');+ });++ it('leaves the launch line untuned when nothing was asked for', async () => {+ const result = await startMtplxServer();+ const start = execPm2Calls.find((a) => a[0] === 'start');+ const launch = start.slice(start.indexOf('--') + 1);+ expect(launch).toEqual(['serve', '--port', expect.any(String), '--model', 'Example/Qwen-MTP']);+ expect(result.config.tuning).toEqual({});+ });+ });++ describe('relaunchMtplxServerWithTuning', () => {+ beforeEach(() => {+ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue(BINARY);+ // A relaunch judges readiness by the endpoint answering; the suite pins+ // the probe unreachable, so shorten the budget rather than waiting it out.+ _resetMtplxServerStateForTests({ startupWait: 20, startupPoll: 5, relaunchReadyTimeout: 30 });+ });++ // Readiness is what the caller's `applied: true` means, so most cases need+ // the endpoint to answer once the relaunched process is up.+ const answerOnceRunning = () => vi.spyOn(openAiModelsProbe, 'probeOpenAiModels')+ .mockImplementation(async () => ({ reachable: pm2State?.status === 'online' }));++ it('relaunches on the same checkpoint with the tuning flags added', async () => {+ await startMtplxServer({ port: 8010 });+ answerOnceRunning();+ const result = await relaunchMtplxServerWithTuning({ contextWindow: 32768 });++ expect(result.applied).toBe(true);+ expect(result.reason).toBeNull();+ const launch = execPm2Calls.filter((a) => a[0] === 'start').pop();+ expect(launch[launch.indexOf('--model') + 1]).toBe('Example/Qwen-MTP');+ expect(launch[launch.indexOf('--port') + 1]).toBe('8010');+ expect(launch[launch.indexOf('--context-window') + 1]).toBe('32768');+ });++ it('merges onto the tuning already on the launch line rather than replacing it', async () => {+ await startMtplxServer({ tuning: { depth: 4 } });+ answerOnceRunning();+ const result = await relaunchMtplxServerWithTuning({ kvQuant: 'q8' });+ expect(result.config.tuning).toEqual({ depth: 4, kvQuant: 'q8' });+ });++ // A sweep EXPECTS launch lines that do not work. Leaving the daemon down+ // would break the whole install's mtplx provider, not just the measurement.+ it('restores the previous configuration when MTPLX rejects the tuning', async () => {+ await startMtplxServer({ tuning: { depth: 2 } });+ answerOnceRunning();++ let rejectNext = true;+ const realExec = pm2Module.execPm2.getMockImplementation();+ vi.spyOn(pm2Module, 'execPm2').mockImplementation(async (args) => {+ const out = await realExec(args);+ if (args[0] === 'start' && args.includes('--context-window') && rejectNext) {+ rejectNext = false;+ pm2State = { name: MTPLX_APP, status: 'errored', pid: null, args: [] };+ }+ if (args[0] === 'logs') return { stdout: '', stderr: 'error: unrecognized arguments' };+ return out;+ });++ const result = await relaunchMtplxServerWithTuning({ contextWindow: 1048576 });+ expect(result.applied).toBe(false);+ expect(result.reason).toMatch(/MTPLX rejected that tuning/);+ // Back up on what it was serving before, not left down.+ expect(pm2State?.status).toBe('online');+ expect(result.config.tuning).toEqual({ depth: 2 });+ const restored = execPm2Calls.filter((a) => a[0] === 'start').pop();+ expect(restored).not.toContain('--context-window');+ expect(restored[restored.indexOf('--depth') + 1]).toBe('2');+ });++ // PM2 says `online` long before an MLX checkpoint is loaded, so a process+ // that never answers is a wedge — and measuring its timeouts would file+ // them as evidence for this tuning.+ it('restores the previous configuration when the relaunch never answers', async () => {+ await startMtplxServer({ tuning: { depth: 2 } });+ const result = await relaunchMtplxServerWithTuning({ depth: 6 });+ expect(result.applied).toBe(false);+ expect(result.reason).toMatch(/never answered/);+ expect(result.config.tuning).toEqual({ depth: 2 });+ expect(pm2State?.status).toBe('online');+ });++ it('refuses when nothing is running, since there is no checkpoint to reuse', async () => {+ const result = await relaunchMtplxServerWithTuning({ depth: 3 });+ expect(result.applied).toBe(false);+ expect(result.reason).toMatch(/not running/);+ expect(execPm2Calls.some((a) => a[0] === 'start')).toBe(false);+ });++ it('will not stop a server PortOS did not start', async () => {+ vi.spyOn(openAiModelsProbe, 'probeOpenAiModels').mockResolvedValue({ reachable: true });+ const result = await relaunchMtplxServerWithTuning({ depth: 3 });+ expect(result.applied).toBe(false);+ expect(result.reason).toMatch(/started outside PortOS/);+ expect(execPm2Calls.some((a) => a[0] === 'delete')).toBe(false);+ });++ // `applied: true` on an empty request would claim a configuration nobody+ // asked for — and a knob that normalized away leaves nothing to apply.+ it('makes no claim when there is no knob to apply', async () => {+ await startMtplxServer();+ execPm2Calls.length = 0;+ expect((await relaunchMtplxServerWithTuning({})).applied).toBe(false);+ expect((await relaunchMtplxServerWithTuning({ maxKvSize: 8192 })).applied).toBe(false);+ expect(execPm2Calls.some((a) => a[0] === 'start')).toBe(false);+ });++ // A PortOS restart re-adopts a live PM2 process by reading its argv back.+ // Losing the tuning there would make the next relaunch drop flags the+ // server is demonstrably running with.+ it('recovers the tuning from the launch line of a re-adopted process', async () => {+ pm2State = {+ name: MTPLX_APP,+ status: 'online',+ pid: 4242,+ args: ['serve', '--port', '8010', '--model', 'Example/Qwen-MTP', '--depth', '5', '--kv-quant', 'q8'],+ };+ const status = await getMtplxServerStatus();+ expect(status.config.tuning).toEqual({ depth: 5, kvQuant: 'q8' });+ });});describe('installMtplx', () => {