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: wake MTPLX before TUI runs
[._.]/ Adam Eivy121da7d0b2dc
diff --git a/client/src/components/settings/LocalLlmTab.jsx b/client/src/components/settings/LocalLlmTab.jsxindex c2f4b54526..f112bfd330 100644--- a/client/src/components/settings/LocalLlmTab.jsx+++ b/client/src/components/settings/LocalLlmTab.jsx@@ -11,7 +11,7 @@ import {getLocalLlmStatus, getLocalLlmCatalog, getLocalLlmHuggingFaceSearch, installLocalLlmModel,deleteLocalLlmModel, migrateLocalLlmBackend, installLocalLlmBackend, upgradeLocalLlmBackend, controlOllamaService,installAudioModel, patchSettingsSlice, getLlamaServerStatus, getLlamaServerUpdateStatus, startLlamaServer, stopLlamaServer, installLlamaServer, upgradeLlamaServer,- downloadSpecDecodeModel, cancelSpecDecodeModelDownload, controlLmStudioService, getMtplxServerStatus, stopMtplxServer, installMtplx,+ downloadSpecDecodeModel, cancelSpecDecodeModelDownload, controlLmStudioService, getMtplxServerStatus, startMtplxServer, stopMtplxServer, installMtplx,searchMtplxModels, pullMtplxModel, removeMtplxModel,saveRuntimeStartupList} from '../../services/api';@@ -505,8 +505,13 @@ export function LocalLlmTab() {() => installMtplx(),'MTPLX installed').then(loadMtplxStatus);- // MTPLX has no Start action: the first PortOS request routed to it starts it.- // What the card saves is the launch line that on-demand start will replay.+ const runtimeStartMtplx = () => runAction(+ 'runtime-start-mtplx',+ () => startMtplxServer(),+ (r) => r?.online ? 'MTPLX is running' : 'MTPLX is loading its checkpoint'+ ).then(loadMtplxStatus);+ // The card can start MTPLX explicitly from its cached checkpoint, and the+ // same launch configuration is replayed when a request wakes it on demand.const saveMtplxLaunch = (launch) => runAction('runtime-save-mtplx-launch',() => patchSettingsSlice('localLlm.mtplx', { launch }),@@ -1056,6 +1061,7 @@ export function LocalLlmTab() {actionInProgress={actionInProgress}onRefresh={loadMtplxStatus}onSaveLaunch={saveMtplxLaunch}+ onStart={runtimeStartMtplx}onStop={runtimeStopMtplx}onInstall={runtimeInstallMtplx}onSearchModels={mtplxSearch}diff --git a/client/src/components/settings/MtplxServerCard.jsx b/client/src/components/settings/MtplxServerCard.jsxindex 0ff03c2f54..decb708d2e 100644--- a/client/src/components/settings/MtplxServerCard.jsx+++ b/client/src/components/settings/MtplxServerCard.jsx@@ -25,6 +25,7 @@ export default function MtplxServerCard({actionInProgress,onRefresh,onSaveLaunch,+ onStart,onStop,onInstall,onSearchModels,@@ -156,11 +157,21 @@ export default function MtplxServerCard({<p className="text-xs text-gray-500">Couldn't read MTPLX's model cache ({status.cacheError}) — an on-demand start will fall through to MTPLX's own default checkpoint.</p>)}<p className="text-[11px] text-gray-500">- MTPLX starts on demand — the first PortOS request routed to it brings it up on these- options, and its idle window (set under Local Runtime Servers) stops it again to release- the checkpoint. There is no Start button because a manually-started server would only pin- those gigabytes ahead of a request that may never come.+ MTPLX starts on demand when a request needs it. You can also start it now with the+ cached checkpoint; its idle window (set under Local Runtime Servers) stops it again to+ release the checkpoint. Neither path downloads weights without an explicit download.</p>+ {!emptyCache && onStart && (+ <button+ onClick={() => onStart?.()}+ disabled={busy}+ className={`${btnClass} bg-port-success/20 hover:bg-port-success/30 text-port-success`}+ title="Start MTPLX with the cached checkpoint; no weights are downloaded"+ >+ {actionInProgress === 'runtime-start-mtplx' ? <BrailleSpinner /> : <Terminal size={13} />}+ Start MTPLX+ </button>+ )}<buttononClick={() => onSaveLaunch({ model: model || null, ...(port ? { port: Number(port) } : {}) })}disabled={busy || emptyCache}diff --git a/client/src/components/settings/MtplxServerCard.test.jsx b/client/src/components/settings/MtplxServerCard.test.jsxindex 290e8d78c2..43bf910f42 100644--- a/client/src/components/settings/MtplxServerCard.test.jsx+++ b/client/src/components/settings/MtplxServerCard.test.jsx@@ -7,6 +7,7 @@ const renderCard = async (status, props = {}) => {const handlers = {onRefresh: vi.fn(),onSaveLaunch: vi.fn(),+ onStart: vi.fn(),onStop: vi.fn(),onInstall: vi.fn(),// The checkpoint manager loads upstream's default listing on mount.@@ -26,9 +27,8 @@ const renderCard = async (status, props = {}) => {};describe('MtplxServerCard', () => {- // MTPLX has no Start button: the first PortOS request routed to it starts it.- // What this card saves is the launch line that on-demand start replays, so the- // user's checkpoint choice survives a stop/start cycle they never see.+ // The card saves the launch line used by both explicit and on-demand starts,+ // so the user's checkpoint choice survives a stop/start cycle they never see.it('saves the cached checkpoint and port the user picked', async () => {const handlers = await renderCard({installed: true,@@ -145,10 +145,11 @@ describe('MtplxServerCard', () => {expect(handlers.onSaveLaunch).toHaveBeenCalled();});- it('says MTPLX starts on demand, so the missing Start button reads as intent', async () => {- await renderCard({ installed: true, running: false, supported: true, cachedModels: ['Example/Qwen-MTP'] });+ it('says MTPLX starts on demand while offering an explicit Start button', async () => {+ const handlers = await renderCard({ installed: true, running: false, supported: true, cachedModels: ['Example/Qwen-MTP'] });expect(screen.getByText(/starts on demand/i)).toBeInTheDocument();- expect(screen.queryByRole('button', { name: /^Start/ })).toBeNull();+ fireEvent.click(screen.getByRole('button', { name: /^Start MTPLX/ }));+ expect(handlers.onStart).toHaveBeenCalledWith();});it('will not offer to stop a server started outside PortOS', async () => {diff --git a/client/src/components/settings/RuntimeServersCard.jsx b/client/src/components/settings/RuntimeServersCard.jsxindex 3233023a65..ceb5d318bf 100644--- a/client/src/components/settings/RuntimeServersCard.jsx+++ b/client/src/components/settings/RuntimeServersCard.jsx@@ -285,6 +285,7 @@ export default function RuntimeServersCard({onConfigureLlama,onConfigureMtplx,onInstallMtplx,+ onStartMtplx,onStopMtplx,onSaveStartup,onSaveIdleWindow,@@ -335,17 +336,15 @@ export default function RuntimeServersCard({status: mtplxStatus,platformReason: mtplxStatus?.supported === false ? 'macOS with Apple Silicon only' : null,onInstall: onInstallMtplx,- // No Start button by design. MTPLX is lazily started by the first PortOS- // request routed to it and stopped again once its idle window elapses, so- // a manual Start would only pin 20GB ahead of a request that may never- // come. Install and Configure (download a checkpoint, set the launch- // options) are the two things that still need a human.- onStart: null,+ // MTPLX can be started explicitly when a verified checkpoint is cached,+ // and is still restarted automatically before a request after an idle+ // release. Neither path downloads or guesses a model.+ onStart: mtplxStatus?.cachedModels?.length ? onStartMtplx : null,onStop: onStopMtplx,startBlockedReason: mtplxStatus?.installed && !mtplxStatus?.running? (mtplxStatus?.cachedModels?.length === 0 && !mtplxStatus?.cacheError? 'No checkpoint yet — use Configure to download one'- : 'Starts on demand')+ : null): null,detail: mtplxStatus?.cachedModels?.length? `${mtplxStatus.cachedModels.length} checkpoint${mtplxStatus.cachedModels.length === 1 ? '' : 's'} cached`diff --git a/client/src/components/settings/RuntimeServersCard.test.jsx b/client/src/components/settings/RuntimeServersCard.test.jsxindex 38e5652ea2..0ce53ece97 100644--- a/client/src/components/settings/RuntimeServersCard.test.jsx+++ b/client/src/components/settings/RuntimeServersCard.test.jsx@@ -19,6 +19,7 @@ const renderCard = (props = {}) => {onConfigureLlama: vi.fn(),onConfigureMtplx: vi.fn(),onInstallMtplx: vi.fn(),+ onStartMtplx: vi.fn(),onSaveIdleWindow: vi.fn(),onStopMtplx: vi.fn(),onSaveStartup: vi.fn(),@@ -124,16 +125,23 @@ describe('RuntimeServersCard', () => {);});- // MTPLX cannot unload its checkpoint in place, so PortOS stops the process- // when it goes idle and the next request starts it again. A manual Start would- // only pin 20GB ahead of a request that may never come.- it('offers no MTPLX Start — it starts on demand', () => {- renderCard({+ // MTPLX can be started on demand or explicitly when a verified checkpoint is+ // already cached. Neither path downloads weights.+ it('offers MTPLX Start when a checkpoint is cached', () => {+ const handlers = renderCard({mtplxStatus: { installed: true, running: false, supported: true, cachedModels: ['Example/Qwen-MTP'], endpoint: 'http://127.0.0.1:8000/v1' },});+ fireEvent.click(within(row('MTPLX')).getByRole('button', { name: /^Start/ }));+ expect(handlers.onStartMtplx).toHaveBeenCalledWith();+ });++ it('keeps MTPLX Start unavailable when no checkpoint is cached', () => {+ renderCard({+ mtplxStatus: { installed: true, running: false, supported: true, cachedModels: [], endpoint: 'http://127.0.0.1:8000/v1' },+ });const mtplx = row('MTPLX');expect(within(mtplx).queryByRole('button', { name: /^Start/ })).toBeNull();- expect(within(mtplx).getByText(/Starts on demand/)).toBeInTheDocument();+ expect(within(mtplx).getByText(/use Configure to download one/)).toBeInTheDocument();});// llama.cpp keeps its Stop: it is started explicitly from the launcher, anddiff --git a/server/services/localModelAgentBenchmark.js b/server/services/localModelAgentBenchmark.jsindex 2a30fc4f33..646f2b421f 100644--- a/server/services/localModelAgentBenchmark.js+++ b/server/services/localModelAgentBenchmark.js@@ -25,6 +25,7 @@ import { isClaudeCommand, isOpencodeCommand } from '../lib/providerModels.js';// different tool-call counts for the same run.import { summarizeOpenCodeEvents } from '../lib/opencodeStream.js';import { getProviderById } from './providers.js';+import { ensureProviderReadyForExecution } from './providerExecutionReadiness.js';import { executeTuiRun } from './tuiPromptRunner.js';import { getRunsPath } from './runner.js';@@ -124,6 +125,30 @@ export async function runOpenCodeAgentBenchmark({ backend, modelId, timeoutMs =const startedAt = Date.now();const benchmarkFilePath = join(scratchDir, 'PORTOS_AGENT_BENCHMARK.txt');try {+ // This benchmark uses the direct PTY runner instead of+ // runPromptThroughProvider, so wake a stopped local daemon before spawning+ // OpenCode. MTPLX releases its checkpoint after the idle window.+ const ready = await ensureProviderReadyForExecution(provider);+ if (!ready.success) {+ return {+ backend,+ modelId,+ providerId: target.providerId,+ providerLabel: target.label,+ measurementMode: 'pty-tui',+ completed: false,+ elapsedMs: Math.max(0, Date.now() - startedAt),+ assistantChars: null,+ outputTokens: null,+ toolCalls: null,+ taskCharsPerSecond: null,+ taskTokensPerSecond: null,+ exitCode: null,+ timedOut: false,+ error: ready.error || `${target.label} is not ready`,+ };+ }+// The one-shot TUI runner owns PTY startup, prompt paste, trust dialogs,// response-file completion, cancellation and run-record cleanup semantics.// Clone only the model pin: the provider's endpoint, env and permissionsdiff --git a/server/services/localModelAgentBenchmark.test.js b/server/services/localModelAgentBenchmark.test.jsindex 2f677758b4..6470accdeb 100644--- a/server/services/localModelAgentBenchmark.test.js+++ b/server/services/localModelAgentBenchmark.test.js@@ -1,6 +1,7 @@import { describe, expect, it, vi, beforeEach } from 'vitest';import { join } from 'path';vi.mock('./providers.js', () => ({ getProviderById: vi.fn() }));+vi.mock('./providerExecutionReadiness.js', () => ({ ensureProviderReadyForExecution: vi.fn().mockResolvedValue({ success: true }) }));vi.mock('./tuiPromptRunner.js', () => ({ executeTuiRun: vi.fn() }));vi.mock('./runner.js', () => ({ getRunsPath: vi.fn(() => '/tmp/portos-benchmark-runs') }));vi.mock('../lib/providerModels.js', () => ({@@ -9,6 +10,7 @@ vi.mock('../lib/providerModels.js', () => ({}));import { getProviderById } from './providers.js';+import { ensureProviderReadyForExecution } from './providerExecutionReadiness.js';import { executeTuiRun } from './tuiPromptRunner.js';import {buildOpenCodeAgentBenchmarkPrompt,@@ -115,6 +117,25 @@ describe('runOpenCodeAgentBenchmark', () => {});});+ it('wakes the MTPLX daemon before running its TUI benchmark', async () => {+ getProviderById.mockResolvedValue({+ id: 'opencode-mtplx-tui',+ type: 'tui',+ command: 'opencode',+ args: [],+ mtplxBacked: true,+ endpoint: 'http://127.0.0.1:8000/v1',+ });++ await runOpenCodeAgentBenchmark({ backend: 'mtplx', modelId: 'mtplx-qwen38-27b-optimized-speed' });++ expect(ensureProviderReadyForExecution).toHaveBeenCalledWith(expect.objectContaining({+ id: 'opencode-mtplx-tui',+ mtplxBacked: true,+ }));+ expect(executeTuiRun).toHaveBeenCalledTimes(1);+ });+it('rejects a model outside the three explicit benchmark targets', async () => {await expect(runOpenCodeAgentBenchmark({ backend: 'llama', modelId: 'other-model' })).rejects.toMatchObject({ code: 'LOCAL_AGENT_BENCHMARK_TARGET_INVALID', status: 400 });diff --git a/server/services/mtplxServerManager.js b/server/services/mtplxServerManager.jsindex 6468f8055c..23b9bde7de 100644--- a/server/services/mtplxServerManager.js+++ b/server/services/mtplxServerManager.js@@ -841,7 +841,10 @@ export async function ensureMtplxRunning() {* it is this install's business.*/export function isMtplxProvider(provider) {- if (!provider || provider.type !== 'api') return false;+ // API providers reach MTPLX directly, while OpenCode TUI providers carry+ // the same local endpoint and need the exact same lazy wake-up before the+ // TUI is spawned.+ if (!provider || !['api', 'tui'].includes(provider.type)) return false;if (!isLocalInstanceEndpoint(provider.endpoint)) return false;// `localRuntimeKind`, not `localBackendForProvider` — the latter only ever// answers 'ollama'/'lmstudio' (it maps those two catalog ports), so it reportsdiff --git a/server/services/mtplxServerManager.test.js b/server/services/mtplxServerManager.test.jsindex bc53f00d12..8a57296d8e 100644--- a/server/services/mtplxServerManager.test.js+++ b/server/services/mtplxServerManager.test.js@@ -679,6 +679,10 @@ describe('mtplxServerManager', () => {it('does not match a CLI provider', () => {expect(isMtplxProvider({ type: 'cli', endpoint: 'http://127.0.0.1:8000/v1', id: 'mtplx', mtplxBacked: true })).toBe(false);});++ it('matches an MTPLX-backed TUI provider', () => {+ expect(isMtplxProvider({ type: 'tui', endpoint: 'http://127.0.0.1:8000/v1', id: 'mtplx-tui', mtplxBacked: true })).toBe(true);+ });});describe('ensureMtplxProviderReady', () => {diff --git a/server/services/promptRunner.js b/server/services/promptRunner.jsindex 4977769233..cb93c968ca 100644--- a/server/services/promptRunner.js+++ b/server/services/promptRunner.js@@ -39,6 +39,7 @@ import { createSingleFlight } from '../lib/singleFlight.js';import { extractJson } from '../lib/jsonExtract.js';import { isCreativeRunSource, withCreativeLatitude } from '../lib/creativeLatitude.js';import { DEFAULT_OUTPUT_RESERVE_TOKENS, estimateTokens } from '../lib/contextBudget.js';+import { ensureProviderReadyForExecution } from './providerExecutionReadiness.js';// The fallback-lifecycle notifiers live in services/autoFixer.js, which// transitively pulls in services/cos.js (PM2 + fs + sockets). Importing it@@ -1243,7 +1244,24 @@ async function executeProviderRunOnce({// module comment promises: gating the *requested* provider at the call// site missed a remote/CLI primary that swaps/fails over to a local// backend, defeating the VRAM/OOM serialization. No-op for cloud/CLI/TUI.- return withLocalConcurrencyGate(effectiveProvider, () => new Promise((resolve, reject) => {+ return withLocalConcurrencyGate(effectiveProvider, async () => {+ // API providers run through the shared toolkit readiness hook. TUI+ // providers spawn OpenCode directly, so they need the same hook here or+ // MTPLX remains stopped until after the TUI has already failed its request.+ if (effectiveProvider.type === PROVIDER_TYPES.TUI) {+ const ready = await ensureProviderReadyForExecution(effectiveProvider).catch((err) => ({+ success: false,+ error: err.message,+ }));+ if (!ready.success) {+ const error = new Error(ready.error || 'Provider readiness check failed');+ error.effectiveProvider = effectiveProvider;+ error.effectiveModel = effectiveModel;+ throw error;+ }+ }++ return new Promise((resolve, reject) => {let text = '';let settled = false;let apiTimeoutHandle = null;@@ -1360,7 +1378,8 @@ async function executeProviderRunOnce({} else {safeReject(new Error(`Unsupported provider type: ${effectiveProvider.type}`));}- })).finally(() => {+ });+ }).finally(() => {if (typeof onRunSettled !== 'function') return;try { onRunSettled(runId); } catch (err) {console.error(`❌ run lifecycle settle hook failed: ${err.message}`);diff --git a/server/services/promptRunner.test.js b/server/services/promptRunner.test.jsindex ee6c9be909..dc1a20c263 100644--- a/server/services/promptRunner.test.js+++ b/server/services/promptRunner.test.js@@ -27,6 +27,10 @@ vi.mock('./tuiPromptRunner.js', () => ({executeTuiRun: vi.fn(),}));+vi.mock('./providerExecutionReadiness.js', () => ({+ ensureProviderReadyForExecution: vi.fn().mockResolvedValue({ success: true }),+}));+// providers.js is a compatibility shim that throws when the toolkit hasn't// been initialized via setAIToolkit(). Mock it so the resolveProviderAndModel// tests can drive the active/by-id lookups directly. `getAllProviders` is@@ -59,6 +63,7 @@ vi.mock('../lib/aiToolkitState.js', () => ({const runner = await import('./runner.js');const tuiRunner = await import('./tuiPromptRunner.js');+const executionReadiness = await import('./providerExecutionReadiness.js');const providers = await import('./providers.js');const autoFixer = await import('./autoFixer.js');const toolkitState = await import('../lib/aiToolkitState.js');@@ -644,6 +649,20 @@ describe('promptRunner — TUI provider routing', () => {expect(runner.executeApiRun).not.toHaveBeenCalled();});+ it('wakes an MTPLX-backed TUI before spawning OpenCode', async () => {+ const provider = tuiProvider({+ id: 'opencode-mtplx-tui',+ mtplxBacked: true,+ endpoint: 'http://127.0.0.1:8000/v1',+ });+ tuiRunner.executeTuiRun.mockImplementation(async ({ onComplete }) => onComplete({ success: true, text: 'ready' }));++ await runPromptThroughProvider({ provider, prompt: 'p', source: 'test' });++ expect(executionReadiness.ensureProviderReadyForExecution).toHaveBeenCalledWith(provider);+ expect(tuiRunner.executeTuiRun).toHaveBeenCalledTimes(1);+ });+it('passes cwd + timeout overrides through to executeTuiRun', async () => {tuiRunner.executeTuiRun.mockImplementation(async ({ onData, onComplete }) => {onData('ok');