Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
feat(tui): shared components and leaves for the OpenTUI model picker
Jack Rudenko4100454fbc62
diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.tsindex d0bc8eff..a970f10c 100644--- a/packages/cli/src/index.ts+++ b/packages/cli/src/index.ts@@ -14,6 +14,9 @@ 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.+import { canDrawTui } from "./tui/runtime/can-draw-tui.js";// ── Startup-timing analytics (startup-trace.ts) ─────────────────────────────// Every launch appends one JSON line to ~/.claudish/startup-metrics.jsonl; a@@ -1039,8 +1042,7 @@ async function runCli() {// report "no sessions" and `exit(0)` — turning a previously working flag into// a silent no-op in every non-git directory. Sessions may well exist there;// claudish just has no worktree structure to group them by.- const canDrawTui = Boolean(process.stdin.isTTY && process.stdout.isTTY);- if (!canDrawTui || cliConfig._hasPrintFlag || !cliConfig.interactive) {+ if (!canDrawTui() || cliConfig._hasPrintFlag || !cliConfig.interactive) {cliConfig.claudeArgs.push("--resume");} else {const { runResumePicker } = await import("./session/resume-picker-run.js");diff --git a/packages/cli/src/probe/probe-tui-app.tsx b/packages/cli/src/probe/probe-tui-app.tsxindex 41e2fdba..de1928eb 100644--- a/packages/cli/src/probe/probe-tui-app.tsx+++ b/packages/cli/src/probe/probe-tui-app.tsx@@ -20,6 +20,7 @@ import {describeProbeState,} from "../providers/probe-live.js";import { getThemeMode } from "../theme/theme-mode.js";+import { useAnimationFrame } from "../tui/hooks/useAnimationFrame.js";import {A,C,@@ -163,16 +164,17 @@ export function useProbeStore(store: ProbeStore): ProbeAppState {return store.getState();}-/** Bumps a counter every 100ms while active — used for progress bar animation and elapsed timers. */-export function useAnimationFrame(active: boolean): number {- const [frame, setFrame] = useState(0);- useEffect(() => {- if (!active) return;- const id = setInterval(() => setFrame((f) => (f + 1) % 1_000_000), 100);- return () => clearInterval(id);- }, [active]);- return frame;-}+/**+ * MOVED to `tui/hooks/useAnimationFrame.ts`, and re-exported here for one+ * release so no `probe/` importer has to change. It is the only exported tick+ * source in the repo and a second OpenTUI app needed it without dragging this+ * whole component module along; `probe/ → tui/` is an edge that already exists+ * (see the `../tui/theme.js` import above), the reverse is not.+ *+ * Removal trigger: delete this line when the picker has shipped and no importer+ * outside `probe/` reads it from here.+ */+export { useAnimationFrame };// ── Helpers ────────────────────────────────────────────────────────diff --git a/packages/cli/src/tui/App.tsx b/packages/cli/src/tui/App.tsxindex cb801890..db2004f2 100644--- a/packages/cli/src/tui/App.tsx+++ b/packages/cli/src/tui/App.tsx@@ -104,13 +104,7 @@ import { VERSION as PKG_VERSION } from "../version.js";import { Footer } from "./components/Footer.js";import { OnepasswordContent, type OpExpansion } from "./components/OnepasswordContent.js";import { OnepasswordDetail } from "./components/OnepasswordDetail.js";-import {- OnepasswordModal,- buildFieldOptions,- fuzzyFilterByTitle,- fuzzyMatch,- isOpModalMode,-} from "./components/OnepasswordModal.js";+import { OnepasswordModal } from "./components/OnepasswordModal.js";import { PrivacyContent } from "./components/PrivacyContent.js";import { PrivacyDetail } from "./components/PrivacyDetail.js";import { ProfileDetail } from "./components/ProfileDetail.js";@@ -123,6 +117,12 @@ import { TabBar } from "./components/TabBar.js";import { DETAIL_H, FOOTER_H, HEADER_H, TABS_H, getChainProviders } from "./constants.js";import { useProfileWizard } from "./hooks/useProfileWizard.js";import { useRouteProbe } from "./hooks/useRouteProbe.js";+import {+ buildFieldOptions,+ fuzzyFilterByTitle,+ fuzzyMatch,+ isOpModalMode,+} from "./onepassword-fields.js";import {ensureProbeProxy,invalidateProbeProxyHandlers,diff --git a/packages/cli/src/tui/components/EmptyState.tsx b/packages/cli/src/tui/components/EmptyState.tsxnew file mode 100644index 00000000..7e4bd28d--- /dev/null+++ b/packages/cli/src/tui/components/EmptyState.tsx@@ -0,0 +1,57 @@+/** @jsxImportSource @opentui/react */+/**+ * EmptyState — one dim row standing in for a list that has no rows.+ *+ * Promoted from the `emptyBody` helper inside `OnepasswordModal.tsx:652-657`,+ * which was the same three lines closed over a label. It is a component rather+ * than a helper because a second and third screen need it, and because an empty+ * panel is the one state where a UI most easily says nothing at all.+ *+ * SAY WHICH EMPTY IT IS. `nothing here` covers four different situations — still+ * loading, loaded and genuinely empty, filtered to nothing, failed — and a+ * picker that renders the same sentence for all four is exactly the complaint+ * this component's callers exist to fix. The label is the whole component;+ * spend it. `hint` is a second, dimmer row for the way out (`press / to clear+ * the filter`), and is omitted rather than padded when there is nothing to say.+ *+ * A FAILURE IS NOT AN EMPTY STATE. Route those to `ErrorBanner`, which carries a+ * severity tier and a colour; a dim grey line is the wrong prominence for+ * something the user has to act on.+ *+ * TWO SIBLING `<text>`s, not one wrapped string: sibling text nodes lay out+ * normally inside a column box (they overprint only when the box is too short+ * for them), and one `<text>` per row is the rule that keeps Yoga from clawing+ * columns back from the last child.+ */++import type { ReactNode } from "react";+import { tokens } from "../viz/tokens.js";++export function EmptyState({+ label,+ hint,+}: {+ /** Why the list is empty, in the user's terms. */+ label: string;+ /** Optional second row: what to do about it. */+ hint?: string;+}): ReactNode {+ // Read at RENDER time — `tokens` re-snapshots when the terminal theme is+ // detected, and a module-level capture would ship the dark palette only.+ // `tokens.idle` is `C.fgMuted`, byte-identical to the `emptyBody` this came+ // from, and it means "waiting", which is what an empty list mostly is.+ const labelFg = tokens.idle;+ const hintFg = tokens.subtle;+ return (+ <box flexDirection="column" flexShrink={0}>+ <text>+ <span fg={labelFg}>{label}</span>+ </text>+ {hint === undefined ? null : (+ <text>+ <span fg={hintFg}>{hint}</span>+ </text>+ )}+ </box>+ );+}diff --git a/packages/cli/src/tui/components/ErrorBanner.tsx b/packages/cli/src/tui/components/ErrorBanner.tsxnew file mode 100644index 00000000..696c702e--- /dev/null+++ b/packages/cli/src/tui/components/ErrorBanner.tsx@@ -0,0 +1,155 @@+/** @jsxImportSource @opentui/react */+/**+ * ErrorBanner — a pinned, severity-coloured block of already-formatted lines.+ *+ * It exists because of four measured defects in how this CLI reports a failed+ * model-discovery today (all four visible in one captured frame): the warning+ * renders in the same plain white as body text, so the most severe thing on+ * screen is the least prominent; it is inline flow text rather than a pinned+ * region, so one redraw loses it; the upstream JSON body wraps mid-word; and+ * nothing distinguishes it from ordinary chatter. This component fixes the first+ * three. The fourth is a property of the LIST, not of the banner.+ *+ * TWO TIERS, NEVER COLLAPSED TO ok/fail. Copied from `TestResult`+ * (`tui/types.ts:79-107`), whose own comment says `unavailable` is "deliberately+ * neutral, not red":+ *+ * · `error` — an actionable failure: a rejected key, a discovery that failed.+ * `tokens.error` on a `C.bgError` wash.+ * · `notice` — expected but notable: an empty roster, a list filtered to+ * nothing. `tokens.warn`, and NO error wash. A user whose+ * provider legitimately lists no models has not hit an error, and+ * painting one teaches them to ignore the red.+ *+ * The two tiers therefore differ in COLOUR as well as in words, which is what a+ * span-level test can assert and a character-frame test cannot see at all.+ *+ * THE CALLER OWNS THE WORDS; THIS OWNS THE CHROME. `lines` arrives formatted and+ * ordered, one row each. Nothing here wraps: pass `width` and each line is+ * `truncate`d to it, which puts an ellipsis in the last column instead of+ * spilling a JSON body across three rows mid-token. Anything too long to fit is+ * the caller's to drop, and the full text belongs in the log, never on screen.+ *+ * BORDERLESS IS THE DEFAULT, and that is a row budget, not a taste. A bordered+ * box spends two rows of chrome; on a 24-row terminal the banner's whole budget+ * is four rows, so a border would leave two rows for three lines that must not+ * be dropped. `bordered` (for a tall terminal) swaps in a full rounded border+ * and a title drawn inside it, costing no extra row for the title.+ *+ * NOT BUILT ON `viz/Panel`, deliberately. `Panel` owns one border colour for the+ * whole app — accent when focused, dim otherwise — and its layout type excludes+ * appearance by construction so a call site cannot restyle it. A severity band+ * needs a RED border, which is precisely the thing `Panel` refuses to express.+ * Same border STYLE, so the two still read as one program.+ */++import type { ReactNode } from "react";+import { A, C } from "../theme.js";+import { displayWidth, truncate } from "../viz/text.js";+import { tokens } from "../viz/tokens.js";+import { BadgeSpan } from "../viz/widgets.js";++export type BannerSeverity = "error" | "notice";++export interface ErrorBannerProps {+ /** `error` = actionable failure; `notice` = expected but notable. */+ severity: BannerSeverity;+ /** Formatted rows, most important first. Never wrapped, never re-ordered. */+ lines: readonly string[];+ /** Usable inner width in columns. Given, every line is truncated to it. */+ width?: number;+ /** Drawn in the border. Only rendered when `bordered`. */+ title?: string;+ /** A full rounded border instead of the 1-column left rule. Costs 2 rows. */+ bordered?: boolean;+ /** A chip at the head of the first row, e.g. `HTTP 401`. */+ badge?: string;+}++export function ErrorBanner({+ severity,+ lines,+ width,+ title,+ bordered = false,+ badge,+}: ErrorBannerProps): ReactNode {+ // NOTHING, not an empty box: an empty flex item still occupies a row, so a+ // banner with no lines would push the footer down by one and leave a black+ // gap where a reader expects content.+ if (lines.length === 0) return null;++ // Read at RENDER time. `C`/`tokens` are reassigned in place when the terminal+ // theme is detected, and a module-level `const` snapshots the dark palette+ // before detection runs — the bug class this repo has hit six times, once+ // visible only in a live screenshot.+ const accent = severity === "error" ? tokens.error : tokens.warn;+ const wash = severity === "error" ? C.bgError : undefined;+ const bodyFg = tokens.text;++ const inner =+ typeof width === "number" && Number.isFinite(width) ? Math.max(1, Math.floor(width)) : null;+ // A badge is drawn INSIDE the first row, so the room it takes has to come off+ // that row's budget or the chip pushes the headline over the edge. Its painted+ // width is `displayWidth(label) + 2` (one space of padding each side, outside+ // the label), plus the one space separating it from the text.+ const badgeCells = badge === undefined ? 0 : displayWidth(badge) + 3;+ const fit = (s: string, reserved: number): string =>+ inner === null ? s : truncate(s, Math.max(1, inner - reserved));++ const body = lines.map((line, i) => {+ const head = i === 0;+ return (+ // biome-ignore lint/suspicious/noArrayIndexKey: a banner row is position-addressed — its index IS its identity, and the priority order is the caller's contract+ <text key={i} flexShrink={0}>+ {head && badge !== undefined ? (+ <>+ <BadgeSpan label={badge} bg={accent} />+ <span> </span>+ </>+ ) : null}+ <span fg={head ? accent : bodyFg} attributes={A.boldIf(head)}>+ {fit(line, head ? badgeCells : 0)}+ </span>+ </text>+ );+ });++ if (bordered) {+ return (+ <box+ border+ borderStyle="rounded"+ borderColor={accent}+ backgroundColor={wash}+ title={title}+ titleAlignment="left"+ flexDirection="column"+ flexShrink={0}+ overflow="hidden"+ paddingLeft={1}+ paddingRight={1}+ >+ {body}+ </box>+ );+ }++ // The 1-column left rule: severity colour, zero chrome ROWS. `title` has no+ // border to live in here and is deliberately not rendered as a row of its own+ // — the headline already carries the display name.+ return (+ <box+ border={["left"]}+ borderStyle="single"+ borderColor={accent}+ backgroundColor={wash}+ flexDirection="column"+ flexShrink={0}+ overflow="hidden"+ paddingLeft={1}+ >+ {body}+ </box>+ );+}diff --git a/packages/cli/src/tui/components/LoadingRow.tsx b/packages/cli/src/tui/components/LoadingRow.tsxnew file mode 100644index 00000000..9b3568df--- /dev/null+++ b/packages/cli/src/tui/components/LoadingRow.tsx@@ -0,0 +1,105 @@+/** @jsxImportSource @opentui/react */+/**+ * LoadingRow — one row that says what is loading and how much is known about it.+ *+ * ONE `<text>`, always: bar · figure · label. Sibling `<text>`s in a row are the+ * arrangement Yoga shrinks from the last child inward, so every part of the row+ * is a `<span>` inside a single text node (`viz/widgets.tsx` documents the+ * measured failure; `resume-picker.tsx:473-484` is where this repo hit it).+ *+ * THE ROW'S SHAPE IS THE HONESTY CONTRACT, and it is chosen by what the caller+ * can actually measure:+ *+ * | Caller knows | Pass | Draws |+ * |---|---|---|+ * | work done / work total | `pct` 0–100 | a determinate `MeterSpan` |+ * | nothing but that it started | `pct` omitted | a travelling `ShimmerSpan` |+ * | the value is absent, not zero | `pct: NaN` | `MeterSpan`'s dim `╌` run |+ *+ * The third row is not a curiosity: `Meter` paints a full-width TRACK for `NaN`+ * unless it is guarded, which is pixel-identical to a healthy 0% — a dead sensor+ * that looks idle. `MeterSpan` already draws `╌` instead, and passing `NaN`+ * through rather than coercing it is what keeps that distinction alive here.+ *+ * A DEADLINE IS NOT PROGRESS. `pct = 100 * elapsed / deadline` renders fine and+ * says something true only if the LABEL says which it is (`… · 2.1s / 5.0s+ * deadline`). Where no deadline is published, omit `pct` and put the elapsed+ * figure in `value` — an elapsed counter with no bar makes exactly one claim.+ *+ * `value` is right-aligned in a reserved column so a counter ticking from `9/31`+ * to `10/31` cannot shove the label sideways every frame.+ */++import type { ColorInput } from "@opentui/core";+import type { ReactNode } from "react";+import { displayWidth, padStartTo } from "../viz/text.js";+import { type Ramp, ramps, tokens } from "../viz/tokens.js";+import { MeterSpan } from "../viz/widgets.js";+import { ShimmerSpan } from "./Shimmer.js";++export interface LoadingRowProps {+ /** What is in flight, e.g. `checking credentials`. Lower case, no ellipsis. */+ label: string;+ /** The counter from `useAnimationFrame` — ignored when `pct` is given. */+ frame: number;+ /** Bar width in cells. */+ width?: number;+ /** 0–100 for a determinate meter; omit for a shimmer; `NaN` for absent data. */+ pct?: number;+ /** The figure between bar and label, e.g. `17/31` or `2.1s`. */+ value?: string;+ /** Columns reserved for `value`, so a growing counter cannot shift the label. */+ valueWidth?: number;+ /** Meter gradient. Defaults to `ramps.volume` — see below. */+ ramp?: Ramp;+ /** Shimmer colour. Defaults to the in-flight tier. */+ fg?: ColorInput;+}++/**+ * `ramps.volume` IS THE DEFAULT, NOT `ramps.load`.+ *+ * A meter colours cells by POSITION along the fill, so the ramp encodes what a+ * FULL bar means. `load` ends red because a full CPU bar is bad; a full progress+ * bar is the best possible outcome, so `load` would paint a finished credential+ * sweep in alarm red and make red mean "error" on one row and "done" on the next.+ * `volume` is the repo's one-hue, no-valence ramp — length carries the+ * comparison, brightness carries the magnitude, and neither makes a health claim.+ * Pass `ramps.savings` if a full bar should read as an achievement rather than as+ * a quantity.+ */+export function LoadingRow({+ label,+ frame,+ width = 12,+ pct,+ value,+ valueWidth,+ ramp = ramps.volume,+ fg,+}: LoadingRowProps): ReactNode {+ // Read at RENDER time: `C`/`tokens` are reassigned in place when the terminal+ // theme is detected, and a module-level capture would pin the dark palette.+ const labelFg = tokens.subtle;+ const valueFg = tokens.text;+ const determinate = pct !== undefined;+ const column = value === undefined ? 0 : Math.max(valueWidth ?? 0, displayWidth(value));++ return (+ <text flexShrink={0}>+ {determinate ? (+ <MeterSpan pct={pct} width={width} ramp={ramp} />+ ) : (+ <ShimmerSpan frame={frame} width={width} {...(fg === undefined ? {} : { fg })} />+ )}+ {value === undefined ? null : (+ <>+ <span> </span>+ <span fg={valueFg}>{padStartTo(value, column)}</span>+ </>+ )}+ <span> </span>+ <span fg={labelFg}>{label}</span>+ </text>+ );+}diff --git a/packages/cli/src/tui/components/OnepasswordModal.test.ts b/packages/cli/src/tui/components/OnepasswordModal.test.tsindex 6f5e2e0f..e7b37cec 100644--- a/packages/cli/src/tui/components/OnepasswordModal.test.ts+++ b/packages/cli/src/tui/components/OnepasswordModal.test.ts@@ -1,18 +1,20 @@/**- * Tests for buildFieldOptions — the pure field-picker option builder in- * OnepasswordModal.tsx. These exercise the GROUPING + the two ★ rows across the+ * Tests for buildFieldOptions — the pure field-picker option builder behind the+ * 1Password add-wizard. These exercise the GROUPING + the two ★ rows across the* three item shapes (no-sections / all-sectioned / mixed). No secrets here: the* DiscoveredField inputs are field METADATA (labels/sections/types) — no secret* values — so structural fixtures are appropriate (the no-handcraft rule targets* secret-like fixtures, which these aren't).*- * buildFieldOptions is a plain function (no JSX), so importing it from the- * OpenTUI component module is safe — the @jsxImportSource pragma only affects JSX.+ * The subject MOVED from `components/OnepasswordModal.tsx` to the JSX-free leaf+ * `../onepassword-fields.ts`, so this file no longer has to justify importing a+ * plain function out of an OpenTUI component module — it imports a plain module.+ * The test bodies are unchanged, which is the point: the move is address-only.*/import { describe, expect, test } from "bun:test";import type { DiscoveredField } from "../../providers/onepassword.js";-import { buildFieldOptions } from "./OnepasswordModal.js";+import { buildFieldOptions } from "../onepassword-fields.js";const V = "Vault";const I = "Item";diff --git a/packages/cli/src/tui/components/OnepasswordModal.tsx b/packages/cli/src/tui/components/OnepasswordModal.tsxindex da447570..e945276b 100644--- a/packages/cli/src/tui/components/OnepasswordModal.tsx+++ b/packages/cli/src/tui/components/OnepasswordModal.tsx@@ -1,8 +1,8 @@/** @jsxImportSource @opentui/react */import type { ReactNode } from "react";-import type { AccountInfo, DiscoveredField } from "../../providers/onepassword.js";+import type { AccountInfo } from "../../providers/onepassword.js";+import type { FieldPickerOption, OpModalMode } from "../onepassword-fields.js";import { A, C } from "../theme.js";-import type { Mode } from "../types.js";/*** Centered modal dialog for the 1Password add-wizard. Rendered as an@@ -24,93 +24,14 @@ import type { Mode } from "../types.js";* matches the Providers <input> + Profiles <select> coexistence model.*/-/** The modal modes this dialog renders for. */-export type OpModalMode =- | "input_op_account"- | "input_op_env"- | "pick_op_scope"- | "pick_op_account"- | "pick_op_kind"- | "pick_op_vault"- | "pick_op_item"- | "pick_op_field";--/** True when the given Mode is one the 1Password modal should render. */-export function isOpModalMode(mode: Mode): mode is OpModalMode {- return (- mode === "input_op_account" ||- mode === "input_op_env" ||- mode === "pick_op_scope" ||- mode === "pick_op_account" ||- mode === "pick_op_kind" ||- mode === "pick_op_vault" ||- mode === "pick_op_item" ||- mode === "pick_op_field"- );-}--/**- * Case-insensitive subsequence fuzzy match: every char of `query` must appear in- * `text` in order (not necessarily adjacent). Empty query matches everything.- * e.g. "dhg" matches "Docker Hub Github credentials".- */-export function fuzzyMatch(query: string, text: string): boolean {- const q = query.trim().toLowerCase();- if (q === "") return true;- const t = text.toLowerCase();- let qi = 0;- for (let ti = 0; ti < t.length && qi < q.length; ti++) {- if (t[ti] === q[qi]) qi++;- }- return qi === q.length;-}--/** Filter a list of {title}-bearing rows by fuzzy-matching `filter` against title. */-export function fuzzyFilterByTitle<T extends { title: string }>(rows: T[], filter: string): T[] {- if (filter.trim() === "") return rows;- return rows.filter((r) => fuzzyMatch(filter, r.title));-}--/**- * The visual role of a field-picker row, driving color + layout in- * renderFieldPicker. `everything`/`section-glob` are the dynamic globs;- * `field` is a concrete ref; `collapsed` is a single-field section shown as- * "Section → ENVNAME"; `header` is a non-selectable group anchor; `blank` is a- * spacer line between groups.- */-export type FieldRowRole =- | "everything-all" // whole-item `**` glob (★ All keys in this item)- | "everything" // sectionless `*` glob (★ All top-level keys)- | "section-glob"- | "field"- | "collapsed"- | "header"- | "blank";-/**- * A field-picker row. Selectable options build an op:// path (`value`); headers- * and blanks are visual-only. `left`/`right` carry the two-column display parts- * (e.g. left="OpenAI", right="OPENAI_API_KEY") so renderFieldPicker can align- * the env-var-name column.+ * `OpModalMode`, `isOpModalMode`, `fuzzyMatch`, `fuzzyFilterByTitle`,+ * `FieldRowRole`, `FieldPickerOption` and `buildFieldOptions` MOVED to+ * `../onepassword-fields.ts`. They are pure functions over plain data with no+ * JSX in them, and `App.tsx`'s state layer calls them — so leaving them here+ * would force `hooks/` to import from `components/` the moment that state moves+ * into a hook. See that file's header for the full rationale.*/-export interface FieldPickerOption {- /** Display label (full, single-column fallback). */- name: string;- /** The op:// path (selectable rows) or "" (headers/blanks). Shown in footer. */- description: string;- /** The op:// path this option builds (single ref or glob); "" for non-rows. */- value: string;- /** False → header/blank: the cursor skips it and Enter ignores it. */- selectable: boolean;- /** Visual role for coloring/layout. */- role: FieldRowRole;- /** Left column text (the field/section label or glob caption). */- left: string;- /** Right column text (the resulting env-var name), or "" when N/A. */- right: string;- /** Indent depth (0 = top/header, 1 = nested under a section). */- indent: number;-}interface OnepasswordModalProps {mode: OpModalMode;@@ -174,136 +95,6 @@ const SCOPE_OPTIONS = [{ name: "project (./.claudish.json)", description: "", value: "project" },];-/** A valid POSIX-ish env var name (matches the resolver's ENV_VAR_NAME_RE). */-const ENV_NAME_RE = /^[A-Z_][A-Z0-9_]*$/;--/**- * A field is IMPORTABLE only if it's a concealed (secret) field whose label is a- * valid env-var name — i.e. something that actually becomes an env var at import.- * Non-concealed fields (notes/username/url) and badly-named fields ("credential")- * are hidden so the picker shows only real keys. (The SDK's fieldType enum value- * is "Concealed"; match case-insensitively to be safe.)- */-function isImportableField(f: DiscoveredField): boolean {- const name = f.label.trim();- if (!ENV_NAME_RE.test(name)) return false;- return String(f.type).toLowerCase() === "concealed";-}--/**- * Build the field-picker option list from discovered fields.- *- * Only IMPORTABLE fields (concealed + valid env-var name) are shown; everything- * else is hidden. Layout:- * - `★ Import everything (N keys)` glob at top (N = importable count).- * FLAT LIST (uniform — no headers/gaps): one selectable "key" row per importable- * field, shown as `ENVNAME · section` (the section is dim context). After a- * MULTI-key section's keys, one "↳ all of <section>" glob row (dynamic). Plus a- * trailing "★ All top-level keys" glob ONLY when there are importable sectionless- * keys (an item-level `op://Item/*` glob matches sectionless fields only — the- * grammar can't span sections). Order: by section (first-seen), keys then the- * section's "all of" glob; sectionless keys last; ★ at the very end.- */-export function buildFieldOptions(- vaultTitle: string,- itemTitle: string,- fields: DiscoveredField[]-): FieldPickerOption[] {- const opts: FieldPickerOption[] = [];-- // Keep only importable fields, preserving order.- const importable = fields.filter(isImportableField);-- // Group by section (first-seen order); sectionless → topLevel.- const sectionOrder: string[] = [];- const bySection = new Map<string, DiscoveredField[]>();- const topLevel: DiscoveredField[] = [];- for (const f of importable) {- if (f.section) {- if (!bySection.has(f.section)) {- bySection.set(f.section, []);- sectionOrder.push(f.section);- }- bySection.get(f.section)!.push(f);- } else {- topLevel.push(f);- }- }-- const hasSections = sectionOrder.length > 0;-- // A single "key" row: ENVNAME (left, green) + section tag (right, dim context).- const keyRow = (f: DiscoveredField, section: string | null): FieldPickerOption => {- const env = f.label.trim() || f.label;- return {- name: `${env} · ${section ?? ""}`,- description: f.reference,- value: f.reference,- selectable: true,- role: "field",- left: env,- right: section ?? "",- indent: 0,- };- };-- // ★ All keys in this item — the WHOLE-item glob (`**`): every importable field- // regardless of section. Shown FIRST whenever the item has any importable key.- // One config entry covers every shape (no-sections / all-sectioned / mixed).- if (importable.length > 0) {- opts.push({- name: `★ All keys in this item (${importable.length}, auto-updates)`,- description: `op://${vaultTitle}/${itemTitle}/**`,- value: `op://${vaultTitle}/${itemTitle}/**`,- selectable: true,- role: "everything-all",- left: "★ All keys in this item",- right: `${importable.length}, auto-updates`,- indent: 0,- });- }-- // Section keys, then (for multi-key sections) one "↳ all of <section>" glob.- for (const section of sectionOrder) {- const inSection = bySection.get(section)!;- for (const f of inSection) opts.push(keyRow(f, section));- if (inSection.length >= 2) {- opts.push({- name: `↳ all of ${section} (${inSection.length}, auto-updates)`,- description: `op://${vaultTitle}/${itemTitle}/${section}/*`,- value: `op://${vaultTitle}/${itemTitle}/${section}/*`,- selectable: true,- role: "section-glob",- left: `↳ all of ${section}`,- right: `${inSection.length}, auto-updates`,- indent: 0,- });- }- }-- // Sectionless keys (no tag).- for (const f of topLevel) opts.push(keyRow(f, null));-- // ★ All top-level keys — the sectionless-only glob (`*`). Shown ONLY for a- // MIXED item (has sections AND top-level keys), as a narrower pick distinct- // from "All keys in this item". For a no-sections item, `**` already equals- // `*`, so this would be a redundant second star — suppress it there.- if (topLevel.length > 0 && hasSections) {- opts.push({- name: `★ All top-level keys (${topLevel.length}, auto-updates)`,- description: `op://${vaultTitle}/${itemTitle}/*`,- value: `op://${vaultTitle}/${itemTitle}/*`,- selectable: true,- role: "everything",- left: "★ All top-level keys",- right: `${topLevel.length}, auto-updates`,- indent: 0,- });- }-- return opts;-}-/*** Width-aware middle-truncate. Keeps the start and (biased) the tail visible so a* long op:// path still shows its disambiguating `/<field>` or `/*` suffix. e.g.diff --git a/packages/cli/src/tui/components/Shimmer.tsx b/packages/cli/src/tui/components/Shimmer.tsxnew file mode 100644index 00000000..c8be4367--- /dev/null+++ b/packages/cli/src/tui/components/Shimmer.tsx@@ -0,0 +1,123 @@+/** @jsxImportSource @opentui/react */+/**+ * Shimmer — the repo's indeterminate-progress idiom, promoted to a component.+ *+ * A travelling `▓▒░▒` bar, lifted from `probe/probe-tui-app.tsx:179` + `:538-543`+ * (the `ANIM_FRAMES[(animFrame + i) % 4]` loop). The PHASE OFFSET is the whole+ * point: without it every cell shows the same glyph and the bar BLINKS; with it+ * the pattern travels, which is what reads as "work is happening" rather than+ * "the screen is flickering". Drive it from `hooks/useAnimationFrame.ts`.+ *+ * USE THIS ONLY WHEN THERE IS NOTHING TO MEASURE. A shimmer makes exactly one+ * claim — time is passing — and that claim is always true. When work is+ * countable (`done/total`) use a determinate `Meter`/`MeterSpan` instead; when a+ * DEADLINE is known but the work is not, that is an elapsed-vs-deadline+ * indicator and not progress, so its label has to say so. Rendering an invented+ * denominator as a bar is the dishonest feedback this component exists to avoid.+ *+ * TWO FORMS, for the same reason `viz/widgets.tsx` ships `Meter` and `MeterSpan`:+ * a `<text>` cannot nest inside a `<text>`, so the standalone form cannot share a+ * row with a label. `Shimmer` is a row of its own; `ShimmerSpan` goes INSIDE+ * someone else's `<text>`. Putting a `<span>` outside a `<text>` renders an error+ * page instead of the UI while the process stays alive and exits 0 — `tsc`,+ * `bun test` and `check-surface` all stay green and only a screenshot catches it,+ * so the two names are kept apart on purpose. `shimmerGlyphs` is extracted so the+ * two forms cannot drift, exactly as `sparkGlyphs` is for `Sparkline`.+ */++import type { ColorInput } from "@opentui/core";+import type { ReactNode } from "react";+import { tokens } from "../viz/tokens.js";++/**+ * ▓ ▒ ░ ▒ — four glyphs, not three. The repeated `▒` is what makes the cycle+ * read as a wave passing rather than as a saw-tooth jumping back to full at+ * every fourth cell.+ */+const ANIM_FRAMES = ["▓", "▒", "░", "▒"] as const;++/**+ * The bar's glyph run at `frame`, `width` cells wide — the pure half, shared by+ * both forms above.+ *+ * `null` (never `""`) for a non-positive or non-finite width, so a caller renders+ * NOTHING rather than an empty `<text>`: an empty text node is still a flex item+ * and still eats a row, which is the convention `viz/widgets.tsx` keeps for every+ * widget with empty input.+ *+ * A negative or fractional `frame` is floored and re-normalised into range rather+ * than trusted: `(-1) % 4` is `-1` in JavaScript, and `ANIM_FRAMES[-1]` is+ * `undefined`, which `join`/`+=` would swallow — one cell silently gone and every+ * cell right of it shifted.+ */+export function shimmerGlyphs(frame: number, width: number): string | null {+ const cells = Math.floor(width);+ if (!Number.isFinite(cells) || cells <= 0) return null;+ const floored = Math.floor(frame);+ const base = Number.isFinite(floored) ? floored : 0;+ const n = ANIM_FRAMES.length;+ let out = "";+ for (let i = 0; i < cells; i++) {+ out += ANIM_FRAMES[(((base + i) % n) + n) % n];+ }+ return out;+}++/**+ * The standalone form — one `<text>`, a row of its own.+ *+ * `flexShrink={0}` for the reason `viz/widgets.tsx` gives on every widget: the+ * width is a cell count the caller computed, so a layout that quietly shortens it+ * has broken the caller's arithmetic. Over-budget overflows and clips visibly+ * instead.+ *+ * `fg` defaults to `tokens.warn` and is read at RENDER time (a default parameter+ * is evaluated per call). In-flight is the `warn` tier app-wide — expected but+ * notable, and deliberately NOT the `error` tier. A module-level `const` here+ * would snapshot the dark palette before theme detection runs and ship a+ * dark-only bar; that bug has been found six times in this repo.+ */+export function Shimmer({+ frame,+ width,+ fg = tokens.warn,+}: {+ /** The counter from `useAnimationFrame` — one step per 100 ms. */+ frame: number;+ /** Bar width, in cells. */+ width: number;+ /** Bar colour. Defaults to the in-flight tier. */+ fg?: ColorInput;+}): ReactNode {+ const glyphs = shimmerGlyphs(frame, width);+ if (glyphs === null) return null;+ return (+ <text fg={fg} flexShrink={0}>+ {glyphs}+ </text>+ );+}++/**+ * The same bar as a `<span>`, for a MIXED-CONTENT row — a label, a counter and a+ * bar in ONE `<text>`. The alternative, a flex row of `<text>` siblings, is the+ * arrangement Yoga silently shrinks: it claws columns back from the LAST child,+ * which is how a branch name once rendered as `mai` with thirty free columns+ * beside it.+ *+ * No layout props: a `<span>` is not a flex item, so its row's `<text>` owns the+ * layout for both.+ */+export function ShimmerSpan({+ frame,+ width,+ fg = tokens.warn,+}: {+ frame: number;+ width: number;+ fg?: ColorInput;+}): ReactNode {+ const glyphs = shimmerGlyphs(frame, width);+ if (glyphs === null) return null;+ return <span fg={fg}>{glyphs}</span>;+}diff --git a/packages/cli/src/tui/hooks/useAnimationFrame.ts b/packages/cli/src/tui/hooks/useAnimationFrame.tsnew file mode 100644index 00000000..b0d6fe8b--- /dev/null+++ b/packages/cli/src/tui/hooks/useAnimationFrame.ts@@ -0,0 +1,33 @@+/**+ * useAnimationFrame — the repo's ONE tick source for indeterminate progress.+ *+ * Lifted verbatim from `probe/probe-tui-app.tsx:167-175`, which now re-exports it+ * so `probe/` needs no edit. It moved for one reason: it was the only exported+ * tick source in the codebase and it lived inside a 1,500-line component module,+ * so a second OpenTUI app could not have it without importing the probe's whole+ * component tree. `probe/ → tui/` is an edge that already exists+ * (`probe-tui-app.tsx:35` imports `../tui/theme.js`); `tui/ → probe/` does not+ * exist and must not be created. Hence the hook lives on the `tui/` side.+ *+ * 100 ms, GATED ON `active`: an inactive caller registers no interval at all, so+ * a screen with nothing in flight costs nothing per frame and a settled screen+ * stops re-rendering entirely. The counter wraps at 1e6 rather than growing+ * without bound — every reader takes it modulo a small bar width.+ *+ * NOT `useTimeline`, which does exist at the 0.1.107 pin and has zero uses here:+ * a timeline is a tween driver for eased property animation, and nothing that+ * reads this counter eases. A 100 ms integer is the house idiom.+ */++import { useEffect, useState } from "react";++/** Bumps a counter every 100ms while active — used for progress bar animation and elapsed timers. */+export function useAnimationFrame(active: boolean): number {+ const [frame, setFrame] = useState(0);+ useEffect(() => {+ if (!active) return;+ const id = setInterval(() => setFrame((f) => (f + 1) % 1_000_000), 100);+ return () => clearInterval(id);+ }, [active]);+ return frame;+}diff --git a/packages/cli/src/tui/onepassword-fields.ts b/packages/cli/src/tui/onepassword-fields.tsnew file mode 100644index 00000000..235b3812--- /dev/null+++ b/packages/cli/src/tui/onepassword-fields.ts@@ -0,0 +1,241 @@+/**+ * onepassword-fields.ts — the 1Password add-wizard's pure logic, with no JSX.+ *+ * WHY THIS FILE EXISTS: it breaks an import edge before that edge is created.+ * `buildFieldOptions`, `fuzzyFilterByTitle`, `fuzzyMatch` and `isOpModalMode`+ * lived inside `components/OnepasswordModal.tsx` and are called from `App.tsx`'s+ * state layer — so the moment that state moves into `hooks/useOnepasswordTab.ts`+ * (the largest extraction planned for this TUI), `hooks/` would import from+ * `components/`. That is the one direction the directory contract forbids: views+ * may read logic, logic may not reach back into views, or the two stop being+ * separable and the next split has nowhere to put anything.+ *+ * These four are already independent of the component — plain functions over+ * plain data, no JSX, no hooks, no renderer. Only their ADDRESS was wrong. The+ * modal and the hook now both import them from here.+ *+ * The types travel with them: `OpModalMode` is the mode subset the modal renders+ * and is what `isOpModalMode` narrows to, and `FieldPickerOption`/`FieldRowRole`+ * are what `buildFieldOptions` returns.+ */++import type { DiscoveredField } from "../providers/onepassword.js";+import type { Mode } from "./types.js";++/** The modal modes this dialog renders for. */+export type OpModalMode =+ | "input_op_account"+ | "input_op_env"+ | "pick_op_scope"+ | "pick_op_account"+ | "pick_op_kind"+ | "pick_op_vault"+ | "pick_op_item"+ | "pick_op_field";++/** True when the given Mode is one the 1Password modal should render. */+export function isOpModalMode(mode: Mode): mode is OpModalMode {+ return (+ mode === "input_op_account" ||+ mode === "input_op_env" ||+ mode === "pick_op_scope" ||+ mode === "pick_op_account" ||+ mode === "pick_op_kind" ||+ mode === "pick_op_vault" ||+ mode === "pick_op_item" ||+ mode === "pick_op_field"+ );+}++/**+ * Case-insensitive subsequence fuzzy match: every char of `query` must appear in+ * `text` in order (not necessarily adjacent). Empty query matches everything.+ * e.g. "dhg" matches "Docker Hub Github credentials".+ */+export function fuzzyMatch(query: string, text: string): boolean {+ const q = query.trim().toLowerCase();+ if (q === "") return true;+ const t = text.toLowerCase();+ let qi = 0;+ for (let ti = 0; ti < t.length && qi < q.length; ti++) {+ if (t[ti] === q[qi]) qi++;+ }+ return qi === q.length;+}++/** Filter a list of {title}-bearing rows by fuzzy-matching `filter` against title. */+export function fuzzyFilterByTitle<T extends { title: string }>(rows: T[], filter: string): T[] {+ if (filter.trim() === "") return rows;+ return rows.filter((r) => fuzzyMatch(filter, r.title));+}++/**+ * The visual role of a field-picker row, driving color + layout in+ * renderFieldPicker. `everything`/`section-glob` are the dynamic globs;+ * `field` is a concrete ref; `collapsed` is a single-field section shown as+ * "Section → ENVNAME"; `header` is a non-selectable group anchor; `blank` is a+ * spacer line between groups.+ */+export type FieldRowRole =+ | "everything-all" // whole-item `**` glob (★ All keys in this item)+ | "everything" // sectionless `*` glob (★ All top-level keys)+ | "section-glob"+ | "field"+ | "collapsed"+ | "header"+ | "blank";++/**+ * A field-picker row. Selectable options build an op:// path (`value`); headers+ * and blanks are visual-only. `left`/`right` carry the two-column display parts+ * (e.g. left="OpenAI", right="OPENAI_API_KEY") so renderFieldPicker can align+ * the env-var-name column.+ */+export interface FieldPickerOption {+ /** Display label (full, single-column fallback). */+ name: string;+ /** The op:// path (selectable rows) or "" (headers/blanks). Shown in footer. */+ description: string;+ /** The op:// path this option builds (single ref or glob); "" for non-rows. */+ value: string;+ /** False → header/blank: the cursor skips it and Enter ignores it. */+ selectable: boolean;+ /** Visual role for coloring/layout. */+ role: FieldRowRole;+ /** Left column text (the field/section label or glob caption). */+ left: string;+ /** Right column text (the resulting env-var name), or "" when N/A. */+ right: string;+ /** Indent depth (0 = top/header, 1 = nested under a section). */+ indent: number;+}++/** A valid POSIX-ish env var name (matches the resolver's ENV_VAR_NAME_RE). */+const ENV_NAME_RE = /^[A-Z_][A-Z0-9_]*$/;++/**+ * A field is IMPORTABLE only if it's a concealed (secret) field whose label is a+ * valid env-var name — i.e. something that actually becomes an env var at import.+ * Non-concealed fields (notes/username/url) and badly-named fields ("credential")+ * are hidden so the picker shows only real keys. (The SDK's fieldType enum value+ * is "Concealed"; match case-insensitively to be safe.)+ */+function isImportableField(f: DiscoveredField): boolean {+ const name = f.label.trim();+ if (!ENV_NAME_RE.test(name)) return false;+ return String(f.type).toLowerCase() === "concealed";+}++/**+ * Build the field-picker option list from discovered fields.+ *+ * Only IMPORTABLE fields (concealed + valid env-var name) are shown; everything+ * else is hidden. Layout:+ * - `★ Import everything (N keys)` glob at top (N = importable count).+ * FLAT LIST (uniform — no headers/gaps): one selectable "key" row per importable+ * field, shown as `ENVNAME · section` (the section is dim context). After a+ * MULTI-key section's keys, one "↳ all of <section>" glob row (dynamic). Plus a+ * trailing "★ All top-level keys" glob ONLY when there are importable sectionless+ * keys (an item-level `op://Item/*` glob matches sectionless fields only — the+ * grammar can't span sections). Order: by section (first-seen), keys then the+ * section's "all of" glob; sectionless keys last; ★ at the very end.+ */+export function buildFieldOptions(+ vaultTitle: string,+ itemTitle: string,+ fields: DiscoveredField[]+): FieldPickerOption[] {+ const opts: FieldPickerOption[] = [];++ // Keep only importable fields, preserving order.+ const importable = fields.filter(isImportableField);++ // Group by section (first-seen order); sectionless → topLevel.+ const sectionOrder: string[] = [];+ const bySection = new Map<string, DiscoveredField[]>();+ const topLevel: DiscoveredField[] = [];+ for (const f of importable) {+ if (f.section) {+ if (!bySection.has(f.section)) {+ bySection.set(f.section, []);+ sectionOrder.push(f.section);+ }+ bySection.get(f.section)!.push(f);+ } else {+ topLevel.push(f);+ }+ }++ const hasSections = sectionOrder.length > 0;++ // A single "key" row: ENVNAME (left, green) + section tag (right, dim context).+ const keyRow = (f: DiscoveredField, section: string | null): FieldPickerOption => {+ const env = f.label.trim() || f.label;+ return {+ name: `${env} · ${section ?? ""}`,+ description: f.reference,+ value: f.reference,+ selectable: true,+ role: "field",+ left: env,+ right: section ?? "",+ indent: 0,+ };+ };++ // ★ All keys in this item — the WHOLE-item glob (`**`): every importable field+ // regardless of section. Shown FIRST whenever the item has any importable key.+ // One config entry covers every shape (no-sections / all-sectioned / mixed).+ if (importable.length > 0) {+ opts.push({+ name: `★ All keys in this item (${importable.length}, auto-updates)`,+ description: `op://${vaultTitle}/${itemTitle}/**`,+ value: `op://${vaultTitle}/${itemTitle}/**`,+ selectable: true,+ role: "everything-all",+ left: "★ All keys in this item",+ right: `${importable.length}, auto-updates`,+ indent: 0,+ });+ }++ // Section keys, then (for multi-key sections) one "↳ all of <section>" glob.+ for (const section of sectionOrder) {+ const inSection = bySection.get(section)!;+ for (const f of inSection) opts.push(keyRow(f, section));+ if (inSection.length >= 2) {+ opts.push({+ name: `↳ all of ${section} (${inSection.length}, auto-updates)`,+ description: `op://${vaultTitle}/${itemTitle}/${section}/*`,+ value: `op://${vaultTitle}/${itemTitle}/${section}/*`,+ selectable: true,+ role: "section-glob",+ left: `↳ all of ${section}`,+ right: `${inSection.length}, auto-updates`,+ indent: 0,+ });+ }+ }++ // Sectionless keys (no tag).+ for (const f of topLevel) opts.push(keyRow(f, null));++ // ★ All top-level keys — the sectionless-only glob (`*`). Shown ONLY for a+ // MIXED item (has sections AND top-level keys), as a narrower pick distinct+ // from "All keys in this item". For a no-sections item, `**` already equals+ // `*`, so this would be a redundant second star — suppress it there.+ if (topLevel.length > 0 && hasSections) {+ opts.push({+ name: `★ All top-level keys (${topLevel.length}, auto-updates)`,+ description: `op://${vaultTitle}/${itemTitle}/*`,+ value: `op://${vaultTitle}/${itemTitle}/*`,+ selectable: true,+ role: "everything",+ left: "★ All top-level keys",+ right: `${topLevel.length}, auto-updates`,+ indent: 0,+ });+ }++ return opts;+}diff --git a/packages/cli/src/tui/runtime/can-draw-tui.ts b/packages/cli/src/tui/runtime/can-draw-tui.tsnew file mode 100644index 00000000..c49ebb01--- /dev/null+++ b/packages/cli/src/tui/runtime/can-draw-tui.ts@@ -0,0 +1,32 @@+/**+ * can-draw-tui.ts — the one oracle for "may this process paint a full-screen UI".+ *+ * THIS FILE IMPORTS NOTHING, AND THAT IS LOAD-BEARING, NOT TIDINESS. It is+ * imported STATICALLY by `index.ts` (and, later, by the model picker's entry+ * point), which are the two coldest paths in the program. Anything this file+ * pulled in would be pulled into `index.ts`'s static graph — and one OpenTUI+ * import there would load a renderer into the MCP stdio path, whose stdout is a+ * protocol. That is the exact hazard `providers/model-ordering.ts:10-18` was+ * created to prevent, one directory over. If this ever genuinely needs an+ * import, the allowlist is a `node:`-prefixed builtin and nothing else.+ *+ * WHY A FUNCTION AND NOT A CONSTANT: `isTTY` is read from the live process, and a+ * module-level `const` would freeze the answer at import time — before the point+ * where anything decides whether to draw.+ *+ * BOTH STREAMS, and both are necessary for different reasons. `stdout` not being+ * a TTY means alternate-screen escapes would land in a stream something else is+ * parsing — `claudish -p --output-format stream-json | jq` reserves that stream+ * for machine-readable output. `stdin` not being a TTY means no keypress can ever+ * arrive, so a picker would block forever waiting for one. The failure of the+ * first is corrupt output; the failure of the second is a hang, and a hang is the+ * worse of the two because it looks like slowness.+ *+ * The rationale above is the reasoning already written out at `index.ts:950-962`+ * for the resume picker, which is where this predicate was an inline `const`.+ */++/** True only when both of our own streams are terminals we may draw on. */+export function canDrawTui(): boolean {+ return Boolean(process.stdin.isTTY && process.stdout.isTTY);+}diff --git a/packages/cli/src/tui/runtime/picker-cancelled.ts b/packages/cli/src/tui/runtime/picker-cancelled.tsnew file mode 100644index 00000000..94678530--- /dev/null+++ b/packages/cli/src/tui/runtime/picker-cancelled.ts@@ -0,0 +1,64 @@+/**+ * picker-cancelled.ts — the two errors the interactive model picker can end with.+ *+ * THIS FILE IMPORTS NOTHING, for the same load-bearing reason as its neighbour+ * `can-draw-tui.ts`: it is imported STATICALLY by `model-selector.ts` and by+ * `index.ts`, so anything it pulled in would join the cold-start graph, and an+ * OpenTUI import here would put a renderer in the MCP stdio path. If one of these+ * ever needs an import, the allowlist is a `node:`-prefixed builtin, nothing else.+ *+ * IT LIVES IN `tui/runtime/` RATHER THAN BESIDE THE PICKER, and that placement is+ * the whole design note. `selectModel` throws `PickerCancelled` synchronously, so+ * it needs a STATIC import of this class — while a static import from+ * `model-selector.ts` into the picker's own directory is precisely what the+ * import-direction rule forbids (the picker is reached by `await import()` only,+ * which is what keeps OpenTUI off the cold-start path). A leaf here satisfies+ * both: the error type is statically importable, the renderer is not.+ */++/**+ * The user declined to pick — Esc, or Ctrl+C inside the picker.+ *+ * NOT AN ERROR CONDITION, despite being an Error. Declining to choose is a+ * legitimate outcome, and the caller's existing prompt-exit handler turns it into+ * a clean exit 0. It is thrown rather than returned so that cancelling unwinds+ * every caller of `selectModel`, whose contract is `Promise<string>` and which+ * therefore has no value to represent "no choice" with.+ */+export class PickerCancelled extends Error {+ constructor(message = "picker cancelled") {+ super(message);+ this.name = "PickerCancelled";+ }+}++/**+ * What to tell a user who asked for a picker in a stream that cannot show one.+ *+ * The exact three lines the non-interactive path already prints, kept here as+ * data so `NoTtyError` and that path cannot drift into telling one user something+ * different from the other. Each names a concrete way forward — the message this+ * replaces was a hang, which named none.+ */+export const NO_TTY_LINES: readonly string[] = [+ "Error: Model must be specified in non-interactive mode",+ "Use --model <model> flag, set CLAUDISH_MODEL env var, or use --profile",+ "Try: claudish --models",+];++/**+ * A picker was requested where nothing can be drawn — piped, redirected, CI, or+ * detached.+ *+ * DELIBERATELY NOT CAUGHT BY THE PROMPT-EXIT HANDLER, unlike `PickerCancelled`.+ * The user did not decline; the environment cannot ask. That has to surface and+ * exit non-zero, carrying the lines above, rather than exiting 0 as a cancel+ * does — an exit 0 with no model chosen is indistinguishable from success, and+ * this whole class of bug is one a headless caller cannot see.+ */+export class NoTtyError extends Error {+ constructor(message = NO_TTY_LINES.join("\n")) {+ super(message);+ this.name = "NoTtyError";+ }+}