Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
feat(picker): an OpenTUI model picker that says what it is showing you
Jack Rudenkocec60172ca4a
diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.tsindex 44c0d481..e1de1a6a 100644--- a/packages/cli/src/index.ts+++ b/packages/cli/src/index.ts@@ -17,6 +17,7 @@ import {// Two leaves that import NOTHING — see their headers. Static here on purpose: they// must not drag anything into this file's cold-start graph.import { canDrawTui } from "./tui/runtime/can-draw-tui.js";+import { PickerCancelled } from "./tui/runtime/picker-cancelled.js";import {type ModelPickerGate,requiresExplicitModel,@@ -275,7 +276,22 @@ await traceSpan("startup:op-import-flag", () => applyOpImport());const isMcpMode = process.argv.includes("--mcp");// Handle Ctrl+C gracefully during interactive prompts+//+// ONE CONDITION WIDER THAN IT WAS, and that is the only edit the new model picker+// needs at a call site. `PickerCancelled` is what `selectModel` now throws when the+// user declines to choose — it replaces a `process.exit(0)` that used to live INSIDE+// the library (`model-selector.ts:822`). This handler is already attached at all three+// entry points that can reach the picker (`:428`, `:432`, `:804`), so the blank line+// and the exit 0 are byte-identical at every one of them and no caller changes.+//+// `NoTtyError` is deliberately NOT caught here. The user did not decline; the+// environment could not ask. An exit 0 with no model chosen is indistinguishable from+// success to a headless caller, so that one has to surface and exit non-zero.function handlePromptExit(err: unknown): void {+ if (err instanceof PickerCancelled) {+ console.log("");+ process.exit(0);+ }if (err && typeof err === "object" && "name" in err && err.name === "ExitPromptError") {console.log("");process.exit(0);diff --git a/packages/cli/src/model-selector-picker.test.ts b/packages/cli/src/model-selector-picker.test.tsnew file mode 100644index 00000000..673ea358--- /dev/null+++ b/packages/cli/src/model-selector-picker.test.ts@@ -0,0 +1,116 @@+import { describe, expect, test } from "bun:test";+/**+ * The picker's PUBLIC CONTRACT — what the two call sites are allowed to assume.+ *+ * FR-5 is that `selectModel(options)` still resolves to a model spec string and that+ * `index.ts` and `profile-commands.ts` keep working. The success path cannot be driven+ * from a unit test (it needs a terminal and a human), so this file pins the parts that+ * CAN be decided without one: the non-TTY refusal, the shape of the cancel error, and —+ * at the source level — that the two call sites still look the way the contract says+ * they do. The last of those is a grep, and a grep is the only mechanism that catches a+ * call site quietly changing shape while every type still checks.+ */+import { readFileSync } from "node:fs";+import { join } from "node:path";+import { selectModel, selectModelInteractive } from "./model-selector.js";+import { NO_TTY_LINES, NoTtyError, PickerCancelled } from "./tui/runtime/picker-cancelled.js";++const SRC = new URL(".", import.meta.url).pathname;+const read = (f: string): string => readFileSync(join(SRC, f), "utf8");++/**+ * Force the non-TTY answer rather than depending on how the suite was launched.+ *+ * `bun test` at a terminal INHERITS that terminal, so an unguarded assertion here would+ * open a full-screen picker in the middle of a test run on a developer's machine and+ * block until they pressed Escape. Setting the flags makes the test decide the same+ * thing in both environments — which is the whole point of `canDrawTui` reading the+ * live process rather than a module-load constant.+ */+async function withoutTty<T>(fn: () => Promise<T>): Promise<T> {+ // `defineProperty`, not assignment: on a stream that really IS a terminal, `isTTY` is+ // a READONLY property and a plain assignment throws `TypeError: Attempted to assign to+ // readonly property`. Measured — this file passed alone (piped stdin, where the+ // property does not exist and assignment silently creates it) and failed inside the+ // full suite, which inherits the developer's terminal. Restoring the ORIGINAL+ // descriptor matters for the same reason: deleting the property would leave a real TTY+ // looking piped for every test file that runs after this one, in the same process.+ const streams = [process.stdin, process.stdout] as const;+ const saved = streams.map((s) => Object.getOwnPropertyDescriptor(s, "isTTY"));+ for (const s of streams) {+ Object.defineProperty(s, "isTTY", { value: false, configurable: true, writable: true });+ }+ try {+ return await fn();+ } finally {+ streams.forEach((s, i) => {+ const d = saved[i];+ if (d) Object.defineProperty(s, "isTTY", d);+ else Reflect.deleteProperty(s as object, "isTTY");+ });+ }+}++describe("selectModelInteractive", () => {+ test("refuses a non-TTY with NoTtyError — never a fallback to inquirer", async () => {+ // Falling back would be falling back to a HANG: inquirer in a non-TTY draws into a+ // stream nothing is reading and then waits for a keypress that cannot arrive.+ // `claudish profile edit` under a pipe reaches exactly this branch.+ await withoutTty(async () => {+ await expect(selectModelInteractive()).rejects.toBeInstanceOf(NoTtyError);+ });+ });++ test("the refusal carries the same lines the non-interactive path prints", async () => {+ await withoutTty(async () => {+ const err = await selectModelInteractive().catch((e: unknown) => e);+ expect(err).toBeInstanceOf(NoTtyError);+ for (const line of NO_TTY_LINES) expect((err as Error).message).toContain(line);+ });+ });++ test("`selectModel` propagates NoTtyError rather than reporting a cancel", async () => {+ // A cancel exits 0. An environment that cannot ask must NOT look like a user who+ // declined — that is an exit 0 with no model chosen, which a headless caller reads+ // as success.+ await withoutTty(async () => {+ const err = await selectModel().catch((e: unknown) => e);+ expect(err).toBeInstanceOf(NoTtyError);+ expect(err).not.toBeInstanceOf(PickerCancelled);+ });+ });+});++describe("PickerCancelled", () => {+ test("is an Error with a stable name, so a cross-module `instanceof` is not the only handle", () => {+ const err = new PickerCancelled();+ expect(err).toBeInstanceOf(Error);+ expect(err.name).toBe("PickerCancelled");+ });+});++describe("the two call sites still look the way the contract says", () => {+ test("index.ts calls selectModel through handlePromptExit, which handles PickerCancelled", () => {+ const src = read("index.ts");+ expect(src).toContain("selectModel({ freeOnly: cliConfig.freeOnly }).catch(handlePromptExit)");+ expect(src).toContain("if (err instanceof PickerCancelled)");+ // And NOT `NoTtyError` — that one must surface and exit non-zero.+ expect(src).not.toContain("instanceof NoTtyError");+ });++ test("profile-commands.ts still calls selectModel and is otherwise untouched", () => {+ const src = read("profile-commands.ts");+ expect(src).toContain("selectModel({");+ // It reaches `handlePromptExit` through `index.ts`'s own `.catch`, so it needs no+ // knowledge of the cancel type at all — which is what "zero call sites change"+ // means here.+ expect(src).not.toContain("PickerCancelled");+ });++ test("selectModel resolves to a string — the signature FR-5 pins", () => {+ // Compile-time, made visible: if the return type ever widened, this line would stop+ // type-checking and `tsc` would name this file.+ const fn: (o?: { message?: string }) => Promise<string> = selectModel;+ expect(typeof fn).toBe("function");+ });+});diff --git a/packages/cli/src/model-selector.ts b/packages/cli/src/model-selector.tsindex db791071..b581806c 100644--- a/packages/cli/src/model-selector.ts+++ b/packages/cli/src/model-selector.ts@@ -51,6 +51,13 @@ import {} from "./providers/provider-definitions.js";import { getRuntimeProviders } from "./providers/runtime-providers.js";import { isChatCapable } from "./providers/transport/probe-discovery.js";+// STATIC, and safe: both are true leaves with ZERO imports of their own+// (`picker/import-direction.test.ts` asserts exactly that, by name). A static+// import of the picker ITSELF would pull a renderer into this module's graph and+// from there into the MCP stdio path — which is why `selectModelInteractive`+// reaches it by `await import()` instead.+import { canDrawTui } from "./tui/runtime/can-draw-tui.js";+import { NoTtyError, PickerCancelled } from "./tui/runtime/picker-cancelled.js";/*** Model data structure@@ -675,9 +682,98 @@ async function fetchPickerModels(}/**- * Select a model interactively with fuzzy search+ * The cross-vendor catalog load — the picker's A2, as one awaitable.+ *+ * Extracted from `selectModelClassic`'s body so the OpenTUI picker runs the SAME two+ * fetches in the same way rather than a second approximation of them. `allSettled`,+ * not `all`: a failed top-100 fetch degrades to the recommended list, and a failed+ * recommended fetch degrades to nothing — neither is allowed to take the picker down,+ * because the rail is derived from provider definitions and stays usable with no+ * catalog at all.+ */+export async function loadPickerCatalog(+ options: { recommended?: boolean; forceUpdate?: boolean } = {}+): Promise<{ top: ModelInfo[]; recommended: ModelInfo[] }> {+ const { recommended = true, forceUpdate = false } = options;+ const [top100Result, recommendedResult] = await Promise.allSettled([+ getTop100Models(),+ recommended ? loadRecommendedModels(forceUpdate) : Promise.resolve([]),+ ]);+ return {+ top:+ top100Result.status === "fulfilled"+ ? sortModelsNewestFirst(dedupeModels(top100Result.value.models.map(modelDocToModelInfo)))+ : [],+ recommended: recommendedResult.status === "fulfilled" ? recommendedResult.value : [],+ };+}++/**+ * The interactive model picker's public entry point — UNCHANGED SIGNATURE.+ *+ * Resolves to a model spec string exactly as it always has, through the same+ * `buildExplicitModelSpec` / `pickerModelPrefix` / `resolveProviderExternalId`+ * functions. What changed is the cancel path: declining to choose used to call+ * `process.exit(0)` from inside this library, and now throws `PickerCancelled`, which+ * the caller's already-attached `handlePromptExit` turns into the same blank line and+ * the same exit 0. Because that handler is attached at all three entry points+ * (`index.ts:428`, `:432`, `:804`), ZERO call sites change and the user-visible+ * result is byte-identical.*/export async function selectModel(options: ModelSelectorOptions = {}): Promise<string> {+ const outcome = await selectModelInteractive(options);+ if (outcome.model === null) throw new PickerCancelled();+ return outcome.model;+}++/** What the picker resolves to. `null` ⟺ the user declined to choose. */+export interface PickerOutcome {+ model: string | null;+}++/**+ * The picker, as a function that RETURNS the user's decision instead of exiting.+ *+ * Three gates, in this order, and the order is the design:+ *+ * 1. **No TTY → `NoTtyError`, never a fallback to inquirer.** Falling back would be+ * falling back to a hang: inquirer in a non-TTY draws into a stream nothing is+ * reading and then waits for a keypress that cannot arrive. `index.ts` cannot reach+ * this branch (its own gate closed it), but `profile-commands.ts:559` can, and+ * `grep isTTY profile-commands.ts` returns nothing. So `claudish profile edit` under+ * a pipe now fails fast with four actionable pointers instead of hanging forever.+ *+ * 2. **`CLAUDISH_PICKER=classic` → the inquirer implementation.** Rollback is an env+ * var rather than a revert, which matters because this screen is on every user's+ * startup path and NO test drives the flow being replaced. The removal trigger is+ * recorded in `ROADMAP.md`.+ *+ * 3. **`--free` keeps its current behaviour — the throw.** `getFreeModels()` is a+ * documented stub returning `[]`, so `--free` has been unreachable since the Zen+ * removal. Routing it to the classic path preserves the exact exception rather than+ * inventing a UI nobody specified for a flag nobody can use.+ *+ * The picker itself is reached by DYNAMIC import, which is what keeps OpenTUI off the+ * cold-start path and out of the MCP stdio path (§9.2).+ */+export async function selectModelInteractive(+ options: ModelSelectorOptions = {}+): Promise<PickerOutcome> {+ if (!canDrawTui()) throw new NoTtyError();+ if (options.freeOnly || process.env.CLAUDISH_PICKER === "classic") {+ return { model: await selectModelClassic(options) };+ }+ const { runModelPicker } = await import("./picker/model-picker-run.js");+ return runModelPicker(options);+}++/**+ * The inquirer implementation, verbatim — still the picker under+ * `CLAUDISH_PICKER=classic`, and still the machine behind `selectModelsForProfile`,+ * which is not being ported in this change and calls `selectModelFromProvider`+ * directly. It is not dead code kept "just in case": it has a live caller.+ */+async function selectModelClassic(options: ModelSelectorOptions = {}): Promise<string> {const { freeOnly = false, recommended = true, message, forceUpdate = false } = options;const catalog = createCatalogClient();@@ -699,18 +795,11 @@ export async function selectModel(options: ModelSelectorOptions = {}): Promise<sthrow new Error("No free models available");}} else {- const [top100Result, recommendedResult] = await Promise.allSettled([- getTop100Models(),- recommended ? loadRecommendedModels(forceUpdate) : Promise.resolve([]),- ]);-- const topModels =- top100Result.status === "fulfilled"- ? sortModelsNewestFirst(dedupeModels(top100Result.value.models.map(modelDocToModelInfo)))- : [];- recommendedModels = recommendedResult.status === "fulfilled" ? recommendedResult.value : [];-- models = topModels.length > 0 ? topModels : recommendedModels;+ // Shared with the OpenTUI picker through `loadPickerCatalog`, so the two UIs+ // cannot drift into fetching different things.+ const loaded = await loadPickerCatalog({ recommended, forceUpdate });+ recommendedModels = loaded.recommended;+ models = loaded.top.length > 0 ? loaded.top : recommendedModels;interactiveProviderChoices = await getInteractiveProviderChoices();pickerProviders = toPickerProviders(interactiveProviderChoices);@@ -853,7 +942,14 @@ export async function selectModel(options: ModelSelectorOptions = {}): Promise<s}}-interface ProviderChoice {+/**+ * One row of the picker's provider list.+ *+ * EXPORTED because it is already the return type of the exported+ * `buildProviderChoices`, so the name was public in everything but spelling — and+ * the OpenTUI picker's data source needs to name it.+ */+export interface ProviderChoice {name: string;value: string;description: string;@@ -1189,7 +1285,7 @@ function getPickerDisplayName(providerValue: string): string {/*** Load models for a specific picker provider value via the CatalogClient.*/-async function loadModelsForPickerProvider(+export async function loadModelsForPickerProvider(providerValue: string,catalog: CatalogClient): Promise<ModelInfo[]> {@@ -1600,7 +1696,12 @@ function buildRowsFromDiscovered(// Order: what it is · how big · what it costs · whether it is on offer.const parts = [c.displayName];- if (contextLength) parts.push(`${Math.round(contextLength / 1024)}K context`);+ // ONE FORMATTER, ONE NUMBER. This line used to divide by 1024 while `context`+ // (three lines down, and what every list row prints) divides by 1000, so a single+ // frame showed the same model as `250K` in its row and `244K context` in its+ // description — measured in the picker's first capture, and reported before that+ // from the old picker's detail line. Neither number was wrong; having two was.+ if (contextLength) parts.push(`${formatContextLength(contextLength)} context`);// A relative multiplier is only meaningful on a plan that bills in credits;// for a per-token provider the real rate is already in `pricing`.if (subscription && c.costFactor !== undefined) parts.push(`×${c.costFactor}`);@@ -1894,23 +1995,10 @@ export async function promptForProfileDescription(): Promise<string> {return description.trim();}-/**- * Select from existing profiles- */-export async function selectProfile(- profiles: { name: string; description?: string; isDefault?: boolean }[]-): Promise<string> {- const selected = await select({- message: "Select a profile:",- choices: profiles.map((p) => ({- name: p.isDefault ? `${p.name} (default)` : p.name,- value: p.name,- description: p.description,- })),- });-- return selected;-}+// `selectProfile` was DELETED here. It had zero importers anywhere in the repo,+// tests included — the profile commands build their own `select` — so it was an+// exported surface that nothing could regress and nothing could exercise. Removed+// with the picker rewrite rather than left for the next reader to re-litigate./*** Confirm actiondiff --git a/packages/cli/src/picker/DiscoveryNotice.tsx b/packages/cli/src/picker/DiscoveryNotice.tsxnew file mode 100644index 00000000..8e67974a--- /dev/null+++ b/packages/cli/src/picker/DiscoveryNotice.tsx@@ -0,0 +1,253 @@+/** @jsxImportSource @opentui/react */+/**+ * picker/DiscoveryNotice.tsx — the four non-`rows` outcomes, rendered.+ *+ * THE WORDS ARE NOT THE DEFECT. Measured against a real 401, the old stderr warning+ * survived on screen in full — provider, cause, HTTP status, endpoint, upstream body,+ * the env var to inspect, where to get a key — and the user still read the short+ * fallback list below it as "this provider has no models". What was wrong was its+ * PRESENTATION: plain white body text for the most severe thing on screen, inline+ * rather than pinned, and a JSON body wrapped mid-word. So this file changes no+ * wording it can avoid changing; it supplies severity, a border, a row budget and a+ * truncation point.+ *+ * THREE TIERS, NEVER COLLAPSED TO ok/fail, copied from `TestResult`+ * (`tui/types.ts:79-107`) whose own comment says `unavailable` is "deliberately+ * neutral, not red":+ *+ * · `failed` → ERROR (red on `C.bgError`)+ * · `empty-roster` / `all-filtered` / `collapsed-empty` → NOTICE (`tokens.warn`)+ * · `rows` / `unsupported` → nothing at all+ *+ * `unsupported` rendering nothing is the load-bearing half of that last row: ~25+ * pickable providers declare no `modelDiscovery`, and for them the catalog list IS+ * the normal, correct UI. A panel there would be noise on the majority case, which+ * is how a user learns to ignore the panel.+ */++import type { ReactNode } from "react";+import type { PickerDiscoveryOutcome } from "../model-selector.js";+import { type BannerSeverity, ErrorBanner } from "../tui/components/ErrorBanner.js";++/** What a notice is, before it is a component — pure, so it can be asserted. */+export interface NoticeContent {+ severity: BannerSeverity;+ /** One row each, in priority order. Never re-ordered by the renderer. */+ lines: string[];+ /** A chip at the head of row one, e.g. `HTTP 401`. */+ badge?: string;+ /** Drawn in the border, and only when the banner is bordered. */+ title: string;+}++/**+ * Collapse the stderr formatter's embedded newlines and indentation to one row, and drop+ * its leading `⚠`.+ *+ * The glyph is the STDERR path's severity marker, and it is the only one that path has.+ * Here the severity is carried by the banner's colour, its left rule and its title, so+ * the glyph would be a fourth encoding of a fact already stated three times — and it+ * costs two columns of a headline measured at exactly the frame width (MEASURED: an+ * 80-column banner line that fits without it wrapped with it, spending a row out of a+ * four-row budget). The stderr wording keeps it, unchanged, which is the whole point of+ * the formatter and the sink being separate.+ *+ * `.trim()` runs BEFORE the strip: the formatter's first line starts with a newline,+ * which the whitespace collapse turns into a leading SPACE, and `^⚠` then matches+ * nothing at all. Measured — the glyph survived the first version of this line.+ */+function oneRow(line: string): string {+ return line.replace(/\s+/g, " ").trim().replace(/^⚠\s*/, "");+}++/**+ * The provenance sentence — the line that says the list below is NOT the live+ * roster.+ *+ * It is the third of the three encodings of that one fact (the panel title and the+ * per-row `CAT` chip are the others), and it is never dropped, because it is the one+ * the user's own report was about. It says the same thing+ * `formatDiscoveryFailureNotice` says for the `catalog` fallback, so a reader who+ * sees both the panel and the scrollback line reads one sentence twice rather than+ * two sentences that have to be reconciled.+ */+function provenance(displayName: string): string {+ return `Showing ${displayName}'s cloud-catalog entries below — not its live roster.`;+}++/**+ * Outcome → banner content, or `null` when the outcome has nothing to say.+ *+ * NO STRING HERE INTERPOLATES AN OPTIONAL FIELD WITHOUT A GUARD. `endpoint` and+ * `status` are both optional on `DiscoveryFailure` — a registered fetcher may report+ * `unauthorized` with neither — and a rendered `undefined` is worse than a shorter+ * sentence. A test sweeps every variant × present/absent for both.+ */+export function discoveryNoticeContent(+ outcome: PickerDiscoveryOutcome,+ displayName: string+): NoticeContent | null {+ switch (outcome.kind) {+ case "rows":+ case "unsupported":+ // Nothing to say, and saying nothing is the decision — see the file header.+ return null;+ case "failed":+ return failedContent(outcome, displayName);+ case "empty-roster":+ return emptyRosterContent(outcome, displayName);+ case "all-filtered":+ return allFilteredContent(outcome, displayName);+ case "collapsed-empty":+ return collapsedContent(outcome, displayName);+ }+}++/** What to say when nothing supplied a fallback list either. */+function nextStep(hasFallback: boolean, displayName: string): string {+ return hasFallback ? provenance(displayName) : "Press c to type a model id directly.";+}++type Failed = Extract<PickerDiscoveryOutcome, { kind: "failed" }>;+type EmptyRoster = Extract<PickerDiscoveryOutcome, { kind: "empty-roster" }>;+type AllFiltered = Extract<PickerDiscoveryOutcome, { kind: "all-filtered" }>;+type Collapsed = Extract<PickerDiscoveryOutcome, { kind: "collapsed-empty" }>;++/**+ * THE WORDS ARE THE FORMATTER'S, NOT THIS FILE'S. `notice` arrives from+ * `formatDiscoveryFailureNotice` — the same array the stderr path writes — so the panel+ * and the scrollback line cannot drift apart. All that happens here is one row per+ * line, and the HTTP status moved into a chip.+ */+function failedContent({ failure, notice, fallbackRows }: Failed, _name: string): NoticeContent {+ const badge = failure.status === undefined ? undefined : `HTTP ${failure.status}`;+ const lines: string[] = [];+ for (const raw of notice) {+ const line = oneRow(raw);+ if (line === "") continue;+ // De-duplicate the status: it is the badge now, and spending nine columns of a+ // 78-column headline saying it twice costs the end of the sentence.+ lines.push(badge === undefined ? line : line.replace(` (${badge})`, ""));+ }+ return {+ severity: "error",+ lines,+ ...(badge === undefined ? {} : { badge }),+ title: fallbackRows.length > 0 ? "discovery failed · showing catalog" : "discovery failed",+ };+}++/**+ * NOTICE, NOT ERROR, and the distinction is the point: an endpoint that answers+ * correctly with nothing has not failed. Painting it red would teach the user to+ * ignore red. It stays visibly distinct from a rejected key in BOTH tier and copy,+ * which is what V7 asks for.+ */+function emptyRosterContent({ failure, fallbackRows }: EmptyRoster, name: string): NoticeContent {+ const at = failure.endpoint ? ` — the endpoint answered at ${failure.endpoint}` : "";+ return {+ severity: "notice",+ lines: [+ `${name}'s model list is empty${at} and listed nothing.`,+ nextStep(fallbackRows.length > 0, name),+ ],+ title: "empty roster",+ };+}++/**+ * The sample ids are what make this self-explaining: they are almost always+ * embeddings, speech models or wildcard routes, which a reader recognises at a glance+ * — and without them "none of them chat-capable" sounds like claudish's fault.+ */+function allFilteredContent(+ { servedCount, sampleIds, fallbackRows }: AllFiltered,+ name: string+): NoticeContent {+ const lines = [+ `${name} served ${servedCount} model${servedCount === 1 ? "" : "s"}, none of them chat-capable.`,+ ];+ if (sampleIds.length > 0) lines.push(`e.g. ${sampleIds.join(", ")}`);+ lines.push(nextStep(fallbackRows.length > 0, name));+ return { severity: "notice", lines, title: "nothing chat-capable" };+}++/** Defensive: unreachable through the one shipped resolver, and still rendered. */+function collapsedContent({ chatCount, fallbackRows }: Collapsed, name: string): NoticeContent {+ const lines = [+ `${chatCount} chat-capable model${chatCount === 1 ? "" : "s"} collapsed to zero choices — please report this.`,+ ];+ if (fallbackRows.length > 0) lines.push(provenance(name));+ return { severity: "notice", lines, title: "no choices" };+}++/**+ * Merge the two credential rows onto one when the width allows.+ *+ * `Check MOONSHOT_API_KEY (…)` and `Get a key: https://…` are one thought and, at+ * the measured 80-column case, 65 columns together — so merging buys a row back for+ * the list at no cost to the words. A long env var plus a long URL does not fit, and+ * then they stay two rows and the banner spends its fourth.+ */+export function mergeCredentialLines(lines: string[], width: number): string[] {+ const i = lines.findIndex((l) => l.startsWith("Check "));+ if (i < 0 || i + 1 >= lines.length) return lines;+ const next = lines[i + 1]!;+ if (!next.startsWith("Get a key:")) return lines;+ // The parenthetical ("a value in your shell overrides stored credentials") is the+ // part that does not fit, and it is advice rather than a fact the user must have —+ // the VARIABLE NAME is the fact, and it survives.+ // `\.?` because the formatter's line ends `(…).` — without it the parenthetical+ // survives, the merge overflows the width test, and the two rows never merge at all.+ const bare = lines[i]!.replace(/\s*\(.*\)\.?\s*$/, "");+ const merged = `${bare} · ${next}`;+ if (merged.length > width) return lines;+ return [...lines.slice(0, i), merged, ...lines.slice(i + 2)];+}++export interface DiscoveryNoticeProps {+ outcome: PickerDiscoveryOutcome;+ displayName: string;+ /** Usable columns, for truncation and for the merge decision. */+ width: number;+ /** Terminal rows, so the banner can choose its chrome budget. */+ height: number;+ /** Hard cap on content rows. 4 borderless, 6 inside a border. */+ maxLines: number;+ /** A full rounded border (2 rows) instead of the 1-column left rule (0 rows). */+ bordered: boolean;+}++/**+ * THE BANNER'S ROW BUDGET IS A BUDGET, NOT A PRIORITY ORDER — four rows at+ * `height < 30`, and the four lines that must never be dropped do not fit in four+ * rows WITH a border (the border alone is two of them). That contradiction is+ * resolved by measurement rather than by ranking: below 30 rows the banner is a+ * 1-column left rule in the severity colour, which costs one COLUMN and zero ROWS.+ *+ * Lines past `maxLines` are dropped from the END, which is the same order the design+ * names — the upstream `detail` body goes first because it is already the tail of+ * the truncated headline, then the sample ids. The full text is never lost: it goes+ * to the deferred stderr write after teardown, and to the debug log.+ */+export function DiscoveryNotice({+ outcome,+ displayName,+ width,+ maxLines,+ bordered,+}: DiscoveryNoticeProps): ReactNode {+ const content = discoveryNoticeContent(outcome, displayName);+ if (content === null) return null;+ const merged = mergeCredentialLines(content.lines, width);+ return (+ <ErrorBanner+ severity={content.severity}+ lines={merged.slice(0, Math.max(1, maxLines))}+ width={width}+ title={content.title}+ bordered={bordered}+ {...(content.badge === undefined ? {} : { badge: content.badge })}+ />+ );+}diff --git a/packages/cli/src/picker/ModelPicker.test.tsx b/packages/cli/src/picker/ModelPicker.test.tsxnew file mode 100644index 00000000..0ec8416c--- /dev/null+++ b/packages/cli/src/picker/ModelPicker.test.tsx@@ -0,0 +1,314 @@+import { describe, expect, test } from "bun:test";+/** @jsxImportSource @opentui/react */+/**+ * Tier 2 — `testRender` over the real component tree, with the loaders injected.+ *+ * `renderOnce()` IS MANDATORY before every capture, or every cell comes back as+ * unpainted filler and the assertion measures nothing.+ *+ * TWO CAPTURES, TWO BLINDNESSES. `captureCharFrame()` sees text and layout and is+ * BLIND to a heat row of coloured spaces and to a one-column stub of background left+ * behind by a squeezed widget — a whole character-level suite once passed over a mangled+ * row. `captureSpans()` sees colour, which is where the severity tiers and the gradient+ * live. Both are used here, for the things each can decide.+ *+ * THE DATA SOURCE IS A PARAMETER, NEVER `mock.module()`: mocking shared infrastructure+ * bleeds across Bun's module registry and breaks sibling e2e files.+ */+import type { CapturedFrame } from "@opentui/core";+import { testRender } from "@opentui/react/test-utils";+import type { ReactNode } from "react";+import type { ModelInfo, PickerDiscoveryOutcome } from "../model-selector.js";+import { C } from "../tui/theme.js";+import { ModelPicker } from "./ModelPicker.js";+import type { CatalogLoad, PickerDataSource, RailChoice } from "./PickerDataSource.js";++// ── a scriptable source ──────────────────────────────────────────────────────────++const rail = (over: Partial<RailChoice> = {}): RailChoice => ({+ value: "kimi",+ label: "kimi",+ description: "Direct API",+ billing: "metered",+ envVar: "MOONSHOT_API_KEY",+ hasDiscovery: true,+ discoveryShape: "deadline",+ ...over,+});++const model = (over: Partial<ModelInfo> = {}): ModelInfo => ({+ id: "kimi-k3",+ name: "kimi-k3",+ description: "a model",+ provider: "Kimi",+ contextLength: 1_000_000,+ context: "1M",+ supportsTools: true,+ pricing: { input: "$1", output: "$2", average: "$9.00/1M" },+ ...over,+});++interface FakeOpts {+ roster?: RailChoice[];+ ready?: Record<string, boolean>;+ outcome?: PickerDiscoveryOutcome;+ catalogRows?: ModelInfo[];+ /** Never settles — the in-flight states. */+ hang?: boolean;+}++function fakeSource(opts: FakeOpts = {}): PickerDataSource {+ const roster = opts.roster ?? [rail()];+ const never = new Promise<never>(() => {});+ return {+ providerRoster: () => roster,+ notEnabledLocalProviders: () => [],+ displayName: (p) => (p === "kimi" ? "Kimi / Moonshot" : p),+ async *probeCredentials(names) {+ if (opts.hang) await never;+ for (const n of names) yield [n, opts.ready?.[n] ?? true] as [string, boolean];+ },+ loadCatalog: (): Promise<CatalogLoad> =>+ opts.hang ? never : Promise.resolve({ top: [], recommended: [] }),+ discoverRoster: (): Promise<PickerDiscoveryOutcome> =>+ opts.hang+ ? never+ : Promise.resolve(+ opts.outcome ?? {+ kind: "rows",+ rows: [model()],+ servedCount: 1,+ chatCount: 1,+ }+ ),+ catalogModels: () => (opts.hang ? never : Promise.resolve(opts.catalogRows ?? [])),+ };+}++/** Always destroy in `finally`: a leaked renderer keeps native threads alive and hangs `bun test`. */+async function draw(+ node: ReactNode,+ width = 80,+ height = 24,+ settleMs = 0+): Promise<{ text: string[]; frame: CapturedFrame }> {+ const { renderOnce, captureCharFrame, captureSpans, renderer } = await testRender(node, {+ width,+ height,+ });+ try {+ await renderOnce();+ if (settleMs > 0) {+ await new Promise((r) => setTimeout(r, settleMs));+ await renderOnce();+ }+ return { text: captureCharFrame().split("\n"), frame: captureSpans() };+ } finally {+ renderer.destroy();+ }+}++const joined = (text: string[]): string => text.join("\n");+const bgs = (f: CapturedFrame): Set<string> =>+ new Set(f.lines.flatMap((l) => l.spans.map((s) => s.bg.toInts().slice(0, 3).join())));+const rgb = (hex: string): string =>+ [1, 3, 5].map((i) => Number.parseInt(hex.slice(i, i + 2), 16)).join();++// ── the first frame ──────────────────────────────────────────────────────────────++describe("the first frame", () => {+ test("lists EVERY pickable provider before any probe resolves", async () => {+ // FR-1's structural half: the rail is derived synchronously, so a blank frame is+ // not reachable — not "unlikely", not reachable.+ const roster = ["openrouter", "google", "kimi"].map((v) => rail({ value: v, label: v }));+ const { text } = await draw(+ <ModelPicker source={fakeSource({ roster, hang: true })} onDone={() => {}} />+ );+ for (const name of ["openrouter", "google", "kimi"]) {+ expect(joined(text)).toContain(name);+ }+ });++ test("no rendered row exceeds the frame width, at 80 and at 145", async () => {+ for (const width of [80, 145]) {+ const { text } = await draw(+ <ModelPicker source={fakeSource()} onDone={() => {}} />,+ width,+ width === 80 ? 24 : 45,+ 30+ );+ const over = text.filter((l) => l.length > width);+ expect({ width, over }).toEqual({ width, over: [] });+ }+ });++ test("the footer's hints are present and unclipped at 80×24", async () => {+ const { text } = await draw(+ <ModelPicker source={fakeSource()} onDone={() => {}} />,+ 80,+ 24,+ 30+ );+ // `captureCharFrame()` ends with a trailing newline, so the LAST element is "".+ const footer = text.filter((l) => l.trim() !== "").pop() ?? "";+ for (const hint of ["move", "select", "filter", "pane", "custom", "cancel"]) {+ expect(footer).toContain(hint);+ }+ });+});++// ── provenance: the user's actual complaint ──────────────────────────────────────++describe("a fallback list says it is a fallback", () => {+ const failed: PickerDiscoveryOutcome = {+ kind: "failed",+ failure: {+ kind: "unauthorized",+ provider: "kimi",+ status: 401,+ endpoint: "https://api.moonshot.ai/v1/models",+ },+ notice: [+ "\n⚠ Kimi / Moonshot could not list its models: the API key was rejected (HTTP 401)\n",+ " Check MOONSHOT_API_KEY (a value in your shell overrides stored credentials).\n",+ " Get a key: https://platform.moonshot.cn/\n",+ " Showing Kimi / Moonshot's cloud-catalog entries below — not its live roster.\n\n",+ ],+ fallbackRows: [model()],+ };++ test("the panel title, the per-row mark and the banner all say it", async () => {+ const { text } = await draw(+ <ModelPicker source={fakeSource({ outcome: failed })} onDone={() => {}} />,+ 80,+ 24,+ 40+ );+ const all = joined(text);+ expect(all).toContain("cloud catalog (fallback)");+ expect(all).toContain("cat");+ expect(all).toContain("not its live roster");+ });++ test("a LIVE roster carries no mark and no fallback title — which is what makes the mark a signal", async () => {+ const { text } = await draw(+ <ModelPicker source={fakeSource()} onDone={() => {}} />,+ 80,+ 24,+ 40+ );+ const all = joined(text);+ expect(all).toContain("live roster");+ expect(all).not.toContain("fallback");+ // The mark's COLUMN is reserved on both kinds of list so the cells left of it do+ // not move; what a live row must not carry is the word.+ expect(all.split("\n").filter((l) => /\bcat\b/.test(l))).toEqual([]);+ });++ test("the failed banner names the provider, the kind, the env var and the key URL", async () => {+ const { text } = await draw(+ <ModelPicker source={fakeSource({ outcome: failed })} onDone={() => {}} />,+ 145,+ 45,+ 40+ );+ const all = joined(text);+ expect(all).toContain("Kimi / Moonshot");+ expect(all).toContain("the API key was rejected");+ expect(all).toContain("MOONSHOT_API_KEY");+ expect(all).toContain("platform.moonshot.cn");+ });++ test("the banner never exceeds four rows on a short terminal", async () => {+ const { text } = await draw(+ <ModelPicker source={fakeSource({ outcome: failed })} onDone={() => {}} />,+ 80,+ 24,+ 40+ );+ // The banner sits between the panes and the footer; count the rows carrying its+ // left rule. Four is the whole budget at `height < 30`, chrome included.+ const ruled = text.filter((l) => l.trimStart().startsWith("│") && l.includes("Moonshot"));+ expect(ruled.length).toBeLessThanOrEqual(4);+ });++ test("`empty-roster` renders in the NOTICE tier, without the error wash", async () => {+ // `captureCharFrame` is blind to this: the two tiers differ in COLOUR as well as in+ // words, and the colour is the half a reader sees first.+ const empty: PickerDiscoveryOutcome = {+ kind: "empty-roster",+ failure: { kind: "empty-roster", provider: "kimi", endpoint: "https://api.test/v1/models" },+ fallbackRows: [model()],+ };+ const failedFrame = await draw(+ <ModelPicker source={fakeSource({ outcome: failed })} onDone={() => {}} />,+ 80,+ 24,+ 40+ );+ const emptyFrame = await draw(+ <ModelPicker source={fakeSource({ outcome: empty })} onDone={() => {}} />,+ 80,+ 24,+ 40+ );+ expect(bgs(failedFrame.frame).has(rgb(C.bgError))).toBe(true);+ expect(bgs(emptyFrame.frame).has(rgb(C.bgError))).toBe(false);+ expect(joined(emptyFrame.text)).toContain("empty");+ });+});++// ── colour, which only spans can see ─────────────────────────────────────────────++describe("the context meter is a real gradient", () => {+ test("a wide row's filled cells carry many distinct colours", async () => {+ // The negative control against a flat one-colour bar and against a four-glyph+ // `░▒▓█` ramp — both score 1 here.+ const rows = [+ model({ id: "a", contextLength: 1_000_000, context: "1M" }),+ model({ id: "b", contextLength: 8_000, context: "8K" }),+ ];+ const { frame } = await draw(+ <ModelPicker+ source={fakeSource({+ outcome: { kind: "rows", rows: [rows[0]!, rows[1]!], servedCount: 2, chatCount: 2 },+ })}+ onDone={() => {}}+ />,+ 145,+ 45,+ 40+ );+ const fgs = new Set(+ frame.lines+ .filter((l) => l.spans.some((s) => s.text.includes("█")))+ .flatMap((l) =>+ l.spans.filter((s) => s.text.includes("█")).map((s) => s.fg.toInts().join())+ )+ );+ expect(fgs.size).toBeGreaterThanOrEqual(12);+ });+});++// ── the rail's steady state ──────────────────────────────────────────────────────++describe("the rail", () => {+ test("collapses unready providers into ONE summary row rather than listing them", async () => {+ const roster = ["openrouter", "google", "kimi"].map((v) => rail({ value: v, label: v }));+ const { text } = await draw(+ <ModelPicker+ source={fakeSource({ roster, ready: { openrouter: true, google: false, kimi: false } })}+ onDone={() => {}}+ />,+ 80,+ 24,+ 40+ );+ const all = joined(text);+ expect(all).toContain("openrouter");+ expect(all).toContain("+2 need a key");+ // The two unready ones are ABSENT from the rail, not listed and greyed — the steady+ // state matches the roster the old picker showed.+ expect(all).not.toContain("google");+ });+});diff --git a/packages/cli/src/picker/ModelPicker.tsx b/packages/cli/src/picker/ModelPicker.tsxnew file mode 100644index 00000000..aefd1192--- /dev/null+++ b/packages/cli/src/picker/ModelPicker.tsx@@ -0,0 +1,625 @@+/** @jsxImportSource @opentui/react */+/**+ * picker/ModelPicker.tsx — the picker itself: two panes, one keyboard handler, and+ * nothing else.+ *+ * THIS FILE IS THE PROOF OF THE `tui/` STRUCTURE RULE, which is why it holds so+ * little. The three async domains live in three hooks (`usePickerProviders`,+ * `useCatalogModels`, `useProviderDiscovery`); the column arithmetic lives in+ * `layout.ts`; the rows, the chrome, the stats panel and the notice are each their+ * own module. What is left here is `filter`, `cursor`, `pane`, `selected`, one+ * `useKeyboard`, and composition JSX. If the rule were unusable it would show up+ * here first.+ *+ * NO AWAIT IS EVER SILENT, STRUCTURALLY RATHER THAN BY DILIGENCE. The rail is+ * derived synchronously, so the first frame is complete before any effect runs; every+ * loader is an effect; and every in-flight task draws an affordance whose SHAPE is+ * chosen by what the caller can actually measure — a determinate meter for the+ * credential fan-out (work done over work total), an elapsed-vs-deadline bar for the+ * one discovery path that has a published deadline, and an elapsed-only shimmer for+ * the three that do not. Nothing invents a denominator.+ *+ * CANCELLATION RETURNS A VALUE. Esc and Ctrl+C both call `onDone(null)`; nothing here+ * calls `process.exit`. The bootstrap's `finally` unmounts React and destroys the+ * renderer in that order, which is what restores the terminal with a fetch still in+ * flight.+ */++import type { ScrollBoxRenderable } from "@opentui/core";+import { useKeyboard, useTerminalDimensions } from "@opentui/react";+import { type ReactNode, useEffect, useMemo, useRef, useState } from "react";+import {+ type ModelInfo,+ buildExplicitModelSpec,+ resolveProviderDisplayPrice,+ resolveProviderExternalId,+} from "../model-selector.js";+import { EmptyState } from "../tui/components/EmptyState.js";+import { ErrorBanner } from "../tui/components/ErrorBanner.js";+import { useAnimationFrame } from "../tui/hooks/useAnimationFrame.js";+import { C } from "../tui/theme.js";+import { truncate } from "../tui/viz/text.js";+import { tokens } from "../tui/viz/tokens.js";+import { Panel } from "../tui/viz/widgets.js";+import { DiscoveryNotice } from "./DiscoveryNotice.js";+import {+ DISCOVERY_DEADLINE_MS,+ type DiscoveryShape,+ type PickerDataSource,+} from "./PickerDataSource.js";+import { StatsStrip } from "./StatsStrip.js";+import { FilterStrip, LoadBar, type LoadTask, PickerFooter, PickerHeader } from "./chrome.js";+import { ModelDetail, ProviderDetail } from "./detail.js";+import { useCatalogModels } from "./hooks/useCatalogModels.js";+import { useDelayedVisible } from "./hooks/useDelayedVisible.js";+import { usePickerProviders } from "./hooks/usePickerProviders.js";+import { useProviderDiscovery } from "./hooks/useProviderDiscovery.js";+import { CHROME, derivePanes, deriveRailLayout, deriveRowLayout } from "./layout.js";+import {+ type ListOrigin,+ ModelRow,+ ProviderRailRow,+ RailHintRow,+ contextMeterPct,+ parseDisplayPrice,+ priceMeterPct,+} from "./rows.js";++/**+ * A quiet scrollbar, built PER CALL — `tokens.*` are reassigned in place on theme+ * detection, so a module-level object would copy the strings and pin the dark track+ * onto a light panel. Lifted from `resume-picker.tsx:636-641`, which learned it the+ * same way.+ */+function scrollbarOptions() {+ return {+ showArrows: false,+ trackOptions: { backgroundColor: tokens.bgPanel, foregroundColor: tokens.border },+ } as const;+}++/**+ * WHICH AFFORDANCE EACH IN-FLIGHT TASK EARNS — the honesty contract, as one pure+ * function so it can be asserted without a renderer.+ *+ * The credential sweep is the only task with a real denominator: the roster is derived+ * synchronously, so `done/total` is work done over work TOTAL. The GET half of+ * discovery has a published DEADLINE and gets an elapsed-vs-deadline bar whose label+ * says `deadline`, because a deadline is not progress. Everything else gets an elapsed+ * figure and a shimmer, which claims only that time is passing.+ *+ * There is deliberately NO `resolving prices` task. `buildDiscoveredModelOutcome`+ * resolves pricing inside the same await as the roster (the fallback leg it already+ * needed supplies it), so there is no second phase — and drawing a label for a phase+ * that never runs is the same lie as an invented denominator.+ */+export function buildLoadTasks(input: {+ creds: { done: number; total: number } | null;+ catalog: boolean;+ roster: { displayName: string; shape: DiscoveryShape; elapsed: number } | null;+ vendor: string | null;+}): LoadTask[] {+ const tasks: LoadTask[] = [];+ if (input.creds) {+ const { done, total } = input.creds;+ tasks.push({+ id: "creds",+ label: "checking credentials",+ pct: total > 0 ? (100 * done) / total : 0,+ value: `${done}/${total}`,+ });+ }+ if (input.catalog) tasks.push({ id: "catalog", label: "cloud catalog" });+ if (input.roster) {+ const { displayName, shape, elapsed } = input.roster;+ const secs = `${(elapsed / 1000).toFixed(1)}s`;+ tasks.push(+ shape === "deadline"+ ? {+ id: "roster",+ // `deadline` rather than `roster · deadline`: MEASURED at 145 columns with+ // three tasks sharing the row, the longer label truncated to+ // `OpenRouter roster · …` — dropping the one word that says this bar is a+ // clock and not a count of work done. The shortest label that keeps it wins.+ label: `${displayName} deadline`,+ pct: Math.min(100, (100 * elapsed) / DISCOVERY_DEADLINE_MS),+ value: `${secs} / ${(DISCOVERY_DEADLINE_MS / 1000).toFixed(1)}s`,+ }+ : { id: "roster", label: `${displayName} roster`, value: secs }+ );+ }+ if (input.vendor !== null) tasks.push({ id: "vendor", label: `${input.vendor} catalog` });+ return tasks;+}++export interface ModelPickerProps {+ source: PickerDataSource;+ /** A model spec, or `null` for cancelled. Called exactly once. */+ onDone: (spec: string | null) => void;+ /** Buffers a failed provider's diagnostic for the ONE write after teardown. */+ onDiscoveryFailure?: (provider: string, notice: readonly string[]) => void;+}++type Pane = "providers" | "models";+type Mode = "browse" | "filter" | "custom";++export function ModelPicker({ source, onDone, onDiscoveryFailure }: ModelPickerProps): ReactNode {+ const { width, height } = useTerminalDimensions();+ const providers = usePickerProviders(source);++ const [selected, setSelected] = useState<string | null>(null);+ const [pane, setPane] = useState<Pane>("models");+ const [mode, setMode] = useState<Mode>("browse");+ const [filter, setFilter] = useState("");+ const [custom, setCustom] = useState("");+ const [modelCursor, setModelCursor] = useState(0);+ const [showMissing, setShowMissing] = useState(false);++ // A provider whose probe came back `missing` is collapsed out of the rail, so the+ // cursor is pinned to a provider VALUE rather than to an index: an index would slide+ // under the user as ~30 probes settle during the first second.+ const railRows = useMemo(+ () =>+ providers.rows.filter(+ (r) => r.readiness !== "missing" || showMissing || r.value === selected+ ),+ [providers.rows, showMissing, selected]+ );+ const current = selected ?? railRows[0]?.value ?? null;+ const currentRow = providers.rows.find((r) => r.value === current) ?? null;+ const displayName = current === null ? "" : source.displayName(current);+ const hasDiscovery = currentRow?.hasDiscovery === true;++ const discovery = useProviderDiscovery(source, current, hasDiscovery, onDiscoveryFailure);+ const { catalog, list } = useCatalogModels(source, current, !hasDiscovery);++ // ── which list is on screen, and where it came from ──────────────────────────+ //+ // PROVENANCE IS A PROPERTY OF THE LIST, NOT OF A ROW. One value decides all three+ // encodings — the panel title, the per-row `CAT` chip and the banner's provenance+ // sentence — so they cannot disagree with each other. Sniffing `ModelInfo.source`+ // or `providerSlug` was the alternative and was wrong: `source` is a display label+ // set on BOTH paths, and `providerSlug` is set only by the catalog converters, so+ // the discriminant would have been the absence of an optional field.+ const listSource: { rows: ModelInfo[]; origin: ListOrigin; fallback: boolean; loading: boolean } =+ useMemo(() => {+ if (hasDiscovery) {+ const o = discovery.outcome;+ if (o === null) return { rows: [], origin: "roster", fallback: false, loading: true };+ if (o.kind === "rows")+ return { rows: o.rows, origin: "roster", fallback: false, loading: false };+ if (o.kind === "unsupported")+ return { rows: [], origin: "catalog", fallback: false, loading: false };+ return { rows: o.fallbackRows, origin: "catalog", fallback: true, loading: false };+ }+ return {+ rows: list.rows,+ origin: "catalog",+ fallback: false,+ loading: list.phase === "loading",+ };+ }, [hasDiscovery, discovery.outcome, list.rows, list.phase]);++ const shown = useMemo(() => {+ const needle = filter.trim().toLowerCase();+ if (!needle) return listSource.rows;+ return listSource.rows.filter((m) => m.id.toLowerCase().includes(needle));+ }, [listSource.rows, filter]);++ // Meter bounds are taken over the VISIBLE list, so the comparison a reader makes is+ // always against what they can see. Re-derived when the filter changes, which is+ // what makes a narrowed list re-scale rather than flatten.+ const bounds = useMemo(() => {+ const ctx = shown.map((m) => m.contextLength ?? 0).filter((n) => n > 0);+ const prices = shown+ .map((m) =>+ current === null ? undefined : parseDisplayPrice(resolveProviderDisplayPrice(current, m))+ )+ .filter((n): n is number => n !== undefined && n > 0);+ return {+ ctxMin: ctx.length > 0 ? Math.min(...ctx) : 0,+ ctxMax: ctx.length > 0 ? Math.max(...ctx) : 0,+ priceMin: prices.length > 0 ? Math.min(...prices) : 0,+ priceMax: prices.length > 0 ? Math.max(...prices) : 0,+ };+ }, [shown, current]);++ // ── layout ──────────────────────────────────────────────────────────────────+ const panes = derivePanes(width);+ const rowLayout = deriveRowLayout(panes.rowCells, { mark: listSource.fallback });+ const railLayout = deriveRailLayout(panes.railInner);+ const twoRowHeader = height >= CHROME.headerTwoRows;+ const statsPanelled = height >= CHROME.statsPanel;+ const bannerBordered = height >= CHROME.bannerBordered;+ const bannerMax = bannerBordered ? 6 : 4;+ // A banner line sized to `width - 2` wrapped by exactly one column — MEASURED, and+ // the reason for the slack rather than the arithmetic: the box spends a border column+ // and a padding column, and the row still wanted one more. A wrapped line costs a row+ // out of a four-row budget, which is the one thing this banner cannot afford.+ const bannerWidth = width - 4;++ // ── in-flight affordances ───────────────────────────────────────────────────+ const busy =+ providers.probing || catalog.phase === "loading" || discovery.busy || listSource.loading;+ const frame = useAnimationFrame(busy);+ const showCreds = useDelayedVisible(providers.probing);+ const showCatalog = useDelayedVisible(catalog.phase === "loading");+ const showRoster = useDelayedVisible(discovery.busy);+ const showVendor = useDelayedVisible(listSource.loading && !hasDiscovery);++ const tasks = buildLoadTasks({+ creds: showCreds ? { done: providers.done, total: providers.total } : null,+ catalog: showCatalog,+ roster:+ showRoster && current !== null+ ? {+ displayName,+ shape: currentRow?.discoveryShape ?? "none",+ elapsed: discovery.startedAt === null ? 0 : Date.now() - discovery.startedAt,+ }+ : null,+ vendor: showVendor ? displayName : null,+ });++ // ── scroll sync: the cursor leads, the viewport follows ─────────────────────+ const modelScroll = useRef<ScrollBoxRenderable | null>(null);+ const railScroll = useRef<ScrollBoxRenderable | null>(null);+ useEffect(() => {+ const sb = modelScroll.current;+ if (!sb || shown.length === 0) return;+ const viewportH = sb.viewport.height;+ const top = sb.scrollTop;+ if (modelCursor < top) sb.scrollTo({ x: 0, y: modelCursor });+ else if (modelCursor >= top + viewportH) sb.scrollTo({ x: 0, y: modelCursor - viewportH + 1 });+ }, [modelCursor, shown.length]);+ useEffect(() => {+ const sb = railScroll.current;+ if (!sb) return;+ const i = railRows.findIndex((r) => r.value === current);+ if (i < 0) return;+ const viewportH = sb.viewport.height;+ const top = sb.scrollTop;+ if (i < top) sb.scrollTo({ x: 0, y: i });+ else if (i >= top + viewportH) sb.scrollTo({ x: 0, y: i - viewportH + 1 });+ }, [current, railRows]);++ // The cursor can outlive the list it indexed — a filter keystroke, or a provider+ // whose roster came back shorter than the last one's.+ useEffect(() => {+ setModelCursor((c) => Math.max(0, Math.min(c, Math.max(0, shown.length - 1))));+ }, [shown.length]);++ // ── keys: ONE handler, because `useKeyboard` is a BROADCAST ─────────────────+ //+ // Every mounted subscriber receives every key — no bubbling, no `stopPropagation` —+ // so mutual exclusion is hand-rolled. Two mutually exclusive halves: a text mode owns+ // every printable key, and browse mode owns the commands. Both modes are explicit+ // (entered with `/` and `c`) rather than type-to-filter, because `c` and `k` are+ // commands here and a filter that swallowed them would put the custom-spec hatch out+ // of reach — the cost `resume-picker.tsx` pays for `a` and `v`.+ const handleTextKey = (key: { name?: string; raw?: string }): void => {+ const name = key.name;+ const setter = mode === "custom" ? setCustom : setFilter;+ if (name === "escape") {+ if (mode === "filter") setFilter("");+ setMode("browse");+ return;+ }+ if (name === "return" || name === "enter") {+ if (mode === "custom") {+ const spec = custom.trim();+ if (spec) onDone(spec);+ return;+ }+ setMode("browse");+ setPane("models");+ return;+ }+ if (name === "backspace") {+ setter((v) => v.slice(0, -1));+ return;+ }+ const ch = key.raw;+ if (ch && ch.length === 1 && ch >= " " && ch !== "\x7f") {+ setter((v) => v + ch);+ setModelCursor(0);+ }+ };++ useKeyboard((key) => {+ const name = key.name;+ if (key.ctrl && name === "c") {+ onDone(null);+ return;+ }+ if (mode === "custom" || mode === "filter") {+ handleTextKey(key);+ return;+ }++ if (name === "escape") {+ if (filter) {+ setFilter("");+ return;+ }+ onDone(null);+ return;+ }+ if (name === "tab") {+ setPane((p) => (p === "providers" ? "models" : "providers"));+ return;+ }+ if (name === "left") {+ setPane("providers");+ return;+ }+ if (name === "right") {+ setPane("models");+ return;+ }+ if (name === "up" || name === "down") {+ const d = name === "up" ? -1 : 1;+ if (pane === "providers") {+ const i = railRows.findIndex((r) => r.value === current);+ const next = railRows[Math.max(0, Math.min(railRows.length - 1, (i < 0 ? 0 : i) + d))];+ if (next) {+ setSelected(next.value);+ setModelCursor(0);+ }+ return;+ }+ setModelCursor((c) => Math.max(0, Math.min(shown.length - 1, c + d)));+ return;+ }+ if (name === "return" || name === "enter") {+ if (pane === "providers") {+ setPane("models");+ return;+ }+ const model = shown[modelCursor];+ if (model && current !== null) {+ // The SAME spec builder the classic path uses, with the provider's own+ // externalId — `or@openai/gpt-5`, not the catalog's bare key. Every row is+ // provider-scoped, so no bare Claude name can leave this picker.+ onDone(buildExplicitModelSpec(current, resolveProviderExternalId(current, model)));+ }+ return;+ }+ if (name === "slash" || key.raw === "/") {+ setMode("filter");+ setPane("models");+ return;+ }+ if (key.raw === "c") {+ setMode("custom");+ return;+ }+ if (key.raw === "k") {+ setShowMissing((v) => !v);+ return;+ }+ if (key.raw === "@") {+ setPane("providers");+ }+ });++ // ── panel titles: the first of the three provenance encodings ───────────────+ const listLabel = listSource.fallback+ ? "cloud catalog (fallback)"+ : listSource.origin === "roster"+ ? "live roster"+ : "cloud catalog";+ // MEASURED: a title that fills the border exactly is DROPPED — `Panel` renders no+ // title at all rather than a clipped one, which turned the loudest provenance+ // encoding into an empty border. Six columns of slack, and the `⚠` that used to+ // prefix the fallback label is gone with it: the word `fallback` carries the meaning,+ // and `Panel`'s title colour is fixed chrome, so a glyph there could not have been+ // coloured to add anything.+ // The PROVENANCE must survive the truncation, so the title spends nothing on a word+ // the panel's own position already says. `models · …` was the first casualty of a+ // title clipped at 52 columns — and the half it clipped was `(fallback)`.+ const panelTitle = truncate(+ `${displayName || "—"} · ${listSource.rows.length} · ${listLabel}`,+ Math.max(8, panes.panelOuter - 8)+ );++ const missingCount = providers.missing.length;+ const notEnabled = providers.notEnabledLocal.length;+ // THE DETAIL BLOCKS ARE HEIGHT-GATED, and 26 rows is where the trade flips. Below it+ // every row belongs to the list, and two rows of prose would cost two GRAPHICS rows —+ // the wrong direction for the whole-frame density count. Above it a short list leaves+ // its panel half empty, and the description the inquirer picker used to show has+ // somewhere to go.+ const showDetail = height >= CHROME.detail;+ const cursorModel = shown[modelCursor] ?? null;+ const cursorSpec =+ cursorModel === null || current === null+ ? null+ : buildExplicitModelSpec(current, resolveProviderExternalId(current, cursorModel));++ return (+ <box flexDirection="column" height={height} backgroundColor={C.bg}>+ <PickerHeader+ right={`${providers.ready.length}/${providers.total} ready · ${catalog.phase === "failed" ? "catalog offline" : `${catalog.size} catalogued`}`}+ twoRows={twoRowHeader}+ />++ <LoadBar tasks={tasks} frame={frame} width={width} />++ <box flexDirection="row" flexGrow={1} minHeight={0} gap={1}>+ {/* ── provider rail ───────────────────────────────────────────────── */}+ <box width={panes.railW} flexDirection="column" minHeight={0}>+ <Panel title="providers" focused={pane === "providers"} flush flexGrow={1} flexBasis={0}>+ <scrollbox+ ref={railScroll}+ focused={false}+ flexGrow={1}+ scrollbarOptions={scrollbarOptions()}+ >+ {railRows.map((r) => (+ <ProviderRailRow+ key={r.value}+ label={r.label}+ readiness={r.readiness}+ billing={r.billing}+ count={r.value === current ? listSource.rows.length : null}+ cursor={r.value === current}+ focused={pane === "providers"}+ layout={railLayout}+ />+ ))}+ {/* An unexplained absence is the defect class this feature is about, so+ both absences are named. Neither row is selectable. */}+ {missingCount > 0 && !showMissing ? (+ <RailHintRow+ text={`+${missingCount} need a key · k`}+ width={railLayout.railInner}+ />+ ) : null}+ {notEnabled > 0 ? (+ <RailHintRow+ text={`+${notEnabled} local not enabled`}+ width={railLayout.railInner}+ />+ ) : null}+ </scrollbox>+ {/* Pinned UNDER the list, so a short rail's leftover space carries the+ selected provider's own copy instead of a void. `flexShrink={0}` lives+ inside the component: the scrollbox above asks for its entire content+ height and Yoga spreads that shortfall across every sibling. */}+ {showDetail && currentRow !== null ? (+ <ProviderDetail+ label={displayName}+ description={currentRow.description}+ envVar={currentRow.envVar}+ width={railLayout.railInner}+ />+ ) : null}+ </Panel>+ </box>++ {/* ── models + filter + shape ──────────────────────────────────────── */}+ <box flexDirection="column" flexGrow={1} minWidth={0} minHeight={0}>+ <Panel title={panelTitle} focused={pane === "models"} flush flexGrow={1} flexBasis={0}>+ <scrollbox+ ref={modelScroll}+ focused={false}+ flexGrow={1}+ scrollbarOptions={scrollbarOptions()}+ >+ {shown.length === 0 ? (+ <EmptyState+ label={emptyLabel(+ listSource.loading,+ filter,+ listSource.rows.length,+ displayName+ )}+ {...(filter ? { hint: "esc clears the filter · c types a spec" } : {})}+ />+ ) : (+ shown.map((m, i) => (+ <ModelRow+ key={`${m.id}-${i}`}+ model={m}+ layout={rowLayout}+ cursor={i === modelCursor}+ ctxPct={contextMeterPct(m.contextLength, bounds.ctxMin, bounds.ctxMax)}+ pricePct={priceMeterPct(+ parseDisplayPrice(+ current === null ? "N/A" : resolveProviderDisplayPrice(current, m)+ ),+ bounds.priceMin,+ bounds.priceMax+ )}+ priceText={current === null ? "N/A" : resolveProviderDisplayPrice(current, m)}+ origin={listSource.fallback ? "catalog" : "roster"}+ />+ ))+ )}+ </scrollbox>+ {/* What Enter will actually return, plus the description the old picker+ showed and this one would otherwise drop. */}+ {showDetail ? (+ <ModelDetail model={cursorModel} spec={cursorSpec} width={panes.panelOuter - 2} />+ ) : null}+ </Panel>++ <FilterStrip+ value={mode === "custom" ? custom : filter}+ active={mode !== "browse"}+ matches={shown.length}+ total={listSource.rows.length}+ width={panes.panelOuter}+ prompt={mode === "custom" ? "provider@model" : "filter"}+ />++ <StatsStrip+ shown={shown}+ total={listSource.rows.length}+ width={panes.panelOuter}+ panelled={statsPanelled}+ priceOf={(m) => (current === null ? "" : resolveProviderDisplayPrice(current, m))}+ />+ </box>+ </box>++ {/* The notice is pinned BELOW both panes and spans the full width: the failure is+ the context for the list above it, and a pinned region is the half of the fix+ the old inline stderr line could not provide. */}+ {discovery.outcome !== null && current !== null ? (+ <DiscoveryNotice+ outcome={discovery.outcome}+ displayName={displayName}+ width={bannerWidth}+ height={height}+ maxLines={bannerMax}+ bordered={bannerBordered}+ />+ ) : null}+ {catalog.phase === "failed" ? (+ <ErrorBanner+ severity="notice"+ lines={["The cloud catalog is unavailable — prices and capability flags may be missing."]}+ width={width - 2}+ />+ ) : null}+ {!hasDiscovery && list.phase === "failed" && current !== null ? (+ <ErrorBanner+ severity="notice"+ lines={[`${displayName}'s catalog list could not be loaded. Press c to type a spec.`]}+ width={bannerWidth}+ />+ ) : null}++ <PickerFooter+ hints={[+ { key: "↑↓", label: "move" },+ { key: "⏎", label: pane === "providers" ? "models" : "select" },+ { key: "/", label: "filter" },+ { key: "⇥", label: "pane" },+ {+ key: "k",+ label: missingCount > 0 ? `${missingCount} hidden` : "hidden",+ on: missingCount > 0,+ },+ { key: "c", label: "custom" },+ { key: "esc", label: filter ? "clear" : "cancel" },+ ]}+ />+ </box>+ );+}++/**+ * SAY WHICH EMPTY IT IS. "Nothing here" covers four different situations — still+ * loading, loaded and genuinely empty, filtered to nothing, and failed — and a picker+ * that prints one sentence for all four is the complaint this feature exists to fix.+ * The failed case never reaches here: it goes to the banner, which has a colour.+ */+function emptyLabel(loading: boolean, filter: string, total: number, displayName: string): string {+ if (loading) return `loading ${displayName || "models"}…`;+ if (filter) return `no model matches “${filter}”`;+ if (total === 0) return `no catalog entries for ${displayName || "this provider"}`;+ return "nothing to show";+}diff --git a/packages/cli/src/picker/PickerDataSource.ts b/packages/cli/src/picker/PickerDataSource.tsnew file mode 100644index 00000000..294008e5--- /dev/null+++ b/packages/cli/src/picker/PickerDataSource.ts@@ -0,0 +1,214 @@+/**+ * picker/PickerDataSource.ts — the four slow things the picker needs, behind one+ * interface, plus the production implementation that wraps the existing functions+ * verbatim.+ *+ * THIS SEAM EXISTS BECAUSE THE STATES THAT MATTER CANNOT BE PHOTOGRAPHED+ * OTHERWISE. The whole feature is about what the picker shows when discovery+ * FAILS, serves nothing, or is still in flight — and of those, only "unauthorized"+ * is reproducible against a live provider (a bogus key, a real 401). An empty+ * roster, a roster where nothing is chat-capable, a network timeout and the+ * in-flight frames themselves are not reachable from outside, and the warm catalog+ * path settles faster than a screenshot can catch. So the loaders are a parameter,+ * a scriptable fake drives the capture runs, and the production impl is the+ * default.+ *+ * NOT `mock.module()`: mocking shared infrastructure bleeds across Bun's module+ * registry and breaks sibling e2e files (`feedback_no_mock_module_bleed`). An+ * injected interface cannot leak into another test file.+ *+ * EVERY MEMBER'S SYNC/ASYNC SHAPE IS PART OF THE CONTRACT. `providerRoster`,+ * `displayName`, `notEnabledLocalProviders` and `discoveryShape` are SYNCHRONOUS+ * because the first frame must render the full rail before any await (FR-1 is met+ * structurally, not by diligence), and because §4.3's indicator shape has to be+ * chosen before the fetch it describes begins. `probeCredentials` is an+ * AsyncIterable rather than a `Promise<Map>` for the same reason: the rail fills in+ * as each probe settles, which is the real loading affordance, and a single+ * awaited map would hide ~30 probes behind one silent pause.+ */++import { credentials } from "../auth/credentials/authority.js";+import { isSubscriptionProvider } from "../handlers/shared/remote-provider-types.js";+import {+ type ModelInfo,+ type PickerDiscoveryOutcome,+ buildDiscoveredModelOutcome,+ buildProviderChoices,+ loadModelsForPickerProvider,+ loadPickerCatalog,+} from "../model-selector.js";+import { isLocalProviderEnabled } from "../profile-config.js";+import { createCatalogClient } from "../providers/model-catalog.js";+import { getAllProviders, getProviderByName } from "../providers/provider-definitions.js";++/** How a provider bills — the rail's tag, and the reason a price meter may be absent. */+export type BillingMode = "sub" | "local" | "metered";++/**+ * Which in-flight indicator a roster discovery earns (§4.3), decided+ * synchronously from the provider's discovery format.+ *+ * `deadline` is the GET half, the only path that sees `FETCH_TIMEOUT_MS` — so an+ * elapsed-vs-deadline bar can be drawn and LABELLED as a deadline. `elapsed` is+ * the registered-fetcher half (ollama-tags, devin-connect, antigravity), where this+ * module owns no deadline at all: inventing 5 000 ms, or copying Ollama's 3 000 ms+ * onto Devin, would be a guess rendered as a fact. An elapsed counter with no+ * denominator makes exactly one claim — time is passing — and that claim is true.+ */+export type DiscoveryShape = "deadline" | "elapsed" | "none";++/** One provider rail row, as the view needs it on frame one. */+export interface RailChoice {+ /** `ProviderDefinition.name` — the value every other call is keyed by. */+ value: string;+ /**+ * What the RAIL prints. Production sets the provider's routing name (`ollama`,+ * `qwen-cloud`) rather than its editorial display name, for two reasons: the rail+ * has 9–10 columns, and the routing name is the string the user can type as a+ * `provider@` prefix. The editorial name goes in the model panel's title and in+ * every notice, where there is room for it — `displayName()` answers that.+ */+ label: string;+ description: string;+ billing: BillingMode;+ /** The env var to name in a credential notice. Empty for OAuth-only providers. */+ envVar: string;+ /** Does this provider list its own live roster? Decides effect C vs effect D. */+ hasDiscovery: boolean;+ discoveryShape: DiscoveryShape;+}++/** What the cross-vendor catalog load (A2) yields. */+export interface CatalogLoad {+ /** The newest-first top list — the corpus behind the `NEW` marker. */+ top: ModelInfo[];+ /** claudish's recommended entries — the corpus behind the `REC` marker. */+ recommended: ModelInfo[];+}++export interface PickerDataSource {+ /** Sync, so frame one is never blank: the rail is derived from definitions. */+ providerRoster(): RailChoice[];+ /** Built-in local providers present in the catalog but not enabled in config (§3.9). */+ notEnabledLocalProviders(): string[];+ /** The provider's editorial display name, for panel titles and notices. */+ displayName(provider: string): string;+ /** Readiness per provider, yielded AS EACH SETTLES — never one awaited map. */+ probeCredentials(names: string[]): AsyncIterable<[string, boolean]>;+ /** A2 — the cross-vendor catalog. */+ loadCatalog(): Promise<CatalogLoad>;+ /** A9 ∥ A12 — one settled outcome per discovery provider, `fallbackRows` included. */+ discoverRoster(provider: string): Promise<PickerDiscoveryOutcome>;+ /** A12 — the vendor catalog list for a provider that has no discovery. */+ catalogModels(provider: string): Promise<ModelInfo[]>;+}++/** How a provider bills, from the two oracles that already answer it. */+export function billingModeOf(provider: string): BillingMode {+ if (isSubscriptionProvider(provider)) return "sub";+ return getProviderByName(provider)?.isLocal === true ? "local" : "metered";+}++/**+ * Which indicator shape a provider's discovery earns.+ *+ * `openai-models-list` is the one format that runs through the GET half, which is+ * the only place `FETCH_TIMEOUT_MS` is referenced. Everything else is a registered+ * fetcher with its own, unpublished deadline.+ */+export function discoveryShapeOf(provider: string): DiscoveryShape {+ const format = getProviderByName(provider)?.modelDiscovery?.format;+ if (!format) return "none";+ return format === "openai-models-list" ? "deadline" : "elapsed";+}++/** The deadline the `deadline` shape is drawn against. Mirrors `FETCH_TIMEOUT_MS`. */+export const DISCOVERY_DEADLINE_MS = 5000;++/**+ * Yield each promise's value as it settles, in COMPLETION order.+ *+ * `Promise.all` would hold every result until the slowest one lands, which is the+ * silent pause this whole design exists to remove: one 1Password handshake is+ * multi-second, and with `all` it would freeze ~30 rows that had already answered.+ *+ * A rejection is mapped by the caller, never here — a generator that throws+ * mid-iteration would abandon the probes that had not yet been drained.+ */+async function* inCompletionOrder<T>(promises: Array<Promise<T>>): AsyncGenerator<T> {+ const live = new Map(promises.map((p, i) => [i, p.then((v) => ({ i, v }))]));+ while (live.size > 0) {+ const { i, v } = await Promise.race(live.values());+ live.delete(i);+ yield v;+ }+}++/**+ * The production data source. Every method wraps an existing function verbatim —+ * no new fetch, no new field, no new plumbing.+ *+ * ONE `CatalogClient` PER PICKER OPEN, captured here rather than per call, so the+ * 24 h slim-cache read and the per-vendor memo are shared by every list the picker+ * renders. `selectModel` made the same choice for the same reason.+ */+export function createPickerDataSource(): PickerDataSource {+ const catalog = createCatalogClient();+ // Resolved once per open. `buildProviderChoices()` is pure and derived — never a+ // membership table (`routing.md:139`) — so calling it twice would be free but+ // would also let the rail and the notices disagree about ordering.+ const choices = buildProviderChoices().filter((c) => c.value !== "skip" && c.value !== "custom");+ const names = new Map(choices.map((c) => [c.value, c.name]));++ return {+ providerRoster(): RailChoice[] {+ return choices.map((c) => ({+ value: c.value,+ label: c.value,+ description: c.description,+ billing: billingModeOf(c.value),+ envVar: getProviderByName(c.value)?.apiKeyEnvVar ?? "",+ hasDiscovery: Boolean(getProviderByName(c.value)?.modelDiscovery),+ discoveryShape: discoveryShapeOf(c.value),+ }));+ },++ notEnabledLocalProviders(): string[] {+ // Derived, so `routing.md:139` holds: no membership list to keep current.+ // `isLocalProviderEnabled` is a pure config read — it never probes a daemon,+ // which is why a dead LM Studio is NOT what this row is about.+ return getAllProviders()+ .filter((d) => d.isLocal === true && !isLocalProviderEnabled(d.name))+ .map((d) => d.name);+ },++ displayName(provider: string): string {+ return names.get(provider) ?? provider;+ },++ probeCredentials(providers: string[]): AsyncIterable<[string, boolean]> {+ return inCompletionOrder(+ providers.map(+ async (name): Promise<[string, boolean]> => [+ name,+ // Documented never to throw (`authority.ts:110-117`), guarded anyway:+ // behind a live renderer an unhandled rejection has nowhere to surface.+ await credentials.isAvailable(name).catch(() => false),+ ]+ )+ );+ },++ loadCatalog(): Promise<CatalogLoad> {+ return loadPickerCatalog();+ },++ discoverRoster(provider: string): Promise<PickerDiscoveryOutcome> {+ return buildDiscoveredModelOutcome(provider, names.get(provider) ?? provider, catalog);+ },++ catalogModels(provider: string): Promise<ModelInfo[]> {+ return loadModelsForPickerProvider(provider, catalog);+ },+ };+}diff --git a/packages/cli/src/picker/StatsStrip.tsx b/packages/cli/src/picker/StatsStrip.tsxnew file mode 100644index 00000000..a0b08abf--- /dev/null+++ b/packages/cli/src/picker/StatsStrip.tsx@@ -0,0 +1,283 @@+/** @jsxImportSource @opentui/react */+/**+ * picker/StatsStrip.tsx — the graphics panel that carries the WHOLE-FRAME density+ * count.+ *+ * IT IS HERE PRE-EMPTIVELY, not after a failed screenshot. The aesthetic contract+ * counts graphics rows against text rows twice: once per panel, and then again over+ * the entire capture — and the skill records a build where every panel passed the+ * first count and the frame was still 28 of 38 rows of text. The provider rail is+ * text (a glyph is not a graphic) and the filter, header and footer are text, so a+ * frame of model rows alone sits near the line. Three rows of bar, spark and meter+ * put it clear of it, and they are rows a reader genuinely uses: what the visible+ * list is made of.+ *+ * THE COLLAPSE IS GATED ON HEIGHT, NOT WIDTH. At 80 columns the right-hand column+ * still has ~57 usable cells — ample for a stacked bar and a sparkline. What is+ * scarce at 80×24 is ROWS. So a short terminal drops the BORDER and the `shown` row+ * (whose count the filter strip already prints) and keeps both graphics rows; an+ * earlier design collapsed on width, to one row, and cost the frame exactly the+ * density this panel exists to supply.+ */++import type { ReactNode } from "react";+import type { ModelInfo } from "../model-selector.js";+import { C, isLightTheme } from "../tui/theme.js";+import { darken, lighten } from "../tui/viz/color.js";+import { padStartTo, padTo } from "../tui/viz/text.js";+import { ramps, tokens } from "../tui/viz/tokens.js";+import { Meter, Panel, Sparkline, StackedBar } from "../tui/viz/widgets.js";+import { parseDisplayPrice } from "./rows.js";++/**+ * PRICE BANDS — the second distribution, and the one that replaced a capability bar.+ *+ * MEASURED, twice. The capability mix is a single category on a subscription roster (the+ * discovery path resolves `supportsTools` and nothing else) AND on every aggregator list+ * (the slim catalog carries no `tools` flag at all), so its bar painted one flat+ * rectangle on both — the aesthetic contract's own negative control, twice over, for a+ * fact the per-row `[TRV]` column already states. Price spreads on every real list, it+ * is what a reader is choosing on, and it complements the context bands rather than+ * repeating them.+ *+ * Fixed absolute edges, not quantiles: "under a dollar per million" is a threshold a+ * reader already holds, while a quantile scale would move under them as the list+ * filtered.+ */+const PRICE_BANDS: ReadonlyArray<{ label: string; max: number }> = [+ { label: "free", max: 0.0001 },+ { label: "<$1", max: 1 },+ { label: "<$5", max: 5 },+ { label: "$5+", max: Number.POSITIVE_INFINITY },+];++/**+ * Models with a per-token rate, bucketed. Flat-rate and unpriced rows are excluded.+ *+ * `priceOf` IS THE CALLER'S, and it must be the same function the ROWS print — MEASURED:+ * reading `m.pricing.average` directly banded all 349 of OpenRouter's models as+ * "unpriced" while every row on screen showed a dollar figure, because an aggregator's+ * real rate lives in its `aggregators[]` entry and `resolveProviderDisplayPrice` is the+ * one function allowed to resolve it. A panel that disagrees with the rows above it is+ * worse than no panel.+ */+export function priceMix(+ models: readonly ModelInfo[],+ priceOf: (m: ModelInfo) => string = (m) => m.pricing?.average ?? ""+): number[] {+ const out = PRICE_BANDS.map(() => 0);+ for (const m of models) {+ const display = priceOf(m);+ // `FREE` is the catalog's own normalisation of `$0.00/1M` (`model-loader.ts:550`),+ // so it carries no digits to parse — and dropping it would hide the cheapest band+ // from the bar that exists to show it. `SUB`/`LOCAL` stay excluded: a flat-rate plan+ // has no point on a per-token axis, and putting it at zero would claim it is free.+ const n = display === "FREE" ? 0 : parseDisplayPrice(display);+ if (n === undefined) continue;+ const i = PRICE_BANDS.findIndex((b) => n < b.max);+ out[i < 0 ? PRICE_BANDS.length - 1 : i]! += 1;+ }+ return out;+}++/**+ * Fit a series to a column budget, because a `Sparkline` paints ONE COLUMN PER+ * SAMPLE and cannot apportion (`Meter` and `StackedBar` can; these two cannot).+ *+ * 342 models in a 48-column slot would paint 342 columns and overflow the panel;+ * 12 models in a 48-column slot paint 12 and leave a 36-column hole that a+ * screenshot fails the panel for. So: bucket-average when there are more samples+ * than columns, and hold each sample for several columns when there are fewer.+ * Averaging rather than sampling every Nth, because a decimated series drops the+ * outlier that was the only interesting thing in it.+ */+export function resample(values: readonly number[], width: number): number[] {+ const cells = Math.max(0, Math.floor(width));+ if (cells === 0 || values.length === 0) return [];+ if (values.length === cells) return [...values];+ return values.length > cells ? bucketMeans(values, cells) : holdEach(values, cells);+}++/** Mean of the FINITE samples in `[from, to)`, or `NaN` when the bucket has none. */+function meanOf(values: readonly number[], from: number, to: number): number {+ let sum = 0;+ let n = 0;+ for (let j = from; j < to && j < values.length; j++) {+ const v = values[j]!;+ if (!Number.isFinite(v)) continue;+ sum += v;+ n++;+ }+ return n > 0 ? sum / n : Number.NaN;+}++/** More samples than columns: one bucket per column, averaged. */+function bucketMeans(values: readonly number[], cells: number): number[] {+ const per = values.length / cells;+ const out: number[] = [];+ for (let i = 0; i < cells; i++) {+ const from = Math.floor(i * per);+ out.push(meanOf(values, from, Math.max(from + 1, Math.floor((i + 1) * per))));+ }+ return out;+}++/** Fewer samples than columns: hold each one for as many columns as it is owed. */+function holdEach(values: readonly number[], cells: number): number[] {+ const out: number[] = [];+ for (let i = 0; i < cells; i++) {+ out.push(values[Math.min(values.length - 1, Math.floor((i * values.length) / cells))]!);+ }+ return out;+}++/**+ * CONTEXT-WINDOW DECADE BUCKETS — a category distribution, which is what a stacked bar+ * is for, and the row that keeps this panel informative on a HOMOGENEOUS list.+ *+ * MEASURED: a subscription roster's capability mix is a single category (the discovery+ * path resolves `supportsTools` and nothing else), so the caps bar alone painted one+ * flat green rectangle — the aesthetic contract's own negative control. Context windows+ * spread across decades on almost every list, including that one (1M × 19, 250K × 2,+ * 131K × 1), so this row carries shape where the other one cannot.+ *+ * Fixed decade edges rather than quantiles of the visible window: the reader is+ * comparing against absolute sizes they already know ("is this a 128 K model or a 1 M+ * one"), and a quantile scale would relabel the same model differently on two screens.+ */+const CTX_BUCKETS: ReadonlyArray<{ label: string; max: number }> = [+ { label: "<32K", max: 32_000 },+ { label: "128K", max: 200_000 },+ { label: "512K", max: 600_000 },+ { label: "1M+", max: Number.POSITIVE_INFINITY },+];++export function ctxMix(models: readonly ModelInfo[]): number[] {+ const out = CTX_BUCKETS.map(() => 0);+ for (const m of models) {+ const n = m.contextLength ?? 0;+ if (n <= 0) continue;+ const i = CTX_BUCKETS.findIndex((b) => n < b.max);+ out[i < 0 ? CTX_BUCKETS.length - 1 : i]! += 1;+ }+ return out;+}++const LABEL_W = 6;++export interface StatsStripProps {+ /** The list as the user currently sees it — every number here is about THAT. */+ shown: readonly ModelInfo[];+ /** Before the filter, so `shown / total` is a real fraction. */+ total: number;+ /** Outer columns the strip occupies (the model panel's width). */+ width: number;+ /** `true` above `CHROME.statsPanel` rows: a bordered panel and the third row. */+ panelled: boolean;+ /** The SAME price resolver the rows print with — see `priceMix`. */+ priceOf?: (m: ModelInfo) => string;+}++/**+ * Three rows when there is room, two when there is not — and both survivors are+ * graphics rows, which is the property §4.6's arithmetic depends on.+ *+ * Each row is a flex ROW of a label `<text>`, a widget and a legend `<text>`, which+ * is the composition the skill prescribes and the one case where sibling `<text>`s+ * are correct: `flexDirection="row"` means three one-row children need exactly the+ * one row they have, so they cannot starve. The widths are arithmetic because the+ * widgets take cell counts, and they are computed from ONE inner width so the three+ * rows cannot drift apart.+ */+export function StatsStrip({ shown, total, width, panelled, priceOf }: StatsStripProps): ReactNode {+ // `Panel` spends 4 columns (border ×2 + padding ×2); the borderless form spends+ // the 2 columns of `paddingX={1}`.+ const inner = Math.max(12, Math.floor(width) - (panelled ? 4 : 2));+ const prices = priceMix(shown, priceOf);+ const priceLegend = PRICE_BANDS.map((b, i) => `${b.label} ${prices[i]}`).join(" · ");+ const buckets = ctxMix(shown);+ const ctxLegend = CTX_BUCKETS.map((b, i) => `${b.label} ${buckets[i]}`).join(" · ");+ const priceW = Math.max(6, inner - LABEL_W - 1 - priceLegend.length - 1);+ const ctxW = Math.max(6, inner - LABEL_W - 1 - ctxLegend.length - 1);+ const shownLegend = `${shown.length} / ${total}`;+ // Two widgets share the third row, so the width is split between them: a sparkline+ // of the list in display order, then how much of the list the filter left.+ const trendW = Math.max(6, Math.floor((inner - LABEL_W - 4 - shownLegend.length) / 2));+ const meterW = Math.max(6, inner - LABEL_W - 4 - shownLegend.length - trendW);++ // EVERY FILL IS DARKENED, and that is the skill's rule 1 for fills rather than taste:+ // a neon token that reads beautifully as one letter is a slab when it is 40 columns+ // of solid background. MEASURED — the first wide capture painted `C.magenta` across+ // most of the ctx row and `C.green` across most of the caps row, and the two bars+ // became the loudest thing on a screen whose actual signal is the list above them.+ // Darkening keeps the hue identity (which is what the legend names) and returns the+ // contrast to the data. Same 0.45 for every segment, so the segments stay comparable.+ // LIGHTEN ON LIGHT, DARKEN ON DARK — `theming.md`'s `area()` rule, called at RENDER+ // time because `isLightTheme()` fails the same silent way `C.*` does: detection runs+ // after this module is imported, so a value captured at load is the pre-detection+ // default forever. Measured on a white page: the darkened fills read as heavy slabs,+ // which is Jack's recorded complaint about the session card's meters ("the colours are+ // too hard", "the progress bars are too heavy, getting all the attention").+ const fill = (c: string): string => (isLightTheme() ? lighten(c, 0.55) : darken(c, 0.45));+ // Cheap → dear, on the same ramp direction the per-row price meter reads.+ const priceSegments = [+ { value: prices[0]!, color: fill(tokens.success) },+ { value: prices[1]!, color: fill(C.yellow) },+ { value: prices[2]!, color: fill(tokens.warn) },+ { value: prices[3]!, color: fill(tokens.error) },+ ];+ // Small window → cool, large → warm, so the row reads left to right as "how big" —+ // the same direction the per-row context meter reads.+ const ctxSegments = [+ { value: buckets[0]!, color: tokens.border },+ { value: buckets[1]!, color: fill(tokens.running) },+ { value: buckets[2]!, color: fill(tokens.info) },+ { value: buckets[3]!, color: fill(C.magenta) },+ ];+ const ctxSeries = resample(+ shown.map((m) => m.contextLength ?? 0),+ trendW+ );++ const body = (+ <>+ <box flexDirection="row" height={1} gap={1} flexShrink={0}>+ <text fg={tokens.subtle}>{padTo("ctx", LABEL_W)}</text>+ <StackedBar segments={ctxSegments} width={ctxW} />+ <text fg={tokens.trace}>{ctxLegend}</text>+ </box>+ <box flexDirection="row" height={1} gap={1} flexShrink={0}>+ <text fg={tokens.subtle}>{padTo("price", LABEL_W)}</text>+ <StackedBar segments={priceSegments} width={priceW} />+ <text fg={tokens.trace}>{priceLegend}</text>+ </box>+ {panelled ? (+ <box flexDirection="row" height={1} gap={1} flexShrink={0}>+ <text fg={tokens.subtle}>{padTo("trend", LABEL_W)}</text>+ <Sparkline values={ctxSeries} fg={tokens.info} />+ <Meter+ pct={total > 0 ? (100 * shown.length) / total : 0}+ width={meterW}+ ramp={ramps.volume}+ />+ <text fg={tokens.trace}>{padStartTo(shownLegend, shownLegend.length)}</text>+ </box>+ ) : null}+ </>+ );++ if (!panelled) {+ return (+ <box flexDirection="column" paddingX={1} flexShrink={0}>+ {body}+ </box>+ );+ }+ return (+ <box flexShrink={0}>+ <Panel title="shape" flexGrow={1}>+ {body}+ </Panel>+ </box>+ );+}diff --git a/packages/cli/src/picker/chrome.tsx b/packages/cli/src/picker/chrome.tsxnew file mode 100644index 00000000..ccf8f940--- /dev/null+++ b/packages/cli/src/picker/chrome.tsx@@ -0,0 +1,201 @@+/** @jsxImportSource @opentui/react */+/**+ * picker/chrome.tsx — the four one-row strips that frame the picker: header, load+ * bar, filter and footer.+ *+ * THEY ARE IN ONE FILE BECAUSE THEY SHARE ONE BUDGET. Every row spent here is a+ * model row the list does not get, and at 80×24 the whole chrome allowance is six+ * rows. Keeping them together is what makes that total visible to the next reader+ * instead of scattered across four files that each look cheap.+ *+ * NONE OF THEM IS A `Panel`. A bordered panel spends two rows of chrome to present+ * one row of content, which is a 200% overhead on a 24-row terminal; the filter strip+ * in particular is a caret and a count. Borders are for the two list panes, which+ * have content worth framing.+ */++import type { ReactNode } from "react";+import { LoadingRow } from "../tui/components/LoadingRow.js";+import { A, C } from "../tui/theme.js";+import { displayWidth, padStartTo, truncate } from "../tui/viz/text.js";+import { tokens } from "../tui/viz/tokens.js";+import { VERSION } from "../version.js";++/**+ * Two rows above 30 terminal rows, one below — the `CHROME.headerTwoRows` gate.+ *+ * The second row is OpenTUI's own self-sizing horizontal rule: a `flexGrow={1}` box+ * with `border={["top"]}`, which needs no width arithmetic at all and re-sizes itself+ * on resize (`TabBar.tsx:50-56` uses the same idiom). It is dim, because rule 6 is+ * dim the chrome and saturate the signal, and a separator is the purest chrome there+ * is.+ *+ * The wordmark is NOT drawn here. `printLogo` already wrote it to the primary screen+ * before this renderer opened, and the picker runs on the alternate screen — so those+ * nine rows come back for free and re-drawing them would spend the gain twice.+ */+export function PickerHeader({+ right,+ twoRows,+}: {+ /** The context line's right-hand group — counts, never a verdict. */+ right: string;+ twoRows: boolean;+}): ReactNode {+ return (+ <box flexDirection="column" flexShrink={0}>+ <box flexDirection="row" justifyContent="space-between" height={1} paddingX={1}>+ <text>+ <span fg={tokens.accent} attributes={A.bold}>+ claudish+ </span>+ <span fg={tokens.subtle}> select a model</span>+ </text>+ <text>+ <span fg={tokens.trace}>{`v${VERSION} · `}</span>+ <span fg={tokens.subtle}>{right}</span>+ </text>+ </box>+ {twoRows ? (+ <box flexDirection="row" height={1} paddingX={1}>+ <box flexGrow={1} border={["top"]} borderStyle="single" borderColor={tokens.border} />+ </box>+ ) : null}+ </box>+ );+}++/** One in-flight task, as the load bar draws it. */+export interface LoadTask {+ /** Stable identity — also the React key. */+ id: string;+ label: string;+ /** 0–100 for a determinate meter; omit for a shimmer. Never an invented denominator. */+ pct?: number;+ /** The figure between bar and label: `17/31`, `2.1s / 5.0s deadline`. */+ value?: string;+ width?: number;+}++/**+ * The load bar — present ONLY while something is in flight, and absent (not empty)+ * otherwise, because an empty flex item still eats a row.+ *+ * Each task draws itself at the honesty its caller can actually support+ * (`LoadingRow`'s own doc table): a determinate meter where work is countable, a+ * travelling shimmer where nothing is, and a labelled elapsed figure where only a+ * deadline is known. Nothing here invents a denominator.+ */+export function LoadBar({+ tasks,+ frame,+ width,+}: { tasks: LoadTask[]; frame: number; width: number }): ReactNode {+ if (tasks.length === 0) return null;+ // THE ROW IS ONE ROW WHATEVER IS IN FLIGHT, so the tasks share its columns instead of+ // overflowing it. MEASURED at 80 columns with all three up: the third task's bar+ // painted and its LABEL was clipped away entirely — the worst possible truncation,+ // because an unexplained bar is exactly the affordance this feature replaced. Each+ // task now takes an equal slice, its meter shrinks toward the 4-cell floor before its+ // label does, and the label ellipsises rather than vanishing.+ const gaps = 2 * (tasks.length - 1);+ const per = Math.max(12, Math.floor((width - 2 - gaps) / tasks.length));+ return (+ <box flexDirection="row" height={1} paddingX={1} gap={2} flexShrink={0}>+ {tasks.map((t) => {+ const value = t.value ?? "";+ const bar = Math.max(4, Math.min(t.width ?? 12, per - displayWidth(value) - 8));+ const label = truncate(t.label, Math.max(3, per - bar - displayWidth(value) - 2));+ return (+ <LoadingRow+ key={t.id}+ label={label}+ frame={frame}+ width={bar}+ {...(t.pct === undefined ? {} : { pct: t.pct })}+ {...(t.value === undefined ? {} : { value })}+ />+ );+ })}+ </box>+ );+}++/**+ * The filter strip: what is typed, and how much it left.+ *+ * `▍` is the caret (`resume-picker.tsx:1002`'s glyph), shown only while the strip+ * owns the keyboard — a caret on an inactive field claims focus it does not have.+ * The match count is right-aligned with `padStartTo` so it cannot jitter as the+ * number of digits changes.+ */+export function FilterStrip({+ value,+ active,+ matches,+ total,+ width,+ prompt = "filter",+}: {+ value: string;+ active: boolean;+ matches: number;+ total: number;+ width: number;+ /** `filter` or `provider@model` — the same strip serves the custom-spec hatch. */+ prompt?: string;+}): ReactNode {+ const count = `${matches} / ${total}`;+ const room = Math.max(1, width - prompt.length - count.length - 6);+ return (+ <box flexDirection="row" justifyContent="space-between" height={1} paddingX={1} flexShrink={0}>+ <text>+ <span fg={active ? tokens.accent : tokens.trace}>{`${prompt} `}</span>+ <span fg={value ? tokens.text : tokens.trace}>+ {value ? truncate(value, room) : active ? "" : "—"}+ </span>+ {active ? <span fg={tokens.accent}>▍</span> : null}+ </text>+ <text>+ {/* Warn only when a list EXISTS and the filter emptied it. `0 / 0` while the+ list is still loading is not a warning, and painting it as one teaches the+ reader to discount the colour everywhere else. */}+ <span fg={matches === 0 && total > 0 ? tokens.warn : tokens.subtle}>+ {padStartTo(count, count.length)}+ </span>+ </text>+ </box>+ );+}++/** One footer hint: the key, then what it does. */+interface Hint {+ key: string;+ label: string;+ /** Dimmed when the action is currently unavailable — shown, never hidden. */+ on?: boolean;+}++/**+ * Keyboard hints as two-tone chips — the `Footer.tsx:179-198` idiom, where the+ * colour slot is deliberately ignored and emphasis is BRIGHTNESS rather than hue.+ * Hue is spent on severity everywhere else in this program; spending it here too+ * would make the footer compete with the banner.+ *+ * Every action is one key and every key is listed. No deep menus, nothing+ * discoverable only by trying it.+ */+export function PickerFooter({ hints }: { hints: Hint[] }): ReactNode {+ return (+ <box flexDirection="row" height={1} paddingX={1} gap={2} flexShrink={0}>+ {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>+ <span fg={h.on === false ? tokens.trace : tokens.subtle}>{` ${h.label}`}</span>+ </text>+ ))}+ </box>+ );+}diff --git a/packages/cli/src/picker/detail.tsx b/packages/cli/src/picker/detail.tsxnew file mode 100644index 00000000..30643576--- /dev/null+++ b/packages/cli/src/picker/detail.tsx@@ -0,0 +1,140 @@+/** @jsxImportSource @opentui/react */+/**+ * picker/detail.tsx — the two pinned blocks under the two lists.+ *+ * THEY EXIST FOR PARITY FIRST AND FOR THE SCREENSHOT SECOND. The inquirer picker+ * showed a description under both prompts — `ProviderChoice.description` under the+ * provider list and `ModelInfo.description` under the model list — and a rewrite that+ * silently dropped both would be a regression dressed as a redesign. The model block+ * also answers the one question a picker must never leave open: what EXACTLY does+ * Enter return? It prints the spec verbatim.+ *+ * The screenshot benefit is the same shape as `resume-picker.tsx`'s activity calendar:+ * a scrollbox with fewer rows than viewport leaves the rest of its panel empty, and a+ * pinned, content-sized sibling occupies that space with something worth reading.+ * `flexShrink={0}` is mandatory on both — a scrollbox's intrinsic height is its ENTIRE+ * content, and Yoga spreads that shortfall across every sibling, which collapses an+ * unprotected block to one row and overprints its children.+ *+ * BOTH ARE HEIGHT-GATED BY THEIR CALLER, not here: on a 24-row terminal every row+ * belongs to the list, and a detail block would trade two model rows — two GRAPHICS+ * rows — for two rows of prose, which is exactly the wrong direction for the whole-frame+ * density count.+ */++import type { ReactNode } from "react";+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";++/**+ * Greedy word wrap to at most `maxLines` rows, with the last row ellipsised.+ *+ * Built on `displayWidth` through `truncate` rather than on `String.length`, because a+ * CJK model description counts double in cells and half in code units — the same reason+ * `padEnd`/`slice` are banned in `viz/text.ts`.+ */+export function wrapWords(text: string, width: number, maxLines: number): string[] {+ const w = Math.max(1, Math.floor(width));+ const words = text.split(/\s+/).filter(Boolean);+ const lines: string[] = [];+ let line = "";+ for (const word of words) {+ const next = line === "" ? word : `${line} ${word}`;+ if (next.length <= w) {+ line = next;+ continue;+ }+ if (line !== "") lines.push(line);+ line = word;+ if (lines.length === maxLines) break;+ }+ if (lines.length < maxLines && line !== "") lines.push(line);+ return lines.slice(0, maxLines).map((l) => truncate(l, w));+}++/**+ * What Enter will return, and what the model is.+ *+ * The spec is rendered in the accent colour and NOT truncated away: it is the value the+ * user is choosing, and a picker that hides its own return value is asking them to+ * guess.+ */+export function ModelDetail({+ model,+ spec,+ width,+}: {+ model: ModelInfo | null;+ spec: string | null;+ width: number;+}): ReactNode {+ const inner = Math.max(8, Math.floor(width) - 2);+ if (model === null || spec === null) {+ return (+ <box flexDirection="column" flexShrink={0} paddingX={1}>+ <text>+ <span fg={tokens.trace}>nothing selected</span>+ </text>+ </box>+ );+ }+ const date = model.releaseDate ? ` · ${model.releaseDate.slice(0, 7)}` : "";+ const head = `${spec}${date}`;+ const body = model.description ?? "";+ return (+ <box flexDirection="column" flexShrink={0} paddingX={1}>+ <text>+ <span fg={tokens.accent} attributes={A.bold}>+ {truncate(head, inner)}+ </span>+ </text>+ {body === "" ? null : (+ <text>+ <span fg={tokens.subtle}>{truncate(body, inner)}</span>+ </text>+ )}+ </box>+ );+}++/**+ * The selected provider, in the rail's own width.+ *+ * The env var is named even when the provider is ready, because it is the single most+ * useful string when something later goes wrong — a stale value in the shell shadows+ * stored credentials, and "check your API key" gives no clue which name to inspect.+ * That is the same reasoning `formatDiscoveryFailureNotice` gives for naming it in a+ * failure notice; here it is available BEFORE the failure.+ */+export function ProviderDetail({+ label,+ description,+ envVar,+ width,+}: {+ label: string;+ description: string;+ envVar: string;+ width: number;+}): ReactNode {+ const inner = Math.max(6, Math.floor(width) - 2);+ return (+ <box flexDirection="column" flexShrink={0} paddingX={1}>+ <text>+ <span fg={tokens.accent}>{truncate(label, inner)}</span>+ </text>+ {wrapWords(description, inner, 3).map((line) => (+ <text key={line}>+ <span fg={tokens.subtle}>{line}</span>+ </text>+ ))}+ {envVar === "" ? null : (+ <text>+ <span fg={tokens.trace}>{truncate(envVar, inner)}</span>+ </text>+ )}+ </box>+ );+}diff --git a/packages/cli/src/picker/fixtures/fixture-source.ts b/packages/cli/src/picker/fixtures/fixture-source.tsnew file mode 100644index 00000000..608769f2--- /dev/null+++ b/packages/cli/src/picker/fixtures/fixture-source.ts@@ -0,0 +1,167 @@+/**+ * picker/fixtures/fixture-source.ts — a scriptable `PickerDataSource`, for the states+ * a live provider cannot be made to produce.+ *+ * DEV-ONLY. It is reached exclusively through a dynamic `await import()` behind the+ * `CLAUDISH_PICKER_FIXTURE` check in `model-picker-run.tsx`, so `bun build --compile`+ * never walks into this directory and the shipped binary carries no fixture data.+ *+ * IT WRAPS THE PRODUCTION SOURCE AND OVERRIDES ONLY THE SHAPE OF AN ANSWER — never+ * the data. The roster is still derived from the provider definitions, every model row+ * is still the real catalog's, every price and context window is still whatever the+ * backend says. What a scenario forges is the OUTCOME VARIANT (an empty roster, a+ * timeout, a roster where nothing is chat-capable), the readiness answers, and+ * latency. That keeps the "never hardcode rosters, context windows or pricing" rule+ * intact inside a capture harness, which matters because a screenshot of invented+ * prices proves nothing about the layout of real ones.+ *+ * WHY A FAKE AT ALL — the four states below are the whole point of the feature and+ * none of them is reachable from outside:+ *+ * · `loading` the warm path settles in under 100 ms, so the in-flight frames+ * (V2/V3/V4) cannot be photographed on a real run at all.+ * · `empty` a provider that answers correctly with nothing chat-capable.+ * · `filtered` a provider that serves only embeddings or wildcard routes.+ * · `timeout` an unreachable endpoint, on demand.+ *+ * V5 (unauthorized) is deliberately NOT the primary use: it is reproducible live with+ * a bogus key against the real endpoint, which is how the "before" frame was measured,+ * 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 CatalogLoad,+ type PickerDataSource,+ type RailChoice,+ createPickerDataSource,+} from "../PickerDataSource.js";++export type FixtureName = "ready" | "loading" | "timeout" | "empty" | "filtered" | "unauthorized";++const NEVER = new Promise<never>(() => {+ /* deliberately never settles — a capture window is finite, this is not */+});++const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));++/**+ * Scenarios that forge a discovery OUTCOME also claim discovery for every provider,+ * so the state is on screen wherever the cursor happens to start. Without that, a+ * capture would have to drive keystrokes to a particular provider and would break the+ * moment the picker order changed.+ */+const FORCED_OUTCOME = new Set<FixtureName>(["timeout", "empty", "filtered", "unauthorized"]);++export function createFixtureDataSource(name: string): PickerDataSource {+ const scenario = (name as FixtureName) ?? "ready";+ const real = createPickerDataSource();+ const forced = FORCED_OUTCOME.has(scenario);+ // `loading` claims discovery too — not to forge an outcome (it has none; it never+ // settles) but so that whichever provider the cursor starts on exercises the ROSTER+ // indicator. Without it the first provider is OpenRouter, which has no discovery, and+ // the one affordance with a published deadline would never appear in a capture.+ const claimsDiscovery = forced || scenario === "loading";++ return {+ providerRoster(): RailChoice[] {+ return real+ .providerRoster()+ .map((r) =>+ claimsDiscovery ? { ...r, hasDiscovery: true, discoveryShape: "deadline" } : r+ );+ },++ notEnabledLocalProviders: () => real.notEnabledLocalProviders(),+ displayName: (p) => real.displayName(p),++ async *probeCredentials(names: string[]): AsyncIterable<[string, boolean]> {+ // EVERY PROVIDER READY, and that is a forgery with a purpose: a capture runs with+ // credential sources disabled so it cannot raise a 1Password or Keychain prompt on+ // the user's desktop, which leaves the real rail three rows long and says nothing+ // about how the rail looks for a configured user.+ for (const n of names) {+ if (scenario === "loading") await sleep(600);+ yield [n, true];+ }+ if (scenario === "loading") await NEVER; // hold the `done/total` meter mid-sweep+ },++ loadCatalog(): Promise<CatalogLoad> {+ return scenario === "loading" ? NEVER : real.loadCatalog();+ },++ async discoverRoster(provider: string): Promise<PickerDiscoveryOutcome> {+ if (scenario === "loading") return NEVER;+ if (!forced) return real.discoverRoster(provider);++ // The fallback list is the REAL vendor catalog for this provider, because the+ // defect being rendered is precisely that an unmarked fallback list reads as a+ // healthy short roster — and that only shows on real rows.+ const fallbackRows = await real.catalogModels(provider).catch((): ModelInfo[] => []);+ const displayName = real.displayName(provider);++ if (scenario === "empty") {+ return {+ kind: "empty-roster",+ failure: {+ kind: "empty-roster",+ provider,+ endpoint: "https://api.example.test/v1/models",+ },+ fallbackRows,+ };+ }+ if (scenario === "filtered") {+ return {+ kind: "all-filtered",+ servedCount: 7,+ sampleIds: ["text-embedding-3-large", "whisper-1", "tts-1-hd"],+ fallbackRows,+ };+ }+ if (scenario === "timeout") {+ return {+ kind: "failed",+ failure: {+ kind: "unreachable",+ provider,+ endpoint: "https://api.example.test/v1/models",+ detail: "The operation was aborted due to timeout",+ },+ notice: [+ `\n⚠ ${displayName} could not list its models: the model list was unreachable at https://api.example.test/v1/models — The operation was aborted due to timeout\n`,+ fallbackRows.length > 0+ ? ` Showing ${displayName}'s cloud-catalog entries below — not its live roster.\n\n`+ : " Falling back to manual model entry.\n\n",+ ],+ fallbackRows,+ };+ }+ return {+ kind: "failed",+ failure: {+ kind: "unauthorized",+ provider,+ status: 401,+ endpoint: "https://api.example.test/v1/models",+ detail:+ '{"error":{"message":"Invalid Authentication","type":"invalid_authentication_error"}}',+ },+ notice: [+ `\n⚠ ${displayName} could not list its models: the API key was rejected (HTTP 401) at https://api.example.test/v1/models\n`,+ " Check EXAMPLE_API_KEY (a value in your shell overrides stored credentials).\n",+ " Get a key: https://platform.example.test/keys\n",+ fallbackRows.length > 0+ ? ` Showing ${displayName}'s cloud-catalog entries below — not its live roster.\n\n`+ : " Falling back to manual model entry.\n\n",+ ],+ fallbackRows,+ };+ },++ catalogModels(provider: string): Promise<ModelInfo[]> {+ return scenario === "loading" ? NEVER : real.catalogModels(provider);+ },+ };+}diff --git a/packages/cli/src/picker/hooks/useCatalogModels.ts b/packages/cli/src/picker/hooks/useCatalogModels.tsnew file mode 100644index 00000000..55322f5c--- /dev/null+++ b/packages/cli/src/picker/hooks/useCatalogModels.ts@@ -0,0 +1,114 @@+/**+ * useCatalogModels — the cross-vendor catalog (A2) and the per-provider vendor list+ * (A12), with one promise memo between them.+ *+ * THE MEMO IS PORTED, NOT INVENTED: `selectModel` keeps a `remoteQueryCache` of+ * `Promise<ModelInfo[]>` keyed by query (`model-selector.ts:693-714`), so a provider+ * revisited during one picker session costs nothing. Caching the PROMISE rather than+ * the result is what makes two rapid arrow-key presses share one request instead of+ * racing two.+ *+ * THE PICKER STAYS USABLE IF THE CATALOG NEVER LANDS (edge case 8). The rail derives+ * from provider definitions, not from the catalog, so provider selection, every+ * discovery provider, the local/user-deployed providers and the custom-spec hatch all+ * work with a dead catalog. What degrades is exactly what the catalog supplies: the+ * vendor lists for non-discovery providers, which then show a `failed` notice instead+ * of rows. No path reaches a blank frame.+ */++import { useCallback, useEffect, useRef, useState } from "react";+import type { ModelInfo } from "../../model-selector.js";+import type { CatalogLoad, PickerDataSource } from "../PickerDataSource.js";++/** The shape `ProbeState` established (`hooks/useRouteProbe.ts:28-33`) — copied, not reinvented. */+export type LoadPhase = "idle" | "loading" | "ready" | "failed";++export interface CatalogState {+ phase: LoadPhase;+ /** Recommended ids, lower-cased — the corpus behind a row's `REC` marker. */+ recommended: Set<string>;+ /** How many models the cross-vendor load returned. A count, not a verdict. */+ size: number;+}++export interface ProviderListState {+ phase: LoadPhase;+ rows: ModelInfo[];+}++export interface CatalogModelsState {+ catalog: CatalogState;+ /** The selected provider's vendor list, when it is a provider that needs one. */+ list: ProviderListState;+}++const IDLE: ProviderListState = { phase: "idle", rows: [] };++export function useCatalogModels(+ source: PickerDataSource,+ provider: string | null,+ /** False for a discovery provider — its list comes from `useProviderDiscovery`. */+ wanted: boolean+): CatalogModelsState {+ const [catalog, setCatalog] = useState<CatalogState>({+ phase: "loading",+ recommended: new Set(),+ size: 0,+ });+ const [lists, setLists] = useState<Record<string, ProviderListState>>({});+ const inflight = useRef(new Map<string, Promise<ModelInfo[]>>());++ useEffect(() => {+ let live = true;+ void (async () => {+ try {+ const load: CatalogLoad = await source.loadCatalog();+ if (!live) return;+ setCatalog({+ phase: "ready",+ recommended: new Set(load.recommended.map((m) => m.id.toLowerCase())),+ size: load.top.length + load.recommended.length,+ });+ } catch {+ if (!live) return;+ // A failed catalog is a NOTICE, not an error: the picker still works, and+ // painting red for a degraded-but-functional screen teaches the user to+ // ignore red.+ setCatalog({ phase: "failed", recommended: new Set(), size: 0 });+ }+ })();+ return () => {+ live = false;+ };+ }, [source]);++ const load = useCallback(+ (name: string): void => {+ const cache = inflight.current;+ if (cache.has(name)) return;+ const request = source.catalogModels(name);+ cache.set(name, request);+ setLists((prev) => ({ ...prev, [name]: { phase: "loading", rows: [] } }));+ void request.then(+ (rows) => setLists((prev) => ({ ...prev, [name]: { phase: "ready", rows } })),+ () => {+ // Dropped from the memo so a retry is possible — a cached rejection would+ // make one transient network failure permanent for the whole session.+ cache.delete(name);+ setLists((prev) => ({ ...prev, [name]: { phase: "failed", rows: [] } }));+ }+ );+ },+ [source]+ );++ useEffect(() => {+ if (provider === null || !wanted) return;+ load(provider);+ }, [provider, wanted, load]);++ return {+ catalog,+ list: provider !== null && wanted ? (lists[provider] ?? IDLE) : IDLE,+ };+}diff --git a/packages/cli/src/picker/hooks/useDelayedVisible.ts b/packages/cli/src/picker/hooks/useDelayedVisible.tsnew file mode 100644index 00000000..d9be8626--- /dev/null+++ b/packages/cli/src/picker/hooks/useDelayedVisible.ts@@ -0,0 +1,49 @@+/**+ * useDelayedVisible — an affordance that is honest when the await is FAST.+ *+ * The catalog fetches are mem- and disk-cached and the credential fan-out can finish+ * before the first paint, so a naive loading bar flashes for one or two 100 ms ticks+ * on every warm start. That reads as a glitch, not as progress, and it is the same+ * class of dishonesty as a bar with an invented denominator: it tells the user+ * something happened that they cannot perceive.+ *+ * So: show nothing for the first `showAfterMs`, and once shown keep it for at least+ * `keepForMs`. A task that settles inside the first window is never announced; a task+ * that is announced does not vanish mid-blink.+ *+ * THE CONSEQUENCE IS STATED RATHER THAN DISCOVERED LATER: the loading states (V2, V3)+ * are photographed against the FIXTURE data source by design, because the real warm+ * path is too fast to capture. That is not a weaker test than a live capture — it is+ * the only reproducible one.+ */++import { useEffect, useRef, useState } from "react";++export function useDelayedVisible(active: boolean, showAfterMs = 120, keepForMs = 300): boolean {+ const [visible, setVisible] = useState(false);+ const shownAt = useRef<number | null>(null);++ useEffect(() => {+ if (active) {+ if (visible) return;+ const t = setTimeout(() => {+ shownAt.current = Date.now();+ setVisible(true);+ }, showAfterMs);+ return () => clearTimeout(t);+ }+ if (!visible) return;+ // Hold for the REMAINDER of the minimum, not the whole of it: a task that ran+ // for 2 s has already been seen, and re-holding the bar for another 300 ms after+ // it finished would make the screen feel slower than it is.+ const elapsed = shownAt.current === null ? keepForMs : Date.now() - shownAt.current;+ const hold = Math.max(0, keepForMs - elapsed);+ const t = setTimeout(() => {+ shownAt.current = null;+ setVisible(false);+ }, hold);+ return () => clearTimeout(t);+ }, [active, visible, showAfterMs, keepForMs]);++ return visible;+}diff --git a/packages/cli/src/picker/hooks/usePickerProviders.ts b/packages/cli/src/picker/hooks/usePickerProviders.tsnew file mode 100644index 00000000..03f3173e--- /dev/null+++ b/packages/cli/src/picker/hooks/usePickerProviders.ts@@ -0,0 +1,94 @@+/**+ * usePickerProviders — the rail's roster, and the credential probe that fills it in.+ *+ * FRAME ONE IS NEVER BLANK, STRUCTURALLY. The roster comes from+ * `source.providerRoster()`, which is synchronous and derived from the provider+ * definitions, so the first render already lists every pickable provider with a `◌`+ * pending marker. The probe then flips each row to `●` or `○` as it settles. That+ * incremental fill IS the loading affordance for the ~30 `credentials.isAvailable`+ * calls — each of which may read env, config, an OAuth file, the macOS Keychain and+ * the 1Password SDK — and it is why `probeCredentials` is an AsyncIterable rather+ * than one awaited map: a map would hold every row hostage to the slowest handshake.+ *+ * MEMBERSHIP IN THE STEADY STATE IS IDENTICAL TO TODAY'S. The old picker filtered+ * unready providers out entirely (`getProviderChoices`), which made the first frame+ * wait for every probe. This mounts the UNFILTERED roster and then collapses the+ * unready ones into one dim, non-selectable summary row — so the rail does not+ * lengthen, no row can be picked that would fail later at `validateApiKeysForModels`,+ * and the absence is EXPLAINED rather than silent, which is the principle the rest of+ * the feature is built on.+ *+ * ONE FAN-OUT PER MOUNT, never per render: `selectModel` hoisted this call for+ * exactly that reason (its comment at `model-selector.ts:660-668`), and the profile+ * wizard's four-times-over probe is the counter-example this must not become.+ */++import { useEffect, useMemo, useState } from "react";+import type { PickerDataSource, RailChoice } from "../PickerDataSource.js";+import type { Readiness } from "../rows.js";++export interface RailRow extends RailChoice {+ readiness: Readiness;+}++export interface PickerProvidersState {+ /** Every pickable provider, in picker order, readiness included. */+ rows: RailRow[];+ /** Ready providers — the selectable ones. */+ ready: RailRow[];+ /** Settled-but-unready providers, collapsed behind one summary row. */+ missing: RailRow[];+ /** Probes settled so far. */+ done: number;+ /** Probes in total — known synchronously, which is what makes this real progress. */+ total: number;+ /** True until the last probe settles. */+ probing: boolean;+ /** Built-in local providers not enabled in config (§3.9) — a hint, not a row. */+ notEnabledLocal: string[];+}++export function usePickerProviders(source: PickerDataSource): PickerProvidersState {+ // The roster is resolved ONCE. `providerRoster()` is pure and derived, so calling+ // it per render would be correct and still wrong: the rows would be new objects+ // every frame and every memo downstream would miss.+ const roster = useMemo(() => source.providerRoster(), [source]);+ const notEnabledLocal = useMemo(() => source.notEnabledLocalProviders(), [source]);+ const [readiness, setReadiness] = useState<Record<string, boolean>>({});++ useEffect(() => {+ let live = true;+ void (async () => {+ for await (const [name, ok] of source.probeCredentials(roster.map((r) => r.value))) {+ if (!live) return;+ // One `setState` per settled probe, deliberately: ~30 of them over a second+ // or two is nowhere near the frame rate at which the mutable-store-plus-poll+ // pattern becomes necessary, and a batched update would lose the incremental+ // fill that is the whole affordance.+ setReadiness((prev) => ({ ...prev, [name]: ok }));+ }+ })();+ return () => {+ // The probes are abandoned, not awaited. Nothing writes to a destroyed+ // renderer because React is unmounted before the renderer is destroyed, and+ // `isAvailable` has no side effect worth draining.+ live = false;+ };+ }, [source, roster]);++ const rows: RailRow[] = roster.map((r) => {+ const settled = readiness[r.value];+ return { ...r, readiness: settled === undefined ? "pending" : settled ? "ready" : "missing" };+ });+ const done = Object.keys(readiness).length;++ return {+ rows,+ ready: rows.filter((r) => r.readiness === "ready"),+ missing: rows.filter((r) => r.readiness === "missing"),+ done,+ total: roster.length,+ probing: done < roster.length,+ notEnabledLocal,+ };+}diff --git a/packages/cli/src/picker/hooks/useProviderDiscovery.ts b/packages/cli/src/picker/hooks/useProviderDiscovery.tsnew file mode 100644index 00000000..33038771--- /dev/null+++ b/packages/cli/src/picker/hooks/useProviderDiscovery.ts@@ -0,0 +1,101 @@+/**+ * useProviderDiscovery — one settled outcome per discovery provider, and the elapsed+ * clock the in-flight indicator is drawn from.+ *+ * NO REJECTION BRANCH, BY CONTRACT. `discoverProviderRoster` never rejects — every+ * throw inside it is mapped to `failed{kind:"unreachable"}` — and+ * `buildDiscoveredModelOutcome` inherits that guarantee through `Promise.allSettled`.+ * That contract is what lets this hook be small; it is also pinned by a unit test+ * with a fetcher registered to throw, because a contract is not a type. The `catch`+ * below exists anyway, for the one failure a contract cannot cover: a data source+ * that is not the production one.+ *+ * THE ELAPSED CLOCK IS NOT STATE. `startedAt` is recorded once per request and the+ * view re-renders from `useAnimationFrame`'s 100 ms tick, computing+ * `Date.now() - startedAt` at render time. Storing elapsed milliseconds in state+ * would be a `setState` per tick for a number nothing else reads.+ *+ * EVERY FAILURE IS REPORTED, NOT JUST THE LAST. `onFailure` fires once per provider+ * whose outcome lands `failed`, in the order they occurred, because that is what the+ * behaviour being preserved does: today each failed selection writes its diagnostic+ * to stderr immediately, so a session that tried two failing providers leaves two+ * lines in the scrollback. Writing one after teardown would be a quiet narrowing.+ */++import { useCallback, useEffect, useRef, useState } from "react";+import type { PickerDiscoveryOutcome } from "../../model-selector.js";+import type { PickerDataSource } from "../PickerDataSource.js";++export interface DiscoveryState {+ /** The selected provider's outcome, or `null` while it is in flight. */+ outcome: PickerDiscoveryOutcome | null;+ /** True while a request for the selected provider is open. */+ busy: boolean;+ /** `Date.now()` when the open request started, for the elapsed figure. */+ startedAt: number | null;+ /** Every outcome seen this session, so a revisit costs nothing. */+ seen: ReadonlyMap<string, PickerDiscoveryOutcome>;+}++export function useProviderDiscovery(+ source: PickerDataSource,+ provider: string | null,+ /** False unless this provider declares `modelDiscovery`. */+ wanted: boolean,+ /** Called once per provider that lands `failed`, for the post-teardown write. */+ onFailure?: (provider: string, notice: readonly string[]) => void+): DiscoveryState {+ const [outcomes, setOutcomes] = useState<Map<string, PickerDiscoveryOutcome>>(new Map());+ const [started, setStarted] = useState<Record<string, number>>({});+ const inflight = useRef(new Map<string, Promise<PickerDiscoveryOutcome>>());+ // A ref, not state: the callback identity must not re-trigger the effect, and a+ // stale closure here would report a failure to a buffer nobody drains.+ const report = useRef(onFailure);+ report.current = onFailure;+ const reported = useRef(new Set<string>());++ const load = useCallback(+ (name: string): void => {+ const cache = inflight.current;+ if (cache.has(name)) return;+ const request = source.discoverRoster(name);+ cache.set(name, request);+ setStarted((prev) => (prev[name] === undefined ? { ...prev, [name]: Date.now() } : prev));+ void request.then(+ (outcome) => {+ setOutcomes((prev) => new Map(prev).set(name, outcome));+ if (outcome.kind === "failed" && !reported.current.has(name)) {+ reported.current.add(name);+ report.current?.(name, outcome.notice);+ }+ },+ (err: unknown) => {+ cache.delete(name);+ setOutcomes((prev) =>+ new Map(prev).set(name, {+ kind: "failed",+ failure: { kind: "unreachable", provider: name, detail: String(err) },+ notice: [`${name} could not list its models: ${String(err)}`],+ fallbackRows: [],+ })+ );+ }+ );+ },+ [source]+ );++ useEffect(() => {+ if (provider === null || !wanted) return;+ load(provider);+ }, [provider, wanted, load]);++ const outcome = provider !== null && wanted ? (outcomes.get(provider) ?? null) : null;+ const busy = provider !== null && wanted && outcome === null;+ return {+ outcome,+ busy,+ startedAt: busy && provider !== null ? (started[provider] ?? null) : null,+ seen: outcomes,+ };+}diff --git a/packages/cli/src/picker/import-direction.test.ts b/packages/cli/src/picker/import-direction.test.tsnew file mode 100644index 00000000..3c5b1400--- /dev/null+++ b/packages/cli/src/picker/import-direction.test.ts@@ -0,0 +1,71 @@+import { describe, expect, test } from "bun:test";+/**+ * The import-direction guard — four greps, each catching a class of mistake that `tsc`+ * compiles happily and that surfaces only as a slow MCP start or a runtime cycle.+ *+ * The rule:+ *+ * `picker/` may import from `tui/`; `tui/` may NEVER import from `picker/`.+ * `model-selector.ts` may reach `picker/` only through a dynamic `await import()`.+ * `tui/hooks/` may never import from `tui/components/`.+ *+ * WHY A GREP AND NOT A TYPE. The hazard is not a compile error — it is a renderer+ * arriving in a process whose stdout is a protocol. `providers/model-ordering.ts:10-18`+ * records the same hazard for the inquirer picker and the fix it forced (moving one+ * comparator out to break the cycle); OpenTUI makes it worse, because the import graph+ * pulls a native library. Nothing in the type system expresses "this edge must be+ * dynamic", so the mechanism is text.+ *+ * THE FOURTH ASSERTION IS SCOPED TO TWO FILES BY NAME, and that is the point of it.+ * `can-draw-tui.ts` and `picker-cancelled.ts` are the two leaves `index.ts` and+ * `model-selector.ts` import STATICALLY; one OpenTUI import added to either would pull+ * the renderer into the cold-start graph with the other three guards still green. It is+ * scoped to those two files rather than to `tui/runtime/`, because that directory is+ * already occupied by `shutdown.ts` (which imports `node:os` and type-imports OpenTUI)+ * — a directory-wide assertion would have been RED on the commit that introduced it,+ * which is the same defect shape as a rule pointing at a file that does not exist.+ */+import { readFileSync, readdirSync, statSync } from "node:fs";+import { join } from "node:path";++const SRC = new URL(".", import.meta.url).pathname.replace(/\/picker\/$/, "");++function walk(dir: string, out: string[] = []): string[] {+ for (const entry of readdirSync(dir)) {+ const full = join(dir, entry);+ if (statSync(full).isDirectory()) walk(full, out);+ else if (/\.(ts|tsx)$/.test(entry)) out.push(full);+ }+ return out;+}++const read = (p: string): string => readFileSync(p, "utf8");++describe("import direction", () => {+ test("tui/ never imports from picker/, in any form", () => {+ const offenders = walk(join(SRC, "tui")).filter((f) => /from\s+"[^"]*picker\//.test(read(f)));+ expect(offenders.map((f) => f.replace(SRC, ""))).toEqual([]);+ });++ test("model-selector.ts reaches picker/ only through a dynamic import", () => {+ const src = read(join(SRC, "model-selector.ts"));+ // A STATIC import from this module into `picker/` is what would put OpenTUI on the+ // cold-start path — which is why `selectModelInteractive` uses `await import()`.+ expect(/^\s*import\s[^\n]*from\s+"\.\/picker\//m.test(src)).toBe(false);+ expect(src.includes('await import("./picker/model-picker-run.js")')).toBe(true);+ });++ test("tui/hooks/ never imports from tui/components/", () => {+ const hooks = join(SRC, "tui", "hooks");+ const offenders = walk(hooks).filter((f) => /from\s+"[^"]*\/components\//.test(read(f)));+ expect(offenders.map((f) => f.replace(SRC, ""))).toEqual([]);+ });++ test("the three statically-imported runtime leaves import NOTHING", () => {+ // Owed since phase 0, whose home for this assertion (`picker/`) did not exist yet.+ for (const leaf of ["can-draw-tui.ts", "picker-cancelled.ts", "should-open-picker.ts"]) {+ const src = read(join(SRC, "tui", "runtime", leaf));+ expect({ leaf, hasImport: /^\s*import\b/m.test(src) }).toEqual({ leaf, hasImport: false });+ }+ });+});diff --git a/packages/cli/src/picker/layout.test.ts b/packages/cli/src/picker/layout.test.tsnew file mode 100644index 00000000..77af000b--- /dev/null+++ b/packages/cli/src/picker/layout.test.ts@@ -0,0 +1,106 @@+import { describe, expect, test } from "bun:test";+/**+ * The column ladder, asserted so it can FAIL ON ITS OWN DEFECT.+ *+ * An earlier formulation of this test checked only that a row's cells did not EXCEED+ * the budget. That would have passed the very configuration the screenshot gate fails:+ * a row that sums to 39 columns short of its width leaves a dead tail, and a row whose+ * context meter has collapsed to one cell is a coloured dot. A test that cannot fail on+ * the defect it guards is not a guard.+ *+ * So the three claims are: the cells sum EXACTLY to the row width, the context meter+ * never drops below `MIN_CTX_CELLS`, and no cell is ever negative — over every width+ * from 40 to 200, which covers both mandatory capture sizes and everything between.+ */+import {+ CHROME,+ MIN_CTX_CELLS,+ derivePanes,+ deriveRailLayout,+ deriveRowLayout,+ railLayoutTotal,+ rowLayoutTotal,+} from "./layout.js";++const WIDTHS = Array.from({ length: 161 }, (_, i) => i + 40);++describe("deriveRowLayout", () => {+ test("cells sum EXACTLY to the row width at every width in [40, 200]", () => {+ const wrong = WIDTHS.map((w) => ({ w, sum: rowLayoutTotal(deriveRowLayout(w)) })).filter(+ ({ w, sum }) => sum !== w+ );+ expect(wrong).toEqual([]);+ });++ test("the context meter never drops below the floor", () => {+ const thin = WIDTHS.map((w) => ({ w, ctx: deriveRowLayout(w).ctx })).filter(+ ({ ctx }) => ctx < MIN_CTX_CELLS+ );+ expect(thin).toEqual([]);+ });++ test("no cell is ever negative", () => {+ const bad = WIDTHS.flatMap((w) =>+ Object.entries(deriveRowLayout(w)).filter(([, v]) => (v as number) < 0)+ );+ expect(bad).toEqual([]);+ });++ test("the ladder drops cells in the stated order as the width shrinks", () => {+ // Widest: everything. The release date is the first thing to go, then the price+ // METER — never its numeral, and never the context meter.+ expect(deriveRowLayout(117).date).toBeGreaterThan(0);+ expect(deriveRowLayout(80).date).toBe(0);+ expect(deriveRowLayout(80).price).toBeGreaterThan(0);+ expect(deriveRowLayout(57).price).toBe(0);+ expect(deriveRowLayout(57).priceNum).toBeGreaterThan(0);+ expect(deriveRowLayout(40).ctx).toBeGreaterThanOrEqual(MIN_CTX_CELLS);+ });++ test("a non-finite or negative width yields the narrowest tier, never NaN columns", () => {+ for (const w of [Number.NaN, Number.POSITIVE_INFINITY, -10]) {+ const l = deriveRowLayout(w);+ expect(Object.values(l).every((v) => Number.isFinite(v))).toBe(true);+ expect(l.ctx).toBeGreaterThanOrEqual(0);+ }+ });+});++describe("derivePanes", () => {+ test("the two mandatory capture widths land where the design says", () => {+ // 80 → a 19-column rail and 57 usable row cells; 145 → 24 and 117.+ expect(derivePanes(80)).toMatchObject({ railW: 19, panelOuter: 60, rowCells: 57 });+ expect(derivePanes(145)).toMatchObject({ railW: 24, panelOuter: 120, rowCells: 117 });+ });++ test("a tiny terminal still yields positive, finite budgets", () => {+ for (const w of [10, 20, Number.NaN]) {+ const p = derivePanes(w);+ expect(p.rowCells).toBeGreaterThan(0);+ expect(p.railInner).toBeGreaterThan(0);+ }+ });+});++describe("deriveRailLayout", () => {+ test("cells sum EXACTLY to the rail's inner width", () => {+ for (const inner of [8, 12, 17, 22, 30]) {+ expect(railLayoutTotal(deriveRailLayout(inner))).toBe(inner);+ }+ });++ test("the served count appears only when the rail is wide enough to hold one", () => {+ expect(deriveRailLayout(17).count).toBe(0);+ expect(deriveRailLayout(22).count).toBeGreaterThan(0);+ });+});++describe("CHROME", () => {+ test("every height gate is a distinct, ordered threshold", () => {+ // They are read as "at or above", so an out-of-order pair would silently make one+ // gate unreachable.+ expect(CHROME.detail).toBeLessThan(CHROME.headerTwoRows);+ expect(CHROME.headerTwoRows).toBeLessThanOrEqual(CHROME.bannerBordered);+ expect(CHROME.bannerBordered).toBeLessThan(CHROME.statsPanel);+ });+});diff --git a/packages/cli/src/picker/layout.ts b/packages/cli/src/picker/layout.tsnew file mode 100644index 00000000..14991400--- /dev/null+++ b/packages/cli/src/picker/layout.ts@@ -0,0 +1,374 @@+/**+ * picker/layout.ts — every column budget the picker spends, in one place.+ *+ * Flexbox owns the BOXES; arithmetic owns the widths of the data widgets, because+ * `Meter`/`MeterSpan`/`Sparkline`/`StackedBar` take a numeric cell count and a+ * number cannot `flexGrow` (bunjs:tui `react-patterns.md`). So a full-width+ * visual is a column budget, and a budget that lives at its call site drifts.+ *+ * THE CONTEXT METER IS THE ELASTIC CELL, and that is the whole design of+ * `deriveRowLayout`. Every other cell is fixed per tier; the meter takes the+ * surplus up to its tier maximum and hands any remainder to the model id. Two+ * consequences, both load-bearing:+ *+ * 1. A row is EXACTLY `rowCells` wide at every width — no unpainted tail, which+ * is the gap a colour screenshot fails a panel for.+ * 2. A row NEVER carries fewer than `MIN_CTX_CELLS` meter cells, at any width,+ * which is what keeps every visible model row a GRAPHICS row at 80 columns.+ * The whole-frame density count depends on that and on nothing else.+ *+ * The ladder is a table of tiers rather than a formula because the cells it drops+ * are editorial, not arithmetic: the release date goes first (it is chrome), then+ * the price METER (the numeral stays — the number is the fact, the bar is the+ * comparison), then the capability column, then the id shrinks. Nothing here drops+ * the context meter.+ */++/**+ * The floor on the context meter, in cells.+ *+ * FOUR, not one: a one-cell meter is a coloured dot, and `rampFor` would blend a+ * whole gradient down to a single colour — the "single-colour bar" the aesthetic+ * contract names as a negative control. Four cells still read as a fill and still+ * carry four distinct ramp colours.+ */+export const MIN_CTX_CELLS = 4;++/** The smallest model-id column worth rendering. Below this a row is unreadable. */+const MIN_ID_CELLS = 8;++/**+ * One model row's cells, left to right. Every number is COLUMNS, and they sum to+ * exactly `rowCells` — asserted over the whole width range by `layout.test.ts`.+ *+ * A zero means the cell is DROPPED at this width (and its separator with it), not+ * that it renders empty: an empty cell would still eat its columns.+ */+export interface RowLayout {+ /** Total columns the row must paint, exactly. */+ rowCells: number;+ /** `▶ ` / ` ` — the cursor gutter, which carries its own trailing space. */+ cursor: number;+ /** Model id, padded/truncated. Absorbs the surplus the meter cannot use. */+ id: number;+ /** The context-window gradient meter. The elastic cell; never below `MIN_CTX_CELLS`. */+ ctx: number;+ /** `padStartTo`-ed context numeral (`256K`). */+ ctxNum: number;+ /** The price meter. 0 at narrow widths — the numeral survives instead. */+ price: number;+ /** `padStartTo`-ed price numeral, or the `SUB` chip's column. */+ priceNum: number;+ /** Capability column — `[TRV]`, five columns, identical at every width (`rows.tsx`). */+ caps: number;+ /**+ * The provenance chip's column (` CAT `), reserved ONLY for a fallback list.+ *+ * INSIDE THE BUDGET, and that is a correction to a measured bug: the chip was first+ * rendered after the last cell, outside the row's width, on the reasoning that a+ * provenance mark should not re-size the cells and make a fallback list+ * geometrically incomparable to a live one. The model panel is `overflow="hidden"`,+ * so the chip was clipped away ENTIRELY — the single highest-value signal in the+ * feature, invisible, in the exact state the feature exists for. Comparability lost+ * to visibility; the two lists are never on screen at the same time anyway.+ */+ mark: number;+ /** Release date, `padStartTo`-ed. 0 below the widest tier — it is chrome. */+ date: number;+ /** Single-space separators the renderer emits. Part of the sum. */+ gaps: number;+}++/** A tier of the ladder: everything fixed, plus the elastic cell's bounds. */+interface Tier {+ cursor: number;+ ctxNum: number;+ price: number;+ priceNum: number;+ caps: number;+ date: number;+ gaps: number;+ /** Nominal id width. The meter only grows past its minimum once this is satisfied. */+ id: number;+ ctxMin: number;+ ctxMax: number;+}++/**+ * The ladder. `min` is inclusive and the rows are ordered widest-first, so the+ * first match wins.+ *+ * `gaps` is the number of single-space separators the row renderer emits between+ * the cells this tier keeps — one fewer than the number of cells, because the+ * cursor gutter carries its own space. It is counted here rather than derived so+ * that `fixedCells` (below) is the single number the elastic split works from; the+ * renderer and this table are kept in step by the exact-sum test, which would fail+ * the instant one emitted a separator the other had not budgeted.+ */+const TIERS: ReadonlyArray<{ min: number; tier: Tier }> = [+ {+ // ≥ 96: everything — both meters, the capability column, the release date.+ min: 96,+ tier: {+ cursor: 2,+ ctxNum: 6,+ price: 10,+ priceNum: 9,+ caps: 5,+ date: 10,+ gaps: 6,+ id: 36,+ ctxMin: 10,+ ctxMax: 24,+ },+ },+ {+ // 70–95: the release date goes first — it is the one cell that is pure chrome.+ min: 70,+ tier: {+ cursor: 2,+ ctxNum: 6,+ price: 8,+ priceNum: 9,+ caps: 5,+ date: 0,+ gaps: 5,+ id: 32,+ ctxMin: 8,+ ctxMax: 16,+ },+ },+ {+ // 56–69 — the 80-column tier, and the one the density count turns on. The+ // price METER goes; its numeral stays, because the number is the fact and the+ // bar is only the comparison.+ min: 56,+ tier: {+ cursor: 2,+ ctxNum: 6,+ // NINE, not eight: `$30.00/1M` is nine columns and an eight-column cell rendered+ // it `$30.00/…`. A truncated PRICE is the one truncation this row cannot afford —+ // it is the number the user is choosing on, and a clipped one reads as a+ // different, smaller number.+ price: 0,+ priceNum: 9,+ caps: 6,+ date: 0,+ gaps: 4,+ id: 23,+ ctxMin: 6,+ ctxMax: 10,+ },+ },+ {+ // 44–55: the id gives way before the meter does.+ min: 44,+ tier: {+ cursor: 2,+ ctxNum: 6,+ price: 0,+ priceNum: 9,+ caps: 6,+ date: 0,+ gaps: 4,+ id: 17,+ ctxMin: 5,+ ctxMax: 10,+ },+ },+ {+ // < 44: id, meter, two numerals. `id: MIN_ID_CELLS` makes the meter pin to+ // `ctxMax` and the id take every remaining column — "id: rest".+ min: 0,+ tier: {+ cursor: 2,+ ctxNum: 5,+ price: 0,+ priceNum: 7,+ caps: 0,+ date: 0,+ gaps: 3,+ id: MIN_ID_CELLS,+ ctxMin: MIN_CTX_CELLS,+ ctxMax: MIN_CTX_CELLS,+ },+ },+];++/** Everything in a tier except the id and the context meter. */+function fixedCells(t: Tier): number {+ return t.cursor + t.ctxNum + t.price + t.priceNum + t.caps + t.date + t.gaps;+}++/**+ * The cell widths for a model row `rowCells` columns wide.+ *+ * Clamped, never trusted: a caller that hands this a negative, fractional or+ * non-finite width gets the narrowest tier rather than NaN columns, because a NaN+ * width reaches `Meter` as a zero-width widget — nothing painted, nothing thrown.+ */+export function deriveRowLayout(rowCells: number, opts: { mark?: boolean } = {}): RowLayout {+ const cells = Number.isFinite(rowCells) ? Math.max(0, Math.floor(rowCells)) : 0;+ const t = (TIERS.find((row) => cells >= row.min) ?? TIERS[TIERS.length - 1]!).tier;+ // ` CAT ` plus its separator, and only when the list is a fallback. It comes out of+ // the ID, which is the one cell with slack — never out of the context meter.+ const mark = opts.mark === true && cells >= 44 ? MARK_CELLS + 1 : 0;+ const fixed = fixedCells(t) + mark;++ // `id + ctx` is whatever the fixed cells leave. Split it so the id gets its+ // nominal width first, the meter takes the surplus up to its tier maximum, and+ // any remainder goes back to the id — which is what makes a 145-column row sum+ // exactly rather than leaving a dead tail where the meter stopped growing.+ const budget = Math.max(0, cells - fixed);+ let ctx = Math.min(Math.max(budget - t.id, MIN_CTX_CELLS), t.ctxMax);+ let id = budget - ctx;++ if (id < MIN_ID_CELLS) {+ // Too narrow for both. The id keeps its floor and the meter gives way down to+ // its own floor; below that the id pays, because a 3-cell meter is still a+ // meter and a 2-column id is not a name.+ id = Math.min(MIN_ID_CELLS, budget);+ ctx = Math.max(0, budget - id);+ if (ctx < MIN_CTX_CELLS) {+ ctx = Math.min(MIN_CTX_CELLS, budget);+ id = Math.max(0, budget - ctx);+ }+ }++ return {+ rowCells: cells,+ cursor: t.cursor,+ id,+ ctx,+ ctxNum: t.ctxNum,+ price: t.price,+ priceNum: t.priceNum,+ caps: t.caps,+ date: t.date,+ gaps: t.gaps,+ mark,+ };+}++/** ` CAT ` — `BadgeSpan` pads one column each side of the label, outside the fill. */+const MARK_CELLS = 5;++/** Sum of every cell plus the separators — must equal `rowCells`. */+export function rowLayoutTotal(l: RowLayout): number {+ return (+ l.cursor + l.id + l.ctx + l.ctxNum + l.price + l.priceNum + l.caps + l.date + l.gaps + l.mark+ );+}++/**+ * The two columns of the picker, and what each leaves for its content.+ *+ * `railW` is 19 / 24 per the design; the rest follows from the two chrome costs+ * the skill MEASURED and this repo re-measured: a `Panel` spends 2 columns of+ * border when `flush` (4 when not), and a `<scrollbox>` inside it spends 1 more+ * for the thumb. The one-column `gap` between the panes is real — it is set on the+ * flex row, so it has to come out of the budget here too.+ */+export interface PaneLayout {+ /** Outer width of the provider rail, borders included. */+ railW: number;+ /** Usable columns inside the rail's flush panel. */+ railInner: number;+ /** Outer width of the model panel. */+ panelOuter: number;+ /** Usable columns for one model row, inside the panel and beside the thumb. */+ rowCells: number;+}++export function derivePanes(width: number): PaneLayout {+ const w = Number.isFinite(width) ? Math.max(20, Math.floor(width)) : 80;+ const railW = w >= 100 ? 24 : 19;+ const panelOuter = Math.max(8, w - railW - 1);+ return {+ railW,+ // MINUS THREE, not two: the flush `Panel` spends 2 columns of border and the+ // `<scrollbox>` inside it spends 1 more for the thumb — the second cost measured by+ // the skill and re-measured here, where budgeting only the border clipped the+ // billing tag on every rail row (`SUB` painted as `SU`).+ railInner: Math.max(4, railW - 3),+ panelOuter,+ rowCells: Math.max(12, panelOuter - 3),+ };+}++/** One provider rail row's cells. The LABEL is the elastic cell here. */+export interface RailLayout {+ railInner: number;+ /** Readiness glyph — `●` / `○` / `◌`. */+ glyph: number;+ /** Provider name, truncated. */+ label: number;+ /** Right-aligned billing tag: `SUB` / `LOCAL` / `$`. */+ tag: number;+ /** Served-model count, or 0 when the rail is too narrow to carry one. */+ count: number;+ gaps: number;+}++/**+ * THE BILLING TAG IS PLAIN COLOURED TEXT, NOT A `BadgeSpan`, and that is a budget+ * decision taken against the skill's default ("discrete status → badge"). A chip+ * pays two columns of padding for its fill; the rail's whole inner width is 17 at+ * 80 columns, so those two columns come straight off the provider NAME — and a+ * rail whose names are all elided has lost more than a chip gains. The readiness+ * glyph and the tag's own colour carry the status, and the model panel spends its+ * chips where there is room for them. §5.3's own mock renders the bare form.+ */+const TAG_CELLS = 5;++export function deriveRailLayout(railInner: number): RailLayout {+ const inner = Number.isFinite(railInner) ? Math.max(4, Math.floor(railInner)) : 17;+ // The count needs a rail wide enough that the NAME does not pay for it.+ const count = inner >= 20 ? 3 : 0;+ let gaps = count > 0 ? 3 : 2;+ let tag = TAG_CELLS;+ let label = inner - 1 - tag - count - gaps;+ if (label < 3) {+ // Absurdly narrow: the tag goes before the name does. A rail of billing tags with+ // no provider names in it is not a rail. `Math.max(1, …)` on the label instead+ // would have kept the tag and OVERFLOWED the row — measured: 9 cells rendered into+ // an 8-column rail, which Yoga then claws back from whichever cell it likes.+ tag = 0;+ gaps = 1;+ label = inner - 1 - count - gaps;+ }+ if (label < 1) {+ gaps = 0;+ label = Math.max(0, inner - 1 - count);+ }+ return { railInner: inner, glyph: 1, label, tag, count, gaps };+}++/** Sum of a rail row's cells — must equal `railInner`. */+export function railLayoutTotal(l: RailLayout): number {+ return l.glyph + l.label + l.tag + l.count + l.gaps;+}++/**+ * Chrome that is HEIGHT-gated, not width-gated — the scarce axis at 80×24 is rows.+ *+ * Each threshold is named once here because every one of them is a row the model+ * list does not get, and §4.6's whole-frame density arithmetic is built on these+ * exact numbers.+ */+export const CHROME = {+ /** Two header rows (identity + context) above this height, one below. */+ headerTwoRows: 30,+ /** `StatsStrip` takes a bordered `Panel` with three rows at or above this. */+ statsPanel: 34,+ /** The discovery banner takes a full border (2 rows of chrome) at or above this. */+ bannerBordered: 30,+ /**+ * The two pinned detail blocks appear at or above this height.+ *+ * Below it every row belongs to a list: a detail block would trade two model rows —+ * two GRAPHICS rows — for two rows of prose, which is the wrong direction for the+ * whole-frame density count on the terminal where that count is tightest.+ */+ detail: 26,+} as const;diff --git a/packages/cli/src/picker/model-picker-run.tsx b/packages/cli/src/picker/model-picker-run.tsxnew file mode 100644index 00000000..6c5395fc--- /dev/null+++ b/packages/cli/src/picker/model-picker-run.tsx@@ -0,0 +1,153 @@+/** @jsxImportSource @opentui/react */+/**+ * picker/model-picker-run.tsx — bootstrap, teardown, and the ONE stderr write.+ *+ * This is the only place `@opentui/core` and `@opentui/react` meet, and it is reached+ * from `model-selector.ts` through a DYNAMIC `await import()` — which is what keeps a+ * renderer out of the cold-start graph and, more importantly, out of the MCP stdio+ * path, whose stdout is a protocol. `providers/model-ordering.ts:10-18` records why+ * that constraint exists; it applies with more force to OpenTUI than to inquirer.+ *+ * THREE DEPARTURES FROM THE SKILL'S STOCK BOOTSTRAP, each forced by a fact:+ *+ * 1. `screenMode: "alternate-screen"`, never `useAlternateScreen: true`. The installed+ * `@opentui/[email protected]` renamed the option; the old key is an unknown key,+ * SILENTLY ignored, and the picker would draw over the user's scrollback.+ *+ * 2. `installShutdown` is not used. Its contract ends in `process.exit(code)`, which is+ * right for an app whose quit key means quit and wrong for a picker, whose entire job+ * is to hand a model spec back to a caller that then launches Claude Code. What it+ * guarantees — never leave the terminal wedged in raw mode inside the alternate+ * screen — is provided by the `finally` below, which always unmounts React and then+ * destroys the renderer, in that order. Same reasoning, same order, as+ * `resume-picker-run.tsx:20-29`.+ *+ * 3. `setStderrQuiet(true)` before the renderer and `false` after. Anything written to+ * the terminal behind a live renderer leaves cells OpenTUI cannot invalidate — ghost+ * characters, not an exception, which is why no test catches it.+ *+ * AND ONE WRITE THAT IS DELIBERATE. The alternate screen is DISCARDED by+ * `renderer.destroy()`, so the in-panel failure notice is gone the instant the user+ * picks a model and Claude Code starts. A scrollback line is the only durable record,+ * and it is the record the current behaviour already provides — including to a user who+ * pipes stderr to a file. So every failure seen during the session is buffered and+ * written once, after teardown, at the same point `resume-picker-run.tsx:115` restores+ * stderr. Every failure, in order, not just the one the user landed on: today each+ * failed selection prints immediately, so a session that tried two failing providers+ * leaves two diagnostics, and writing one would be a quiet narrowing.+ */++import { createCliRenderer } from "@opentui/core";+import { createRoot } from "@opentui/react";+import { setStderrQuiet } from "../logger.js";+import type { ModelSelectorOptions } from "../model-selector.js";+import { ensureEndpointsRegistered } from "../providers/endpoint-registration.js";+import { applyRendererThemeMode } from "../theme/renderer-theme.js";+import { ModelPicker } from "./ModelPicker.js";+import { type PickerDataSource, createPickerDataSource } from "./PickerDataSource.js";++/** What the picker hands back. `null` ⟺ the user declined to choose. */+export interface ModelPickerOutcome {+ model: string | null;+}++/**+ * A scriptable data source, selected by `CLAUDISH_PICKER_FIXTURE=<name>`.+ *+ * DEV-ONLY, AND REACHED BY DYNAMIC IMPORT BEHIND THE ENV CHECK, so+ * `bun build --compile` never walks into `picker/fixtures/` and the shipped binary+ * carries no fixture data. The states it forces — a timeout, an empty roster, a roster+ * where nothing is chat-capable, and the in-flight frames themselves — are not+ * reachable against a live provider, and they are the states this feature exists to+ * render. A capture of the happy path alone would validate nothing.+ */+async function resolveDataSource(): Promise<PickerDataSource> {+ const name = process.env.CLAUDISH_PICKER_FIXTURE;+ if (!name) return createPickerDataSource();+ const { createFixtureDataSource } = await import("./fixtures/fixture-source.js");+ return createFixtureDataSource(name);+}++export async function runModelPicker(+ _options: ModelSelectorOptions = {}+): Promise<ModelPickerOutcome> {+ // Before the first render, exactly as `tui/index.tsx:38` does it: the rail is built+ // from `getAllProviders()`, so a custom or predefined endpoint must already be in the+ // roster or it is simply not there to pick. Re-entry calls this again — idempotent by+ // design. It is synchronous, and it runs before `createCliRenderer`, so it costs no+ // frame. (`claudish profile edit` reaches `selectModel` WITHOUT passing through+ // `index.ts:590`, so without this line that path enumerates an unregistered roster.)+ ensureEndpointsRegistered();++ const source = await resolveDataSource();++ /** Buffered diagnostics: provider → the lines, in the order the failures occurred. */+ const deferred: Array<{ provider: string; lines: readonly string[] }> = [];++ setStderrQuiet(true);++ const renderer = await createCliRenderer({+ screenMode: "alternate-screen",+ exitOnCtrlC: false, // the picker maps Ctrl+C to "cancel", which RETURNS a value+ });++ // Light/dark palette selection BEFORE first paint. Unanswered → null → dark, which+ // is the status quo. This is what makes every `C.*`/`tokens.*` read in the tree+ // below resolve to the right palette — and why none of them may be a module-level+ // `const`, which would have snapshotted dark before this line ran.+ await applyRendererThemeMode(renderer);++ const root = createRoot(renderer);++ let chosen: string | null = null;+ try {+ await new Promise<void>((resolve) => {+ let settled = false;+ const done = (spec: string | null): void => {+ // Enter and Ctrl+C can both land before the tree stops rendering, and resolving+ // twice would leave the second teardown racing the first.+ if (settled) return;+ settled = true;+ chosen = spec;+ resolve();+ };+ root.render(+ <ModelPicker+ source={source}+ onDone={done}+ onDiscoveryFailure={(provider, lines) => deferred.push({ provider, lines })}+ />+ );+ });+ } finally {+ // Order is load-bearing, and the reason this is a `finally`: unmount React first so+ // nothing can paint into a destroyed renderer, then destroy, which is what actually+ // restores the terminal out of raw mode and off the alternate screen. Each step is+ // guarded on its own — a throwing unmount must not be able to skip the destroy.+ // In-flight fetches are abandoned, not awaited; nothing writes to a dead renderer+ // because the tree is already gone.+ try {+ root.unmount();+ } catch {+ /* the tree is already gone; the destroy below is what matters */+ }+ try {+ renderer.destroy();+ } catch {+ /* nothing left to restore */+ }+ setStderrQuiet(false);++ // THE ONE ALLOWED WRITE. `picker/**` and `tui/**` are forbidden from touching+ // stdout/stderr — the renderer owns the terminal — and this block is the explicit+ // exception, asserted as such by `no-terminal-writes.test.ts`. It runs AFTER the+ // renderer is destroyed, so there is no buffer left to corrupt. The lines carry+ // their own newlines, so the bytes match what `warnDiscoveryFailure` has always+ // written.+ for (const entry of deferred) {+ for (const line of entry.lines) process.stderr.write(line);+ }+ }++ return { model: chosen };+}diff --git a/packages/cli/src/picker/no-terminal-writes.test.ts b/packages/cli/src/picker/no-terminal-writes.test.tsnew file mode 100644index 00000000..d2ff2299--- /dev/null+++ b/packages/cli/src/picker/no-terminal-writes.test.ts@@ -0,0 +1,67 @@+import { describe, expect, test } from "bun:test";+/**+ * THE RENDERER OWNS THE TERMINAL.+ *+ * Inside `picker/` and `tui/`, `process.stdout.write`, `process.stderr.write` and+ * `console.*` are forbidden. Anything written behind a live renderer leaves cells+ * OpenTUI cannot invalidate — ghost characters that survive every redraw — and the+ * failure is silent: no exception, no stderr, and `tsc`, `bun test` and `check-surface`+ * all stay green. Only a screenshot catches it, and only if someone happens to take one+ * of that screen.+ *+ * `setStderrQuiet(true)` is NOT a defence. It sets a module flag read in exactly one+ * place — `logStderr`, `logger.ts:294` — so a raw `process.stderr.write` sails straight+ * past it. That is not hypothetical: `warnDiscoveryFailure` (`model-selector.ts:1305`)+ * is four such raw writes, which is precisely why the OpenTUI picker never calls it and+ * carries the failure as render state instead.+ *+ * A GREP IS CRUDE, AND IT IS THE ONLY MECHANISM THAT CATCHES THIS CLASS. The allowlist+ * is two paths, each with a reason, rather than a pattern — a pattern would rot into+ * permission.+ */+import { readFileSync, readdirSync, statSync } from "node:fs";+import { join } from "node:path";++const SRC = new URL(".", import.meta.url).pathname.replace(/\/picker\/$/, "");++/**+ * Both entries write only AFTER their renderer is destroyed, when there is no buffer+ * left to corrupt.+ */+const ALLOWED = new Set([+ // The one deferred diagnostic, in the `finally` after `renderer.destroy()`.+ "/picker/model-picker-run.tsx",+ // The post-TUI login handoff, which runs after the config TUI has torn down.+ "/tui/index.tsx",+ // `installShutdown`'s failure report, which its own comment pins to after `destroy()`.+ "/tui/runtime/shutdown.ts",+]);++function walk(dir: string, out: string[] = []): string[] {+ for (const entry of readdirSync(dir)) {+ const full = join(dir, entry);+ if (statSync(full).isDirectory()) walk(full, out);+ else if (/\.(ts|tsx)$/.test(entry) && !/\.test\.tsx?$/.test(entry)) out.push(full);+ }+ return out;+}++const WRITE = /process\.std(out|err)\.write|console\.(log|error|warn|info)\s*\(/;++describe("no terminal writes behind a live renderer", () => {+ test("picker/ and tui/ never write to stdout, stderr or console", () => {+ const files = [...walk(join(SRC, "picker")), ...walk(join(SRC, "tui"))];+ const offenders = files+ .map((f) => f.replace(SRC, ""))+ .filter((rel) => !ALLOWED.has(rel))+ .filter((rel) => WRITE.test(readFileSync(join(SRC, rel), "utf8")));+ expect(offenders).toEqual([]);+ });++ test("the allowlist is not empty and every entry still exists", () => {+ // A stale allowlist entry is a rule that has quietly stopped applying to anything.+ for (const rel of ALLOWED) {+ expect(readFileSync(join(SRC, rel), "utf8").length).toBeGreaterThan(0);+ }+ });+});diff --git a/packages/cli/src/picker/row-semantics.test.ts b/packages/cli/src/picker/row-semantics.test.tsnew file mode 100644index 00000000..9a2054fe--- /dev/null+++ b/packages/cli/src/picker/row-semantics.test.ts@@ -0,0 +1,256 @@+import { describe, expect, test } from "bun:test";+import type { ModelInfo, PickerDiscoveryOutcome } from "../model-selector.js";+/**+ * The pure arithmetic behind a model row and a discovery notice — the tier that needs+ * no renderer, and the tier where the honesty rules are actually decidable.+ *+ * Two of these assertions exist because the alternative reading is silently plausible:+ * an absent context window must yield `NaN` (which paints `╌`) and NEVER 0 (which+ * paints the same full track a healthy tiny window paints), and no rendered notice may+ * contain the substring `undefined`.+ */+import type { DiscoveryFailure } from "../providers/model-discovery.js";+import { discoveryNoticeContent, mergeCredentialLines } from "./DiscoveryNotice.js";+import { ctxMix, priceMix, resample } from "./StatsStrip.js";+import { billingTag, contextMeterPct, parseDisplayPrice, priceMeterPct } from "./rows.js";++const model = (over: Partial<ModelInfo> = {}): ModelInfo => ({+ id: "m",+ name: "m",+ description: "",+ provider: "p",+ ...over,+});++describe("contextMeterPct", () => {+ test("is monotonic and bounded 0..100", () => {+ const pcts = [8_000, 32_000, 128_000, 512_000, 1_000_000].map((n) =>+ contextMeterPct(n, 8_000, 1_000_000)+ );+ expect(pcts.every((p) => p >= 0 && p <= 100)).toBe(true);+ expect([...pcts].sort((a, b) => a - b)).toEqual(pcts);+ });++ test("an absent window is NaN, never 0", () => {+ // 0 would paint a full `░` track — pixel-identical to a healthy 8 K model.+ expect(Number.isNaN(contextMeterPct(undefined, 1000, 2000))).toBe(true);+ expect(Number.isNaN(contextMeterPct(0, 1000, 2000))).toBe(true);+ });++ test("a homogeneous list does not collapse its smallest row to an empty bar", () => {+ // MEASURED on the first capture: a 250K/1M roster scaled to its own bounds painted+ // every 250K row at exactly 0%. The floor is anchored six doublings below the max.+ expect(contextMeterPct(250_000, 250_000, 1_000_000)).toBeGreaterThan(50);+ expect(contextMeterPct(1_000_000, 250_000, 1_000_000)).toBe(100);+ });++ test("a degenerate range answers 100 rather than dividing by zero", () => {+ expect(contextMeterPct(1000, 1000, 1000)).toBe(100);+ expect(contextMeterPct(1000, 0, 0)).toBe(100);+ });+});++describe("priceMeterPct", () => {+ test("CHEAPER IS A LONGER BAR — the ramp ends green, so the fill is cheapness", () => {+ const cheap = priceMeterPct(0.1, 0.1, 15);+ const dear = priceMeterPct(15, 0.1, 15);+ expect(cheap).toBe(100);+ expect(dear).toBe(0);+ });++ test("free is a full bar; an absent rate is NaN", () => {+ expect(priceMeterPct(0, 0.1, 15)).toBe(100);+ expect(Number.isNaN(priceMeterPct(undefined, 0.1, 15))).toBe(true);+ });+});++describe("parseDisplayPrice", () => {+ test("reads the number out of a display string and nothing out of a word", () => {+ expect(parseDisplayPrice("$9.00/1M")).toBe(9);+ expect(parseDisplayPrice("$0.15/1M")).toBe(0.15);+ expect(parseDisplayPrice("SUB")).toBeUndefined();+ expect(parseDisplayPrice("N/A")).toBeUndefined();+ });+});++describe("billingTag", () => {+ test("each mode has its own word and its own colour", () => {+ const tags = (["sub", "local", "metered"] as const).map(billingTag);+ expect(tags.map((t) => t.text)).toEqual(["SUB", "LOCAL", "$"]);+ expect(new Set(tags.map((t) => t.fg)).size).toBe(3);+ });+});++describe("ctxMix / priceMix", () => {+ test("price bands are exclusive and count only rows with a per-token rate", () => {+ // A subscription row has no number to band, and inventing one would put a flat-rate+ // plan somewhere on a price axis it does not sit on.+ const list = [+ model({ pricing: { input: "", output: "", average: "FREE" } }),+ model({ pricing: { input: "", output: "", average: "$0.15/1M" } }),+ model({ pricing: { input: "", output: "", average: "$2.90/1M" } }),+ model({ pricing: { input: "", output: "", average: "$30.00/1M" } }),+ model({ pricing: { input: "", output: "", average: "SUB" } }),+ model({}),+ ];+ expect(priceMix(list)).toEqual([1, 1, 1, 1]);+ });++ test("context buckets sum to the models that HAVE a window", () => {+ const list = [+ model({ contextLength: 8_000 }),+ model({ contextLength: 131_072 }),+ model({ contextLength: 1_000_000 }),+ model({}),+ ];+ expect(ctxMix(list).reduce((a, b) => a + b, 0)).toBe(3);+ });+});++describe("resample", () => {+ test("always paints exactly the requested number of columns", () => {+ for (const n of [0, 1, 5, 21, 342]) {+ for (const w of [1, 8, 48]) {+ expect(+ resample(+ Array.from({ length: n }, (_, i) => i),+ w+ ).length+ ).toBe(n === 0 ? 0 : w);+ }+ }+ });+});++const failure = (over: Partial<DiscoveryFailure> = {}): DiscoveryFailure => ({+ kind: "unauthorized",+ provider: "kimi",+ ...over,+});++describe("discoveryNoticeContent", () => {+ test("`failed` is the ERROR tier; the three empty states are the NOTICE tier", () => {+ const rows: PickerDiscoveryOutcome[] = [+ { kind: "failed", failure: failure(), notice: ["⚠ x failed"], fallbackRows: [] },+ { kind: "empty-roster", failure: failure({ kind: "empty-roster" }), fallbackRows: [] },+ { kind: "all-filtered", servedCount: 3, sampleIds: ["e"], fallbackRows: [] },+ { kind: "collapsed-empty", servedCount: 3, chatCount: 3, fallbackRows: [] },+ ];+ expect(rows.map((o) => discoveryNoticeContent(o, "Kimi")?.severity)).toEqual([+ "error",+ "notice",+ "notice",+ "notice",+ ]);+ });++ test("`rows` and `unsupported` render nothing at all", () => {+ expect(+ discoveryNoticeContent(+ { kind: "rows", rows: [model()], servedCount: 1, chatCount: 1 },+ "Kimi"+ )+ ).toBeNull();+ expect(+ discoveryNoticeContent({ kind: "unsupported", reason: "no-descriptor" }, "Kimi")+ ).toBeNull();+ });++ test("`empty-roster` and `all-filtered` say DIFFERENT things — V7's automatable half", () => {+ const empty = discoveryNoticeContent(+ { kind: "empty-roster", failure: failure({ kind: "empty-roster" }), fallbackRows: [] },+ "Kimi"+ );+ const filtered = discoveryNoticeContent(+ {+ kind: "all-filtered",+ servedCount: 7,+ sampleIds: ["text-embedding-3-large"],+ fallbackRows: [],+ },+ "Kimi"+ );+ expect(empty?.lines[0]).toContain("empty");+ expect(filtered?.lines[0]).toContain("none of them chat-capable");+ expect(filtered?.lines.join(" ")).toContain("text-embedding-3-large");+ expect(empty?.lines[0]).not.toBe(filtered?.lines[0]);+ });++ test("a fallback list gets the PROVENANCE sentence; no fallback gets a next step", () => {+ const withRows = discoveryNoticeContent(+ { kind: "empty-roster", failure: failure({ kind: "empty-roster" }), fallbackRows: [model()] },+ "Kimi"+ );+ const without = discoveryNoticeContent(+ { kind: "empty-roster", failure: failure({ kind: "empty-roster" }), fallbackRows: [] },+ "Kimi"+ );+ expect(withRows?.lines.join(" ")).toContain("not its live roster");+ expect(without?.lines.join(" ")).toContain("Press c");+ });++ test("the HTTP status becomes a badge and leaves the headline once", () => {+ const c = discoveryNoticeContent(+ {+ kind: "failed",+ failure: failure({ status: 401 }),+ notice: ["\n⚠ Kimi could not list its models: the API key was rejected (HTTP 401)\n"],+ fallbackRows: [model()],+ },+ "Kimi"+ );+ expect(c?.badge).toBe("HTTP 401");+ expect(c?.lines[0]).not.toContain("(HTTP 401)");+ expect(c?.lines[0]).toContain("the API key was rejected");+ });++ test("NO rendered notice ever contains the substring `undefined`", () => {+ // Every variant × endpoint present/absent × status present/absent. `endpoint` and+ // `status` are both optional and a registered fetcher may report neither.+ const variants: PickerDiscoveryOutcome[] = [];+ for (const endpoint of [undefined, "https://api.test/v1/models"]) {+ for (const status of [undefined, 500]) {+ const f = failure({+ ...(endpoint === undefined ? {} : { endpoint }),+ ...(status === undefined ? {} : { status }),+ });+ variants.push({ kind: "failed", failure: f, notice: ["⚠ x"], fallbackRows: [] });+ variants.push({+ kind: "empty-roster",+ failure: { ...f, kind: "empty-roster" },+ fallbackRows: [],+ });+ }+ }+ variants.push({ kind: "all-filtered", servedCount: 1, sampleIds: [], fallbackRows: [] });+ variants.push({ kind: "collapsed-empty", servedCount: 1, chatCount: 1, fallbackRows: [] });+ for (const v of variants) {+ const c = discoveryNoticeContent(v, "Kimi");+ expect([v.kind, c?.lines.join(" ").includes("undefined") ?? false]).toEqual([v.kind, false]);+ }+ });+});++describe("mergeCredentialLines", () => {+ test("merges the env-var and key-URL rows when they fit, dropping the parenthetical", () => {+ const lines = [+ "⚠ Kimi could not list its models: the API key was rejected",+ "Check MOONSHOT_API_KEY (a value in your shell overrides stored credentials).",+ "Get a key: https://platform.moonshot.cn/",+ "Showing Kimi's cloud-catalog entries below — not its live roster.",+ ];+ const merged = mergeCredentialLines(lines, 78);+ expect(merged.length).toBe(3);+ expect(merged[1]).toBe("Check MOONSHOT_API_KEY · Get a key: https://platform.moonshot.cn/");+ });++ test("leaves them apart when the merge would not fit", () => {+ const lines = [+ "head",+ "Check A_VERY_LONG_ENVIRONMENT_VARIABLE_NAME_INDEED (advice).",+ "Get a key: https://example.test/an/extremely/long/path/to/the/api/keys/page",+ "tail",+ ];+ expect(mergeCredentialLines(lines, 40)).toEqual(lines);+ });+});diff --git a/packages/cli/src/picker/rows.tsx b/packages/cli/src/picker/rows.tsxnew file mode 100644index 00000000..9e1e0c41--- /dev/null+++ b/packages/cli/src/picker/rows.tsx@@ -0,0 +1,361 @@+/** @jsxImportSource @opentui/react */+/**+ * picker/rows.tsx — one model row, one provider rail row, and the pure arithmetic+ * behind both.+ *+ * A RENDERING CHANGE, NOT A DATA CHANGE — which is the single largest risk+ * reduction available in this feature. The row the old picker printed was+ * `kimi@kimi-k3 ($9.00/1M, 1M [TRV], 2026-07)`: a price, a context window, three+ * capability flags and a release date, four visual encodings concatenated into one+ * parenthetical string. Every value a rich row needs therefore ALREADY reaches the+ * view, so this file adds no fetch, no field and no plumbing, and a row regression+ * can only ever be visual.+ *+ * ONE `<text>` PER ROW, ALWAYS. Yoga claws columns back from the LAST `<text>`+ * child of a row, which is how a branch name once rendered as `mai` with thirty+ * free columns beside it (`resume-picker.tsx:473-484`). So every cell is a+ * `<span>` inside a single text node, and the widgets used here are the `*Span`+ * twin `MeterSpan` — never `Meter`, which is a `<text>` and+ * cannot nest.+ *+ * COLOUR IS READ AT RENDER TIME, never captured in a module-level `const`:+ * `C`/`tokens` are reassigned in place when the terminal theme is detected, and a+ * snapshot taken at import would ship the dark palette to a light terminal. That+ * bug has been found six times in this repo, once visible only in a live+ * screenshot.+ */++import type { ReactNode } from "react";+import type { ModelInfo } from "../model-selector.js";+import { A, C } from "../tui/theme.js";+import { padStartTo, padTo, truncate } from "../tui/viz/text.js";+import { ramps, tokens } from "../tui/viz/tokens.js";+import { MeterSpan } from "../tui/viz/widgets.js";+import type { BillingMode } from "./PickerDataSource.js";+import type { RailLayout, RowLayout } from "./layout.js";++/** Readiness, in `ProvidersContent.tsx:225`'s exact vocabulary. */+export type Readiness = "pending" | "ready" | "missing";++/**+ * LOG-SCALED, and that is not a refinement — it is what makes the column readable.+ *+ * A picker list spans 8 K (a small local pull) to 1 M (Gemini): two and a half+ * decades. On a linear scale every model except the top one paints at or near zero,+ * so the meter would carry no information for 95% of the rows while looking like it+ * did. On a log scale the decades are evenly spaced and a 128 K model reads as+ * visibly larger than a 32 K one.+ *+ * Bounds come from the CURRENTLY FILTERED list, so the column re-scales as the user+ * narrows it — the comparison a reader is making is always against what they can+ * see. A degenerate range (one row, or every row identical) yields 100: a full bar+ * is the honest answer when the largest thing visible is also the smallest.+ *+ * THE SCALE'S FLOOR IS AT LEAST SIX DOUBLINGS BELOW THE LARGEST, never simply the+ * list's own minimum — MEASURED on the first capture. A roster of 250 K and 1 M models+ * scaled to its own bounds paints every 250 K row at exactly 0%: an empty track, which+ * is the glyph `Meter` uses for "nothing", under a numeral that says 250 K. The column+ * stops carrying information precisely when the list is homogeneous, which is most+ * lists. Anchoring the floor at `max / 64` makes the bar mean something stable — "how+ * big, on a log scale spanning at least six doublings" — and the 250 K row reads at two+ * thirds instead of at zero.+ *+ * `NaN` for an absent window, deliberately: `MeterSpan` paints `NaN` as a dim `╌`+ * run, while 0 paints the same full `░` track a healthy-but-tiny window paints.+ * Absent data and small data must not look alike.+ */+export function contextMeterPct(ctx: number | undefined, min: number, max: number): number {+ if (!ctx || !Number.isFinite(ctx) || ctx <= 0) return Number.NaN;+ if (!Number.isFinite(max) || max <= 0) return 100;+ const lo = Math.min(Number.isFinite(min) && min > 0 ? min : max, max / 64);+ if (max <= lo) return 100;+ const pct = (100 * (Math.log(ctx) - Math.log(lo))) / (Math.log(max) - Math.log(lo));+ return Math.min(100, Math.max(0, pct));+}++/**+ * THE FILL IS CHEAPNESS, NOT COST, and the ramp is why.+ *+ * `ramps.savings` runs red → yellow → green, so a FULL bar is green. A meter+ * colours cells by position along the fill, so if length encoded cost the dearest+ * model on screen would paint a full green bar — red meaning "cheap" on one row and+ * green meaning "expensive" on the next, which is the one-colour-one-meaning rule+ * broken inside a single column. Encoding cheapness instead makes a long green bar+ * "costs you least" and a one-cell red stub "costs you most", which is both true+ * and the direction a reader scanning for a cheap model wants.+ *+ * Log-scaled for the same reason as the context meter: per-token prices on one+ * screen span $0.05 to $15 per million.+ */+export function priceMeterPct(price: number | undefined, min: number, max: number): number {+ if (price === undefined || !Number.isFinite(price) || price < 0) return Number.NaN;+ if (price === 0) return 100;+ if (!Number.isFinite(min) || !Number.isFinite(max) || min <= 0 || max <= min) return 100;+ const clamped = Math.min(Math.max(price, min), max);+ const t = (Math.log(clamped) - Math.log(min)) / (Math.log(max) - Math.log(min));+ return Math.min(100, Math.max(0, 100 * (1 - t)));+}++/**+ * `$9.00/1M` → 9. `SUB`, `LOCAL`, `N/A` → undefined.+ *+ * Parsed rather than plumbed because `resolveProviderDisplayPrice` is the ONE+ * function allowed to decide what a row costs (its `isSubscriptionProvider`-first+ * rule is test-pinned), and it answers a display string. Re-deriving the number+ * from a second source would be a second opinion about money.+ */+export function parseDisplayPrice(display: string): number | undefined {+ const m = /\d+(\.\d+)?/.exec(display);+ if (!m) return undefined;+ const n = Number.parseFloat(m[0]);+ return Number.isFinite(n) ? n : undefined;+}++/** The rail's billing tag — right-aligned text, the colour carrying the meaning. */+export function billingTag(mode: BillingMode): { text: string; fg: string } {+ if (mode === "sub") return { text: "SUB", fg: tokens.success };+ if (mode === "local") return { text: "LOCAL", fg: tokens.running };+ return { text: "$", fg: tokens.subtle };+}++/** `●` ready · `○` needs a key · `◌` probe in flight — `ProvidersContent.tsx:225`. */+export function readinessGlyph(r: Readiness): { glyph: string; fg: string } {+ if (r === "ready") return { glyph: "●", fg: tokens.success };+ if (r === "missing") return { glyph: "○", fg: tokens.dead };+ return { glyph: "◌", fg: tokens.warn };+}++/** Where a list came from — the one value that drives all three fallback encodings. */+export type ListOrigin = "roster" | "catalog";++/**+ * A flat-rate price gets a dim `╌` run where the METER would be, and its word in+ * `tokens.success` where the numeral would be — never a 0% or zero-width meter. A+ * subscription has no per-token number, and an empty bar in the cheapness column would+ * read as "the cheapest thing on screen", which is a different claim from "this is not+ * billed per token". `Meter` makes the same distinction for `NaN`, in the same glyph.+ *+ * NOT A `BadgeSpan`, AND THAT IS MEASURED. The first capture rendered ` SUB ` as a chip+ * on all 21 rows of a subscription provider's roster, and the chips — adjacent rows,+ * same fill, no gap between them — fused into one solid green RECTANGLE down the price+ * column with the labels floating in it. That is the failure `viz/widgets.tsx` records+ * for 24 `UP` chips in a service list, arriving vertically instead of horizontally. A+ * chip is for a status that DISTINGUISHES a row; when every row carries it, the chip is+ * a wall. The rail's per-provider `SUB` tag already says it once, where it is true of+ * the provider rather than of each model.+ */+function isFlatRateLabel(priceText: string): boolean {+ return priceText === "SUB" || priceText === "LOCAL" || priceText === "FREE";+}++/** Flat rate is `success` (it costs nothing more), absent is `dead`, a rate is body ink. */+function priceFg(priceText: string, flat: boolean): string {+ if (flat) return tokens.success;+ return priceText === "N/A" ? tokens.dead : tokens.text;+}++export interface ModelRowProps {+ model: ModelInfo;+ layout: RowLayout;+ cursor: boolean;+ /** 0–100, or `NaN` for an absent window. From `contextMeterPct`. */+ ctxPct: number;+ /** 0–100, `NaN` when there is no per-token rate to compare. */+ pricePct: number;+ /** Whatever `resolveProviderDisplayPrice` said — `SUB`, `$1.25/1M`, `N/A`. */+ priceText: string;+ /** `catalog` adds the `CAT` chip that says this row is not the live roster. */+ origin: ListOrigin;+}++export function ModelRow({+ model,+ layout,+ cursor,+ ctxPct,+ pricePct,+ priceText,+ origin,+}: ModelRowProps): ReactNode {+ // Render-time reads — see the file header.+ const idFg = cursor ? C.strong : tokens.text;+ const flat = isFlatRateLabel(priceText);++ // THE WASH LIVES ON THE BOX, not on the `<text>`: a text node is only as wide as+ // its content, so a row highlighted that way stops at its last glyph and reads as+ // a floating chip rather than as a bar. The box fills the panel's width — which is+ // why the panel is `flush`, so there is no padding gutter to break the band — and+ // `height={1}` keeps a row from overprinting its neighbour. Same construction as+ // `resume-picker.tsx:999`.+ return (+ <box height={1} flexShrink={0} backgroundColor={cursor ? C.bgHighlight : undefined}>+ <text attributes={A.boldIf(cursor)}>+ <span fg={cursor ? tokens.accent : tokens.trace}>{cursor ? "▶ " : " "}</span>+ <span fg={idFg}>{padTo(model.id, layout.id)}</span>+ <span> </span>+ <MeterSpan pct={ctxPct} width={layout.ctx} ramp={ramps.volume} />+ <span> </span>+ <span fg={tokens.subtle}>{padStartTo(model.context || "N/A", layout.ctxNum)}</span>+ {layout.price > 0 ? <span> </span> : null}+ {layout.price > 0 && flat ? <span fg={tokens.dead}>{"╌".repeat(layout.price)}</span> : null}+ {layout.price > 0 && !flat ? (+ <MeterSpan pct={pricePct} width={layout.price} ramp={ramps.savings} />+ ) : null}+ <span> </span>+ <span fg={priceFg(priceText, flat)}>{padStartTo(priceText, layout.priceNum)}</span>+ {layout.caps > 0 ? <span> </span> : null}+ {layout.caps > 0 ? capsCell(model, layout.caps) : null}+ {layout.date > 0 ? <span> </span> : null}+ {layout.date > 0 ? (+ <span fg={tokens.trace}>+ {padStartTo(model.releaseDate ? model.releaseDate.slice(0, 7) : "—", layout.date)}+ </span>+ ) : null}+ {layout.mark > 0 ? <span> </span> : null}+ {layout.mark > 0 ? (+ <span fg={tokens.warn} attributes={A.boldIf(origin === "catalog")}>+ {padStartTo(origin === "catalog" ? "cat" : "", layout.mark - 1)}+ </span>+ ) : null}+ </text>+ </box>+ );+}++/**+ * THE `cat` MARK SAYS "THIS ROW IS NOT THE LIVE ROSTER", in the warn colour, on every+ * row of a fallback list — and it is TEXT rather than a chip for the third time in this+ * file, for the reason the other two record.+ *+ * MEASURED: as a `BadgeSpan` it was right on the four-row Kimi fallback and wrong on the+ * seventeen-row OpenRouter one, where seventeen identical orange chips in adjacent rows+ * fused into a solid slab down the panel — louder than the list it was annotating, and+ * no longer reading as seventeen labels. A chip marks a row that DIFFERS from its+ * neighbours; a whole-list property gets a coloured word. The loud encodings of this+ * same fact are the panel title and the banner, which appear once each.+ *+ * The column is reserved on BOTH kinds of list (it renders blank on a live one), so the+ * cells left of it do not move between them.+ *+ * Defect 4 of the measured failure is that a cloud-catalog fallback list renders+ * identically to a healthy roster — prices, descriptions, the lot — so the eye goes+ * to the list, the list looks fine, and it is simply short. That is the user's+ * complaint verbatim. Three encodings fix it and all three derive from ONE value (the+ * outcome variant that produced the list): the panel title, the banner's provenance+ * sentence, and this chip.+ *+ * Outside the budget because the budget is EXACT: a provenance cell that consumed+ * columns would re-size every other cell between a live list and a fallback list, so+ * the two would not be visually comparable. Overflow clips at the panel edge, which+ * is the failure mode every widget in `viz/` prefers — visible, and attributable to+ * the row.+ */++/**+ * `[TRV]` — one letter per capability, bright when present, `tokens.dead` when not.+ * Five columns for all three flags, identical at every width.+ *+ * DELIBERATELY NOT `BadgeSpan` CHIPS, AND THAT IS MEASURED. The first wide capture+ * rendered the capability column as three chips per row, and because every model in a+ * roster carries the same capability, the `T` chips down 21 adjacent rows fused into+ * one solid green RECTANGLE — `viz/widgets.tsx`'s measured 24-`UP`-chips failure,+ * arriving vertically. The general rule this settles: a chip marks a row that DIFFERS+ * from its neighbours; a per-row ATTRIBUTE column, where every row has a value, uses+ * coloured glyphs. The one chip left in a model row is `CAT`, which marks a whole list+ * whose provenance the reader must not miss.+ *+ * It still survives greyscale and colour-blindness, because the letters are the label:+ * `[T··]` and `[TRV]` differ in glyphs, not only in hue.+ */+function capsCell(model: ModelInfo, width: number): ReactNode {+ const flags: Array<{ label: string; on: boolean; color: string }> = [+ { label: "T", on: model.supportsTools === true, color: tokens.success },+ { label: "R", on: model.supportsReasoning === true, color: tokens.running },+ { label: "V", on: model.supportsVision === true, color: C.magenta },+ ];+ return (+ <>+ <span fg={tokens.trace}>{"["}</span>+ {flags.map((f) => (+ <span key={f.label} fg={f.on ? f.color : tokens.dead}>+ {f.label}+ </span>+ ))}+ <span fg={tokens.trace}>{"]"}</span>+ {width > 5 ? <span>{" ".repeat(width - 5)}</span> : null}+ </>+ );+}++export interface RailRowProps {+ label: string;+ readiness: Readiness;+ billing: BillingMode;+ /** Served-model count once a list for this provider has landed; `null` until then. */+ count: number | null;+ cursor: boolean;+ focused: boolean;+ layout: RailLayout;+}++/**+ * One provider. The glyph is readiness, the tag is billing, the count is how many+ * models this session has actually seen for it — `null`, drawn `—`, until a list+ * lands, because a count invented before the list is a number with no source.+ *+ * The cursor wash is `bgHighlight` while the rail has focus and the quieter `bgAlt`+ * while the model pane does, so the screen always shows exactly one active cursor.+ */+export function ProviderRailRow({+ label,+ readiness,+ billing,+ count,+ cursor,+ focused,+ layout,+}: RailRowProps): ReactNode {+ const { glyph, fg } = readinessGlyph(readiness);+ const tag = billingTag(billing);+ return (+ <box+ height={1}+ flexShrink={0}+ backgroundColor={cursor ? (focused ? C.bgHighlight : C.bgAlt) : undefined}+ >+ <text attributes={A.boldIf(cursor)}>+ <span fg={fg}>{glyph}</span>+ <span> </span>+ <span fg={cursor ? tokens.accent : tokens.text}>{padTo(label, layout.label)}</span>+ {layout.tag > 0 ? <span> </span> : null}+ {layout.tag > 0 ? <span fg={tag.fg}>{padStartTo(tag.text, layout.tag)}</span> : null}+ {layout.count > 0 ? <span> </span> : null}+ {layout.count > 0 ? (+ <span fg={tokens.subtle}>+ {padStartTo(count === null ? "—" : String(count), layout.count)}+ </span>+ ) : null}+ </text>+ </box>+ );+}++/**+ * A dim, NON-SELECTABLE row for something the rail is deliberately not listing —+ * the providers with no credential, collapsed, and the local providers that are in+ * the catalog but not enabled in config.+ *+ * An unexplained absence is the defect class this whole feature is about, so the+ * rail says the number out loud. It stays unselectable because a row that cannot be+ * picked must not look like one that can: offering it would trade a silent absence+ * for a dead end.+ */+export function RailHintRow({ text, width }: { text: string; width: number }): ReactNode {+ return (+ <box height={1} flexShrink={0}>+ <text>+ <span fg={tokens.trace}>{truncate(text, width)}</span>+ </text>+ </box>+ );+}diff --git a/packages/cli/src/providers/model-catalog.ts b/packages/cli/src/providers/model-catalog.tsindex 157d8f98..82401246 100644--- a/packages/cli/src/providers/model-catalog.ts+++ b/packages/cli/src/providers/model-catalog.ts@@ -235,6 +235,20 @@ function slimEntryToCatalogModel(entry: SlimModelEntry): CatalogModel {contextWindow: entry.contextWindow,supportsVision: entry.supportsVision,releaseDate: entry.releaseDate,+ // THE TWO CAPABILITY FLAGS THE SLIM CACHE ACTUALLY CARRIES, forwarded in the+ // shape every renderer reads. They were dropped here: `supportsVision` above+ // goes into a field only the probe path reads, and `reasoning` was not mapped+ // at all — so every aggregator-served list (OpenRouter's 349 models, and it is+ // the default provider) rendered its capability column entirely dead while the+ // data sat in the cache. Visible the moment a row carries a capability column.+ //+ // `tools` is NOT here because the slim payload does not carry it: that is a+ // models-index gap, not a CLI one, and inventing `true` would be worse than a+ // dim glyph. Recorded rather than guessed.+ capabilities: {+ ...(entry.supportsVision === undefined ? {} : { vision: entry.supportsVision }),+ ...(entry.reasoning === undefined ? {} : { thinking: true }),+ },};}diff --git a/packages/cli/src/tui/App.tsx b/packages/cli/src/tui/App.tsxindex db2004f2..a8734650 100644--- a/packages/cli/src/tui/App.tsx+++ b/packages/cli/src/tui/App.tsx@@ -19,6 +19,7 @@ import {recordKeychainHydratedVar,} from "../auth/credentials/keychain-source.js";import { invalidateOpResolutionCache } from "../auth/credentials/op-source.js";+import { log } from "../logger.js";import {disableLocalProvider,enableLocalProvider,@@ -1110,13 +1111,20 @@ export function App({ requestLogin }: AppProps = {}) {// The entry IS saved; the live resolve just couldn't run. Surface a// warning (and log the detail to stderr) without rolling back.const msg = testErr instanceof Error ? testErr.message : String(testErr);- console.error(`[claudish] 1Password add: saved but live resolve failed: ${msg}`);+ // `log()`, NOT `console.error`: this runs while the config TUI's renderer owns+ // the screen, and anything written there leaves cells OpenTUI cannot+ // invalidate — ghost characters that survive every redraw, with no exception+ // and nothing on stderr to explain them. The user already gets the message in+ // the status strip below; the detail belongs in the debug log.+ // (Found by `picker/no-terminal-writes.test.ts`, which exists for this class.)+ log(`[claudish] 1Password add: saved but live resolve failed: ${msg}`);setStatusMsg(`1Password ${kindWord} saved (${scope}) — live resolve failed: ${msg}`);}} catch (err: unknown) {// A genuine PERSIST failure (config write) — the rare real error.const msg = err instanceof Error ? err.message : String(err);- console.error(`[claudish] 1Password add failed to persist: ${msg}`);+ // Same reason as above: the renderer owns the terminal until it is destroyed.+ log(`[claudish] 1Password add failed to persist: ${msg}`);setStatusMsg(`1Password add failed: ${msg}`);setMode("browse");resetOpWizard();