Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
feat(picker): the provider list is the default screen, and nothing is prefetched
Jack Rudenkoff00f56c7b7c
diff --git a/packages/cli/src/model-selector.ts b/packages/cli/src/model-selector.tsindex 75d6ebae..19778bc3 100644--- a/packages/cli/src/model-selector.ts+++ b/packages/cli/src/model-selector.ts@@ -1738,97 +1738,6 @@ export async function buildDiscoveredModelRows(return outcome.kind === "rows" ? outcome.rows : [];}-/**- * One provider's LIVE roster, for MERGING into the cross-provider list — the- * outcome reduced to the three answers an aggregate view can act on.- *- * WHY IT IS NOT {@link buildDiscoveredModelOutcome}. The owner searched `gemini`- * in the flat list and got eleven rows, every one of them `or@`: the list was- * built from the cloud catalog alone, so every provider that serves its roster- * through live discovery — Antigravity, Devin, the coding plans, both local- * daemons — was invisible until you first selected it. That is the opposite of- * the feature: the flat list's whole value is seeing one model on several routes- * at different prices, and the routes it was hiding are the FLAT-RATE ones, which- * are exactly the rows worth finding.- *- * TWO DIFFERENCES FROM THE SCOPED PATH, AND BOTH ARE ABOUT COST:- *- * 1. **No `loadModelsForPickerProvider` leg.** That is the live `?provider=`- * query measured at 10 018 ms for 22 concurrent callers. Prices come from- * {@link servedModelsForProvider} instead — the same local served-by index the- * rest of the flat list is built from, ~1 ms for the whole roster — so the- * merge costs one roster request per provider and no catalog traffic at all.- * 2. **No fallback rows.** A provider whose discovery fails contributes nothing- * NEW here; its catalog rows are already in the list, so repeating them under- * a `catalog` mark would double the provider's rows. Hence `FallbackTaken`- * is `"unknown"`: the notice states the cause and claims nothing about what- * is shown instead, because at this call site nothing has been substituted.- *- * NEVER REJECTS, inheriting {@link discoverProviderRoster}'s contract and- * guarding it anyway — a rejection behind a live renderer leaves a progress- * indicator running against a promise that never settles.- */-export type PreloadedRoster =- | { kind: "rows"; rows: ModelInfo[] }- /** Reachable, and it added nothing. Not a failure, and never reported as one. */- | { kind: "empty"; reason: "unsupported" | "empty-roster" | "all-filtered" }- | { kind: "failed"; failure: DiscoveryFailure; notice: string[] };--export async function preloadProviderRoster(- provider: string,- displayName: string,- catalog: CatalogClient-): Promise<PreloadedRoster> {- let roster: RosterOutcome;- try {- roster = await discoverProviderRoster(provider);- } catch (e: unknown) {- roster = {- kind: "failed",- failure: {- kind: "unreachable",- provider,- detail: oneLineDetail((e as Error)?.message ?? String(e)),- },- };- }-- if (roster.kind === "unsupported") return { kind: "empty", reason: "unsupported" };- if (roster.kind === "failed") {- const { failure } = roster;- if (failure.kind === "empty-roster") return { kind: "empty", reason: "empty-roster" };- const def = getProviderByName(provider);- return {- kind: "failed",- failure,- notice: formatDiscoveryFailureNotice(- displayName,- failure,- def ?? { apiKeyEnvVar: "", apiKeyUrl: "" },- "unknown"- ),- };- }-- const served = rankDiscoveredModels(roster.models);- const discovered = served.filter((m) => isChatCapable(m.id));- if (discovered.length === 0) return { kind: "empty", reason: "all-filtered" };- // The local served-by index is the price source: a metered discovery provider- // shows the real rate, and a flat-rate one ignores it (`buildRowsFromDiscovered`).- const rows = buildRowsFromDiscovered(- provider,- displayName,- discovered,- servedModelsForProvider(provider, catalog)- );- return rows.length > 0 ? { kind: "rows", rows } : { kind: "empty", reason: "all-filtered" };-}--/** A multi-line upstream detail as one line, so a notice stays one row. */-function oneLineDetail(s: string): string {- return s.replace(/\s+/g, " ").trim();-}-/*** Chat-capable discovered models → picker rows. Pure; no I/O.*diff --git a/packages/cli/src/picker/ModelPicker.test.tsx b/packages/cli/src/picker/ModelPicker.test.tsxindex 705fbfb5..7899c915 100644--- a/packages/cli/src/picker/ModelPicker.test.tsx+++ b/packages/cli/src/picker/ModelPicker.test.tsx@@ -19,13 +19,19 @@ import { describe, expect, test } from "bun:test";* any list row. Both are decidable from a frame, and both would have failed the* build that shipped.*+ * AND THE ONES ABOUT THE ROUND-TWO CORRECTION, which are about what the picker does+ * NOT do. `calls` counts every loader the fake is asked for, so "nothing is fetched+ * before the user asks for it" is an assertion rather than a claim in a comment —+ * and it is the one that would have caught the build the owner rejected, which+ * looked correct and simply did too much.+ ** 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";import type { ReactNode } from "react";-import type { ModelInfo, PickerDiscoveryOutcome, PreloadedRoster } from "../model-selector.js";+import type { ModelInfo, PickerDiscoveryOutcome } from "../model-selector.js";import type { DescriptionIndex } from "../providers/model-descriptions.js";import { C } from "../tui/theme.js";import { ModelPicker } from "./ModelPicker.js";@@ -62,22 +68,31 @@ interface FakeOpts {roster?: PickerProviderChoice[];ready?: Record<string, boolean>;outcome?: PickerDiscoveryOutcome;+ /** Per-provider discovery outcomes. Falls back to `outcome`. */+ outcomes?: Record<string, PickerDiscoveryOutcome>;/** Per-provider served lists; falls back to `served`. */byProvider?: Record<string, ModelInfo[]>;served?: ModelInfo[];- /** Per-provider LIVE roster outcomes, for the cross-provider merge. */- liveRosters?: Record<string, PreloadedRoster>;/** `modelId` → prose sentence, as the description index answers. */descriptions?: Record<string, string>;/** Never settles — the in-flight states. */hang?: boolean;}-function fakeSource(opts: FakeOpts = {}): PickerDataSource {+/** Every loader the picker may reach for, counted. See the file header. */+interface Calls {+ catalog: number;+ descriptions: number;+ discover: string[];+}++function fakeSource(opts: FakeOpts = {}): PickerDataSource & { calls: Calls } {const roster = opts.roster ?? [provider()];const never = new Promise<never>(() => {});const descriptions = opts.descriptions ?? {};+ const calls: Calls = { catalog: 0, descriptions: 0, discover: [] };return {+ calls,providerRoster: () => roster,notEnabledLocalProviders: () => [],displayName: (p) => roster.find((r) => r.value === p)?.label ?? p,@@ -85,27 +100,29 @@ function fakeSource(opts: FakeOpts = {}): PickerDataSource {if (opts.hang) await never;for (const n of names) yield [n, opts.ready?.[n] ?? true] as [string, boolean];},- ensureCatalog: (): Promise<void> => (opts.hang ? never : Promise.resolve()),+ ensureCatalog: (): Promise<void> => {+ calls.catalog++;+ return 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 }- ),- rosterRows: (p): Promise<PreloadedRoster> =>- opts.hang+ discoverRoster: (p): Promise<PickerDiscoveryOutcome> => {+ calls.discover.push(p);+ return opts.hang? never: Promise.resolve(- opts.liveRosters?.[p] ?? { kind: "empty", reason: "unsupported" as const }- ),- descriptions: (): Promise<DescriptionIndex> =>- opts.hang+ opts.outcomes?.[p] ??+ opts.outcome ?? { kind: "rows", rows: [model()], servedCount: 1, chatCount: 1 }+ );+ },+ descriptions: (): Promise<DescriptionIndex> => {+ calls.descriptions++;+ return opts.hang? never: Promise.resolve({get: (id: string) => descriptions[id],size: Object.keys(descriptions).length,- }),+ });+ },};}@@ -113,6 +130,8 @@ interface Drawn {text: string[];frame: CapturedFrame;press: (keys: string[]) => Promise<void>;+ /** Re-render until the frame satisfies `pred`, or give up and let the assert speak. */+ until: (pred: (text: string[]) => boolean) => Promise<void>;recapture: () => { text: string[]; frame: CapturedFrame };destroy: () => void;}@@ -139,6 +158,22 @@ async function draw(node: ReactNode, width = 80, height = 24, settleMs = 30): Prawait new Promise((r) => setTimeout(r, 20));await renderOnce();},+ /**+ * A FIXED SLEEP AFTER A KEYSTROKE IS A FLAKE, and this suite proved it: the+ * keystroke that opens a list starts an effect, and on a loaded machine the+ * 20 ms after it is not always enough for the effect, the state update and the+ * next paint. Under `bun test` with 212 files in flight it failed once and+ * passed alone, which is the worst signal there is. Polling for the CONDITION+ * the test is about takes the load out of the assertion; the deadline is short+ * enough that a genuine regression still fails in well under a second.+ */+ until: async (pred) => {+ for (let i = 0; i < 40; i++) {+ if (pred(captureCharFrame().split("\n"))) return;+ await new Promise((r) => setTimeout(r, 25));+ await renderOnce();+ }+ },recapture,destroy: () => renderer.destroy(),};@@ -149,6 +184,18 @@ 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();+/**+ * HAS A MODEL LIST FINISHED PAINTING? The filter row's `newest first` is drawn by+ * the list phase and by nothing else — not by the loading dialog, not by the+ * provider list — so it is the one string that separates "the view flipped" from+ * "the view flipped and the rows are there".+ *+ * `▶` would not do: every list in this picker draws a cursor, including the one the+ * keystroke just left, so a predicate on it is satisfied before anything has+ * happened and waits for nothing.+ */+const listPainted = (t: string[]): boolean => t.join("").includes("newest first");+const providerListPainted = (t: string[]): boolean => t.join("").includes("choose a provider");/** Rows that carry painted content — the dialog's actual footprint. */const painted = (text: string[]): string[] => text.filter((l) => l.trim() !== "");/**@@ -183,21 +230,21 @@ describe("the dialog", () => {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 `▶`.+ // keys drove. One list, one `▶` — on the landing screen and inside a list alike.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" })],- })}+ source={fakeSource({ roster, served: [model({ id: "a" }), model({ id: "b" })] })}onDone={() => {}}/>);try {expect(joined(d.text).split("▶").length - 1).toBe(1);+ await d.press(["a"]);+ await d.until(listPainted);+ expect(joined(d.recapture().text).split("▶").length - 1).toBe(1);} finally {d.destroy();}@@ -210,6 +257,7 @@ describe("the dialog", () => {const d = await draw(<ModelPickersource={fakeSource({+ roster: [provider({ hasDiscovery: false })],served: [model({ id: "a", contextLength: 1_000_000, context: "1M" }),model({ id: "b", contextLength: 8_000, context: "8K" }),@@ -219,7 +267,9 @@ describe("the dialog", () => {/>);try {- const rows = d.text.filter((l) => /\ba\b|\bb\b/.test(l));+ await d.press(["a"]);+ await d.until(listPainted);+ const rows = d.recapture().text.filter((l) => /\ba\b|\bb\b/.test(l));expect(rows.length).toBeGreaterThan(0);for (const row of rows) expect(row).not.toMatch(/[█▓▒░╌]/);} finally {@@ -234,21 +284,39 @@ describe("the dialog", () => {] 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: [] });+ expect({ width, over: d.text.filter((l) => l.length > width) }).toEqual({+ width,+ over: [],+ });+ await d.press(["a"]);+ await d.until(listPainted);+ expect({+ width,+ over: d.recapture().text.filter((l) => l.length > width),+ }).toEqual({ width, over: [] });} finally {d.destroy();}}});- test("the key hints are present and unclipped at 80×24", async () => {- const d = await draw(<ModelPicker source={fakeSource()} onDone={() => {}} />);+ test("the key hints are present and unclipped at 80×24, in BOTH lists", async () => {+ const d = await draw(+ <ModelPicker+ source={fakeSource({ roster: [provider({ hasDiscovery: false })] })}+ 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);+ const footer = (): string => painted(d.recapture().text).at(-2) ?? "";+ for (const hint of ["move", "open", "all models", "custom", "quit"]) {+ expect(footer()).toContain(hint);+ }+ await d.press(["a"]);+ await d.until(listPainted);+ for (const hint of ["move", "select", "filter", "custom", "providers"]) {+ expect(footer()).toContain(hint);}} finally {d.destroy();@@ -256,128 +324,157 @@ describe("the dialog", () => {});});-// ── one flat list, provider as a COLUMN ──────────────────────────────────────────+// ── the landing screen, and everything it does NOT do ────────────────────────────-describe("the flat cross-provider list", () => {+describe("the picker opens on the PROVIDER list", () => {const roster = [- provider({ value: "openrouter", label: "OpenRouter", shortcut: "or@", hasDiscovery: false }),- provider({ value: "kimi-coding", label: "Kimi Coding", shortcut: "kc@", hasDiscovery: false }),+ provider({+ value: "openrouter",+ label: "OpenRouter",+ shortcut: "or@",+ envVar: "OPENROUTER_API_KEY",+ hasDiscovery: false,+ }),+ provider({ value: "kimi-coding", label: "Kimi Coding", shortcut: "kc@", hasDiscovery: true }),];- test("merges every credentialled provider and NAMES the provider on each row", async () => {+ test("lands on providers — not on a 574-row list of every model", async () => {+ // The owner, verbatim: "we should not show the full list of models, we should+ // show a list of providers by default and only when we go inside we load and+ // resolve all models".const d = await draw(<ModelPicker- source={fakeSource({- roster,- byProvider: {- openrouter: [model({ id: "glm-5.3-flash" })],- "kimi-coding": [model({ id: "kimi-k3" })],- },- })}+ source={fakeSource({ roster, byProvider: { openrouter: [model({ id: "glm-5.3" })] } })}onDone={() => {}}/>);try {const all = joined(d.text);- expect(all).toContain("glm-5.3-flash");- expect(all).toContain("kimi-k3");- // THE COLUMN IS A NAME, NOT A SHORTCUT. It printed `or@` / `kc@` and the- // owner's question on a live run was "what is 'or' means" — a routing- // shortcut only reads as information to someone who already knows it.+ expect(all).toContain("choose a provider");expect(all).toContain("OpenRouter");- expect(all).toContain("Kimi Coding");+ // Not one model id, because nothing has been asked for one.+ expect(all).not.toContain("glm-5.3");} finally {d.destroy();}});- test("a provider with no credential contributes NO rows, and the count says so", async () => {+ test("FETCHES NOTHING before the user asks — no catalog, no roster, no descriptions", async () => {+ // "why we prefetching? we should not, as we show on demand". The build this+ // replaces warmed the cloud catalog AND fanned out one roster request per+ // credentialled provider, on a screen that could show neither.+ const source = fakeSource({ roster });+ const d = await draw(<ModelPicker source={source} onDone={() => {}} />);+ try {+ expect(source.calls).toEqual({ catalog: 0, descriptions: 0, discover: [] });+ // …and the screen does not claim to be doing any of it.+ expect(joined(d.text)).not.toContain("cloud catalog");+ expect(joined(d.text)).not.toContain("live rosters");+ } finally {+ d.destroy();+ }+ });++ test("a provider with NO credential is not on the list, and the omission is counted", async () => {+ // "we should not show unsetted providers, just active". Not deleted — counted,+ // with the key that brings them back, because an unexplained absence is the+ // defect class this feature exists to remove.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" })],- },- })}+ source={fakeSource({ roster, ready: { openrouter: true, "kimi-coding": false } })}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");+ const before = joined(d.text);+ expect(before).toContain("OpenRouter");+ expect(before).not.toContain("Kimi Coding");+ expect(before).not.toContain("MOONSHOT_API_KEY");+ expect(before).toContain("+1 more need a key");++ await d.press(["k"]);+ const after = joined(d.recapture().text);+ expect(after).toContain("Kimi Coding");+ // Revealed WITH the exact variable to inspect, which is the whole value of+ // showing them at all.+ expect(after).toContain("MOONSHOT_API_KEY");} finally {d.destroy();}});- test("A LIVE ROSTER IS MERGED INTO THE FLAT LIST — the `gemini` bug, as an assertion", async () => {- // The owner filtered `gemini` on a live run and got eleven rows, every one of- // them `or@`, while Antigravity was serving gemini models on a FLAT-RATE- // subscription — invisible, because the flat list was the cloud catalog alone- // and Antigravity has no catalog entries at all. The subscription route is the- // one most worth finding, so its absence was the worst possible absence.- const withDiscovery = [- provider({ value: "openrouter", label: "OpenRouter", shortcut: "or@", hasDiscovery: false }),- provider({- value: "antigravity",- label: "Antigravity",- shortcut: "ag@",- billing: "sub",- envVar: "",- hasDiscovery: true,- }),- ];+ test("NO model count is printed for a provider nothing has counted yet", async () => {+ // "we could not show number of models for some of them". A `0`, a `—` or a guess+ // in that column is a claim; silence is not.+ const d = await draw(<ModelPicker source={fakeSource({ roster })} onDone={() => {}} />);+ try {+ const row = d.text.find((l) => l.includes("OpenRouter")) ?? "";+ expect(row).toContain("OpenRouter");+ expect(row).not.toMatch(/\bmodels?\b/);+ expect(row).not.toContain("—");+ } finally {+ d.destroy();+ }+ });++ test("Escape on the landing screen CANCELS by returning null — never `process.exit`", async () => {+ let got: string | null | undefined;const d = await draw(<ModelPicker- source={fakeSource({- roster: withDiscovery,- byProvider: {- openrouter: [model({ id: "gemini-3.8-flash" })],- // No catalog entries whatsoever — the real Antigravity's situation.- antigravity: [],- },- liveRosters: {- antigravity: {- kind: "rows",- rows: [model({ id: "gemini-3.8-flash-tiered", context: "1M" })],- },- },- })}- onDone={() => {}}- />,- 145,- 45+ source={fakeSource({ roster })}+ onDone={(spec) => {+ got = spec;+ }}+ />);try {- await d.press(["g", "e", "m", "i", "n", "i"]);+ await d.press(["ESCAPE"]);+ expect(got).toBeNull();+ } finally {+ d.destroy();+ }+ });+});++// ── entering a provider is what fetches it ───────────────────────────────────────++describe("entering a provider loads THAT provider, on demand", () => {+ const roster = [+ provider({ value: "openrouter", label: "OpenRouter", shortcut: "or@", hasDiscovery: false }),+ provider({ value: "devin", label: "Devin", shortcut: "dv@", hasDiscovery: true }),+ ];++ test("`⏎` asks the provider under the cursor, and ONLY that one", async () => {+ const source = fakeSource({+ roster,+ byProvider: { openrouter: [model({ id: "glm-5.3" })], devin: [] },+ outcomes: {+ devin: { kind: "rows", rows: [model({ id: "devin-1" })], servedCount: 1, chatCount: 1 },+ },+ });+ const d = await draw(<ModelPicker source={source} onDone={() => {}} />);+ try {+ await d.press(["ARROW_DOWN"]);+ await d.press(["RETURN"]);+ await d.until(listPainted);+ expect(source.calls.discover).toEqual(["devin"]);const all = joined(d.recapture().text);- // BOTH routes, from two different sources, in one filtered list.- expect(all).toContain("gemini-3.8-flash");- expect(all).toContain("gemini-3.8-flash-tiered");- expect(all).toContain("OpenRouter");- expect(all).toContain("Antigravity");+ expect(all).toContain("Devin");+ expect(all).toContain("devin-1");} finally {d.destroy();}});- test("one model on two providers is TWO rows, and the title counts both honestly", async () => {- // The owner's rule for the flat list, and the count that goes with it: the- // rows are ROUTES, so labelling their number "models" would be off by exactly- // the amount that makes the list useful.+ test("inside one provider a model appears exactly ONCE", async () => {+ // The owner's rule: "if we enter to provider catalog, not all models — then the+ // model will be just one".const d = await draw(<ModelPickersource={fakeSource({- roster,+ roster: [provider({ value: "openrouter", label: "OpenRouter", hasDiscovery: false })],byProvider: {- openrouter: [model({ id: "gpt-6-astra" })],- "kimi-coding": [model({ id: "gpt-6-astra" })],+ openrouter: [model({ id: "gpt-6-astra" }), model({ id: "gpt-6-astra" })],},})}onDone={() => {}}@@ -386,46 +483,67 @@ describe("the flat cross-provider list", () => {45);try {- const all = joined(d.text);- expect(all).toContain("1 models · 2 routes");- // Two rows, one per provider, each naming its own provider.- expect(all).toContain("OpenRouter");- expect(all).toContain("Kimi Coding");+ await d.press(["RETURN"]);+ await d.until(listPainted);+ const rows = d.recapture().text.filter((l) => l.includes("gpt-6-astra"));+ // One list row, plus the detail line under the list that prints the spec.+ expect(rows.filter((l) => l.includes("OpenRouter")).length).toBe(1);} finally {d.destroy();}});- test("a provider whose roster FAILS is counted, not silently absent", async () => {- // The aggregate shape: once the list queries every ready provider at once, a- // banner per failure would push the list off the screen and a banner for the- // first one would speak for the rest.- const withDiscovery = [- provider({ value: "openrouter", label: "OpenRouter", shortcut: "or@", hasDiscovery: false }),- provider({ value: "devin", label: "Devin", shortcut: "dv@", hasDiscovery: true }),- ];- const failures: string[] = [];+ test("`esc` comes back to the provider list rather than quitting", async () => {+ let got: string | null | undefined = undefined;+ const d = await draw(+ <ModelPicker+ source={fakeSource({ roster })}+ onDone={(spec) => {+ got = spec;+ }}+ />+ );+ try {+ await d.press(["RETURN"]);+ await d.until(listPainted);+ await d.press(["ESCAPE"]);+ // A LONE `\x1B` IS AMBIGUOUS UNTIL THE NEXT BYTE OR A TIMEOUT: the parser has+ // to wait to see whether it is the head of `\x1B[B`. One more render pass+ // after that timeout is what makes a bare Escape observable in a test — a+ // real keyboard gets the same delay and nobody notices.+ await d.press([]);+ await d.until(providerListPainted);+ expect(joined(d.recapture().text)).toContain("choose a provider");+ expect(got).toBeUndefined();+ } finally {+ d.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(<ModelPickersource={fakeSource({- roster: withDiscovery,- byProvider: { openrouter: [model({ id: "glm-5.3-flash" })], devin: [] },- liveRosters: {- devin: {- kind: "failed",- failure: { kind: "unreachable", provider: "devin", detail: "timeout" },- notice: ["\n⚠ Devin could not list its models: timeout\n"],- },- },+ roster: [provider({ value: "openrouter", label: "OpenRouter", hasDiscovery: false })],+ byProvider: { openrouter: [model({ id: "gpt-6" })] },})}- onDone={() => {}}- onDiscoveryFailure={(p) => failures.push(p)}+ onDone={(spec) => {+ got = spec;+ }}/>);try {- expect(joined(d.recapture().text)).toContain("could not be listed");- // The full diagnostic still reaches the ONE post-teardown stderr write.- expect(failures).toEqual(["devin"]);+ await d.press(["RETURN"]);+ await d.until(listPainted);+ 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();}@@ -435,16 +553,17 @@ describe("the flat cross-provider list", () => {const d = await draw(<ModelPickersource={fakeSource({- roster,+ roster: [provider({ value: "openrouter", label: "OpenRouter", hasDiscovery: false })],byProvider: {- openrouter: [model({ id: "glm-5.3-flash" })],- "kimi-coding": [model({ id: "kimi-k3" })],+ openrouter: [model({ id: "glm-5.3-flash" }), model({ id: "kimi-k3" })],},})}onDone={() => {}}/>);try {+ await d.press(["RETURN"]);+ await d.until(listPainted);await d.press(["g", "l", "m"]);const all = joined(d.recapture().text);expect(all).toContain("glm-5.3-flash");@@ -454,92 +573,189 @@ describe("the flat cross-provider list", () => {}});- 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={() => {}}- />- );+ test("`/` makes the letter commands typeable — `codex` is a real model name", async () => {+ // The one collision filter-first creates: `c` opens the custom-spec dialog, so+ // the first keystroke of `codex` would navigate instead of filter. `/` is the+ // escape hatch, and without a test it is the kind of thing that quietly stops+ // working.+ const source = (): PickerDataSource =>+ fakeSource({+ roster: [provider({ value: "openrouter", label: "OpenRouter", hasDiscovery: false })],+ byProvider: { openrouter: [model({ id: "codex-2" }), model({ id: "kimi-k3" })] },+ });+ const d = await draw(<ModelPicker source={source()} onDone={() => {}} />);try {- // Bare `p` NAVIGATES — that is the collision, asserted so the escape hatch has+ await d.press(["RETURN"]);+ await d.until(listPainted);+ // Bare `c` 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");+ await d.press(["c"]);+ expect(joined(d.recapture().text)).toContain("type a model spec");d.destroy();} finally {/* destroyed above; the second half needs a fresh tree */}- const e = await draw(+ const e = await draw(<ModelPicker source={source()} onDone={() => {}} />);+ try {+ await e.press(["RETURN"]);+ await e.until(listPainted);+ await e.press(["/"]);+ await e.press(["c"]);+ await e.press(["o"]);+ const all = joined(e.recapture().text);+ expect(all).toContain("codex-2");+ expect(all).not.toContain("kimi-k3");+ } finally {+ e.destroy();+ }+ });+});++// ── the cross-provider list, which is no longer the default ──────────────────────++describe("`a` opens the 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("it is ONE cached catalog fetch, not a fan-out across providers", async () => {+ const source = fakeSource({+ roster,+ byProvider: {+ openrouter: [model({ id: "glm-5.3-flash" })],+ "kimi-coding": [model({ id: "kimi-k3" })],+ },+ });+ const d = await draw(<ModelPicker source={source} onDone={() => {}} />);+ try {+ await d.press(["a"]);+ await d.until(listPainted);+ const all = joined(d.recapture().text);+ expect(all).toContain("all models");+ expect(all).toContain("glm-5.3-flash");+ expect(all).toContain("kimi-k3");+ // ONE warm. And not a single roster request: no provider was opened.+ expect(source.calls.catalog).toBe(1);+ expect(source.calls.discover).toEqual([]);+ } finally {+ d.destroy();+ }+ });++ test("one model on two providers is TWO rows, and the title counts both honestly", async () => {+ // The owner's rule for this list, and the count that goes with it: the rows are+ // ROUTES, so labelling their number "models" would be off by exactly the amount+ // that makes the list useful.+ const d = await draw(<ModelPickersource={fakeSource({roster,byProvider: {- openrouter: [model({ id: "phi3" }), model({ id: "kimi-k3" })],- "kimi-coding": [],+ openrouter: [model({ id: "gpt-6-astra" })],+ "kimi-coding": [model({ id: "gpt-6-astra" })],},})}onDone={() => {}}- />+ />,+ 145,+ 45);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");+ await d.press(["a"]);+ await d.until(listPainted);+ const all = joined(d.recapture().text);+ expect(all).toContain("1 models · 2 routes");+ expect(all).toContain("OpenRouter");+ expect(all).toContain("Kimi Coding");} finally {- e.destroy();+ d.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;+ test("a provider with no credential contributes NO rows, and the count says so", async () => {const d = await draw(<ModelPicker- source={fakeSource({ roster, byProvider: { openrouter: [model({ id: "gpt-6" })] } })}- onDone={(spec) => {- got = spec;- }}+ 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 {- 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");+ await d.press(["a"]);+ await d.until(listPainted);+ const all = joined(d.recapture().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("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;- }}- />- );+ test("A ROSTER ALREADY OPENED IS MERGED IN — and one not opened costs no request", async () => {+ // The `gemini` report — "why i search gemini i see only open router models, no+ // models from antigravity and devin and subscriptions" — was first answered by+ // fetching every roster at startup, which the owner then rejected as+ // prefetching. This is the answer that survives both: a roster fetched because+ // he OPENED that provider improves this list for free, and a provider he never+ // opened is simply not represented here.+ const withDiscovery = [+ provider({ value: "openrouter", label: "OpenRouter", shortcut: "or@", hasDiscovery: false }),+ provider({+ value: "antigravity",+ label: "Antigravity",+ shortcut: "ag@",+ billing: "sub",+ envVar: "",+ hasDiscovery: true,+ }),+ ];+ const source = fakeSource({+ roster: withDiscovery,+ byProvider: {+ openrouter: [model({ id: "gemini-3.8-flash" })],+ // No catalog entries whatsoever — the real Antigravity's situation.+ antigravity: [],+ },+ outcomes: {+ antigravity: {+ kind: "rows",+ rows: [model({ id: "gemini-3.8-flash-tiered", context: "1M" })],+ servedCount: 1,+ chatCount: 1,+ },+ },+ });+ const d = await draw(<ModelPicker source={source} onDone={() => {}} />, 145, 45);try {+ // Open Antigravity, look at it, come back out, then ask for all models.+ await d.press(["ARROW_DOWN"]);+ await d.press(["RETURN"]);+ await d.until(listPainted);await d.press(["ESCAPE"]);- expect(got).toBeNull();+ // The bare-Escape flush — see the `esc comes back` test. Without it the+ // NEXT key is read as `\x1B` + `a`, which is alt-a and not two keystrokes.+ await d.press([]);+ await d.until(providerListPainted);+ await d.press(["a"]);+ await d.until(listPainted);+ await d.press(["g", "e", "m", "i", "n", "i"]);+ const all = joined(d.recapture().text);+ // BOTH routes, from two different sources, in one filtered list.+ expect(all).toContain("gemini-3.8-flash");+ expect(all).toContain("gemini-3.8-flash-tiered");+ expect(all).toContain("OpenRouter");+ expect(all).toContain("Antigravity");+ // Exactly one roster request, and it was the one he opened.+ expect(source.calls.discover).toEqual(["antigravity"]);} finally {d.destroy();}@@ -566,20 +782,22 @@ describe("a fallback list says it is a fallback — and that it may not work", (fallbackRows: [model(), model({ id: "kimi-k2.6" })],};- /** Reach the scoped view: `p` opens the provider dialog, Enter scopes to row one. */+ /**+ * Reach the scoped view: Enter on the first provider.+ *+ * ONE PRESS, and the failure it renders is now a failure the user ASKED for —+ * which is the round-two improvement that came free with on-demand loading. The+ * red panel, the `catalog` rows and `r retry` are unchanged; only the moment+ * they appear is.+ */async function scoped(outcome: PickerDiscoveryOutcome, width = 80, height = 24): Promise<Drawn> {const d = await draw(<ModelPicker source={fakeSource({ outcome })} onDone={() => {}} />,width,height);- // 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));+ await d.until(listPainted);return { ...d, ...d.recapture() };}@@ -680,61 +898,47 @@ describe("a fallback list says it is a fallback — and that it may not work", (});});-// ── the provider dialog, which replaced the rail ─────────────────────────────────+// ── what the screen says while it is waiting ─────────────────────────────────────-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,- }),- ];+describe("the loading states", () => {+ test("startup names the ONE thing it is doing, and claims no other", async () => {+ // The screen the owner rejected said `cloud catalog fetching…` and `live rosters+ // 0/11 providers` before he had asked for either. Startup now probes credentials+ // and nothing else, and the screen says so.const d = await draw(- <ModelPicker- source={fakeSource({ roster, ready: { "opencode-zen-go": false } })}- onDone={() => {}}- />+ <ModelPicker source={fakeSource({ hang: true })} onDone={() => {}} />,+ 80,+ 24,+ 0);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");+ const all = joined(d.text);+ expect(all).toContain("credentials");+ expect(all).toContain("checking");+ expect(all).not.toContain("cloud catalog");+ expect(all).not.toContain("live rosters");} finally {d.destroy();}});-});--// ── the loading dialog ───────────────────────────────────────────────────────────-describe("the loading dialog", () => {- test("names what it is waiting for rather than spinning", async () => {+ test("a provider still being listed says which provider, and for how long", async () => {+ // The per-provider in-flight state, which is now reachable because the fetch+ // happens in response to a keystroke.const d = await draw(- <ModelPicker source={fakeSource({ hang: true })} onDone={() => {}} />,- 80,- 24,- 0+ <ModelPicker+ source={{+ ...fakeSource({ roster: [provider({ label: "Kimi / Moonshot" })] }),+ discoverRoster: () => new Promise<never>(() => {}),+ }}+ onDone={() => {}}+ />);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");+ await d.press(["RETURN"]);+ const all = joined(d.recapture().text);+ expect(all).toContain("Kimi / Moonshot");+ expect(all).toContain("deadline");} finally {d.destroy();}diff --git a/packages/cli/src/picker/ModelPicker.tsx b/packages/cli/src/picker/ModelPicker.tsxindex a68cbdb4..f3304503 100644--- a/packages/cli/src/picker/ModelPicker.tsx+++ b/packages/cli/src/picker/ModelPicker.tsx@@ -26,18 +26,31 @@* 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.+ * 2. **One list at a time, one cursor in it.** 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".* 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.*+ * THE DEFAULT SCREEN IS THE PROVIDER LIST, AND NOTHING IS FETCHED BEFORE IT. An+ * intermediate build landed on a flat 574-row cross-provider list and warmed the+ * cloud catalog AND every credentialled provider's live roster to fill it — a+ * `cloud catalog fetching… / live rosters 0/11 providers` screen the user had to+ * watch before he could do anything. The owner's three corrections, verbatim:+ * *"why we prefetching? we should not, as we show on demand"*, *"we should not+ * show the full list of models, we should show a list of providers by default and+ * only when we go inside we load and resolve all models"*, and *"we should not+ * show unsetted providers, just active"*. So:+ *+ * · Startup does ONE thing: probe credentials, streaming each answer into the+ * provider list as it settles. No catalog, no roster, no description index.+ * · `⏎` on a provider fetches THAT provider's roster and shows it. The failure+ * UX improves for free — a red panel now answers a request the user made.+ * · `a` opens the cross-provider list, built from the ONE cached catalog fetch,+ * enriched by whatever rosters he has already opened and by nothing else.+ ** 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@@ -79,9 +92,8 @@ import {toPickerRow,usePickerModels,} from "./hooks/usePickerModels.js";-import { usePickerProviders } from "./hooks/usePickerProviders.js";-import { usePreloadedRosters } from "./hooks/usePreloadedRosters.js";-import { useProviderDiscovery } from "./hooks/useProviderDiscovery.js";+import { type ProviderState, usePickerProviders } from "./hooks/usePickerProviders.js";+import { rowsFromOutcomes, useProviderDiscovery } from "./hooks/useProviderDiscovery.js";import {deriveDialogLayout,deriveRowLayout,@@ -105,11 +117,15 @@ import { ColumnHeader, HintRow, ModelRow, ProviderRow } from "./rows.js";* 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.+ *+ * AND THERE IS NO `live rosters` TASK ANY MORE. It had the most defensible meter in+ * the file — a real `done/total` over the providers about to be asked — and it was+ * still wrong, because the work it measured was work nobody had asked for. A+ * truthful bar for an unwanted fan-out is a truthful answer to the wrong question.*/export function buildLoadTasks(input: {creds: { done: number; total: number } | null;catalog: boolean;- rosters?: { done: number; total: number } | null;roster: { displayName: string; shape: DiscoveryShape; elapsed: number } | null;}): LoadTask[] {const tasks: LoadTask[] = [];@@ -123,18 +139,6 @@ export function buildLoadTasks(input: {});}if (input.catalog) tasks.push({ id: "catalog", label: "cloud catalog", value: "fetching…" });- if (input.rosters) {- // A SECOND REAL DENOMINATOR. The providers that will be asked are known as- // soon as their credential probes settle, so `done/total` is work done over- // work total — the same thing that earns the credential sweep its meter.- const { done, total } = input.rosters;- tasks.push({- id: "rosters",- label: "live rosters",- pct: total > 0 ? (100 * done) / total : 0,- value: `${done}/${total} providers`,- });- }if (input.roster) {const { displayName, shape, elapsed } = input.roster;const secs = `${(elapsed / 1000).toFixed(1)}s`;@@ -163,50 +167,116 @@ export interface ModelPickerProps {/*** Which dialog is on screen. ONE at a time, and one keyboard owner each — there is* never a second cursor to disambiguate.+ *+ * `providers` IS THE LANDING VIEW. `models` is reached by entering a provider+ * (`scope` set) or by asking for the cross-provider list (`scope` null); `esc`+ * from either comes back here, and `esc` HERE is what cancels the picker.*/type View = "models" | "providers" | "custom";export function ModelPicker({ source, onDone, onDiscoveryFailure }: ModelPickerProps): ReactNode {const { width, height } = useTerminalDimensions();+ // THE ONLY WORK STARTUP DOES. Every other loader below is gated on a view the+ // user has actually opened.const providers = usePickerProviders(source);- // EVERY ready provider's LIVE roster, concurrently, merged as each lands — the- // fix for "why i search gemini i see only open router models". See the hook.- const rosters = usePreloadedRosters(- source,- providers.roster,- providers.readySet,- onDiscoveryFailure- );- const catalog = usePickerModels(- source,- providers.roster,- providers.readySet,- rosters.rowsByProvider- );- const descriptions = useModelDescriptions(source);- const [view, setView] = useState<View>("models");+ const [view, setView] = useState<View>("providers");const [filter, setFilter] = useState("");/**- * `/` was pressed: every printable key types, INCLUDING `p`, `c` and `r`.+ * `/` was pressed: every printable key types, INCLUDING `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.+ * It exists for exactly one case, and that case is real: a model id beginning+ * with one of the two letter commands — `codex`, `r1` — would navigate on its+ * first keystroke instead of filtering. `/` 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 [cursor, setCursor] = useState(0);const [providerCursor, setProviderCursor] = useState(0);- /** `null` = the flat cross-provider list; a name = scoped to that provider. */+ /**+ * Are the providers with NO credential on screen?+ *+ * Off by default, on the owner's instruction: *"we should not show unsetted+ * providers, just active"*. They are not deleted — one summary row says how many+ * were left out and which key brings them back — because an unexplained absence+ * is the defect class this whole feature is about. A fact behind one keystroke is+ * reachable; fourteen `○ needs SOMETHING_API_KEY` rows in front of the four the+ * user can actually use are not.+ */+ const [revealKeyless, setRevealKeyless] = useState(false);+ /** `null` = the cross-provider list; a name = scoped to that provider. */const [scope, setScope] = useState<string | null>(null);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);+ /**+ * DISCOVERY RUNS ONLY WHILE A PROVIDER'S OWN LIST IS OPEN — the `null` when the+ * view is not `models` is the on-demand rule, in one argument. Outcomes already+ * settled stay in `seen`, so coming back to a provider costs nothing and the+ * all-models view can reuse what has been fetched.+ */+ const discovery = useProviderDiscovery(+ source,+ view === "models" ? scope : null,+ hasDiscovery,+ onDiscoveryFailure+ );+ /** Rosters the user has already opened. No fetch — see `rowsFromOutcomes`. */+ const liveRows = useMemo(() => rowsFromOutcomes(discovery.seen), [discovery.seen]);++ /**+ * THE CATALOG IS FETCHED FOR THE VIEWS THAT READ IT, AND FOR NO OTHER.+ *+ * The cross-provider list is built from it, and so is a provider that does not+ * list its own roster. A discovery provider needs nothing from it — its rows come+ * from its own endpoint — unless discovery comes back `unsupported`, at which+ * point the catalog IS the list and the warm starts then.+ */+ const wantCatalog =+ view === "models" &&+ (scope === null || !hasDiscovery || discovery.outcome?.kind === "unsupported");+ const catalog = usePickerModels(+ source,+ providers.roster,+ providers.readySet,+ liveRows,+ wantCatalog+ );+ const descriptions = useModelDescriptions(source, view === "models");++ /**+ * WHICH PROVIDERS ARE ON SCREEN, and the one number that explains the rest.+ *+ * Active first and always; the keyless ones are appended only when `k` has asked+ * for them, so the cursor's index into this array stays valid across the toggle+ * for every row that was already visible.+ */+ const keyless = providers.missing;+ const providerRows: ProviderState[] = revealKeyless+ ? [...providers.ready, ...keyless]+ : providers.ready;++ /**+ * A MODEL COUNT ONLY WHERE ONE IS ACTUALLY KNOWN — the owner's rule: *"we could+ * not show number of models for some of them"*.+ *+ * Two sources, both already in hand and neither of them a fetch this map causes.+ * A roster the user opened is the truest answer for that provider, so it wins;+ * the catalog answers for the rest, but ONLY once the user has asked for a view+ * that warmed it. A provider in neither set gets `null`, which `ProviderRow`+ * prints as nothing at all.+ */+ const counts = useMemo((): ReadonlyMap<string, number> => {+ const known = new Map<string, number>();+ for (const [name, rows] of liveRows) known.set(name, new Set(rows.map((m) => m.id)).size);+ if (catalog.phase === "ready") {+ for (const [name, n] of catalog.counts) if (!known.has(name)) known.set(name, n);+ }+ return known;+ }, [liveRows, catalog.counts, catalog.phase]);// ── which list is on screen, and where it came from ──────────────────────────//@@ -285,15 +355,16 @@ export function ModelPicker({ source, onDone, onDiscoveryFailure }: ModelPickerP}, [list.rows, filter, labels]);// ── in-flight affordances ───────────────────────────────────────────────────- const busy = providers.probing || catalog.phase !== "ready" || discovery.busy || rosters.busy;+ //+ // `catalog.phase === "loading"`, NEVER `!== "ready"`. The third state is `idle`,+ // which is what the catalog is on the provider list — not fetching, not fetched,+ // and not wanted. Drawing a `cloud catalog fetching…` row for it would put the+ // owner's own complaint back on the landing screen with no request behind it.+ const busy = providers.probing || catalog.phase === "loading" || discovery.busy;const frame = useAnimationFrame(busy);const tasks = buildLoadTasks({creds: providers.probing ? { done: providers.done, total: providers.total } : null,- catalog: catalog.phase !== "ready",- // The live-roster sweep has a REAL denominator — the set of ready discovery- // providers is known the moment their probes settle — so it gets the same- // determinate meter the credential sweep does, and for the same reason.- rosters: rosters.busy ? { done: rosters.done, total: rosters.total } : null,+ catalog: catalog.phase === "loading",roster:discovery.busy && scope !== null? {@@ -333,6 +404,11 @@ export function ModelPicker({ source, onDone, onDiscoveryFailure }: ModelPickerPuseEffect(() => {setCursor((c) => Math.max(0, Math.min(c, Math.max(0, shown.length - 1))));}, [shown.length]);+ // The SAME hazard on the provider list, from two directions: `k` folds fourteen+ // rows away under the cursor, and the list GROWS as probes settle under it.+ useEffect(() => {+ setProviderCursor((c) => Math.max(0, Math.min(c, Math.max(0, providerRows.length - 1))));+ }, [providerRows.length]);const top = scrollWindow(cursor, shown.length, layout.listRows);const window = shown.slice(top, top + layout.listRows);@@ -348,10 +424,14 @@ export function ModelPicker({ source, onDone, onDiscoveryFailure }: ModelPickerP// 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.+ // cannot express (`esc`, `enter`, the arrows) plus TWO letters, and those two 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 `codex` must get `codex`+ // and not the custom-spec dialog.+ //+ // THE PROVIDER LIST TAKES NO FILTER AND SO NEEDS NO ESCAPE HATCH: its letters+ // (`a`, `k`, `c`) are always commands, which is affordable because that list is+ // short and named, never hundreds of rows a user needs to narrow.useKeyboard((key) => {const name = key.name;if (key.ctrl && name === "c") {@@ -378,24 +458,56 @@ export function ModelPicker({ source, onDone, onDiscoveryFailure }: ModelPickerP}if (view === "providers") {- if (name === "escape" || key.raw === "p") {- setView("models");+ // THE LANDING VIEW OWNS CANCEL. `esc` goes one step back everywhere else in+ // this picker; here there is no step back, so it is what returns `null`.+ if (name === "escape") {+ onDone(null);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)));+ setProviderCursor((c) => Math.max(0, Math.min(providerRows.length - 1, c + d)));+ return;+ }+ if (name === "pageup" || name === "pagedown") {+ const d = (name === "pageup" ? -1 : 1) * layout.listRows;+ setProviderCursor((c) => Math.max(0, Math.min(providerRows.length - 1, c + d)));+ return;+ }+ if (name === "home") {+ setProviderCursor(0);+ return;+ }+ if (name === "end") {+ setProviderCursor(Math.max(0, providerRows.length - 1));return;}if (name === "return" || name === "enter") {- const chosen = providers.rows[providerCursor];+ // ENTERING A PROVIDER IS WHAT FETCHES ITS ROSTER. Nothing before this+ // keystroke asked that endpoint anything.+ const chosen = providerRows[providerCursor];if (chosen) {setScope(chosen.value);setFilter("");+ setTyping(false);setCursor(0);+ setView("models");}+ return;+ }+ if (key.raw === "a") {+ setScope(null);+ setFilter("");+ setTyping(false);+ setCursor(0);setView("models");+ return;+ }+ if (key.raw === "k") {+ setRevealKeyless((v) => !v);+ return;}+ if (key.raw === "c") setView("custom");return;}@@ -406,12 +518,11 @@ export function ModelPicker({ source, onDone, onDiscoveryFailure }: ModelPickerPsetCursor(0);return;}- if (scope !== null) {- setScope(null);- setCursor(0);- return;- }- onDone(null);+ // ONE WAY BACK, AND IT IS THE SAME ONE FROM BOTH MODEL LISTS. A scoped list+ // and the cross-provider list are both something the user OPENED from the+ // provider list, so `esc` returns him to it rather than quitting — quitting+ // is `esc` there, or Ctrl+C anywhere.+ setView("providers");return;}if (name === "up" || name === "down") {@@ -442,16 +553,6 @@ export function ModelPicker({ source, onDone, onDiscoveryFailure }: ModelPickerPreturn;}const commandsLive = filter === "" && !typing;- if (commandsLive && key.raw === "p") {- setProviderCursor(- Math.max(- 0,- providers.rows.findIndex((r) => r.value === scope)- )- );- setView("providers");- return;- }if (commandsLive && key.raw === "c") {setView("custom");return;@@ -462,7 +563,7 @@ export function ModelPicker({ source, onDone, onDiscoveryFailure }: ModelPickerP}if (key.raw === "/") {// Not inserted: `/` FOCUSES the filter, which here means "stop treating- // p / c / r as commands". See `typing`.+ // c / r as commands". See `typing`.setTyping(true);return;}@@ -517,66 +618,132 @@ export function ModelPicker({ source, onDone, onDiscoveryFailure }: ModelPickerP}if (view === "providers") {- const readyCount = providers.ready.length;- // One row taller than the model list: this dialog spends no column header and- // no description block, but it DOES carry the same provider detail line, which- // is the answer to "we need add more details about provider".- const providerRows = layout.listRows + 2;- const providerTop = scrollWindow(providerCursor, providers.rows.length, providerRows);- const providerWindow = providers.rows.slice(providerTop, providerTop + providerRows);- const here = providers.rows[providerCursor] ?? null;+ const settled = !providers.probing;+ // One row taller than the model list's list: this dialog spends no column+ // header and no description block, and two of the three rows it spends+ // instead — the omitted-provider summary and the credential sweep — are+ // rendered blank rather than dropped, so the list does not shift under the+ // cursor when a sweep finishes or `k` is pressed.+ const windowRows = layout.listRows;+ const providerTop = scrollWindow(providerCursor, providerRows.length, windowRows);+ const providerWindow = providerRows.slice(providerTop, providerTop + windowRows);+ const here = providerRows[providerCursor] ?? null;return (<Centred width={width} height={height}><Dialog- key="providers"- title="providers"- status={`${readyCount} of ${providers.total} have credentials`}+ key={`providers-${providerRows.length === 0 ? "empty" : "list"}`}+ title="choose a provider"+ status={+ settled+ ? `${providers.ready.length} of ${providers.total} have credentials`+ : `${providers.ready.length} ready · ${providers.done}/${providers.total} checked`+ }width={layout.width}marginLeft={0}>- {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}- />- ))}- {/* 31 providers do not fit in one screen, and a list that silently stops- is the same unexplained absence this feature exists to remove. */}+ {/* TWO ROWS WHEN IT IS EMPTY, because `EmptyState` with a hint IS two+ rows and a one-row box would overprint the second onto the row+ below it. */}+ <box+ flexDirection="column"+ height={Math.min(+ windowRows,+ Math.max(providerWindow.length === 0 ? 2 : 1, providerWindow.length)+ )}+ flexShrink={0}+ overflow="hidden"+ >+ {providerWindow.length === 0 ? (+ <EmptyState+ label={+ settled+ ? `no credential for any of the ${providers.total} providers`+ : "checking which providers you have credentials for…"+ }+ {...(settled ? { hint: "k shows what each one needs" } : {})}+ />+ ) : (+ providerWindow.map((r) => (+ <ProviderRow+ key={r.value}+ label={r.label}+ shortcut={r.shortcut}+ readiness={r.readiness}+ billing={r.billing}+ count={counts.get(r.value) ?? null}+ hasDiscovery={r.hasDiscovery}+ note={r.envVar === "" ? "needs sign-in" : `needs ${r.envVar}`}+ cursor={r.value === here?.value}+ inner={layout.inner}+ />+ ))+ )}+ </box>+ {/* A list that silently stops is the same unexplained absence this+ feature exists to remove. */}<HintRowtext={- providers.rows.length > providerWindow.length- ? `${providerCursor + 1} of ${providers.rows.length} — ↑↓ for more`+ providerRows.length > providerWindow.length+ ? `${providerCursor + 1} of ${providerRows.length} — ↑↓ for more`: ""}width={layout.inner}/>- {providers.notEnabledLocal.length > 0 ? (- <HintRow- text={`${providers.notEnabledLocal.join(", ")} — local, not enabled in your config`}- width={layout.inner}+ {/* THE OMITTED PROVIDERS, COUNTED. They are off the list because the user+ cannot launch any of them, and stated here because "where did the other+ fourteen go" must have an answer on the screen that dropped them. */}+ <HintRow+ text={+ keyless.length === 0+ ? ""+ : revealKeyless+ ? `showing ${keyless.length} with no credential · k hides them again`+ : `+${keyless.length} more need a key · k`+ }+ width={layout.inner}+ />+ {/* A DIFFERENT REASON, ON ITS OWN LINE. These are not missing a key: they+ are opt-in in your config (`config.localProviders`) and were never+ probed for liveness. */}+ <HintRow+ text={+ providers.notEnabledLocal.length > 0+ ? `${providers.notEnabledLocal.join(", ")} — local, not enabled in your config`+ : ""+ }+ width={layout.inner}+ />+ {/* THE ONE METER IN THE PICKER, on the one screen that waits for anything.+ It is `done/total` over a roster derived synchronously — real progress+ over countable work — and it disappears, leaving its row, when the last+ probe settles. */}+ {settled ? (+ <HintRow text="" width={layout.inner} />+ ) : (+ <LoadTasks+ tasks={tasks}+ frame={frame}+ labelWidth={12}+ barWidth={Math.max(8, Math.min(22, layout.inner - 40))}/>- ) : null}+ )}<Rule />- {/* The SAME line the model list carries, plus the count — so "what is- this provider" has one answer wherever it is asked. */}+ {/* The SAME line the model list carries, plus the count when one is+ known — so "what is this provider" has one answer wherever it is+ asked. */}<ProviderLinefacts={here === null ? null : factsOf(here)}width={layout.inner}- count={here === null ? null : (catalog.counts.get(here.value) ?? null)}+ count={here === null ? null : (counts.get(here.value) ?? null)}/><Hintshints={[{ key: "↑↓", label: "move" },- { key: "⏎", label: "show only this provider" },- { key: "esc", label: "back to all models" },+ { key: "⏎", label: "open", on: here !== null },+ { key: "a", label: "all models" },+ { key: "k", label: revealKeyless ? "hide" : "keyless", on: keyless.length > 0 },+ { key: "c", label: "custom" },+ { key: "esc", label: "quit" },]}/></Dialog>@@ -589,7 +756,7 @@ export function ModelPicker({ source, onDone, onDiscoveryFailure }: ModelPickerP<Centred width={width} height={height}><Dialogkey="loading"- title={scope === null ? "choose a model" : scopedName}+ title={scope === null ? "all models" : scopedName}status="finding models…"width={layout.width}marginLeft={0}@@ -606,7 +773,7 @@ export function ModelPicker({ source, onDone, onDiscoveryFailure }: ModelPickerP</text></box><Rule />- <Hints hints={[{ key: "esc", label: "cancel" }]} />+ <Hints hints={[{ key: "esc", label: "providers" }]} /></Dialog></Centred>);@@ -624,11 +791,15 @@ export function ModelPicker({ source, onDone, onDiscoveryFailure }: ModelPickerP? `${countModels(list.rows)} models · ${list.rows.length} routes · ${providers.ready.length}/${providers.total} providers`: (notice?.title ?? `${list.rows.length} models`);+ // THE CROSS-PROVIDER LIST IS LABELLED AS WHAT IT IS. It used to be the screen the+ // picker opened on, so `choose a model` was the whole dialog's purpose; it is now+ // one of the two things a provider list can open, and the other one is titled with+ // its provider's name. `all models` says which of the two you are looking at.return (<Centred width={width} height={height}><Dialogkey="models"- title={scope === null ? "choose a model" : scopedName}+ title={scope === null ? "all models" : scopedName}status={status}width={layout.width}marginLeft={0}@@ -661,7 +832,10 @@ export function ModelPicker({ source, onDone, onDiscoveryFailure }: ModelPickerPin every state. */}<boxflexDirection="column"- height={Math.min(layout.listRows, Math.max(1, window.length))}+ height={Math.min(+ layout.listRows,+ Math.max(window.length === 0 && filter !== "" ? 2 : 1, window.length)+ )}flexShrink={0}overflow="hidden">@@ -686,11 +860,12 @@ export function ModelPicker({ source, onDone, onDiscoveryFailure }: ModelPickerP</box>{/* ONE status row, ALWAYS rendered — see `CHROME_ROWS`. It carries the- scroll position when the list overflows, then the AGGREGATE discovery- failure (a per-provider banner is the wrong shape once the list spans- every provider), then the pending sweep, then nothing. */}+ scroll position when the list overflows, then whatever is still in+ flight, then nothing. There is no aggregate failure line any more:+ with the fan-out gone, the only roster that can fail is one the user+ opened, and that one gets the banner above this list. */}<HintRow- text={statusRow(cursor, shown.length, window.length, tasks, rosters.failures.length)}+ text={statusRow(cursor, shown.length, window.length, tasks)}width={layout.inner}/>@@ -710,18 +885,18 @@ export function ModelPicker({ source, onDone, onDiscoveryFailure }: ModelPickerP}width={layout.inner}/>+ {/* ONE KEY PER ACTION, AND EVERY ACTION IN THE ROW. `p` is gone: `esc` is+ the way back to the provider list from both model lists, and a second+ key for the one destination bought nothing while costing the row the+ columns `r retry` needs at 80. */}<Hintshints={[{ key: "↑↓", label: "move" },- { key: "⏎", label: "select" },+ { key: "⏎", label: "select", on: selected !== null },{ key: "/", label: "filter" },...(scope !== null && hasDiscovery ? [{ key: "r", label: "retry" }] : []),- { key: "p", label: "providers" },{ key: "c", label: "custom" },- {- key: "esc",- label: filter !== "" ? "clear" : scope !== null ? "all models" : "cancel",- },+ { key: "esc", label: filter !== "" ? "clear" : "providers" },]}/></Dialog>@@ -814,33 +989,26 @@ const MAX_BANNER_ROWS = 5;/*** 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 which providers could- * not be listed, then nothing.+ * longer than the window, then what is still loading, then nothing.*- * THE FAILURE LINE IS AGGREGATE, AND THAT IS THE POINT. The per-provider banner- * above the list is right when the user has SCOPED to one provider and asked it a- * question. It is the wrong shape once the flat list queries every ready provider- * at once: a banner per failure would push the list off the screen, and a banner- * for the first one would silently speak for the rest. So the count is stated in- * one dim row, `p` is named as the place the detail lives, and the full diagnostic- * for every failure still goes to the post-teardown stderr write, in order.+ * IT NO LONGER CARRIES AN AGGREGATE FAILURE COUNT, because there is no longer an+ * aggregate. That line existed for the startup fan-out — thirteen rosters in+ * flight at once, where a banner per failure would have pushed the list off the+ * screen and a banner for the first would have spoken for the rest. With rosters+ * fetched one at a time, on request, the only roster that can fail is the one the+ * user just opened, and it gets the full banner above its own list.*- * Pure so the priority can be asserted. The scroll position wins over everything- * because it changes on every keypress; the failures win over the pending sweep- * because the sweep is about to end and the failures are not.+ * Pure so the priority can be asserted. The scroll position wins over the pending+ * work because it changes on every keypress.*/export function statusRow(cursor: number,shown: number,visible: number,- tasks: LoadTask[],- rosterFailures = 0+ 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(", ")}`;- if (rosterFailures > 0) {- return `${rosterFailures} provider${rosterFailures === 1 ? "" : "s"} could not be listed — press p to see which`;- }return "";}@@ -869,7 +1037,7 @@ function emptyLabel(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`;+ return `no credential for any of the ${providers.total} providers — esc, then k, shows 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 e2a9b541..6ed7cf33 100644--- a/packages/cli/src/picker/PickerDataSource.ts+++ b/packages/cli/src/picker/PickerDataSource.ts@@ -41,10 +41,8 @@ import { isSubscriptionProvider } from "../handlers/shared/remote-provider-typesimport {type ModelInfo,type PickerDiscoveryOutcome,- type PreloadedRoster,buildDiscoveredModelOutcome,buildProviderChoices,- preloadProviderRoster,providerShortcut,servedModelsForProvider,} from "../model-selector.js";@@ -106,13 +104,6 @@ export interface PickerDataSource {servedModels(provider: string): ModelInfo[];/** One settled outcome per discovery provider, `fallbackRows` included. */discoverRoster(provider: string): Promise<PickerDiscoveryOutcome>;- /**- * This provider's LIVE roster, for merging into the flat cross-provider list.- *- * Distinct from `discoverRoster`: no catalog fallback leg, so no `?provider=`- * query — see `model-selector.ts:preloadProviderRoster`. Never rejects.- */- rosterRows(provider: string): Promise<PreloadedRoster>;/*** One editorial sentence per model, for the detail pane. Resolves late and is* never awaited before a first paint; the slim catalog carries no description.@@ -241,10 +232,6 @@ export function createPickerDataSource(): PickerDataSource {return buildDiscoveredModelOutcome(provider, names.get(provider) ?? provider, catalog);},- rosterRows(provider: string): Promise<PreloadedRoster> {- return preloadProviderRoster(provider, names.get(provider) ?? provider, catalog);- },-descriptions(): Promise<DescriptionIndex> {return loadModelDescriptions();},diff --git a/packages/cli/src/picker/fixtures/fixture-source.ts b/packages/cli/src/picker/fixtures/fixture-source.tsindex bb981815..1b55dc31 100644--- a/packages/cli/src/picker/fixtures/fixture-source.ts+++ b/packages/cli/src/picker/fixtures/fixture-source.ts@@ -18,8 +18,11 @@* WHY A FAKE AT ALL — the four states below are the whole point of the feature and* none of them is reachable from outside:*- * · `loading` the warm path settles in under 100 ms, so the in-flight frames- * cannot be photographed on a real run at all.+ * · `loading` the credential sweep held mid-`done/total` — the landing screen's+ * only in-flight state, and on a real machine it is over in a second.+ * · `discovering` credentials settle normally and the ROSTER never comes back.+ * This is the per-provider wait, which exists only because a roster+ * is now fetched when the user OPENS that provider.* · `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.@@ -29,7 +32,7 @@* and a live capture beats a forged one every time. The scenario exists as a control.*/-import type { ModelInfo, PickerDiscoveryOutcome, PreloadedRoster } from "../../model-selector.js";+import type { ModelInfo, PickerDiscoveryOutcome } from "../../model-selector.js";import type { DescriptionIndex } from "../../providers/model-descriptions.js";import {type PickerDataSource,@@ -37,7 +40,14 @@ import {createPickerDataSource,} from "../PickerDataSource.js";-export type FixtureName = "ready" | "loading" | "timeout" | "empty" | "filtered" | "unauthorized";+export type FixtureName =+ | "ready"+ | "loading"+ | "discovering"+ | "timeout"+ | "empty"+ | "filtered"+ | "unauthorized";const NEVER = new Promise<never>(() => {/* deliberately never settles — a capture window is finite, this is not */@@ -60,7 +70,7 @@ export function createFixtureDataSource(name: string): PickerDataSource {// `loading` claims discovery too — not to forge an outcome (it has none; it never// 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";+ const claimsDiscovery = forced || scenario === "loading" || scenario === "discovering";return {providerRoster(): PickerProviderChoice[] {@@ -94,26 +104,6 @@ export function createFixtureDataSource(name: string): PickerDataSource {return real.servedModels(provider);},- /**- * The cross-provider roster merge, forged the same way `discoverRoster` is:- * the SHAPE of the answer and its latency, never the data.- *- * `loading` never settles, which is what holds the `done/total` roster meter- * mid-sweep for a capture. A forced-failure scenario fails EVERY provider, so- * the aggregate "N providers could not be listed" line is photographable at- * all — with the real source it needs several providers to be broken at once,- * which is not a state a capture run can arrange.- */- async rosterRows(provider: string): Promise<PreloadedRoster> {- if (scenario === "loading") return NEVER;- if (!forced) return real.rosterRows(provider);- const outcome = await this.discoverRoster(provider);- if (outcome.kind === "failed") {- return { kind: "failed", failure: outcome.failure, notice: outcome.notice };- }- return { kind: "empty", reason: "empty-roster" };- },-descriptions(): Promise<DescriptionIndex> {// NOT forged: a description is editorial text from the real catalog, and a// capture of an invented sentence proves nothing about how a real one wraps.@@ -121,7 +111,11 @@ export function createFixtureDataSource(name: string): PickerDataSource {},async discoverRoster(provider: string): Promise<PickerDiscoveryOutcome> {- if (scenario === "loading") return NEVER;+ // `discovering` is the whole point of that scenario: the credential sweep+ // finishes, the provider list is on screen and usable, and the roster the+ // user just asked for never lands. It is the only way to photograph the+ // per-provider wait, which against a real provider is over in a second.+ if (scenario === "loading" || scenario === "discovering") return NEVER;if (!forced) return real.discoverRoster(provider);// The fallback list is the REAL vendor catalog for this provider, because thediff --git a/packages/cli/src/picker/hooks/useModelDescriptions.ts b/packages/cli/src/picker/hooks/useModelDescriptions.tsindex 78e3e283..e2971c40 100644--- a/packages/cli/src/picker/hooks/useModelDescriptions.ts+++ b/packages/cli/src/picker/hooks/useModelDescriptions.ts@@ -14,17 +14,31 @@* footer down under the reader's cursor, seconds after they started reading.*/-import { useEffect, useState } from "react";+import { useEffect, useRef, useState } from "react";import {type DescriptionIndex,emptyDescriptionIndex,} from "../../providers/model-descriptions.js";import type { PickerDataSource } from "../PickerDataSource.js";-export function useModelDescriptions(source: PickerDataSource): DescriptionIndex {+export function useModelDescriptions(+ source: PickerDataSource,+ /**+ * FALSE UNTIL A MODEL LIST IS ON SCREEN. A description describes a MODEL, and+ * the picker now opens on the provider list, where not one of them can be+ * shown — so fetching the index at startup would be a megabyte spent on a+ * screen that has nowhere to put it. Same rule as the catalog warm beside it:+ * on demand, once, when the view that uses it is asked for.+ */+ enabled = true+): DescriptionIndex {const [index, setIndex] = useState<DescriptionIndex>(emptyDescriptionIndex);+ /** Asked for ONCE per picker open, however often `enabled` flips. */+ const asked = useRef(false);useEffect(() => {+ if (!enabled || asked.current) return;+ asked.current = true;let live = true;void source.descriptions().then((loaded) => {@@ -38,7 +52,7 @@ export function useModelDescriptions(source: PickerDataSource): DescriptionIndexreturn () => {live = false;};- }, [source]);+ }, [source, enabled]);return index;}diff --git a/packages/cli/src/picker/hooks/usePickerModels.ts b/packages/cli/src/picker/hooks/usePickerModels.tsindex 99eb0856..9c3748ff 100644--- a/packages/cli/src/picker/hooks/usePickerModels.ts+++ b/packages/cli/src/picker/hooks/usePickerModels.ts@@ -96,18 +96,34 @@ export function usePickerModels(/** Providers whose credential probe came back true. */ready: ReadonlySet<string>,/**- * LIVE roster rows per provider, merged in as they land- * (`usePreloadedRosters`). Empty on the first frames, and that is the design:- * the catalog rows paint immediately and each roster joins them when it- * arrives, rather than the list waiting for the slowest provider.+ * LIVE roster rows for the providers the user has already OPENED this session+ * (`rowsFromOutcomes`). Empty until he opens one, and that is the design: a+ * roster is fetched because he asked for that provider, and once it is in hand+ * it costs nothing to let it improve the cross-provider list too.*/- liveRows: ReadonlyMap<string, ModelInfo[]> = EMPTY_LIVE+ liveRows: ReadonlyMap<string, ModelInfo[]> = EMPTY_LIVE,+ /**+ * FALSE UNTIL A MODEL LIST IS ACTUALLY ON SCREEN — the whole point of this+ * parameter.+ *+ * The picker opens on the provider list, which needs no catalog at all, and+ * the owner's instruction was blunt: *"why we prefetching? we should not, as+ * we show on demand"*. So the cross-vendor warm does not run at startup; it+ * runs the first time a list of MODELS is asked for, which is one cached fetch+ * for the view that needs it rather than eleven that nobody asked for.+ */+ enabled = true): PickerModelsState {- const [phase, setPhase] = useState<LoadPhase>("loading");+ const [phase, setPhase] = useState<LoadPhase>("idle");const cache = useRef(new Map<string, PickerRow[]>());+ /** The warm is asked for ONCE per picker open, however often `enabled` flips. */+ const warmed = useRef(false);useEffect(() => {+ if (!enabled || warmed.current) return;+ warmed.current = true;let live = true;+ setPhase("loading");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.@@ -121,7 +137,7 @@ export function usePickerModels(return () => {live = false;};- }, [source]);+ }, [source, enabled]);// 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 wholediff --git a/packages/cli/src/picker/hooks/usePreloadedRosters.ts b/packages/cli/src/picker/hooks/usePreloadedRosters.tsdeleted file mode 100644index 836754f9..00000000--- a/packages/cli/src/picker/hooks/usePreloadedRosters.ts+++ /dev/null@@ -1,166 +0,0 @@-/**- * usePreloadedRosters — every ready provider's LIVE roster, fetched concurrently- * and merged into the flat list as each one lands.- *- * THE DEFECT THIS FIXES WAS REPORTED FROM A LIVE RUN. The owner typed `gemini`- * into the filter and got eleven rows, every one of them `or@`. His words: *"why i- * search gemini i see only open router models, no models from antigravity and- * devin and subscriptions"*. The flat list was built from the cloud catalog alone,- * so the thirteen providers that serve their roster through live discovery —- * Antigravity, Devin, both Qwen consoles, Grok Build, OpenCode Zen Go, the coding- * plans, Ollama and LM Studio — contributed NOTHING until the user had already- * guessed to scope to them. MEASURED on this machine: eight of those thirteen have- * zero catalog entries by design, so they were entirely absent from a list whose- * title said `437 models`.- *- * IT MATTERS MORE THAN A MISSING ROW. The one genuinely useful thing about a- * cross-provider list is seeing the same model on several routes at different- * prices — `gpt-6-astra` on `or@` at $30.00, on `oai@` at $30.00, on `cx@` as- * `SUB`. The routes that were being hidden are the FLAT-RATE ones: Antigravity- * serves gemini and claude models on a subscription that costs nothing at the- * point of use. A user searching `gemini` was quoted $2.25/1M and never told he- * already had it.- *- * THREE RULES KEEP IT FROM BECOMING THE FAN-OUT THAT WAS REJECTED:- *- * 1. **Concurrent, never serial.** One request per provider, all in flight at- * once, results merged in completion order.- * 2. **No catalog leg.** `source.rosterRows` calls `preloadProviderRoster`, which- * does NOT run `loadModelsForPickerProvider` — that live `?provider=` query is- * the one measured at 10 018 ms for 22 concurrent callers. Prices come from the- * local served-by index instead.- * 3. **Never blocks a paint.** The catalog rows are on screen before the first- * request settles; each roster is merged when it arrives and the header count- * moves. A picker that waited for the slowest provider would be trading one- * complaint for a worse one.- *- * READY PROVIDERS ONLY. An uncredentialled provider's roster request cannot- * succeed — it would spend a round-trip to be told 401 — and its rows could not be- * launched anyway. `usePickerProviders` has already answered which are ready, one- * `setState` at a time, so this fires each provider's request the moment its own- * probe settles rather than waiting for the whole sweep.- *- * A FAILURE IS COUNTED, NOT SWALLOWED. `failures` carries one entry per provider- * whose roster could not be listed, and the caller renders the aggregate — `2- * providers could not be listed · p` — because a per-provider banner is the wrong- * shape for a state that is about the list as a whole. The full diagnostic still- * goes to the post-teardown stderr write, exactly as the scoped path's does.- */--import { useEffect, useMemo, useRef, useState } from "react";-import { log } from "../../logger.js";-import type { ModelInfo } from "../../model-selector.js";-import type { PickerDataSource, PickerProviderChoice } from "../PickerDataSource.js";--export interface RosterPreloadState {- /** Live rows per provider, added as each roster lands. */- rowsByProvider: ReadonlyMap<string, ModelInfo[]>;- /** Providers whose roster could not be listed, in the order they failed. */- failures: readonly string[];- /** Rosters settled so far. */- done: number;- /** Rosters that will be asked for. Grows as credential probes settle. */- total: number;- /** True while any request is open. */- busy: boolean;-}--export function usePreloadedRosters(- source: PickerDataSource,- roster: PickerProviderChoice[],- /** Providers whose credential probe came back true. */- ready: ReadonlySet<string>,- /** Called once per provider that fails, for the ONE write after teardown. */- onFailure?: (provider: string, notice: readonly string[]) => void-): RosterPreloadState {- const [rowsByProvider, setRows] = useState<Map<string, ModelInfo[]>>(new Map());- const [failures, setFailures] = useState<string[]>([]);- const [done, setDone] = useState(0);- const [total, setTotal] = useState(0);- /** Providers already asked. One request per provider per picker open. */- const asked = useRef(new Set<string>());- const startedAt = useRef<number | null>(null);- // A ref, not a dependency: the callback identity must not re-trigger the- // effect, and a stale closure would report a failure to a buffer nobody drains.- const report = useRef(onFailure);- report.current = onFailure;-- /**- * ONE liveness flag for the whole mount, NOT one per effect run.- *- * The ready set is re-derived every render, so this effect re-runs often. A- * `let live = true` inside it would be flipped false by the NEXT run's cleanup- * while its own requests were still in flight — every roster started before the- * last credential probe settled would land, find `live === false`, and merge- * nothing. The bug is invisible in a test with instant probes and total on a- * real machine, which is the worst combination there is.- */- const alive = useRef(true);- useEffect(- () => () => {- alive.current = false;- },- []- );-- // The ready SET cannot be a dependency (a new Set every frame); its signature can.- const signature = useMemo(() => [...ready].sort().join(","), [ready]);-- useEffect(() => {- const wanted = roster.filter((r) => r.hasDiscovery && ready.has(r.value));- const fresh = wanted.filter((r) => !asked.current.has(r.value));- if (fresh.length === 0) return;-- for (const r of fresh) asked.current.add(r.value);- if (startedAt.current === null) startedAt.current = Date.now();- setTotal(asked.current.size);-- // CONCURRENT: every request starts here, in this tick. Nothing awaits the- // previous one, and each merges itself when it settles.- for (const choice of fresh) {- void source.rosterRows(choice.value).then(- (outcome) => {- if (!alive.current) return;- setDone((n) => n + 1);- if (outcome.kind === "rows") {- setRows((prev) => new Map(prev).set(choice.value, outcome.rows));- return;- }- if (outcome.kind === "failed") {- setFailures((prev) => (prev.includes(choice.value) ? prev : [...prev, choice.value]));- report.current?.(choice.value, outcome.notice);- }- },- // `preloadProviderRoster` never rejects by contract; a contract is not a- // type, and an unhandled rejection behind a live renderer has nowhere to- // surface. Count it settled so the meter cannot stall at 12/13 forever.- (err: unknown) => {- if (!alive.current) return;- setDone((n) => n + 1);- setFailures((prev) => (prev.includes(choice.value) ? prev : [...prev, choice.value]));- log(`[picker] roster preload for ${choice.value} rejected: ${String(err)}`);- }- );- }- // The requests are abandoned on unmount, never awaited: React is unmounted- // before the renderer is destroyed, so nothing can paint into a dead one.- // biome-ignore lint/correctness/useExhaustiveDependencies: `signature` is the stable projection of `ready`; depending on the Set itself re-runs every frame- }, [source, roster, signature, ready]);-- const busy = total > 0 && done < total;- // ONE line, when the last roster lands, with the numbers the owner asked for.- // It goes to the debug log rather than the terminal: the renderer owns the- // terminal while the picker is up.- const logged = useRef(false);- if (!busy && total > 0 && !logged.current) {- logged.current = true;- const rows = [...rowsByProvider.values()].reduce((n, r) => n + r.length, 0);- log(- `[picker] preloaded ${total} live roster(s) concurrently in ${- startedAt.current === null ? 0 : Date.now() - startedAt.current- } ms: ${rows} row(s) merged, ${failures.length} provider(s) could not be listed`- );- }-- return { rowsByProvider, failures, done, total, busy };-}diff --git a/packages/cli/src/picker/hooks/useProviderDiscovery.ts b/packages/cli/src/picker/hooks/useProviderDiscovery.tsindex ffc49c1c..f5eddef9 100644--- a/packages/cli/src/picker/hooks/useProviderDiscovery.ts+++ b/packages/cli/src/picker/hooks/useProviderDiscovery.ts@@ -23,7 +23,7 @@*/import { useCallback, useEffect, useRef, useState } from "react";-import type { PickerDiscoveryOutcome } from "../../model-selector.js";+import type { ModelInfo, PickerDiscoveryOutcome } from "../../model-selector.js";import type { PickerDataSource } from "../PickerDataSource.js";export interface DiscoveryState {@@ -132,3 +132,29 @@ export function useProviderDiscovery(seen: outcomes,};}++/**+ * The rosters ALREADY IN HAND, as the cross-provider list wants them.+ *+ * THIS IS WHAT REPLACED THE STARTUP FAN-OUT. An earlier build fired one roster+ * request per credentialled provider the moment the picker opened — thirteen+ * requests, a `live rosters 0/11 providers` meter, and the owner's verdict was+ * *"why we prefetching? we should not, as we show on demand"*. Every one of those+ * requests is now made for a provider the user actually opened, by the hook above.+ * This function spends no network at all: it re-reads the outcomes that are+ * already settled, so a provider he visited enriches the all-models view for free+ * and a provider he did not visit is simply not represented there.+ *+ * ONLY `rows`. A failure's `fallbackRows` are the catalog's, which the flat list+ * already holds under the same provider — merging them would double that+ * provider's rows and launder a fallback into a live roster at the same time.+ */+export function rowsFromOutcomes(+ seen: ReadonlyMap<string, PickerDiscoveryOutcome>+): Map<string, ModelInfo[]> {+ const out = new Map<string, ModelInfo[]>();+ for (const [provider, outcome] of seen) {+ if (outcome.kind === "rows") out.set(provider, outcome.rows);+ }+ return out;+}diff --git a/packages/cli/src/picker/layout.test.ts b/packages/cli/src/picker/layout.test.tsindex 2185521d..1073ae97 100644--- a/packages/cli/src/picker/layout.test.ts+++ b/packages/cli/src/picker/layout.test.ts@@ -22,7 +22,9 @@ import {MAX_DIALOG_WIDTH,MAX_LIST_ROWS,deriveDialogLayout,+ deriveProviderRowLayout,deriveRowLayout,+ providerRowTotal,rowLayoutTotal,scrollWindow,} from "./layout.js";@@ -83,6 +85,43 @@ describe("deriveRowLayout", () => {});});+describe("deriveProviderRowLayout", () => {+ test("cells sum EXACTLY to the row width at every width in [40, 200]", () => {+ // THE DEFECT THIS WOULD HAVE CAUGHT IS THE ONE THAT WAS THERE. The provider+ // row's four widths used to be `const`s inside the component with an+ // `inner - 2 - 2 - … - 3` for the name, and they summed two columns SHORT —+ // every provider row painted a two-cell dead tail and nothing said so.+ const wrong = WIDTHS.map((w) => ({+ w,+ sum: providerRowTotal(deriveProviderRowLayout(w)),+ })).filter(({ w, sum }) => sum !== w);+ expect(wrong).toEqual([]);+ });++ test("no cell is ever negative, at any width including absurd ones", () => {+ for (const w of [...WIDTHS, 0, 1, 8, 20, -5, Number.NaN, Number.POSITIVE_INFINITY]) {+ const l = deriveProviderRowLayout(w);+ for (const [cell, n] of Object.entries(l)) {+ expect({ w, cell, ok: Number.isFinite(n) && n >= 0 }).toEqual({ w, cell, ok: true });+ }+ }+ });++ test("the name is CAPPED at the longest name there is — the surplus goes right", () => {+ // `Grok Build (subscription)` is 25 cells, the longest in the roster, so a name+ // column wider than 26 is dead air between a provider and the shortcut that+ // qualifies it. Past the cap the extra columns go to the right-aligned tail,+ // which is where a count belongs.+ const narrow = deriveProviderRowLayout(72);+ const wide = deriveProviderRowLayout(140);+ expect(narrow.name).toBe(26);+ expect(wide.name).toBe(26);+ expect(wide.tail - narrow.tail).toBe(140 - 72);+ expect(wide.shortcut).toBe(narrow.shortcut);+ expect(wide.billing).toBe(narrow.billing);+ });+});+describe("deriveDialogLayout", () => {test("the dialog FITS 80x24 and 145x45 — it is centred in the terminal, never clipped", () => {const small = deriveDialogLayout(80, 24);diff --git a/packages/cli/src/picker/layout.ts b/packages/cli/src/picker/layout.tsindex ef355dae..fd0aca73 100644--- a/packages/cli/src/picker/layout.ts+++ b/packages/cli/src/picker/layout.ts@@ -232,6 +232,104 @@ export function providerColumn(return { cells, text };}+/**+ * ONE PROVIDER ROW'S CELLS — the provider list's budget, in the same file as the+ * model row's and for the same reason.+ *+ * It used to live inside `ProviderRow` as four `const`s and an `inner - 2 - 2 -+ * … - 3` expression, which is exactly the drift this file's header warns about:+ * the numbers summed to two columns SHORT of the row, so every provider row+ * painted two unused cells on its right edge and nothing said so. A budget with+ * a test that pins the sum cannot do that.+ *+ * THE TAIL IS SIZED FOR THE ENV VAR, NOT FOR THE COUNT. It carries either a model+ * count (`263 models`) or the credential a keyless provider wants (`needs+ * MOONSHOT_API_KEY`, 22 cells), and a truncated variable name is worse than+ * useless — `needs MOON…` sends the reader looking for a variable that does not+ * exist. Keyless providers are hidden by default now, but `k` reveals them in+ * this same list, so the cell is still theirs to fit.+ */+export interface ProviderRowLayout {+ inner: number;+ /** `▶ ` / ` `, carrying its own trailing space. */+ cursor: number;+ /** `● ` — the readiness glyph and one space. */+ glyph: number;+ /** The readable display name. The elastic cell. */+ name: number;+ /** `zengo@` — the routing shortcut. */+ shortcut: number;+ /** `SUB` / `local` / `$`. */+ billing: number;+ /** Right-aligned: the count, or what a keyless provider needs. */+ tail: number;+ /** One space after the name. Part of the sum. */+ gaps: number;+}++const PROVIDER_GLYPH_CELLS = 2;+const PROVIDER_SHORTCUT_CELLS = 9;+const PROVIDER_BILLING_CELLS = 6;+const PROVIDER_TAIL_CELLS = 26;+const PROVIDER_GAP_AFTER_NAME = 1;+/** Below this a provider name is no longer a name. */+const MIN_PROVIDER_NAME_CELLS = 6;+/**+ * The widest a provider NAME column is ever drawn, whatever the terminal gives it.+ *+ * MEASURED over the whole roster: `Grok Build (subscription)` is 25 cells and+ * nothing is longer, so 26 fits every name whole. Past that the cell is dead air,+ * and at 92 columns it was 46 — twenty blank cells between `OpenRouter` and the+ * `or@` that qualifies it, which reads as two unrelated columns rather than one+ * fact. The surplus goes to the TAIL, which is right-aligned: the count then sits+ * on the dialog's right edge where a number belongs, and the row still sums to+ * `inner` exactly.+ */+const MAX_PROVIDER_NAME_CELLS = 26;++export function deriveProviderRowLayout(inner: number): ProviderRowLayout {+ const cells = Number.isFinite(inner) ? Math.max(0, Math.floor(inner)) : 0;+ let shortcut = PROVIDER_SHORTCUT_CELLS;+ let billing = PROVIDER_BILLING_CELLS;+ let tail = PROVIDER_TAIL_CELLS;+ const fixed = (): number =>+ CURSOR_CELLS + PROVIDER_GLYPH_CELLS + shortcut + billing + tail + PROVIDER_GAP_AFTER_NAME;+ let name = cells - fixed();+ if (name < MIN_PROVIDER_NAME_CELLS) {+ // The tail gives way first — a count is re-stated in full on the detail line+ // below, so it is the one cell here that is a duplicate rather than a fact.+ tail = Math.max(0, tail - (MIN_PROVIDER_NAME_CELLS - name));+ name = cells - fixed();+ }+ if (name < MIN_PROVIDER_NAME_CELLS) {+ shortcut = Math.max(0, shortcut - (MIN_PROVIDER_NAME_CELLS - name));+ name = cells - fixed();+ }+ if (name < 0) {+ billing = Math.max(0, billing + name);+ name = Math.max(0, cells - fixed());+ }+ if (name > MAX_PROVIDER_NAME_CELLS) {+ tail += name - MAX_PROVIDER_NAME_CELLS;+ name = MAX_PROVIDER_NAME_CELLS;+ }+ return {+ inner: cells,+ cursor: CURSOR_CELLS,+ glyph: PROVIDER_GLYPH_CELLS,+ name,+ shortcut,+ billing,+ tail,+ gaps: PROVIDER_GAP_AFTER_NAME,+ };+}++/** Sum of every provider cell plus its separator — must equal `inner`. */+export function providerRowTotal(l: ProviderRowLayout): number {+ return l.cursor + l.glyph + l.name + l.shortcut + l.billing + l.tail + l.gaps;+}+/** The widest the dialog is ever drawn, however wide the terminal is. */export const MAX_DIALOG_WIDTH = 96;/** The tallest the dialog is ever drawn, however tall the terminal is. */diff --git a/packages/cli/src/picker/row-semantics.test.ts b/packages/cli/src/picker/row-semantics.test.tsindex 95ac57de..0b700260 100644--- a/packages/cli/src/picker/row-semantics.test.ts+++ b/packages/cli/src/picker/row-semantics.test.ts@@ -68,6 +68,16 @@ describe("priceFg", () => {expect(priceFg("local")).toBe(priceFg("N/A"));expect(priceFg("local")).not.toBe(priceFg("$2.25"));});++ test("AN EXPENSIVE PRICE IS NOT PAINTED AS AN ALARM — one colour, one meaning", () => {+ // A prototype of this dialog bucketed metered prices and drew anything over+ // $10/1M in orange; the owner and the reviewer both read `$30.00` as an error,+ // because red-orange is what this app spends on a failure and on `SUB`. A+ // number is a number: the numeral is body ink at every magnitude, and the+ // comparison the reader is making is between the DIGITS.+ const prices = ["$0.15", "$2.25", "$12.50", "$15.00", "$30.00"].map(priceFg);+ expect(new Set(prices).size).toBe(1);+ });});describe("billingLabel / readinessGlyph", () => {diff --git a/packages/cli/src/picker/rows.tsx b/packages/cli/src/picker/rows.tsxindex 0e5f7240..b11a75d6 100644--- a/packages/cli/src/picker/rows.tsx+++ b/packages/cli/src/picker/rows.tsx@@ -59,7 +59,7 @@ import { A, C } from "../tui/theme.js";import { padStartTo, padTo, truncate } from "../tui/viz/text.js";import { tokens } from "../tui/viz/tokens.js";import type { BillingMode } from "./PickerDataSource.js";-import { GAPS, type RowLayout } from "./layout.js";+import { GAPS, type RowLayout, deriveProviderRowLayout } from "./layout.js";/** Readiness, in `ProvidersContent.tsx:225`'s exact vocabulary. */export type Readiness = "pending" | "ready" | "missing";@@ -198,9 +198,18 @@ export interface ProviderRowProps {shortcut: string;readiness: Readiness;billing: BillingMode;- /** Models this provider serves, or `null` before the catalog has answered. */+ /**+ * How many models this provider offers, or `null` for "not known yet".+ *+ * `null` PRINTS NOTHING — not `0`, not `—`, not a guess. The owner's rule,+ * verbatim: *"we could not show number of models for some of them"*. This+ * column is now only filled for a provider whose roster the user has already+ * opened, or whose count is already in hand from a catalog the user asked for;+ * everything else is silent, because a wrong count is worse than no count and+ * an em dash still occupies the place where a number goes.+ */count: number | null;- /** Does this provider list its own roster? Decides what `0` in the catalog means. */+ /** Does this provider list its own roster? Decides what a known `0` means. */hasDiscovery: boolean;/** Why it is not selectable — an env var name, or empty. */note: string;@@ -210,14 +219,21 @@ export interface ProviderRowProps {}/**- * One provider, in the `p` dialog.+ * One provider, in the list the picker now OPENS ON.+ *+ * IT IS THE DEFAULT SCREEN, NOT A DETOUR. The build this replaces landed on a flat+ * 574-row cross-provider list and reached the providers through `p`; the owner's+ * verdict was *"we should not show the full list of models, we should show a list+ * of providers by default and only when we go inside we load and resolve all+ * models"*. So this row is the first thing the picker draws, and entering one is+ * what makes that provider's roster be fetched at all.*- * 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.+ * IT IS A DIALOG, NOT A RAIL. 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 ProviderRow({label,@@ -232,15 +248,7 @@ export function ProviderRow({}: ProviderRowProps): ReactNode {const { glyph, fg } = readinessGlyph(readiness);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);+ const L = deriveProviderRowLayout(inner);// `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@@ -248,22 +256,22 @@ export function ProviderRow({// has not been asked yet.const countText =count === null- ? "—"+ ? "": count === 0 && hasDiscovery? "asks its own roster": `${count} model${count === 1 ? "" : "s"}`;+ const tail = readiness === "missing" && note !== "" ? note : countText;return (<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 ? 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={fg}>{padTo(glyph, L.glyph)}</span>+ <span fg={cursor ? C.strong : tokens.text}>{padTo(truncate(label, L.name), L.name)}</span>+ <span>{gap(L.gaps)}</span>+ <span fg={tokens.subtle}>{padTo(truncate(shortcut, L.shortcut), L.shortcut)}</span>+ <span fg={bill.fg}>{padTo(bill.text, L.billing)}</span><span fg={readiness === "missing" ? tokens.dead : tokens.subtle}>- {padStartTo(readiness === "missing" && note !== "" ? note : countText, countCell)}+ {padStartTo(truncate(tail, L.tail), L.tail)}</span></text></box>diff --git a/packages/cli/src/tui/theme-contrast.test.ts b/packages/cli/src/tui/theme-contrast.test.tsindex 5ca54470..0ad2851f 100644--- a/packages/cli/src/tui/theme-contrast.test.ts+++ b/packages/cli/src/tui/theme-contrast.test.ts@@ -105,6 +105,16 @@ describe("light TUI palette contrast", () => {expect(contrastRatio(C.fgMuted, C.chipLabelBg)).toBeGreaterThanOrEqual(4.5);});+ it("RAISES the keycap chip off the panel it is drawn on", () => {+ // Legible ink is only half of a keycap: the chip also has to be visibly+ // raised off the band beneath it or it reads as a tinted word rather than as+ // a key you press. The owner reported exactly that from a live light-theme+ // run, and the old `#d1d5db` measured 1.32:1 against `bgAlt` — under the+ // 1.7:1 this file already requires of every stage block.+ setThemeMode("light");+ expect(contrastRatio(C.chipKeyBg, C.bgAlt)).toBeGreaterThanOrEqual(1.7);+ });+it("re-snapshots semantic tokens and ramps", () => {setThemeMode("light");expect(tokens.success).toBe(C.green);diff --git a/packages/cli/src/tui/theme.ts b/packages/cli/src/tui/theme.tsindex 9c21ca14..30c6d995 100644--- a/packages/cli/src/tui/theme.ts+++ b/packages/cli/src/tui/theme.ts@@ -149,7 +149,14 @@ const LIGHT: TuiPalette = {pillKeyBg: "#2d6e3e",pillOauthBg: "#1f6d75",- chipKeyBg: "#d1d5db", // key segment — theme text (`C.fg`) rides on top+ // A KEYCAP HAS TO READ AS A KEY, which means it has to be visibly RAISED off+ // the panel it sits on — and `#d1d5db` was not. MEASURED against the panel+ // band it is drawn on (`bgAlt`, `#f3f4f6`): 1.32:1, below the 1.7:1 this file+ // already requires of every stage block, so the picker's footer chips read as+ // faintly tinted words rather than as keys. The owner said so from a live run.+ // `#9ca3af` keeps 5.4:1 under `C.fg` — still past the 4.5:1 the footer's own+ // contrast test demands — while sitting 2.3:1 off the band.+ chipKeyBg: "#9ca3af", // key segment — theme text (`C.fg`) rides on topchipLabelBg: "#e5e7eb", // label segment};