supercode-cli 0.4.19

supercode — a lightweight, fully-customizable AI coding agent CLI in Rust. Any model via OpenRouter; natively continues Claude Code and Codex sessions.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
//! UX-30 — an interactive arrow-key list picker for the resume/model
//! overlays, built on the SAME raw-`termios` technique `hidden_input.rs`
//! (UX-18) already established: query the current mode with `tcgetattr`,
//! flip the bits we need, restore via an RAII guard on every exit path.
//! This intentionally adds NO new dependency (no `dialoguer`/`inquire`):
//! `libc` is already a direct dep of this crate for exactly this kind of
//! termios work, and a single-column list with ↑/↓/Enter/Esc is well
//! within what ~150 lines of raw ANSI + `read()` can do cleanly — pulling
//! in a whole prompt-toolkit crate (plus ITS transitive tree, plus a
//! fresh `cargo-deny` license/advisory surface to keep track of) for that
//! is more than this ticket's AC asks for.
//!
//! **TTY-gating is load-bearing, not cosmetic.** [`available`] (and the
//! pure decision it wraps, [`should_launch_picker`]) is the ONLY thing
//! standing between a machine/piped/scripted invocation and a picker that
//! blocks forever reading keystrokes nobody sends. Every call site in
//! `main.rs` checks it before ever constructing a picker; [`pick`] also
//! checks it internally (belt-and-suspenders — see `hidden_input.rs`'s
//! same pattern) and returns `Ok(None)` immediately rather than reading if
//! it's somehow called off a non-tty anyway.
//!
//! **Windows (UX-12): degraded, not ported — documented honestly.** The
//! raw-mode internals below (`RawGuard`/`get_termios`/`read_one`/
//! `interpret_key`/`read_escape_sequence`) are Unix-only (`libc::termios` +
//! byte-at-a-time `read(2)` + hand-parsed `CSI` escape sequences). A real
//! Windows port needs `SetConsoleMode` with `ENABLE_VIRTUAL_TERMINAL_INPUT`
//! (so arrow keys arrive as the same `ESC [ A`/`ESC [ B` sequences this
//! module already parses) PLUS a non-blocking peek built from
//! `WaitForSingleObject` + `ReadFile` on the console handle — and that
//! `WaitForSingleObject` peek does NOT have the same "a ready signal means a
//! byte is retrievable without blocking" guarantee `poll(2)` gives on a Unix
//! tty (a console handle can signal on a single keystroke, then a
//! line-mode `ReadFile` blocks for the rest of the line) — exactly the
//! "subtle raw-mode/poll semantics that can't be cleanly gated" this
//! module's own UX-12 assessment flagged as unsafe to port blind. Per
//! UX-12's explicit guidance, this degrades instead: [`available`] reports
//! `false` unconditionally on Windows, which routes every call site in
//! `main.rs` through its already-existing, already-tested "no interactive
//! picker" fallback (the exact same path a piped/non-tty Unix invocation
//! already takes — `resume` demands an explicit session path, `chat`'s
//! `/model` prints "not a terminal — pass --model to switch"). No call site
//! silently hangs or no-ops; every one gives an explicit, actionable
//! message. `run`/`chat`/`--version` and all non-picker functionality are
//! completely unaffected. A real arrow-key picker on Windows is a
//! legitimate follow-on, not attempted here.

use std::io;
#[cfg(unix)]
use std::io::{IsTerminal, Write};
#[cfg(unix)]
use std::os::unix::io::RawFd;

#[cfg(unix)]
use crate::ui;

/// One selectable row: a primary label plus a dim detail string shown
/// alongside it (e.g. a session's age + title, or a model alias's slug).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PickerItem {
    pub label: String,
    pub detail: String,
    /// BP-8 (catalog:152 "Session picker UX" — search/PREVIEW): a longer
    /// body shown, dim, under the row while it is highlighted. Empty by
    /// default; only [`pick_searchable`] renders it.
    pub preview: String,
}

impl PickerItem {
    pub fn new(label: impl Into<String>, detail: impl Into<String>) -> Self {
        Self {
            label: label.into(),
            detail: detail.into(),
            preview: String::new(),
        }
    }

