Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
fix(picker): never open the model picker without a terminal
Jack Rudenkoc0951e75a95a
diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.tsindex a970f10c..44c0d481 100644--- a/packages/cli/src/index.ts+++ b/packages/cli/src/index.ts@@ -14,9 +14,14 @@ import {suppressStartupTraceTerminalOutput,traceSpan,} from "./startup-trace.js";-// A leaf that imports NOTHING — see its header. Static here on purpose: it must-// not drag anything into this file's cold-start graph.+// 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 {+ type ModelPickerGate,+ requiresExplicitModel,+ shouldOpenPicker,+} from "./tui/runtime/should-open-picker.js";// ── Startup-timing analytics (startup-trace.ts) ─────────────────────────────// Every launch appends one JSON line to ~/.claudish/startup-metrics.jsonl; a@@ -783,22 +788,35 @@ async function runCli() {// Show interactive model selector ONLY when no model configuration exists// Skip if: explicit --model, OR profile provides tier mappings (Claude Code uses these internally)- const hasProfileTiers =+ const hasProfileTiers = Boolean(cliConfig.modelOpus ||- cliConfig.modelSonnet ||- cliConfig.modelHaiku ||- cliConfig.modelSubagent;+ cliConfig.modelSonnet ||+ cliConfig.modelHaiku ||+ cliConfig.modelSubagent+ );// `--advisor` with no main model is a native session: Claude Code picks its own- // model, so there is nothing to select and nothing to demand. Both gates below- // were satisfied by --advisor implying --monitor; the predicate replaces that.+ // model, so there is nothing to select and nothing to demand. It rides INSIDE the+ // gate below, beside `monitor`, rather than as a separate `&&` at each call site:+ // a term carried by only one of the two gates is how they drift apart.const advisorNativeSession = isAdvisorNativeSession(cliConfig);- if (- cliConfig.interactive &&- !cliConfig.monitor &&- !advisorNativeSession &&- !cliConfig.model &&- !hasProfileTiers- ) {+ // ONE predicate behind BOTH gates below (tui/runtime/should-open-picker.ts), and the+ // second is the exact complement of the first, so no input can skip the picker+ // silently AND keep the error quiet. The `interactive` flag alone is not enough:+ // cli.ts turns it on whenever no prompt was given, which includes `claudish <+ // /dev/null`, a CI runner and a detached run — none of which can answer a prompt.+ // Hence the TTY term, from the same oracle the resume picker uses below.+ const pickerCanDraw = canDrawTui();+ // Rebuilt per call rather than hoisted: the picker ASSIGNS cliConfig.model between+ // the two gates, and the second one must see the model the first one obtained.+ const pickerGate = (): ModelPickerGate => ({+ interactive: cliConfig.interactive,+ monitor: cliConfig.monitor,+ advisorNativeSession,+ model: cliConfig.model,+ hasProfileTiers,+ });++ if (shouldOpenPicker(pickerGate(), pickerCanDraw)) {// Human wait (the interactive picker) + per-provider credential probes.cliConfig.model = (await traceSpan("startup:model-select",@@ -808,14 +826,14 @@ async function runCli() {console.log(""); // Empty line after selection}- // In non-interactive mode, model must be specified (via --model, env var, or profile)- if (- !cliConfig.interactive &&- !cliConfig.monitor &&- !advisorNativeSession &&- !cliConfig.model &&- !hasProfileTiers- ) {+ // No picker could run — non-interactive, or no terminal to draw one on — so the+ // model has to come from the command line (--model, env var, or profile). NOT a+ // fallback to the line-oriented prompt: in a non-TTY that prompt is the bug, not+ // the safety net, so "falling back" would be falling back to a hang. These three+ // lines — naming four ways to supply a model — are what a piped bare `claudish`+ // prints now, where it used to paint a provider list into stdout and then block+ // forever (measured: 195 bytes of menu, cursor-hide escape, killed at 45s).+ if (requiresExplicitModel(pickerGate(), pickerCanDraw)) {console.error("Error: Model must be specified in non-interactive mode");console.error("Use --model <model> flag, set CLAUDISH_MODEL env var, or use --profile");console.error("Try: claudish --models");diff --git a/packages/cli/src/tui/runtime/should-open-picker.test.ts b/packages/cli/src/tui/runtime/should-open-picker.test.tsnew file mode 100644index 00000000..d337a054--- /dev/null+++ b/packages/cli/src/tui/runtime/should-open-picker.test.ts@@ -0,0 +1,234 @@+/**+ * Tests for the model picker's launch gate — `shouldOpenPicker` and its exact+ * complement `requiresExplicitModel`.+ *+ * The subject is pure and total over five booleans, so the whole 2^5 = 32-cell+ * grid is enumerated against a HAND-WRITTEN table below rather than against a+ * re-statement of the implementation's own expression. The one cell the feature+ * exists for is `{interactive: true, tty: false}` — a piped or detached+ * `claudish` with no `--model`, which used to open a prompt into a stream nobody+ * reads and block on a keypress that could never arrive. It must not open the+ * picker, and it must not go quiet either: the complement has to fire so the run+ * gets the four actionable lines and exit 1.+ *+ * Written from the requirement (architecture §7, D6), not from the code.+ */++import { describe, expect, test } from "bun:test";+import {+ type ModelPickerGate,+ requiresExplicitModel,+ shouldOpenPicker,+} from "./should-open-picker.js";++/**+ * A grid row. The mask is five space-separated fields in a fixed order —+ * `interactive monitor model tiers tty` — each either the flag's letter (true) or+ * `-` (false). A typo in a mask throws rather than silently reading as false.+ */+type Row = [mask: string, open: boolean, needsExplicit: boolean];++const FIELDS = ["i", "m", "d", "p", "t"] as const;++function parse(mask: string): { gate: ModelPickerGate; tty: boolean } {+ const tokens = mask.split(" ");+ if (tokens.length !== FIELDS.length) throw new Error(`bad mask: ${mask}`);+ const bits = tokens.map((token, index) => {+ if (token === "-") return false;+ if (token === FIELDS[index]) return true;+ throw new Error(`bad mask field ${index} in "${mask}": ${token}`);+ });+ return {+ gate: {+ interactive: bits[0],+ monitor: bits[1],+ // A real spec string, because an empty string is falsy and would silently+ // test the "no model" cell instead of the "model given" one.+ model: bits[2] ? "or@deepseek/deepseek-r1" : undefined,+ hasProfileTiers: bits[3],+ },+ tty: bits[4],+ };+}++// i = interactive · m = --monitor · d = --model given · p = profile tiers · t = TTY+// Enumerated in binary order with `t` least significant, so every cell is present+// exactly once and the four interesting ones are annotated.+const GRID: Row[] = [+ ["- - - - -", false, true], // non-interactive, no screen, nothing configured → error+ ["- - - - t", false, true], // a terminal, but no human waiting (prompt came another way)+ ["- - - p -", false, false],+ ["- - - p t", false, false],+ ["- - d - -", false, false],+ ["- - d - t", false, false],+ ["- - d p -", false, false],+ ["- - d p t", false, false],+ ["- m - - -", false, false],+ ["- m - - t", false, false],+ ["- m - p -", false, false],+ ["- m - p t", false, false],+ ["- m d - -", false, false],+ ["- m d - t", false, false],+ ["- m d p -", false, false],+ ["- m d p t", false, false],+ ["i - - - -", false, true], // THE DEFECT CELL: piped/detached bare `claudish`+ ["i - - - t", true, false], // the only cell that opens the picker+ ["i - - p -", false, false],+ ["i - - p t", false, false],+ ["i - d - -", false, false],+ ["i - d - t", false, false],+ ["i - d p -", false, false],+ ["i - d p t", false, false],+ ["i m - - -", false, false],+ ["i m - - t", false, false],+ ["i m - p -", false, false],+ ["i m - p t", false, false],+ ["i m d - -", false, false],+ ["i m d - t", false, false],+ ["i m d p -", false, false],+ ["i m d p t", false, false],+];++describe("shouldOpenPicker / requiresExplicitModel — the 2^5 grid", () => {+ test("the grid is complete: 32 distinct cells", () => {+ expect(GRID).toHaveLength(32);+ expect(new Set(GRID.map(([mask]) => mask)).size).toBe(32);+ });++ for (const [mask, open, needsExplicit] of GRID) {+ test(`[${mask}] → open=${open} explicit=${needsExplicit}`, () => {+ const { gate, tty } = parse(mask);+ expect(shouldOpenPicker(gate, tty)).toBe(open);+ expect(requiresExplicitModel(gate, tty)).toBe(needsExplicit);+ });+ }++ test("no cell both skips the picker and stays silent about it", () => {+ for (const [mask] of GRID) {+ const { gate, tty } = parse(mask);+ // Independently derived from the mask, not from the module: a run needs a+ // model unless --monitor, --model or profile tiers already answered for it.+ const needsAModel = mask[2] === "-" && mask[4] === "-" && mask[6] === "-";+ const open = shouldOpenPicker(gate, tty);+ const explicit = requiresExplicitModel(gate, tty);+ if (needsAModel) {+ expect(open !== explicit).toBe(true); // exactly one, never both, never neither+ } else {+ expect(open).toBe(false);+ expect(explicit).toBe(false);+ }+ }+ });++ test("no TTY never opens the picker, whatever else is set", () => {+ let checked = 0;+ for (const [mask] of GRID) {+ const { gate } = parse(mask);+ expect(shouldOpenPicker(gate, false)).toBe(false);+ checked++;+ }+ expect(checked).toBe(32);+ });+});++/**+ * `advisorNativeSession` is the sixth input, and it is deliberately NOT a sixth+ * mask field: doubling the grid to 64 hand-written rows would bury the five that+ * describe real command lines. Instead it is pinned against `monitor`, whose 32+ * cells are already enumerated above — the claim the module's own comment makes.+ */+describe("advisorNativeSession — a reason no model is needed, exactly like --monitor", () => {+ test("over all 32 cells it is indistinguishable from --monitor", () => {+ let checked = 0;+ for (const [mask] of GRID) {+ const { gate, tty } = parse(mask);+ const viaMonitor = { ...gate, monitor: true, advisorNativeSession: false };+ const viaAdvisor = { ...gate, monitor: false, advisorNativeSession: true };+ expect(shouldOpenPicker(viaAdvisor, tty)).toBe(shouldOpenPicker(viaMonitor, tty));+ expect(requiresExplicitModel(viaAdvisor, tty)).toBe(+ requiresExplicitModel(viaMonitor, tty)+ );+ checked++;+ }+ expect(checked).toBe(32);+ });++ test("`--advisor` on a terminal asks nothing and errors about nothing", () => {+ // The regression this guards: Claude Code picks its own model for a native+ // advisor session, so demanding --model would make a working command fail.+ const gate: ModelPickerGate = { interactive: true, advisorNativeSession: true };+ expect(shouldOpenPicker(gate, true)).toBe(false);+ expect(requiresExplicitModel(gate, true)).toBe(false);+ });++ test("the complement law still holds with the advisor term set", () => {+ for (const [mask] of GRID) {+ const { gate, tty } = parse(mask);+ const advisor = { ...gate, advisorNativeSession: true };+ // No model is ever needed once the advisor term is on, so BOTH gates must+ // be false — never "skip the picker silently and demand a model anyway".+ expect(shouldOpenPicker(advisor, tty)).toBe(false);+ expect(requiresExplicitModel(advisor, tty)).toBe(false);+ }+ });+});++describe("shouldOpenPicker — the invocations these cells stand for", () => {+ /** What `cli.ts` produces for each real command line, plus `canDrawTui()`. */+ const tty = true;+ const piped = false;++ test("bare `claudish` at a terminal opens the picker", () => {+ const gate: ModelPickerGate = { interactive: true, monitor: false };+ expect(shouldOpenPicker(gate, tty)).toBe(true);+ expect(requiresExplicitModel(gate, tty)).toBe(false);+ });++ test("`claudish < /dev/null` fails fast instead of prompting", () => {+ // cli.ts sets interactive=true here: no positional prompt, no --stdin, no -p.+ const gate: ModelPickerGate = { interactive: true, monitor: false };+ expect(shouldOpenPicker(gate, piped)).toBe(false);+ expect(requiresExplicitModel(gate, piped)).toBe(true);+ });++ test("`claudish -p` keeps its existing behaviour: no picker, explicit model required", () => {+ // _hasPrintFlag stops cli.ts's interactive default, so the picker was already+ // excluded here before this gate existed — and headless-vs-interactive.md is+ // why that must stay: `-p --input-format stream-json` turns a wrong flag into+ // silence and exit 0.+ const gate: ModelPickerGate = { interactive: false, monitor: false };+ expect(shouldOpenPicker(gate, tty)).toBe(false);+ expect(requiresExplicitModel(gate, tty)).toBe(true);+ });++ test("a positional prompt keeps its existing behaviour too", () => {+ const gate: ModelPickerGate = { interactive: false, monitor: false };+ expect(shouldOpenPicker(gate, tty)).toBe(false);+ expect(requiresExplicitModel(gate, tty)).toBe(true);+ });++ test("`--model` piped asks nothing and errors about nothing", () => {+ const gate: ModelPickerGate = { interactive: true, model: "gk@grok-4-latest" };+ expect(shouldOpenPicker(gate, piped)).toBe(false);+ expect(requiresExplicitModel(gate, piped)).toBe(false);+ });++ test("`--monitor` piped asks nothing and errors about nothing", () => {+ const gate: ModelPickerGate = { interactive: true, monitor: true };+ expect(shouldOpenPicker(gate, piped)).toBe(false);+ expect(requiresExplicitModel(gate, piped)).toBe(false);+ });++ test("profile tiers piped ask nothing and error about nothing", () => {+ // Claude Code resolves opus/sonnet/haiku/subagent internally, so claudish+ // needs no single model — the case that must not be turned into exit 1.+ const gate: ModelPickerGate = { interactive: true, hasProfileTiers: true };+ expect(shouldOpenPicker(gate, piped)).toBe(false);+ expect(requiresExplicitModel(gate, piped)).toBe(false);+ });++ test("an absent field reads as false, so a partial gate cannot open the picker", () => {+ expect(shouldOpenPicker({}, tty)).toBe(false);+ expect(requiresExplicitModel({}, tty)).toBe(true);+ });+});diff --git a/packages/cli/src/tui/runtime/should-open-picker.ts b/packages/cli/src/tui/runtime/should-open-picker.tsnew file mode 100644index 00000000..b4e9a775--- /dev/null+++ b/packages/cli/src/tui/runtime/should-open-picker.ts@@ -0,0 +1,120 @@+/**+ * should-open-picker.ts — the model picker's launch gate, as one pure predicate.+ *+ * THE DEFECT THIS CLOSES. Until now nothing asked whether a terminal was there.+ * `index.ts` opened the picker on `cliConfig.interactive` alone, and `cli.ts`+ * sets that flag true whenever there is no positional prompt, no `--stdin` and+ * no `-p`:+ *+ * if (!config._hasPositionalPrompt && !config.stdin && !config._hasPrintFlag)+ * config.interactive = true;+ *+ * So `claudish < /dev/null`, `claudish` on a CI runner, and `claudish` detached+ * all reached a prompt that drew into a stream nobody reads and then blocked on a+ * keypress that could never arrive. `-p` was already excluded — `_hasPrintFlag`+ * exists precisely to stop that default flipping on — and+ * `ai-docs/architecture/headless-vs-interactive.md` is why that matters: `-p+ * --input-format stream-json` is the mode where a wrong flag yields silence and+ * exit 0, so the picker must never appear in it. This predicate makes the piped+ * and detached cases fail the same way, by asking the one question that was+ * missing.+ *+ * WHY NOT A FALLBACK TO THE LINE-ORIENTED PROMPT. Inquirer in a non-TTY is the+ * bug, not the safety net: it draws into an unread stream and waits for a key+ * that cannot come. "Falling back" would be falling back to a hang. So+ * `requiresExplicitModel` routes the same cases to the existing non-interactive+ * error — four actionable lines naming `--model`, `CLAUDISH_MODEL`, `--profile`+ * and `claudish --models` — and exit 1.+ *+ * THE TTY ANSWER IS A PARAMETER, NOT AN IMPORT. Both functions here are total+ * over their inputs and read nothing from the process, which is what makes the+ * whole 2^5 grid table-testable without running `runCli`. `index.ts` supplies the+ * answer from `canDrawTui()`, the single isTTY oracle next door. For the same+ * reason as that file: THIS MODULE IMPORTS NOTHING, and keeps `index.ts`'s cold+ * static graph clean.+ */++/**+ * Everything the gate is allowed to look at, derived at the call site from+ * `ClaudishConfig`.+ *+ * `hasProfileTiers` is an input rather than four fields so the predicate's domain+ * stays small enough to enumerate: five booleans, which is the 32-cell grid its+ * test walks, plus `advisorNativeSession`, which the test pins as behaving exactly+ * like `monitor` rather than doubling the grid to 64 rows.+ */+export interface ModelPickerGate {+ /**+ * `cli.ts`'s interactive default: no positional prompt, no `--stdin`, no `-p`.+ * False means some other channel already carries the prompt, so there is no+ * point in the launch sequence at which a human is waiting to choose.+ */+ interactive?: boolean;+ /** `--monitor` proxies to the real Anthropic API and runs no model of ours. */+ monitor?: boolean;+ /**+ * `--advisor` with no main model: Claude Code runs natively and picks its own+ * model, so there is nothing to select and nothing to demand. A term of the+ * gate rather than a condition beside it — see `noModelConfigured`.+ */+ advisorNativeSession?: boolean;+ /** `--model` / `CLAUDISH_MODEL` / a profile's single spec — already chosen. */+ model?: string;+ /**+ * True when `--model-opus/-sonnet/-haiku/-subagent` (or a profile supplying+ * them) is present: Claude Code picks per tier internally, so claudish needs no+ * single model and must not ask for one.+ */+ hasProfileTiers?: boolean;+}++/**+ * True when no model configuration of any kind exists for this run, so SOMETHING+ * has to supply one before the proxy can start.+ *+ * Not exported: it is the shared left-hand side of the two gates below, and both+ * of them are what call sites should ask. Exporting a third name would invite a+ * third gate that drifts from these two.+ *+ * `advisorNativeSession` belongs HERE, beside `monitor`, and not AND-ed onto one+ * call site: it is a reason no model is needed, so it must suppress the picker+ * and the error together. A term carried by only one of the two gates is exactly+ * the drift this file exists to prevent — it would let a run skip the picker+ * silently and still be told to name a model, or the reverse.+ */+function noModelConfigured(gate: ModelPickerGate): boolean {+ return (+ !gate.monitor && !gate.advisorNativeSession && !gate.model && !gate.hasProfileTiers+ );+}++/**+ * May the interactive model picker be opened for this run?+ *+ * @param gate - The run's model configuration and interactivity.+ * @param tty - `canDrawTui()` — both of our own streams are terminals.+ * @returns True only when a model is missing, a human is waiting, and there is a+ * screen to paint on. `{interactive: true, tty: false}` is the case this whole+ * file exists for, and it is false.+ */+export function shouldOpenPicker(gate: ModelPickerGate, tty: boolean): boolean {+ return noModelConfigured(gate) && Boolean(gate.interactive) && tty;+}++/**+ * Must this run be told to name a model on the command line instead?+ *+ * The exact complement of `shouldOpenPicker` over the runs that need a model:+ * when `noModelConfigured(gate)` holds, exactly one of the two is true, and when+ * it does not, both are false. That law is what makes the second call site safe+ * to widen — there is no input for which the picker is skipped silently AND the+ * error stays quiet.+ *+ * @param gate - The run's model configuration and interactivity.+ * @param tty - `canDrawTui()` — both of our own streams are terminals.+ * @returns True when a model is still needed and no picker can supply it, either+ * because the run is non-interactive or because there is no terminal.+ */+export function requiresExplicitModel(gate: ModelPickerGate, tty: boolean): boolean {+ return noModelConfigured(gate) && !shouldOpenPicker(gate, tty);+}