newt-tui 0.8.0

Newt-Agent TUI surfaces (ratatui): code mode + pilot mode
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
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
//! **One inline-panel driver, for every panel.**
//!
//! `/psyche` and `/backends` each carried their own event loop, and the two
//! were near-verbatim: the same `PanelRawGuard::enter`, the same terminal
//! build and `clear`, the same 250 ms `event::poll`, the same
//! `KeyEventKind::Press` filter, the same CONTROL extraction, the same
//! trailing `clear`, the same scoped-so-the-restore-lands-here comment. They
//! differed in exactly two things — **the key table** and **the outcome
//! type** — which is precisely what [`Screen::key`] and the caller's own
//! return value parameterize.
//!
//! That is the reuse discipline's own test, applied before adding a third
//! panel rather than after: a second implementation is warranted only when
//! the existing abstraction cannot be widened to cover the new case, and
//! nothing in either loop resisted this one. The measured hazard is in
//! CLAUDE.md — five spinners, four erase strategies, three animation clocks —
//! and a third copy of a raw-mode loop is how a `/settings` panel would have
//! inherited whatever the other two get wrong next.
//!
//! # What the driver owns, and what it must not
//!
//! It owns the terminal lifecycle: raw mode, the viewport, the repaint
//! cadence, and giving the terminal back. It owns no policy — no key means
//! anything here, and no panel's outcome is interpreted. A driver that
//! started deciding what Enter means would be back to one loop per panel,
//! wearing a shared name.
//!
//! # Where a panel draws
//!
//! Under the cockpit the presenter LENDS reserved rows on the real terminal
//! (`SurfaceRequest::Panel`), because fd 1 is a pty slave the cockpit is
//! capturing and a panel that draws there never reaches the screen. Off the
//! cockpit a panel takes the bottom rows of stdout as it always has. Both
//! arrive here as one `Option<&PanelWindow>`, so no panel implements that
//! choice twice.

use std::io;
use std::time::Duration;

use crossterm::event::{self, Event, KeyCode, KeyEventKind, KeyModifiers};
use newt_core::tty::raw_mode::RawModeGuard;

use crate::inline_viewport::InlineTerm;
use crate::modal_size::{ModalSize, SizeKey, MIN_ROWS};
use crate::panel_controls::{Controls, Effect};
use crate::session_worker::PanelWindow;

/// The component vocabulary is shared directly with NewtUI. Newt retains
/// event decoding and the terminal driver, and each panel interprets its own
/// close outcome.
pub(crate) use newtui::{Flow, Key};

/// Fold control into printable keys so a plain-character binding cannot fire
/// with control held. Preserve Newt's existing bindings: keys it did not bind
/// still arrive as `Other`, even if NewtUI names them for another host.
pub(crate) fn key_from_event(code: KeyCode, ctrl: bool) -> Key {
    match (code, ctrl) {
        (KeyCode::Char(c), true) => Key::Ctrl(c),
        (KeyCode::Char(c), false) => Key::Char(c),
        (KeyCode::Up, _) => Key::Up,
        (KeyCode::Down, _) => Key::Down,
        (KeyCode::Left, _) => Key::Left,
        (KeyCode::Right, _) => Key::Right,
        (KeyCode::Enter, _) => Key::Enter,
        (KeyCode::Esc, _) => Key::Esc,
        (KeyCode::Backspace, _) => Key::Backspace,
        (KeyCode::Tab, _) => Key::Tab,
        _ => Key::Other,
    }
}

/// A panel: something that draws itself and answers keys.
///
/// The whole surface a panel must implement to be driven. Note what is
/// ABSENT — no terminal, no raw mode, no poll interval, no repaint. A panel
/// that reached for those would be a second driver.
pub(crate) trait Screen {
    /// Render the current state into the panel's rows.
    fn draw(&self, frame: &mut ratatui::Frame);

    /// Handle one key press.
    fn key(&mut self, key: Key) -> Flow;
}

