A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
feat(ui): make configuration pickers compact and inline (#2182)
kta38ad5d538a0
diff --git a/packages/coding-agent/.changes/ui-inline-pickers.md b/packages/coding-agent/.changes/ui-inline-pickers.mdnew file mode 100644index 0000000000..5674488046--- /dev/null+++ b/packages/coding-agent/.changes/ui-inline-pickers.md@@ -0,0 +1,20 @@+- Changed model, provider, and MCP pickers to compact inline lists with responsive search and keyboard navigation.+- Added selected-model catalog prices for input, cached input, and output per million tokens.+- Split the configuration menu into separate single-purpose pickers and dropped the tab bar and tab navigation; each command opens only its own picker.+- Changed model rows to right-align the provider label with a require sign in hint beside it, and to list signed-in providers first with Prime Inference pinned on top when signed in.+- Added per-model effort squares to the models picker; left/right adjusts the highlighted model's reasoning level and Enter applies the model and effort together.+- Fixed the models picker search to keep signed-in providers above unsigned matches, with Prime Inference pinned on top of the signed-in group.+- Softened the selected row highlight in menu pickers: the selection background blends toward the editor surface and the selected label renders bold instead of accent-colored.+- Refined the effort squares: clusters align across rows with arrow hints on the highlighted row, spaced squares in a stronger purple, and the selected level labeled beside them.+- Folded the USD per million tokens unit into the model detail header line and left clear whitespace at the end of the detail block.+- Rounded model picker token prices to at most three decimals, showing sub-$0.001 rates as <0.001 instead of a misleading $0.+- Centered the models picker effort cluster near the row midpoint with square glyphs; fills render light gray and reserve the saturated purple for the highlighted row.+- Removed the explanatory title and subtitle lines from the model, provider, and MCP pickers; the search row now leads each picker.+- Moved the model detail pricing unit onto the price row as "dollars per 1 million tokens" and left the provider/model line bare.+- Fixed the effort cluster so changing the level never shifts the row; the level label renders in a fixed-width cell sized to the longest supported level name.+- Refined the model picker effort marks to the larger medium-square glyphs, softened the effort purple, and shortened the pricing unit to "$ / 1M tokens".+- Dropped the provider/model-id line from the inline model detail block; the prices now follow the list row directly.+- Settled the effort marks on the filled ■ and empty □ squares, the largest square pair the terminal fonts cover.+- Tightened the effort square spacing; the squares now render edge to edge and the cluster stays centered.+- Fixed model selection retaining focus until the model and explicitly selected effort finish applying, preserving the default effort when it is untouched.+- Fixed arrow keys editing model searches and removed the unused configuration-tab binding.diff --git a/packages/coding-agent/docs/keybindings.md b/packages/coding-agent/docs/keybindings.mdindex 94248e10da..72928d323f 100644--- a/packages/coding-agent/docs/keybindings.md+++ b/packages/coding-agent/docs/keybindings.md@@ -117,13 +117,9 @@ Modifier combinations: `ctrl+shift+x`, `alt+ctrl+x`, `ctrl+shift+alt+x`, `ctrl+1| `app.model.toggleScope` | `alt+s` | Toggle between all and scoped models || `app.thinking.toggle` | `ctrl+t` | Collapse or expand thinking blocks |-### Configuration Menu+### Configuration Pickers-Use `tab` to cycle forward and `shift+tab` to cycle backward through Providers, Models, and MCP Connections. Use `escape` to close the menu. Left and right move the cursor in the active search field.--| Keybinding id | Default | Description |-|--------|---------|-------------|-| `app.configuration.previousTab` | `shift+tab` | Select the previous configuration tab |+Models, Providers, and MCP Connections open as separate pickers. Use `escape` to close a picker. Left and right edit a nonempty search field; with an empty model search, they adjust the highlighted model's effort.### Display and Message Queuediff --git a/packages/coding-agent/src/core/keybindings.ts b/packages/coding-agent/src/core/keybindings.tsindex 1efbaaca00..57ffba268b 100644--- a/packages/coding-agent/src/core/keybindings.ts+++ b/packages/coding-agent/src/core/keybindings.ts@@ -19,7 +19,6 @@ export interface AppKeybindings {"app.suspend": true;"app.model.select": true;"app.model.toggleScope": true;- "app.configuration.previousTab": true;"app.tools.expand": true;"app.messages.expand": true;"app.edits.expand": true;@@ -87,7 +86,6 @@ export const KEYBINDINGS = {},"app.model.select": { defaultKeys: "ctrl+l", description: "Open model selector" },"app.model.toggleScope": { defaultKeys: "alt+s", description: "Toggle model selector scope" },- "app.configuration.previousTab": { defaultKeys: "shift+tab", description: "Select previous configuration tab" },"app.tools.expand": { defaultKeys: "ctrl+o", description: "Toggle tool output", defaultKeyScope: "editor" },"app.messages.expand": {defaultKeys: "ctrl+p",diff --git a/packages/coding-agent/src/modes/interactive/components/configuration-menu.ts b/packages/coding-agent/src/modes/interactive/components/configuration-menu.tsindex ce269c7634..f61a424ed6 100644--- a/packages/coding-agent/src/modes/interactive/components/configuration-menu.ts+++ b/packages/coding-agent/src/modes/interactive/components/configuration-menu.ts@@ -1,18 +1,9 @@-import type { Api, Model } from "@earendil-works/pi-ai";-import {- type Component,- Container,- type Focusable,- getKeybindings,- type TUI,- visibleWidth,- wrapTextWithAnsi,-} from "@earendil-works/pi-tui";+import type { Api, Model, ModelThinkingLevel } from "@earendil-works/pi-ai";+import { Container, type Focusable, type TUI, truncateToWidth } from "@earendil-works/pi-tui";import type { AuthStorage } from "../../../core/auth-storage.js";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 { ModelSelectorComponent } from "./model-selector.js";import { type AuthSelectorProvider, OAuthSelectorComponent } from "./oauth-selector.js";@@ -37,71 +28,15 @@ export interface ConfigurationMenuOptions {configuredProviders: ReadonlySet<string>;recentModels?: ReadonlyArray<string>;initialModelSearch?: string;+ thinkingLevel?: ModelThinkingLevel;getRows?: () => number;requestRender: () => void;onSelectProvider: (provider: AuthSelectorProvider) => void;onSelectMcpConnection: (provider: AuthSelectorProvider) => void;- onSelectModel: (model: Model<Api>) => void;+ onSelectModel: (model: Model<Api>, thinkingLevel?: ModelThinkingLevel) => void;onCancel: () => void;}-const TAB_LABELS: Record<ConfigurationMenuTab, string> = {- providers: "Providers",- models: "Models",- "mcp-connections": "MCP Connections",-};--class ConfigurationMenuTabBar implements Component {- constructor(private readonly getActiveTab: () => ConfigurationMenuTab) {}-- render(width: number): string[] {- return this.getLines(width);- }-- getRowCount(width: number): number {- return this.getLines(width).length;- }-- private getLines(width: number): string[] {- const safeWidth = Math.max(1, width);- const activeTab = this.getActiveTab();- const labels = CONFIGURATION_MENU_TABS.map((tab) => {- const label = `[${tab === activeTab ? "▶" : " "} ${TAB_LABELS[tab]}]`;- return tab === activeTab ? theme.bold(theme.fg("accent", label)) : theme.fg("text", label);- });- const lines = this.wrapItems(- [theme.bold(theme.fg("muted", "Tabs:")), ...labels],- theme.fg("muted", " "),- safeWidth,- );- const tabKey = keyText("tui.input.tab", { primaryOnly: true });- const shiftTabKey = keyText("app.configuration.previousTab", { primaryOnly: true });- const closeKey = keyText("tui.select.cancel", { primaryOnly: true });- const hint = `${theme.fg("dim", `${tabKey}/${shiftTabKey}`)}${theme.fg("muted", " switch tabs · ")}${theme.fg("dim", closeKey)}${theme.fg("muted", " close")}`;- return [...lines, ...wrapTextWithAnsi(hint, safeWidth)];- }-- private wrapItems(items: string[], separator: string, width: number): string[] {- const lines: string[] = [];- let line = "";- for (const item of items) {- const candidate = line ? `${line}${separator}${item}` : item;- if (line && visibleWidth(candidate) > width) {- lines.push(...wrapTextWithAnsi(line, width));- line = item;- } else {- line = candidate;- }- }- if (line) {- lines.push(...wrapTextWithAnsi(line, width));- }- return lines;- }-- invalidate(): void {}-}-export class ConfigurationMenuComponent extends Container implements Focusable {private readonly bodies: {providers: OAuthSelectorComponent;@@ -110,13 +45,12 @@ export class ConfigurationMenuComponent extends Container implements Focusable {};private activeTab: ConfigurationMenuTab;private _focused = false;- private renderWidth = 78;+ private busy = false;constructor(private readonly options: ConfigurationMenuOptions) {super();this.activeTab = options.initialTab;- const tabBar = new ConfigurationMenuTabBar(() => this.activeTab);- const getHeaderRows = () => tabBar.getRowCount(getMenuPanelInnerWidth(this.renderWidth)) + 1;+ const getRows = () => Math.max(1, (options.getRows?.() ?? 24) - 1);const providerOptions = options.providerOptions.filter((provider) => (provider.category ?? "provider") === "provider",);@@ -130,11 +64,10 @@ export class ConfigurationMenuComponent extends Container implements Focusable {options.onCancel,(providerId) => options.modelRegistry.getProviderAuthStatus(providerId),{- getRows: options.getRows,- header: tabBar,- getHeaderRows,- title: "Providers",- subtitle: "Connect with a subscription or API key.",+ getRows,+ inline: true,+ title: "",+ subtitle: "",searchPlaceholder: "Search providers",},);@@ -149,10 +82,10 @@ export class ConfigurationMenuComponent extends Container implements Focusable {{availableModels: options.availableModels,configuredProviders: options.configuredProviders,- header: tabBar,- getHeaderRows,- getRows: options.getRows,+ getRows,+ inline: true,recentModels: options.recentModels,+ thinkingLevel: options.thinkingLevel,},);const mcpConnections = new OAuthSelectorComponent(@@ -163,12 +96,12 @@ export class ConfigurationMenuComponent extends Container implements Focusable {options.onCancel,(providerId) => options.modelRegistry.getProviderAuthStatus(providerId),{- getRows: options.getRows,- header: tabBar,- getHeaderRows,- title: "MCP Connections",- subtitle: "Connect MCP integrations and service credentials.",+ getRows,+ inline: true,+ title: "",+ subtitle: "",searchPlaceholder: "Search MCP connections",+ emptyMessage: "No MCP connections. Use /mcp add to configure a server.",},);@@ -190,8 +123,17 @@ export class ConfigurationMenuComponent extends Container implements Focusable {}override render(width: number): string[] {- this.renderWidth = width;- return super.render(width);+ const selectKey = keyText("tui.select.confirm", { primaryOnly: true });+ const closeKey = keyText("tui.select.cancel", { primaryOnly: true });+ const navigate = `${keyText("tui.select.up", { primaryOnly: true })}/${keyText("tui.select.down", { primaryOnly: true })}`;+ const effort = `${keyText("tui.editor.cursorLeft", { primaryOnly: true })}/${keyText("tui.editor.cursorRight", { primaryOnly: true })}`;+ const hint =+ width >= 70+ ? this.activeTab === "models"+ ? `${navigate} model · ${effort} effort · ${selectKey} select · ${closeKey} close`+ : `${navigate} navigate · ${selectKey} select · ${closeKey} close`+ : `${selectKey} select · ${closeKey} close`;+ return [...super.render(width), truncateToWidth(theme.fg("dim", ` ${hint}`), width, "", true)];}getActiveTab(): ConfigurationMenuTab {@@ -226,33 +168,16 @@ export class ConfigurationMenuComponent extends Container implements Focusable {this.bodies.models.updateState(currentModel, models, configuredProviders);}+ setBusy(busy: boolean): void {+ this.busy = busy;+ }+handleInput(keyData: string): void {- const kb = getKeybindings();- if (kb.matches(keyData, "tui.input.tab")) {- this.switchTab(1);- return;- }- if (kb.matches(keyData, "app.configuration.previousTab")) {- this.switchTab(-1);- return;- }- if (- this.activeTab === "models" &&- (kb.matches(keyData, "tui.editor.cursorLeft") || kb.matches(keyData, "tui.editor.cursorRight"))- ) {- this.activeBody.getSearchInput().handleInput(keyData);- return;- }+ if (this.busy) return;this.activeBody.handleInput(keyData);}private get activeBody(): OAuthSelectorComponent | ModelSelectorComponent {return this.bodies[this.activeTab];}-- private switchTab(direction: 1 | -1): void {- const currentIndex = CONFIGURATION_MENU_TABS.indexOf(this.activeTab);- const nextIndex = (currentIndex + direction + CONFIGURATION_MENU_TABS.length) % CONFIGURATION_MENU_TABS.length;- this.setActiveTab(CONFIGURATION_MENU_TABS[nextIndex] ?? "providers");- }}diff --git a/packages/coding-agent/src/modes/interactive/components/menu-panel.ts b/packages/coding-agent/src/modes/interactive/components/menu-panel.tsindex f9e6899d2c..41e72209cd 100644--- a/packages/coding-agent/src/modes/interactive/components/menu-panel.ts+++ b/packages/coding-agent/src/modes/interactive/components/menu-panel.ts@@ -12,6 +12,7 @@ import { theme } from "../theme/theme.js";interface MenuPanelOptions {title: string;subtitle?: string;+ inline?: boolean;}export interface MenuViewportProvider {@@ -20,6 +21,7 @@ export interface MenuViewportProvider {interface MenuListOptions {compact?: boolean | (() => boolean);+ inline?: boolean;}interface MenuListLayoutOptions extends MenuViewportProvider {@@ -46,9 +48,9 @@ const ROW_PADDING_X = 2;const ROW_PADDING_Y = 1;const ANSI_RESET = "\x1b[0m";-export function getMenuPanelInnerWidth(width: number): number {- const safeWidth = Math.max(PANEL_PADDING_X * 2 + 1, width);- return Math.max(1, safeWidth - PANEL_PADDING_X * 2);+export function getMenuPanelInnerWidth(width: number, inline = false): number {+ const padding = inline ? 1 : PANEL_PADDING_X;+ return Math.max(1, width - padding * 2);}interface FullWidthMenuComponent {@@ -189,6 +191,26 @@ export function getMenuListLayout(options: MenuListLayoutOptions): MenuListLayou: { compact: false, visibleItems: comfortableLayout.visibleItems };}+function reduceInlineTrailingSegments(segments: ReadonlyArray<string>, budget: number): string[] {+ let current = segments.filter((segment) => segment.length > 0);+ while (current.length > 1 && visibleWidth(current.join(" · ")) > budget) {+ current = current.slice(1);+ }+ return current;+}++/**+ * Rendered width of a trailing cluster at the given row width, mirroring how+ * MenuRow degrades and truncates it. Pickers use this to budget row content.+ */+export function getInlineTrailingWidth(segments: ReadonlyArray<string>, width: number): number {+ const innerWidth = Math.max(1, width - 2);+ const budget = Math.max(1, innerWidth - 5);+ const reduced = reduceInlineTrailingSegments(segments, budget);+ if (reduced.length === 0) return 0;+ return Math.min(visibleWidth(reduced.join(" · ")), budget);+}+function paddedBackgroundLine(text: string,width: number,@@ -235,6 +257,18 @@ export class MenuPanel extends Container {}override render(width: number): string[] {+ if (this.options.inline) {+ const lines: string[] = [];+ if (this.title) lines.push(theme.fg("muted", ` ${this.title}`));+ for (const child of this.children) {+ lines.push(+ ...child+ .render(fillsMenuPanel(child) ? width : getMenuPanelInnerWidth(width, true))+ .map((line) => (fillsMenuPanel(child) ? line : ` ${line}`)),+ );+ }+ return lines.map((line) => truncateToWidth(line, width, "", true));+ }const safeWidth = Math.max(PANEL_PADDING_X * 2 + 1, width);const innerWidth = getMenuPanelInnerWidth(width);const lines: string[] = [];@@ -274,7 +308,10 @@ export class MenuSearchInput implements Component, Focusable, FullWidthMenuComporeadonly fillsMenuPanel = true;private readonly input = new Input();- constructor(private readonly placeholder: string) {}+ constructor(+ private readonly placeholder: string,+ private readonly inline = false,+ ) {}get focused(): boolean {return this.input.focused;@@ -309,6 +346,16 @@ export class MenuSearchInput implements Component, Focusable, FullWidthMenuCompo}render(width: number): string[] {+ if (this.inline) {+ const border = theme.fg("borderMuted", "─".repeat(Math.max(0, width)));+ let content = this.input.render(Math.max(1, width - 2))[0] ?? "";+ if (this.getValue() === "") {+ content = this.focused+ ? `${content.trimEnd()}${theme.fg("dim", this.placeholder)}`+ : `> ${theme.fg("dim", this.placeholder)}`;+ }+ return [border, truncateToWidth(` ${content}`, width, "", true), border];+ }const safeWidth = Math.max(FIELD_PADDING_X * 2 + 1, width);const innerWidth = Math.max(1, safeWidth - FIELD_PADDING_X * 2);const content =@@ -327,7 +374,13 @@ interface MenuRowOptions {primary: string;secondary?: string;meta?: string;+ /**+ * Inline-only segments rendered right-aligned; the last segment sits flush against the+ * row's right edge. Earlier segments drop first when the row is too narrow.+ */+ trailing?: ReadonlyArray<string>;selected: boolean;+ inline?: boolean;}export class MenuRow implements Component, FullWidthMenuComponent {@@ -353,6 +406,32 @@ export class MenuRow implements Component, FullWidthMenuComponent {}renderContent(width: number): string[] {+ if (this.options.inline) {+ // Trailing rows run flush to the right edge; legacy rows keep a one-column margin.+ const hasTrailing = this.options.trailing !== undefined;+ const innerWidth = Math.max(1, hasTrailing ? width - 2 : width - 3);+ const trailing = this.getInlineTrailing(width, innerWidth);+ const trailingWidth = visibleWidth(trailing);+ const gap = trailingWidth > 0 ? 2 : 0;+ const primaryWidth = Math.max(1, innerWidth - trailingWidth - gap);+ const primaryText = theme.fg("text", this.options.primary);+ const primary = truncateToWidth(+ this.selected ? theme.bold(primaryText) : primaryText,+ primaryWidth,+ "…",+ true,+ );+ const filler = " ".repeat(Math.max(0, innerWidth - visibleWidth(primary) - trailingWidth));+ const content = `${this.selected ? "›" : " "} ${primary}${filler}${trailing}`;+ return [+ paddedBackgroundLine(+ content,+ width,+ 0,+ this.selected ? theme.getSoftSelectionBackgroundColor() : undefined,+ ),+ ];+ }const safeWidth = Math.max(ROW_PADDING_X * 2 + 1, width);const meta = this.options.meta ? theme.fg("muted", this.options.meta) : "";const secondary = this.options.secondary ? theme.fg("muted", this.options.secondary) : "";@@ -383,9 +462,21 @@ export class MenuRow implements Component, FullWidthMenuComponent {}private rowLine(text: string, width: number, selected: boolean): string {- const background = selected ? theme.getSelectionBackgroundColor() : theme.getEditorBackgroundColor();+ const background = selected ? theme.getSoftSelectionBackgroundColor() : theme.getEditorBackgroundColor();return paddedBackgroundLine(text, width, ROW_PADDING_X, background);}++ private getInlineTrailing(width: number, innerWidth: number): string {+ if (this.options.trailing === undefined) {+ const secondary = width >= 60 ? this.options.secondary : undefined;+ const details = [secondary, this.options.meta].filter(Boolean).join(" · ");+ return details ? truncateToWidth(theme.fg("muted", details), Math.floor(innerWidth / 2), "…") : "";+ }+ const budget = Math.max(1, innerWidth - 5);+ const segments = reduceInlineTrailingSegments(this.options.trailing, budget);+ if (segments.length === 0) return "";+ return truncateToWidth(theme.fg("muted", segments.join(" · ")), budget, "…");+ }}export class MenuList extends Container implements FullWidthMenuComponent {@@ -396,6 +487,11 @@ export class MenuList extends Container implements FullWidthMenuComponent {}override render(width: number): string[] {+ if (this.options.inline) {+ return this.children.flatMap((child) =>+ child instanceof MenuRow ? child.renderContent(width) : child.render(width),+ );+ }const lines: string[] = [];const compact = this.isCompact();for (let index = 0; index < this.children.length; index++) {diff --git a/packages/coding-agent/src/modes/interactive/components/model-selector.ts b/packages/coding-agent/src/modes/interactive/components/model-selector.tsindex 58a08eb319..3b014929d2 100644--- a/packages/coding-agent/src/modes/interactive/components/model-selector.ts+++ b/packages/coding-agent/src/modes/interactive/components/model-selector.ts@@ -1,4 +1,10 @@-import { type Model, modelsAreEqual } from "@earendil-works/pi-ai";+import {+ clampThinkingLevel,+ getSupportedThinkingLevels,+ type Model,+ type ModelThinkingLevel,+ modelsAreEqual,+} from "@earendil-works/pi-ai";import {type Component,Container,@@ -8,11 +14,15 @@ import {Spacer,Text,type TUI,+ truncateToWidth,+ visibleWidth,} from "@earendil-works/pi-tui";import type { ModelRegistry } from "../../../core/model-registry.js";+import { PRIME_INFERENCE_PROVIDER_ID } from "../../../core/prime-inference-auth.js";import { theme } from "../theme/theme.js";import { keyHint } from "./keybinding-hints.js";import {+ getInlineTrailingWidth,getMenuListLayout,MenuList,MenuPanel,@@ -112,18 +122,34 @@ export interface ModelSelectorOptions {subtitle?: string;getRows?: () => number;recentModels?: ReadonlyArray<string>;+ inline?: boolean;+ thinkingLevel?: ModelThinkingLevel;}type ModelScope = "all" | "scoped";const PREFERRED_VISIBLE_MODELS = 10;const MODEL_LIST_RESERVED_ROWS = {- base: 7,+ base: 4,detail: 2,};const MODEL_SCROLL_INDICATOR_ROWS = 1;const MODEL_HELP_MIN_ROWS = 12;const MODEL_DETAIL_MIN_ROWS = 14;+const EFFORT_NAME_COLUMN_MAX = 30;+const EFFORT_NAME_COLUMN_MIN = 12;+const PRICE_UNIT_TEXT = "$ / 1M tokens";+/** Wide detail columns must still fit the longest label, "Cached input". */+const PRICE_COLUMN_MIN_WIDTH = 13;++interface EffortLayout {+ nameColumn: number;+ squareSlots: number;+ gap: number;+ labelWidth: number;+ showLabel: boolean;+ showCluster: boolean;+}/*** Component that renders a model selector with search@@ -149,12 +175,18 @@ export class ModelSelectorComponent extends Container implements Focusable {private searchQuery = "";private currentModel?: Model<any>;private modelRegistry: ModelRegistry;- private onSelectCallback: (model: Model<any>) => void;+ private onSelectCallback: (model: Model<any>, thinkingLevel?: ModelThinkingLevel) => void;private onCancelCallback: () => void;private availableModels?: ReadonlyArray<Model<any>>;private configuredProviders?: ReadonlySet<string>;private recentRank: Map<string, number>;private errorMessage?: string;+ private configuredAuth = new Map<string, boolean>();+ private readonly effortLevels = new Map<string, ModelThinkingLevel>();+ private readonly editedEffortModels = new Set<string>();+ private initialThinkingLevel?: ModelThinkingLevel;+ private readonly inline: boolean;+ private renderWidth = 80;private tui: TUI;private scopedModels: ReadonlyArray<ScopedModelItem>;private scope: ModelScope = "all";@@ -178,7 +210,7 @@ export class ModelSelectorComponent extends Container implements Focusable {currentModel: Model<any> | undefined,modelRegistry: ModelRegistry,scopedModels: ReadonlyArray<ScopedModelItem>,- onSelect: (model: Model<any>) => void,+ onSelect: (model: Model<any>, thinkingLevel?: ModelThinkingLevel) => void,onCancel: () => void,initialSearchInput?: string,options: ModelSelectorOptions = {},@@ -186,6 +218,7 @@ export class ModelSelectorComponent extends Container implements Focusable {super();this.tui = tui;+ this.inline = options.inline === true;this.currentModel = currentModel;this.modelRegistry = modelRegistry;this.scopedModels = scopedModels;@@ -194,18 +227,20 @@ export class ModelSelectorComponent extends Container implements Focusable {this.onCancelCallback = onCancel;this.availableModels = options.availableModels;this.configuredProviders = options.configuredProviders;+ this.initialThinkingLevel = options.thinkingLevel;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 ?? "All models across supported providers.",+ title: "",+ subtitle: options.subtitle,+ inline: this.inline,});this.addChild(this.panel);if (options.header) {this.panel.addChild(options.header);- this.panel.addChild(new Spacer(1));+ if (!this.inline) this.panel.addChild(new Spacer(1));}// Add hint about model filtering@@ -220,7 +255,7 @@ export class ModelSelectorComponent extends Container implements Focusable {this.panel.addChild(this.headerHelpContainer);// Create search input- this.searchInput = new MenuSearchInput("Search models");+ this.searchInput = new MenuSearchInput("Search models", this.inline);if (initialSearchInput) {this.searchInput.setValue(initialSearchInput);}@@ -229,10 +264,10 @@ export class ModelSelectorComponent extends Container implements Focusable {};this.panel.addChild(this.searchInput);- this.panel.addChild(new Spacer(1));+ if (!this.inline) this.panel.addChild(new Spacer(1));// Create list container- this.listContainer = new MenuList({ compact: () => this.listLayout.compact });+ this.listContainer = new MenuList({ compact: () => this.listLayout.compact, inline: this.inline });this.panel.addChild(this.listContainer);this.updateResponsiveLayout();@@ -277,6 +312,7 @@ export class ModelSelectorComponent extends Container implements Focusable {private loadModels(): void {let models: ModelItem[];this.errorMessage = undefined;+ this.configuredAuth.clear();if (this.availableModels === undefined) {this.modelRegistry.refresh();@@ -343,7 +379,144 @@ export class ModelSelectorComponent extends Container implements Focusable {}private isProviderConfigured(item: ModelItem): boolean {- return this.configuredProviders?.has(item.provider) || this.modelRegistry.hasConfiguredAuth(item.model);+ const key = this.getModelKey(item);+ let configured = this.configuredAuth.get(key);+ if (configured === undefined) {+ configured = this.configuredProviders?.has(item.provider) || this.modelRegistry.hasConfiguredAuth(item.model);+ this.configuredAuth.set(key, configured);+ }+ return configured;+ }++ private isPinnedProvider(item: ModelItem): boolean {+ return item.provider === PRIME_INFERENCE_PROVIDER_ID && this.isProviderConfigured(item);+ }++ private getSelectableLevels(item: ModelItem): ModelThinkingLevel[] {+ const levels = getSupportedThinkingLevels(item.model);+ if (levels.length === 1 && levels[0] === "off") return [];+ return levels;+ }++ private getEffort(item: ModelItem): ModelThinkingLevel | undefined {+ const levels = this.getSelectableLevels(item);+ if (levels.length === 0) return undefined;+ const key = this.getModelKey(item);+ const stored = this.effortLevels.get(key);+ if (stored !== undefined && levels.includes(stored)) return stored;+ const initial = this.initialThinkingLevel ?? "off";+ const level = levels.includes(initial) ? initial : clampThinkingLevel(item.model, initial);+ const resolved = levels.includes(level) ? level : levels[0]!;+ this.effortLevels.set(key, resolved);+ return resolved;+ }++ private adjustEffort(item: ModelItem, direction: number): boolean {+ const levels = this.getSelectableLevels(item);+ if (levels.length === 0) return false;+ const current = this.getEffort(item) ?? levels[0]!;+ const index = levels.indexOf(current);+ const next = levels[(index + direction + levels.length) % levels.length]!;+ this.effortLevels.set(this.getModelKey(item), next);+ this.editedEffortModels.add(this.getModelKey(item));+ return true;+ }++ private getTrailingSegments(item: ModelItem, isCurrent: boolean, isConfigured: boolean): string[] {+ const segments: string[] = [];+ if (isCurrent) segments.push("current");+ if (!isConfigured) segments.push("require sign in");+ segments.push(item.provider);+ return segments;+ }++ private getEffortLayout(startIndex: number, endIndex: number): EffortLayout {+ const empty: EffortLayout = {+ nameColumn: 0,+ squareSlots: 0,+ gap: 0,+ labelWidth: 0,+ showLabel: false,+ showCluster: false,+ };+ const reasoningItems: ModelItem[] = [];+ for (let i = startIndex; i < endIndex; i++) {+ const item = this.filteredModels[i];+ if (item && this.getSelectableLevels(item).length > 0) reasoningItems.push(item);+ }+ if (reasoningItems.length === 0) return empty;++ const width = this.renderWidth;+ let maxTrailingWidth = 0;+ for (let i = startIndex; i < endIndex; i++) {+ const item = this.filteredModels[i];+ if (!item) continue;+ const segments = this.getTrailingSegments(+ item,+ modelsAreEqual(this.currentModel, item.model),+ this.isProviderConfigured(item),+ );+ maxTrailingWidth = Math.max(maxTrailingWidth, getInlineTrailingWidth(segments, width));+ }+ const available = Math.max(1, width - 2 - maxTrailingWidth - 2);++ const maxNameColumn = Math.min(+ Math.max(...reasoningItems.map((item) => visibleWidth(item.model.name))),+ EFFORT_NAME_COLUMN_MAX,+ );+ const squareSlots = Math.max(+ ...reasoningItems.map((item) => this.getSelectableLevels(item).filter((level) => level !== "off").length),+ );+ const clusterWidth = squareSlots;+ // Fixed label cell sized to the longest supported level name, so changing+ // the selected level never changes the cluster span or its centered gap.+ const labelWidth = Math.max(+ ...reasoningItems.flatMap((item) => this.getSelectableLevels(item).map((level) => visibleWidth(level))),+ );+ // Arrow slots and the spaces around the squares and label. The ladder+ // keeps one of those columns as the gap after the name cell, shrinks the+ // name column next, and only then drops the label or the whole cluster,+ // so rows stay aligned at every width.+ const arrowsAndGaps = 6;+ // Sit the cluster near the row's horizontal center, clamped between the+ // name column and the trailing zone.+ const place = (nameColumn: number, showLabel: boolean): EffortLayout => {+ const span = clusterWidth + (showLabel ? labelWidth + 5 : 4);+ const desired = Math.floor(width / 2 - span / 2) - 2 - nameColumn;+ const gap = Math.max(1, Math.min(desired, available - nameColumn - span));+ return { nameColumn, squareSlots, gap, labelWidth, showLabel, showCluster: true };+ };+ if (maxNameColumn + clusterWidth + labelWidth + arrowsAndGaps <= available) {+ return place(maxNameColumn, true);+ }+ const labelNameColumn = available - clusterWidth - labelWidth - arrowsAndGaps;+ if (labelNameColumn >= EFFORT_NAME_COLUMN_MIN) {+ return place(Math.min(maxNameColumn, labelNameColumn), true);+ }+ if (maxNameColumn + clusterWidth + arrowsAndGaps <= available) {+ return place(maxNameColumn, false);+ }+ const clusterNameColumn = available - clusterWidth - arrowsAndGaps;+ if (clusterNameColumn >= EFFORT_NAME_COLUMN_MIN) {+ return place(Math.min(maxNameColumn, clusterNameColumn), false);+ }+ return empty;+ }++ private renderEffortSquares(+ levels: ModelThinkingLevel[],+ effort: ModelThinkingLevel | undefined,+ squareSlots: number,+ selected: boolean,+ ): string {+ const onLevels = levels.filter((level) => level !== "off");+ if (onLevels.length === 0) return "";+ const filledColor = selected ? theme.getEffortSquareColor() : (glyph: string) => theme.fg("muted", glyph);+ const filled = effort === undefined || effort === "off" ? 0 : onLevels.indexOf(effort) + 1;+ const squares = onLevels.map((_, index) => (index < filled ? filledColor("■") : theme.fg("dim", "□")));+ // The glyphs carry their own cell padding, so render them edge to edge.+ const marks = squares.join("");+ return marks + " ".repeat(Math.max(0, squareSlots - visibleWidth(marks)));}private sortModels(models: ModelItem[]): ModelItem[] {@@ -351,6 +524,8 @@ export class ModelSelectorComponent extends Container implements Focusable {sorted.sort((a, b) => {const configuredDiff = Number(this.isProviderConfigured(b)) - Number(this.isProviderConfigured(a));if (configuredDiff !== 0) return configuredDiff;+ const pinnedDiff = Number(this.isPinnedProvider(b)) - Number(this.isPinnedProvider(a));+ if (pinnedDiff !== 0) return pinnedDiff;const aIsCurrent = modelsAreEqual(this.currentModel, a.model);const bIsCurrent = modelsAreEqual(this.currentModel, b.model);if (aIsCurrent !== bIsCurrent) return aIsCurrent ? -1 : 1;@@ -398,9 +573,10 @@ export class ModelSelectorComponent extends Container implements Focusable {});matches.sort((a, b) =>+ Number(this.isProviderConfigured(b.item)) - Number(this.isProviderConfigured(a.item)) ||+ Number(this.isPinnedProvider(b.item)) - Number(this.isPinnedProvider(a.item)) ||a.quality - b.quality ||a.score - b.score ||- Number(this.isProviderConfigured(b.item)) - Number(this.isProviderConfigured(a.item)) ||Number(modelsAreEqual(this.currentModel, b.item.model)) -Number(modelsAreEqual(this.currentModel, a.item.model)) ||this.recentRankOf(a.item) - this.recentRankOf(b.item) ||@@ -415,6 +591,7 @@ export class ModelSelectorComponent extends Container implements Focusable {}override render(width: number): string[] {+ this.renderWidth = width;const previousLayoutKey = this.responsiveLayoutKey;this.updateResponsiveLayout();if (this.responsiveLayoutKey !== previousLayoutKey) {@@ -436,6 +613,10 @@ export class ModelSelectorComponent extends Container implements Focusable {const endIndex = Math.min(startIndex + maxVisible, this.filteredModels.length);// Show visible slice of filtered models+ const effortLayout = this.inline+ ? this.getEffortLayout(startIndex, endIndex)+ : { nameColumn: 0, squareSlots: 0, gap: 0, labelWidth: 0, showLabel: false, showCluster: false };+for (let i = startIndex; i < endIndex; i++) {const item = this.filteredModels[i];if (!item) continue;@@ -447,14 +628,33 @@ export class ModelSelectorComponent extends Container implements Focusable {? isCurrent? theme.fg("success", "current"): undefined- : theme.fg("warning", isCurrent ? "current · sign in" : "sign in");+ : theme.fg("warning", isCurrent ? "current · require sign in" : "require sign in");+ const inlineSegments = this.getTrailingSegments(item, isCurrent, isConfigured);+ let primary = this.inline ? item.model.name : item.id;+ if (this.inline && effortLayout.showCluster) {+ const levels = this.getSelectableLevels(item);+ const effort = this.getEffort(item);+ if (levels.length > 0 && effort !== undefined) {+ const nameCell = truncateToWidth(item.model.name, effortLayout.nameColumn, "…", true);+ const gap = " ".repeat(effortLayout.gap);+ const leftArrow = isSelected ? theme.fg("dim", "←") : " ";+ const rightArrow = isSelected ? theme.fg("dim", "→") : " ";+ const squares = this.renderEffortSquares(levels, effort, effortLayout.squareSlots, isSelected);+ const label = effortLayout.showLabel ? theme.fg("muted", effort.padEnd(effortLayout.labelWidth)) : "";+ primary = label+ ? `${nameCell}${gap}${leftArrow} ${squares} ${rightArrow} ${label}`+ : `${nameCell}${gap}${leftArrow} ${squares} ${rightArrow}`;+ }+ }this.listContainer.addChild(new MenuRow({- primary: item.id,- secondary: item.provider,- meta,+ primary,+ secondary: this.inline ? undefined : item.provider,+ meta: this.inline ? undefined : meta,+ trailing: this.inline ? inlineSegments : undefined,selected: isSelected,+ inline: this.inline,}),);}@@ -476,7 +676,12 @@ export class ModelSelectorComponent extends Container implements Focusable {this.listContainer.addChild(new Text(theme.fg("muted", "No matching models"), 0, 0));} else {const selected = this.filteredModels[this.selectedIndex];- if (selected && this.shouldShowSelectedDetails()) {+ if (selected && this.inline && this.getInlineDetailRows() > 0) {+ this.listContainer.addChild({+ render: (width) => this.renderInlineModelDetails(selected, width),+ invalidate: () => {},+ });+ } else if (selected && !this.inline && this.shouldShowSelectedDetails()) {this.listContainer.addChild(new Spacer(1));this.listContainer.addChild(new Text(theme.fg("muted", selected.model.name), 0, 0));}@@ -495,6 +700,19 @@ export class ModelSelectorComponent extends Container implements Focusable {}return;}+ // Keep arrows available for editing a filter; an empty filter controls effort.+ if (+ this.searchInput.getValue() === "" &&+ (kb.matches(keyData, "tui.editor.cursorLeft") || kb.matches(keyData, "tui.editor.cursorRight"))+ ) {+ const direction = kb.matches(keyData, "tui.editor.cursorLeft") ? -1 : 1;+ const selected = this.filteredModels[this.selectedIndex];+ if (selected && this.adjustEffort(selected, direction)) {+ this.updateList();+ this.tui.requestRender();+ return;+ }+ }// Up arrow - wrap to bottom when at topif (kb.matches(keyData, "tui.select.up")) {const selectableCount = this.getSelectableCount();@@ -508,6 +726,13 @@ export class ModelSelectorComponent extends Container implements Focusable {if (selectableCount === 0) return;this.selectedIndex = this.selectedIndex === selectableCount - 1 ? 0 : this.selectedIndex + 1;this.updateList();+ } else if (kb.matches(keyData, "tui.select.pageUp") || kb.matches(keyData, "tui.select.pageDown")) {+ const direction = kb.matches(keyData, "tui.select.pageUp") ? -1 : 1;+ this.selectedIndex = Math.max(+ 0,+ Math.min(this.filteredModels.length - 1, this.selectedIndex + direction * this.listLayout.visibleItems),+ );+ this.updateList();}// Enterelse if (kb.matches(keyData, "tui.select.confirm")) {@@ -519,19 +744,19 @@ export class ModelSelectorComponent extends Container implements Focusable {}// Pass everything else to search inputelse {+ const previousQuery = this.searchInput.getValue();this.searchInput.handleInput(keyData);- this.filterModels(this.searchInput.getValue());+ if (previousQuery !== this.searchInput.getValue()) this.filterModels(this.searchInput.getValue());}}- private handleSelect(model: Model<any>): void {- this.onSelectCallback(model);- }-private handleConfirm(): void {const selectedModel = this.filteredModels[this.selectedIndex];if (selectedModel) {- this.handleSelect(selectedModel.model);+ const effort = this.editedEffortModels.has(this.getModelKey(selectedModel))+ ? this.getEffort(selectedModel)+ : undefined;+ this.onSelectCallback(selectedModel.model, effort);return;}}@@ -545,6 +770,30 @@ export class ModelSelectorComponent extends Container implements Focusable {}private updateResponsiveLayout(): void {+ if (this.inline) {+ this.headerHelpContainer.clear();+ const scopeRows = this.scopeText ? 1 : 0;+ if (this.scopeText) {+ this.headerHelpContainer.addChild({+ render: (width) => [+ truncateToWidth(theme.fg("muted", `${this.getScopeText()} · ${this.getScopeHintText()}`), width),+ ],+ invalidate: () => {},+ });+ }+ const detailRows = this.getInlineDetailRows();+ this.listLayout = getMenuListLayout({+ getRows: this.viewport.getRows,+ preferredVisibleItems: 8,+ totalItems: this.filteredModels.length,+ reservedRows: this.getHeaderRows() + 3 + scopeRows + detailRows,+ comfortableItemRows: 1,+ comfortableListPaddingRows: 0,+ scrollIndicatorRows: 1,+ });+ this.responsiveLayoutKey = `inline:${this.getHeaderRows()}:${detailRows}:${this.listLayout.visibleItems}:${this.renderWidth}`;+ return;+ }const showHeaderHelp = this.shouldShowHeaderHelp();let headerHelpRows = 0;this.headerHelpContainer.clear();@@ -590,6 +839,51 @@ export class ModelSelectorComponent extends Container implements Focusable {return this.hasRows(MODEL_HELP_MIN_ROWS);}+ private getInlineDetailRows(): number {+ const detailRows = this.renderWidth >= 58 ? 4 : 5;+ return this.hasRows(this.getHeaderRows() + 5 + (this.scopeText ? 1 : 0) + detailRows) ? detailRows : 0;+ }++ private renderInlineModelDetails(item: ModelItem, width: number): string[] {+ const price = (value: number | undefined) => {+ if (value === undefined || !Number.isFinite(value) || value < 0) return "—";+ if (value === 0) return "$0";+ const rounded = Math.round(value * 1000) / 1000;+ return rounded === 0 ? "<0.001" : `$${rounded}`;+ };+ const entries = [+ ["Input", price(item.model.cost?.input)],+ ["Cached input", price(item.model.cost?.cacheRead)],+ ["Output", price(item.model.cost?.output)],+ ];+ const unit = theme.fg("muted", PRICE_UNIT_TEXT);+ const lines = [""];+ if (width >= 58) {+ // Shrink the columns so the unit can trail the Output column.+ const columnWidth = Math.max(+ PRICE_COLUMN_MIN_WIDTH,+ Math.floor((width - 2 - (visibleWidth(PRICE_UNIT_TEXT) + 1)) / 3),+ );+ const row = (index: number) =>+ entries+ .map((entry) => {+ const text = entry[index] ?? "";+ return text + " ".repeat(Math.max(0, columnWidth - visibleWidth(text)));+ })+ .join("");+ lines.push(`${theme.fg("muted", row(0))} ${unit}`, row(1));+ } else {+ lines.push(+ ...entries.map(([label, value], index) => {+ const suffix = index === entries.length - 1 ? ` ${unit}` : "";+ return `${theme.fg("muted", `${label}:`)} ${value}${suffix}`;+ }),+ );+ }+ lines.push("");+ return lines.map((line) => truncateToWidth(` ${line}`, width, "…", true));+ }+private shouldShowSelectedDetails(): boolean {return this.hasRows(MODEL_DETAIL_MIN_ROWS);}diff --git a/packages/coding-agent/src/modes/interactive/components/oauth-selector.ts b/packages/coding-agent/src/modes/interactive/components/oauth-selector.tsindex 7ea9ec50aa..5564cc7c6a 100644--- a/packages/coding-agent/src/modes/interactive/components/oauth-selector.ts+++ b/packages/coding-agent/src/modes/interactive/components/oauth-selector.ts@@ -6,6 +6,7 @@ import {getKeybindings,Spacer,TruncatedText,+ truncateToWidth,} from "@earendil-works/pi-tui";import type { AuthStatus, AuthStorage } from "../../../core/auth-storage.js";import { PRIME_INFERENCE_PROVIDER_ID } from "../../../core/prime-inference-auth.js";@@ -36,6 +37,8 @@ export interface OAuthSelectorOptions extends MenuViewportProvider {title?: string;subtitle?: string;searchPlaceholder?: string;+ inline?: boolean;+ emptyMessage?: string;}export function compareAuthSelectorProviders(a: AuthSelectorProvider, b: AuthSelectorProvider): number {@@ -86,6 +89,8 @@ export class OAuthSelectorComponent extends Container implements Focusable {});private readonly viewport: MenuViewportProvider;private readonly getHeaderRows: () => number;+ private readonly inline: boolean;+ private readonly emptyMessage?: string;constructor(mode: "login" | "logout",@@ -99,6 +104,8 @@ export class OAuthSelectorComponent extends Container implements Focusable {super();this.mode = mode;+ this.inline = options.inline === true;+ this.emptyMessage = options.emptyMessage;this.authStorage = authStorage;this.getAuthStatus = getAuthStatus ?? ((providerId) => this.authStorage.getAuthStatus(providerId));this.viewport = options;@@ -116,15 +123,19 @@ export class OAuthSelectorComponent extends Container implements Focusable {: (this.categories[0] ?? "provider");const panel = new MenuPanel({- title: options.title ?? (mode === "login" ? "Providers" : "Saved Credentials"),+ title:+ this.inline && options.header+ ? ""+ : (options.title ?? (mode === "login" ? "Providers" : "Saved Credentials")),subtitle:options.subtitle ??(mode === "login" ? "Connect with a subscription or API key." : "Choose a credential to remove."),+ inline: this.inline,});this.addChild(panel);if (options.header) {panel.addChild(options.header);- panel.addChild(new Spacer(1));+ if (!this.inline) panel.addChild(new Spacer(1));}if (this.categories.length > 1) {@@ -133,7 +144,7 @@ export class OAuthSelectorComponent extends Container implements Focusable {panel.addChild(new Spacer(1));}- this.searchInput = new MenuSearchInput(options.searchPlaceholder ?? "Search providers");+ this.searchInput = new MenuSearchInput(options.searchPlaceholder ?? "Search providers", this.inline);this.searchInput.onSubmit = () => {const selectedProvider = this.filteredProviders[this.selectedIndex];if (selectedProvider) {@@ -141,9 +152,9 @@ export class OAuthSelectorComponent extends Container implements Focusable {}};panel.addChild(this.searchInput);- panel.addChild(new Spacer(1));+ if (!this.inline) panel.addChild(new Spacer(1));- this.listContainer = new MenuList({ compact: () => this.listLayout.compact });+ this.listContainer = new MenuList({ compact: () => this.listLayout.compact, inline: this.inline });panel.addChild(this.listContainer);this.filterProviders("");@@ -291,13 +302,18 @@ export class OAuthSelectorComponent extends Container implements Focusable {if (!provider) continue;const isSelected = i === this.selectedIndex;+ const authLabel = provider.authType === "oauth" ? "subscription" : "api key";this.listContainer.addChild(new MenuRow({- primary: provider.name,- secondary: provider.authType === "oauth" ? "subscription" : "api key",- meta: this.formatStatusIndicator(provider),+ primary: this.inline ? `${provider.name} · ${authLabel}` : provider.name,+ secondary: this.inline ? undefined : authLabel,+ meta:+ this.inline && !this.isProviderConfigured(provider) && !this.isProviderStale(provider)+ ? undefined+ : this.formatStatusIndicator(provider),selected: isSelected,+ inline: this.inline,}),);}@@ -310,11 +326,16 @@ export class OAuthSelectorComponent extends Container implements Focusable {if (this.filteredProviders.length === 0) {const message =this.allProviders.length === 0- ? this.mode === "login"- ? "No providers available"- : "No providers logged in. Use /login first."+ ? (this.emptyMessage ??+ (this.mode === "login" ? "No providers available" : "No providers logged in. Use /login first.")): "No matching providers";this.listContainer.addChild(new TruncatedText(theme.fg("muted", message), 1, 0));+ } else if (this.inline && this.getInlineDetailRows() > 0) {+ const selected = this.filteredProviders[this.selectedIndex];+ this.listContainer.addChild({+ render: (width) => ["", truncateToWidth(` ${this.formatStatusIndicator(selected)}`, width)],+ invalidate: () => {},+ });}}@@ -370,6 +391,13 @@ export class OAuthSelectorComponent extends Container implements Focusable {if (this.filteredProviders.length === 0) return;this.selectedIndex = Math.min(this.filteredProviders.length - 1, this.selectedIndex + 1);this.updateList();+ } else if (kb.matches(keyData, "tui.select.pageUp") || kb.matches(keyData, "tui.select.pageDown")) {+ const direction = kb.matches(keyData, "tui.select.pageUp") ? -1 : 1;+ this.selectedIndex = Math.max(+ 0,+ Math.min(this.filteredProviders.length - 1, this.selectedIndex + direction * this.listLayout.visibleItems),+ );+ this.updateList();}// Only steal left/right for tabs when the search field is empty, so cursor// editing still works while filtering.@@ -393,13 +421,23 @@ export class OAuthSelectorComponent extends Container implements Focusable {} else if (kb.matches(keyData, "tui.select.cancel")) {this.onCancelCallback();} else {+ const previousQuery = this.searchInput.getValue();this.searchInput.handleInput(keyData);- this.filterProviders(this.searchInput.getValue());+ if (previousQuery !== this.searchInput.getValue()) this.filterProviders(this.searchInput.getValue());}}private get reservedRows(): number {- return PROVIDER_LIST_RESERVED_ROWS + this.getHeaderRows() + (this.tabBar ? TAB_BAR_RESERVED_ROWS : 0);+ return (+ (this.inline ? 3 + this.getInlineDetailRows() : PROVIDER_LIST_RESERVED_ROWS) ++ this.getHeaderRows() ++ (this.tabBar ? TAB_BAR_RESERVED_ROWS : 0)+ );+ }++ private getInlineDetailRows(): number {+ const minimumRows = this.getHeaderRows() + (this.tabBar ? TAB_BAR_RESERVED_ROWS : 0) + 7;+ return (this.viewport.getRows?.() ?? Number.POSITIVE_INFINITY) >= minimumRows ? 2 : 0;}private updateLayout(): void {@@ -408,8 +446,9 @@ export class OAuthSelectorComponent extends Container implements Focusable {preferredVisibleItems: PREFERRED_VISIBLE_PROVIDERS,totalItems: this.filteredProviders.length,reservedRows: this.reservedRows,- comfortableItemRows: 3,- compactItemRows: 2,+ comfortableItemRows: this.inline ? 1 : 3,+ compactItemRows: this.inline ? undefined : 2,+ comfortableListPaddingRows: this.inline ? 0 : undefined,scrollIndicatorRows: PROVIDER_SCROLL_INDICATOR_ROWS,});}diff --git a/packages/coding-agent/src/modes/interactive/interactive-mode.ts b/packages/coding-agent/src/modes/interactive/interactive-mode.tsindex d37636663a..7cd3c24313 100644--- a/packages/coding-agent/src/modes/interactive/interactive-mode.ts+++ b/packages/coding-agent/src/modes/interactive/interactive-mode.ts@@ -82,6 +82,7 @@ import {DEFAULT_HEARTBEAT_DELIVERY_MODE,parseHeartbeatCommand,} from "../../core/cron-jobs.js";+import { DEFAULT_THINKING_LEVEL } from "../../core/defaults.js";import type {AutocompleteProviderFactory,ContextUsage,@@ -1064,6 +1065,8 @@ export class InteractiveMode {private connectionModelsFetchedAt = 0;private connectionModelsRefreshVersion = 0;private connectionModelsRefreshInFlight: { version: number; promise: Promise<AgentConnectionModel[]> } | undefined;+ private closeConfigurationMenu: (() => void) | undefined;+ private configurationModelSelection: Promise<void> | undefined;private connectionState: AgentConnectionState | undefined;private connectionResourceSnapshot: AgentConnectionResourceSnapshot | undefined;private heartbeatCatalog: AgentConnectionHeartbeat[] = [];@@ -1833,11 +1836,8 @@ export class InteractiveMode {}private async showOnboardingModelSelection(splash: OnboardingSplashHandle): Promise<void> {- try {- await this.showConfigurationMenu("models");- } finally {- splash.dismiss();- }+ splash.dismiss();+ await this.showConfigurationMenu("models");}private async runOnboardingFlow(showPrimeCliSplash = this.shouldRunPrimeCliOnboardingSplash()): Promise<void> {@@ -3634,6 +3634,7 @@ export class InteractiveMode {}private resetExtensionUI(): void {+ this.closeConfigurationMenu?.();this.cancelActiveConnectionExtensionUiRequests();this.closeHeartbeatManager();if (this.extensionSelector) {@@ -8126,17 +8127,19 @@ export class InteractiveMode {});}- private applyThinkingLevel(level: ThinkingLevel): void {- void this.agentConnection+ private applyThinkingLevel(level: ThinkingLevel): Promise<boolean> {+ return this.agentConnection.setThinkingLevel(level).then(() => {this.patchConnectionState({ thinkingLevel: level });this.footer.invalidate();this.updateEditorBorderColor();this.showStatus(`Thinking level: ${level}`);+ return true;}).catch((error) => {this.showError(error instanceof Error ? error.message : String(error));+ return false;});}@@ -8145,40 +8148,31 @@ export class InteractiveMode {}private showConfigurationMenu(initialTab: ConfigurationMenuTab, initialModelSearch?: string): Promise<void> {+ if (this.configurationModelSelection) return this.configurationModelSelection;+ this.closeConfigurationMenu?.();const modelCatalog = this.getCachedModelCandidates();const authFlows = this.createAuthFlows();const providerOptions = authFlows.getLoginProviderOptions();return new Promise((resolve) => {- let handle: OverlayHandle | undefined;let settled = false;- let hidden = false;- let removed = false;+ let busy = false;let menu: ConfigurationMenuComponent;- const hide = () => {- if (removed) return;- removed = true;- hidden = true;- handle?.hide();- this.ui.requestRender();- };- const conceal = () => {- if (hidden || removed) return;- hidden = true;- handle?.setHidden(true);+ const restoreEditor = () => {+ if (!this.editorContainer.children.includes(menu)) return;+ this.editorContainer.clear();+ this.editorContainer.addChild(this.editor);+ this.ui.setFocus(this.editor);this.ui.requestRender();};- const show = () => {- if (!hidden || removed || settled) return;- hidden = false;- handle?.setHidden(false);- handle?.focus();- this.ui.requestRender();+ const focus = () => {+ if (!settled && this.editorContainer.children.includes(menu)) this.ui.setFocus(menu);};const finish = () => {if (settled) return;settled = true;- hide();+ restoreEditor();+ if (this.closeConfigurationMenu === finish) this.closeConfigurationMenu = undefined;resolve();};const refreshModels = (force: boolean) => {@@ -8193,12 +8187,13 @@ export class InteractiveMode {});};const authenticate = (provider: AuthSelectorProvider, tab: "providers" | "mcp-connections") => {- if (settled) return;+ if (settled || busy) return;+ busy = true;void authFlows.loginProvider(provider).then(async (authResult) => {if (settled) return;- handle?.focus();+ focus();menu.refreshAuthentication();if (authResult.status !== "success") return;@@ -8214,6 +8209,7 @@ export class InteractiveMode {}await this.prepareForModelSelectionAfterLogin(authResult);+ if (settled) return;menu.updateModels(this.getCurrentModel(),this.getCachedModelCandidates(),@@ -8223,8 +8219,11 @@ export class InteractiveMode {refreshModels(true);}).catch((error) => {- handle?.focus();- this.showError(error instanceof Error ? error.message : String(error));+ focus();+ if (!settled) this.showError(error instanceof Error ? error.message : String(error));+ })+ .finally(() => {+ busy = false;});};@@ -8240,37 +8239,61 @@ export class InteractiveMode {configuredProviders: this.connectionConfiguredProviders,recentModels: this.settingsManager.getRecentModels(),initialModelSearch,- getRows: () => this.ui.terminal.rows,+ thinkingLevel: this.getCurrentModel()?.reasoning+ ? this.connectionState?.thinkingLevel+ : (this.settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL),+ getRows: () => Math.max(1, Math.min(20, this.ui.terminal.rows - 3)),requestRender: () => this.ui.requestRender(),onSelectProvider: (provider) => authenticate(provider, "providers"),onSelectMcpConnection: (provider) => authenticate(provider, "mcp-connections"),- onSelectModel: (model) => {+ onSelectModel: (model, thinkingLevel) => {+ if (settled || busy) return;+ busy = true;void (async () => {let completed = false;+ let selectionInFlight: Promise<void> | undefined;try {const ready = await this.ensureModelProviderConfigured(model, authFlows, providerOptions);- handle?.focus();+ if (settled) return;+ focus();menu.refreshAuthentication();menu.updateModels(this.getCurrentModel(),this.getCachedModelCandidates(),this.connectionConfiguredProviders,);- if (!ready || settled) return;- conceal();- await this.completeModelSelection(model);- completed = true;+ if (!ready) return;+ menu.setBusy(true);+ const selection = (async () => {+ await this.completeModelSelection(model);+ if (settled) return false;+ return thinkingLevel === undefined || (await this.applyThinkingLevel(thinkingLevel));+ })();+ selectionInFlight = selection.then(+ () => {},+ () => {},+ );+ this.configurationModelSelection = selectionInFlight;+ completed = await selection;} catch (error) {- show();- this.showError(error instanceof Error ? error.message : String(error));+ focus();+ if (!settled) this.showError(error instanceof Error ? error.message : String(error));} finally {+ busy = false;+ if (this.configurationModelSelection === selectionInFlight)+ this.configurationModelSelection = undefined;+ menu.setBusy(false);if (completed) finish();}})();},onCancel: finish,});- handle = this.showFullPaneOverlay(menu, 96);+ this.closeConfigurationMenu = finish;+ this.editorContainer.clear();+ this.editorContainer.addChild(menu);+ focus();+ this.ui.requestRender();refreshModels(initialModelSearch !== undefined);});}@@ -10139,6 +10162,7 @@ ${interrupt ? `| \`${interrupt}\` | Interrupt current operation |\n` : ""}${shor}stop(options: { preserveAltScreen?: boolean } = {}): void {+ this.closeConfigurationMenu?.();this.unregisterSignalHandlers();this.clearCtrlCExitHint({ render: false });this.clearEscapeRepeat();diff --git a/packages/coding-agent/src/modes/interactive/theme/theme.ts b/packages/coding-agent/src/modes/interactive/theme/theme.tsindex 10a9c6f257..a8dcca9859 100644--- a/packages/coding-agent/src/modes/interactive/theme/theme.ts+++ b/packages/coding-agent/src/modes/interactive/theme/theme.ts@@ -197,6 +197,9 @@ function refinementColors(light: boolean): Record<RefinementColor, string> {}const ADAPTIVE_LIGHT_BG_ACCENT: Rgb = { r: 0, g: 95, b: 135 };+const SOFT_SELECTION_ALPHA = 0.5;+const EFFORT_SQUARE_DARK_COLOR = "#a78bfa";+const EFFORT_SQUARE_LIGHT_COLOR = "#8b5cf6";const SURFACE_MIN_LUMINANCE_DELTA = 12;const SURFACE_CONTRAST_ALPHA = 0.08;// Selection rows must stand out clearly, much more than passive surfaces.@@ -513,6 +516,36 @@ export class Theme {return (str: string) => `${ansi}${str}\x1b[49m`;}+ /**+ * Row-selection highlight for menu rows: the selection color blended halfway+ * toward the editor surface, a softer band than the full selection block.+ */+ getSoftSelectionBackgroundColor(): (str: string) => string {+ const terminalBg = getDefaultTerminalColors()?.background;+ const selectedBgValue = this.bgColorValues.get("selectedBg");+ // Basic ANSI colors (0-15) are terminal-defined; their rendered color is+ // unknown, so no reliable blend base exists.+ if (!terminalBg || (typeof selectedBgValue === "number" && selectedBgValue < 16)) {+ return (str: string) => this.bg("selectedBg", str);+ }+ const surfaceRgb = colorValueToRgb(this.bgColorValues.get("userMessageBg"));+ const selectionRgb = colorValueToRgb(selectedBgValue);+ if (!surfaceRgb || !selectionRgb) {+ return (str: string) => this.bg("selectedBg", str);+ }+ const surfaceAnsi = bestAnsiColor(surfaceRgb, this.mode);+ // Half contrast by default; strengthen the blend only when quantization+ // would collapse the highlight into the editor surface.+ for (const alpha of [SOFT_SELECTION_ALPHA, 0.75, 1]) {+ const adjusted = bestAnsiColor(blendColor(selectionRgb, surfaceRgb, alpha), this.mode);+ if (adjusted !== "" && adjusted !== surfaceAnsi) {+ const ansi = bgAnsi(adjusted, this.mode);+ return (str: string) => `${ansi}${str}[49m`;+ }+ }+ return this.getSelectionBackgroundColor();+ }+private surfaceBackgroundColor(color: ThemeBg): (str: string) => string {const terminalBg = getDefaultTerminalColors()?.background;const surfaceRgb = colorValueToRgb(this.bgColorValues.get(color));@@ -534,6 +567,17 @@ export class Theme {return (str: string) => `${ansi}${str}\x1b[49m`;}+ /** Filled effort squares: a pastel purple that reads softer than the theme accent. */+ getEffortSquareColor(): (str: string) => string {+ const hex = getTerminalBackgroundKind() === "light" ? EFFORT_SQUARE_LIGHT_COLOR : EFFORT_SQUARE_DARK_COLOR;+ const color = bestAnsiColor(hexToRgb(hex), this.mode);+ if (color === "") {+ return (str: string) => this.fg("accent", str);+ }+ const ansi = fgAnsi(color, this.mode);+ return (str: string) => `${ansi}${str}[39m`;+ }+getAdaptiveAccentColor(): (str: string) => string {const ansi =getTerminalBackgroundKind() === "light"diff --git a/packages/coding-agent/test/agent-traces.test.ts b/packages/coding-agent/test/agent-traces.test.tsindex 6d9cfbacb3..8d73ad9655 100644--- a/packages/coding-agent/test/agent-traces.test.ts+++ b/packages/coding-agent/test/agent-traces.test.ts@@ -710,6 +710,15 @@ describe("agent trace upload", () => {// The rate-limited cycle re-arms itself; the retry succeeds without any caller waiting.await advanceTimersUntil(() => calls.length === 1);expect(attempts).toBe(2);+ // Receiving the request is not completion: wait for the durable cursor before teardown.+ const sessionFile = sessionManager.getSessionFile()!;+ const signature = await stat(sessionFile);+ await advanceTimersUntil(() => readOutboxEntry(tempDir, sessionFile)?.size === signature.size);+ expect(readOutboxEntry(tempDir, sessionFile)).toEqual({+ sessionFile,+ size: signature.size,+ mtimeMs: signature.mtimeMs,+ });});it.each([503])("honors Retry-After when retrying HTTP %i", async (status) => {diff --git a/packages/coding-agent/test/configuration-menu.test.ts b/packages/coding-agent/test/configuration-menu.test.tsindex e63c750d31..79267e0ad8 100644--- a/packages/coding-agent/test/configuration-menu.test.ts+++ b/packages/coding-agent/test/configuration-menu.test.ts@@ -24,14 +24,24 @@ describe("ConfigurationMenuComponent", () => {getRows?: () => number;requestRender?: () => void;onSelectProvider?: () => void;+ onSelectModel?: (model: { id: string }) => void;+ modelCount?: number;+ cost?: { input: number; output: number; cacheRead: number; cacheWrite: number };+ noCost?: boolean;onCancel?: () => void;} = {},): Promise<ConfigurationMenuComponent> {- const harness = await createHarness({- models: [{ id: "faux-1", name: "Faux One", reasoning: true }],- });+ const specifications = Array.from({ length: options.modelCount ?? 1 }, (_, index) => ({+ id: `faux-${index + 1}`,+ name: index === 0 ? "Faux One" : `Faux ${index + 1}`,+ reasoning: true,+ }));+ const harness = await createHarness({ models: specifications });harnesses.push(harness);const model = harness.getModel("faux-1")!;+ const models = specifications.map(({ id }) => harness.getModel(id)!);+ if (options.cost) model.cost = options.cost;+ if (options.noCost) model.cost = undefined as unknown as typeof model.cost;return new ConfigurationMenuComponent({initialTab: options.initialTab ?? "providers",tui: createFakeTui(),@@ -48,13 +58,13 @@ describe("ConfigurationMenuComponent", () => {modelRegistry: harness.session.modelRegistry,currentModel: model,scopedModels: [],- availableModels: [model],+ availableModels: models,configuredProviders: new Set([model.provider]),getRows: options.getRows,requestRender: options.requestRender ?? (() => {}),onSelectProvider: options.onSelectProvider ?? (() => {}),onSelectMcpConnection: () => {},- onSelectModel: () => {},+ onSelectModel: options.onSelectModel ?? (() => {}),onCancel: options.onCancel ?? (() => {}),});}@@ -74,64 +84,79 @@ describe("ConfigurationMenuComponent", () => {}});- it("uses one clearly delineated three-tab menu and keeps each tab body mounted", async () => {+ it("renders one single-purpose picker per command without tab chrome", async () => {const requestRender = vi.fn();const selectProvider = vi.fn();const menu = await createMenu({ requestRender, onSelectProvider: selectProvider });let output = stripAnsi(menu.render(120).join("\n"));- expect(output).toContain("Tabs:");- expect(output).toContain("[▶ Providers]");- expect(output).toContain("[ Models]");- expect(output).toContain("[ MCP Connections]");+ expect(output).toContain("Search providers");expect(output).toContain("Anthropic");+ expect(output).not.toContain("Faux One");expect(output).not.toContain("Serper (web search)");- menu.handleInput("a");- menu.setActiveTab("models");- output = stripAnsi(menu.render(120).join("\n"));- expect(output).toContain("[ Providers]");- expect(output).toContain("[▶ Models]");+ const models = await createMenu({ initialTab: "models" });+ output = stripAnsi(models.render(120).join("\n"));+ expect(output).toContain("Search models");expect(output).toContain("Faux One");+ expect(output).not.toContain("Anthropic");+ expect(output).not.toContain("Serper (web search)");++ const mcp = await createMenu({ initialTab: "mcp-connections" });+ output = stripAnsi(mcp.render(120).join("\n"));+ expect(output).toContain("Search MCP connections");+ expect(output).toContain("Serper (web search)");+ expect(output).not.toContain("Anthropic");+ menu.handleInput("a");+ menu.setActiveTab("models");menu.setActiveTab("providers");- output = stripAnsi(menu.render(120).join("\n"));expect(menu.getSearchValue("providers")).toBe("a");- expect(output).toContain("Anthropic");expect(requestRender).toHaveBeenCalled();-menu.handleInput("\r");expect(selectProvider).toHaveBeenCalledWith(expect.objectContaining({ id: "anthropic" }));+ });- menu.setActiveTab("mcp-connections");- output = stripAnsi(menu.render(120).join("\n"));- expect(output).toContain("[▶ MCP Connections]");- expect(output).toContain("Serper (web search)");- expect(output).not.toContain("Anthropic");+ it("renders no explanatory header above the picker search rows", async () => {+ const menu = await createMenu({ initialTab: "models" });+ const lines = stripAnsi(menu.render(120).join("\n")).split("\n");+ const output = lines.join("\n");+ expect(output).not.toContain("Models");+ expect(output).not.toContain("All models across supported providers.");+ expect(output).not.toContain("Providers");+ expect(output).not.toContain("Connect with a subscription or API key.");+ expect(output).not.toContain("MCP Connections");+ expect(output).not.toContain("Connect MCP integrations and service credentials.");+ // The search row is the first content; nothing renders above it.+ expect(lines[0]).toContain("─");+ expect(output).toContain("Search models");++ const providers = await createMenu({ initialTab: "providers" });+ const providerLines = stripAnsi(providers.render(120).join("\n")).split("\n");+ expect(providerLines[0]).toContain("─");+ expect(providerLines.join("\n")).toContain("Search providers");++ const mcp = await createMenu({ initialTab: "mcp-connections" });+ const mcpLines = stripAnsi(mcp.render(120).join("\n")).split("\n");+ expect(mcpLines[0]).toContain("─");+ expect(mcpLines.join("\n")).toContain("Search MCP connections");});- it("switches tabs with Tab and Shift+Tab while preserving focus and search state", async () => {- const menu = await createMenu();+ it("keeps Tab and Shift+Tab inside the picker without switching bodies", async () => {+ const menu = await createMenu({ initialTab: "models" });menu.focused = true;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/Shift+Tab switch tabs"));- expect(shortcutsLine).toBeGreaterThan(tabsLine);- expect(lines[shortcutsLine]).toContain("Esc close");+ expect(lines.some((line) => line.includes("↑/↓ model"))).toBe(true);+ expect(lines.some((line) => line.includes("←/→ effort"))).toBe(true);+ expect(lines.some((line) => line.includes("Esc close"))).toBe(true);+ expect(lines.some((line) => line.includes("tabs"))).toBe(false);- menu.handleInput("\t");- expect(menu.getActiveTab()).toBe("models");- expect(menu.focused).toBe(true);menu.handleInput("f");expect(menu.getSearchValue("models")).toBe("f");menu.handleInput("\t");- expect(menu.getActiveTab()).toBe("mcp-connections");+ expect(menu.getActiveTab()).toBe("models");+ expect(menu.focused).toBe(true);expect(menu.getSearchValue("models")).toBe("f");- menu.handleInput("\t");- expect(menu.getActiveTab()).toBe("providers");-- menu.handleInput("\x1b[Z");- expect(menu.getActiveTab()).toBe("mcp-connections");menu.handleInput("\x1b[Z");expect(menu.getActiveTab()).toBe("models");expect(menu.getSearchValue("models")).toBe("f");@@ -167,12 +192,12 @@ describe("ConfigurationMenuComponent", () => {menu.updateModels(postLoginModel);let output = stripAnsi(menu.render(120).join("\n"));- expect(output).toContain("faux-1");+ expect(output).toContain("Faux One");expect(menu.getSearchValue("models")).toBe("faux");menu.updateModels(postLoginModel, [firstModel, postLoginModel]);output = stripAnsi(menu.render(120).join("\n"));- const postLoginRow = output.split("\n").find((line) => line.includes("faux-2"));+ const postLoginRow = output.split("\n").find((line) => line.includes("Faux Two"));expect(postLoginRow).toContain("current");});@@ -196,16 +221,10 @@ describe("ConfigurationMenuComponent", () => {expect(onCancel).toHaveBeenCalledOnce();});- it("wraps complete tab labels at narrow widths without overflowing the viewport", async () => {- const menu = await createMenu({ getRows: () => 24 });-+ it("keeps each picker inside narrow viewports without overflowing", async () => {for (const tab of ["providers", "models", "mcp-connections"] as const) {- menu.setActiveTab(tab);+ const menu = await createMenu({ initialTab: tab, getRows: () => 24 });const lines = menu.render(24);- const output = stripAnsi(lines.join("\n"));- expect(output).toContain("Providers");- expect(output).toContain("Models");- expect(output).toContain("MCP Connections");expect(lines.length).toBeLessThanOrEqual(24);for (const line of lines) {expect(visibleWidth(line)).toBe(24);@@ -213,14 +232,89 @@ describe("ConfigurationMenuComponent", () => {}});- it("keeps the active marker visible across supported themes", async () => {+ it("keeps picker content visible across supported themes", async () => {const menu = await createMenu();for (const themeName of ["dark", "light", "prime"] as const) {initTheme(themeName);const rendered = menu.render(120).join("\n");- expect(stripAnsi(rendered)).toContain("[▶ Providers]");+ expect(stripAnsi(rendered)).toContain("Anthropic");expect(rendered).not.toBe(stripAnsi(rendered));}});++ it("rounds catalog input, cached-input, and output rates per million tokens", async () => {+ const menu = await createMenu({+ initialTab: "models",+ cost: { input: 1.1525, cacheRead: 0.0000015, output: 2.75, cacheWrite: 3 },+ });+ for (const width of [120, 48]) {+ const lines = stripAnsi(menu.render(width).join("\n")).split("\n");+ const output = lines.join("\n");+ expect(output).toContain("Input");+ expect(output).toContain("Cached input");+ expect(output).toContain("Output");+ expect(output).toContain("$1.153");+ expect(output).toContain("<0.001");+ expect(output).toContain("$2.75");+ expect(output).not.toContain("$1.1525");+ expect(output).not.toContain("$3");+ // The provider/model-id header line is gone; the unit trails the price+ // row and the block ends with clear whitespace.+ expect(output).not.toContain("faux/faux-1");+ expect(output).not.toContain("USD / 1M tokens");+ const unitLine = lines.find((line) => line.includes("$ / 1M tokens"));+ expect(unitLine).toBeDefined();+ expect(unitLine).toContain("Output");+ const lastPriceRow = lines.findIndex((line) => line.includes("$2.75"));+ expect(lastPriceRow).toBeGreaterThan(0);+ expect(lines[lastPriceRow + 1]?.trim()).toBe("");+ }+ });++ it("distinguishes catalog zero rates from invalid prices", async () => {+ const menu = await createMenu({+ initialTab: "models",+ cost: { input: 0, cacheRead: Number.NaN, output: Number.POSITIVE_INFINITY, cacheWrite: 0 },+ });+ const output = stripAnsi(menu.render(48).join("\n"));+ expect(output).toContain("Input: $0");+ expect(output).toContain("Cached input: —");+ expect(output).toContain("Output: —");+ expect(output).not.toMatch(/NaN|Infinity/);++ const missingCostMenu = await createMenu({ initialTab: "models", noCost: true });+ const missingCostOutput = stripAnsi(missingCostMenu.render(48).join("\n"));+ expect(missingCostOutput).toContain("Input: —");+ expect(missingCostOutput).toContain("Cached input: —");+ expect(missingCostOutput).toContain("Output: —");+ });++ it("keeps navigation and selection usable when an inline picker is resized", async () => {+ let rows = 20;+ const onSelectModel = vi.fn();+ const menu = await createMenu({ initialTab: "models", modelCount: 18, getRows: () => rows, onSelectModel });+ menu.render(120);+ menu.handleInput("\x1b[6~");+ for (const width of [120, 60, 24]) {+ rows = 12;+ const lines = menu.render(width);+ expect(lines.length).toBeLessThanOrEqual(rows);+ for (const line of lines) expect(visibleWidth(line)).toBe(width);+ }+ menu.handleInput("\r");+ expect(onSelectModel).toHaveBeenCalledOnce();+ expect(onSelectModel.mock.calls[0]?.[0].id).not.toBe("faux-1");+ });++ it("reserves space for search and selection on short, narrow terminals", async () => {+ const menu = await createMenu({ getRows: () => 8 });+ for (const tab of ["providers", "models", "mcp-connections"] as const) {+ menu.setActiveTab(tab);+ const lines = menu.render(24);+ expect(lines.length).toBeLessThanOrEqual(8);+ expect(stripAnsi(lines.join("\n"))).toContain("Enter select");+ for (const line of lines) expect(visibleWidth(line)).toBe(24);+ }+ });});diff --git a/packages/coding-agent/test/interactive-mode-status.test.ts b/packages/coding-agent/test/interactive-mode-status.test.tsindex a013a0df67..795af614c4 100644--- a/packages/coding-agent/test/interactive-mode-status.test.ts+++ b/packages/coding-agent/test/interactive-mode-status.test.ts@@ -7,6 +7,7 @@ import {type Component,Container,getKeybindings,+ Input,resetCapabilitiesCache,setCapabilities,setKeybindings,@@ -2340,7 +2341,10 @@ describe("InteractiveMode model selection persistence", () => {handleModelCommand(searchTerm?: string): Promise<void>;setupAutocompleteProvider(): void;};- type ModelSelectorOverlayHarness = {+ type ModelSelectorHarness = {+ editor: Input;+ editorContainer: Container;+ closeConfigurationMenu: (() => void) | undefined;agentConnection: {getModelCatalog(): Promise<AgentConnectionModelCatalog>;setModel(provider: string, modelId: string): Promise<void>;@@ -2355,6 +2359,7 @@ describe("InteractiveMode model selection persistence", () => {modelRegistry: ModelRegistry;settingsManager: {getRecentModels(): string[];+ getDefaultThinkingLevel(): undefined;setDefaultModelAndProvider(provider: string, modelId: string): void;};};@@ -2377,7 +2382,7 @@ describe("InteractiveMode model selection persistence", () => {};ensureModelProviderConfigured(model: AgentConnectionModel,- authFlows: ReturnType<ModelSelectorOverlayHarness["createAuthFlows"]>,+ authFlows: ReturnType<ModelSelectorHarness["createAuthFlows"]>,providerOptions: ReadonlyArray<AuthSelectorProvider>,): Promise<boolean>;completeModelSelection(model: AgentConnectionModel): Promise<void>;@@ -2400,10 +2405,11 @@ describe("InteractiveMode model selection persistence", () => {provider,id,name: id,+ cost: { input: 1, output: 5, cacheRead: 0.1, cacheWrite: 1.25 },}) as AgentConnectionModel;- const overlayPrototype = InteractiveMode.prototype as unknown as ModelSelectorOverlayHarness;+ const selectorPrototype = InteractiveMode.prototype as unknown as ModelSelectorHarness;- function createSelectorOverlayHarness(options: {+ function createSelectorHarness(options: {connectionModels: AgentConnectionModel[];catalogModels?: AgentConnectionModel[];configuredProviders?: ReadonlyArray<string>;@@ -2418,10 +2424,6 @@ describe("InteractiveMode model selection persistence", () => {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(@@ -2438,7 +2440,7 @@ describe("InteractiveMode model selection persistence", () => {registryModels.find((model) => model.provider === provider && model.id === modelId),),} as unknown as ModelRegistry;- const fakeThis = Object.create(InteractiveMode.prototype) as ModelSelectorOverlayHarness;+ const fakeThis = Object.create(InteractiveMode.prototype) as ModelSelectorHarness;fakeThis.agentConnection = {getModelCatalog:options.getModelCatalog ??@@ -2460,14 +2462,20 @@ describe("InteractiveMode model selection persistence", () => {fakeThis.connectionModelsFetchedAt = options.connectionModelsFetchedAt ?? 0;fakeThis.connectionModelsRefreshVersion = 0;fakeThis.connectionModelsRefreshInFlight = undefined;+ fakeThis.editor = new Input();+ fakeThis.editor.setValue("draft [paste #1] [image #2]");+ fakeThis.editorContainer = new Container();+ fakeThis.editorContainer.addChild(fakeThis.editor);fakeThis.ui = {requestRender: vi.fn(),+ setFocus: vi.fn(),terminal: { rows: 24 },} as unknown as TUI;fakeThis.uiServices = {modelRegistry,settingsManager: {getRecentModels: vi.fn(() => []),+ getDefaultThinkingLevel: vi.fn(() => undefined),setDefaultModelAndProvider: vi.fn(),},};@@ -2478,41 +2486,36 @@ 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.applyConnectionModelCatalog = selectorPrototype.applyConnectionModelCatalog;fakeThis.findExactModelMatch = (InteractiveMode.prototype as unknown as {findExactModelMatch(searchTerm: string): Promise<AgentConnectionModel | undefined>;}).findExactModelMatch;- fakeThis.getConnectionAvailableModels = overlayPrototype.getConnectionAvailableModels;- fakeThis.getCachedModelCandidates = overlayPrototype.getCachedModelCandidates;- fakeThis.getModelSelectorRefreshPromise = overlayPrototype.getModelSelectorRefreshPromise;+ fakeThis.getConnectionAvailableModels = selectorPrototype.getConnectionAvailableModels;+ fakeThis.getCachedModelCandidates = selectorPrototype.getCachedModelCandidates;+ fakeThis.getModelSelectorRefreshPromise = selectorPrototype.getModelSelectorRefreshPromise;fakeThis.createAuthFlows = vi.fn(() => ({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, focus };- });- fakeThis.showConfigurationMenu = overlayPrototype.showConfigurationMenu;+ fakeThis.ensureModelProviderConfigured = selectorPrototype.ensureModelProviderConfigured;+ fakeThis.completeModelSelection = selectorPrototype.completeModelSelection;+ fakeThis.showFullPaneOverlay = vi.fn();+ fakeThis.showConfigurationMenu = selectorPrototype.showConfigurationMenu;fakeThis.maybeWarnAboutAnthropicSubscriptionAuth = vi.fn(async () => {});fakeThis.checkDaxnutsEasterEgg = vi.fn();fakeThis.setupAutocompleteProvider = vi.fn();return {fakeThis,- hide,- setHidden,- focus,getSelector: () => {- if (!overlayComponent) {- throw new Error("Expected model selector overlay to be shown");+ const component = fakeThis.editorContainer.children[0];+ if (!component || component === fakeThis.editor) {+ throw new Error("Expected model selector in the prompt area");}- return overlayComponent as ConfigurationMenuComponent;+ return component as ConfigurationMenuComponent;},};}@@ -2612,8 +2615,8 @@ describe("InteractiveMode model selection persistence", () => {getLoginProviderOptions: () => [],loginProvider: async () => ({ status: "cancelled" as const }),}));- fakeThis.ensureModelProviderConfigured = overlayPrototype.ensureModelProviderConfigured;- fakeThis.completeModelSelection = overlayPrototype.completeModelSelection;+ fakeThis.ensureModelProviderConfigured = selectorPrototype.ensureModelProviderConfigured;+ fakeThis.completeModelSelection = selectorPrototype.completeModelSelection;fakeThis.findExactModelMatch = vi.fn(async () => model);fakeThis.maybeWarnAboutAnthropicSubscriptionAuth = vi.fn(async () => {});fakeThis.checkDaxnutsEasterEgg = vi.fn();@@ -2636,14 +2639,15 @@ describe("InteractiveMode model selection persistence", () => {const cachedModel = createModel("openai", "gpt-5.5");const liveModels = createDeferred<AgentConnectionModel[]>();const getAvailableModels = vi.fn(() => liveModels.promise);- const { fakeThis, getSelector } = createSelectorOverlayHarness({+ const { fakeThis, getSelector } = createSelectorHarness({connectionModels: [cachedModel],getAvailableModels,});const result = fakeThis.showConfigurationMenu("models");- expect(fakeThis.showFullPaneOverlay).toHaveBeenCalledTimes(1);+ expect(fakeThis.showFullPaneOverlay).not.toHaveBeenCalled();+ expect(fakeThis.editorContainer.children).toEqual([getSelector()]);expect(getAvailableModels).toHaveBeenCalledTimes(1);getSelector().handleInput("\x1b");@@ -2657,7 +2661,7 @@ describe("InteractiveMode model selection persistence", () => {const beta = { ...createModel("openai", "beta"), name: "Beta Model" };const liveModels = createDeferred<AgentConnectionModel[]>();const getAvailableModels = vi.fn(async () => [alpha]);- const { fakeThis, getSelector } = createSelectorOverlayHarness({+ const { fakeThis, getSelector } = createSelectorHarness({connectionModels: [alpha],connectionModelsFetchedAt: Date.now(),getAvailableModels,@@ -2692,7 +2696,7 @@ describe("InteractiveMode model selection persistence", () => {const alpha = createModel("openai", "alpha");const beta = createModel("openai", "beta");const getAvailableModels = vi.fn(async () => [beta]);- const { fakeThis } = createSelectorOverlayHarness({+ const { fakeThis } = createSelectorHarness({connectionModels: [alpha],connectionModelsFetchedAt: Date.now(),getAvailableModels,@@ -2706,7 +2710,7 @@ describe("InteractiveMode model selection persistence", () => {test("does not exact-match local fallback before daemon catalog loads", async () => {const localOnly = createModel("openai", "local-only");const getAvailableModels = vi.fn(async () => []);- const { fakeThis } = createSelectorOverlayHarness({+ const { fakeThis } = createSelectorHarness({connectionModels: [],registryModels: [localOnly],getAvailableModels,@@ -2719,7 +2723,7 @@ describe("InteractiveMode model selection persistence", () => {test("keeps a fetched empty daemon catalog empty", () => {const localOnly = createModel("openai", "local-only");- const { fakeThis } = createSelectorOverlayHarness({+ const { fakeThis } = createSelectorHarness({connectionModels: [],connectionModelsFetchedAt: Date.now(),registryModels: [localOnly],@@ -2732,7 +2736,7 @@ describe("InteractiveMode model selection persistence", () => {const localOnly = createModel("openai", "local-only");const liveModels = createDeferred<AgentConnectionModel[]>();const getAvailableModels = vi.fn(() => liveModels.promise);- const { fakeThis, getSelector } = createSelectorOverlayHarness({+ const { fakeThis, getSelector } = createSelectorHarness({connectionModels: [],registryModels: [localOnly],getAvailableModels,@@ -2756,7 +2760,7 @@ describe("InteractiveMode model selection persistence", () => {const scopedModel = createModel("openai", "scoped");const catalogModel = createModel("anthropic", "catalog");const getAvailableModels = vi.fn(async () => [catalogModel]);- const { fakeThis, getSelector } = createSelectorOverlayHarness({+ const { fakeThis, getSelector } = createSelectorHarness({connectionModels: [catalogModel],connectionModelsFetchedAt: Date.now(),getAvailableModels,@@ -2774,7 +2778,7 @@ describe("InteractiveMode model selection persistence", () => {expect(getSelector().render(120).join("\n")).toContain("catalog");expect(getAvailableModels).not.toHaveBeenCalled();getSelector().handleInput("\t");- expect(getSelector().getActiveTab()).toBe("mcp-connections");+ expect(getSelector().getActiveTab()).toBe("models");getSelector().handleInput("\x1b");await expect(result).resolves.toBeUndefined();@@ -2784,7 +2788,7 @@ describe("InteractiveMode model selection persistence", () => {test("uses a fresh cached model catalog without starting another refresh", async () => {const cachedModel = createModel("openai", "gpt-5.5");const getAvailableModels = vi.fn(async () => [cachedModel]);- const { fakeThis, getSelector } = createSelectorOverlayHarness({+ const { fakeThis, getSelector } = createSelectorHarness({connectionModels: [cachedModel],connectionModelsFetchedAt: Date.now(),getAvailableModels,@@ -2792,17 +2796,18 @@ describe("InteractiveMode model selection persistence", () => {const result = fakeThis.showConfigurationMenu("models");- expect(fakeThis.showFullPaneOverlay).toHaveBeenCalledTimes(1);+ expect(fakeThis.showFullPaneOverlay).not.toHaveBeenCalled();+ expect(fakeThis.editorContainer.children).toEqual([getSelector()]);expect(getAvailableModels).not.toHaveBeenCalled();getSelector().handleInput("\x1b");await expect(result).resolves.toBeUndefined();});- test("closes the model selector before the selected model finishes applying", async () => {+ test("keeps the model selector focused until the selected model finishes applying", async () => {const model = createModel("openai", "gpt-5.5");const apply = createDeferred<void>();- const { fakeThis, getSelector, hide, setHidden } = createSelectorOverlayHarness({+ const { fakeThis, getSelector } = createSelectorHarness({connectionModels: [model],applySelectedModel: vi.fn(() => apply.promise),});@@ -2818,21 +2823,24 @@ describe("InteractiveMode model selection persistence", () => {getSelector().handleInput("\r");await flushAsyncWork();- expect(setHidden).toHaveBeenCalledWith(true);- expect(hide).not.toHaveBeenCalled();+ expect(fakeThis.editorContainer.children).toEqual([getSelector()]);+ expect(fakeThis.ui.setFocus).toHaveBeenLastCalledWith(getSelector());+ expect(fakeThis.closeConfigurationMenu).toBeDefined();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.closeConfigurationMenu).toBeUndefined();+ expect(fakeThis.editorContainer.children).toEqual([fakeThis.editor]);+ expect(fakeThis.editor.getValue()).toBe("draft [paste #1] [image #2]");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({+ const { fakeThis, getSelector } = createSelectorHarness({connectionModels: [model],applySelectedModel: vi.fn(async () => {throw new Error("model switch failed");@@ -2844,15 +2852,16 @@ describe("InteractiveMode model selection persistence", () => {getSelector().handleInput("\r");await flushAsyncWork();- expect(hide).not.toHaveBeenCalled();- expect(setHidden).toHaveBeenNthCalledWith(1, true);- expect(setHidden).toHaveBeenNthCalledWith(2, false);- expect(focus).toHaveBeenCalled();+ expect(fakeThis.closeConfigurationMenu).toBeDefined();+ expect(fakeThis.editorContainer.children).toEqual([getSelector()]);+ expect(fakeThis.ui.setFocus).toHaveBeenLastCalledWith(getSelector());expect(fakeThis.showError).toHaveBeenCalledWith("model switch failed");getSelector().handleInput("\x1b");await expect(result).resolves.toBeUndefined();- expect(hide).toHaveBeenCalledTimes(1);+ expect(fakeThis.closeConfigurationMenu).toBeUndefined();+ expect(fakeThis.editorContainer.children).toEqual([fakeThis.editor]);+ expect(fakeThis.editor.getValue()).toBe("draft [paste #1] [image #2]");});test("authenticates an unavailable model provider before applying the model", async () => {@@ -2873,7 +2882,7 @@ describe("InteractiveMode model selection persistence", () => {};});const applySelectedModel = vi.fn(async () => {});- const { fakeThis, getSelector, hide } = createSelectorOverlayHarness({+ const { fakeThis, getSelector } = createSelectorHarness({connectionModels: [],catalogModels: [model],configuredProviders: [],@@ -2892,7 +2901,9 @@ describe("InteractiveMode model selection persistence", () => {expect(loginProvider).toHaveBeenCalledWith(provider);expect(getModelCatalog).toHaveBeenCalledTimes(1);expect(applySelectedModel).toHaveBeenCalledWith(model);- expect(hide).toHaveBeenCalledTimes(1);+ expect(fakeThis.closeConfigurationMenu).toBeUndefined();+ expect(fakeThis.editorContainer.children).toEqual([fakeThis.editor]);+ expect(fakeThis.editor.getValue()).toBe("draft [paste #1] [image #2]");await expect(result).resolves.toBeUndefined();});@@ -2901,7 +2912,7 @@ describe("InteractiveMode model selection persistence", () => {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({+ const { fakeThis, getSelector } = createSelectorHarness({connectionModels: [],catalogModels: [model],configuredProviders: [],@@ -2916,8 +2927,9 @@ describe("InteractiveMode model selection persistence", () => {await flushAsyncWork();expect(loginProvider).toHaveBeenCalledWith(provider);+ expect(fakeThis.ui.setFocus).toHaveBeenLastCalledWith(getSelector());expect(applySelectedModel).not.toHaveBeenCalled();- expect(hide).not.toHaveBeenCalled();+ expect(fakeThis.closeConfigurationMenu).toBeDefined();getSelector().handleInput("\x1b");await expect(result).resolves.toBeUndefined();@@ -2927,7 +2939,7 @@ describe("InteractiveMode model selection persistence", () => {const alpha = createModel("openai", "alpha");const beta = { ...createModel("openai", "beta"), name: "Beta Model" };const liveModels = createDeferred<AgentConnectionModel[]>();- const { fakeThis, getSelector } = createSelectorOverlayHarness({+ const { fakeThis, getSelector } = createSelectorHarness({connectionModels: [alpha],getAvailableModels: vi.fn(() => liveModels.promise),});@@ -2949,11 +2961,41 @@ describe("InteractiveMode model selection persistence", () => {await expect(result).resolves.toBeUndefined();});+ test("cancels a pending selection without applying the model or stealing editor focus", async () => {+ const model = createModel("openai", "gpt-5.5");+ const provider: AuthSelectorProvider = { id: "openai", name: "OpenAI", authType: "api_key" };+ const authentication = createDeferred<AuthenticationResult>();+ const loginProvider = vi.fn(() => authentication.promise);+ const applySelectedModel = vi.fn(async () => {});+ const { fakeThis, getSelector } = createSelectorHarness({+ connectionModels: [],+ catalogModels: [model],+ configuredProviders: [],+ connectionModelsFetchedAt: Date.now(),+ providerOptions: [provider],+ loginProvider,+ applySelectedModel,+ });+ const result = fakeThis.showConfigurationMenu("models");+ const selector = getSelector();+ selector.handleInput("\r");+ selector.handleInput("\r");+ expect(loginProvider).toHaveBeenCalledOnce();+ selector.handleInput("\x1b");+ await result;+ authentication.resolve({ status: "cancelled" });+ await flushAsyncWork();+ expect(applySelectedModel).not.toHaveBeenCalled();+ expect(fakeThis.editorContainer.children).toEqual([fakeThis.editor]);+ expect(fakeThis.ui.setFocus).toHaveBeenLastCalledWith(fakeThis.editor);+ expect(fakeThis.editor.getValue()).toBe("draft [paste #1] [image #2]");+ });+test("refreshes fresh cached selector results when opened with a search", async () => {const alpha = createModel("openai", "alpha");const beta = { ...createModel("openai", "beta"), name: "Beta Model" };const getAvailableModels = vi.fn(async () => [beta]);- const { fakeThis, getSelector } = createSelectorOverlayHarness({+ const { fakeThis, getSelector } = createSelectorHarness({connectionModels: [alpha],connectionModelsFetchedAt: Date.now(),getAvailableModels,@@ -2977,7 +3019,7 @@ describe("InteractiveMode model selection persistence", () => {.fn<() => Promise<AgentConnectionModelCatalog>>().mockImplementationOnce(() => oldModels.promise).mockImplementationOnce(async () => ({ models: [freshModel], configuredProviders: [freshModel.provider] }));- const fakeThis = Object.create(InteractiveMode.prototype) as ModelSelectorOverlayHarness & {+ const fakeThis = Object.create(InteractiveMode.prototype) as ModelSelectorHarness & {connectionCommands: unknown[];connectionResourceSnapshot: unknown;refreshConnectionCatalog(): Promise<void>;@@ -2998,8 +3040,8 @@ describe("InteractiveMode model selection persistence", () => {fakeThis.connectionModelsRefreshVersion = 0;fakeThis.connectionModelsRefreshInFlight = undefined;fakeThis.getScopedModelState = vi.fn(() => []);- fakeThis.applyConnectionModelCatalog = overlayPrototype.applyConnectionModelCatalog;- fakeThis.getConnectionAvailableModels = overlayPrototype.getConnectionAvailableModels;+ fakeThis.applyConnectionModelCatalog = selectorPrototype.applyConnectionModelCatalog;+ fakeThis.getConnectionAvailableModels = selectorPrototype.getConnectionAvailableModels;fakeThis.refreshConnectionCatalog = (InteractiveMode.prototype as unknown as { refreshConnectionCatalog(): Promise<void> }).refreshConnectionCatalog;@@ -3022,7 +3064,7 @@ describe("InteractiveMode model selection persistence", () => {test("keeps the cached model catalog when a catalog refresh fails", async () => {const cachedModel = createModel("openai", "cached");- const fakeThis = Object.create(InteractiveMode.prototype) as ModelSelectorOverlayHarness & {+ const fakeThis = Object.create(InteractiveMode.prototype) as ModelSelectorHarness & {connectionCommands: unknown[];connectionResourceSnapshot: unknown;refreshConnectionCatalog(): Promise<void>;@@ -3046,7 +3088,7 @@ describe("InteractiveMode model selection persistence", () => {fakeThis.connectionModelsFetchedAt = Date.now();fakeThis.connectionModelsRefreshVersion = 0;fakeThis.connectionModelsRefreshInFlight = undefined;- fakeThis.applyConnectionModelCatalog = overlayPrototype.applyConnectionModelCatalog;+ fakeThis.applyConnectionModelCatalog = selectorPrototype.applyConnectionModelCatalog;fakeThis.refreshConnectionCatalog = (InteractiveMode.prototype as unknown as { refreshConnectionCatalog(): Promise<void> }).refreshConnectionCatalog;@@ -3066,7 +3108,7 @@ describe("InteractiveMode model selection persistence", () => {const getAvailableModels = vi.fn(async () => {throw new Error("models unavailable");});- const { fakeThis, getSelector, hide } = createSelectorOverlayHarness({+ const { fakeThis, getSelector } = createSelectorHarness({connectionModels: [],getAvailableModels,});@@ -3075,10 +3117,12 @@ describe("InteractiveMode model selection persistence", () => {await flushAsyncWork();expect(fakeThis.showError).toHaveBeenCalledWith("models unavailable");- expect(hide).not.toHaveBeenCalled();+ expect(fakeThis.closeConfigurationMenu).toBeDefined();getSelector().handleInput("\x1b");await expect(result).resolves.toBeUndefined();- expect(hide).toHaveBeenCalledTimes(1);+ expect(fakeThis.closeConfigurationMenu).toBeUndefined();+ expect(fakeThis.editorContainer.children).toEqual([fakeThis.editor]);+ expect(fakeThis.editor.getValue()).toBe("draft [paste #1] [image #2]");});});@@ -4033,7 +4077,10 @@ describe("InteractiveMode Prime CLI onboarding", () => {await flushAsyncWork();expect(fakeThis.showConfigurationMenu).toHaveBeenCalledWith("models");- expect(dismiss).not.toHaveBeenCalled();+ expect(dismiss).toHaveBeenCalledOnce();+ expect(dismiss.mock.invocationCallOrder[0]).toBeLessThan(+ vi.mocked(fakeThis.showConfigurationMenu).mock.invocationCallOrder[0]!,+ );configuration.resolve();await expect(onboarding).resolves.toBeUndefined();@@ -4081,7 +4128,10 @@ describe("InteractiveMode Prime CLI onboarding", () => {expect(showProgress).toHaveBeenNthCalledWith(2, "Preparing models...");expect(fakeThis.prepareForModelSelectionAfterLogin).toHaveBeenCalledTimes(1);expect(fakeThis.showConfigurationMenu).toHaveBeenCalledWith("models");- expect(dismiss).not.toHaveBeenCalled();+ expect(dismiss).toHaveBeenCalledOnce();+ expect(dismiss.mock.invocationCallOrder[0]).toBeLessThan(+ vi.mocked(fakeThis.showConfigurationMenu).mock.invocationCallOrder[0]!,+ );configuration.resolve();await expect(onboarding).resolves.toBeUndefined();diff --git a/packages/coding-agent/test/menu-panel.test.ts b/packages/coding-agent/test/menu-panel.test.tsindex c5164ce8fe..bfc6f30a3e 100644--- a/packages/coding-agent/test/menu-panel.test.ts+++ b/packages/coding-agent/test/menu-panel.test.ts@@ -1,4 +1,5 @@import { type Component, TruncatedText, visibleWidth } from "@earendil-works/pi-tui";+import chalk from "chalk";import stripAnsi from "strip-ansi";import { beforeAll, describe, expect, it } from "vitest";import {@@ -89,6 +90,28 @@ describe("MenuPanel", () => {}});+ it("renders selected rows with a bold non-accent primary and a soft highlight", () => {+ const previousChalkLevel = chalk.level;+ chalk.level = 3;+ try {+ const fullRow = new MenuRow({ primary: "openai/gpt-5", secondary: "openai", selected: true });+ const fullOutput = fullRow.render(40).join("\n");+ expect(stripAnsi(fullOutput)).toContain("openai/gpt-5");+ expect(fullOutput).toContain("\x1b[1m");+ expect(fullOutput).not.toContain(theme.getFgAnsi("accent"));+ expect(fullOutput).toContain(theme.getBgAnsi("selectedBg"));++ const inlineRow = new MenuRow({ primary: "GPT 5.5", trailing: ["openai"], selected: true, inline: true });+ const inlineOutput = inlineRow.renderContent(80).join("\n");+ expect(stripAnsi(inlineOutput)).toContain("GPT 5.5");+ expect(inlineOutput).toContain("\x1b[1m");+ expect(inlineOutput).not.toContain(theme.getFgAnsi("accent"));+ expect(inlineOutput).toContain(theme.getBgAnsi("selectedBg"));+ } finally {+ chalk.level = previousChalkLevel;+ }+ });+it("collapses adjacent row padding around the selected row", () => {const createList = (selectedIndex: number): MenuList => {const list = new MenuList();diff --git a/packages/coding-agent/test/model-selector-actions.test.ts b/packages/coding-agent/test/model-selector-actions.test.tsindex 88b6d0b4d5..4740faf3db 100644--- a/packages/coding-agent/test/model-selector-actions.test.ts+++ b/packages/coding-agent/test/model-selector-actions.test.ts@@ -6,7 +6,7 @@ import { VirtualTerminal } from "../../tui/test/virtual-terminal.js";import { KeybindingsManager } from "../src/core/keybindings.js";import { buildPrimeInferenceModels } from "../src/core/prime-inference-model-catalog.js";import { ModelSelectorComponent } from "../src/modes/interactive/components/model-selector.js";-import { initTheme } from "../src/modes/interactive/theme/theme.js";+import { initTheme, theme } from "../src/modes/interactive/theme/theme.js";import { createHarness, type Harness } from "./suite/harness.js";function createFakeTui(): TUI {@@ -244,17 +244,17 @@ describe("ModelSelectorComponent", () => {await waitForAsyncRender();- expect(selector.render(120)).toHaveLength(12);+ expect(selector.render(120).length).toBeLessThanOrEqual(12);selector.handleInput("\x1b[B");const output = stripAnsi(selector.render(120).join("\n"));- expect(selector.render(120)).toHaveLength(12);+ expect(selector.render(120).length).toBeLessThanOrEqual(12);expect(output).toContain("faux-2");expect(output).toContain("(2/12)");});- it("keeps exact matches ahead of weaker signed-in matches and prefers sign-in for equivalent matches", async () => {+ it("keeps signed-in matches above unsigned matches and orders by quality within them", async () => {const harness = await createHarness({models: [{ id: "base", name: "Base", reasoning: true }],});@@ -290,8 +290,8 @@ describe("ModelSelectorComponent", () => {const signedOutExactRow = lines.findIndex((line) => line.includes("opencode"));const signedInFuzzyRow = lines.findIndex((line) => line.includes("glorious-language-model-5.2"));expect(signedInExactRow).toBeGreaterThanOrEqual(0);- expect(signedInExactRow).toBeLessThan(signedOutExactRow);- expect(signedOutExactRow).toBeLessThan(signedInFuzzyRow);+ expect(signedInExactRow).toBeLessThan(signedInFuzzyRow);+ expect(signedInFuzzyRow).toBeLessThan(signedOutExactRow);});it("orders provider-qualified exact, prefix, and fuzzy matches by quality", async () => {@@ -302,8 +302,8 @@ describe("ModelSelectorComponent", () => {const base = harness.getModel("base")!;const exact = { ...base, provider: "openai", id: "gpt-5", name: "GPT-5" };- const prefix = { ...base, provider: "prime-inference", id: "openai-gpt-5-preview", name: "GPT-5 Preview" };- const fuzzy = { ...base, provider: "prime-inference", id: "other-openai-gpt-5", name: "Other GPT-5" };+ const prefix = { ...base, provider: "openai", id: "openai-gpt-5-preview", name: "GPT-5 Preview" };+ const fuzzy = { ...base, provider: "openai", id: "other-openai-gpt-5", name: "Other GPT-5" };const selector = new ModelSelectorComponent(createFakeTui(),undefined,@@ -314,7 +314,7 @@ describe("ModelSelectorComponent", () => {"openai/gpt5",{availableModels: [fuzzy, prefix, exact],- configuredProviders: new Set(["prime-inference"]),+ configuredProviders: new Set(["openai"]),},);@@ -331,6 +331,419 @@ describe("ModelSelectorComponent", () => {expect(prefixRow).toBeLessThan(fuzzyRow);});+ it("keeps signed-in providers above unsigned matches in search results", async () => {+ const harness = await createHarness({+ models: [{ id: "base", name: "Base", reasoning: true }],+ });+ harnesses.push(harness);++ const base = harness.getModel("base")!;+ const primeCodex = { ...base, provider: "prime-inference", id: "codex-prime", name: "Prime Codex Model" };+ const openaiExact = { ...base, provider: "openai", id: "codex", name: "Standard Codex" };+ const openaiWeaker = { ...base, provider: "openai", id: "glorious-codex-thing", name: "Glorious Codex" };+ const opencodeCodex = { ...base, provider: "opencode", id: "gpt-5-codex", name: "Rival Codex" };+ const vercelCodex = {+ ...base,+ provider: "vercel-ai-gateway",+ id: "codex-gateway",+ name: "Gateway Codex",+ };+ const selector = new ModelSelectorComponent(+ createFakeTui(),+ undefined,+ harness.session.modelRegistry,+ [],+ () => {},+ () => {},+ "codex",+ {+ availableModels: [opencodeCodex, vercelCodex, openaiWeaker, openaiExact, primeCodex],+ configuredProviders: new Set(["prime-inference", "openai"]),+ inline: true,+ },+ );++ await waitForAsyncRender();++ const lines = stripAnsi(selector.render(80).join("\n")).split("\n");+ const rowOf = (text: string) => lines.findIndex((line) => line.includes(text));+ const primeRow = rowOf("Prime Codex Model");+ const openaiExactRow = rowOf("Standard Codex");+ const openaiWeakerRow = rowOf("Glorious Codex");+ const opencodeRow = rowOf("Rival Codex");+ const vercelRow = rowOf("Gateway Codex");+ expect(primeRow).toBeGreaterThanOrEqual(0);+ expect(primeRow).toBeLessThan(openaiExactRow);+ expect(openaiExactRow).toBeLessThan(openaiWeakerRow);+ expect(openaiWeakerRow).toBeLessThan(opencodeRow);+ expect(openaiWeakerRow).toBeLessThan(vercelRow);+ });++ it("right-aligns the provider with the require sign in hint to its left", async () => {+ const harness = await createHarness({+ models: [{ id: "base", name: "Base", reasoning: true }],+ });+ harnesses.push(harness);++ const base = harness.getModel("base")!;+ const configured = { ...base, provider: "signed-in-beta", id: "beta-one", name: "Beta One" };+ const unconfigured = { ...base, provider: "unsigned-zeta", id: "zeta-one", name: "Zeta One" };+ const selector = new ModelSelectorComponent(+ createFakeTui(),+ undefined,+ harness.session.modelRegistry,+ [],+ () => {},+ () => {},+ undefined,+ {+ availableModels: [configured, unconfigured],+ configuredProviders: new Set([configured.provider]),+ inline: true,+ },+ );++ await waitForAsyncRender();++ const lines = stripAnsi(selector.render(80).join("\n")).split("\n");+ const configuredRow = lines.find((line) => line.includes("Beta One"));+ const unconfiguredRow = lines.find((line) => line.includes("Zeta One"));+ expect(configuredRow).toBeDefined();+ expect(unconfiguredRow).toBeDefined();+ expect(configuredRow?.endsWith("signed-in-beta")).toBe(true);+ expect(unconfiguredRow?.endsWith("unsigned-zeta")).toBe(true);+ expect(unconfiguredRow).toContain("require sign in · unsigned-zeta");+ expect(configuredRow).not.toContain("require sign in");+ });++ it("pins signed-in Prime Inference models above other signed-in providers", async () => {+ const harness = await createHarness({+ models: [{ id: "base", name: "Base", reasoning: true }],+ });+ harnesses.push(harness);++ const base = harness.getModel("base")!;+ const prime = { ...base, provider: "prime-inference", id: "glm-5-3", name: "GLM 5.3" };+ const signedIn = { ...base, provider: "signed-in-beta", id: "beta-one", name: "Beta One" };+ const unsigned = { ...base, provider: "unsigned-zeta", id: "zeta-one", name: "Zeta One" };+ const selector = new ModelSelectorComponent(+ createFakeTui(),+ undefined,+ harness.session.modelRegistry,+ [],+ () => {},+ () => {},+ undefined,+ {+ availableModels: [unsigned, signedIn, prime],+ configuredProviders: new Set([prime.provider, signedIn.provider]),+ inline: true,+ },+ );++ await waitForAsyncRender();++ const lines = stripAnsi(selector.render(80).join("\n")).split("\n");+ const primeRow = lines.findIndex((line) => line.includes("GLM 5.3"));+ const signedInRow = lines.findIndex((line) => line.includes("Beta One"));+ const unsignedRow = lines.findIndex((line) => line.includes("Zeta One"));+ expect(primeRow).toBeGreaterThanOrEqual(0);+ expect(primeRow).toBeLessThan(signedInRow);+ expect(signedInRow).toBeLessThan(unsignedRow);+ });++ it("keeps Prime Inference models ordered with the rest when it is not signed in", async () => {+ const previousPrimeKey = process.env.PRIME_API_KEY;+ delete process.env.PRIME_API_KEY;+ try {+ const harness = await createHarness({+ models: [{ id: "base", name: "Base", reasoning: true }],+ });+ harnesses.push(harness);++ const base = harness.getModel("base")!;+ const prime = { ...base, provider: "prime-inference", id: "glm-5-3", name: "GLM 5.3" };+ const signedIn = { ...base, provider: "signed-in-beta", id: "beta-one", name: "Beta One" };+ const unsigned = { ...base, provider: "a-unsigned", id: "alpha-one", name: "Alpha One" };+ const selector = new ModelSelectorComponent(+ createFakeTui(),+ undefined,+ harness.session.modelRegistry,+ [],+ () => {},+ () => {},+ undefined,+ {+ availableModels: [prime, signedIn, unsigned],+ configuredProviders: new Set([signedIn.provider]),+ inline: true,+ },+ );++ await waitForAsyncRender();++ const lines = stripAnsi(selector.render(80).join("\n")).split("\n");+ const primeRow = lines.findIndex((line) => line.includes("GLM 5.3"));+ const signedInRow = lines.findIndex((line) => line.includes("Beta One"));+ const unsignedRow = lines.findIndex((line) => line.includes("Alpha One"));+ expect(signedInRow).toBeGreaterThanOrEqual(0);+ expect(signedInRow).toBeLessThan(unsignedRow);+ expect(unsignedRow).toBeLessThan(primeRow);+ expect(lines.findIndex((line) => line.includes("require sign in · prime-inference"))).toBe(primeRow);+ } finally {+ if (previousPrimeKey === undefined) {+ delete process.env.PRIME_API_KEY;+ } else {+ process.env.PRIME_API_KEY = previousPrimeKey;+ }+ }+ });++ it("renders effort squares for the preselected level and adjusts with left/right", async () => {+ const harness = await createHarness({+ models: [{ id: "reasoning", name: "Reasoning One", reasoning: true }],+ });+ harnesses.push(harness);++ const base = harness.getModel("reasoning")!;+ const model = { ...base, provider: "signed-in-beta", id: "beta-one", name: "Beta One" };+ const selector = new ModelSelectorComponent(+ createFakeTui(),+ undefined,+ harness.session.modelRegistry,+ [],+ () => {},+ () => {},+ undefined,+ {+ availableModels: [model],+ configuredProviders: new Set([model.provider]),+ inline: true,+ thinkingLevel: "low",+ },+ );++ await waitForAsyncRender();++ const row = () =>+ stripAnsi(selector.render(80).join("\n"))+ .split("\n")+ .find((line) => line.includes("Beta One"));++ expect(row()).toContain("← ■■□□ → low");+ // The cluster sits near the row's horizontal center, clear of the name.+ expect(row()?.search(/[■□]/)).toBe(34);++ selector.handleInput("\x1b[C");+ expect(row()).toContain("■■■□");+ expect(row()).toContain("medium");++ selector.handleInput("\x1b[D");+ selector.handleInput("\x1b[D");+ selector.handleInput("\x1b[D");+ expect(row()).toContain("□□□□");+ expect(row()).toContain("off");++ selector.handleInput("\x1b[D");+ expect(row()).toContain("■■■■");+ expect(row()).toContain("high");+ });++ it("shows no effort squares for models without reasoning support", async () => {+ const harness = await createHarness({+ models: [{ id: "base", name: "Base", reasoning: true }],+ });+ harnesses.push(harness);++ const base = harness.getModel("base")!;+ const model = { ...base, provider: "signed-in-beta", id: "beta-one", name: "Beta One", reasoning: false };+ const selector = new ModelSelectorComponent(+ createFakeTui(),+ undefined,+ harness.session.modelRegistry,+ [],+ () => {},+ () => {},+ undefined,+ {+ availableModels: [model],+ configuredProviders: new Set([model.provider]),+ inline: true,+ thinkingLevel: "high",+ },+ );++ await waitForAsyncRender();++ const renderRow = () =>+ stripAnsi(selector.render(80).join("\n"))+ .split("\n")+ .find((line) => line.includes("Beta One"));++ expect(renderRow()).toBeDefined();+ expect(renderRow()).not.toContain("■");+ expect(renderRow()).not.toContain("□");+ expect(renderRow()).not.toContain("←");+ expect(renderRow()).not.toContain("→");++ selector.handleInput("\x1b[C");+ expect(renderRow()).not.toContain("■");+ });++ it("applies the selected model and effort level together on confirm", async () => {+ const harness = await createHarness({+ models: [{ id: "reasoning", name: "Reasoning One", reasoning: true }],+ });+ harnesses.push(harness);++ const base = harness.getModel("reasoning")!;+ const model = { ...base, provider: "signed-in-beta", id: "beta-one", name: "Beta One" };+ let selectedId: string | undefined;+ let selectedLevel: string | undefined;+ const selector = new ModelSelectorComponent(+ createFakeTui(),+ undefined,+ harness.session.modelRegistry,+ [],+ (selected, thinkingLevel) => {+ selectedId = selected.id;+ selectedLevel = thinkingLevel;+ },+ () => {},+ undefined,+ {+ availableModels: [model],+ configuredProviders: new Set([model.provider]),+ inline: true,+ },+ );++ await waitForAsyncRender();++ const row = () =>+ stripAnsi(selector.render(80).join("\n"))+ .split("\n")+ .find((line) => line.includes("Beta One"));+ expect(row()).toContain("□□□□");+ expect(row()).toContain("off");++ selector.handleInput("\x1b[C");+ expect(row()).toContain("■□□□");++ selector.handleInput("\r");+ expect(selectedId).toBe("beta-one");+ expect(selectedLevel).toBe("minimal");+ });++ it("aligns effort squares, arrows, and labels across rows", async () => {+ const harness = await createHarness({+ models: [{ id: "reasoning", name: "Reasoning One", reasoning: true }],+ });+ harnesses.push(harness);++ const base = harness.getModel("reasoning")!;+ const short = { ...base, provider: "signed-in-beta", id: "beta-one", name: "GLM 5.3" };+ const long = { ...base, provider: "unsigned-zeta", id: "zeta-one", name: "A Considerably Longer Model Name" };+ const selector = new ModelSelectorComponent(+ createFakeTui(),+ undefined,+ harness.session.modelRegistry,+ [],+ () => {},+ () => {},+ undefined,+ {+ availableModels: [short, long],+ configuredProviders: new Set([short.provider]),+ inline: true,+ thinkingLevel: "low",+ },+ );++ await waitForAsyncRender();++ const rawLines = selector.render(80).join("\n").split("\n");+ const lines = rawLines.map((line) => stripAnsi(line));+ const shortRow = lines.find((line) => line.includes("GLM 5.3"));+ const longRow = lines.find((line) => line.includes("A Considerably Longer"));+ expect(shortRow).toBeDefined();+ expect(longRow).toBeDefined();+ expect(shortRow?.search(/[■□]/)).toBe(longRow?.search(/[■□]/));+ expect(shortRow?.indexOf(" low")).toBe(longRow?.indexOf(" low"));+ expect(shortRow).toContain("←");+ expect(shortRow).toContain("→");+ expect(longRow).not.toContain("←");+ expect(longRow).not.toContain("→");+ expect(longRow).toContain("■■□□");++ // Purple fills are reserved for the highlighted row; other rows fill light gray.+ const shortRaw = rawLines.find((line) => line.includes("GLM 5.3"));+ const longRaw = rawLines.find((line) => line.includes("A Considerably Longer"));+ expect(shortRaw).toContain(theme.getEffortSquareColor()("■"));+ expect(shortRaw).toContain(theme.fg("dim", "□"));+ expect(longRaw).not.toContain(theme.getEffortSquareColor()("■"));+ expect(longRaw).toContain(theme.fg("muted", "■"));+ expect(longRaw).toContain(theme.fg("dim", "□"));+ });++ it("keeps the effort cluster width stable across level changes", async () => {+ const harness = await createHarness({+ models: [{ id: "reasoning", name: "Reasoning One", reasoning: true }],+ });+ harnesses.push(harness);++ const base = harness.getModel("reasoning")!;+ const model = { ...base, provider: "signed-in-beta", id: "beta-one", name: "Beta One" };+ const selector = new ModelSelectorComponent(+ createFakeTui(),+ undefined,+ harness.session.modelRegistry,+ [],+ () => {},+ () => {},+ undefined,+ {+ availableModels: [model],+ configuredProviders: new Set([model.provider]),+ inline: true,+ thinkingLevel: "low",+ },+ );++ await waitForAsyncRender();++ const row = () =>+ stripAnsi(selector.render(80).join("\n"))+ .split("\n")+ .find((line) => line.includes("Beta One"));+ const before = row();+ expect(before).toBeDefined();+ const labelStart = before?.indexOf("→") ?? -1;+ expect(labelStart).toBeGreaterThan(0);+ const labelCell = (text: string) => text.slice(labelStart + 2, labelStart + 9);+ // The label cell is fixed to the longest supported level name ("minimal").+ expect(labelCell(before ?? "")).toBe("low ");++ selector.handleInput("\x1b[C");+ const medium = row();+ // Cluster start, arrow, and label cell all stay in place; only the+ // square fills change.+ expect(medium?.search(/[■□]/)).toBe(before?.search(/[■□]/));+ expect(medium?.indexOf("→")).toBe(labelStart);+ expect(labelCell(medium ?? "")).toBe("medium ");++ selector.handleInput("\x1b[C");+ expect(labelCell(row() ?? "")).toBe("high ");++ selector.handleInput("\x1b[C");+ expect(labelCell(row() ?? "")).toBe("off ");++ selector.handleInput("\x1b[C");+ const longest = row();+ expect(longest?.search(/[■□]/)).toBe(before?.search(/[■□]/));+ expect(labelCell(longest ?? "")).toBe("minimal");+ });+it("uses current model, recency, and alphabetical order for equivalent matches", async () => {const harness = await createHarness({models: [diff --git a/packages/coding-agent/test/suite/regressions/2182-picker-selection.test.ts b/packages/coding-agent/test/suite/regressions/2182-picker-selection.test.tsnew file mode 100644index 0000000000..3722f939ed--- /dev/null+++ b/packages/coding-agent/test/suite/regressions/2182-picker-selection.test.ts@@ -0,0 +1,183 @@+import type { ModelThinkingLevel } from "@earendil-works/pi-ai";+import { Container, Input, setKeybindings, type TUI } from "@earendil-works/pi-tui";+import stripAnsi from "strip-ansi";+import { afterEach, beforeAll, beforeEach, expect, it, vi } from "vitest";+import { KEYBINDINGS, KeybindingsManager } from "../../../src/core/keybindings.js";+import type { ConfigurationMenuComponent } from "../../../src/modes/interactive/components/configuration-menu.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 { createHarness, type Harness } from "../harness.js";++const harnesses: Harness[] = [];+beforeAll(() => initTheme("dark"));+beforeEach(() => setKeybindings(new KeybindingsManager()));+afterEach(() => {+ while (harnesses.length) harnesses.pop()?.cleanup();+});+function deferred() {+ let resolve!: () => void;+ const promise = new Promise<void>((done) => {+ resolve = done;+ });+ return { promise, resolve };+}+async function fixture() {+ const harness = await createHarness({+ models: [+ { id: "plain", name: "Plain", reasoning: false },+ { id: "reason", name: "Reason", reasoning: true },+ ],+ });+ harnesses.push(harness);+ const model = harness.getModel("reason")!;+ const plain = harness.getModel("plain")!;+ const editor = new Input();+ editor.setValue("preserved draft");+ const editorContainer = new Container();+ editorContainer.addChild(editor);+ const setThinkingLevel = vi.fn(async (_level: ModelThinkingLevel) => {});+ const mode = Object.assign(Object.create(InteractiveMode.prototype) as object, {+ editor,+ editorContainer,+ ui: { terminal: { rows: 30 }, requestRender: vi.fn(), setFocus: vi.fn() },+ uiServices: {+ modelRegistry: harness.session.modelRegistry,+ settingsManager: {+ getRecentModels: () => [],+ getDefaultThinkingLevel: () => "medium",+ },+ },+ connectionConfiguredProviders: new Set([model.provider]),+ connectionState: { thinkingLevel: "off" },+ getCurrentModel: () => plain,+ getScopedModelState: () => [],+ getCachedModelCandidates: () => [model],+ getModelSelectorRefreshPromise: () => undefined,+ createAuthFlows: () => ({ getLoginProviderOptions: () => [] }),+ ensureModelProviderConfigured: async () => true,+ completeModelSelection: vi.fn(async () => {}),+ agentConnection: { setThinkingLevel },+ patchConnectionState: vi.fn(),+ footer: { invalidate: vi.fn() },+ updateEditorBorderColor: vi.fn(),+ showStatus: vi.fn(),+ showError: vi.fn(),+ }) as unknown as {+ showConfigurationMenu(tab: "models"): Promise<void>;+ completeModelSelection: ReturnType<typeof vi.fn<() => Promise<void>>>;+ ui: { setFocus: ReturnType<typeof vi.fn> };+ showError: ReturnType<typeof vi.fn>;+ };+ return {+ harness,+ model,+ mode,+ editor,+ editorContainer,+ setThinkingLevel,+ menu: () => editorContainer.children[0] as ConfigurationMenuComponent,+ };+}++it("retains picker focus and draft until model and explicit effort both complete", async () => {+ const f = await fixture();+ const modelApplied = deferred();+ const effortApplied = deferred();+ f.mode.completeModelSelection.mockImplementation(() => modelApplied.promise);+ f.setThinkingLevel.mockImplementation(() => effortApplied.promise);+ const done = f.mode.showConfigurationMenu("models");+ const menu = f.menu();+ expect(stripAnsi(menu.render(100).join("\n"))).toContain("medium");+ menu.handleInput("\x1b[C");+ menu.handleInput("\r");+ await vi.waitFor(() => expect(f.mode.completeModelSelection).toHaveBeenCalledOnce());+ let finished = false;+ void done.then(() => {+ finished = true;+ });+ menu.handleInput("\x1b");+ menu.handleInput("\r");+ const competing = f.mode.showConfigurationMenu("models");+ expect(f.menu()).toBe(menu);+ expect(f.mode.ui.setFocus).toHaveBeenLastCalledWith(menu);+ expect(f.setThinkingLevel).not.toHaveBeenCalled();+ modelApplied.resolve();+ await vi.waitFor(() => expect(f.setThinkingLevel).toHaveBeenCalledWith("high"));+ expect(finished).toBe(false);+ expect(f.menu()).toBe(menu);+ effortApplied.resolve();+ await Promise.all([done, competing]);+ expect(f.mode.completeModelSelection).toHaveBeenCalledOnce();+ expect(f.editorContainer.children).toEqual([f.editor]);+ expect(f.editor.getValue()).toBe("preserved draft");+});++it("leaves untouched effort to the normal model-switch default restoration", async () => {+ const f = await fixture();+ f.harness.session.settingsManager.setDefaultThinkingLevel("high");+ f.mode.completeModelSelection.mockImplementation(async () => {+ await f.harness.session.setModel(f.model);+ });+ const done = f.mode.showConfigurationMenu("models");+ f.menu().handleInput("\r");+ await done;+ expect(f.setThinkingLevel).not.toHaveBeenCalled();+ expect(f.harness.session.thinkingLevel).toBe("high");+});++it("keeps a failed effort selection open and allows retry", async () => {+ const f = await fixture();+ f.setThinkingLevel.mockRejectedValueOnce(new Error("effort update failed"));+ const done = f.mode.showConfigurationMenu("models");+ const menu = f.menu();+ menu.handleInput("\x1b[C");+ menu.handleInput("\r");+ await vi.waitFor(() => expect(f.mode.showError).toHaveBeenCalledWith("effort update failed"));+ expect(f.menu()).toBe(menu);+ menu.handleInput("\r");+ await done;+ expect(f.setThinkingLevel).toHaveBeenCalledTimes(2);+ expect(f.editorContainer.children).toEqual([f.editor]);+});++it.each([false, true])("edits search text with arrows for reasoning=%s", async (reasoning) => {+ const f = await fixture();+ const selected = vi.fn();+ const cancel = vi.fn();+ const model = reasoning ? f.model : f.harness.getModel("plain")!;+ const selector = new ModelSelectorComponent(+ { requestRender: () => {} } as TUI,+ model,+ f.harness.session.modelRegistry,+ [],+ selected,+ cancel,+ undefined,+ { availableModels: [model], thinkingLevel: "medium", inline: true },+ );+ selector.handleInput("re");+ selector.handleInput("\x1b[D");+ selector.handleInput("a");+ expect(selector.getSearchInput().getValue()).toBe("rae");+ selector.handleInput("\x1b[C");+ selector.handleInput("b");+ expect(selector.getSearchInput().getValue()).toBe("raeb");+ selector.handleInput("\x01");+ selector.handleInput("\x1b[D");+ expect(cancel).toHaveBeenCalledOnce();+ selector.getSearchInput().setValue("");+ selector.updateState(model, [model]);+ if (reasoning) {+ selector.handleInput("\x1b[C");+ selector.handleInput("\r");+ expect(selected).toHaveBeenLastCalledWith(model, "high");+ } else {+ selector.handleInput("\x1b[D");+ expect(cancel).toHaveBeenCalledTimes(2);+ }+});++it("does not publish the removed configuration tab action", () => {+ expect(Object.keys(KEYBINDINGS)).not.toContain("app.configuration.previousTab");+});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.tsindex 93b41ed17e..fd18b596cf 100644--- 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@@ -84,7 +84,7 @@ describe("ENG-4575 model authentication", () => {const unauthenticatedRow = lines.findIndex((line) => line.includes("requires-auth"));expect(authenticatedRow).toBeGreaterThanOrEqual(0);expect(authenticatedRow).toBeLessThan(unauthenticatedRow);- expect(lines[unauthenticatedRow]).toContain("current · sign in");+ expect(lines[unauthenticatedRow]).toContain("current · require sign in");selector.handleInput("\r");expect(selectedProvider).toBe(unauthenticated.provider);diff --git a/packages/coding-agent/test/suite/regressions/4658-onboarding-transitions.test.ts b/packages/coding-agent/test/suite/regressions/4658-onboarding-transitions.test.tsindex 1a1ce0f440..b4fedfadf0 100644--- a/packages/coding-agent/test/suite/regressions/4658-onboarding-transitions.test.ts+++ b/packages/coding-agent/test/suite/regressions/4658-onboarding-transitions.test.ts@@ -1,10 +1,10 @@-import { type Component, type OverlayHandle, setKeybindings, type TUI } from "@earendil-works/pi-tui";+import { Container, Input, setKeybindings, type TUI } from "@earendil-works/pi-tui";import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";import { KeybindingsManager } from "../../../src/core/keybindings.js";import type { ModelRegistry } from "../../../src/core/model-registry.js";import type { AgentConnectionModel } from "../../../src/modes/agent-connection/types.js";import type { AuthenticationResult } from "../../../src/modes/interactive/auth-flows.js";-import type { ConfigurationMenuComponent } from "../../../src/modes/interactive/components/configuration-menu.js";+import { ConfigurationMenuComponent } from "../../../src/modes/interactive/components/configuration-menu.js";import { InteractiveMode } from "../../../src/modes/interactive/interactive-mode.js";import { initTheme } from "../../../src/modes/interactive/theme/theme.js";import { createHarness, type Harness } from "../harness.js";@@ -30,6 +30,8 @@ interface InteractiveOnboardingHarness {interface ConfigurationHarness {showConfigurationMenu(tab: "providers" | "models" | "mcp-connections"): Promise<void>;+ editor: Input;+ editorContainer: Container;ui: TUI;uiServices: {modelRegistry: ModelRegistry;@@ -43,7 +45,6 @@ interface ConfigurationHarness {getLoginProviderOptions(): Array<{ id: string; name: string; authType: "api_key" }>;loginProvider(): Promise<AuthenticationResult>;};- showFullPaneOverlay(component: Component, width: number): OverlayHandle;showError(message: string): void;showStatus(message: string): void;}@@ -70,7 +71,7 @@ describe("ENG-4658 onboarding transitions", () => {}});- test("keeps the splash mounted until first-launch model selection closes", async () => {+ test("dismisses the splash before opening first-launch model selection inline", async () => {const harness = await createHarness({ provider: "prime-inference", withConfiguredAuth: false });harnesses.push(harness);const order: string[] = [];@@ -107,7 +108,7 @@ describe("ENG-4658 onboarding transitions", () => {const onboarding = fakeThis.runOnboardingFlow(false);await vi.waitFor(() => expect(fakeThis.showConfigurationMenu).toHaveBeenCalledWith("models"));- expect(order).not.toContain("dismiss");+ expect(order.slice(-2)).toEqual(["dismiss", "configuration:models"]);configuration.resolve();await onboarding;@@ -117,32 +118,25 @@ describe("ENG-4658 onboarding transitions", () => {"login","progress:Preparing models...","prepare",- "configuration:models","dismiss",+ "configuration:models",]);});- test("keeps the configuration overlay mounted while provider authentication is pending", async () => {+ test("keeps the inline picker mounted during authentication and restores the draft after closing", async () => {const harness = await createHarness();harnesses.push(harness);const login = deferred<AuthenticationResult>();- const setHidden = vi.fn();- const hide = vi.fn();- const focus = vi.fn();- let menu: ConfigurationMenuComponent | undefined;- const overlayHandle: OverlayHandle = {- hide,- setHidden,- isHidden: () => false,- focus,- unfocus: vi.fn(),- isFocused: () => true,- };const model = harness.getModel() as AgentConnectionModel;const fakeThis = Object.create(InteractiveMode.prototype) as ConfigurationHarness;+ fakeThis.editor = new Input();+ fakeThis.editor.setValue("draft prompt");+ fakeThis.editorContainer = new Container();+ fakeThis.editorContainer.addChild(fakeThis.editor);fakeThis.ui = {terminal: { rows: 24 },requestRender: vi.fn(),+ setFocus: vi.fn(),} as unknown as TUI;fakeThis.uiServices = {modelRegistry: harness.session.modelRegistry,@@ -156,24 +150,25 @@ describe("ENG-4658 onboarding transitions", () => {getLoginProviderOptions: () => [{ id: model.provider, name: model.provider, authType: "api_key" }],loginProvider: () => login.promise,});- fakeThis.showFullPaneOverlay = (component) => {- menu = component as ConfigurationMenuComponent;- return overlayHandle;- };fakeThis.showError = vi.fn();fakeThis.showStatus = vi.fn();const configuration = fakeThis.showConfigurationMenu("providers");- expect(menu).toBeDefined();- menu?.handleInput("\r");+ const menu = fakeThis.editorContainer.children[0] as ConfigurationMenuComponent;+ expect(menu).toBeInstanceOf(ConfigurationMenuComponent);+ menu.handleInput("\r");- expect(setHidden).not.toHaveBeenCalled();- expect(hide).not.toHaveBeenCalled();+ expect(fakeThis.editorContainer.children).toEqual([menu]);+ expect(fakeThis.editor.getValue()).toBe("draft prompt");login.resolve({ status: "cancelled" });- await vi.waitFor(() => expect(focus).toHaveBeenCalled());- menu?.handleInput("\x1b");+ await vi.waitFor(() => expect(fakeThis.ui.setFocus).toHaveBeenCalledTimes(2));+ expect(fakeThis.ui.setFocus).toHaveBeenLastCalledWith(menu);+ expect(fakeThis.editorContainer.children).toEqual([menu]);+ menu.handleInput("\x1b");await expect(configuration).resolves.toBeUndefined();- expect(hide).toHaveBeenCalledOnce();+ expect(fakeThis.editorContainer.children).toEqual([fakeThis.editor]);+ expect(fakeThis.ui.setFocus).toHaveBeenLastCalledWith(fakeThis.editor);+ expect(fakeThis.editor.getValue()).toBe("draft prompt");});});diff --git a/packages/coding-agent/test/theme-adaptive.test.ts b/packages/coding-agent/test/theme-adaptive.test.tsindex c97015d981..6f7a3517c0 100644--- a/packages/coding-agent/test/theme-adaptive.test.ts+++ b/packages/coding-agent/test/theme-adaptive.test.ts@@ -307,6 +307,52 @@ describe("adaptive TUI theme colors", () => {expect(selection).toMatch(/\x1b\[48;2;\d+;\d+;\d+mx\x1b\[49m/);});+ it("blends the soft selection halfway toward the editor surface", () => {+ setDefaultTerminalColors({+ foreground: { r: 235, g: 219, b: 178 },+ background: { r: 29, g: 32, b: 33 },+ });++ const soft = theme.getSoftSelectionBackgroundColor()("x");+ expect(soft).toMatch(/\x1b\[48;2;\d+;\d+;\d+mx\x1b\[49m/);+ const selectionLuminance = extractRgbLuminance(theme.bg("selectedBg", "x"));+ const surfaceLuminance = extractRgbLuminance(theme.bg("userMessageBg", "x"));+ const softLuminance = extractRgbLuminance(soft);+ expect(softLuminance).toBeLessThan(selectionLuminance);+ expect(softLuminance).toBeGreaterThan(surfaceLuminance);+ expect(Math.abs(softLuminance - (selectionLuminance + surfaceLuminance) / 2)).toBeLessThan(1.5);+ });++ it("keeps the plain selection background for soft highlights when the terminal background is unknown", () => {+ expect(theme.getSoftSelectionBackgroundColor()("x")).toBe(theme.bg("selectedBg", "x"));+ });++ it("strengthens the soft selection when quantization collapses it into the editor surface", () => {+ // Prime selectedBg #222226 and userMessageBg #1a1a1f quantize to the same+ // 256-color cell for every blend alpha, so the soft highlight falls back+ // to the adaptive selection machinery to stay visible.+ setThemeInstance(+ new Theme(+ {} as ConstructorParameters<typeof Theme>[0],+ { selectedBg: "#222226", userMessageBg: "#1a1a1f" } as ConstructorParameters<typeof Theme>[1],+ "256color",+ ),+ );+ setDefaultTerminalColors({+ foreground: { r: 235, g: 219, b: 178 },+ background: { r: 29, g: 32, b: 33 },+ });++ const soft = theme.getSoftSelectionBackgroundColor()("x");+ const match = /48;5;(\d+)m/.exec(soft);+ if (!match) throw new Error(`Expected 256-color background escape, got: ${JSON.stringify(soft)}`);+ const surfaceMatch = /48;5;(\d+)m/.exec(theme.bg("userMessageBg", "x"));+ if (!surfaceMatch) throw new Error("Expected a 256-color editor surface escape");+ expect(Number(match[1])).not.toBe(Number(surfaceMatch[1]));++ initTheme("prime");+ });+it("uses COLORFGBG for automatic default theme selection when OSC colors are unavailable", () => {process.env.COLORFGBG = "0;15";clearDefaultTerminalColors();