    /// BP-8: attach the preview line shown under this row when selected.
    pub fn with_preview(mut self, preview: impl Into<String>) -> Self {
        self.preview = preview.into();
        self
    }
}

/// BP-8 (catalog:152): case-insensitive substring match of `query` against a
/// row's label AND detail, returning the indices that survive. An empty
/// query matches everything, so the first render is the unfiltered list.
/// Multiple whitespace-separated terms must ALL match (any order) — typing
/// `otter fix` finds the session named `…-otter` titled "fix the parser".
pub fn filter_items(items: &[PickerItem], query: &str) -> Vec<usize> {
    let terms: Vec<String> = query.split_whitespace().map(|t| t.to_lowercase()).collect();
    items
        .iter()
        .enumerate()
        .filter(|(_, item)| {
            if terms.is_empty() {
                return true;
            }
            let hay = format!("{} {} {}", item.label, item.detail, item.preview).to_lowercase();
            terms.iter().all(|t| hay.contains(t.as_str()))
        })
        .map(|(i, _)| i)
        .collect()
}

/// BP-8 (catalog:152): what [`pick_searchable`] returned.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PickOutcome {
    /// The index (into the ORIGINAL `items` slice) the user chose.
    Selected(usize),
    /// Esc / Ctrl-C / EOF.
    Cancelled,
    /// The user asked to widen the candidate scope (Ctrl-W) — only ever
    /// returned when the caller offered a widening.
    Widen,
}

/// The pure yes/no this module's TTY-gating boils down to: launch a picker
/// only when BOTH stdin (to read keys) and stdout (to draw it) are real
/// terminals. Factored out from [`available`] so the decision itself is
/// unit-testable without needing an actual terminal (or the absence of
/// one) in the test process.
#[cfg(unix)]
pub fn should_launch_picker(stdin_is_tty: bool, stdout_is_tty: bool) -> bool {
    stdin_is_tty && stdout_is_tty
}

/// Whether an interactive picker can run right now. Every call site in
/// `main.rs` checks this BEFORE building a candidate list or calling
/// [`pick`], so a non-tty/piped/scripted run never launches one — it falls
/// back to the pre-UX-30 arg-driven behavior instead (UX-30 dev/03).
#[cfg(unix)]
pub fn available() -> bool {
    should_launch_picker(io::stdin().is_terminal(), io::stdout().is_terminal())
}

/// Windows: always `false` — see the module doc's "Windows" section for
/// why this is a deliberate, documented degrade rather than an oversight.
#[cfg(windows)]
pub fn available() -> bool {
    false
}

/// Cap on rendered rows: keeps the picker on-screen without viewport
/// scrolling, which this minimal implementation doesn't attempt. Callers
/// building the candidate list (`main.rs`) already truncate to this same
/// bound, so the count never silently disagrees with what's shown.
pub const MAX_ITEMS: usize = 20;

#[cfg(unix)]
struct RawGuard {
    fd: RawFd,
    orig: libc::termios,
}

#[cfg(unix)]
impl Drop for RawGuard {
    fn drop(&mut self) {
        // SAFETY: `fd` is the stdin descriptor this guard was built for,
        // `orig` is the termios `tcgetattr` produced for that same fd
        // before `pick` mutated it. Best-effort restore, mirroring
        // `hidden_input.rs::TermiosGuard` — there's nothing more useful to
        // do with a restore failure than leave the terminal as-is.
        unsafe {
            libc::tcsetattr(self.fd, libc::TCSANOW, &self.orig);
        }
    }
}

#[cfg(unix)]
fn get_termios(fd: RawFd) -> io::Result<libc::termios> {
    let mut term = std::mem::MaybeUninit::<libc::termios>::uninit();
    // SAFETY: `term` is a validly-sized out-pointer for `tcgetattr`.
    if unsafe { libc::tcgetattr(fd, term.as_mut_ptr()) } != 0 {
        return Err(io::Error::last_os_error());
    }
    // SAFETY: `tcgetattr` above returned success, so `term` is initialized.
    Ok(unsafe { term.assume_init() })
}

