diff --git a/crates/rocm-dash-tui/src/app/actions.rs b/crates/rocm-dash-tui/src/app/actions.rs index efa84c5e6a..4bd76526de 100644 --- a/crates/rocm-dash-tui/src/app/actions.rs +++ b/crates/rocm-dash-tui/src/app/actions.rs @@ -13,8 +13,8 @@ use crate::ui; use super::AppState; use super::summary::summarize_json_value; use super::types::{ - ActiveTab, ChatConsent, ChatKeyCtx, MENU_ITEMS, Modal, OPTIONS_TABS, PALETTE_DESTS, PaneFocus, - ScrollTarget, + ActiveTab, ChatConsent, ChatKeyCtx, MENU_ITEMS, MenuItem, Modal, OPTIONS_TABS, PALETTE_DESTS, + PaneFocus, ScrollTarget, }; #[cfg(test)] use super::types::{ChatProvider, ChatRole}; @@ -284,7 +284,7 @@ pub(crate) fn apply_action(state: &mut AppState, action: KeyAction) -> bool { } KeyAction::MenuMove(d) => match state.modal { Modal::Menu => { - state.menu_sel = wrap_cursor(state.menu_sel, d, MENU_ITEMS); + state.menu_sel = wrap_cursor(state.menu_sel, d, MENU_ITEMS.len()); } Modal::Palette => { state.palette_sel = wrap_cursor(state.palette_sel, d, PALETTE_DESTS.len()); @@ -297,12 +297,12 @@ pub(crate) fn apply_action(state: &mut AppState, action: KeyAction) -> bool { } } KeyAction::MenuActivate => match state.modal { - Modal::Menu => match state.menu_sel { - 0 => { + Modal::Menu => match MENU_ITEMS.get(state.menu_sel) { + Some(MenuItem::Options) => { state.modal = Modal::Options; state.options_tab = 0; } - 1 => { + Some(MenuItem::Help) => { state.modal = Modal::GlobalHelp; } // Issue #145: this must share `KeyAction::Quit`'s own gate — @@ -312,7 +312,10 @@ pub(crate) fn apply_action(state: &mut AppState, action: KeyAction) -> bool { // `open_quit_confirm` closes the Esc menu itself when a // prompt opens, so a decline doesn't strand the user back in // it (same as every other row here already does on success). - _ => return request_quit(state), + Some(MenuItem::Quit) => return request_quit(state), + // Never set by `OpenMenu` or `MenuMove`, which keep the + // selection in range; do nothing rather than quit. + None => {} }, Modal::Palette => { if let Some((_, tab)) = PALETTE_DESTS.get(state.palette_sel) { @@ -1467,6 +1470,54 @@ mod tests { assert_eq!(s.options_tab, OPTIONS_TABS.len() - 1); } + #[test] + fn esc_menu_selection_wraps_over_its_three_rows_and_each_row_runs_its_own_action() { + let mut s = st(); + apply_action(&mut s, KeyAction::OpenMenu); + assert_eq!(s.menu_sel, 0, "the menu opens on its first row"); + // Up from the first row wraps to the last; down from the last wraps + // back to the first. + apply_action(&mut s, KeyAction::MenuMove(-1)); + assert_eq!(s.menu_sel, 2); + apply_action(&mut s, KeyAction::MenuMove(1)); + assert_eq!(s.menu_sel, 0); + // A full lap of down-presses visits every row once and comes back. + let mut lap = Vec::new(); + for _ in 0..3 { + apply_action(&mut s, KeyAction::MenuMove(1)); + lap.push(s.menu_sel); + } + assert_eq!(lap, [1, 2, 0]); + assert_eq!(s.modal, Modal::Menu, "moving never closes the menu"); + + // Row 0 opens Options on its first tab; row 1 opens the global help; + // row 2 is Quit, which exits at once when nothing is being served. + s.options_tab = 3; + s.menu_sel = 0; + assert!(!apply_action(&mut s, KeyAction::MenuActivate)); + assert_eq!(s.modal, Modal::Options); + assert_eq!(s.options_tab, 0); + s.modal = Modal::Menu; + s.menu_sel = 1; + assert!(!apply_action(&mut s, KeyAction::MenuActivate)); + assert_eq!(s.modal, Modal::GlobalHelp); + s.modal = Modal::Menu; + s.menu_sel = 2; + assert!(apply_action(&mut s, KeyAction::MenuActivate)); + } + + #[test] + fn esc_menu_selection_past_the_last_row_does_nothing() { + // Nothing sets `menu_sel` out of range (`OpenMenu` resets it and + // `MenuMove` wraps it). If it ever were, activating must not take the + // destructive Quit path: no quit request, and the menu stays open. + let mut s = st(); + s.modal = Modal::Menu; + s.menu_sel = MENU_ITEMS.len() + 4; + assert!(!apply_action(&mut s, KeyAction::MenuActivate)); + assert_eq!(s.modal, Modal::Menu); + } + #[test] fn palette_activation_switches_tab() { let mut s = st(); diff --git a/crates/rocm-dash-tui/src/app/mod.rs b/crates/rocm-dash-tui/src/app/mod.rs index 4061e2cb35..9bbc7ef147 100644 --- a/crates/rocm-dash-tui/src/app/mod.rs +++ b/crates/rocm-dash-tui/src/app/mod.rs @@ -74,9 +74,9 @@ pub use scrollbar::{FooterChip, ScrollDrag, ScrollbarHandle}; #[cfg(test)] pub(crate) use terminal::restore_after_session; pub use types::{ - ActiveTab, ChatConsent, ChatKeyCtx, ChatRole, ChatTurn, ConnState, Focus, MENU_ITEMS, Modal, - OPTIONS_TABS, PALETTE_DESTS, PaneFocus, PlannedAction, ReplayState, ResolvedArgs, ScrollTarget, - UpdateStatus, format_mmss, + ActiveTab, ChatConsent, ChatKeyCtx, ChatRole, ChatTurn, ConnState, Focus, MENU_ITEMS, MenuItem, + Modal, OPTIONS_TABS, PALETTE_DESTS, PaneFocus, PlannedAction, ReplayState, ResolvedArgs, + ScrollTarget, UpdateStatus, format_mmss, }; pub(crate) use types::{ChatProvider, PendingApproval, SlashOutcome, SlashToolRequest}; diff --git a/crates/rocm-dash-tui/src/app/types.rs b/crates/rocm-dash-tui/src/app/types.rs index 7ffc341630..27fb3962ae 100644 --- a/crates/rocm-dash-tui/src/app/types.rs +++ b/crates/rocm-dash-tui/src/app/types.rs @@ -575,8 +575,37 @@ impl ScrollTarget { ]; } -/// Esc-menu rows: Options / Help / Quit. -pub const MENU_ITEMS: usize = 3; +/// One selectable row of the Esc main menu. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum MenuItem { + Options, + Help, + Quit, +} + +impl MenuItem { + /// The text the menu draws for this row. + #[must_use] + pub const fn label(self) -> &'static str { + match self { + Self::Options => "Options", + Self::Help => "Help", + Self::Quit => "Quit", + } + } +} + +/// Esc-menu rows, top to bottom. +/// +/// The one list the menu is built from: the wrap bound of +/// `KeyAction::MenuMove` and the row an activation runs (`app/actions.rs`), +/// and the rows, labels and reserved height `draw_menu` paints +/// (`ui/menu.rs`), all read it. A new row is added here and gets an +/// arm in the `KeyAction::MenuActivate` match, which the compiler requires +/// for every `MenuItem`. A `MenuItem` left out of this list is not caught by +/// the compiler (stable Rust cannot check that without a derive macro this +/// crate doesn't depend on), the same limit as `ScrollTarget::ALL` above. +pub const MENU_ITEMS: &[MenuItem] = &[MenuItem::Options, MenuItem::Help, MenuItem::Quit]; /// Command-palette destinations (label, tab). pub const PALETTE_DESTS: &[(&str, ActiveTab)] = &[ diff --git a/crates/rocm-dash-tui/src/ui/menu.rs b/crates/rocm-dash-tui/src/ui/menu.rs index 5afced580e..74137a8b97 100644 --- a/crates/rocm-dash-tui/src/ui/menu.rs +++ b/crates/rocm-dash-tui/src/ui/menu.rs @@ -12,7 +12,7 @@ use ratatui::style::{Modifier, Style}; use ratatui::text::{Line, Span}; use ratatui::widgets::{Clear, Paragraph}; -use crate::app::{AppState, OPTIONS_TABS, PALETTE_DESTS}; +use crate::app::{AppState, MENU_ITEMS, OPTIONS_TABS, PALETTE_DESTS}; use crate::ui::panel::{self, BoxRole, centered_rect, draw_popup_frame, grey_overlay}; use crate::ui::theme::Theme; @@ -25,8 +25,9 @@ use crate::ui::theme::Theme; /// Row (relative to `inner.y`) where the Esc menu's selectable items begin, /// just below the 5-row logo (rows 1..=5). const MENU_ITEMS_Y: u16 = 8; -/// Number of selectable rows in the Esc menu (Options / Help / Quit). -const MENU_ITEM_COUNT: u16 = 3; +/// Number of selectable rows in the Esc menu, counted from the one list +/// ([`MENU_ITEMS`]) the key handling and the drawn rows also use. +const MENU_ITEM_COUNT: u16 = MENU_ITEMS.len() as u16; /// Minimum inner width the logo needs before the menu will render. const MENU_MIN_WIDTH: u16 = 31; @@ -54,9 +55,8 @@ pub fn draw_menu(f: &mut Frame, area: Rect, sel: usize, theme: &Theme) { let cx = inner.x + inner.width.saturating_sub(logo_w) / 2; draw_logo(f, cx, inner.y + 1, theme); - let items = ["Options", "Help", "Quit"]; let mx = inner.x + 4; - for (i, label) in items.iter().enumerate() { + for (i, item) in MENU_ITEMS.iter().enumerate() { let y = inner.y + MENU_ITEMS_Y + i as u16; if y >= inner.y + inner.height { break; @@ -75,7 +75,7 @@ pub fn draw_menu(f: &mut Frame, area: Rect, sel: usize, theme: &Theme) { f.render_widget( Paragraph::new(Line::from(vec![ Span::styled(cur, Style::default().fg(theme.accent)), - Span::styled(*label, st), + Span::styled(item.label(), st), ])), Rect::new(mx, y, inner.width.saturating_sub(4), 1), ); @@ -267,7 +267,7 @@ pub fn opt_row( #[cfg(test)] mod tests { - use super::{draw_logo, grey_overlay, opt_row}; + use super::{MENU_ITEMS, draw_logo, grey_overlay, opt_row}; use crate::ui::tests::flat; use crate::ui::theme::Theme; use ratatui::Terminal; @@ -299,6 +299,148 @@ mod tests { ); } + /// The text between the menu box's side borders, outer blanks trimmed. + fn inside(row: &str) -> &str { + row.trim().trim_matches('│').trim() + } + + /// Render `draw_menu` on a `w`x`h` screen with `sel` focused and return the + /// rows below the logo that carry menu text inside the box, as + /// `(screen row, text inside the borders)`. The bottom border does not + /// start with a side border, so it is excluded. + fn drawn_item_rows(w: u16, h: u16, sel: usize) -> Vec<(usize, String)> { + let theme = Theme::from_name("default-dark"); + let area = Rect::new(0, 0, w, h); + let rows = crate::ui::tests::rows(w, h, |f| super::draw_menu(f, area, sel, &theme)); + let logo_end = rows + .iter() + .rposition(|r| r.contains('█')) + .expect("the logo is drawn when the menu fits"); + rows.iter() + .enumerate() + .skip(logo_end + 1) + .filter(|(_, r)| r.trim_start().starts_with('│') && !inside(r).is_empty()) + .map(|(y, r)| (y, inside(r).to_string())) + .collect() + } + + #[test] + fn esc_menu_draws_options_help_quit_in_order_with_only_the_selected_row_marked() { + // Characterisation of the drawn rows: the same three labels in the same + // order, one "▸ " cursor on the selected row and a blank cursor column + // on the others. + for (sel, expected) in [ + (0usize, ["▸ Options", "Help", "Quit"]), + (1, ["Options", "▸ Help", "Quit"]), + (2, ["Options", "Help", "▸ Quit"]), + ] { + let drawn = drawn_item_rows(120, 30, sel); + let texts: Vec<&str> = drawn.iter().map(|(_, t)| t.as_str()).collect(); + assert_eq!(texts, expected, "rows drawn with sel={sel}"); + // The three items are on consecutive screen rows. + assert_eq!(drawn[1].0, drawn[0].0 + 1, "sel={sel}"); + assert_eq!(drawn[2].0, drawn[1].0 + 1, "sel={sel}"); + } + } + + #[test] + fn esc_menu_item_rows_sit_at_a_fixed_column_with_focus_styling() { + use ratatui::style::Modifier; + let theme = Theme::from_name("default-dark"); + let area = Rect::new(0, 0, 120, 30); + let mut term = Terminal::new(TestBackend::new(120, 30)).unwrap(); + term.draw(|f| super::draw_menu(f, area, 1, &theme)).unwrap(); + // One render: the row text and the cell styles both come from this buffer. + let buf = term.backend().buffer(); + let rows: Vec = (0..buf.area.height) + .map(|y| { + (0..buf.area.width) + .map(|x| buf[(x, y)].symbol()) + .collect::() + }) + .collect(); + let y_of = |label: &str| -> u16 { + rows.iter() + .position(|r| inside(r) == label || inside(r) == format!("▸ {label}")) + .unwrap_or_else(|| panic!("no row for {label}")) as u16 + }; + // Locate the box's left border on the Help row instead of hardcoding + // where the popup sits, so a change to the popup's size does not + // break this test. The cursor column is 7 cells right of that border + // and the label 2 more. + let help_y = y_of("Help"); + let border_x = (0..buf.area.width) + .find(|&x| buf[(x, help_y)].symbol() == "│") + .expect("the Help row starts inside a bordered box"); + let (cursor_x, label_x) = (border_x + 7, border_x + 9); + assert_eq!(buf[(cursor_x, help_y)].symbol(), "▸"); + assert_eq!(buf[(cursor_x, help_y)].style().fg, Some(theme.accent)); + assert_eq!(buf[(label_x, help_y)].symbol(), "H"); + assert_eq!(buf[(label_x, help_y)].style().fg, Some(theme.accent)); + assert!( + buf[(label_x, help_y)] + .style() + .add_modifier + .contains(Modifier::BOLD), + "the selected label is bold" + ); + for (label, first) in [("Options", "O"), ("Quit", "Q")] { + let y = y_of(label); + assert_eq!(buf[(label_x, y)].symbol(), first, "{label}"); + assert_eq!(buf[(label_x, y)].style().fg, Some(theme.fg), "{label}"); + assert!( + !buf[(label_x, y)] + .style() + .add_modifier + .contains(Modifier::BOLD), + "{label} is not bold when unselected" + ); + assert_eq!(buf[(cursor_x, y)].symbol(), " ", "{label} has no cursor"); + } + } + + #[test] + fn esc_menu_is_drawn_only_when_the_box_is_tall_enough_for_every_item() { + // End-to-end counterpart of `esc_menu_requires_room_for_all_items`: on + // a 120-column screen the box has 13 rows at height 19 (the logo would + // show but not every item) and 14 at height 20, the smallest screen on + // which Options, Help and Quit all fit. + let theme = Theme::from_name("default-dark"); + let render = |h: u16| { + let area = Rect::new(0, 0, 120, h); + crate::ui::tests::rows(120, h, |f| super::draw_menu(f, area, 0, &theme)).join("\n") + }; + let short = render(19); + assert!( + !short.contains('█') + && !short.contains("Options") + && !short.contains("Help") + && !short.contains("Quit"), + "height 19 must draw an empty frame:\n{short}" + ); + let just_fits = render(20); + assert!(just_fits.contains('█'), "logo at height 20"); + for label in ["Options", "Help", "Quit"] { + assert!(just_fits.contains(label), "{label} at height 20"); + } + } + + #[test] + fn esc_menu_draws_the_rows_of_the_list_the_selection_walks() { + // The drawn rows and the wrap bound of `KeyAction::MenuMove` both come + // from `MENU_ITEMS` (`app/types.rs`), so what is drawn is exactly what + // the selection can reach, label for label. + let drawn = drawn_item_rows(120, 30, 0); + let drawn: Vec<&str> = drawn + .iter() + .map(|(_, t)| t.trim_start_matches("▸ ")) + .collect(); + let listed: Vec<&str> = MENU_ITEMS.iter().map(|i| i.label()).collect(); + assert_eq!(drawn, listed); + // `label()` is on both sides above, so pin the wording itself too. + assert_eq!(listed, ["Options", "Help", "Quit"]); + } + #[test] fn draw_logo_paints_block_wordmark() { let theme = Theme::from_name("default-dark"); diff --git a/docs/architecture.md b/docs/architecture.md index edba1fc0ed..ed86486022 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -215,7 +215,7 @@ The old agent.rs was split (mechanical relocation — the shared seam types stay [`app/mod.rs`](../crates/rocm-dash-tui/src/app/mod.rs) is modularized (ROCMAI-84, Phase 4 of ROCMAI-27's sequencing) into an `app/` directory. [`app/types.rs`](../crates/rocm-dash-tui/src/app/types.rs), [`app/event_loop.rs`](../crates/rocm-dash-tui/src/app/event_loop.rs), [`app/scrollbar.rs`](../crates/rocm-dash-tui/src/app/scrollbar.rs), and [`app/actions.rs`](../crates/rocm-dash-tui/src/app/actions.rs) follow full domain extraction. [`app/chat.rs`](../crates/rocm-dash-tui/src/app/chat.rs), [`app/slash.rs`](../crates/rocm-dash-tui/src/app/slash.rs), and [`app/summary.rs`](../crates/rocm-dash-tui/src/app/summary.rs) were extracted earlier via mechanical relocation, the same convention the `agent/` split above follows. `quit_confirm`, `tool_approval`, `overlays`, `scroll` and `chat_state` each hold a further `impl AppState` block for one cohesive group of reducer methods: - [`app/mod.rs`](../crates/rocm-dash-tui/src/app/mod.rs) — keeps `AppState` and its constructor, the theme picker, row selection, the `apply_event` reducer entry point and the handful of items that stay with it (`ProviderSwitch`, `HISTORY_CAP`, `BENCH_CAP`); the rest of `AppState`'s methods live in the child-module `impl` blocks listed below (`apply_action` itself is a free function in [`app/actions.rs`](../crates/rocm-dash-tui/src/app/actions.rs)) — the modularization effort's "reducer's reason to exist." `crate::app::*` paths for the public surface moved out are unchanged via re-exports (see the re-export block's comment for what counts as "public surface"). -- [`app/types.rs`](../crates/rocm-dash-tui/src/app/types.rs) — shared type/enum defs: `Focus`, `ResolvedArgs`, connection/tab/chat/replay state, `Modal`, `UpdateStatus`, `PaneFocus`, `ScrollTarget`, the slash/plan/approval payload types, and the Esc-menu, command-palette and options-panel navigation data (`MENU_ITEMS`, `PALETTE_DESTS`, `OPTIONS_TABS`) that `app/actions.rs` reads, and that [`ui/menu.rs`](../crates/rocm-dash-tui/src/ui/menu.rs) renders (the palette destinations and options tabs; the Esc menu's own item count is a separate constant there); no `AppState` access. +- [`app/types.rs`](../crates/rocm-dash-tui/src/app/types.rs) — shared type/enum defs: `Focus`, `ResolvedArgs`, connection/tab/chat/replay state, `Modal`, `UpdateStatus`, `PaneFocus`, `ScrollTarget`, the slash/plan/approval payload types, and the Esc-menu, command-palette and options-panel navigation data (`MenuItem` and `MENU_ITEMS`, `PALETTE_DESTS`, `OPTIONS_TABS`) that `app/actions.rs` reads, and that [`ui/menu.rs`](../crates/rocm-dash-tui/src/ui/menu.rs) renders; the Esc menu's rows, their labels, the key handling's wrap bound and the height `draw_menu` reserves all come from the one `MENU_ITEMS` list; no `AppState` access. - [`app/event_loop.rs`](../crates/rocm-dash-tui/src/app/event_loop.rs) — the tick loop that drives the dashboard: `run`, `event_loop`, the frame-draw shutdown gate and the registry-probe seeding. - [`app/chat_runtime.rs`](../crates/rocm-dash-tui/src/app/chat_runtime.rs) — the live chat backend the tick loop owns, a leaf of `event_loop.rs`: `ChatRuntime` holds the agent the next submit is routed to plus the saved auto-detected local one that `/provider local` restores. `ChatRuntime::start` resolves the backend before the first frame, and `drain_provider_switch`, `drain_endpoint_rebuild` and `drain_dispatch` each consume one of `AppState`'s one-shot edges (`provider_switch`, `chat_endpoint_rebuild`, `chat_dispatch`). The detect and persist edges do not touch the backend and stay in `event_loop.rs`. - [`app/terminal.rs`](../crates/rocm-dash-tui/src/app/terminal.rs) — terminal restoration and shutdown arbitration, a leaf of `event_loop.rs`: `restore_terminal` and its writer lock, the `SHUTTING_DOWN` latch, the termination-signal watcher (`spawn_termination_watcher`; its `TerminationSignals` has a `cfg(unix)` and a `cfg(windows)` variant) and the Ctrl+C key path (`is_ctrl_c`, `exit_on_ctrl_c`). `app/mod.rs` re-exports the items the rest of the crate and `apps/rocm` use. diff --git a/tests/e2e-cucumber/tests/e2e/dash_steps.rs b/tests/e2e-cucumber/tests/e2e/dash_steps.rs index 1f87dc8581..0adff0282c 100644 --- a/tests/e2e-cucumber/tests/e2e/dash_steps.rs +++ b/tests/e2e-cucumber/tests/e2e/dash_steps.rs @@ -1964,8 +1964,8 @@ async fn dashboard_menu_is_displayed(world: &mut E2eWorld) { .unwrap_or_else(|e| panic!("dashboard menu did not appear: {e}")); } -/// Navigates `Modal::Menu`'s items (`["Options", "Help", "Quit"]`, -/// `ui/menu.rs`) down to "Quit" and activates it — `j` twice from the +/// Navigates `Modal::Menu`'s items (Options, Help, Quit: `MENU_ITEMS` in +/// the dash-TUI's `app/types.rs`) down to "Quit" and activates it — `j` twice from the /// default `menu_sel: 0`, then `Enter` (`KeyAction::MenuActivate`). Requires /// the menu to already be open (`the dashboard menu is displayed`). #[when("the user selects Quit from the dashboard menu")]