Skip to content

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

fix: close local review-gate findings

Adam Eivy6a0de1cfdb22
diff --git a/client/src/pages/AIProviders.jsx b/client/src/pages/AIProviders.jsx
index de8f3b79ab..743ad3bf71 100644
--- a/client/src/pages/AIProviders.jsx
+++ b/client/src/pages/AIProviders.jsx
@@ -2,7 +2,7 @@ import { useState, useEffect, useCallback } from 'react';
import toast from '../components/ui/Toast';
import * as api from '../services/api';
import socket from '../services/socket';
-import { filterSelectableModels, filterGenerationModels, isEmbeddingModel, mergeModelLists, configuredDefaultIn, localBackendForProvider, modelOptionLabel, providerTypeClass, isTuiProvider, isApiProvider, isProcessProvider, isOllamaBackedProvider, isAntigravityProvider, isCursorCommand, isGrokBuildCli, isLocalEndpoint, effectiveModelContextWindow } from '../utils/providers';
+import { filterSelectableModels, filterGenerationModels, isEmbeddingModel, mergeModelLists, configuredDefaultIn, localBackendForProvider, modelOptionLabel, providerTypeClass, isTuiProvider, isApiProvider, isProcessProvider, isOllamaBackedProvider, isAntigravityProvider, supportsModelRefresh, isGrokBuildCli, isLocalEndpoint, effectiveModelContextWindow } from '../utils/providers';
import useLocalModels from '../hooks/useLocalModels';
import BrailleSpinner from '../components/BrailleSpinner';
import EmptyState from '../components/EmptyState';
@@ -154,40 +154,6 @@ export default function AIProviders() {
loadData();
};
- const supportsModelRefresh = (provider) => {
- // Claude Ollama (ollama-backed claude CLI/TUI) refreshes its model list from
- // the local Ollama daemon — including the TUI variant, which the server now
- // refreshes via the type==='tui' && ollamaBacked branch. Check this before
- // the generic TUI gate so the TUI variant's Refresh Models button shows.
- if (isOllamaBackedProvider(provider)) {
- return true;
- }
- // Antigravity (`agy`) exposes a per-session `--model` flag and an
- // `agy models` catalog, so BOTH its CLI and TUI providers refresh (the
- // server has a type==='tui' branch for it) — checked before the generic
- // TUI gate, same as Claude Ollama above.
- if (isAntigravityProvider(provider)) {
- return true;
- }
- if (isTuiProvider(provider)) {
- return false;
- }
- // Gemini/Grok Build CLIs use their own local model configuration (no PortOS
- // model list to refresh — same as the configured-default sentinel).
- if (provider.type === 'cli' && (provider.command === 'gemini' || provider.command === 'grok')) {
- return false;
- }
- // Cursor is hidden for the OPPOSITE reason, so it gets its own clause rather
- // than joining the two above: `cursor-agent models` does print an
- // authoritative per-account catalog, there just isn't a server-side fetcher
- // for it yet, so the button could only ever produce an error toast. This
- // clause is temporary where theirs are permanent.
- if (provider.type === 'cli' && isCursorCommand(provider.command)) {
- return false;
- }
- // All other providers support refresh (API and CLI)
- return true;
- };
const handleRefreshModels = async (id) => {
setRefreshing(prev => ({ ...prev, [id]: true }));
diff --git a/client/src/utils/providers.js b/client/src/utils/providers.js
index b4b214f03e..ebf493f7b3 100644
--- a/client/src/utils/providers.js
+++ b/client/src/utils/providers.js
@@ -125,6 +125,45 @@ export const isAntigravityProvider = (provider) => {
*/
export const isCursorCommand = (command) => commandBasename(command) === 'cursor-agent';
+/**
+ * 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.
+ *
+ * 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
+ * @returns {boolean}
+ */
+export const supportsModelRefresh = (provider) => {
+ // Claude Ollama (ollama-backed claude CLI/TUI) refreshes its model list from
+ // the local Ollama daemon — including the TUI variant, which the server
+ // refreshes via the type==='tui' && ollamaBacked branch. Check this before
+ // the generic TUI gate so the TUI variant's Refresh Models button shows.
+ if (isOllamaBackedProvider(provider)) return true;
+ // Antigravity (`agy`) exposes a per-session `--model` flag and an
+ // `agy models` catalog, so BOTH its CLI and TUI providers refresh (the
+ // server has a type==='tui' branch for it) — checked before the generic
+ // TUI gate, same as Claude Ollama above.
+ if (isAntigravityProvider(provider)) return true;
+ if (isTuiProvider(provider)) return false;
+ // Gemini/Grok Build CLIs use their own local model configuration (no PortOS
+ // model list to refresh — same as the configured-default sentinel).
+ if (provider?.type === 'cli' && (provider.command === 'gemini' || provider.command === 'grok')) return false;
+ // Cursor is hidden for the OPPOSITE reason, so it gets its own clause rather
+ // than joining the two above: `cursor-agent models` does print an
+ // authoritative per-account catalog, there just isn't a server-side fetcher
+ // for it yet, so the button could only ever produce an error toast. This
+ // clause is temporary where theirs are permanent.
+ if (provider?.type === 'cli' && isCursorCommand(provider.command)) return false;
+ // All other providers support refresh (API and CLI)
+ return true;
+};
+
export const knownProviderContextWindow = (provider) => {
if (!isProcessProvider(provider)) return null;
const id = String(provider?.id || '').toLowerCase();
diff --git a/client/src/utils/providers.test.js b/client/src/utils/providers.test.js
index 448810629a..544e3e7857 100644
--- a/client/src/utils/providers.test.js
+++ b/client/src/utils/providers.test.js
@@ -36,6 +36,7 @@ import {
isKimiProvider,
isCodexProvider,
isCursorCommand,
+ supportsModelRefresh,
isAntigravityProvider,
effortLevelsForProvider,
resolveCliEffort,
@@ -732,7 +733,40 @@ describe('isKimiProvider (mirror of server providerModels)', () => {
});
});
-describe('isCursorCommand (mirror of server lib/providerModels.js)', () => {
+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.
+ it('hides the button for cursor — no server-side fetcher exists yet', () => {
+ expect(supportsModelRefresh({ id: 'cursor-cli', type: 'cli', command: 'cursor-agent' })).toBe(false);
+ // Path-configured cursor must be hidden too, or the button 404s.
+ expect(supportsModelRefresh({ id: 'custom', type: 'cli', command: '/Users/x/.local/bin/cursor-agent' })).toBe(false);
+ });
+
+ it('hides the button for the TUI variant via the generic TUI gate', () => {
+ expect(supportsModelRefresh({ id: 'cursor-tui', type: 'tui', command: 'cursor-agent' })).toBe(false);
+ });
+
+ it('keeps hiding it for gemini/grok, whose model config is CLI-local', () => {
+ expect(supportsModelRefresh({ id: 'grok-cli', type: 'cli', command: 'grok' })).toBe(false);
+ expect(supportsModelRefresh({ id: 'gemini-cli', type: 'cli', command: 'gemini' })).toBe(false);
+ });
+
+ 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 })).toBe(true);
+ expect(supportsModelRefresh({ id: 'antigravity-tui', type: 'tui', command: 'agy' })).toBe(true);
+ expect(supportsModelRefresh({ id: 'claude-code', type: 'cli', command: 'claude' })).toBe(true);
+ expect(supportsModelRefresh({ id: 'lmstudio', type: 'api', endpoint: 'http://localhost:1234/v1' })).toBe(true);
+ });
+
+ it('does not throw on a nullish provider', () => {
+ expect(() => supportsModelRefresh(null)).not.toThrow();
+ expect(() => supportsModelRefresh(undefined)).not.toThrow();
+ });
+});
+
+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);
diff --git a/scripts/migrations/231-cursor-providers.test.js b/scripts/migrations/231-cursor-providers.test.js
index 383a1ffb36..37599ae9d2 100644
--- a/scripts/migrations/231-cursor-providers.test.js
+++ b/scripts/migrations/231-cursor-providers.test.js
@@ -76,28 +76,32 @@ describe('migration 231 — Cursor providers', () => {
expect(out.providers['cursor-tui']).toBeDefined();
});
- it('deep-copies shipped arrays/objects so mutating the install cannot corrupt the frozen defaults', async () => {
+ // Replaces a pair of "deep-copy isolation" tests that could not fail: they
+ // mutated a value re-parsed from disk, which has no reference relationship to
+ // the module-level CURSOR_MODELS, so `structuredClone` could be deleted
+ // outright and they would still pass. What is actually worth pinning is the
+ // frozen payload this migration installs — it is the historical record an
+ // upgraded install receives, and it must match what a fresh install seeds.
+ it('installs the exact frozen model catalog and tier pointers', () => {
writeJson(providersPath, { providers: {} });
- await migration.up({ rootDir });
- const first = readJson(providersPath);
- first.providers['cursor-cli'].models.push('mutated');
-
- // A second install run must still ship the pristine model list.
- const rootDir2 = mkdtempSync(join(tmpdir(), 'migration-231-b-'));
- mkdirSync(join(rootDir2, 'data'), { recursive: true });
- const providersPath2 = join(rootDir2, 'data/providers.json');
- writeJson(providersPath2, { providers: {} });
- await migration.up({ rootDir: rootDir2 });
- expect(readJson(providersPath2).providers['cursor-cli'].models).not.toContain('mutated');
- rmSync(rootDir2, { recursive: true, force: true });
- });
-
- it('gives the CLI and TUI entries independent model arrays (they share one source list)', async () => {
- writeJson(providersPath, { providers: {} });
- await migration.up({ rootDir });
- const out = readJson(providersPath);
- out.providers['cursor-cli'].models.push('leaked');
- expect(out.providers['cursor-tui'].models).not.toContain('leaked');
+ return migration.up({ rootDir }).then(() => {
+ const out = readJson(providersPath);
+ for (const id of ['cursor-cli', 'cursor-tui']) {
+ const p = out.providers[id];
+ expect(p.defaultModel).toBe('auto');
+ expect(p.lightModel).toBe('composer-2.5');
+ expect(p.mediumModel).toBe('claude-sonnet-5-thinking-high');
+ expect(p.heavyModel).toBe('claude-opus-5-thinking-high');
+ expect(p.models).toHaveLength(27);
+ // Every tier pointer must be selectable, or the picker renders blank.
+ for (const tier of [p.defaultModel, p.lightModel, p.mediumModel, p.heavyModel]) {
+ expect(p.models, `${id}: ${tier} missing from models`).toContain(tier);
+ }
+ }
+ // Both entries are built from one shared CURSOR_MODELS constant — they must
+ // ship the same catalog, or a user's CLI and TUI offer different models.
+ expect(out.providers['cursor-cli'].models).toEqual(out.providers['cursor-tui'].models);
+ });
});
it('is idempotent — a second run makes no changes', async () => {
diff --git a/server/lib/README.md b/server/lib/README.md
index 13189a2637..fe665c1729 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -116,7 +116,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `cliChildEnv.js` | The one place the AI-CLI child environment is composed, replacing the hand-rolled copy every spawn site carried — which made each env-level fix an N-file sweep (#3194). `buildCliChildEnv({ baseEnv, before, provider, model, cwd, extra, guard })` returns a COMPLETE env for `spawn`: layers `baseEnv → before → provider.envVars → buildOpencodeEnvVars → extra`, pins `PWD` to `cwd`, strips `CLAUDECODE`, and (with `guard: true`) prepends the pm2 guard shim onto the final `PATH`. `composeProviderEnv({ before, provider, model, extra })` returns just the ordered provider layers, for sites that build a DELTA someone else bases and spawns (the CoS runner payload, a shell-session overlay). The two slots are not interchangeable: `before` sits UNDER `provider.envVars` (forgeTokenEnv/claudeSettingsEnv, so a provider override still wins), `extra` sits OVER it (TERM/COLORTERM for a PTY). `cliChildEnv.test.js` asserts the composed order per call site and **discovers** any new site that hand-rolls the tuple instead of calling these — so the call-site list stays in the test, not in prose here. |
| `cliProviderArgs.js` | Per-CLI argv conventions (`buildCliArgs`) for stdin prompt delivery — dependency-light extraction from runner.js so out-of-process callers (autofixer) can import it. |
| `cliProviderRun.js` | One-shot CLI provider invocation (`pickCliProvider` + `runCliProviderPrompt`) — lightweight path for the autofixer + calendar MCP sync to honor the configured provider/model. |
-| `cursor.js` | Cursor Agent (`cursor-agent`) provider helpers — id/command constants (`CURSOR_CLI_ID`/`CURSOR_TUI_ID`/`CURSOR_COMMAND`), `isCursorCommand`/`isCursorCliProvider`/`isCursorTuiProvider` predicates, and `ensureCursorHeadlessArgs` (`--print --force`) / `ensureCursorTuiArgs` (`--force`) argv builders. `--force` is load-bearing beyond approvals: it also clears cursor's workspace-trust gate, which otherwise EXITS a headless run before any work happens. The prompt rides raw stdin (like claude/codex, unlike grok/kimi), and cursor needs no configured-default sentinel — its `auto` router is a real model id passed straight to `--model`. |
+| `cursor.js` | Cursor Agent (`cursor-agent`) provider helpers — the `CURSOR_COMMAND` binary constant, the `isCursorCommand` predicate, and the `ensureCursorHeadlessArgs` (`--print --force`) / `ensureCursorTuiArgs` (`--force`) argv builders. `--force` is load-bearing beyond approvals: it also clears cursor's workspace-trust gate, which otherwise EXITS a headless run before any work happens. The prompt rides raw stdin (like claude/codex, unlike grok/kimi), and cursor needs no configured-default sentinel — its `auto` router is a real model id passed straight to `--model`. |
| `grok.js` | xAI Grok Build (`grok`) provider helpers — id/endpoint constants (`GROK_API_ID`/`GROK_CLI_ID`/`GROK_TUI_ID`/`GROK_API_ENDPOINT`), `isGrokCommand`/`isGrokCliProvider`/`isGrokTuiProvider` predicates, `ensureGrokHeadlessArgs`/`ensureGrokTuiArgs` argv builders (grok reads its prompt from `--prompt-file /dev/stdin`, not raw stdin; model selection uses the `GROK_CONFIGURED_DEFAULT` sentinel in `providerModels.js` so PortOS omits `--model` like Antigravity), and `prepareGrokPromptFile` (Windows temp-file delivery fallback). |
| `grokVideoClip.js` | Clip lengths grok's `image_to_video` actually delivers — `GROK_VIDEO_DURATIONS` (`[6, 10]`, measured in #3022: a 2s/3s request returns the same 6.04s clip), `GROK_VIDEO_DEFAULT_DURATION`, `resolveGrokDuration()` (validate an already-grok-shaped request, else default), and `nearestGrokDuration()` (round a length authored against another backend's continuous contract UP to the shortest clip that covers it — for translating a CD/commission `targetDurationSeconds`). Dependency-free so `validation.js` / `routes/videoGen.js` can derive their schemas from the same list the services gate on. |
| `kimi.js` | Moonshot AI Kimi Code (`kimi`) provider helpers — id constants (`KIMI_CLI_ID`/`KIMI_TUI_ID`), `isKimiCommand`/`isKimiCliProvider`/`isKimiTuiProvider` predicates, `ensureKimiHeadlessArgs` (`--print`, implies `--afk`) / `ensureKimiTuiArgs` (`--yolo`) argv builders (model selection uses the `KIMI_CONFIGURED_DEFAULT` sentinel in `providerModels.js` so PortOS omits `--model` like Grok/Antigravity), and `prepareKimiPrompt` (delivers the prompt as the `--prompt <value>` argv, not stdin). |
diff --git a/server/lib/cursor.js b/server/lib/cursor.js
index 4ab3aa383b..4a3f7c6c16 100644
--- a/server/lib/cursor.js
+++ b/server/lib/cursor.js
@@ -64,11 +64,17 @@ export function isCursorCommand(command) {
// `--print` (`-p`) puts cursor-agent in non-interactive print mode.
const PRINT_FLAGS = ['--print', '-p'];
-// Approval/trust postures. `--force`/`-f`/`--yolo` run everything unprompted and
-// also satisfy the workspace-trust gate; `--auto-review` is the server-classifier
-// middle ground; `--trust` clears trust only. Any one present means the user
-// pinned their own posture — don't add another.
-const APPROVAL_FLAGS = ['--force', '-f', '--yolo', '--auto-review', '--trust'];
+// APPROVAL postures — flags that decide what happens when a tool call needs
+// permission. `--force`/`-f`/`--yolo` run everything unprompted; `--auto-review`
+// is the server-classifier middle ground. Any one present means the user pinned
+// their own posture, so don't add another.
+//
+// `--trust` is deliberately NOT in this list. It clears the workspace-trust gate
+// and nothing else, so treating it as an approval posture would suppress
+// `--force` and leave an unattended run to stall on the first tool prompt with
+// nobody to answer it — burning the full provider timeout to produce nothing.
+// A user who pins `--trust` still gets `--force` added, which is a superset of it.
+const APPROVAL_FLAGS = ['--force', '-f', '--yolo', '--auto-review'];
/**
* Build the headless (one-shot) argv for the Cursor Agent CLI. Ensures, when not
diff --git a/server/lib/cursor.test.js b/server/lib/cursor.test.js
index e128d94487..519372e6e2 100644
--- a/server/lib/cursor.test.js
+++ b/server/lib/cursor.test.js
@@ -42,12 +42,19 @@ describe('ensureCursorHeadlessArgs', () => {
expect(ensureCursorHeadlessArgs(['-p'], null)).toEqual(['-p', '--force']);
});
- it('respects any user-pinned trust/approval posture instead of adding --force', () => {
- for (const flag of ['--force', '-f', '--yolo', '--auto-review', '--trust']) {
+ it('respects any user-pinned APPROVAL posture instead of adding --force', () => {
+ for (const flag of ['--force', '-f', '--yolo', '--auto-review']) {
expect(ensureCursorHeadlessArgs(['--print', flag], null)).toEqual(['--print', flag]);
}
});
+ // `--trust` only clears the workspace-trust gate — it is NOT an approval
+ // posture. Treating it as one would suppress `--force` and leave an unattended
+ // run stalled on the first tool prompt until the provider timeout expires.
+ it('still adds --force when the user pinned only --trust', () => {
+ expect(ensureCursorHeadlessArgs(['--print', '--trust'], null)).toEqual(['--print', '--trust', '--force']);
+ });
+
it('respects a joined posture flag (--force=true style)', () => {
expect(ensureCursorHeadlessArgs(['--print', '--force=true'], null)).toEqual(['--print', '--force=true']);
});
@@ -76,12 +83,16 @@ describe('ensureCursorTuiArgs', () => {
expect(ensureCursorTuiArgs([])).toEqual(['--force']);
});
- it('leaves a user-pinned posture alone', () => {
- for (const flag of ['--force', '-f', '--yolo', '--auto-review', '--trust']) {
+ it('leaves a user-pinned approval posture alone', () => {
+ for (const flag of ['--force', '-f', '--yolo', '--auto-review']) {
expect(ensureCursorTuiArgs([flag])).toEqual([flag]);
}
});
+ it('still adds --force when the user pinned only --trust (trust is not approval)', () => {
+ expect(ensureCursorTuiArgs(['--trust'])).toEqual(['--trust', '--force']);
+ });
+
it('does not mutate the caller-supplied args array and is idempotent', () => {
const base = [];
const once = ensureCursorTuiArgs(base);
diff --git a/server/lib/providerModels.test.js b/server/lib/providerModels.test.js
index cf0d7091e3..7d15fec059 100644
--- a/server/lib/providerModels.test.js
+++ b/server/lib/providerModels.test.js
@@ -741,11 +741,14 @@ describe('providerModels', () => {
it('maps a bare Claude id on a Bedrock box', () => {
const spy = vi.spyOn(console, 'error').mockImplementation(() => {});
- withBedrock(() => {
- expect(resolveInjectedTuiModel('claude-opus-4-8', { id: 'claude-code-tui' }, 'claude'))
- .toBe('global.anthropic.claude-opus-4-8');
- });
- spy.mockRestore();
+ try {
+ withBedrock(() => {
+ expect(resolveInjectedTuiModel('claude-opus-4-8', { id: 'claude-code-tui' }, 'claude'))
+ .toBe('global.anthropic.claude-opus-4-8');
+ });
+ } finally {
+ spy.mockRestore();
+ }
});
it('namespaces an Ollama id for opencode and never Bedrock-maps it', () => {
@@ -774,16 +777,25 @@ describe('providerModels', () => {
.map((p) => p.command),
)];
expect(commands.length).toBeGreaterThan(1);
+ // Filter with the SAME predicate the helper gates on, not an exact-string
+ // `!== 'claude'` — a seed that ever ships a pathed `/opt/homebrew/bin/claude`
+ // TUI command would otherwise fail this spuriously instead of flagging a
+ // real regression.
+ const nonClaude = commands.filter((c) => !isClaudeCommand(c));
+ expect(nonClaude.length).toBeGreaterThan(0);
const spy = vi.spyOn(console, 'error').mockImplementation(() => {});
- withBedrock(() => {
- for (const command of commands.filter((c) => c !== 'claude')) {
- expect(
- resolveInjectedTuiModel('claude-opus-5-thinking-high', { id: `${command}-tui` }, command),
- `${command} must not have its model id Bedrock-rewritten`,
- ).toBe('claude-opus-5-thinking-high');
- }
- });
- spy.mockRestore();
+ try {
+ withBedrock(() => {
+ for (const command of nonClaude) {
+ expect(
+ resolveInjectedTuiModel('claude-opus-5-thinking-high', { id: `${command}-tui` }, command),
+ `${command} must not have its model id Bedrock-rewritten`,
+ ).toBe('claude-opus-5-thinking-high');
+ }
+ });
+ } finally {
+ spy.mockRestore();
+ }
});
});
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.js
index 7f3738ef3a..d3fd1ca3f0 100644
--- a/server/services/agentTuiSpawning.js
+++ b/server/services/agentTuiSpawning.js
@@ -225,11 +225,14 @@ function shellHasLiveChild(shellPid) {
function appendModelArgs(args, model, command, provider) {
const effectiveModel = resolveCliModel(model);
if (!effectiveModel) return args;
- // OpenCode TUI launches with `opencode --model ollama/<id>` (the top-level
- // flag preselects the model). Respect a user-baked --model/-m pin (mirrors
- // buildTuiInvocation/buildCliArgs) rather than appending a second flag that
- // overrides it.
- if (isOpencodeCommand(command) && hasModelFlag(args)) return args;
+ // Respect a user-baked --model/-m pin for EVERY command rather than appending
+ // a second flag that overrides it — the same gate `buildTuiInvocation` and
+ // `buildCliArgs` apply, and the documented convention repo-wide ("a baked pin
+ // wins"). This used to be scoped to opencode alone, so a pinned claude/codex —
+ // and now cursor — provider spawned `--model <pin> --model <ui-choice>`, where
+ // last-flag-wins silently discarded the user's pin (or the CLI rejected the
+ // duplicate outright).
+ if (hasModelFlag(args)) return args;
// Antigravity never reaches here: buildTuiSpawnConfig resolves its model and
// effort together up front (agy validates the pair) — see antigravity.js.
diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.js
index 42b015298b..c8d37b4b79 100644
--- a/server/services/agentTuiSpawning.test.js
+++ b/server/services/agentTuiSpawning.test.js
@@ -144,15 +144,17 @@ vi.mock('../lib/providerModels.js', async (importOriginal) => ({
// Mirror the real behaviour: pass through the model string, return null for
// the codex-configured-default sentinel or null/undefined input.
resolveCliModel: vi.fn((m) => (m === 'codex-configured-default' || !m) ? null : m),
- // Bedrock map is a no-op off Bedrock — mirror that pass-through here (the
- // mapper itself is unit-tested in providerModels.test.js).
- resolveBedrockCliModel: vi.fn((m) => m),
+ // NOTE: `appendModelArgs` calls `resolveInjectedTuiModel`, which is pulled in
+ // REAL via importOriginal above and calls `resolveBedrockCliModel` /
+ // `prefixOpencodeModel` as module-INTERNAL references — a vi.mock override of
+ // those two names cannot intercept an internal call, so stubbing them here
+ // would be dead weight that reads as protection. Instead the suite pins the
+ // one input the real mapper keys on (`CLAUDE_CODE_USE_BEDROCK`, cleared in
+ // beforeEach below), so these assertions are deterministic regardless of the
+ // ambient env on a developer's Bedrock box or a CI runner.
// Mirror the real opencode-command basename match (fully unit-tested in
// providerModels.test.js).
isOpencodeCommand: vi.fn((c) => typeof c === 'string' && c.split(/[\\/]/).pop().toLowerCase().replace(/\.exe$/, '') === 'opencode'),
- // Mirror the real ollama/ namespacing for opencode providers (fully unit-
- // tested in providerModels.test.js).
- prefixOpencodeModel: vi.fn((p, m) => (typeof p?.command === 'string' && p.command.split(/[\\/]/).pop().toLowerCase().replace(/\.exe$/, '') === 'opencode' && p?.ollamaBacked === true && m && !String(m).startsWith('ollama/')) ? `ollama/${m}` : m),
// Mirror hasModelFlag (real impl unit-tested in providerModels.test.js).
hasModelFlag: vi.fn((a) => Array.isArray(a) && a.some((x) => x === '--model' || x === '-m' || (typeof x === 'string' && (x.startsWith('--model=') || x.startsWith('-m=')))))
}));
@@ -203,6 +205,62 @@ import { MAX_RUNTIME_WRAP_UP_GRACE_MS } from '../lib/tuiHandshake.js';
import { markHostShuttingDown, resetHostShutdownFlagForTests } from '../lib/hostShutdown.js';
describe('agent TUI spawning', () => {
+ // `buildTuiSpawnConfig` → `appendModelArgs` → the REAL `resolveInjectedTuiModel`,
+ // whose Bedrock arm reads process.env directly (see the vi.mock note above on why
+ // stubbing the mapper can't intercept that internal call). Pin the var here so a
+ // developer's Bedrock box — or a CI runner that exports it — can't flip these
+ // assertions; the tests that WANT Bedrock set it explicitly.
+ const bedrockBefore = process.env.CLAUDE_CODE_USE_BEDROCK;
+ beforeEach(() => { delete process.env.CLAUDE_CODE_USE_BEDROCK; });
+ afterEach(() => {
+ if (bedrockBefore === undefined) delete process.env.CLAUDE_CODE_USE_BEDROCK;
+ else process.env.CLAUDE_CODE_USE_BEDROCK = bedrockBefore;
+ });
+
+ // Regression guard for the drift this path actually shipped: `appendModelArgs`
+ // was a second, open-coded copy of the model-injection ladder, so cursor's
+ // Bedrock exemption landed only in `buildTuiInvocation` and a cursor CoS agent
+ // on a Bedrock box launched with a rewritten, unroutable model id. Both copies
+ // now delegate to `resolveInjectedTuiModel`; re-inlining the mapper here would
+ // break this test.
+ it('does not Bedrock-map a cursor TUI model id that merely contains "claude"', () => {
+ process.env.CLAUDE_CODE_USE_BEDROCK = '1';
+ const config = buildTuiSpawnConfig({
+ id: 'cursor-tui',
+ type: 'tui',
+ command: 'cursor-agent',
+ args: ['--force'],
+ }, 'claude-opus-5-thinking-high');
+ expect(config.args).toEqual(['--force', '--model', 'claude-opus-5-thinking-high']);
+ expect(config.args.join(' ')).not.toContain('anthropic.');
+ });
+
+ it('still Bedrock-maps a claude TUI model id on a Bedrock box', () => {
+ process.env.CLAUDE_CODE_USE_BEDROCK = '1';
+ const config = buildTuiSpawnConfig({
+ id: 'claude-code-tui',
+ type: 'tui',
+ command: 'claude',
+ args: ['--dangerously-skip-permissions'],
+ }, 'claude-opus-4-8');
+ expect(config.args).toContain('global.anthropic.claude-opus-4-8');
+ });
+
+ // A user-baked --model pin used to be honored only for opencode here, so a
+ // pinned claude/codex/cursor TUI spawned `--model <pin> --model <ui-choice>`
+ // and last-flag-wins silently discarded the pin.
+ it('honors a user-baked --model pin instead of appending a second flag', () => {
+ const config = buildTuiSpawnConfig({
+ id: 'cursor-tui',
+ type: 'tui',
+ command: 'cursor-agent',
+ args: ['--force', '--model', 'composer-2.5'],
+ }, 'auto');
+ expect(config.args.filter((a) => a === '--model')).toHaveLength(1);
+ expect(config.args).toContain('composer-2.5');
+ expect(config.args).not.toContain('auto');
+ });
+
it('builds a codex TUI command without a model flag for the configured-default sentinel', () => {
const config = buildTuiSpawnConfig({
id: 'codex-tui',