#[cfg(unix)]
fn set_termios(fd: RawFd, term: &libc::termios) -> io::Result<()> {
    // SAFETY: `fd` is a valid, open descriptor and `term` a validly
    // initialized termios (either a prior successful `tcgetattr`, or a
    // copy of one with only well-defined bitflag fields changed).
    if unsafe { libc::tcsetattr(fd, libc::TCSANOW, term) } != 0 {
        return Err(io::Error::last_os_error());
    }
    Ok(())
}

/// Read exactly one byte from `fd` with whatever blocking/timeout
/// semantics its current termios `VMIN`/`VTIME` establish. `Ok(None)`
/// means "read timed out with zero bytes" (only possible when `VMIN` is
/// 0), never a real EOF-vs-timeout ambiguity on a terminal fd.
#[cfg(unix)]
fn read_one(fd: RawFd) -> io::Result<Option<u8>> {
    let mut buf = [0u8; 1];
    // SAFETY: `buf` is a valid 1-byte out-buffer for `read(2)`, `fd` is
    // open for reading (stdin).
    let n = unsafe { libc::read(fd, buf.as_mut_ptr() as *mut libc::c_void, 1) };
    if n < 0 {
        return Err(io::Error::last_os_error());
    }
    if n == 0 {
        return Ok(None);
    }
    Ok(Some(buf[0]))
}

/// What the user did with the picker.
#[cfg(unix)]
enum KeyAction {
    Up,
    Down,
    Select,
    Cancel,
    Ignore,
    /// BP-8: a printable character typed into the search query.
    Type(char),
    /// BP-8: Backspace/Delete — drop the last query character.
    Erase,
    /// BP-8: Ctrl-W — widen the candidate scope.
    Widen,
}

/// Interpret one raw input byte already known to have arrived in "raw,
/// blocking one-byte-at-a-time" mode (`VMIN=1, VTIME=0`). `Esc` is handed
/// off to [`read_escape_sequence`] to disambiguate a bare Escape (cancel)
/// from the start of a `CSI` arrow-key sequence (`ESC [ A`/`ESC [ B`).
#[cfg(unix)]
fn interpret_key(fd: RawFd, b: u8) -> io::Result<KeyAction> {
    match b {
        b'\r' | b'\n' => Ok(KeyAction::Select),
        0x03 => Ok(KeyAction::Cancel), // Ctrl-C (ISIG is off — see `pick`)
        b'q' | b'Q' => Ok(KeyAction::Cancel),
        b'k' | b'K' => Ok(KeyAction::Up), // vim-style bonus alongside arrows
        b'j' | b'J' => Ok(KeyAction::Down),
        0x1b => read_escape_sequence(fd),
        _ => Ok(KeyAction::Ignore),
    }
}

/// BP-8: the SEARCHING picker's key map. Deliberately separate from
/// [`interpret_key`]: once every printable byte is query input, `j`/`k`/`q`
/// can no longer mean move/cancel, so only the arrows navigate and only Esc
/// (or Ctrl-C) cancels. The non-searching [`pick`] keeps its vim keys
/// untouched — the model overlay never wanted a query line.
#[cfg(unix)]
fn interpret_search_key(fd: RawFd, b: u8) -> io::Result<KeyAction> {
    match b {
        b'\r' | b'\n' => Ok(KeyAction::Select),
        0x03 => Ok(KeyAction::Cancel), // Ctrl-C (ISIG is off)
        0x17 => Ok(KeyAction::Widen),  // Ctrl-W
        0x7f | 0x08 => Ok(KeyAction::Erase),
        0x1b => read_escape_sequence(fd),
        b if (0x20..0x7f).contains(&b) => Ok(KeyAction::Type(b as char)),
        _ => Ok(KeyAction::Ignore),
    }
}

