linesmith 0.1.3

A Rust status line for Claude Code and other AI coding CLIs
Documentation
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
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
//! Main Menu screen: top-level navigation per ADR-0016.
//!
//! Renders seven rows (Edit Lines, Edit Colors, Powerline Setup,
//! Terminal Options, Global Overrides, Install to Claude Code,
//! Exit) through the shared [`super::list_screen`] widget. Enter
//! on any non-Exit row navigates to a placeholder; Enter on Exit
//! quits. Esc on this screen also quits — sub-screens use Esc for
//! back-navigation, so the top-level handler is the only place
//! Esc shortcut-quits.

use std::borrow::Cow;
use std::mem;

use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use ratatui::layout::Rect;
use ratatui::Frame;

use linesmith_core::theme::ThemeRegistry;

use crate::config::{Config, LayoutMode};

use super::app::{AppScreen, ScreenOutcome};
use super::install_screen::InstallScreenState;
use super::items_editor::{ItemsEditorPrev, ItemsEditorState, LineKey};
use super::line_picker::LinePickerState;
use super::list_screen::{
    self, ListOutcome, ListRowData, ListScreenState, ListScreenView, VerbHint,
};
use super::placeholder::PlaceholderState;
use super::theme_picker::ThemePickerState;

#[derive(Debug, Default, Clone)]
pub(super) struct MainMenuState {
    list: ListScreenState,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum MainMenuItem {
    EditLines,
    EditColors,
    PowerlineSetup,
    TerminalOptions,
    GlobalOverrides,
    InstallToClaudeCode,
    Exit,
}

impl MainMenuItem {
    fn label(self) -> &'static str {
        match self {
            Self::EditLines => "Edit Lines",
            Self::EditColors => "Edit Colors",
            Self::PowerlineSetup => "Powerline Setup",
            Self::TerminalOptions => "Terminal Options",
            Self::GlobalOverrides => "Global Overrides",
            Self::InstallToClaudeCode => "Install to Claude Code",
            Self::Exit => "Exit",
        }
    }

    fn description(self) -> &'static str {
        match self {
            Self::EditLines => "Add, remove, and reorder segments",
            Self::EditColors => "Customize colors per segment or via theme",
            Self::PowerlineSetup => "Configure powerline-style separators",
            Self::TerminalOptions => "Terminal width detection and color level",
            Self::GlobalOverrides => "Engine knobs (Inherit Colors, Bold, etc.)",
            Self::InstallToClaudeCode => "Wire linesmith into Claude Code settings",
            Self::Exit => "Quit the configuration editor",
        }
    }
}

/// Display order. Index is the cursor position; the slice and the
/// [`MainMenuItem`] enum are paired sources of truth, pinned by a
/// test that asserts the slice equals an explicit literal.
const MENU_ITEMS: &[MainMenuItem] = &[
    MainMenuItem::EditLines,
    MainMenuItem::EditColors,
    MainMenuItem::PowerlineSetup,
    MainMenuItem::TerminalOptions,
    MainMenuItem::GlobalOverrides,
    MainMenuItem::InstallToClaudeCode,
    MainMenuItem::Exit,
];

/// Drive the menu through the shared list widget. Esc and the
/// `Exit` row both quit; every other row navigates to a placeholder.
///
/// `Action(_)` and `MoveSwap` are unreachable given the
/// configuration (`verbs = &[]`, `move_mode_supported = false`);
/// they fall through to `unreachable!` so a misconfiguration that
/// would silently swallow keypresses fails loudly instead.
pub(super) fn update(
    state: &mut MainMenuState,
    config: &Config,
    theme_registry: &ThemeRegistry,
    install_ctx: InstallContext<'_>,
    key: KeyEvent,
) -> ScreenOutcome {
    if key.modifiers == KeyModifiers::NONE && key.code == KeyCode::Esc {
        return ScreenOutcome::Quit;
    }
    match list_screen::handle_key(&mut state.list, key, MENU_ITEMS.len(), &[], false) {
        ListOutcome::Activate => activate(state, config, theme_registry, install_ctx),
        ListOutcome::Consumed | ListOutcome::Unhandled => ScreenOutcome::Stay,
        outcome @ (ListOutcome::Action(_) | ListOutcome::MoveSwap { .. }) => {
            unreachable!(
                "main menu: list_screen returned {outcome:?} despite verbs=&[] \
                 and move_mode_supported=false; update this dispatch arm if \
                 those args changed",
            )
        }
    }
}

