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: decouple MTPLX cache discovery from daemon lifecycle
Adam Eivy2ca404ca63ed
diff --git a/server/lib/README.md b/server/lib/README.mdindex c33a662225..c070f25981 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -214,7 +214,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `opencodeConfig.js` | OpenCode config builder — `buildOpencodeEnvVars(provider, model)` builds dynamic `OPENCODE_CONFIG_CONTENT` declaring model ids under the namespace the provider's marker selects: a local runtime (`ollama` / `mtplx` / `llama` / `vllm` / `sglang`, bare ids) or a hosted gateway from `providerGateways.js` (`vendor/model` ids kept whole). Fixes --model rejection. Also attaches the key for a key-bearing namespace, and pins `small_model` to the run model for a gateway so OpenCode's own side calls (titles, summarization) can't land on its built-in default — a billed model the operator never chose. Under a `no-tool` public-review profile it also applies `hardenOpencodeConfigForNoTool` — root `permission: deny`, an emptied tool map on every agent, `tool_call: false` on every declared model, and no MCP/plugins/share/autoupdate — which IS OpenCode's enforced tool-free recipe, since it ships no read-only argv flag (`providerVendors.js` pairs it with `run --agent` + `OPENCODE_PUBLIC_REVIEW_AGENT`). The harden step also copies `agent.build`'s generation settings onto that agent, so the stage's configured thinking effort reaches the model that actually runs. || `localProviderRuntime.js` | Which LOCAL daemon a provider talks to, and where — `LOCAL_RUNTIMES` (llama.cpp / Ollama / LM Studio / MTPLX / vLLM: label, binary, canonical base URL read from `opencodeConfig.js` rather than re-typed, manage/docs links, model-download hint), `localBackendForProvider` + `localEndpointPort` + `isLocalInstanceHost` (moved here from `services/localModelHealing.js`, which re-exports them, so the healing path and the readiness checklist classify a provider identically — loopback/bind-all only, so a LAN/Tailscale peer on port 11434 is NOT claimed as a local daemon), `localRuntimeKind(provider)` (the `*Backed` markers first, then that classifier; `orcarouter` excluded as a remote API), `modelPinIsOffered(provider, model)` (the ONE rule for validating a stored model pin against a provider record: an empty `models` array and a local daemon's cached snapshot are both pass-throughs, so a freshly pulled Ollama model is never rejected as "not offered"), `localRuntimeForProvider(provider)` → the row with the endpoint the provider ITSELF configures (`OPENCODE_CONFIG_CONTENT`'s `baseURL`, `ANTHROPIC_BASE_URL`, or `endpoint`), then the `OLLAMA_URL`/`OLLAMA_HOST`/`LM_STUDIO_URL` override the backend managers read, then the canonical default — and `null` when that resolved endpoint fails `isLocalInstanceEndpoint` (an API provider on another machine has no local daemon to check, whatever its name says) — plus `normalizeOpenAiBaseUrl`. Pure; the probing half is `services/providerReadiness.js`. Optional `setupStateDetail` overrides `providerReadiness`'s per-state prose for a runtime whose local setup is not a model cache (vLLM's is a compose project); `standbyWhenStopped` marks an installed runtime such as llama.cpp whose stopped state is intentional standby rather than incomplete setup. || `managedDaemon.js` | Shared mechanism for the local daemons PortOS runs as optional PM2 processes (`services/llamaServerManager.js` → `portos-llama-server`, `services/mtplxServerManager.js` → `portos-mtplx`, `services/slotstreamServerManager.js` → `portos-slotstream`). Owns their PM2 process names — `LLAMA_APP`, `MTPLX_APP`, `SLOTSTREAM_APP`, and the `isModelServerProcess(name)` predicate over them — so a caller like the CoS health monitor can recognize a model server without importing a manager; the managers re-export those names. `createDaemonWatcher({...})` supplies the common PM2 launch-line re-adoption, endpoint probe, status skeleton, bounded log view, and port-release wait while managers retain daemon-specific parsing and lifecycle policy. `createDaemonLogBuffer({maxLines?})` is the bounded timestamped ring buffer of what PortOS logged around a launch, plus `withPm2Logs(output)` → that buffer followed by anything `pm2 logs` has which it doesn't already hold, deduped and re-capped (PM2's lines are a VIEW, never folded into the buffer — PM2 owns them and re-reads them every status call). `pm2ArgValue(args, flag)` reads one value back out of a PM2 process's recorded argv so a manager can recover a still-online daemon's launch config after a PortOS restart; `null` means the flag was absent, which a relaunch must leave off rather than defaulting. Also the shared **idle reaper**, for a daemon that cannot release its weights any other way: `registerIdleDaemon({name, getIdleMs, isPinned?, isRunning?, stop})` (seeds `lastUsedAt` to NOW, so a hand-started daemon gets a full window; `isPinned` exempts user-pinned servers), `markDaemonUsed(name)` — call on real traffic, NEVER on a status poll — `daemonLastUsedAt(name)`, `daemonReleaseReason(name)`, `idleWindowMs(minutes)` (minutes → ms; `0` = never, `null` = not configured, kept distinct), `evaluateMemoryPressurePolicy({...})` (pure policy function evaluating current state, pressure reading, and recent history), `reapIdleDaemons(now?, options?)` → the names stopped (stops idle daemons whose window elapsed, and runs a pressure-aware pass releasing the least recently used unpinned daemon under sustained host memory pressure; at most one daemon stopped per tick), and `startIdleReaper({intervalMs?})` / `stopIdleReaper()` (ONE interval for all registrants, `unref`'d, idempotent). `mtplxServerManager` and `slotstreamServerManager` register: llama.cpp releases its checkpoint in place via `--sleep-idle-seconds` and must NOT be stopped for it. Deliberately mechanism only — what a launch line means and when a daemon may start is exactly what differs between the two. |-| `mtplxModels.js` | `listMtplxCachedModels({command?})` → `{models, error}` from `mtplx models --json` (walks local directories — pulls no weights, loads no model, but see `mtplxRuntime.js`: on an un-warmed Homebrew wrapper the spawn ITSELF is a several-hundred-megabyte runtime download, so poll callers must gate on `describeMtplxRuntime().ready` first) `servableMtplxCachedModels(models)` → the rows MTPLX itself calls complete, and `pickMtplxCachedModel(models)` → the one repo id to hand `mtplx serve --model`. `models: null` means the cache could not be READ (no binary, command failed, unparseable) and is deliberately distinct from `[]` (read, and empty), because `services/localRuntimeSetup.js` starts MTPLX on its own default in the first case and refuses with the `mtplx pull` command in the second. Exists because `mtplx serve` defaults `--model` to one hard-coded checkpoint and exits 1 before binding when that repo is not cached — even on a host holding a different MTP model that serves fine. Picks only entries MTPLX itself calls complete (`validation.ok !== false`, so a half-finished pull is not served), preferring one with a recorded `mtplx_runtime.json` exactness contract. `describeMtplxCache(cache)` → `{state: 'unknown'\|'empty'\|'partial'\|'ready', model, count, error}` folds both into the one value `services/providerReadiness.js` puts on the checklist and `describeRuntimeSetup` picks a button from — so an empty cache is named up front instead of only inside the failure of a Start that could never work. |+| `mtplxModels.js` | `services/localCachedModels.js` owns provider-refresh discovery and gates it on runtime readiness without loading the process manager. `listMtplxCachedModels({command?})` → `{models, error}` from `mtplx models --json` (walks local directories — pulls no weights, loads no model, but see `mtplxRuntime.js`: on an un-warmed Homebrew wrapper the spawn ITSELF is a several-hundred-megabyte runtime download, so poll callers must gate on `describeMtplxRuntime().ready` first) `servableMtplxCachedModels(models)` → the rows MTPLX itself calls complete, and `pickMtplxCachedModel(models)` → the one repo id to hand `mtplx serve --model`. `models: null` means the cache could not be READ (no binary, command failed, unparseable) and is deliberately distinct from `[]` (read, and empty), because `services/localRuntimeSetup.js` starts MTPLX on its own default in the first case and refuses with the `mtplx pull` command in the second. Exists because `mtplx serve` defaults `--model` to one hard-coded checkpoint and exits 1 before binding when that repo is not cached — even on a host holding a different MTP model that serves fine. Picks only entries MTPLX itself calls complete (`validation.ok !== false`, so a half-finished pull is not served), preferring one with a recorded `mtplx_runtime.json` exactness contract. `describeMtplxCache(cache)` → `{state: 'unknown'\|'empty'\|'partial'\|'ready', model, count, error}` folds both into the one value `services/providerReadiness.js` puts on the checklist and `describeRuntimeSetup` picks a button from — so an empty cache is named up front instead of only inside the failure of a Start that could never work. || `mtplxRuntime.js` | `describeMtplxRuntime(binaryPath, {env?})` → `{ready, wrapper, venvPath}` — is MTPLX's own Python runtime on disk, decided by READING the binary rather than running it. Homebrew's `mtplx` is a shell wrapper that lazily bootstraps a version-keyed Python venv (a multi-hundred-megabyte pip install) on its first invocation, and `brew upgrade` re-arms it, so a status poll or an 8s-judged PM2 start is really a package download. This parses the wrapper's own `VENV=` assignment, honours `$MTPLX_BREW_VENV` the way `${MTPLX_BREW_VENV:-…}` does, and tests `<venv>/bin/mtplx` for executability — the wrapper's own `[ ! -x … ]` guard, so the two cannot disagree. Anything unrecognisable (a pip install, a compiled binary, an unparseable script) reports `ready: true, wrapper: false`, i.e. the status quo — never a block over a parse failure. || `slotstreamCatalog.js` | `SLOTSTREAM_CATALOG` — the curated mixture-of-experts checkpoints worth streaming from SSD (the technique only pays off on MoE: a dense model of the same size would stream every layer for every token). `resolveSlotstreamRepo(idOrRepo)` maps a catalog id or an `owner/name` repo id to a repo (null for anything else), `slotstreamModelDirName(repo)` flattens it to the single-segment cache directory whose NAME is the id a start hands `--model`, and `selectSlotstreamRepoFiles(siblings)` picks the `.safetensors`/config/tokenizer files a checkpoint is made of while dropping mirrored `original/`, GGUF, ONNX, and PyTorch copies of the same weights (which can double a 100 GB+ pull) and any name that is not a plain relative path. || `slotstreamModels.js` | `listSlotstreamCachedModels({cacheDir?})` → `{models, error}` from a local directory walk of the SSD-streaming MoE cache (no network, no model load), `pickSlotstreamCachedModel(models, requested?)` → the checkpoint id to hand `slotstream serve --model`, and `planSlotstreamMemory({totalBytes?, overrideGb?})` → `{targetGb, expectedPeakGb, expectedWarmDecodeToks, auto}` so the LLMs row can show the memory plan instead of hiding it. `models: null` means the cache could not be READ and is deliberately distinct from `[]` (read, and empty), because a start never fetches weights. |diff --git a/server/services/bootstrap.js b/server/services/bootstrap.jsindex e95e91f98e..fdbb0f7830 100644--- a/server/services/bootstrap.js+++ b/server/services/bootstrap.js@@ -270,7 +270,7 @@ export const bootstrapServices = async ({ io, dataDir, dataReferenceDir, serverD// checkpoint — and for Slotstream it pruned the record's other shipped ids.// This lets the refresh merge in what is actually on disk; it answers// `null` for every other provider, reads a local cache rather than calling- // a model, and imports each runtime's manager lazily so neither subtree+ // a model, and imports each runtime's cache reader lazily so neither subtree// reaches the boot closure (see `services/localCachedModels.js`).cachedModelIds: localCachedModelIds}),diff --git a/server/services/localCachedModels.js b/server/services/localCachedModels.jsindex 1867f865f4..155cd19afb 100644--- a/server/services/localCachedModels.js+++ b/server/services/localCachedModels.js@@ -32,21 +32,23 @@** ## Never a boot cost*- * Each runtime's manager is imported lazily and only for a provider whose- * runtime it owns, so an install with neither daemon never loads either- * subtree — and nothing here runs outside an explicit refresh request.+ * Runtime readers are imported lazily and only for a matching provider. MTPLX+ * discovery owns no process state and reads its cache without importing the+ * daemon manager or registering its idle policy. Slotstream retains its manager+ * adapter: that public probe also recognizes the managed process's live port.+ * Nothing here runs outside an explicit refresh request.*/import { isLocalInstanceEndpoint, localRuntimeKind } from '../lib/localProviderRuntime.js';/**- * Runtime key → the manager function that answers for it. Values are loaders- * rather than functions so the module graph stays out of the boot closure every- * server suite pays for (see `server/AGENTS.md` → Import scoping).+ * Runtime key → the cache probe that answers for it. Each probe defers its+ * runtime dependencies so they stay out of the boot closure every server suite+ * pays for (see `server/AGENTS.md` → Import scoping).*/const CACHED_MODEL_PROBES = {- mtplx: () => import('./mtplxServerManager.js').then((m) => m.mtplxCachedModelIds),- slotstream: () => import('./slotstreamServerManager.js').then((m) => m.slotstreamCachedModelIds),+ mtplx: mtplxCachedModelIds,+ slotstream: async (provider) => (await import('./slotstreamServerManager.js')).slotstreamCachedModelIds(provider),};/**@@ -61,7 +63,7 @@ const CACHED_MODEL_PROBES = {* The local-endpoint test comes first and costs nothing: a daemon on a tailnet* peer is someone else's process, and its checkpoints are on that machine — so* a provider aimed there must never be answered with THIS host's cache. It also- * keeps the ~one refresh per non-local provider from loading either manager.+ * keeps the ~one refresh per non-local provider from loading either runtime subtree.** `localRuntimeKind` resolves the shipped `mtplx` record by id (#6466) same as* it resolves a marker-backed wrapper, so one lookup routes both. Each probe@@ -73,8 +75,58 @@ const CACHED_MODEL_PROBES = {*/export async function localCachedModelIds(provider) {if (!isLocalInstanceEndpoint(provider?.endpoint)) return null;- const load = CACHED_MODEL_PROBES[localRuntimeKind(provider)];- if (!load) return null;- const probe = await load();- return probe(provider);+ const probe = CACHED_MODEL_PROBES[localRuntimeKind(provider)];+ return probe ? probe(provider) : null;+}++/**+ * The checkpoints THIS machine can serve, for an MTPLX provider's model refresh.+ *+ * `mtplx serve` loads one checkpoint and reports only that one through+ * `/v1/models`, under the slug its launch line minted — so the refresh a user+ * clicks after pulling a second checkpoint returned the same lone id it+ * returned before, and the new weights never appeared in the provider's model+ * list. The cache is the real catalog of what is servable here, so it is merged+ * in (`aiToolkit`'s `cachedModelIds` hook).+ *+ * Only entries MTPLX itself calls complete are listed (`servableMtplxCachedModels`+ * — the same rule a start is picked with): an interrupted pull leaves a directory+ * that lists but cannot load, and offering it as a selectable model just moves+ * the failure into an agent run.+ *+ * `null` for anything that is not an MTPLX provider AND for a cache that could+ * not be read (no binary, a cold Homebrew wrapper, a failed listing) —+ * deliberately not `[]`, which the caller must be free to read as "read, and+ * genuinely empty". Both answers leave the endpoint probe's result untouched.+ *+ * Gated on `describeMtplxRuntime().ready` for the reason `lib/mtplxModels.js`+ * spells out: on a host whose Homebrew wrapper has not bootstrapped its venv,+ * invoking `mtplx` IS a several-hundred-megabyte download. A refresh click is+ * explicit, but it is not consent to that — and it would time out anyway.+ *+ * @param {{type?: string, endpoint?: string, mtplxBacked?: boolean}|null} provider+ * @returns {Promise<string[]|null>}+ */+export async function mtplxCachedModelIds(provider) {+ // LOCAL first, and on its own line: the `mtplxBacked` marker rides the record+ // across a user's federated machines, so a provider pointed at a peer's MTPLX+ // carries every signal below while its checkpoints are on the OTHER machine.+ // Answering there would offer this host's cache as that provider's catalog.+ if (!isLocalInstanceEndpoint(provider?.endpoint)) return null;+ // `localRuntimeKind` now reads both signals the shipped records carry: the+ // `mtplxBacked` marker on the OpenCode CLI/TUI wrappers, and the bare `id` on+ // the API record — a plain OpenAI-compatible endpoint with no marker of its+ // own (#6466). A bare `:8000` is deliberately NOT a third signal here: that+ // port is generic, and this must not offer MTPLX's checkpoints as the+ // catalog of someone else's local API.+ if (localRuntimeKind(provider) !== 'mtplx') return null;+ const { findCommandOnPath } = await import('../lib/processEnv.js');+ const binaryPath = findCommandOnPath('mtplx');+ if (!binaryPath) return null;+ const { describeMtplxRuntime } = await import('../lib/mtplxRuntime.js');+ if (!(await describeMtplxRuntime(binaryPath)).ready) return null;+ const { listMtplxCachedModels, servableMtplxCachedModels } = await import('../lib/mtplxModels.js');+ const { models } = await listMtplxCachedModels();+ if (!Array.isArray(models)) return null;+ return servableMtplxCachedModels(models).map((row) => row.repo_id);}diff --git a/server/services/localCachedModels.test.js b/server/services/localCachedModels.test.jsindex b11f87f9f9..93b4c33498 100644--- a/server/services/localCachedModels.test.js+++ b/server/services/localCachedModels.test.js@@ -1,91 +1,85 @@-/**- * The routing half of the cached-checkpoint refresh hook.- *- * The per-runtime probes are pinned in their own managers' suites; what this- * file guards is the dispatch around them: which providers reach a probe at all,- * and — the property with a real cost behind it — that a provider belonging to- * neither runtime never loads either daemon manager. That import is the only- * reason the hook is a module rather than a direct call, so a regression there- * is silent and expensive rather than visible.- */-+/** Provider-refresh cache discovery must not load MTPLX lifecycle policy. */import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';-const mtplxProbe = vi.hoisted(() => vi.fn());-const slotstreamProbe = vi.hoisted(() => vi.fn());-const loaded = vi.hoisted(() => []);+const mocks = vi.hoisted(() => ({+ findCommand: vi.fn(),+ runtime: vi.fn(),+ cache: vi.fn(),+ slotstream: vi.fn(),+}));+// Fail even on a dynamic import: static import-closure checks cannot see this+// regression, and merely importing the manager registers its idle daemon.vi.mock('./mtplxServerManager.js', () => {- loaded.push('mtplx');- return { mtplxCachedModelIds: mtplxProbe };-});-vi.mock('./slotstreamServerManager.js', () => {- loaded.push('slotstream');- return { slotstreamCachedModelIds: slotstreamProbe };+ throw new Error('MTPLX cache discovery must not import the process manager');});+vi.mock('../lib/processEnv.js', () => ({ findCommandOnPath: mocks.findCommand }));+vi.mock('../lib/mtplxRuntime.js', () => ({ describeMtplxRuntime: mocks.runtime }));+vi.mock('../lib/mtplxModels.js', async (importOriginal) => ({+ ...await importOriginal(),+ listMtplxCachedModels: mocks.cache,+}));+vi.mock('./slotstreamServerManager.js', () => ({ slotstreamCachedModelIds: mocks.slotstream }));import { localCachedModelIds } from './localCachedModels.js';+const local = { id: 'mtplx', type: 'api', endpoint: 'http://127.0.0.1:8000/v1' };beforeEach(() => {- loaded.length = 0;- mtplxProbe.mockResolvedValue(['Vendor/Example-MTPLX']);- slotstreamProbe.mockResolvedValue(['example-4bit']);-});--afterEach(() => {- vi.clearAllMocks();+ mocks.findCommand.mockReturnValue('/example/bin/mtplx');+ mocks.runtime.mockResolvedValue({ ready: true });+ mocks.cache.mockResolvedValue({ models: [+ { repo_id: 'Vendor/Example-MTPLX', validation: { ok: true } },+ { repo_id: 'Vendor/Older-MTPLX' },+ { repo_id: 'Vendor/Partial-MTPLX', validation: { ok: false } },+ ], error: null });+ mocks.slotstream.mockResolvedValue(['example-4bit']);});+afterEach(() => vi.clearAllMocks());describe('localCachedModelIds', () => {- // FIRST in the file on purpose. A mock factory runs once per module, so- // `loaded` only ever records the very first import of each manager — after any- // routing case below has run, this assertion would read empty however the- // dispatcher behaved. Its positive control at the end is what proves the- // recorder works at all, and it is only available here.- it('loads neither daemon manager for a provider of no cached-catalog runtime', async () => {- expect(await localCachedModelIds({ id: 'claude-ollama', type: 'cli', ollamaBacked: true, endpoint: 'http://127.0.0.1:11434/v1' })).toBeNull();- expect(await localCachedModelIds({ id: 'openai', type: 'api', endpoint: 'https://api.example.com/v1' })).toBeNull();- // The whole reason this is a module of lazy loaders rather than a direct- // call: an install running neither daemon must not pull their PM2/daemon- // subtrees in on an unrelated provider's refresh.- expect(loaded).toEqual([]);-- await localCachedModelIds({ id: 'mtplx', type: 'api', endpoint: 'http://127.0.0.1:8000/v1' });- expect(loaded).toEqual(['mtplx']);+ it.each([+ ['the shipped API record', local],+ ['a marked CLI wrapper', { ...local, id: 'opencode-mtplx', type: 'cli', mtplxBacked: true }],+ ['a marked TUI wrapper', { ...local, id: 'opencode-mtplx-tui', type: 'tui', mtplxBacked: true }],+ ])('lists complete checkpoints for %s without importing MTPLX lifecycle policy', async (_label, provider) => {+ expect(await localCachedModelIds(provider)).toEqual(['Vendor/Example-MTPLX', 'Vendor/Older-MTPLX']);+ expect(mocks.cache).toHaveBeenCalledOnce();+ expect(mocks.slotstream).not.toHaveBeenCalled();});it.each([- ['the marked OpenCode wrapper', { id: 'opencode-mtplx', type: 'cli', command: 'opencode', mtplxBacked: true, endpoint: 'http://127.0.0.1:8000/v1' }],- // The shipped record is a plain OpenAI-compatible endpoint with no vendor- // marker, so its id is the only thing left to route on.- ['the unmarked API record', { id: 'mtplx', type: 'api', endpoint: 'http://127.0.0.1:8000/v1' }],- ])('routes %s to the MTPLX probe', async (_label, provider) => {- expect(await localCachedModelIds(provider)).toEqual(['Vendor/Example-MTPLX']);- expect(mtplxProbe).toHaveBeenCalledWith(provider);- expect(slotstreamProbe).not.toHaveBeenCalled();+ ['an unrelated local API on the same port', { ...local, id: 'example-api' }],+ ['a peer MTPLX', { ...local, endpoint: 'http://192.0.2.10:8000/v1' }],+ ['a cloud API', { id: 'openai', type: 'api', endpoint: 'https://api.example.com/v1' }],+ ])('does not inspect local caches for %s', async (_label, provider) => {+ expect(await localCachedModelIds(provider)).toBeNull();+ expect(mocks.findCommand).not.toHaveBeenCalled();+ expect(mocks.cache).not.toHaveBeenCalled();+ expect(mocks.slotstream).not.toHaveBeenCalled();});- it('routes a Slotstream provider to the Slotstream probe', async () => {- const provider = { id: 'slotstream', type: 'api', endpoint: 'http://127.0.0.1:5564/v1' };- expect(await localCachedModelIds(provider)).toEqual(['example-4bit']);- expect(mtplxProbe).not.toHaveBeenCalled();+ it('does not invoke a missing binary or bootstrap a cold runtime during refresh', async () => {+ mocks.findCommand.mockReturnValueOnce(null);+ expect(await localCachedModelIds(local)).toBeNull();+ expect(mocks.runtime).not.toHaveBeenCalled();+ mocks.runtime.mockResolvedValueOnce({ ready: false });+ expect(await localCachedModelIds(local)).toBeNull();+ expect(mocks.cache).not.toHaveBeenCalled();});- // A daemon on a tailnet peer is someone else's process and its checkpoints are- // on that machine — answering with THIS host's cache would put models the- // provider cannot reach into its catalog.- it('refuses a provider pointed at another machine even when it names the runtime', async () => {- expect(await localCachedModelIds({ id: 'mtplx', type: 'api', mtplxBacked: true, endpoint: 'http://100.64.0.5:8000/v1' })).toBeNull();- expect(mtplxProbe).not.toHaveBeenCalled();+ it('keeps an unreadable cache distinct from a successfully read empty cache', async () => {+ mocks.cache.mockResolvedValueOnce({ models: null, error: 'listing failed' });+ expect(await localCachedModelIds(local)).toBeNull();+ mocks.cache.mockResolvedValueOnce({ models: [], error: null });+ expect(await localCachedModelIds(local)).toEqual([]);});-- it('passes a probe’s own refusal straight through', async () => {- // `null` from a probe means "read nothing usable" — the toolkit leaves the- // endpoint's answer untouched, which is not the same as this router deciding- // the provider was never a candidate.- mtplxProbe.mockResolvedValue(null);- expect(await localCachedModelIds({ id: 'mtplx', type: 'api', endpoint: 'http://127.0.0.1:8000/v1' })).toBeNull();- expect(mtplxProbe).toHaveBeenCalled();+ it('preserves the Slotstream manager adapter and its refusal result', async () => {+ const provider = { id: 'slotstream', type: 'api', endpoint: 'http://127.0.0.1:5564/v1' };+ expect(await localCachedModelIds(provider)).toEqual(['example-4bit']);+ expect(mocks.slotstream).toHaveBeenCalledWith(provider);+ mocks.slotstream.mockResolvedValueOnce(null);+ expect(await localCachedModelIds(provider)).toBeNull();+ expect(mocks.findCommand).not.toHaveBeenCalled();});});diff --git a/server/services/mtplxServerManager.js b/server/services/mtplxServerManager.jsindex 56d9c401b4..3e6b0eb0a1 100644--- a/server/services/mtplxServerManager.js+++ b/server/services/mtplxServerManager.js@@ -30,7 +30,7 @@ import { sleep } from '../lib/fileUtils.js';import { ServerError } from '../lib/errorHandler.js';import { launchArgs, normalizeTuning, tuningSpecsFor } from '../lib/localModelTuning.js';import { LOCAL_RUNTIMES, localEndpointPort, localRuntimeKind, isLocalInstanceEndpoint } from '../lib/localProviderRuntime.js';-import { listMtplxCachedModels, pickMtplxCachedModel, servableMtplxCachedModels } from '../lib/mtplxModels.js';+import { listMtplxCachedModels, pickMtplxCachedModel } from '../lib/mtplxModels.js';import { describeMtplxRuntime } from '../lib/mtplxRuntime.js';import { probeOpenAiModels } from '../lib/openAiModelsProbe.js';import { createDaemonWatcher, pm2ArgValue, idleWindowMs, markDaemonUsed, registerIdleDaemon, MTPLX_APP } from '../lib/managedDaemon.js';@@ -46,6 +46,8 @@ import { runStreamingCommand } from '../lib/streamingSpawn.js';import { execPm2, getAppStatusStrict, clearJlistCache, getSavedProcessNames } from './pm2.js';export { MTPLX_APP };+// Compatibility export; provider cache discovery owns no daemon lifecycle state.+export { mtplxCachedModelIds } from './localCachedModels.js';const PROBE_TIMEOUT_MS = 1500;/**@@ -1011,55 +1013,6 @@ export function isMtplxProvider(provider) {return Boolean(managedPort) && localEndpointPort(provider.endpoint) === managedPort;}-/**- * The checkpoints THIS machine can serve, for an MTPLX provider's model refresh.- *- * `mtplx serve` loads one checkpoint and reports only that one through- * `/v1/models`, under the slug its launch line minted — so the refresh a user- * clicks after pulling a second checkpoint returned the same lone id it- * returned before, and the new weights never appeared in the provider's model- * list. The cache is the real catalog of what is servable here, so it is merged- * in (`aiToolkit`'s `cachedModelIds` hook).- *- * Only entries MTPLX itself calls complete are listed (`servableMtplxCachedModels`- * — the same rule a start is picked with): an interrupted pull leaves a directory- * that lists but cannot load, and offering it as a selectable model just moves- * the failure into an agent run.- *- * `null` for anything that is not an MTPLX provider AND for a cache that could- * not be read (no binary, a cold Homebrew wrapper, a failed listing) —- * deliberately not `[]`, which the caller must be free to read as "read, and- * genuinely empty". Both answers leave the endpoint probe's result untouched.- *- * Gated on `describeMtplxRuntime().ready` for the reason `lib/mtplxModels.js`- * spells out: on a host whose Homebrew wrapper has not bootstrapped its venv,- * invoking `mtplx` IS a several-hundred-megabyte download. A refresh click is- * explicit, but it is not consent to that — and it would time out anyway.- *- * @param {{type?: string, endpoint?: string, mtplxBacked?: boolean}|null} provider- * @returns {Promise<string[]|null>}- */-export async function mtplxCachedModelIds(provider) {- // LOCAL first, and on its own line: the `mtplxBacked` marker rides the record- // across a user's federated machines, so a provider pointed at a peer's MTPLX- // carries every signal below while its checkpoints are on the OTHER machine.- // Answering there would offer this host's cache as that provider's catalog.- if (!isLocalInstanceEndpoint(provider?.endpoint)) return null;- // `localRuntimeKind` now reads both signals the shipped records carry: the- // `mtplxBacked` marker on the OpenCode CLI/TUI wrappers, and the bare `id` on- // the API record — a plain OpenAI-compatible endpoint with no marker of its- // own (#6466). A bare `:8000` is deliberately NOT a third signal here: that- // port is generic, and this must not offer MTPLX's checkpoints as the- // catalog of someone else's local API.- if (localRuntimeKind(provider) !== 'mtplx') return null;- const binaryPath = resolveMtplxBinary();- if (!binaryPath) return null;- if (!(await describeMtplxRuntime(binaryPath)).ready) return null;- const { models } = await listMtplxCachedModels();- if (!Array.isArray(models)) return null;- return servableMtplxCachedModels(models).map((row) => row.repo_id);-}-/*** The `ensureProviderReady` shape `services/aiProvider.js` expects, for MTPLX.*diff --git a/server/services/mtplxServerManager.test.js b/server/services/mtplxServerManager.test.jsindex b28ed91103..66a070b566 100644--- a/server/services/mtplxServerManager.test.js+++ b/server/services/mtplxServerManager.test.js@@ -972,73 +972,9 @@ describe('mtplxServerManager', () => {* checkpoint per process and reports only that one, so without this a refresh* after pulling a second checkpoint answered with the same lone id.*/- describe('mtplxCachedModelIds', () => {- const CACHED = [cachedModel('Example/Qwen-MTP'), cachedModel('Other/Ornith-MTP')];-- beforeEach(() => {- vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue(BINARY);- vi.spyOn(mtplxModels, 'listMtplxCachedModels').mockResolvedValue({ models: CACHED, error: null });- });-- // The three shipped records carry three different signals: the marker on the- // OpenCode wrappers, the bare id on the API record, and the served port for- // a provider a user built themselves.- it.each([- ['an mtplxBacked CLI wrapper', { id: 'opencode-mtplx', type: 'cli', command: 'opencode', mtplxBacked: true, endpoint: 'http://127.0.0.1:8000/v1' }],- ['an mtplxBacked TUI wrapper', { id: 'opencode-mtplx-tui', type: 'tui', command: 'opencode', mtplxBacked: true, endpoint: 'http://127.0.0.1:8000/v1' }],- ['the unmarked API record', { id: 'mtplx', type: 'api', endpoint: 'http://127.0.0.1:8000/v1' }],- ])('lists the servable checkpoints for %s', async (_label, provider) => {- expect(await mtplxCachedModelIds(provider)).toEqual(['Example/Qwen-MTP', 'Other/Ornith-MTP']);- });-- // :8000 is a generic port. Claiming any local server on it would offer MTPLX- // checkpoints as the model list of someone else's API.- it.each([- ['another local API on the same port', { id: 'some-local-api', type: 'api', endpoint: 'http://127.0.0.1:8000/v1' }],- ['a remote provider', { id: 'openai', type: 'api', endpoint: 'https://api.example.com/v1' }],- ['an MTPLX on another machine', { id: 'peer-mtplx', type: 'api', mtplxBacked: true, endpoint: 'http://100.64.0.5:8000/v1' }],- ])('answers null for %s', async (_label, provider) => {- expect(await mtplxCachedModelIds(provider)).toBeNull();- });-- // An interrupted `mtplx pull` leaves a directory that lists but cannot load.- // Offering it as a selectable model just moves the failure into an agent run.- it('drops a checkpoint MTPLX itself calls incomplete', async () => {- vi.spyOn(mtplxModels, 'listMtplxCachedModels').mockResolvedValue({- models: [cachedModel('Example/Qwen-MTP'), { repo_id: 'Half/Pulled-MTP', validation: { ok: false } }],- error: null,- });- expect(await mtplxCachedModelIds({ id: 'mtplx', type: 'api', endpoint: 'http://127.0.0.1:8000/v1' }))- .toEqual(['Example/Qwen-MTP']);- });-- // `null`, never `[]`: a cache PortOS could not read must not read as "this- // machine has no checkpoints" and blank a provider's model list.- it('answers null when the cache could not be read', async () => {- vi.spyOn(mtplxModels, 'listMtplxCachedModels').mockResolvedValue({ models: null, error: '`mtplx models` timed out' });- expect(await mtplxCachedModelIds({ id: 'mtplx', type: 'api', endpoint: 'http://127.0.0.1:8000/v1' })).toBeNull();- });-- it('answers null without invoking mtplx when the binary is not on PATH', async () => {- vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue(null);- expect(await mtplxCachedModelIds({ id: 'mtplx', type: 'api', endpoint: 'http://127.0.0.1:8000/v1' })).toBeNull();- expect(mtplxModels.listMtplxCachedModels).not.toHaveBeenCalled();- });-- // On a host whose Homebrew wrapper has not bootstrapped its venv, invoking- // `mtplx` IS a several-hundred-megabyte download. A refresh click is not- // consent to that — and it would outrun the cache-query budget anyway.- it('does not invoke mtplx while its Python runtime is still un-bootstrapped', async () => {- // The probe honours $MTPLX_BREW_VENV exactly as the wrapper does, so a- // value in the developer's own environment would decide this test.- vi.stubEnv('MTPLX_BREW_VENV', '');- const wrapper = await writeMtplxWrapper(testLogDir, join(testLogDir, 'venv-2.10.1'));- vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue(wrapper);-- expect(await mtplxCachedModelIds({ id: 'mtplx', type: 'api', endpoint: 'http://127.0.0.1:8000/v1' })).toBeNull();- expect(mtplxModels.listMtplxCachedModels).not.toHaveBeenCalled();- vi.unstubAllEnvs();- });+ it('keeps the cached-model export compatible with the discovery owner', async () => {+ const discovery = await import('./localCachedModels.js');+ expect(mtplxCachedModelIds).toBe(discovery.mtplxCachedModelIds);});describe('ensureMtplxProviderReady', () => {