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
surface stored model pins a provider catalog has retired (#7315)
[._.]/ Adam Eivycb79f4e9c554
diff --git a/client/src/components/providers/RetiredModelPinsPanel.jsx b/client/src/components/providers/RetiredModelPinsPanel.jsxnew file mode 100644index 0000000000..80c5cf50ae--- /dev/null+++ b/client/src/components/providers/RetiredModelPinsPanel.jsx@@ -0,0 +1,139 @@+import { useCallback, useEffect, useState } from 'react';+import { Link } from 'react-router';+import { AlertTriangle } from 'lucide-react';+import toast from '../ui/Toast';+import * as api from '../../services/api';+import Banner from '../ui/Banner';+import { modeLabel, RENDER_TARGET_OPTIONS } from '../../lib/imageGenModes';+import { pluralize } from '../../lib/textUtils';++/**+ * The user-facing name for a pin, composed HERE rather than on the server.+ *+ * The server sends the structured descriptor (`kind`, `mode`, `target`, …); the+ * human names for those ids already live in the client registries the Settings+ * pages render from, so composing here is what keeps the panel and the page it+ * deep-links to calling the same row the same thing — the server's own `label`+ * would say "universe-bible render model" where Settings says "Universe Bible &+ * canon renders". Falls back to the server label for any kind with no registry+ * entry (task and per-app pins, whose names are the user's own task ids).+ */+const pinLabel = (pin) => {+ if (pin.kind === 'imageGen') return `${modeLabel(pin.mode)} image model`;+ if (pin.kind === 'renderDefault') {+ const target = RENDER_TARGET_OPTIONS.find((option) => option.id === pin.target);+ return target ? `${target.label} — model` : pin.label;+ }+ return pin.label;+};++/**+ * "These pins name a model your provider no longer serves" (#7315).+ *+ * A vendor retires a model id, the install's catalog refresh picks that up, and+ * every stored pin still naming it rots silently until a render or a scheduled+ * run dies with a raw vendor error. PortOS re-points only the ONE pin it owns+ * (`AGY_IMAGEGEN_DEFAULT_MODEL`, #7314); a pin the USER chose can only be+ * surfaced, because substituting it would render something different under the+ * chosen model's name and bury the vendor's own "unknown model" error.+ *+ * So this warns and offers a one-click clear back to "inherit" — it never+ * rewrites a pin on its own. Renders nothing at all when every pin is healthy,+ * which is the normal state; the panel must not cost a healthy install a row.+ *+ * `reloadKey` re-reads the audit when the caller knows a catalog moved (the+ * Providers page bumps it after a model refresh) — a retirement is only+ * observable once the refresh lands, so the pin it rotted has to surface then+ * rather than waiting for the next full page load.+ */+export default function RetiredModelPinsPanel({ reloadKey = 0 }) {+ const [pins, setPins] = useState([]);+ const [providers, setProviders] = useState({});+ const [clearing, setClearing] = useState(null);++ const load = useCallback(async () => {+ // `silent` — a provider service that isn't up yet is not something to toast+ // about on a page the user opened to look at providers. The panel simply+ // stays hidden, which is indistinguishable from "no stale pins".+ const data = await api.getModelPinWarnings({ silent: true }).catch(() => null);+ setPins(Array.isArray(data?.pins) ? data.pins : []);+ setProviders(data?.providers && typeof data.providers === 'object' ? data.providers : {});+ }, []);++ useEffect(() => { load(); }, [load, reloadKey]);++ const handleClear = async (pin) => {+ setClearing(pin.id);+ const result = await api.clearModelPin(pin.id).catch(() => null);+ setClearing(null);+ if (!result) return;+ // Drop the row locally rather than waiting on a reload: the write already+ // landed, and re-reading would blink the whole panel. `load()` still runs so+ // a pin that was cleared in another tab disappears too.+ // The write already landed, so the local removal IS the new state — a+ // re-read would spend a full server audit to learn what we just did.+ setPins((current) => current.filter((entry) => entry.id !== pin.id));+ toast.success(`Cleared the ${pinLabel(pin)} pin — it now inherits the default.`);+ };++ if (pins.length === 0) return null;++ return (+ <Banner+ tone="warning"+ size="lg"+ icon={AlertTriangle}+ title={`${pluralize(pins.length, 'model pin')} ${pins.length === 1 ? 'names' : 'name'} a model that is no longer offered`}+ >+ <p className="mt-1 text-xs text-gray-400">+ These were pinned by hand, so PortOS will not swap them for you — a substitution would render under+ the name you chose. Clear one to inherit the default, or pick a listed model where the pin lives.+ </p>+ <ul className="mt-3 space-y-2">+ {pins.map((pin) => {+ const provider = providers[pin.providerId];+ const offered = Array.isArray(provider?.available) ? provider.available : [];+ return (+ <li+ key={pin.id}+ className="flex flex-wrap items-start justify-between gap-2 rounded border border-port-border bg-port-card p-3"+ >+ <div className="min-w-0 flex-1">+ <div className="text-sm font-medium text-white">+ {pinLabel(pin)}: <code className="text-port-warning">{pin.model}</code>+ </div>+ <div className="mt-0.5 text-xs text-gray-400">+ {pin.location} · {provider?.name || pin.providerId}+ </div>+ {offered.length > 0 && (+ <div className="mt-1 break-words text-xs text-gray-500">+ Now offered: {offered.slice(0, 6).join(', ')}+ {offered.length > 6 ? ` +${offered.length - 6} more` : ''}+ </div>+ )}+ </div>+ <div className="flex shrink-0 items-center gap-2">+ {pin.href && (+ <Link+ to={pin.href}+ className="rounded bg-port-border px-3 py-1.5 text-xs text-white transition-colors hover:bg-port-border/80"+ >+ Open setting+ </Link>+ )}+ <button+ type="button"+ onClick={() => handleClear(pin)}+ disabled={clearing === pin.id}+ className="rounded bg-port-accent px-3 py-1.5 text-xs text-white transition-colors hover:bg-port-accent/80 disabled:opacity-50"+ >+ {clearing === pin.id ? 'Clearing…' : 'Clear pin'}+ </button>+ </div>+ </li>+ );+ })}+ </ul>+ </Banner>+ );+}diff --git a/client/src/components/providers/RetiredModelPinsPanel.test.jsx b/client/src/components/providers/RetiredModelPinsPanel.test.jsxnew file mode 100644index 0000000000..45314bbdde--- /dev/null+++ b/client/src/components/providers/RetiredModelPinsPanel.test.jsx@@ -0,0 +1,123 @@+import { describe, expect, it, vi, beforeEach } from 'vitest';+import { fireEvent, render, screen, waitFor } from '@testing-library/react';+import { MemoryRouter } from 'react-router';++vi.mock('../../services/api', () => ({+ getModelPinWarnings: vi.fn(),+ clearModelPin: vi.fn(),+}));+vi.mock('../ui/Toast', () => ({+ default: Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn() }),+}));++import * as api from '../../services/api';+import RetiredModelPinsPanel from './RetiredModelPinsPanel.jsx';++const STALE = {+ pins: [{+ id: 'settings:imageGen.agy.model',+ kind: 'imageGen',+ mode: 'agy',+ providerId: 'antigravity-cli',+ model: 'gemini-3.5-flash-low',+ label: 'Agy CLI image model',+ location: 'Settings → Media Gen → Image Gen',+ href: '/media/image?settings=1',+ }],+ providers: {+ 'antigravity-cli': { id: 'antigravity-cli', name: 'Antigravity CLI', available: ['gemini-3.6-flash'] },+ },+};++const renderPanel = (props = {}) =>+ render(<MemoryRouter><RetiredModelPinsPanel {...props} /></MemoryRouter>);++beforeEach(() => vi.clearAllMocks());++describe('RetiredModelPinsPanel', () => {+ it('names the stale pin, where it lives, and what the catalog now offers', async () => {+ api.getModelPinWarnings.mockResolvedValue(STALE);+ renderPanel();++ // Composed from the client's own registries, so the panel and the Settings+ // page it deep-links to name the same row the same way.+ expect(await screen.findByText('Agy image model:')).toBeTruthy();+ expect(screen.getByText('gemini-3.5-flash-low')).toBeTruthy();+ expect(screen.getByText(/Settings → Media Gen → Image Gen/)).toBeTruthy();+ expect(screen.getByText(/Now offered: gemini-3.6-flash/)).toBeTruthy();+ expect(screen.getByRole('link', { name: 'Open setting' })).toHaveAttribute(+ 'href', '/media/image?settings=1',+ );+ });++ it('names a render-default pin by its Settings label, not its raw target id', async () => {+ api.getModelPinWarnings.mockResolvedValue({+ pins: [{+ id: 'settings:renderDefaults.universe-bible.imageModel',+ kind: 'renderDefault',+ target: 'universe-bible',+ providerId: 'antigravity-cli',+ model: 'gemini-3.5-flash-low',+ label: 'universe-bible render model',+ location: 'Settings → Media Gen → Render Defaults',+ }],+ providers: {},+ });+ renderPanel();++ expect(await screen.findByText('Universe Bible & canon renders — model:')).toBeTruthy();+ });++ it('renders nothing on a healthy install', async () => {+ api.getModelPinWarnings.mockResolvedValue({ pins: [], providers: {} });+ const { container } = renderPanel();+ await waitFor(() => expect(api.getModelPinWarnings).toHaveBeenCalled());+ expect(container).toBeEmptyDOMElement();+ });++ it('stays hidden rather than erroring when the audit cannot be read', async () => {+ // A provider service that isn't up yet is not something to shout about on a+ // page the user opened to look at providers.+ api.getModelPinWarnings.mockRejectedValue(new Error('service down'));+ const { container } = renderPanel();+ await waitFor(() => expect(api.getModelPinWarnings).toHaveBeenCalled());+ expect(container).toBeEmptyDOMElement();+ });++ it('clears only the pin the user clicked, and never rewrites it to another model', async () => {+ api.getModelPinWarnings.mockResolvedValue(STALE);+ api.clearModelPin.mockResolvedValue({ cleared: true, id: 'settings:imageGen.agy.model' });+ renderPanel();++ fireEvent.click(await screen.findByRole('button', { name: 'Clear pin' }));++ await waitFor(() => expect(api.clearModelPin).toHaveBeenCalledWith('settings:imageGen.agy.model'));+ // Exactly one write, naming the pin — no substitute model id anywhere in it.+ expect(api.clearModelPin).toHaveBeenCalledTimes(1);+ await waitFor(() => expect(screen.queryByText('Agy image model:')).toBeNull());+ // The write already landed, so the row goes without a second audit read.+ expect(api.getModelPinWarnings).toHaveBeenCalledTimes(1);+ });++ it('keeps the row when the clear fails, so the warning is not silently lost', async () => {+ api.getModelPinWarnings.mockResolvedValue(STALE);+ api.clearModelPin.mockRejectedValue(new Error('write failed'));+ renderPanel();++ fireEvent.click(await screen.findByRole('button', { name: 'Clear pin' }));++ await waitFor(() => expect(api.clearModelPin).toHaveBeenCalled());+ expect(await screen.findByText('Agy image model:')).toBeTruthy();+ });++ it('re-reads when the caller signals a catalog refresh landed', async () => {+ api.getModelPinWarnings.mockResolvedValue({ pins: [], providers: {} });+ const { rerender } = renderPanel({ reloadKey: 0 });+ await waitFor(() => expect(api.getModelPinWarnings).toHaveBeenCalledTimes(1));++ api.getModelPinWarnings.mockResolvedValue(STALE);+ rerender(<MemoryRouter><RetiredModelPinsPanel reloadKey={1} /></MemoryRouter>);++ expect(await screen.findByText('Agy image model:')).toBeTruthy();+ });+});diff --git a/client/src/pages/AIProviders.jsx b/client/src/pages/AIProviders.jsxindex e303e3d73d..fa2b9bb929 100644--- a/client/src/pages/AIProviders.jsx+++ b/client/src/pages/AIProviders.jsx@@ -23,6 +23,7 @@ import FleetProviderSetup from '../components/providers/FleetProviderSetup';import FleetHostSetup from '../components/providers/FleetHostSetup';import LocalPersistentMindSetupCard from '../components/settings/LocalPersistentMindSetupCard.jsx';import ProviderConnections from '../components/providers/ProviderConnections';+import RetiredModelPinsPanel from '../components/providers/RetiredModelPinsPanel';// The two local apps an API provider can front. Their installer lives on the// Models → LLMs page (it starts the service too), so the provider card@@ -88,6 +89,10 @@ export default function AIProviders() {const [loading, setLoading] = useState(true);const [loadError, setLoadError] = useState(false);const [testResults, setTestResults] = useState({});+ // Bumped after every catalog refresh so the retired-pin panel re-reads: a+ // refresh is the moment a retirement becomes observable, and the pin that+ // just rotted should surface without the user reloading the page.+ const [modelPinReloadKey, setModelPinReloadKey] = useState(0);const [refreshing, setRefreshing] = useState({});// `undefined` = this page has not asked the account endpoint yet; `null` =// the endpoint did not give a verdict. The distinction keeps a failed fetch@@ -500,6 +505,7 @@ export default function AIProviders() {// The catalog a card just learned is graded by the readiness checklist,// which the server computes from the stored record.loadReadiness();+ setModelPinReloadKey(key => key + 1);} else {toast.error('Failed to refresh models - provider may not support this feature');}@@ -774,6 +780,10 @@ export default function AIProviders() {<div className="flex-1 overflow-auto p-4 space-y-6">+ {/* A retirement only becomes observable when a catalog refresh lands, so+ the panel re-reads on every refresh — see RetiredModelPinsPanel. */}+ <RetiredModelPinsPanel reloadKey={modelPinReloadKey} />+<LocalPersistentMindSetupCard compact onApplied={loadData} /><FleetHostSetup compact providers={providers} />diff --git a/client/src/pages/AIProviders.test.jsx b/client/src/pages/AIProviders.test.jsxindex 2fc9de3d02..c2abd300f4 100644--- a/client/src/pages/AIProviders.test.jsx+++ b/client/src/pages/AIProviders.test.jsx@@ -21,6 +21,10 @@ const api = vi.hoisted(() => ({createProvider: vi.fn(),updateProvider: vi.fn(),refreshProviderModels: vi.fn(),+ // The retired-model-pin panel reads on mount. Resolved empty so a healthy+ // install renders nothing extra — the panel has its own suite.+ getModelPinWarnings: vi.fn().mockResolvedValue({ pins: [], providers: {} }),+ clearModelPin: vi.fn(),setActiveProvider: vi.fn().mockResolvedValue({}),getOrchestrationProfiles: vi.fn().mockResolvedValue({ profiles: [] }),createRun: vi.fn().mockResolvedValue({ runId: 'run-1' }),diff --git a/client/src/services/apiProviders.js b/client/src/services/apiProviders.jsindex 3d9732dea9..607b0be13e 100644--- a/client/src/services/apiProviders.js+++ b/client/src/services/apiProviders.js@@ -22,6 +22,17 @@ export const deleteProvider = (id) => request(`/providers/${id}`, { method: 'DELexport const getSampleProviders = () => request('/providers/samples');export const testProvider = (id) => request(`/providers/${id}/test`, { method: 'POST' });export const refreshProviderModels = (id, options) => request(`/providers/${id}/refresh-models`, { method: 'POST', ...options });+// Stored model pins naming a model their provider no longer lists (#7315).+// Derived on read, so it reflects a pin cleared a moment ago without a refresh.+export const getModelPinWarnings = (options) => request('/providers/model-pins', options);+// Clear ONE stale pin back to "inherit". PortOS never rewrites a user's pin on+// its own — it surfaces the retirement and this is the user's one-click undo.+export const clearModelPin = (pinId, options) => request('/providers/model-pins/clear', {+ method: 'POST',+ body: JSON.stringify({ pinId }),+ ...options,+});+// Which provider runtimes (claude, codex, opencode, …) are runnable on this// host, and which of them PortOS can install for you. Installs happen only// after an explicit Providers-page click; the status payload carries booleansdiff --git a/docs/API.md b/docs/API.mdindex e9fa8b70c7..816e5e8fe7 100644--- a/docs/API.md+++ b/docs/API.md@@ -124,6 +124,8 @@ legacy list for local Apps/Dashboard views.| GET | `/providers/readiness` | Requirements checklist per provider backed by a LOCAL daemon (llama.cpp / Ollama / LM Studio / MTPLX), keyed by provider id: is the daemon installed, is it answering at the endpoint THIS provider points at, and is it serving the provider's default model. Each entry also carries `setup` — what the one-click fix below can do about the unmet checks (`null` when nothing is auto-fixable here). Providers with no local dependency are absent from the map. Complements `/providers/runtimes` (which answers "can PortOS run this CLI?"). Booleans, labels, and the provider's own endpoint only — never a resolved binary path. Skips disabled providers; 15s endpoint-probe cache (one probe per distinct endpoint), 60s binary-PATH cache, both dropped by the llama-server start/stop/install routes. || POST | `/providers/readiness/setup?provider=<id>` | Install and/or start the LOCAL DAEMON that provider points at (llama.cpp / Ollama / LM Studio / MTPLX), streaming progress as SSE — the "do it for me" half of `/providers/readiness`, so an unmet requirement is fixed from the card instead of from a vendor setup doc. The request names a PROVIDER only: the runtime kind and endpoint are re-derived server-side from the stored record, so no query value reaches a spawn argument (an optional `runtime=` is cross-checked and 409s on a mismatch). Every command comes from a fixed per-runtime table. Never downloads model weights, never starts llama-server (it needs a checkpoint you choose), and never runs MTPLX's privileged fan-control helper. Single-flight. || POST | `/providers/readiness/serve-model?provider=<id>` | Relaunch the local daemon so it answers under the model id THIS provider sends — the other half of the readiness model mismatch. `llama-server` serves one model per process under the `--alias` on its launch line, so the fix keeps the loaded weights and changes only the name; the whole launch line is carried forward and the previous one restored if the relaunch is rejected or never answers. The model id is re-derived server-side from the stored record. 400s for a runtime that has no such label (Ollama / LM Studio / MTPLX name a model after its weights), 409s when PortOS did not start the daemon. |+| GET | `/providers/model-pins` | Stored model pins naming a model their provider no longer lists. A vendor retires an id, the install's catalog refresh picks that up, and every pin still naming it rots silently until a render or a scheduled run dies with a raw vendor error. Answers `{ pins, providers }` — each pin carries where it lives and a deep link, and `providers` carries only the catalogs a stale pin actually names. Covers the Image Gen and render-default settings pins plus global and per-app scheduled-task pins. Derived on read, never persisted, so a pin cleared a moment ago is already gone from the answer and one that rotted before this shipped is reported on the first read. Every UNKNOWN case (no pin, empty catalog, unresolved provider) reads as "still listed" — a false "your pin is gone" tells the user to change a setting that works. |+| POST | `/providers/model-pins/clear` | Clear ONE stale pin back to "inherit", named by the `pinId` the endpoint above reported. PortOS re-points only the shipped default it owns; a pin the USER chose is surfaced and never rewritten, because substituting it would render under the chosen model's name and bury the vendor's own "unknown model" error. Clears the model field only, never the sibling mode/provider/enabled choices. An id naming a pin that is already gone answers `{ cleared: false }` rather than 404ing, and an id matching no collected pin reaches no writer. || GET | `/providers/codex/account?fresh=1` | Is a ChatGPT subscription signed in, and usable right now? Answers `{ readiness }` with a `status` of `runtime-missing` / `unknown` / `signed-out` / `login-pending` / `ready` / `quota-exhausted` / `reauth-required`, plus the plan name and quota percentages. Read from the Codex app-server's own `account/read` — PortOS never opens Codex's credential file and the payload carries no token, account id, or credential path. This is the ONLY call that may spawn `codex app-server`, and it runs from an explicit page fetch: nothing on the boot path calls it, and `GET /providers` decorates its Codex cards from the cached snapshot only. `fresh=1` skips the 15s TTL for the poll after a sign-in. || POST | `/providers/codex/account/login` | Start an explicit ChatGPT sign-in. Returns `{ login }` — a bounded `loginId` plus `authUrl` (browser flow) or `verificationUrl` + `userCode` (device-code flow, via `{ "deviceCode": true }`). A POST because it begins an OAuth flow; never a side effect of a read. 409s while another sign-in is already pending. || POST | `/providers/codex/account/login/cancel` | Abandon the pending sign-in named by `{ loginId }`, then re-read. 409s for an id that is not the pending login, so a stale tab cannot cancel a flow the user started afterwards. |diff --git a/server/lib/README.md b/server/lib/README.mdindex 558e5681d1..e11949a433 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -206,6 +206,7 @@ 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`. || `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. |diff --git a/server/lib/importScoping.test.js b/server/lib/importScoping.test.jsindex 4d2f8a5f16..19127a5520 100644--- a/server/lib/importScoping.test.js+++ b/server/lib/importScoping.test.js@@ -501,7 +501,22 @@ describe('deferred imports stay deferred (#6156)', () => {// covers it (services/decksSync.db.test.js) measures a further +40, all of it// that one new test file's own closure — decks.js plus the syncWire/db-gate// leaves it asserts against, no production edge. Raise by exactly those deltas.-const MAX_STATIC_INSTANTIATIONS = 103995;+// Surfacing stored model pins the provider catalog has retired (#7315) measures+// +38. 11 are the modelPinReconcile leaf suite's own closure: the leaf plus+// providerModels.js and its leaves, plus localProviderRuntime.js — the leaf+// delegates its base membership rule to that module's `modelPinIsOffered`+// rather than re-deriving it, which is what gives the audit the local-daemon+// carve-out (an Ollama-backed provider's stored `models` is a stale snapshot,+// so judging a pin against it reports a serving model as retired). 4 are the+// route suite, which reaches the route through a dynamic import and statically+// pulls only express and two error/test leaves. The audit suite adds nothing —+// it reaches everything through vi.mock + await import. The rest is+// routes/providers.js gaining services/modelPinAudit.js, whose own closure is+// 34 light files: settings.js (already reached), imageGenCapabilities.js, and+// dependency-free leaves. Its three HEAVY stores — apps.js, taskSchedule.js,+// providers.js — stay behind memoized call-site `await import()`, without which+// that one edge alone measured +449.+const MAX_STATIC_INSTANTIATIONS = 104033;const SKIP_DIRS = new Set(['node_modules', 'coverage', 'dist', 'data']);diff --git a/server/lib/index.js b/server/lib/index.jsindex b278432e0c..5e6cdedb56 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 './modelPinReconcile.js';export * from './modelPricing.js';export * from './navManifest.js';export * from './noReplaceMove.js';diff --git a/server/lib/modelPinReconcile.js b/server/lib/modelPinReconcile.jsnew file mode 100644index 0000000000..8956d83fb8--- /dev/null+++ b/server/lib/modelPinReconcile.js@@ -0,0 +1,138 @@+/**+ * Retired-model-pin reconciliation (#7315).+ *+ * A vendor retires a model id, the install's catalog refresh picks that up, and+ * every stored pin still naming the retired id keeps sitting in settings —+ * rotting silently until a render or a scheduled run dies with a raw vendor+ * error naming a model the user no longer remembers choosing. That already+ * happened once to the ONE pin PortOS owns (`AGY_IMAGEGEN_DEFAULT_MODEL`, fixed+ * in #7314 by a render-time re-point gated on `modelIsShippedDefault`).+ *+ * A pin PortOS does NOT own cannot be healed the same way. Substituting a+ * user's pin would render something different under their chosen model's name+ * and bury the vendor's own "unknown model" error, so such a pin can only be+ * SURFACED. This leaf is the membership half of that: given a pin and the+ * provider record that serves it, is the id still listed?+ *+ * The comparison is deliberately STATE-BASED ("is this pin in today's+ * catalog?") rather than a diff of one refresh against the previous one. The+ * diff form only ever notices retirements that happen after it ships, so every+ * pin that rotted before — including the ones this issue was filed about — stays+ * invisible until the vendor happens to retire something else. It is also+ * idempotent: clearing a pin makes its warning disappear immediately instead of+ * waiting for the next refresh, and nothing has to be persisted, migrated, or+ * kept from federating.+ *+ * Pure leaf (nothing outside `server/lib`, no Node built-ins) so the audit+ * service, the route, and the suite can all share one membership rule.+ */++import { modelPinIsOffered } from './localProviderRuntime.js';+import {+ antigravityBaseModels,+ antigravityCatalogListsModel,+ filterSelectableModels,+ isAntigravityProvider,+ isConfiguredDefaultModel,+} from './providerModels.js';++/**+ * The string model ids a provider record actually lists, with the+ * "use the CLI's own default" sentinels dropped — they are a posture, not a+ * model, and can never be the thing a pin names.+ * Private: `catalogOfferings` is the public view, and a caller wanting the raw+ * listed ids already has `filterSelectableModels`.+ * @param {{models?: unknown[]}|null|undefined} provider+ * @returns {string[]}+ */+function catalogModelIds(provider) {+ const models = Array.isArray(provider?.models) ? provider.models : [];+ return filterSelectableModels(models.filter((m) => typeof m === 'string'));+}++/**+ * The user-facing "what the catalog now offers" list for a provider: agy's+ * family collapses to base ids (the effort tier rides on `--effort`, so+ * `gemini-3.6-flash-low` is not a different model to pick), everything else is+ * its listed ids verbatim.+ * @param {{models?: unknown[]}|null|undefined} provider+ * @returns {string[]}+ */+export function catalogOfferings(provider) {+ const ids = catalogModelIds(provider);+ return isAntigravityProvider(provider) ? antigravityBaseModels(ids) : ids;+}++/**+ * 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.+ *+ * 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 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.+ *+ * @param {{id?:string, command?:string, models?:unknown[]}|null|undefined} provider+ * @param {string|null|undefined} modelId+ * @returns {boolean}+ */+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));+}++/**+ * Which of `pins` name a model their provider no longer lists.+ *+ * A pin descriptor is `{ id, providerId, model, label, location, ... }`; every+ * field rides through onto the warning untouched so a collector can carry+ * whatever the UI needs (a deep link, a clearability flag) without this leaf+ * knowing about it. Warnings are returned in the order the pins were given, so+ * a stable collector order yields a stable panel.+ *+ * `providers` is the provider records keyed by id. A pin naming a provider that+ * is not in the map is left alone — see `providerCatalogListsModel`.+ *+ * @param {Array<{id:string, providerId:string, model:string}>} pins+ * @param {Record<string, {id?:string, name?:string, models?:unknown[]}>} providers+ * @returns {Array<object>}+ */+export function reconcileModelPins(pins, providers) {+ const byId = providers && typeof providers === 'object' ? providers : {};+ return (Array.isArray(pins) ? pins : [])+ .filter((pin) => pin && typeof pin.model === 'string' && pin.model.trim() !== '')+ .filter((pin) => !providerCatalogListsModel(byId[pin.providerId], pin.model))+ .map((pin) => ({ ...pin, model: pin.model.trim() }));+}diff --git a/server/lib/modelPinReconcile.test.js b/server/lib/modelPinReconcile.test.jsnew file mode 100644index 0000000000..c9a7ae75b3--- /dev/null+++ b/server/lib/modelPinReconcile.test.js@@ -0,0 +1,121 @@+import { describe, it, expect } from 'vitest';+import {+ catalogOfferings,+ providerCatalogListsModel,+ reconcileModelPins,+} from './modelPinReconcile.js';+import { ANTIGRAVITY_CONFIGURED_DEFAULT } from './providerModels.js';++const AGY = {+ id: 'antigravity-cli',+ command: 'agy',+ models: ['gemini-3.6-flash-low', 'gemini-3.6-flash-high', 'claude-sonnet-4-6'],+};+const CODEX = { id: 'codex', command: 'codex', models: ['gpt-5-codex', 'gpt-5'] };++describe('providerCatalogListsModel', () => {+ it('reports a retired agy pin as unlisted, and a live one as listed', () => {+ // The incident this issue was filed about: a tier the vendor dropped.+ expect(providerCatalogListsModel(AGY, 'gemini-3.5-flash-low')).toBe(false);+ expect(providerCatalogListsModel(AGY, 'gemini-3.6-flash-low')).toBe(true);+ });++ it('compares the agy family on BASE ids, so an effort tier is not a retirement', () => {+ // `--effort` carries the tier, so `gemini-3.6-flash` and its suffixed+ // variants are the same `--model` value. A base-blind exact match would+ // report both of these as retired.+ expect(providerCatalogListsModel(AGY, 'gemini-3.6-flash')).toBe(true);+ expect(providerCatalogListsModel(AGY, 'gemini-3.6-flash-medium')).toBe(true);+ });++ it('matches non-agy providers exactly', () => {+ expect(providerCatalogListsModel(CODEX, 'gpt-5-codex')).toBe(true);+ expect(providerCatalogListsModel(CODEX, 'gpt-4o')).toBe(false);+ });++ it('tolerates OpenCode namespace addressing in either direction', () => {+ // A pin is stored BARE and namespaced at spawn (`prefixOpencodeModel`), so a+ // catalog holding the qualified form is the same model, not a retirement.+ const opencode = { id: 'opencode', command: 'opencode', models: ['ollama/qwen3:8b'] };+ expect(providerCatalogListsModel(opencode, 'qwen3:8b')).toBe(true);+ expect(providerCatalogListsModel(opencode, 'ollama/qwen3:8b')).toBe(true);+ expect(providerCatalogListsModel(opencode, 'qwen3:14b')).toBe(false);+ });++ it('never reports a LOCAL-daemon pin as retired, even when the record omits it', () => {+ // A local-backed provider's `models` is a stale cached snapshot while the+ // daemon is the authority, so judging a pin against the record would report+ // a model that is installed and serving as retired — and this feature would+ // then offer a one-click button to delete it. Inherited from modelPinIsOffered.+ const ollama = {+ id: 'opencode-ollama',+ command: 'opencode',+ ollamaBacked: true,+ models: ['ollama/qwen3:8b'],+ };+ expect(providerCatalogListsModel(ollama, 'qwen3:32b')).toBe(true);+ // ...while a NON-local provider with the same shaped catalog still reports it.+ expect(providerCatalogListsModel({ ...ollama, ollamaBacked: false }, 'qwen3:32b')).toBe(false);+ });++ describe('every unknown answer reads as "still listed"', () => {+ // A false "your pin is gone" tells the user to change a setting that works,+ // which is strictly worse than missing one.+ // One row per distinct branch — a whitespace/null pin lands on the same+ // guard as a blank one, and an absent catalog on the same guard as an empty.+ it.each([+ ['a blank pin', AGY, ''],+ ['a configured-default sentinel', AGY, ANTIGRAVITY_CONFIGURED_DEFAULT],+ ['an empty catalog', { ...AGY, models: [] }, 'gemini-3.5-flash-low'],+ ['a sentinel-only catalog', { ...AGY, models: [ANTIGRAVITY_CONFIGURED_DEFAULT] }, 'gemini-3.5-flash-low'],+ ['no provider record', null, 'gemini-3.5-flash-low'],+ ])('%s', (_label, provider, model) => {+ expect(providerCatalogListsModel(provider, model)).toBe(true);+ });+ });+});++describe('catalogOfferings', () => {+ it('drops sentinels and non-strings from what it offers', () => {+ const provider = { ...CODEX, models: ['gpt-5', ANTIGRAVITY_CONFIGURED_DEFAULT, null, { id: 'x' }] };+ expect(catalogOfferings(provider)).toEqual(['gpt-5']);+ });++ it('offers agy base ids, since the effort tier is not a separate choice', () => {+ expect(catalogOfferings(AGY)).toEqual(['gemini-3.6-flash', 'claude-sonnet-4-6']);+ expect(catalogOfferings(CODEX)).toEqual(['gpt-5-codex', 'gpt-5']);+ });+});++describe('reconcileModelPins', () => {+ const providers = { 'antigravity-cli': AGY, codex: CODEX };++ it('returns only the pins whose provider no longer lists them, in input order', () => {+ const pins = [+ { id: 'a', providerId: 'antigravity-cli', model: 'gemini-3.5-flash-low' },+ { id: 'b', providerId: 'codex', model: 'gpt-5-codex' },+ { id: 'c', providerId: 'codex', model: 'gpt-4o' },+ ];+ expect(reconcileModelPins(pins, providers).map((p) => p.id)).toEqual(['a', 'c']);+ });++ it('carries every descriptor field through to the warning, and trims the model', () => {+ const pin = {+ id: 'a', providerId: 'codex', model: ' gpt-4o ', label: 'L', location: 'Loc', href: '/x',+ };+ expect(reconcileModelPins([pin], providers)).toEqual([{ ...pin, model: 'gpt-4o' }]);+ });++ it('leaves a pin alone when its provider is not in the map', () => {+ // The provider record is gone — a different problem, and nothing to compare+ // the pin against.+ const pins = [{ id: 'a', providerId: 'deleted-provider', model: 'gpt-4o' }];+ expect(reconcileModelPins(pins, providers)).toEqual([]);+ });++ it('tolerates absent/garbage inputs rather than throwing on a page load', () => {+ expect(reconcileModelPins(null, providers)).toEqual([]);+ expect(reconcileModelPins([null, { id: 'a' }, { id: 'b', model: ' ' }], providers)).toEqual([]);+ expect(reconcileModelPins([{ id: 'a', providerId: 'codex', model: 'gpt-4o' }], null)).toEqual([]);+ });+});diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 6183dc714a..fe525a3544 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -568,6 +568,15 @@ export const codexLoginStartSchema = z.object({deviceCode: z.boolean().optional().default(false),});+// POST /api/providers/model-pins/clear (#7315) — clear ONE stored model pin+// back to "inherit" by the id `GET /model-pins` reported. Addressed by pin id+// rather than a "clear everything stale" verb so an audit landing between the+// user's click and this write cannot widen what they approved. The id is+// resolved against a freshly collected pin list, so this bounds the shape only.+export const modelPinClearSchema = z.object({+ pinId: z.string().trim().min(1).max(300),+});+// POST /api/providers/bindings/:id/link (and /link/preview).//// Every revision the caller reviewed is named explicitly. Omitting one isdiff --git a/server/routes/providers.js b/server/routes/providers.jsindex 96f99d3c1e..f2ec01da1e 100644--- a/server/routes/providers.js+++ b/server/routes/providers.js@@ -17,6 +17,7 @@ import {import { Router } from 'express';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { testVision, runVisionTestSuite, checkVisionHealth } from '../services/visionTest.js';+import { auditModelPins, clearModelPin } from '../services/modelPinAudit.js';import { providerSchema, providerActiveSchema, validate } from '../lib/aiToolkit/validation.js';import { withRefreshCapability } from '../lib/aiToolkit/internal/modelFetchers.js';import { ALLOWED_COMMANDS } from '../cos-runner/allowedCommands.js';@@ -26,6 +27,7 @@ import {validateRequest,codexLoginCancelSchema,codexLoginStartSchema,+ modelPinClearSchema,providerVisionTestSchema,providerVisionSuiteSchema,providerBindingCreateSchema,@@ -798,6 +800,22 @@ export function createPortOSProviderRoutes(aiToolkit) {: publicStatus;};+ // GET /model-pins — stored model pins naming a model their provider no longer+ // lists (#7315). Registered BEFORE '/:id' so the literal path is not read as a+ // provider id. Derived on read, never persisted: see services/modelPinAudit.js.+ router.get('/model-pins', asyncHandler(async (_req, res) => {+ res.json(await auditModelPins());+ }));++ // POST /model-pins/clear — clear ONE pin back to "inherit". A pin is the+ // user's own choice, so PortOS surfaces a retirement and never rewrites it;+ // this is that one-click clear. Clearing a pin that is already gone is a+ // success with `cleared: false`, not a 404 — the outcome the caller wanted.+ router.post('/model-pins/clear', asyncHandler(async (req, res) => {+ const { pinId } = validateRequest(modelPinClearSchema, req.body ?? {});+ res.json(await clearModelPin(pinId));+ }));+router.get('/status', asyncHandler(async (req, res) => {const statuses = providerStatusService.getAllStatuses();// Enrich with time until recoverydiff --git a/server/routes/providers.modelPins.test.js b/server/routes/providers.modelPins.test.jsnew file mode 100644index 0000000000..0a6306c437--- /dev/null+++ b/server/routes/providers.modelPins.test.js@@ -0,0 +1,54 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express, { Router } from 'express';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';++const auditModelPins = vi.hoisted(() => vi.fn());+const clearModelPin = vi.hoisted(() => vi.fn());+vi.mock('../services/modelPinAudit.js', () => ({ auditModelPins, clearModelPin }));++const { createPortOSProviderRoutes } = await import('./providers.js');++const app = () => {+ const toolkit = { services: { providers: {} }, routes: { providers: Router() } };+ const instance = express();+ instance.use(express.json());+ instance.use('/api/providers', createPortOSProviderRoutes(toolkit));+ instance.use(errorMiddleware);+ return instance;+};++beforeEach(() => vi.clearAllMocks());++describe('GET /model-pins', () => {+ it('serves the audit, and is not swallowed by the /:id provider route', async () => {+ // The literal path is registered BEFORE '/:id'; registered after, this would+ // 404 as "no provider named model-pins".+ auditModelPins.mockResolvedValue({ pins: [{ id: 'settings:imageGen.agy.model' }], providers: {} });++ const res = await request(app()).get('/api/providers/model-pins');++ expect(res.status).toBe(200);+ expect(res.body.pins).toEqual([{ id: 'settings:imageGen.agy.model' }]);+ });+});++describe('POST /model-pins/clear', () => {+ it('clears the named pin', async () => {+ clearModelPin.mockResolvedValue({ cleared: true, id: 'task:audit' });++ const res = await request(app()).post('/api/providers/model-pins/clear').send({ pinId: 'task:audit' });++ expect(res.status).toBe(200);+ expect(res.body).toEqual({ cleared: true, id: 'task:audit' });+ expect(clearModelPin).toHaveBeenCalledWith('task:audit');+ });++ it('rejects a body with no pin id before reaching the service', async () => {+ const res = await request(app()).post('/api/providers/model-pins/clear').send({});++ expect(res.status).toBe(400);+ expect(clearModelPin).not.toHaveBeenCalled();+ });++});diff --git a/server/services/modelPinAudit.js b/server/services/modelPinAudit.jsnew file mode 100644index 0000000000..36f98419c2--- /dev/null+++ b/server/services/modelPinAudit.js@@ -0,0 +1,319 @@+/**+ * Retired-model-pin audit (#7315).+ *+ * Collects every stored model pin PortOS does NOT own, asks+ * `lib/modelPinReconcile.js` whether the provider still lists it, and returns+ * the ones that have rotted — so a Settings surface can say "this pin names a+ * model your provider no longer serves" instead of letting a render or a+ * scheduled run die on a raw vendor error months later.+ *+ * **Surface, never auto-rewrite.** A user's pin is a deliberate choice;+ * substituting one would render something different under the chosen model's+ * name (the behavior #7314 explicitly rejected). Clearing a pin back to+ * "inherit" is a one-click action the user takes — `clearModelPin` below — and+ * nothing here writes on its own.+ *+ * **Derived on read, never persisted.** The audit is a pure function of the+ * stores it reads, so there is no record to migrate, seed, keep in sync with a+ * refresh, or keep off the federation layer — and a pin that rotted BEFORE this+ * shipped is reported on the first read rather than waiting for the next+ * retirement. See modelPinReconcile.js for why that beats diffing one refresh+ * against the previous one.+ *+ * **Adding a pin source is one row in `PIN_SOURCES`.** Each row pairs the+ * collector that finds those pins with the writer that clears one, so a source+ * cannot be half-registered — the failure mode when the two halves were+ * separate tables was a Clear button that threw at click time.+ */++import { ANTIGRAVITY_CLI_ID } from '../lib/antigravity.js';+import { CODEX_CLI_ID } from '../lib/codex.js';+import { IMAGE_GEN_MODE } from '../lib/generationModes.js';+import { MODEL_OVERRIDE_CAPABLE_MODES } from '../lib/imageGenCapabilities.js';+import { catalogOfferings, reconcileModelPins } from '../lib/modelPinReconcile.js';+import { normalizeRenderPinValue, RENDER_TARGETS } from '../lib/renderTargets.js';+import { getSettings, updateSettingsWith } from './settings.js';++/**+ * The pin STORES are reached through deferred imports, not top-level ones.+ *+ * This module is imported eagerly by `routes/providers.js`, and `apps.js` /+ * `taskSchedule.js` / `providers.js` each drag a heavy subtree behind them —+ * enough to push the server suite past its static-instantiation budget+ * (`lib/importScoping.test.js`, and the "Import scoping" section of+ * server/AGENTS.md). The audit is a user-triggered read, so paying for those+ * trees at call time costs nothing anybody is waiting on.+ *+ * Each loader memoizes the PROMISE rather than the resolved module: two+ * collectors reach for `taskSchedule.js` inside the same `Promise.all`, and+ * concurrent `import()` calls of a mocked module can let one caller escape the+ * mock unless they share a single in-flight promise.+ */+let appsModule = null;+let providersModule = null;+let taskScheduleModule = null;+const loadAppsModule = () => (appsModule ||= import('./apps.js'));+const loadProvidersModule = () => (providersModule ||= import('./providers.js'));+const loadTaskScheduleModule = () => (taskScheduleModule ||= import('./taskSchedule.js'));++/**+ * Which provider record serves each cloud image-gen mode that can carry a pin.+ *+ * The mode SET is derived from `MODEL_OVERRIDE_CAPABLE_MODES` rather than+ * hand-listed, so a third override-capable backend cannot land a capability+ * entry and then be silently un-audited — the guard in this module's suite+ * fails when a mode gains `supportsModelOverride` with no row here. Grok is+ * absent on its own merits: its image backend is fixed, so there is no pin.+ *+ * The mode -> provider-record-id fact itself has no registry today+ * (`CLOUD_PROVIDER_SPECS` carries label/params but no provider id, and+ * imageGen/agy.js hardcodes its own), so it lives here as one map of the two+ * fields rather than two maps over the same keys.+ */+const PINNED_IMAGE_MODES = Object.freeze({+ [IMAGE_GEN_MODE.AGY]: { providerId: ANTIGRAVITY_CLI_ID, label: 'Agy CLI' },+ [IMAGE_GEN_MODE.CODEX]: { providerId: CODEX_CLI_ID, label: 'Codex CLI' },+});++/** Exported for the coverage guard above — not a runtime dependency. */+export const PINNED_IMAGE_MODE_IDS = Object.freeze(Object.keys(PINNED_IMAGE_MODES));+export { MODEL_OVERRIDE_CAPABLE_MODES };++const trimmed = (value) => (typeof value === 'string' ? value.trim() : '');++/**+ * One pin descriptor, or nothing when either half of the pair is missing.+ *+ * A pin with no model is not a pin, and a pin whose provider cannot be named is+ * not judgeable — `reconcileModelPins` would have to guess which catalog to+ * compare it against, and a wrong guess is a false retirement. Returns an array+ * so every collector can stay a single `flatMap`.+ */+const pinIf = ({ model, providerId, ...rest }) => {+ const id = trimmed(model);+ const provider = trimmed(providerId);+ return id && provider ? [{ ...rest, model: id, providerId: provider }] : [];+};++/** `settings.imageGen.<mode>.model` — the install-wide Image Gen pins. */+function collectImageGenPins({ settings }) {+ return Object.entries(PINNED_IMAGE_MODES).flatMap(([mode, { providerId, label }]) => pinIf({+ id: `settings:imageGen.${mode}.model`,+ mode,+ providerId,+ model: settings?.imageGen?.[mode]?.model,+ label: `${label} image model`,+ location: 'Settings → Media Gen → Image Gen',+ href: '/media/image?settings=1',+ }));+}++/**+ * `settings.renderDefaults.<target>.imageModel` — the per-surface pins.+ *+ * Gated on the entry's own `imageMode`: the same field holds a local diffusion+ * checkpoint id when the surface renders locally, and that is not a CLI catalog+ * entry to reconcile against. An entry pinning a model with no mode inherits+ * the install default, whose provider we cannot name from here — left alone+ * rather than guessed at.+ */+function collectRenderDefaultPins({ settings }) {+ return RENDER_TARGETS.flatMap((target) => {+ const entry = settings?.renderDefaults?.[target];+ const mode = normalizeRenderPinValue(entry?.imageMode);+ return pinIf({+ id: `settings:renderDefaults.${target}.imageModel`,+ target,+ providerId: mode ? PINNED_IMAGE_MODES[mode]?.providerId : null,+ model: normalizeRenderPinValue(entry?.imageModel),+ label: `${target} render model`,+ location: 'Settings → Media Gen → Render Defaults',+ href: '/media/image?settings=1',+ });+ });+}++/** `schedule.tasks.<taskType>.model` — the global scheduled-task pins. */+function collectTaskSchedulePins({ schedule }) {+ return Object.entries(schedule?.tasks || {}).flatMap(([taskType, task]) => pinIf({+ id: `task:${taskType}`,+ taskType,+ providerId: task?.providerId,+ model: task?.model,+ label: `${taskType} task model`,+ location: 'Chief of Staff → Schedule',+ href: '/cos/schedule',+ }));+}++/**+ * Per-app task-type override pins, which OUTRANK the global pin at spawn+ * (#4783). An override that pins a model but no provider runs on whatever the+ * global task pin names, so that is the catalog to judge it against; with+ * neither, the provider is the install's active one and unknowable from here,+ * so the pin is left alone.+ *+ * Reads `taskTypeOverrides` straight off the records `getActiveApps()` already+ * returned rather than calling `getAppTaskTypeOverrides(app.id)` per app. That+ * accessor re-loads the whole apps store TWICE per call and can `atomicWrite`+ * it (its legacy-format migration) — a write in a path this module advertises+ * as derived-on-read. Skipping the migration cannot change the answer: the+ * legacy `disabledTaskTypes` field migrates to `{ enabled: false }` entries+ * that carry no model, so they can never yield a pin.+ */+async function collectAppOverridePins({ schedule }) {+ const { getActiveApps } = await loadAppsModule();+ const apps = await getActiveApps().catch(() => []);+ return (apps || []).flatMap((app) =>+ Object.entries(app?.taskTypeOverrides || {}).flatMap(([taskType, override]) => pinIf({+ id: `app:${app.id}:${taskType}`,+ appId: app.id,+ taskType,+ providerId: trimmed(override?.providerId) || schedule?.tasks?.[taskType]?.providerId,+ model: override?.model,+ label: `${app.name || app.id} · ${taskType} task model`,+ location: 'Chief of Staff → Schedule → per-app overrides',+ href: '/cos/schedule',+ })),+ );+}++/**+ * The pin sources, in the order the panel reads them (install-wide first).+ *+ * ONE table, not a collector list beside a clearer map: the read half and the+ * write half of a pin source belong together, and keying them separately meant+ * a kind registered in one and missed in the other failed only when a user+ * clicked Clear. Adding a pin source is one row.+ *+ * Each `clear` touches the MODEL only — never the sibling mode/provider/enabled+ * fields, which are separate choices the user did not ask to undo.+ */+const PIN_SOURCES = Object.freeze([+ {+ kind: 'imageGen',+ collect: collectImageGenPins,+ clear: (pin) => updateSettingsWith((current) => ({+ ...current,+ imageGen: {+ ...(current.imageGen || {}),+ [pin.mode]: withoutKey(current.imageGen?.[pin.mode], 'model'),+ },+ })),+ },+ {+ kind: 'renderDefault',+ collect: collectRenderDefaultPins,+ clear: (pin) => updateSettingsWith((current) => ({+ ...current,+ renderDefaults: {+ ...(current.renderDefaults || {}),+ [pin.target]: withoutKey(current.renderDefaults?.[pin.target], 'imageModel'),+ },+ })),+ },+ {+ kind: 'task',+ collect: collectTaskSchedulePins,+ clear: async (pin) => {+ const { updateTaskInterval } = await loadTaskScheduleModule();+ return updateTaskInterval(pin.taskType, { model: null });+ },+ },+ {+ kind: 'appOverride',+ collect: collectAppOverridePins,+ clear: async (pin) => {+ const { updateAppTaskTypeOverride } = await loadAppsModule();+ return updateAppTaskTypeOverride(pin.appId, pin.taskType, { model: null });+ },+ },+]);++/**+ * Every stored model pin PortOS does not own, in `PIN_SOURCES` order.+ *+ * Reads each backing store ONCE and hands every collector the same context.+ * Two collectors need the task schedule, and `loadSchedule` is neither memoized+ * nor TTL-cached — it re-parses and re-normalizes the whole file every call,+ * and two concurrent calls that both see `needsSave` each queue their own+ * rewrite of it.+ *+ * A collector that throws must not take the whole audit down with it: one+ * unreadable store is a missing section, not a failed page.+ *+ * @returns {Promise<Array<object>>}+ */+async function collectModelPins() {+ const { loadSchedule } = await loadTaskScheduleModule();+ const [settings, schedule] = await Promise.all([+ getSettings().catch(() => ({})),+ loadSchedule().catch(() => null),+ ]);+ const context = { settings, schedule };+ const collected = await Promise.all(PIN_SOURCES.map(async ({ kind, collect }) => {+ const pins = await Promise.resolve(collect(context)).catch((error) => {+ console.error(`❌ Model pin collector ${kind} failed: ${error.message}`);+ return [];+ });+ return pins.map((pin) => ({ ...pin, kind }));+ }));+ return collected.flat();+}++/**+ * The stale pins, plus the catalog each one's provider now offers.+ *+ * `providers` is keyed by provider id and carries only the providers a stale+ * pin actually names, so a 200-model Ollama catalog is not shipped to a page+ * with no Ollama pin on it.+ *+ * @returns {Promise<{pins: Array<object>, providers: Record<string, object>}>}+ */+export async function auditModelPins() {+ const { listProviders } = await loadProvidersModule();+ // The pin stores and the provider catalog are independent reads.+ const [providerList, pins] = await Promise.all([listProviders(), collectModelPins()]);+ const byId = Object.fromEntries(providerList.map((provider) => [provider.id, provider]));+ const stale = reconcileModelPins(pins, byId);+ const providers = Object.fromEntries(+ [...new Set(stale.map((pin) => pin.providerId))].map((id) => [id, {+ id,+ name: byId[id]?.name || id,+ available: catalogOfferings(byId[id]),+ }]),+ );+ return { pins: stale, providers };+}++/**+ * One parent object with `key` REMOVED — "back to inherit" is the absence of+ * the field, not a blank string sitting where a model id used to be. `''` would+ * also read as no-pin at every resolver, but it survives a settings round-trip+ * and shows up in the file as a value the user never typed.+ */+const withoutKey = (parent, key) => {+ const next = { ...(parent || {}) };+ delete next[key];+ return next;+};++/**+ * Clear ONE pin back to "inherit", by the `id` the audit reported.+ *+ * Deliberately id-addressed rather than "clear everything stale": the user is+ * approving each pin's removal, and an audit read between their click and this+ * write must not widen what they approved. An id naming a pin that is no longer+ * stored resolves to `{ cleared: false }` rather than throwing — the pin is+ * already gone, which is the outcome the caller wanted.+ *+ * @param {string} pinId+ * @returns {Promise<{cleared: boolean, id: string}>}+ */+export async function clearModelPin(pinId) {+ const pins = await collectModelPins();+ const pin = pins.find((candidate) => candidate.id === pinId);+ if (!pin) return { cleared: false, id: pinId };+ await PIN_SOURCES.find((source) => source.kind === pin.kind).clear(pin);+ return { cleared: true, id: pinId };+}diff --git a/server/services/modelPinAudit.test.js b/server/services/modelPinAudit.test.jsnew file mode 100644index 0000000000..d37f402e62--- /dev/null+++ b/server/services/modelPinAudit.test.js@@ -0,0 +1,205 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++vi.mock('./providers.js', () => ({ listProviders: vi.fn() }));+vi.mock('./settings.js', () => ({ getSettings: vi.fn(), updateSettingsWith: vi.fn() }));+vi.mock('./taskSchedule.js', () => ({ loadSchedule: vi.fn(), updateTaskInterval: vi.fn() }));+vi.mock('./apps.js', () => ({+ getActiveApps: vi.fn(),+ updateAppTaskTypeOverride: vi.fn(),+}));++const { listProviders } = await import('./providers.js');+const { getSettings, updateSettingsWith } = await import('./settings.js');+const { loadSchedule, updateTaskInterval } = await import('./taskSchedule.js');+const { getActiveApps, updateAppTaskTypeOverride } = await import('./apps.js');+const {+ auditModelPins, clearModelPin, MODEL_OVERRIDE_CAPABLE_MODES, PINNED_IMAGE_MODE_IDS,+} = await import('./modelPinAudit.js');++// The retirement that motivated #7315: `gemini-3.5-flash-low` is gone, the+// 3.6 tiers replaced it.+const AGY = {+ id: 'antigravity-cli',+ name: 'Antigravity CLI',+ command: 'agy',+ models: ['gemini-3.6-flash-low', 'gemini-3.6-flash-high'],+};+const CODEX = { id: 'codex', name: 'Codex', command: 'codex', models: ['gpt-5-codex'] };++const settingsWith = (overrides) => ({ imageGen: {}, renderDefaults: {}, ...overrides });++beforeEach(() => {+ vi.clearAllMocks();+ listProviders.mockResolvedValue([AGY, CODEX]);+ getSettings.mockResolvedValue(settingsWith({}));+ loadSchedule.mockResolvedValue({ tasks: {} });+ getActiveApps.mockResolvedValue([]);+});++describe('image-gen pin coverage', () => {+ it('audits every cloud mode that can carry a model override', () => {+ // Without this, a third override-capable backend lands a capability entry+ // and is then silently un-audited — its pins would never surface.+ expect([...PINNED_IMAGE_MODE_IDS].sort()).toEqual([...MODEL_OVERRIDE_CAPABLE_MODES].sort());+ });+});++describe('auditModelPins', () => {+ it('reports a retired Settings image-gen pin with where it lives and what is offered', async () => {+ getSettings.mockResolvedValue(settingsWith({+ imageGen: { agy: { enabled: true, model: 'gemini-3.5-flash-low' } },+ }));++ const { pins, providers } = await auditModelPins();++ expect(pins).toHaveLength(1);+ expect(pins[0]).toMatchObject({+ id: 'settings:imageGen.agy.model',+ providerId: 'antigravity-cli',+ model: 'gemini-3.5-flash-low',+ location: 'Settings → Media Gen → Image Gen',+ });+ // Offered as BASE ids — the effort tier rides on `--effort`, so listing both+ // suffixed variants would read as two models to choose between.+ expect(providers['antigravity-cli'].available).toEqual(['gemini-3.6-flash']);+ });++ it('stays silent while every pin is still served', async () => {+ getSettings.mockResolvedValue(settingsWith({+ imageGen: { agy: { model: 'gemini-3.6-flash-low' }, codex: { model: 'gpt-5-codex' } },+ }));+ await expect(auditModelPins()).resolves.toEqual({ pins: [], providers: {} });+ });++ it('ships a catalog only for the providers a stale pin actually names', async () => {+ getSettings.mockResolvedValue(settingsWith({+ imageGen: { agy: { model: 'gemini-3.5-flash-low' }, codex: { model: 'gpt-5-codex' } },+ }));+ const { providers } = await auditModelPins();+ expect(Object.keys(providers)).toEqual(['antigravity-cli']);+ });++ it('judges a renderDefaults pin only when its own mode names a CLI provider', async () => {+ // The same field holds a local diffusion checkpoint when the surface renders+ // locally, and an entry with no mode inherits a default whose provider is+ // unknowable from here. Neither is a retirement.+ getSettings.mockResolvedValue(settingsWith({+ renderDefaults: {+ 'universe-bible': { imageMode: 'agy', imageModel: 'gemini-3.5-flash-low' },+ 'music-video': { imageMode: 'local', imageModel: 'flux-dev-retired' },+ deck: { imageModel: 'gemini-3.5-flash-low' },+ },+ }));+ const { pins } = await auditModelPins();+ expect(pins.map((p) => p.id)).toEqual(['settings:renderDefaults.universe-bible.imageModel']);+ });++ it('reports a scheduled-task pin against the provider the task names', async () => {+ loadSchedule.mockResolvedValue({+ tasks: {+ 'code-review': { providerId: 'antigravity-cli', model: 'gemini-3.5-flash-low' },+ healthy: { providerId: 'codex', model: 'gpt-5-codex' },+ unpinned: { providerId: 'codex', model: null },+ },+ });+ const { pins } = await auditModelPins();+ expect(pins.map((p) => p.id)).toEqual(['task:code-review']);+ });++ it('falls back to the global task provider for an app override that pins only a model', async () => {+ // A per-app override OUTRANKS the global pin at spawn (#4783) but may name+ // only the model, in which case it runs on the global task's provider.+ getActiveApps.mockResolvedValue([{+ id: 'app-1',+ name: 'Example App',+ taskTypeOverrides: { 'code-review': { model: 'gemini-3.5-flash-low' } },+ }]);+ loadSchedule.mockResolvedValue({ tasks: { 'code-review': { providerId: 'antigravity-cli' } } });++ const { pins } = await auditModelPins();+ expect(pins).toHaveLength(1);+ expect(pins[0]).toMatchObject({ id: 'app:app-1:code-review', providerId: 'antigravity-cli' });+ });++ it('leaves an app override alone when no provider can be resolved for it', async () => {+ // With neither pin the task runs on the install's ACTIVE provider, which is+ // not knowable here — guessing would produce a false retirement warning.+ getActiveApps.mockResolvedValue([{+ id: 'app-1',+ name: 'Example App',+ taskTypeOverrides: { 'code-review': { model: 'gemini-3.5-flash-low' } },+ }]);+ await expect(auditModelPins()).resolves.toMatchObject({ pins: [] });+ });++ it('renders the other sections when one store cannot be read', async () => {+ getSettings.mockResolvedValue(settingsWith({ imageGen: { agy: { model: 'gemini-3.5-flash-low' } } }));+ loadSchedule.mockRejectedValue(new Error('schedule unreadable'));+ const { pins } = await auditModelPins();+ expect(pins.map((p) => p.id)).toEqual(['settings:imageGen.agy.model']);+ });+});++describe('clearModelPin', () => {+ it('removes the image-gen model key and leaves its sibling settings untouched', async () => {+ getSettings.mockResolvedValue(settingsWith({+ imageGen: { agy: { enabled: true, agyPath: '/bin/agy', model: 'gemini-3.5-flash-low' } },+ other: 'kept',+ }));++ await expect(clearModelPin('settings:imageGen.agy.model')).resolves.toEqual({+ cleared: true, id: 'settings:imageGen.agy.model',+ });++ const next = updateSettingsWith.mock.calls[0][0](settingsWith({+ imageGen: { agy: { enabled: true, agyPath: '/bin/agy', model: 'gemini-3.5-flash-low' } },+ other: 'kept',+ }));+ // "Back to inherit" is the ABSENCE of the field — a blank string survives a+ // settings round-trip as a value the user never typed.+ expect('model' in next.imageGen.agy).toBe(false);+ expect(next.imageGen.agy).toEqual({ enabled: true, agyPath: '/bin/agy' });+ expect(next.other).toBe('kept');+ });++ it('clears a renderDefaults pin without disturbing its mode', async () => {+ getSettings.mockResolvedValue(settingsWith({+ renderDefaults: { deck: { imageMode: 'agy', imageModel: 'gemini-3.5-flash-low' } },+ }));+ await clearModelPin('settings:renderDefaults.deck.imageModel');+ const next = updateSettingsWith.mock.calls[0][0](settingsWith({+ renderDefaults: { deck: { imageMode: 'agy', imageModel: 'gemini-3.5-flash-low' } },+ }));+ expect(next.renderDefaults.deck).toEqual({ imageMode: 'agy' });+ });++ it('clears a scheduled-task pin through the schedule writer', async () => {+ loadSchedule.mockResolvedValue({ tasks: { audit: { providerId: 'codex', model: 'gpt-4o' } } });+ await clearModelPin('task:audit');+ expect(updateTaskInterval).toHaveBeenCalledWith('audit', { model: null });+ });++ it('clears a per-app override pin through the apps writer', async () => {+ getActiveApps.mockResolvedValue([{+ id: 'app-1',+ name: 'Example App',+ taskTypeOverrides: { audit: { providerId: 'codex', model: 'gpt-4o' } },+ }]);+ await clearModelPin('app:app-1:audit');+ expect(updateAppTaskTypeOverride).toHaveBeenCalledWith('app-1', 'audit', { model: null });+ });++ it('reaches no writer for an id that names no collected pin', async () => {+ // The re-collect is a write-target ALLOWLIST, not just a freshness check:+ // the route bounds `pinId` to a string and nothing more, and+ // `updateTaskInterval` CREATES a task when absent — so a parsed id would+ // let a request mint a schedule entry. An id already cleared takes this+ // same branch and is a success with `cleared: false`, not a 404.+ await expect(clearModelPin('settings:imageGen.agy.model; DROP')).resolves.toEqual({+ cleared: false, id: 'settings:imageGen.agy.model; DROP',+ });+ expect(updateSettingsWith).not.toHaveBeenCalled();+ expect(updateTaskInterval).not.toHaveBeenCalled();+ expect(updateAppTaskTypeOverride).not.toHaveBeenCalled();+ });+});