/// After a lone `ESC` (0x1b) byte, peek for the rest of a `CSI` sequence
/// with a short non-blocking window (switches the fd to `VMIN=0, VTIME=1`
/// — a 100ms timeout — for just this peek, then restores blocking
/// single-byte mode). No follow-up byte within that window means the user
/// pressed a bare Escape to cancel, not an arrow key.
#[cfg(unix)]
fn read_escape_sequence(fd: RawFd) -> io::Result<KeyAction> {
    let blocking = get_termios(fd)?;
    let mut peek = blocking;
    peek.c_cc[libc::VMIN] = 0;
    peek.c_cc[libc::VTIME] = 1; // deciseconds — 100ms
    set_termios(fd, &peek)?;
    let next = read_one(fd)?;
    set_termios(fd, &blocking)?; // back to blocking single-byte reads

    if next != Some(b'[') {
        return Ok(KeyAction::Cancel);
    }
    match read_one(fd)? {
        Some(b'A') => Ok(KeyAction::Up),   // ESC [ A — cursor up
        Some(b'B') => Ok(KeyAction::Down), // ESC [ B — cursor down
        _ => Ok(KeyAction::Ignore),        // some other CSI sequence — ignore
    }
}

/// Render one row: `"> "` + accent-bold label + dim detail when selected,
/// two-space indent + plain label + dim detail otherwise.
#[cfg(unix)]
fn render_row(item: &PickerItem, selected: bool) -> String {
    if selected {
        format!(
            "{} {}  {}",
            ui::bold(ui::ACCENT, ">"),
            ui::bold(ui::ACCENT, &item.label),
            ui::paint(ui::DIM, &item.detail)
        )
    } else {
        format!("  {}  {}", item.label, ui::paint(ui::DIM, &item.detail))
    }
}

/// Draw the full item list once (used for the initial render).
#[cfg(unix)]
fn draw_initial(out: &mut impl Write, items: &[PickerItem], selected: usize) -> io::Result<()> {
    for (i, item) in items.iter().enumerate() {
        writeln!(out, "\r{}", render_row(item, i == selected))?;
    }
    out.flush()
}

/// Redraw the item list in place: move the cursor back up over every row
/// this picker owns, then rewrite each one (clearing the line first so a
/// shorter new row never leaves stale trailing characters behind).
#[cfg(unix)]
fn redraw(out: &mut impl Write, items: &[PickerItem], selected: usize) -> io::Result<()> {
    write!(out, "\x1b[{}A", items.len())?; // cursor up N lines
    for (i, item) in items.iter().enumerate() {
        writeln!(out, "\r\x1b[2K{}", render_row(item, i == selected))?;
    }
    out.flush()
}