/// Pre-resolved install state passed through to the InstallToClaudeCode
/// row's activate path. Bundles the two values so the dispatch signature
/// doesn't grow another pair every time a new context-dependent screen
/// lands.
#[derive(Debug, Clone, Copy)]
pub(super) struct InstallContext<'a> {
    pub settings_path: Option<&'a std::path::Path>,
    pub install_command: &'a str,
}

/// Resolve the highlighted menu item to a `ScreenOutcome`. Exit
/// short-circuits to `Quit`; every other item packs the current
/// state into a `Placeholder` so Esc back-nav can restore the
/// cursor row.
///
/// The cursor is always in range here: `handle_key` clamps it
/// before returning `Activate`.
fn activate(
    state: &mut MainMenuState,
    config: &Config,
    theme_registry: &ThemeRegistry,
    install_ctx: InstallContext<'_>,
) -> ScreenOutcome {
    debug_assert!(
        state.list.cursor() < MENU_ITEMS.len(),
        "list_screen::handle_key must clamp the cursor before Activate",
    );
    let item = MENU_ITEMS[state.list.cursor()];
    if matches!(item, MainMenuItem::Exit) {
        return ScreenOutcome::Quit;
    }
    // `mem::take` swaps the in-place state for a default that the
    // caller's `NavigateTo` immediately overwrites. The defaulted
    // MainMenuState is never observable: `app::update` applies the
    // outcome synchronously before the event loop yields back to
    // `view`, so no render path can see it.
    let prev = mem::take(state);
    match item {
        // Single-line configs go straight to the items editor with
        // `LineKey::Single`. Multi-line configs route through the
        // line picker so the user picks which `[line.N]` to edit.
        // `_` covers any future `#[non_exhaustive]` variant.
        MainMenuItem::EditLines => match config.layout {
            // Mirror `build_lines`'s auto-promotion: when the user
            // has `[line.N]` sub-tables but no `[line].segments`
            // array (and no explicit `layout = "multi-line"`), the
            // runtime renders the numbered lines. Editing the
            // empty `[line].segments` here would let the user
            // change a line set the renderer doesn't read; route
            // to the picker instead so the editor and renderer
            // stay in sync.
            LayoutMode::SingleLine if multi_line_auto_promotes(config) => {
                // Surface the layout mismatch so a user who
                // explicitly typed `segments = []` to test single-
                // line behavior knows the editor sided with the
                // numbered tables (and matches what `build_lines`
                // renders). Without this, the screen swap is silent
                // and looks like an editor bug.
                linesmith_core::lsm_debug!(
                    "main menu: auto-promoted to multi-line picker — `[line].segments` is empty and `[line.N]` sub-tables are present",
                );
                ScreenOutcome::NavigateTo(AppScreen::LinePicker(LinePickerState::new(prev)))
            }
            LayoutMode::SingleLine => ScreenOutcome::NavigateTo(AppScreen::ItemsEditor(
                ItemsEditorState::new(LineKey::Single, ItemsEditorPrev::MainMenu(prev)),
            )),
            LayoutMode::MultiLine => {
                ScreenOutcome::NavigateTo(AppScreen::LinePicker(LinePickerState::new(prev)))
            }
            _ => ScreenOutcome::NavigateTo(AppScreen::Placeholder(PlaceholderState::new(
                MainMenuItem::EditLines.label(),
                prev,
            ))),
        },
        MainMenuItem::EditColors => {
            // Theme picker. v0.1 ships theme selection only;
            // per-segment color overrides land in a future "Edit
            // Colors" mode. Until then, this row is the theme-
            // switching surface.
            let current = config.theme.as_deref().unwrap_or("default");
            ScreenOutcome::NavigateTo(AppScreen::ThemePicker(ThemePickerState::new(
                prev,
                theme_registry,
                current,
            )))
        }
        MainMenuItem::InstallToClaudeCode => {
            if let Some(settings_path) = install_ctx.settings_path {
                ScreenOutcome::NavigateTo(AppScreen::InstallToClaudeCode(InstallScreenState::new(
                    prev,
                    settings_path.to_path_buf(),
                    install_ctx.install_command.to_string(),
                )))
            } else {
                // $HOME unset → no settings path resolves. Surface
                // through the Placeholder so the user sees the
                // menu row resolve to something rather than
                // silently no-op.
                ScreenOutcome::NavigateTo(AppScreen::Placeholder(PlaceholderState::new(
                    MainMenuItem::InstallToClaudeCode.label(),
                    prev,
                )))
            }
        }
        other => ScreenOutcome::NavigateTo(AppScreen::Placeholder(PlaceholderState::new(
            other.label(),
            prev,
        ))),
    }
}