/// Restore the terminal on EVERY exit path of a panel — return, error, panic.
///
/// **RAII, not happy-path control flow**, and that distinction is the whole
/// point (#1889). Both panels used to call `enable_raw_mode()` and then
/// `disable_raw_mode()` as a STATEMENT after the loop closure. An error return
/// reached it; a **panic unwound straight past**, leaving the operator in a
/// shell with no echo and no line discipline — a session that looks broken,
/// recoverable only with `reset`.
///
/// `SplashScreenGuard`'s doc (#1411) enumerated the crate's raw-mode pairs and
/// called the splash "the only one with no guard at all". These two panels
/// were not in that count. This is the conversion.
///
/// The guard binds BEFORE the fallible call — the ordering
/// `AltScreenGuard::enter` pays for and `InlineGuard::enter` repeats: from that
/// point the restore is owed regardless of what the next line does.
///
/// `enter_panel_raw_mode_is_the_only_way_in` pins that neither panel reaches
/// past this type to crossterm; `panel_raw_mode_pty_test` proves the Drop
/// against a real tty, from a parent that outlives the panicking child.
///
/// **SUBSUMED onto [`RawModeGuard`] (#1905).** This owned raw mode and nothing
/// else, through crossterm's `enable_raw_mode`/`disable_raw_mode` — which keep
/// ONE process-global "mode prior to raw" and so restore to a fixed state
/// rather than to what this guard found. C2b (#1891) hit that as a live defect
/// in `InlineGuard`: an inner frame closing handed the terminal back to cooked
/// while the outer frame was still up. `RawModeGuard` captures the prior
/// termios at `enter` and restores exactly that, so nesting composes.
///
/// A newtype rather than a plain alias, because the panels' own tests and the
/// PTY child name this type, and because the doc above is about the panels.
///
/// Moved here from `config_panel` with the driver it belongs to, unchanged:
/// the guard is part of running a panel, and leaving it behind in one panel's
/// module while both panels used it was the same split this file closes.
pub(crate) struct PanelRawGuard {
    _raw: RawModeGuard,
}

impl PanelRawGuard {
    pub(crate) fn enter() -> io::Result<Self> {
        Ok(Self {
            _raw: RawModeGuard::enter()?,
        })
    }
}

/// #1950: through the ONE inline constructor, so a terminal that will not
/// answer `ESC[6n` anchors the panel instead of refusing to open it.
/// #1979: leases its rows with `OnCollision::Shift`. A panel opens while the
/// prompt viewport is live and bottom-pinned, so asking for the bottom rows
/// outright is #1977 — the panel drew and the prompt's next repaint erased its
/// body. Shifting mints the nearest free rows ABOVE the holder, which is the
/// anchor-above-the-prompt fix expressed as the mint's policy rather than as a
/// special case in the fallback.
/// Placed under the transcript when the terminal says where that is
/// (`inline_viewport::lease_below_transcript`), so the cursor comes back
/// there when the panel closes and the next line prints under the last one.
pub(crate) fn make_terminal(height: u16) -> io::Result<InlineTerm> {
    let lease =
        crate::inline_viewport::lease_below_transcript(height, newt_core::tty::OnCollision::Shift)?;
    crate::inline_viewport::inline_terminal(lease)
}

/// Lease `wanted` rows, or — when another surface holds what that needs —
/// the `granted` rows the panel already had, or, when a terminal shrink left
/// fewer free rows than that, the most that fit, down to [`MIN_ROWS`]. The
/// arbiter's refusal is the ownership rule: a panel never takes rows it was
/// not lent, and an ungrantable size change degrades the panel rather than
/// closing it. Only when not even `MIN_ROWS` is granted is the refusal an
/// error. Returns the terminal and the height it got. The lease-taker is
/// injected so the rule is tested against a fake arbiter.
fn relet<T>(
    granted: u16,
    wanted: u16,
    mut lease: impl FnMut(u16) -> io::Result<T>,
) -> io::Result<(T, u16)> {
    let refused = match lease(wanted) {
        Ok(terminal) => return Ok((terminal, wanted)),
        Err(error) => error,
    };
    for rows in (MIN_ROWS..=granted).rev().filter(|rows| *rows != wanted) {
        if let Ok(terminal) = lease(rows) {
            return Ok((terminal, rows));
        }
    }
    Err(refused)
}

