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
refactor([issue-3620]): collapse the model-refresh vendor dispatch into one table and ship it as canRefreshModels
[._.]/ Adam Eivy645750a82886
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex d8a12e0010..d6e08e6b13 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -34,3 +34,5 @@## Internal- **The six provider-seed migrations share one shell instead of six copies of it.** Every migration that ships a new AI provider to already-installed setups (OpenCode Ollama, its TUI sibling, Grok, Cerebras, Kimi, Cursor) repeated the same byte-identical read → validate → add-missing-ids → write body, so any hardening of it was a six-file sweep nobody did — and none of the six had picked up the reserved-key guard (`__proto__` / `constructor` / `prototype`) the split-migration family already applies. They now call a shared `makeProviderSeedMigration` factory that carries that guard, and each migration keeps only its own frozen provider payload, since a migration is the historical record of what it installed. Their duplicated shell tests collapse into one suite against the factory; every payload assertion each migration already made still runs unchanged.+- **Whether a provider can refresh its model list is now the server's answer, not the client's guess.** The "Refresh Models" button used to be gated by a hand-written client-side re-derivation of the server's model-refresh dispatch — a mirror kept in step by a comment, backed by a parity test that transcribed the same dispatch a *second* time (so it only ever proved the mirror matched the test's copy). It drifted, silently, in both directions: too generous showed a button that errored on every click, too stingy hid the feature with no error at all. A gemini provider configured by absolute path was in the second bucket. The server now derives the answer from one per-vendor table and sends it on the providers payload as `canRefreshModels`; the client just reads it. The three keying conventions that had accumulated as prose above each branch (exact command string, path-tolerant command basename, display-name substring — and which of them a TUI provider is allowed to use) are columns in that table now, so adding the next vendor is one row instead of four coordinated edits across two repos' worth of files. The field is computed per response and never stored, so it can't go stale against the dispatch it describes. No shipped provider's button visibility changes; the one behavior that does is that a provider whose *command* is literally `gemini` now refreshes as gemini even if someone named it "Claude Something", which is the same "an exact command beats a display-name substring" rule the dispatch had already grown for cursor and Antigravity.+>>>>>>> 664e998f3 (refactor([issue-3620]): collapse the model-refresh vendor dispatch into one table and ship it as canRefreshModels)diff --git a/client/src/utils/providers.js b/client/src/utils/providers.jsindex 87db00b417..f51bb60602 100644--- a/client/src/utils/providers.js+++ b/client/src/utils/providers.js@@ -114,93 +114,26 @@ export const isAntigravityProvider = (provider) => {return base === 'agy' || base === 'antigravity';};-/**- * True when a provider command points at Cursor's agent binary. MIRROR of- * `isCursorCommand` in server/lib/cursor.js — keep in lockstep.- *- * Matches ONLY `cursor-agent`, never a bare `cursor`: that is Cursor's GUI- * editor launcher, not the coding agent.- * @param {string|null|undefined} command- * @returns {boolean}- */-export const isCursorCommand = (command) => commandBasename(command) === 'cursor-agent';--/**- * True when a command points at the Antigravity binary. MIRROR of- * `isAntigravityCommand` in server/lib/aiToolkit/internal/antigravity.js — keep- * in lockstep. Distinct from {@link isAntigravityProvider}, which also matches- * the shipped provider IDs: the server's model-refresh dispatch tests the- * COMMAND alone on its TUI arm, so mirroring that needs the narrower predicate.- * @param {string|null|undefined} command- * @returns {boolean}- */-export const isAntigravityCommand = (command) => {- const base = commandBasename(command);- return base === 'agy' || base === 'antigravity';-};-/*** Whether the AI Providers page should offer a "Refresh Models" button for this* provider — i.e. whether the server has a model fetcher that can answer for it.*- * Lives here rather than inside `AIProviders.jsx` so it is unit-testable: as a- * module-local in the page it had no coverage at all, and deleting a clause left- * the suite green while the button came back and error-toasted on every click.+ * Reads the server's own answer off the payload. `canRefreshModels` is derived+ * on read from the per-vendor fetcher table+ * (`server/lib/aiToolkit/internal/modelFetchers.js`) and decorated onto every+ * provider-shaped response in `routes/providers.js`, so there is exactly one+ * definition of "refreshable" and it lives next to the dispatch that has to+ * honor it.*- * MIRRORS the server dispatch in `_refreshCLIProviderModels`- * (server/lib/aiToolkit/providers.js) — a provider the server can't fetch for- * must return false here, or the button 404s. Keep the two in lockstep.- * @param {{type?:string, command?:string, id?:string, name?:string, endpoint?:string}|null|undefined} provider+ * This used to be a ~40-line hand-written mirror of both server dispatch arms,+ * kept in lockstep by a comment. It drifted in both directions: too generous+ * showed a button that 404'd, too stingy hid the feature with no error at all.+ * Strict `=== true` so a legacy payload from an older server (no such field)+ * hides the button rather than offering one that 404s.+ * @param {{canRefreshModels?:boolean}|null|undefined} provider* @returns {boolean}*/-export const supportsModelRefresh = (provider) => {- // Mirrors `refreshProviderModels`, which routes on `provider.type` FIRST and- // only then applies per-vendor tests — so this follows the same two-level- // shape. It is an ALLOWLIST: the server throws for any CLI it has no fetcher- // for. Written as a deny-list previously, it returned true for `codex` and- // `kimi-cli` (both shipped), whose Refresh button 404'd on every click.- const name = String(provider?.name || '').toLowerCase();- const command = provider?.command;-- // Every API provider routes to _refreshAPIProviderModels.- if (isApiProvider(provider)) return true;-- if (isTuiProvider(provider)) {- // A TUI's model is normally fixed by the CLI/config; the server carries- // exactly three exceptions, and — unlike its CLI arm — none consults the- // provider NAME, so this must not either.- return isOllamaBackedProvider(provider)- || provider?.id === 'antigravity-tui'- || isAntigravityCommand(command)- || provider?.id === 'cursor-tui'- || isCursorCommand(command);- }-- if (isCliProvider(provider)) {- if (isOllamaBackedProvider(provider)) return true;- // Command-only, matching the server's cursor arm — which deliberately omits- // a name test so an unrelated provider named e.g. "Cursor Notes" doesn't- // claim a refresh the server would refuse. Kept above the name-substring- // tests to mirror the server's own ordering (see `_refreshCLIProviderModels`):- // there, a renamed "Cursor Claude Opus" must reach the cursor fetcher rather- // than the Anthropic one. Ordering is immaterial to this predicate's boolean- // result — every arm here returns true — but the mirror is only readable, and- // only stays checkable, if it matches the dispatch it claims to mirror.- if (isCursorCommand(command)) return true;- if (isAntigravityCommand(command)) return true;- // Deliberately the RAW command string, not a basename: the server's claude- // and gemini arms compare `provider.command === 'claude'` exactly. Matching- // on basename here would re-open the same 404 in a new place — a renamed,- // path-configured `/opt/homebrew/bin/claude` would show a button the server- // still refuses. Widening BOTH sides is tracked separately; until then the- // mirror stays faithful rather than optimistic.- return name.includes('claude') || command === 'claude'- || name.includes('antigravity')- || name.includes('gemini') || command === 'gemini';- }-- return false;-};+export const supportsModelRefresh = (provider) => provider?.canRefreshModels === true;export const knownProviderContextWindow = (provider) => {if (!isProcessProvider(provider)) return null;diff --git a/client/src/utils/providers.test.js b/client/src/utils/providers.test.jsindex 4e7b4eee45..47508d91a0 100644--- a/client/src/utils/providers.test.js+++ b/client/src/utils/providers.test.js@@ -35,8 +35,6 @@ import {isGrokBuildCli,isKimiProvider,isCodexProvider,- isCursorCommand,- isAntigravityCommand,supportsModelRefresh,isAntigravityProvider,effortLevelsForProvider,@@ -62,6 +60,10 @@ import {} from './providers.js';import { PROVIDER_TYPES as SERVER_PROVIDER_TYPES } from '../../../server/lib/aiToolkit/constants.js';import SHIPPED_PROVIDERS from '../../../data.reference/providers.json';+// The server's own payload decorator, so the shipped-catalog walk below tests+// the REAL derivation instead of a hand transcription of it (#3620). Pure and+// dependency-free — it imports nothing outside the vendored aiToolkit.+import { withRefreshCapabilityList } from '../../../server/lib/aiToolkit/internal/modelFetchers.js';import {effortLevelsForProvider as serverEffortLevelsForProvider,isAntigravityProvider as serverIsAntigravityProvider,@@ -736,152 +738,65 @@ describe('isKimiProvider (mirror of server providerModels)', () => {});describe('supportsModelRefresh', () => {- // Guards the AI Providers page's "Refresh Models" button. Lived as a- // module-local in AIProviders.jsx with zero coverage until it moved here.- // The contract is a MIRROR of the server's `_refreshCLIProviderModels`- // dispatch: anything the server throws for must be false here, or the button- // 404s on every click.- // `_fetchCursorModels` shells `cursor-agent models`, so cursor now refreshes.- // Command-keyed on BOTH arms (path- and `.exe`-tolerant), because the server's- // cursor branch is — a name test would be wrong in the other direction, see- // the "Cursor Notes" case below.- it('offers the button for cursor, including a path-configured binary', () => {- expect(supportsModelRefresh({ id: 'cursor-cli', type: 'cli', command: 'cursor-agent', name: 'Cursor Agent CLI' })).toBe(true);- expect(supportsModelRefresh({ id: 'custom', type: 'cli', command: '/home/x/.local/bin/cursor-agent', name: 'Cursor' })).toBe(true);- });-- it('offers it for the cursor TUI too — `--model` applies to the session', () => {- expect(supportsModelRefresh({ id: 'cursor-tui', type: 'tui', command: 'cursor-agent', name: 'Cursor Agent TUI' })).toBe(true);- expect(supportsModelRefresh({ id: 'cursor-tui', type: 'tui', command: '/home/x/.local/bin/cursor-agent', name: 'renamed' })).toBe(true);- });-- // Pins the `id === '<vendor>-tui'` half of each TUI arm's OR. Every other case- // here matches on the COMMAND, so deleting those id clauses left the suite- // green while a shipped TUI provider repointed at a wrapper script silently- // lost its button (the server's TUI arms still serve it via the same id test).- it('offers it for a shipped cursor-tui / antigravity-tui repointed at a wrapper', () => {- expect(supportsModelRefresh({ id: 'cursor-tui', type: 'tui', command: '/opt/bin/cursor-wrap', name: 'Cursor Agent TUI' })).toBe(true);- expect(supportsModelRefresh({ id: 'antigravity-tui', type: 'tui', command: '/opt/bin/agy-wrap', name: 'Antigravity TUI' })).toBe(true);- // …but an unshipped id with an unrelated command still gets nothing.- expect(supportsModelRefresh({ id: 'custom-tui', type: 'tui', command: '/opt/bin/cursor-wrap', name: 'Custom' })).toBe(false);- });-- it('does not offer it for a provider merely NAMED cursor, or for the GUI binary', () => {- // "cursor" is an ordinary English word, and a bare `cursor` is the GUI- // editor launcher — neither reaches the server's command-keyed arm.- expect(supportsModelRefresh({ id: 'x', type: 'cli', command: 'some-other-binary', name: 'Cursor Notes' })).toBe(false);- expect(supportsModelRefresh({ id: 'x', type: 'cli', command: 'cursor', name: 'Cursor' })).toBe(false);- });-- // Regression: these two SHIP in data.reference/providers.json and the old- // deny-list reported true for both, so the button 404'd on every click.- it('hides the button for shipped CLIs the server has no fetcher for', () => {- expect(supportsModelRefresh({ id: 'codex', type: 'cli', command: 'codex', name: 'Codex CLI' })).toBe(false);- expect(supportsModelRefresh({ id: 'kimi-cli', type: 'cli', command: 'kimi', name: 'Kimi Code CLI' })).toBe(false);- expect(supportsModelRefresh({ id: 'grok-cli', type: 'cli', command: 'grok', name: 'Grok Build CLI' })).toBe(false);- });-- // The server's claude/gemini arms compare the RAW command string, so this- // must too — a basename-tolerant client would show a button on a renamed,- // path-configured binary that the server still refuses, which is the same- // 404 in a new place. (Widening both sides is tracked separately.)- it('matches the server on the raw command string, not a basename', () => {- expect(supportsModelRefresh({ id: 'c', type: 'cli', command: 'claude', name: 'renamed' })).toBe(true);- expect(supportsModelRefresh({ id: 'c', type: 'cli', command: '/opt/homebrew/bin/claude', name: 'renamed' })).toBe(false);- // A name carrying the vendor word is the server's other accepted signal.- expect(supportsModelRefresh({ id: 'c', type: 'cli', command: '/opt/homebrew/bin/claude', name: 'Claude Code CLI' })).toBe(true);- });-- // Antigravity is the one vendor the server matches by NAME on its CLI arm but- // NOT on its TUI arm — mirror that asymmetry or the button drifts either way.- it('mirrors the antigravity name/command asymmetry between cli and tui', () => {- expect(supportsModelRefresh({ id: 'x', type: 'cli', command: '/usr/bin/weird', name: 'Antigravity Nightly' })).toBe(true);- expect(supportsModelRefresh({ id: 'x', type: 'tui', command: '/usr/bin/weird', name: 'Antigravity Nightly' })).toBe(false);- expect(supportsModelRefresh({ id: 'x', type: 'tui', command: '/opt/bin/agy', name: 'whatever' })).toBe(true);- });-- // Pins the COMMAND half of the antigravity CLI test, which the server hoisted- // above its name test. Only the NAME half was covered above, so deleting- // `isAntigravityCommand(command)` here left the suite green while an- // agy-commanded provider under any other name lost a button the server serves.- it('offers it for an agy-commanded CLI provider whose name says nothing about it', () => {- expect(supportsModelRefresh({ id: 'x', type: 'cli', command: 'agy', name: 'My Coding Agent' })).toBe(true);- expect(supportsModelRefresh({ id: 'x', type: 'cli', command: '/opt/homebrew/bin/agy', name: 'My Coding Agent' })).toBe(true);- });-- it('still offers it for the providers the server CAN fetch for', () => {- // Ollama-backed and antigravity are checked BEFORE the TUI gate, so their- // TUI variants must still refresh — the ordering is the load-bearing part.- expect(supportsModelRefresh({ id: 'claude-ollama-tui', type: 'tui', ollamaBacked: true, name: 'Claude Ollama TUI' })).toBe(true);- expect(supportsModelRefresh({ id: 'antigravity-tui', type: 'tui', command: 'agy', name: 'Antigravity TUI' })).toBe(true);- expect(supportsModelRefresh({ id: 'claude-code', type: 'cli', command: 'claude', name: 'Claude Code CLI' })).toBe(true);- expect(supportsModelRefresh({ id: 'lmstudio', type: 'api', endpoint: 'http://localhost:1234/v1', name: 'LM Studio' })).toBe(true);- expect(supportsModelRefresh({ id: 'cerebras', type: 'api', name: 'Cerebras' })).toBe(true);+ // Guards the AI Providers page's "Refresh Models" button. It is now a READ of+ // the server-derived `canRefreshModels` field — the server owns the one+ // per-vendor fetcher table (server/lib/aiToolkit/internal/modelFetchers.js)+ // and the providers route decorates every payload with the answer.+ //+ // What used to be here was a ~40-line hand-written mirror of both server+ // dispatch arms, "kept in lockstep" by a comment, plus a parity test that+ // re-implemented the server dispatch a SECOND time — so it only proved the+ // mirror matched the test's own copy. Both are gone with #3620/#3616.+ it('reads the flag the server put on the payload', () => {+ expect(supportsModelRefresh({ id: 'claude-code', canRefreshModels: true })).toBe(true);+ expect(supportsModelRefresh({ id: 'codex', canRefreshModels: false })).toBe(false);+ });++ it('ignores the command/name/type shapes it used to sniff', () => {+ // The whole point: the client no longer has an opinion. A codex provider+ // the server says it CAN refresh gets a button; a claude provider the+ // server says it cannot, does not.+ expect(supportsModelRefresh({ type: 'cli', command: 'codex', name: 'Codex CLI', canRefreshModels: true })).toBe(true);+ expect(supportsModelRefresh({ type: 'cli', command: 'claude', name: 'Claude Code CLI', canRefreshModels: false })).toBe(false);+ expect(supportsModelRefresh({ type: 'api', endpoint: 'http://localhost:1234/v1', canRefreshModels: false })).toBe(false);+ });++ it('hides the button when the field is absent — an older server, not a hint to guess', () => {+ // Strict `=== true`: guessing from the shape is what produced a button that+ // 404'd on every click. Absent means "this server does not say", so stay quiet.+ expect(supportsModelRefresh({ id: 'claude-code', type: 'cli', command: 'claude', name: 'Claude Code CLI' })).toBe(false);+ expect(supportsModelRefresh({ id: 'x', canRefreshModels: 'yes' })).toBe(false);+ expect(supportsModelRefresh({ id: 'x', canRefreshModels: 1 })).toBe(false);});it('does not throw on a nullish provider', () => {- expect(() => supportsModelRefresh(null)).not.toThrow();- expect(() => supportsModelRefresh(undefined)).not.toThrow();- });-- // The real lockstep gate: walk the SHIPPED catalog and compare this predicate- // against a transcription of the server's own dispatch. Targeted cases above- // can only cover the mismatches someone already thought of; this catches the- // next provider added to the seed without a matching client branch, which is- // exactly how codex and kimi-cli ended up with a button that 404'd.- it('agrees with the server dispatch for every shipped provider', () => {- // Transcribed from `refreshProviderModels` + `_refreshCLIProviderModels`- // (server/lib/aiToolkit/providers.js). Note the type-routing order and that- // the tui arm does NOT consult the provider name.- const serverWouldRefresh = (p) => {- const name = String(p.name || '').toLowerCase();- if (p.type === 'api') return true;- if (p.type === 'cli') {- if (isOllamaBackedProvider(p)) return true;- // Command-only, and ABOVE the name tests — the server orders it that way- // so a renamed "Cursor Claude Opus" reaches the cursor fetcher.- if (isCursorCommand(p.command)) return true;- if (isAntigravityCommand(p.command)) return true;- if (name.includes('claude') || p.command === 'claude') return true;- if (name.includes('antigravity')) return true;- if (name.includes('gemini') || p.command === 'gemini') return true;- return false; // server throws → route 404s- }- if (p.type === 'tui' && isOllamaBackedProvider(p)) return true;- if (p.type === 'tui' && (p.id === 'antigravity-tui' || isAntigravityCommand(p.command))) return true;- if (p.type === 'tui' && (p.id === 'cursor-tui' || isCursorCommand(p.command))) return true;- return false;- };-- const providers = Object.values(SHIPPED_PROVIDERS.providers);- expect(providers.length).toBeGreaterThan(20);- for (const p of providers) {- expect(- supportsModelRefresh(p),- `${p.id}: client and server disagree on model-refresh support`,- ).toBe(serverWouldRefresh(p));- }+ expect(supportsModelRefresh(null)).toBe(false);+ expect(supportsModelRefresh(undefined)).toBe(false);+ });++ // The shipped-catalog walk, retargeted at the payload field. It used to+ // compare this predicate against a hand transcription of the server dispatch;+ // now it runs the SERVER's own decorator over the shipped seed and asserts the+ // button visibility that produces. That is the real lockstep gate: a provider+ // added to the seed without a fetcher-table row (how codex and kimi-cli ended+ // up with a 404ing button) shows up here.+ it('agrees with the server decorator for every shipped provider', () => {+ const decorated = withRefreshCapabilityList(Object.values(SHIPPED_PROVIDERS.providers));+ expect(decorated.length).toBeGreaterThan(20);++ const withButton = decorated.filter(supportsModelRefresh).map((p) => p.id).sort();+ // Frozen from the pre-#3620 dispatch chains — the refactor must not change+ // WHICH shipped provider offers the button.+ expect(withButton).toEqual([+ 'antigravity-cli', 'antigravity-tui', 'cerebras', 'claude-code',+ 'claude-code-bedrock', 'claude-ollama', 'claude-ollama-tui', 'cursor-cli',+ 'cursor-tui', 'grok', 'lmstudio', 'nvidia-kimi', 'ollama',+ 'opencode-ollama', 'opencode-ollama-tui',+ ]);});});-describe('isCursorCommand (mirror of server lib/cursor.js)', () => {- it('matches the agent binary bare, by path, and with a Windows .exe', () => {- expect(isCursorCommand('cursor-agent')).toBe(true);- expect(isCursorCommand('/Users/x/.local/bin/cursor-agent')).toBe(true);- expect(isCursorCommand('C:\\tools\\Cursor-Agent.exe')).toBe(true);- });-- it('does NOT match a bare `cursor` — that is the GUI editor launcher', () => {- expect(isCursorCommand('cursor')).toBe(false);- expect(isCursorCommand('/usr/local/bin/cursor')).toBe(false);- });-- it('rejects other CLIs and nullish input', () => {- expect(isCursorCommand('claude')).toBe(false);- expect(isCursorCommand('')).toBe(false);- expect(isCursorCommand(null)).toBe(false);- });-+describe('cursor providers', () => {it('offers no effort ladder — cursor bakes the reasoning tier into the model id', () => {expect(effortLevelsForProvider({ id: 'cursor-cli', command: 'cursor-agent' })).toBeNull();expect(effortLevelsForProvider({ id: 'cursor-tui', command: 'cursor-agent' }, 'claude-opus-5-thinking-high')).toBeNull();diff --git a/server/lib/aiToolkit/index.js b/server/lib/aiToolkit/index.jsindex afbae99683..ddeb67f8f3 100644--- a/server/lib/aiToolkit/index.js+++ b/server/lib/aiToolkit/index.js@@ -6,7 +6,7 @@import { fileURLToPath } from 'url';import { dirname, join } from 'path';-import { createProviderService, isOllamaBackedProvider } from './providers.js';+import { canRefreshModels, createProviderService, isOllamaBackedProvider } from './providers.js';import { createRunnerService } from './runner.js';import { createPromptsService } from './prompts.js';import { createProviderStatusService } from './providerStatus.js';@@ -25,7 +25,7 @@ export * from './validation.js';export * from './errorDetection.js';export * from './constants.js';export { createProviderService, createRunnerService, createPromptsService, createProviderStatusService };-export { isOllamaBackedProvider };+export { isOllamaBackedProvider, canRefreshModels };export { createProvidersRoutes, createRunsRoutes, createPromptsRoutes, createProviderStatusRoutes };export function createAIToolkit(config = {}) {diff --git a/server/lib/aiToolkit/internal/modelFetchers.js b/server/lib/aiToolkit/internal/modelFetchers.jsnew file mode 100644index 0000000000..ed9ad7eeb3--- /dev/null+++ b/server/lib/aiToolkit/internal/modelFetchers.js@@ -0,0 +1,163 @@+/**+ * The single per-vendor table behind model refresh.+ *+ * Before this table, adding one vendor to the refresh feature meant four+ * coordinated hand edits: the TUI `else if` chain in `refreshProviderModels`,+ * the CLI `if` chain in `_refreshCLIProviderModels`, the client's+ * `supportsModelRefresh` mirror, and a SECOND transcription of the server+ * dispatch inside the client's parity test. Nothing structurally stopped the+ * next vendor from making three of the four. Now: one row here, and the+ * capability rides to the client on the payload as `canRefreshModels`.+ *+ * ## The columns are the keying conventions+ *+ * Vendors are not identified the same way, and the differences used to live in+ * prose above each branch. They are columns now:+ *+ * - `cliMatch` — the STRONG identity signal for a `cli` provider: the launch+ * command (path/exe-tolerant for vendors whose users configure+ * an absolute path), or a structural marker (`ollamaBacked`).+ * - `cliNameMatch` — the WEAK signal: a substring of the user-editable DISPLAY+ * NAME. Only consulted once no row has claimed the provider by+ * command, so `name: 'Claude via Antigravity'` + `command:+ * 'claude'` still reaches Anthropic — the right answer for a+ * claude binary. A vendor whose word is ordinary English+ * (cursor: a DB cursor, a text cursor) deliberately has NO+ * name column, or a provider a user named "Cursor Notes" would+ * hijack the refresh.+ * - `tuiMatch` — a `tui` provider's model is normally fixed by its CLI/config,+ * so only the vendors whose `--model` flag also applies to the+ * interactive session carry this column. It never consults the+ * display name: unlike the CLI arm, an EXACT shipped-id match+ * is the only non-command signal it admits.+ * - `fetch` — the provider-service method name that performs the probe.+ * Kept as a string so this table stays a pure data module with+ * no dependency on the service object it is dispatched from.+ *+ * Adding a vendor is one row. `modelFetchers.test.js` pins that by driving a+ * hypothetical vendor through the table rather than through a chain.+ */+import { ANTIGRAVITY_TUI_ID, isAntigravityCommand } from './antigravity.js';+import { CURSOR_TUI_ID, isCursorCommand } from './cursor.js';+import { isOllamaBackedProvider } from './ollamaBacked.js';++const displayName = (provider) => String(provider?.name || '').toLowerCase();++/**+ * Ordered vendor rows. Order is load-bearing in exactly one place: the+ * ollama row must come first, so a `claude` CLI pointed at a local Ollama+ * daemon pulls the installed (tool-use-capable) Ollama models instead of the+ * static Anthropic list. Every other `cliMatch` in the table is mutually+ * exclusive, and the name pass runs in table order (claude, antigravity,+ * gemini) exactly as the old chain did.+ */+export const MODEL_FETCHERS = [+ {+ key: 'ollama',+ // Not a command test: the marker can be `ollamaBacked`, an id, or an+ // ANTHROPIC_BASE_URL. Still a STRONG signal, so it sits in the first pass.+ cliMatch: (p) => isOllamaBackedProvider(p),+ tuiMatch: (p) => isOllamaBackedProvider(p),+ fetch: '_fetchOllamaToolCapableModels',+ },+ {+ key: 'cursor',+ // No `cliNameMatch` on purpose — see the column notes above.+ cliMatch: (p) => isCursorCommand(p?.command),+ tuiMatch: (p) => p?.id === CURSOR_TUI_ID || isCursorCommand(p?.command),+ fetch: '_fetchCursorModels',+ },+ {+ key: 'claude',+ // Raw-string equality, NOT a basename: `_fetchAnthropicModels` returns a+ // static list, so widening this to every binary named `claude` on disk is a+ // separate call from widening the vendors that probe their own CLI.+ cliMatch: (p) => p?.command === 'claude',+ cliNameMatch: (p) => displayName(p).includes('claude'),+ fetch: '_fetchAnthropicModels',+ },+ {+ key: 'antigravity',+ cliMatch: (p) => isAntigravityCommand(p?.command),+ cliNameMatch: (p) => displayName(p).includes('antigravity'),+ tuiMatch: (p) => p?.id === ANTIGRAVITY_TUI_ID || isAntigravityCommand(p?.command),+ fetch: '_fetchAntigravityModels',+ },+ {+ key: 'gemini',+ cliMatch: (p) => p?.command === 'gemini',+ cliNameMatch: (p) => displayName(p).includes('gemini'),+ fetch: '_fetchGeminiModels',+ },+];++/**+ * The row that will serve `provider`'s model refresh, or `null` when no vendor+ * claims it (the caller then throws its own 400 — this function never throws).+ *+ * `api` providers are deliberately NOT resolved here: they don't route through+ * the table at all, they go to the generic `_refreshAPIProviderModels`. Ask+ * {@link canRefreshModels} for the capability answer that spans both.+ *+ * The CLI arm runs the command pass to exhaustion BEFORE the name pass, which+ * is the generalization of the ordering the old chain had already grown case by+ * case ("an exact command match is a stronger identity signal than a name+ * substring, so it must win"). The one behavior this changes versus the old+ * chain: a provider named e.g. "Claude Opus" whose command is literally+ * `gemini` now reaches the gemini fetcher instead of having Anthropic's static+ * list persisted onto it. Which vendors are refreshable at all is unchanged —+ * the union of the two passes is the same set the chain matched.+ */+export function resolveModelFetcher(provider, table = MODEL_FETCHERS) {+ if (!provider) return null;+ if (provider.type === 'tui') {+ return table.find((f) => f.tuiMatch?.(provider)) || null;+ }+ if (provider.type === 'cli') {+ return table.find((f) => f.cliMatch?.(provider))+ || table.find((f) => f.cliNameMatch?.(provider))+ || null;+ }+ return null;+}++/**+ * Whether the server can refresh this provider's model list — i.e. whether+ * `POST /providers/:id/refresh-models` will answer rather than 400.+ *+ * Pure and side-effect free, so the route can decorate every provider payload+ * with it (as `canRefreshModels`) and the client can stop re-deriving the+ * answer from command/name string sniffing. It is DERIVED ON READ and never+ * stored: `saveProviders` must never see it, or it goes stale against this+ * table the first time a user repoints a provider's command.+ *+ * `table` is injectable for the "adding a vendor is exactly one row" test —+ * production callers always take the default.+ *+ * @param {{type?:string, id?:string, name?:string, command?:string}|null|undefined} provider+ * @param {Array} [table]+ * @returns {boolean}+ */+export function canRefreshModels(provider, table = MODEL_FETCHERS) {+ if (!provider) return false;+ // Every API provider routes to the generic `_refreshAPIProviderModels`.+ if (provider.type === 'api') return true;+ return resolveModelFetcher(provider, table) !== null;+}++/**+ * Decorate one provider (or a nullish miss, passed through untouched) with the+ * derived `canRefreshModels` flag. Returns a COPY — the caller's object, which+ * may be the live cached record `saveProviders` writes back to disk, is never+ * mutated.+ */+export function withRefreshCapability(provider) {+ if (!provider) return provider;+ return { ...provider, canRefreshModels: canRefreshModels(provider) };+}++/** Array form of {@link withRefreshCapability}. */+export function withRefreshCapabilityList(providers) {+ if (!Array.isArray(providers)) return providers;+ return providers.map(withRefreshCapability);+}diff --git a/server/lib/aiToolkit/internal/modelFetchers.test.js b/server/lib/aiToolkit/internal/modelFetchers.test.jsnew file mode 100644index 0000000000..bc2d39bef2--- /dev/null+++ b/server/lib/aiToolkit/internal/modelFetchers.test.js@@ -0,0 +1,220 @@+import { describe, it, expect } from 'vitest';+import { readFileSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import { dirname, resolve } from 'node:path';+import { MODEL_FETCHERS, canRefreshModels, resolveModelFetcher, withRefreshCapability, withRefreshCapabilityList } from './modelFetchers.js';++const __dirname = dirname(fileURLToPath(import.meta.url));+const SHIPPED = JSON.parse(readFileSync(resolve(__dirname, '../../../../data.reference/providers.json'), 'utf8'));++// The shipped ids whose "Refresh Models" button is visible TODAY, transcribed+// from the pre-table `refreshProviderModels` + `_refreshCLIProviderModels`+// chains before they collapsed into MODEL_FETCHERS (#3620). This is the+// regression gate for the refactor: the table may reorganize how a vendor is+// matched, but it must not change WHICH shipped provider can refresh — the+// failure mode is silent in both directions (a button that 404s, or a feature+// that vanishes with no error at all).+const SHIPPED_REFRESHABLE = [+ 'antigravity-cli', 'antigravity-tui', 'cerebras', 'claude-code',+ 'claude-code-bedrock', 'claude-ollama', 'claude-ollama-tui', 'cursor-cli',+ 'cursor-tui', 'grok', 'lmstudio', 'nvidia-kimi', 'ollama', 'opencode-ollama',+ 'opencode-ollama-tui',+];+const SHIPPED_NOT_REFRESHABLE = [+ 'claude-code-tui', 'claude-code-tui-bedrock', 'codex', 'codex-tui',+ 'grok-cli', 'grok-tui', 'kimi-cli', 'kimi-tui',+];++describe('MODEL_FETCHERS — shipped catalog visibility is unchanged', () => {+ it('every shipped provider is classified, and the two lists cover the catalog', () => {+ const ids = Object.keys(SHIPPED.providers).sort();+ expect(ids.length).toBeGreaterThan(20);+ expect([...SHIPPED_REFRESHABLE, ...SHIPPED_NOT_REFRESHABLE].sort()).toEqual(ids);+ });++ it('answers exactly as the pre-table dispatch chains did', () => {+ for (const provider of Object.values(SHIPPED.providers)) {+ expect(+ canRefreshModels(provider),+ `${provider.id}: model-refresh visibility changed`,+ ).toBe(SHIPPED_REFRESHABLE.includes(provider.id));+ }+ });+});++describe('resolveModelFetcher — the ordering the old chains encoded in prose', () => {+ it('routes an Ollama-backed claude CLI to Ollama, not the static Anthropic list', () => {+ // The one load-bearing row order: ollama first.+ const p = { id: 'claude-ollama', type: 'cli', command: 'claude', name: 'Claude Ollama', ollamaBacked: true };+ expect(resolveModelFetcher(p).fetch).toBe('_fetchOllamaToolCapableModels');+ });++ it('lets a command beat a display name — a renamed cursor still reaches cursor-agent', () => {+ // Renaming a cursor provider "Cursor Claude Opus" must not persist+ // Anthropic ids that cursor-agent will reject.+ const p = { id: 'x', type: 'cli', command: 'cursor-agent', name: 'Cursor Claude Opus' };+ expect(resolveModelFetcher(p).fetch).toBe('_fetchCursorModels');+ });++ it('lets an agy command beat a claude name — "Antigravity Claude Sonnet" stays on agy', () => {+ const p = { id: 'x', type: 'cli', command: '/opt/homebrew/bin/agy', name: 'Antigravity Claude Sonnet 4.6' };+ expect(resolveModelFetcher(p).fetch).toBe('_fetchAntigravityModels');+ });++ it('lets a claude command beat an antigravity name — the right answer for a claude binary', () => {+ const p = { id: 'x', type: 'cli', command: 'claude', name: 'Claude via Antigravity' };+ expect(resolveModelFetcher(p).fetch).toBe('_fetchAnthropicModels');+ });++ it('falls through to the display name only when no command claims the provider', () => {+ expect(resolveModelFetcher({ id: 'x', type: 'cli', command: '/usr/bin/weird', name: 'Antigravity Nightly' }).fetch)+ .toBe('_fetchAntigravityModels');+ expect(resolveModelFetcher({ id: 'x', type: 'cli', command: '/usr/bin/weird', name: 'Gemini Preview' }).fetch)+ .toBe('_fetchGeminiModels');+ expect(resolveModelFetcher({ id: 'x', type: 'cli', command: '/opt/homebrew/bin/claude', name: 'Claude Code CLI' }).fetch)+ .toBe('_fetchAnthropicModels');+ });++ it('never lets an ordinary English name claim cursor', () => {+ // "cursor" is a DB cursor / a text cursor — there is deliberately no+ // cliNameMatch column on that row.+ expect(resolveModelFetcher({ id: 'x', type: 'cli', command: 'some-binary', name: 'Cursor Notes' })).toBeNull();+ // A bare `cursor` is the GUI editor launcher, not the agent binary.+ expect(resolveModelFetcher({ id: 'x', type: 'cli', command: 'cursor', name: 'Cursor' })).toBeNull();+ });++ it('returns null for a CLI no vendor claims — the caller throws its own 400', () => {+ for (const command of ['codex', 'kimi', 'grok']) {+ expect(resolveModelFetcher({ id: command, type: 'cli', command, name: `${command} CLI` })).toBeNull();+ }+ });+});++describe('resolveModelFetcher — the TUI arm never consults the display name', () => {+ it('serves the three vendors whose --model applies to the interactive session', () => {+ expect(resolveModelFetcher({ id: 'claude-ollama-tui', type: 'tui', ollamaBacked: true }).fetch)+ .toBe('_fetchOllamaToolCapableModels');+ expect(resolveModelFetcher({ id: 'x', type: 'tui', command: '/opt/bin/agy' }).fetch)+ .toBe('_fetchAntigravityModels');+ expect(resolveModelFetcher({ id: 'x', type: 'tui', command: 'cursor-agent' }).fetch)+ .toBe('_fetchCursorModels');+ });++ it('admits a shipped TUI id repointed at a wrapper script', () => {+ // An EXACT shipped-id match, never a name substring: it can only admit the+ // provider PortOS itself seeds, and probing the user's wrapper is right.+ expect(resolveModelFetcher({ id: 'cursor-tui', type: 'tui', command: '/opt/bin/cursor-wrap' }).fetch)+ .toBe('_fetchCursorModels');+ expect(resolveModelFetcher({ id: 'antigravity-tui', type: 'tui', command: '/opt/bin/agy-wrap' }).fetch)+ .toBe('_fetchAntigravityModels');+ expect(resolveModelFetcher({ id: 'custom-tui', type: 'tui', command: '/opt/bin/cursor-wrap' })).toBeNull();+ });++ it('ignores a vendor name on a TUI — the asymmetry with the CLI arm is deliberate', () => {+ expect(resolveModelFetcher({ id: 'x', type: 'tui', command: '/usr/bin/weird', name: 'Antigravity Nightly' })).toBeNull();+ expect(resolveModelFetcher({ id: 'x', type: 'tui', command: 'claude', name: 'Claude Code TUI' })).toBeNull();+ });+});++describe('canRefreshModels', () => {+ it('is true for every API provider — they route to the generic fetcher', () => {+ expect(canRefreshModels({ id: 'cerebras', type: 'api', name: 'Cerebras' })).toBe(true);+ expect(canRefreshModels({ id: 'lmstudio', type: 'api', endpoint: 'http://localhost:1234/v1' })).toBe(true);+ });++ it('is false for a nullish provider and for an unknown type', () => {+ expect(canRefreshModels(null)).toBe(false);+ expect(canRefreshModels(undefined)).toBe(false);+ expect(canRefreshModels({ id: 'x', type: 'mystery', command: 'claude', name: 'Claude' })).toBe(false);+ });+});++describe('withRefreshCapability', () => {+ it('returns a copy — the caller\'s (possibly cached, about-to-be-saved) record is untouched', () => {+ const provider = { id: 'codex', type: 'cli', command: 'codex', name: 'Codex CLI' };+ const decorated = withRefreshCapability(provider);+ expect(decorated).not.toBe(provider);+ expect(decorated.canRefreshModels).toBe(false);+ expect(provider.canRefreshModels).toBeUndefined();+ });++ it('passes a nullish provider straight through (GET /active with none set)', () => {+ expect(withRefreshCapability(null)).toBeNull();+ expect(withRefreshCapabilityList(undefined)).toBeUndefined();+ });++ it('decorates every entry of a list', () => {+ const list = withRefreshCapabilityList([+ { id: 'a', type: 'api' },+ { id: 'b', type: 'cli', command: 'codex', name: 'Codex' },+ ]);+ expect(list.map((p) => p.canRefreshModels)).toEqual([true, false]);+ });+});++describe('adding a vendor is exactly ONE table row', () => {+ // Drives the TABLE, not the chain: the whole point of #3620 is that a new+ // vendor cannot half-land (server CLI arm but not TUI arm, or server but not+ // client). Injecting a single row must light up every arm at once.+ const acmeRow = {+ key: 'acme',+ cliMatch: (p) => p?.command === 'acme-agent',+ cliNameMatch: (p) => String(p?.name || '').toLowerCase().includes('acme'),+ tuiMatch: (p) => p?.id === 'acme-tui' || p?.command === 'acme-agent',+ fetch: '_fetchAcmeModels',+ };+ const withAcme = [...MODEL_FETCHERS, acmeRow];+ const acmeCli = { id: 'acme-cli', type: 'cli', command: 'acme-agent', name: 'Acme CLI' };+ const acmeTui = { id: 'acme-tui', type: 'tui', command: '/opt/bin/acme-wrap', name: 'Acme TUI' };++ it('is invisible to every arm before the row exists', () => {+ expect(canRefreshModels(acmeCli)).toBe(false);+ expect(canRefreshModels(acmeTui)).toBe(false);+ expect(resolveModelFetcher(acmeCli)).toBeNull();+ });++ it('lights up the CLI arm, the TUI arm, and the payload flag from that one row', () => {+ expect(resolveModelFetcher(acmeCli, withAcme).fetch).toBe('_fetchAcmeModels');+ expect(resolveModelFetcher(acmeTui, withAcme).fetch).toBe('_fetchAcmeModels');+ expect(canRefreshModels(acmeCli, withAcme)).toBe(true);+ expect(canRefreshModels(acmeTui, withAcme)).toBe(true);+ // …and its display-name column works without touching any other vendor.+ expect(resolveModelFetcher({ id: 'x', type: 'cli', command: '/usr/bin/weird', name: 'Acme Nightly' }, withAcme).fetch)+ .toBe('_fetchAcmeModels');+ });++ it('leaves every shipped provider\'s answer untouched', () => {+ for (const provider of Object.values(SHIPPED.providers)) {+ expect(canRefreshModels(provider, withAcme)).toBe(canRefreshModels(provider));+ }+ });+});++describe('MODEL_FETCHERS shape', () => {+ it('every row names a fetcher method and carries at least one match column', () => {+ for (const row of MODEL_FETCHERS) {+ expect(typeof row.key, 'row is missing a key').toBe('string');+ expect(typeof row.fetch, `${row.key}: fetch must be a method NAME (string)`).toBe('string');+ expect(+ Boolean(row.cliMatch || row.cliNameMatch || row.tuiMatch),+ `${row.key}: a row that matches nothing is dead weight`,+ ).toBe(true);+ }+ });++ it('has unique keys', () => {+ const keys = MODEL_FETCHERS.map((f) => f.key);+ expect(new Set(keys).size).toBe(keys.length);+ });++ it('every `fetch` names a real method on the provider service', async () => {+ // The table holds method NAMES so it can stay a pure data module; that+ // indirection would otherwise fail only at refresh time, as a TypeError+ // surfaced to the user as a 502.+ const { createProviderService } = await import('../providers.js');+ const service = createProviderService({ dataDir: './data' });+ for (const row of MODEL_FETCHERS) {+ expect(typeof service[row.fetch], `${row.key}: no such method ${row.fetch}`).toBe('function');+ }+ });+});diff --git a/server/lib/aiToolkit/internal/ollamaBacked.js b/server/lib/aiToolkit/internal/ollamaBacked.jsnew file mode 100644index 0000000000..42ec20729c--- /dev/null+++ b/server/lib/aiToolkit/internal/ollamaBacked.js@@ -0,0 +1,24 @@+/**+ * Whether `provider` is served by an Ollama daemon rather than its nominal+ * cloud/CLI backend. Covers three shapes: the built-in `ollama` API provider+ * itself (id match — its `endpoint` carries the daemon URL, not `envVars`);+ * an `api`-type provider whose `endpoint` points at Ollama (generic local+ * setups); and the Claude-Ollama CLI/TUI pattern — a `claude` process that+ * carries the `ollamaBacked` marker or an `ANTHROPIC_BASE_URL` pointed at+ * Ollama, running the full Claude Code harness but generating tokens from a+ * local model, so its model list must come from Ollama (filtered to+ * tool-use-capable models) rather than the static Anthropic list.+ *+ * Lives in `internal/` rather than `providers.js` so the model-fetcher table+ * (`internal/modelFetchers.js`) can key its ollama row on it without importing+ * back into `providers.js` and forming a module cycle. Re-exported from+ * `providers.js` (and from `server/services/providers.js`) so hosts can+ * classify providers the same way this module's own refresh dispatch does,+ * instead of re-deriving the shape check and risking drift.+ */+export function isOllamaBackedProvider(provider) {+ if (provider?.id === 'ollama') return true;+ if (provider?.ollamaBacked === true) return true;+ const base = String(provider?.envVars?.ANTHROPIC_BASE_URL || provider?.endpoint || '');+ return /:11434\b/.test(base) || /ollama/i.test(base);+}diff --git a/server/lib/aiToolkit/providers.js b/server/lib/aiToolkit/providers.jsindex ec21bed3f8..9ac154a54e 100644--- a/server/lib/aiToolkit/providers.js+++ b/server/lib/aiToolkit/providers.js@@ -12,17 +12,24 @@ import {ANTIGRAVITY_TUI_ID,ensureAntigravityPrintArgs,ensureAntigravityTuiArgs,- isAntigravityCommand,LEGACY_GEMINI_CLI_ID,LEGACY_GEMINI_TUI_ID,parseAntigravityModelList,} from './internal/antigravity.js';import {CURSOR_COMMAND,- CURSOR_TUI_ID,- isCursorCommand,parseCursorModelList,} from './internal/cursor.js';+import { isOllamaBackedProvider } from './internal/ollamaBacked.js';+import { canRefreshModels, resolveModelFetcher } from './internal/modelFetchers.js';++// Re-exported (rather than defined here) so the model-fetcher table can key its+// ollama row on the same predicate without importing back into this module.+export { isOllamaBackedProvider };+// The pure capability predicate that both refresh arms below dispatch through —+// exported so the providers route can decorate its payload with it and the+// client stops re-deriving refreshability from command/name string sniffing.+export { canRefreshModels };const __dirname = dirname(fileURLToPath(import.meta.url));const DEFAULT_SAMPLE_PATH = join(__dirname, 'defaults/providers.sample.json');@@ -115,27 +122,6 @@ const TOOL_USE_RE = new RegExp(['deepseek-v3', 'deepseek-r1',].join('|'), 'i');-/**- * Whether `provider` is served by an Ollama daemon rather than its nominal- * cloud/CLI backend. Covers three shapes: the built-in `ollama` API provider- * itself (id match — its `endpoint` carries the daemon URL, not `envVars`);- * an `api`-type provider whose `endpoint` points at Ollama (generic local- * setups); and the Claude-Ollama CLI/TUI pattern — a `claude` process that- * carries the `ollamaBacked` marker or an `ANTHROPIC_BASE_URL` pointed at- * Ollama, running the full Claude Code harness but generating tokens from a- * local model, so its model list must come from Ollama (filtered to- * tool-use-capable models) rather than the static Anthropic list. Exported- * (re-exported by `server/services/providers.js`) so hosts can classify- * providers the same way this module's own refresh dispatch does, instead of- * re-deriving the shape check and risking drift.- */-export function isOllamaBackedProvider(provider) {- if (provider?.id === 'ollama') return true;- if (provider?.ollamaBacked === true) return true;- const base = String(provider?.envVars?.ANTHROPIC_BASE_URL || provider?.endpoint || '');- return /:11434\b/.test(base) || /ollama/i.test(base);-}-/** Normalize an Ollama base URL (strip trailing slash + an OpenAI-compat `/v1`). */function ollamaBaseFromProvider(provider) {const base = String(provider?.envVars?.ANTHROPIC_BASE_URL || provider?.endpoint || 'http://localhost:11434');@@ -754,32 +740,19 @@ export function createProviderService(config = {}) {let models = null;try {+ // A TUI provider's model is normally fixed by its CLI/config, so only+ // the vendors whose `--model` flag also applies to the interactive+ // session carry a `tuiMatch` column in the table (ollama-backed,+ // antigravity, cursor today). One lookup replaces the per-vendor+ // `else if` chain this used to be — see internal/modelFetchers.js.+ const tuiFetcher = provider.type === 'tui' ? resolveModelFetcher(provider) : null;+if (provider.type === 'api') {models = await this._refreshAPIProviderModels(provider);} else if (provider.type === 'cli') {models = await this._refreshCLIProviderModels(provider);- } else if (provider.type === 'tui' && isOllamaBackedProvider(provider)) {- // TUI providers normally don't refresh (their model is fixed by the- // CLI/config), but the Claude-Ollama TUI variant still needs its- // tool-use-capable Ollama model list pulled live, same as the CLI one.- models = await this._fetchOllamaToolCapableModels(provider);- } else if (provider.type === 'tui' && (provider.id === ANTIGRAVITY_TUI_ID || isAntigravityCommand(provider.command))) {- // Same exception for the Antigravity TUI: `agy --model` applies to the- // interactive session too, so its catalog must refresh like the CLI's.- models = await this._fetchAntigravityModels(provider);- } else if (provider.type === 'tui' && (provider.id === CURSOR_TUI_ID || isCursorCommand(provider.command))) {- // And for the Cursor TUI: `cursor-agent --model` applies to the- // interactive session too — the binary's own `Tip:` line documents- // both `--model <id>` and the in-session `/model <id>` — so its- // catalog must refresh like the CLI's.- // The id test alongside the command one (which the CLI arm below- // deliberately does without) carries none of that arm's hazard: it is- // an EXACT shipped-id match, not a name substring, so it can only- // admit the provider PortOS itself seeds — and if the user repointed- // its command at a wrapper, probing that wrapper is the right answer.- // Shaped to match the antigravity arm above; both collapse together- // when the dispatch becomes a table (#3620).- models = await this._fetchCursorModels(provider);+ } else if (tuiFetcher) {+ models = await this[tuiFetcher.fetch](provider);} else {// No branch matched — this provider type/shape has no fetcher. Say so,// the same 400 the CLI arm's own fall-through throws. Previously this@@ -880,66 +853,18 @@ export function createProviderService(config = {}) {},async _refreshCLIProviderModels(provider) {- const providerName = provider.name.toLowerCase();-- // Claude Ollama: a `claude` CLI pointed at a local Ollama daemon. Pull the- // installed Ollama models (filtered to tool-use-capable ones — the agent- // harness depends on reliable tool-calling) instead of the static Anthropic- // list. Checked BEFORE the generic claude branch below.- if (isOllamaBackedProvider(provider)) {- return await this._fetchOllamaToolCapableModels(provider);- }-- // Cursor is keyed on the command BASENAME — path/exe-tolerant like the- // antigravity branch, so a binary configured by absolute path still- // refreshes rather than falling through to the throw below while the- // client's mirrored gate still offers the button. Unlike every vendor- // around it there is deliberately NO name test: "cursor" is an ordinary- // English word (a DB cursor, a text cursor), so a `name.includes('cursor')`- // clause would hijack the refresh for an unrelated provider the user- // happened to name "Cursor Notes".- //- // It sits ABOVE the name-substring branches on purpose, and the order is- // load-bearing: those branches match on the DISPLAY NAME, so a cursor- // provider a user renamed "Cursor Claude Opus" or "Cursor Antigravity"- // would otherwise be routed to _fetchAnthropicModels / _fetchAntigravityModels- // and have that vendor's catalog persisted onto it — ids cursor-agent will- // reject, written silently because the client (command-keyed) shows the- // Refresh button. An exact command match is a stronger identity signal- // than a name substring, so it must win. Same reasoning that already puts- // the ollama check first.- if (isCursorCommand(provider.command)) {- return await this._fetchCursorModels(provider);- }-- // Antigravity's COMMAND test is hoisted for the same reason, and split from- // its name test below to do it. It is path/exe-tolerant (`isAntigravityCommand`,- // not `command === 'agy'`) so a provider configured with the absolute binary- // path still refreshes; matches the TUI branch in refreshProviderModels.- // Left fused below the claude name test, an `agy` provider named- // "Antigravity Claude Sonnet 4.6" — the natural name for a second agy- // provider, since agy's own catalog carries claude ids — got Anthropic's- // static list persisted onto it AND lost the `antigravity-configured-default`- // sentinel from `models` while `defaultModel` still pointed at it, which- // blanks the model <select> and reads as "unset".- if (isAntigravityCommand(provider.command)) {- return await this._fetchAntigravityModels(provider);- }-- if (providerName.includes('claude') || provider.command === 'claude') {- return await this._fetchAnthropicModels(provider);- }-- // The NAME tests stay below the command tests above: they are the weaker- // signal, so they only get a say once no command has claimed the provider.- // `name: 'Claude via Antigravity'` + `command: 'claude'` therefore still- // reaches Anthropic, which is the right answer for a claude binary.- if (providerName.includes('antigravity')) {- return await this._fetchAntigravityModels(provider);- }-- if (providerName.includes('gemini') || provider.command === 'gemini') {- return await this._fetchGeminiModels(provider);+ // One lookup, not a per-vendor `if` chain. The table+ // (internal/modelFetchers.js) also owns the ORDER this used to encode in+ // prose: the ollama row first (a `claude` CLI pointed at a local Ollama+ // daemon must pull the installed tool-use-capable models, not the static+ // Anthropic list), then every command/structural match, and only then the+ // weaker display-name matches — so a cursor provider a user renamed+ // "Cursor Claude Opus" reaches cursor-agent rather than having Anthropic's+ // catalog persisted onto it.+ const fetcher = resolveModelFetcher(provider);++ if (fetcher) {+ return await this[fetcher.fetch](provider);}// 400, not the rethrow's 502 default: nothing upstream failed — this CLIdiff --git a/server/lib/aiToolkit/routes/providers.js b/server/lib/aiToolkit/routes/providers.jsindex 1a695737c9..984639c17e 100644--- a/server/lib/aiToolkit/routes/providers.js+++ b/server/lib/aiToolkit/routes/providers.js@@ -1,6 +1,17 @@import { Router } from 'express';import { ToolkitHttpError, defaultAsyncHandler } from '../internal/httpError.js';import { providerSchema, providerActiveSchema, validate } from '../validation.js';+import { withRefreshCapability, withRefreshCapabilityList } from '../internal/modelFetchers.js';++// `canRefreshModels` is DERIVED ON READ and decorated HERE, at the route —+// never inside `getAllProviders()`. Computing it in the service would put it on+// the object `saveProviders` writes back, so it would land in providers.json and+// go stale against the fetcher table the first time a user repoints a command.+// Decorating on the way out keeps the persisted record clean while every+// provider-shaped response still carries the flag, so the client can read it+// instead of re-deriving refreshability from command/name string sniffing.+// Safe against a round-trip: `providerSchema.partial()` on PUT strips unknown+// keys, so even a client that echoes the whole object back cannot persist it.export function createProvidersRoutes(providerService, options = {}) {const router = Router();@@ -12,12 +23,12 @@ export function createProvidersRoutes(providerService, options = {}) {router.get('/', asyncHandler(async (req, res) => {const data = await providerService.getAllProviders();- res.json(data);+ res.json({ ...data, providers: withRefreshCapabilityList(data.providers) });}));router.get('/active', asyncHandler(async (req, res) => {const provider = await providerService.getActiveProvider();- res.json(provider);+ res.json(withRefreshCapability(provider));}));router.put('/active', asyncHandler(async (req, res) => {@@ -33,7 +44,7 @@ export function createProvidersRoutes(providerService, options = {}) {throw new ServerError('Provider not found', { status: 404 });}- res.json(provider);+ res.json(withRefreshCapability(provider));}));router.get('/samples', asyncHandler(async (req, res) => {@@ -48,7 +59,7 @@ export function createProvidersRoutes(providerService, options = {}) {throw new ServerError('Provider not found', { status: 404 });}- res.json(provider);+ res.json(withRefreshCapability(provider));}));router.post('/', asyncHandler(async (req, res) => {@@ -58,7 +69,7 @@ export function createProvidersRoutes(providerService, options = {}) {}const provider = await providerService.createProvider(result.data);- res.status(201).json(provider);+ res.status(201).json(withRefreshCapability(provider));}));router.put('/:id', asyncHandler(async (req, res) => {@@ -75,7 +86,7 @@ export function createProvidersRoutes(providerService, options = {}) {throw new ServerError('Provider not found', { status: 404 });}- res.json(provider);+ res.json(withRefreshCapability(provider));}));router.delete('/:id', asyncHandler(async (req, res) => {@@ -106,7 +117,7 @@ export function createProvidersRoutes(providerService, options = {}) {throw new ServerError('Provider not found', { status: 404 });}- res.json(provider);+ res.json(withRefreshCapability(provider));}));return router;diff --git a/server/lib/aiToolkit/routes/providers.refreshCapability.test.js b/server/lib/aiToolkit/routes/providers.refreshCapability.test.jsnew file mode 100644index 0000000000..cab3f328c1--- /dev/null+++ b/server/lib/aiToolkit/routes/providers.refreshCapability.test.js@@ -0,0 +1,96 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import express from 'express';+import { mkdtemp, rm, readFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { request } from '../../testHelper.js';+import { asyncHandler, errorMiddleware, ServerError } from '../../errorHandler.js';+import { createProviderService } from '../providers.js';+import { createProvidersRoutes } from './providers.js';++// #3620 — `canRefreshModels` is DERIVED ON READ from the per-vendor fetcher+// table and decorated at the ROUTE. If it were computed in `getAllProviders()`+// instead it would ride the object `saveProviders` writes back and land in+// providers.json, where it would go stale against the table the first time a+// user repointed a provider's command — reintroducing exactly the drift the+// field exists to remove. These tests pin both halves: the payload has it, the+// file never does.++describe('#3620: providers route decorates canRefreshModels without persisting it', () => {+ let dataDir;+ let app;++ const providersFile = () => join(dataDir, 'providers.json');+ const readStored = async () => JSON.parse(await readFile(providersFile(), 'utf8'));++ beforeEach(async () => {+ dataDir = await mkdtemp(join(tmpdir(), 'portos-providers-'));+ const service = createProviderService({ dataDir });+ app = express();+ app.use(express.json());+ app.use('/api/providers', createProvidersRoutes(service, { asyncHandler, ServerError }));+ app.use(errorMiddleware);+ });++ afterEach(async () => {+ await rm(dataDir, { recursive: true, force: true });+ });++ const createProvider = (body) => request(app).post('/api/providers').send(body);++ it('GET / carries the flag per provider — true for a refreshable CLI, false otherwise', async () => {+ await createProvider({ id: 'claude-code', name: 'Claude Code CLI', type: 'cli', command: 'claude' });+ await createProvider({ id: 'codex', name: 'Codex CLI', type: 'cli', command: 'codex' });++ const res = await request(app).get('/api/providers');+ expect(res.status).toBe(200);+ const byId = Object.fromEntries(res.body.providers.map((p) => [p.id, p]));+ expect(byId['claude-code'].canRefreshModels).toBe(true);+ expect(byId.codex.canRefreshModels).toBe(false);+ });++ it('never writes the field to providers.json — not on create, not on update', async () => {+ await createProvider({ id: 'claude-code', name: 'Claude Code CLI', type: 'cli', command: 'claude' });+ await request(app).get('/api/providers');++ const afterCreate = await readStored();+ expect(afterCreate.providers['claude-code']).not.toHaveProperty('canRefreshModels');++ // The round-trip hazard: a client that echoes the decorated payload back.+ // `providerSchema.partial()` strips unknown keys, so it cannot be stored.+ const put = await request(app)+ .put('/api/providers/claude-code')+ .send({ name: 'Claude Code CLI', enabled: false, canRefreshModels: true });+ expect(put.status).toBe(200);++ const afterUpdate = await readStored();+ expect(afterUpdate.providers['claude-code']).not.toHaveProperty('canRefreshModels');+ expect(afterUpdate.providers['claude-code'].enabled).toBe(false);+ // …and the response still reports the DERIVED value, not the echoed one.+ expect(put.body.canRefreshModels).toBe(true);+ });++ it('a POSTed canRefreshModels is not stored either, and does not fake the answer', async () => {+ const res = await createProvider({+ id: 'codex', name: 'Codex CLI', type: 'cli', command: 'codex', canRefreshModels: true,+ });+ expect(res.status).toBe(201);+ // Derived from the table, which has no codex row — the client's button+ // must stay hidden regardless of what the payload claimed.+ expect(res.body.canRefreshModels).toBe(false);++ const stored = await readStored();+ expect(stored.providers.codex).not.toHaveProperty('canRefreshModels');+ });++ it('decorates GET /:id and GET /active too, so every read agrees', async () => {+ await createProvider({ id: 'claude-code', name: 'Claude Code CLI', type: 'cli', command: 'claude' });+ await request(app).put('/api/providers/active').send({ id: 'claude-code' });++ const byId = await request(app).get('/api/providers/claude-code');+ expect(byId.body.canRefreshModels).toBe(true);++ const active = await request(app).get('/api/providers/active');+ expect(active.body.canRefreshModels).toBe(true);+ });+});diff --git a/server/routes/providers.js b/server/routes/providers.jsindex f24b6aa5b3..13299a3d23 100644--- a/server/routes/providers.js+++ b/server/routes/providers.js@@ -3,6 +3,7 @@ import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { testVision, runVisionTestSuite, checkVisionHealth } from '../services/visionTest.js';import { getAllProviderStatuses, getProviderStatus, markProviderAvailable, getTimeUntilRecovery } from '../services/providerStatus.js';import { providerSchema, providerActiveSchema, validate } from '../lib/aiToolkit/validation.js';+import { withRefreshCapability } from '../lib/aiToolkit/internal/modelFetchers.js';/*** Sanitize a provider object for client responses.@@ -28,6 +29,23 @@ const sanitizeProvider = (provider) => {return sanitized;};+/**+ * The shape a provider takes on its way OUT to the client: secrets stripped,+ * plus the derived `canRefreshModels` flag the AI Providers page reads to+ * decide whether to offer a "Refresh Models" button (#3620).+ *+ * Order matters. `canRefreshModels` is computed on the RAW provider, before+ * sanitization: the ollama row of the fetcher table keys partly on+ * `envVars.ANTHROPIC_BASE_URL`, which `sanitizeProvider` redacts to `'***'`+ * when the user marked it secret — deriving after would silently drop the+ * Refresh button for a Claude-Ollama provider.+ *+ * These PortOS routes SHADOW the toolkit's own (which decorate the same way);+ * the toolkit keeps its copy so it stays correct standalone. Both decorate on+ * the way out only — the field is never persisted.+ */+const presentProvider = (provider) => sanitizeProvider(withRefreshCapability(provider));+/*** Create PortOS-specific provider routes* Extends AI Toolkit routes with vision testing endpoints@@ -41,13 +59,13 @@ export function createPortOSProviderRoutes(aiToolkit) {const data = await providerService.getAllProviders();res.json({activeProvider: data.activeProvider,- providers: data.providers.map(sanitizeProvider)+ providers: data.providers.map(presentProvider)});}));router.get('/active', asyncHandler(async (req, res) => {const provider = await providerService.getActiveProvider();- res.json(sanitizeProvider(provider));+ res.json(presentProvider(provider));}));// PUT /active must be defined before PUT /:id to avoid the wildcard@@ -62,12 +80,12 @@ export function createPortOSProviderRoutes(aiToolkit) {if (!provider) {throw new ServerError('Provider not found', { status: 404 });}- res.json(sanitizeProvider(provider));+ res.json(presentProvider(provider));}));router.get('/samples', asyncHandler(async (req, res) => {const providers = await providerService.getSampleProviders();- res.json({ providers: providers.map(sanitizeProvider) });+ res.json({ providers: providers.map(presentProvider) });}));// Provider status routes MUST be defined before toolkit routes,@@ -132,7 +150,7 @@ export function createPortOSProviderRoutes(aiToolkit) {router.get('/:id', asyncHandler(async (req, res) => {const provider = await providerService.getProviderById(req.params.id);if (!provider) throw new ServerError('Provider not found', { status: 404 });- res.json(sanitizeProvider(provider));+ res.json(presentProvider(provider));}));// PUT /:id — intercept to (a) validate the body via a partial provider@@ -167,7 +185,7 @@ export function createPortOSProviderRoutes(aiToolkit) {}const provider = await providerService.updateProvider(req.params.id, updates);- res.json(sanitizeProvider(provider));+ res.json(presentProvider(provider));}));// POST / — intercept to (a) validate the body against providerSchema so@@ -181,7 +199,7 @@ export function createPortOSProviderRoutes(aiToolkit) {throw new ServerError('Invalid provider data', { status: 400, code: 'VALIDATION_ERROR', context: { details: validation.errors } });}const provider = await providerService.createProvider(validation.data);- res.status(201).json(sanitizeProvider(provider));+ res.status(201).json(presentProvider(provider));}));// Mount base toolkit routes last (GET/PUT /:id and POST / are now shadoweddiff --git a/server/routes/providers.refreshCapability.test.js b/server/routes/providers.refreshCapability.test.jsnew file mode 100644index 0000000000..b3ebcf32fe--- /dev/null+++ b/server/routes/providers.refreshCapability.test.js@@ -0,0 +1,87 @@+import { describe, it, expect, vi } from 'vitest';+import express from 'express';+import { Router } from 'express';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';+import { createPortOSProviderRoutes } from './providers.js';++// #3620 — these PortOS routes SHADOW the toolkit's own GET handlers (they strip+// secrets first), so the toolkit's decoration alone never reaches the client.+// This suite pins that the sanitized responses carry `canRefreshModels` too,+// and that it is derived BEFORE redaction — the Claude-Ollama case below is the+// one where deriving after would silently hide the Refresh button.++const CLAUDE_OLLAMA = {+ id: 'claude-ollama',+ name: 'Claude Ollama',+ type: 'cli',+ command: 'claude',+ apiKey: 'sk-secret',+ envVars: { ANTHROPIC_BASE_URL: 'http://localhost:11434' },+ secretEnvVars: ['ANTHROPIC_BASE_URL'],+};+const CODEX = { id: 'codex', name: 'Codex CLI', type: 'cli', command: 'codex', envVars: {} };++function appWith(providerService) {+ const toolkit = { services: { providers: providerService }, routes: { providers: Router() } };+ const app = express();+ app.use(express.json());+ app.use('/api/providers', createPortOSProviderRoutes(toolkit));+ app.use(errorMiddleware);+ return app;+}++describe('#3620: sanitized PortOS provider routes carry canRefreshModels', () => {+ it('GET / decorates each provider and still strips the apiKey', async () => {+ const app = appWith({+ getAllProviders: vi.fn().mockResolvedValue({ activeProvider: 'codex', providers: [CLAUDE_OLLAMA, CODEX] }),+ });++ const res = await request(app).get('/api/providers');+ expect(res.status).toBe(200);+ const byId = Object.fromEntries(res.body.providers.map((p) => [p.id, p]));+ expect(byId['claude-ollama'].canRefreshModels).toBe(true);+ expect(byId.codex.canRefreshModels).toBe(false);+ expect(byId['claude-ollama'].apiKey).toBeUndefined();+ expect(byId['claude-ollama'].hasApiKey).toBe(true);+ });++ it('derives the flag BEFORE redaction — a secret ANTHROPIC_BASE_URL still counts', async () => {+ // `sanitizeProvider` rewrites the value to '***', which no longer looks like+ // an Ollama endpoint. Sanitizing first would report `false` here and drop+ // the Refresh button for every Claude-Ollama install that marked the var+ // secret — a silent regression with no error anywhere.+ const app = appWith({ getProviderById: vi.fn().mockResolvedValue(CLAUDE_OLLAMA) });++ const res = await request(app).get('/api/providers/claude-ollama');+ expect(res.status).toBe(200);+ expect(res.body.envVars.ANTHROPIC_BASE_URL).toBe('***');+ expect(res.body.canRefreshModels).toBe(true);+ });++ it('decorates GET /active as well', async () => {+ const app = appWith({ getActiveProvider: vi.fn().mockResolvedValue(CODEX) });++ const res = await request(app).get('/api/providers/active');+ expect(res.status).toBe(200);+ expect(res.body.canRefreshModels).toBe(false);+ });++ it('decorates the PUT /:id response without persisting the field', async () => {+ const updateProvider = vi.fn().mockResolvedValue({ ...CODEX, enabled: false });+ const app = appWith({+ getProviderById: vi.fn().mockResolvedValue(CODEX),+ updateProvider,+ });++ const res = await request(app)+ .put('/api/providers/codex')+ .send({ enabled: false, canRefreshModels: true });+ expect(res.status).toBe(200);+ // Derived, not echoed: the table has no codex row.+ expect(res.body.canRefreshModels).toBe(false);+ // `providerSchema.partial()` strips the unknown key before it reaches the+ // service, so it can never be written to providers.json.+ expect(updateProvider.mock.calls[0][1]).not.toHaveProperty('canRefreshModels');+ });+});