Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

show public models and authenticate on selection (#454)

ktecc2660c2583
diff --git a/packages/coding-agent/CHANGELOG.md b/packages/coding-agent/CHANGELOG.md
index 769625b65b..53c4c3a353 100644
--- a/packages/coding-agent/CHANGELOG.md
+++ b/packages/coding-agent/CHANGELOG.md
@@ -2,6 +2,9 @@
## [Unreleased]
+- Changed `/model` to show all public models with authenticated providers first and open provider authentication when an unavailable model is selected ([ENG-4575](https://linear.app/primeintellect/issue/ENG-4575/show-all-models-in-model-and-prompt-auth-on-selection)).
+- Changed the shared configuration menu to cycle tabs with Tab, use Shift+Tab for model scope, show an Escape close hint, preserve arrow-key search editing, and remove the model selector's provider shortcut.
+- Fixed searchable selectors retaining their previous scroll position after the query changed.
- Changed interactive, print, JSON, RPC, piped-stdin, and no-session clients to use the same daemon-owned runtime while preserving their existing commands, output protocols, and lifecycle behavior ([ENG-4685](https://linear.app/primeintellect/issue/ENG-4685)).
- Added RPC controls for schedules, heartbeats, agent messaging, and live session observation ([ENG-4685](https://linear.app/primeintellect/issue/ENG-4685)).
- Fixed daemon-backed headless startup, rollback routing, RPC wire compatibility, and duplicate client runtime preparation ([ENG-4685](https://linear.app/primeintellect/issue/ENG-4685)).
diff --git a/packages/coding-agent/docs/keybindings.md b/packages/coding-agent/docs/keybindings.md
index 4469b5f2bc..dfbd5347a1 100644
--- a/packages/coding-agent/docs/keybindings.md
+++ b/packages/coding-agent/docs/keybindings.md
@@ -119,17 +119,12 @@ Modifier combinations: `ctrl+shift+x`, `alt+ctrl+x`, `ctrl+shift+alt+x`, `ctrl+1
| Keybinding id | Default | Description |
|--------|---------|-------------|
| `app.model.select` | `ctrl+l` | Open model selector |
-| `app.provider.add` | `ctrl+p` | Add provider from the model selector |
+| `app.model.toggleScope` | `shift+tab` | Toggle between all and scoped models |
| `app.thinking.toggle` | `ctrl+t` | Collapse or expand thinking blocks |
### Configuration Menu
-Used inside the shared Providers, Models, and MCP Connections menu. When a search field contains text, its cursor movement takes precedence over these default arrow bindings.
-
-| Keybinding id | Default | Description |
-|--------|---------|-------------|
-| `app.configuration.previousTab` | `left` | Open the previous configuration tab |
-| `app.configuration.nextTab` | `right` | Open the next configuration tab |
+Use `tab` to cycle through Providers, Models, and MCP Connections, and `escape` to close the menu. Left and right move the cursor in the active search field.
### Display and Message Queue
diff --git a/packages/coding-agent/src/core/keybindings.ts b/packages/coding-agent/src/core/keybindings.ts
index 22f9a96ad2..588bd3a49c 100644
--- a/packages/coding-agent/src/core/keybindings.ts
+++ b/packages/coding-agent/src/core/keybindings.ts
@@ -18,9 +18,7 @@ export interface AppKeybindings {
"app.exit": true;
"app.suspend": true;
"app.model.select": true;
- "app.provider.add": true;
- "app.configuration.previousTab": true;
- "app.configuration.nextTab": true;
+ "app.model.toggleScope": true;
"app.tools.expand": true;
"app.thinking.toggle": true;
"app.subagents.focus": true;
@@ -85,9 +83,7 @@ export const KEYBINDINGS = {
description: "Suspend to background",
},
"app.model.select": { defaultKeys: "ctrl+l", description: "Open model selector" },
- "app.provider.add": { defaultKeys: "ctrl+p", description: "Add provider" },
- "app.configuration.previousTab": { defaultKeys: "left", description: "Open previous configuration tab" },
- "app.configuration.nextTab": { defaultKeys: "right", description: "Open next configuration tab" },
+ "app.model.toggleScope": { defaultKeys: "shift+tab", description: "Toggle model selector scope" },
"app.tools.expand": { defaultKeys: "ctrl+o", description: "Toggle tool output" },
"app.thinking.toggle": {
defaultKeys: "ctrl+t",
diff --git a/packages/coding-agent/src/core/model-registry.ts b/packages/coding-agent/src/core/model-registry.ts
index c9e78a4248..4f88a6e346 100644
--- a/packages/coding-agent/src/core/model-registry.ts
+++ b/packages/coding-agent/src/core/model-registry.ts
@@ -274,6 +274,11 @@ export type ResolvedRequestAuth =
error: string;
};
+export interface ModelCatalogSnapshot {
+ models: Model<Api>[];
+ configuredProviders: string[];
+}
+
/** Result of loading custom models from models.json */
interface CustomModelsResult {
models: Model<Api>[];
@@ -790,6 +795,20 @@ export class ModelRegistry {
}
}
+ async refreshModelCatalog(): Promise<ModelCatalogSnapshot> {
+ const availableModels = await this.refreshAvailableModels();
+ const availablePrivateModels = new Set(
+ availableModels.filter(isPrivatePrimeInferenceModel).map((model) => `${model.provider}/${model.id}`),
+ );
+ return {
+ models: this.models.filter(
+ (model) =>
+ !isPrivatePrimeInferenceModel(model) || availablePrivateModels.has(`${model.provider}/${model.id}`),
+ ),
+ configuredProviders: [...new Set(availableModels.map((model) => model.provider))],
+ };
+ }
+
async canUseModel(model: Model<Api>): Promise<boolean> {
if (!this.hasConfiguredAuth(model)) {
return false;
diff --git a/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts b/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts
index 00e31212b6..661810c111 100644
--- a/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts
+++ b/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts
@@ -52,6 +52,7 @@ import type {
AgentConnectionForkOptions,
AgentConnectionHeartbeat,
AgentConnectionModel,
+ AgentConnectionModelCatalog,
AgentConnectionModelCycleResult,
AgentConnectionNavigateTreeOptions,
AgentConnectionNavigateTreeResult,
@@ -427,6 +428,20 @@ export class DaemonAgentConnection implements AgentConnection {
return data.models;
}
+ async getModelCatalog(): Promise<AgentConnectionModelCatalog> {
+ if (!this.client.supportsServerCapability("model_catalog")) {
+ const models = await this.getAvailableModels();
+ return {
+ models,
+ configuredProviders: [...new Set(models.map((model) => model.provider))],
+ };
+ }
+ return this.requestData<AgentConnectionModelCatalog>({
+ type: "get_model_catalog",
+ activeSessionId: this.activeSessionId,
+ });
+ }
+
async getSessionStats(): Promise<SessionStats> {
return this.requestData<SessionStats>({
type: "get_session_stats",
@@ -1925,6 +1940,7 @@ function invalidatesCachedSnapshot(commandType: DaemonCommandBody["type"]): bool
case "get_session_stats":
case "get_commands":
case "get_resource_snapshot":
+ case "get_model_catalog":
case "get_available_models":
case "get_queue":
case "cron_list":
diff --git a/packages/coding-agent/src/modes/agent-connection/in-process-agent-connection.ts b/packages/coding-agent/src/modes/agent-connection/in-process-agent-connection.ts
index 3157bc1966..c6644ff46e 100644
--- a/packages/coding-agent/src/modes/agent-connection/in-process-agent-connection.ts
+++ b/packages/coding-agent/src/modes/agent-connection/in-process-agent-connection.ts
@@ -41,6 +41,7 @@ import type {
AgentConnectionForkOptions,
AgentConnectionHeartbeat,
AgentConnectionModel,
+ AgentConnectionModelCatalog,
AgentConnectionModelCycleResult,
AgentConnectionNavigateTreeOptions,
AgentConnectionNavigateTreeResult,
@@ -147,6 +148,10 @@ export class InProcessAgentConnection implements AgentConnection {
return this.session.modelRegistry.refreshAvailableModels();
}
+ async getModelCatalog(): Promise<AgentConnectionModelCatalog> {
+ return this.session.modelRegistry.refreshModelCatalog();
+ }
+
async getSessionStats(): Promise<SessionStats> {
return this.session.getSessionStats();
}
diff --git a/packages/coding-agent/src/modes/agent-connection/index.ts b/packages/coding-agent/src/modes/agent-connection/index.ts
index 7a6097c7d2..ee620b5465 100644
--- a/packages/coding-agent/src/modes/agent-connection/index.ts
+++ b/packages/coding-agent/src/modes/agent-connection/index.ts
@@ -20,6 +20,7 @@ export type {
AgentConnectionHeartbeat,
AgentConnectionLabelEntry,
AgentConnectionModel,
+ AgentConnectionModelCatalog,
AgentConnectionModelChangeEntry,
AgentConnectionModelCycleResult,
AgentConnectionNavigateTreeOptions,
diff --git a/packages/coding-agent/src/modes/agent-connection/types.ts b/packages/coding-agent/src/modes/agent-connection/types.ts
index 8bbd56a3e5..817e376924 100644
--- a/packages/coding-agent/src/modes/agent-connection/types.ts
+++ b/packages/coding-agent/src/modes/agent-connection/types.ts
@@ -46,6 +46,10 @@ import type { SessionStats } from "../../core/session-stats.js";
*/
export type AgentConnectionQueueMode = "all" | "one-at-a-time";
export type AgentConnectionModel = Model<Api>;
+export interface AgentConnectionModelCatalog {
+ models: AgentConnectionModel[];
+ configuredProviders: string[];
+}
export type AgentConnectionSavedSessionScope = "current" | "all";
export interface AgentConnectionSessionHeader {
@@ -590,6 +594,7 @@ export interface AgentConnection {
getSessionHeader(): Promise<AgentConnectionSessionHeader | undefined>;
getCommands(): Promise<AgentConnectionSlashCommand[]>;
getResourceSnapshot(): Promise<AgentConnectionResourceSnapshot>;
+ getModelCatalog(): Promise<AgentConnectionModelCatalog>;
getAvailableModels(): Promise<AgentConnectionModel[]>;
getSessionStats(): Promise<SessionStats>;
getContextTree(): Promise<ContextTreeNode>;
diff --git a/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts b/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts
index 18218af6d8..86bba27ff2 100644
--- a/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts
+++ b/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts
@@ -7,7 +7,6 @@ import {
type Component,
clippedFullscreenDockHeight,
type Focusable,
- fuzzyFilter,
ProcessTerminal,
setKeybindings,
TUI,
@@ -18,7 +17,7 @@ import {
import { APP_TITLE, appendRotatingLog, getAgentDir, getClientErrorLogPath, VERSION } from "../../config.js";
import type { AgentSessionRuntimeConfig } from "../../core/agent-session-config.js";
import { KeybindingsManager } from "../../core/keybindings.js";
-import type { ModelRegistry } from "../../core/model-registry.js";
+import type { ModelCatalogSnapshot, ModelRegistry } from "../../core/model-registry.js";
import { findExactModelReferenceMatch } from "../../core/model-resolver.js";
import { resolvePrimeInferencePostLoginModelAction } from "../../core/prime-inference-model-selection.js";
import { SessionManager } from "../../core/session-manager.js";
@@ -67,6 +66,7 @@ import {
theme,
} from "../interactive/theme/theme.js";
import { WORKING_ICON_INTERVAL_MS, workingIconFrame } from "../interactive/theme/working-icon.js";
+import { getModelArgumentCompletions } from "../model-autocomplete.js";
import {
formatPackageUpdateNotice,
formatTmuxWarningNotice,
@@ -230,22 +230,19 @@ export function formatAgentsViewStatusLine(text: string): string {
export async function getAgentsViewModelArgumentCompletions(
prefix: string,
- modelRegistry: Pick<ModelRegistry, "refreshAvailableModels">,
+ modelRegistry: Pick<ModelRegistry, "refreshModelCatalog">,
): Promise<AutocompleteItem[] | null> {
- const models = await modelRegistry.refreshAvailableModels();
- if (models.length === 0) {
- return null;
- }
- const items = models.map((model) => ({
- id: model.id,
- provider: model.provider,
- label: `${model.provider}/${model.id}`,
- }));
- const filtered = fuzzyFilter(items, prefix, (item) => `${item.id} ${item.provider}`);
- if (filtered.length === 0) {
- return null;
- }
- return filtered.map((item) => ({ value: item.label, label: item.id, description: item.provider }));
+ const catalog = await modelRegistry.refreshModelCatalog();
+ return getModelArgumentCompletions(prefix, catalog.models);
+}
+
+export function syncAgentsViewModelMenuAfterAuth(
+ menu: Pick<ConfigurationMenuComponent, "refreshAuthentication" | "updateModels">,
+ currentModel: Model<Api> | undefined,
+ catalog: ModelCatalogSnapshot,
+): void {
+ menu.refreshAuthentication();
+ menu.updateModels(currentModel, catalog.models, new Set(catalog.configuredProviders));
}
export function shouldReconnectAgentsViewDaemon(reason: DaemonClosingReason | undefined): boolean {
@@ -1011,14 +1008,15 @@ class AgentsViewMode implements Component, Focusable {
case "model": {
const searchTerm = command.args || undefined;
if (searchTerm) {
- // Mirror the in-session /model behavior: an exact provider/id or
- // unique model id reference applies directly without the picker.
- const match = findExactModelReferenceMatch(
- searchTerm,
- await this.options.uiServices.modelRegistry.refreshAvailableModels(),
- );
+ const authFlows = this.createAuthFlows();
+ const providerOptions = authFlows.getLoginProviderOptions();
+ const catalog = await this.options.uiServices.modelRegistry.refreshModelCatalog();
+ const match = findExactModelReferenceMatch(searchTerm, catalog.models);
if (match) {
- this.applyDefaultModel(match);
+ const { ready } = await this.ensureDefaultModelProviderConfigured(match, authFlows, providerOptions);
+ if (ready) {
+ this.applyDefaultModel(match);
+ }
return;
}
}
@@ -1088,10 +1086,41 @@ class AgentsViewMode implements Component, Focusable {
this.setStatusMessage(warning, { tone: "warning", sticky: true });
}
+ private async ensureDefaultModelProviderConfigured(
+ model: Model<Api>,
+ authFlows: ProviderAuthFlows,
+ providerOptions: ReadonlyArray<AuthSelectorProvider>,
+ ): Promise<{ ready: boolean; refreshedCatalog?: ModelCatalogSnapshot }> {
+ const modelRegistry = this.options.uiServices.modelRegistry;
+ if (modelRegistry.hasConfiguredAuth(model)) return { ready: true };
+
+ const provider = providerOptions.find(
+ (option) => option.id === model.provider && (option.category ?? "provider") === "provider",
+ );
+ if (!provider) {
+ this.setStatusMessage(`Authentication for ${model.provider} must be configured externally.`, {
+ tone: "error",
+ });
+ return { ready: false };
+ }
+
+ const result = await authFlows.loginProvider(provider);
+ if (result.status !== "success") return { ready: false };
+
+ const refreshedCatalog = await modelRegistry.refreshModelCatalog();
+ if (modelRegistry.hasConfiguredAuth(model)) return { ready: true, refreshedCatalog };
+
+ this.setStatusMessage(`Authentication completed, but ${model.provider} is still unavailable.`, {
+ tone: "error",
+ });
+ return { ready: false, refreshedCatalog };
+ }
+
private async showConfigurationMenu(initialTab: ConfigurationMenuTab, initialModelSearch?: string): Promise<void> {
const modelRegistry = this.options.uiServices.modelRegistry;
const authFlows = this.createAuthFlows();
- const availableModels = await modelRegistry.refreshAvailableModels();
+ const providerOptions = authFlows.getLoginProviderOptions();
+ const initialCatalog = await modelRegistry.refreshModelCatalog();
return new Promise((resolve) => {
let handle: OverlayHandle | undefined;
let settled = false;
@@ -1116,11 +1145,14 @@ class AgentsViewMode implements Component, Focusable {
.then(async (authResult) => {
if (settled) return;
handle?.focus();
- menu.refreshAuthentication();
- if (authResult.status !== "success" || tab === "mcp-connections") return;
+ if (authResult.status !== "success" || tab === "mcp-connections") {
+ menu.refreshAuthentication();
+ return;
+ }
await this.applyPrimeInferenceFallbackAfterLogin(authResult);
- menu.updateModels(this.getDefaultModelForNewAgents(), await modelRegistry.refreshAvailableModels());
+ const catalog = await modelRegistry.refreshModelCatalog();
+ syncAgentsViewModelMenuAfterAuth(menu, this.getDefaultModelForNewAgents(), catalog);
menu.setActiveTab("models");
})
.catch((error) => {
@@ -1133,11 +1165,12 @@ class AgentsViewMode implements Component, Focusable {
initialTab,
tui: this.ui,
authStorage: modelRegistry.authStorage,
- providerOptions: authFlows.getLoginProviderOptions(),
+ providerOptions,
modelRegistry,
currentModel: this.getDefaultModelForNewAgents(),
scopedModels: [],
- availableModels,
+ availableModels: initialCatalog.models,
+ configuredProviders: new Set(initialCatalog.configuredProviders),
recentModels: this.options.uiServices.settingsManager.getRecentModels(),
initialModelSearch,
getRows: () => this.ui.terminal.rows,
@@ -1145,8 +1178,26 @@ class AgentsViewMode implements Component, Focusable {
onSelectProvider: (provider) => authenticate(provider, "providers"),
onSelectMcpConnection: (provider) => authenticate(provider, "mcp-connections"),
onSelectModel: (model) => {
- this.applyDefaultModel(model);
- finish();
+ void (async () => {
+ try {
+ const result = await this.ensureDefaultModelProviderConfigured(model, authFlows, providerOptions);
+ handle?.focus();
+ if (result.refreshedCatalog) {
+ syncAgentsViewModelMenuAfterAuth(
+ menu,
+ this.getDefaultModelForNewAgents(),
+ result.refreshedCatalog,
+ );
+ } else {
+ menu.refreshAuthentication();
+ }
+ if (!result.ready || settled) return;
+ this.applyDefaultModel(model);
+ finish();
+ } catch (error) {
+ this.setStatusMessage(error instanceof Error ? error.message : String(error), { tone: "error" });
+ }
+ })();
},
onCancel: finish,
});
diff --git a/packages/coding-agent/src/modes/daemon/daemon-mode.ts b/packages/coding-agent/src/modes/daemon/daemon-mode.ts
index 8314b1bbb9..6858595f9c 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-mode.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-mode.ts
@@ -237,6 +237,7 @@ const DAEMON_COMMAND_TYPES: ReadonlySet<string> = new Set([
"get_context_tree",
"get_commands",
"get_resource_snapshot",
+ "get_model_catalog",
"get_available_models",
"get_queue",
"clear_queue",
@@ -3149,6 +3150,15 @@ export class AgentDaemon {
});
}
+ case "get_model_catalog": {
+ const state = this.getSessionState(command.activeSessionId);
+ return success(
+ command.id,
+ "get_model_catalog",
+ await state.runtime.session.modelRegistry.refreshModelCatalog(),
+ );
+ }
+
case "get_queue": {
const state = this.getSessionState(command.activeSessionId);
return success(command.id, "get_queue", {
diff --git a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts b/packages/coding-agent/src/modes/daemon/daemon-protocol.ts
index 5243e7614d..559135c5fe 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-protocol.ts
@@ -49,8 +49,8 @@ import type { SessionSummary } from "./daemon-session-list.js";
export const DAEMON_PROTOCOL_NAME = "prime-agent.daemon";
export const DAEMON_PROTOCOL_VERSION = 4;
export const DAEMON_COMMAND_ENVELOPE_MIN_PROTOCOL_VERSION = 2;
-export const DAEMON_SCHEMA_REVISION = 1;
-export const DAEMON_SCHEMA_ID = "protocol-4-schema-1-f55df8742274";
+export const DAEMON_SCHEMA_REVISION = 2;
+export const DAEMON_SCHEMA_ID = "protocol-4-schema-2-cbdbe20e7ce4";
export type DaemonProtocolName = typeof DAEMON_PROTOCOL_NAME;
export type DaemonProtocolVersion = number;
@@ -69,7 +69,11 @@ export type DaemonClientCapability =
| "slim_attach"
| "chunked_snapshot"
| "client_owned_sessions";
-export type DaemonServerCapability = DaemonClientCapability | "heartbeat_catalog" | "heartbeat_management";
+export type DaemonServerCapability =
+ | DaemonClientCapability
+ | "heartbeat_catalog"
+ | "heartbeat_management"
+ | "model_catalog";
export type DaemonReplayStatus = "complete" | "partial" | "unavailable";
export interface DaemonProtocolInfo {
@@ -100,6 +104,7 @@ export const DAEMON_DEFAULT_SERVER_CAPABILITIES: readonly DaemonServerCapability
...DAEMON_SUPPORTED_CLIENT_CAPABILITIES,
"heartbeat_catalog",
"heartbeat_management",
+ "model_catalog",
];
export interface DaemonRuntimeIdentity {
@@ -462,6 +467,7 @@ export type DaemonCommand =
| { id?: string; type: "get_context_tree"; activeSessionId: string }
| { id?: string; type: "get_commands"; activeSessionId: string }
| { id?: string; type: "get_resource_snapshot"; activeSessionId: string }
+ | { id?: string; type: "get_model_catalog"; activeSessionId: string }
| { id?: string; type: "get_available_models"; activeSessionId: string }
| { id?: string; type: "get_queue"; activeSessionId: string }
| { id?: string; type: "clear_queue"; activeSessionId: string }
@@ -613,6 +619,7 @@ export const DAEMON_COMMAND_COMPATIBILITY = {
get_context_tree: LEGACY_DAEMON_COMMAND,
get_commands: LEGACY_DAEMON_COMMAND,
get_resource_snapshot: LEGACY_DAEMON_COMMAND,
+ get_model_catalog: { minProtocol: 4, capability: "model_catalog" },
get_available_models: LEGACY_DAEMON_COMMAND,
get_queue: LEGACY_DAEMON_COMMAND,
clear_queue: LEGACY_DAEMON_COMMAND,
@@ -924,6 +931,7 @@ const READ_ONLY_DAEMON_COMMANDS: ReadonlySet<DaemonCommand["type"]> = new Set([
"get_context_tree",
"get_commands",
"get_resource_snapshot",
+ "get_model_catalog",
"get_available_models",
"get_queue",
"cron_list",
diff --git a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
index e5b2403be4..b85b89949a 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
@@ -148,6 +148,7 @@ const DAEMON_COMMAND_TYPES: ReadonlySet<string> = new Set([
"get_context_tree",
"get_commands",
"get_resource_snapshot",
+ "get_model_catalog",
"get_available_models",
"get_queue",
"clear_queue",
diff --git a/packages/coding-agent/src/modes/interactive/components/configuration-menu.ts b/packages/coding-agent/src/modes/interactive/components/configuration-menu.ts
index 3144176ba9..dc4f22b5e9 100644
--- a/packages/coding-agent/src/modes/interactive/components/configuration-menu.ts
+++ b/packages/coding-agent/src/modes/interactive/components/configuration-menu.ts
@@ -13,7 +13,7 @@ import type { ModelRegistry } from "../../../core/model-registry.js";
import { theme } from "../theme/theme.js";
import { keyText } from "./keybinding-hints.js";
import { getMenuPanelInnerWidth } from "./menu-panel.js";
-import { type ModelSelectorAction, ModelSelectorComponent } from "./model-selector.js";
+import { ModelSelectorComponent } from "./model-selector.js";
import { type AuthSelectorProvider, OAuthSelectorComponent } from "./oauth-selector.js";
export const CONFIGURATION_MENU_TABS = ["providers", "models", "mcp-connections"] as const;
@@ -34,6 +34,7 @@ export interface ConfigurationMenuOptions {
currentModel: Model<Api> | undefined;
scopedModels: ReadonlyArray<ConfigurationMenuScopedModel>;
availableModels: ReadonlyArray<Model<Api>>;
+ configuredProviders: ReadonlySet<string>;
recentModels?: ReadonlyArray<string>;
initialModelSearch?: string;
getRows?: () => number;
@@ -44,10 +45,6 @@ export interface ConfigurationMenuOptions {
onCancel: () => void;
}
-const MODEL_SELECTOR_ACTIONS: readonly ModelSelectorAction[] = [
- { id: "add_provider", label: "Add provider...", description: "subscription or API key" },
-];
-
const TAB_LABELS: Record<ConfigurationMenuTab, string> = {
providers: "Providers",
models: "Models",
@@ -77,14 +74,9 @@ class ConfigurationMenuTabBar implements Component {
theme.fg("muted", " "),
safeWidth,
);
- const previousKey = keyText("app.configuration.previousTab", { primaryOnly: true });
- const nextKey = keyText("app.configuration.nextTab", { primaryOnly: true });
- const hint = `${theme.fg("dim", `${previousKey}/${nextKey}`)}${theme.fg("muted", " switch tabs")}`;
- const lastLine = lines.at(-1);
- if (lastLine && visibleWidth(`${lastLine} ${hint}`) <= safeWidth) {
- lines[lines.length - 1] = `${lastLine} ${hint}`;
- return lines;
- }
+ const tabKey = keyText("tui.input.tab", { primaryOnly: true });
+ const closeKey = keyText("tui.select.cancel", { primaryOnly: true });
+ const hint = `${theme.fg("dim", tabKey)}${theme.fg("muted", " switch tabs · ")}${theme.fg("dim", closeKey)}${theme.fg("muted", " close")}`;
return [...lines, ...wrapTextWithAnsi(hint, safeWidth)];
}
@@ -154,11 +146,10 @@ export class ConfigurationMenuComponent extends Container implements Focusable {
options.onCancel,
options.initialModelSearch,
{
- actions: MODEL_SELECTOR_ACTIONS,
availableModels: options.availableModels,
+ configuredProviders: options.configuredProviders,
header: tabBar,
getHeaderRows,
- onAction: () => this.setActiveTab("providers"),
getRows: options.getRows,
recentModels: options.recentModels,
},
@@ -226,24 +217,25 @@ export class ConfigurationMenuComponent extends Container implements Focusable {
this.options.requestRender();
}
- updateModels(currentModel: Model<Api> | undefined, models?: ReadonlyArray<Model<Api>>): void {
- this.bodies.models.updateState(currentModel, models);
+ updateModels(
+ currentModel: Model<Api> | undefined,
+ models?: ReadonlyArray<Model<Api>>,
+ configuredProviders?: ReadonlySet<string>,
+ ): void {
+ this.bodies.models.updateState(currentModel, models, configuredProviders);
}
handleInput(keyData: string): void {
const kb = getKeybindings();
- if (
- kb.matches(keyData, "app.configuration.previousTab") &&
- (this.activeSearchIsEmpty() || !kb.matches(keyData, "tui.editor.cursorLeft"))
- ) {
- this.switchTab(-1);
+ if (kb.matches(keyData, "tui.input.tab")) {
+ this.switchTab();
return;
}
if (
- kb.matches(keyData, "app.configuration.nextTab") &&
- (this.activeSearchIsEmpty() || !kb.matches(keyData, "tui.editor.cursorRight"))
+ this.activeTab === "models" &&
+ (kb.matches(keyData, "tui.editor.cursorLeft") || kb.matches(keyData, "tui.editor.cursorRight"))
) {
- this.switchTab(1);
+ this.activeBody.getSearchInput().handleInput(keyData);
return;
}
this.activeBody.handleInput(keyData);
@@ -253,13 +245,9 @@ export class ConfigurationMenuComponent extends Container implements Focusable {
return this.bodies[this.activeTab];
}
- private activeSearchIsEmpty(): boolean {
- return this.activeBody.getSearchInput().getValue() === "";
- }
-
- private switchTab(direction: -1 | 1): void {
+ private switchTab(): void {
const currentIndex = CONFIGURATION_MENU_TABS.indexOf(this.activeTab);
- const nextIndex = (currentIndex + direction + CONFIGURATION_MENU_TABS.length) % CONFIGURATION_MENU_TABS.length;
+ const nextIndex = (currentIndex + 1) % CONFIGURATION_MENU_TABS.length;
this.setActiveTab(CONFIGURATION_MENU_TABS[nextIndex] ?? "providers");
}
}
diff --git a/packages/coding-agent/src/modes/interactive/components/model-selector.ts b/packages/coding-agent/src/modes/interactive/components/model-selector.ts
index 5563c96336..a3ccd7598c 100644
--- a/packages/coding-agent/src/modes/interactive/components/model-selector.ts
+++ b/packages/coding-agent/src/modes/interactive/components/model-selector.ts
@@ -11,7 +11,7 @@ import {
} from "@earendil-works/pi-tui";
import type { ModelRegistry } from "../../../core/model-registry.js";
import { theme } from "../theme/theme.js";
-import { keyHint, keyText } from "./keybinding-hints.js";
+import { keyHint } from "./keybinding-hints.js";
import {
getMenuListLayout,
MenuList,
@@ -33,18 +33,11 @@ interface ScopedModelItem {
thinkingLevel?: string;
}
-export interface ModelSelectorAction {
- id: string;
- label: string;
- description: string;
-}
-
export interface ModelSelectorOptions {
- actions?: ReadonlyArray<ModelSelectorAction>;
availableModels?: ReadonlyArray<Model<any>>;
+ configuredProviders?: ReadonlySet<string>;
header?: Component;
getHeaderRows?: () => number;
- onAction?: (actionId: string) => void;
subtitle?: string;
getRows?: () => number;
recentModels?: ReadonlyArray<string>;
@@ -82,13 +75,13 @@ export class ModelSelectorComponent extends Container implements Focusable {
private activeModels: ModelItem[] = [];
private filteredModels: ModelItem[] = [];
private selectedIndex: number = 0;
+ private searchQuery = "";
private currentModel?: Model<any>;
private modelRegistry: ModelRegistry;
private onSelectCallback: (model: Model<any>) => void;
private onCancelCallback: () => void;
- private actions: ReadonlyArray<ModelSelectorAction>;
private availableModels?: ReadonlyArray<Model<any>>;
- private onActionCallback?: (actionId: string) => void;
+ private configuredProviders?: ReadonlySet<string>;
private recentRank: Map<string, number>;
private errorMessage?: string;
private tui: TUI;
@@ -128,16 +121,15 @@ export class ModelSelectorComponent extends Container implements Focusable {
this.scope = scopedModels.length > 0 ? "scoped" : "all";
this.onSelectCallback = onSelect;
this.onCancelCallback = onCancel;
- this.actions = options.actions ?? [];
this.availableModels = options.availableModels;
- this.onActionCallback = options.onAction;
+ this.configuredProviders = options.configuredProviders;
this.recentRank = new Map((options.recentModels ?? []).map((key, i) => [key, i]));
this.viewport = { getRows: options.getRows };
this.getHeaderRows = options.header ? (options.getHeaderRows ?? (() => 2)) : () => 0;
this.panel = new MenuPanel({
title: "Models",
- subtitle: options.subtitle ?? "Available from configured providers.",
+ subtitle: options.subtitle ?? "All models across supported providers.",
});
this.addChild(this.panel);
if (options.header) {
@@ -150,11 +142,8 @@ export class ModelSelectorComponent extends Container implements Focusable {
this.scopeText = new Text(this.getScopeText(), 0, 0);
this.scopeHintText = new Text(this.getScopeHintText(), 0, 0);
} else {
- const hintText =
- this.actions.length > 0
- ? `Only showing models from configured providers. ${keyText("app.provider.add")} to add providers and access more models.`
- : "Only showing models from configured providers. Use /login to add providers and see more models.";
- this.warningText = new Text(theme.fg("warning", hintText), 0, 0);
+ const hintText = "Signed-in providers first. Other models prompt sign-in.";
+ this.warningText = new Text(theme.fg("muted", hintText), 0, 0);
}
this.headerHelpContainer = new Container();
this.panel.addChild(this.headerHelpContainer);
@@ -189,9 +178,14 @@ export class ModelSelectorComponent extends Container implements Focusable {
this.updateState(this.currentModel, availableModels);
}
- updateState(currentModel: Model<any> | undefined, availableModels = this.availableModels): void {
+ updateState(
+ currentModel: Model<any> | undefined,
+ availableModels = this.availableModels,
+ configuredProviders = this.configuredProviders,
+ ): void {
this.currentModel = currentModel;
this.availableModels = availableModels;
+ this.configuredProviders = configuredProviders;
const query = this.searchInput.getValue();
const selectedKey = this.getSelectedModelKey();
@@ -277,11 +271,15 @@ export class ModelSelectorComponent extends Container implements Focusable {
return this.recentRank.get(`${item.provider}/${item.id}`) ?? Number.MAX_SAFE_INTEGER;
}
+ private isProviderConfigured(item: ModelItem): boolean {
+ return this.configuredProviders?.has(item.provider) || this.modelRegistry.hasConfiguredAuth(item.model);
+ }
+
private sortModels(models: ModelItem[]): ModelItem[] {
const sorted = [...models];
- // Current model first, then most-recently-used, then provider; within a
- // provider, featured flagships before the long tail, each alphabetical.
sorted.sort((a, b) => {
+ const configuredDiff = Number(this.isProviderConfigured(b)) - Number(this.isProviderConfigured(a));
+ if (configuredDiff !== 0) return configuredDiff;
const aIsCurrent = modelsAreEqual(this.currentModel, a.model);
const bIsCurrent = modelsAreEqual(this.currentModel, b.model);
if (aIsCurrent !== bIsCurrent) return aIsCurrent ? -1 : 1;
@@ -304,7 +302,7 @@ export class ModelSelectorComponent extends Container implements Focusable {
}
private getScopeHintText(): string {
- return keyHint("tui.input.tab", "scope") + theme.fg("muted", " (all/scoped)");
+ return keyHint("app.model.toggleScope", "scope") + theme.fg("muted", " (all/scoped)");
}
private setScope(scope: ModelScope): void {
@@ -320,19 +318,25 @@ export class ModelSelectorComponent extends Container implements Focusable {
}
private filterModels(query: string): void {
+ const queryChanged = query !== this.searchQuery;
+ this.searchQuery = query;
if (query.trim()) {
const scored = fuzzyFilterScored(
this.activeModels,
query,
({ id, provider }) => `${id} ${provider} ${provider}/${id} ${provider} ${id}`,
);
- // Among equally-good matches (e.g. glm-5 / glm-5.1 / glm-5.2), prefer the most-recently-used.
- scored.sort((a, b) => a.score - b.score || this.recentRankOf(a.item) - this.recentRankOf(b.item));
+ scored.sort(
+ (a, b) =>
+ a.score - b.score ||
+ Number(this.isProviderConfigured(b.item)) - Number(this.isProviderConfigured(a.item)) ||
+ this.recentRankOf(a.item) - this.recentRankOf(b.item),
+ );
this.filteredModels = scored.map((r) => r.item);
} else {
this.filteredModels = this.activeModels;
}
- this.selectedIndex = Math.min(this.selectedIndex, Math.max(0, this.getSelectableCount() - 1));
+ this.selectedIndex = queryChanged ? 0 : Math.min(this.selectedIndex, Math.max(0, this.getSelectableCount() - 1));
this.updateList();
}
@@ -364,12 +368,18 @@ export class ModelSelectorComponent extends Container implements Focusable {
const isSelected = i === this.selectedIndex;
const isCurrent = modelsAreEqual(this.currentModel, item.model);
+ const isConfigured = this.isProviderConfigured(item);
+ const meta = isConfigured
+ ? isCurrent
+ ? theme.fg("success", "current")
+ : undefined
+ : theme.fg("warning", isCurrent ? "current · sign in" : "sign in");
this.listContainer.addChild(
new MenuRow({
primary: item.id,
secondary: item.provider,
- meta: isCurrent ? theme.fg("success", "current") : undefined,
+ meta,
selected: isSelected,
}),
);
@@ -401,12 +411,7 @@ export class ModelSelectorComponent extends Container implements Focusable {
handleInput(keyData: string): void {
const kb = getKeybindings();
- const addProviderAction = this.actions[0];
- if (addProviderAction && kb.matches(keyData, "app.provider.add")) {
- this.onActionCallback?.(addProviderAction.id);
- return;
- }
- if (kb.matches(keyData, "tui.input.tab")) {
+ if (kb.matches(keyData, "app.model.toggleScope")) {
if (this.scopedModelItems.length > 0) {
const nextScope: ModelScope = this.scope === "all" ? "scoped" : "all";
this.setScope(nextScope);
diff --git a/packages/coding-agent/src/modes/interactive/components/oauth-selector.ts b/packages/coding-agent/src/modes/interactive/components/oauth-selector.ts
index b38401877e..5cd527fa0d 100644
--- a/packages/coding-agent/src/modes/interactive/components/oauth-selector.ts
+++ b/packages/coding-agent/src/modes/interactive/components/oauth-selector.ts
@@ -72,6 +72,7 @@ export class OAuthSelectorComponent extends Container implements Focusable {
private allProviders: AuthSelectorProvider[];
private filteredProviders: AuthSelectorProvider[];
private selectedIndex: number = 0;
+ private searchQuery = "";
private mode: "login" | "logout";
/** Tabs present in the data, in display order. Empty/single → no tab bar. */
private categories: AuthSelectorCategory[] = [];
@@ -184,11 +185,15 @@ export class OAuthSelectorComponent extends Container implements Focusable {
}
private filterProviders(query: string): void {
+ const queryChanged = query !== this.searchQuery;
+ this.searchQuery = query;
const inCategory = this.allProviders.filter((p) => this.inActiveCategory(p));
this.filteredProviders = query
? fuzzyFilter(inCategory, query, (provider) => `${provider.name} ${provider.id} ${provider.authType}`)
: inCategory;
- this.selectedIndex = Math.max(0, Math.min(this.selectedIndex, Math.max(0, this.filteredProviders.length - 1)));
+ this.selectedIndex = queryChanged
+ ? 0
+ : Math.max(0, Math.min(this.selectedIndex, Math.max(0, this.filteredProviders.length - 1)));
this.updateTabBar();
this.updateList();
}
diff --git a/packages/coding-agent/src/modes/interactive/components/prime-team-selector.ts b/packages/coding-agent/src/modes/interactive/components/prime-team-selector.ts
index b840d57716..62b438815d 100644
--- a/packages/coding-agent/src/modes/interactive/components/prime-team-selector.ts
+++ b/packages/coding-agent/src/modes/interactive/components/prime-team-selector.ts
@@ -25,6 +25,7 @@ export class PrimeTeamSelectorComponent extends Container implements Focusable {
private readonly allOptions: PrimeTeamOption[];
private filteredOptions: PrimeTeamOption[];
private selectedIndex = 0;
+ private searchQuery = "";
private _focused = false;
private listLayout = getMenuListLayout({
preferredVisibleItems: PREFERRED_VISIBLE_TEAMS,
@@ -76,10 +77,14 @@ export class PrimeTeamSelectorComponent extends Container implements Focusable {
}
private filterOptions(query: string): void {
+ const queryChanged = query !== this.searchQuery;
+ this.searchQuery = query;
this.filteredOptions = query
? fuzzyFilter(this.allOptions, query, (option) => this.getSearchText(option))
: this.allOptions;
- this.selectedIndex = Math.max(0, Math.min(this.selectedIndex, Math.max(0, this.filteredOptions.length - 1)));
+ this.selectedIndex = queryChanged
+ ? 0
+ : Math.max(0, Math.min(this.selectedIndex, Math.max(0, this.filteredOptions.length - 1)));
this.updateList();
}
diff --git a/packages/coding-agent/src/modes/interactive/components/scoped-models-selector.ts b/packages/coding-agent/src/modes/interactive/components/scoped-models-selector.ts
index c5a82d9ad7..415ea862bf 100644
--- a/packages/coding-agent/src/modes/interactive/components/scoped-models-selector.ts
+++ b/packages/coding-agent/src/modes/interactive/components/scoped-models-selector.ts
@@ -93,6 +93,7 @@ export class ScopedModelsSelectorComponent extends Container implements Focusabl
private enabledIds: EnabledIds = null;
private filteredItems: ModelItem[] = [];
private selectedIndex = 0;
+ private searchQuery = "";
private searchInput: Input;
// Focusable implementation - propagate to searchInput for IME cursor positioning
@@ -181,9 +182,11 @@ export class ScopedModelsSelectorComponent extends Container implements Focusabl
private refresh(): void {
const query = this.searchInput.getValue();
+ const queryChanged = query !== this.searchQuery;
+ this.searchQuery = query;
const items = this.buildItems();
this.filteredItems = query ? fuzzyFilter(items, query, (i) => `${i.model.id} ${i.model.provider}`) : items;
- this.selectedIndex = Math.min(this.selectedIndex, Math.max(0, this.filteredItems.length - 1));
+ this.selectedIndex = queryChanged ? 0 : Math.min(this.selectedIndex, Math.max(0, this.filteredItems.length - 1));
this.updateList();
this.footerText.setText(this.getFooterText());
}
diff --git a/packages/coding-agent/src/modes/interactive/components/session-selector.ts b/packages/coding-agent/src/modes/interactive/components/session-selector.ts
index 6cbb70755b..37b2eda747 100644
--- a/packages/coding-agent/src/modes/interactive/components/session-selector.ts
+++ b/packages/coding-agent/src/modes/interactive/components/session-selector.ts
@@ -290,6 +290,7 @@ class SessionList implements Component, Focusable {
private allSessions: AgentConnectionSavedSessionInfo[] = [];
private filteredSessions: FlatSessionNode[] = [];
private selectedIndex: number = 0;
+ private searchQuery = "";
private searchInput: Input;
private showCwd = false;
private sortMode: SortMode = "recent";
@@ -384,6 +385,8 @@ class SessionList implements Component, Focusable {
}
private filterSessions(query: string): void {
+ const queryChanged = query !== this.searchQuery;
+ this.searchQuery = query;
const trimmed = query.trim();
const nameFiltered =
this.nameFilter === "all" ? this.allSessions : this.allSessions.filter((session) => hasSessionName(session));
@@ -402,7 +405,9 @@ class SessionList implements Component, Focusable {
ancestorContinues: [],
}));
}
- this.selectedIndex = Math.min(this.selectedIndex, Math.max(0, this.filteredSessions.length - 1));
+ this.selectedIndex = queryChanged
+ ? 0
+ : Math.min(this.selectedIndex, Math.max(0, this.filteredSessions.length - 1));
}
private setConfirmingDeletePath(path: string | null): void {
diff --git a/packages/coding-agent/src/modes/interactive/interactive-mode.ts b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
index f9c8bf8cc5..be29e82cfa 100644
--- a/packages/coding-agent/src/modes/interactive/interactive-mode.ts
+++ b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
@@ -34,7 +34,6 @@ import {
CombinedAutocompleteProvider,
type Component,
Container,
- fuzzyFilter,
Loader,
type LoaderIndicatorOptions,
Markdown,
@@ -135,6 +134,7 @@ import type {
AgentConnectionExtensionUiResponse,
AgentConnectionHeartbeat,
AgentConnectionModel,
+ AgentConnectionModelCatalog,
AgentConnectionQueueState,
AgentConnectionResourceDiagnostic,
AgentConnectionResourceSnapshot,
@@ -150,6 +150,7 @@ import type {
AgentConnectionState,
AgentConnectionToolDefinition,
} from "../agent-connection/index.js";
+import { getModelArgumentCompletions } from "../model-autocomplete.js";
import {
checkForPackageUpdates,
checkTmuxKeyboardSetup,
@@ -826,6 +827,8 @@ export class InteractiveMode {
private skillCommands = new Map<string, string>();
private connectionCommands: AgentConnectionSlashCommand[] = [];
private connectionModels: AgentConnectionModel[] = [];
+ private connectionModelCatalog: AgentConnectionModel[] = [];
+ private connectionConfiguredProviders = new Set<string>();
private connectionModelsFetchedAt = 0;
private connectionModelsRefreshVersion = 0;
private connectionModelsRefreshInFlight: { version: number; promise: Promise<AgentConnectionModel[]> } | undefined;
@@ -1111,32 +1114,8 @@ export class InteractiveMode {
const modelCommand = slashCommands.find((command) => command.name === "model");
if (modelCommand) {
- modelCommand.getArgumentCompletions = (prefix: string): AutocompleteItem[] | null => {
- const models =
- this.connectionState && this.connectionState.scopedModels.length > 0
- ? this.connectionState.scopedModels.map((s) => s.model)
- : this.connectionModels;
-
- if (models.length === 0) return null;
-
- // Create items with provider/id format
- const items = models.map((m) => ({
- id: m.id,
- provider: m.provider,
- label: `${m.provider}/${m.id}`,
- }));
-
- // Fuzzy filter by model ID + provider (allows "opus anthropic" to match)
- const filtered = fuzzyFilter(items, prefix, (item) => `${item.id} ${item.provider}`);
-
- if (filtered.length === 0) return null;
-
- return filtered.map((item) => ({
- value: item.label,
- label: item.id,
- description: item.provider,
- }));
- };
+ modelCommand.getArgumentCompletions = (prefix: string): AutocompleteItem[] | null =>
+ getModelArgumentCompletions(prefix, this.getCachedModelCandidates());
}
const effortCommand = slashCommands.find((command) => command.name === "effort");
@@ -2330,15 +2309,15 @@ export class InteractiveMode {
private async refreshConnectionCatalog(): Promise<void> {
this.invalidateConnectionModelRefresh();
- const [state, commands, models, resources] = await Promise.all([
+ const [state, commands, modelCatalog, resources] = await Promise.all([
this.agentConnection.getState(),
this.agentConnection.getCommands(),
- this.agentConnection.getAvailableModels(),
+ this.agentConnection.getModelCatalog(),
this.agentConnection.getResourceSnapshot(),
]);
this.applyConnectionStateSnapshot(state);
this.connectionCommands = commands;
- this.connectionModels = models;
+ this.applyConnectionModelCatalog(modelCatalog);
this.connectionModelsFetchedAt = Date.now();
this.connectionResourceSnapshot = resources;
}
@@ -7070,11 +7049,10 @@ export class InteractiveMode {
const model = await this.findExactModelMatch(searchTerm);
if (model) {
try {
- this.showStatus(`Switching model: ${model.id}`);
- await this.applySelectedModel(model);
- this.showStatus(`Model: ${model.id}`);
- void this.maybeWarnAboutAnthropicSubscriptionAuth(model);
- this.checkDaxnutsEasterEgg(model);
+ const authFlows = this.createAuthFlows();
+ const providerOptions = authFlows.getLoginProviderOptions();
+ if (!(await this.ensureModelProviderConfigured(model, authFlows, providerOptions))) return;
+ await this.completeModelSelection(model);
} catch (error) {
this.showError(error instanceof Error ? error.message : String(error));
}
@@ -7127,6 +7105,50 @@ export class InteractiveMode {
this.setupAutocompleteProvider();
}
+ private async completeModelSelection(model: AgentConnectionModel): Promise<void> {
+ this.showStatus(`Switching model: ${model.id}`);
+ await this.applySelectedModel(model);
+ this.showStatus(`Model: ${model.id}`);
+ void this.maybeWarnAboutAnthropicSubscriptionAuth(model);
+ this.checkDaxnutsEasterEgg(model);
+ }
+
+ private async ensureModelProviderConfigured(
+ model: AgentConnectionModel,
+ authFlows: ProviderAuthFlows,
+ providerOptions: ReadonlyArray<AuthSelectorProvider>,
+ ): Promise<boolean> {
+ if (this.isModelProviderConfigured(model)) return true;
+
+ const provider = providerOptions.find(
+ (option) => option.id === model.provider && (option.category ?? "provider") === "provider",
+ );
+ if (!provider) {
+ this.showError(`Authentication for ${model.provider} must be configured externally.`);
+ return false;
+ }
+
+ const result = await authFlows.loginProvider(provider);
+ if (result.status !== "success") return false;
+
+ this.invalidateConnectionModels();
+ await this.getConnectionAvailableModels();
+ if (this.isModelProviderConfigured(model)) return true;
+
+ this.showError(`Authentication completed, but ${model.provider} is still unavailable.`);
+ return false;
+ }
+
+ private isModelProviderConfigured(model: AgentConnectionModel): boolean {
+ return this.connectionConfiguredProviders.has(model.provider) || this.modelRegistry.hasConfiguredAuth(model);
+ }
+
+ private applyConnectionModelCatalog(catalog: AgentConnectionModelCatalog): void {
+ this.connectionModelCatalog = [...catalog.models];
+ this.connectionConfiguredProviders = new Set(catalog.configuredProviders);
+ this.connectionModels = catalog.models.filter((model) => this.connectionConfiguredProviders.has(model.provider));
+ }
+
private async getConnectionAvailableModels(): Promise<AgentConnectionModel[]> {
const inFlight = this.connectionModelsRefreshInFlight;
if (inFlight && inFlight.version === this.connectionModelsRefreshVersion) {
@@ -7134,14 +7156,13 @@ export class InteractiveMode {
}
const version = this.connectionModelsRefreshVersion;
- const promise = this.agentConnection.getAvailableModels().then((models) => {
- const nextModels = [...models];
+ const promise = this.agentConnection.getModelCatalog().then((catalog) => {
if (version !== this.connectionModelsRefreshVersion) {
return [...this.connectionModels];
}
- this.connectionModels = nextModels;
+ this.applyConnectionModelCatalog(catalog);
this.connectionModelsFetchedAt = Date.now();
- return nextModels;
+ return [...this.connectionModels];
});
this.connectionModelsRefreshInFlight = { version, promise };
@@ -7154,12 +7175,17 @@ export class InteractiveMode {
}
}
+ private async getConnectionModelCatalog(): Promise<AgentConnectionModel[]> {
+ await this.getConnectionAvailableModels();
+ return [...this.connectionModelCatalog];
+ }
+
private getCachedModelCandidates(): AgentConnectionModel[] {
const modelsById = new Map<string, AgentConnectionModel>();
for (const scoped of this.getScopedModelState()) {
modelsById.set(`${scoped.model.provider}/${scoped.model.id}`, scoped.model);
}
- for (const model of this.connectionModels) {
+ for (const model of this.connectionModelCatalog) {
modelsById.set(`${model.provider}/${model.id}`, model);
}
return [...modelsById.values()];
@@ -7168,14 +7194,15 @@ export class InteractiveMode {
private getModelSelectorRefreshPromise(
options: { force?: boolean } = {},
): Promise<AgentConnectionModel[]> | undefined {
+ const refreshCatalog = () => this.getConnectionAvailableModels().then(() => this.getCachedModelCandidates());
if (this.connectionModelsRefreshInFlight) {
- return this.getConnectionAvailableModels();
+ return refreshCatalog();
}
if (options.force || this.connectionModelsFetchedAt === 0) {
- return this.getConnectionAvailableModels();
+ return refreshCatalog();
}
if (Date.now() - this.connectionModelsFetchedAt > MODEL_CATALOG_REFRESH_TTL_MS) {
- return this.getConnectionAvailableModels();
+ return refreshCatalog();
}
return undefined;
}
@@ -7187,10 +7214,16 @@ export class InteractiveMode {
private invalidateConnectionModels(): void {
this.connectionModels = [];
+ this.connectionConfiguredProviders = new Set();
this.connectionModelsFetchedAt = 0;
this.invalidateConnectionModelRefresh();
}
+ private async refreshConnectionModelsAfterAuthChange(): Promise<void> {
+ this.invalidateConnectionModels();
+ await this.getConnectionAvailableModels();
+ }
+
private async getModelCandidates(): Promise<AgentConnectionModel[]> {
const scopedModels = this.getScopedModelState();
if (scopedModels.length > 0) {
@@ -7367,7 +7400,7 @@ export class InteractiveMode {
}
private showConfigurationMenu(initialTab: ConfigurationMenuTab, initialModelSearch?: string): Promise<void> {
- const availableModels = this.getCachedModelCandidates();
+ const modelCatalog = this.getCachedModelCandidates();
const authFlows = this.createAuthFlows();
const providerOptions = authFlows.getLoginProviderOptions();
@@ -7375,13 +7408,28 @@ export class InteractiveMode {
let handle: OverlayHandle | undefined;
let settled = false;
let hidden = false;
+ let removed = false;
let menu: ConfigurationMenuComponent;
const hide = () => {
- if (hidden) return;
+ if (removed) return;
+ removed = true;
hidden = true;
handle?.hide();
this.ui.requestRender();
};
+ const conceal = () => {
+ if (hidden || removed) return;
+ hidden = true;
+ handle?.setHidden(true);
+ this.ui.requestRender();
+ };
+ const show = () => {
+ if (!hidden || removed || settled) return;
+ hidden = false;
+ handle?.setHidden(false);
+ handle?.focus();
+ this.ui.requestRender();
+ };
const finish = () => {
if (settled) return;
settled = true;
@@ -7393,7 +7441,7 @@ export class InteractiveMode {
if (!refreshPromise) return;
void refreshPromise
.then((models) => {
- if (!settled) menu.updateModels(this.getCurrentModel(), models);
+ if (!settled) menu.updateModels(this.getCurrentModel(), models, this.connectionConfiguredProviders);
})
.catch((error) => {
if (!settled) this.showError(error instanceof Error ? error.message : String(error));
@@ -7421,7 +7469,11 @@ export class InteractiveMode {
}
await this.prepareForModelSelectionAfterLogin(authResult);
- menu.updateModels(this.getCurrentModel());
+ menu.updateModels(
+ this.getCurrentModel(),
+ this.getCachedModelCandidates(),
+ this.connectionConfiguredProviders,
+ );
menu.setActiveTab("models");
refreshModels(true);
})
@@ -7439,7 +7491,8 @@ export class InteractiveMode {
modelRegistry: this.modelRegistry,
currentModel: this.getCurrentModel(),
scopedModels: this.getScopedModelState(),
- availableModels,
+ availableModels: modelCatalog,
+ configuredProviders: this.connectionConfiguredProviders,
recentModels: this.settingsManager.getRecentModels(),
initialModelSearch,
getRows: () => this.ui.terminal.rows,
@@ -7447,16 +7500,28 @@ export class InteractiveMode {
onSelectProvider: (provider) => authenticate(provider, "providers"),
onSelectMcpConnection: (provider) => authenticate(provider, "mcp-connections"),
onSelectModel: (model) => {
- hide();
- this.showStatus(`Switching model: ${model.id}`);
- void this.applySelectedModel(model)
- .then(() => {
- this.showStatus(`Model: ${model.id}`);
- void this.maybeWarnAboutAnthropicSubscriptionAuth(model);
- this.checkDaxnutsEasterEgg(model);
- })
- .catch((error) => this.showError(error instanceof Error ? error.message : String(error)))
- .finally(finish);
+ void (async () => {
+ let completed = false;
+ try {
+ const ready = await this.ensureModelProviderConfigured(model, authFlows, providerOptions);
+ handle?.focus();
+ menu.refreshAuthentication();
+ menu.updateModels(
+ this.getCurrentModel(),
+ this.getCachedModelCandidates(),
+ this.connectionConfiguredProviders,
+ );
+ if (!ready || settled) return;
+ conceal();
+ await this.completeModelSelection(model);
+ completed = true;
+ } catch (error) {
+ show();
+ this.showError(error instanceof Error ? error.message : String(error));
+ } finally {
+ if (completed) finish();
+ }
+ })();
},
onCancel: finish,
});
@@ -7468,7 +7533,7 @@ export class InteractiveMode {
private async showModelsSelector(): Promise<void> {
let allModels: AgentConnectionModel[];
try {
- allModels = await this.getConnectionAvailableModels();
+ allModels = await this.getConnectionModelCatalog();
} catch (error) {
this.showError(error instanceof Error ? error.message : String(error));
return;
@@ -7899,6 +7964,7 @@ export class InteractiveMode {
showError: (message) => this.showError(message),
getAvailableModels: () => this.getConnectionAvailableModels(),
onAuthChanged: async () => {
+ await this.refreshConnectionModelsAfterAuthChange();
await this.updateAvailableProviderCount();
this.footer.invalidate();
this.updateEditorBorderColor();
@@ -7910,10 +7976,6 @@ export class InteractiveMode {
}
private async prepareForModelSelectionAfterLogin(authResult: AuthenticationResult): Promise<boolean> {
- if (authResult.status === "success" && authResult.kind !== "service") {
- this.invalidateConnectionModels();
- }
-
const currentModel = this.getCurrentModel();
// The agent core uses unknown/unknown as its no-model sentinel.
const selectedModel =
diff --git a/packages/coding-agent/src/modes/model-autocomplete.ts b/packages/coding-agent/src/modes/model-autocomplete.ts
new file mode 100644
index 0000000000..cbe5814a8d
--- /dev/null
+++ b/packages/coding-agent/src/modes/model-autocomplete.ts
@@ -0,0 +1,28 @@
+import type { AutocompleteItem } from "@earendil-works/pi-tui";
+import { fuzzyFilter } from "@earendil-works/pi-tui";
+
+export interface ModelAutocompleteCandidate {
+ id: string;
+ provider: string;
+}
+
+export function getModelArgumentCompletions(
+ prefix: string,
+ models: ReadonlyArray<ModelAutocompleteCandidate>,
+): AutocompleteItem[] | null {
+ if (models.length === 0) return null;
+
+ const items = models.map((model) => ({
+ id: model.id,
+ provider: model.provider,
+ label: `${model.provider}/${model.id}`,
+ }));
+ const filtered = fuzzyFilter(items, prefix, (item) => `${item.id} ${item.provider}`);
+ if (filtered.length === 0) return null;
+
+ return filtered.map((item) => ({
+ value: item.label,
+ label: item.id,
+ description: item.provider,
+ }));
+}
diff --git a/packages/coding-agent/test/agent-connection-daemon.test.ts b/packages/coding-agent/test/agent-connection-daemon.test.ts
index 93133fe078..7583c5e827 100644
--- a/packages/coding-agent/test/agent-connection-daemon.test.ts
+++ b/packages/coding-agent/test/agent-connection-daemon.test.ts
@@ -150,6 +150,23 @@ class FakeDaemonClient {
},
},
};
+ case "get_model_catalog":
+ return {
+ type: "response",
+ command: command.type,
+ success: true,
+ data: {
+ models: [getModel("openai", "gpt-5.1")],
+ configuredProviders: ["openai"],
+ },
+ };
+ case "get_available_models":
+ return {
+ type: "response",
+ command: command.type,
+ success: true,
+ data: { models: [getModel("openai", "gpt-5.1")] },
+ };
case "get_session_context":
return {
type: "response",
@@ -2100,6 +2117,37 @@ describe("DaemonAgentConnection", () => {
});
});
+ it("loads the full model catalog through the daemon protocol", async () => {
+ const fakeClient = new FakeDaemonClient();
+ fakeClient.serverCapabilities.add("model_catalog");
+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1");
+ await connection.attach();
+
+ const catalog = await connection.getModelCatalog();
+
+ expect(catalog.configuredProviders).toEqual(["openai"]);
+ expect(catalog.models[0]).toMatchObject({ provider: "openai", id: "gpt-5.1" });
+ expect(fakeClient.requests[1]).toMatchObject({
+ type: "get_model_catalog",
+ activeSessionId: "active-1",
+ });
+ });
+
+ it("falls back to configured models when the daemon lacks model catalog support", async () => {
+ const fakeClient = new FakeDaemonClient();
+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1");
+ await connection.attach();
+
+ const catalog = await connection.getModelCatalog();
+
+ expect(catalog.configuredProviders).toEqual(["openai"]);
+ expect(catalog.models[0]).toMatchObject({ provider: "openai", id: "gpt-5.1" });
+ expect(fakeClient.requests[1]).toMatchObject({
+ type: "get_available_models",
+ activeSessionId: "active-1",
+ });
+ });
+
it("loads session context through the daemon protocol", async () => {
const fakeClient = new FakeDaemonClient();
const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1");
diff --git a/packages/coding-agent/test/agent-connection-in-process.test.ts b/packages/coding-agent/test/agent-connection-in-process.test.ts
index 6afdb4c600..1c55dfc9cb 100644
--- a/packages/coding-agent/test/agent-connection-in-process.test.ts
+++ b/packages/coding-agent/test/agent-connection-in-process.test.ts
@@ -1,4 +1,5 @@
import type { AgentMessage } from "@earendil-works/pi-agent-core";
+import { getModel } from "@earendil-works/pi-ai";
import { describe, expect, it } from "vitest";
import type { AgentSessionEvent, AgentSessionEventListener } from "../src/core/agent-session.js";
import type { AgentSessionRuntime } from "../src/core/agent-session-runtime.js";
@@ -74,6 +75,7 @@ function createFakeSession(id: string, messages: AgentMessage[]): FakeSessionCon
thinkingLevel,
model: null,
});
+ const model = getModel("openai", "gpt-5.1");
const session = {
sessionManager: {
getCwd: () => `/tmp/${id}`,
@@ -99,6 +101,9 @@ function createFakeSession(id: string, messages: AgentMessage[]): FakeSessionCon
messages,
pendingMessageCount: 0,
goalState: emptyGoalState(),
+ modelRegistry: {
+ refreshModelCatalog: async () => ({ models: model ? [model] : [], configuredProviders: ["openai"] }),
+ },
scopedModels: [],
getActiveToolNames: () => ["ipython"],
getContextUsage: () => undefined,
@@ -137,6 +142,18 @@ function createFakeSession(id: string, messages: AgentMessage[]): FakeSessionCon
}
describe("InProcessAgentConnection", () => {
+ it("loads the full model catalog through the connection boundary", async () => {
+ const session = createFakeSession("models", []);
+ const runtime = new FakeRuntime(session.session);
+ const connection = new InProcessAgentConnection(asRuntime(runtime));
+
+ const catalog = await connection.getModelCatalog();
+
+ expect(catalog.configuredProviders).toEqual(["openai"]);
+ expect(catalog.models).toHaveLength(1);
+ expect(catalog.models[0]).toMatchObject({ provider: "openai", id: "gpt-5.1" });
+ });
+
it("exposes serializable tool metadata without local execution or renderer callbacks", async () => {
const session = createFakeSession("tools", []);
const runtime = new FakeRuntime(session.session);
diff --git a/packages/coding-agent/test/configuration-menu.test.ts b/packages/coding-agent/test/configuration-menu.test.ts
index 8bb765fe6b..eb7afc3d25 100644
--- a/packages/coding-agent/test/configuration-menu.test.ts
+++ b/packages/coding-agent/test/configuration-menu.test.ts
@@ -1,4 +1,4 @@
-import { type KeyId, setKeybindings, type TUI, visibleWidth } from "@earendil-works/pi-tui";
+import { setKeybindings, type TUI, visibleWidth } from "@earendil-works/pi-tui";
import stripAnsi from "strip-ansi";
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { KeybindingsManager } from "../src/core/keybindings.js";
@@ -24,6 +24,7 @@ describe("ConfigurationMenuComponent", () => {
getRows?: () => number;
requestRender?: () => void;
onSelectProvider?: () => void;
+ onCancel?: () => void;
} = {},
): Promise<ConfigurationMenuComponent> {
const harness = await createHarness({
@@ -48,12 +49,13 @@ describe("ConfigurationMenuComponent", () => {
currentModel: model,
scopedModels: [],
availableModels: [model],
+ configuredProviders: new Set([model.provider]),
getRows: options.getRows,
requestRender: options.requestRender ?? (() => {}),
onSelectProvider: options.onSelectProvider ?? (() => {}),
onSelectMcpConnection: () => {},
onSelectModel: () => {},
- onCancel: () => {},
+ onCancel: options.onCancel ?? (() => {}),
});
}
@@ -108,27 +110,25 @@ describe("ConfigurationMenuComponent", () => {
expect(output).not.toContain("Anthropic");
});
- it("switches tabs with configured bindings and preserves focus and search state", async () => {
- setKeybindings(
- new KeybindingsManager({
- "app.configuration.previousTab": "ctrl+y" as KeyId,
- "app.configuration.nextTab": "ctrl+x" as KeyId,
- }),
- );
+ it("switches tabs with Tab and preserves focus and search state", async () => {
const menu = await createMenu();
menu.focused = true;
- expect(stripAnsi(menu.render(120).join("\n"))).toContain("Ctrl+Y/Ctrl+X switch tabs");
+ const lines = stripAnsi(menu.render(120).join("\n")).split("\n");
+ const tabsLine = lines.findIndex((line) => line.includes("[▶ Providers]"));
+ const shortcutsLine = lines.findIndex((line) => line.includes("Tab switch tabs"));
+ expect(shortcutsLine).toBeGreaterThan(tabsLine);
+ expect(lines[shortcutsLine]).toContain("Esc close");
- menu.handleInput("\x18");
+ menu.handleInput("\t");
expect(menu.getActiveTab()).toBe("models");
expect(menu.focused).toBe(true);
menu.handleInput("f");
expect(menu.getSearchValue("models")).toBe("f");
- menu.handleInput("\x18");
+ menu.handleInput("\t");
expect(menu.getActiveTab()).toBe("mcp-connections");
expect(menu.getSearchValue("models")).toBe("f");
- menu.handleInput("\x19");
- expect(menu.getActiveTab()).toBe("models");
+ menu.handleInput("\t");
+ expect(menu.getActiveTab()).toBe("providers");
});
it("keeps the existing catalog while syncing a post-login current model", async () => {
@@ -150,6 +150,7 @@ describe("ConfigurationMenuComponent", () => {
currentModel: undefined,
scopedModels: [],
availableModels: [firstModel],
+ configuredProviders: new Set([firstModel.provider]),
initialModelSearch: "faux",
requestRender: () => {},
onSelectProvider: () => {},
@@ -169,16 +170,24 @@ describe("ConfigurationMenuComponent", () => {
expect(postLoginRow).toContain("current");
});
- it("keeps default arrow keys in the active search field while it contains text", async () => {
- const menu = await createMenu();
+ it("keeps arrow keys in the active search field and uses Escape to close", async () => {
+ const onCancel = vi.fn();
+ const menu = await createMenu({ initialTab: "models", onCancel });
+
+ menu.handleInput("\x1b[D");
+ expect(menu.getActiveTab()).toBe("models");
+ expect(onCancel).not.toHaveBeenCalled();
menu.handleInput("a");
menu.handleInput("n");
menu.handleInput("\x1b[D");
menu.handleInput("\x1b[C");
- expect(menu.getActiveTab()).toBe("providers");
+ expect(menu.getActiveTab()).toBe("models");
expect(menu.getSearchValue()).toBe("an");
+
+ menu.handleInput("\x1b");
+ expect(onCancel).toHaveBeenCalledOnce();
});
it("wraps complete tab labels at narrow widths without overflowing the viewport", async () => {
diff --git a/packages/coding-agent/test/daemon-protocol.test.ts b/packages/coding-agent/test/daemon-protocol.test.ts
index 56a43d85f9..48e732ad8d 100644
--- a/packages/coding-agent/test/daemon-protocol.test.ts
+++ b/packages/coding-agent/test/daemon-protocol.test.ts
@@ -58,6 +58,14 @@ describe("daemon protocol helpers", () => {
);
});
+ it("capability-gates the optional model catalog surface", () => {
+ expect(DAEMON_COMMAND_COMPATIBILITY.get_model_catalog).toEqual({
+ minProtocol: 4,
+ capability: "model_catalog",
+ });
+ expect(DAEMON_DEFAULT_SERVER_CAPABILITIES).toContain("model_catalog");
+ });
+
it("creates versioned command and event envelopes", () => {
const command = { id: "cmd-1", type: "attach", activeSessionId: "active-1" } as const;
const commandEnvelope = createDaemonCommandEnvelope(command, "cmd-1", "client-1");
diff --git a/packages/coding-agent/test/interactive-mode-status.test.ts b/packages/coding-agent/test/interactive-mode-status.test.ts
index b823bd4bd8..92033f81f3 100644
--- a/packages/coding-agent/test/interactive-mode-status.test.ts
+++ b/packages/coding-agent/test/interactive-mode-status.test.ts
@@ -5,8 +5,10 @@ import {
CombinedAutocompleteProvider,
type Component,
Container,
+ getKeybindings,
resetCapabilitiesCache,
setCapabilities,
+ setKeybindings,
type TUI,
visibleWidth,
} from "@earendil-works/pi-tui";
@@ -16,6 +18,7 @@ import { type AuthStatus, AuthStorage } from "../src/core/auth-storage.js";
import type { AgentCronJob } from "../src/core/cron-jobs.js";
import type { AutocompleteProviderFactory } from "../src/core/extensions/types.js";
import { emptyGoalState, type GoalState } from "../src/core/goals.js";
+import { KeybindingsManager } from "../src/core/keybindings.js";
import type { ModelRegistry } from "../src/core/model-registry.js";
import { PRIME_INFERENCE_PROVIDER_ID } from "../src/core/prime-inference-auth.js";
import type {
@@ -23,6 +26,7 @@ import type {
AgentConnectionExtensionUiResponse,
AgentConnectionHeartbeat,
AgentConnectionModel,
+ AgentConnectionModelCatalog,
AgentConnectionResourceDiagnostic,
AgentConnectionResourceSnapshot,
AgentConnectionRlmChildAgentSnapshot,
@@ -35,6 +39,7 @@ import { AgentActivityTracker } from "../src/modes/interactive/agent-activity.js
import type { AuthenticationResult } from "../src/modes/interactive/auth-flows.js";
import { BashExecutionComponent } from "../src/modes/interactive/components/bash-execution.js";
import type { ConfigurationMenuComponent } from "../src/modes/interactive/components/configuration-menu.js";
+import type { AuthSelectorProvider } from "../src/modes/interactive/components/oauth-selector.js";
import type { ToolExecutionComponent } from "../src/modes/interactive/components/tool-execution.js";
import {
formatSplashCwd,
@@ -1216,9 +1221,15 @@ describe("InteractiveMode startup onboarding warnings", () => {
describe("InteractiveMode model candidates", () => {
type ModelCandidatesHarness = {
- agentConnection: { getAvailableModels: () => Promise<AgentConnectionModel[]> };
+ agentConnection: { getModelCatalog: () => Promise<AgentConnectionModelCatalog> };
connectionModels: AgentConnectionModel[];
+ connectionModelCatalog: AgentConnectionModel[];
+ connectionConfiguredProviders: Set<string>;
+ connectionModelsFetchedAt: number;
+ connectionModelsRefreshVersion: number;
+ connectionModelsRefreshInFlight: { version: number; promise: Promise<AgentConnectionModel[]> } | undefined;
getScopedModelState(): AgentConnectionState["scopedModels"];
+ applyConnectionModelCatalog(catalog: AgentConnectionModelCatalog): void;
getConnectionAvailableModels(): Promise<AgentConnectionModel[]>;
getModelCandidates(): Promise<AgentConnectionModel[]>;
getScopedModelsFromModelIds(
@@ -1237,11 +1248,17 @@ describe("InteractiveMode model candidates", () => {
test("loads unscoped model candidates through AgentConnection", async () => {
const model = createModel("openai", "gpt-5.5");
- const getAvailableModels = vi.fn(async () => [model]);
+ const getModelCatalog = vi.fn(async () => ({ models: [model], configuredProviders: [model.provider] }));
const fakeThis: ModelCandidatesHarness = {
- agentConnection: { getAvailableModels },
+ agentConnection: { getModelCatalog },
connectionModels: [],
+ connectionModelCatalog: [],
+ connectionConfiguredProviders: new Set(),
+ connectionModelsFetchedAt: 0,
+ connectionModelsRefreshVersion: 0,
+ connectionModelsRefreshInFlight: undefined,
getScopedModelState: () => [],
+ applyConnectionModelCatalog: prototype.applyConnectionModelCatalog,
getConnectionAvailableModels: prototype.getConnectionAvailableModels,
getModelCandidates: prototype.getModelCandidates,
getScopedModelsFromModelIds: prototype.getScopedModelsFromModelIds,
@@ -1250,17 +1267,26 @@ describe("InteractiveMode model candidates", () => {
const result = await prototype.getModelCandidates.call(fakeThis);
expect(result).toEqual([model]);
- expect(getAvailableModels).toHaveBeenCalledTimes(1);
+ expect(getModelCatalog).toHaveBeenCalledTimes(1);
expect(fakeThis.connectionModels).toEqual([model]);
});
test("uses connection state for scoped model candidates", async () => {
const model = createModel("anthropic", "claude-opus-4-5");
- const getAvailableModels = vi.fn(async () => [createModel("openai", "gpt-5.5")]);
+ const getModelCatalog = vi.fn(async () => {
+ const available = createModel("openai", "gpt-5.5");
+ return { models: [available], configuredProviders: [available.provider] };
+ });
const fakeThis: ModelCandidatesHarness = {
- agentConnection: { getAvailableModels },
+ agentConnection: { getModelCatalog },
connectionModels: [],
+ connectionModelCatalog: [],
+ connectionConfiguredProviders: new Set(),
+ connectionModelsFetchedAt: 0,
+ connectionModelsRefreshVersion: 0,
+ connectionModelsRefreshInFlight: undefined,
getScopedModelState: () => [{ model, thinkingLevel: "medium" }],
+ applyConnectionModelCatalog: prototype.applyConnectionModelCatalog,
getConnectionAvailableModels: prototype.getConnectionAvailableModels,
getModelCandidates: prototype.getModelCandidates,
getScopedModelsFromModelIds: prototype.getScopedModelsFromModelIds,
@@ -1269,7 +1295,7 @@ describe("InteractiveMode model candidates", () => {
const result = await prototype.getModelCandidates.call(fakeThis);
expect(result).toEqual([model]);
- expect(getAvailableModels).not.toHaveBeenCalled();
+ expect(getModelCatalog).not.toHaveBeenCalled();
});
test("maps selected scoped model IDs from connection candidates", () => {
@@ -1300,6 +1326,17 @@ describe("InteractiveMode model selection persistence", () => {
updateEditorBorderColor(): void;
showStatus(message: string): void;
showError(message: string): void;
+ connectionConfiguredProviders: Set<string>;
+ createAuthFlows(): {
+ getLoginProviderOptions(): ReadonlyArray<AuthSelectorProvider>;
+ loginProvider(provider: AuthSelectorProvider): Promise<AuthenticationResult>;
+ };
+ ensureModelProviderConfigured(
+ model: AgentConnectionModel,
+ authFlows: ReturnType<ModelSelectionHarness["createAuthFlows"]>,
+ providerOptions: ReadonlyArray<AuthSelectorProvider>,
+ ): Promise<boolean>;
+ completeModelSelection(model: AgentConnectionModel): Promise<void>;
findExactModelMatch(searchTerm: string): Promise<AgentConnectionModel | undefined>;
maybeWarnAboutAnthropicSubscriptionAuth(model: AgentConnectionModel): Promise<void>;
checkDaxnutsEasterEgg(model: AgentConnectionModel): void;
@@ -1309,10 +1346,12 @@ describe("InteractiveMode model selection persistence", () => {
};
type ModelSelectorOverlayHarness = {
agentConnection: {
- getAvailableModels(): Promise<AgentConnectionModel[]>;
+ getModelCatalog(): Promise<AgentConnectionModelCatalog>;
setModel(provider: string, modelId: string): Promise<void>;
};
connectionModels: AgentConnectionModel[];
+ connectionModelCatalog: AgentConnectionModel[];
+ connectionConfiguredProviders: Set<string>;
connectionModelsFetchedAt: number;
connectionModelsRefreshVersion: number;
connectionModelsRefreshInFlight: { version: number; promise: Promise<AgentConnectionModel[]> } | undefined;
@@ -1331,14 +1370,21 @@ describe("InteractiveMode model selection persistence", () => {
showError(message: string): void;
getScopedModelState(): AgentConnectionState["scopedModels"];
getCurrentModel(): AgentConnectionModel | undefined;
+ applyConnectionModelCatalog(catalog: AgentConnectionModelCatalog): void;
findExactModelMatch(searchTerm: string): Promise<AgentConnectionModel | undefined>;
getConnectionAvailableModels(): Promise<AgentConnectionModel[]>;
getCachedModelCandidates(): AgentConnectionModel[];
getModelSelectorRefreshPromise(options?: { force?: boolean }): Promise<AgentConnectionModel[]> | undefined;
createAuthFlows(): {
- getLoginProviderOptions(): ReadonlyArray<never>;
- loginProvider(): Promise<AuthenticationResult>;
- };
+ getLoginProviderOptions(): ReadonlyArray<AuthSelectorProvider>;
+ loginProvider(provider: AuthSelectorProvider): Promise<AuthenticationResult>;
+ };
+ ensureModelProviderConfigured(
+ model: AgentConnectionModel,
+ authFlows: ReturnType<ModelSelectorOverlayHarness["createAuthFlows"]>,
+ providerOptions: ReadonlyArray<AuthSelectorProvider>,
+ ): Promise<boolean>;
+ completeModelSelection(model: AgentConnectionModel): Promise<void>;
applySelectedModel(model: AgentConnectionModel): Promise<void>;
showFullPaneOverlay(
component: Component,
@@ -1363,21 +1409,34 @@ describe("InteractiveMode model selection persistence", () => {
function createSelectorOverlayHarness(options: {
connectionModels: AgentConnectionModel[];
+ catalogModels?: AgentConnectionModel[];
+ configuredProviders?: ReadonlyArray<string>;
registryModels?: AgentConnectionModel[];
getAvailableModels?: () => Promise<AgentConnectionModel[]>;
+ getModelCatalog?: () => Promise<AgentConnectionModelCatalog>;
+ providerOptions?: AuthSelectorProvider[];
+ loginProvider?: (provider: AuthSelectorProvider) => Promise<AuthenticationResult>;
applySelectedModel?: (model: AgentConnectionModel) => Promise<void>;
currentModel?: AgentConnectionModel;
connectionModelsFetchedAt?: number;
scopedModels?: AgentConnectionState["scopedModels"];
+ hasConfiguredAuth?: (model: AgentConnectionModel) => boolean;
}) {
let overlayComponent: Component | undefined;
const hide = vi.fn();
+ const setHidden = vi.fn();
+ const focus = vi.fn();
const registryModels = [...(options.registryModels ?? options.connectionModels)];
+ const catalogModels = [...(options.catalogModels ?? options.connectionModels)];
+ const configuredProviders = new Set(
+ options.configuredProviders ?? options.connectionModels.map((model) => model.provider),
+ );
const modelRegistry = {
authStorage: AuthStorage.inMemory(),
refresh: vi.fn(),
getError: vi.fn(() => undefined),
getAvailable: vi.fn(() => registryModels),
+ hasConfiguredAuth: vi.fn((model: AgentConnectionModel) => options.hasConfiguredAuth?.(model) ?? false),
getProviderAuthStatus: vi.fn(() => ({ configured: false })),
find: vi.fn((provider: string, modelId: string) =>
registryModels.find((model) => model.provider === provider && model.id === modelId),
@@ -1385,10 +1444,24 @@ describe("InteractiveMode model selection persistence", () => {
} as unknown as ModelRegistry;
const fakeThis = Object.create(InteractiveMode.prototype) as ModelSelectorOverlayHarness;
fakeThis.agentConnection = {
- getAvailableModels: options.getAvailableModels ?? vi.fn(async () => options.connectionModels),
+ getModelCatalog:
+ options.getModelCatalog ??
+ vi.fn(async () => {
+ const models = options.getAvailableModels
+ ? await options.getAvailableModels()
+ : options.connectionModels;
+ return {
+ models: options.catalogModels ?? models,
+ configuredProviders: options.configuredProviders
+ ? [...options.configuredProviders]
+ : models.map((model) => model.provider),
+ };
+ }),
setModel: vi.fn(async () => {}),
};
fakeThis.connectionModels = [...options.connectionModels];
+ fakeThis.connectionModelCatalog = catalogModels;
+ fakeThis.connectionConfiguredProviders = configuredProviders;
fakeThis.connectionModelsFetchedAt = options.connectionModelsFetchedAt ?? 0;
fakeThis.connectionModelsRefreshVersion = 0;
fakeThis.connectionModelsRefreshInFlight = undefined;
@@ -1410,6 +1483,7 @@ describe("InteractiveMode model selection persistence", () => {
fakeThis.showError = vi.fn();
fakeThis.getScopedModelState = vi.fn(() => options.scopedModels ?? []);
fakeThis.getCurrentModel = vi.fn(() => options.currentModel);
+ fakeThis.applyConnectionModelCatalog = overlayPrototype.applyConnectionModelCatalog;
fakeThis.findExactModelMatch = (
InteractiveMode.prototype as unknown as {
findExactModelMatch(searchTerm: string): Promise<AgentConnectionModel | undefined>;
@@ -1419,13 +1493,15 @@ describe("InteractiveMode model selection persistence", () => {
fakeThis.getCachedModelCandidates = overlayPrototype.getCachedModelCandidates;
fakeThis.getModelSelectorRefreshPromise = overlayPrototype.getModelSelectorRefreshPromise;
fakeThis.createAuthFlows = vi.fn(() => ({
- getLoginProviderOptions: () => [],
- loginProvider: async () => ({ status: "cancelled" as const }),
+ getLoginProviderOptions: () => options.providerOptions ?? [],
+ loginProvider: options.loginProvider ?? (async () => ({ status: "cancelled" as const })),
}));
fakeThis.applySelectedModel = options.applySelectedModel ?? vi.fn(async () => {});
+ fakeThis.ensureModelProviderConfigured = overlayPrototype.ensureModelProviderConfigured;
+ fakeThis.completeModelSelection = overlayPrototype.completeModelSelection;
fakeThis.showFullPaneOverlay = vi.fn((component: Component) => {
overlayComponent = component;
- return { hide, setHidden: vi.fn(), focus: vi.fn() };
+ return { hide, setHidden, focus };
});
fakeThis.showConfigurationMenu = overlayPrototype.showConfigurationMenu;
fakeThis.maybeWarnAboutAnthropicSubscriptionAuth = vi.fn(async () => {});
@@ -1435,6 +1511,8 @@ describe("InteractiveMode model selection persistence", () => {
return {
fakeThis,
hide,
+ setHidden,
+ focus,
getSelector: () => {
if (!overlayComponent) {
throw new Error("Expected model selector overlay to be shown");
@@ -1534,6 +1612,13 @@ describe("InteractiveMode model selection persistence", () => {
fakeThis.updateEditorBorderColor = vi.fn();
fakeThis.showStatus = vi.fn();
fakeThis.showError = vi.fn();
+ fakeThis.connectionConfiguredProviders = new Set([model.provider]);
+ fakeThis.createAuthFlows = vi.fn(() => ({
+ getLoginProviderOptions: () => [],
+ loginProvider: async () => ({ status: "cancelled" as const }),
+ }));
+ fakeThis.ensureModelProviderConfigured = overlayPrototype.ensureModelProviderConfigured;
+ fakeThis.completeModelSelection = overlayPrototype.completeModelSelection;
fakeThis.findExactModelMatch = vi.fn(async () => model);
fakeThis.maybeWarnAboutAnthropicSubscriptionAuth = vi.fn(async () => {});
fakeThis.checkDaxnutsEasterEgg = vi.fn();
@@ -1582,7 +1667,16 @@ describe("InteractiveMode model selection persistence", () => {
connectionModelsFetchedAt: Date.now(),
getAvailableModels,
});
- fakeThis.connectionModelsRefreshInFlight = { version: 0, promise: liveModels.promise };
+ fakeThis.connectionModelsRefreshInFlight = {
+ version: 0,
+ promise: liveModels.promise.then((models) => {
+ fakeThis.applyConnectionModelCatalog({
+ models,
+ configuredProviders: models.map((model) => model.provider),
+ });
+ return models;
+ }),
+ };
const result = fakeThis.showConfigurationMenu("models", "beta");
await flushAsyncWork();
@@ -1662,6 +1756,8 @@ describe("InteractiveMode model selection persistence", () => {
});
test("keeps cached daemon models visible when scoped models are active", async () => {
+ const previousKeybindings = getKeybindings();
+ setKeybindings(new KeybindingsManager());
const scopedModel = createModel("openai", "scoped");
const catalogModel = createModel("anthropic", "catalog");
const getAvailableModels = vi.fn(async () => [catalogModel]);
@@ -1679,12 +1775,15 @@ describe("InteractiveMode model selection persistence", () => {
expect(fakeThis.getCachedModelCandidates()).toEqual([scopedModel, catalogModel]);
await expect(fakeThis.findExactModelMatch("catalog")).resolves.toEqual(catalogModel);
- getSelector().handleInput("\t");
+ getSelector().handleInput("\x1b[Z");
expect(getSelector().render(120).join("\n")).toContain("catalog");
expect(getAvailableModels).not.toHaveBeenCalled();
+ getSelector().handleInput("\t");
+ expect(getSelector().getActiveTab()).toBe("mcp-connections");
getSelector().handleInput("\x1b");
await expect(result).resolves.toBeUndefined();
+ setKeybindings(previousKeybindings);
});
test("uses a fresh cached model catalog without starting another refresh", async () => {
@@ -1708,7 +1807,7 @@ describe("InteractiveMode model selection persistence", () => {
test("closes the model selector before the selected model finishes applying", async () => {
const model = createModel("openai", "gpt-5.5");
const apply = createDeferred<void>();
- const { fakeThis, getSelector, hide } = createSelectorOverlayHarness({
+ const { fakeThis, getSelector, hide, setHidden } = createSelectorOverlayHarness({
connectionModels: [model],
applySelectedModel: vi.fn(() => apply.promise),
});
@@ -1724,16 +1823,111 @@ describe("InteractiveMode model selection persistence", () => {
getSelector().handleInput("\r");
await flushAsyncWork();
- expect(hide).toHaveBeenCalledTimes(1);
+ expect(setHidden).toHaveBeenCalledWith(true);
+ expect(hide).not.toHaveBeenCalled();
expect(fakeThis.showStatus).toHaveBeenCalledWith("Switching model: gpt-5.5");
expect(resolved).toBe(false);
apply.resolve();
await expect(result).resolves.toBeUndefined();
+ expect(hide).toHaveBeenCalledTimes(1);
expect(fakeThis.showStatus).toHaveBeenCalledWith("Model: gpt-5.5");
});
+ test("reopens the model selector when the selected model fails to apply", async () => {
+ const model = createModel("openai", "gpt-5.5");
+ const { fakeThis, getSelector, hide, setHidden, focus } = createSelectorOverlayHarness({
+ connectionModels: [model],
+ applySelectedModel: vi.fn(async () => {
+ throw new Error("model switch failed");
+ }),
+ });
+
+ const result = fakeThis.showConfigurationMenu("models");
+ await flushAsyncWork();
+ getSelector().handleInput("\r");
+ await flushAsyncWork();
+
+ expect(hide).not.toHaveBeenCalled();
+ expect(setHidden).toHaveBeenNthCalledWith(1, true);
+ expect(setHidden).toHaveBeenNthCalledWith(2, false);
+ expect(focus).toHaveBeenCalled();
+ expect(fakeThis.showError).toHaveBeenCalledWith("model switch failed");
+
+ getSelector().handleInput("\x1b");
+ await expect(result).resolves.toBeUndefined();
+ expect(hide).toHaveBeenCalledTimes(1);
+ });
+
+ test("authenticates an unavailable model provider before applying the model", async () => {
+ const model = createModel("openai", "gpt-5.5");
+ const provider: AuthSelectorProvider = { id: "openai", name: "OpenAI", authType: "api_key" };
+ let authenticated = false;
+ const getModelCatalog = vi.fn(async () => ({
+ models: [model],
+ configuredProviders: [],
+ }));
+ const loginProvider = vi.fn(async (): Promise<AuthenticationResult> => {
+ authenticated = true;
+ return {
+ status: "success",
+ providerId: provider.id,
+ providerName: provider.name,
+ authType: provider.authType,
+ };
+ });
+ const applySelectedModel = vi.fn(async () => {});
+ const { fakeThis, getSelector, hide } = createSelectorOverlayHarness({
+ connectionModels: [],
+ catalogModels: [model],
+ configuredProviders: [],
+ connectionModelsFetchedAt: Date.now(),
+ getModelCatalog,
+ providerOptions: [provider],
+ loginProvider,
+ applySelectedModel,
+ hasConfiguredAuth: () => authenticated,
+ });
+
+ const result = fakeThis.showConfigurationMenu("models");
+ getSelector().handleInput("\r");
+ await flushAsyncWork();
+
+ expect(loginProvider).toHaveBeenCalledWith(provider);
+ expect(getModelCatalog).toHaveBeenCalledTimes(1);
+ expect(applySelectedModel).toHaveBeenCalledWith(model);
+ expect(hide).toHaveBeenCalledTimes(1);
+ await expect(result).resolves.toBeUndefined();
+ });
+
+ test("keeps the model selector open when provider authentication is cancelled", async () => {
+ const model = createModel("openai", "gpt-5.5");
+ const provider: AuthSelectorProvider = { id: "openai", name: "OpenAI", authType: "api_key" };
+ const loginProvider = vi.fn(async () => ({ status: "cancelled" as const }));
+ const applySelectedModel = vi.fn(async () => {});
+ const { fakeThis, getSelector, hide } = createSelectorOverlayHarness({
+ connectionModels: [],
+ catalogModels: [model],
+ configuredProviders: [],
+ connectionModelsFetchedAt: Date.now(),
+ providerOptions: [provider],
+ loginProvider,
+ applySelectedModel,
+ });
+
+ const result = fakeThis.showConfigurationMenu("models");
+ getSelector().handleInput("\r");
+ await flushAsyncWork();
+
+ expect(loginProvider).toHaveBeenCalledWith(provider);
+ expect(applySelectedModel).not.toHaveBeenCalled();
+ expect(hide).not.toHaveBeenCalled();
+
+ getSelector().handleInput("\x1b");
+ await expect(result).resolves.toBeUndefined();
+ });
+
test("refreshes model selector results in the background without clearing search", async () => {
const alpha = createModel("openai", "alpha");
const beta = { ...createModel("openai", "beta"), name: "Beta Model" };
@@ -1783,11 +1977,11 @@ describe("InteractiveMode model selection persistence", () => {
test("does not let a stale model refresh overwrite a newer catalog refresh", async () => {
const oldModel = createModel("openai", "old");
const freshModel = createModel("openai", "fresh");
- const oldModels = createDeferred<AgentConnectionModel[]>();
- const getAvailableModels = vi
- .fn<() => Promise<AgentConnectionModel[]>>()
+ const oldModels = createDeferred<AgentConnectionModelCatalog>();
+ const getModelCatalog = vi
+ .fn<() => Promise<AgentConnectionModelCatalog>>()
.mockImplementationOnce(() => oldModels.promise)
- .mockImplementationOnce(async () => [freshModel]);
+ .mockImplementationOnce(async () => ({ models: [freshModel], configuredProviders: [freshModel.provider] }));
const fakeThis = Object.create(InteractiveMode.prototype) as ModelSelectorOverlayHarness & {
connectionCommands: unknown[];
connectionResourceSnapshot: unknown;
@@ -1797,17 +1991,20 @@ describe("InteractiveMode model selection persistence", () => {
invalidateConnectionModelRefresh(): void;
};
fakeThis.agentConnection = {
- getAvailableModels,
+ getModelCatalog,
getState: vi.fn(async () => createConnectionState()),
getCommands: vi.fn(async () => []),
getResourceSnapshot: vi.fn(async () => ({})),
setModel: vi.fn(async () => {}),
} as never;
fakeThis.connectionModels = [];
+ fakeThis.connectionModelCatalog = [];
+ fakeThis.connectionConfiguredProviders = new Set();
fakeThis.connectionModelsFetchedAt = 0;
fakeThis.connectionModelsRefreshVersion = 0;
fakeThis.connectionModelsRefreshInFlight = undefined;
fakeThis.getScopedModelState = vi.fn(() => []);
+ fakeThis.applyConnectionModelCatalog = overlayPrototype.applyConnectionModelCatalog;
fakeThis.getConnectionAvailableModels = overlayPrototype.getConnectionAvailableModels;
fakeThis.refreshConnectionCatalog = (
InteractiveMode.prototype as unknown as { refreshConnectionCatalog(): Promise<void> }
@@ -1822,7 +2019,7 @@ describe("InteractiveMode model selection persistence", () => {
const staleRefresh = fakeThis.getConnectionAvailableModels();
await fakeThis.refreshConnectionCatalog();
- oldModels.resolve([oldModel]);
+ oldModels.resolve({ models: [oldModel], configuredProviders: [oldModel.provider] });
await expect(staleRefresh).resolves.toEqual([freshModel]);
@@ -1839,7 +2036,10 @@ describe("InteractiveMode model selection persistence", () => {
invalidateConnectionModelRefresh(): void;
};
fakeThis.agentConnection = {
- getAvailableModels: vi.fn(async () => [createModel("openai", "fresh")]),
+ getModelCatalog: vi.fn(async () => {
+ const fresh = createModel("openai", "fresh");
+ return { models: [fresh], configuredProviders: [fresh.provider] };
+ }),
getState: vi.fn(async () => createConnectionState()),
getCommands: vi.fn(async () => {
throw new Error("commands unavailable");
@@ -1848,9 +2048,12 @@ describe("InteractiveMode model selection persistence", () => {
setModel: vi.fn(async () => {}),
} as never;
fakeThis.connectionModels = [cachedModel];
+ fakeThis.connectionModelCatalog = [cachedModel];
+ fakeThis.connectionConfiguredProviders = new Set([cachedModel.provider]);
fakeThis.connectionModelsFetchedAt = Date.now();
fakeThis.connectionModelsRefreshVersion = 0;
fakeThis.connectionModelsRefreshInFlight = undefined;
+ fakeThis.applyConnectionModelCatalog = overlayPrototype.applyConnectionModelCatalog;
fakeThis.refreshConnectionCatalog = (
InteractiveMode.prototype as unknown as { refreshConnectionCatalog(): Promise<void> }
).refreshConnectionCatalog;
@@ -2201,12 +2404,12 @@ describe("InteractiveMode post-login model preparation", () => {
}),
).resolves.toBe(true);
- expect(fakeThis.invalidateConnectionModels).toHaveBeenCalledTimes(1);
+ expect(fakeThis.invalidateConnectionModels).not.toHaveBeenCalled();
expect(fakeThis.applySelectedModel).toHaveBeenCalledWith(fallbackModel);
expect(flushSettings).toHaveBeenCalledTimes(1);
});
- test("invalidates cached models after any model-provider login", async () => {
+ test("preserves refreshed models after any model-provider login", async () => {
const fakeThis = Object.create(InteractiveMode.prototype) as LoginHarness;
fakeThis.invalidateConnectionModels = vi.fn();
fakeThis.getCurrentModel = vi.fn(() => loginPrimeModel);
@@ -2231,7 +2434,7 @@ describe("InteractiveMode post-login model preparation", () => {
}),
).resolves.toBe(false);
- expect(fakeThis.invalidateConnectionModels).toHaveBeenCalledTimes(1);
+ expect(fakeThis.invalidateConnectionModels).not.toHaveBeenCalled();
expect(fakeThis.applySelectedModel).not.toHaveBeenCalled();
});
});
diff --git a/packages/coding-agent/test/model-registry.test.ts b/packages/coding-agent/test/model-registry.test.ts
index 6e44df8e50..dc9ec2b43a 100644
--- a/packages/coding-agent/test/model-registry.test.ts
+++ b/packages/coding-agent/test/model-registry.test.ts
@@ -1122,6 +1122,36 @@ describe("ModelRegistry", () => {
});
describe("auth refresh across processes", () => {
+ test("model catalog includes unauthenticated public models and hides private Prime routes", async () => {
+ const savedPrimeApiKey = process.env.PRIME_API_KEY;
+ const savedOpenAiApiKey = process.env.OPENAI_API_KEY;
+ delete process.env.PRIME_API_KEY;
+ delete process.env.OPENAI_API_KEY;
+ try {
+ const registry = ModelRegistry.create(authStorage, modelsJsonPath);
+
+ const unauthenticated = await registry.refreshModelCatalog();
+ expect(unauthenticated.models.some((model) => model.provider === "openai")).toBe(true);
+ expect(unauthenticated.configuredProviders).not.toContain("openai");
+ expect(
+ unauthenticated.models.some(
+ (model) => model.provider === "prime-inference" && model.id.startsWith("internal/"),
+ ),
+ ).toBe(false);
+
+ authStorage.setRuntimeApiKey("openai", "test-key");
+ const authenticated = await registry.refreshModelCatalog();
+ expect(authenticated.configuredProviders).toContain("openai");
+ } finally {
+ if (savedPrimeApiKey !== undefined) {
+ process.env.PRIME_API_KEY = savedPrimeApiKey;
+ }
+ if (savedOpenAiApiKey !== undefined) {
+ process.env.OPENAI_API_KEY = savedOpenAiApiKey;
+ }
+ }
+ });
+
test("refresh() picks up credentials written by another process", () => {
const savedEnvKey = process.env.PRIME_API_KEY;
delete process.env.PRIME_API_KEY;
diff --git a/packages/coding-agent/test/model-selector-actions.test.ts b/packages/coding-agent/test/model-selector-actions.test.ts
index e56dc53ced..0553b3751f 100644
--- a/packages/coding-agent/test/model-selector-actions.test.ts
+++ b/packages/coding-agent/test/model-selector-actions.test.ts
@@ -1,4 +1,4 @@
-import { type KeyId, setKeybindings, type TUI } from "@earendil-works/pi-tui";
+import { setKeybindings, type TUI } from "@earendil-works/pi-tui";
import stripAnsi from "strip-ansi";
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { KeybindingsManager } from "../src/core/keybindings.js";
@@ -16,7 +16,7 @@ async function waitForAsyncRender(): Promise<void> {
await new Promise((resolve) => setTimeout(resolve, 0));
}
-describe("ModelSelectorComponent provider actions", () => {
+describe("ModelSelectorComponent", () => {
const harnesses: Harness[] = [];
beforeAll(() => {
@@ -33,15 +33,13 @@ describe("ModelSelectorComponent provider actions", () => {
}
});
- it("shows provider setup shortcut in the warning and emits the selected action", async () => {
+ it("explains model authentication without a provider shortcut", async () => {
const harness = await createHarness({
models: [{ id: "faux-1", name: "One", reasoning: true }],
});
harnesses.push(harness);
- let selectedAction: string | undefined;
let selectedModel: string | undefined;
- setKeybindings(new KeybindingsManager({ "app.provider.add": "ctrl+x" as KeyId }));
const selector = new ModelSelectorComponent(
createFakeTui(),
harness.getModel("faux-1"),
@@ -53,10 +51,6 @@ describe("ModelSelectorComponent provider actions", () => {
() => {},
undefined,
{
- actions: [{ id: "add_provider", label: "Add provider...", description: "subscription or API key" }],
- onAction: (actionId) => {
- selectedAction = actionId;
- },
subtitle: "Choose a Prime model, or add another provider.",
},
);
@@ -65,16 +59,11 @@ describe("ModelSelectorComponent provider actions", () => {
const output = stripAnsi(selector.render(120).join("\n"));
expect(output).toContain("Choose a Prime model, or add another provider.");
- expect(output).toContain("Ctrl+X to add providers and access more models.");
- expect(output.indexOf("add provider")).toBeLessThan(output.indexOf("Search models"));
- expect(output.match(/add provider/g)).toHaveLength(1);
+ expect(output).toContain("Signed-in providers first.");
+ expect(output).not.toContain("opens providers");
selector.handleInput("\r");
expect(selectedModel).toBe("faux-1");
-
- selector.handleInput("\x18");
-
- expect(selectedAction).toBe("add_provider");
});
it("renders injected daemon models without refreshing the local registry", async () => {
@@ -278,19 +267,16 @@ describe("ModelSelectorComponent provider actions", () => {
})),
});
harnesses.push(harness);
- const scopedModels = Array.from({ length: 12 }, (_, index) => {
- const model = harness.getModel(`faux-${index + 1}`);
- if (!model) {
- throw new Error(`Missing model faux-${index + 1}`);
- }
- return { model };
- });
+ const scopedModel = harness.getModel("faux-1");
+ if (!scopedModel) {
+ throw new Error("Missing model faux-1");
+ }
const selector = new ModelSelectorComponent(
createFakeTui(),
harness.getModel("faux-1"),
harness.session.modelRegistry,
- scopedModels,
+ [{ model: scopedModel }],
() => {},
() => {},
undefined,
@@ -299,12 +285,20 @@ describe("ModelSelectorComponent provider actions", () => {
await waitForAsyncRender();
- const lines = selector.render(120);
- const output = stripAnsi(lines.join("\n"));
+ let lines = selector.render(120);
+ let output = stripAnsi(lines.join("\n"));
expect(lines.length).toBeLessThanOrEqual(16);
expect(output).toContain("Scope: ");
+ expect(output).toContain("Shift+Tab scope");
expect(output).toContain("(all/scoped)");
+ expect(output).not.toContain("(1/12)");
+
+ selector.handleInput("\x1b[Z");
+ lines = selector.render(120);
+ output = stripAnsi(lines.join("\n"));
+
+ expect(lines.length).toBeLessThanOrEqual(16);
expect(output).toContain("(1/12)");
});
});
diff --git a/packages/coding-agent/test/selector-search-reset.test.ts b/packages/coding-agent/test/selector-search-reset.test.ts
new file mode 100644
index 0000000000..be2d93d1dd
--- /dev/null
+++ b/packages/coding-agent/test/selector-search-reset.test.ts
@@ -0,0 +1,185 @@
+import { setKeybindings, type TUI } from "@earendil-works/pi-tui";
+import { afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
+import { AuthStorage } from "../src/core/auth-storage.js";
+import { KeybindingsManager } from "../src/core/keybindings.js";
+import type { AgentConnectionSavedSessionInfo } from "../src/modes/agent-connection/index.js";
+import { ModelSelectorComponent } from "../src/modes/interactive/components/model-selector.js";
+import { OAuthSelectorComponent } from "../src/modes/interactive/components/oauth-selector.js";
+import { PrimeTeamSelectorComponent } from "../src/modes/interactive/components/prime-team-selector.js";
+import { ScopedModelsSelectorComponent } from "../src/modes/interactive/components/scoped-models-selector.js";
+import { SessionSelectorComponent } from "../src/modes/interactive/components/session-selector.js";
+import { initTheme } from "../src/modes/interactive/theme/theme.js";
+import { createHarness, type Harness } from "./suite/harness.js";
+
+const DOWN = "\x1b[B";
+
+function createFakeTui(): TUI {
+ return { requestRender: () => {} } as unknown as TUI;
+}
+
+function moveDown(component: { handleInput(data: string): void }, count: number): void {
+ for (let index = 0; index < count; index++) {
+ component.handleInput(DOWN);
+ }
+}
+
+function makeSession(index: number): AgentConnectionSavedSessionInfo {
+ return {
+ path: `/tmp/session-${index}.jsonl`,
+ id: `session-${index}`,
+ cwd: "/tmp",
+ name: `Session ${index}`,
+ created: new Date(index),
+ modified: new Date(index),
+ messageCount: 1,
+ firstMessage: "common topic",
+ allMessagesText: "common topic",
+ };
+}
+
+async function flushPromises(): Promise<void> {
+ await new Promise<void>((resolve) => setImmediate(resolve));
+}
+
+describe("searchable selector navigation", () => {
+ const harnesses: Harness[] = [];
+
+ beforeAll(() => {
+ initTheme("dark");
+ });
+
+ beforeEach(() => {
+ setKeybindings(new KeybindingsManager());
+ });
+
+ afterEach(() => {
+ while (harnesses.length > 0) {
+ harnesses.pop()?.cleanup();
+ }
+ });
+
+ it("selects the first model after the search query changes", async () => {
+ const harness = await createHarness({
+ models: Array.from({ length: 12 }, (_, index) => ({
+ id: `faux-${index + 1}`,
+ name: `Faux ${index + 1}`,
+ reasoning: true,
+ })),
+ });
+ harnesses.push(harness);
+ let selectedModelId: string | undefined;
+ const selector = new ModelSelectorComponent(
+ createFakeTui(),
+ undefined,
+ harness.session.modelRegistry,
+ [],
+ (model) => {
+ selectedModelId = model.id;
+ },
+ () => {},
+ undefined,
+ { availableModels: harness.models },
+ );
+
+ moveDown(selector, 8);
+ selector.handleInput("f");
+ selector.handleInput("\r");
+
+ expect(selectedModelId).toBe("faux-1");
+ });
+
+ it("selects the first provider after the search query changes", () => {
+ let selectedProviderId: string | undefined;
+ const selector = new OAuthSelectorComponent(
+ "login",
+ AuthStorage.inMemory(),
+ Array.from({ length: 12 }, (_, index) => ({
+ id: `provider-${index + 1}`,
+ name: `Provider ${String(index + 1).padStart(2, "0")}`,
+ authType: "api_key" as const,
+ })),
+ (provider) => {
+ selectedProviderId = provider.id;
+ },
+ () => {},
+ );
+
+ moveDown(selector, 8);
+ selector.handleInput("p");
+ selector.handleInput("\r");
+
+ expect(selectedProviderId).toBe("provider-1");
+ });
+
+ it("selects the first team after the search query changes", () => {
+ let selectedTeamId: string | undefined;
+ const selector = new PrimeTeamSelectorComponent(
+ Array.from({ length: 12 }, (_, index) => ({
+ teamId: `team-${index + 1}`,
+ name: `Team ${String(index + 1).padStart(2, "0")}`,
+ })),
+ undefined,
+ (team) => {
+ selectedTeamId = team?.teamId;
+ },
+ () => {},
+ );
+
+ moveDown(selector, 8);
+ selector.handleInput("t");
+ selector.handleInput("\r");
+
+ expect(selectedTeamId).toBe("team-1");
+ });
+
+ it("toggles the first scoped model after the search query changes", async () => {
+ const harness = await createHarness({
+ models: Array.from({ length: 12 }, (_, index) => ({
+ id: `faux-${index + 1}`,
+ name: `Faux ${index + 1}`,
+ reasoning: true,
+ })),
+ });
+ harnesses.push(harness);
+ let enabledModelIds: string[] | null | undefined;
+ const selector = new ScopedModelsSelectorComponent(
+ { allModels: harness.models, enabledModelIds: [] },
+ {
+ onChange: (ids) => {
+ enabledModelIds = ids;
+ },
+ onPersist: () => {},
+ onCancel: () => {},
+ },
+ );
+
+ moveDown(selector, 8);
+ selector.handleInput("f");
+ selector.handleInput("\r");
+
+ expect(enabledModelIds).toEqual([`${harness.models[0]?.provider}/faux-1`]);
+ });
+
+ it("selects the first session after the search query changes", async () => {
+ const sessions = Array.from({ length: 12 }, (_, index) => makeSession(index + 1));
+ let selectedPath: string | undefined;
+ const selector = new SessionSelectorComponent(
+ async () => sessions,
+ async () => sessions,
+ (path) => {
+ selectedPath = path;
+ },
+ () => {},
+ () => {},
+ () => {},
+ );
+ await flushPromises();
+
+ const list = selector.getSessionList();
+ moveDown(list, 8);
+ list.handleInput("c");
+ list.handleInput("\r");
+
+ expect(selectedPath).toBe(sessions.at(-1)?.path);
+ });
+});
diff --git a/packages/coding-agent/test/suite/regressions/4573-prime-inference-login-default.test.ts b/packages/coding-agent/test/suite/regressions/4573-prime-inference-login-default.test.ts
index e64804985f..7a45c358b6 100644
--- a/packages/coding-agent/test/suite/regressions/4573-prime-inference-login-default.test.ts
+++ b/packages/coding-agent/test/suite/regressions/4573-prime-inference-login-default.test.ts
@@ -10,7 +10,6 @@ import { createHarness, type Harness } from "../harness.js";
type LoginHarness = {
prepareForModelSelectionAfterLogin(authResult: AuthenticationResult): Promise<boolean>;
- invalidateConnectionModels(): void;
getCurrentModel(): AgentConnectionModel | undefined;
getConnectionAvailableModels(): Promise<AgentConnectionModel[]>;
applySelectedModel(model: AgentConnectionModel): Promise<void>;
@@ -86,7 +85,6 @@ describe("ENG-4573 Prime Inference login default", () => {
};
const order: string[] = [];
const fakeThis = Object.create(InteractiveMode.prototype) as LoginHarness;
- fakeThis.invalidateConnectionModels = vi.fn(() => order.push("invalidate"));
fakeThis.getCurrentModel = vi.fn(() => placeholderModel);
fakeThis.getConnectionAvailableModels = vi.fn(async () => {
order.push("refresh");
@@ -119,6 +117,6 @@ describe("ENG-4573 Prime Inference login default", () => {
expect(fakeThis.applySelectedModel).toHaveBeenCalledWith(fallbackModel);
expect(fakeThis.showError).not.toHaveBeenCalled();
- expect(order).toEqual(["invalidate", "refresh", "select", "persist"]);
+ expect(order).toEqual(["refresh", "select", "persist"]);
});
});
diff --git a/packages/coding-agent/test/suite/regressions/4575-model-auth-selection.test.ts b/packages/coding-agent/test/suite/regressions/4575-model-auth-selection.test.ts
new file mode 100644
index 0000000000..efdf3558e8
--- /dev/null
+++ b/packages/coding-agent/test/suite/regressions/4575-model-auth-selection.test.ts
@@ -0,0 +1,247 @@
+import { type AutocompleteProvider, setKeybindings, type TUI } from "@earendil-works/pi-tui";
+import stripAnsi from "strip-ansi";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+import { KeybindingsManager } from "../../../src/core/keybindings.js";
+import type { AgentConnectionModel, AgentConnectionModelCatalog } from "../../../src/modes/agent-connection/types.js";
+import {
+ getAgentsViewModelArgumentCompletions,
+ syncAgentsViewModelMenuAfterAuth,
+} from "../../../src/modes/agents-view/agents-view-mode.js";
+import { ModelSelectorComponent } from "../../../src/modes/interactive/components/model-selector.js";
+import { InteractiveMode } from "../../../src/modes/interactive/interactive-mode.js";
+import { initTheme } from "../../../src/modes/interactive/theme/theme.js";
+import { getModelArgumentCompletions } from "../../../src/modes/model-autocomplete.js";
+import { createHarness, type Harness } from "../harness.js";
+
+interface ConnectionAuthRefreshHarness {
+ agentConnection: { getModelCatalog(): Promise<AgentConnectionModelCatalog> };
+ connectionModels: AgentConnectionModel[];
+ connectionModelCatalog: AgentConnectionModel[];
+ connectionConfiguredProviders: Set<string>;
+ connectionModelsFetchedAt: number;
+ connectionModelsRefreshVersion: number;
+ connectionModelsRefreshInFlight: { version: number; promise: Promise<AgentConnectionModel[]> } | undefined;
+ invalidateConnectionModels(): void;
+ applyConnectionModelCatalog(catalog: AgentConnectionModelCatalog): void;
+ getConnectionAvailableModels(): Promise<AgentConnectionModel[]>;
+ getConnectionModelCatalog(): Promise<AgentConnectionModel[]>;
+ refreshConnectionModelsAfterAuthChange(): Promise<void>;
+}
+
+interface InteractiveAutocompleteHarness {
+ connectionState: { scopedModels: Array<{ model: AgentConnectionModel }> };
+ connectionModelCatalog: AgentConnectionModel[];
+ connectionCommands: [];
+ skillCommands: Map<string, string>;
+ uiServices: { settingsManager: { getEnableSkillCommands(): boolean } };
+ bindLocalSessionExtensions: boolean;
+ fdPath: undefined;
+ currentModelSupportsFastMode(): boolean;
+ getAvailableThinkingLevels(): [];
+ getCurrentCwd(): string;
+ createBaseAutocompleteProvider(): AutocompleteProvider;
+}
+
+describe("ENG-4575 model authentication", () => {
+ const harnesses: Harness[] = [];
+
+ beforeEach(() => {
+ initTheme("dark");
+ setKeybindings(new KeybindingsManager());
+ });
+
+ afterEach(() => {
+ for (const harness of harnesses.splice(0)) {
+ harness.cleanup();
+ }
+ });
+
+ test("shows unauthenticated public models after authenticated providers", async () => {
+ const harness = await createHarness({
+ models: [{ id: "base", name: "Base", reasoning: true }],
+ });
+ harnesses.push(harness);
+
+ const base = harness.getModel("base")!;
+ const unauthenticated = { ...base, provider: "a-unauthenticated", id: "requires-auth" };
+ const authenticated = { ...base, provider: "z-authenticated", id: "available" };
+ let selectedProvider: string | undefined;
+ const selector = new ModelSelectorComponent(
+ { requestRender: () => {} } as unknown as TUI,
+ unauthenticated,
+ harness.session.modelRegistry,
+ [],
+ (model) => {
+ selectedProvider = model.provider;
+ },
+ () => {},
+ undefined,
+ {
+ availableModels: [unauthenticated, authenticated],
+ configuredProviders: new Set([authenticated.provider]),
+ recentModels: [`${unauthenticated.provider}/${unauthenticated.id}`],
+ },
+ );
+
+ const lines = stripAnsi(selector.render(120).join("\n")).split("\n");
+ const authenticatedRow = lines.findIndex((line) => line.includes("available"));
+ const unauthenticatedRow = lines.findIndex((line) => line.includes("requires-auth"));
+ expect(authenticatedRow).toBeGreaterThanOrEqual(0);
+ expect(authenticatedRow).toBeLessThan(unauthenticatedRow);
+ expect(lines[unauthenticatedRow]).toContain("current · sign in");
+
+ selector.handleInput("\r");
+ expect(selectedProvider).toBe(unauthenticated.provider);
+ });
+
+ test("keeps locally authenticated providers configured when the connection catalog omits them", async () => {
+ const harness = await createHarness({
+ models: [{ id: "base", name: "Base", reasoning: true }],
+ });
+ harnesses.push(harness);
+ const model = harness.getModel("base")!;
+ const selector = new ModelSelectorComponent(
+ { requestRender: () => {} } as unknown as TUI,
+ undefined,
+ harness.session.modelRegistry,
+ [],
+ () => {},
+ () => {},
+ undefined,
+ {
+ availableModels: [model],
+ configuredProviders: new Set(),
+ },
+ );
+
+ const row = stripAnsi(selector.render(120).join("\n"))
+ .split("\n")
+ .find((line) => line.includes("base"));
+ expect(row).toBeDefined();
+ expect(row).not.toContain("sign in");
+ });
+
+ test("refetches configured providers after authentication changes", async () => {
+ const harness = await createHarness({ models: [{ id: "base", name: "Base", reasoning: true }] });
+ harnesses.push(harness);
+ const model = { ...harness.getModel("base")!, provider: "openai" } as AgentConnectionModel;
+ const getModelCatalog = vi.fn(async () => ({ models: [model], configuredProviders: [] }));
+ const fakeThis = Object.create(InteractiveMode.prototype) as ConnectionAuthRefreshHarness;
+ fakeThis.agentConnection = { getModelCatalog };
+ fakeThis.connectionModels = [model];
+ fakeThis.connectionModelCatalog = [model];
+ fakeThis.connectionConfiguredProviders = new Set([model.provider]);
+ fakeThis.connectionModelsFetchedAt = Date.now();
+ fakeThis.connectionModelsRefreshVersion = 0;
+ fakeThis.connectionModelsRefreshInFlight = undefined;
+
+ await fakeThis.refreshConnectionModelsAfterAuthChange();
+
+ expect(getModelCatalog).toHaveBeenCalledOnce();
+ expect(fakeThis.connectionConfiguredProviders).toEqual(new Set());
+ expect(fakeThis.connectionModels).toEqual([]);
+ expect(fakeThis.connectionModelCatalog).toEqual([model]);
+ });
+
+ test("returns the full public catalog to catalog-facing selectors", async () => {
+ const harness = await createHarness({ models: [{ id: "base", name: "Base", reasoning: true }] });
+ harnesses.push(harness);
+ const model = { ...harness.getModel("base")!, provider: "openai" } as AgentConnectionModel;
+ const fakeThis = Object.create(InteractiveMode.prototype) as ConnectionAuthRefreshHarness;
+ fakeThis.agentConnection = {
+ getModelCatalog: vi.fn(async () => ({ models: [model], configuredProviders: [] })),
+ };
+ fakeThis.connectionModels = [];
+ fakeThis.connectionModelCatalog = [];
+ fakeThis.connectionConfiguredProviders = new Set();
+ fakeThis.connectionModelsFetchedAt = 0;
+ fakeThis.connectionModelsRefreshVersion = 0;
+ fakeThis.connectionModelsRefreshInFlight = undefined;
+
+ await expect(fakeThis.getConnectionModelCatalog()).resolves.toEqual([model]);
+ expect(fakeThis.connectionModels).toEqual([]);
+ });
+
+ test("uses the full public catalog for scoped-session model autocomplete", async () => {
+ const harness = await createHarness({ models: [{ id: "base", name: "Base", reasoning: true }] });
+ harnesses.push(harness);
+ const base = harness.getModel("base")!;
+ const scoped = { ...base, provider: "custom", id: "scoped-only" } as AgentConnectionModel;
+ const publicModel = { ...base, provider: "openai", id: "gpt-5.4" } as AgentConnectionModel;
+ const fakeThis = Object.create(InteractiveMode.prototype) as InteractiveAutocompleteHarness;
+ fakeThis.connectionState = { scopedModels: [{ model: scoped }] };
+ fakeThis.connectionModelCatalog = [publicModel];
+ fakeThis.connectionCommands = [];
+ fakeThis.skillCommands = new Map();
+ fakeThis.uiServices = { settingsManager: { getEnableSkillCommands: () => false } };
+ fakeThis.bindLocalSessionExtensions = false;
+ fakeThis.fdPath = undefined;
+ fakeThis.currentModelSupportsFastMode = () => false;
+ fakeThis.getAvailableThinkingLevels = () => [];
+ fakeThis.getCurrentCwd = () => "/tmp";
+
+ const provider = fakeThis.createBaseAutocompleteProvider();
+ const scopedInput = "/model scoped-only";
+ const scopedSuggestions = await provider.getSuggestions([scopedInput], 0, scopedInput.length, {
+ signal: new AbortController().signal,
+ });
+ const publicInput = "/model gpt-5.4";
+ const publicSuggestions = await provider.getSuggestions([publicInput], 0, publicInput.length, {
+ signal: new AbortController().signal,
+ });
+
+ expect(scopedSuggestions?.items).toContainEqual({
+ value: "custom/scoped-only",
+ label: "scoped-only",
+ description: "custom",
+ });
+ expect(publicSuggestions?.items).toContainEqual({
+ value: "openai/gpt-5.4",
+ label: "gpt-5.4",
+ description: "openai",
+ });
+ });
+
+ test("uses the full public catalog for agents view model autocomplete", async () => {
+ const harness = await createHarness({ models: [{ id: "base", name: "Base", reasoning: true }] });
+ harnesses.push(harness);
+ const publicModel = { ...harness.getModel("base")!, provider: "openai", id: "gpt-5.4" };
+ const refreshModelCatalog = vi.fn(async () => ({ models: [publicModel], configuredProviders: [] }));
+
+ const completions = await getAgentsViewModelArgumentCompletions("gpt-5.4", { refreshModelCatalog });
+
+ expect(refreshModelCatalog).toHaveBeenCalledOnce();
+ expect(completions).toContainEqual({
+ value: "openai/gpt-5.4",
+ label: "gpt-5.4",
+ description: "openai",
+ });
+ });
+
+ test("syncs agents view model rows after provider authentication", async () => {
+ const harness = await createHarness({ models: [{ id: "base", name: "Base", reasoning: true }] });
+ harnesses.push(harness);
+ const model = { ...harness.getModel("base")!, provider: "openai" };
+ const menu = {
+ refreshAuthentication: vi.fn(),
+ updateModels: vi.fn(),
+ };
+
+ syncAgentsViewModelMenuAfterAuth(menu, undefined, {
+ models: [model],
+ configuredProviders: [model.provider],
+ });
+
+ expect(menu.refreshAuthentication).toHaveBeenCalledOnce();
+ expect(menu.updateModels).toHaveBeenCalledWith(undefined, [model], new Set([model.provider]));
+ });
+
+ test("filters shared model argument completions by provider and model id", () => {
+ expect(
+ getModelArgumentCompletions("openai gpt-5.4", [
+ { provider: "prime-inference", id: "openai/gpt-5.5" },
+ { provider: "openai", id: "gpt-5.4" },
+ ]),
+ ).toContainEqual({ value: "openai/gpt-5.4", label: "gpt-5.4", description: "openai" });
+ });
+});