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
flag a retired model pin inline at every model picker (#7327)
[._.]/ Adam Eivyae128aa7b392
diff --git a/client/src/components/cos/TaskAddForm.jsx b/client/src/components/cos/TaskAddForm.jsxindex d9cff06b2c..47b8145802 100644--- a/client/src/components/cos/TaskAddForm.jsx+++ b/client/src/components/cos/TaskAddForm.jsx@@ -441,6 +441,14 @@ export default function TaskAddForm({ providers, providersLoaded = true, apps, o});}, [soleAvailableModel, selectedProvider]);const NO_ACCOUNT_MODELS_NOTE = 'Your signed-in ChatGPT account exposes no models.';+ // The flag fires from two different lists, so the suffix has to name the right+ // one: an account catalog that dropped the model, or the provider's own+ // catalog retiring it (#7327). Both keep the option SELECTABLE — the point is+ // to tell the user the pin is dead, here where they can change it, not to+ // silently swap their model.+ const unlistedNote = modelSource === MODEL_SOURCE.shipped+ ? 'no longer offered by this provider'+ : 'not in account catalog';const modelSourceNote = (() => {if (!isCodexSubscriptionProvider(selectedProvider)) return '';if (modelSource === MODEL_SOURCE.account) return 'Models your signed-in ChatGPT account can run.';@@ -1149,7 +1157,7 @@ export default function TaskAddForm({ providers, providersLoaded = true, apps, o{availableModels.map(m => (<option key={m} value={m}>{unlistedSelection && m === newTask.model- ? `${m} (not in account catalog)`+ ? `${m} (${unlistedNote})`: m.replace('claude-', '').replace(/-\d+$/, '')}</option>))}diff --git a/client/src/utils/providerModels.js b/client/src/utils/providerModels.jsindex dd03509fbf..22556ab877 100644--- a/client/src/utils/providerModels.js+++ b/client/src/utils/providerModels.js@@ -11,6 +11,10 @@* the pure leaf `server/lib/providerModels.js`; `effortLevelsForProvider` /* `resolveCliEffort` delegate to the server's and add the one rung the browser* needs — the ladder the server publishes on a sanitized provider inventory.+ * Whether a stored pin is still SERVED is likewise the server's own+ * `modelPinIsOffered` (`server/lib/modelPinMembership.js`), not a second rule:+ * a picker that flagged a pin the spawner would happily run — or stayed silent+ * on one it would reject — is worse than not flagging at all.* The generation-control tables still mirror `server/lib/opencodeConfig.js` /* `server/lib/aiToolkit/internal/generationOptions.js`. Helpers marked* CLIENT-ONLY are rendering concerns with no server twin.@@ -28,6 +32,10 @@ import {isConfiguredDefaultModel,splitAntigravityModel,} from '../../../server/lib/providerModels.js';+// THE model-pin membership rule, shared with the spawner and the retired-pin+// audit. Taken from the browser-safe leaf, not `localProviderRuntime.js`, whose+// endpoint half reaches `opencodeConfig.js` → `zod` (not a client dependency).+import { modelPinIsOffered } from '../../../server/lib/modelPinMembership.js';export {CODEX_CONFIGURED_DEFAULT,@@ -186,9 +194,26 @@ export const MODEL_SOURCE = Object.freeze({* Every other state (never fetched, failed read, non-Codex provider) falls back* to the shipped list unchanged.*- * ADDITIVE: a stored `selectedModel` the catalog no longer lists is retained as- * its own option and reported via `unlistedSelection`, so an existing task- * template renders what it actually holds instead of silently changing model.+ * ADDITIVE in BOTH branches: a stored `selectedModel` the list no longer offers+ * is retained as its own option and reported via `unlistedSelection`, so an+ * existing task template renders what it actually holds instead of silently+ * changing model — and the picker can say so.+ *+ * The shipped branch asks `modelPinIsOffered` (server/lib/modelPinMembership.js),+ * the SAME rule the spawner and the retired-pin audit use, rather than a bare+ * `includes`. That rule is what makes the flag honest here instead of noisy:+ * it passes a configured-default sentinel, an empty catalog, and a+ * local-daemon provider (whose `models` is a cached snapshot while the daemon+ * is the authority) — and it tolerates the two same-model-spelled-differently+ * forms, so a legacy agy `-high` pin whose BASE is still listed reads as+ * offered and only a genuinely retired one is flagged. Until #7327 this branch+ * hardcoded `false`, so the flag only ever fired for a Codex account catalog+ * and every OTHER picker rendered a rotted pin as a perfectly normal option.+ *+ * The ACCOUNT branch deliberately keeps its own bare membership test: a+ * successfully-read EMPTY account catalog means the account really exposes no+ * models, so a pin there IS unavailable — while `modelPinIsOffered` reads an+ * empty catalog as "nothing to validate against" and would pass it.** CLIENT-ONLY (no server mirror).* @param {{id?:string, command?:string, models?:unknown[]}|null|undefined} provider@@ -202,7 +227,18 @@ export const resolveProviderModelOptions = (provider, selectedModel) => {selectedModel,);const catalog = codexCatalogModelIds(provider);- if (!catalog) return { models: shipped, source: MODEL_SOURCE.shipped, unlistedSelection: false };+ if (!catalog) {+ // `withStaleAntigravityPin` may already have kept the pin selectable; this+ // appends the cases it deliberately does not cover (a bare retired id on+ // any provider). Selectable and flagged are complementary — never let one+ // drop the other.+ const unlisted = !!selectedModel && !modelPinIsOffered(provider, selectedModel);+ return {+ models: unlisted && !shipped.includes(selectedModel) ? [...shipped, selectedModel] : shipped,+ source: MODEL_SOURCE.shipped,+ unlistedSelection: unlisted,+ };+ }const models = filterSelectableModels(catalog);const unlistedSelection = !!selectedModel&& !isConfiguredDefaultModel(selectedModel)diff --git a/client/src/utils/providers.test.js b/client/src/utils/providers.test.jsindex fc311bfab6..b20229282c 100644--- a/client/src/utils/providers.test.js+++ b/client/src/utils/providers.test.js@@ -435,6 +435,55 @@ describe('Antigravity base-model split', () => {expect(result.unlistedSelection).toBe(true);});+ // #7327 — the shipped branch used to hardcode `unlistedSelection: false`, so+ // the flag fired ONLY for a Codex account catalog and every other picker+ // (Media Gen, CoS schedule, per-app overrides) rendered a rotted pin as a+ // perfectly normal option. It now asks the same `modelPinIsOffered` rule the+ // spawner and the retired-pin audit use.+ describe('shipped catalog (#7327)', () => {+ const agy = (models) => ({ id: 'antigravity-cli', command: 'agy', models });+ const AGY_CATALOG = ['gemini-3.6-flash-low', 'gemini-3.6-flash-high', 'claude-sonnet-4-6'];++ it('flags a retired pin AND keeps it selectable', () => {+ const result = resolveProviderModelOptions(agy(AGY_CATALOG), 'gemini-3.5-flash');+ expect(result.unlistedSelection).toBe(true);+ // Selectable and flagged are complementary — a picker that hid the pin+ // would render blank and read as "no model".+ expect(result.models).toContain('gemini-3.5-flash');+ expect(result.source).toBe(MODEL_SOURCE.shipped);+ });++ it('does not flag a legacy agy pin whose BASE is still listed', () => {+ // `withStaleAntigravityPin` already keeps this selectable; the server+ // splits it into base + `--effort` and runs it, so flagging it would be+ // a false "your pin is gone".+ const result = resolveProviderModelOptions(agy(AGY_CATALOG), 'gemini-3.6-flash-high');+ expect(result.unlistedSelection).toBe(false);+ expect(result.models).toContain('gemini-3.6-flash-high');+ });++ it('never flags a local-daemon pin, whose catalog is only a cached snapshot', () => {+ const ollama = { id: 'opencode-ollama', command: 'opencode', ollamaBacked: true, models: ['ollama/qwen3:8b'] };+ expect(resolveProviderModelOptions(ollama, 'qwen3:32b').unlistedSelection).toBe(false);+ });++ it('never flags an empty catalog or a configured-default sentinel', () => {+ // "We have no catalog" must not read as "the model is gone".+ expect(resolveProviderModelOptions({ id: 'custom', models: [] }, 'anything').unlistedSelection).toBe(false);+ expect(resolveProviderModelOptions(agy(AGY_CATALOG), ANTIGRAVITY_CONFIGURED_DEFAULT).unlistedSelection).toBe(false);+ });++ it('appends a retired BARE pin that withStaleAntigravityPin deliberately skips', () => {+ // That helper only keeps an id carrying an effort SUFFIX. Without the+ // append here a bare retired pin matched no option and the select+ // rendered blank.+ const codex = { id: 'codex', command: 'codex', models: ['gpt-5', 'gpt-5-mini'] };+ const result = resolveProviderModelOptions(codex, 'gpt-4o');+ expect(result.unlistedSelection).toBe(true);+ expect(result.models).toEqual(['gpt-5', 'gpt-5-mini', 'gpt-4o']);+ });+ });+it('leaves a non-subscription provider on its own catalog', () => {const agy = { id: 'antigravity-cli', command: 'agy', models: CATALOG, codexModelCatalog: { models: [], error: null } };expect(resolveProviderModelOptions(agy, '').source).toBe(MODEL_SOURCE.shipped);diff --git a/server/lib/README.md b/server/lib/README.mdindex 61a1e408d8..88b35acdb6 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -206,7 +206,8 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `providerVendors.js` | `PROVIDER_VENDORS` — one row per coding-agent CLI/TUI vendor (claude/codex/antigravity/opencode/grok/kimi/cursor, plus a deliberately-incomplete legacy `gemini-cli` row), consumed by every dispatch site that used to hand-roll its own vendor if-chain across ~8 branches in 5 files (#3618): `applyCommandDefaults`/`prepareCliPrompt` (re-exported from `tuiHandshake.js`/`cliProviderArgs.js`), `buildVendorCliArgs`/`buildVendorSpawnConfig` (consumed by `cliProviderArgs.js#buildCliArgs` / `agentCliSpawning.js#buildCliSpawnConfig`), `inferTuiCommand` (re-exported from `tuiHandshake.js`), and `injectTuiModelAndEffort` — the shared antigravity-validates-the-pair-vs-everyone-else `--model`/`--effort` injection used by both `tuiHandshake.js#buildTuiInvocation` and `agentTuiSpawning.js#buildTuiSpawnConfig`, replacing a second copy of that split that had already drifted once before this file existed. Doesn't rewrite any vendor's argv-building logic — that stays in `antigravity.js`/`grok.js`/`kimi.js`/`cursor.js`/`codex.js`. Dependency-light on purpose, mirroring those files. || `publicReviewSpawnGate.js` | The ordered spawn-time preconditions a public-content review stage must clear before `runAgentSpawn` starts an agent for it — `checkPublicReviewSpawnPreconditions` returns the FIRST failing gate as `{ reason, category, emit }` (or null), running them in the order that is the contract: `publicReviewScanBlock` (the model-abuse scan cleared at least one PR), `publicReviewEligibilityBlock` (a complete eligibility verdict COVERING every PR the issue watcher saw — a partial gate is not a pass), `publicReviewProviderBlock` from `providerVendors.js` (the vendor row declares a maintained recipe for the requested posture; it owns the ordinary-task `null` posture, the re-derivation #5866 got wrong), then the model itself. `emit` tells the caller how to announce it: `warn-log` for the two fail-closed CONTENT gates, whose block must not raise an investigator that could retry the same unvalidated input, `agent:error` for a provider/model misconfiguration that should. `validateModel` is injected rather than imported — it is the one gate that probes a live runtime, so taking it as a parameter keeps this leaf out of the local-LLM graph and makes the gate ORDER testable with a stub. || `modelCapabilityTests.js` | Catalog + scoring for the CAPABILITY tests on `/models/performance` (run by `services/modelCapabilityTests.js`): `CAPABILITY_TESTS` (sandbox repair / image analysis / story outline / fiction scene / rhetoric evaluator, each gated on the capability badges the install catalog already shows), `applicabilityFor` + `applicableTests` (`applicable` / `not-applicable` / `unknown` — an UNCLAIMED capability is never a failure, and `null` capabilities mean the runtime reported none, which is distinct from `[]`), `scoreKeywords` + `VISION_FIXTURE_KEYWORDS` (required vs bonus terms, word-boundary matched with a negation guard so "no dog" doesn't score a dog), `scoreStoryBeats` + `HEROS_JOURNEY_BEATS` (coverage AND ordering, judged only over the beats present), `scoreSandboxRepair` (verdict from observed disk facts — editing the test instead of the module fails outright), `formatAgentEvent` (one agent stream frame → a transcript line), `rollUpVerdict`, and the verbatim `CAPABILITY_TEST_PROMPTS` / `SANDBOX_TASK_PROMPT` the consent gate shows. Pure, so any stored transcript can be re-scored with no provider call. |-| `modelPinReconcile.js` | Retired-model-pin membership rule (#7315) — `providerCatalogListsModel(provider, modelId)` (is a stored pin still served? delegates the base rule to `modelPinIsOffered` — so it inherits that helper's local-daemon carve-out, without which a freshly pulled Ollama model reads as retired — and layers on the two same-model-spelled-differently tolerances: agy compares on BASE ids via `antigravityCatalogListsModel`, and OpenCode's `namespace/model` form matches a bare pin, since a pin is stored bare and namespaced at spawn), `catalogOfferings` (the listed ids with sentinels dropped, agy collapsed to base ids for a picker), and `reconcileModelPins(pins, providers)` — which pin descriptors name a model their provider no longer lists. Every UNKNOWN case (no pin, empty catalog, unresolved provider) answers "still listed": a false "your pin is gone" tells the user to change a setting that works. Derived on read, never persisted — see `services/modelPinAudit.js`. |+| `modelPinMembership.js` | THE model-pin membership rule, and the local-daemon classification it rests on — `modelPinIsOffered(provider, model)` (may this provider be handed this model? a configured-default sentinel, an empty catalog and a local daemon's cached snapshot are all pass-throughs, so a freshly pulled Ollama model is never rejected as "not offered"; beyond those the match is exact, with two same-model-spelled-differently tolerances: agy compares on BASE ids, since `--effort` carries the tier and the spawner splits a suffixed pin into exactly that, and OpenCode's `namespace/model` form matches a bare pin, since pins are stored bare and namespaced at spawn), plus `localRuntimeKind(provider)` (the `*Backed` markers first, then the endpoint/name classifier; `orcarouter` excluded as a remote API) and `localBackendForProvider`. Split out of `localProviderRuntime.js` — which re-exports all three, so existing importers are untouched — because the browser needs this rule for a picker and must not pull that module's endpoint graph (`opencodeConfig.js` → `zod`, not a client dependency) to get it. Consumed by `cliProviderRun.js`, `routes/brainSettings.js`, `services/agentProviderResolution.js`, `modelPinReconcile.js` and `client/src/utils/providerModels.js` — one answer for all five (#7327). |+| `modelPinReconcile.js` | Retired-model-pin AUDIT over the shared membership rule (#7315) — `providerCatalogListsModel(provider, modelId)` (is a stored pin still served? `modelPinIsOffered` from `modelPinMembership.js` verbatim, plus the one case a retirement check answers differently from a spawn-time one: nothing is pinned at all. The agy base-id and OpenCode namespace tolerances used to be layered HERE above a stricter rule, which made the audit and the three spawn-time callers disagree about the same pin; they moved down into the rule in #7327), `catalogOfferings` (the listed ids with sentinels dropped, agy collapsed to base ids for a picker), and `reconcileModelPins(pins, providers)` — which pin descriptors name a model their provider no longer lists. Every UNKNOWN case (no pin, empty catalog, unresolved provider) answers "still listed": a false "your pin is gone" tells the user to change a setting that works. Derived on read, never persisted — see `services/modelPinAudit.js`. || `modelPricing.js` | Per-model API billing rates for the /devtools/usage cost estimates — `resolveModelRates(providerId, model)` (exact → family regex → provider default → blended fallback, with a `matched` tier; also derives `cacheReadPer1M`/`cacheWritePer1M` from the input rate via per-family multipliers), `isFreeProvider` (ollama/lmstudio/`ollamaBacked`/localhost = free), `estimateCostUsd(tokensIn, tokensOut, rates, cache?)` — `tokensIn` is UNCACHED input; cache tiers are priced separately via the optional 4th arg — and `PRICING_AS_OF`. Informational only (PortOS runs on subscriptions); still excludes batch/long-context tiers. || `usageRange.js` | `resolveUsageRange({ period, from, to })` — pure period→inclusive-YYYY-MM-DD range resolution for the usage cost report (explicit dates win; `all` unbounded; default 7d). || `subscriptionSavings.js` | Subscription-vs-API savings math for the usage page — `resolveSavingsWindow` (clamps an open-ended report range to today / first activity day), `prorateMonthlyCost` (monthly plan price → this window's share, `DAYS_PER_MONTH`, capped by `MAX_MONTHLY_COST`), `savingsPercent` / `costMultiplier` (null, never 0, when the comparison is undefined), `attributeReportCostToFamilies` (groups report rows by their stamped `family`), `roundCents` (the one money rounder), and `buildSubscriptionSavings({ entries, range, unmatchedApiCost })` → per-family rows + totals. Pure. |@@ -227,7 +228,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `providerTranscriptUsage.js` | Parsers for the session files the coding CLIs write to disk (0 tokens to read) — `parseClaudeTranscript` (`~/.claude/projects/<cwd-slug>/*.jsonl`), `parseCodexRollout` (`~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl`), `parseGrokTurns`/`parseGrokChatHistory`/`decodeGrokSessionDir` (`~/.grok/sessions/<encodeURIComponent(cwd)>/<id>/`), `parseAgyTranscript`/`parseAgyHistory` (`~/.gemini/antigravity-cli/`), `parseKimiWireLog`/`parseKimiSessionIndex` (`~/.kimi-code/sessions/.../agents/<id>/wire.jsonl`, indexed by `~/.kimi-code/session_index.jsonl`), `claudeProjectSlug`, `totalTranscriptTokens`. Each de-duplicates a format hazard that otherwise inflates counts badly: Claude repeats one response across several lines sharing a `message.id`, Codex's `total_token_usage` is cumulative and repeated, grok's `turn_completed.usage` has shipped in both per-prompt and cumulative shapes (detected and delta'd, never summed raw) while its `_meta.totalTokens` is context occupancy and never billed. Antigravity writes no token fields at all, so its parser returns chars for the caller to estimate from. Kimi's `usage.record` lines are already discrete per-call deltas (no cumulative-snapshot trap), but split across one `wire.jsonl` per agent — a subagent's spend is never in its parent's file. Each parser returns per-model buckets (`byModel`) plus the message keys it counted (`countedKeys`), and accepts an `exclude` set — that is what stops two overlapping PortOS runs from both billing the same messages. Tolerant of truncated (mid-write) files; consumed by `services/usageReconciler.js`. || `opencodeCatalogCache.js` | Primes the on-disk catalog `opencode models` prints from — `primeOpencodeCatalogCache()` fetches OpenCode's `api.json` with Node's fetch and atomically writes `$XDG_CACHE_HOME/opencode/models.json` (`~/.cache` when unset). OpenCode refreshes that file from a forked task whose failures it swallows (`opencode models --refresh` still prints `Models cache refreshed`) and its HTTP client has no Happy Eyeballs, so a host advertising an unreachable IPv6 default route freezes the catalog indefinitely while other machines on the same account list newer models. Refuses to fetch or write when `OPENCODE_MODELS_PATH` / a custom `OPENCODE_MODELS_URL` / `OPENCODE_DISABLE_MODELS_FETCH` means PortOS cannot be sure which file OpenCode reads, when the file is under five minutes old, or when the body did not parse as a catalog — a stale list beats an empty picker. Never throws; the caller probes either way. || `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. |+| `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), `localEndpointPort` + `isLocalInstanceHost`, and re-exports of `localBackendForProvider` / `localRuntimeKind` / `modelPinIsOffered` — all three now live in the browser-safe leaf `modelPinMembership.js` (a picker needs the pin rule and must not pull the endpoint graph below to get it), so existing importers here are untouched — `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` | `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. |diff --git a/server/lib/importScoping.test.js b/server/lib/importScoping.test.jsindex f5c901671d..fb950a2ce0 100644--- a/server/lib/importScoping.test.js+++ b/server/lib/importScoping.test.js@@ -527,7 +527,17 @@ describe('deferred imports stay deferred (#6156)', () => {// that drift apart disable review, CI approval, and merge for every external PR.// Putting both halves in one pure leaf is what keeps the contract test out of the// coordinator's service subtree entirely.-const MAX_STATIC_INSTANTIATIONS = 104101;+// Splitting the model-pin membership rule out of `localProviderRuntime.js` into+// the browser-safe leaf `modelPinMembership.js` (#7327) measures +297. Almost+// all of it is one extra module NODE, not a new subtree: `localProviderRuntime`+// is reached from a great many suites and now instantiates the leaf beside it,+// so each of those closures grows by one. The rest is the leaf's own suite —+// the leaf plus `providerModels.js`, `localEndpoint.js` and `ports.js`, all of+// which that suite's predecessor already pulled. Nothing gained an edge into a+// heavy subtree, and the split REMOVES one for the browser, which is its point:+// `localProviderRuntime` reaches `opencodeConfig.js` → `zod` to resolve+// ENDPOINTS, a question no picker asks. Raise by exactly that delta.+const MAX_STATIC_INSTANTIATIONS = 104330;const SKIP_DIRS = new Set(['node_modules', 'coverage', 'dist', 'data']);diff --git a/server/lib/index.js b/server/lib/index.jsindex 84e5b435b3..ad7f35fc24 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -448,6 +448,7 @@ export * from './learningVerdict.js';export * from './mediaItemKey.js';export * from './assetProvenance.js';export * from './migrationMarker.js';+export * from './modelPinMembership.js';export * from './modelPinReconcile.js';export * from './modelPricing.js';export * from './navManifest.js';diff --git a/server/lib/localProviderRuntime.js b/server/lib/localProviderRuntime.jsindex c7c37fce70..5526eb6c34 100644--- a/server/lib/localProviderRuntime.js+++ b/server/lib/localProviderRuntime.js@@ -17,10 +17,13 @@* Kept side-effect-free so both the readiness service and its tests can reason* about the mapping without a daemon on the host.*- * `localBackendForProvider` (and the loopback-host rules under it) lived in- * `services/localModelHealing.js` until this module existed; it moved here so- * the healing path and the readiness path classify a provider identically, and- * `localModelHealing.js` re-exports it for its existing callers.+ * The CLASSIFICATION half (`localBackendForProvider`, `localRuntimeKind`, and+ * the `modelPinIsOffered` rule built on it) has since moved on to+ * `modelPinMembership.js`, which this module re-exports so every existing+ * importer is untouched: a browser picker needs that rule and must not pull the+ * endpoint graph below (`opencodeConfig.js` → `zod`) to get it. Before that it+ * lived in `services/localModelHealing.js`, which still re-exports+ * `localBackendForProvider` for its own callers.** Endpoint resolution deliberately prefers the provider's OWN configuration* over any default: a user who moved llama-server to another port edited@@ -28,47 +31,18 @@* report their working setup as broken.*/-import { localRuntimeNamespace, isOpencodeCommand, parseOpencodeConfigContent } from './providerModels.js';+import { isOpencodeCommand, parseOpencodeConfigContent } from './providerModels.js';import { opencodeLocalBaseUrl } from './opencodeConfig.js';+import { localRuntimeKind } from './modelPinMembership.js';import { PORTS } from './ports.js';-import { isLocalInstanceHost, isLocalInstanceEndpoint, localEndpointPort } from './localEndpoint.js';+import { isLocalInstanceEndpoint } from './localEndpoint.js';export { isLocalInstanceHost, isLocalInstanceEndpoint, localEndpointPort } from './localEndpoint.js';--// Default OpenAI-compatible ports for the two local backends PortOS manages. An-// endpoint-only provider (no id/name) pointed at one of these on the local-// instance maps to that backend.-const BACKEND_DEFAULT_PORT = { 11434: 'ollama', 1234: 'lmstudio' };--/**- * True when a hostname names the SAME local instance the backend manager runs- * on — any loopback (`127.0.0.0/8`, `::1`), `localhost`, or the unspecified /- * bind-all address (`0.0.0.0`, `::`, which a manager bound to all interfaces- * reports while a provider reaches it as localhost). These all canonicalize to- * one token so spelling differences don't block healing. Deliberately NOT- * link-local / LAN / Tailscale hosts — a peer on another box is a DIFFERENT- * instance whose installed models we must not heal against, and whose daemon- * PortOS must not offer to install here.- */-// MIRROR of `isOllamaProvider` in services/ollamaManager.js — keep in lockstep.-// Inlined so this module stays free of the manager's module graph.-const isOllamaShape = (provider) =>- provider?.id === 'ollama' ||- /ollama/i.test(provider?.name || '') ||- /(^|[/:])(?:localhost|127\.0\.0\.1|\[::1\]):11434\b/i.test(String(provider?.endpoint || ''));--/**- * Which local backend (if any) a provider maps to. Matches by id/name first- * (`ollama` / `lmstudio`), then by an endpoint pointing at the backend's default- * port on THIS machine's local instance.- * @returns {'ollama'|'lmstudio'|null}- */-export function localBackendForProvider(provider) {- if (isOllamaShape(provider)) return 'ollama';- if (provider?.id === 'lmstudio' || /lm[\s-]?studio/i.test(provider?.name || '')) return 'lmstudio';- const port = localEndpointPort(provider?.endpoint);- return port ? (BACKEND_DEFAULT_PORT[port] || null) : null;-}+// The local-backend classifier and the model-pin membership rule moved to the+// browser-safe leaf `modelPinMembership.js` so a picker can share them without+// pulling this module's endpoint graph (`opencodeConfig.js` → `zod`, not a+// client dependency). Re-exported so every existing importer is untouched.+export { localBackendForProvider, localRuntimeKind, modelPinIsOffered } from './modelPinMembership.js';/*** One row per local runtime PortOS knows how to check for.@@ -280,77 +254,6 @@ function opencodeConfiguredBaseUrl(provider, namespace) {return typeof baseUrl === 'string' && baseUrl.trim() !== '' ? baseUrl : null;}-/**- * The local-runtime kind a provider is backed by, from its explicit markers- * first and its endpoint/name only as a fallback.- *- * The `*Backed` markers are authoritative — they are what the spawner itself- * keys on. Hosted gateways (`providerGateways.js`) are deliberately excluded:- * each is an OpenCode local *namespace* but a remote hosted API, so there is no- * local daemon to check.- *- * @param {object|null|undefined} provider- * @returns {'llama'|'ollama'|'lmstudio'|'mtplx'|'vllm'|'sglang'|'slotstream'|null}- */-export function localRuntimeKind(provider) {- if (!provider || typeof provider !== 'object') return null;- // Marker-based, NOT command-based: this also resolves `claude-ollama`, which- // carries `ollamaBacked` without being an OpenCode provider.- const namespace = localRuntimeNamespace(provider);- if (namespace) return namespace;- if (provider?.id === 'slotstream' || /slotstream/i.test(provider?.name || '')) return 'slotstream';- if (Number(localEndpointPort(provider?.endpoint)) === PORTS.SLOTSTREAM) return 'slotstream';- // The shipped `mtplx` record is a plain OpenAI-compatible API provider with no- // marker of its own — `mtplxBacked` only ever rides the OpenCode/Claude CLI- // wrappers, never this record (#6466). `id` is the one signal it carries.- // Deliberately NO port arm here, unlike slotstream two lines up: slotstream's- // port is a PortOS-dedicated constant, while MTPLX's is user-configurable and- // its default (`:8000`) is a generic port — keying on it would claim an- // unrelated local API as MTPLX. `isMtplxProvider` in `mtplxServerManager.js`- // layers a narrower port check on top of this for an unmarked/unnamed- // provider aimed at wherever the managed daemon is actually listening right- // now; that check needs live process state this side-effect-free module- // cannot import without a cycle.- if (provider?.id === 'mtplx') return 'mtplx';- return localBackendForProvider(provider);-}--/**- * Whether a provider may be handed `model` — the one rule for validating a- * stored model pin against a provider record.- *- * Two providers are pass-throughs, for opposite reasons:- *- * - one that enumerates NO models has nothing to validate against, so any id- * is its caller's to choose;- * - one backed by a LOCAL daemon has a `models` array that is only a cached- * snapshot, while the daemon on this machine is the authority. Every model- * picker in PortOS deliberately offers what the daemon reports rather than- * what the record lists, so judging a local pin against the record rejects- * a model that is installed and serving — that is how a pr-reviewer stage- * pinned to a freshly pulled Ollama model got "not offered by provider" on- * every dispatch.- *- * The shipped `mtplx` API record falls into the second bucket now that- * `localRuntimeKind` names it (#6466): it lists one static id, but `mtplx serve`- * names its process after whatever checkpoint is actually loaded, so the- * record's `models` array is exactly the same kind of stale snapshot Ollama's- * is — pass-through is correct here for the same reason, not a side effect of- * the collapse.- *- * Anything else enumerates its own catalog, and a pin outside it reaches the- * CLI as a model it cannot serve.- *- * @param {object|null|undefined} provider- * @param {string|null|undefined} model- * @returns {boolean}- */-export function modelPinIsOffered(provider, model) {- const offered = Array.isArray(provider?.models) ? provider.models : [];- if (offered.length === 0 || localRuntimeKind(provider)) return true;- return offered.includes(model);-}-/*** The local runtime a provider needs, with the endpoint PortOS should probe.*diff --git a/server/lib/localProviderRuntime.test.js b/server/lib/localProviderRuntime.test.jsindex 8fa61f2d38..49bede578d 100644--- a/server/lib/localProviderRuntime.test.js+++ b/server/lib/localProviderRuntime.test.js@@ -2,10 +2,7 @@ import { describe, it, expect, vi, afterEach } from 'vitest';import {LOCAL_RUNTIMES,isLocalInstanceEndpoint,- localBackendForProvider,localRuntimeForProvider,- localRuntimeKind,- modelPinIsOffered,normalizeOpenAiBaseUrl,} from './localProviderRuntime.js';import { opencodeLocalBaseUrl } from './opencodeConfig.js';@@ -54,68 +51,6 @@ describe('isLocalInstanceEndpoint', () => {});});-describe('localRuntimeKind', () => {- it('reads the explicit backing markers first', () => {- expect(localRuntimeKind({ command: 'opencode', llamaBacked: true })).toBe('llama');- expect(localRuntimeKind({ command: 'opencode', mtplxBacked: true })).toBe('mtplx');- expect(localRuntimeKind({ command: 'opencode', vllmBacked: true })).toBe('vllm');- expect(localRuntimeKind({ command: 'opencode', sglangBacked: true })).toBe('sglang');- expect(localRuntimeKind({ command: 'opencode', ollamaBacked: true })).toBe('ollama');- // claude-ollama is not an OpenCode provider but is still Ollama-backed.- expect(localRuntimeKind({ command: 'claude', ollamaBacked: true })).toBe('ollama');- // The marker is what makes a RENAMED LM Studio wrapper still resolve. The- // name/endpoint fallback below would miss this record entirely — it carries- // neither an `lmstudio` id/name nor a :1234 endpoint of its own.- expect(localRuntimeKind({ command: 'opencode', name: 'Coding box', lmstudioBacked: true })).toBe('lmstudio');- });-- it('treats OrcaRouter as remote, not a local daemon', () => {- expect(localRuntimeKind({ command: 'opencode', orcarouterBacked: true })).toBeNull();- });-- it('falls back to the endpoint/name heuristic for plain API providers', () => {- expect(localRuntimeKind({ type: 'api', id: 'ollama', endpoint: 'http://localhost:11434/v1' })).toBe('ollama');- expect(localRuntimeKind({ type: 'api', id: 'x', endpoint: 'http://localhost:1234/v1' })).toBe('lmstudio');- expect(localRuntimeKind({ type: 'api', id: 'x', name: 'LM Studio local' })).toBe('lmstudio');- });-- it('does NOT claim a peer machine daemon as a local runtime', () => {- // A provider pointed at another box on the LAN/tailnet used to match on the- // bare port, so the card offered to install Ollama HERE for a daemon that- // lives — and may simply be switched off — over there.- expect(localRuntimeKind({ type: 'api', id: 'x', endpoint: 'http://192.0.2.10:11434/v1' })).toBeNull();- expect(localRuntimeKind({ type: 'api', id: 'x', endpoint: 'http://192.0.2.10:1234/v1' })).toBeNull();- // Every loopback / bind-all spelling still resolves.- expect(localRuntimeKind({ type: 'api', id: 'x', endpoint: 'http://0.0.0.0:1234' })).toBe('lmstudio');- expect(localRuntimeKind({ type: 'api', id: 'x', endpoint: 'http://[::1]:1234/v1' })).toBe('lmstudio');- });-- it('returns null for a remote provider and for junk input', () => {- expect(localRuntimeKind({ type: 'api', id: 'openai', endpoint: 'https://api.openai.com/v1' })).toBeNull();- expect(localRuntimeKind(null)).toBeNull();- expect(localRuntimeKind('nope')).toBeNull();- });-- it('recognizes Slotstream by id, name, and dedicated port — never 11434', () => {- expect(localRuntimeKind({ id: 'slotstream' })).toBe('slotstream');- expect(localRuntimeKind({ name: 'Slotstream (local)' })).toBe('slotstream');- expect(localRuntimeKind({ endpoint: `http://127.0.0.1:${PORTS.SLOTSTREAM}/v1` })).toBe('slotstream');- expect(localRuntimeKind({ endpoint: 'http://127.0.0.1:11434/v1' })).toBe('ollama');- });-- // #6466 — the shipped `mtplx` API record (`type: 'api'`, no `mtplxBacked`- // marker) is the one shape none of the earlier fallbacks reach, so it needs- // its own id-based arm rather than a generic port check.- it('recognizes the shipped mtplx API record by id, with no port arm', () => {- expect(localRuntimeKind({ id: 'mtplx', type: 'api', endpoint: 'http://127.0.0.1:8000/v1' })).toBe('mtplx');- // :8000 is a generic port a user's own local API could equally be bound- // to — MTPLX's is user-configurable, so an unrelated `id` on that same- // port must never resolve as MTPLX the way slotstream's DEDICATED port- // resolves above.- expect(localRuntimeKind({ id: 'some-local-api', type: 'api', endpoint: 'http://127.0.0.1:8000/v1' })).toBeNull();- });-});-describe('localRuntimeForProvider', () => {it('prefers the baseURL the provider itself declares over the canonical default', () => {const runtime = localRuntimeForProvider({@@ -243,75 +178,3 @@ describe('localRuntimeForProvider', () => {expect(runtime.endpoint).toBe('http://127.0.0.1:8000/v1');});});--describe('modelPinIsOffered', () => {- it('passes through when the provider lists no models of its own', () => {- expect(modelPinIsOffered({ id: 'custom-api', models: [] }, 'anything')).toBe(true);- expect(modelPinIsOffered({ id: 'custom-api' }, 'anything')).toBe(true);- });-- it('validates a pin against the listed catalog for a non-local provider', () => {- const provider = { id: 'openai', models: ['gpt-x', 'gpt-y'] };- expect(modelPinIsOffered(provider, 'gpt-x')).toBe(true);- expect(modelPinIsOffered(provider, 'gpt-z')).toBe(false);- });-- it('passes through for a local-daemon provider, whatever the pin', () => {- // Ollama/LM Studio's `models` array is a cached snapshot; the daemon on- // this machine is the authority, so a pin outside the stale list must- // still be considered offered.- const provider = { command: 'opencode', ollamaBacked: true, models: ['stale-model'] };- expect(modelPinIsOffered(provider, 'freshly-pulled-model')).toBe(true);- });-- // #6466 — decision: the shipped mtplx API record is a pass-through too, once- // `localRuntimeKind` names it. `mtplx serve` names its process after whatever- // checkpoint is actually loaded, so the record's static `models` entry is the- // same kind of stale snapshot Ollama's is — judging a pin against it would- // reject a checkpoint that is installed and serving.- it('passes through for the shipped mtplx API record, whatever the pin', () => {- const provider = {- id: 'mtplx',- type: 'api',- endpoint: 'http://127.0.0.1:8000/v1',- models: ['mtplx-qwen38-27b-optimized-speed'],- };- expect(modelPinIsOffered(provider, 'a-different-checkpoint-the-daemon-now-serves')).toBe(true);- });-- it('is id-based, not locality-gated, matching the existing ollama/slotstream id checks', () => {- // `localRuntimeKind`'s id-based arms (ollama, slotstream, and now mtplx)- // do not themselves check the endpoint's locality — the callers that need- // that distinction (`isMtplxProvider`, `localRuntimeForProvider`) apply it- // on top. `modelPinIsOffered` calls `localRuntimeKind` raw, so an `id:- // 'mtplx'` record pointed at another machine passes through here exactly- // as an `id: 'ollama'` one already does — not a new gap this issue opens.- const provider = {- id: 'mtplx',- type: 'api',- endpoint: 'http://192.0.2.10:8000/v1',- models: ['mtplx-qwen38-27b-optimized-speed'],- };- expect(modelPinIsOffered(provider, 'a-different-checkpoint')).toBe(true);- });-});--describe('localBackendForProvider', () => {- // Moved here from services/localModelHealing.js, which now re-exports it —- // these cases pin the behavior its healing path depends on.- it('matches by id, name, and local endpoint port', () => {- expect(localBackendForProvider({ id: 'ollama' })).toBe('ollama');- expect(localBackendForProvider({ name: 'My Ollama' })).toBe('ollama');- expect(localBackendForProvider({ endpoint: 'http://localhost:11434/v1' })).toBe('ollama');- expect(localBackendForProvider({ id: 'lmstudio' })).toBe('lmstudio');- expect(localBackendForProvider({ name: 'lm-studio' })).toBe('lmstudio');- expect(localBackendForProvider({ endpoint: 'http://127.0.0.1:1234/v1' })).toBe('lmstudio');- });-- it('declines a remote host, an unknown port, and junk', () => {- expect(localBackendForProvider({ endpoint: 'http://192.0.2.10:11434/v1' })).toBeNull();- expect(localBackendForProvider({ endpoint: 'http://localhost:9999' })).toBeNull();- expect(localBackendForProvider({ id: 'anthropic', endpoint: 'https://api.anthropic.com/v1' })).toBeNull();- expect(localBackendForProvider(null)).toBeNull();- });-});diff --git a/server/lib/modelPinMembership.js b/server/lib/modelPinMembership.jsnew file mode 100644index 0000000000..1224cc66b1--- /dev/null+++ b/server/lib/modelPinMembership.js@@ -0,0 +1,152 @@+/**+ * Which LOCAL daemon backs a provider, and whether a stored model pin is one+ * that provider may still be handed.+ *+ * Split out of `localProviderRuntime.js` (which re-exports every name here, so+ * its existing importers are untouched) for one reason: the browser needs this+ * rule. A picker that renders a stored pin has to know whether the catalog+ * still lists it, and `localProviderRuntime.js` reaches `opencodeConfig.js` —+ * and through it `zod`, which is not a client dependency — to resolve+ * ENDPOINTS, a question no picker asks. This leaf carries only what the+ * membership rule needs (`providerModels.js`, `localEndpoint.js`, `ports.js`),+ * all of which the client already imports, so `client/src/utils/providerModels.js`+ * can mirror the server's answer instead of re-deriving a second one.+ *+ * The endpoint half stayed behind in `localProviderRuntime.js`.+ */++import { localRuntimeNamespace, isAntigravityProvider, antigravityCatalogListsModel, filterSelectableModels, isConfiguredDefaultModel } from './providerModels.js';+import { PORTS } from './ports.js';+import { isLocalInstanceHost, localEndpointPort } from './localEndpoint.js';++// Default OpenAI-compatible ports for the two local backends PortOS manages. An+// endpoint-only provider (no id/name) pointed at one of these on the local+// instance maps to that backend.+const BACKEND_DEFAULT_PORT = { 11434: 'ollama', 1234: 'lmstudio' };++// MIRROR of `isOllamaProvider` in services/ollamaManager.js — keep in lockstep.+// Inlined so this module stays free of the manager's module graph.+const isOllamaShape = (provider) =>+ provider?.id === 'ollama' ||+ /ollama/i.test(provider?.name || '') ||+ /(^|[/:])(?:localhost|127\.0\.0\.1|\[::1\]):11434\b/i.test(String(provider?.endpoint || ''));++/**+ * Which local backend (if any) a provider maps to. Matches by id/name first+ * (`ollama` / `lmstudio`), then by an endpoint pointing at the backend's default+ * port on THIS machine's local instance.+ * @returns {'ollama'|'lmstudio'|null}+ */+export function localBackendForProvider(provider) {+ if (isOllamaShape(provider)) return 'ollama';+ if (provider?.id === 'lmstudio' || /lm[\s-]?studio/i.test(provider?.name || '')) return 'lmstudio';+ const port = localEndpointPort(provider?.endpoint);+ return port ? (BACKEND_DEFAULT_PORT[port] || null) : null;+}++/**+ * The local-runtime kind a provider is backed by, from its explicit markers+ * first and its endpoint/name only as a fallback.+ *+ * The `*Backed` markers are authoritative — they are what the spawner itself+ * keys on. Hosted gateways (`providerGateways.js`) are deliberately excluded:+ * each is an OpenCode local *namespace* but a remote hosted API, so there is no+ * local daemon to check.+ *+ * @param {object|null|undefined} provider+ * @returns {'llama'|'ollama'|'lmstudio'|'mtplx'|'vllm'|'sglang'|'slotstream'|null}+ */+export function localRuntimeKind(provider) {+ if (!provider || typeof provider !== 'object') return null;+ // Marker-based, NOT command-based: this also resolves `claude-ollama`, which+ // carries `ollamaBacked` without being an OpenCode provider.+ const namespace = localRuntimeNamespace(provider);+ if (namespace) return namespace;+ if (provider?.id === 'slotstream' || /slotstream/i.test(provider?.name || '')) return 'slotstream';+ if (Number(localEndpointPort(provider?.endpoint)) === PORTS.SLOTSTREAM) return 'slotstream';+ // The shipped `mtplx` record is a plain OpenAI-compatible API provider with no+ // marker of its own — `mtplxBacked` only ever rides the OpenCode/Claude CLI+ // wrappers, never this record (#6466). `id` is the one signal it carries.+ // Deliberately NO port arm here, unlike slotstream two lines up: slotstream's+ // port is a PortOS-dedicated constant, while MTPLX's is user-configurable and+ // its default (`:8000`) is a generic port — keying on it would claim an+ // unrelated local API as MTPLX. `isMtplxProvider` in `mtplxServerManager.js`+ // layers a narrower port check on top of this for an unmarked/unnamed+ // provider aimed at wherever the managed daemon is actually listening right+ // now; that check needs live process state this side-effect-free module+ // cannot import without a cycle.+ if (provider?.id === 'mtplx') return 'mtplx';+ return localBackendForProvider(provider);+}++/**+ * `namespace/model` reduced to the bare model id — a no-op on an id with no+ * slash, which is exactly how OpenCode itself splits `provider/model`: on the+ * FIRST slash only.+ */+const bareOpencodeModel = (value) => value.slice(value.indexOf('/') + 1);++/**+ * Whether a provider may be handed `model` — the ONE rule for validating a+ * stored model pin against a provider record.+ *+ * Three pins pass through unconditionally, for three different reasons:+ *+ * - a CONFIGURED-DEFAULT SENTINEL is not a model at all, it is "use the CLI's+ * own default". `resolveCliModel` turns it into no `--model` flag, so every+ * provider can be handed it whatever its catalog says;+ * - a provider that enumerates NO models has nothing to validate against, so+ * any id is its caller's to choose;+ * - one backed by a LOCAL daemon has a `models` array that is only a cached+ * snapshot, while the daemon on this machine is the authority. Every model+ * picker in PortOS deliberately offers what the daemon reports rather than+ * what the record lists, so judging a local pin against the record rejects+ * a model that is installed and serving — that is how a pr-reviewer stage+ * pinned to a freshly pulled Ollama model got "not offered by provider" on+ * every dispatch.+ *+ * The shipped `mtplx` API record falls into the third bucket now that+ * `localRuntimeKind` names it (#6466): it lists one static id, but `mtplx serve`+ * names its process after whatever checkpoint is actually loaded, so the+ * record's `models` array is exactly the same kind of stale snapshot Ollama's+ * is — pass-through is correct here for the same reason, not a side effect of+ * the collapse.+ *+ * Beyond the pass-throughs the comparison is exact, with two tolerances for a+ * pin that is the SAME model spelled differently — not a laxer rule (#7327).+ * Both live here rather than in a wrapper so all four callers share one answer:+ *+ * - **agy compares on BASE ids.** Once `--effort` carries the tier,+ * `gemini-3.6-flash` and `gemini-3.6-flash-low` are the same `--model`+ * value — `resolveAntigravityModelAndEffort` splits a suffixed pin into+ * exactly that base plus `--effort` before spawning — and a tier the base+ * does not offer is clamped by `antigravityModelEffortLevels` rather than+ * being a different model. Without this a bare base id pinned against a+ * suffix-only catalog was rejected as unserveable by the very helper that+ * would have spawned it.+ * - **OpenCode addresses models as `namespace/model`.** A pin is stored BARE+ * and namespaced at spawn (`prefixOpencodeModel`), so a catalog holding the+ * qualified form — or a pin hand-written that way — is the same model.+ *+ * Anything else enumerates its own catalog, and a pin outside it reaches the+ * CLI as a model it cannot serve.+ *+ * @param {object|null|undefined} provider+ * @param {string|null|undefined} model+ * @returns {boolean}+ */+export function modelPinIsOffered(provider, model) {+ const offered = Array.isArray(provider?.models) ? provider.models : [];+ if (isConfiguredDefaultModel(model)) return true;+ if (offered.length === 0 || localRuntimeKind(provider)) return true;+ if (offered.includes(model)) return true;+ if (typeof model !== 'string' || model.trim() === '') return false;++ const id = model.trim();+ // Sentinels are a posture, not a model, so they can never be what a pin+ // matches against here — and `antigravityCatalogListsModel` reads an empty+ // base list as "no catalog", which is the same pass-through as above.+ const ids = filterSelectableModels(offered.filter((m) => typeof m === 'string'));+ if (isAntigravityProvider(provider)) return antigravityCatalogListsModel(id, ids);+ return ids.some((listed) => bareOpencodeModel(listed) === bareOpencodeModel(id));+}diff --git a/server/lib/modelPinMembership.test.js b/server/lib/modelPinMembership.test.jsnew file mode 100644index 0000000000..b42ab71907--- /dev/null+++ b/server/lib/modelPinMembership.test.js@@ -0,0 +1,204 @@+import { describe, it, expect } from 'vitest';+import {+ localBackendForProvider,+ localRuntimeKind,+ modelPinIsOffered,+} from './modelPinMembership.js';+import { CODEX_CONFIGURED_DEFAULT } from './providerModels.js';+import { PORTS } from './ports.js';++describe('localRuntimeKind', () => {+ it('reads the explicit backing markers first', () => {+ expect(localRuntimeKind({ command: 'opencode', llamaBacked: true })).toBe('llama');+ expect(localRuntimeKind({ command: 'opencode', mtplxBacked: true })).toBe('mtplx');+ expect(localRuntimeKind({ command: 'opencode', vllmBacked: true })).toBe('vllm');+ expect(localRuntimeKind({ command: 'opencode', sglangBacked: true })).toBe('sglang');+ expect(localRuntimeKind({ command: 'opencode', ollamaBacked: true })).toBe('ollama');+ // claude-ollama is not an OpenCode provider but is still Ollama-backed.+ expect(localRuntimeKind({ command: 'claude', ollamaBacked: true })).toBe('ollama');+ // The marker is what makes a RENAMED LM Studio wrapper still resolve. The+ // name/endpoint fallback below would miss this record entirely — it carries+ // neither an `lmstudio` id/name nor a :1234 endpoint of its own.+ expect(localRuntimeKind({ command: 'opencode', name: 'Coding box', lmstudioBacked: true })).toBe('lmstudio');+ });++ it('treats OrcaRouter as remote, not a local daemon', () => {+ expect(localRuntimeKind({ command: 'opencode', orcarouterBacked: true })).toBeNull();+ });++ it('falls back to the endpoint/name heuristic for plain API providers', () => {+ expect(localRuntimeKind({ type: 'api', id: 'ollama', endpoint: 'http://localhost:11434/v1' })).toBe('ollama');+ expect(localRuntimeKind({ type: 'api', id: 'x', endpoint: 'http://localhost:1234/v1' })).toBe('lmstudio');+ expect(localRuntimeKind({ type: 'api', id: 'x', name: 'LM Studio local' })).toBe('lmstudio');+ });++ it('does NOT claim a peer machine daemon as a local runtime', () => {+ // A provider pointed at another box on the LAN/tailnet used to match on the+ // bare port, so the card offered to install Ollama HERE for a daemon that+ // lives — and may simply be switched off — over there.+ expect(localRuntimeKind({ type: 'api', id: 'x', endpoint: 'http://192.0.2.10:11434/v1' })).toBeNull();+ expect(localRuntimeKind({ type: 'api', id: 'x', endpoint: 'http://192.0.2.10:1234/v1' })).toBeNull();+ // Every loopback / bind-all spelling still resolves.+ expect(localRuntimeKind({ type: 'api', id: 'x', endpoint: 'http://0.0.0.0:1234' })).toBe('lmstudio');+ expect(localRuntimeKind({ type: 'api', id: 'x', endpoint: 'http://[::1]:1234/v1' })).toBe('lmstudio');+ });++ it('returns null for a remote provider and for junk input', () => {+ expect(localRuntimeKind({ type: 'api', id: 'openai', endpoint: 'https://api.openai.com/v1' })).toBeNull();+ expect(localRuntimeKind(null)).toBeNull();+ expect(localRuntimeKind('nope')).toBeNull();+ });++ it('recognizes Slotstream by id, name, and dedicated port — never 11434', () => {+ expect(localRuntimeKind({ id: 'slotstream' })).toBe('slotstream');+ expect(localRuntimeKind({ name: 'Slotstream (local)' })).toBe('slotstream');+ expect(localRuntimeKind({ endpoint: `http://127.0.0.1:${PORTS.SLOTSTREAM}/v1` })).toBe('slotstream');+ expect(localRuntimeKind({ endpoint: 'http://127.0.0.1:11434/v1' })).toBe('ollama');+ });++ // #6466 — the shipped `mtplx` API record (`type: 'api'`, no `mtplxBacked`+ // marker) is the one shape none of the earlier fallbacks reach, so it needs+ // its own id-based arm rather than a generic port check.+ it('recognizes the shipped mtplx API record by id, with no port arm', () => {+ expect(localRuntimeKind({ id: 'mtplx', type: 'api', endpoint: 'http://127.0.0.1:8000/v1' })).toBe('mtplx');+ // :8000 is a generic port a user's own local API could equally be bound+ // to — MTPLX's is user-configurable, so an unrelated `id` on that same+ // port must never resolve as MTPLX the way slotstream's DEDICATED port+ // resolves above.+ expect(localRuntimeKind({ id: 'some-local-api', type: 'api', endpoint: 'http://127.0.0.1:8000/v1' })).toBeNull();+ });+});++describe('modelPinIsOffered', () => {+ it('passes through when the provider lists no models of its own', () => {+ expect(modelPinIsOffered({ id: 'custom-api', models: [] }, 'anything')).toBe(true);+ expect(modelPinIsOffered({ id: 'custom-api' }, 'anything')).toBe(true);+ });++ it('validates a pin against the listed catalog for a non-local provider', () => {+ const provider = { id: 'openai', models: ['gpt-x', 'gpt-y'] };+ expect(modelPinIsOffered(provider, 'gpt-x')).toBe(true);+ expect(modelPinIsOffered(provider, 'gpt-z')).toBe(false);+ });++ it('passes through for a local-daemon provider, whatever the pin', () => {+ // Ollama/LM Studio's `models` array is a cached snapshot; the daemon on+ // this machine is the authority, so a pin outside the stale list must+ // still be considered offered.+ const provider = { command: 'opencode', ollamaBacked: true, models: ['stale-model'] };+ expect(modelPinIsOffered(provider, 'freshly-pulled-model')).toBe(true);+ });++ // #6466 — decision: the shipped mtplx API record is a pass-through too, once+ // `localRuntimeKind` names it. `mtplx serve` names its process after whatever+ // checkpoint is actually loaded, so the record's static `models` entry is the+ // same kind of stale snapshot Ollama's is — judging a pin against it would+ // reject a checkpoint that is installed and serving.+ it('passes through for the shipped mtplx API record, whatever the pin', () => {+ const provider = {+ id: 'mtplx',+ type: 'api',+ endpoint: 'http://127.0.0.1:8000/v1',+ models: ['mtplx-qwen38-27b-optimized-speed'],+ };+ expect(modelPinIsOffered(provider, 'a-different-checkpoint-the-daemon-now-serves')).toBe(true);+ });++ it('is id-based, not locality-gated, matching the existing ollama/slotstream id checks', () => {+ // `localRuntimeKind`'s id-based arms (ollama, slotstream, and now mtplx)+ // do not themselves check the endpoint's locality — the callers that need+ // that distinction (`isMtplxProvider`, `localRuntimeForProvider`) apply it+ // on top. `modelPinIsOffered` calls `localRuntimeKind` raw, so an `id:+ // 'mtplx'` record pointed at another machine passes through here exactly+ // as an `id: 'ollama'` one already does — not a new gap this issue opens.+ const provider = {+ id: 'mtplx',+ type: 'api',+ endpoint: 'http://192.0.2.10:8000/v1',+ models: ['mtplx-qwen38-27b-optimized-speed'],+ };+ expect(modelPinIsOffered(provider, 'a-different-checkpoint')).toBe(true);+ });+});++describe('localBackendForProvider', () => {+ // Moved here from services/localModelHealing.js, which now re-exports it —+ // these cases pin the behavior its healing path depends on.+ it('matches by id, name, and local endpoint port', () => {+ expect(localBackendForProvider({ id: 'ollama' })).toBe('ollama');+ expect(localBackendForProvider({ name: 'My Ollama' })).toBe('ollama');+ expect(localBackendForProvider({ endpoint: 'http://localhost:11434/v1' })).toBe('ollama');+ expect(localBackendForProvider({ id: 'lmstudio' })).toBe('lmstudio');+ expect(localBackendForProvider({ name: 'lm-studio' })).toBe('lmstudio');+ expect(localBackendForProvider({ endpoint: 'http://127.0.0.1:1234/v1' })).toBe('lmstudio');+ });++ it('declines a remote host, an unknown port, and junk', () => {+ expect(localBackendForProvider({ endpoint: 'http://192.0.2.10:11434/v1' })).toBeNull();+ expect(localBackendForProvider({ endpoint: 'http://localhost:9999' })).toBeNull();+ expect(localBackendForProvider({ id: 'anthropic', endpoint: 'https://api.anthropic.com/v1' })).toBeNull();+ expect(localBackendForProvider(null)).toBeNull();+ });+});++// #7327 — the agy base-id and OpenCode namespace tolerances used to live one+// level UP, in `modelPinReconcile.js`, so the retired-pin audit and the three+// spawn-time callers of this rule disagreed about the same pin. Each case below+// is one this rule REJECTED while the spawner it guards would have run the+// model happily.+describe('modelPinIsOffered — same model, spelled differently', () => {+ const AGY = {+ id: 'antigravity-cli',+ command: 'agy',+ models: ['gemini-3.6-flash-low', 'gemini-3.6-flash-high', 'claude-sonnet-4-6'],+ };++ it('accepts a bare agy base id against a suffix-only catalog', () => {+ // `resolveAntigravityModelAndEffort` splits a suffixed pin into exactly this+ // base plus `--effort` before spawning, so the base id IS what agy receives.+ // Rejecting it made `cliProviderRun` fall back to the provider default for a+ // model it would itself have spawned.+ expect(modelPinIsOffered(AGY, 'gemini-3.6-flash')).toBe(true);+ // A tier the base does not list is clamped by `antigravityModelEffortLevels`,+ // not a different model.+ expect(modelPinIsOffered(AGY, 'gemini-3.6-flash-medium')).toBe(true);+ });++ it('still rejects an agy pin whose BASE the catalog dropped', () => {+ // The tolerance is a spelling rule, not a laxer one: a retirement is still+ // a retirement at every tier.+ expect(modelPinIsOffered(AGY, 'gemini-3.5-flash')).toBe(false);+ expect(modelPinIsOffered(AGY, 'gemini-3.5-flash-low')).toBe(false);+ });++ it('matches an OpenCode `namespace/model` catalog against a bare pin', () => {+ // Pins are stored BARE and namespaced at spawn by `prefixOpencodeModel`.+ // A gateway-backed OpenCode provider is NOT a local daemon, so it reaches+ // the exact comparison rather than the pass-through above.+ const gateway = {+ id: 'opencode-openrouter',+ command: 'opencode',+ gatewayBacked: 'openrouter',+ models: ['openrouter/claude-sonnet-4'],+ };+ expect(modelPinIsOffered(gateway, 'claude-sonnet-4')).toBe(true);+ expect(modelPinIsOffered(gateway, 'openrouter/claude-sonnet-4')).toBe(true);+ expect(modelPinIsOffered(gateway, 'claude-opus-4')).toBe(false);+ });++ it('accepts a configured-default sentinel against any catalog', () => {+ // The sentinel is a posture ("use the CLI's own default"), not a model:+ // `resolveCliModel` turns it into no `--model` flag at all, so no catalog+ // can retire it. Rejecting it 400'd a legitimate brain-settings save.+ expect(modelPinIsOffered({ id: 'codex', models: ['gpt-5'] }, CODEX_CONFIGURED_DEFAULT)).toBe(true);+ });++ it('rejects a blank or non-string pin against a real catalog', () => {+ // "Nothing is pinned" is the AUDIT's question, answered one level up in+ // `modelPinReconcile.js`. Here the caller is asking what to hand a CLI, and+ // a blank id is not in the catalog.+ for (const pin of ['', ' ', null, undefined, 42]) {+ expect(modelPinIsOffered({ id: 'codex', models: ['gpt-5'] }, pin)).toBe(false);+ }+ });+});diff --git a/server/lib/modelPinReconcile.js b/server/lib/modelPinReconcile.jsindex 8956d83fb8..e878fbb9c1 100644--- a/server/lib/modelPinReconcile.js+++ b/server/lib/modelPinReconcile.js@@ -27,13 +27,11 @@* service, the route, and the suite can all share one membership rule.*/-import { modelPinIsOffered } from './localProviderRuntime.js';+import { modelPinIsOffered } from './modelPinMembership.js';import {antigravityBaseModels,- antigravityCatalogListsModel,filterSelectableModels,isAntigravityProvider,- isConfiguredDefaultModel,} from './providerModels.js';/**@@ -66,32 +64,27 @@ export function catalogOfferings(provider) {/*** Is `modelId` still served by `provider`?*- * Delegates the base rule to `modelPinIsOffered` — the repo's existing "is this- * stored pin valid against this provider record?" test — and adds only the- * tolerances a RETIREMENT check needs on top. Re-deriving the base rule here- * would have dropped its local-daemon carve-out, which is load-bearing: an- * Ollama/LM Studio/MTPLX-backed provider's `models` array is a stale cached- * snapshot while the daemon on this machine is the authority, so judging a- * local pin against the record reports a model that is installed and serving as- * retired — and this feature would then offer a one-click button to delete it.+ * THE membership rule, `modelPinIsOffered`, verbatim — plus the one case a+ * RETIREMENT check answers differently from a spawn-time check: nothing is+ * pinned at all. This wrapper exists only to name that case and to give the+ * audit a signature in its own vocabulary (`(provider, modelId)`, the pin's+ * side of the question).*- * That is the whole reason for the posture below: every case where the answer- * is genuinely UNKNOWN answers `true`. A false "your pin is gone" tells the- * user to change a setting that works, which is strictly worse than missing- * one. `modelPinIsOffered` supplies two of those cases (an empty catalog, a- * local-daemon provider); this function adds two more (nothing is pinned, and- * no provider record could be resolved to compare against).+ * The rule's posture is what makes this safe to surface in a UI: every case+ * where the answer is genuinely UNKNOWN answers `true`. A false "your pin is+ * gone" tells the user to change a setting that works, which is strictly worse+ * than missing one. `modelPinIsOffered` supplies the configured-default+ * sentinel, an empty catalog, a local-daemon provider, and the two+ * same-model-spelled-differently tolerances (agy base ids, OpenCode's+ * `namespace/model` form); this function adds the last two — nothing is+ * pinned, and no provider record could be resolved to compare against.*- * The two tolerances layered on top are both "the same model, spelled- * differently", not a laxer rule:- *- * - **agy compares on BASE ids.** Once `--effort` carries the tier,- * `gemini-3.6-flash` and `gemini-3.6-flash-low` are the same `--model`- * value, and a tier the base does not offer is clamped by- * `antigravityModelEffortLevels` rather than being a different model.- * - **OpenCode addresses models as `namespace/model`.** A pin is stored BARE- * and namespaced at spawn (`prefixOpencodeModel`), so a catalog holding the- * qualified form — or a pin hand-written that way — is the same model.+ * Those tolerances used to be layered HERE, above a stricter+ * `modelPinIsOffered`, which meant the audit and the three spawn-time callers+ * disagreed about the same pin: `cliProviderRun` rejected a bare agy base id+ * against a suffix-only catalog and silently fell back to the provider default+ * — for a model it would itself have spawned. They moved down into the rule+ * (#7327), so there is now one answer and the browser can mirror it.** @param {{id?:string, command?:string, models?:unknown[]}|null|undefined} provider* @param {string|null|undefined} modelId@@ -99,18 +92,8 @@ export function catalogOfferings(provider) {*/export function providerCatalogListsModel(provider, modelId) {if (typeof modelId !== 'string' || modelId.trim() === '') return true;- const id = modelId.trim();- if (isConfiguredDefaultModel(id)) return true;if (!provider) return true;- // Empty catalog, local daemon, or a plain exact match — all "still served".- if (modelPinIsOffered(provider, id)) return true;-- const ids = catalogModelIds(provider);- if (isAntigravityProvider(provider)) return antigravityCatalogListsModel(id, ids);- // `bare` is a no-op on an id with no slash, which is exactly how OpenCode- // itself splits `provider/model` — on the FIRST slash only.- const bare = (value) => value.slice(value.indexOf('/') + 1);- return ids.some((listed) => bare(listed) === bare(id));+ return modelPinIsOffered(provider, modelId.trim());}/**