/// Run an interactive arrow-key picker over `items`, prefixed by `header`.
/// Returns `Ok(Some(index))` for a selection (Enter), `Ok(None)` for a
/// cancel (Esc/`q`/Ctrl-C) or if the terminal isn't actually available
/// (see module docs — callers are expected to have already checked
/// [`available`]; this is a defensive second check, not the primary gate).
///
/// `items` must be non-empty; an empty slice returns `Ok(None)` without
/// touching the terminal at all (nothing to pick from).
pub fn pick(header: &str, items: &[PickerItem]) -> io::Result<Option<usize>> {
    if items.is_empty() || !available() {
        return Ok(None);
    }

    #[cfg(unix)]
    {
        let fd = libc::STDIN_FILENO;
        let orig = get_termios(fd)?;
        let mut raw = orig;
        // ICANON off: read byte-at-a-time instead of line-buffered. ECHO off:
        // arrow/enter/escape keystrokes never echo raw bytes to the screen —
        // this picker draws its own representation. ISIG off: Ctrl-C arrives
        // as byte 0x03 (handled as Cancel above) instead of raising SIGINT —
        // deliberately different from `hidden_input.rs`'s choice to leave
        // ISIG on: THIS runs before any turn/agent work exists to interrupt,
        // so a clean in-picker cancel (terminal restored by `RawGuard::drop`)
        // is strictly better here than killing the whole process.
        raw.c_lflag &= !(libc::ICANON | libc::ECHO | libc::ISIG);
        raw.c_cc[libc::VMIN] = 1;
        raw.c_cc[libc::VTIME] = 0;
        set_termios(fd, &raw)?;
        let _guard = RawGuard { fd, orig };

        let mut out = io::stdout();
        if !header.is_empty() {
            writeln!(out, "{}", ui::bold(ui::ACCENT, header))?;
        }
        writeln!(
            out,
            "{}",
            ui::paint(
                ui::DIM,
                "  ↑/↓ or j/k to move · Enter to select · Esc/q to cancel"
            )
        )?;

        let mut selected = 0usize;
        draw_initial(&mut out, items, selected)?;

        loop {
            // `read_one` under this loop's blocking `VMIN=1, VTIME=0` termios
            // returns `None` ONLY on a genuine EOF (see its doc comment) —
            // never a spurious "no key yet" wakeup for a real interactive
            // user, whose call simply blocks until a byte arrives. A
            // driverless pty whose write end has gone away (e.g. `--yes`
            // under `script`/`ssh -tt`/expect-style automation on a fresh
            // install, with nobody ever typing) hits this on every read —
            // `read()` returns 0 immediately and forever — so looping here
            // with `continue` was an unbounded, CPU-spinning hang. Treat a
            // genuine EOF as Cancel, same as Esc/q/Ctrl-C, so every caller of
            // `pick` (not just onboarding) gets a bounded return instead.
            let Some(b) = read_one(fd)? else {
                return Ok(None);
            };
            match interpret_key(fd, b)? {
                KeyAction::Up => {
                    selected = selected.checked_sub(1).unwrap_or(items.len() - 1);
                    redraw(&mut out, items, selected)?;
                }
                KeyAction::Down => {
                    selected = (selected + 1) % items.len();
                    redraw(&mut out, items, selected)?;
                }
                KeyAction::Select => return Ok(Some(selected)),
                KeyAction::Cancel => return Ok(None),
                // The searching picker's own actions never arrive here:
                // this loop reads through `interpret_key`, which does not
                // produce them.
                KeyAction::Ignore | KeyAction::Type(_) | KeyAction::Erase | KeyAction::Widen => {}
            }
        }
        // `_guard` drops here (or on any early return above), restoring the
        // original termios on every exit path — including a panic unwind.
    }
    #[cfg(windows)]
    {
        // Unreachable at runtime: `available()` is unconditionally `false`
        // on Windows (see module doc "Windows" section), so the guard
        // clause above already returned. Kept as a safe fallback (not a
        // panic) purely so this function type-checks for Windows targets.
        let _ = header;
        Ok(None)
    }
}

/// BP-8 (catalog:152 "Session picker UX"): the resume picker with the row's
/// own semantics — type-to-search over every candidate, a preview under the
/// highlighted row, and an offered scope widening.
///
/// `widen_hint`, when given, is the label of a broader candidate set the
/// caller can supply (e.g. "all directories"); Ctrl-W returns
/// [`PickOutcome::Widen`] and the caller re-enters with the wider list. That
/// keeps scope policy where it belongs — with the caller that knows what the
/// scopes ARE — instead of teaching the terminal widget about sessions.
pub fn pick_searchable(
    header: &str,
    items: &[PickerItem],
    widen_hint: Option<&str>,
) -> io::Result<PickOutcome> {
    if items.is_empty() || !available() {
        return Ok(PickOutcome::Cancelled);
    }
    #[cfg(unix)]
    {
        let fd = libc::STDIN_FILENO;
        let orig = get_termios(fd)?;
        let mut raw = orig;
        raw.c_lflag &= !(libc::ICANON | libc::ECHO | libc::ISIG);
        raw.c_cc[libc::VMIN] = 1;
        raw.c_cc[libc::VTIME] = 0;
        set_termios(fd, &raw)?;
        let _guard = RawGuard { fd, orig };

        let mut out = io::stdout();
        if !header.is_empty() {
            writeln!(out, "{}", ui::bold(ui::ACCENT, header))?;
        }
        let mut hint =
            "  type to search · ↑/↓ to move · Enter to select · Esc to cancel".to_string();
        if let Some(label) = widen_hint {
            hint.push_str(&format!(" · Ctrl-W for {label}"));
        }
        writeln!(out, "{}", ui::paint(ui::DIM, &hint))?;

        let mut query = String::new();
        let mut selected = 0usize;
        let mut drawn = 0usize;
        loop {
            let visible = filter_items(items, &query);
            if selected >= visible.len() {
                selected = visible.len().saturating_sub(1);
            }
            drawn = draw_search(&mut out, items, &visible, selected, &query, drawn)?;
            let Some(b) = read_one(fd)? else {
                return Ok(PickOutcome::Cancelled);
            };
            match interpret_search_key(fd, b)? {
                KeyAction::Up => {
                    if !visible.is_empty() {
                        selected = selected.checked_sub(1).unwrap_or(visible.len() - 1);
                    }
                }
                KeyAction::Down => {
                    if !visible.is_empty() {
                        selected = (selected + 1) % visible.len();
                    }
                }
                KeyAction::Select => {
                    if let Some(index) = visible.get(selected) {
                        return Ok(PickOutcome::Selected(*index));
                    }
                }
                KeyAction::Cancel => return Ok(PickOutcome::Cancelled),
                KeyAction::Widen if widen_hint.is_some() => return Ok(PickOutcome::Widen),
                KeyAction::Type(c) => {
                    query.push(c);
                    selected = 0;
                }
                KeyAction::Erase => {
                    query.pop();
                    selected = 0;
                }
                KeyAction::Widen | KeyAction::Ignore => {}
            }
        }
    }
    #[cfg(windows)]
    {
        let _ = (header, widen_hint);
        Ok(PickOutcome::Cancelled)
    }
}

