Skip to content

Claude Code. Any Model. The most powerful AI coding agent now speaks every language.

wip(picker): preloaded rosters, descriptions, mid flexbox conversion

Jack Rudenkoec9d2ca634fc
diff --git a/packages/cli/src/model-loader.ts b/packages/cli/src/model-loader.ts
index 6f0fbd56..1682ad5b 100644
--- a/packages/cli/src/model-loader.ts
+++ b/packages/cli/src/model-loader.ts
@@ -938,6 +938,35 @@ export async function getModelsByProvider(provider: string, limit = 200): Promis
return data.models ?? [];
}
+/**
+ * Every active model the catalog knows, in ONE request.
+ *
+ * WHY A BULK PAGE RATHER THAN N QUERIES. The picker needs one editorial fact per
+ * model — the description — for every row it can draw. The slim catalog
+ * (`?catalog=slim`, the file behind `all-models.json`) deliberately carries none:
+ * `model-catalog.ts:servedByVendor` says so in its own doc comment, and a check
+ * of the on-disk cache confirms 0 of 704 entries have one. Asking per model, or
+ * per provider, is the fan-out this picker already measured at 10 018 ms.
+ *
+ * MEASURED 2026-09-10 against the live endpoint: `limit=1500` returns all 1016
+ * active models, 1.06 MB, in 2.8 s; `limit=1000` returns 1000 with
+ * `hasMore: true`, so the limit is honoured rather than capped. The caller caches
+ * the projection it needs on disk under the shared Firebase TTL, so this runs at
+ * most once a day and never blocks a first paint.
+ */
+export async function getAllModelDocs(limit = 1500): Promise<ModelDoc[]> {
+ const url = `${FIREBASE_BASE_URL}?status=active&limit=${limit}`;
+ const response = await fetch(url, {
+ signal: AbortSignal.timeout(SEARCH_FETCH_TIMEOUT_MS),
+ });
+ if (!response.ok) {
+ throw new Error(`Firebase catalog query returned ${response.status} ${response.statusText}`);
+ }
+ const data = (await response.json()) as ModelDoc[] | { models?: ModelDoc[] };
+ if (Array.isArray(data)) return data;
+ return data.models ?? [];
+}
+
// ─── Legacy loaders retained for cli.ts --model flag validation ──────────────
/**
diff --git a/packages/cli/src/model-selector.ts b/packages/cli/src/model-selector.ts
index 19778bc3..75d6ebae 100644
--- a/packages/cli/src/model-selector.ts
+++ b/packages/cli/src/model-selector.ts
@@ -1738,6 +1738,97 @@ 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.tsx
index 882056c1..705fbfb5 100644
--- a/packages/cli/src/picker/ModelPicker.test.tsx
+++ b/packages/cli/src/picker/ModelPicker.test.tsx
@@ -25,7 +25,8 @@ import { describe, expect, test } from "bun:test";
import type { CapturedFrame } from "@opentui/core";
import { testRender } from "@opentui/react/test-utils";
import type { ReactNode } from "react";
-import type { ModelInfo, PickerDiscoveryOutcome } from "../model-selector.js";
+import type { ModelInfo, PickerDiscoveryOutcome, PreloadedRoster } from "../model-selector.js";
+import type { DescriptionIndex } from "../providers/model-descriptions.js";
import { C } from "../tui/theme.js";
import { ModelPicker } from "./ModelPicker.js";
import { MAX_DIALOG_ROWS } from "./layout.js";
@@ -64,6 +65,10 @@ interface FakeOpts {
/** 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;
}
@@ -71,6 +76,7 @@ interface FakeOpts {
function fakeSource(opts: FakeOpts = {}): PickerDataSource {
const roster = opts.roster ?? [provider()];
const never = new Promise<never>(() => {});
+ const descriptions = opts.descriptions ?? {};
return {
providerRoster: () => roster,
notEnabledLocalProviders: () => [],
@@ -87,6 +93,19 @@ function fakeSource(opts: FakeOpts = {}): PickerDataSource {
: Promise.resolve(
opts.outcome ?? { kind: "rows", rows: [model()], servedCount: 1, chatCount: 1 }
),
+ rosterRows: (p): Promise<PreloadedRoster> =>
+ opts.hang
+ ? never
+ : Promise.resolve(
+ opts.liveRosters?.[p] ?? { kind: "empty", reason: "unsupported" as const }
+ ),
+ descriptions: (): Promise<DescriptionIndex> =>
+ opts.hang
+ ? never
+ : Promise.resolve({
+ get: (id: string) => descriptions[id],
+ size: Object.keys(descriptions).length,
+ }),
};
}
@@ -245,7 +264,7 @@ describe("the flat cross-provider list", () => {
provider({ value: "kimi-coding", label: "Kimi Coding", shortcut: "kc@", hasDiscovery: false }),
];
- test("merges every credentialled provider and prints the routing shortcut per row", async () => {
+ test("merges every credentialled provider and NAMES the provider on each row", async () => {
const d = await draw(
<ModelPicker
source={fakeSource({
@@ -262,10 +281,11 @@ describe("the flat cross-provider list", () => {
const all = joined(d.text);
expect(all).toContain("glm-5.3-flash");
expect(all).toContain("kimi-k3");
- // The column teaches the `provider@model` syntax the CLI already takes on argv,
- // and `or@` vs `kc@` cannot collide the way two `opencod…` rail rows did.
- expect(all).toContain("or@");
- expect(all).toContain("kc@");
+ // 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("OpenRouter");
+ expect(all).toContain("Kimi Coding");
} finally {
d.destroy();
}
@@ -296,6 +316,121 @@ describe("the flat cross-provider list", () => {
}
});
+ 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,
+ }),
+ ];
+ 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
+ );
+ try {
+ 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");
+ } 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.
+ const d = await draw(
+ <ModelPicker
+ source={fakeSource({
+ roster,
+ byProvider: {
+ openrouter: [model({ id: "gpt-6-astra" })],
+ "kimi-coding": [model({ id: "gpt-6-astra" })],
+ },
+ })}
+ onDone={() => {}}
+ />,
+ 145,
+ 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");
+ } 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[] = [];
+ const d = await draw(
+ <ModelPicker
+ source={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"],
+ },
+ },
+ })}
+ onDone={() => {}}
+ onDiscoveryFailure={(p) => failures.push(p)}
+ />
+ );
+ 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"]);
+ } finally {
+ d.destroy();
+ }
+ });
+
test("typing filters immediately — there is no search mode to enter", async () => {
const d = await draw(
<ModelPicker
diff --git a/packages/cli/src/picker/ModelPicker.tsx b/packages/cli/src/picker/ModelPicker.tsx
index aedd43ad..a68cbdb4 100644
--- a/packages/cli/src/picker/ModelPicker.tsx
+++ b/packages/cli/src/picker/ModelPicker.tsx
@@ -61,19 +61,34 @@ import { type ReactNode, useEffect, useMemo, useState } from "react";
import type { ModelInfo } from "../model-selector.js";
import { EmptyState } from "../tui/components/EmptyState.js";
import { useAnimationFrame } from "../tui/hooks/useAnimationFrame.js";
+import { truncate } from "../tui/viz/text.js";
import { tokens } from "../tui/viz/tokens.js";
import { DiscoveryNotice, discoveryNoticeContent, noticeRows } from "./DiscoveryNotice.js";
import {
DISCOVERY_DEADLINE_MS,
type DiscoveryShape,
type PickerDataSource,
+ type PickerProviderChoice,
} from "./PickerDataSource.js";
import { Dialog, FilterRow, Hints, type LoadTask, LoadTasks, Rule } from "./chrome.js";
-import { SelectionLine } from "./detail.js";
-import { type PickerRow, toPickerRow, usePickerModels } from "./hooks/usePickerModels.js";
+import { DescriptionBlock, type ProviderFacts, ProviderLine, SelectionLine } from "./detail.js";
+import { useModelDescriptions } from "./hooks/useModelDescriptions.js";
+import {
+ type PickerRow,
+ dedupeByModelId,
+ 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 { deriveDialogLayout, deriveRowLayout, scrollWindow } from "./layout.js";
+import {
+ deriveDialogLayout,
+ deriveRowLayout,
+ providerCellsFor,
+ providerColumn,
+ scrollWindow,
+} from "./layout.js";
import { ColumnHeader, HintRow, ModelRow, ProviderRow } from "./rows.js";
/**
@@ -94,6 +109,7 @@ import { ColumnHeader, HintRow, ModelRow, ProviderRow } from "./rows.js";
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[] = [];
@@ -107,6 +123,18 @@ 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`;
@@ -141,7 +169,21 @@ type View = "models" | "providers" | "custom";
export function ModelPicker({ source, onDone, onDiscoveryFailure }: ModelPickerProps): ReactNode {
const { width, height } = useTerminalDimensions();
const providers = usePickerProviders(source);
- const catalog = usePickerModels(source, providers.roster, providers.readySet);
+ // 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 [filter, setFilter] = useState("");
@@ -176,6 +218,13 @@ export function ModelPicker({ source, onDone, onDiscoveryFailure }: ModelPickerP
// mark means "the live roster was asked for and could not be had"; nothing asked
// for a live roster here, so marking every row would spend the loudest signal in
// the feature on the ordinary case and teach the reader to ignore it.
+ // ONE ROW PER MODEL INSIDE A PROVIDER, N ROWS ACROSS PROVIDERS. The owner stated
+ // the rule: *"if model has more than one provider that going to be two lines in
+ // 'all models' list. and if we enter to provider catalog, not all models — then
+ // the model will be just one"*. The flat list's identity is `(provider, modelId)`
+ // and `usePickerModels` applies it; every scoped branch below goes through
+ // `dedupeByModelId`, so a live roster overlapping the catalog for the SAME
+ // provider cannot show the same model twice.
const list = useMemo((): { rows: RowView[]; fallback: boolean; loading: boolean } => {
if (scope === null) {
return { rows: catalog.rows, fallback: false, loading: catalog.phase !== "ready" };
@@ -185,8 +234,8 @@ export function ModelPicker({ source, onDone, onDiscoveryFailure }: ModelPickerP
// string or a different spec spelling — instead of by the three deliberate
// provenance encodings.
const project = (rows: ModelInfo[]): RowView[] =>
- scopedChoice === null ? [] : rows.map((m) => toPickerRow(scopedChoice, m));
- const scoped = catalog.rows.filter((r) => r.provider === scope);
+ scopedChoice === null ? [] : dedupeByModelId(rows.map((m) => toPickerRow(scopedChoice, m)));
+ const scoped = dedupeByModelId(catalog.rows.filter((r) => r.provider === scope));
if (!hasDiscovery) return { rows: scoped, fallback: false, loading: catalog.phase !== "ready" };
const o = discovery.outcome;
if (o === null) return { rows: [], fallback: false, loading: true };
@@ -195,23 +244,56 @@ export function ModelPicker({ source, onDone, onDiscoveryFailure }: ModelPickerP
return { rows: project(o.fallbackRows), fallback: true, loading: false };
}, [scope, scopedChoice, hasDiscovery, discovery.outcome, catalog.rows, catalog.phase]);
+ /**
+ * The provider cell for every provider on screen — collision-proof by
+ * construction, and computed from the ROSTER rather than from the rows so the
+ * column does not change width as rosters merge in behind the cursor.
+ */
+ // The column budget depends only on the TERMINAL, never on the banner — a
+ // banner takes rows, not columns — so it is derived from a base layout here and
+ // stays put while a notice appears and disappears above the list.
+ const providerCells = providerCellsFor(deriveDialogLayout(width, height).inner, list.fallback);
+ const column = useMemo(
+ () => providerColumn(providers.roster, truncate, providerCells),
+ [providers.roster, providerCells]
+ );
+ /** Provider → its WHOLE display name, for the filter and the detail line. */
+ const labels = useMemo(
+ () => new Map(providers.roster.map((r) => [r.value, r.label])),
+ [providers.roster]
+ );
+ /** Provider → what it IS: how it bills, and the credential it wants. */
+ const facts = useMemo(
+ () => new Map<string, ProviderFacts>(providers.roster.map((r) => [r.value, factsOf(r)])),
+ [providers.roster]
+ );
+
const shown = useMemo(() => {
const needle = filter.trim().toLowerCase();
if (!needle) return list.rows;
- // The provider shortcut is matched too, which is how provider scoping survives
- // the rail's deletion: typing `kc` narrows to Kimi Coding in three keystrokes.
+ // THREE THINGS MATCH, and the readable NAME is one of them — the column now
+ // prints `OpenRouter`, so typing `openr` must narrow to it or the filter
+ // contradicts the screen. The shortcut still matches (`kc` reaches Kimi
+ // Coding in three keystrokes, which is how provider scoping survived the
+ // rail's deletion) and so does the model id.
return list.rows.filter(
(r) =>
- r.model.id.toLowerCase().includes(needle) || r.shortcut.toLowerCase().startsWith(needle)
+ r.model.id.toLowerCase().includes(needle) ||
+ r.shortcut.toLowerCase().startsWith(needle) ||
+ (labels.get(r.provider) ?? "").toLowerCase().includes(needle)
);
- }, [list.rows, filter]);
+ }, [list.rows, filter, labels]);
// ── in-flight affordances ───────────────────────────────────────────────────
- const busy = providers.probing || catalog.phase !== "ready" || discovery.busy;
+ const busy = providers.probing || catalog.phase !== "ready" || discovery.busy || rosters.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,
roster:
discovery.busy && scope !== null
? {
@@ -238,7 +320,13 @@ export function ModelPicker({ source, onDone, onDiscoveryFailure }: ModelPickerP
? 0
: noticeRows(notice, Math.max(8, base.inner - 2), MAX_BANNER_ROWS).lines.length;
const layout = deriveDialogLayout(width, height, bannerRows);
- const rowLayout = deriveRowLayout(layout.inner, { mark: list.fallback });
+ // `column.cells`, not `providerCells`: a collision may have WIDENED the column
+ // past what the row budgeted, and the header and the rows must agree whichever
+ // number won.
+ const rowLayout = deriveRowLayout(layout.inner, {
+ mark: list.fallback,
+ providerCells: column.cells,
+ });
// The cursor can outlive the list it indexed — a filter keystroke, or a scope
// whose roster came back shorter than the last one's.
@@ -394,231 +482,365 @@ export function ModelPicker({ source, onDone, onDiscoveryFailure }: ModelPickerP
if (view === "custom") {
return (
- <Dialog
- key="custom"
- title="type a model spec"
- status="provider@model"
- width={layout.width}
- marginLeft={layout.marginLeft}
- >
- <box height={1} flexShrink={0}>
- <text>
- <span fg={tokens.accent}>{"› "}</span>
- <span fg={tokens.text}>{custom}</span>
- <span fg={tokens.accent}>▍</span>
- </text>
- </box>
- <box height={1} flexShrink={0}>
- <text>
- <span fg={tokens.subtle}>
- {"e.g. or@openai/gpt-5, kc@kimi-k3, [email protected] — anything argv accepts"}
- </span>
- </text>
- </box>
- <Rule />
- <Hints
- hints={[
- { key: "⏎", label: "launch it", on: custom.trim() !== "" },
- { key: "esc", label: "back" },
- ]}
- />
- </Dialog>
+ <Centred width={width} height={height}>
+ <Dialog
+ key="custom"
+ title="type a model spec"
+ status="provider@model"
+ width={layout.width}
+ marginLeft={0}
+ >
+ <box height={1} flexShrink={0}>
+ <text>
+ <span fg={tokens.accent}>{"› "}</span>
+ <span fg={tokens.text}>{custom}</span>
+ <span fg={tokens.accent}>▍</span>
+ </text>
+ </box>
+ <box height={1} flexShrink={0}>
+ <text>
+ <span fg={tokens.subtle}>
+ {"e.g. or@openai/gpt-5, kc@kimi-k3, [email protected] — anything argv accepts"}
+ </span>
+ </text>
+ </box>
+ <Rule />
+ <Hints
+ hints={[
+ { key: "⏎", label: "launch it", on: custom.trim() !== "" },
+ { key: "esc", label: "back" },
+ ]}
+ />
+ </Dialog>
+ </Centred>
);
}
if (view === "providers") {
const readyCount = providers.ready.length;
- // Two rows taller than the model list: this dialog spends no column header
- // and no selection line, so the rows it saves go back to the rows.
+ // 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;
return (
- <Dialog
- key="providers"
- title="providers"
- status={`${readyCount} of ${providers.total} have credentials`}
- width={layout.width}
- marginLeft={layout.marginLeft}
- >
- {providerWindow.map((r) => (
- <ProviderRow
- key={r.value}
- label={r.label}
- shortcut={r.shortcut}
- readiness={r.readiness}
- billing={r.billing}
- count={catalog.counts.get(r.value) ?? null}
- hasDiscovery={r.hasDiscovery}
- note={r.envVar === "" ? "needs sign-in" : `needs ${r.envVar}`}
- cursor={r.value === providers.rows[providerCursor]?.value}
- inner={layout.inner}
- />
- ))}
- {/* 31 providers do not fit in eleven rows, and a list that silently stops at
- twelve is the same unexplained absence this feature exists to remove. */}
- <HintRow
- text={
- providers.rows.length > providerWindow.length
- ? `${providerCursor + 1} of ${providers.rows.length} — ↑↓ for more`
- : ""
- }
- width={layout.inner}
- />
- {providers.notEnabledLocal.length > 0 ? (
+ <Centred width={width} height={height}>
+ <Dialog
+ key="providers"
+ title="providers"
+ status={`${readyCount} of ${providers.total} have credentials`}
+ 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. */}
<HintRow
- text={`${providers.notEnabledLocal.join(", ")} — local, not enabled in your config`}
+ text={
+ providers.rows.length > providerWindow.length
+ ? `${providerCursor + 1} of ${providers.rows.length} — ↑↓ for more`
+ : ""
+ }
width={layout.inner}
/>
- ) : null}
- <Rule />
- <Hints
- hints={[
- { key: "↑↓", label: "move" },
- { key: "⏎", label: "show only this provider" },
- { key: "esc", label: "back to all models" },
- ]}
- />
- </Dialog>
+ {providers.notEnabledLocal.length > 0 ? (
+ <HintRow
+ text={`${providers.notEnabledLocal.join(", ")} — local, not enabled in your config`}
+ width={layout.inner}
+ />
+ ) : null}
+ <Rule />
+ {/* The SAME line the model list carries, plus the count — so "what is
+ this provider" has one answer wherever it is asked. */}
+ <ProviderLine
+ facts={here === null ? null : factsOf(here)}
+ width={layout.inner}
+ count={here === null ? null : (catalog.counts.get(here.value) ?? null)}
+ />
+ <Hints
+ hints={[
+ { key: "↑↓", label: "move" },
+ { key: "⏎", label: "show only this provider" },
+ { key: "esc", label: "back to all models" },
+ ]}
+ />
+ </Dialog>
+ </Centred>
);
}
if (phase === "loading") {
return (
- <Dialog
- key="loading"
- title={scope === null ? "choose a model" : scopedName}
- status="finding models…"
- width={layout.width}
- marginLeft={layout.marginLeft}
- >
- <LoadTasks
- tasks={tasks}
- frame={frame}
- labelWidth={14}
- barWidth={Math.max(8, Math.min(22, layout.inner - 40))}
- />
- <box height={1} flexShrink={0}>
- <text>
- <span fg={tokens.trace}>models appear as soon as they are ready</span>
- </text>
- </box>
- <Rule />
- <Hints hints={[{ key: "esc", label: "cancel" }]} />
- </Dialog>
+ <Centred width={width} height={height}>
+ <Dialog
+ key="loading"
+ title={scope === null ? "choose a model" : scopedName}
+ status="finding models…"
+ width={layout.width}
+ marginLeft={0}
+ >
+ <LoadTasks
+ tasks={tasks}
+ frame={frame}
+ labelWidth={14}
+ barWidth={Math.max(8, Math.min(22, layout.inner - 40))}
+ />
+ <box height={1} flexShrink={0}>
+ <text>
+ <span fg={tokens.trace}>models appear as soon as they are ready</span>
+ </text>
+ </box>
+ <Rule />
+ <Hints hints={[{ key: "esc", label: "cancel" }]} />
+ </Dialog>
+ </Centred>
);
}
+ // THE COUNT IS COMPUTED THE WAY IT IS LABELLED, and the two views count
+ // differently because their rows mean different things. The flat list holds one
+ // row per ROUTE — a model on three providers is three rows — so calling that
+ // number "models" would be a claim about the catalog that is off by the exact
+ // amount the list is useful. Both numbers are printed: the models are what the
+ // reader is choosing between, the routes are why the same name appears twice. A
+ // provider view has one route in scope, so its rows ARE models and it says so.
const status =
scope === null
- ? `${list.rows.length} models · ${providers.ready.length}/${providers.total} providers`
+ ? `${countModels(list.rows)} models · ${list.rows.length} routes · ${providers.ready.length}/${providers.total} providers`
: (notice?.title ?? `${list.rows.length} models`);
return (
- <Dialog
- key="models"
- title={scope === null ? "choose a model" : scopedName}
- status={status}
- width={layout.width}
- marginLeft={layout.marginLeft}
- >
- {/* The banner sits ABOVE the rows it qualifies, never below them: the eye
- goes to the list, and a warning under a healthy-looking list is a warning
- nobody reads. That is the user's own report, verbatim. */}
- {discovery.outcome === null ? null : (
- <DiscoveryNotice
- outcome={discovery.outcome}
- displayName={scopedName}
- width={Math.max(8, layout.inner - 2)}
- maxRows={MAX_BANNER_ROWS}
- />
- )}
-
- <FilterRow
- value={filter}
- matches={shown.length}
- total={list.rows.length}
- width={layout.inner}
- />
- <ColumnHeader layout={rowLayout} />
-
- {/* CONTENT-SIZED, CAPPED — never `flexGrow`. A four-row Kimi fallback makes a
- short dialog; it does not make a tall dialog with fifteen rows of unpainted
- background in it, which is what the rejected full-screen build did and what
- the reader read as "this provider has nothing". The cap is `listRows`, and
- the banner's rows have already come out of it, so the box is bounded above
- in every state. */}
- <box
- flexDirection="column"
- height={Math.min(layout.listRows, Math.max(1, window.length))}
- flexShrink={0}
- overflow="hidden"
+ <Centred width={width} height={height}>
+ <Dialog
+ key="models"
+ title={scope === null ? "choose a model" : scopedName}
+ status={status}
+ width={layout.width}
+ marginLeft={0}
>
- {window.length === 0 ? (
- <EmptyState
- label={emptyLabel(list.loading, filter, list.rows.length, scopedName, providers)}
- {...(filter === "" ? {} : { hint: "esc clears the filter" })}
+ {/* The banner sits ABOVE the rows it qualifies, never below them: the eye
+ goes to the list, and a warning under a healthy-looking list is a warning
+ nobody reads. That is the user's own report, verbatim. */}
+ {discovery.outcome === null ? null : (
+ <DiscoveryNotice
+ outcome={discovery.outcome}
+ displayName={scopedName}
+ width={Math.max(8, layout.inner - 2)}
+ maxRows={MAX_BANNER_ROWS}
/>
- ) : (
- window.map((r, i) => (
- <ModelRow
- key={r.spec}
- model={r.model}
- shortcut={r.shortcut}
- price={r.price}
- layout={rowLayout}
- cursor={top + i === cursor}
- origin={list.fallback ? "catalog" : "roster"}
- />
- ))
)}
- </box>
-
- {/* ONE status row, ALWAYS rendered — see `CHROME_ROWS`. It carries the
- scroll position when the list overflows, the pending sweep when work is
- still in flight behind a usable list ("models appear as soon as they are
- ready" is a promise the screen has to keep), and nothing otherwise. */}
- <HintRow text={statusRow(cursor, shown.length, window.length, tasks)} width={layout.inner} />
-
- <Rule />
- <SelectionLine
- model={selected?.model ?? null}
- spec={selected?.spec ?? null}
- width={layout.inner}
- />
- <Hints
- hints={[
- { key: "↑↓", label: "move" },
- { key: "⏎", label: "select" },
- { 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" },
- ]}
- />
- </Dialog>
+
+ <FilterRow
+ value={filter}
+ matches={shown.length}
+ total={list.rows.length}
+ width={layout.inner}
+ />
+ <ColumnHeader layout={rowLayout} />
+
+ {/* CONTENT-SIZED, CAPPED — never `flexGrow`. A four-row Kimi fallback makes a
+ short dialog; it does not make a tall dialog with fifteen rows of unpainted
+ background in it, which is what the rejected full-screen build did and what
+ the reader read as "this provider has nothing". The cap is `listRows`, and
+ the banner's rows have already come out of it, so the box is bounded above
+ in every state. */}
+ <box
+ flexDirection="column"
+ height={Math.min(layout.listRows, Math.max(1, window.length))}
+ flexShrink={0}
+ overflow="hidden"
+ >
+ {window.length === 0 ? (
+ <EmptyState
+ label={emptyLabel(list.loading, filter, list.rows.length, scopedName, providers)}
+ {...(filter === "" ? {} : { hint: "esc clears the filter" })}
+ />
+ ) : (
+ window.map((r, i) => (
+ <ModelRow
+ key={r.spec}
+ model={r.model}
+ providerLabel={column.text.get(r.provider) ?? r.shortcut}
+ price={r.price}
+ layout={rowLayout}
+ cursor={top + i === cursor}
+ origin={list.fallback ? "catalog" : "roster"}
+ />
+ ))
+ )}
+ </box>
+
+ {/* ONE status row, ALWAYS rendered — see `CHROME_ROWS`. It carries the
+ scroll position when the list overflows, 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. */}
+ <HintRow
+ text={statusRow(cursor, shown.length, window.length, tasks, rosters.failures.length)}
+ width={layout.inner}
+ />
+
+ <Rule />
+ <SelectionLine
+ model={selected?.model ?? null}
+ spec={selected?.spec ?? null}
+ width={layout.inner}
+ />
+ <ProviderLine
+ facts={selected === null ? null : (facts.get(selected.provider) ?? null)}
+ width={layout.inner}
+ />
+ <DescriptionBlock
+ text={
+ selected === null ? "" : descriptionOf(selected, descriptions.get.bind(descriptions))
+ }
+ width={layout.inner}
+ />
+ <Hints
+ hints={[
+ { key: "↑↓", label: "move" },
+ { key: "⏎", label: "select" },
+ { 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",
+ },
+ ]}
+ />
+ </Dialog>
+ </Centred>
+ );
+}
+
+/**
+ * The full-height flex root that puts the dialog in the MIDDLE of the terminal.
+ *
+ * "why we not showing provider first and let show it in a middle of the screen".
+ * The dialog used to be pinned to row one with the rest of a 45-row terminal
+ * painted black below it, which is what "inline" bought — and it bought nothing,
+ * because `CliRendererConfig` at `@opentui/[email protected]` has no `height` key, so
+ * the renderer is sized to `stdout.rows` in `main-screen` mode exactly as it is in
+ * the alternate screen. The region was always the whole terminal; only the dialog
+ * was at the top.
+ *
+ * FLEXBOX, NOT SPACER BOXES. `justifyContent="center"` on a column root centres it
+ * vertically and `alignItems="center"` horizontally, so neither axis needs the
+ * margin arithmetic the previous build did by hand — and both re-centre on a
+ * resize with no code at all. The dialog is a fixed-width, content-height flex
+ * item, which is what makes it centre rather than stretch.
+ */
+function Centred({
+ width,
+ height,
+ children,
+}: {
+ width: number;
+ height: number;
+ children: ReactNode;
+}): ReactNode {
+ return (
+ <box
+ flexDirection="column"
+ width={Math.max(1, Math.floor(width))}
+ height={Math.max(1, Math.floor(height))}
+ justifyContent="center"
+ alignItems="center"
+ >
+ {children}
+ </box>
);
}
+/**
+ * The prose sentence for a row, or `""`.
+ *
+ * `catalogModelToModelInfo` substitutes `"<provider> model"` when the catalog has
+ * no description, which every slim-catalog row hits — so a raw `model.description`
+ * would print `unknown model` under half the list. The real index is tried first
+ * and the placeholder is filtered out, because a blank line is honest and
+ * `unknown model` is not.
+ */
+export function descriptionOf(
+ row: { model: ModelInfo },
+ lookup: (id: string) => string | undefined
+): string {
+ const found = lookup(row.model.id);
+ if (found !== undefined && found !== "") return found;
+ const own = (row.model.description ?? "").trim();
+ return own === "" || /^\S+ model$/i.test(own) ? "" : own;
+}
+
+/**
+ * How many DISTINCT models a list of rows covers.
+ *
+ * Exported so the title's arithmetic can be asserted: `N models · M routes` is
+ * only honest if the two numbers are computed differently, and a regression that
+ * made them equal would be invisible on a screenshot of a roster where no model
+ * happens to be served twice.
+ */
+export function countModels(rows: readonly { model: ModelInfo }[]): number {
+ return new Set(rows.map((r) => r.model.id)).size;
+}
+
+/** A roster entry as the facts the detail line prints. Derived, never a table. */
+function factsOf(choice: PickerProviderChoice): ProviderFacts {
+ return {
+ label: choice.label,
+ shortcut: choice.shortcut,
+ billing: choice.billing,
+ envVar: choice.envVar,
+ };
+}
+
/** The banner's half of the inline row budget. */
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 nothing.
+ * longer than the window, then what is still loading, then which providers could
+ * not be listed, 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.
*
- * Pure so the priority can be asserted. The scroll position wins over the pending
- * sweep because it changes on every keypress and the sweep changes once.
+ * 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.
*/
export function statusRow(
cursor: number,
shown: number,
visible: number,
- tasks: LoadTask[]
+ tasks: LoadTask[],
+ rosterFailures = 0
): 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 "";
}
diff --git a/packages/cli/src/picker/PickerDataSource.ts b/packages/cli/src/picker/PickerDataSource.ts
index e5b9d19e..e2a9b541 100644
--- a/packages/cli/src/picker/PickerDataSource.ts
+++ b/packages/cli/src/picker/PickerDataSource.ts
@@ -41,14 +41,17 @@ import { isSubscriptionProvider } from "../handlers/shared/remote-provider-types
import {
type ModelInfo,
type PickerDiscoveryOutcome,
+ type PreloadedRoster,
buildDiscoveredModelOutcome,
buildProviderChoices,
+ preloadProviderRoster,
providerShortcut,
servedModelsForProvider,
} from "../model-selector.js";
import { isLocalProviderEnabled } from "../profile-config.js";
import { ensureCatalogReady } from "../providers/catalog-client.js";
import { createCatalogClient } from "../providers/model-catalog.js";
+import { type DescriptionIndex, loadModelDescriptions } from "../providers/model-descriptions.js";
import { getAllProviders, getProviderByName } from "../providers/provider-definitions.js";
/** How a provider bills — the row's tag, and the reason a price may be absent. */
@@ -103,6 +106,18 @@ 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.
+ */
+ descriptions(): Promise<DescriptionIndex>;
}
/** How a provider bills, from the two oracles that already answer it. */
@@ -225,5 +240,13 @@ export function createPickerDataSource(): PickerDataSource {
discoverRoster(provider: string): Promise<PickerDiscoveryOutcome> {
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/chrome.tsx b/packages/cli/src/picker/chrome.tsx
index 9337af08..a3417465 100644
--- a/packages/cli/src/picker/chrome.tsx
+++ b/packages/cli/src/picker/chrome.tsx
@@ -17,9 +17,10 @@
import type { ReactNode } from "react";
import { LoadingRow } from "../tui/components/LoadingRow.js";
-import { A, C } from "../tui/theme.js";
+import { C } from "../tui/theme.js";
import { displayWidth, truncate } from "../tui/viz/text.js";
import { tokens } from "../tui/viz/tokens.js";
+import { BadgeSpan } from "../tui/viz/widgets.js";
/**
* The bordered box, with its title composed left-and-right on the border line.
@@ -155,22 +156,46 @@ export interface Hint {
}
/**
- * Keyboard hints as two-tone pairs — the `Footer.tsx:179-198` idiom, where the
- * colour slot is deliberately ignored and emphasis is BRIGHTNESS rather than hue.
- * Hue is spent on severity everywhere else in this program; spending it here too
- * would make the footer compete with the failure banner.
+ * Keyboard hints as KEYCAPS — a badge per key, then its label in dim text.
*
- * Every action is one key and every key is listed. No deep menus, nothing
- * discoverable only by trying it.
+ * THE BADGE IS THE HOUSE PATTERN FOR A DISCRETE TOKEN: dark ink on a saturated
+ * fill, one space of padding each side (`aesthetics-and-color.md`). Bold white
+ * text on the panel background, which is what this row used to be, is the same
+ * treatment the model ids two rows above get — so `p` in `p providers` read as a
+ * word rather than as a key you press, which is exactly what the owner said when
+ * he asked for "better button highlighting".
+ *
+ * `BadgeSpan`, NOT `Badge`: one `<text>` per hint carries both the chip and its
+ * label, and a `<text>` cannot nest in a `<text>`.
+ *
+ * ONE FILL FOR EVERY KEYCAP, AND IT IS THE ONE THIS PROGRAM ALREADY USES.
+ * `C.chipKeyBg` is the config TUI's footer chip (`Footer.tsx:186-190` — neutral
+ * grey, `C.fg` ink, bold, one space each side), so the picker's footer is the same
+ * object as every other footer in claudish rather than a second invention. It is
+ * deliberately NOT a saturated hue: every hue in this dialog already means one
+ * thing — `FREE` success, `SUB` warn, `catalog` warn, errors red, focus accent —
+ * and borrowing one for the footer would put the quietest row on screen in
+ * competition with the failure banner. A keycap reads as a key because of its
+ * SHAPE, a filled chip with padding; the fill's job is to be neutral.
+ *
+ * `pickInk` chooses the ink from the fill rather than hardcoding white, which is
+ * what keeps the chip legible in the light palette, where `chipKeyBg` is `#d1d5db`
+ * and white ink would vanish.
+ *
+ * AN UNAVAILABLE ACTION LOSES THE CHIP RATHER THAN BEING HIDDEN — dim text, no
+ * fill, so "there is a key here but not now" is visibly different from both a live
+ * key and an absent one. Every action is one key and every key is here.
*/
export function Hints({ hints }: { hints: Hint[] }): ReactNode {
return (
- <box flexDirection="row" height={1} gap={2} flexShrink={0} overflow="hidden">
+ <box flexDirection="row" height={1} gap={1} flexShrink={0} overflow="hidden">
{hints.map((h) => (
- <text key={h.key}>
- <span fg={h.on === false ? tokens.trace : C.strong} attributes={A.boldIf(h.on !== false)}>
- {h.key}
- </span>
+ <text key={h.key} flexShrink={0}>
+ {h.on === false ? (
+ <span fg={tokens.trace}>{` ${h.key} `}</span>
+ ) : (
+ <BadgeSpan label={h.key} bg={C.chipKeyBg} />
+ )}
<span fg={h.on === false ? tokens.trace : tokens.subtle}>{` ${h.label}`}</span>
</text>
))}
diff --git a/packages/cli/src/picker/detail.tsx b/packages/cli/src/picker/detail.tsx
index 43367ccc..5a851688 100644
--- a/packages/cli/src/picker/detail.tsx
+++ b/packages/cli/src/picker/detail.tsx
@@ -1,6 +1,7 @@
/** @jsxImportSource @opentui/react */
/**
- * picker/detail.tsx — the one row under the list that says what Enter will do.
+ * picker/detail.tsx — the pane under the list that says what Enter will do, what
+ * the provider IS, and what the model IS.
*
* IT ANSWERS THE QUESTION A PICKER MUST NEVER LEAVE OPEN: what EXACTLY does Enter
* return? It prints the spec verbatim — `[email protected]`, the same string
@@ -8,12 +9,25 @@
* have typed on argv — so the picker teaches its own CLI instead of hiding behind
* a private label.
*
- * ONE ROW, NOT THREE. The previous build pinned a description block under each of
- * its two lists. Descriptions are per-model editorial text that the slim catalog
- * mostly does not carry, and two rows of prose cost two rows of list on a dialog
- * whose whole list is eleven rows. What survives is the three facts that differ
- * between models a reader is choosing BETWEEN: the exact spec, the capabilities,
- * and how old it is.
+ * THEN TWO THINGS THE LIST CANNOT SAY, BOTH ADDED BECAUSE THE OWNER ASKED FOR THEM
+ * BY NAME:
+ *
+ * · **What the provider is.** "we need add more details about provider — now it
+ * has no sense, like what is 'or' means". A row now carries the readable name;
+ * this line carries the rest of the answer — how it bills (a flat-rate plan
+ * charges nothing per token, which is the single most decision-relevant fact
+ * about a route) and which credential it authenticates with, named exactly, so
+ * a reader can go and check the variable rather than guess at it. Every field
+ * comes from `ProviderDefinition` through `PickerProviderChoice`; nothing here
+ * is a table.
+ * · **What the model is.** The old inquirer picker printed the catalog's prose
+ * sentence under the highlighted row and the new dialog dropped it, leaving
+ * `spec · capabilities · date` — four facts about a model's shape and none
+ * about its purpose. It is back, wrapped to the dialog and capped at
+ * `DESCRIPTION_ROWS`. The slim catalog carries no description (0 of 704
+ * entries), so it arrives on its own clock from `providers/model-descriptions`
+ * and the rows are rendered blank until it does — never collapsed, or every
+ * row below would jump when it lands.
*
* CAPABILITIES ARE EXCEPTION-ONLY AND THEY LIVE HERE, NOT ON EVERY ROW. The
* previous build printed `[TRV]` on all 21 rows of a roster where every model had
@@ -26,6 +40,9 @@ import type { ModelInfo } from "../model-selector.js";
import { A } from "../tui/theme.js";
import { truncate } from "../tui/viz/text.js";
import { tokens } from "../tui/viz/tokens.js";
+import { wrapWords } from "./DiscoveryNotice.js";
+import type { BillingMode } from "./PickerDataSource.js";
+import { DESCRIPTION_ROWS } from "./layout.js";
/**
* `tools reasoning vision`, and ONLY the ones the catalog affirmatively says are
@@ -63,6 +80,44 @@ export function detailText(spec: string, model: ModelInfo): { text: string; warn
};
}
+/** What a provider IS, in one row: how it bills and what it authenticates with. */
+export interface ProviderFacts {
+ label: string;
+ shortcut: string;
+ billing: BillingMode;
+ /** The env var it reads. Empty for a provider that signs in instead. */
+ envVar: string;
+}
+
+/**
+ * The words for a provider, as one pure function.
+ *
+ * BILLING LEADS, because it is the fact that changes a decision: a flat-rate plan
+ * costs nothing at the point of use, which is why `SUB` rows are worth finding and
+ * why the row above prints `SUB` rather than a per-token number it does not have.
+ * The credential comes second, named exactly — "check your API key" gives no clue
+ * which of thirty variables to inspect, and a key shadowed by a stale value in the
+ * shell is the single most common cause of a rejected provider in this repo's
+ * issue history.
+ */
+export function providerFactsText(facts: ProviderFacts): {
+ billing: string;
+ /** The same claim in the fewest words, for a row that cannot afford the sentence. */
+ billingShort: string;
+ auth: string;
+} {
+ const billing =
+ facts.billing === "sub"
+ ? "flat-rate subscription — no per-token charge"
+ : facts.billing === "local"
+ ? "runs on this machine — no charge, no network"
+ : "metered — billed per token";
+ const billingShort =
+ facts.billing === "sub" ? "flat-rate plan" : facts.billing === "local" ? "local" : "metered";
+ const auth = facts.envVar === "" ? "signs in — no API key variable" : facts.envVar;
+ return { billing, billingShort, auth };
+}
+
export function SelectionLine({
model,
spec,
@@ -100,3 +155,122 @@ export function SelectionLine({
</box>
);
}
+
+/**
+ * One row: which provider this is, how it bills, what key it wants.
+ *
+ * ALWAYS ONE ROW, blank when nothing is selected, because the list above is
+ * content-sized and a detail pane that collapsed would move every row on the
+ * screen each time the cursor left the last item.
+ */
+export function ProviderLine({
+ facts,
+ width,
+ /** Models this provider serves. `null` in the model list, a number in the `p` dialog. */
+ count = null,
+}: {
+ facts: ProviderFacts | null;
+ width: number;
+ count?: number | null;
+}): ReactNode {
+ const inner = Math.max(8, Math.floor(width));
+ if (facts === null) {
+ return (
+ <box height={1} flexShrink={0}>
+ <text>
+ <span fg={tokens.trace}> </span>
+ </text>
+ </box>
+ );
+ }
+ const { billing, billingShort, auth } = providerFactsText(facts);
+ const billingFg =
+ facts.billing === "sub"
+ ? tokens.warn
+ : facts.billing === "local"
+ ? tokens.trace
+ : tokens.subtle;
+ const tail = count === null ? "" : ` · ${count} model${count === 1 ? "" : "s"}`;
+ // THE VARIABLE NAME IS NEVER THE FIELD THAT GIVES WAY, and the BILLING CLAUSE
+ // is. A truncated env var (`OPENCODE_GO…`) sends the reader hunting for a
+ // variable that does not exist — this dialog shipped that defect once already —
+ // and a dangling ` · ` with nothing after it is the same lie with worse manners.
+ // MEASURED at 80 columns: the long sentence plus `OPENCODE_GO_API_KEY` is 71 of
+ // 72 usable cells, so the short form is not a fallback for freak widths, it is
+ // what 80 columns gets. Both forms make the same claim.
+ const name = truncate(facts.label, Math.max(4, inner - 12));
+ const fixed = name.length + facts.shortcut.length + 1 + 3 + 3 + auth.length + tail.length;
+ const clause = fixed + billing.length <= inner ? billing : billingShort;
+ const room = Math.max(0, inner - (fixed - auth.length) - clause.length);
+ const shown = truncate(auth, room);
+ return (
+ <box height={1} flexShrink={0}>
+ <text>
+ <span fg={tokens.text}>{name}</span>
+ <span fg={tokens.trace}>{` ${facts.shortcut}`}</span>
+ <span fg={tokens.subtle}>{" · "}</span>
+ <span fg={billingFg}>{clause}</span>
+ {shown === "" ? null : (
+ <>
+ <span fg={tokens.subtle}>{" · "}</span>
+ <span fg={tokens.subtle}>{shown}</span>
+ </>
+ )}
+ {tail === "" ? null : <span fg={tokens.trace}>{tail}</span>}
+ </text>
+ </box>
+ );
+}
+
+/**
+ * The catalog's prose sentence for the selected model, wrapped and capped.
+ *
+ * FIXED HEIGHT, ALWAYS RENDERED. The sentence arrives on its own clock — the slim
+ * catalog carries none, so it comes from a bulk fetch that resolves seconds after
+ * the list is already usable — and a block that grew from zero rows to two when it
+ * landed would shove the footer down under the reader's cursor.
+ *
+ * TRUNCATED WITH AN ELLIPSIS AT THE CAP rather than scrolled: a description is
+ * orientation, not documentation, and the models that carry a 1 183-character one
+ * are describing an API, not answering "is this the model I want".
+ */
+export function descriptionLines(text: string, width: number, rows = DESCRIPTION_ROWS): string[] {
+ const inner = Math.max(8, Math.floor(width));
+ const cap = Math.max(1, Math.floor(rows));
+ const clean = text.replace(/\s+/g, " ").trim();
+ if (clean === "") return [];
+ const wrapped = wrapWords(clean, inner);
+ if (wrapped.length <= cap) return wrapped;
+ const kept = wrapped.slice(0, cap);
+ const last = kept[cap - 1] ?? "";
+ // `truncate` puts the ellipsis in the last column, so shave a column first —
+ // otherwise the row is one cell over budget and Yoga claws it back somewhere.
+ kept[cap - 1] = truncate(`${last} ${wrapped.slice(cap).join(" ")}`, inner);
+ return kept;
+}
+
+export function DescriptionBlock({
+ text,
+ width,
+ rows = DESCRIPTION_ROWS,
+}: {
+ /** Empty while the index is still loading, or when the catalog has no sentence. */
+ text: string;
+ width: number;
+ rows?: number;
+}): ReactNode {
+ const lines = descriptionLines(text, width, rows);
+ const cap = Math.max(1, Math.floor(rows));
+ return (
+ <box flexDirection="column" height={cap} flexShrink={0} overflow="hidden">
+ {Array.from({ length: cap }, (_, i) => (
+ // biome-ignore lint/suspicious/noArrayIndexKey: a wrapped row is position-addressed — its index IS its identity
+ <box key={i} height={1} flexShrink={0}>
+ <text>
+ <span fg={tokens.subtle}>{lines[i] ?? " "}</span>
+ </text>
+ </box>
+ ))}
+ </box>
+ );
+}
diff --git a/packages/cli/src/picker/fixtures/fixture-source.ts b/packages/cli/src/picker/fixtures/fixture-source.ts
index 6ce19416..bb981815 100644
--- a/packages/cli/src/picker/fixtures/fixture-source.ts
+++ b/packages/cli/src/picker/fixtures/fixture-source.ts
@@ -29,7 +29,8 @@
* and a live capture beats a forged one every time. The scenario exists as a control.
*/
-import type { ModelInfo, PickerDiscoveryOutcome } from "../../model-selector.js";
+import type { ModelInfo, PickerDiscoveryOutcome, PreloadedRoster } from "../../model-selector.js";
+import type { DescriptionIndex } from "../../providers/model-descriptions.js";
import {
type PickerDataSource,
type PickerProviderChoice,
@@ -93,6 +94,32 @@ 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.
+ return scenario === "loading" ? NEVER : real.descriptions();
+ },
+
async discoverRoster(provider: string): Promise<PickerDiscoveryOutcome> {
if (scenario === "loading") return NEVER;
if (!forced) return real.discoverRoster(provider);
diff --git a/packages/cli/src/picker/hooks/useModelDescriptions.ts b/packages/cli/src/picker/hooks/useModelDescriptions.ts
new file mode 100644
index 00000000..78e3e283
--- /dev/null
+++ b/packages/cli/src/picker/hooks/useModelDescriptions.ts
@@ -0,0 +1,44 @@
+/**
+ * useModelDescriptions — the catalog's prose sentence per model, on its own clock.
+ *
+ * IT IS DELIBERATELY THE LAST THING TO ARRIVE. The list is built from the slim
+ * catalog, which carries no `description` at all (0 of 704 entries on disk), so
+ * the sentence comes from a bulk fetch of the rich catalog — MEASURED at 2.8 s for
+ * all 1 016 active models, cached on disk for a day. Nothing waits for it: the
+ * rows are already usable, and a description is worth having on the row the cursor
+ * is on and worth nothing on a row nobody has looked at.
+ *
+ * `DescriptionIndex.size === 0` therefore means "not loaded yet", never "no model
+ * has one" — which is why the detail block renders blank rows rather than
+ * collapsing. A block that grew by two rows when this landed would shove the
+ * footer down under the reader's cursor, seconds after they started reading.
+ */
+
+import { useEffect, useState } from "react";
+import {
+ type DescriptionIndex,
+ emptyDescriptionIndex,
+} from "../../providers/model-descriptions.js";
+import type { PickerDataSource } from "../PickerDataSource.js";
+
+export function useModelDescriptions(source: PickerDataSource): DescriptionIndex {
+ const [index, setIndex] = useState<DescriptionIndex>(emptyDescriptionIndex);
+
+ useEffect(() => {
+ let live = true;
+ void source.descriptions().then(
+ (loaded) => {
+ if (live) setIndex(loaded);
+ },
+ () => {
+ // Documented never to reject; guarded anyway. A missing sentence must
+ // never be able to take the picker down.
+ }
+ );
+ return () => {
+ live = false;
+ };
+ }, [source]);
+
+ return index;
+}
diff --git a/packages/cli/src/picker/hooks/usePickerModels.ts b/packages/cli/src/picker/hooks/usePickerModels.ts
index 93cc1994..99eb0856 100644
--- a/packages/cli/src/picker/hooks/usePickerModels.ts
+++ b/packages/cli/src/picker/hooks/usePickerModels.ts
@@ -94,7 +94,14 @@ export function usePickerModels(
source: PickerDataSource,
roster: PickerProviderChoice[],
/** Providers whose credential probe came back true. */
- ready: ReadonlySet<string>
+ 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.
+ */
+ liveRows: ReadonlyMap<string, ModelInfo[]> = EMPTY_LIVE
): PickerModelsState {
const [phase, setPhase] = useState<LoadPhase>("loading");
const cache = useRef(new Map<string, PickerRow[]>());
@@ -131,16 +138,76 @@ export function usePickerModels(
cached = source.servedModels(choice.value).map((m) => toPickerRow(choice, m));
cache.current.set(choice.value, cached);
}
- // The COUNT is what the catalog serves, credentials or not — the provider
+ // THE LIVE ROSTER WINS AND THE CATALOG ROWS STAY, deduped by
+ // `(provider, modelId)`.
+ //
+ // The same model id under two DIFFERENT providers is two rows on purpose —
+ // that is the whole value of a cross-provider list, and the reason
+ // `gpt-6-astra` is worth seeing at $30.00 on `or@` beside `SUB` on `cx@`.
+ // This loop is per provider, so the dedupe below can only ever collapse the
+ // OVERLAP between one provider's live roster and its catalog entries. The
+ // live entry wins because it is what this account can actually call: the
+ // endpoint answered for THESE credentials, where the catalog answers for
+ // everyone.
+ const live = liveRows.get(choice.value);
+ const merged =
+ live === undefined || live.length === 0
+ ? dedupeByProviderModel(cached)
+ : dedupeByProviderModel([...live.map((m) => toPickerRow(choice, m)), ...cached]);
+ // The COUNT is what this provider offers, credentials or not — the provider
// dialog shows it beside `needs OPENAI_API_KEY`, and "0 models" there would
// read as "this provider has nothing" rather than "you have no key".
- counts.set(choice.value, cached.length);
- if (ready.has(choice.value)) rows.push(...cached);
+ counts.set(choice.value, merged.length);
+ if (ready.has(choice.value)) rows.push(...merged);
}
// Newest first, across providers. The same comparator the classic picker
// uses, so two lists of the same models cannot disagree about their order.
rows.sort((a, b) => compareByReleaseDateDesc(a.model, b.model));
return { rows, counts, phase };
// biome-ignore lint/correctness/useExhaustiveDependencies: `signature` is the stable projection of `ready`; depending on the Set itself rebuilds every frame
- }, [source, roster, phase, signature, ready]);
+ }, [source, roster, phase, signature, ready, liveRows]);
+}
+
+/** No live rosters yet — a shared empty map, so the memo's identity is stable. */
+const EMPTY_LIVE: ReadonlyMap<string, ModelInfo[]> = new Map();
+
+/**
+ * ROW IDENTITY DEPENDS ON THE VIEW, and the owner stated the rule directly: *"if
+ * model has more than one provider that going to be two lines in 'all models'
+ * list. and if we enter to provider catalog, not all models — then the model will
+ * be just one"*.
+ *
+ * · **The flat cross-provider list** keys on `(provider, modelId)`. A model on
+ * three providers is three rows, because the route and the billing differ and
+ * that difference IS the list's value — `gpt-6-astra` at `$30.00` on OpenRouter
+ * beside the same model as `SUB` on Codex.
+ * · **A provider-scoped list** keys on `modelId` alone. One route is in scope, so
+ * a second row of the same model would mean nothing.
+ *
+ * Both are spelled out rather than sharing one parameterised helper, because the
+ * two call sites are the two views and a reader should be able to see which rule
+ * each one applies without following a flag.
+ */
+export function dedupeByProviderModel(rows: PickerRow[]): PickerRow[] {
+ const seen = new Set<string>();
+ const out: PickerRow[] = [];
+ for (const row of rows) {
+ const key = `${row.provider}${row.model.id}`;
+ if (seen.has(key)) continue;
+ seen.add(key);
+ out.push(row);
+ }
+ return out;
+}
+
+/** One row per model id — the rule INSIDE one provider's catalog. */
+export function dedupeByModelId(rows: PickerRow[]): PickerRow[] {
+ const seen = new Set<string>();
+ const out: PickerRow[] = [];
+ for (const row of rows) {
+ if (seen.has(row.model.id)) continue;
+ seen.add(row.model.id);
+ out.push(row);
+ }
+ return out;
}
diff --git a/packages/cli/src/picker/hooks/usePreloadedRosters.ts b/packages/cli/src/picker/hooks/usePreloadedRosters.ts
new file mode 100644
index 00000000..836754f9
--- /dev/null
+++ b/packages/cli/src/picker/hooks/usePreloadedRosters.ts
@@ -0,0 +1,166 @@
+/**
+ * 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/layout.test.ts b/packages/cli/src/picker/layout.test.ts
index 8f8ef447..2185521d 100644
--- a/packages/cli/src/picker/layout.test.ts
+++ b/packages/cli/src/picker/layout.test.ts
@@ -84,16 +84,32 @@ describe("deriveRowLayout", () => {
});
describe("deriveDialogLayout", () => {
- test("the dialog fits 80x24 with room to spare, and does not grow at 145x45", () => {
+ test("the dialog FITS 80x24 and 145x45 — it is centred in the terminal, never clipped", () => {
const small = deriveDialogLayout(80, 24);
const large = deriveDialogLayout(145, 45);
expect(small.width).toBe(76);
expect(small.marginLeft).toBe(2);
- // Capped, not stretched: a picker is a question, not a viewport.
+ // Capped in WIDTH, not stretched: a picker is a question, not a viewport.
expect(large.width).toBe(MAX_DIALOG_WIDTH);
expect(large.marginLeft).toBeGreaterThan(2);
- expect(small.listRows).toBe(large.listRows);
- expect(small.listRows + CHROME_ROWS).toBeLessThanOrEqual(MAX_DIALOG_ROWS);
+ // It DOES grow in height with the terminal, and that is the change: the old
+ // fixed 18 rows existed to keep an "inline" region small, and inline never
+ // held — the renderer is sized to `stdout.rows` at this pin whatever the
+ // screen mode. Growth is bounded by the cap and by the terminal itself.
+ expect(large.listRows).toBeGreaterThan(small.listRows);
+ expect(small.listRows + CHROME_ROWS).toBeLessThanOrEqual(24);
+ expect(large.listRows + CHROME_ROWS).toBeLessThanOrEqual(MAX_DIALOG_ROWS);
+ expect(large.listRows + CHROME_ROWS).toBeLessThanOrEqual(45);
+ });
+
+ test("a centred dialog leaves air above and below at every height it can be drawn", () => {
+ // What makes a centred box read as centred. A dialog exactly as tall as the
+ // terminal is not centred, it is full-screen — which is the build that was
+ // rejected — and one taller than the terminal is clipped at both ends.
+ for (const h of [20, 24, 30, 45, 60]) {
+ const l = deriveDialogLayout(120, h);
+ expect(l.listRows + CHROME_ROWS).toBeLessThanOrEqual(h - 2);
+ }
});
test("a banner takes its rows OUT of the list, so the dialog height never changes", () => {
diff --git a/packages/cli/src/picker/layout.ts b/packages/cli/src/picker/layout.ts
index 33a29a6d..ef355dae 100644
--- a/packages/cli/src/picker/layout.ts
+++ b/packages/cli/src/picker/layout.ts
@@ -7,25 +7,48 @@
* full-width row is a column budget, and a budget that lives at its call site
* drifts between the header and the rows it labels.
*
- * THE MODEL ID IS THE ELASTIC CELL, and every other cell is fixed at every width.
- * That is the whole difference from the two-pane build this replaces, whose five
- * responsive tiers existed to keep a gradient meter on every row down to 44
- * columns. There is no meter now, so there is no ladder: the four fixed cells are
- * the four facts a reader chooses on (which provider, how much context, what it
- * costs, and whether the row is verified), and the name takes everything left.
- * One layout at 80 columns and at 145.
- *
- * THE DIALOG IS CONTENT-SIZED, NOT SCREEN-SIZED. It renders INLINE
- * (`screenMode: "main-screen"`), so its height is rows it actually occupies in the
- * user's scrollback rather than a viewport it has taken over — which is why the
- * row budget below caps at `MAX_DIALOG_ROWS` and does not grow with the terminal.
- * A 45-row terminal gets the same 18-row dialog as a 24-row one, with the extra
- * rows left to the shell. The unpainted-black-hole failure of the previous build
- * cannot occur here: a short list makes a short box.
+ * THE PROVIDER COMES FIRST AND IT IS SPELLED OUT. The column used to print the
+ * routing shortcut — `or@`, `oai@`, `cx@` — and the owner's question was exactly
+ * *"what is 'or' means"*. A routing shortcut is information only to someone who
+ * already knows it; it does not teach, it obscures. So the leftmost cell is the
+ * provider's readable display name (`OpenRouter`, `OpenAI Codex`, `Kimi /
+ * Moonshot`), the shortcut moves to the `p` dialog where it sits beside the name
+ * that explains it, and the exact routable spec stays on the detail line, which
+ * prints it in full.
+ *
+ * THE MODEL ID IS STILL THE ELASTIC CELL, and every other cell is fixed at every
+ * width. There is no responsive ladder: the four fixed cells are the four facts a
+ * reader chooses on (which provider, how much context, what it costs, and whether
+ * the row is verified) and the name takes everything left. One layout at 80
+ * columns and at 145.
+ *
+ * TWO DIFFERENT PROVIDERS MUST NEVER RENDER IDENTICALLY. That collision — two
+ * providers both drawn as `opencod…` — is what the previous provider rail was
+ * rejected for, and a readable name column can reproduce it (`OpenCode Zen` and
+ * `OpenCode Zen Go` share a twelve-character prefix). `providerColumn` therefore
+ * derives the width from the names actually on screen and widens until every one
+ * of them is distinct; `MIN_PROVIDER_CELLS` is set from the whole 31-provider
+ * roster, at which no pair collides.
+ *
+ * THE DIALOG IS CENTRED AND CONTENT-SIZED. It renders in `main-screen` mode, but
+ * `CliRendererConfig` at `@opentui/[email protected]` carries no `height` key — the
+ * renderer is sized to `stdout.rows` whatever the mode — so "inline" never meant a
+ * small region: the previous build simply pinned its dialog to the top and left
+ * the rest of a 45-row terminal black. It is now centred in a full-height flex
+ * root, vertically and horizontally, which is what the owner asked for and what
+ * the row budget below is sized against.
*/
-/** The widest routing shortcut in the roster (`mistral@`), so the column never elides. */
-const PROVIDER_CELLS = 8;
+/**
+ * The provider name column, and the bound that makes it collision-proof.
+ *
+ * MEASURED over the whole 31-provider roster: at 14 columns every display name
+ * truncates to a distinct string, and at 12 `OpenCode Zen` and `OpenCode Zen Go`
+ * collide. 14 is therefore the floor, not a taste. The cap keeps one long
+ * subscription name (`Grok Build (subscription)`, 25) from eating the model id.
+ */
+const MIN_PROVIDER_CELLS = 14;
+const MAX_PROVIDER_CELLS = 20;
/** `262K`, `1M`, `N/A`. */
const CTX_CELLS = 6;
/** `$30.00`, `FREE`, `SUB`, `local`, `N/A`. */
@@ -34,12 +57,21 @@ const PRICE_CELLS = 9;
const MARK_CELLS = 8;
/** `▶ ` / ` ` — the cursor gutter, which carries its own trailing space. */
const CURSOR_CELLS = 2;
-/** Air between the name and the provider column, and between the numeric columns. */
-const GAP_AFTER_ID = 4;
-const GAP_AFTER_PROVIDER = 4;
-const GAP_AFTER_CTX = 5;
+/** Air after the provider name, after the model id, and between the numerals. */
+const GAP_AFTER_PROVIDER = 2;
+const GAP_AFTER_ID = 3;
+const GAP_AFTER_CTX = 4;
/** Below this the name is no longer a name. */
const MIN_ID_CELLS = 10;
+/**
+ * The model id column the provider name is not allowed to eat into.
+ *
+ * MEASURED against the ids actually on screen: `deepseek-v4-flash-vision-exp` is
+ * 28 cells and `kimi-k2.7-code-highspeed` is 24, so 30 fits the long tail whole.
+ * Every column past this belongs to the provider name, which is why the column is
+ * 14 wide at 80 and 20 at 145 rather than a constant that is wrong at both.
+ */
+const COMFORTABLE_ID_CELLS = 30;
/**
* One model row's cells, left to right. Every number is COLUMNS, and they sum to
@@ -49,10 +81,10 @@ export interface RowLayout {
/** Total columns the row must paint, exactly. */
inner: number;
cursor: number;
+ /** The provider's readable display name, left-aligned. FIRST cell after the gutter. */
+ provider: number;
/** Model id, padded/truncated. Absorbs every column the fixed cells do not use. */
id: number;
- /** The routing shortcut, right-aligned: `or@`, `kc@`. */
- provider: number;
/** Context window numeral, right-aligned. */
ctx: number;
/** Price / `SUB` / `FREE` / `local`, right-aligned. */
@@ -70,25 +102,29 @@ export interface RowLayout {
* non-finite width gets a floor rather than NaN columns, because a NaN width
* reaches `padTo` as a zero-width cell — nothing painted, nothing thrown.
*/
-export function deriveRowLayout(inner: number, opts: { mark?: boolean } = {}): RowLayout {
+export function deriveRowLayout(
+ inner: number,
+ opts: { mark?: boolean; providerCells?: number } = {}
+): RowLayout {
const cells = Number.isFinite(inner) ? Math.max(0, Math.floor(inner)) : 0;
const mark = opts.mark === true ? MARK_CELLS : 0;
- const gaps = GAP_AFTER_ID + GAP_AFTER_PROVIDER + GAP_AFTER_CTX;
+ const gaps = GAP_AFTER_PROVIDER + GAP_AFTER_ID + GAP_AFTER_CTX;
// Everything except the elastic id. The mark carries no separator of its own —
// the price column is right-aligned, so the gap is already inside it.
- let provider = PROVIDER_CELLS;
+ let provider = clampProviderCells(opts.providerCells ?? MIN_PROVIDER_CELLS);
let ctx = CTX_CELLS;
let price = PRICE_CELLS;
let id = cells - (CURSOR_CELLS + provider + ctx + price + mark + gaps);
if (id < MIN_ID_CELLS) {
// Absurdly narrow. The columns give way in the order they are least missed:
- // the mark's padding first (it is a whole-list property the title also
- // states), then the provider column, then the price. Nothing here drops the
- // CONTEXT numeral or the name, because those two are the row.
+ // the provider name shrinks toward its collision-proof floor first, then the
+ // price. Nothing here drops the CONTEXT numeral or the name, because those
+ // two are the row — and the provider never goes below the floor, because a
+ // provider that cannot be told apart from another one is worse than absent.
const shortfall = MIN_ID_CELLS - id;
- const takeFromProvider = Math.min(provider, shortfall);
+ const takeFromProvider = Math.min(Math.max(0, provider - MIN_PROVIDER_CELLS), shortfall);
provider -= takeFromProvider;
const stillShort = shortfall - takeFromProvider;
const takeFromPrice = Math.min(Math.max(0, price - 4), stillShort);
@@ -99,60 +135,156 @@ export function deriveRowLayout(inner: number, opts: { mark?: boolean } = {}): R
// Narrower than the fixed cells themselves. Give the name what is left and
// let the row paint short rather than overflow, which Yoga would claw back
// from whichever cell it liked.
- ctx = Math.max(0, ctx + id);
+ const deficit = -id;
+ const fromProvider = Math.min(provider, deficit);
+ provider -= fromProvider;
+ ctx = Math.max(0, ctx - (deficit - fromProvider));
id = 0;
}
- return { inner: cells, cursor: CURSOR_CELLS, id, provider, ctx, price, mark, gaps };
+ return { inner: cells, cursor: CURSOR_CELLS, provider, id, ctx, price, mark, gaps };
+}
+
+function clampProviderCells(n: number): number {
+ const v = Number.isFinite(n) ? Math.floor(n) : MIN_PROVIDER_CELLS;
+ return Math.max(MIN_PROVIDER_CELLS, Math.min(MAX_PROVIDER_CELLS, v));
+}
+
+/**
+ * How many columns the provider NAME can afford at this row width.
+ *
+ * A constant would be wrong at both ends: 14 cells elides `OpenCode Zen Go` on a
+ * 145-column terminal that has 22 spare columns doing nothing, and 20 cells eats
+ * the model id at 80. So the floor is the collision-proof minimum and everything
+ * past a comfortable id column goes to the name, capped so one 25-character
+ * subscription name cannot take the row over.
+ */
+export function providerCellsFor(inner: number, mark = false): number {
+ const base = deriveRowLayout(inner, { mark });
+ return clampProviderCells(MIN_PROVIDER_CELLS + Math.max(0, base.id - COMFORTABLE_ID_CELLS));
}
/** Sum of every cell plus the separators — must equal `inner`. */
export function rowLayoutTotal(l: RowLayout): number {
- return l.cursor + l.id + l.provider + l.ctx + l.price + l.mark + l.gaps;
+ return l.cursor + l.provider + l.id + l.ctx + l.price + l.mark + l.gaps;
}
/** The separators, named so the renderer and the budget cannot disagree. */
export const GAPS = {
- afterId: GAP_AFTER_ID,
afterProvider: GAP_AFTER_PROVIDER,
+ afterId: GAP_AFTER_ID,
afterCtx: GAP_AFTER_CTX,
} as const;
+/**
+ * How wide the provider column must be for these names, and what each one prints.
+ *
+ * THE INVARIANT IS UNIQUENESS, NOT WIDTH: no two providers may render the same
+ * string. The search starts at what the row can afford (`providerCellsFor`) and
+ * WIDENS until every truncated name is distinct — and if even the cap collides
+ * (it does not for today's roster; a user's custom endpoints can make it), the
+ * colliding names fall back to their routing shortcut, which is unique by
+ * construction because it is the shortest prefix that parses back to exactly one
+ * provider.
+ *
+ * Pure, so the guarantee can be asserted without a renderer.
+ */
+export function providerColumn(
+ entries: readonly { value: string; label: string; shortcut: string }[],
+ truncate: (s: string, width: number) => string,
+ /** What the row can afford — `providerCellsFor`. The floor is still the minimum. */
+ want: number = MIN_PROVIDER_CELLS
+): { cells: number; text: ReadonlyMap<string, string> } {
+ const distinct = new Map<string, { label: string; shortcut: string }>();
+ for (const e of entries) distinct.set(e.value, { label: e.label, shortcut: e.shortcut });
+
+ const from = clampProviderCells(want);
+ const start = Math.min(
+ MAX_PROVIDER_CELLS,
+ Math.max(from, ...[...distinct.values()].map((e) => e.label.length))
+ );
+ for (let cells = from; cells <= start; cells++) {
+ const text = new Map<string, string>();
+ const seen = new Set<string>();
+ let ok = true;
+ for (const [value, e] of distinct) {
+ const cut = truncate(e.label, cells);
+ if (seen.has(cut)) {
+ ok = false;
+ break;
+ }
+ seen.add(cut);
+ text.set(value, cut);
+ }
+ if (ok) return { cells, text };
+ }
+
+ // Nothing in range separates them. Keep the widest column and disambiguate the
+ // colliding names with the one string that cannot collide.
+ const cells = start;
+ const text = new Map<string, string>();
+ const seen = new Set<string>();
+ for (const [value, e] of distinct) {
+ const cut = truncate(e.label, cells);
+ text.set(value, seen.has(cut) ? truncate(e.shortcut, cells) : cut);
+ seen.add(cut);
+ }
+ return { cells, text };
+}
+
/** The widest the dialog is ever drawn, however wide the terminal is. */
-export const MAX_DIALOG_WIDTH = 92;
+export const MAX_DIALOG_WIDTH = 96;
/** The tallest the dialog is ever drawn, however tall the terminal is. */
-export const MAX_DIALOG_ROWS = 18;
+export const MAX_DIALOG_ROWS = 28;
/** The most model rows the list ever shows at once. Scroll, do not grow. */
-export const MAX_LIST_ROWS = 11;
+export const MAX_LIST_ROWS = 17;
/** Fewer than this and the list stops being a list. */
const MIN_LIST_ROWS = 3;
-/** Below this the dialog cannot carry its own chrome plus a usable list. */
-const MIN_DIALOG_ROWS = 11;
+
+/** Rows the description block always occupies, blank or not. */
+export const DESCRIPTION_ROWS = 2;
/**
* Chrome rows the populated dialog ALWAYS spends: two border rows, the filter
- * row, the column header, the status row, the rule, the selection detail line
- * and the key hints.
+ * row, the column header, the status row, the rule, the selection spec line, the
+ * provider line, two description rows and the key hints.
*
- * "ALWAYS" IS THE LOAD-BEARING WORD. The status row is rendered even when it is
- * blank, so that a list which starts overflowing (or a credential sweep that
- * finishes) does not shove every row below it by one. What is deliberately NOT
- * fixed is the LIST's height: it is content-sized up to `listRows`, because the
- * failure state's whole point is a four-row fallback list that reads as four rows
- * rather than as four rows in a panel built for eleven — the unpainted hole the
- * rejected build produced, which the reader read as "this provider has nothing".
+ * "ALWAYS" IS THE LOAD-BEARING WORD. Every one of these is rendered even when it
+ * is blank, so that a list which starts overflowing — or a description that
+ * arrives after the catalog — does not shove every row below it by one. What is
+ * deliberately NOT fixed is the LIST's height: it is content-sized up to
+ * `listRows`, because the failure state's whole point is a four-row fallback list
+ * that reads as four rows rather than as four rows in a panel built for
+ * seventeen.
+ *
+ * THE DESCRIPTION IS TWO ROWS AND THE PROVIDER LINE IS ONE, which is three rows
+ * of list surrendered. They earn it: the list says what a model COSTS, and until
+ * this the screen never said what a model or a provider IS. The old inquirer
+ * picker printed the same sentence and the owner asked for it back by name.
*
* The banner's rows come OUT of the list's budget rather than being added to the
* box, so the dialog is bounded above in every state and only ever SHRINKS from
* its cap. Shape changes between phases are remounted with `key={…}`, which is
* the documented cure for inline reconciliation tearing.
*/
-export const CHROME_ROWS = 8;
+export const CHROME_ROWS =
+ 2 /* border */ +
+ 1 /* filter */ +
+ 1 /* column header */ +
+ 1 /* status */ +
+ 1 /* rule */ +
+ 1 /* selection spec */ +
+ 1 /* provider line */ +
+ DESCRIPTION_ROWS +
+ 1; /* key hints */
+
+/** Below this the dialog cannot carry its own chrome plus a usable list. */
+const MIN_DIALOG_ROWS = CHROME_ROWS + MIN_LIST_ROWS;
export interface DialogLayout {
/** Outer width including the border columns. */
width: number;
- /** Columns of terminal to the left of the border. */
+ /** Columns of terminal to the left of the border. Flexbox centres; this is the floor. */
marginLeft: number;
/** Usable content columns: `width` less two border columns and two of padding. */
inner: number;
@@ -164,20 +296,17 @@ export interface DialogLayout {
* Size the dialog for a terminal, and for however many rows a banner has taken.
*
* `extraRows` is the honest coupling between the failure banner and the list: a
- * five-row 401 explanation and eleven model rows do not both fit, and the rows that
- * must give way are the list's — the banner is the REASON the list is short, so
- * hiding the banner to show more of an unverified list would invert the whole point
- * of the state.
- *
- * MEASURED, AND IT BOUNDS WHAT "INLINE" BUYS AT THIS PIN. `screenMode: "main-screen"`
- * still sizes the renderer to `stdout.rows` — `CliRendererConfig` at
- * `@opentui/[email protected]` carries no `width`/`height` key at all, whatever the
- * upstream option table says — so the picker owns the whole terminal while it is up,
- * and the banner above scrolls with the rest of the scrollback. What inline still
- * buys, and it is the reason for choosing it: nothing is SWAPPED, so the final frame
- * survives `destroy()` and the shell prompt returns directly under the dialog rather
- * than under a restored screen that never showed it. Capping the dialog at
- * `MAX_DIALOG_ROWS` is what keeps that owned region small instead of filling 45 rows.
+ * five-row 401 explanation and seventeen model rows do not both fit, and the rows
+ * that must give way are the list's — the banner is the REASON the list is short,
+ * so hiding the banner to show more of an unverified list would invert the whole
+ * point of the state.
+ *
+ * `- 2` LEAVES ONE ROW OF AIR ABOVE AND BELOW, which is what makes a centred
+ * dialog read as centred rather than as clipped. It grows with the terminal up to
+ * `MAX_DIALOG_ROWS` now that the dialog is centred in a full-height root: the old
+ * fixed 18 rows existed to keep an "inline" region small, and inline never held —
+ * `CliRendererConfig` at this pin has no `height` key, so the renderer has always
+ * owned every row of the terminal.
*/
export function deriveDialogLayout(
termWidth: number,
@@ -189,9 +318,7 @@ export function deriveDialogLayout(
const width = Math.min(w - 4, MAX_DIALOG_WIDTH);
// Two columns of margin at 80, centred once the terminal is wider than the cap.
const marginLeft = Math.max(2, Math.floor((w - width) / 2));
- // `- 6`: the shell prompt and the claudish banner keep their rows wherever the
- // terminal is tall enough to spare them.
- const budget = Math.min(MAX_DIALOG_ROWS, Math.max(MIN_DIALOG_ROWS, h - 6));
+ const budget = Math.min(MAX_DIALOG_ROWS, Math.max(MIN_DIALOG_ROWS, h - 2));
const listRows = Math.max(
MIN_LIST_ROWS,
Math.min(MAX_LIST_ROWS, budget - CHROME_ROWS - Math.max(0, Math.floor(extraRows)))
@@ -204,10 +331,10 @@ export function deriveDialogLayout(
* visible while moving the viewport as little as possible.
*
* Pure, and computed rather than held in a ref, because there is no `<scrollbox>`
- * here: eleven rows are sliced out of the array and rendered as plain `<text>`
- * rows. That deletes two measured OpenTUI traps at once — a scrollbox's intrinsic
- * height is its WHOLE content, which starves every sibling in the same column, and
- * its reconciler desyncs when a content-derived key changes under it.
+ * here: the visible rows are sliced out of the array and rendered as plain
+ * `<text>` rows. That deletes two measured OpenTUI traps at once — a scrollbox's
+ * intrinsic height is its WHOLE content, which starves every sibling in the same
+ * column, and its reconciler desyncs when a content-derived key changes under it.
*/
export function scrollWindow(cursor: number, total: number, rows: number): number {
const size = Math.max(1, Math.floor(rows));
diff --git a/packages/cli/src/picker/row-semantics.test.ts b/packages/cli/src/picker/row-semantics.test.ts
index c3b3261d..95ac57de 100644
--- a/packages/cli/src/picker/row-semantics.test.ts
+++ b/packages/cli/src/picker/row-semantics.test.ts
@@ -17,7 +17,10 @@ import {
noticeRows,
wrapWords,
} from "./DiscoveryNotice.js";
-import { capabilityWords, detailText } from "./detail.js";
+import { truncate } from "../tui/viz/text.js";
+import { capabilityWords, descriptionLines, detailText, providerFactsText } from "./detail.js";
+import { type PickerRow, dedupeByModelId, dedupeByProviderModel } from "./hooks/usePickerModels.js";
+import { providerColumn } from "./layout.js";
import { billingLabel, priceFg, priceLabel, readinessGlyph } from "./rows.js";
const model = (over: Partial<ModelInfo> = {}): ModelInfo => ({
@@ -118,6 +121,154 @@ describe("detailText", () => {
});
});
+describe("providerFactsText", () => {
+ test("billing is a SENTENCE, not a symbol — a flat rate says it costs nothing per token", () => {
+ const sub = providerFactsText({
+ label: "Kimi Coding",
+ shortcut: "kc@",
+ billing: "sub",
+ envVar: "KIMI_CODING_API_KEY",
+ });
+ expect(sub.billing).toContain("flat-rate");
+ expect(sub.billing).toContain("no per-token");
+ // The short form makes the SAME claim in fewer words, for a row that cannot
+ // afford the sentence — never a different claim, and never silence.
+ expect(sub.billingShort).toContain("flat-rate");
+ expect(sub.billingShort.length).toBeLessThan(sub.billing.length);
+ expect(
+ providerFactsText({ label: "", shortcut: "", billing: "metered", envVar: "" }).billing
+ ).toContain("per token");
+ expect(
+ providerFactsText({ label: "", shortcut: "", billing: "local", envVar: "" }).billing
+ ).toContain("this machine");
+ });
+
+ test("the credential is NAMED, and a sign-in provider says so instead of naming nothing", () => {
+ // A truncated or absent variable name sends the reader hunting for a variable
+ // that does not exist — a defect this dialog has already shipped once.
+ expect(
+ providerFactsText({
+ label: "OpenRouter",
+ shortcut: "or@",
+ billing: "metered",
+ envVar: "OPENROUTER_API_KEY",
+ }).auth
+ ).toBe("OPENROUTER_API_KEY");
+ expect(
+ providerFactsText({ label: "Devin", shortcut: "dv@", billing: "sub", envVar: "" }).auth
+ ).toContain("signs in");
+ });
+});
+
+describe("descriptionLines", () => {
+ test("a short sentence is one row and is not padded into two", () => {
+ expect(descriptionLines("A fast model.", 40, 2)).toEqual(["A fast model."]);
+ });
+
+ test("no row exceeds the width, and an over-long blurb ends in an ellipsis", () => {
+ const long =
+ "Kimi's most capable model to date, with 2.8 trillion parameters, native visual reasoning, " +
+ "and a context window measured in millions of tokens across every supported modality.";
+ const rows = descriptionLines(long, 40, 2);
+ expect(rows.length).toBe(2);
+ for (const r of rows) expect(r.length).toBeLessThanOrEqual(40);
+ expect(rows[1]?.endsWith("…")).toBe(true);
+ });
+
+ test("an absent description is NO rows — the block draws its own blanks", () => {
+ // Returning `[""]` would be indistinguishable from a one-row description at the
+ // call site, and the block's fixed height is what keeps the footer still.
+ expect(descriptionLines(" ", 40, 2)).toEqual([]);
+ });
+});
+
+describe("row identity depends on the VIEW", () => {
+ const row = (provider: string, id: string, spec: string): PickerRow =>
+ ({ provider, shortcut: "", spec, price: "", model: model({ id }) }) as PickerRow;
+
+ test("ALL MODELS: one model on N providers is N rows, with N distinct specs", () => {
+ // The owner's rule, verbatim: "if model has more than one provider that going
+ // to be two lines in 'all models' list". `gpt-6-astra` at $30.00 on OpenRouter
+ // beside the same model as SUB on Codex is the single most useful thing this
+ // list does, and keying on the model id alone would delete two of the three.
+ const kept = dedupeByProviderModel([
+ row("openrouter", "gpt-6-astra", "openrouter@openai/gpt-6-astra"),
+ row("openai", "gpt-6-astra", "oai@gpt-6-astra"),
+ row("openai-codex", "gpt-6-astra", "cx@gpt-6-astra"),
+ ]);
+ expect(kept.length).toBe(3);
+ expect(new Set(kept.map((r) => r.spec)).size).toBe(3);
+ });
+
+ test("ALL MODELS: the same model TWICE under ONE provider is still one row", () => {
+ // A provider's live roster and its catalog entries overlap, and that overlap
+ // is not two routes — it is one route described twice.
+ const kept = dedupeByProviderModel([
+ row("kimi", "kimi-k3", "kimi@kimi-k3"),
+ row("kimi", "kimi-k3", "kimi@kimi-k3"),
+ row("kimi", "kimi-k2.6", "[email protected]"),
+ ]);
+ expect(kept.map((r) => r.model.id)).toEqual(["kimi-k3", "kimi-k2.6"]);
+ });
+
+ test("PROVIDER CATALOG: one row per model id, roster and catalog collapsed", () => {
+ // "and if we enter to provider catalog, not all models - then the model will
+ // be just one". One route is in scope, so a second row would mean nothing —
+ // even when the two sources spell the spec differently.
+ const kept = dedupeByModelId([
+ row("kimi", "kimi-k3", "kimi@kimi-k3"),
+ row("kimi", "kimi-k3", "kimi@moonshot/kimi-k3"),
+ row("kimi", "kimi-k2.6", "[email protected]"),
+ ]);
+ expect(kept.length).toBe(2);
+ // The FIRST wins, and the caller puts the live roster first — what the
+ // endpoint answered for THESE credentials beats what the catalog says.
+ expect(kept[0]?.spec).toBe("kimi@kimi-k3");
+ });
+});
+
+describe("providerColumn", () => {
+ const entry = (value: string, label: string, shortcut: string) => ({ value, label, shortcut });
+
+ test("NO TWO PROVIDERS EVER RENDER THE SAME STRING — the rejected rail's defect", () => {
+ // `OpenCode Zen` and `OpenCode Zen Go` share a twelve-character prefix, which is
+ // exactly the collision that rendered two different providers as `opencod…`.
+ const { cells, text } = providerColumn(
+ [
+ entry("opencode-zen", "OpenCode Zen", "zen@"),
+ entry("opencode-zen-go", "OpenCode Zen Go", "zengo@"),
+ entry("sakana", "Sakana Fugu", "fugu@"),
+ entry("sakana-subscription", "Sakana Fugu Subscription", "sc@"),
+ entry("openrouter", "OpenRouter", "or@"),
+ ],
+ truncate
+ );
+ const drawn = [...text.values()];
+ expect(new Set(drawn).size).toBe(drawn.length);
+ for (const s of drawn) expect(s.length).toBeLessThanOrEqual(cells);
+ });
+
+ test("a name that FITS is printed whole — truncation is the exception, not the rule", () => {
+ const { text } = providerColumn(
+ [entry("openrouter", "OpenRouter", "or@"), entry("openai", "OpenAI", "oai@")],
+ truncate
+ );
+ expect(text.get("openrouter")).toBe("OpenRouter");
+ expect(text.get("openai")).toBe("OpenAI");
+ });
+
+ test("names that cannot be separated at ANY width fall back to the unique shortcut", () => {
+ // Two custom endpoints with the same long name is a real configuration; the
+ // shortcut is unique by construction because it is the shortest prefix that
+ // parses back to exactly one provider.
+ const same = "A Very Long Custom Endpoint Name";
+ const { text } = providerColumn([entry("a", same, "aa@"), entry("b", same, "bb@")], truncate);
+ const drawn = [...text.values()];
+ expect(new Set(drawn).size).toBe(2);
+ expect(drawn.some((s) => s.includes("bb@"))).toBe(true);
+ });
+});
+
const failure = (over: Partial<DiscoveryFailure> = {}): DiscoveryFailure => ({
kind: "unauthorized",
provider: "kimi",
diff --git a/packages/cli/src/picker/rows.tsx b/packages/cli/src/picker/rows.tsx
index 0a1ebe1f..0e5f7240 100644
--- a/packages/cli/src/picker/rows.tsx
+++ b/packages/cli/src/picker/rows.tsx
@@ -17,6 +17,17 @@
* place and it is not here — it is the loading dialog, where `done/total` is real
* progress over countable work.
*
+ * THE PROVIDER COLUMN IS FIRST, AND IT IS A NAME. It used to be last-but-three and
+ * printed the routing shortcut (`or@`, `oai@`, `cx@`); the owner's question on a
+ * live run was *"what is 'or' means"*. A shortcut only reads as information to
+ * someone who already knows it, so it teaches nothing about a screen whose whole
+ * job is to say what is on offer. The column now prints the provider's readable
+ * display name, sourced from the provider definitions through
+ * `PickerProviderChoice.label` — never a name table here — and it leads the row,
+ * because "which provider" is the question the user asked first. The shortcut is
+ * not lost: it sits beside the full name in the `p` dialog, and inside the exact
+ * `provider@model` spec on the detail line.
+ *
* COLOUR ENCODES MEANING, ONE MEANING EACH, APP-WIDE:
*
* `FREE` success costs nothing
@@ -111,10 +122,10 @@ export function ColumnHeader({ layout }: { layout: RowLayout }): ReactNode {
<box height={1} flexShrink={0}>
<text>
<span fg={tokens.trace}>{" "}</span>
+ <span fg={tokens.trace}>{padTo("provider", layout.provider)}</span>
+ <span>{gap(GAPS.afterProvider)}</span>
<span fg={tokens.trace}>{padTo("model", layout.id)}</span>
<span>{gap(GAPS.afterId)}</span>
- <span fg={tokens.trace}>{padStartTo("provider", layout.provider)}</span>
- <span>{gap(GAPS.afterProvider)}</span>
<span fg={tokens.trace}>{padStartTo("ctx", layout.ctx)}</span>
<span>{gap(GAPS.afterCtx)}</span>
<span fg={tokens.trace}>{padStartTo("$/1M", layout.price)}</span>
@@ -126,8 +137,17 @@ export function ColumnHeader({ layout }: { layout: RowLayout }): ReactNode {
export interface ModelRowProps {
model: ModelInfo;
- /** The routing shortcut of the provider that would serve it — `or@`, `kc@`. */
- shortcut: string;
+ /**
+ * The provider's READABLE display name, already fitted to `layout.provider` and
+ * guaranteed distinct from every other provider on screen (`providerColumn`).
+ *
+ * It replaced the routing shortcut — `or@`, `oai@`, `cx@` — because the owner
+ * asked, verbatim, *"what is 'or' means"*. A shortcut is information only to
+ * someone who already knows it. The shortcut still exists where it explains
+ * itself: beside the full name in the `p` dialog, and inside the exact spec on
+ * the detail line under this list.
+ */
+ providerLabel: string;
/** Whatever `resolveProviderDisplayPrice` said, already reshaped by `priceLabel`. */
price: string;
layout: RowLayout;
@@ -138,7 +158,7 @@ export interface ModelRowProps {
export function ModelRow({
model,
- shortcut,
+ providerLabel,
price,
layout,
cursor,
@@ -154,10 +174,12 @@ export function ModelRow({
<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={cursor ? C.strong : tokens.subtle}>
+ {padTo(truncate(providerLabel, layout.provider), layout.provider)}
+ </span>
+ <span>{gap(GAPS.afterProvider)}</span>
<span fg={idFg}>{padTo(model.id, layout.id)}</span>
<span>{gap(GAPS.afterId)}</span>
- <span fg={tokens.subtle}>{padStartTo(shortcut, layout.provider)}</span>
- <span>{gap(GAPS.afterProvider)}</span>
<span fg={tokens.subtle}>{padStartTo(model.context || "N/A", layout.ctx)}</span>
<span>{gap(GAPS.afterCtx)}</span>
<span fg={priceFg(price)}>{padStartTo(price, layout.price)}</span>
diff --git a/packages/cli/src/providers/model-descriptions.ts b/packages/cli/src/providers/model-descriptions.ts
new file mode 100644
index 00000000..95bfcf8c
--- /dev/null
+++ b/packages/cli/src/providers/model-descriptions.ts
@@ -0,0 +1,177 @@
+/**
+ * providers/model-descriptions.ts — one prose sentence per model, indexed by id
+ * and by alias.
+ *
+ * WHY THIS FILE EXISTS AT ALL. The old inquirer picker printed a model's
+ * description under the highlighted row — "Kimi's most capable model to date,
+ * with 2.8 trillion parameters…" — and that sentence is the only thing on the
+ * screen that says what a model IS rather than what it costs. The OpenTUI picker
+ * lost it, because its list is built from the SLIM catalog and the slim payload
+ * carries no `description`: 0 of 704 entries on disk have one, and
+ * `model-catalog.ts:servedByVendor` records that gap as the price of reading the
+ * served-by index locally. `catalogModelToModelInfo` therefore substitutes
+ * `"<provider> model"`, which is a placeholder, not a description.
+ *
+ * THE RICH ENDPOINT HAS THEM AND IT IS ONE REQUEST. MEASURED 2026-09-10 against
+ * the live catalog: `?status=active&limit=1500` returns all 1016 active models in
+ * 2.8 s / 1.06 MB, and 978 of them carry a description (p50 180 characters).
+ * Everything else in that payload is already known locally, so only the
+ * projection is kept — id, aliases, description — which is what makes a daily
+ * disk cache cheap enough to be worth having.
+ *
+ * IT NEVER BLOCKS A LIST. The caller starts this beside the rows rather than in
+ * front of them: the picker paints from the slim index immediately and the
+ * detail line fills in when this lands. A description is worth waiting for on the
+ * selected row and worth nothing at all on a row nobody has looked at.
+ *
+ * IT NEVER THROWS. Every failure — offline, a 500, an unparseable body, an
+ * unwritable cache dir — resolves to whatever index it already had, because a
+ * missing sentence must never be able to take the picker down.
+ */
+
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import { homedir } from "node:os";
+import { dirname, join } from "node:path";
+import { log } from "../logger.js";
+import { getAllModelDocs } from "../model-loader.js";
+import { FIREBASE_CACHE_TTL_MS } from "./cache-ttl.js";
+
+/** Firebase-derived data — OK to cache locally per the catalog policy. */
+export const MODEL_DESCRIPTIONS_CACHE_PATH = join(
+ homedir(),
+ ".claudish",
+ "model-descriptions.json"
+);
+
+interface DescriptionCache {
+ version: 1;
+ lastUpdated: string;
+ /** `modelId` → description. Aliases are expanded on read, not stored twice. */
+ byId: Record<string, string>;
+ /** `alias` → `modelId`. Kept apart so an alias cannot shadow a real id. */
+ aliases: Record<string, string>;
+}
+
+/**
+ * The index the picker reads. Lookup is case-insensitive on the id, because a
+ * row's id comes from the slim catalog and an alias from a live roster, and the
+ * two do not agree about case (`GLM-4.6` vs `glm-4.6`).
+ */
+export interface DescriptionIndex {
+ get(modelId: string): string | undefined;
+ /** How many models carry a sentence. Zero means "not loaded yet", never "none exist". */
+ readonly size: number;
+}
+
+const EMPTY_INDEX: DescriptionIndex = { get: () => undefined, size: 0 };
+
+/** The empty index, as a named value, so a caller's "not loaded yet" reads as intent. */
+export function emptyDescriptionIndex(): DescriptionIndex {
+ return EMPTY_INDEX;
+}
+
+function indexFrom(cache: DescriptionCache): DescriptionIndex {
+ const byId = new Map<string, string>();
+ for (const [id, text] of Object.entries(cache.byId)) byId.set(id.toLowerCase(), text);
+ for (const [alias, id] of Object.entries(cache.aliases)) {
+ const text = cache.byId[id];
+ if (text !== undefined && !byId.has(alias.toLowerCase())) byId.set(alias.toLowerCase(), text);
+ }
+ return {
+ get: (modelId: string) => byId.get(modelId.toLowerCase()),
+ size: Object.keys(cache.byId).length,
+ };
+}
+
+function readCache(path: string): DescriptionCache | null {
+ if (!existsSync(path)) return null;
+ try {
+ const raw = JSON.parse(readFileSync(path, "utf-8")) as Partial<DescriptionCache>;
+ if (!raw || typeof raw !== "object" || typeof raw.byId !== "object" || raw.byId === null) {
+ return null;
+ }
+ return {
+ version: 1,
+ lastUpdated:
+ typeof raw.lastUpdated === "string" ? raw.lastUpdated : new Date(0).toISOString(),
+ byId: raw.byId as Record<string, string>,
+ aliases: (raw.aliases ?? {}) as Record<string, string>,
+ };
+ } catch {
+ return null;
+ }
+}
+
+function writeCache(path: string, cache: DescriptionCache): void {
+ try {
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(path, JSON.stringify(cache), "utf-8");
+ } catch (e: unknown) {
+ // A read-only home is not a reason to have no descriptions this session.
+ log(`[model-descriptions] cache write failed: ${(e as Error)?.message ?? String(e)}`);
+ }
+}
+
+function isFresh(cache: DescriptionCache): boolean {
+ const age = Date.now() - new Date(cache.lastUpdated).getTime();
+ return Number.isFinite(age) && age >= 0 && age <= FIREBASE_CACHE_TTL_MS;
+}
+
+/** One in-process promise: a picker with two views must not fetch this twice. */
+let _inflight: Promise<DescriptionIndex> | null = null;
+
+/**
+ * The description index — fresh cache, else one bulk fetch, else the stale cache.
+ *
+ * THE STALE CACHE IS PREFERRED TO NOTHING. A description is editorial text about a
+ * model that already exists; a day-old sentence is right, and an absent one is the
+ * defect this file was written to fix.
+ */
+export async function loadModelDescriptions(
+ path: string = MODEL_DESCRIPTIONS_CACHE_PATH
+): Promise<DescriptionIndex> {
+ if (_inflight) return _inflight;
+ _inflight = (async (): Promise<DescriptionIndex> => {
+ const cached = readCache(path);
+ if (cached && isFresh(cached)) {
+ log(`[model-descriptions] ${Object.keys(cached.byId).length} descriptions from disk cache`);
+ return indexFrom(cached);
+ }
+ const started = Date.now();
+ try {
+ const docs = await getAllModelDocs();
+ const byId: Record<string, string> = {};
+ const aliases: Record<string, string> = {};
+ for (const doc of docs) {
+ const text = (doc.description ?? "").trim();
+ if (text === "") continue;
+ byId[doc.modelId] = text;
+ for (const alias of doc.aliases ?? []) {
+ if (alias !== doc.modelId && aliases[alias] === undefined) aliases[alias] = doc.modelId;
+ }
+ }
+ const fresh: DescriptionCache = {
+ version: 1,
+ lastUpdated: new Date().toISOString(),
+ byId,
+ aliases,
+ };
+ writeCache(path, fresh);
+ log(
+ `[model-descriptions] fetched ${docs.length} models, ${Object.keys(byId).length} with a description, in ${Date.now() - started} ms`
+ );
+ return indexFrom(fresh);
+ } catch (e: unknown) {
+ log(
+ `[model-descriptions] fetch failed after ${Date.now() - started} ms: ${(e as Error)?.message ?? String(e)}`
+ );
+ return cached ? indexFrom(cached) : EMPTY_INDEX;
+ }
+ })();
+ return _inflight;
+}
+
+/** Test seam: drop the in-process memo so a second call re-reads. */
+export function _resetModelDescriptions(): void {
+ _inflight = null;
+}