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
fix: make an MTPLX tuning relaunch diagnose and recover honestly
[._.]/ Adam Eivy6a93483445d6
diff --git a/client/src/components/settings/MtplxServerCard.jsx b/client/src/components/settings/MtplxServerCard.jsxindex 21d12798a0..617e037332 100644--- a/client/src/components/settings/MtplxServerCard.jsx+++ b/client/src/components/settings/MtplxServerCard.jsx@@ -44,6 +44,7 @@ export default function MtplxServerCard({const cachedRows = status?.cachedModelRows || cached.map((repo) => ({ repo }));const emptyCache = Boolean(status?.installed) && cached.length === 0 && !status?.cacheError;const external = status?.running && status?.managed === false;+ const tuningFlags = status?.tuningFlags || [];return (<div className="bg-port-card border border-port-border rounded-xl p-4 sm:p-6 space-y-4">@@ -95,6 +96,16 @@ export default function MtplxServerCard({{status.config?.model && (<p><span className="text-gray-500">Model:</span> <code className="text-gray-300">{status.config.model}</code></p>)}+ {/*+ A measured assessment relaunches this daemon with tuning flags+ and leaves them on. Every later request through the `mtplx`+ provider runs under them, so a card that showed only the model+ would report a server as plain "running" while it is serving+ with, say, MTP decoding switched off.+ */}+ {tuningFlags.length > 0 && (+ <p><span className="text-gray-500">Tuning:</span> <code className="text-port-warning">{tuningFlags.join(' ')}</code></p>+ )}{external && (<p className="text-blue-300">Started outside PortOS — stop it where you started it.</p>)}diff --git a/client/src/components/settings/MtplxServerCard.test.jsx b/client/src/components/settings/MtplxServerCard.test.jsxindex 2acbad8b65..3a233a6720 100644--- a/client/src/components/settings/MtplxServerCard.test.jsx+++ b/client/src/components/settings/MtplxServerCard.test.jsx@@ -124,6 +124,30 @@ describe('MtplxServerCard', () => {expect(screen.queryByRole('button', { name: /Stop MTPLX/ })).toBeNull();});+ // A measured assessment relaunches this daemon with tuning flags and leaves+ // them on, so every later request through the `mtplx` provider runs under+ // them. A card showing only the model would report the server as plain+ // "running" while it serves with, say, MTP decoding switched off.+ it('names the tuning flags the running daemon was launched with', async () => {+ await renderCard({+ installed: true, running: true, managed: true, supported: true,+ endpoint: 'http://127.0.0.1:8000/v1',+ config: { model: 'Example/Qwen-MTP', port: 8000, tuning: { generationMode: 'ar' } },+ tuningFlags: ['--generation-mode', 'ar'],+ });+ expect(screen.getByText('--generation-mode ar')).toBeInTheDocument();+ });++ it('says nothing about tuning for a daemon running on plain defaults', async () => {+ await renderCard({+ installed: true, running: true, managed: true, supported: true,+ endpoint: 'http://127.0.0.1:8000/v1',+ config: { model: 'Example/Qwen-MTP', port: 8000, tuning: {} },+ tuningFlags: [],+ });+ expect(screen.queryByText(/Tuning:/)).toBeNull();+ });+it('offers the install when the binary is missing', async () => {const handlers = await renderCard({ installed: false, running: false, supported: true });fireEvent.click(screen.getByRole('button', { name: /Install MTPLX/ }));diff --git a/server/services/mtplxServerManager.js b/server/services/mtplxServerManager.jsindex f8e356420c..8b6f634716 100644--- a/server/services/mtplxServerManager.js+++ b/server/services/mtplxServerManager.js@@ -60,7 +60,17 @@ let startupWaitMs = 8_000;* to the 10s per-test timeout to flake under CI load.*/let startupPollMs = 1500;-const PORT_RELEASE_TIMEOUT_MS = 5000;+/**+ * How long to let the stopped daemon give the port up before starting the next+ * one. Six times llama.cpp's five seconds, because what is being torn down is a+ * multi-gigabyte MLX process and giving up early is the expensive mistake here:+ * `startMtplxServer` refuses a bound port BEFORE it launches anything, so a+ * relaunch that jumps the gun fails the tuned start AND the restore behind it,+ * leaving the install's `mtplx` provider down over a race rather than over+ * anything the user tuned. Mutable through the test seam below, like the other+ * budgets here, so a suite exercising a still-held port does not sit it out.+ */+let portReleaseTimeoutMs = 30_000;/*** How long a TUNING relaunch waits for the new launch line to answer before* calling it wedged and putting the previous configuration back.@@ -154,7 +164,7 @@ function parseTuningFromArgs(list) {/** Block until the port is free, or the release budget elapses. */async function waitForPortRelease(port) {- const deadline = Date.now() + PORT_RELEASE_TIMEOUT_MS;+ const deadline = Date.now() + portReleaseTimeoutMs;while (Date.now() < deadline && await isPortInUse(port)) await sleep(200);}@@ -170,18 +180,37 @@ async function waitForPortRelease(port) {* provider down for minutes per bad launch line, and a tuning sweep is EXPECTED* to produce bad launch lines.*- * `false` means it will not serve — dead or wedged; either way, restore.+ * Resolves `{ ready, reason }` — and the two not-ready cases carry DIFFERENT+ * reasons, because they send the user to different places. A process PM2 marks+ * `errored` printed something on the way out, and that tail is the whole+ * diagnosis ("metal buffer allocation failed"); reporting it as "never answered+ * on its port" would throw away the one fact that explains the failure.*/async function waitForRelaunchedEndpoint(endpoint) {const deadline = Date.now() + relaunchReadyTimeoutMs;while (Date.now() < deadline) {- if (await probeEndpoint(endpoint)) return true;+ if (await probeEndpoint(endpoint)) return { ready: true, reason: null };clearJlistCache();const proc = await getAppStatusStrict(MTPLX_APP);- if (proc && ['errored', 'stopped', 'not_found'].includes(proc.status)) return false;+ if (proc && ['errored', 'stopped', 'not_found'].includes(proc.status)) {+ return { ready: false, reason: `MTPLX exited while loading (${await exitTail(proc.status)})` };+ }await sleep(1000);}- return false;+ return { ready: false, reason: 'MTPLX relaunched but never answered on its port' };+}++/**+ * The last few lines the dead process printed, appended to its PM2 status —+ * the same tail `startMtplxServer` surfaces for a server that dies inside its+ * startup window, so a launch line that fails later is diagnosed the same way.+ */+async function exitTail(status) {+ const pm2Logs = await execPm2(['logs', MTPLX_APP, '--nostream', '--lines', '15']).catch(() => null);+ const lines = `${pm2Logs?.stderr || pm2Logs?.stdout || ''}`.split('\n').map((l) => l.trimEnd()).filter(Boolean);+ for (const line of lines) appendLog(line);+ const tail = lines.slice(-4).join(' | ');+ return tail ? `PM2 status: ${status} — ${tail}` : `PM2 status: ${status}`;}/** Resolve the `mtplx` executable on the child-process PATH. */@@ -242,6 +271,14 @@ export async function getMtplxServerStatus() {port: currentConfig?.port ?? DEFAULT_PORT,endpoint,config: isManagedActive ? currentConfig : null,+ // The tuning flags the running daemon was LAUNCHED with, rendered by the+ // catalog that owns the transport rather than re-derived in the UI. A+ // measured assessment relaunches this daemon and leaves its flags on, so a+ // status that reported only the model would show a server as plain+ // "running" while it serves with, say, MTP decoding switched off. Empty for+ // an untuned server, and for one PortOS does not manage — it cannot read+ // another process's launch line.+ tuningFlags: isManagedActive ? launchArgs('mtplx', currentConfig?.tuning) : [],// Is this PM2 app in the saved dump `pm2 resurrect` replays at boot?// `null` = the dump could not be read, which is not the same as "no".runAtStartup: savedApps === null ? null : savedApps.includes(MTPLX_APP),@@ -563,51 +600,77 @@ export async function relaunchMtplxServerWithTuning(tuning = {}) {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 };- });+ const started = await startMtplxServer(next).catch((err) => ({ failure: err }));if (started.failure) {- return { applied: false, reason: `MTPLX rejected that tuning: ${started.failure}`, config: started.config };+ const reason = launchFailureReason(started.failure);+ console.error(`❌ MTPLX: tuning launch failed (${started.failure.message}) — restoring the previous configuration`);+ return { applied: false, reason, config: await restorePrevious(previous) };}// `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 waitForRelaunchedEndpoint(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');+ const ready = started.online ? { ready: true, reason: null } : await waitForRelaunchedEndpoint(started.endpoint);+ if (ready.ready) return { applied: true, reason: null, config: started.config };++ // 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: ${ready.reason} — restoring the previous configuration`);await stopMtplxServer().catch(() => {});+ return { applied: false, reason: ready.reason, config: await restorePrevious(previous) };+}++/**+ * Why the tuned launch failed, in the caller's words.+ *+ * "MTPLX rejected that tuning" is only true when `mtplx serve` actually ran and+ * exited. `startMtplxServer` also throws from guards that fire BEFORE the+ * process starts — most realistically the port still being held by the daemon+ * that was just stopped — and reporting those as a rejected tuning sends the+ * user looking for a bad flag that was never even passed.+ */+const launchFailureReason = (err) => (err?.code === 'MTPLX_EXITED'+ ? `MTPLX rejected that tuning: ${err.message}`+ : `PortOS could not start MTPLX with that tuning: ${err?.message || 'relaunch failed'}`);++/**+ * Put the configuration MTPLX was serving before back up, and WAIT for it.+ *+ * Returning as soon as `startMtplxServer` does would hand back a config the+ * daemon is still minutes from honouring — and the caller goes straight on to+ * measure, so every sample times out and a junk `does-not-fit` record is stored+ * against the model. That record then counts as "assessed", dropping the model+ * out of the unassessed list and the sweep's `unmeasured` scope for good.+ *+ * `null` when it could not be brought back at all, which is the honest answer:+ * the caller reports the tuning as not applied either way, and a config here+ * would claim a daemon that is not running.+ */+async function restorePrevious(previous) {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,- };+ if (!restored) return null;+ if (restored.online) return restored.config;+ const back = await waitForRelaunchedEndpoint(restored.endpoint);+ if (back.ready) return restored.config;+ console.error(`❌ MTPLX: the restored configuration ${back.reason}`);+ return null;}/** Clears in-memory state (used by test suites). */-export function _resetMtplxServerStateForTests({ startupWait, startupPoll, relaunchReadyTimeout } = {}) {+export function _resetMtplxServerStateForTests({ startupWait, startupPoll, portRelease, 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;+ portReleaseTimeoutMs = Number.isFinite(portRelease) ? portRelease : 30_000;relaunchReadyTimeoutMs = Number.isFinite(relaunchReadyTimeout) ? relaunchReadyTimeout : 300_000;}diff --git a/server/services/mtplxServerManager.test.js b/server/services/mtplxServerManager.test.jsindex 360379a24a..19c7538024 100644--- a/server/services/mtplxServerManager.test.js+++ b/server/services/mtplxServerManager.test.js@@ -27,7 +27,7 @@ describe('mtplxServerManager', () => {// A start that never answers on its port is the NORMAL path here (the probe// 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 });+ _resetMtplxServerStateForTests({ startupWait: 50, startupPoll: 5, portRelease: 20 });vi.restoreAllMocks();pm2State = null;execPm2Calls = [];@@ -101,6 +101,26 @@ describe('mtplxServerManager', () => {expect(installed.unsupportedReason).toBeNull();});+ // The card renders these rather than re-deriving flags from the knob ids,+ // so the catalog that owns the transport stays the only thing that renders+ // a flag. A tuned daemon that reported no flags would look plain "running"+ // while every request through the mtplx provider ran under them.+ it('reports the tuning flags the running daemon was launched with', async () => {+ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue(BINARY);+ await startMtplxServer({ tuning: { depth: 5 } });+ expect((await getMtplxServerStatus()).tuningFlags).toEqual(['--depth', '5']);+ });++ it('reports no tuning flags for a server PortOS does not manage', async () => {+ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue(BINARY);+ vi.spyOn(openAiModelsProbe, 'probeOpenAiModels').mockResolvedValue({ reachable: true });+ const status = await getMtplxServerStatus();+ expect(status.running).toBe(true);+ // PortOS cannot read another process's launch line, so claiming it is+ // untuned would be a guess dressed as a fact.+ expect(status.tuningFlags).toEqual([]);+ });+it('flags the process as boot-persisted only when the PM2 dump names it', async () => {vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue(BINARY);expect((await getMtplxServerStatus()).runAtStartup).toBe(false);@@ -233,7 +253,7 @@ describe('mtplxServerManager', () => {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 });+ _resetMtplxServerStateForTests({ startupWait: 20, startupPoll: 5, portRelease: 20, relaunchReadyTimeout: 30 });});// Readiness is what the caller's `applied: true` means, so most cases need@@ -241,6 +261,15 @@ describe('mtplxServerManager', () => {const answerOnceRunning = () => vi.spyOn(openAiModelsProbe, 'probeOpenAiModels').mockImplementation(async () => ({ reachable: pm2State?.status === 'online' }));+ // Reachable UNLESS the running launch line carries `flag` — a tuning MTPLX+ // starts under but never serves under, with the previous configuration+ // coming back healthy. The restore now waits for readiness too, so a probe+ // pinned unreachable for everything would model both halves failing.+ const answerUnless = (flag) => vi.spyOn(openAiModelsProbe, 'probeOpenAiModels')+ .mockImplementation(async () => ({+ reachable: pm2State?.status === 'online' && !(pm2State.args || []).includes(flag),+ }));+it('relaunches on the same checkpoint with the tuning flags added', async () => {await startMtplxServer({ port: 8010 });answerOnceRunning();@@ -303,13 +332,27 @@ describe('mtplxServerManager', () => {// 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 });+ answerUnless('--context-window');+ const result = await relaunchMtplxServerWithTuning({ contextWindow: 65536 });expect(result.applied).toBe(false);expect(result.reason).toMatch(/never answered/);expect(result.config.tuning).toEqual({ depth: 2 });expect(pm2State?.status).toBe('online');});+ // The restore is only worth anything if the daemon is SERVING again when it+ // returns. `startMtplxServer` proves only that the process survived its+ // first seconds, and the caller measures immediately after — so returning+ // early would have it sample a checkpoint still loading, time every sample+ // out, and store a junk does-not-fit record that counts as "assessed".+ it('reports no config when the previous configuration could not be brought back', async () => {+ await startMtplxServer({ tuning: { depth: 2 } });+ // Nothing answers again — the tuned line, and the restore behind it.+ const result = await relaunchMtplxServerWithTuning({ contextWindow: 65536 });+ expect(result.applied).toBe(false);+ expect(result.config).toBeNull();+ });+// A launch line MTPLX ACCEPTS but the machine cannot hold dies partway// through loading the checkpoint — after the short startup window has// already returned. Waiting the full readiness budget out on a process PM2@@ -317,9 +360,10 @@ describe('mtplxServerManager', () => {// per bad launch line, and a sweep is expected to produce several.it('restores immediately when PM2 shows the relaunch died, not after the full budget', async () => {await startMtplxServer({ tuning: { depth: 2 } });+ answerUnless('--context-window');// Long enough that sitting it out would blow the per-test timeout, so the// assertion is about noticing the death rather than about the clock.- _resetMtplxServerStateForTests({ startupWait: 20, startupPoll: 5, relaunchReadyTimeout: 60_000 });+ _resetMtplxServerStateForTests({ startupWait: 20, startupPoll: 5, portRelease: 20, relaunchReadyTimeout: 60_000 });const realExec = pm2Module.execPm2.getMockImplementation();vi.spyOn(pm2Module, 'execPm2').mockImplementation(async (args) => {@@ -328,15 +372,37 @@ describe('mtplxServerManager', () => {if (args[0] === 'start' && args.includes('--context-window')) {setTimeout(() => { if (pm2State) pm2State.status = 'errored'; }, 30);}+ if (args[0] === 'logs') return { stdout: '', stderr: 'metal buffer allocation failed' };return out;});const result = await relaunchMtplxServerWithTuning({ contextWindow: 1048576 });expect(result.applied).toBe(false);- expect(result.reason).toMatch(/never answered/);+ // The two not-ready states are distinct: PM2 has a status and a log tail+ // for a process that DIED, and reporting that as "never answered on its+ // port" would discard the one fact that explains the failure.+ expect(result.reason).toMatch(/exited while loading/);+ expect(result.reason).toMatch(/metal buffer allocation failed/);expect(result.config.tuning).toEqual({ depth: 2 });});+ // "MTPLX rejected that tuning" is only true when `mtplx serve` actually ran.+ // `startMtplxServer` also throws from guards that fire BEFORE it launches+ // anything — most realistically the port still held by the daemon just+ // stopped — and blaming the tuning sends the user hunting a flag that was+ // never passed.+ it('does not blame the tuning for a failure that happened before MTPLX ran', async () => {+ await startMtplxServer({ tuning: { depth: 2 } });+ answerOnceRunning();+ // The stopped daemon is still holding the port when the next start tries.+ vi.spyOn(platform, 'isPortInUse').mockResolvedValue(true);++ const result = await relaunchMtplxServerWithTuning({ depth: 6 });+ expect(result.applied).toBe(false);+ expect(result.reason).toMatch(/could not start MTPLX/);+ expect(result.reason).not.toMatch(/rejected that tuning/);+ });+it('refuses when PM2 cannot be read, without calling the daemon external', async () => {// `pm2 jlist` fails transiently while MTPLX is still answering: running,// but PortOS cannot prove it owns the process.