/// BP-8: render the query line, the filtered rows, and the selected row's
/// preview, clearing whatever the previous frame drew. Returns the number of
/// lines this frame owns, so the next one can move back over exactly them
/// (the row count changes as the query narrows, which is why [`redraw`]'s
/// fixed `items.len()` can't serve here).
#[cfg(unix)]
fn draw_search(
    out: &mut impl Write,
    items: &[PickerItem],
    visible: &[usize],
    selected: usize,
    query: &str,
    previous: usize,
) -> io::Result<usize> {
    if previous > 0 {
        write!(out, "\x1b[{previous}A")?;
    }
    let mut lines = 0usize;
    writeln!(
        out,
        "\r\x1b[2K{} {}",
        ui::bold(ui::ACCENT, "search:"),
        if query.is_empty() { "" } else { query }
    )?;
    lines += 1;
    if visible.is_empty() {
        writeln!(out, "\r\x1b[2K{}", ui::paint(ui::DIM, "  (no match)"))?;
        lines += 1;
    }
    for (row, index) in visible.iter().enumerate() {
        writeln!(
            out,
            "\r\x1b[2K{}",
            render_row(&items[*index], row == selected)
        )?;
        lines += 1;
        if row == selected && !items[*index].preview.is_empty() {
            writeln!(
                out,
                "\r\x1b[2K      {}",
                ui::paint(ui::DIM, &items[*index].preview)
            )?;
            lines += 1;
        }
    }
    // Clear any rows the previous, longer frame left behind.
    for _ in lines..previous {
        writeln!(out, "\r\x1b[2K")?;
        lines += 1;
    }
    out.flush()?;
    Ok(lines)
}

#[cfg(all(test, unix))]
mod tests {
    use super::*;

    #[test]
    fn gating_requires_both_stdin_and_stdout_tty() {
        assert!(should_launch_picker(true, true));
        assert!(!should_launch_picker(false, true));
        assert!(!should_launch_picker(true, false));
        assert!(!should_launch_picker(false, false));
    }

