Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
feat(picker): a compact inline dialog, because the dashboard was the defect
Jack Rudenko43218b4d0aa2
diff --git a/packages/cli/src/model-selector-discovery.test.ts b/packages/cli/src/model-selector-discovery.test.tsindex 0b058fab..8149f685 100644--- a/packages/cli/src/model-selector-discovery.test.ts+++ b/packages/cli/src/model-selector-discovery.test.ts@@ -102,6 +102,9 @@ function stubCatalog(rows: CatalogModel[] | null): CatalogClient {async searchModels() {return [];},+ servedByVendor() {+ return rows === null ? [] : rows;+ },};}diff --git a/packages/cli/src/model-selector.ts b/packages/cli/src/model-selector.tsindex b581806c..19778bc3 100644--- a/packages/cli/src/model-selector.ts+++ b/packages/cli/src/model-selector.ts@@ -17,6 +17,7 @@ import { confirm, input, search, select } from "@inquirer/prompts";import { lookupModel, lookupModelCapabilities } from "./adapters/model-catalog.js";import { credentials } from "./auth/credentials/authority.js";import { isSubscriptionProvider } from "./handlers/shared/remote-provider-types.js";+import { log } from "./logger.js";import {type AggregatorEntry,type ModelDoc,@@ -458,13 +459,54 @@ function sortModelsNewestFirst(models: ModelInfo[]): ModelInfo[] {* `pplx-embed`, then `bge`), and recurred each time, because a list is made in* more than one place. Every list either UI can render now returns through here.*- * Honest limit: `isChatCapable` is name-based, so `gemini-3.5-transcribe` still- * gets through (`transcribe` is in none of its patterns). Adding a pattern has a- * real false-positive risk on model names, and the catalog's own modality field- * can answer it properly — that is a models-index issue, not a CLI regex.+ * HONEST LIMIT, AND IT IS LOGGED RATHER THAN LEFT AS A COMMENT. `isChatCapable`+ * reads a model ID, and an ID is not a modality contract. The transcribe / voice+ * / video families now have patterns (`probe-discovery.ts`, which records why),+ * but a generator whose name says nothing — `seedance-2.5` (video),+ * `flux-2-pro` (image) — cannot be excluded without a vendor-family blacklist,+ * which is the workaround that has already recurred three times.+ *+ * The complete fix is a modality field on the slim catalog payload; `ModelDoc`+ * carries `capabilities.imageGeneration` / `audioInput` / `audioOutput` /+ * `embedding` and the slim entry carries none of them, so every aggregator-served+ * list is name-classified only. That is a models-index gap, filed there. What is+ * owed HERE is visibility, so the residue is named ONCE per process in the debug+ * log — a picker screenshot is otherwise the only place it shows up.*/export function toPickerRows(models: ModelInfo[]): ModelInfo[] {- return sortModelsNewestFirst(dedupeModels(models.filter((m) => isChatCapable(m.id))));+ const kept = sortModelsNewestFirst(dedupeModels(models.filter((m) => isChatCapable(m.id))));+ logModalityGapOnce(kept);+ return kept;+}++/** Names that are known non-chat but carry no modality signal in the ID itself. */+const UNINFERABLE_NON_CHAT = [/\bseedance\b/i, /\bflux\b/i, /\bveo\b/i, /\bimagen\b/i];++let _modalityGapLogged = false;++/**+ * Say in the log which rows survived the name filter but are known-suspect, and+ * say why nothing more can be done in this repo.+ *+ * ONCE per process: `toPickerRows` is the chokepoint for every list either UI+ * renders, so a per-call line would be dozens of identical lines per picker open.+ * It never writes to a terminal — `log()` goes to the debug file — because the+ * renderer owns the terminal while the picker is up.+ */+function logModalityGapOnce(kept: ModelInfo[]): void {+ if (_modalityGapLogged) return;+ const suspect = kept.filter((m) => UNINFERABLE_NON_CHAT.some((re) => re.test(m.id)));+ if (suspect.length === 0) return;+ _modalityGapLogged = true;+ log(+ `[Models] ${suspect.length} row(s) may not be chat models and cannot be classified from the id: ` ++ `${suspect+ .slice(0, 8)+ .map((m) => m.id)+ .join(+ ", "+ )}. The slim catalog carries no modality field — models-index gap, not a CLI regex.`+ );}/**@@ -1302,6 +1344,53 @@ export async function loadModelsForPickerProvider(}}+/**+ * The models a picker provider SERVES, from the catalog's local served-by index.+ *+ * The synchronous twin of `loadModelsForPickerProvider`, and the source of the+ * OpenTUI picker's ONE flat cross-provider list. It answers the same question+ * through the same two chokepoints (`toPickerRows`, `dedupeByProviderSpec`) and+ * differs in exactly one way: it never leaves the machine. That matters because+ * the flat list asks about every provider at once, and 22 concurrent+ * `?provider=` queries were measured taking 10 s and returning zero rows —+ * "this provider has no models", which is the defect this whole feature exists+ * to remove, manufactured by the fix for it.+ *+ * `servedByVendor` records why the served-by index is not a second authority.+ */+export function servedModelsForProvider(+ providerValue: string,+ catalog: CatalogClient+): ModelInfo[] {+ const firebaseSlug = pickerProviderToFirebaseSlug[providerValue] ?? providerValue;+ return dedupeByProviderSpec(+ providerValue,+ toPickerRows(catalog.servedByVendor(firebaseSlug).map(catalogModelToModelInfo))+ );+}++/**+ * The `provider@` shortcut a picker row prints in its provider column — `or@`,+ * `cx@`, `kc@`, `gk@`.+ *+ * DERIVED FROM THE DEFINITION, never a table. It is the SHORTEST spelling that+ * parses back to this provider, which is what makes the column double as a+ * lesson in the `provider@model` syntax the CLI already takes on argv, and what+ * makes it collision-proof where the old provider rail was not (the rail+ * truncated two different providers to the same `opencod…`).+ *+ * DELIBERATELY NOT `pickerModelPrefix`. That one applies the readability+ * OVERRIDES (`google@`, `openrouter@`) because it builds the spec the user will+ * copy off their screen; a fixed-width column wants the short form, and the full+ * spec is on the detail line one row below. Both derive from the same definition,+ * so neither can name a provider the other cannot.+ */+export function providerShortcut(providerValue: string): string {+ const def = getProviderByName(providerValue);+ const prefix = def?.shortestPrefix || def?.shortcuts?.[0];+ return prefix ? `${prefix}@` : `${providerValue}@`;+}+async function searchModelsForPickerProvider(providerValue: string,searchTerm: string,diff --git a/packages/cli/src/picker/DiscoveryNotice.tsx b/packages/cli/src/picker/DiscoveryNotice.tsxindex 8e67974a..b78ef1db 100644--- a/packages/cli/src/picker/DiscoveryNotice.tsx+++ b/packages/cli/src/picker/DiscoveryNotice.tsx@@ -28,6 +28,7 @@import type { ReactNode } from "react";import type { PickerDiscoveryOutcome } from "../model-selector.js";import { type BannerSeverity, ErrorBanner } from "../tui/components/ErrorBanner.js";+import { displayWidth } from "../tui/viz/text.js";/** What a notice is, before it is a component — pure, so it can be asserted. */export interface NoticeContent {@@ -36,7 +37,14 @@ export interface NoticeContent {lines: string[];/** A chip at the head of row one, e.g. `HTTP 401`. */badge?: string;- /** Drawn in the border, and only when the banner is bordered. */+ /**+ * The dialog's right-hand status — `live roster unavailable`, `empty roster`.+ *+ * It is the FIRST of the three encodings of one fact, and it is the loudest,+ * because a title in a border is read before anything inside it. The others are+ * the per-row `catalog` mark and the provenance sentence. All three derive from+ * this same `NoticeContent`, so they cannot disagree.+ */title: string;}@@ -62,17 +70,27 @@ function oneRow(line: string): string {/*** The provenance sentence — the line that says the list below is NOT the live- * roster.+ * roster, AND that being in the list does not mean it will run.*- * It is the third of the three encodings of that one fact (the panel title and the- * per-row `CAT` chip are the others), and it is never dropped, because it is the one- * the user's own report was about. It says the same thing- * `formatDiscoveryFailureNotice` says for the `catalog` fallback, so a reader who- * sees both the panel and the scrollback line reads one sentence twice rather than- * two sentences that have to be reconciled.+ * IT IS TWO CLAIMS, AND THE SECOND ONE IS THE ONE THAT WAS MISSING. The stderr+ * wording says where the rows came from ("cloud-catalog entries … not its live+ * roster"), which is a statement about provenance. What it never said is the+ * CONSEQUENCE: discovery failed because the credential was rejected, so nothing+ * has confirmed that this account can call any of these models. A reader who is+ * told only "these are catalog entries" reasonably concludes the list is merely+ * differently-sourced, picks one, and finds out at launch. So the sentence names+ * the count, the provenance and the risk in that order.+ *+ * This is the third of the three encodings of the same fact — the dialog title+ * (`live roster unavailable`), the per-row `catalog` mark, and this — and all+ * three derive from ONE value, the outcome variant, so they cannot disagree.*/-function provenance(displayName: string): string {- return `Showing ${displayName}'s cloud-catalog entries below — not its live roster.`;+function provenance(displayName: string, rows: number): string {+ const n = rows === 1 ? "row" : "rows";+ return (+ `The ${rows} ${n} below are catalog entries, not ${displayName}'s live roster — ` ++ "they do not confirm access, so launching one may still fail."+ );}/**@@ -104,8 +122,8 @@ export function discoveryNoticeContent(}/** What to say when nothing supplied a fallback list either. */-function nextStep(hasFallback: boolean, displayName: string): string {- return hasFallback ? provenance(displayName) : "Press c to type a model id directly.";+function nextStep(rows: number, displayName: string): string {+ return rows > 0 ? provenance(displayName, rows) : "Press c to type a model id directly.";}type Failed = Extract<PickerDiscoveryOutcome, { kind: "failed" }>;@@ -119,21 +137,34 @@ type Collapsed = Extract<PickerDiscoveryOutcome, { kind: "collapsed-empty" }>;* and the scrollback line cannot drift apart. All that happens here is one row per* line, and the HTTP status moved into a chip.*/-function failedContent({ failure, notice, fallbackRows }: Failed, _name: string): NoticeContent {+function failedContent({ failure, notice, fallbackRows }: Failed, name: string): NoticeContent {const badge = failure.status === undefined ? undefined : `HTTP ${failure.status}`;const lines: string[] = [];for (const raw of notice) {const line = oneRow(raw);if (line === "") continue;+ // The formatter's own closing line is REPLACED, not appended to. It says where+ // the rows came from and stops there; the panel's version says what that means+ // for the user's next keystroke (`provenance`, above). Two sentences making+ // overlapping claims about the same list is exactly the reconciliation this+ // file exists to avoid, so the shorter one gives way here — and the stderr path+ // keeps it verbatim, which is the whole reason the formatter and the sink are+ // separate.+ if (/^Showing .* not its live roster\.$/.test(line)) continue;+ if (line === "Falling back to manual model entry.") continue;// De-duplicate the status: it is the badge now, and spending nine columns of a// 78-column headline saying it twice costs the end of the sentence.lines.push(badge === undefined ? line : line.replace(` (${badge})`, ""));}+ lines.push(nextStep(fallbackRows.length, name));return {severity: "error",lines,...(badge === undefined ? {} : { badge }),- title: fallbackRows.length > 0 ? "discovery failed · showing catalog" : "discovery failed",+ // The dialog RIGHT-hand status. "unavailable" rather than "failed": the+ // provider is not broken, claudish could not read its roster, and the two read+ // very differently to someone deciding whether to trust the rows below.+ title: "live roster unavailable",};}@@ -149,7 +180,7 @@ function emptyRosterContent({ failure, fallbackRows }: EmptyRoster, name: stringseverity: "notice",lines: [`${name}'s model list is empty${at} and listed nothing.`,- nextStep(fallbackRows.length > 0, name),+ nextStep(fallbackRows.length, name),],title: "empty roster",};@@ -168,7 +199,7 @@ function allFilteredContent(`${name} served ${servedCount} model${servedCount === 1 ? "" : "s"}, none of them chat-capable.`,];if (sampleIds.length > 0) lines.push(`e.g. ${sampleIds.join(", ")}`);- lines.push(nextStep(fallbackRows.length > 0, name));+ lines.push(nextStep(fallbackRows.length, name));return { severity: "notice", lines, title: "nothing chat-capable" };}@@ -177,7 +208,7 @@ function collapsedContent({ chatCount, fallbackRows }: Collapsed, name: string):const lines = [`${chatCount} chat-capable model${chatCount === 1 ? "" : "s"} collapsed to zero choices — please report this.`,];- if (fallbackRows.length > 0) lines.push(provenance(name));+ if (fallbackRows.length > 0) lines.push(provenance(name, fallbackRows.length));return { severity: "notice", lines, title: "no choices" };}@@ -205,49 +236,105 @@ export function mergeCredentialLines(lines: string[], width: number): string[] {return [...lines.slice(0, i), merged, ...lines.slice(i + 2)];}+/**+ * Greedy word wrap, measured in CELLS.+ *+ * `ErrorBanner` deliberately does not wrap — it truncates, so a JSON body cannot+ * spill three rows mid-token — and that is right for a headline whose tail is an+ * upstream payload. It is wrong for the provenance sentence, whose tail ("so+ * launching one may still fail") is the single most useful clause in the state and+ * the one a truncation would take first. So the caller wraps, and the banner still+ * truncates whatever a wrap could not fix.+ *+ * Built on `displayWidth` rather than `String.length`: a CJK model id counts double+ * in cells and half in code units, which is the same reason `padEnd`/`slice` are+ * banned in `viz/text.ts`.+ */+export function wrapWords(text: string, width: number): string[] {+ const w = Math.max(8, Math.floor(width));+ if (displayWidth(text) <= w) return [text];+ const out: string[] = [];+ let line = "";+ for (const word of text.split(/\s+/).filter(Boolean)) {+ const next = line === "" ? word : `${line} ${word}`;+ if (displayWidth(next) <= w) {+ line = next;+ continue;+ }+ if (line !== "") out.push(line);+ line = word;+ }+ if (line !== "") out.push(line);+ return out;+}++/**+ * The rows a notice will actually paint — merged, wrapped and capped.+ *+ * PURE, AND EXPORTED, because the dialog has to know the COUNT before it lays out:+ * the banner and the list share one inline row budget, and the rows that give way+ * are the list's. A component that only knew its own height would have to be+ * measured after the fact, which inline mode does not forgive.+ *+ * Lines past `maxRows` are dropped from the END, which is the priority order the+ * caller built them in: cause, then recovery, then provenance. Nothing is lost —+ * the full text goes to the deferred stderr write after teardown and to the debug+ * log.+ */+export function noticeRows(+ content: NoticeContent,+ width: number,+ maxRows: number+): { severity: BannerSeverity; badge?: string; lines: string[] } {+ const merged = mergeCredentialLines(content.lines, width);+ const wrapped: string[] = [];+ for (const [i, line] of merged.entries()) {+ // Row one carries the badge, so it wraps against a shorter width. It is also+ // the one line allowed to be truncated rather than wrapped: its tail is the+ // upstream error body, which reads no better across two rows than across one.+ if (i === 0) wrapped.push(line);+ else wrapped.push(...wrapWords(line, width));+ }+ return {+ severity: content.severity,+ ...(content.badge === undefined ? {} : { badge: content.badge }),+ lines: wrapped.slice(0, Math.max(1, Math.floor(maxRows))),+ };+}+export interface DiscoveryNoticeProps {outcome: PickerDiscoveryOutcome;displayName: string;- /** Usable columns, for truncation and for the merge decision. */+ /** Usable columns, for truncation, wrapping and the merge decision. */width: number;- /** Terminal rows, so the banner can choose its chrome budget. */- height: number;- /** Hard cap on content rows. 4 borderless, 6 inside a border. */- maxLines: number;- /** A full rounded border (2 rows) instead of the 1-column left rule (0 rows). */- bordered: boolean;+ /** Hard cap on content rows — the banner's half of the dialog's row budget. */+ maxRows: number;}/**- * THE BANNER'S ROW BUDGET IS A BUDGET, NOT A PRIORITY ORDER — four rows at- * `height < 30`, and the four lines that must never be dropped do not fit in four- * rows WITH a border (the border alone is two of them). That contradiction is- * resolved by measurement rather than by ranking: below 30 rows the banner is a- * 1-column left rule in the severity colour, which costs one COLUMN and zero ROWS.+ * The banner, inside the dialog, as a 1-column left rule in the severity colour.*- * Lines past `maxLines` are dropped from the END, which is the same order the design- * names — the upstream `detail` body goes first because it is already the tail of- * the truncated headline, then the sample ids. The full text is never lost: it goes- * to the deferred stderr write after teardown, and to the debug log.+ * BORDERLESS, UNCONDITIONALLY. The previous build gated a full border on terminal+ * height, which was one more responsive branch to reason about and to photograph.+ * Inside a dialog that already has a border, a second one is chrome around chrome:+ * the rule costs one COLUMN and zero ROWS, and rows are the scarce axis when the+ * whole thing is inline in someone's scrollback.*/export function DiscoveryNotice({outcome,displayName,width,- maxLines,- bordered,+ maxRows,}: DiscoveryNoticeProps): ReactNode {const content = discoveryNoticeContent(outcome, displayName);if (content === null) return null;- const merged = mergeCredentialLines(content.lines, width);+ const rows = noticeRows(content, width, maxRows);return (<ErrorBanner- severity={content.severity}- lines={merged.slice(0, Math.max(1, maxLines))}+ severity={rows.severity}+ lines={rows.lines}width={width}- title={content.title}- bordered={bordered}- {...(content.badge === undefined ? {} : { badge: content.badge })}+ {...(rows.badge === undefined ? {} : { badge: rows.badge })}/>);}diff --git a/packages/cli/src/picker/ModelPicker.test.tsx b/packages/cli/src/picker/ModelPicker.test.tsxindex 0ec8416c..882056c1 100644--- a/packages/cli/src/picker/ModelPicker.test.tsx+++ b/packages/cli/src/picker/ModelPicker.test.tsx@@ -7,13 +7,20 @@ import { describe, expect, test } from "bun:test";* unpainted filler and the assertion measures nothing.** TWO CAPTURES, TWO BLINDNESSES. `captureCharFrame()` sees text and layout and is- * BLIND to a heat row of coloured spaces and to a one-column stub of background left- * behind by a squeezed widget — a whole character-level suite once passed over a mangled- * row. `captureSpans()` sees colour, which is where the severity tiers and the gradient- * live. Both are used here, for the things each can decide.+ * BLIND to a wash of coloured spaces and to a one-column stub of background left+ * behind by a squeezed widget — a whole character-level suite once passed over a+ * mangled row. `captureSpans()` sees colour, which is where the severity tiers and+ * the selection wash live. Both are used here, for the things each can decide.*- * THE DATA SOURCE IS A PARAMETER, NEVER `mock.module()`: mocking shared infrastructure- * bleeds across Bun's module registry and breaks sibling e2e files.+ * THE ASSERTIONS THAT MATTER MOST ARE THE ONES ABOUT THE REJECTED BUILD. The owner's+ * report was "super unclear what is happening"; the diagnosis was two panes each+ * holding a cursor, and a meter on every row carrying a value that was identical on+ * 19 of 32 rows. So: exactly ONE cursor glyph on screen, and NO block-fill glyph in+ * any list row. Both are decidable from a frame, and both would have failed the+ * build that shipped.+ *+ * THE DATA SOURCE IS A PARAMETER, NEVER `mock.module()`: mocking shared+ * infrastructure bleeds across Bun's module registry and breaks sibling e2e files.*/import type { CapturedFrame } from "@opentui/core";import { testRender } from "@opentui/react/test-utils";@@ -21,13 +28,15 @@ import type { ReactNode } from "react";import type { ModelInfo, PickerDiscoveryOutcome } from "../model-selector.js";import { C } from "../tui/theme.js";import { ModelPicker } from "./ModelPicker.js";-import type { CatalogLoad, PickerDataSource, RailChoice } from "./PickerDataSource.js";+import { MAX_DIALOG_ROWS } from "./layout.js";+import type { PickerDataSource, PickerProviderChoice } from "./PickerDataSource.js";// ── a scriptable source ──────────────────────────────────────────────────────────-const rail = (over: Partial<RailChoice> = {}): RailChoice => ({+const provider = (over: Partial<PickerProviderChoice> = {}): PickerProviderChoice => ({value: "kimi",- label: "kimi",+ label: "Kimi / Moonshot",+ shortcut: "kimi@",description: "Direct API",billing: "metered",envVar: "MOONSHOT_API_KEY",@@ -49,63 +58,71 @@ const model = (over: Partial<ModelInfo> = {}): ModelInfo => ({});interface FakeOpts {- roster?: RailChoice[];+ roster?: PickerProviderChoice[];ready?: Record<string, boolean>;outcome?: PickerDiscoveryOutcome;- catalogRows?: ModelInfo[];+ /** Per-provider served lists; falls back to `served`. */+ byProvider?: Record<string, ModelInfo[]>;+ served?: ModelInfo[];/** Never settles — the in-flight states. */hang?: boolean;}function fakeSource(opts: FakeOpts = {}): PickerDataSource {- const roster = opts.roster ?? [rail()];+ const roster = opts.roster ?? [provider()];const never = new Promise<never>(() => {});return {providerRoster: () => roster,notEnabledLocalProviders: () => [],- displayName: (p) => (p === "kimi" ? "Kimi / Moonshot" : p),+ displayName: (p) => roster.find((r) => r.value === p)?.label ?? p,async *probeCredentials(names) {if (opts.hang) await never;for (const n of names) yield [n, opts.ready?.[n] ?? true] as [string, boolean];},- loadCatalog: (): Promise<CatalogLoad> =>- opts.hang ? never : Promise.resolve({ top: [], recommended: [] }),+ ensureCatalog: (): Promise<void> => (opts.hang ? never : Promise.resolve()),+ servedModels: (p) => opts.byProvider?.[p] ?? opts.served ?? [model()],discoverRoster: (): Promise<PickerDiscoveryOutcome> =>opts.hang? never: Promise.resolve(- opts.outcome ?? {- kind: "rows",- rows: [model()],- servedCount: 1,- chatCount: 1,- }+ opts.outcome ?? { kind: "rows", rows: [model()], servedCount: 1, chatCount: 1 }),- catalogModels: () => (opts.hang ? never : Promise.resolve(opts.catalogRows ?? [])),};}+interface Drawn {+ text: string[];+ frame: CapturedFrame;+ press: (keys: string[]) => Promise<void>;+ recapture: () => { text: string[]; frame: CapturedFrame };+ destroy: () => void;+}+/** Always destroy in `finally`: a leaked renderer keeps native threads alive and hangs `bun test`. */-async function draw(- node: ReactNode,- width = 80,- height = 24,- settleMs = 0-): Promise<{ text: string[]; frame: CapturedFrame }> {- const { renderOnce, captureCharFrame, captureSpans, renderer } = await testRender(node, {- width,- height,- });- try {+async function draw(node: ReactNode, width = 80, height = 24, settleMs = 30): Promise<Drawn> {+ const { renderOnce, captureCharFrame, captureSpans, renderer, mockInput } = await testRender(+ node,+ { width, height }+ );+ await renderOnce();+ if (settleMs > 0) {+ await new Promise((r) => setTimeout(r, settleMs));await renderOnce();- if (settleMs > 0) {- await new Promise((r) => setTimeout(r, settleMs));- await renderOnce();- }- return { text: captureCharFrame().split("\n"), frame: captureSpans() };- } finally {- renderer.destroy();}+ const recapture = (): { text: string[]; frame: CapturedFrame } => ({+ text: captureCharFrame().split("\n"),+ frame: captureSpans(),+ });+ return {+ ...recapture(),+ press: async (keys) => {+ await mockInput.pressKeys(keys as never);+ await new Promise((r) => setTimeout(r, 20));+ await renderOnce();+ },+ recapture,+ destroy: () => renderer.destroy(),+ };}const joined = (text: string[]): string => text.join("\n");@@ -113,53 +130,290 @@ const bgs = (f: CapturedFrame): Set<string> =>new Set(f.lines.flatMap((l) => l.spans.map((s) => s.bg.toInts().slice(0, 3).join())));const rgb = (hex: string): string =>[1, 3, 5].map((i) => Number.parseInt(hex.slice(i, i + 2), 16)).join();+/** Rows that carry painted content — the dialog's actual footprint. */+const painted = (text: string[]): string[] => text.filter((l) => l.trim() !== "");+/**+ * The frame with its border glyphs and line breaks flattened away.+ *+ * A wrapped sentence is still ONE sentence to the reader, and an assertion that+ * cannot see across a wrap would pass a build that had truncated the half that+ * matters.+ */+const flat = (text: string[]): string =>+ text+ .join(" ")+ .replace(/[│┃▌╭╮╰╯─]/g, " ")+ .replace(/\s+/g, " ");++// ── the shape of the thing ───────────────────────────────────────────────────────-// ── the first frame ──────────────────────────────────────────────────────────────+describe("the dialog", () => {+ test("is COMPACT and INLINE — it does not fill a 45-row terminal", async () => {+ // The whole correction, in one assertion. The rejected build was+ // `height={terminalHeight}` on the alternate screen; this one is a box that+ // leaves the user's shell on screen around it.+ const d = await draw(<ModelPicker source={fakeSource()} onDone={() => {}} />, 145, 45);+ try {+ expect(painted(d.text).length).toBeLessThanOrEqual(20);+ // …and it is horizontally bounded too, not a full-width strip.+ expect(Math.max(...painted(d.text).map((l) => l.trimEnd().length))).toBeLessThan(145);+ } finally {+ d.destroy();+ }+ });-describe("the first frame", () => {- test("lists EVERY pickable provider before any probe resolves", async () => {- // FR-1's structural half: the rail is derived synchronously, so a blank frame is- // not reachable — not "unlikely", not reachable.- const roster = ["openrouter", "google", "kimi"].map((v) => rail({ value: v, label: v }));- const { text } = await draw(- <ModelPicker source={fakeSource({ roster, hang: true })} onDone={() => {}} />+ test("has EXACTLY ONE cursor — the direct answer to “unclear what is happening”", async () => {+ // Two panes each held a cursor and only a border colour said which one the arrow+ // keys drove. One list, one `▶`.+ const roster = ["openrouter", "kimi", "google"].map((v) =>+ provider({ value: v, label: v, shortcut: `${v}@`, hasDiscovery: false })+ );+ const d = await draw(+ <ModelPicker+ source={fakeSource({+ roster,+ served: [model({ id: "a" }), model({ id: "b" })],+ })}+ onDone={() => {}}+ />+ );+ try {+ expect(joined(d.text).split("▶").length - 1).toBe(1);+ } finally {+ d.destroy();+ }+ });++ test("NO list row carries a bar, a gradient or a block fill", async () => {+ // The rejected build put a context meter and a price meter on every row because a+ // whole-frame graphics-density gate counted a row with a bar as a graphics row.+ // Of 32 visible rows, 19 read `1M` and their bars were indistinguishable.+ const d = await draw(+ <ModelPicker+ source={fakeSource({+ served: [+ model({ id: "a", contextLength: 1_000_000, context: "1M" }),+ model({ id: "b", contextLength: 8_000, context: "8K" }),+ ],+ })}+ onDone={() => {}}+ />);- for (const name of ["openrouter", "google", "kimi"]) {- expect(joined(text)).toContain(name);+ try {+ const rows = d.text.filter((l) => /\ba\b|\bb\b/.test(l));+ expect(rows.length).toBeGreaterThan(0);+ for (const row of rows) expect(row).not.toMatch(/[█▓▒░╌]/);+ } finally {+ d.destroy();}});test("no rendered row exceeds the frame width, at 80 and at 145", async () => {- for (const width of [80, 145]) {- const { text } = await draw(- <ModelPicker source={fakeSource()} onDone={() => {}} />,- width,- width === 80 ? 24 : 45,- 30- );- const over = text.filter((l) => l.length > width);- expect({ width, over }).toEqual({ width, over: [] });+ for (const [width, height] of [+ [80, 24],+ [145, 45],+ ] as const) {+ const d = await draw(<ModelPicker source={fakeSource()} onDone={() => {}} />, width, height);+ try {+ const over = d.text.filter((l) => l.length > width);+ expect({ width, over }).toEqual({ width, over: [] });+ } finally {+ d.destroy();+ }}});- test("the footer's hints are present and unclipped at 80×24", async () => {- const { text } = await draw(- <ModelPicker source={fakeSource()} onDone={() => {}} />,- 80,- 24,- 30+ test("the key hints are present and unclipped at 80×24", async () => {+ const d = await draw(<ModelPicker source={fakeSource()} onDone={() => {}} />);+ try {+ // The hints row is the last PAINTED row above the bottom border.+ const footer = painted(d.text).at(-2) ?? "";+ for (const hint of ["move", "select", "providers", "custom", "cancel"]) {+ expect(footer).toContain(hint);+ }+ } finally {+ d.destroy();+ }+ });+});++// ── one flat list, provider as a COLUMN ──────────────────────────────────────────++describe("the flat cross-provider list", () => {+ const roster = [+ provider({ value: "openrouter", label: "OpenRouter", shortcut: "or@", hasDiscovery: false }),+ provider({ value: "kimi-coding", label: "Kimi Coding", shortcut: "kc@", hasDiscovery: false }),+ ];++ test("merges every credentialled provider and prints the routing shortcut per row", async () => {+ const d = await draw(+ <ModelPicker+ source={fakeSource({+ roster,+ byProvider: {+ openrouter: [model({ id: "glm-5.3-flash" })],+ "kimi-coding": [model({ id: "kimi-k3" })],+ },+ })}+ onDone={() => {}}+ />);- // `captureCharFrame()` ends with a trailing newline, so the LAST element is "".- const footer = text.filter((l) => l.trim() !== "").pop() ?? "";- for (const hint of ["move", "select", "filter", "pane", "custom", "cancel"]) {- expect(footer).toContain(hint);+ try {+ const all = joined(d.text);+ expect(all).toContain("glm-5.3-flash");+ expect(all).toContain("kimi-k3");+ // The column teaches the `provider@model` syntax the CLI already takes on argv,+ // and `or@` vs `kc@` cannot collide the way two `opencod…` rail rows did.+ expect(all).toContain("or@");+ expect(all).toContain("kc@");+ } finally {+ d.destroy();+ }+ });++ test("a provider with no credential contributes NO rows, and the count says so", async () => {+ const d = await draw(+ <ModelPicker+ source={fakeSource({+ roster,+ ready: { openrouter: true, "kimi-coding": false },+ byProvider: {+ openrouter: [model({ id: "glm-5.3-flash" })],+ "kimi-coding": [model({ id: "kimi-k3" })],+ },+ })}+ onDone={() => {}}+ />+ );+ try {+ const all = joined(d.text);+ expect(all).toContain("glm-5.3-flash");+ expect(all).not.toContain("kimi-k3");+ // The absence is EXPLAINED, in the title, rather than silent.+ expect(all).toContain("1/2 providers");+ } finally {+ d.destroy();+ }+ });++ test("typing filters immediately — there is no search mode to enter", async () => {+ const d = await draw(+ <ModelPicker+ source={fakeSource({+ roster,+ byProvider: {+ openrouter: [model({ id: "glm-5.3-flash" })],+ "kimi-coding": [model({ id: "kimi-k3" })],+ },+ })}+ onDone={() => {}}+ />+ );+ try {+ await d.press(["g", "l", "m"]);+ const all = joined(d.recapture().text);+ expect(all).toContain("glm-5.3-flash");+ expect(all).not.toContain("kimi-k3");+ } finally {+ d.destroy();+ }+ });++ test("`/` makes the three letter commands typeable — `phi3` is a real model", async () => {+ // The one collision filter-first creates: `p` opens the provider dialog, so the+ // first keystroke of `phi3` would navigate instead of filter. `/` is the escape+ // hatch, and without a test it is the kind of thing that quietly stops working.+ const d = await draw(+ <ModelPicker+ source={fakeSource({+ roster,+ byProvider: {+ openrouter: [model({ id: "phi3" }), model({ id: "kimi-k3" })],+ "kimi-coding": [],+ },+ })}+ onDone={() => {}}+ />+ );+ try {+ // Bare `p` NAVIGATES — that is the collision, asserted so the escape hatch has+ // something to be an escape from.+ await d.press(["p"]);+ expect(joined(d.recapture().text)).toContain("have credentials");+ d.destroy();+ } finally {+ /* destroyed above; the second half needs a fresh tree */+ }+ const e = await draw(+ <ModelPicker+ source={fakeSource({+ roster,+ byProvider: {+ openrouter: [model({ id: "phi3" }), model({ id: "kimi-k3" })],+ "kimi-coding": [],+ },+ })}+ onDone={() => {}}+ />+ );+ try {+ await e.press(["/"]);+ await e.press(["p"]);+ await e.press(["h"]);+ const all = joined(e.recapture().text);+ expect(all).toContain("phi3");+ expect(all).not.toContain("kimi-k3");+ } finally {+ e.destroy();+ }+ });++ test("Enter returns the provider-scoped spec, never a bare model id", async () => {+ // A bare Claude-shaped name reaching `route()` degrades to OpenRouter, so the+ // picker must never emit one.+ let got: string | null | undefined;+ const d = await draw(+ <ModelPicker+ source={fakeSource({ roster, byProvider: { openrouter: [model({ id: "gpt-6" })] } })}+ onDone={(spec) => {+ got = spec;+ }}+ />+ );+ try {+ await d.press(["RETURN"]);+ // `openrouter@`, not the column's `or@`: `buildExplicitModelSpec` applies the+ // readability OVERRIDES because this is the string the user copies off their+ // screen, while a fixed-width column wants the short form. Both parse back to+ // the same provider — `providerShortcut` records why they differ.+ expect(got).toBe("openrouter@gpt-6");+ } finally {+ d.destroy();+ }+ });++ test("Escape with an empty filter CANCELS by returning null — never `process.exit`", async () => {+ let got: string | null | undefined;+ const d = await draw(+ <ModelPicker+ source={fakeSource({ roster })}+ onDone={(spec) => {+ got = spec;+ }}+ />+ );+ try {+ await d.press(["ESCAPE"]);+ expect(got).toBeNull();+ } finally {+ d.destroy();}});});// ── provenance: the user's actual complaint ──────────────────────────────────────-describe("a fallback list says it is a fallback", () => {+describe("a fallback list says it is a fallback — and that it may not work", () => {const failed: PickerDiscoveryOutcome = {kind: "failed",failure: {@@ -174,141 +428,180 @@ describe("a fallback list says it is a fallback", () => {" Get a key: https://platform.moonshot.cn/\n"," Showing Kimi / Moonshot's cloud-catalog entries below — not its live roster.\n\n",],- fallbackRows: [model()],+ fallbackRows: [model(), model({ id: "kimi-k2.6" })],};- test("the panel title, the per-row mark and the banner all say it", async () => {- const { text } = await draw(- <ModelPicker source={fakeSource({ outcome: failed })} onDone={() => {}} />,- 80,- 24,- 40+ /** Reach the scoped view: `p` opens the provider dialog, Enter scopes to row one. */+ async function scoped(outcome: PickerDiscoveryOutcome, width = 80, height = 24): Promise<Drawn> {+ const d = await draw(+ <ModelPicker source={fakeSource({ outcome })} onDone={() => {}} />,+ width,+ height);- const all = joined(text);- expect(all).toContain("cloud catalog (fallback)");- expect(all).toContain("cat");- expect(all).toContain("not its live roster");+ // TWO presses, not one batch: `useKeyboard` reads `view` from the render that+ // subscribed, so a batched `p`+Enter is handled entirely by the MODEL view's+ // closure and the provider dialog never sees the Enter. A real keyboard cannot+ // do that; `pressKeys` with no delay can.+ await d.press(["p"]);+ await d.press(["RETURN"]);+ await new Promise((r) => setTimeout(r, 40));+ return { ...d, ...d.recapture() };+ }++ test("the title, the per-row mark and the banner all say it", async () => {+ const d = await scoped(failed);+ try {+ const all = joined(d.text);+ expect(all).toContain("live roster unavailable");+ expect(all).toContain("catalog");+ // The sentence WRAPS across two rows, so it is matched against the frame with+ // its border glyphs and line breaks flattened away. A substring test over raw+ // rows would fail on the wrap and say nothing about whether a reader can read+ // it.+ expect(flat(d.text)).toContain("not Kimi / Moonshot's live roster");+ } finally {+ d.destroy();+ }});- test("a LIVE roster carries no mark and no fallback title — which is what makes the mark a signal", async () => {- const { text } = await draw(- <ModelPicker source={fakeSource()} onDone={() => {}} />,- 80,- 24,- 40- );- const all = joined(text);- expect(all).toContain("live roster");- expect(all).not.toContain("fallback");- // The mark's COLUMN is reserved on both kinds of list so the cells left of it do- // not move; what a live row must not carry is the word.- expect(all.split("\n").filter((l) => /\bcat\b/.test(l))).toEqual([]);+ test("THE HONESTY LINE IS ON SCREEN AT 80 COLUMNS", async () => {+ // Neither the shipped build nor the rejected one said this. Catalog rows are not+ // merely differently-sourced: discovery failed on the credential, so nothing has+ // confirmed the account can call any of them.+ const d = await scoped(failed);+ try {+ expect(joined(d.text)).toContain("may still fail");+ } finally {+ d.destroy();+ }});- test("the failed banner names the provider, the kind, the env var and the key URL", async () => {- const { text } = await draw(- <ModelPicker source={fakeSource({ outcome: failed })} onDone={() => {}} />,- 145,- 45,- 40- );- const all = joined(text);- expect(all).toContain("Kimi / Moonshot");- expect(all).toContain("the API key was rejected");- expect(all).toContain("MOONSHOT_API_KEY");- expect(all).toContain("platform.moonshot.cn");+ test("the banner names the provider, the cause, the env var and the key URL", async () => {+ const d = await scoped(failed, 145, 45);+ try {+ const all = joined(d.text);+ expect(all).toContain("Kimi / Moonshot");+ expect(all).toContain("the API key was rejected");+ expect(all).toContain("MOONSHOT_API_KEY");+ expect(all).toContain("platform.moonshot.cn");+ } finally {+ d.destroy();+ }});- test("the banner never exceeds four rows on a short terminal", async () => {- const { text } = await draw(- <ModelPicker source={fakeSource({ outcome: failed })} onDone={() => {}} />,- 80,- 24,- 40- );- // The banner sits between the panes and the footer; count the rows carrying its- // left rule. Four is the whole budget at `height < 30`, chrome included.- const ruled = text.filter((l) => l.trimStart().startsWith("│") && l.includes("Moonshot"));- expect(ruled.length).toBeLessThanOrEqual(4);+ test("`r retry` is offered — the rejected build had no way back from a failure", async () => {+ const d = await scoped(failed);+ try {+ expect(joined(d.text)).toContain("retry");+ } finally {+ d.destroy();+ }+ });++ test("a LIVE roster carries no mark — which is what makes the mark a signal", async () => {+ const d = await scoped({+ kind: "rows",+ rows: [model()],+ servedCount: 1,+ chatCount: 1,+ });+ try {+ expect(joined(d.text)).not.toContain("catalog");+ } finally {+ d.destroy();+ }+ });++ test("a banner NEVER makes the dialog taller — its rows come out of the list's", async () => {+ // The inline-mode bound. `main-screen` reserves rows by scrolling the user's+ // terminal, so the dialog is allowed to shrink below its cap (a four-row+ // fallback list should look like four rows) but never to exceed it.+ const withBanner = await scoped(failed);+ try {+ expect(painted(withBanner.text).length).toBeLessThanOrEqual(MAX_DIALOG_ROWS);+ } finally {+ withBanner.destroy();+ }});test("`empty-roster` renders in the NOTICE tier, without the error wash", async () => {// `captureCharFrame` is blind to this: the two tiers differ in COLOUR as well as in// words, and the colour is the half a reader sees first.- const empty: PickerDiscoveryOutcome = {+ const failedFrame = await scoped(failed);+ const failedBgs = bgs(failedFrame.frame);+ failedFrame.destroy();+ const emptyFrame = await scoped({kind: "empty-roster",failure: { kind: "empty-roster", provider: "kimi", endpoint: "https://api.test/v1/models" },fallbackRows: [model()],- };- const failedFrame = await draw(- <ModelPicker source={fakeSource({ outcome: failed })} onDone={() => {}} />,- 80,- 24,- 40- );- const emptyFrame = await draw(- <ModelPicker source={fakeSource({ outcome: empty })} onDone={() => {}} />,- 80,- 24,- 40- );- expect(bgs(failedFrame.frame).has(rgb(C.bgError))).toBe(true);- expect(bgs(emptyFrame.frame).has(rgb(C.bgError))).toBe(false);- expect(joined(emptyFrame.text)).toContain("empty");+ });+ try {+ expect(failedBgs.has(rgb(C.bgError))).toBe(true);+ expect(bgs(emptyFrame.frame).has(rgb(C.bgError))).toBe(false);+ expect(joined(emptyFrame.text)).toContain("empty");+ } finally {+ emptyFrame.destroy();+ }});});-// ── colour, which only spans can see ─────────────────────────────────────────────+// ── the provider dialog, which replaced the rail ─────────────────────────────────-describe("the context meter is a real gradient", () => {- test("a wide row's filled cells carry many distinct colours", async () => {- // The negative control against a flat one-colour bar and against a four-glyph- // `░▒▓█` ramp — both score 1 here.- const rows = [- model({ id: "a", contextLength: 1_000_000, context: "1M" }),- model({ id: "b", contextLength: 8_000, context: "8K" }),+describe("the provider dialog", () => {+ test("`p` lists every provider at FULL WIDTH, credentials and counts included", async () => {+ // The rail truncated two different providers to the same `opencod…`. A dialog at+ // 76 columns cannot.+ const roster = [+ provider({+ value: "opencode-zen",+ label: "OpenCode Zen",+ shortcut: "zen@",+ hasDiscovery: false,+ }),+ provider({+ value: "opencode-zen-go",+ label: "OpenCode Zen Go",+ shortcut: "zengo@",+ hasDiscovery: false,+ }),];- const { frame } = await draw(+ const d = await draw(<ModelPicker- source={fakeSource({- outcome: { kind: "rows", rows: [rows[0]!, rows[1]!], servedCount: 2, chatCount: 2 },- })}+ source={fakeSource({ roster, ready: { "opencode-zen-go": false } })}onDone={() => {}}- />,- 145,- 45,- 40+ />);- const fgs = new Set(- frame.lines- .filter((l) => l.spans.some((s) => s.text.includes("█")))- .flatMap((l) =>- l.spans.filter((s) => s.text.includes("█")).map((s) => s.fg.toInts().join())- )- );- expect(fgs.size).toBeGreaterThanOrEqual(12);+ try {+ await d.press(["p"]);+ const all = joined(d.recapture().text);+ expect(all).toContain("OpenCode Zen");+ expect(all).toContain("OpenCode Zen Go");+ // The absence is explained with the exact variable to inspect.+ expect(all).toContain("MOONSHOT_API_KEY");+ expect(all).toContain("1 of 2 have credentials");+ } finally {+ d.destroy();+ }});});-// ── the rail's steady state ──────────────────────────────────────────────────────+// ── the loading dialog ───────────────────────────────────────────────────────────-describe("the rail", () => {- test("collapses unready providers into ONE summary row rather than listing them", async () => {- const roster = ["openrouter", "google", "kimi"].map((v) => rail({ value: v, label: v }));- const { text } = await draw(- <ModelPicker- source={fakeSource({ roster, ready: { openrouter: true, google: false, kimi: false } })}- onDone={() => {}}- />,+describe("the loading dialog", () => {+ test("names what it is waiting for rather than spinning", async () => {+ const d = await draw(+ <ModelPicker source={fakeSource({ hang: true })} onDone={() => {}} />,80,24,- 40+ 0);- const all = joined(text);- expect(all).toContain("openrouter");- expect(all).toContain("+2 need a key");- // The two unready ones are ABSENT from the rail, not listed and greyed — the steady- // state matches the roster the old picker showed.- expect(all).not.toContain("google");+ try {+ const all = joined(d.text);+ expect(all).toContain("credentials");+ expect(all).toContain("cloud catalog");+ expect(all).toContain("models appear as soon as they are ready");+ } finally {+ d.destroy();+ }});});diff --git a/packages/cli/src/picker/ModelPicker.tsx b/packages/cli/src/picker/ModelPicker.tsxindex aefd1192..aedd43ad 100644--- a/packages/cli/src/picker/ModelPicker.tsx+++ b/packages/cli/src/picker/ModelPicker.tsx@@ -1,115 +1,112 @@/** @jsxImportSource @opentui/react *//**- * picker/ModelPicker.tsx — the picker itself: two panes, one keyboard handler, and- * nothing else.+ * picker/ModelPicker.tsx — one inline dialog, one list, one cursor.*- * THIS FILE IS THE PROOF OF THE `tui/` STRUCTURE RULE, which is why it holds so- * little. The three async domains live in three hooks (`usePickerProviders`,- * `useCatalogModels`, `useProviderDiscovery`); the column arithmetic lives in- * `layout.ts`; the rows, the chrome, the stats panel and the notice are each their- * own module. What is left here is `filter`, `cursor`, `pane`, `selected`, one- * `useKeyboard`, and composition JSX. If the rule were unusable it would show up- * here first.+ * WHAT THIS FILE IS A CORRECTION OF. The first build of this picker was a+ * full-screen two-pane dashboard: a provider rail beside a model list, a gradient+ * context meter and a gradient price meter on every row, an aggregate-distribution+ * panel, and a five-tier responsive column ladder to keep all of it on an+ * 80-column terminal. The owner's verdict, verbatim: *"no no no this is super+ * unclear what is happening, that should be dialog style"*. A three-model design+ * panel then voted unanimously that the form, not the engineering, was the defect.*- * NO AWAIT IS EVER SILENT, STRUCTURALLY RATHER THAN BY DILIGENCE. The rail is- * derived synchronously, so the first frame is complete before any effect runs; every- * loader is an effect; and every in-flight task draws an affordance whose SHAPE is- * chosen by what the caller can actually measure — a determinate meter for the- * credential fan-out (work done over work total), an elapsed-vs-deadline bar for the- * one discovery path that has a published deadline, and an elapsed-only shimmer for- * the three that do not. Nothing invents a denominator.+ * THE ROOT CAUSE IS MEASURABLE, WHICH IS WHY IT IS WORTH WRITING DOWN. The house+ * TUI guidance requires that over half of a whole frame be graphics rows. On a+ * screen whose content IS a list, a row counts as a graphics row only if it+ * carries a bar — so the gate did not permit a meter on every row, it REQUIRED+ * one. The result, measured on the rejected capture: of 32 visible rows 19 read+ * `1M`, and their meters were indistinguishable. The loudest element on the screen+ * carried the least information, and the aggregate panel above it was added (by+ * its own file header) pre-emptively to top up the same count. The gate is for+ * persistent monitoring surfaces. A picker is a one-shot question.*- * CANCELLATION RETURNS A VALUE. Esc and Ctrl+C both call `onDone(null)`; nothing here- * calls `process.exit`. The bootstrap's `finally` unmounts React and destroys the- * renderer in that order, which is what restores the terminal with a fetch still in- * flight.+ * THREE STRUCTURAL DECISIONS FOLLOW, and each one deletes a class of defect:+ *+ * 1. **Inline** (`screenMode: "main-screen"`). The shell prompt and the claudish+ * banner stay on screen above the dialog. It reads as a program ASKING+ * something rather than as a program that has taken the terminal, and the+ * guidance's own `screenMode` table assigns inline to a one-shot command.+ * 2. **One flat cross-provider list.** Two panes meant two cursors with only a+ * border colour to say which one the arrow keys drove — the literal cause of+ * "unclear what is happening". The provider becomes a COLUMN, printed as the+ * routing shortcut the user could have typed (`or@`, `kc@`, `gk@`), which also+ * kills the truncation collision that rendered two different providers as+ * `opencod…`. Filtering on `kc` scopes to Kimi Coding faster than a rail ever+ * did.+ * 3. **No per-row graphics.** Plain aligned columns; colour reserved for meaning,+ * one meaning each (`rows.tsx` lists them). The one meter left in the picker is+ * the credential sweep's `done/total`, which is real progress over countable+ * work.+ *+ * NO AWAIT IS EVER SILENT, STRUCTURALLY RATHER THAN BY DILIGENCE. The roster is+ * derived synchronously, so the first frame is complete before any effect runs;+ * every loader is an effect; and every in-flight task draws an affordance whose+ * SHAPE is chosen by what the caller can actually measure. Nothing invents a+ * denominator.+ *+ * CANCELLATION RETURNS A VALUE. Esc and Ctrl+C both call `onDone(null)`; nothing+ * here calls `process.exit`. The bootstrap's `finally` unmounts React and destroys+ * the renderer in that order, which is what restores the terminal with a fetch+ * still in flight.+ *+ * NO BRANDING IS DRAWN HERE. `printLogo` already wrote the wordmark, `Claude Code.+ * Any Model.` and the version to the scrollback before this renderer opened, and+ * inline mode keeps them on screen — so a second miniature wordmark inside the+ * dialog would be claudish reinventing a logo it already has. The dialog's title+ * bar is a panel title, not a mark.*/-import type { ScrollBoxRenderable } from "@opentui/core";import { useKeyboard, useTerminalDimensions } from "@opentui/react";-import { type ReactNode, useEffect, useMemo, useRef, useState } from "react";-import {- type ModelInfo,- buildExplicitModelSpec,- resolveProviderDisplayPrice,- resolveProviderExternalId,-} from "../model-selector.js";+import { type ReactNode, useEffect, useMemo, useState } from "react";+import type { ModelInfo } from "../model-selector.js";import { EmptyState } from "../tui/components/EmptyState.js";-import { ErrorBanner } from "../tui/components/ErrorBanner.js";import { useAnimationFrame } from "../tui/hooks/useAnimationFrame.js";-import { C } from "../tui/theme.js";-import { truncate } from "../tui/viz/text.js";import { tokens } from "../tui/viz/tokens.js";-import { Panel } from "../tui/viz/widgets.js";-import { DiscoveryNotice } from "./DiscoveryNotice.js";+import { DiscoveryNotice, discoveryNoticeContent, noticeRows } from "./DiscoveryNotice.js";import {DISCOVERY_DEADLINE_MS,type DiscoveryShape,type PickerDataSource,} from "./PickerDataSource.js";-import { StatsStrip } from "./StatsStrip.js";-import { FilterStrip, LoadBar, type LoadTask, PickerFooter, PickerHeader } from "./chrome.js";-import { ModelDetail, ProviderDetail } from "./detail.js";-import { useCatalogModels } from "./hooks/useCatalogModels.js";-import { useDelayedVisible } from "./hooks/useDelayedVisible.js";+import { Dialog, FilterRow, Hints, type LoadTask, LoadTasks, Rule } from "./chrome.js";+import { SelectionLine } from "./detail.js";+import { type PickerRow, toPickerRow, usePickerModels } from "./hooks/usePickerModels.js";import { usePickerProviders } from "./hooks/usePickerProviders.js";import { useProviderDiscovery } from "./hooks/useProviderDiscovery.js";-import { CHROME, derivePanes, deriveRailLayout, deriveRowLayout } from "./layout.js";-import {- type ListOrigin,- ModelRow,- ProviderRailRow,- RailHintRow,- contextMeterPct,- parseDisplayPrice,- priceMeterPct,-} from "./rows.js";--/**- * A quiet scrollbar, built PER CALL — `tokens.*` are reassigned in place on theme- * detection, so a module-level object would copy the strings and pin the dark track- * onto a light panel. Lifted from `resume-picker.tsx:636-641`, which learned it the- * same way.- */-function scrollbarOptions() {- return {- showArrows: false,- trackOptions: { backgroundColor: tokens.bgPanel, foregroundColor: tokens.border },- } as const;-}+import { deriveDialogLayout, deriveRowLayout, scrollWindow } from "./layout.js";+import { ColumnHeader, HintRow, ModelRow, ProviderRow } from "./rows.js";/*** WHICH AFFORDANCE EACH IN-FLIGHT TASK EARNS — the honesty contract, as one pure* function so it can be asserted without a renderer.*- * The credential sweep is the only task with a real denominator: the roster is derived- * synchronously, so `done/total` is work done over work TOTAL. The GET half of- * discovery has a published DEADLINE and gets an elapsed-vs-deadline bar whose label- * says `deadline`, because a deadline is not progress. Everything else gets an elapsed- * figure and a shimmer, which claims only that time is passing.+ * The credential sweep is the only task with a real denominator: the roster is+ * derived synchronously, so `done/total` is work done over work TOTAL. The GET half+ * of discovery has a published DEADLINE and gets an elapsed-vs-deadline bar whose+ * label says `deadline`, because a deadline is not progress. Everything else gets an+ * elapsed figure and a shimmer, which claims only that time is passing.*- * There is deliberately NO `resolving prices` task. `buildDiscoveredModelOutcome`- * resolves pricing inside the same await as the roster (the fallback leg it already- * needed supplies it), so there is no second phase — and drawing a label for a phase- * that never runs is the same lie as an invented denominator.+ * There is deliberately NO `resolving prices` task. `servedModels` resolves pricing+ * from the same local index the rows came from, so there is no second phase — and+ * drawing a label for a phase that never runs is the same lie as an invented+ * denominator.*/export function buildLoadTasks(input: {creds: { done: number; total: number } | null;catalog: boolean;roster: { displayName: string; shape: DiscoveryShape; elapsed: number } | null;- vendor: string | null;}): LoadTask[] {const tasks: LoadTask[] = [];if (input.creds) {const { done, total } = input.creds;tasks.push({id: "creds",- label: "checking credentials",+ label: "credentials",pct: total > 0 ? (100 * done) / total : 0,- value: `${done}/${total}`,+ value: `${done}/${total} checked`,});}- if (input.catalog) tasks.push({ id: "catalog", label: "cloud catalog" });+ if (input.catalog) tasks.push({ id: "catalog", label: "cloud catalog", value: "fetching…" });if (input.roster) {const { displayName, shape, elapsed } = input.roster;const secs = `${(elapsed / 1000).toFixed(1)}s`;@@ -117,18 +114,13 @@ export function buildLoadTasks(input: {shape === "deadline"? {id: "roster",- // `deadline` rather than `roster · deadline`: MEASURED at 145 columns with- // three tasks sharing the row, the longer label truncated to- // `OpenRouter roster · …` — dropping the one word that says this bar is a- // clock and not a count of work done. The shortest label that keeps it wins.- label: `${displayName} deadline`,+ label: displayName,pct: Math.min(100, (100 * elapsed) / DISCOVERY_DEADLINE_MS),- value: `${secs} / ${(DISCOVERY_DEADLINE_MS / 1000).toFixed(1)}s`,+ value: `${secs} / ${(DISCOVERY_DEADLINE_MS / 1000).toFixed(1)}s deadline`,}- : { id: "roster", label: `${displayName} roster`, value: secs }+ : { id: "roster", label: displayName, value: `discovering… ${secs}` });}- if (input.vendor !== null) tasks.push({ id: "vendor", label: `${input.vendor} catalog` });return tasks;}@@ -140,486 +132,523 @@ export interface ModelPickerProps {onDiscoveryFailure?: (provider: string, notice: readonly string[]) => void;}-type Pane = "providers" | "models";-type Mode = "browse" | "filter" | "custom";+/**+ * Which dialog is on screen. ONE at a time, and one keyboard owner each — there is+ * never a second cursor to disambiguate.+ */+type View = "models" | "providers" | "custom";export function ModelPicker({ source, onDone, onDiscoveryFailure }: ModelPickerProps): ReactNode {const { width, height } = useTerminalDimensions();const providers = usePickerProviders(source);+ const catalog = usePickerModels(source, providers.roster, providers.readySet);- const [selected, setSelected] = useState<string | null>(null);- const [pane, setPane] = useState<Pane>("models");- const [mode, setMode] = useState<Mode>("browse");+ const [view, setView] = useState<View>("models");const [filter, setFilter] = useState("");+ /**+ * `/` was pressed: every printable key types, INCLUDING `p`, `c` and `r`.+ *+ * It exists for exactly one case, and that case is real: `phi3` is an Ollama+ * model, and with the three letter commands live on an empty filter its first+ * keystroke would open the provider dialog instead. `/` is the escape hatch the+ * design names, and it costs nothing when it is not needed — a filter with+ * anything in it already types every key.+ */+ const [typing, setTyping] = useState(false);const [custom, setCustom] = useState("");- const [modelCursor, setModelCursor] = useState(0);- const [showMissing, setShowMissing] = useState(false);-- // A provider whose probe came back `missing` is collapsed out of the rail, so the- // cursor is pinned to a provider VALUE rather than to an index: an index would slide- // under the user as ~30 probes settle during the first second.- const railRows = useMemo(- () =>- providers.rows.filter(- (r) => r.readiness !== "missing" || showMissing || r.value === selected- ),- [providers.rows, showMissing, selected]- );- const current = selected ?? railRows[0]?.value ?? null;- const currentRow = providers.rows.find((r) => r.value === current) ?? null;- const displayName = current === null ? "" : source.displayName(current);- const hasDiscovery = currentRow?.hasDiscovery === true;+ const [cursor, setCursor] = useState(0);+ const [providerCursor, setProviderCursor] = useState(0);+ /** `null` = the flat cross-provider list; a name = scoped to that provider. */+ const [scope, setScope] = useState<string | null>(null);- const discovery = useProviderDiscovery(source, current, hasDiscovery, onDiscoveryFailure);- const { catalog, list } = useCatalogModels(source, current, !hasDiscovery);+ const scopedChoice = providers.roster.find((r) => r.value === scope) ?? null;+ const scopedName = scope === null ? "" : source.displayName(scope);+ const hasDiscovery = scopedChoice?.hasDiscovery === true;+ const discovery = useProviderDiscovery(source, scope, hasDiscovery, onDiscoveryFailure);// ── which list is on screen, and where it came from ──────────────────────────//// PROVENANCE IS A PROPERTY OF THE LIST, NOT OF A ROW. One value decides all three- // encodings — the panel title, the per-row `CAT` chip and the banner's provenance- // sentence — so they cannot disagree with each other. Sniffing `ModelInfo.source`- // or `providerSlug` was the alternative and was wrong: `source` is a display label- // set on BOTH paths, and `providerSlug` is set only by the catalog converters, so- // the discriminant would have been the absence of an optional field.- const listSource: { rows: ModelInfo[]; origin: ListOrigin; fallback: boolean; loading: boolean } =- useMemo(() => {- if (hasDiscovery) {- const o = discovery.outcome;- if (o === null) return { rows: [], origin: "roster", fallback: false, loading: true };- if (o.kind === "rows")- return { rows: o.rows, origin: "roster", fallback: false, loading: false };- if (o.kind === "unsupported")- return { rows: [], origin: "catalog", fallback: false, loading: false };- return { rows: o.fallbackRows, origin: "catalog", fallback: true, loading: false };- }- return {- rows: list.rows,- origin: "catalog",- fallback: false,- loading: list.phase === "loading",- };- }, [hasDiscovery, discovery.outcome, list.rows, list.phase]);+ // encodings — the dialog's status title, the per-row `catalog` mark and the+ // banner's provenance sentence — so they cannot disagree with each other.+ //+ // The UNSCOPED list is catalog-derived too, and is deliberately NOT marked. A+ // mark means "the live roster was asked for and could not be had"; nothing asked+ // for a live roster here, so marking every row would spend the loudest signal in+ // the feature on the ordinary case and teach the reader to ignore it.+ const list = useMemo((): { rows: RowView[]; fallback: boolean; loading: boolean } => {+ if (scope === null) {+ return { rows: catalog.rows, fallback: false, loading: catalog.phase !== "ready" };+ }+ // A DISCOVERED ROSTER AND A CATALOG LIST GO THROUGH THE SAME ROW BUILDER, so a+ // fallback list cannot be distinguishable by accident — a different price+ // string or a different spec spelling — instead of by the three deliberate+ // provenance encodings.+ const project = (rows: ModelInfo[]): RowView[] =>+ scopedChoice === null ? [] : rows.map((m) => toPickerRow(scopedChoice, m));+ const scoped = catalog.rows.filter((r) => r.provider === scope);+ if (!hasDiscovery) return { rows: scoped, fallback: false, loading: catalog.phase !== "ready" };+ const o = discovery.outcome;+ if (o === null) return { rows: [], fallback: false, loading: true };+ if (o.kind === "rows") return { rows: project(o.rows), fallback: false, loading: false };+ if (o.kind === "unsupported") return { rows: scoped, fallback: false, loading: false };+ return { rows: project(o.fallbackRows), fallback: true, loading: false };+ }, [scope, scopedChoice, hasDiscovery, discovery.outcome, catalog.rows, catalog.phase]);const shown = useMemo(() => {const needle = filter.trim().toLowerCase();- if (!needle) return listSource.rows;- return listSource.rows.filter((m) => m.id.toLowerCase().includes(needle));- }, [listSource.rows, filter]);-- // Meter bounds are taken over the VISIBLE list, so the comparison a reader makes is- // always against what they can see. Re-derived when the filter changes, which is- // what makes a narrowed list re-scale rather than flatten.- const bounds = useMemo(() => {- const ctx = shown.map((m) => m.contextLength ?? 0).filter((n) => n > 0);- const prices = shown- .map((m) =>- current === null ? undefined : parseDisplayPrice(resolveProviderDisplayPrice(current, m))- )- .filter((n): n is number => n !== undefined && n > 0);- return {- ctxMin: ctx.length > 0 ? Math.min(...ctx) : 0,- ctxMax: ctx.length > 0 ? Math.max(...ctx) : 0,- priceMin: prices.length > 0 ? Math.min(...prices) : 0,- priceMax: prices.length > 0 ? Math.max(...prices) : 0,- };- }, [shown, current]);-- // ── layout ──────────────────────────────────────────────────────────────────- const panes = derivePanes(width);- const rowLayout = deriveRowLayout(panes.rowCells, { mark: listSource.fallback });- const railLayout = deriveRailLayout(panes.railInner);- const twoRowHeader = height >= CHROME.headerTwoRows;- const statsPanelled = height >= CHROME.statsPanel;- const bannerBordered = height >= CHROME.bannerBordered;- const bannerMax = bannerBordered ? 6 : 4;- // A banner line sized to `width - 2` wrapped by exactly one column — MEASURED, and- // the reason for the slack rather than the arithmetic: the box spends a border column- // and a padding column, and the row still wanted one more. A wrapped line costs a row- // out of a four-row budget, which is the one thing this banner cannot afford.- const bannerWidth = width - 4;+ if (!needle) return list.rows;+ // The provider shortcut is matched too, which is how provider scoping survives+ // the rail's deletion: typing `kc` narrows to Kimi Coding in three keystrokes.+ return list.rows.filter(+ (r) =>+ r.model.id.toLowerCase().includes(needle) || r.shortcut.toLowerCase().startsWith(needle)+ );+ }, [list.rows, filter]);// ── in-flight affordances ───────────────────────────────────────────────────- const busy =- providers.probing || catalog.phase === "loading" || discovery.busy || listSource.loading;+ const busy = providers.probing || catalog.phase !== "ready" || discovery.busy;const frame = useAnimationFrame(busy);- const showCreds = useDelayedVisible(providers.probing);- const showCatalog = useDelayedVisible(catalog.phase === "loading");- const showRoster = useDelayedVisible(discovery.busy);- const showVendor = useDelayedVisible(listSource.loading && !hasDiscovery);-const tasks = buildLoadTasks({- creds: showCreds ? { done: providers.done, total: providers.total } : null,- catalog: showCatalog,+ creds: providers.probing ? { done: providers.done, total: providers.total } : null,+ catalog: catalog.phase !== "ready",roster:- showRoster && current !== null+ discovery.busy && scope !== null? {- displayName,- shape: currentRow?.discoveryShape ?? "none",+ displayName: scopedName,+ shape: scopedChoice?.discoveryShape ?? "none",elapsed: discovery.startedAt === null ? 0 : Date.now() - discovery.startedAt,}: null,- vendor: showVendor ? displayName : null,});+ // The loading DIALOG replaces the list only while there is nothing to show at+ // all. Once rows exist the list wins and the pending work drops to a footer+ // note: "models appear as soon as they are ready" is a promise the screen has to+ // keep, and a spinner in front of a usable list breaks it.+ const phase: "loading" | "list" = tasks.length > 0 && list.rows.length === 0 ? "loading" : "list";- // ── scroll sync: the cursor leads, the viewport follows ─────────────────────- const modelScroll = useRef<ScrollBoxRenderable | null>(null);- const railScroll = useRef<ScrollBoxRenderable | null>(null);- useEffect(() => {- const sb = modelScroll.current;- if (!sb || shown.length === 0) return;- const viewportH = sb.viewport.height;- const top = sb.scrollTop;- if (modelCursor < top) sb.scrollTo({ x: 0, y: modelCursor });- else if (modelCursor >= top + viewportH) sb.scrollTo({ x: 0, y: modelCursor - viewportH + 1 });- }, [modelCursor, shown.length]);- useEffect(() => {- const sb = railScroll.current;- if (!sb) return;- const i = railRows.findIndex((r) => r.value === current);- if (i < 0) return;- const viewportH = sb.viewport.height;- const top = sb.scrollTop;- if (i < top) sb.scrollTo({ x: 0, y: i });- else if (i >= top + viewportH) sb.scrollTo({ x: 0, y: i - viewportH + 1 });- }, [current, railRows]);-- // The cursor can outlive the list it indexed — a filter keystroke, or a provider+ // ── layout ──────────────────────────────────────────────────────────────────+ const notice =+ scope !== null && discovery.outcome !== null+ ? discoveryNoticeContent(discovery.outcome, scopedName)+ : null;+ const base = deriveDialogLayout(width, height);+ const bannerRows =+ notice === null+ ? 0+ : noticeRows(notice, Math.max(8, base.inner - 2), MAX_BANNER_ROWS).lines.length;+ const layout = deriveDialogLayout(width, height, bannerRows);+ const rowLayout = deriveRowLayout(layout.inner, { mark: list.fallback });++ // The cursor can outlive the list it indexed — a filter keystroke, or a scope// whose roster came back shorter than the last one's.useEffect(() => {- setModelCursor((c) => Math.max(0, Math.min(c, Math.max(0, shown.length - 1))));+ setCursor((c) => Math.max(0, Math.min(c, Math.max(0, shown.length - 1))));}, [shown.length]);+ const top = scrollWindow(cursor, shown.length, layout.listRows);+ const window = shown.slice(top, top + layout.listRows);+ const selected = shown[cursor] ?? null;+// ── keys: ONE handler, because `useKeyboard` is a BROADCAST ─────────────────//- // Every mounted subscriber receives every key — no bubbling, no `stopPropagation` —- // so mutual exclusion is hand-rolled. Two mutually exclusive halves: a text mode owns- // every printable key, and browse mode owns the commands. Both modes are explicit- // (entered with `/` and `c`) rather than type-to-filter, because `c` and `k` are- // commands here and a filter that swallowed them would put the custom-spec hatch out- // of reach — the cost `resume-picker.tsx` pays for `a` and `v`.- const handleTextKey = (key: { name?: string; raw?: string }): void => {+ // Every mounted subscriber receives every key — no bubbling, no+ // `stopPropagation` — so mutual exclusion is hand-rolled. Here it is trivial,+ // because there is one view at a time and one cursor in it.+ //+ // FILTER-FIRST, WITH ONE ESCAPE HATCH. In the model view every printable key+ // that is not a bound command types into the filter immediately — there is no+ // search MODE to enter, which is one fewer thing the reader has to know before+ // the screen does anything. The commands that survive are the ones a filter+ // cannot express (`esc`, `enter`, the arrows) plus three letters, and those three+ // are live ONLY while the filter is empty and `/` has not been pressed: once+ // anything is typed they are letters again, because a user typing `phi` must get+ // `phi` and not the provider dialog.+ useKeyboard((key) => {const name = key.name;- const setter = mode === "custom" ? setCustom : setFilter;- if (name === "escape") {- if (mode === "filter") setFilter("");- setMode("browse");+ if (key.ctrl && name === "c") {+ onDone(null);return;}- if (name === "return" || name === "enter") {- if (mode === "custom") {++ if (view === "custom") {+ if (name === "escape") {+ setView("models");+ return;+ }+ if (name === "return" || name === "enter") {const spec = custom.trim();if (spec) onDone(spec);return;}- setMode("browse");- setPane("models");- return;- }- if (name === "backspace") {- setter((v) => v.slice(0, -1));+ if (name === "backspace") {+ setCustom((v) => v.slice(0, -1));+ return;+ }+ if (printable(key.raw)) setCustom((v) => v + key.raw);return;}- const ch = key.raw;- if (ch && ch.length === 1 && ch >= " " && ch !== "\x7f") {- setter((v) => v + ch);- setModelCursor(0);- }- };- useKeyboard((key) => {- const name = key.name;- if (key.ctrl && name === "c") {- onDone(null);- return;- }- if (mode === "custom" || mode === "filter") {- handleTextKey(key);+ if (view === "providers") {+ if (name === "escape" || key.raw === "p") {+ setView("models");+ return;+ }+ if (name === "up" || name === "down") {+ const d = name === "up" ? -1 : 1;+ setProviderCursor((c) => Math.max(0, Math.min(providers.rows.length - 1, c + d)));+ return;+ }+ if (name === "return" || name === "enter") {+ const chosen = providers.rows[providerCursor];+ if (chosen) {+ setScope(chosen.value);+ setFilter("");+ setCursor(0);+ }+ setView("models");+ }return;}if (name === "escape") {- if (filter) {+ if (filter !== "" || typing) {setFilter("");+ setTyping(false);+ setCursor(0);+ return;+ }+ if (scope !== null) {+ setScope(null);+ setCursor(0);return;}onDone(null);return;}- if (name === "tab") {- setPane((p) => (p === "providers" ? "models" : "providers"));+ if (name === "up" || name === "down") {+ const d = name === "up" ? -1 : 1;+ setCursor((c) => Math.max(0, Math.min(shown.length - 1, c + d)));return;}- if (name === "left") {- setPane("providers");+ if (name === "pageup" || name === "pagedown") {+ const d = (name === "pageup" ? -1 : 1) * layout.listRows;+ setCursor((c) => Math.max(0, Math.min(shown.length - 1, c + d)));return;}- if (name === "right") {- setPane("models");+ if (name === "home") {+ setCursor(0);return;}- if (name === "up" || name === "down") {- const d = name === "up" ? -1 : 1;- if (pane === "providers") {- const i = railRows.findIndex((r) => r.value === current);- const next = railRows[Math.max(0, Math.min(railRows.length - 1, (i < 0 ? 0 : i) + d))];- if (next) {- setSelected(next.value);- setModelCursor(0);- }- return;- }- setModelCursor((c) => Math.max(0, Math.min(shown.length - 1, c + d)));+ if (name === "end") {+ setCursor(Math.max(0, shown.length - 1));return;}if (name === "return" || name === "enter") {- if (pane === "providers") {- setPane("models");- return;- }- const model = shown[modelCursor];- if (model && current !== null) {- // The SAME spec builder the classic path uses, with the provider's own- // externalId — `or@openai/gpt-5`, not the catalog's bare key. Every row is- // provider-scoped, so no bare Claude name can leave this picker.- onDone(buildExplicitModelSpec(current, resolveProviderExternalId(current, model)));- }+ if (selected) onDone(selected.spec);return;}- if (name === "slash" || key.raw === "/") {- setMode("filter");- setPane("models");+ if (name === "backspace") {+ setFilter((v) => v.slice(0, -1));+ setCursor(0);return;}- if (key.raw === "c") {- setMode("custom");+ const commandsLive = filter === "" && !typing;+ if (commandsLive && key.raw === "p") {+ setProviderCursor(+ Math.max(+ 0,+ providers.rows.findIndex((r) => r.value === scope)+ )+ );+ setView("providers");return;}- if (key.raw === "k") {- setShowMissing((v) => !v);+ if (commandsLive && key.raw === "c") {+ setView("custom");return;}- if (key.raw === "@") {- setPane("providers");+ if (commandsLive && key.raw === "r" && scope !== null && hasDiscovery) {+ discovery.retry(scope);+ return;+ }+ if (key.raw === "/") {+ // Not inserted: `/` FOCUSES the filter, which here means "stop treating+ // p / c / r as commands". See `typing`.+ setTyping(true);+ return;+ }+ if (printable(key.raw)) {+ setFilter((v) => v + key.raw);+ setCursor(0);}});- // ── panel titles: the first of the three provenance encodings ───────────────- const listLabel = listSource.fallback- ? "cloud catalog (fallback)"- : listSource.origin === "roster"- ? "live roster"- : "cloud catalog";- // MEASURED: a title that fills the border exactly is DROPPED — `Panel` renders no- // title at all rather than a clipped one, which turned the loudest provenance- // encoding into an empty border. Six columns of slack, and the `⚠` that used to- // prefix the fallback label is gone with it: the word `fallback` carries the meaning,- // and `Panel`'s title colour is fixed chrome, so a glyph there could not have been- // coloured to add anything.- // The PROVENANCE must survive the truncation, so the title spends nothing on a word- // the panel's own position already says. `models · …` was the first casualty of a- // title clipped at 52 columns — and the half it clipped was `(fallback)`.- const panelTitle = truncate(- `${displayName || "—"} · ${listSource.rows.length} · ${listLabel}`,- Math.max(8, panes.panelOuter - 8)- );-- const missingCount = providers.missing.length;- const notEnabled = providers.notEnabledLocal.length;- // THE DETAIL BLOCKS ARE HEIGHT-GATED, and 26 rows is where the trade flips. Below it- // every row belongs to the list, and two rows of prose would cost two GRAPHICS rows —- // the wrong direction for the whole-frame density count. Above it a short list leaves- // its panel half empty, and the description the inquirer picker used to show has- // somewhere to go.- const showDetail = height >= CHROME.detail;- const cursorModel = shown[modelCursor] ?? null;- const cursorSpec =- cursorModel === null || current === null- ? null- : buildExplicitModelSpec(current, resolveProviderExternalId(current, cursorModel));-- return (- <box flexDirection="column" height={height} backgroundColor={C.bg}>- <PickerHeader- right={`${providers.ready.length}/${providers.total} ready · ${catalog.phase === "failed" ? "catalog offline" : `${catalog.size} catalogued`}`}- twoRows={twoRowHeader}- />+ // ── the three dialogs ───────────────────────────────────────────────────────+ //+ // `key={view}-{phase}` FORCES A REMOUNT WHEN THE TREE CHANGES SHAPE. Inline mode+ // reserves rows by scrolling the main screen, and OpenTUI's in-place+ // reconciliation tore the panel when the chrome below a banner changed shape+ // (`probe-tui-app.tsx:1455-1462` records the same failure and the same cure). A+ // loading dialog flipping to a list dialog is exactly that transition.- <LoadBar tasks={tasks} frame={frame} width={width} />-- <box flexDirection="row" flexGrow={1} minHeight={0} gap={1}>- {/* ── provider rail ───────────────────────────────────────────────── */}- <box width={panes.railW} flexDirection="column" minHeight={0}>- <Panel title="providers" focused={pane === "providers"} flush flexGrow={1} flexBasis={0}>- <scrollbox- ref={railScroll}- focused={false}- flexGrow={1}- scrollbarOptions={scrollbarOptions()}- >- {railRows.map((r) => (- <ProviderRailRow- key={r.value}- label={r.label}- readiness={r.readiness}- billing={r.billing}- count={r.value === current ? listSource.rows.length : null}- cursor={r.value === current}- focused={pane === "providers"}- layout={railLayout}- />- ))}- {/* An unexplained absence is the defect class this feature is about, so- both absences are named. Neither row is selectable. */}- {missingCount > 0 && !showMissing ? (- <RailHintRow- text={`+${missingCount} need a key · k`}- width={railLayout.railInner}- />- ) : null}- {notEnabled > 0 ? (- <RailHintRow- text={`+${notEnabled} local not enabled`}- width={railLayout.railInner}- />- ) : null}- </scrollbox>- {/* Pinned UNDER the list, so a short rail's leftover space carries the- selected provider's own copy instead of a void. `flexShrink={0}` lives- inside the component: the scrollbox above asks for its entire content- height and Yoga spreads that shortfall across every sibling. */}- {showDetail && currentRow !== null ? (- <ProviderDetail- label={displayName}- description={currentRow.description}- envVar={currentRow.envVar}- width={railLayout.railInner}- />- ) : null}- </Panel>+ if (view === "custom") {+ return (+ <Dialog+ key="custom"+ title="type a model spec"+ status="provider@model"+ width={layout.width}+ marginLeft={layout.marginLeft}+ >+ <box height={1} flexShrink={0}>+ <text>+ <span fg={tokens.accent}>{"› "}</span>+ <span fg={tokens.text}>{custom}</span>+ <span fg={tokens.accent}>▍</span>+ </text>+ </box>+ <box height={1} flexShrink={0}>+ <text>+ <span fg={tokens.subtle}>+ {"e.g. or@openai/gpt-5, kc@kimi-k3, [email protected] — anything argv accepts"}+ </span>+ </text></box>+ <Rule />+ <Hints+ hints={[+ { key: "⏎", label: "launch it", on: custom.trim() !== "" },+ { key: "esc", label: "back" },+ ]}+ />+ </Dialog>+ );+ }- {/* ── models + filter + shape ──────────────────────────────────────── */}- <box flexDirection="column" flexGrow={1} minWidth={0} minHeight={0}>- <Panel title={panelTitle} focused={pane === "models"} flush flexGrow={1} flexBasis={0}>- <scrollbox- ref={modelScroll}- focused={false}- flexGrow={1}- scrollbarOptions={scrollbarOptions()}- >- {shown.length === 0 ? (- <EmptyState- label={emptyLabel(- listSource.loading,- filter,- listSource.rows.length,- displayName- )}- {...(filter ? { hint: "esc clears the filter · c types a spec" } : {})}- />- ) : (- shown.map((m, i) => (- <ModelRow- key={`${m.id}-${i}`}- model={m}- layout={rowLayout}- cursor={i === modelCursor}- ctxPct={contextMeterPct(m.contextLength, bounds.ctxMin, bounds.ctxMax)}- pricePct={priceMeterPct(- parseDisplayPrice(- current === null ? "N/A" : resolveProviderDisplayPrice(current, m)- ),- bounds.priceMin,- bounds.priceMax- )}- priceText={current === null ? "N/A" : resolveProviderDisplayPrice(current, m)}- origin={listSource.fallback ? "catalog" : "roster"}- />- ))- )}- </scrollbox>- {/* What Enter will actually return, plus the description the old picker- showed and this one would otherwise drop. */}- {showDetail ? (- <ModelDetail model={cursorModel} spec={cursorSpec} width={panes.panelOuter - 2} />- ) : null}- </Panel>-- <FilterStrip- value={mode === "custom" ? custom : filter}- active={mode !== "browse"}- matches={shown.length}- total={listSource.rows.length}- width={panes.panelOuter}- prompt={mode === "custom" ? "provider@model" : "filter"}+ if (view === "providers") {+ const readyCount = providers.ready.length;+ // Two rows taller than the model list: this dialog spends no column header+ // and no selection line, so the rows it saves go back to the rows.+ const providerRows = layout.listRows + 2;+ const providerTop = scrollWindow(providerCursor, providers.rows.length, providerRows);+ const providerWindow = providers.rows.slice(providerTop, providerTop + providerRows);+ return (+ <Dialog+ key="providers"+ title="providers"+ status={`${readyCount} of ${providers.total} have credentials`}+ width={layout.width}+ marginLeft={layout.marginLeft}+ >+ {providerWindow.map((r) => (+ <ProviderRow+ key={r.value}+ label={r.label}+ shortcut={r.shortcut}+ readiness={r.readiness}+ billing={r.billing}+ count={catalog.counts.get(r.value) ?? null}+ hasDiscovery={r.hasDiscovery}+ note={r.envVar === "" ? "needs sign-in" : `needs ${r.envVar}`}+ cursor={r.value === providers.rows[providerCursor]?.value}+ inner={layout.inner}/>-- <StatsStrip- shown={shown}- total={listSource.rows.length}- width={panes.panelOuter}- panelled={statsPanelled}- priceOf={(m) => (current === null ? "" : resolveProviderDisplayPrice(current, m))}+ ))}+ {/* 31 providers do not fit in eleven rows, and a list that silently stops at+ twelve is the same unexplained absence this feature exists to remove. */}+ <HintRow+ text={+ providers.rows.length > providerWindow.length+ ? `${providerCursor + 1} of ${providers.rows.length} — ↑↓ for more`+ : ""+ }+ width={layout.inner}+ />+ {providers.notEnabledLocal.length > 0 ? (+ <HintRow+ text={`${providers.notEnabledLocal.join(", ")} — local, not enabled in your config`}+ width={layout.inner}/>+ ) : null}+ <Rule />+ <Hints+ hints={[+ { key: "↑↓", label: "move" },+ { key: "⏎", label: "show only this provider" },+ { key: "esc", label: "back to all models" },+ ]}+ />+ </Dialog>+ );+ }++ if (phase === "loading") {+ return (+ <Dialog+ key="loading"+ title={scope === null ? "choose a model" : scopedName}+ status="finding models…"+ width={layout.width}+ marginLeft={layout.marginLeft}+ >+ <LoadTasks+ tasks={tasks}+ frame={frame}+ labelWidth={14}+ barWidth={Math.max(8, Math.min(22, layout.inner - 40))}+ />+ <box height={1} flexShrink={0}>+ <text>+ <span fg={tokens.trace}>models appear as soon as they are ready</span>+ </text></box>- </box>+ <Rule />+ <Hints hints={[{ key: "esc", label: "cancel" }]} />+ </Dialog>+ );+ }++ const status =+ scope === null+ ? `${list.rows.length} models · ${providers.ready.length}/${providers.total} providers`+ : (notice?.title ?? `${list.rows.length} models`);- {/* The notice is pinned BELOW both panes and spans the full width: the failure is- the context for the list above it, and a pinned region is the half of the fix- the old inline stderr line could not provide. */}- {discovery.outcome !== null && current !== null ? (+ return (+ <Dialog+ key="models"+ title={scope === null ? "choose a model" : scopedName}+ status={status}+ width={layout.width}+ marginLeft={layout.marginLeft}+ >+ {/* The banner sits ABOVE the rows it qualifies, never below them: the eye+ goes to the list, and a warning under a healthy-looking list is a warning+ nobody reads. That is the user's own report, verbatim. */}+ {discovery.outcome === null ? null : (<DiscoveryNoticeoutcome={discovery.outcome}- displayName={displayName}- width={bannerWidth}- height={height}- maxLines={bannerMax}- bordered={bannerBordered}- />- ) : null}- {catalog.phase === "failed" ? (- <ErrorBanner- severity="notice"- lines={["The cloud catalog is unavailable — prices and capability flags may be missing."]}- width={width - 2}+ displayName={scopedName}+ width={Math.max(8, layout.inner - 2)}+ maxRows={MAX_BANNER_ROWS}/>- ) : null}- {!hasDiscovery && list.phase === "failed" && current !== null ? (- <ErrorBanner- severity="notice"- lines={[`${displayName}'s catalog list could not be loaded. Press c to type a spec.`]}- width={bannerWidth}- />- ) : null}+ )}- <PickerFooter+ <FilterRow+ value={filter}+ matches={shown.length}+ total={list.rows.length}+ width={layout.inner}+ />+ <ColumnHeader layout={rowLayout} />++ {/* CONTENT-SIZED, CAPPED — never `flexGrow`. A four-row Kimi fallback makes a+ short dialog; it does not make a tall dialog with fifteen rows of unpainted+ background in it, which is what the rejected full-screen build did and what+ the reader read as "this provider has nothing". The cap is `listRows`, and+ the banner's rows have already come out of it, so the box is bounded above+ in every state. */}+ <box+ flexDirection="column"+ height={Math.min(layout.listRows, Math.max(1, window.length))}+ flexShrink={0}+ overflow="hidden"+ >+ {window.length === 0 ? (+ <EmptyState+ label={emptyLabel(list.loading, filter, list.rows.length, scopedName, providers)}+ {...(filter === "" ? {} : { hint: "esc clears the filter" })}+ />+ ) : (+ window.map((r, i) => (+ <ModelRow+ key={r.spec}+ model={r.model}+ shortcut={r.shortcut}+ price={r.price}+ layout={rowLayout}+ cursor={top + i === cursor}+ origin={list.fallback ? "catalog" : "roster"}+ />+ ))+ )}+ </box>++ {/* ONE status row, ALWAYS rendered — see `CHROME_ROWS`. It carries the+ scroll position when the list overflows, the pending sweep when work is+ still in flight behind a usable list ("models appear as soon as they are+ ready" is a promise the screen has to keep), and nothing otherwise. */}+ <HintRow text={statusRow(cursor, shown.length, window.length, tasks)} width={layout.inner} />++ <Rule />+ <SelectionLine+ model={selected?.model ?? null}+ spec={selected?.spec ?? null}+ width={layout.inner}+ />+ <Hintshints={[{ key: "↑↓", label: "move" },- { key: "⏎", label: pane === "providers" ? "models" : "select" },+ { key: "⏎", label: "select" },{ key: "/", label: "filter" },- { key: "⇥", label: "pane" },- {- key: "k",- label: missingCount > 0 ? `${missingCount} hidden` : "hidden",- on: missingCount > 0,- },+ ...(scope !== null && hasDiscovery ? [{ key: "r", label: "retry" }] : []),+ { key: "p", label: "providers" },{ key: "c", label: "custom" },- { key: "esc", label: filter ? "clear" : "cancel" },+ { key: "esc", label: filter !== "" ? "clear" : scope !== null ? "all models" : "cancel" },]}/>- </box>+ </Dialog>);}+/** The banner's half of the inline row budget. */+const MAX_BANNER_ROWS = 5;+/**- * SAY WHICH EMPTY IT IS. "Nothing here" covers four different situations — still- * loading, loaded and genuinely empty, filtered to nothing, and failed — and a picker- * that prints one sentence for all four is the complaint this feature exists to fix.- * The failed case never reaches here: it goes to the banner, which has a colour.+ * The one status row's text, in priority order: where the cursor is in a list+ * longer than the window, then what is still loading, then nothing.+ *+ * Pure so the priority can be asserted. The scroll position wins over the pending+ * sweep because it changes on every keypress and the sweep changes once.*/-function emptyLabel(loading: boolean, filter: string, total: number, displayName: string): string {- if (loading) return `loading ${displayName || "models"}…`;- if (filter) return `no model matches “${filter}”`;- if (total === 0) return `no catalog entries for ${displayName || "this provider"}`;+export function statusRow(+ cursor: number,+ shown: number,+ visible: number,+ tasks: LoadTask[]+): string {+ if (shown > visible && visible > 0) return `${cursor + 1} of ${shown} — ↑↓ for more`;+ if (tasks.length > 0) return `still checking: ${tasks.map((t) => t.label).join(", ")}`;+ return "";+}++/** One row of the list, whichever list it is. */+type RowView = PickerRow;++/** Every key that is not a command types into the filter. */+function printable(raw: string | undefined): raw is string {+ return raw !== undefined && raw.length === 1 && raw >= " " && raw !== "\x7f";+}++/**+ * SAY WHICH EMPTY IT IS. "Nothing here" covers five different situations — still+ * loading, no provider has a credential, loaded and genuinely empty, filtered to+ * nothing, and failed — and a picker that prints one sentence for all five is the+ * complaint this feature exists to fix. The failed case never reaches here: it goes+ * to the banner, which has a colour.+ */+function emptyLabel(+ loading: boolean,+ filter: string,+ total: number,+ scopedName: string,+ providers: { ready: unknown[]; probing: boolean; total: number }+): string {+ if (loading) return `loading ${scopedName || "models"}…`;+ if (filter !== "") return `no model matches “${filter}”`;+ if (providers.ready.length === 0 && !providers.probing) {+ return `no credential for any of the ${providers.total} providers — press p to see what each one needs`;+ }+ if (total === 0) return `no catalog entries for ${scopedName || "these providers"}`;return "nothing to show";}diff --git a/packages/cli/src/picker/PickerDataSource.ts b/packages/cli/src/picker/PickerDataSource.tsindex 294008e5..e5b9d19e 100644--- a/packages/cli/src/picker/PickerDataSource.ts+++ b/packages/cli/src/picker/PickerDataSource.ts@@ -17,14 +17,23 @@* registry and breaks sibling e2e files (`feedback_no_mock_module_bleed`). An* injected interface cannot leak into another test file.*- * EVERY MEMBER'S SYNC/ASYNC SHAPE IS PART OF THE CONTRACT. `providerRoster`,- * `displayName`, `notEnabledLocalProviders` and `discoveryShape` are SYNCHRONOUS- * because the first frame must render the full rail before any await (FR-1 is met- * structurally, not by diligence), and because §4.3's indicator shape has to be- * chosen before the fetch it describes begins. `probeCredentials` is an- * AsyncIterable rather than a `Promise<Map>` for the same reason: the rail fills in- * as each probe settles, which is the real loading affordance, and a single- * awaited map would hide ~30 probes behind one silent pause.+ * EVERY MEMBER'S SYNC/ASYNC SHAPE IS PART OF THE CONTRACT.+ *+ * · `providerRoster`, `displayName`, `notEnabledLocalProviders`,+ * `discoveryShape` are SYNCHRONOUS because the first frame must be complete+ * before any await, and because the in-flight indicator's SHAPE has to be+ * chosen before the fetch it describes begins.+ * · `servedModels` is SYNCHRONOUS, and that is the decision that makes one flat+ * cross-provider list affordable at all. It reads the catalog's local+ * served-by index; the async `loadModelsForPickerProvider` asks the same+ * question with a live `?provider=` query per owner slug, and 22 of those+ * fired together were MEASURED at 10 s returning zero rows. `servedByVendor`+ * in `providers/model-catalog.ts` records why the index is the same authority+ * and not a second one.+ * · `probeCredentials` is an AsyncIterable rather than a `Promise<Map>` so the+ * `done/total` counter advances as each probe settles; a single awaited map+ * would hide ~30 probes behind one silent pause, one of which is a+ * multi-second 1Password handshake.*/import { credentials } from "../auth/credentials/authority.js";@@ -34,14 +43,15 @@ import {type PickerDiscoveryOutcome,buildDiscoveredModelOutcome,buildProviderChoices,- loadModelsForPickerProvider,- loadPickerCatalog,+ providerShortcut,+ servedModelsForProvider,} from "../model-selector.js";import { isLocalProviderEnabled } from "../profile-config.js";+import { ensureCatalogReady } from "../providers/catalog-client.js";import { createCatalogClient } from "../providers/model-catalog.js";import { getAllProviders, getProviderByName } from "../providers/provider-definitions.js";-/** How a provider bills — the rail's tag, and the reason a price meter may be absent. */+/** How a provider bills — the row's tag, and the reason a price may be absent. */export type BillingMode = "sub" | "local" | "metered";/**@@ -57,50 +67,42 @@ export type BillingMode = "sub" | "local" | "metered";*/export type DiscoveryShape = "deadline" | "elapsed" | "none";-/** One provider rail row, as the view needs it on frame one. */-export interface RailChoice {+/** One provider, as every view of the picker needs it on frame one. */+export interface PickerProviderChoice {/** `ProviderDefinition.name` — the value every other call is keyed by. */value: string;+ /** The editorial display name — `Kimi / Moonshot`, `OpenAI Codex`. */+ label: string;/**- * What the RAIL prints. Production sets the provider's routing name (`ollama`,- * `qwen-cloud`) rather than its editorial display name, for two reasons: the rail- * has 9–10 columns, and the routing name is the string the user can type as a- * `provider@` prefix. The editorial name goes in the model panel's title and in- * every notice, where there is room for it — `displayName()` answers that.+ * The routing shortcut this provider's rows print, `kc@` / `or@` / `gk@`.+ * DERIVED (`providerShortcut`), never a table, and it is the string the user+ * can retype on argv.*/- label: string;+ shortcut: string;description: string;billing: BillingMode;/** The env var to name in a credential notice. Empty for OAuth-only providers. */envVar: string;- /** Does this provider list its own live roster? Decides effect C vs effect D. */+ /** Does this provider list its own live roster? Decides whether `p` runs discovery. */hasDiscovery: boolean;discoveryShape: DiscoveryShape;}-/** What the cross-vendor catalog load (A2) yields. */-export interface CatalogLoad {- /** The newest-first top list — the corpus behind the `NEW` marker. */- top: ModelInfo[];- /** claudish's recommended entries — the corpus behind the `REC` marker. */- recommended: ModelInfo[];-}-export interface PickerDataSource {- /** Sync, so frame one is never blank: the rail is derived from definitions. */- providerRoster(): RailChoice[];- /** Built-in local providers present in the catalog but not enabled in config (§3.9). */+ /** Sync, so frame one is never blank: derived from the provider definitions. */+ providerRoster(): PickerProviderChoice[];+ /** Built-in local providers present in the catalog but not enabled in config. */notEnabledLocalProviders(): string[];- /** The provider's editorial display name, for panel titles and notices. */+ /** The provider's editorial display name, for dialog titles and notices. */displayName(provider: string): string;/** Readiness per provider, yielded AS EACH SETTLES — never one awaited map. */probeCredentials(names: string[]): AsyncIterable<[string, boolean]>;- /** A2 — the cross-vendor catalog. */- loadCatalog(): Promise<CatalogLoad>;- /** A9 ∥ A12 — one settled outcome per discovery provider, `fallbackRows` included. */+ /** Make the cross-vendor catalog usable. Bounded, and never throws. */+ ensureCatalog(): Promise<void>;+ /** What this provider SERVES, from the local served-by index. Sync. */+ servedModels(provider: string): ModelInfo[];+ /** One settled outcome per discovery provider, `fallbackRows` included. */discoverRoster(provider: string): Promise<PickerDiscoveryOutcome>;- /** A12 — the vendor catalog list for a provider that has no discovery. */- catalogModels(provider: string): Promise<ModelInfo[]>;}/** How a provider bills, from the two oracles that already answer it. */@@ -125,6 +127,17 @@ export function discoveryShapeOf(provider: string): DiscoveryShape {/** The deadline the `deadline` shape is drawn against. Mirrors `FETCH_TIMEOUT_MS`. */export const DISCOVERY_DEADLINE_MS = 5000;+/**+ * How long the picker will wait for a cold catalog before drawing what it has.+ *+ * It is NOT rendered as a determinate bar, deliberately. `ensureCatalogReady`+ * races this timeout against `refreshCatalog(8000)` — two different numbers, so+ * there is no single denominator a bar could honestly be drawn against. The+ * catalog row gets a shimmer and an elapsed figure, which claims only that time+ * is passing.+ */+const CATALOG_WAIT_MS = 5000;+/*** Yield each promise's value as it settles, in COMPLETION order.*@@ -156,15 +169,16 @@ export function createPickerDataSource(): PickerDataSource {const catalog = createCatalogClient();// Resolved once per open. `buildProviderChoices()` is pure and derived — never a// membership table (`routing.md:139`) — so calling it twice would be free but- // would also let the rail and the notices disagree about ordering.+ // would also let the roster and the notices disagree about ordering.const choices = buildProviderChoices().filter((c) => c.value !== "skip" && c.value !== "custom");const names = new Map(choices.map((c) => [c.value, c.name]));return {- providerRoster(): RailChoice[] {+ providerRoster(): PickerProviderChoice[] {return choices.map((c) => ({value: c.value,- label: c.value,+ label: c.name,+ shortcut: providerShortcut(c.value),description: c.description,billing: billingModeOf(c.value),envVar: getProviderByName(c.value)?.apiKeyEnvVar ?? "",@@ -199,16 +213,17 @@ export function createPickerDataSource(): PickerDataSource {);},- loadCatalog(): Promise<CatalogLoad> {- return loadPickerCatalog();+ async ensureCatalog(): Promise<void> {+ // Documented never to throw; guarded anyway, for the same reason as above.+ await ensureCatalogReady(CATALOG_WAIT_MS).catch(() => undefined);},- discoverRoster(provider: string): Promise<PickerDiscoveryOutcome> {- return buildDiscoveredModelOutcome(provider, names.get(provider) ?? provider, catalog);+ servedModels(provider: string): ModelInfo[] {+ return servedModelsForProvider(provider, catalog);},- catalogModels(provider: string): Promise<ModelInfo[]> {- return loadModelsForPickerProvider(provider, catalog);+ discoverRoster(provider: string): Promise<PickerDiscoveryOutcome> {+ return buildDiscoveredModelOutcome(provider, names.get(provider) ?? provider, catalog);},};}diff --git a/packages/cli/src/picker/StatsStrip.tsx b/packages/cli/src/picker/StatsStrip.tsxdeleted file mode 100644index a0b08abf..00000000--- a/packages/cli/src/picker/StatsStrip.tsx+++ /dev/null@@ -1,283 +0,0 @@-/** @jsxImportSource @opentui/react */-/**- * picker/StatsStrip.tsx — the graphics panel that carries the WHOLE-FRAME density- * count.- *- * IT IS HERE PRE-EMPTIVELY, not after a failed screenshot. The aesthetic contract- * counts graphics rows against text rows twice: once per panel, and then again over- * the entire capture — and the skill records a build where every panel passed the- * first count and the frame was still 28 of 38 rows of text. The provider rail is- * text (a glyph is not a graphic) and the filter, header and footer are text, so a- * frame of model rows alone sits near the line. Three rows of bar, spark and meter- * put it clear of it, and they are rows a reader genuinely uses: what the visible- * list is made of.- *- * THE COLLAPSE IS GATED ON HEIGHT, NOT WIDTH. At 80 columns the right-hand column- * still has ~57 usable cells — ample for a stacked bar and a sparkline. What is- * scarce at 80×24 is ROWS. So a short terminal drops the BORDER and the `shown` row- * (whose count the filter strip already prints) and keeps both graphics rows; an- * earlier design collapsed on width, to one row, and cost the frame exactly the- * density this panel exists to supply.- */--import type { ReactNode } from "react";-import type { ModelInfo } from "../model-selector.js";-import { C, isLightTheme } from "../tui/theme.js";-import { darken, lighten } from "../tui/viz/color.js";-import { padStartTo, padTo } from "../tui/viz/text.js";-import { ramps, tokens } from "../tui/viz/tokens.js";-import { Meter, Panel, Sparkline, StackedBar } from "../tui/viz/widgets.js";-import { parseDisplayPrice } from "./rows.js";--/**- * PRICE BANDS — the second distribution, and the one that replaced a capability bar.- *- * MEASURED, twice. The capability mix is a single category on a subscription roster (the- * discovery path resolves `supportsTools` and nothing else) AND on every aggregator list- * (the slim catalog carries no `tools` flag at all), so its bar painted one flat- * rectangle on both — the aesthetic contract's own negative control, twice over, for a- * fact the per-row `[TRV]` column already states. Price spreads on every real list, it- * is what a reader is choosing on, and it complements the context bands rather than- * repeating them.- *- * Fixed absolute edges, not quantiles: "under a dollar per million" is a threshold a- * reader already holds, while a quantile scale would move under them as the list- * filtered.- */-const PRICE_BANDS: ReadonlyArray<{ label: string; max: number }> = [- { label: "free", max: 0.0001 },- { label: "<$1", max: 1 },- { label: "<$5", max: 5 },- { label: "$5+", max: Number.POSITIVE_INFINITY },-];--/**- * Models with a per-token rate, bucketed. Flat-rate and unpriced rows are excluded.- *- * `priceOf` IS THE CALLER'S, and it must be the same function the ROWS print — MEASURED:- * reading `m.pricing.average` directly banded all 349 of OpenRouter's models as- * "unpriced" while every row on screen showed a dollar figure, because an aggregator's- * real rate lives in its `aggregators[]` entry and `resolveProviderDisplayPrice` is the- * one function allowed to resolve it. A panel that disagrees with the rows above it is- * worse than no panel.- */-export function priceMix(- models: readonly ModelInfo[],- priceOf: (m: ModelInfo) => string = (m) => m.pricing?.average ?? ""-): number[] {- const out = PRICE_BANDS.map(() => 0);- for (const m of models) {- const display = priceOf(m);- // `FREE` is the catalog's own normalisation of `$0.00/1M` (`model-loader.ts:550`),- // so it carries no digits to parse — and dropping it would hide the cheapest band- // from the bar that exists to show it. `SUB`/`LOCAL` stay excluded: a flat-rate plan- // has no point on a per-token axis, and putting it at zero would claim it is free.- const n = display === "FREE" ? 0 : parseDisplayPrice(display);- if (n === undefined) continue;- const i = PRICE_BANDS.findIndex((b) => n < b.max);- out[i < 0 ? PRICE_BANDS.length - 1 : i]! += 1;- }- return out;-}--/**- * Fit a series to a column budget, because a `Sparkline` paints ONE COLUMN PER- * SAMPLE and cannot apportion (`Meter` and `StackedBar` can; these two cannot).- *- * 342 models in a 48-column slot would paint 342 columns and overflow the panel;- * 12 models in a 48-column slot paint 12 and leave a 36-column hole that a- * screenshot fails the panel for. So: bucket-average when there are more samples- * than columns, and hold each sample for several columns when there are fewer.- * Averaging rather than sampling every Nth, because a decimated series drops the- * outlier that was the only interesting thing in it.- */-export function resample(values: readonly number[], width: number): number[] {- const cells = Math.max(0, Math.floor(width));- if (cells === 0 || values.length === 0) return [];- if (values.length === cells) return [...values];- return values.length > cells ? bucketMeans(values, cells) : holdEach(values, cells);-}--/** Mean of the FINITE samples in `[from, to)`, or `NaN` when the bucket has none. */-function meanOf(values: readonly number[], from: number, to: number): number {- let sum = 0;- let n = 0;- for (let j = from; j < to && j < values.length; j++) {- const v = values[j]!;- if (!Number.isFinite(v)) continue;- sum += v;- n++;- }- return n > 0 ? sum / n : Number.NaN;-}--/** More samples than columns: one bucket per column, averaged. */-function bucketMeans(values: readonly number[], cells: number): number[] {- const per = values.length / cells;- const out: number[] = [];- for (let i = 0; i < cells; i++) {- const from = Math.floor(i * per);- out.push(meanOf(values, from, Math.max(from + 1, Math.floor((i + 1) * per))));- }- return out;-}--/** Fewer samples than columns: hold each one for as many columns as it is owed. */-function holdEach(values: readonly number[], cells: number): number[] {- const out: number[] = [];- for (let i = 0; i < cells; i++) {- out.push(values[Math.min(values.length - 1, Math.floor((i * values.length) / cells))]!);- }- return out;-}--/**- * CONTEXT-WINDOW DECADE BUCKETS — a category distribution, which is what a stacked bar- * is for, and the row that keeps this panel informative on a HOMOGENEOUS list.- *- * MEASURED: a subscription roster's capability mix is a single category (the discovery- * path resolves `supportsTools` and nothing else), so the caps bar alone painted one- * flat green rectangle — the aesthetic contract's own negative control. Context windows- * spread across decades on almost every list, including that one (1M × 19, 250K × 2,- * 131K × 1), so this row carries shape where the other one cannot.- *- * Fixed decade edges rather than quantiles of the visible window: the reader is- * comparing against absolute sizes they already know ("is this a 128 K model or a 1 M- * one"), and a quantile scale would relabel the same model differently on two screens.- */-const CTX_BUCKETS: ReadonlyArray<{ label: string; max: number }> = [- { label: "<32K", max: 32_000 },- { label: "128K", max: 200_000 },- { label: "512K", max: 600_000 },- { label: "1M+", max: Number.POSITIVE_INFINITY },-];--export function ctxMix(models: readonly ModelInfo[]): number[] {- const out = CTX_BUCKETS.map(() => 0);- for (const m of models) {- const n = m.contextLength ?? 0;- if (n <= 0) continue;- const i = CTX_BUCKETS.findIndex((b) => n < b.max);- out[i < 0 ? CTX_BUCKETS.length - 1 : i]! += 1;- }- return out;-}--const LABEL_W = 6;--export interface StatsStripProps {- /** The list as the user currently sees it — every number here is about THAT. */- shown: readonly ModelInfo[];- /** Before the filter, so `shown / total` is a real fraction. */- total: number;- /** Outer columns the strip occupies (the model panel's width). */- width: number;- /** `true` above `CHROME.statsPanel` rows: a bordered panel and the third row. */- panelled: boolean;- /** The SAME price resolver the rows print with — see `priceMix`. */- priceOf?: (m: ModelInfo) => string;-}--/**- * Three rows when there is room, two when there is not — and both survivors are- * graphics rows, which is the property §4.6's arithmetic depends on.- *- * Each row is a flex ROW of a label `<text>`, a widget and a legend `<text>`, which- * is the composition the skill prescribes and the one case where sibling `<text>`s- * are correct: `flexDirection="row"` means three one-row children need exactly the- * one row they have, so they cannot starve. The widths are arithmetic because the- * widgets take cell counts, and they are computed from ONE inner width so the three- * rows cannot drift apart.- */-export function StatsStrip({ shown, total, width, panelled, priceOf }: StatsStripProps): ReactNode {- // `Panel` spends 4 columns (border ×2 + padding ×2); the borderless form spends- // the 2 columns of `paddingX={1}`.- const inner = Math.max(12, Math.floor(width) - (panelled ? 4 : 2));- const prices = priceMix(shown, priceOf);- const priceLegend = PRICE_BANDS.map((b, i) => `${b.label} ${prices[i]}`).join(" · ");- const buckets = ctxMix(shown);- const ctxLegend = CTX_BUCKETS.map((b, i) => `${b.label} ${buckets[i]}`).join(" · ");- const priceW = Math.max(6, inner - LABEL_W - 1 - priceLegend.length - 1);- const ctxW = Math.max(6, inner - LABEL_W - 1 - ctxLegend.length - 1);- const shownLegend = `${shown.length} / ${total}`;- // Two widgets share the third row, so the width is split between them: a sparkline- // of the list in display order, then how much of the list the filter left.- const trendW = Math.max(6, Math.floor((inner - LABEL_W - 4 - shownLegend.length) / 2));- const meterW = Math.max(6, inner - LABEL_W - 4 - shownLegend.length - trendW);-- // EVERY FILL IS DARKENED, and that is the skill's rule 1 for fills rather than taste:- // a neon token that reads beautifully as one letter is a slab when it is 40 columns- // of solid background. MEASURED — the first wide capture painted `C.magenta` across- // most of the ctx row and `C.green` across most of the caps row, and the two bars- // became the loudest thing on a screen whose actual signal is the list above them.- // Darkening keeps the hue identity (which is what the legend names) and returns the- // contrast to the data. Same 0.45 for every segment, so the segments stay comparable.- // LIGHTEN ON LIGHT, DARKEN ON DARK — `theming.md`'s `area()` rule, called at RENDER- // time because `isLightTheme()` fails the same silent way `C.*` does: detection runs- // after this module is imported, so a value captured at load is the pre-detection- // default forever. Measured on a white page: the darkened fills read as heavy slabs,- // which is Jack's recorded complaint about the session card's meters ("the colours are- // too hard", "the progress bars are too heavy, getting all the attention").- const fill = (c: string): string => (isLightTheme() ? lighten(c, 0.55) : darken(c, 0.45));- // Cheap → dear, on the same ramp direction the per-row price meter reads.- const priceSegments = [- { value: prices[0]!, color: fill(tokens.success) },- { value: prices[1]!, color: fill(C.yellow) },- { value: prices[2]!, color: fill(tokens.warn) },- { value: prices[3]!, color: fill(tokens.error) },- ];- // Small window → cool, large → warm, so the row reads left to right as "how big" —- // the same direction the per-row context meter reads.- const ctxSegments = [- { value: buckets[0]!, color: tokens.border },- { value: buckets[1]!, color: fill(tokens.running) },- { value: buckets[2]!, color: fill(tokens.info) },- { value: buckets[3]!, color: fill(C.magenta) },- ];- const ctxSeries = resample(- shown.map((m) => m.contextLength ?? 0),- trendW- );-- const body = (- <>- <box flexDirection="row" height={1} gap={1} flexShrink={0}>- <text fg={tokens.subtle}>{padTo("ctx", LABEL_W)}</text>- <StackedBar segments={ctxSegments} width={ctxW} />- <text fg={tokens.trace}>{ctxLegend}</text>- </box>- <box flexDirection="row" height={1} gap={1} flexShrink={0}>- <text fg={tokens.subtle}>{padTo("price", LABEL_W)}</text>- <StackedBar segments={priceSegments} width={priceW} />- <text fg={tokens.trace}>{priceLegend}</text>- </box>- {panelled ? (- <box flexDirection="row" height={1} gap={1} flexShrink={0}>- <text fg={tokens.subtle}>{padTo("trend", LABEL_W)}</text>- <Sparkline values={ctxSeries} fg={tokens.info} />- <Meter- pct={total > 0 ? (100 * shown.length) / total : 0}- width={meterW}- ramp={ramps.volume}- />- <text fg={tokens.trace}>{padStartTo(shownLegend, shownLegend.length)}</text>- </box>- ) : null}- </>- );-- if (!panelled) {- return (- <box flexDirection="column" paddingX={1} flexShrink={0}>- {body}- </box>- );- }- return (- <box flexShrink={0}>- <Panel title="shape" flexGrow={1}>- {body}- </Panel>- </box>- );-}diff --git a/packages/cli/src/picker/chrome.tsx b/packages/cli/src/picker/chrome.tsxindex ccf8f940..9337af08 100644--- a/packages/cli/src/picker/chrome.tsx+++ b/packages/cli/src/picker/chrome.tsx@@ -1,175 +1,153 @@/** @jsxImportSource @opentui/react *//**- * picker/chrome.tsx — the four one-row strips that frame the picker: header, load- * bar, filter and footer.+ * picker/chrome.tsx — the dialog frame and the four one-row strips inside it.*- * THEY ARE IN ONE FILE BECAUSE THEY SHARE ONE BUDGET. Every row spent here is a- * model row the list does not get, and at 80×24 the whole chrome allowance is six- * rows. Keeping them together is what makes that total visible to the next reader- * instead of scattered across four files that each look cheap.+ * THEY ARE IN ONE FILE BECAUSE THEY SHARE ONE ROW BUDGET. The dialog is drawn+ * INLINE, in the user's scrollback, so every row it spends is a row of their+ * terminal it consumed and did not give back — a very different economy from a+ * full-screen app, which pays nothing for chrome it draws inside a viewport it has+ * already taken. Seven rows of chrome and eleven of list is the whole allowance+ * (`layout.ts`), and keeping the strips together is what makes that total visible+ * to the next reader instead of scattered across four files that each look cheap.*- * NONE OF THEM IS A `Panel`. A bordered panel spends two rows of chrome to present- * one row of content, which is a 200% overhead on a 24-row terminal; the filter strip- * in particular is a caret and a count. Borders are for the two list panes, which- * have content worth framing.+ * THE DIALOG IS THE ONLY BORDER. The rejected build framed two panels and drew a+ * header strip, a load strip, a filter strip, a stats panel and a footer outside+ * them. One box, one title, one question.*/import type { ReactNode } from "react";import { LoadingRow } from "../tui/components/LoadingRow.js";import { A, C } from "../tui/theme.js";-import { displayWidth, padStartTo, truncate } from "../tui/viz/text.js";+import { displayWidth, truncate } from "../tui/viz/text.js";import { tokens } from "../tui/viz/tokens.js";-import { VERSION } from "../version.js";/**- * Two rows above 30 terminal rows, one below — the `CHROME.headerTwoRows` gate.+ * The bordered box, with its title composed left-and-right on the border line.*- * The second row is OpenTUI's own self-sizing horizontal rule: a `flexGrow={1}` box- * with `border={["top"]}`, which needs no width arithmetic at all and re-sizes itself- * on resize (`TabBar.tsx:50-56` uses the same idiom). It is dim, because rule 6 is- * dim the chrome and saturate the signal, and a separator is the purest chrome there- * is.+ * ONE COMPOSED TITLE, NOT TWO ELEMENTS, because OpenTUI's box draws exactly one+ * `title` and there is no second slot. The status half is padded into the same+ * string, which is what produces `╭─ choose a model ──── 312 models · 24/31 ─╮`+ * out of a single prop.*- * The wordmark is NOT drawn here. `printLogo` already wrote it to the primary screen- * before this renderer opened, and the picker runs on the alternate screen — so those- * nine rows come back for free and re-drawing them would spend the gain twice.+ * IT IS BUDGETED SHORT ON PURPOSE. MEASURED on the previous build: a title that+ * fills its border exactly is DROPPED — the box renders no title at all rather+ * than a clipped one — so the loudest label on the screen silently became an empty+ * border. Six columns of slack, and the status half is truncated before the name+ * half is, because "choose a model" is the thing the dialog is FOR.*/-export function PickerHeader({- right,- twoRows,+export function Dialog({+ title,+ status,+ width,+ marginLeft,+ children,}: {- /** The context line's right-hand group — counts, never a verdict. */- right: string;- twoRows: boolean;+ title: string;+ /** The right-hand group — counts, never a verdict. May be empty. */+ status: string;+ width: number;+ marginLeft: number;+ children?: ReactNode;}): ReactNode {return (- <box flexDirection="column" flexShrink={0}>- <box flexDirection="row" justifyContent="space-between" height={1} paddingX={1}>- <text>- <span fg={tokens.accent} attributes={A.bold}>- claudish- </span>- <span fg={tokens.subtle}> select a model</span>- </text>- <text>- <span fg={tokens.trace}>{`v${VERSION} · `}</span>- <span fg={tokens.subtle}>{right}</span>- </text>- </box>- {twoRows ? (- <box flexDirection="row" height={1} paddingX={1}>- <box flexGrow={1} border={["top"]} borderStyle="single" borderColor={tokens.border} />- </box>- ) : null}+ <box+ marginLeft={marginLeft}+ width={width}+ border+ borderStyle="rounded"+ borderColor={tokens.accent}+ backgroundColor={tokens.bgPanel}+ title={composeTitle(title, status, width)}+ titleAlignment="left"+ flexDirection="column"+ flexShrink={0}+ overflow="hidden"+ paddingLeft={1}+ paddingRight={1}+ >+ {children}</box>);}-/** One in-flight task, as the load bar draws it. */-export interface LoadTask {- /** Stable identity — also the React key. */- id: string;- label: string;- /** 0–100 for a determinate meter; omit for a shimmer. Never an invented denominator. */- pct?: number;- /** The figure between bar and label: `17/31`, `2.1s / 5.0s deadline`. */- value?: string;- width?: number;-}-/**- * The load bar — present ONLY while something is in flight, and absent (not empty)- * otherwise, because an empty flex item still eats a row.+ * Exported for the width test — the arithmetic, without a renderer.*- * Each task draws itself at the honesty its caller can actually support- * (`LoadingRow`'s own doc table): a determinate meter where work is countable, a- * travelling shimmer where nothing is, and a labelled elapsed figure where only a- * deadline is known. Nothing here invents a denominator.+ * The leading and trailing spaces are NOT decoration: the box draws the title+ * immediately after `╭─`, so without them the border reads `╭─choose a model──`+ * with the words fused to the rule. MEASURED in a frame capture, not guessed.*/-export function LoadBar({- tasks,- frame,- width,-}: { tasks: LoadTask[]; frame: number; width: number }): ReactNode {- if (tasks.length === 0) return null;- // THE ROW IS ONE ROW WHATEVER IS IN FLIGHT, so the tasks share its columns instead of- // overflowing it. MEASURED at 80 columns with all three up: the third task's bar- // painted and its LABEL was clipped away entirely — the worst possible truncation,- // because an unexplained bar is exactly the affordance this feature replaced. Each- // task now takes an equal slice, its meter shrinks toward the 4-cell floor before its- // label does, and the label ellipsises rather than vanishing.- const gaps = 2 * (tasks.length - 1);- const per = Math.max(12, Math.floor((width - 2 - gaps) / tasks.length));- return (- <box flexDirection="row" height={1} paddingX={1} gap={2} flexShrink={0}>- {tasks.map((t) => {- const value = t.value ?? "";- const bar = Math.max(4, Math.min(t.width ?? 12, per - displayWidth(value) - 8));- const label = truncate(t.label, Math.max(3, per - bar - displayWidth(value) - 2));- return (- <LoadingRow- key={t.id}- label={label}- frame={frame}- width={bar}- {...(t.pct === undefined ? {} : { pct: t.pct })}- {...(t.value === undefined ? {} : { value })}- />- );- })}- </box>- );+export function composeTitle(title: string, status: string, width: number): string {+ const room = Math.max(6, Math.floor(width) - 8);+ const left = truncate(title, room);+ if (status === "") return ` ${left} `;+ const right = truncate(status, Math.max(0, room - displayWidth(left) - 3));+ if (right === "") return ` ${left} `;+ const pad = Math.max(1, room - displayWidth(left) - displayWidth(right));+ return ` ${left}${" ".repeat(pad)}${right} `;}/**- * The filter strip: what is typed, and how much it left.+ * The filter row: what is typed, and what the list is ordered by.+ *+ * FILTER-FIRST, NO SEARCH MODE. Typing narrows the list immediately — the `/`+ * prompt is always drawn and the caret is always live, because a picker's fastest+ * path is a user who already roughly knows what they want typing three letters of+ * it. The previous build made filtering a MODE entered with `/`, which is one more+ * thing the reader has to know before the screen does anything.*- * `▍` is the caret (`resume-picker.tsx:1002`'s glyph), shown only while the strip- * owns the keyboard — a caret on an inactive field claims focus it does not have.- * The match count is right-aligned with `padStartTo` so it cannot jitter as the- * number of digits changes.+ * The right-hand group answers "why is this row at the top" while nothing is+ * typed, and "how much did I just cut" once something is.*/-export function FilterStrip({+export function FilterRow({value,- active,matches,total,width,- prompt = "filter",}: {value: string;- active: boolean;matches: number;total: number;width: number;- /** `filter` or `provider@model` — the same strip serves the custom-spec hatch. */- prompt?: string;}): ReactNode {- const count = `${matches} / ${total}`;- const room = Math.max(1, width - prompt.length - count.length - 6);+ const right = value === "" ? "newest first" : `${matches} of ${total}`;+ const room = Math.max(1, width - displayWidth(right) - 4);return (- <box flexDirection="row" justifyContent="space-between" height={1} paddingX={1} flexShrink={0}>+ <box flexDirection="row" justifyContent="space-between" height={1} flexShrink={0}><text>- <span fg={active ? tokens.accent : tokens.trace}>{`${prompt} `}</span>- <span fg={value ? tokens.text : tokens.trace}>- {value ? truncate(value, room) : active ? "" : "—"}- </span>- {active ? <span fg={tokens.accent}>▍</span> : null}+ <span fg={tokens.accent}>{"/ "}</span>+ <span fg={tokens.text}>{truncate(value, room)}</span>+ <span fg={tokens.accent}>▍</span></text><text>- {/* Warn only when a list EXISTS and the filter emptied it. `0 / 0` while the- list is still loading is not a warning, and painting it as one teaches the- reader to discount the colour everywhere else. */}- <span fg={matches === 0 && total > 0 ? tokens.warn : tokens.subtle}>- {padStartTo(count, count.length)}+ {/* Warn only when a list EXISTS and the filter emptied it. `0 of 0` while+ the list is still loading is not a warning, and painting it as one+ teaches the reader to discount the colour everywhere else. */}+ <span fg={value !== "" && matches === 0 && total > 0 ? tokens.warn : tokens.subtle}>+ {right}</span></text></box>);}+/**+ * The rule above the footer — OpenTUI's own self-sizing horizontal line.+ *+ * A `flexGrow={1}` box with `border={["top"]}` needs no width arithmetic at all+ * and re-sizes itself on resize (`TabBar.tsx:50-56` uses the same idiom). Dim,+ * because a separator is the purest chrome there is.+ */+export function Rule(): ReactNode {+ return (+ <box flexDirection="row" height={1} flexShrink={0}>+ <box flexGrow={1} border={["top"]} borderStyle="single" borderColor={tokens.border} />+ </box>+ );+}+/** One footer hint: the key, then what it does. */-interface Hint {+export interface Hint {key: string;label: string;/** Dimmed when the action is currently unavailable — shown, never hidden. */@@ -177,17 +155,17 @@ interface Hint {}/**- * Keyboard hints as two-tone chips — the `Footer.tsx:179-198` idiom, where the+ * Keyboard hints as two-tone pairs — the `Footer.tsx:179-198` idiom, where the* colour slot is deliberately ignored and emphasis is BRIGHTNESS rather than hue.* Hue is spent on severity everywhere else in this program; spending it here too- * would make the footer compete with the banner.+ * would make the footer compete with the failure banner.** Every action is one key and every key is listed. No deep menus, nothing* discoverable only by trying it.*/-export function PickerFooter({ hints }: { hints: Hint[] }): ReactNode {+export function Hints({ hints }: { hints: Hint[] }): ReactNode {return (- <box flexDirection="row" height={1} paddingX={1} gap={2} flexShrink={0}>+ <box flexDirection="row" height={1} gap={2} flexShrink={0} overflow="hidden">{hints.map((h) => (<text key={h.key}><span fg={h.on === false ? tokens.trace : C.strong} attributes={A.boldIf(h.on !== false)}>@@ -199,3 +177,66 @@ export function PickerFooter({ hints }: { hints: Hint[] }): ReactNode {</box>);}++/** One in-flight task, as the loading dialog draws it. */+export interface LoadTask {+ /** Stable identity — also the React key. */+ id: string;+ label: string;+ /** 0–100 for a determinate meter; omit for a shimmer. NEVER an invented denominator. */+ pct?: number;+ /** The figure after the bar: `8/31 checked`, `discovering… 3.2s`. */+ value?: string;+}++/**+ * The loading dialog's body: one named row per operation actually running.+ *+ * THE SHAPE OF EACH ROW IS THE HONESTY CONTRACT, and it is chosen by what the+ * caller can measure, not by what looks busiest:+ *+ * · The credential sweep has a real denominator — the roster is derived+ * synchronously, so `done/total` is work done over work TOTAL. It gets the+ * one determinate meter in the whole picker, and it EARNS it: a bounded value+ * with real variance over time is the one thing a gradient bar is for.+ * · The catalog warm races a 5 s wait against an 8 s refresh. Two numbers, so no+ * single denominator a bar could honestly be drawn against — shimmer.+ * · A roster discovery gets a deadline bar ONLY on the GET half, whose+ * `FETCH_TIMEOUT_MS` is published, and the label says `deadline` because a+ * deadline is not progress. The three fetcher providers publish nothing, so+ * they get elapsed and a shimmer. Inventing 5 000 ms for Devin would be a+ * guess rendered as a fact.+ */+export function LoadTasks({+ tasks,+ frame,+ labelWidth,+ barWidth,+}: {+ tasks: LoadTask[];+ frame: number;+ labelWidth: number;+ barWidth: number;+}): ReactNode {+ return (+ <box flexDirection="column" flexShrink={0}>+ {tasks.map((t) => (+ <LoadingRow+ key={t.id}+ label={t.label}+ frame={frame}+ width={barWidth}+ labelWidth={labelWidth}+ // `running`, NOT `ShimmerSpan`'s default `warn`. MEASURED in the light+ // palette, where `warn` is `#c2410c` and the catalog shimmer read as a+ // rust-red alarm bar — the one hue this app spends on `SUB` and on an+ // unverified `catalog` row. A fetch in flight is not a warning, and it+ // now matches the determinate meter's blue ramp beside it.+ fg={tokens.running}+ {...(t.pct === undefined ? {} : { pct: t.pct })}+ {...(t.value === undefined ? {} : { value: t.value })}+ />+ ))}+ </box>+ );+}diff --git a/packages/cli/src/picker/detail.tsx b/packages/cli/src/picker/detail.tsxindex 30643576..43367ccc 100644--- a/packages/cli/src/picker/detail.tsx+++ b/packages/cli/src/picker/detail.tsx@@ -1,25 +1,24 @@/** @jsxImportSource @opentui/react *//**- * picker/detail.tsx — the two pinned blocks under the two lists.+ * picker/detail.tsx — the one row under the list that says what Enter will do.*- * THEY EXIST FOR PARITY FIRST AND FOR THE SCREENSHOT SECOND. The inquirer picker- * showed a description under both prompts — `ProviderChoice.description` under the- * provider list and `ModelInfo.description` under the model list — and a rewrite that- * silently dropped both would be a regression dressed as a redesign. The model block- * also answers the one question a picker must never leave open: what EXACTLY does- * Enter return? It prints the spec verbatim.+ * IT ANSWERS THE QUESTION A PICKER MUST NEVER LEAVE OPEN: what EXACTLY does Enter+ * return? It prints the spec verbatim — `[email protected]`, the same string+ * `buildExplicitModelSpec` hands the launcher and the same string the user could+ * have typed on argv — so the picker teaches its own CLI instead of hiding behind+ * a private label.*- * The screenshot benefit is the same shape as `resume-picker.tsx`'s activity calendar:- * a scrollbox with fewer rows than viewport leaves the rest of its panel empty, and a- * pinned, content-sized sibling occupies that space with something worth reading.- * `flexShrink={0}` is mandatory on both — a scrollbox's intrinsic height is its ENTIRE- * content, and Yoga spreads that shortfall across every sibling, which collapses an- * unprotected block to one row and overprints its children.+ * ONE ROW, NOT THREE. The previous build pinned a description block under each of+ * its two lists. Descriptions are per-model editorial text that the slim catalog+ * mostly does not carry, and two rows of prose cost two rows of list on a dialog+ * whose whole list is eleven rows. What survives is the three facts that differ+ * between models a reader is choosing BETWEEN: the exact spec, the capabilities,+ * and how old it is.*- * BOTH ARE HEIGHT-GATED BY THEIR CALLER, not here: on a 24-row terminal every row- * belongs to the list, and a detail block would trade two model rows — two GRAPHICS- * rows — for two rows of prose, which is exactly the wrong direction for the whole-frame- * density count.+ * CAPABILITIES ARE EXCEPTION-ONLY AND THEY LIVE HERE, NOT ON EVERY ROW. The+ * previous build printed `[TRV]` on all 21 rows of a roster where every model had+ * all three — a column with no variance, in the place a reader is scanning names.+ * On the selected row they are worth three words; on forty rows they are noise.*/import type { ReactNode } from "react";@@ -29,39 +28,42 @@ import { truncate } from "../tui/viz/text.js";import { tokens } from "../tui/viz/tokens.js";/**- * Greedy word wrap to at most `maxLines` rows, with the last row ellipsised.+ * `tools reasoning vision`, and ONLY the ones the catalog affirmatively says are+ * there.*- * Built on `displayWidth` through `truncate` rather than on `String.length`, because a- * CJK model description counts double in cells and half in code units — the same reason- * `padEnd`/`slice` are banned in `viz/text.ts`.+ * `undefined` is not `false`. The slim catalog carries `supportsTools` for most+ * models and `supportsReasoning` for some, and a missing flag means "the catalog+ * does not say" — printing its absence would be claiming a fact nobody has.*/-export function wrapWords(text: string, width: number, maxLines: number): string[] {- const w = Math.max(1, Math.floor(width));- const words = text.split(/\s+/).filter(Boolean);- const lines: string[] = [];- let line = "";- for (const word of words) {- const next = line === "" ? word : `${line} ${word}`;- if (next.length <= w) {- line = next;- continue;- }- if (line !== "") lines.push(line);- line = word;- if (lines.length === maxLines) break;- }- if (lines.length < maxLines && line !== "") lines.push(line);- return lines.slice(0, maxLines).map((l) => truncate(l, w));+export function capabilityWords(model: ModelInfo): string[] {+ const words: string[] = [];+ if (model.supportsTools === true) words.push("tools");+ if (model.supportsReasoning === true) words.push("reasoning");+ if (model.supportsVision === true) words.push("vision");+ return words;}/**- * What Enter will return, and what the model is.+ * The detail line's text, as one pure function so the sentence can be asserted+ * without a renderer.*- * The spec is rendered in the accent colour and NOT truncated away: it is the value the- * user is choosing, and a picker that hides its own return value is asking them to- * guess.+ * The one exception that is LOUD rather than quiet: a model the catalog says+ * takes no tools cannot drive Claude Code at all, which is disqualifying rather+ * than comparative. It is stated in words on the row the cursor is on, in the+ * error colour, instead of being one dim letter in a column of forty.*/-export function ModelDetail({+export function detailText(spec: string, model: ModelInfo): { text: string; warn: string } {+ const parts = [spec];+ const caps = capabilityWords(model);+ if (caps.length > 0) parts.push(caps.join(" "));+ if (model.releaseDate) parts.push(model.releaseDate.slice(0, 7));+ return {+ text: parts.join(" · "),+ warn: model.supportsTools === false ? "no tool support — Claude Code cannot run it" : "",+ };+}++export function SelectionLine({model,spec,width,@@ -70,71 +72,31 @@ export function ModelDetail({spec: string | null;width: number;}): ReactNode {- const inner = Math.max(8, Math.floor(width) - 2);+ const inner = Math.max(8, Math.floor(width));if (model === null || spec === null) {return (- <box flexDirection="column" flexShrink={0} paddingX={1}>+ <box height={1} flexShrink={0}><text><span fg={tokens.trace}>nothing selected</span></text></box>);}- const date = model.releaseDate ? ` · ${model.releaseDate.slice(0, 7)}` : "";- const head = `${spec}${date}`;- const body = model.description ?? "";+ const { text, warn } = detailText(spec, model);+ const room = warn === "" ? inner : Math.max(8, inner - warn.length - 3);return (- <box flexDirection="column" flexShrink={0} paddingX={1}>+ <box height={1} flexShrink={0}><text><span fg={tokens.accent} attributes={A.bold}>- {truncate(head, inner)}+ {truncate(text, room)}</span>+ {warn === "" ? null : (+ <>+ <span fg={tokens.subtle}>{" · "}</span>+ <span fg={tokens.error}>{warn}</span>+ </>+ )}</text>- {body === "" ? null : (- <text>- <span fg={tokens.subtle}>{truncate(body, inner)}</span>- </text>- )}- </box>- );-}--/**- * The selected provider, in the rail's own width.- *- * The env var is named even when the provider is ready, because it is the single most- * useful string when something later goes wrong — a stale value in the shell shadows- * stored credentials, and "check your API key" gives no clue which name to inspect.- * That is the same reasoning `formatDiscoveryFailureNotice` gives for naming it in a- * failure notice; here it is available BEFORE the failure.- */-export function ProviderDetail({- label,- description,- envVar,- width,-}: {- label: string;- description: string;- envVar: string;- width: number;-}): ReactNode {- const inner = Math.max(6, Math.floor(width) - 2);- return (- <box flexDirection="column" flexShrink={0} paddingX={1}>- <text>- <span fg={tokens.accent}>{truncate(label, inner)}</span>- </text>- {wrapWords(description, inner, 3).map((line) => (- <text key={line}>- <span fg={tokens.subtle}>{line}</span>- </text>- ))}- {envVar === "" ? null : (- <text>- <span fg={tokens.trace}>{truncate(envVar, inner)}</span>- </text>- )}</box>);}diff --git a/packages/cli/src/picker/fixtures/fixture-source.ts b/packages/cli/src/picker/fixtures/fixture-source.tsindex 608769f2..6ce19416 100644--- a/packages/cli/src/picker/fixtures/fixture-source.ts+++ b/packages/cli/src/picker/fixtures/fixture-source.ts@@ -19,7 +19,7 @@* none of them is reachable from outside:** · `loading` the warm path settles in under 100 ms, so the in-flight frames- * (V2/V3/V4) cannot be photographed on a real run at all.+ * cannot be photographed on a real run at all.* · `empty` a provider that answers correctly with nothing chat-capable.* · `filtered` a provider that serves only embeddings or wildcard routes.* · `timeout` an unreachable endpoint, on demand.@@ -31,9 +31,8 @@import type { ModelInfo, PickerDiscoveryOutcome } from "../../model-selector.js";import {- type CatalogLoad,type PickerDataSource,- type RailChoice,+ type PickerProviderChoice,createPickerDataSource,} from "../PickerDataSource.js";@@ -47,7 +46,7 @@ const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms/*** Scenarios that forge a discovery OUTCOME also claim discovery for every provider,- * so the state is on screen wherever the cursor happens to start. Without that, a+ * so the state is on screen wherever the cursor happens to be scoped. Without that, a* capture would have to drive keystrokes to a particular provider and would break the* moment the picker order changed.*/@@ -58,17 +57,16 @@ export function createFixtureDataSource(name: string): PickerDataSource {const real = createPickerDataSource();const forced = FORCED_OUTCOME.has(scenario);// `loading` claims discovery too — not to forge an outcome (it has none; it never- // settles) but so that whichever provider the cursor starts on exercises the ROSTER- // indicator. Without it the first provider is OpenRouter, which has no discovery, and- // the one affordance with a published deadline would never appear in a capture.+ // settles) but so that a scoped provider exercises the ROSTER indicator, whose+ // deadline shape is otherwise unreachable in a capture.const claimsDiscovery = forced || scenario === "loading";return {- providerRoster(): RailChoice[] {+ providerRoster(): PickerProviderChoice[] {return real.providerRoster().map((r) =>- claimsDiscovery ? { ...r, hasDiscovery: true, discoveryShape: "deadline" } : r+ claimsDiscovery ? { ...r, hasDiscovery: true, discoveryShape: "deadline" as const } : r);},@@ -78,8 +76,8 @@ export function createFixtureDataSource(name: string): PickerDataSource {async *probeCredentials(names: string[]): AsyncIterable<[string, boolean]> {// EVERY PROVIDER READY, and that is a forgery with a purpose: a capture runs with// credential sources disabled so it cannot raise a 1Password or Keychain prompt on- // the user's desktop, which leaves the real rail three rows long and says nothing- // about how the rail looks for a configured user.+ // the user's desktop, which leaves the real roster three rows long and says nothing+ // about how the list looks for a configured user.for (const n of names) {if (scenario === "loading") await sleep(600);yield [n, true];@@ -87,8 +85,12 @@ export function createFixtureDataSource(name: string): PickerDataSource {if (scenario === "loading") await NEVER; // hold the `done/total` meter mid-sweep},- loadCatalog(): Promise<CatalogLoad> {- return scenario === "loading" ? NEVER : real.loadCatalog();+ ensureCatalog(): Promise<void> {+ return scenario === "loading" ? NEVER : real.ensureCatalog();+ },++ servedModels(provider: string): ModelInfo[] {+ return real.servedModels(provider);},async discoverRoster(provider: string): Promise<PickerDiscoveryOutcome> {@@ -98,7 +100,7 @@ export function createFixtureDataSource(name: string): PickerDataSource {// The fallback list is the REAL vendor catalog for this provider, because the// defect being rendered is precisely that an unmarked fallback list reads as a// healthy short roster — and that only shows on real rows.- const fallbackRows = await real.catalogModels(provider).catch((): ModelInfo[] => []);+ const fallbackRows = real.servedModels(provider);const displayName = real.displayName(provider);if (scenario === "empty") {@@ -159,9 +161,5 @@ export function createFixtureDataSource(name: string): PickerDataSource {fallbackRows,};},-- catalogModels(provider: string): Promise<ModelInfo[]> {- return scenario === "loading" ? NEVER : real.catalogModels(provider);- },};}diff --git a/packages/cli/src/picker/hooks/useCatalogModels.ts b/packages/cli/src/picker/hooks/useCatalogModels.tsdeleted file mode 100644index 55322f5c..00000000--- a/packages/cli/src/picker/hooks/useCatalogModels.ts+++ /dev/null@@ -1,114 +0,0 @@-/**- * useCatalogModels — the cross-vendor catalog (A2) and the per-provider vendor list- * (A12), with one promise memo between them.- *- * THE MEMO IS PORTED, NOT INVENTED: `selectModel` keeps a `remoteQueryCache` of- * `Promise<ModelInfo[]>` keyed by query (`model-selector.ts:693-714`), so a provider- * revisited during one picker session costs nothing. Caching the PROMISE rather than- * the result is what makes two rapid arrow-key presses share one request instead of- * racing two.- *- * THE PICKER STAYS USABLE IF THE CATALOG NEVER LANDS (edge case 8). The rail derives- * from provider definitions, not from the catalog, so provider selection, every- * discovery provider, the local/user-deployed providers and the custom-spec hatch all- * work with a dead catalog. What degrades is exactly what the catalog supplies: the- * vendor lists for non-discovery providers, which then show a `failed` notice instead- * of rows. No path reaches a blank frame.- */--import { useCallback, useEffect, useRef, useState } from "react";-import type { ModelInfo } from "../../model-selector.js";-import type { CatalogLoad, PickerDataSource } from "../PickerDataSource.js";--/** The shape `ProbeState` established (`hooks/useRouteProbe.ts:28-33`) — copied, not reinvented. */-export type LoadPhase = "idle" | "loading" | "ready" | "failed";--export interface CatalogState {- phase: LoadPhase;- /** Recommended ids, lower-cased — the corpus behind a row's `REC` marker. */- recommended: Set<string>;- /** How many models the cross-vendor load returned. A count, not a verdict. */- size: number;-}--export interface ProviderListState {- phase: LoadPhase;- rows: ModelInfo[];-}--export interface CatalogModelsState {- catalog: CatalogState;- /** The selected provider's vendor list, when it is a provider that needs one. */- list: ProviderListState;-}--const IDLE: ProviderListState = { phase: "idle", rows: [] };--export function useCatalogModels(- source: PickerDataSource,- provider: string | null,- /** False for a discovery provider — its list comes from `useProviderDiscovery`. */- wanted: boolean-): CatalogModelsState {- const [catalog, setCatalog] = useState<CatalogState>({- phase: "loading",- recommended: new Set(),- size: 0,- });- const [lists, setLists] = useState<Record<string, ProviderListState>>({});- const inflight = useRef(new Map<string, Promise<ModelInfo[]>>());-- useEffect(() => {- let live = true;- void (async () => {- try {- const load: CatalogLoad = await source.loadCatalog();- if (!live) return;- setCatalog({- phase: "ready",- recommended: new Set(load.recommended.map((m) => m.id.toLowerCase())),- size: load.top.length + load.recommended.length,- });- } catch {- if (!live) return;- // A failed catalog is a NOTICE, not an error: the picker still works, and- // painting red for a degraded-but-functional screen teaches the user to- // ignore red.- setCatalog({ phase: "failed", recommended: new Set(), size: 0 });- }- })();- return () => {- live = false;- };- }, [source]);-- const load = useCallback(- (name: string): void => {- const cache = inflight.current;- if (cache.has(name)) return;- const request = source.catalogModels(name);- cache.set(name, request);- setLists((prev) => ({ ...prev, [name]: { phase: "loading", rows: [] } }));- void request.then(- (rows) => setLists((prev) => ({ ...prev, [name]: { phase: "ready", rows } })),- () => {- // Dropped from the memo so a retry is possible — a cached rejection would- // make one transient network failure permanent for the whole session.- cache.delete(name);- setLists((prev) => ({ ...prev, [name]: { phase: "failed", rows: [] } }));- }- );- },- [source]- );-- useEffect(() => {- if (provider === null || !wanted) return;- load(provider);- }, [provider, wanted, load]);-- return {- catalog,- list: provider !== null && wanted ? (lists[provider] ?? IDLE) : IDLE,- };-}diff --git a/packages/cli/src/picker/hooks/useDelayedVisible.ts b/packages/cli/src/picker/hooks/useDelayedVisible.tsdeleted file mode 100644index d9be8626..00000000--- a/packages/cli/src/picker/hooks/useDelayedVisible.ts+++ /dev/null@@ -1,49 +0,0 @@-/**- * useDelayedVisible — an affordance that is honest when the await is FAST.- *- * The catalog fetches are mem- and disk-cached and the credential fan-out can finish- * before the first paint, so a naive loading bar flashes for one or two 100 ms ticks- * on every warm start. That reads as a glitch, not as progress, and it is the same- * class of dishonesty as a bar with an invented denominator: it tells the user- * something happened that they cannot perceive.- *- * So: show nothing for the first `showAfterMs`, and once shown keep it for at least- * `keepForMs`. A task that settles inside the first window is never announced; a task- * that is announced does not vanish mid-blink.- *- * THE CONSEQUENCE IS STATED RATHER THAN DISCOVERED LATER: the loading states (V2, V3)- * are photographed against the FIXTURE data source by design, because the real warm- * path is too fast to capture. That is not a weaker test than a live capture — it is- * the only reproducible one.- */--import { useEffect, useRef, useState } from "react";--export function useDelayedVisible(active: boolean, showAfterMs = 120, keepForMs = 300): boolean {- const [visible, setVisible] = useState(false);- const shownAt = useRef<number | null>(null);-- useEffect(() => {- if (active) {- if (visible) return;- const t = setTimeout(() => {- shownAt.current = Date.now();- setVisible(true);- }, showAfterMs);- return () => clearTimeout(t);- }- if (!visible) return;- // Hold for the REMAINDER of the minimum, not the whole of it: a task that ran- // for 2 s has already been seen, and re-holding the bar for another 300 ms after- // it finished would make the screen feel slower than it is.- const elapsed = shownAt.current === null ? keepForMs : Date.now() - shownAt.current;- const hold = Math.max(0, keepForMs - elapsed);- const t = setTimeout(() => {- shownAt.current = null;- setVisible(false);- }, hold);- return () => clearTimeout(t);- }, [active, visible, showAfterMs, keepForMs]);-- return visible;-}diff --git a/packages/cli/src/picker/hooks/usePickerModels.ts b/packages/cli/src/picker/hooks/usePickerModels.tsnew file mode 100644index 00000000..93cc1994--- /dev/null+++ b/packages/cli/src/picker/hooks/usePickerModels.ts@@ -0,0 +1,146 @@+/**+ * usePickerModels — ONE flat cross-provider list, and the per-provider counts the+ * provider dialog prints.+ *+ * THIS HOOK IS THE FIX FOR "SUPER UNCLEAR WHAT IS HAPPENING". The build it+ * replaces asked the user which PROVIDER before it would answer which MODEL, and+ * put a cursor in each of the two lists with only a border colour to say which one+ * the arrow keys drove. One list has one cursor. So the provider stops being a+ * navigation step and becomes a COLUMN — the routing shortcut, which is also the+ * string the user could have typed on argv.+ *+ * IT IS AFFORDABLE BECAUSE `servedModels` IS SYNCHRONOUS. The obvious+ * implementation — `loadModelsForPickerProvider` per provider — was MEASURED at+ * 10 s for 22 concurrent owner-slug queries, every one of which aborted on its+ * shared timeout and returned zero rows. That is not a slow picker; it is the+ * picker saying "this provider has no models", which is the exact complaint this+ * feature exists to remove. `PickerDataSource.servedModels` reads the catalog's+ * local served-by index instead, in about a millisecond, and+ * `model-catalog.ts:servedByVendor` records why that index is the same authority+ * rather than a second one.+ *+ * ONLY CREDENTIALLED PROVIDERS CONTRIBUTE ROWS, and the absence is EXPLAINED+ * rather than silent: the count in the dialog title reads `24/31 providers`, and+ * `p` lists all 31 with the reason each unready one is not there. A row the user+ * cannot launch is worse than a row that is missing — it fails at+ * `validateApiKeysForModels`, after the picker has closed.+ *+ * ONE `servedModels` CALL PER PROVIDER PER OPEN, held in a ref. Readiness arrives+ * as ~31 separate `setState`s (that incremental fill IS the loading affordance),+ * so a memo that re-derived every provider's rows on each of them would read the+ * slim cache ~500 times.+ */++import { useEffect, useMemo, useRef, useState } from "react";+import {+ type ModelInfo,+ buildExplicitModelSpec,+ compareByReleaseDateDesc,+ resolveProviderDisplayPrice,+ resolveProviderExternalId,+} from "../../model-selector.js";+import type { PickerDataSource, PickerProviderChoice } from "../PickerDataSource.js";+import { priceLabel } from "../rows.js";++/** One choice in the flat list: a model AND the provider that would serve it. */+export interface PickerRow {+ /** `ProviderDefinition.name` — what every source call is keyed by. */+ provider: string;+ /** The routing shortcut printed in the provider column: `or@`, `kc@`. */+ shortcut: string;+ /** Exactly what Enter returns. */+ spec: string;+ /** Already reshaped by `priceLabel` — `$2.25`, `SUB`, `FREE`, `local`. */+ price: string;+ model: ModelInfo;+}++/** The shape `ProbeState` established (`hooks/useRouteProbe.ts:28-33`) — copied, not reinvented. */+export type LoadPhase = "idle" | "loading" | "ready";++export interface PickerModelsState {+ /** Every (provider, model) pair a credentialled provider serves, newest first. */+ rows: PickerRow[];+ /** Rows per provider — the `p` dialog's count column. */+ counts: ReadonlyMap<string, number>;+ /** Whether the cross-vendor catalog warm has settled. */+ phase: LoadPhase;+}++/**+ * One model under one provider, as a row.+ *+ * EXPORTED BECAUSE THERE ARE TWO LISTS AND THEY MUST NOT DIFFER. The flat list is+ * built from the served-by index; a scoped list may instead be a live discovery+ * roster or its catalog fallback. If those paths built rows differently, a fallback+ * list would be distinguishable by ACCIDENT — a different price string, a different+ * spec spelling — rather than by the three deliberate provenance encodings, and a+ * reader would learn to read the accident instead of the mark.+ */+export function toPickerRow(choice: PickerProviderChoice, model: ModelInfo): PickerRow {+ return {+ provider: choice.value,+ shortcut: choice.shortcut,+ // The SAME spec builder the classic path uses, with the provider's own+ // externalId — `or@openai/gpt-5`, not the catalog's bare key. Every row is+ // provider-scoped, so no bare Claude name can leave this picker.+ spec: buildExplicitModelSpec(choice.value, resolveProviderExternalId(choice.value, model)),+ price: priceLabel(resolveProviderDisplayPrice(choice.value, model), choice.billing),+ model,+ };+}++export function usePickerModels(+ source: PickerDataSource,+ roster: PickerProviderChoice[],+ /** Providers whose credential probe came back true. */+ ready: ReadonlySet<string>+): PickerModelsState {+ const [phase, setPhase] = useState<LoadPhase>("loading");+ const cache = useRef(new Map<string, PickerRow[]>());++ useEffect(() => {+ let live = true;+ void (async () => {+ // Bounded, and documented never to throw. A cold cache is the only case+ // this actually waits for; a warm one returns on the first line.+ await source.ensureCatalog();+ if (!live) return;+ // The warm may have REPLACED the slim cache on disk, so anything derived+ // from it before now is stale by construction.+ cache.current.clear();+ setPhase("ready");+ })();+ return () => {+ live = false;+ };+ }, [source]);++ // The ready set is re-derived per render by `usePickerProviders`, so it cannot+ // be a memo dependency directly — a new Set every frame would rebuild the whole+ // list every frame. Its SIGNATURE can.+ const signature = useMemo(() => [...ready].sort().join(","), [ready]);++ return useMemo(() => {+ if (phase !== "ready") return { rows: [], counts: new Map(), phase };+ const counts = new Map<string, number>();+ const rows: PickerRow[] = [];+ for (const choice of roster) {+ let cached = cache.current.get(choice.value);+ if (cached === undefined) {+ cached = source.servedModels(choice.value).map((m) => toPickerRow(choice, m));+ cache.current.set(choice.value, cached);+ }+ // The COUNT is what the catalog serves, credentials or not — the provider+ // dialog shows it beside `needs OPENAI_API_KEY`, and "0 models" there would+ // read as "this provider has nothing" rather than "you have no key".+ counts.set(choice.value, cached.length);+ if (ready.has(choice.value)) rows.push(...cached);+ }+ // Newest first, across providers. The same comparator the classic picker+ // uses, so two lists of the same models cannot disagree about their order.+ rows.sort((a, b) => compareByReleaseDateDesc(a.model, b.model));+ return { rows, counts, phase };+ // biome-ignore lint/correctness/useExhaustiveDependencies: `signature` is the stable projection of `ready`; depending on the Set itself rebuilds every frame+ }, [source, roster, phase, signature, ready]);+}diff --git a/packages/cli/src/picker/hooks/usePickerProviders.ts b/packages/cli/src/picker/hooks/usePickerProviders.tsindex 03f3173e..937dc73f 100644--- a/packages/cli/src/picker/hooks/usePickerProviders.ts+++ b/packages/cli/src/picker/hooks/usePickerProviders.ts@@ -1,22 +1,25 @@/**- * usePickerProviders — the rail's roster, and the credential probe that fills it in.+ * usePickerProviders — the provider roster, and the credential probe that fills it+ * in.*- * FRAME ONE IS NEVER BLANK, STRUCTURALLY. The roster comes from- * `source.providerRoster()`, which is synchronous and derived from the provider- * definitions, so the first render already lists every pickable provider with a `◌`- * pending marker. The probe then flips each row to `●` or `○` as it settles. That- * incremental fill IS the loading affordance for the ~30 `credentials.isAvailable`- * calls — each of which may read env, config, an OAuth file, the macOS Keychain and- * the 1Password SDK — and it is why `probeCredentials` is an AsyncIterable rather- * than one awaited map: a map would hold every row hostage to the slowest handshake.+ * `done/total` FROM THIS HOOK IS THE ONE DETERMINATE BAR IN THE PICKER, and it+ * earns the bar because both numbers are real: the roster is derived+ * synchronously from the provider definitions, so `total` is known before the+ * first probe starts, and `done` is work actually completed. Nothing else the+ * picker waits on has a denominator, and nothing else gets a meter.+ *+ * `probeCredentials` is an AsyncIterable rather than one awaited map for the same+ * reason: each of ~31 `credentials.isAvailable` calls may read env, config, an+ * OAuth file, the macOS Keychain and the 1Password SDK, and a single awaited map+ * would hold every answer hostage to the slowest handshake.** MEMBERSHIP IN THE STEADY STATE IS IDENTICAL TO TODAY'S. The old picker filtered- * unready providers out entirely (`getProviderChoices`), which made the first frame- * wait for every probe. This mounts the UNFILTERED roster and then collapses the- * unready ones into one dim, non-selectable summary row — so the rail does not- * lengthen, no row can be picked that would fail later at `validateApiKeysForModels`,- * and the absence is EXPLAINED rather than silent, which is the principle the rest of- * the feature is built on.+ * unready providers out entirely (`getProviderChoices`), which made the first+ * frame wait for every probe. This mounts the UNFILTERED roster: a provider with+ * no credential contributes no MODEL rows (they would fail later at+ * `validateApiKeysForModels`, after the picker has closed) but it keeps its place+ * in the `p` dialog, with the env var it wants — so the absence is EXPLAINED+ * rather than silent, which is the principle the rest of the feature is built on.** ONE FAN-OUT PER MOUNT, never per render: `selectModel` hoisted this call for* exactly that reason (its comment at `model-selector.ts:660-668`), and the profile@@ -24,20 +27,24 @@*/import { useEffect, useMemo, useState } from "react";-import type { PickerDataSource, RailChoice } from "../PickerDataSource.js";+import type { PickerDataSource, PickerProviderChoice } from "../PickerDataSource.js";import type { Readiness } from "../rows.js";-export interface RailRow extends RailChoice {+export interface ProviderState extends PickerProviderChoice {readiness: Readiness;}export interface PickerProvidersState {+ /** The roster as handed over — stable identity, for downstream memos. */+ roster: PickerProviderChoice[];/** Every pickable provider, in picker order, readiness included. */- rows: RailRow[];- /** Ready providers — the selectable ones. */- ready: RailRow[];+ rows: ProviderState[];+ /** Ready providers — the ones that contribute model rows. */+ ready: ProviderState[];+ /** The same set, by name, for the flat list's membership test. */+ readySet: ReadonlySet<string>;/** Settled-but-unready providers, collapsed behind one summary row. */- missing: RailRow[];+ missing: ProviderState[];/** Probes settled so far. */done: number;/** Probes in total — known synchronously, which is what makes this real progress. */@@ -76,15 +83,19 @@ export function usePickerProviders(source: PickerDataSource): PickerProvidersSta};}, [source, roster]);- const rows: RailRow[] = roster.map((r) => {+ const rows: ProviderState[] = roster.map((r) => {const settled = readiness[r.value];return { ...r, readiness: settled === undefined ? "pending" : settled ? "ready" : "missing" };});const done = Object.keys(readiness).length;+ const readyRows = rows.filter((r) => r.readiness === "ready");+return {+ roster,rows,- ready: rows.filter((r) => r.readiness === "ready"),+ ready: readyRows,+ readySet: new Set(readyRows.map((r) => r.value)),missing: rows.filter((r) => r.readiness === "missing"),done,total: roster.length,diff --git a/packages/cli/src/picker/hooks/useProviderDiscovery.ts b/packages/cli/src/picker/hooks/useProviderDiscovery.tsindex 33038771..ffc49c1c 100644--- a/packages/cli/src/picker/hooks/useProviderDiscovery.ts+++ b/packages/cli/src/picker/hooks/useProviderDiscovery.ts@@ -35,6 +35,20 @@ export interface DiscoveryState {startedAt: number | null;/** Every outcome seen this session, so a revisit costs nothing. */seen: ReadonlyMap<string, PickerDiscoveryOutcome>;+ /**+ * Discard this provider's settled outcome and ask again.+ *+ * A DISCOVERY FAILURE IS OFTEN TRANSIENT AND THE PREVIOUS BUILD HAD NO WAY BACK.+ * A timeout, a laptop that just came off a captive portal, a key pasted into+ * another shell — every one of those is fixed by asking a second time, and the+ * only recourse the picker offered was to quit it and start again, which throws+ * away the whole credential sweep. `r` is the answer.+ *+ * It clears the memo as well as the outcome, deliberately: the memo exists so+ * that ARROWING back to a provider costs nothing, and a retry is the one moment+ * where "you already asked" is the wrong answer.+ */+ retry: (provider: string) => void;}export function useProviderDiscovery(@@ -85,6 +99,24 @@ export function useProviderDiscovery([source]);+ const retry = useCallback(+ (name: string): void => {+ inflight.current.delete(name);+ reported.current.delete(name);+ setOutcomes((prev) => {+ const next = new Map(prev);+ next.delete(name);+ return next;+ });+ // The elapsed clock restarts HERE rather than inside `load`, whose own+ // `setStarted` is deliberately write-once so an arrow-key revisit does not+ // reset a running counter. A retry is a new request and gets a new clock.+ setStarted((prev) => ({ ...prev, [name]: Date.now() }));+ load(name);+ },+ [load]+ );+useEffect(() => {if (provider === null || !wanted) return;load(provider);@@ -95,6 +127,7 @@ export function useProviderDiscovery(return {outcome,busy,+ retry,startedAt: busy && provider !== null ? (started[provider] ?? null) : null,seen: outcomes,};diff --git a/packages/cli/src/picker/layout.test.ts b/packages/cli/src/picker/layout.test.tsindex 77af000b..8f8ef447 100644--- a/packages/cli/src/picker/layout.test.ts+++ b/packages/cli/src/picker/layout.test.ts@@ -1,25 +1,30 @@import { describe, expect, test } from "bun:test";/**- * The column ladder, asserted so it can FAIL ON ITS OWN DEFECT.+ * The dialog's two budgets — columns in a row, rows in a box — asserted so they can+ * FAIL ON THEIR OWN DEFECT.*- * An earlier formulation of this test checked only that a row's cells did not EXCEED- * the budget. That would have passed the very configuration the screenshot gate fails:- * a row that sums to 39 columns short of its width leaves a dead tail, and a row whose- * context meter has collapsed to one cell is a coloured dot. A test that cannot fail on- * the defect it guards is not a guard.+ * An earlier formulation of the column test checked only that a row's cells did not+ * EXCEED the budget. That would have passed the very configuration a colour+ * screenshot fails: a row that sums 39 columns short of its width leaves a dead tail+ * the panel paints as background. A test that cannot fail on the defect it guards is+ * not a guard, so the claim is that the cells sum EXACTLY.*- * So the three claims are: the cells sum EXACTLY to the row width, the context meter- * never drops below `MIN_CTX_CELLS`, and no cell is ever negative — over every width- * from 40 to 200, which covers both mandatory capture sizes and everything between.+ * The row budget is the one that inline mode makes load-bearing. The dialog reserves+ * rows by scrolling the user's terminal, so a populated dialog and a+ * discovery-failure dialog that were different heights would rewrite rows already+ * handed back to the shell. `deriveDialogLayout` takes the banner's rows out of the+ * LIST's rather than adding them to the box, and that invariant is asserted here+ * rather than left to a screenshot.*/import {- CHROME,- MIN_CTX_CELLS,- derivePanes,- deriveRailLayout,+ CHROME_ROWS,+ MAX_DIALOG_ROWS,+ MAX_DIALOG_WIDTH,+ MAX_LIST_ROWS,+ deriveDialogLayout,deriveRowLayout,- railLayoutTotal,rowLayoutTotal,+ scrollWindow,} from "./layout.js";const WIDTHS = Array.from({ length: 161 }, (_, i) => i + 40);@@ -32,11 +37,12 @@ describe("deriveRowLayout", () => {expect(wrong).toEqual([]);});- test("the context meter never drops below the floor", () => {- const thin = WIDTHS.map((w) => ({ w, ctx: deriveRowLayout(w).ctx })).filter(- ({ ctx }) => ctx < MIN_CTX_CELLS- );- expect(thin).toEqual([]);+ test("cells still sum EXACTLY when the fallback mark is reserved", () => {+ const wrong = WIDTHS.map((w) => ({+ w,+ sum: rowLayoutTotal(deriveRowLayout(w, { mark: true })),+ })).filter(({ w, sum }) => sum !== w);+ expect(wrong).toEqual([]);});test("no cell is ever negative", () => {@@ -46,61 +52,107 @@ describe("deriveRowLayout", () => {expect(bad).toEqual([]);});- test("the ladder drops cells in the stated order as the width shrinks", () => {- // Widest: everything. The release date is the first thing to go, then the price- // METER — never its numeral, and never the context meter.- expect(deriveRowLayout(117).date).toBeGreaterThan(0);- expect(deriveRowLayout(80).date).toBe(0);- expect(deriveRowLayout(80).price).toBeGreaterThan(0);- expect(deriveRowLayout(57).price).toBe(0);- expect(deriveRowLayout(57).priceNum).toBeGreaterThan(0);- expect(deriveRowLayout(40).ctx).toBeGreaterThanOrEqual(MIN_CTX_CELLS);+ test("the model name is the elastic cell — it grows, and nothing else does", () => {+ // The whole point of deleting the five-tier ladder: one layout at every width,+ // with every column the reader compares on held constant and the NAME absorbing+ // the difference. A regression that started widening the price column would show+ // up here and nowhere else.+ const narrow = deriveRowLayout(72);+ const wide = deriveRowLayout(88);+ expect(wide.id - narrow.id).toBe(16);+ expect(wide.provider).toBe(narrow.provider);+ expect(wide.ctx).toBe(narrow.ctx);+ expect(wide.price).toBe(narrow.price);+ });++ test("the fallback mark comes out of the NAME, never out of a compared column", () => {+ const live = deriveRowLayout(72);+ const fallback = deriveRowLayout(72, { mark: true });+ expect(fallback.provider).toBe(live.provider);+ expect(fallback.ctx).toBe(live.ctx);+ expect(fallback.price).toBe(live.price);+ expect(fallback.id).toBeLessThan(live.id);});- test("a non-finite or negative width yields the narrowest tier, never NaN columns", () => {+ test("a non-finite or negative width yields finite columns, never NaN", () => {for (const w of [Number.NaN, Number.POSITIVE_INFINITY, -10]) {const l = deriveRowLayout(w);expect(Object.values(l).every((v) => Number.isFinite(v))).toBe(true);- expect(l.ctx).toBeGreaterThanOrEqual(0);+ expect(l.id).toBeGreaterThanOrEqual(0);}});});-describe("derivePanes", () => {- test("the two mandatory capture widths land where the design says", () => {- // 80 → a 19-column rail and 57 usable row cells; 145 → 24 and 117.- expect(derivePanes(80)).toMatchObject({ railW: 19, panelOuter: 60, rowCells: 57 });- expect(derivePanes(145)).toMatchObject({ railW: 24, panelOuter: 120, rowCells: 117 });+describe("deriveDialogLayout", () => {+ test("the dialog fits 80x24 with room to spare, and does not grow at 145x45", () => {+ const small = deriveDialogLayout(80, 24);+ const large = deriveDialogLayout(145, 45);+ expect(small.width).toBe(76);+ expect(small.marginLeft).toBe(2);+ // Capped, not stretched: a picker is a question, not a viewport.+ expect(large.width).toBe(MAX_DIALOG_WIDTH);+ expect(large.marginLeft).toBeGreaterThan(2);+ expect(small.listRows).toBe(large.listRows);+ expect(small.listRows + CHROME_ROWS).toBeLessThanOrEqual(MAX_DIALOG_ROWS);});- test("a tiny terminal still yields positive, finite budgets", () => {- for (const w of [10, 20, Number.NaN]) {- const p = derivePanes(w);- expect(p.rowCells).toBeGreaterThan(0);- expect(p.railInner).toBeGreaterThan(0);+ test("a banner takes its rows OUT of the list, so the dialog height never changes", () => {+ // The inline-mode invariant. `listRows + CHROME_ROWS + banner` is the whole box.+ for (const [w, h] of [+ [80, 24],+ [145, 45],+ [100, 30],+ ] as const) {+ const plain = deriveDialogLayout(w, h);+ for (const banner of [1, 3, 5]) {+ const withBanner = deriveDialogLayout(w, h, banner);+ expect({ banner, total: withBanner.listRows + banner }).toEqual({+ banner,+ total: plain.listRows,+ });+ }}});-});-describe("deriveRailLayout", () => {- test("cells sum EXACTLY to the rail's inner width", () => {- for (const inner of [8, 12, 17, 22, 30]) {- expect(railLayoutTotal(deriveRailLayout(inner))).toBe(inner);+ test("a tiny or non-finite terminal still yields positive, finite budgets", () => {+ for (const [w, h] of [+ [10, 6],+ [24, 8],+ [Number.NaN, Number.NaN],+ ] as const) {+ const l = deriveDialogLayout(w, h);+ expect(l.width).toBeGreaterThan(0);+ expect(l.inner).toBeGreaterThan(0);+ expect(l.listRows).toBeGreaterThan(0);+ expect(Number.isFinite(l.marginLeft)).toBe(true);}});- test("the served count appears only when the rail is wide enough to hold one", () => {- expect(deriveRailLayout(17).count).toBe(0);- expect(deriveRailLayout(22).count).toBeGreaterThan(0);+ test("the list never exceeds its cap however tall the terminal is", () => {+ for (const h of [24, 45, 80, 200]) {+ expect(deriveDialogLayout(120, h).listRows).toBeLessThanOrEqual(MAX_LIST_ROWS);+ }});});-describe("CHROME", () => {- test("every height gate is a distinct, ordered threshold", () => {- // They are read as "at or above", so an out-of-order pair would silently make one- // gate unreachable.- expect(CHROME.detail).toBeLessThan(CHROME.headerTwoRows);- expect(CHROME.headerTwoRows).toBeLessThanOrEqual(CHROME.bannerBordered);- expect(CHROME.bannerBordered).toBeLessThan(CHROME.statsPanel);+describe("scrollWindow", () => {+ test("a list that fits is never scrolled", () => {+ for (const c of [0, 3, 9]) expect(scrollWindow(c, 10, 11)).toBe(0);+ });++ test("the cursor is always inside the window", () => {+ const total = 312;+ const rows = 11;+ for (let c = 0; c < total; c++) {+ const top = scrollWindow(c, total, rows);+ expect({ c, inside: c >= top && c < top + rows }).toEqual({ c, inside: true });+ expect(top).toBeGreaterThanOrEqual(0);+ expect(top + rows).toBeLessThanOrEqual(total);+ }+ });++ test("an out-of-range cursor is clamped rather than scrolling past the end", () => {+ expect(scrollWindow(9999, 20, 5)).toBe(15);+ expect(scrollWindow(-4, 20, 5)).toBe(0);});});diff --git a/packages/cli/src/picker/layout.ts b/packages/cli/src/picker/layout.tsindex 14991400..33a29a6d 100644--- a/packages/cli/src/picker/layout.ts+++ b/packages/cli/src/picker/layout.ts@@ -1,374 +1,220 @@/**- * picker/layout.ts — every column budget the picker spends, in one place.+ * picker/layout.ts — every column and row budget the picker dialog spends, in one+ * place.*- * Flexbox owns the BOXES; arithmetic owns the widths of the data widgets, because- * `Meter`/`MeterSpan`/`Sparkline`/`StackedBar` take a numeric cell count and a- * number cannot `flexGrow` (bunjs:tui `react-patterns.md`). So a full-width- * visual is a column budget, and a budget that lives at its call site drifts.+ * Flexbox owns the BOXES; arithmetic owns the widths of the cells inside a row,+ * because a row is one `<text>` of `<span>`s and a span cannot `flexGrow`. So a+ * full-width row is a column budget, and a budget that lives at its call site+ * drifts between the header and the rows it labels.*- * THE CONTEXT METER IS THE ELASTIC CELL, and that is the whole design of- * `deriveRowLayout`. Every other cell is fixed per tier; the meter takes the- * surplus up to its tier maximum and hands any remainder to the model id. Two- * consequences, both load-bearing:+ * THE MODEL ID IS THE ELASTIC CELL, and every other cell is fixed at every width.+ * That is the whole difference from the two-pane build this replaces, whose five+ * responsive tiers existed to keep a gradient meter on every row down to 44+ * columns. There is no meter now, so there is no ladder: the four fixed cells are+ * the four facts a reader chooses on (which provider, how much context, what it+ * costs, and whether the row is verified), and the name takes everything left.+ * One layout at 80 columns and at 145.*- * 1. A row is EXACTLY `rowCells` wide at every width — no unpainted tail, which- * is the gap a colour screenshot fails a panel for.- * 2. A row NEVER carries fewer than `MIN_CTX_CELLS` meter cells, at any width,- * which is what keeps every visible model row a GRAPHICS row at 80 columns.- * The whole-frame density count depends on that and on nothing else.- *- * The ladder is a table of tiers rather than a formula because the cells it drops- * are editorial, not arithmetic: the release date goes first (it is chrome), then- * the price METER (the numeral stays — the number is the fact, the bar is the- * comparison), then the capability column, then the id shrinks. Nothing here drops- * the context meter.- */--/**- * The floor on the context meter, in cells.- *- * FOUR, not one: a one-cell meter is a coloured dot, and `rampFor` would blend a- * whole gradient down to a single colour — the "single-colour bar" the aesthetic- * contract names as a negative control. Four cells still read as a fill and still- * carry four distinct ramp colours.+ * THE DIALOG IS CONTENT-SIZED, NOT SCREEN-SIZED. It renders INLINE+ * (`screenMode: "main-screen"`), so its height is rows it actually occupies in the+ * user's scrollback rather than a viewport it has taken over — which is why the+ * row budget below caps at `MAX_DIALOG_ROWS` and does not grow with the terminal.+ * A 45-row terminal gets the same 18-row dialog as a 24-row one, with the extra+ * rows left to the shell. The unpainted-black-hole failure of the previous build+ * cannot occur here: a short list makes a short box.*/-export const MIN_CTX_CELLS = 4;-/** The smallest model-id column worth rendering. Below this a row is unreadable. */-const MIN_ID_CELLS = 8;+/** The widest routing shortcut in the roster (`mistral@`), so the column never elides. */+const PROVIDER_CELLS = 8;+/** `262K`, `1M`, `N/A`. */+const CTX_CELLS = 6;+/** `$30.00`, `FREE`, `SUB`, `local`, `N/A`. */+const PRICE_CELLS = 9;+/** ` catalog` — reserved ONLY on a fallback list, so a live list is not indented. */+const MARK_CELLS = 8;+/** `▶ ` / ` ` — the cursor gutter, which carries its own trailing space. */+const CURSOR_CELLS = 2;+/** Air between the name and the provider column, and between the numeric columns. */+const GAP_AFTER_ID = 4;+const GAP_AFTER_PROVIDER = 4;+const GAP_AFTER_CTX = 5;+/** Below this the name is no longer a name. */+const MIN_ID_CELLS = 10;/*** One model row's cells, left to right. Every number is COLUMNS, and they sum to- * exactly `rowCells` — asserted over the whole width range by `layout.test.ts`.- *- * A zero means the cell is DROPPED at this width (and its separator with it), not- * that it renders empty: an empty cell would still eat its columns.+ * exactly `inner` — asserted over the whole width range by `layout.test.ts`.*/export interface RowLayout {/** Total columns the row must paint, exactly. */- rowCells: number;- /** `▶ ` / ` ` — the cursor gutter, which carries its own trailing space. */+ inner: number;cursor: number;- /** Model id, padded/truncated. Absorbs the surplus the meter cannot use. */+ /** Model id, padded/truncated. Absorbs every column the fixed cells do not use. */id: number;- /** The context-window gradient meter. The elastic cell; never below `MIN_CTX_CELLS`. */+ /** The routing shortcut, right-aligned: `or@`, `kc@`. */+ provider: number;+ /** Context window numeral, right-aligned. */ctx: number;- /** `padStartTo`-ed context numeral (`256K`). */- ctxNum: number;- /** The price meter. 0 at narrow widths — the numeral survives instead. */+ /** Price / `SUB` / `FREE` / `local`, right-aligned. */price: number;- /** `padStartTo`-ed price numeral, or the `SUB` chip's column. */- priceNum: number;- /** Capability column — `[TRV]`, five columns, identical at every width (`rows.tsx`). */- caps: number;- /**- * The provenance chip's column (` CAT `), reserved ONLY for a fallback list.- *- * INSIDE THE BUDGET, and that is a correction to a measured bug: the chip was first- * rendered after the last cell, outside the row's width, on the reasoning that a- * provenance mark should not re-size the cells and make a fallback list- * geometrically incomparable to a live one. The model panel is `overflow="hidden"`,- * so the chip was clipped away ENTIRELY — the single highest-value signal in the- * feature, invisible, in the exact state the feature exists for. Comparability lost- * to visibility; the two lists are never on screen at the same time anyway.- */+ /** ` catalog` — 0 on a live list. */mark: number;- /** Release date, `padStartTo`-ed. 0 below the widest tier — it is chrome. */- date: number;/** Single-space separators the renderer emits. Part of the sum. */gaps: number;}-/** A tier of the ladder: everything fixed, plus the elastic cell's bounds. */-interface Tier {- cursor: number;- ctxNum: number;- price: number;- priceNum: number;- caps: number;- date: number;- gaps: number;- /** Nominal id width. The meter only grows past its minimum once this is satisfied. */- id: number;- ctxMin: number;- ctxMax: number;-}--/**- * The ladder. `min` is inclusive and the rows are ordered widest-first, so the- * first match wins.- *- * `gaps` is the number of single-space separators the row renderer emits between- * the cells this tier keeps — one fewer than the number of cells, because the- * cursor gutter carries its own space. It is counted here rather than derived so- * that `fixedCells` (below) is the single number the elastic split works from; the- * renderer and this table are kept in step by the exact-sum test, which would fail- * the instant one emitted a separator the other had not budgeted.- */-const TIERS: ReadonlyArray<{ min: number; tier: Tier }> = [- {- // ≥ 96: everything — both meters, the capability column, the release date.- min: 96,- tier: {- cursor: 2,- ctxNum: 6,- price: 10,- priceNum: 9,- caps: 5,- date: 10,- gaps: 6,- id: 36,- ctxMin: 10,- ctxMax: 24,- },- },- {- // 70–95: the release date goes first — it is the one cell that is pure chrome.- min: 70,- tier: {- cursor: 2,- ctxNum: 6,- price: 8,- priceNum: 9,- caps: 5,- date: 0,- gaps: 5,- id: 32,- ctxMin: 8,- ctxMax: 16,- },- },- {- // 56–69 — the 80-column tier, and the one the density count turns on. The- // price METER goes; its numeral stays, because the number is the fact and the- // bar is only the comparison.- min: 56,- tier: {- cursor: 2,- ctxNum: 6,- // NINE, not eight: `$30.00/1M` is nine columns and an eight-column cell rendered- // it `$30.00/…`. A truncated PRICE is the one truncation this row cannot afford —- // it is the number the user is choosing on, and a clipped one reads as a- // different, smaller number.- price: 0,- priceNum: 9,- caps: 6,- date: 0,- gaps: 4,- id: 23,- ctxMin: 6,- ctxMax: 10,- },- },- {- // 44–55: the id gives way before the meter does.- min: 44,- tier: {- cursor: 2,- ctxNum: 6,- price: 0,- priceNum: 9,- caps: 6,- date: 0,- gaps: 4,- id: 17,- ctxMin: 5,- ctxMax: 10,- },- },- {- // < 44: id, meter, two numerals. `id: MIN_ID_CELLS` makes the meter pin to- // `ctxMax` and the id take every remaining column — "id: rest".- min: 0,- tier: {- cursor: 2,- ctxNum: 5,- price: 0,- priceNum: 7,- caps: 0,- date: 0,- gaps: 3,- id: MIN_ID_CELLS,- ctxMin: MIN_CTX_CELLS,- ctxMax: MIN_CTX_CELLS,- },- },-];--/** Everything in a tier except the id and the context meter. */-function fixedCells(t: Tier): number {- return t.cursor + t.ctxNum + t.price + t.priceNum + t.caps + t.date + t.gaps;-}-/**- * The cell widths for a model row `rowCells` columns wide.+ * The cell widths for a row `inner` columns wide.** Clamped, never trusted: a caller that hands this a negative, fractional or- * non-finite width gets the narrowest tier rather than NaN columns, because a NaN- * width reaches `Meter` as a zero-width widget — nothing painted, nothing thrown.+ * non-finite width gets a floor rather than NaN columns, because a NaN width+ * reaches `padTo` as a zero-width cell — nothing painted, nothing thrown.*/-export function deriveRowLayout(rowCells: number, opts: { mark?: boolean } = {}): RowLayout {- const cells = Number.isFinite(rowCells) ? Math.max(0, Math.floor(rowCells)) : 0;- const t = (TIERS.find((row) => cells >= row.min) ?? TIERS[TIERS.length - 1]!).tier;- // ` CAT ` plus its separator, and only when the list is a fallback. It comes out of- // the ID, which is the one cell with slack — never out of the context meter.- const mark = opts.mark === true && cells >= 44 ? MARK_CELLS + 1 : 0;- const fixed = fixedCells(t) + mark;-- // `id + ctx` is whatever the fixed cells leave. Split it so the id gets its- // nominal width first, the meter takes the surplus up to its tier maximum, and- // any remainder goes back to the id — which is what makes a 145-column row sum- // exactly rather than leaving a dead tail where the meter stopped growing.- const budget = Math.max(0, cells - fixed);- let ctx = Math.min(Math.max(budget - t.id, MIN_CTX_CELLS), t.ctxMax);- let id = budget - ctx;+export function deriveRowLayout(inner: number, opts: { mark?: boolean } = {}): RowLayout {+ const cells = Number.isFinite(inner) ? Math.max(0, Math.floor(inner)) : 0;+ const mark = opts.mark === true ? MARK_CELLS : 0;+ const gaps = GAP_AFTER_ID + GAP_AFTER_PROVIDER + GAP_AFTER_CTX;++ // Everything except the elastic id. The mark carries no separator of its own —+ // the price column is right-aligned, so the gap is already inside it.+ let provider = PROVIDER_CELLS;+ let ctx = CTX_CELLS;+ let price = PRICE_CELLS;+ let id = cells - (CURSOR_CELLS + provider + ctx + price + mark + gaps);if (id < MIN_ID_CELLS) {- // Too narrow for both. The id keeps its floor and the meter gives way down to- // its own floor; below that the id pays, because a 3-cell meter is still a- // meter and a 2-column id is not a name.- id = Math.min(MIN_ID_CELLS, budget);- ctx = Math.max(0, budget - id);- if (ctx < MIN_CTX_CELLS) {- ctx = Math.min(MIN_CTX_CELLS, budget);- id = Math.max(0, budget - ctx);- }+ // Absurdly narrow. The columns give way in the order they are least missed:+ // the mark's padding first (it is a whole-list property the title also+ // states), then the provider column, then the price. Nothing here drops the+ // CONTEXT numeral or the name, because those two are the row.+ const shortfall = MIN_ID_CELLS - id;+ const takeFromProvider = Math.min(provider, shortfall);+ provider -= takeFromProvider;+ const stillShort = shortfall - takeFromProvider;+ const takeFromPrice = Math.min(Math.max(0, price - 4), stillShort);+ price -= takeFromPrice;+ id = cells - (CURSOR_CELLS + provider + ctx + price + mark + gaps);+ }+ if (id < 0) {+ // Narrower than the fixed cells themselves. Give the name what is left and+ // let the row paint short rather than overflow, which Yoga would claw back+ // from whichever cell it liked.+ ctx = Math.max(0, ctx + id);+ id = 0;}- return {- rowCells: cells,- cursor: t.cursor,- id,- ctx,- ctxNum: t.ctxNum,- price: t.price,- priceNum: t.priceNum,- caps: t.caps,- date: t.date,- gaps: t.gaps,- mark,- };+ return { inner: cells, cursor: CURSOR_CELLS, id, provider, ctx, price, mark, gaps };}-/** ` CAT ` — `BadgeSpan` pads one column each side of the label, outside the fill. */-const MARK_CELLS = 5;--/** Sum of every cell plus the separators — must equal `rowCells`. */+/** Sum of every cell plus the separators — must equal `inner`. */export function rowLayoutTotal(l: RowLayout): number {- return (- l.cursor + l.id + l.ctx + l.ctxNum + l.price + l.priceNum + l.caps + l.date + l.gaps + l.mark- );+ return l.cursor + l.id + l.provider + l.ctx + l.price + l.mark + l.gaps;}+/** The separators, named so the renderer and the budget cannot disagree. */+export const GAPS = {+ afterId: GAP_AFTER_ID,+ afterProvider: GAP_AFTER_PROVIDER,+ afterCtx: GAP_AFTER_CTX,+} as const;++/** The widest the dialog is ever drawn, however wide the terminal is. */+export const MAX_DIALOG_WIDTH = 92;+/** The tallest the dialog is ever drawn, however tall the terminal is. */+export const MAX_DIALOG_ROWS = 18;+/** The most model rows the list ever shows at once. Scroll, do not grow. */+export const MAX_LIST_ROWS = 11;+/** Fewer than this and the list stops being a list. */+const MIN_LIST_ROWS = 3;+/** Below this the dialog cannot carry its own chrome plus a usable list. */+const MIN_DIALOG_ROWS = 11;+/**- * The two columns of the picker, and what each leaves for its content.+ * Chrome rows the populated dialog ALWAYS spends: two border rows, the filter+ * row, the column header, the status row, the rule, the selection detail line+ * and the key hints.+ *+ * "ALWAYS" IS THE LOAD-BEARING WORD. The status row is rendered even when it is+ * blank, so that a list which starts overflowing (or a credential sweep that+ * finishes) does not shove every row below it by one. What is deliberately NOT+ * fixed is the LIST's height: it is content-sized up to `listRows`, because the+ * failure state's whole point is a four-row fallback list that reads as four rows+ * rather than as four rows in a panel built for eleven — the unpainted hole the+ * rejected build produced, which the reader read as "this provider has nothing".*- * `railW` is 19 / 24 per the design; the rest follows from the two chrome costs- * the skill MEASURED and this repo re-measured: a `Panel` spends 2 columns of- * border when `flush` (4 when not), and a `<scrollbox>` inside it spends 1 more- * for the thumb. The one-column `gap` between the panes is real — it is set on the- * flex row, so it has to come out of the budget here too.+ * The banner's rows come OUT of the list's budget rather than being added to the+ * box, so the dialog is bounded above in every state and only ever SHRINKS from+ * its cap. Shape changes between phases are remounted with `key={…}`, which is+ * the documented cure for inline reconciliation tearing.*/-export interface PaneLayout {- /** Outer width of the provider rail, borders included. */- railW: number;- /** Usable columns inside the rail's flush panel. */- railInner: number;- /** Outer width of the model panel. */- panelOuter: number;- /** Usable columns for one model row, inside the panel and beside the thumb. */- rowCells: number;-}--export function derivePanes(width: number): PaneLayout {- const w = Number.isFinite(width) ? Math.max(20, Math.floor(width)) : 80;- const railW = w >= 100 ? 24 : 19;- const panelOuter = Math.max(8, w - railW - 1);- return {- railW,- // MINUS THREE, not two: the flush `Panel` spends 2 columns of border and the- // `<scrollbox>` inside it spends 1 more for the thumb — the second cost measured by- // the skill and re-measured here, where budgeting only the border clipped the- // billing tag on every rail row (`SUB` painted as `SU`).- railInner: Math.max(4, railW - 3),- panelOuter,- rowCells: Math.max(12, panelOuter - 3),- };-}--/** One provider rail row's cells. The LABEL is the elastic cell here. */-export interface RailLayout {- railInner: number;- /** Readiness glyph — `●` / `○` / `◌`. */- glyph: number;- /** Provider name, truncated. */- label: number;- /** Right-aligned billing tag: `SUB` / `LOCAL` / `$`. */- tag: number;- /** Served-model count, or 0 when the rail is too narrow to carry one. */- count: number;- gaps: number;+export const CHROME_ROWS = 8;++export interface DialogLayout {+ /** Outer width including the border columns. */+ width: number;+ /** Columns of terminal to the left of the border. */+ marginLeft: number;+ /** Usable content columns: `width` less two border columns and two of padding. */+ inner: number;+ /** How many model rows fit. The list scrolls within this. */+ listRows: number;}/**- * THE BILLING TAG IS PLAIN COLOURED TEXT, NOT A `BadgeSpan`, and that is a budget- * decision taken against the skill's default ("discrete status → badge"). A chip- * pays two columns of padding for its fill; the rail's whole inner width is 17 at- * 80 columns, so those two columns come straight off the provider NAME — and a- * rail whose names are all elided has lost more than a chip gains. The readiness- * glyph and the tag's own colour carry the status, and the model panel spends its- * chips where there is room for them. §5.3's own mock renders the bare form.+ * Size the dialog for a terminal, and for however many rows a banner has taken.+ *+ * `extraRows` is the honest coupling between the failure banner and the list: a+ * five-row 401 explanation and eleven model rows do not both fit, and the rows that+ * must give way are the list's — the banner is the REASON the list is short, so+ * hiding the banner to show more of an unverified list would invert the whole point+ * of the state.+ *+ * MEASURED, AND IT BOUNDS WHAT "INLINE" BUYS AT THIS PIN. `screenMode: "main-screen"`+ * still sizes the renderer to `stdout.rows` — `CliRendererConfig` at+ * `@opentui/[email protected]` carries no `width`/`height` key at all, whatever the+ * upstream option table says — so the picker owns the whole terminal while it is up,+ * and the banner above scrolls with the rest of the scrollback. What inline still+ * buys, and it is the reason for choosing it: nothing is SWAPPED, so the final frame+ * survives `destroy()` and the shell prompt returns directly under the dialog rather+ * than under a restored screen that never showed it. Capping the dialog at+ * `MAX_DIALOG_ROWS` is what keeps that owned region small instead of filling 45 rows.*/-const TAG_CELLS = 5;--export function deriveRailLayout(railInner: number): RailLayout {- const inner = Number.isFinite(railInner) ? Math.max(4, Math.floor(railInner)) : 17;- // The count needs a rail wide enough that the NAME does not pay for it.- const count = inner >= 20 ? 3 : 0;- let gaps = count > 0 ? 3 : 2;- let tag = TAG_CELLS;- let label = inner - 1 - tag - count - gaps;- if (label < 3) {- // Absurdly narrow: the tag goes before the name does. A rail of billing tags with- // no provider names in it is not a rail. `Math.max(1, …)` on the label instead- // would have kept the tag and OVERFLOWED the row — measured: 9 cells rendered into- // an 8-column rail, which Yoga then claws back from whichever cell it likes.- tag = 0;- gaps = 1;- label = inner - 1 - count - gaps;- }- if (label < 1) {- gaps = 0;- label = Math.max(0, inner - 1 - count);- }- return { railInner: inner, glyph: 1, label, tag, count, gaps };-}--/** Sum of a rail row's cells — must equal `railInner`. */-export function railLayoutTotal(l: RailLayout): number {- return l.glyph + l.label + l.tag + l.count + l.gaps;+export function deriveDialogLayout(+ termWidth: number,+ termHeight: number,+ extraRows = 0+): DialogLayout {+ const w = Number.isFinite(termWidth) ? Math.max(24, Math.floor(termWidth)) : 80;+ const h = Number.isFinite(termHeight) ? Math.floor(termHeight) : 24;+ const width = Math.min(w - 4, MAX_DIALOG_WIDTH);+ // Two columns of margin at 80, centred once the terminal is wider than the cap.+ const marginLeft = Math.max(2, Math.floor((w - width) / 2));+ // `- 6`: the shell prompt and the claudish banner keep their rows wherever the+ // terminal is tall enough to spare them.+ const budget = Math.min(MAX_DIALOG_ROWS, Math.max(MIN_DIALOG_ROWS, h - 6));+ const listRows = Math.max(+ MIN_LIST_ROWS,+ Math.min(MAX_LIST_ROWS, budget - CHROME_ROWS - Math.max(0, Math.floor(extraRows)))+ );+ return { width, marginLeft, inner: Math.max(8, width - 4), listRows };}/**- * Chrome that is HEIGHT-gated, not width-gated — the scarce axis at 80×24 is rows.+ * The scroll window for a cursor in a list — the offset that keeps the cursor+ * visible while moving the viewport as little as possible.*- * Each threshold is named once here because every one of them is a row the model- * list does not get, and §4.6's whole-frame density arithmetic is built on these- * exact numbers.+ * Pure, and computed rather than held in a ref, because there is no `<scrollbox>`+ * here: eleven rows are sliced out of the array and rendered as plain `<text>`+ * rows. That deletes two measured OpenTUI traps at once — a scrollbox's intrinsic+ * height is its WHOLE content, which starves every sibling in the same column, and+ * its reconciler desyncs when a content-derived key changes under it.*/-export const CHROME = {- /** Two header rows (identity + context) above this height, one below. */- headerTwoRows: 30,- /** `StatsStrip` takes a bordered `Panel` with three rows at or above this. */- statsPanel: 34,- /** The discovery banner takes a full border (2 rows of chrome) at or above this. */- bannerBordered: 30,- /**- * The two pinned detail blocks appear at or above this height.- *- * Below it every row belongs to a list: a detail block would trade two model rows —- * two GRAPHICS rows — for two rows of prose, which is the wrong direction for the- * whole-frame density count on the terminal where that count is tightest.- */- detail: 26,-} as const;+export function scrollWindow(cursor: number, total: number, rows: number): number {+ const size = Math.max(1, Math.floor(rows));+ if (total <= size) return 0;+ const c = Math.max(0, Math.min(total - 1, Math.floor(cursor)));+ // Keep the cursor one row inside the window where there is room, so the next+ // press reveals a row rather than only moving the highlight.+ const top = Math.min(Math.max(0, c - Math.floor(size / 2)), total - size);+ return Math.max(0, top);+}diff --git a/packages/cli/src/picker/model-picker-run.tsx b/packages/cli/src/picker/model-picker-run.tsxindex 6c5395fc..27ab0814 100644--- a/packages/cli/src/picker/model-picker-run.tsx+++ b/packages/cli/src/picker/model-picker-run.tsx@@ -10,9 +10,21 @@** THREE DEPARTURES FROM THE SKILL'S STOCK BOOTSTRAP, each forced by a fact:*- * 1. `screenMode: "alternate-screen"`, never `useAlternateScreen: true`. The installed- * `@opentui/[email protected]` renamed the option; the old key is an unknown key,- * SILENTLY ignored, and the picker would draw over the user's scrollback.+ * 1. `screenMode: "main-screen"` — INLINE, and never `useAlternateScreen`. Two+ * separate facts are packed into that one line.+ *+ * The KEY: `@opentui/[email protected]` renamed `useAlternateScreen` to `screenMode`,+ * and the old key is an unknown key — silently ignored, no warning, no type+ * error.+ *+ * The VALUE: the picker is a one-shot command, which is the row the guidance's+ * own `screenMode` table assigns to `main-screen`. The first build chose the+ * alternate screen and was rejected. Inline is not cosmetic here — it is what+ * makes the dialog read as a program ASKING something rather than a program that+ * has taken the terminal, it keeps the shell prompt and the claudish banner+ * (`printLogo`, already written above) on screen so the dialog needs no branding+ * of its own, and it means the failure notice is still in the scrollback after+ * the picker closes instead of being discarded with the alternate buffer.** 2. `installShutdown` is not used. Its contract ends in `process.exit(code)`, which is* right for an app whose quit key means quit and wrong for a picker, whose entire job@@ -26,15 +38,17 @@* the terminal behind a live renderer leaves cells OpenTUI cannot invalidate — ghost* characters, not an exception, which is why no test catches it.*- * AND ONE WRITE THAT IS DELIBERATE. The alternate screen is DISCARDED by- * `renderer.destroy()`, so the in-panel failure notice is gone the instant the user- * picks a model and Claude Code starts. A scrollback line is the only durable record,- * and it is the record the current behaviour already provides — including to a user who- * pipes stderr to a file. So every failure seen during the session is buffered and- * written once, after teardown, at the same point `resume-picker-run.tsx:115` restores- * stderr. Every failure, in order, not just the one the user landed on: today each- * failed selection prints immediately, so a session that tried two failing providers- * leaves two diagnostics, and writing one would be a quiet narrowing.+ * AND ONE WRITE THAT IS DELIBERATE, WHICH INLINE MODE MAKES SMALLER BUT NOT+ * UNNECESSARY. Inline rendering leaves the last frame in the scrollback, so the+ * in-dialog failure notice survives `destroy()` — that is one of the reasons for+ * choosing it. What it does NOT survive is truncation: the dialog shows five rows of+ * a notice that may carry an upstream JSON body, and a user piping stderr to a file+ * gets nothing from a rendered frame at all. So every failure seen during the session+ * is buffered and written once, after teardown, at the same point+ * `resume-picker-run.tsx:115` restores stderr. Every failure, in order, not just the+ * one the user landed on: today each failed selection prints immediately, so a session+ * that tried two failing providers leaves two diagnostics, and writing one would be a+ * quiet narrowing.*/import { createCliRenderer } from "@opentui/core";@@ -87,7 +101,14 @@ export async function runModelPicker(setStderrQuiet(true);const renderer = await createCliRenderer({- screenMode: "alternate-screen",+ screenMode: "main-screen",+ // MEASURED: without this, `destroy()` WIPES the region and inline mode buys+ // nothing over the alternate screen — a tmux capture taken one second after Esc+ // held nothing but the shell's own `EXIT=0`, with the dialog and the claudish+ // banner both gone. Leaving the last frame is the whole point of rendering+ // inline: what the user chose, and any discovery failure they were shown, stay+ // in the scrollback where they can be read after Claude Code has started.+ clearOnShutdown: false,exitOnCtrlC: false, // the picker maps Ctrl+C to "cancel", which RETURNS a value});diff --git a/packages/cli/src/picker/row-semantics.test.ts b/packages/cli/src/picker/row-semantics.test.tsindex 9a2054fe..c3b3261d 100644--- a/packages/cli/src/picker/row-semantics.test.ts+++ b/packages/cli/src/picker/row-semantics.test.ts@@ -1,18 +1,24 @@import { describe, expect, test } from "bun:test";import type { ModelInfo, PickerDiscoveryOutcome } from "../model-selector.js";/**- * The pure arithmetic behind a model row and a discovery notice — the tier that needs- * no renderer, and the tier where the honesty rules are actually decidable.+ * The pure semantics behind a row, a detail line and a discovery notice — the tier+ * that needs no renderer, and the tier where the honesty rules are actually+ * decidable.*- * Two of these assertions exist because the alternative reading is silently plausible:- * an absent context window must yield `NaN` (which paints `╌`) and NEVER 0 (which- * paints the same full track a healthy tiny window paints), and no rendered notice may- * contain the substring `undefined`.+ * Three of these assertions exist because the alternative reading is silently+ * plausible: a fallback list must say it MAY NOT WORK and not merely that it came+ * from somewhere else; a capability the catalog is silent about must not be+ * rendered as absent; and no rendered notice may contain the substring `undefined`.*/import type { DiscoveryFailure } from "../providers/model-discovery.js";-import { discoveryNoticeContent, mergeCredentialLines } from "./DiscoveryNotice.js";-import { ctxMix, priceMix, resample } from "./StatsStrip.js";-import { billingTag, contextMeterPct, parseDisplayPrice, priceMeterPct } from "./rows.js";+import {+ discoveryNoticeContent,+ mergeCredentialLines,+ noticeRows,+ wrapWords,+} from "./DiscoveryNotice.js";+import { capabilityWords, detailText } from "./detail.js";+import { billingLabel, priceFg, priceLabel, readinessGlyph } from "./rows.js";const model = (over: Partial<ModelInfo> = {}): ModelInfo => ({id: "m",@@ -22,103 +28,93 @@ const model = (over: Partial<ModelInfo> = {}): ModelInfo => ({...over,});-describe("contextMeterPct", () => {- test("is monotonic and bounded 0..100", () => {- const pcts = [8_000, 32_000, 128_000, 512_000, 1_000_000].map((n) =>- contextMeterPct(n, 8_000, 1_000_000)- );- expect(pcts.every((p) => p >= 0 && p <= 100)).toBe(true);- expect([...pcts].sort((a, b) => a - b)).toEqual(pcts);- });-- test("an absent window is NaN, never 0", () => {- // 0 would paint a full `░` track — pixel-identical to a healthy 8 K model.- expect(Number.isNaN(contextMeterPct(undefined, 1000, 2000))).toBe(true);- expect(Number.isNaN(contextMeterPct(0, 1000, 2000))).toBe(true);+describe("priceLabel", () => {+ test("the `/1M` suffix goes — the column header says it once for the whole list", () => {+ expect(priceLabel("$9.00/1M", "metered")).toBe("$9.00");+ expect(priceLabel("$0.15/1M", "metered")).toBe("$0.15");});- test("a homogeneous list does not collapse its smallest row to an empty bar", () => {- // MEASURED on the first capture: a 250K/1M roster scaled to its own bounds painted- // every 250K row at exactly 0%. The floor is anchored six doublings below the max.- expect(contextMeterPct(250_000, 250_000, 1_000_000)).toBeGreaterThan(50);- expect(contextMeterPct(1_000_000, 250_000, 1_000_000)).toBe(100);+ test("a flat-rate plan keeps its word instead of a number it does not have", () => {+ expect(priceLabel("SUB", "sub")).toBe("SUB");+ expect(priceLabel("FREE", "metered")).toBe("FREE");+ // A local model costs nothing per token and says so in lower case: shouting is+ // reserved for the two labels that are about money.+ expect(priceLabel("$3.00/1M", "local")).toBe("local");+ expect(priceLabel("LOCAL", "metered")).toBe("local");});- test("a degenerate range answers 100 rather than dividing by zero", () => {- expect(contextMeterPct(1000, 1000, 1000)).toBe(100);- expect(contextMeterPct(1000, 0, 0)).toBe(100);+ test("an absent price is `N/A`, and never an empty cell", () => {+ // An empty price column would read as "free", which is a claim about money.+ expect(priceLabel("N/A", "metered")).toBe("N/A");+ expect(priceLabel("", "metered")).toBe("N/A");});});-describe("priceMeterPct", () => {- test("CHEAPER IS A LONGER BAR — the ramp ends green, so the fill is cheapness", () => {- const cheap = priceMeterPct(0.1, 0.1, 15);- const dear = priceMeterPct(15, 0.1, 15);- expect(cheap).toBe(100);- expect(dear).toBe(0);+describe("priceFg", () => {+ test("the three labels that are ABOUT MONEY are three distinct colours", () => {+ // `FREE` (costs nothing), `SUB` (a flat-rate plan, so no per-token number+ // exists) and a rate are three different financial claims, and a reader+ // scanning for a cheap model separates them by hue before reading the word.+ expect(new Set(["FREE", "SUB", "$2.25"].map(priceFg)).size).toBe(3);});- test("free is a full bar; an absent rate is NaN", () => {- expect(priceMeterPct(0, 0.1, 15)).toBe(100);- expect(Number.isNaN(priceMeterPct(undefined, 0.1, 15))).toBe(true);+ test("the two labels that are NOT prices share the dim tier, deliberately", () => {+ // `local` and `N/A` are both "there is no number here". Giving them separate+ // hues would put two more meanings into a column that already carries three,+ // and neither is a fact the reader acts on.+ expect(priceFg("local")).toBe(priceFg("N/A"));+ expect(priceFg("local")).not.toBe(priceFg("$2.25"));});});-describe("parseDisplayPrice", () => {- test("reads the number out of a display string and nothing out of a word", () => {- expect(parseDisplayPrice("$9.00/1M")).toBe(9);- expect(parseDisplayPrice("$0.15/1M")).toBe(0.15);- expect(parseDisplayPrice("SUB")).toBeUndefined();- expect(parseDisplayPrice("N/A")).toBeUndefined();+describe("billingLabel / readinessGlyph", () => {+ test("each billing mode has its own WORD, and only the flat-rate one is coloured", () => {+ const tags = (["sub", "local", "metered"] as const).map(billingLabel);+ expect(tags.map((t) => t.text)).toEqual(["SUB", "local", "$"]);+ // `SUB` is the one that changes what a launch COSTS, so it is the one that+ // gets a hue; the other two recede. Colour spent evenly is colour spent on+ // nothing.+ expect(tags[0]?.fg).not.toBe(tags[1]?.fg);+ expect(tags[0]?.fg).not.toBe(tags[2]?.fg);});-});-describe("billingTag", () => {- test("each mode has its own word and its own colour", () => {- const tags = (["sub", "local", "metered"] as const).map(billingTag);- expect(tags.map((t) => t.text)).toEqual(["SUB", "LOCAL", "$"]);- expect(new Set(tags.map((t) => t.fg)).size).toBe(3);+ test("readiness has three states, not two — pending is not missing", () => {+ const g = (["pending", "ready", "missing"] as const).map(readinessGlyph);+ expect(new Set(g.map((x) => x.glyph)).size).toBe(3);+ expect(new Set(g.map((x) => x.fg)).size).toBe(3);});});-describe("ctxMix / priceMix", () => {- test("price bands are exclusive and count only rows with a per-token rate", () => {- // A subscription row has no number to band, and inventing one would put a flat-rate- // plan somewhere on a price axis it does not sit on.- const list = [- model({ pricing: { input: "", output: "", average: "FREE" } }),- model({ pricing: { input: "", output: "", average: "$0.15/1M" } }),- model({ pricing: { input: "", output: "", average: "$2.90/1M" } }),- model({ pricing: { input: "", output: "", average: "$30.00/1M" } }),- model({ pricing: { input: "", output: "", average: "SUB" } }),- model({}),- ];- expect(priceMix(list)).toEqual([1, 1, 1, 1]);+describe("capabilityWords", () => {+ test("a capability the catalog is SILENT about is not rendered as absent", () => {+ // `undefined` is not `false`. The slim catalog carries `supportsTools` for most+ // models and nothing for some, and printing an absence would be claiming a fact+ // nobody has.+ expect(capabilityWords(model({ supportsTools: true }))).toEqual(["tools"]);+ expect(capabilityWords(model({}))).toEqual([]);+ expect(capabilityWords(model({ supportsTools: false }))).toEqual([]);});- test("context buckets sum to the models that HAVE a window", () => {- const list = [- model({ contextLength: 8_000 }),- model({ contextLength: 131_072 }),- model({ contextLength: 1_000_000 }),- model({}),- ];- expect(ctxMix(list).reduce((a, b) => a + b, 0)).toBe(3);+ test("all three are listed in a fixed order when all three are known", () => {+ expect(+ capabilityWords(model({ supportsTools: true, supportsReasoning: true, supportsVision: true }))+ ).toEqual(["tools", "reasoning", "vision"]);});});-describe("resample", () => {- test("always paints exactly the requested number of columns", () => {- for (const n of [0, 1, 5, 21, 342]) {- for (const w of [1, 8, 48]) {- expect(- resample(- Array.from({ length: n }, (_, i) => i),- w- ).length- ).toBe(n === 0 ? 0 : w);- }- }+describe("detailText", () => {+ test("the exact spec leads, so the picker never hides its own return value", () => {+ const { text } = detailText("[email protected]", model({ releaseDate: "2026-09-14" }));+ expect(text.startsWith("[email protected]")).toBe(true);+ expect(text).toContain("2026-09");+ });++ test("`supportsTools: false` is DISQUALIFYING and says so in words", () => {+ // A model that cannot take tool definitions cannot drive Claude Code at all,+ // which is a different claim from "it is a bit less capable".+ expect(detailText("x@y", model({ supportsTools: false })).warn).toContain("no tool support");+ expect(detailText("x@y", model({ supportsTools: true })).warn).toBe("");+ expect(detailText("x@y", model({})).warn).toBe("");});});@@ -156,7 +152,7 @@ describe("discoveryNoticeContent", () => {).toBeNull();});- test("`empty-roster` and `all-filtered` say DIFFERENT things — V7's automatable half", () => {+ test("`empty-roster` and `all-filtered` say DIFFERENT things", () => {const empty = discoveryNoticeContent({ kind: "empty-roster", failure: failure({ kind: "empty-roster" }), fallbackRows: [] },"Kimi"@@ -176,17 +172,47 @@ describe("discoveryNoticeContent", () => {expect(empty?.lines[0]).not.toBe(filtered?.lines[0]);});- test("a fallback list gets the PROVENANCE sentence; no fallback gets a next step", () => {- const withRows = discoveryNoticeContent(- { kind: "empty-roster", failure: failure({ kind: "empty-roster" }), fallbackRows: [model()] },+ test("A FALLBACK LIST SAYS IT MAY NOT WORK, not merely where it came from", () => {+ // The single most useful sentence in this state, and the one the shipped stderr+ // wording never carried: discovery failed because the credential was rejected,+ // so nothing has confirmed the account can call any of these models. A reader+ // told only "catalog entries" concludes the list is differently-sourced, picks+ // one, and finds out at launch.+ const c = discoveryNoticeContent(+ {+ kind: "failed",+ failure: failure({ status: 401 }),+ notice: [+ "\n⚠ Kimi could not list its models: the API key was rejected (HTTP 401)\n",+ " Showing Kimi's cloud-catalog entries below — not its live roster.\n\n",+ ],+ fallbackRows: [model(), model({ id: "b" }), model({ id: "c" }), model({ id: "d" })],+ },"Kimi");+ const joined = c?.lines.join(" ") ?? "";+ expect(joined).toContain("The 4 rows below");+ expect(joined).toContain("not Kimi's live roster");+ expect(joined).toContain("may still fail");+ // The formatter's own shorter sentence is REPLACED, not printed beside it.+ expect(joined).not.toContain("Showing Kimi's cloud-catalog entries");+ });++ test("no fallback list gets a next step instead of a provenance sentence", () => {const without = discoveryNoticeContent({ kind: "empty-roster", failure: failure({ kind: "empty-roster" }), fallbackRows: [] },"Kimi");- expect(withRows?.lines.join(" ")).toContain("not its live roster");expect(without?.lines.join(" ")).toContain("Press c");+ expect(without?.lines.join(" ")).not.toContain("may still fail");+ });++ test("the dialog status for a failure says UNAVAILABLE, not broken", () => {+ const c = discoveryNoticeContent(+ { kind: "failed", failure: failure(), notice: ["⚠ x"], fallbackRows: [model()] },+ "Kimi"+ );+ expect(c?.title).toBe("live roster unavailable");});test("the HTTP status becomes a badge and leaves the headline once", () => {@@ -231,6 +257,53 @@ describe("discoveryNoticeContent", () => {});});+describe("wrapWords / noticeRows", () => {+ test("a line that fits is returned untouched", () => {+ expect(wrapWords("short enough", 40)).toEqual(["short enough"]);+ });++ test("no wrapped row exceeds the width", () => {+ const long =+ "The 4 rows below are catalog entries, not Kimi / Moonshot's live roster — they do not confirm access, so launching one may still fail.";+ for (const w of [30, 48, 70]) {+ for (const line of wrapWords(long, w)) expect(line.length).toBeLessThanOrEqual(w);+ }+ });++ test("THE `may still fail` CLAUSE SURVIVES AT 80 COLUMNS", () => {+ // It is the tail of the sentence, so a truncating banner would take it first —+ // which is exactly the failure this whole state exists to prevent.+ const content = discoveryNoticeContent(+ {+ kind: "failed",+ failure: failure({ status: 401 }),+ notice: [+ "\n⚠ Kimi could not list its models: the API key was rejected (HTTP 401)\n",+ " Check MOONSHOT_API_KEY (a value in your shell overrides stored credentials).\n",+ " Get a key: https://platform.moonshot.cn/\n",+ ],+ fallbackRows: [model(), model({ id: "b" }), model({ id: "c" }), model({ id: "d" })],+ },+ "Kimi"+ );+ // 76-column dialog: 2 border, 2 padding, 2 for the banner's own rule + gutter.+ const rows = noticeRows(content!, 70, 5);+ expect(rows.lines.join(" ")).toContain("may still fail");+ expect(rows.lines.length).toBeLessThanOrEqual(5);+ expect(rows.badge).toBe("HTTP 401");+ });++ test("the row count is knowable BEFORE render — the inline row budget depends on it", () => {+ const content = discoveryNoticeContent(+ { kind: "failed", failure: failure(), notice: ["⚠ x"], fallbackRows: [] },+ "Kimi"+ );+ const rows = noticeRows(content!, 70, 5);+ expect(rows.lines.length).toBeGreaterThan(0);+ expect(rows.lines.length).toBeLessThanOrEqual(5);+ });+});+describe("mergeCredentialLines", () => {test("merges the env-var and key-URL rows when they fit, dropping the parenthetical", () => {const lines = [diff --git a/packages/cli/src/picker/rows.tsx b/packages/cli/src/picker/rows.tsxindex 9e1e0c41..0a1ebe1f 100644--- a/packages/cli/src/picker/rows.tsx+++ b/packages/cli/src/picker/rows.tsx@@ -1,22 +1,39 @@/** @jsxImportSource @opentui/react *//**- * picker/rows.tsx — one model row, one provider rail row, and the pure arithmetic- * behind both.+ * picker/rows.tsx — one model row, one provider row, one column header, and the+ * pure label arithmetic behind them.*- * A RENDERING CHANGE, NOT A DATA CHANGE — which is the single largest risk- * reduction available in this feature. The row the old picker printed was- * `kimi@kimi-k3 ($9.00/1M, 1M [TRV], 2026-07)`: a price, a context window, three- * capability flags and a release date, four visual encodings concatenated into one- * parenthetical string. Every value a rich row needs therefore ALREADY reaches the- * view, so this file adds no fetch, no field and no plumbing, and a row regression- * can only ever be visual.+ * PLAIN ALIGNED TEXT. NO METERS, NO GRADIENTS, NO PER-ROW CHIPS. The build this+ * replaces drew a context meter and a price meter on every row, and the reason it+ * had to is written down: a whole-frame graphics-density gate counts a list row+ * carrying a bar as a graphics row, so on a screen whose content IS a list there is+ * no way to pass it without decorating every row. The result was measured — of 32+ * visible rows, 19 read `1M`, and their bars were indistinguishable. Two full+ * columns of gradient encoding one repeated value, beside the numerals that already+ * said it.+ *+ * A meter belongs where a bounded value VARIES and where a reader is comparing+ * magnitudes rather than reading names. In this file there is exactly one such+ * place and it is not here — it is the loading dialog, where `done/total` is real+ * progress over countable work.+ *+ * COLOUR ENCODES MEANING, ONE MEANING EACH, APP-WIDE:+ *+ * `FREE` success costs nothing+ * `SUB` warn a flat-rate plan, so no per-token number exists+ * `local` trace runs on this machine+ * `catalog` warn NOT this provider's live roster — see `DiscoveryNotice`+ * `N/A` dead the catalog does not say+ * selection accent + `C.bgHighlight`, and a `▶` so it survives greyscale+ *+ * Anything else is body ink. In particular the price NUMERAL is not colour-coded:+ * a value takes discrete buckets or nothing at all, and three buckets of dollars+ * would put a third meaning on `success` in a column already carrying `FREE`.** ONE `<text>` PER ROW, ALWAYS. Yoga claws columns back from the LAST `<text>`* child of a row, which is how a branch name once rendered as `mai` with thirty* free columns beside it (`resume-picker.tsx:473-484`). So every cell is a- * `<span>` inside a single text node, and the widgets used here are the `*Span`- * twin `MeterSpan` — never `Meter`, which is a `<text>` and- * cannot nest.+ * `<span>` inside a single text node.** COLOUR IS READ AT RENDER TIME, never captured in a module-level `const`:* `C`/`tokens` are reassigned in place when the terminal theme is detected, and a@@ -29,93 +46,42 @@ import type { ReactNode } from "react";import type { ModelInfo } from "../model-selector.js";import { A, C } from "../tui/theme.js";import { padStartTo, padTo, truncate } from "../tui/viz/text.js";-import { ramps, tokens } from "../tui/viz/tokens.js";-import { MeterSpan } from "../tui/viz/widgets.js";+import { tokens } from "../tui/viz/tokens.js";import type { BillingMode } from "./PickerDataSource.js";-import type { RailLayout, RowLayout } from "./layout.js";+import { GAPS, type RowLayout } from "./layout.js";/** Readiness, in `ProvidersContent.tsx:225`'s exact vocabulary. */export type Readiness = "pending" | "ready" | "missing";-/**- * LOG-SCALED, and that is not a refinement — it is what makes the column readable.- *- * A picker list spans 8 K (a small local pull) to 1 M (Gemini): two and a half- * decades. On a linear scale every model except the top one paints at or near zero,- * so the meter would carry no information for 95% of the rows while looking like it- * did. On a log scale the decades are evenly spaced and a 128 K model reads as- * visibly larger than a 32 K one.- *- * Bounds come from the CURRENTLY FILTERED list, so the column re-scales as the user- * narrows it — the comparison a reader is making is always against what they can- * see. A degenerate range (one row, or every row identical) yields 100: a full bar- * is the honest answer when the largest thing visible is also the smallest.- *- * THE SCALE'S FLOOR IS AT LEAST SIX DOUBLINGS BELOW THE LARGEST, never simply the- * list's own minimum — MEASURED on the first capture. A roster of 250 K and 1 M models- * scaled to its own bounds paints every 250 K row at exactly 0%: an empty track, which- * is the glyph `Meter` uses for "nothing", under a numeral that says 250 K. The column- * stops carrying information precisely when the list is homogeneous, which is most- * lists. Anchoring the floor at `max / 64` makes the bar mean something stable — "how- * big, on a log scale spanning at least six doublings" — and the 250 K row reads at two- * thirds instead of at zero.- *- * `NaN` for an absent window, deliberately: `MeterSpan` paints `NaN` as a dim `╌`- * run, while 0 paints the same full `░` track a healthy-but-tiny window paints.- * Absent data and small data must not look alike.- */-export function contextMeterPct(ctx: number | undefined, min: number, max: number): number {- if (!ctx || !Number.isFinite(ctx) || ctx <= 0) return Number.NaN;- if (!Number.isFinite(max) || max <= 0) return 100;- const lo = Math.min(Number.isFinite(min) && min > 0 ? min : max, max / 64);- if (max <= lo) return 100;- const pct = (100 * (Math.log(ctx) - Math.log(lo))) / (Math.log(max) - Math.log(lo));- return Math.min(100, Math.max(0, pct));-}--/**- * THE FILL IS CHEAPNESS, NOT COST, and the ramp is why.- *- * `ramps.savings` runs red → yellow → green, so a FULL bar is green. A meter- * colours cells by position along the fill, so if length encoded cost the dearest- * model on screen would paint a full green bar — red meaning "cheap" on one row and- * green meaning "expensive" on the next, which is the one-colour-one-meaning rule- * broken inside a single column. Encoding cheapness instead makes a long green bar- * "costs you least" and a one-cell red stub "costs you most", which is both true- * and the direction a reader scanning for a cheap model wants.- *- * Log-scaled for the same reason as the context meter: per-token prices on one- * screen span $0.05 to $15 per million.- */-export function priceMeterPct(price: number | undefined, min: number, max: number): number {- if (price === undefined || !Number.isFinite(price) || price < 0) return Number.NaN;- if (price === 0) return 100;- if (!Number.isFinite(min) || !Number.isFinite(max) || min <= 0 || max <= min) return 100;- const clamped = Math.min(Math.max(price, min), max);- const t = (Math.log(clamped) - Math.log(min)) / (Math.log(max) - Math.log(min));- return Math.min(100, Math.max(0, 100 * (1 - t)));-}+/** Where a list came from — the one value that drives every provenance encoding. */+export type ListOrigin = "roster" | "catalog";/**- * `$9.00/1M` → 9. `SUB`, `LOCAL`, `N/A` → undefined.+ * What the price column prints.*- * Parsed rather than plumbed because `resolveProviderDisplayPrice` is the ONE- * function allowed to decide what a row costs (its `isSubscriptionProvider`-first- * rule is test-pinned), and it answers a display string. Re-deriving the number- * from a second source would be a second opinion about money.+ * `resolveProviderDisplayPrice` is the ONE function allowed to decide what a row+ * costs (its `isSubscriptionProvider`-first rule is test-pinned) and it answers a+ * display string, so this only ever RESHAPES that answer — it never recomputes it.+ * Two reshapes, both to buy columns back for the model name: the `/1M` suffix goes+ * because the column header says `$/1M` once for the whole list, and `LOCAL`+ * becomes `local` because a local model has no price at all and shouting is for+ * things that cost money.*/-export function parseDisplayPrice(display: string): number | undefined {- const m = /\d+(\.\d+)?/.exec(display);- if (!m) return undefined;- const n = Number.parseFloat(m[0]);- return Number.isFinite(n) ? n : undefined;+export function priceLabel(display: string, billing: BillingMode): string {+ if (billing === "local") return "local";+ const s = (display || "N/A").trim();+ if (s === "LOCAL") return "local";+ if (s === "SUB" || s === "FREE" || s === "N/A") return s;+ return s.replace(/\s*\/\s*1M$/i, "");}-/** The rail's billing tag — right-aligned text, the colour carrying the meaning. */-export function billingTag(mode: BillingMode): { text: string; fg: string } {- if (mode === "sub") return { text: "SUB", fg: tokens.success };- if (mode === "local") return { text: "LOCAL", fg: tokens.running };- return { text: "$", fg: tokens.subtle };+/** The one colour each price label is allowed to have. */+export function priceFg(label: string): string {+ if (label === "FREE") return tokens.success;+ if (label === "SUB") return tokens.warn;+ if (label === "local") return tokens.trace;+ if (label === "N/A") return tokens.dead;+ return tokens.text;}/** `●` ready · `○` needs a key · `◌` probe in flight — `ProvidersContent.tsx:225`. */@@ -125,96 +91,79 @@ export function readinessGlyph(r: Readiness): { glyph: string; fg: string } {return { glyph: "◌", fg: tokens.warn };}-/** Where a list came from — the one value that drives all three fallback encodings. */-export type ListOrigin = "roster" | "catalog";+/** The provider view's billing word, in the same colours a model row uses. */+export function billingLabel(mode: BillingMode): { text: string; fg: string } {+ if (mode === "sub") return { text: "SUB", fg: tokens.warn };+ if (mode === "local") return { text: "local", fg: tokens.trace };+ return { text: "$", fg: tokens.subtle };+}++const SPACES = " ";+const gap = (n: number): string => SPACES.slice(0, Math.max(0, n));/**- * A flat-rate price gets a dim `╌` run where the METER would be, and its word in- * `tokens.success` where the numeral would be — never a 0% or zero-width meter. A- * subscription has no per-token number, and an empty bar in the cheapness column would- * read as "the cheapest thing on screen", which is a different claim from "this is not- * billed per token". `Meter` makes the same distinction for `NaN`, in the same glyph.- *- * NOT A `BadgeSpan`, AND THAT IS MEASURED. The first capture rendered ` SUB ` as a chip- * on all 21 rows of a subscription provider's roster, and the chips — adjacent rows,- * same fill, no gap between them — fused into one solid green RECTANGLE down the price- * column with the labels floating in it. That is the failure `viz/widgets.tsx` records- * for 24 `UP` chips in a service list, arriving vertically instead of horizontally. A- * chip is for a status that DISTINGUISHES a row; when every row carries it, the chip is- * a wall. The rail's per-provider `SUB` tag already says it once, where it is true of- * the provider rather than of each model.+ * The column header. It exists so the four fixed cells are NAMED rather than+ * guessed at, which is the cheapest possible answer to "what is happening here":+ * the previous build printed `262K` and `$30.00/1M` beside two unlabelled bars.*/-function isFlatRateLabel(priceText: string): boolean {- return priceText === "SUB" || priceText === "LOCAL" || priceText === "FREE";-}--/** Flat rate is `success` (it costs nothing more), absent is `dead`, a rate is body ink. */-function priceFg(priceText: string, flat: boolean): string {- if (flat) return tokens.success;- return priceText === "N/A" ? tokens.dead : tokens.text;+export function ColumnHeader({ layout }: { layout: RowLayout }): ReactNode {+ return (+ <box height={1} flexShrink={0}>+ <text>+ <span fg={tokens.trace}>{" "}</span>+ <span fg={tokens.trace}>{padTo("model", layout.id)}</span>+ <span>{gap(GAPS.afterId)}</span>+ <span fg={tokens.trace}>{padStartTo("provider", layout.provider)}</span>+ <span>{gap(GAPS.afterProvider)}</span>+ <span fg={tokens.trace}>{padStartTo("ctx", layout.ctx)}</span>+ <span>{gap(GAPS.afterCtx)}</span>+ <span fg={tokens.trace}>{padStartTo("$/1M", layout.price)}</span>+ {layout.mark > 0 ? <span fg={tokens.trace}>{padStartTo("", layout.mark)}</span> : null}+ </text>+ </box>+ );}export interface ModelRowProps {model: ModelInfo;+ /** The routing shortcut of the provider that would serve it — `or@`, `kc@`. */+ shortcut: string;+ /** Whatever `resolveProviderDisplayPrice` said, already reshaped by `priceLabel`. */+ price: string;layout: RowLayout;cursor: boolean;- /** 0–100, or `NaN` for an absent window. From `contextMeterPct`. */- ctxPct: number;- /** 0–100, `NaN` when there is no per-token rate to compare. */- pricePct: number;- /** Whatever `resolveProviderDisplayPrice` said — `SUB`, `$1.25/1M`, `N/A`. */- priceText: string;- /** `catalog` adds the `CAT` chip that says this row is not the live roster. */+ /** `catalog` marks a row that is NOT from the provider's live roster. */origin: ListOrigin;}export function ModelRow({model,+ shortcut,+ price,layout,cursor,- ctxPct,- pricePct,- priceText,origin,}: ModelRowProps): ReactNode {// Render-time reads — see the file header.const idFg = cursor ? C.strong : tokens.text;- const flat = isFlatRateLabel(priceText);-- // THE WASH LIVES ON THE BOX, not on the `<text>`: a text node is only as wide as- // its content, so a row highlighted that way stops at its last glyph and reads as- // a floating chip rather than as a bar. The box fills the panel's width — which is- // why the panel is `flush`, so there is no padding gutter to break the band — and- // `height={1}` keeps a row from overprinting its neighbour. Same construction as- // `resume-picker.tsx:999`.return (+ // THE WASH LIVES ON THE BOX, not on the `<text>`: a text node is only as wide+ // as its content, so a row highlighted that way stops at its last glyph and+ // reads as a floating chip rather than as a bar. `height={1}` keeps a row from+ // overprinting its neighbour.<box height={1} flexShrink={0} backgroundColor={cursor ? C.bgHighlight : undefined}><text attributes={A.boldIf(cursor)}><span fg={cursor ? tokens.accent : tokens.trace}>{cursor ? "▶ " : " "}</span><span fg={idFg}>{padTo(model.id, layout.id)}</span>- <span> </span>- <MeterSpan pct={ctxPct} width={layout.ctx} ramp={ramps.volume} />- <span> </span>- <span fg={tokens.subtle}>{padStartTo(model.context || "N/A", layout.ctxNum)}</span>- {layout.price > 0 ? <span> </span> : null}- {layout.price > 0 && flat ? <span fg={tokens.dead}>{"╌".repeat(layout.price)}</span> : null}- {layout.price > 0 && !flat ? (- <MeterSpan pct={pricePct} width={layout.price} ramp={ramps.savings} />- ) : null}- <span> </span>- <span fg={priceFg(priceText, flat)}>{padStartTo(priceText, layout.priceNum)}</span>- {layout.caps > 0 ? <span> </span> : null}- {layout.caps > 0 ? capsCell(model, layout.caps) : null}- {layout.date > 0 ? <span> </span> : null}- {layout.date > 0 ? (- <span fg={tokens.trace}>- {padStartTo(model.releaseDate ? model.releaseDate.slice(0, 7) : "—", layout.date)}- </span>- ) : null}- {layout.mark > 0 ? <span> </span> : null}+ <span>{gap(GAPS.afterId)}</span>+ <span fg={tokens.subtle}>{padStartTo(shortcut, layout.provider)}</span>+ <span>{gap(GAPS.afterProvider)}</span>+ <span fg={tokens.subtle}>{padStartTo(model.context || "N/A", layout.ctx)}</span>+ <span>{gap(GAPS.afterCtx)}</span>+ <span fg={priceFg(price)}>{padStartTo(price, layout.price)}</span>{layout.mark > 0 ? (- <span fg={tokens.warn} attributes={A.boldIf(origin === "catalog")}>- {padStartTo(origin === "catalog" ? "cat" : "", layout.mark - 1)}+ <span fg={tokens.warn}>+ {padStartTo(origin === "catalog" ? "catalog" : "", layout.mark)}</span>) : null}</text>@@ -222,139 +171,96 @@ export function ModelRow({);}-/**- * THE `cat` MARK SAYS "THIS ROW IS NOT THE LIVE ROSTER", in the warn colour, on every- * row of a fallback list — and it is TEXT rather than a chip for the third time in this- * file, for the reason the other two record.- *- * MEASURED: as a `BadgeSpan` it was right on the four-row Kimi fallback and wrong on the- * seventeen-row OpenRouter one, where seventeen identical orange chips in adjacent rows- * fused into a solid slab down the panel — louder than the list it was annotating, and- * no longer reading as seventeen labels. A chip marks a row that DIFFERS from its- * neighbours; a whole-list property gets a coloured word. The loud encodings of this- * same fact are the panel title and the banner, which appear once each.- *- * The column is reserved on BOTH kinds of list (it renders blank on a live one), so the- * cells left of it do not move between them.- *- * Defect 4 of the measured failure is that a cloud-catalog fallback list renders- * identically to a healthy roster — prices, descriptions, the lot — so the eye goes- * to the list, the list looks fine, and it is simply short. That is the user's- * complaint verbatim. Three encodings fix it and all three derive from ONE value (the- * outcome variant that produced the list): the panel title, the banner's provenance- * sentence, and this chip.- *- * Outside the budget because the budget is EXACT: a provenance cell that consumed- * columns would re-size every other cell between a live list and a fallback list, so- * the two would not be visually comparable. Overflow clips at the panel edge, which- * is the failure mode every widget in `viz/` prefers — visible, and attributable to- * the row.- */--/**- * `[TRV]` — one letter per capability, bright when present, `tokens.dead` when not.- * Five columns for all three flags, identical at every width.- *- * DELIBERATELY NOT `BadgeSpan` CHIPS, AND THAT IS MEASURED. The first wide capture- * rendered the capability column as three chips per row, and because every model in a- * roster carries the same capability, the `T` chips down 21 adjacent rows fused into- * one solid green RECTANGLE — `viz/widgets.tsx`'s measured 24-`UP`-chips failure,- * arriving vertically. The general rule this settles: a chip marks a row that DIFFERS- * from its neighbours; a per-row ATTRIBUTE column, where every row has a value, uses- * coloured glyphs. The one chip left in a model row is `CAT`, which marks a whole list- * whose provenance the reader must not miss.- *- * It still survives greyscale and colour-blindness, because the letters are the label:- * `[T··]` and `[TRV]` differ in glyphs, not only in hue.- */-function capsCell(model: ModelInfo, width: number): ReactNode {- const flags: Array<{ label: string; on: boolean; color: string }> = [- { label: "T", on: model.supportsTools === true, color: tokens.success },- { label: "R", on: model.supportsReasoning === true, color: tokens.running },- { label: "V", on: model.supportsVision === true, color: C.magenta },- ];- return (- <>- <span fg={tokens.trace}>{"["}</span>- {flags.map((f) => (- <span key={f.label} fg={f.on ? f.color : tokens.dead}>- {f.label}- </span>- ))}- <span fg={tokens.trace}>{"]"}</span>- {width > 5 ? <span>{" ".repeat(width - 5)}</span> : null}- </>- );-}--export interface RailRowProps {+export interface ProviderRowProps {label: string;+ shortcut: string;readiness: Readiness;billing: BillingMode;- /** Served-model count once a list for this provider has landed; `null` until then. */+ /** Models this provider serves, or `null` before the catalog has answered. */count: number | null;+ /** Does this provider list its own roster? Decides what `0` in the catalog means. */+ hasDiscovery: boolean;+ /** Why it is not selectable — an env var name, or empty. */+ note: string;cursor: boolean;- focused: boolean;- layout: RailLayout;+ /** Usable content columns. */+ inner: number;}/**- * One provider. The glyph is readiness, the tag is billing, the count is how many- * models this session has actually seen for it — `null`, drawn `—`, until a list- * lands, because a count invented before the list is a number with no source.+ * One provider, in the `p` dialog.*- * The cursor wash is `bgHighlight` while the rail has focus and the quieter `bgAlt`- * while the model pane does, so the screen always shows exactly one active cursor.+ * IT IS A DIALOG, NOT A RAIL, and that is the fix for the complaint. The rejected+ * build put a 19-column provider rail permanently beside the model list, which+ * gave the screen two cursors with only a border colour to say which one the arrow+ * keys drove — "super unclear what is happening", precisely described. It also+ * truncated two different providers to the same `opencod…`. At full dialog width+ * the names are whole, and only one list is ever on screen.*/-export function ProviderRailRow({+export function ProviderRow({label,+ shortcut,readiness,billing,count,+ hasDiscovery,+ note,cursor,- focused,- layout,-}: RailRowProps): ReactNode {+ inner,+}: ProviderRowProps): ReactNode {const { glyph, fg } = readinessGlyph(readiness);- const tag = billingTag(billing);+ const bill = billingLabel(billing);+ // The right-hand cell carries EITHER a count OR the env var a missing provider+ // wants, and the env var is the longer of the two by a wide margin+ // (`MOONSHOT_API_KEY` is 16, `needs ` makes 22). It is sized for the env var,+ // because a truncated variable name is worse than useless — `needs MOON…` sends+ // the reader looking for a variable that does not exist.+ const countCell = 26;+ const shortcutCell = 9;+ const billCell = 6;+ const nameCell = Math.max(6, inner - 2 - 2 - shortcutCell - billCell - countCell - 3);+ // `0 models` IS A DIFFERENT CLAIM FOR A DISCOVERY PROVIDER, and printing it there+ // would be the original defect in miniature: Devin and Antigravity carry no catalog+ // entries by design and ask their own endpoint for a roster the moment you scope to+ // them, so "0 models" reads as "this provider has nothing" about a provider that+ // has not been asked yet.+ const countText =+ count === null+ ? "—"+ : count === 0 && hasDiscovery+ ? "asks its own roster"+ : `${count} model${count === 1 ? "" : "s"}`;return (- <box- height={1}- flexShrink={0}- backgroundColor={cursor ? (focused ? C.bgHighlight : C.bgAlt) : undefined}- >+ <box height={1} flexShrink={0} backgroundColor={cursor ? C.bgHighlight : undefined}><text attributes={A.boldIf(cursor)}>+ <span fg={cursor ? tokens.accent : tokens.trace}>{cursor ? "▶ " : " "}</span><span fg={fg}>{glyph}</span><span> </span>- <span fg={cursor ? tokens.accent : tokens.text}>{padTo(label, layout.label)}</span>- {layout.tag > 0 ? <span> </span> : null}- {layout.tag > 0 ? <span fg={tag.fg}>{padStartTo(tag.text, layout.tag)}</span> : null}- {layout.count > 0 ? <span> </span> : null}- {layout.count > 0 ? (- <span fg={tokens.subtle}>- {padStartTo(count === null ? "—" : String(count), layout.count)}- </span>- ) : null}+ <span fg={cursor ? C.strong : tokens.text}>{padTo(label, nameCell)}</span>+ <span> </span>+ <span fg={tokens.subtle}>{padTo(shortcut, shortcutCell)}</span>+ <span fg={bill.fg}>{padTo(bill.text, billCell)}</span>+ <span fg={readiness === "missing" ? tokens.dead : tokens.subtle}>+ {padStartTo(readiness === "missing" && note !== "" ? note : countText, countCell)}+ </span></text></box>);}/**- * A dim, NON-SELECTABLE row for something the rail is deliberately not listing —- * the providers with no credential, collapsed, and the local providers that are in- * the catalog but not enabled in config.+ * A dim, NON-SELECTABLE row for something a list is deliberately not showing.** An unexplained absence is the defect class this whole feature is about, so the- * rail says the number out loud. It stays unselectable because a row that cannot be+ * number is said out loud. It stays unselectable because a row that cannot be* picked must not look like one that can: offering it would trade a silent absence* for a dead end.*/-export function RailHintRow({ text, width }: { text: string; width: number }): ReactNode {+export function HintRow({ text, width }: { text: string; width: number }): ReactNode {return (<box height={1} flexShrink={0}><text>- <span fg={tokens.trace}>{truncate(text, width)}</span>+ <span fg={tokens.trace}>{truncate(` ${text}`, width)}</span></text></box>);diff --git a/packages/cli/src/providers/model-catalog.ts b/packages/cli/src/providers/model-catalog.tsindex 82401246..b26789da 100644--- a/packages/cli/src/providers/model-catalog.ts+++ b/packages/cli/src/providers/model-catalog.ts@@ -82,6 +82,29 @@ export interface CatalogClient {* Cross-vendor search. Delegates to Firebase `?search=...` for live results.*/searchModels(term: string, limit?: number): Promise<CatalogModel[]>;++ /**+ * Every model the slim catalog says this vendor SERVES — synchronous, local,+ * no network, for EVERY slug rather than only the aggregator ones.+ *+ * WHY IT EXISTS SEPARATELY FROM `modelsByVendor`. The picker draws ONE flat+ * cross-provider list, so it asks this question about ~31 providers at once.+ * `modelsByVendor` answers it for an owner slug with a live `?provider=` query,+ * and 22 of those fired together took 10 s and returned nothing (measured:+ * every one aborted on its shared timeout, while the same query alone takes+ * ~1.1 s). A picker cannot spend that, and it must not degrade to "this+ * provider has no models", which is the exact complaint this feature exists to+ * remove.+ *+ * IT IS NOT A SECOND AUTHORITY. `aggregators[].provider` is already the+ * served-by index — `modelsByVendor`'s own owner branch filters its rich+ * lineage list THROUGH it (`filterToServedByProvider`) precisely because+ * lineage is not service. This reads the same field for the same question and+ * skips the lineage query, so its membership is the served-by set exactly. The+ * cost is per-model richness: `description` and the owner slug are absent from+ * the slim payload, so a row's blurb is derived rather than editorial.+ */+ servedByVendor(vendorSlug: string): CatalogModel[];}// ─── Slug classification ─────────────────────────────────────────────────────@@ -242,12 +265,16 @@ function slimEntryToCatalogModel(entry: SlimModelEntry): CatalogModel {// the default provider) rendered its capability column entirely dead while the// data sat in the cache. Visible the moment a row carries a capability column.//- // `tools` is NOT here because the slim payload does not carry it: that is a- // models-index gap, not a CLI one, and inventing `true` would be worse than a- // dim glyph. Recorded rather than guessed.+ // `supportsTools` IS carried by the slim payload (~97% of models, per its own+ // field doc) and was left unmapped here, so every aggregator-served row showed+ // a dead tools flag while the answer sat one property away. It is forwarded+ // ONLY when present — `undefined` stays `undefined` rather than becoming+ // `false`, because "the catalog does not say" and "this model cannot take+ // tools" are different claims and only the second one disqualifies a model.capabilities: {...(entry.supportsVision === undefined ? {} : { vision: entry.supportsVision }),...(entry.reasoning === undefined ? {} : { thinking: true }),+ ...(entry.supportsTools === undefined ? {} : { tools: entry.supportsTools }),},};}@@ -374,5 +401,21 @@ export function createCatalogClient(deps: CatalogClientDeps = {}): CatalogClientconst docs = await _searchModels(term, limit);return docs.map(modelDocToCatalogModel);},++ servedByVendor(vendorSlug: string): CatalogModel[] {+ const slug = vendorSlug.toLowerCase();+ // Local-only vendors are absent from the catalog BY DESIGN, so an empty+ // answer here is a fact, not a miss. Their rosters come from their own+ // daemons through `modelDiscovery`.+ if (NO_CATALOG_VENDOR_SLUGS.has(slug)) return [];+ const { entries } = readSlimCacheWithFreshness(_readSlimCache);+ const out: CatalogModel[] = [];+ for (const entry of entries) {+ if (entry.aggregators?.some((agg) => agg.provider.toLowerCase() === slug)) {+ out.push(slimEntryToCatalogModel(entry));+ }+ }+ return out;+ },};}diff --git a/packages/cli/src/providers/transport/probe-discovery.ts b/packages/cli/src/providers/transport/probe-discovery.tsindex 42a2a8d9..98d3d00a 100644--- a/packages/cli/src/providers/transport/probe-discovery.ts+++ b/packages/cli/src/providers/transport/probe-discovery.ts@@ -39,9 +39,28 @@ const SMALL_MODEL_PATTERNS = [/*** Models that can't handle a `/v1/chat/completions` probe request: image- * generation, embeddings, TTS, ASR. These often appear in /v1/models lists- * alongside chat models (especially on LiteLLM aggregators) but will 404- * or 400 the probe. Filter them out before ranking.+ * generation, embeddings, TTS, ASR, speech-to-text, video generation. These+ * often appear in /v1/models lists alongside chat models (especially on+ * LiteLLM aggregators) but will 404 or 400 the probe. Filter them out before+ * ranking.+ *+ * WHAT THIS CANNOT DO, STATED RATHER THAN IMPLIED. Every pattern here reads a+ * model ID, and an ID is not a modality contract. The three families below were+ * added after a screenshot of the model picker listed all seven of+ * `mai-transcribe-2`, `mai-transcribe-1.5`, `gpt-transcribe`, `mai-voice-2`,+ * `mai-voice-2-flash`, `flux-3-video` and `seedance-2.5` as launchable coding+ * models — and only six of those seven say what they are in their name.+ * `seedance-2.5` is a video generator whose ID carries no signal at all, and+ * `flux-2-*` is an image generator for the same reason; neither can be excluded+ * here without a vendor-family blacklist, which is the workaround this file has+ * already paid for three times (`:498`, then `pplx-embed`, then `bge`).+ *+ * The complete fix is a modality field on the catalog document — `ModelDoc`+ * already carries `capabilities.imageGeneration` / `audioInput` / `audioOutput`+ * / `embedding`, but the SLIM payload every aggregator list is built from+ * carries none of them. That is a models-index gap and it is filed there, not+ * patched here. `toPickerRows` (model-selector.ts) logs the residue once per+ * process so the gap is visible in a debug log rather than only in a screenshot.*/const NON_CHAT_PATTERNS = [/\bimage\b/i,@@ -58,7 +77,21 @@ const NON_CHAT_PATTERNS = [/\bmoderation\b/i,/\brerank/i,/\bspeech\b/i,- /-(image|tts|audio|embedding|vision-only)(-|$)/i,+ // Speech-to-text. `gemini-3.5-transcribe` is the case `toPickerRows` named as+ // getting through, and `mai-transcribe-*` / `gpt-transcribe` are the observed+ // leaks. No chat model in any served roster carries the word.+ /\btranscribe\b/i,+ /\btranscription\b/i,+ // Text-to-speech under a name that does not say `tts`: `mai-voice-2`,+ // `mai-voice-2-flash`.+ /\bvoice\b/i,+ // Video GENERATION (`flux-3-video`, `*-video-gen`). Accepted risk, recorded:+ // a future video-UNDERSTANDING chat model named `video-something` would be+ // dropped too. No such model is in any roster today, and the alternative —+ // listing a generator as a coding target — fails at launch instead of in the+ // list.+ /\bvideo\b/i,+ /-(image|tts|audio|embedding|vision-only|transcribe|voice|video|speech)(-|$)/i,];function isSmallName(name: string): boolean {diff --git a/packages/cli/src/tui/components/LoadingRow.tsx b/packages/cli/src/tui/components/LoadingRow.tsxindex 9b3568df..f8f1592f 100644--- a/packages/cli/src/tui/components/LoadingRow.tsx+++ b/packages/cli/src/tui/components/LoadingRow.tsx@@ -32,7 +32,7 @@import type { ColorInput } from "@opentui/core";import type { ReactNode } from "react";-import { displayWidth, padStartTo } from "../viz/text.js";+import { displayWidth, padStartTo, padTo } from "../viz/text.js";import { type Ramp, ramps, tokens } from "../viz/tokens.js";import { MeterSpan } from "../viz/widgets.js";import { ShimmerSpan } from "./Shimmer.js";@@ -54,6 +54,17 @@ export interface LoadingRowProps {ramp?: Ramp;/** Shimmer colour. Defaults to the in-flight tier. */fg?: ColorInput;+ /**+ * Put the LABEL first, padded to this many columns, instead of last.+ *+ * The default (bar · figure · label) reads well in a horizontal strip where the+ * bars line up and the labels trail off. It reads badly as a stacked list of+ * named operations, which is what a loading DIALOG is: there the reader is+ * scanning "what is claudish doing", so the names have to form the left column+ * and the bars the second. Both orders keep one `<text>` per row, and the+ * padding is what makes the bars align.+ */+ labelWidth?: number;}/**@@ -77,6 +88,7 @@ export function LoadingRow({valueWidth,ramp = ramps.volume,fg,+ labelWidth,}: LoadingRowProps): ReactNode {// Read at RENDER time: `C`/`tokens` are reassigned in place when the terminal// theme is detected, and a module-level capture would pin the dark palette.@@ -84,14 +96,31 @@ export function LoadingRow({const valueFg = tokens.text;const determinate = pct !== undefined;const column = value === undefined ? 0 : Math.max(valueWidth ?? 0, displayWidth(value));+ const bar = determinate ? (+ <MeterSpan pct={pct} width={width} ramp={ramp} />+ ) : (+ <ShimmerSpan frame={frame} width={width} {...(fg === undefined ? {} : { fg })} />+ );++ if (labelWidth !== undefined) {+ return (+ <text flexShrink={0}>+ <span fg={labelFg}>{padTo(label, labelWidth)}</span>+ <span> </span>+ {bar}+ {value === undefined ? null : (+ <>+ <span> </span>+ <span fg={valueFg}>{padTo(value, column)}</span>+ </>+ )}+ </text>+ );+ }return (<text flexShrink={0}>- {determinate ? (- <MeterSpan pct={pct} width={width} ramp={ramp} />- ) : (- <ShimmerSpan frame={frame} width={width} {...(fg === undefined ? {} : { fg })} />- )}+ {bar}{value === undefined ? null : (<><span> </span>