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
show cached-but-unserved checkpoints when refreshing an MTPLX or Slotstream provider, and stop the refresh scrolling the page to the top
[._.]/ Adam Eivyca01674b650c
diff --git a/client/src/pages/AIProviders.jsx b/client/src/pages/AIProviders.jsxindex d0d69222b9..933782c50d 100644--- a/client/src/pages/AIProviders.jsx+++ b/client/src/pages/AIProviders.jsx@@ -257,8 +257,17 @@ export default function AIProviders() {};}, [activeRun]);+ // `setLoading(true)` swaps the entire list for the page skeleton, which+ // unmounts the scroll container and drops the user back at the top. That is+ // right for the first load and wrong for every reload that follows a click on+ // a card — after enabling, deleting, or saving a provider several screens+ // down, the card you just acted on scrolled out from under you. So the+ // skeleton is shown only while there is nothing to keep on screen; a reload+ // over an already-rendered list refreshes in place and holds the scroll+ // position. The `loadError` path still swaps in the error state, because there+ // genuinely is nothing left to show.const loadData = async () => {- setLoading(true);+ setLoading(providers.length === 0);setLoadError(false);let providersFailed = false;const [providersData, appsData, statusData, orchestrationProfilesData] = await Promise.all([@@ -463,13 +472,36 @@ export default function AIProviders() {loadReadiness();};+ // Applied to the clicked card in place. `loadData()` here instead flipped+ // `loading` back on, swapping the whole page for the skeleton and dropping the+ // user at the top of the list — a card several screens down was unreachable+ // after refreshing it.+ //+ // Only the two fields a refresh writes are taken from the response: the record+ // it returns is a bare `presentProvider`, so replacing the whole entry would+ // drop the fields only the LIST endpoint adds (`executionModes`,+ // `prerequisitesMet`, the codex account) and un-group a unified card. Those+ // two fields fan out to every mode in the group server-side+ // (`sharedModeUpdates`), so they are applied to the siblings here too rather+ // than leaving them showing the pre-refresh catalog until the next poll.+ // `modelContextWindows` is copied even when absent — a refresh that pruned it+ // must not leave the stale map behind.const handleRefreshModels = async (id) => {setRefreshing(prev => ({ ...prev, [id]: true }));try {const result = await api.refreshProviderModels(id, { silent: true });if (result) {toast.success(`Models refreshed for ${result.name}`);- loadData();+ setProviders(current => {+ const refreshed = current.find(p => p.id === result.id);+ const group = new Set([result.id, ...(refreshed?.executionModes || []).map(mode => mode.id)]);+ return current.map(p => (group.has(p.id)+ ? { ...p, models: result.models, modelContextWindows: result.modelContextWindows }+ : p));+ });+ // The catalog a card just learned is graded by the readiness checklist,+ // which the server computes from the stored record.+ loadReadiness();} else {toast.error('Failed to refresh models - provider may not support this feature');}diff --git a/client/src/pages/AIProviders.test.jsx b/client/src/pages/AIProviders.test.jsxindex 77b171512e..8bc4a6901a 100644--- a/client/src/pages/AIProviders.test.jsx+++ b/client/src/pages/AIProviders.test.jsx@@ -20,6 +20,7 @@ const api = vi.hoisted(() => ({getSampleProviders: vi.fn(),createProvider: vi.fn(),updateProvider: vi.fn(),+ refreshProviderModels: vi.fn(),setActiveProvider: vi.fn().mockResolvedValue({}),getOrchestrationProfiles: vi.fn().mockResolvedValue({ profiles: [] }),createRun: vi.fn().mockResolvedValue({ runId: 'run-1' }),@@ -1867,3 +1868,98 @@ describe('AIProviders orchestration profiles', () => {});});});++// A refresh used to end in `loadData()`, which flips the page's `loading` flag+// back on — the whole list is replaced by the skeleton and the browser lands at+// the top, so the card the user clicked (often several screens down) scrolls out+// from under them. The card has to update in place instead.+describe('AIProviders model refresh', () => {+ const executionModes = [{ id: 'opencode-mtplx', type: 'cli' }, { id: 'opencode-mtplx-tui', type: 'tui' }];++ const mtplxProviders = () => ({+ activeProvider: null,+ providers: [+ {+ id: 'opencode-mtplx', name: 'OpenCode MTPLX', type: 'cli', command: 'opencode', enabled: true,+ models: ['mtplx-served'], canRefreshModels: true, executionModes,+ },+ {+ id: 'opencode-mtplx-tui', name: 'OpenCode MTPLX TUI', type: 'tui', command: 'opencode', enabled: true,+ models: ['mtplx-served'], canRefreshModels: true, executionModes,+ },+ ],+ });++ beforeEach(() => {+ vi.clearAllMocks();+ api.getApps.mockResolvedValue([]);+ api.getProviderStatuses.mockResolvedValue({ providers: {} });+ api.getProviderRuntimes.mockResolvedValue({ runtimes: {} });+ api.getProviderReadiness.mockResolvedValue({ readiness: {} });+ api.getCodexAccount.mockImplementation(() => new Promise(() => {}));+ api.getProviders.mockResolvedValue(mtplxProviders());+ localModels.value = { ctxById: {}, installed: { ollama: null, lmstudio: null } };+ });++ it('applies the refreshed catalog to the clicked card without reloading the page', async () => {+ api.refreshProviderModels.mockResolvedValue({+ id: 'opencode-mtplx', name: 'OpenCode MTPLX', type: 'cli', command: 'opencode', enabled: true,+ models: ['mtplx-served', 'wang-yang/Ornith-1.0-35B-MTPLX'], canRefreshModels: true,+ });++ renderPage();+ fireEvent.click(await screen.findByRole('button', { name: 'Refresh Models' }));++ await waitFor(() => expect(toast.success).toHaveBeenCalledWith('Models refreshed for OpenCode MTPLX'));+ expect(await screen.findByText(/Models: mtplx-served, wang-yang\/Ornith-1\.0-35B-MTPLX/)).toBeInTheDocument();+ // One load, from the initial mount — the refresh must not re-fetch the whole+ // page, which is what unmounted the list and reset the scroll position.+ expect(api.getProviders).toHaveBeenCalledTimes(1);+ // The unified card keeps its grouping: replacing the entry wholesale with+ // the bare record the refresh route returns would drop `executionModes` and+ // split one card into two.+ expect(screen.getAllByRole('button', { name: 'Refresh Models' })).toHaveLength(1);+ });++ it('keeps the stored catalog when the refresh is unsupported', async () => {+ api.refreshProviderModels.mockResolvedValue(null);++ renderPage();+ fireEvent.click(await screen.findByRole('button', { name: 'Refresh Models' }));++ await waitFor(() => expect(toast.error).toHaveBeenCalled());+ expect(screen.getByText(/Models: mtplx-served$/)).toBeInTheDocument();+ });++ // The root cause under the refresh button, which the other four reload paths+ // on this page share: `loadData` flipped `loading` on unconditionally, so ANY+ // reload after a click swapped the whole list for the page skeleton and+ // returned the user to the top. The skeleton belongs to the first load only.+ it('reloads after enabling a provider without swapping the list for the skeleton', async () => {+ api.updateProvider.mockResolvedValue({});+ // The reload is held OPEN so the assertions run while it is in flight — that+ // window is the whole bug, and after it resolves the skeleton is gone again+ // whether or not it ever appeared.+ let releaseReload;+ api.getProviders+ .mockResolvedValueOnce(mtplxProviders())+ .mockImplementationOnce(() => new Promise((resolve) => { releaseReload = resolve; }));++ renderPage();+ // The first load DOES show the skeleton — there is nothing else to show, and+ // this is what keeps the assertion below from passing vacuously.+ expect(screen.getByLabelText('Loading providers')).toBeInTheDocument();+ fireEvent.click(await screen.findByRole('button', { name: 'Disable' }));++ await waitFor(() => expect(api.getProviders).toHaveBeenCalledTimes(2));+ expect(screen.queryByLabelText('Loading providers')).toBeNull();+ // ...and the card the user just clicked is still the thing on screen.+ expect(screen.getByRole('heading', { name: 'OpenCode MTPLX' })).toBeInTheDocument();++ releaseReload({+ ...mtplxProviders(),+ providers: mtplxProviders().providers.map(p => ({ ...p, enabled: false })),+ });+ expect(await screen.findByRole('button', { name: 'Enable' })).toBeInTheDocument();+ });+});diff --git a/server/lib/README.md b/server/lib/README.mdindex 4b18477c57..db81bf64be 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -207,7 +207,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) and `pickMtplxCachedModel(models)` → the 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` | `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/lib/aiToolkit/index.js b/server/lib/aiToolkit/index.jsindex 29332d62f1..f2f4511760 100644--- a/server/lib/aiToolkit/index.js+++ b/server/lib/aiToolkit/index.js@@ -63,14 +63,19 @@ export function createAIToolkit(config = {}) {// Host persistence hook fired after every providers.json write — see// createProviderService(). PortOS keeps its provider connection graph// reconciled through it; unset standalone.- onProvidersSaved = null+ onProvidersSaved = null,+ // Host probe for the checkpoints a one-model-per-process local runtime has+ // cached but is not serving — see createProviderService(). Unset+ // standalone, so a refresh reports only what the endpoint answers with.+ cachedModelIds = null} = config;const providerService = createProviderService({dataDir,providersFile,sampleFile: sampleProvidersFile,- onProvidersSaved+ onProvidersSaved,+ cachedModelIds});let providerStatusService = null;diff --git a/server/lib/aiToolkit/providers.js b/server/lib/aiToolkit/providers.jsindex 9720ec26d2..bb97765bed 100644--- a/server/lib/aiToolkit/providers.js+++ b/server/lib/aiToolkit/providers.js@@ -466,7 +466,16 @@ export function createProviderService(config = {}) {// its machine-local provider connection graph (#6367) reconciled with a// file any old client, migration or downgraded release may also write.// Unset standalone, so the toolkit behaves exactly as before.- onProvidersSaved = null+ onProvidersSaved = null,+ // Host hook: the model ids a LOCAL one-checkpoint-per-process runtime has+ // on disk but is not currently serving. `(provider) => Promise<string[]|null>`,+ // where `null` means "not that kind of provider, or the cache could not be+ // read" — deliberately distinct from `[]` ("read, and nothing is cached"),+ // which must not resurrect a stale list. Injected rather than imported+ // because reading a cache means host I/O and this directory stays+ // self-contained (see AGENTS.md); PortOS supplies MTPLX's `mtplx models+ // --json` listing from `services/mtplxServerManager.js`.+ cachedModelIds = null} = config;const PROVIDERS_PATH = join(dataDir, providersFile);@@ -978,24 +987,35 @@ export function createProviderService(config = {}) {// `else if` chain this used to be — see internal/modelFetchers.js.const tuiFetcher = provider.type === 'tui' ? resolveModelFetcher(provider) : null;- if (provider.type === 'api') {- fetched = await this._refreshAPIProviderModels(provider);- } else if (provider.type === 'cli') {- fetched = await this._refreshCLIProviderModels(provider);- } else if (tuiFetcher) {- fetched = await this[tuiFetcher.fetch](provider);- } else {+ const probe = provider.type === 'api'+ ? () => this._refreshAPIProviderModels(provider)+ : provider.type === 'cli'+ ? () => this._refreshCLIProviderModels(provider)+ : tuiFetcher+ ? () => this[tuiFetcher.fetch](provider)+ : null;++ if (!probe) {// No branch matched — this provider type/shape has no fetcher. Say so,// the same 400 the CLI arm's own fall-through throws. Previously this// fell out as `fetched === null` and the route rendered it as// `404 Provider not found or not an API type`, which is exactly the// false message the rethrow above set out to stop showing: a plain// `codex-tui`/`grok-tui` provider exists and its type is fine, it just- // has no catalog to fetch.+ // has no catalog to fetch. Thrown OUT here rather than from inside the+ // wrapper below, which is allowed to answer over a failed probe — a+ // provider with no fetcher at all must still 400.const unsupported = new Error(`Model refresh not supported for ${provider.type} provider '${provider.id}'`);unsupported.status = 400;throw unsupported;}++ // ONE wrapper over every arm rather than a per-vendor call: which+ // providers have cached-but-unserved models is the host's question, not+ // this dispatch's, and the shipped MTPLX records alone span two arms (an+ // unmarked `api` record plus the `mtplxBacked` OpenCode wrappers the+ // fetcher table routes). The hook answers `null` for everything else.+ fetched = await this._withCachedCheckpoints(provider, probe);} catch (error) {console.error(`Failed to refresh models for ${provider.name}:`, error.message);// RETHROW rather than collapsing to null. `null` means one specific@@ -1268,16 +1288,83 @@ export function createProviderService(config = {}) {* guarded generic parser instead of executing an OpenCode model-list command* (which would inventory the harness, not the MTPLX runtime).*+ * That endpoint answers with a single id no matter how many checkpoints are+ * cached; `fetchProviderModelCatalog` merges the rest in around every arm+ * (see `_withCachedCheckpoints`), so this stays the plain probe its siblings+ * below are.+ ** This only runs from an explicit refresh request; seeding the disabled* provider never starts MTPLX, downloads a model, or issues an LLM call.** @param {object} provider- * @returns {Promise<string[]>}+ * @returns {Promise<{models: string[], contextWindows: Record<string, number>}>}*/async _fetchMtplxModels(provider) {return this._refreshAPIProviderModels(provider);},+ /**+ * Add the checkpoints a one-model-per-process local runtime has ON DISK to+ * whatever its server is answering with right now.+ *+ * MTPLX and Slotstream load a single checkpoint and report only that one+ * through `/v1/models` — so a refresh after pulling a second checkpoint+ * returned the same lone id it returned before, and the newly downloaded+ * weights were unreachable from the provider's model list. The cache is the+ * honest catalog of what the machine can serve;+ * `providerReadiness.catalogCheck` already grades `servesOneModel` runtimes+ * leniently for exactly this reason (one servable id is all such a provider+ * needs), and the pinned-model check still flags a provider aimed at a+ * checkpoint the daemon has not loaded.+ *+ * The served probe comes FIRST in the merged list: it is the one id that is+ * live right now, so it stays the natural default. Its context windows are+ * kept as-is — a cached-but-unloaded checkpoint declares none, and guessing+ * one would be worse than the caller's own fallback.+ *+ * A failed probe is survivable here and only here: when the cache lists+ * something servable, a stopped daemon still has a real catalog to report,+ * so the refresh succeeds instead of failing with `HTTP error`. With nothing+ * cached the probe's error is rethrown unchanged, preserving the+ * throw-don't-degrade posture `_refreshAPIProviderModels` documents.+ *+ * @param {object} provider+ * @param {() => Promise<unknown>} probeServed+ */+ async _withCachedCheckpoints(provider, probeServed) {+ // Both probes start before either is awaited: they are independent, and on+ // the MTPLX path one is a subprocess while the other is an HTTP request to+ // a daemon that may be down — sequentially that is the subprocess PLUS a+ // connect timeout on every refresh click, rather than the longer of the two.+ //+ // `Promise.resolve().then` around the host call, not just `.catch` after+ // it: a probe that throws SYNCHRONOUSLY would otherwise unwind past the+ // handler and fail a refresh the endpoint could have answered on its own.+ const [cached, probed] = await Promise.all([+ typeof cachedModelIds === 'function'+ ? Promise.resolve().then(() => cachedModelIds(provider)).catch(() => null)+ : null,+ probeServed().then((result) => ({ result }), (error) => ({ error })),+ ]);+ if (!Array.isArray(cached) || cached.length === 0) {+ if (probed.error) throw probed.error;+ return probed.result;+ }+ const catalog = toModelCatalog(probed.result) || { models: [], contextWindows: {} };+ // A failed probe means the daemon is not answering — NOT that its+ // launch-line id stopped existing. That id is in a different namespace+ // from the cache (MTPLX answers as a slug its launch line minted, its+ // cache yields HF repo ids) and is typically the record's own+ // `defaultModel`, so dropping it would prune the pin off a provider merely+ // because its server was stopped. A SUCCESSFUL probe stays authoritative,+ // so a genuinely delisted model still disappears.+ const stale = probed.error && Array.isArray(provider?.models) ? provider.models : [];+ return {+ models: [...new Set([...catalog.models, ...stale, ...cached])],+ contextWindows: catalog.contextWindows,+ };+ },+/*** Fetch the downloaded catalog from the local LM Studio server for its* harness wrappers. Refresh-only, like every other local fetcher here: itdiff --git a/server/lib/aiToolkit/providers.test.js b/server/lib/aiToolkit/providers.test.jsindex 66a156dd53..182ee89e3f 100644--- a/server/lib/aiToolkit/providers.test.js+++ b/server/lib/aiToolkit/providers.test.js@@ -1570,6 +1570,127 @@ rl.on('line', (line) => {expect(url).toBe('http://127.0.0.1:8000/v1/models');}});++ /**+ * The cached-checkpoint half of that refresh.+ *+ * MTPLX loads ONE checkpoint per process and reports only that one, under+ * the slug its launch line minted — so clicking "Refresh Models" after+ * pulling a second checkpoint kept answering with the same lone id, and the+ * new weights were unreachable from the provider's model list. The host+ * injects the on-disk listing (`services/mtplxServerManager.js`); this+ * directory stays self-contained.+ *+ * Driven through `refreshProviderModels` — the boundary the route calls —+ * so the PERSISTED record is what proves the behavior.+ */+ describe('cached checkpoints the daemon is not serving', () => {+ const SERVED = 'mtplx-qwen38-27b-optimized-speed';+ const CACHED = 'wang-yang/Ornith-1.0-35B-MTPLX';+ const MTPLX_ENDPOINT = 'http://127.0.0.1:8000/v1';++ let cachedModelIds;+ let hostedService;++ /** The listing a running MTPLX answers with. */+ const servesModels = (ids) => vi.stubGlobal('fetch', vi.fn().mockResolvedValue({+ ok: true,+ status: 200,+ json: async () => ({ data: ids.map((id) => ({ id, context_length: 262144 })) }),+ }));++ const seedProvider = (shape = {}) => hostedService.createProvider({+ name: 'MTPLX provider',+ type: 'cli',+ command: 'opencode',+ mtplxBacked: true,+ endpoint: MTPLX_ENDPOINT,+ models: [SERVED],+ ...shape,+ });++ beforeEach(() => {+ // Keyed on the endpoint, the way the real host predicate is: every+ // provider that is not MTPLX's gets `null` and an untouched probe.+ cachedModelIds = vi.fn(async (provider) => (+ provider.endpoint === MTPLX_ENDPOINT ? [SERVED, CACHED] : null+ ));+ hostedService = createProviderService({+ dataDir: TEST_DATA_DIR,+ providersFile: 'providers.json',+ cachedModelIds,+ });+ });++ // Two rows, because there are two dispatch arms: the `mtplxBacked` fetcher+ // (which the test above already pins BOTH OpenCode modes reach) and the+ // generic `api` branch, which the marker never reaches.+ it.each([+ ['an OpenCode wrapper', { type: 'cli', command: 'opencode', mtplxBacked: true }],+ ['the unmarked API record', { type: 'api' }],+ ])('adds them to what %s is serving', async (_label, shape) => {+ servesModels([SERVED]);+ const provider = await seedProvider(shape);+ const updated = await hostedService.refreshProviderModels(provider.id);+ // Served first — it is the one id live right now, so it stays the+ // natural default — then what the daemon has on disk but has not loaded.+ expect(updated.models).toEqual([SERVED, CACHED]);+ // Only the served entry declares a window; guessing one for an unloaded+ // checkpoint would be worse than the caller's own fallback.+ expect(updated.modelContextWindows).toEqual({ [SERVED]: 262144 });+ });++ // The served id and the cached ids are DIFFERENT namespaces — MTPLX+ // answers as a slug its launch line minted, its cache yields HF repo ids —+ // and the slug is the shipped record's `defaultModel`. A stopped daemon+ // must not cost the provider its pin, so a FAILED probe keeps what the+ // record already listed. (A successful one stays authoritative: the+ // delisting cases above still prune.)+ it('reports the cache when the daemon is stopped, keeping the pin it can no longer probe', async () => {+ const provider = await seedProvider({ defaultModel: SERVED });+ vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('ECONNREFUSED')));+ const updated = await hostedService.refreshProviderModels(provider.id);+ expect(updated.models).toEqual([SERVED, CACHED]);+ expect(updated.models).toContain(updated.defaultModel);+ });++ // The mirror of the case above: when the endpoint DOES answer, its list is+ // the truth, so an id it dropped leaves the record.+ it('drops a delisted model when the daemon answers', async () => {+ const provider = await seedProvider({ models: [SERVED, 'retired-checkpoint'] });+ servesModels([SERVED]);+ const updated = await hostedService.refreshProviderModels(provider.id);+ expect(updated.models).toEqual([SERVED, CACHED]);+ });++ it('rethrows the probe failure when nothing is cached', async () => {+ // The throw-don't-degrade posture `_refreshAPIProviderModels` documents:+ // with no cache to fall back on, an unreachable endpoint must not+ // persist a plausible-looking list over the one already stored.+ const provider = await seedProvider({});+ cachedModelIds.mockResolvedValue([]);+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: false, status: 503 }));+ await expect(hostedService.refreshProviderModels(provider.id)).rejects.toThrow(/503/);+ expect((await hostedService.getProviderById(provider.id)).models).toEqual([SERVED]);+ });++ it('leaves a provider the host does not claim exactly as the endpoint answered', async () => {+ servesModels(['gpt-example']);+ const provider = await hostedService.createProvider({+ name: 'Other API', type: 'api', endpoint: 'https://api.example.com/v1', models: [],+ });+ expect((await hostedService.refreshProviderModels(provider.id)).models).toEqual(['gpt-example']);+ });++ it('survives a throwing probe rather than failing the refresh', async () => {+ // `mtplx models` runs a subprocess, so it can time out — a refresh that+ // still has the endpoint's answer should report it.+ servesModels([SERVED]);+ const provider = await seedProvider({});+ cachedModelIds.mockRejectedValue(new Error('`mtplx models` timed out'));+ expect((await hostedService.refreshProviderModels(provider.id)).models).toEqual([SERVED]);+ });+ });});describe('OrcaRouter model refresh and sibling-key resolution', () => {diff --git a/server/lib/mtplxModels.js b/server/lib/mtplxModels.jsindex 067eb9eff8..7e416e5308 100644--- a/server/lib/mtplxModels.js+++ b/server/lib/mtplxModels.js@@ -74,24 +74,42 @@ export async function listMtplxCachedModels({ command = 'mtplx' } = {}) {return { models: parsed.models, error: null };}+/**+ * The cache rows MTPLX itself calls complete, in listing order.+ *+ * `validation.ok` is false for a directory missing required files or an MTP+ * sidecar, which is what an interrupted `mtplx pull` leaves behind. That rule+ * decides both what PortOS may START a server on and what it may OFFER as a+ * selectable model, so it lives here once rather than being spelled at each —+ * the shape it reads is upstream's `models --json`, and a second copy would go+ * stale the first time that payload grows a new incompleteness marker.+ *+ * `[]` for a non-array input: callers that must distinguish "could not read the+ * cache" check `listMtplxCachedModels`' own `models: null` before calling.+ *+ * @param {object[]|null|undefined} models - rows from `listMtplxCachedModels`+ * @returns {object[]}+ */+export function servableMtplxCachedModels(models) {+ if (!Array.isArray(models)) return [];+ return models.filter((row) => typeof row?.repo_id === 'string' && row.repo_id !== '' && row?.validation?.ok !== false);+}+/*** The cached repo id PortOS should hand `mtplx serve --model`, or null when the* cache holds nothing servable.*- * Only entries MTPLX itself calls complete are eligible: `validation.ok` is- * false for a directory missing required files or an MTP sidecar, which is what- * an interrupted `mtplx pull` leaves behind — starting the server on one of- * those trades an honest "nothing is cached" for a load failure minutes later.- * Among complete entries, one carrying `mtplx_runtime.json` wins: that is the- * recorded exactness contract, and the runtime warns on stats from artifacts- * without it.+ * Only entries MTPLX itself calls complete are eligible (see+ * `servableMtplxCachedModels`) — starting the server on a partial pack trades an+ * honest "nothing is cached" for a load failure minutes later. Among complete+ * entries, one carrying `mtplx_runtime.json` wins: that is the recorded+ * exactness contract, and the runtime warns on stats from artifacts without it.** @param {object[]|null|undefined} models - rows from `listMtplxCachedModels`* @returns {string|null}*/export function pickMtplxCachedModel(models) {- if (!Array.isArray(models)) return null;- const usable = models.filter((row) => typeof row?.repo_id === 'string' && row.repo_id !== '' && row?.validation?.ok !== false);+ const usable = servableMtplxCachedModels(models);const verified = usable.find((row) => row.has_runtime_contract === true);return (verified || usable[0])?.repo_id ?? null;}diff --git a/server/services/bootstrap.js b/server/services/bootstrap.jsindex d0614b8031..cd06e871fd 100644--- a/server/services/bootstrap.js+++ b/server/services/bootstrap.js@@ -151,6 +151,7 @@ import { outcomesStore as liOutcomesStore } from './layeredIntelligenceOutcomes.import * as gameStore from './games/store.js';import * as fableLoomStore from './fableLoom/store.js';import { prerequisitesMetForRouting } from './providerPrerequisites.js';+import { localCachedModelIds } from './localCachedModels.js';import { stopCodexAppServer } from './codexAppServer.js';/**@@ -263,7 +264,15 @@ export const bootstrapServices = async ({ io, dataDir, dataReferenceDir, serverD// this host (#4611), so a run falls through to the next candidate instead// of dying at spawn time. Sync by contract: it reads the runtime probe's// cache and never blocks.- prerequisitesMet: prerequisitesMetForRouting+ prerequisitesMet: prerequisitesMetForRouting,+ // MTPLX and Slotstream each serve one checkpoint per process and report+ // only that one, so a refresh could never surface a newly downloaded+ // 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+ // reaches the boot closure (see `services/localCachedModels.js`).+ cachedModelIds: localCachedModelIds}),// Compatibility shims for services that import from the old service files.diff --git a/server/services/localCachedModels.js b/server/services/localCachedModels.jsnew file mode 100644index 0000000000..306208ac7f--- /dev/null+++ b/server/services/localCachedModels.js@@ -0,0 +1,80 @@+/**+ * What a local one-model-per-process runtime has on disk but is not serving.+ *+ * This is the `cachedModelIds` hook `lib/aiToolkit` calls on every model refresh+ * (wired in `services/bootstrap.js`). The toolkit stays self-contained — it+ * cannot read a cache directory or spawn a listing — so the answer is injected+ * from here.+ *+ * ## Why the hook exists+ *+ * MTPLX and Slotstream each load ONE checkpoint per process and report only that+ * one through their OpenAI-compatible `/v1/models`. A refresh probes that+ * endpoint, so it answered with the same lone id no matter how many checkpoints+ * the machine held: a checkpoint the user had just downloaded never appeared in+ * the provider's model list. Worse for Slotstream, whose shipped record lists+ * three ids — the refresh PRUNED the other two, `defaultModel` included.+ *+ * The cache is the honest catalog of what this machine can serve, and+ * `services/providerReadiness.js`'s `catalogCheck` already grades+ * `servesOneModel` runtimes leniently for exactly this reason (one servable id+ * is all such a provider needs), while its pinned-model check still flags a+ * provider aimed at a checkpoint the daemon has not loaded.+ *+ * ## Why only these two runtimes+ *+ * `servesOneModel` is not the qualifying property — having a PortOS-readable+ * cache in the SAME id namespace as the served id is. llama.cpp's served id is+ * an `--alias` label over a GGUF path, so its cached files are not candidate+ * model ids at all (the readiness checklist's serve-model button exists for+ * that mismatch instead); vLLM and SGLang bake the served id into an+ * operator-owned compose project with no PortOS-side cache to list.+ *+ * ## 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.+ */++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).+ */+const CACHED_MODEL_PROBES = {+ mtplx: () => import('./mtplxServerManager.js').then((m) => m.mtplxCachedModelIds),+ slotstream: () => import('./slotstreamServerManager.js').then((m) => m.slotstreamCachedModelIds),+};++/**+ * The cached-but-unserved model ids for `provider`, or `null`.+ *+ * `null` means "no cached catalog to add" — a provider of another runtime, or a+ * cache that could not be READ. It is deliberately distinct from `[]` ("read,+ * and genuinely empty"): the toolkit leaves the endpoint probe's own answer+ * untouched for `null` and for `[]` alike, but the distinction is the same one+ * `listMtplxCachedModels` draws and must not collapse here.+ *+ * 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.+ *+ * `provider.id` backs up `localRuntimeKind` because the shipped `mtplx` record+ * is a plain OpenAI-compatible endpoint carrying no vendor marker for+ * `localRuntimeKind` to read. Each probe re-checks identity itself, so a key+ * match is routing, not a verdict.+ *+ * @param {{id?: string, type?: string, endpoint?: string}|null|undefined} provider+ * @returns {Promise<string[]|null>}+ */+export async function localCachedModelIds(provider) {+ if (!isLocalInstanceEndpoint(provider?.endpoint)) return null;+ const load = CACHED_MODEL_PROBES[localRuntimeKind(provider) || provider?.id];+ if (!load) return null;+ const probe = await load();+ return probe(provider);+}diff --git a/server/services/localCachedModels.test.js b/server/services/localCachedModels.test.jsnew file mode 100644index 0000000000..b11f87f9f9--- /dev/null+++ b/server/services/localCachedModels.test.js@@ -0,0 +1,91 @@+/**+ * 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.+ */++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(() => []);++vi.mock('./mtplxServerManager.js', () => {+ loaded.push('mtplx');+ return { mtplxCachedModelIds: mtplxProbe };+});+vi.mock('./slotstreamServerManager.js', () => {+ loaded.push('slotstream');+ return { slotstreamCachedModelIds: slotstreamProbe };+});++import { localCachedModelIds } from './localCachedModels.js';++beforeEach(() => {+ loaded.length = 0;+ mtplxProbe.mockResolvedValue(['Vendor/Example-MTPLX']);+ slotstreamProbe.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 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();+ });++ 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();+ });++ // 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('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();+ });+});diff --git a/server/services/mtplxServerManager.js b/server/services/mtplxServerManager.jsindex 67bcdb1215..0edcec3d05 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 } from '../lib/mtplxModels.js';+import { listMtplxCachedModels, pickMtplxCachedModel, servableMtplxCachedModels } 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';@@ -1005,6 +1005,57 @@ 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;+ // Two signals, because the shipped records carry two (#6466 collapses these+ // into `localRuntimeKind`): `localRuntimeKind` reads+ // the `mtplxBacked` marker on the OpenCode CLI/TUI wrappers, and `id` names the+ // API record — a plain OpenAI-compatible endpoint with no marker to read, the+ // same shortcut `hardwareRequirementsForProvider` takes for it. A bare `:8000`+ // is deliberately NOT a third: that port is generic, and this must not offer+ // MTPLX's checkpoints as the catalog of someone else's local API.+ const ours = localRuntimeKind(provider) === 'mtplx' || provider?.id === 'mtplx';+ if (!ours) 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 2a34592773..b28ed91103 100644--- a/server/services/mtplxServerManager.test.js+++ b/server/services/mtplxServerManager.test.js@@ -12,6 +12,7 @@ import {ensureMtplxRunning,ensureMtplxProviderReady,isMtplxProvider,+ mtplxCachedModelIds,MTPLX_APP,} from './mtplxServerManager.js';import * as processEnv from '../lib/processEnv.js';@@ -24,6 +25,25 @@ import * as streamingSpawn from '../lib/streamingSpawn.js';const BINARY = '/opt/homebrew/bin/mtplx';const cachedModel = (repoId, extra = {}) => ({ repo_id: repoId, validation: { ok: true }, ...extra });++/**+ * A Homebrew `mtplx` shim on disk: the few-line wrapper that lazily bootstraps a+ * version-keyed Python venv. `describeMtplxRuntime` reads its `VENV=` line and+ * tests the venv for executability rather than running it, so writing a real one+ * is how a suite exercises the un-bootstrapped runtime without a download.+ */+const writeMtplxWrapper = async (dir, venv) => {+ const path = join(dir, 'mtplx');+ await writeFile(path, [+ '#!/bin/bash',+ `VENV="\${MTPLX_BREW_VENV:-${venv}}"`,+ 'if [ ! -x "$VENV/bin/mtplx" ]; then echo "MTPLX runtime is not installed. Bootstrapping with pip..."; fi',+ 'exec "$VENV/bin/mtplx" "$@"',+ '',+ ].join('\n'));+ await chmod(path, 0o755);+ return path;+};const FAST_TIMING = {startupWait: 50,startupPoll: 0,@@ -682,15 +702,7 @@ describe('mtplxServerManager', () => {let runtimeDir = null;const wrapperOnPath = async (venv) => {- const path = join(runtimeDir, 'mtplx');- await writeFile(path, [- '#!/bin/bash',- `VENV="\${MTPLX_BREW_VENV:-${venv}}"`,- 'if [ ! -x "$VENV/bin/mtplx" ]; then echo "MTPLX runtime is not installed. Bootstrapping with pip..."; fi',- 'exec "$VENV/bin/mtplx" "$@"',- '',- ].join('\n'));- await chmod(path, 0o755);+ const path = await writeMtplxWrapper(runtimeDir, venv);vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue(path);return path;};@@ -955,6 +967,80 @@ describe('mtplxServerManager', () => {});});+ /**+ * The catalog an MTPLX provider's "Refresh Models" merges in. MTPLX serves ONE+ * 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();+ });+ });+describe('ensureMtplxProviderReady', () => {it('passes through a provider that is not MTPLX without touching PM2', async () => {const result = await ensureMtplxProviderReady({ type: 'api', endpoint: 'https://api.example.com/v1', id: 'remote' });diff --git a/server/services/slotstreamServerManager.js b/server/services/slotstreamServerManager.jsindex 30fd2cd76e..aa2f983746 100644--- a/server/services/slotstreamServerManager.js+++ b/server/services/slotstreamServerManager.js@@ -540,6 +540,32 @@ export function isSlotstreamProvider(provider) {return Boolean(managedPort) && Number(localEndpointPort(provider.endpoint)) === managedPort;}+/**+ * The checkpoints THIS machine can serve, for a Slotstream provider's model+ * refresh — the Slotstream half of `services/localCachedModels.js`.+ *+ * Same shape of bug as MTPLX, and worse in one way: `slotstream serve` loads one+ * checkpoint and answers only under that id, while the shipped `slotstream`+ * record lists THREE. So a refresh did not merely fail to add a newly downloaded+ * checkpoint — it pruned the record's other two shipped ids down to whatever the+ * daemon happened to have loaded, including the `defaultModel` pin whenever that+ * was not the loaded one.+ *+ * `null` for a provider that is not this daemon's and for a cache that could not+ * be READ — deliberately not `[]`, which the caller must be free to read as+ * "read, and genuinely empty". Unlike MTPLX this costs no subprocess and needs+ * no runtime gate: the listing is a directory read (`lib/slotstreamModels.js`).+ *+ * @param {{type?: string, endpoint?: string}|null} provider+ * @returns {Promise<string[]|null>}+ */+export async function slotstreamCachedModelIds(provider) {+ if (!isSlotstreamProvider(provider)) return null;+ const { models } = await listSlotstreamCachedModels();+ if (!Array.isArray(models)) return null;+ return models.map((row) => row?.id).filter((id) => typeof id === 'string' && id !== '');+}+export async function ensureSlotstreamProviderReady(provider) {if (!isSlotstreamProvider(provider)) return { success: true };const { ready, reason } = await ensureSlotstreamRunning();diff --git a/server/services/slotstreamServerManager.test.js b/server/services/slotstreamServerManager.test.jsindex 32906cbfd1..c18efb3d2e 100644--- a/server/services/slotstreamServerManager.test.js+++ b/server/services/slotstreamServerManager.test.js@@ -24,6 +24,7 @@ import {_resetSlotstreamServerStateForTests,ensureSlotstreamRunning,isSlotstreamProvider,+ slotstreamCachedModelIds,SLOTSTREAM_APP,} from './slotstreamServerManager.js';import * as processEnv from '../lib/processEnv.js';@@ -309,4 +310,34 @@ describe('slotstreamServerManager', () => {})).toBe(false);});});++ /**+ * The catalog a Slotstream provider's "Refresh Models" merges in. The daemon+ * serves ONE checkpoint and answers only under that id, while the shipped+ * record lists three — so before this, a refresh pruned the other two shipped+ * ids (and the `defaultModel` pin whenever it was not the loaded one) down to+ * whatever happened to be loaded.+ */+ describe('slotstreamCachedModelIds', () => {+ const local = { type: 'api', id: 'slotstream', endpoint: `http://127.0.0.1:${PORTS.SLOTSTREAM}/v1` };++ it('lists every cached checkpoint, not just the loaded one', async () => {+ vi.spyOn(slotstreamModels, 'listSlotstreamCachedModels').mockResolvedValue({+ models: [cachedModel('qwen-moe'), cachedModel('gpt-oss-120b-mxfp4')],+ error: null,+ });+ expect(await slotstreamCachedModelIds(local)).toEqual(['qwen-moe', 'gpt-oss-120b-mxfp4']);+ });++ it('answers null for a provider that is not this daemon’s', async () => {+ expect(await slotstreamCachedModelIds({ ...local, endpoint: `http://192.0.2.10:${PORTS.SLOTSTREAM}/v1` })).toBeNull();+ });++ // `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(slotstreamModels, 'listSlotstreamCachedModels').mockResolvedValue({ models: null, error: 'EACCES' });+ expect(await slotstreamCachedModelIds(local)).toBeNull();+ });+ });});