/// The driver's one line over the panel's hint row (inside the bottom
/// border, past the scrollbar gutter) while a mode is live.
fn draw_overlay(frame: &mut ratatui::Frame, text: &str) {
    let area = frame.area();
    if area.height < 3 || area.width < 4 {
        return;
    }
    let line = ratatui::layout::Rect {
        x: area.x + 2,
        y: area.bottom() - 2,
        width: area.width - 3,
        height: 1,
    };
    frame.render_widget(ratatui::widgets::Clear, line);
    frame.render_widget(
        ratatui::widgets::Paragraph::new(text.to_string())
            .style(crate::theme::style(crate::theme::Role::Identity)),
        line,
    );
}

/// Erase the panel's own rows, and only those, then force a full repaint.
///
/// ratatui's `clear` on an inline viewport is `CUP(top)` + `ESC[J`: it erases
/// to the END OF THE SCREEN, taking the rows of whatever holds the space below
/// the panel (a `Refuse` lease on the bottom rows). The panel owns
/// `area.top()..area.bottom()` and nothing else.
fn clear_own_rows(terminal: &mut InlineTerm) -> io::Result<()> {
    use ratatui::backend::{Backend, ClearType};
    let area = terminal.get_frame().area();
    for y in area.top()..area.bottom() {
        let backend = terminal.backend_mut();
        backend.set_cursor_position(ratatui::layout::Position { x: 0, y })?;
        backend.clear_region(ClearType::CurrentLine)?;
    }
    // Both buffers reset (each swap resets the inactive one), so the next draw
    // repaints every cell, as `clear` guaranteed.
    terminal.swap_buffers();
    terminal.swap_buffers();
    Ok(())
}

/// What the driver does with one terminal event.
#[derive(Debug, PartialEq, Eq)]
enum Input {
    Key(Key),
    /// The terminal resized: measure the container again and redraw (#2571).
    Remeasure,
    /// The operator sized the modal: Shift-↑/↓, or Ctrl-Z to zoom.
    Size(SizeKey),
    /// A mouse event, for a drag of the panel's top border.
    Mouse(crossterm::event::MouseEvent),
    Ignore,
}

/// Pure, so the rule that a resize is never dropped is pinned without a tty.
fn classify(event: Event) -> Input {
    match event {
        // Release and Repeat are not presses. Without this filter a terminal
        // that reports both delivers every key twice.
        Event::Key(key) if key.kind != KeyEventKind::Press => Input::Ignore,
        // The sizing keys belong to the driver, not the panel: every modal
        // sizes the same way. None of them was a panel key — Shift-↑/↓ reached
        // panels as plain ↑/↓, and no panel binds Ctrl-Z. (Ctrl-↑/↓ would
        // have collided with macOS Mission Control.)
        Event::Key(key)
            if key.modifiers.contains(KeyModifiers::SHIFT) && key.code == KeyCode::Up =>
        {
            Input::Size(SizeKey::Grow)
        }
        Event::Key(key)
            if key.modifiers.contains(KeyModifiers::SHIFT) && key.code == KeyCode::Down =>
        {
            Input::Size(SizeKey::Shrink)
        }
        Event::Key(key)
            if key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('z') =>
        {
            Input::Size(SizeKey::Zoom)
        }
        Event::Key(key) => Input::Key(key_from_event(
            key.code,
            key.modifiers.contains(KeyModifiers::CONTROL),
        )),
        Event::Resize(..) => Input::Remeasure,
        Event::Mouse(mouse) => Input::Mouse(mouse),
        _ => Input::Ignore,
    }
}