    /// `pick`'s main loop now maps `read_one`'s `Ok(None)` straight to
    /// Cancel instead of the old `else { continue }` (an unbounded,
    /// CPU-spinning loop on a driverless pty whose write end has gone
    /// away — every read there returns EOF immediately and forever). A
    /// real pty isn't safely constructible in this in-process test binary
    /// (see `available_is_false_under_the_test_harness`'s doc comment —
    /// repointing fd 0 stomps process-global state shared with every
    /// other concurrently-running test); a plain `pipe(2)` is, and it
    /// exercises the exact primitive the loop's fix depends on: closing
    /// the write end makes a read of the read end return a genuine,
    /// immediate `Ok(0)` (EOF, not a hang) — `read_one` must report that
    /// as `Ok(None)`, which the CLI-level, real-pty proof (`--yes` under
    /// a driverless pty, `crates/cli/tests/onboarding_cli.rs`) then
    /// relies on this loop turning into `Cancel` rather than spinning.
    #[test]
    fn read_one_reports_a_closed_pipe_as_eof_not_a_hang() {
        let mut fds = [0i32; 2];
        // SAFETY: `fds` is a valid 2-element out-array for `pipe(2)`.
        let rc = unsafe { libc::pipe(fds.as_mut_ptr()) };
        assert_eq!(rc, 0, "pipe(2) failed: {}", io::Error::last_os_error());
        let (read_fd, write_fd) = (fds[0], fds[1]);
        // SAFETY: `write_fd` was just returned open by `pipe(2)` above and
        // not used anywhere else yet; closing it is what makes the read
        // end observe EOF instead of blocking for a writer that'll never
        // come.
        unsafe { libc::close(write_fd) };
        let result = read_one(read_fd);
        // SAFETY: `read_fd` was returned open by `pipe(2)` above; `pick`'s
        // real callers instead restore termios via `RawGuard` — there's
        // no termios on a plain pipe fd here to worry about.
        unsafe { libc::close(read_fd) };
        assert!(
            matches!(result, Ok(None)),
            "expected Ok(None) (EOF) on a closed pipe's read end, got {result:?}"
        );
    }

    /// BP-8 (catalog:152): the search half of the picker row, as a pure
    /// function over the same `PickerItem`s the picker renders.
    #[test]
    fn filter_matches_label_detail_and_preview_case_insensitively() {
        let items = vec![
            PickerItem::new("abc123  2m ago", "fix the parser").with_preview("why is x nil?"),
            PickerItem::new("def456  1h ago", "add a flag"),
        ];
        assert_eq!(filter_items(&items, ""), vec![0, 1]);
        assert_eq!(filter_items(&items, "PARSER"), vec![0]);
        assert_eq!(filter_items(&items, "def"), vec![1]);
        assert_eq!(
            filter_items(&items, "nil"),
            vec![0],
            "preview is searched too"
        );
        // Every whitespace-separated term must match, in any order.
        assert_eq!(filter_items(&items, "abc parser"), vec![0]);
        assert!(filter_items(&items, "abc flag").is_empty());
        assert!(filter_items(&items, "zzz").is_empty());
    }

    #[test]
    fn picker_item_new_stores_both_fields() {
        let item = PickerItem::new("alias", "vendor/slug");
        assert_eq!(item.label, "alias");
        assert_eq!(item.detail, "vendor/slug");
    }

    #[test]
    fn render_row_marks_the_selected_row_and_only_that_one() {
        let item = PickerItem::new("sess-1", "2m ago");
        let sel = render_row(&item, true);
        let unsel = render_row(&item, false);
        assert_ne!(sel, unsel);
        assert!(unsel.contains("sess-1"));
        assert!(sel.contains("sess-1"));
    }

    /// Under `cargo test`, stdin/stdout are captured pipes, never a real
    /// terminal — so `available()` is deterministically `false` here.
    /// This is itself the non-tty-gating proof for the process-global
    /// `is_terminal()` wrapper: see `crates/cli/tests/picker_available_cli.rs`
    /// for the real-binary-level, CI-enforced proof that a caller actually
    /// SKIPS the picker (and doesn't hang) when this is false, and
    /// `UX-30.md` for the real-PTY manual check that the picker DOES run
    /// (and DOES navigate/select) when it's true — the same split
    /// `hidden_input.rs` documents for the same reason (a safe in-process
    /// test can't repoint fd 0 at a pty without stomping process-global
    /// state shared with every other test running concurrently in this
    /// binary).
    #[test]
    fn available_is_false_under_the_test_harness() {
        assert!(!available());
    }
}