/// Mirrors the auto-promotion rule in
/// `linesmith_core::segments::builder::build_lines`: when a config
/// has `[line.N]` sub-tables but no `[line].segments` array, the
/// runtime renders the numbered lines even without an explicit
/// `layout = "multi-line"` declaration. The editor must follow the
/// same rule so EditLines opens the screen that maps to what's
/// actually being rendered.
fn multi_line_auto_promotes(config: &Config) -> bool {
    config
        .line
        .as_ref()
        .is_some_and(|l| l.segments.is_empty() && !l.numbered.is_empty())
}

pub(super) fn view(state: &MainMenuState, frame: &mut Frame, area: Rect) {
    let row_data: Vec<ListRowData<'static>> = MENU_ITEMS
        .iter()
        .map(|item| ListRowData {
            label: Cow::Borrowed(item.label()),
            description: Cow::Borrowed(item.description()),
        })
        .collect();
    let verbs: [VerbHint<'_>; 0] = [];
    let view = ListScreenView {
        title: " linesmith config ",
        rows: &row_data,
        verbs: &verbs,
        move_mode_supported: false,
    };
    list_screen::render(&state.list, &view, area, frame);
}

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

    fn key(code: KeyCode) -> KeyEvent {
        KeyEvent::new(code, KeyModifiers::NONE)
    }

    fn key_mod(code: KeyCode, mods: KeyModifiers) -> KeyEvent {
        KeyEvent::new(code, mods)
    }

    /// Built-in-only registry; routing tests don't exercise theme content.
    fn registry() -> ThemeRegistry {
        ThemeRegistry::with_built_ins()
    }

    /// Inert install context for routing tests that don't exercise the
    /// InstallToClaudeCode arm. `None` settings_path routes that row
    /// to a Placeholder (the "$HOME unset" fallback).
    fn no_install_ctx() -> InstallContext<'static> {
        InstallContext {
            settings_path: None,
            install_command: "linesmith",
        }
    }

    #[test]
    fn esc_quits() {
        let mut state = MainMenuState::default();
        let outcome = update(
            &mut state,
            &Config::default(),
            &registry(),
            no_install_ctx(),
            key(KeyCode::Esc),
        );
        assert!(matches!(outcome, ScreenOutcome::Quit));
    }

    #[test]
    fn esc_with_modifier_does_not_quit() {
        // Mirror of placeholder's `esc_with_modifier_does_not_back_navigate`.
        // The strict `key.modifiers == NONE` gate is intentional —
        // chord Esc variants should fall through to the list widget
        // (which treats them as `Unhandled`) rather than quit. A
        // future change to `(KeyCode::Esc, _)` would silently quit
        // on Shift+Esc / Ctrl+Esc; this test makes that change a
        // deliberate edit. The cursor assertion pins the full
        // no-op contract so a regression that mutates cursor state
        // mid-fall-through still fails.
        for mods in [KeyModifiers::SHIFT, KeyModifiers::CONTROL] {
            let mut state = MainMenuState::default();
            let outcome = update(
                &mut state,
                &Config::default(),
                &registry(),
                no_install_ctx(),
                key_mod(KeyCode::Esc, mods),
            );
            assert!(
                matches!(outcome, ScreenOutcome::Stay),
                "mods={mods:?} should fall through to Stay, got {outcome:?}",
            );
            assert_eq!(state.list.cursor(), 0, "mods={mods:?} cursor moved");
        }
    }

    #[test]
    fn menu_items_matches_expected_layout() {
        // Pin `MENU_ITEMS` to the literal slice so any drift —
        // adding a variant, removing one, reordering, duplicating
        // — becomes a deliberate edit to this test. Iterating
        // `MENU_ITEMS` and pattern-matching each item only catches
        // variants already in the slice; equality against the
        // literal is the structural pin.
        assert_eq!(
            MENU_ITEMS,
            &[
                MainMenuItem::EditLines,
                MainMenuItem::EditColors,
                MainMenuItem::PowerlineSetup,
                MainMenuItem::TerminalOptions,
                MainMenuItem::GlobalOverrides,
                MainMenuItem::InstallToClaudeCode,
                MainMenuItem::Exit,
            ],
        );
    }

    #[test]
    fn cursor_preserved_across_activate_esc_activate_round_trip() {
        // Walk Activate → (placeholder) → Esc-back → Activate
        // again and pin that the second placeholder carries the
        // same cursor as the first. Catches a regression that
        // resets the MainMenuState on Esc back-nav — most likely
        // shape would be replacing the `mem::take` round-trip
        // with a fresh `MainMenuState::default()` somewhere along
        // the back-nav path.
        use super::super::app::{update as app_update, AppScreen, Event};
        let mut model = super::super::app::Model::new(
            crate::config::Config::default(),
            toml_edit::DocumentMut::new(),
            String::new(),
            None,
            crate::theme::default_theme().clone(),
            registry(),
            crate::theme::Capability::None,
            None,
            None,
            "linesmith".to_string(),
        );
        // Down twice → cursor on row 2 (Powerline Setup).
        model = app_update(model, Event::Key(key(KeyCode::Down)));
        model = app_update(model, Event::Key(key(KeyCode::Down)));
        // Activate → Placeholder.
        model = app_update(model, Event::Key(key(KeyCode::Enter)));
        let cursor_first = match &model.screen {
            AppScreen::Placeholder(p) => {
                assert_eq!(p.name, "Powerline Setup");
                p.prev.list.cursor()
            }
            other => panic!("expected Placeholder after first activate, got {other:?}"),
        };
        assert_eq!(cursor_first, 2);
        // Esc → MainMenu. Pin the cursor on the restored MainMenu
        // *before* the second Activate, so a regression that
        // resets cursor here fails this assertion directly rather
        // than getting masked by the subsequent name-mismatch.
        model = app_update(model, Event::Key(key(KeyCode::Esc)));
        match &model.screen {
            AppScreen::MainMenu(state) => {
                assert_eq!(state.list.cursor(), 2, "cursor must survive Esc back-nav",)
            }
            other => panic!("expected MainMenu after Esc, got {other:?}"),
        }
        // Second Activate → Placeholder with the same cursor packed
        // into prev. Confirms the dispatch chain wires the restored
        // cursor through to a fresh placeholder.
        model = app_update(model, Event::Key(key(KeyCode::Enter)));
        match &model.screen {
            AppScreen::Placeholder(p) => {
                assert_eq!(p.name, "Powerline Setup");
                assert_eq!(p.prev.list.cursor(), 2);
            }
            other => panic!("expected Placeholder on second activate, got {other:?}"),
        }
    }

    #[test]
    fn edit_lines_on_multi_line_layout_routes_to_line_picker() {
        // Multi-line layouts render `[line.N]`, not `[line]`, so the
        // user picks which line to edit before the items editor
        // opens. Pin the screen variant AND that the previous menu
        // state round-trips through `mem::take` so Esc back-nav
        // restores the EditLines row.
        let mut state = MainMenuState::default();
        let cfg = Config {
            layout: LayoutMode::MultiLine,
            ..Config::default()
        };
        let outcome = update(
            &mut state,
            &cfg,
            &registry(),
            no_install_ctx(),
            key(KeyCode::Enter),
        );
        match outcome {
            ScreenOutcome::NavigateTo(AppScreen::LinePicker(p)) => {
                assert_eq!(
                    p.prev.list.cursor(),
                    0,
                    "prev MainMenu cursor must round-trip for Esc back-nav",
                );
            }
            other => panic!("expected LinePicker(Edit Lines), got {other:?}"),
        }
    }

    #[test]
    fn enter_on_default_cursor_navigates_to_items_editor() {
        // Default cursor is row 0 = "Edit Lines", which routes to
        // the items editor on a single-line layout. Constructing
        // the config explicitly (rather than relying on
        // `Config::default()`'s `LayoutMode::default()`) defends
        // against a future `#[default]` flip silently shifting the
        // test's meaning to "default-config routes to ItemsEditor"
        // instead of "single-line routes to ItemsEditor".
        let mut state = MainMenuState::default();
        let cfg = Config {
            layout: LayoutMode::SingleLine,
            ..Config::default()
        };
        let outcome = update(
            &mut state,
            &cfg,
            &registry(),
            no_install_ctx(),
            key(KeyCode::Enter),
        );
        match outcome {
            ScreenOutcome::NavigateTo(AppScreen::ItemsEditor(s)) => {
                assert_eq!(s.line(), super::super::items_editor::LineKey::Single);
            }
            other => panic!("expected ItemsEditor(Single), got {other:?}"),
        }
    }

    #[test]
    fn edit_lines_auto_promotes_to_line_picker_when_numbered_tables_present() {
        // A config with `[line.1]` sub-tables but no explicit
        // `layout = "multi-line"` is auto-promoted to multi-line by
        // `build_lines`. Editing through the single-line items
        // editor would let the user mutate the empty `[line].segments`
        // array — a different surface than what the renderer reads.
        // Pin that EditLines opens the picker in this case so editor
        // and renderer stay in sync.
        use crate::config::{LineConfig, LineEntry};
        use std::collections::BTreeMap;
        let mut numbered = BTreeMap::new();
        let mut line_one = toml::value::Table::new();
        line_one.insert("segments".to_string(), toml::Value::Array(vec![]));
        numbered.insert("1".to_string(), toml::Value::Table(line_one));
        let cfg = Config {
            layout: LayoutMode::SingleLine,
            line: Some(LineConfig {
                segments: Vec::<LineEntry>::new(),
                numbered,
            }),
            ..Config::default()
        };
        let mut state = MainMenuState::default();
        let outcome = update(
            &mut state,
            &cfg,
            &registry(),
            no_install_ctx(),
            key(KeyCode::Enter),
        );
        match outcome {
            ScreenOutcome::NavigateTo(AppScreen::LinePicker(_)) => {}
            other => {
                panic!("expected LinePicker for auto-promoted multi-line config, got {other:?}",)
            }
        }
    }

    #[test]
    fn edit_colors_routes_to_theme_picker_regardless_of_layout_mode() {
        // EditLines has layout-conditional routing (single-line →
        // ItemsEditor, multi-line → LinePicker). EditColors should
        // be layout-independent — the theme picker applies to both.
        // Pin so a future refactor that mistakenly mirrors EditLines'
        // conditional doesn't silently send multi-line users to a
        // placeholder.
        for layout in [LayoutMode::SingleLine, LayoutMode::MultiLine] {
            let cfg = Config {
                layout,
                ..Config::default()
            };
            let mut state = MainMenuState::default();
            // Cursor on EditColors (row 1).
            update(
                &mut state,
                &cfg,
                &registry(),
                no_install_ctx(),
                key(KeyCode::Down),
            );
            let outcome = update(
                &mut state,
                &cfg,
                &registry(),
                no_install_ctx(),
                key(KeyCode::Enter),
            );
            assert!(
                matches!(
                    outcome,
                    ScreenOutcome::NavigateTo(AppScreen::ThemePicker(_))
                ),
                "layout={layout:?}: expected ThemePicker, got {outcome:?}",
            );
        }
    }

    #[test]
    fn edit_colors_threads_config_theme_into_picker_initial_cursor() {
        // The EditColors arm reads `config.theme.as_deref().unwrap_or("default")`
        // and passes that string into `ThemePickerState::new` as the
        // `current` arg. The picker uses it to seed the initial
        // cursor position. Pin the wiring end-to-end so a regression
        // that hard-codes `"default"`, passes `""`, or threads the
        // wrong field doesn't slip past the screen-variant assertions
        // already in `enter_on_each_non_exit_row_routes_to_correct_screen`.
        let cfg = Config {
            theme: Some("dracula".into()),
            ..Config::default()
        };
        let mut state = MainMenuState::default();
        // Cursor on EditColors (row 1).
        update(
            &mut state,
            &cfg,
            &registry(),
            no_install_ctx(),
            key(KeyCode::Down),
        );
        let outcome = update(
            &mut state,
            &cfg,
            &registry(),
            no_install_ctx(),
            key(KeyCode::Enter),
        );
        match outcome {
            ScreenOutcome::NavigateTo(AppScreen::ThemePicker(p)) => {
                assert_eq!(
                    p.cursor_theme().name(),
                    "dracula",
                    "MainMenu must thread `config.theme` into the picker's initial cursor",
                );
            }
            other => panic!("expected ThemePicker, got {other:?}"),
        }
    }

    #[test]
    fn theme_picker_round_trips_main_menu_cursor_through_esc_back_nav() {
        // Drive the full Activate → ThemePicker → Esc → MainMenu
        // path via `app::update` and pin that the restored MainMenu
        // cursor lands on EditColors (row 1), not the default 0.
        // Mirrors `cursor_preserved_across_activate_esc_activate_round_trip`
        // for Placeholder. Catches a regression that resets the
        // MainMenuState anywhere along the back-nav chain — most
        // likely shape would be calling `mem::take(&mut state.prev)`
        // a second time mid-flight, or replacing it with
        // `MainMenuState::default()` in the picker's Esc arm.
        use super::super::app::{update as app_update, AppScreen, Event, Model};
        let model = Model::new(
            crate::config::Config::default(),
            toml_edit::DocumentMut::new(),
            String::new(),
            None,
            crate::theme::default_theme().clone(),
            registry(),
            crate::theme::Capability::None,
            None,
            None,
            "linesmith".to_string(),
        );
        // Walk to EditColors (row 1).
        let model = app_update(model, Event::Key(key(KeyCode::Down)));
        // Activate → ThemePicker.
        let model = app_update(model, Event::Key(key(KeyCode::Enter)));
        match &model.screen {
            AppScreen::ThemePicker(_) => {}
            other => panic!("expected ThemePicker after Enter on EditColors, got {other:?}"),
        }
        // Esc → MainMenu, cursor preserved on row 1.
        let model = app_update(model, Event::Key(key(KeyCode::Esc)));
        match &model.screen {
            AppScreen::MainMenu(state) => {
                assert_eq!(
                    state.list.cursor(),
                    1,
                    "MainMenu cursor must survive Esc back-nav from ThemePicker",
                );
            }
            other => panic!("expected MainMenu after Esc, got {other:?}"),
        }
    }

    #[test]
    fn edit_lines_does_not_auto_promote_when_segments_array_is_populated() {
        // Counter-pin to `edit_lines_auto_promotes_…`: when BOTH
        // `[line].segments` is non-empty AND `[line.N]` sub-tables
        // exist, `build_lines` resolves to single-line + warn; the
        // editor must follow that resolution rather than silently
        // promoting on every numbered-tables-present case. A
        // regression that auto-promotes "whenever numbered is non-
        // empty" would silently re-route the user's deliberate
        // single-line edits to the picker.
        use crate::config::{LineConfig, LineEntry};
        use std::collections::BTreeMap;
        let mut numbered = BTreeMap::new();
        let mut line_one = toml::value::Table::new();
        line_one.insert("segments".to_string(), toml::Value::Array(vec![]));
        numbered.insert("1".to_string(), toml::Value::Table(line_one));
        let cfg = Config {
            layout: LayoutMode::SingleLine,
            line: Some(LineConfig {
                segments: vec![LineEntry::Id("model".to_string())],
                numbered,
            }),
            ..Config::default()
        };
        let mut state = MainMenuState::default();
        let outcome = update(
            &mut state,
            &cfg,
            &registry(),
            no_install_ctx(),
            key(KeyCode::Enter),
        );
        match outcome {
            ScreenOutcome::NavigateTo(AppScreen::ItemsEditor(s)) => {
                assert_eq!(s.line(), super::super::items_editor::LineKey::Single);
            }
            other => panic!(
                "expected ItemsEditor(Single) when both segments AND numbered are populated, got {other:?}",
            ),
        }
    }

    #[test]
    fn enter_on_exit_row_quits() {
        // Walking the cursor down to the Exit row (last) and
        // pressing Enter must emit `Quit`, not navigate.
        let mut state = MainMenuState::default();
        for _ in 0..(MENU_ITEMS.len() - 1) {
            let outcome = update(
                &mut state,
                &Config::default(),
                &registry(),
                no_install_ctx(),
                key(KeyCode::Down),
            );
            assert!(matches!(outcome, ScreenOutcome::Stay));
        }
        assert_eq!(MENU_ITEMS[state.list.cursor()], MainMenuItem::Exit);
        let outcome = update(
            &mut state,
            &Config::default(),
            &registry(),
            no_install_ctx(),
            key(KeyCode::Enter),
        );
        assert!(matches!(outcome, ScreenOutcome::Quit));
    }

    #[test]
    fn enter_on_each_non_exit_row_routes_to_correct_screen() {
        // Walks the menu and asserts every non-Exit row routes to
        // its expected destination. EditLines opens the items
        // editor; EditColors opens the theme picker; every other
        // row still opens a placeholder named after the item's
        // label. Catches a copy-paste bug in `activate` where the
        // wrong item label / variant could ship.
        for (idx, item) in MENU_ITEMS.iter().enumerate() {
            if matches!(item, MainMenuItem::Exit) {
                continue;
            }
            let mut state = MainMenuState::default();
            for _ in 0..idx {
                update(
                    &mut state,
                    &Config::default(),
                    &registry(),
                    no_install_ctx(),
                    key(KeyCode::Down),
                );
            }
            assert_eq!(state.list.cursor(), idx);
            let outcome = update(
                &mut state,
                &Config::default(),
                &registry(),
                no_install_ctx(),
                key(KeyCode::Enter),
            );
            match (item, outcome) {
                (MainMenuItem::EditLines, ScreenOutcome::NavigateTo(AppScreen::ItemsEditor(_))) => {
                }
                (
                    MainMenuItem::EditColors,
                    ScreenOutcome::NavigateTo(AppScreen::ThemePicker(_)),
                ) => {}
                (other_item, ScreenOutcome::NavigateTo(AppScreen::Placeholder(p))) => {
                    assert_eq!(p.name, other_item.label(), "row {idx}");
                }
                (item, outcome) => panic!("row {idx} ({item:?}): unexpected outcome {outcome:?}",),
            }
        }
    }

    #[test]
    fn enter_on_install_row_with_resolved_settings_path_opens_install_screen() {
        // The default-pathed `no_install_ctx()` routes
        // InstallToClaudeCode to the Placeholder fallback. Pin the
        // happy path explicitly: when `settings_path` is `Some`,
        // pressing Enter on that row opens the real install screen.
        // A regression that swapped the variant order or pattern-
        // matched the wrong arm would only surface here.
        let install_row = MENU_ITEMS
            .iter()
            .position(|i| matches!(i, MainMenuItem::InstallToClaudeCode))
            .expect("install row present");
        let mut state = MainMenuState::default();
        for _ in 0..install_row {
            update(
                &mut state,
                &Config::default(),
                &registry(),
                no_install_ctx(),
                key(KeyCode::Down),
            );
        }
        let path = std::path::PathBuf::from("/tmp/test-settings.json");
        let ctx = InstallContext {
            settings_path: Some(&path),
            install_command: "linesmith",
        };
        let outcome = update(
            &mut state,
            &Config::default(),
            &registry(),
            ctx,
            key(KeyCode::Enter),
        );
        match outcome {
            ScreenOutcome::NavigateTo(AppScreen::InstallToClaudeCode(_)) => {}
            other => panic!("expected InstallToClaudeCode, got {other:?}"),
        }
    }

    #[test]
    fn placeholder_carries_main_menu_state_for_back_nav() {
        // After activating, the previous MainMenuState (with cursor
        // position) lives inside the Placeholder so Esc can restore
        // it. Pin that the cursor index is preserved across the
        // transition.
        let mut state = MainMenuState::default();
        update(
            &mut state,
            &Config::default(),
            &registry(),
            no_install_ctx(),
            key(KeyCode::Down),
        );
        update(
            &mut state,
            &Config::default(),
            &registry(),
            no_install_ctx(),
            key(KeyCode::Down),
        );
        // Cursor now on row 2 (Powerline Setup). Activating it
        // should pack a MainMenuState with cursor=2 into the
        // Placeholder.
        let outcome = update(
            &mut state,
            &Config::default(),
            &registry(),
            no_install_ctx(),
            key(KeyCode::Enter),
        );
        match outcome {
            ScreenOutcome::NavigateTo(AppScreen::Placeholder(p)) => {
                assert_eq!(p.name, "Powerline Setup");
                assert_eq!(p.prev.list.cursor(), 2);
            }
            other => panic!("expected Placeholder, got {other:?}"),
        }
    }

    #[test]
    fn down_advances_cursor() {
        let mut state = MainMenuState::default();
        update(
            &mut state,
            &Config::default(),
            &registry(),
            no_install_ctx(),
            key(KeyCode::Down),
        );
        assert_eq!(state.list.cursor(), 1);
    }

    #[test]
    fn up_at_top_wraps_to_last() {
        let mut state = MainMenuState::default();
        update(
            &mut state,
            &Config::default(),
            &registry(),
            no_install_ctx(),
            key(KeyCode::Up),
        );
        assert_eq!(state.list.cursor(), MENU_ITEMS.len() - 1);
    }

    fn render_to_string(state: &MainMenuState, width: u16, height: u16) -> String {
        use ratatui::backend::TestBackend;
        use ratatui::Terminal;
        let backend = TestBackend::new(width, height);
        let mut terminal = Terminal::new(backend).expect("backend");
        terminal
            .draw(|frame| view(state, frame, frame.area()))
            .expect("draw");
        crate::tui::buffer_to_string(terminal.backend().buffer())
    }

    #[test]
    fn snapshot_main_menu_default_cursor() {
        let state = MainMenuState::default();
        insta::assert_snapshot!("main_menu_default_cursor", render_to_string(&state, 60, 14));
    }

    #[test]
    fn snapshot_main_menu_cursor_on_install_row() {
        let install_row = MENU_ITEMS
            .iter()
            .position(|i| matches!(i, MainMenuItem::InstallToClaudeCode))
            .expect("install row present");
        let mut state = MainMenuState::default();
        for _ in 0..install_row {
            update(
                &mut state,
                &Config::default(),
                &registry(),
                no_install_ctx(),
                key(KeyCode::Down),
            );
        }
        insta::assert_snapshot!(
            "main_menu_cursor_on_install_row",
            render_to_string(&state, 60, 14)
        );
    }
}