/// Run `screen` until it closes, and report whether the operator applied.
///
/// The raw-mode guard is scoped so its restore lands where the original bare
/// statement did. An error mid-loop returns `Err` with the guard already
/// dropped and the terminal handed back — the caller keeps whatever state its
/// screen accumulated, which is how `backend_panel` still reports file
/// operations that committed before a terminal failure.
///
/// # Errors
///
/// The terminal could not be taken, built, polled, read or repainted.
pub(crate) fn drive(
    screen: &mut dyn Screen,
    height: u16,
    window: Option<&PanelWindow>,
) -> io::Result<bool> {
    let mut applied = false;
    let loop_result = {
        let _raw = PanelRawGuard::enter()?;
        (|| -> io::Result<()> {
            let mut size = ModalSize::new(height);
            let mut terminal = match window {
                Some(window) => window.terminal()?,
                None => make_terminal(size.requested())?,
            };
            let mut controls = Controls::new(crate::prefix::current());
            // Drag-capable mouse capture for as long as the panel is open, on
            // the REAL terminal (under the cockpit, stdout is its capture pty).
            #[cfg(unix)]
            let _mouse = crate::mouse::MouseCaptureGuard::enable_drag(match window {
                Some(window) => crate::mouse::MouseSink::Tty(window.output()?),
                None => crate::mouse::MouseSink::Stdout,
            });
            clear_own_rows(&mut terminal)?;
            loop {
                let overlay = controls.overlay();
                terminal.draw(|f| {
                    screen.draw(f);
                    if let Some(text) = &overlay {
                        draw_overlay(f, text);
                    }
                })?;
                // A poll rather than a blocking read: the panel repaints on a
                // cadence so a status line or a spinner can change without a
                // keypress, and a timed-out poll is not an event.
                if !event::poll(Duration::from_millis(250))? {
                    continue;
                }
                // `Some(rows)`: lay out again at a new requested height;
                // `Some(None)`: again at the same request (a terminal resize).
                let area = window.map_or_else(|| terminal.get_frame().area(), PanelWindow::area);
                let effect = match classify(event::read()?) {
                    Input::Key(key) => controls.key(key),
                    Input::Mouse(mouse) => controls.mouse(mouse, area),
                    Input::Size(key) => Effect::Size(key),
                    Input::Remeasure => Effect::Redraw,
                    Input::Ignore => Effect::Nothing,
                };
                let relayout = match effect {
                    Effect::Forward(key) => {
                        if let Flow::Close(apply) = screen.key(key) {
                            applied = apply;
                            break;
                        }
                        None
                    }
                    // #2571: a panel never owns its size. The container is
                    // measured again — by the presenter that lent the rows, or
                    // by a fresh bottom-rows lease — and the region is cleared,
                    // so a narrower terminal leaves no stale cells behind.
                    // A terminal resize and a redraw lay out again at the same
                    // request; a size change at a new one.
                    Effect::Redraw => Some(None),
                    Effect::Size(key) => size.apply(key, area.height).map(Some),
                    Effect::Nothing => None,
                };
                if let Some(rows) = relayout {
                    terminal = match window {
                        Some(window) => {
                            window.remeasure(rows);
                            window.terminal()?
                        }
                        None => {
                            let granted = terminal.get_frame().area().height;
                            // Release the old lease first: under
                            // `OnCollision::Shift` a new one taken while it is
                            // held would be minted ABOVE it.
                            drop(terminal);
                            let (terminal, got) = relet(granted, size.requested(), make_terminal)?;
                            // An ungrantable grow/zoom kept the old rows: the
                            // size state follows what was actually granted.
                            if got != size.requested() {
                                size = ModalSize::new(got);
                            }
                            terminal
                        }
                    };
                    clear_own_rows(&mut terminal)?;
                }
            }
            clear_own_rows(&mut terminal)?;
            Ok(())
        })()
    };
    loop_result.map(|()| applied)
}

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

    /// #2573 review: with a row holder in the way, an ungrantable size keeps
    /// the panel at the rows it had — it neither closes nor takes more.
    #[test]
    fn an_ungrantable_lease_keeps_the_panel_at_its_granted_rows() {
        // A fake arbiter: 12 free rows above a holder of the bottom rows.
        let free = 12;
        let asked = std::cell::RefCell::new(Vec::new());
        let mut arbiter = |rows: u16| {
            asked.borrow_mut().push(rows);
            if rows <= free {
                Ok(rows)
            } else {
                Err(io::Error::other("another surface already owns these rows"))
            }
        };
        assert_eq!(relet(8, 10, &mut arbiter).unwrap(), (10, 10), "grantable");
        assert_eq!(
            relet(8, 20, &mut arbiter).unwrap(),
            (8, 8),
            "kept, not closed"
        );
        assert_eq!(
            *asked.borrow(),
            vec![10, 20, 8],
            "the fallback asks the arbiter too"
        );
        // #2573 hardening: a shrink that leaves fewer free rows than the panel
        // had degrades to what fits; it does not close the panel.
        assert_eq!(
            relet(20, 20, &mut arbiter).unwrap(),
            (12, 12),
            "degrades to the free rows"
        );
        let mut five_free = |rows: u16| {
            if rows <= 5 {
                Ok(rows)
            } else {
                Err(io::Error::other("another surface already owns these rows"))
            }
        };
        assert_eq!(relet(7, 7, &mut five_free).unwrap(), (5, 5));
        let mut none_free = |rows: u16| -> io::Result<u16> {
            let _ = rows;
            Err(io::Error::other("another surface already owns these rows"))
        };
        assert!(
            relet(7, 7, &mut none_free).is_err(),
            "not even MIN_ROWS fits: the only error"
        );
    }

    /// Grounds the fake arbiter above in the real one: a holder of the bottom
    /// rows (a prompt viewport, say) makes a full-screen lease ungrantable, and
    /// `relet` keeps the smaller lease `Shift` can mint above the holder.
    #[test]
    #[serial_test::serial(tty_arbiter)]
    fn with_a_real_row_holder_relet_keeps_what_the_arbiter_grants() {
        use newt_core::tty::{OnCollision, Region, Terminal};
        let screen =
            ratatui::backend::Backend::size(&ratatui::backend::CrosstermBackend::new(io::stdout()))
                .map_or(24, |size| size.height);
        let holder = Terminal::lease_region(
            Region::Rows {
                top: screen - 3,
                height: 3,
            },
            OnCollision::Refuse,
        )
        .expect("the holder takes the bottom rows");
        let lease = |rows| crate::inline_viewport::lease_bottom_rows(rows, OnCollision::Shift);
        assert!(
            lease(screen).is_err(),
            "the whole screen overlaps the holder"
        );
        let (_kept, rows) = relet(6, screen, lease).expect("falls back, stays open");
        assert_eq!(rows, 6);
        // #2574: a zoom asks for all of it; the holder still wins.
        let (_kept, rows) = relet(6, crate::modal_size::FILL, lease).expect("zoom falls back");
        assert_eq!(rows, 6);
        drop(holder);
    }

    /// #2571: the regression this pins is a panel frozen at its opening size
    /// because `drive` read keys only and dropped `Event::Resize`.
    #[test]
    fn a_resize_is_never_dropped_and_only_presses_are_keys() {
        use crossterm::event::{KeyEvent, KeyEventState};
        assert_eq!(classify(Event::Resize(80, 24)), Input::Remeasure);
        assert_eq!(classify(Event::Resize(1, 1)), Input::Remeasure);
        let key = |kind| {
            Event::Key(KeyEvent {
                code: KeyCode::Char('j'),
                modifiers: KeyModifiers::NONE,
                kind,
                state: KeyEventState::NONE,
            })
        };
        assert_eq!(
            classify(key(KeyEventKind::Press)),
            Input::Key(Key::Char('j'))
        );
        assert_eq!(classify(key(KeyEventKind::Release)), Input::Ignore);
        assert_eq!(classify(key(KeyEventKind::Repeat)), Input::Ignore);
        assert_eq!(classify(Event::FocusGained), Input::Ignore);
    }

    /// The modal sizing keys are the driver's, and plain arrows stay the
    /// panel's (they scroll and select).
    #[test]
    fn shift_arrows_size_the_modal_and_ctrl_z_zooms() {
        use crossterm::event::{KeyEvent, KeyEventState};
        let press = |code, modifiers| {
            Event::Key(KeyEvent {
                code,
                modifiers,
                kind: KeyEventKind::Press,
                state: KeyEventState::NONE,
            })
        };
        assert_eq!(
            classify(press(KeyCode::Up, KeyModifiers::SHIFT)),
            Input::Size(SizeKey::Grow)
        );
        assert_eq!(
            classify(press(KeyCode::Down, KeyModifiers::SHIFT)),
            Input::Size(SizeKey::Shrink)
        );
        assert_eq!(
            classify(press(KeyCode::Char('z'), KeyModifiers::CONTROL)),
            Input::Size(SizeKey::Zoom)
        );
        assert_eq!(
            classify(press(KeyCode::Up, KeyModifiers::NONE)),
            Input::Key(Key::Up)
        );
        assert_eq!(
            classify(press(KeyCode::Char('z'), KeyModifiers::NONE)),
            Input::Key(Key::Char('z'))
        );
    }

    /// **The structural half of #1889.** The PTY test proves `PanelRawGuard`
    /// restores; this proves the panels go through it.
    ///
    /// Without it the two tests together are still vacuous in the way that
    /// matters: a guard can be correct and unused, which is exactly the state
    /// these files were in before — `enable_raw_mode()` called directly, the
    /// restore a statement a panic skips. Counted over the source because the
    /// property is "no other path exists", and absence is not observable by
    /// calling something.
    #[test]
    fn enter_panel_raw_mode_is_the_only_way_in() {
        // PRODUCTION code only, and not merely for tidiness: this test lives
        // IN config_panel.rs, so `include_str!` pulls in its own needles and
        // the first run read 2 enables where there is one. Cutting at the
        // test module is also the right scope — the property is that no
        // production path reaches raw mode except through the guard.
        //
        // #1898 hardened the cut: the version that shipped here split at the
        // FIRST `#[cfg(test)]` anywhere and fell back to "" when it found
        // none. `rich_input.rs` has an inline one 700 lines early, and "" makes
        // every `count() == 0` assertion pass having read nothing.
        // All THREE files now: the guard moved here with the driver, and the
        // property — no production path reaches raw mode except through it —
        // is only meaningful if the panels are scanned too.
        let driver = crate::production_source(include_str!("panel.rs"));
        let config = crate::production_source(include_str!("config_panel.rs"));
        let backend = crate::production_source(include_str!("backend_panel.rs"));
        // Count CALL forms, not the name: the guard's own doc comment
        // discusses `enable_raw_mode()` and `disable_raw_mode()` in prose, and
        // a test that counted mentions would move every time someone edited a
        // comment — noise that trains people to adjust the number.
        // #1905 SUBSUMED the raw half onto `RawModeGuard`, so the count that
        // was "exactly one" is now "none" in BOTH files. The one nesting-aware
        // owner lives in newt-core; a bare crossterm call reappearing here
        // would be a second owner restoring to a fixed state rather than to
        // what it found — the defect C2b hit in `InlineGuard`.
        // COMMENTS STRIPPED, not call-shapes matched. The original counted
        // `enable_raw_mode()?` exactly because the guard's own doc discusses
        // both names in prose — and that doc now lives in THIS file, so a
        // bare-name count reads its own explanation as a violation. Dropping
        // comment lines first says what is actually meant ("no call, in any
        // form"), and stops a future edit to the prose from moving a number.
        let code_only = |source: &str| -> String {
            source
                .lines()
                .filter(|line| !line.trim_start().starts_with("//"))
                .collect::<Vec<_>>()
                .join("\n")
        };
        for (name, source) in [
            ("panel", &driver),
            ("config_panel", &config),
            ("backend_panel", &backend),
        ] {
            let code = code_only(source);
            assert_eq!(
                code.matches("enable_raw_mode(").count(),
                0,
                "{name}: raw mode comes from RawModeGuard, never crossterm directly"
            );
            assert_eq!(
                code.matches("disable_raw_mode(").count(),
                0,
                "{name}: a bare disable means a restore that a panic skips"
            );
        }
        assert!(
            driver.contains("_raw: RawModeGuard"),
            "PanelRawGuard must HOLD a RawModeGuard — composition, not a \
             reimplementation"
        );
        // And the loop itself is gone from both panels: a panel that grew its
        // own `event::poll` back would be the third copy this file removed.
        for (name, source) in [("config_panel", &config), ("backend_panel", &backend)] {
            assert_eq!(
                source.matches("event::poll(").count(),
                0,
                "{name}: the event loop belongs to panel::drive"
            );
        }
        // The guard itself must still be a Drop obligation. A guard whose
        // restore moved into an inherent method would satisfy every count
        // above and leak on unwind again.
        // No `impl Drop for PanelRawGuard` any more, and its absence is the
        // point: the restore is the FIELD's, so there is nothing here to
        // forget. A hand-written Drop reappearing would mean a second restore
        // racing the field's.
        assert!(
            !driver.contains("impl Drop for PanelRawGuard"),
            "the restore is RawModeGuard's; a Drop impl here would be a second one"
        );
    }

    /// A screen that records what it was asked and closes on demand — no
    /// terminal, so the DISPATCH is testable without a TTY even though
    /// [`drive`] itself is not.
    #[derive(Default)]
    struct Recorder {
        seen: Vec<Key>,
        close_on: Option<(Key, bool)>,
    }

    impl Screen for Recorder {
        fn draw(&self, _frame: &mut ratatui::Frame) {}

        fn key(&mut self, key: Key) -> Flow {
            self.seen.push(key);
            match self.close_on {
                Some((c, applied)) if c == key => Flow::Close(applied),
                _ => Flow::Stay,
            }
        }
    }

    /// A component's vocabulary crosses the host boundary unchanged. A local
    /// replacement enum would make these assignments stop compiling.
    #[test]
    fn screens_accept_newtui_keys_and_return_newtui_flow_directly() {
        let mut screen = Recorder {
            close_on: Some((Key::Enter, true)),
            ..Recorder::default()
        };
        let key: newtui::Key = Key::Enter;
        let flow: newtui::Flow = screen.key(key);
        assert_eq!(flow, newtui::Flow::Close(true));
    }

    /// **A plain-character binding cannot fire with control held.**
    ///
    /// The whole reason this vocabulary exists. Four key tables previously
    /// answered this differently — two guarded `Char(c) if !ctrl`, one did not
    /// guard its command line (so Ctrl-S typed a literal `s` into the line
    /// Ctrl-S opens), and one discarded the flag entirely (so Ctrl-Q
    /// cancelled). Folding control into the key makes the wrong reading
    /// inexpressible instead of guarded eight times.
    #[test]
    fn control_is_folded_into_the_key_rather_than_carried_beside_it() {
        assert_eq!(key_from_event(KeyCode::Char('q'), false), Key::Char('q'));
        assert_eq!(key_from_event(KeyCode::Char('q'), true), Key::Ctrl('q'));
        assert_ne!(
            key_from_event(KeyCode::Char('s'), true),
            Key::Char('s'),
            "Ctrl-S must not be readable as a plain `s`"
        );
        // A non-character key ignores the modifier: no panel binds Ctrl-Up,
        // and inventing a distinction nothing uses would grow the vocabulary
        // for nothing.
        assert_eq!(key_from_event(KeyCode::Up, true), Key::Up);
        assert_eq!(key_from_event(KeyCode::Esc, true), Key::Esc);
        // Anything unbound arrives as one arm a table matches once.
        for code in [
            KeyCode::F(7),
            KeyCode::Delete,
            KeyCode::Insert,
            KeyCode::BackTab,
            KeyCode::Home,
            KeyCode::End,
            KeyCode::PageUp,
            KeyCode::PageDown,
            KeyCode::Null,
        ] {
            assert_eq!(key_from_event(code, false), Key::Other);
            assert_eq!(key_from_event(code, true), Key::Other);
        }
    }

    /// `Flow` says one thing, and a panel cannot accidentally say it by
    /// returning a bare bool from `key` — the two arms are not both `bool`.
    #[test]
    fn a_close_carries_whether_the_operator_applied() {
        let mut screen = Recorder {
            close_on: Some((Key::Enter, true)),
            ..Recorder::default()
        };
        assert_eq!(screen.key(Key::Up), Flow::Stay);
        assert_eq!(screen.key(Key::Enter), Flow::Close(true));

        let mut cancelled = Recorder {
            close_on: Some((Key::Esc, false)),
            ..Recorder::default()
        };
        assert_eq!(cancelled.key(Key::Esc), Flow::Close(false));
        assert_eq!(
            cancelled.seen,
            vec![Key::Esc],
            "the screen sees the key it closed on"
        );
    }

    /// Control reaches the screen as part of the key, so a table that binds
    /// `Char('s')` and one that binds `Ctrl('s')` are reading two things.
    #[test]
    fn the_screen_is_told_about_control() {
        let mut screen = Recorder::default();
        screen.key(Key::Ctrl('s'));
        screen.key(Key::Char('s'));
        assert_eq!(screen.seen, vec![Key::Ctrl('s'), Key::Char('s')]);
    }
}