From 8fe26467051adad56c329bb400ab628b489dacb1 Mon Sep 17 00:00:00 2001 From: Felipe Coury Date: Mon, 30 Nov 2026 19:53:51 +0000 Subject: [PATCH] Enable mouse-wheel scrolling in the Agent command center (#64808) ## Why The mouse wheel scrolls the help view, but browsing a long task list requires keyboard navigation. Once the list can scroll independently of the selection, task shortcuts need to account for an offscreen target. ## What changed Scroll the task list without moving the selection, and keep task titles reachable in short viewports. When the selection is offscreen, show a reveal hint and make the first task shortcut bring the selection back into view. Keyboard navigation resumes following the selection. Suppress repeats from the key that revealed the task so holding a shortcut such as Stop cannot immediately act on it. On Windows, peek at queued console input to account for press/release pairs emitted by legacy ConPTY input. ## Testing Cover wheel paging and short viewports with a rendering snapshot, test that Stop requires a fresh press after revealing a hidden selection, and verify that the Windows release probe leaves queued input intact. GitOrigin-RevId: ebd7c0993978de3fc07245adf930f9fc63b306c1 --- codex-rs/tui/src/activation_key_guard.rs | 16 +- .../tui/src/activation_key_guard_tests.rs | 20 ++ codex-rs/tui/src/app/agent_center/hints.rs | 9 +- .../tui/src/app/agent_center/navigation.rs | 66 +++++-- codex-rs/tui/src/app/agent_center/render.rs | 18 +- codex-rs/tui/src/app/agent_center/rows.rs | 29 ++- codex-rs/tui/src/app/agent_center_tests.rs | 180 +++++++++++++++++- .../tui/src/app/agents_overview_actions.rs | 7 +- codex-rs/tui/src/app/agents_overview_view.rs | 36 +++- .../tui/src/app/conversation_workspace.rs | 24 ++- codex-rs/tui/src/app/input.rs | 11 +- ...mmand_center__live_center_after_wheel.snap | 24 +++ codex-rs/tui/src/chatwidget/interaction.rs | 9 +- codex-rs/tui/src/keymap.rs | 9 + .../terminal_capabilities/keyboard_modes.rs | 13 ++ .../terminal_probe/windows.rs | 17 +- codex-rs/tui/src/tui.rs | 3 + codex-rs/tui/src/tui/alternate_screen.rs | 4 - ...dows_tests.rs => windows_console_tests.rs} | 70 ++++++- 19 files changed, 506 insertions(+), 59 deletions(-) create mode 100644 codex-rs/tui/src/app/snapshots/codex_tui__app__agents_overview__tests__command_center__live_center_after_wheel.snap rename codex-rs/tui/src/tui/{alternate_screen_windows_tests.rs => windows_console_tests.rs} (54%) diff --git a/codex-rs/tui/src/activation_key_guard.rs b/codex-rs/tui/src/activation_key_guard.rs index 0bec31b293..d74b8e1837 100644 --- a/codex-rs/tui/src/activation_key_guard.rs +++ b/codex-rs/tui/src/activation_key_guard.rs @@ -22,6 +22,7 @@ pub(crate) struct ActivationKeyGuard { key: KeyBinding, block_until: Instant, legacy_repeat_fallback: bool, + ignore_paired_release: bool, active: bool, } @@ -31,10 +32,23 @@ impl ActivationKeyGuard { key, block_until: now.checked_add(INITIAL_GUARD).unwrap_or(now), legacy_repeat_fallback: !reported_repeats_only, + ignore_paired_release: false, active: true, } } + /// Protect a task action from autorepeat delivered as plain presses. Some keyboard + /// settings delay the first repeat a full second, so leave room for delivery latency. + /// Subsequent repeats extend the window. A physical release or distinct press ends it. + pub(crate) fn for_task_action(key: KeyBinding, now: Instant) -> Self { + Self { + block_until: now + Duration::from_millis(1_250), + ignore_paired_release: + crate::terminal_capabilities::keyboard_modes::activation_release_may_be_paired(), + ..Self::new_at(key, now, /*reported_repeats_only*/ false) + } + } + pub(crate) fn extend_for_protected_view(&mut self, now: Instant) { self.legacy_repeat_fallback = true; self.block_until = self.block_until.max(now + INITIAL_GUARD); @@ -51,7 +65,7 @@ impl ActivationKeyGuard { if self.key.is_same_physical_key(key) { if kind == KeyEventKind::Release { - self.active = false; + self.active = self.ignore_paired_release; return true; } // Without the legacy fallback, only a reported Repeat is treated as held. diff --git a/codex-rs/tui/src/activation_key_guard_tests.rs b/codex-rs/tui/src/activation_key_guard_tests.rs index e1b8147e1f..51f1824224 100644 --- a/codex-rs/tui/src/activation_key_guard_tests.rs +++ b/codex-rs/tui/src/activation_key_guard_tests.rs @@ -12,6 +12,26 @@ fn suppresses_activation_until_release_and_bounds_legacy_presses() { assert!(guard.consume_at(key, KeyEventKind::Release, start)); assert!(!guard.consume_at(key, KeyEventKind::Press, start)); + // At the longest ordinary keyboard delay the first repeat arrives just after a second. + let repeat = start + Duration::from_millis(1_050); + for ignore_paired_release in [false, true] { + let mut guard = ActivationKeyGuard { + ignore_paired_release, + ..ActivationKeyGuard::for_task_action(key, start) + }; + assert!(guard.consume_at(key, KeyEventKind::Press, repeat)); + assert!(guard.consume_at(key, KeyEventKind::Release, repeat)); + assert_eq!( + guard.consume_at(key, KeyEventKind::Press, repeat), + ignore_paired_release + ); + assert!(!guard.consume_at( + key, + KeyEventKind::Press, + repeat + Duration::from_millis(1_001) + )); + } + let mut guard = ActivationKeyGuard::new_at(key, start, /*reported_repeats_only*/ false); for elapsed in [900, 1_300] { assert!(guard.consume_at( diff --git a/codex-rs/tui/src/app/agent_center/hints.rs b/codex-rs/tui/src/app/agent_center/hints.rs index 8302c9acd2..584965e62a 100644 --- a/codex-rs/tui/src/app/agent_center/hints.rs +++ b/codex-rs/tui/src/app/agent_center/hints.rs @@ -152,6 +152,13 @@ impl AgentsOverviewView { let state = self.state(); let mut hints = Vec::new(); let help = state.help_top.is_some(); + let hidden = !help && state.selection_offscreen; + if hidden + && let Some(hint) = self.center_list_hint(ListAction::Accept) + && self.editing_allows_hint(&state, hint) + { + hints.push((hint.display_label(), "show selection".into())); + } if !help && !state.editing_metadata() && ![KeyModifiers::NONE, KeyModifiers::SHIFT] @@ -200,7 +207,7 @@ impl AgentsOverviewView { hints.push((navigation, if help { "scroll" } else { "move" }.into())); } } - if help { + if help || hidden { return hints; } if let Some(hint) = self diff --git a/codex-rs/tui/src/app/agent_center/navigation.rs b/codex-rs/tui/src/app/agent_center/navigation.rs index 6daeacfab2..8787982ce3 100644 --- a/codex-rs/tui/src/app/agent_center/navigation.rs +++ b/codex-rs/tui/src/app/agent_center/navigation.rs @@ -42,7 +42,19 @@ pub(super) fn visible_page( .position(|row| row.selection_index() == Some(selected_index)) .unwrap_or_default(); let height = usize::from(state.scroll_area.height).max(1); - let mut start = state.scroll.min(entries.len().saturating_sub(height)); + let limit = entries.len().saturating_sub(height); + let mut start = state.scroll.min(limit); + if state.wheel_scrolled { + // Start a wheel page at a heading or title. A detail needs its title above it. + while matches!( + entries.get(start), + Some(TaskListRow::Context(_) | TaskListRow::Gap) + ) { + start += 1; + } + state.scroll = start.min(limit); + return (selected, start..(start + height).min(entries.len())); + } if selected <= start { start = selected; if height > 1 && selected > 0 && matches!(entries[selected - 1], TaskListRow::Group(_)) { @@ -61,6 +73,15 @@ impl AgentsOverviewView { indices: &[usize], state: &AgentsOverviewViewState, ) -> Vec { + let mut rows = self.grouped_rows(indices, state); + // A heading or separator would occupy the only line and hide the task. + if state.scroll_area.height == 1 { + rows.retain(|row| !matches!(row, TaskListRow::Group(_) | TaskListRow::Gap)); + } + rows + } + + fn grouped_rows(&self, indices: &[usize], state: &AgentsOverviewViewState) -> Vec { let mut entries = Vec::new(); let mut previous = None; for index in indices.iter().copied() { @@ -104,7 +125,7 @@ impl AgentsOverviewView { return; } let indices = self.selectable_indices(); - let entries = self.center_rows(&indices, &self.state()); + let entries = self.grouped_rows(&indices, &self.state()); let mut sections = Vec::new(); let mut current = None; for row in entries { @@ -132,26 +153,49 @@ impl AgentsOverviewView { } } + pub(in crate::app) fn follow_keyboard_selection(&self) { + self.state().wheel_scrolled = false; + } + pub(in crate::app) fn scroll_mouse(&self, event: MouseEvent) -> bool { let mut state = self.state(); - let Some(top) = state.help_top else { - return false; - }; let Some(rows) = crate::bottom_pane::wheel_rows_in(event, state.scroll_area) else { return false; }; - let height = state.scroll_area.height as isize; - let next = top - .saturating_add_signed(isize::from(rows).clamp(-height, height)) - .min(state.scroll_limit); - state.help_top = Some(next); - next != top + if state.rename_target.is_some() || state.scroll_limit == 0 { + return false; + } + let top = state.help_top.unwrap_or(state.scroll); + let next = if state.help_top.is_none() && !state.short_page_starts.is_empty() { + let mut starts = state.short_page_starts.iter().copied(); + if rows > 0 { + starts.find(|&start| start > top) + } else { + starts.rfind(|&start| start < top) + } + .unwrap_or(top) + } else { + let step = state.scroll_area.height as isize; + top.saturating_add_signed(isize::from(rows).clamp(-step, step)) + .min(state.scroll_limit) + }; + if next == top { + return false; + } + if state.help_top.is_some() { + state.help_top = Some(next); + } else { + state.wheel_scrolled = true; + state.scroll = next; + } + true } pub(super) fn select_filter(&mut self, filter: usize) { let mut state = self.state(); state.status_filter = filter; state.scroll = 0; + state.wheel_scrolled = false; drop(state); self.reconcile_command_center_selection(); } diff --git a/codex-rs/tui/src/app/agent_center/render.rs b/codex-rs/tui/src/app/agent_center/render.rs index 3d486fc5fc..4938468040 100644 --- a/codex-rs/tui/src/app/agent_center/render.rs +++ b/codex-rs/tui/src/app/agent_center/render.rs @@ -156,7 +156,6 @@ impl Renderable for AgentsOverviewView { self.layout_center_help(layout.body, top) .render(layout.body, buf); } - let footer_hints = self.center_footer_hints(); let mut state = self.state(); state.row_hits.clear(); let header_active = self.hint_focus.is_active() && !help; @@ -317,6 +316,14 @@ impl Renderable for AgentsOverviewView { } else { None }; + drop(state); + if !help { + self.render_center_rows( + layout.list, + buf, + /*progress_in_footer*/ progress.is_some(), + ); + } if let Some((label, started_at)) = progress { let glyph = self.dock_motion.as_ref().map_or("", |(motion, frames)| { loading_glyph_with_delay(started_at, LOADING_FRAME_INTERVAL, *motion, frames) @@ -334,13 +341,13 @@ impl Renderable for AgentsOverviewView { } else if let Some(notice) = notice.filter(|_| !help) { line(notice.dim(), footer, buf); } else { - let hints = footer_hints + let hints = self + .center_footer_hints() .into_iter() .map(|(key, label)| Hint::key(key, label)); let row = self.hint_focus.render_row(hints, footer.width); line(row.line, footer, buf); } - drop(state); if help { return; } @@ -351,11 +358,6 @@ impl Renderable for AgentsOverviewView { .set_style(Style::default().dim()); } } - self.render_center_rows( - layout.list, - buf, - /*progress_in_footer*/ progress.is_some(), - ); if !layout.details.is_empty() { self.render_details(layout.details, buf); } diff --git a/codex-rs/tui/src/app/agent_center/rows.rs b/codex-rs/tui/src/app/agent_center/rows.rs index 4a239f642f..9bdf712d44 100644 --- a/codex-rs/tui/src/app/agent_center/rows.rs +++ b/codex-rs/tui/src/app/agent_center/rows.rs @@ -11,6 +11,7 @@ use super::*; use crate::bottom_pane::selection_style; use crate::resume_picker::format_relative_time; use crate::status::format_directory_display; +use std::ops::Range; fn columns(area: Rect, widths: Option<(u16, u16)>) -> (Rect, Rect, Rect) { let gutter = area.width.min(/*other*/ 4); @@ -40,6 +41,9 @@ pub(super) struct TaskListLayout { padding: u16, heading: &'static str, indices: Vec, + entries: Vec, + selected: usize, + page: Range, } impl AgentsOverviewView { @@ -56,12 +60,29 @@ impl AgentsOverviewView { let heading = "Tasks"; let viewport = row(area, top_padding, area.height - top_padding - padding); state.scroll_area = viewport; - state.scroll_limit = 0; + let entries = self.center_rows(&indices, &state); + let limit = entries.len().saturating_sub(usize::from(viewport.height)); + state.scroll_limit = limit; + // At two or three lines high, the wheel pages by whole items. Each + // heading, task or notice can start a page, with its details below. + state.short_page_starts.clear(); + if (2..=3).contains(&viewport.height) && state.list_width < STATUS_COLUMNS_MIN_WIDTH { + state + .short_page_starts + .extend((0..limit).filter(|&i| { + !matches!(entries[i], TaskListRow::Context(_) | TaskListRow::Gap) + })); + state.short_page_starts.push(limit); + } + let (selected, page) = visible_page(&entries, self.selected, &mut state); TaskListLayout { area, padding, heading, indices, + entries, + selected, + page, } } @@ -77,13 +98,16 @@ impl AgentsOverviewView { padding, heading, indices, + entries, + selected, + page, } = self.layout_task_viewport(area); let mut state = self.state(); let viewport = state.scroll_area; - let entries = self.center_rows(&indices, &state); if area.is_empty() { return; } + state.selection_offscreen = !entries.is_empty() && !page.contains(&selected); if entries.is_empty() { line( if state.connection_notice.is_some() { @@ -154,7 +178,6 @@ impl AgentsOverviewView { .right_aligned() .render(updated, buf); } - let (_, page) = visible_page(&entries, self.selected, &mut state); let has_previous = page.start > 0; let has_next = page.end < entries.len(); for (offset, entry) in entries[page].iter().enumerate() { diff --git a/codex-rs/tui/src/app/agent_center_tests.rs b/codex-rs/tui/src/app/agent_center_tests.rs index 01401cffd7..bea9b091d3 100644 --- a/codex-rs/tui/src/app/agent_center_tests.rs +++ b/codex-rs/tui/src/app/agent_center_tests.rs @@ -495,10 +495,81 @@ async fn live_center_columns() { ); } +#[tokio::test] +async fn holding_stop_after_wheeling_reveals_the_task_until_a_fresh_press() -> Result<()> { + use crossterm::event::KeyEventKind; + + let (mut app, mut events, _ops) = make_test_app_with_channels().await; + crate::app::test_support::enable_side_retention(&mut app)?; + // Stop takes priority over a matching list shortcut, including while hidden. + let config: TuiKeymap = toml::from_str("[list]\ncancel = 'x'\n[agents]\nstop = 'x'")?; + app.keymap = RuntimeKeymap::from_config(&config).unwrap(); + let mut tui = crate::tui::test_support::make_test_tui()?; + tui.set_owned_screen(/*owned*/ true)?; + let mut server = crate::start_embedded_app_server_for_picker(&app.config).await?; + let id = ThreadId::from_u128(/*value*/ 100); + let tasks = (0..7) + .map(|index| { + let mut task = overview_thread( + ThreadId::from_u128(100 + index), + /*parent_thread_id*/ None, + &format!("Working task {index}"), + ThreadStatus::Active { + active_flags: vec![], + }, + ); + task.updated_at -= index as i64; + task + }) + .collect(); + let view = app.agents_overview_view(tasks, Some(id)); + app.agents_overview.workspace.replace_view(view); + app.agents_overview.workspace.focus_center(); + let page = |app: &crate::app::App| { + screen( + app.agents_overview.workspace.view.as_ref().unwrap(), + /*width*/ 40, + /*height*/ 9, + ) + }; + let first = page(&app); + let wheel = MouseEvent { + row: painted_row(&first, "Working task 0"), + ..WHEEL_DOWN + }; + while app + .agents_overview + .workspace + .view + .as_ref() + .unwrap() + .scroll_mouse(wheel) + { + page(&app); + } + assert!(!page(&app).contains("Working task 0")); + while events.try_recv().is_ok() {} + let stop = KeyEvent::from(KeyCode::Char('x')); + for kind in [ + KeyEventKind::Press, + KeyEventKind::Repeat, + KeyEventKind::Press, + KeyEventKind::Release, + ] { + Box::pin(app.handle_workspace_key(&mut tui, &mut server, KeyEvent { kind, ..stop })).await; + assert_eq!(page(&app), first); + assert!(events.try_recv().is_err()); + } + Box::pin(app.handle_workspace_key(&mut tui, &mut server, stop)).await; + assert_matches!(events.try_recv(), Ok(AppEvent::StopAgentsOverviewThread { thread_id }) if thread_id == id); + tui.set_owned_screen(/*owned*/ false)?; + Ok(()) +} + #[tokio::test] async fn live_center_pages_visible_rows_without_wrapping() { for (count, offline) in [(5, false), (30, true)] { - let app = make_test_app().await; + let mut app = make_test_app().await; let first = ThreadId::from_u128(/*value*/ 100); let threads = (0..count) .map(|index| { @@ -509,6 +580,13 @@ async fn live_center_pages_visible_rows_without_wrapping() { ThreadStatus::Idle, ); thread.updated_at -= index as i64; + if offline { + thread.git_info = Some(codex_app_server_protocol::GitInfo { + sha: None, + branch: Some(format!("branch-{index:02}")), + origin_url: None, + }); + } if index >= 10 { thread.cwd = test_path_buf(&format!("/tmp/second-project-{index:02}")) .abs() @@ -516,16 +594,104 @@ async fn live_center_pages_visible_rows_without_wrapping() { } thread }) - .collect(); - let mut view = app.agents_overview_view(threads, Some(first)); + .collect::>(); + let mut view = app.agents_overview_view(threads.clone(), Some(first)); if offline { + // Each title and its context should be reachable in a short viewport. + for height in 7..=11 { + use crossterm::event::MouseEventKind; + let first = screen(&view, /*width*/ 40, height); + let row = painted_row(&first, "Paging task 00"); + for kind in [MouseEventKind::ScrollDown, MouseEventKind::ScrollUp] { + let mut pages = screen(&view, /*width*/ 40, height); + let wheel = MouseEvent { + row, + kind, + ..WHEEL_DOWN + }; + while view.scroll_mouse(wheel) { + let frame = screen(&view, /*width*/ 40, height); + assert!(frame.contains("Paging task"), "{frame}"); + assert!( + !pages.ends_with(&frame), + "stationary wheel at height {height}" + ); + pages.push_str(&frame); + } + for index in 0..count { + assert!(pages.contains(&format!("Paging task {index:02}"))); + if height > 7 { + let branch = format!("branch-{index:02}"); + assert!( + pages.contains(&branch), + "missing {branch} at height {height}" + ); + } + } + } + view.follow_keyboard_selection(); + } app.agents_overview .view_state .lock() .unwrap() .connection_notice = Some("Reconnecting…"); view.handle_key_event(KeyCode::Char('/').into()); + screen(&view, /*width*/ 48, /*height*/ 12); + assert!(view.scroll_mouse(WHEEL_DOWN)); view.handle_paste("Paging".into()); + assert!(screen(&view, /*width*/ 48, /*height*/ 12).contains("Paging task 00")); + } else { + let page = + |view: &AgentsOverviewView| screen(view, /*width*/ 48, /*height*/ 10); + let first_page = page(&view); + assert!(!view.scroll_mouse(MouseEvent { + row: 0, + ..WHEEL_DOWN + })); + assert!(view.scroll_mouse(WHEEL_DOWN)); + let next_page = page(&view); + let short = + |view: &AgentsOverviewView| screen(view, /*width*/ 48, /*height*/ 9); + // Return from a resized guide and wheel before the task list is repainted. + short(&view); + view.handle_key_event(KeyCode::Char('?').into()); + page(&view); + view.handle_key_event(KeyCode::Esc.into()); + assert!(view.scroll_mouse(WHEEL_DOWN)); + assert_eq!(page(&view), next_page); + + app.primary_thread_id = Some(first); + let mut current = app.agents_overview_view(threads, Some(first)); + current.follow_changed_conversation(&view); + assert_eq!(page(¤t), first_page); + view = current; + for _ in 0..3 { + short(&view); + view.scroll_mouse(WHEEL_DOWN); + } + let short_page = short(&view); + insta::assert_snapshot!( + "live_center_after_wheel", + format!("{next_page}\n\n{short_page}") + ); + assert!(!next_page.contains("Paging task 00")); + assert_eq!(view.rows[view.selected_index().unwrap()].thread_id, first); + for _ in 0..count { + view.scroll_mouse(WHEEL_DOWN); + } + assert!(!view.scroll_mouse(WHEEL_DOWN)); + assert!(page(&view).contains("Paging task 04")); + // The first shortcut brings its target back into view. + view.handle_key_event(KeyCode::Char('?').into()); + page(&view); + view.handle_key_event(KeyCode::Esc.into()); + view.handle_key_event(KeyCode::Char('r').into()); + assert_eq!(page(&view), first_page); + view.handle_key_event(KeyCode::Char('r').into()); + assert!(page(&view).contains("Rename")); + assert!(!view.scroll_mouse(WHEEL_DOWN)); + view.handle_key_event(KeyCode::Esc.into()); } screen(&view, /*width*/ 110, /*height*/ 18); view.handle_key_event(KeyCode::PageDown.into()); @@ -600,6 +766,14 @@ async fn live_center_pages_full_task_rows_and_restores_the_first_heading() { assert_eq!(selected(&view), expected); } + // Three visible lines fit one complete title and detail pair. + view.handle_key_event(KeyCode::Home.into()); + screen(&view, /*width*/ 40, /*height*/ 9); + for expected in [ids[1], ids[2]] { + view.handle_key_event(KeyCode::PageDown.into()); + assert_eq!(selected(&view), expected); + } + let mut view = app.agents_overview_view(threads, Some(ids[0])); let initial = screen(&view, /*width*/ 80, /*height*/ 16); view.handle_key_event(KeyCode::PageDown.into()); diff --git a/codex-rs/tui/src/app/agents_overview_actions.rs b/codex-rs/tui/src/app/agents_overview_actions.rs index 9d4dd74903..8b3f5431ba 100644 --- a/codex-rs/tui/src/app/agents_overview_actions.rs +++ b/codex-rs/tui/src/app/agents_overview_actions.rs @@ -81,7 +81,12 @@ async fn run_lifecycle_modal( if let Some(key) = app.route_key_chord_event(tui, key) { if dock_owns_input { if let Some(view) = &mut app.agents_overview.workspace.view { - view.handle_key_event(key); + super::conversation_workspace::dispatch_docked_key( + view, + &mut app.chat_widget, + key, + app.routed_key_activation, + ); } } else { app.chat_widget.handle_key_event_with_activation_key(key, app.routed_key_activation); diff --git a/codex-rs/tui/src/app/agents_overview_view.rs b/codex-rs/tui/src/app/agents_overview_view.rs index 98c1a786ab..d3cc147c34 100644 --- a/codex-rs/tui/src/app/agents_overview_view.rs +++ b/codex-rs/tui/src/app/agents_overview_view.rs @@ -186,6 +186,9 @@ pub(super) struct AgentsOverviewViewState { scroll: usize, scroll_area: Rect, scroll_limit: usize, + short_page_starts: Vec, + wheel_scrolled: bool, + selection_offscreen: bool, list_width: u16, status_filter: usize, help_top: Option, @@ -391,7 +394,9 @@ impl AgentsOverviewView { && self.visible_indices().contains(&index) { self.selected = index; - self.state().show_more_selected = false; + let mut state = self.state(); + state.wheel_scrolled = false; + state.show_more_selected = false; } } @@ -534,6 +539,7 @@ impl AgentsOverviewView { let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner); let searching = state.searching; if searching { + state.wheel_scrolled = false; edit(&mut state.search); state.restart_history_search(); } @@ -726,6 +732,7 @@ impl BottomPaneView for AgentsOverviewView { fn on_ctrl_c(&mut self) -> CancellationEvent { let mut state = self.state(); if state.editing_metadata() { + state.wheel_scrolled = false; let restore = state.searching.then_some(state.browse_selection); state.history = None; state.searching = false; @@ -763,7 +770,13 @@ impl BottomPaneView for AgentsOverviewView { false } - fn handle_key_event(&mut self, mut key: KeyEvent) { + fn handle_key_event(&mut self, key: KeyEvent) { + self.handle_task_key(key, || {}); + } +} + +impl AgentsOverviewView { + pub(super) fn handle_task_key(&mut self, mut key: KeyEvent, on_reveal: impl FnOnce()) { // Terminals encode Shift-Tab as either BackTab or Tab with the shift modifier. if key.code == KeyCode::BackTab { key.code = KeyCode::Tab; @@ -772,6 +785,7 @@ impl BottomPaneView for AgentsOverviewView { if key.kind == crossterm::event::KeyEventKind::Release { return; } + self.follow_keyboard_selection(); if self.rename_key(key) || self.command_center_key(key) { return; } @@ -819,10 +833,19 @@ impl BottomPaneView for AgentsOverviewView { return; } - if self.state().task_actions_blocked() - && self.keymap.action_for(key) != Some(ListAction::Cancel) + // A task shortcut after wheeling the highlight out of sight first reveals + // its target. Movement still follows the keyboard selection. + let hidden = self.state().selection_offscreen + && !self.agents_keymap.resume.is_pressed(key) + && !self.agents_keymap.toggle_grouping.is_pressed(key); + let list_action = self + .keymap + .action_for(key) + .filter(|_| !hidden || !self.editor_keymap.agents_binding_matches(key)); + if (hidden || self.state().task_actions_blocked()) + && list_action != Some(ListAction::Cancel) { - match self.keymap.action_for(key) { + match list_action { Some(ListAction::MoveUp) => self.move_selection(/*forward*/ false), Some(ListAction::MoveDown) => self.move_selection(/*forward*/ true), Some(action @ (ListAction::PageUp | ListAction::PageDown)) => { @@ -831,6 +854,7 @@ impl BottomPaneView for AgentsOverviewView { Some(action @ (ListAction::JumpTop | ListAction::JumpBottom)) => { self.jump_selection(action) } + _ if hidden => on_reveal(), _ => {} } return; @@ -942,7 +966,7 @@ impl BottomPaneView for AgentsOverviewView { return; } - if let Some(action) = self.keymap.action_for(key) { + if let Some(action) = list_action { if self.state().rename_target.is_some() && matches!(action, ListAction::JumpTop | ListAction::JumpBottom) { diff --git a/codex-rs/tui/src/app/conversation_workspace.rs b/codex-rs/tui/src/app/conversation_workspace.rs index 5674d55f70..29a9d95d2a 100644 --- a/codex-rs/tui/src/app/conversation_workspace.rs +++ b/codex-rs/tui/src/app/conversation_workspace.rs @@ -4,12 +4,14 @@ use super::App; use super::agents_overview_view::AgentsOverviewView; use super::sidebar::PaneFocus; +use crate::activation_key_guard::ActivationKeyGuard; use crate::activation_key_guard::ActivationKeySuppression; use crate::app_event::AppEvent; use crate::app_event::ExitMode; use crate::app_server_session::AppServerSession; use crate::bottom_pane::BottomPaneView; use crate::bottom_pane::CancellationEvent; +use crate::chatwidget::ChatWidget; use crate::key_hint::KeyBinding; use crate::key_hint::KeyBindingListExt; use crate::render::renderable::Renderable; @@ -26,6 +28,20 @@ use ratatui::layout::Constraint; use ratatui::layout::Layout; use ratatui::layout::Rect; +pub(super) fn dispatch_docked_key( + view: &mut AgentsOverviewView, + widget: &mut ChatWidget, + key: KeyEvent, + activation: Option, +) { + view.handle_task_key(key, || { + widget.set_view_transition_key_guard(ActivationKeyGuard::for_task_action( + activation.unwrap_or_else(|| KeyBinding::from_event(key)), + Instant::now(), + )); + }); +} + const CENTER_WIDTH: u16 = 36; // One column for the divider and one for padding before the conversation. const GUTTER_WIDTH: u16 = 2; @@ -55,6 +71,9 @@ impl Workspace { pub(super) fn focus_center(&mut self) { self.focus = Some(Pane::Center); + if let Some(view) = &self.view { + view.follow_keyboard_selection(); + } } pub(super) fn replace_view(&mut self, mut view: AgentsOverviewView) { @@ -185,7 +204,7 @@ impl App { .view .as_ref() .is_some_and(|view| !view.owns_nested_input()) - && !self.agents_overview_binding_matches(key) + && !self.keymap.agents_binding_matches(key) { let bindings = &self.keymap.app; let main = bindings.focus_main_composer.is_pressed(key); @@ -234,6 +253,7 @@ impl App { .send(AppEvent::Exit(ExitMode::ShutdownFirst)); } } else { + let activation = self.routed_key_activation; // The destination widget inherits this guard, including during a slow resume. if self.keymap.list.action_for(key) == Some(crate::keymap::ListAction::Accept) { let activation = self @@ -246,7 +266,7 @@ impl App { crate::activation_key_guard::ActivationKeySuppression::ReportedRepeats, ); } - view.handle_key_event(key); + dispatch_docked_key(view, &mut self.chat_widget, key, activation); } if view.is_complete() { self.agents_overview.workspace.focus = None; diff --git a/codex-rs/tui/src/app/input.rs b/codex-rs/tui/src/app/input.rs index 5502bb8c86..df22f70712 100644 --- a/codex-rs/tui/src/app/input.rs +++ b/codex-rs/tui/src/app/input.rs @@ -174,7 +174,7 @@ impl App { let was_pending = self.key_chord_matcher.is_pending(); if !was_pending && self.workspace_center_owns_input() - && self.agents_overview_binding_matches(key_event) + && self.keymap.agents_binding_matches(key_event) { return Some(key_event); } @@ -315,15 +315,6 @@ impl App { } } - pub(super) fn agents_overview_binding_matches(&self, key: KeyEvent) -> bool { - keymap_action_ids() - .filter(|id| id.context == crate::keymap::KeymapContext::Agents) - .any(|id| { - bindings_for_action(&self.keymap, id.context.config_name(), id.action) - .is_some_and(|bindings| bindings.is_pressed(key)) - }) - } - pub(super) fn active_keymap_contexts(&self) -> crate::keymap::KeymapContextSet { if self.workspace_center_owns_input() && let Some(view) = &self.agents_overview.workspace.view diff --git a/codex-rs/tui/src/app/snapshots/codex_tui__app__agents_overview__tests__command_center__live_center_after_wheel.snap b/codex-rs/tui/src/app/snapshots/codex_tui__app__agents_overview__tests__command_center__live_center_after_wheel.snap new file mode 100644 index 0000000000..9a218b17b8 --- /dev/null +++ b/codex-rs/tui/src/app/snapshots/codex_tui__app__agents_overview__tests__command_center__live_center_after_wheel.snap @@ -0,0 +1,24 @@ +--- +source: tui/src/app/agent_center_tests.rs +expression: "format!(\"{next_page}\\n\\n{short_page}\")" +--- + Agent command center Group: Project g + All 5 Needs you 0 Working 0 › + ──────────────────────────────────────────── + ↑ Tasks + ○ Paging task 01 + Ready + ○ Paging task 02 + Ready + ↓ + enter show selection · ? help · ↑/↓ move + + Agent command center Group: Project g + All 5 Needs you 0 Working 0 › + ──────────────────────────────────────────── + ↑ Tasks + ○ Paging task 02 + Ready + ○ Paging task 03 + ↓ + enter show selection · ? help · ↑/↓ move diff --git a/codex-rs/tui/src/chatwidget/interaction.rs b/codex-rs/tui/src/chatwidget/interaction.rs index 6eb4c20610..f638fa97b6 100644 --- a/codex-rs/tui/src/chatwidget/interaction.rs +++ b/codex-rs/tui/src/chatwidget/interaction.rs @@ -120,10 +120,17 @@ impl ChatWidget { /// Held keys belong to the terminal input stream across conversation switches. pub(crate) fn inherit_view_transition_key_guard(&mut self, previous: &mut Self) { if let Some(guard) = previous.bottom_pane.view_transition_key_guard.take() { - self.bottom_pane.view_transition_key_guard = Some(guard); + self.set_view_transition_key_guard(guard); } } + pub(crate) fn set_view_transition_key_guard( + &mut self, + guard: crate::activation_key_guard::ActivationKeyGuard, + ) { + self.bottom_pane.view_transition_key_guard = Some(guard); + } + pub(crate) fn protect_modal_from_held_activation_key(&mut self, now: Instant) { if !self.bottom_pane.reports_key_releases() && let Some(guard) = &mut self.bottom_pane.view_transition_key_guard diff --git a/codex-rs/tui/src/keymap.rs b/codex-rs/tui/src/keymap.rs index 49b4328c29..175acc4d2a 100644 --- a/codex-rs/tui/src/keymap.rs +++ b/codex-rs/tui/src/keymap.rs @@ -1865,6 +1865,15 @@ impl RuntimeKeymap { Ok(resolved) } + pub(crate) fn agents_binding_matches(&self, key: KeyEvent) -> bool { + keymap_action_ids() + .filter(|id| id.context == KeymapContext::Agents) + .any(|id| { + bindings_for_action(self, id.context.config_name(), id.action) + .is_some_and(|bindings| bindings.is_pressed(key)) + }) + } + /// Resolve the visible primary shortcut from configured declaration order. pub(crate) fn primary_hint( &self, diff --git a/codex-rs/tui/src/terminal_capabilities/keyboard_modes.rs b/codex-rs/tui/src/terminal_capabilities/keyboard_modes.rs index 7baf7c8db2..e5019a48ca 100644 --- a/codex-rs/tui/src/terminal_capabilities/keyboard_modes.rs +++ b/codex-rs/tui/src/terminal_capabilities/keyboard_modes.rs @@ -79,6 +79,19 @@ fn parse_bool_env(value: Option<&str>) -> Option { } } +/// Check immediately after a task activation press. With legacy VT input, +/// ConPTY writes a down/up pair together for each repeated character. +/// With Win32 input enabled, the physical release normally arrives later. +/// A buffered tap can look like a pair, so keep the guard when ambiguous. +pub(crate) fn activation_release_may_be_paired() -> bool { + #[cfg(windows)] + if std::io::IsTerminal::is_terminal(&std::io::stdin()) { + use std::os::windows::io::AsRawHandle; + return super::terminal_probe::release_may_be_queued(std::io::stdin().as_raw_handle()); + } + false +} + pub(super) fn running_in_vscode_terminal() -> bool { detect_vscode_terminal() == VscodeDetection::VsCode } diff --git a/codex-rs/tui/src/terminal_capabilities/terminal_probe/windows.rs b/codex-rs/tui/src/terminal_capabilities/terminal_probe/windows.rs index 57dd734767..c3fceb668f 100644 --- a/codex-rs/tui/src/terminal_capabilities/terminal_probe/windows.rs +++ b/codex-rs/tui/src/terminal_capabilities/terminal_probe/windows.rs @@ -1,4 +1,4 @@ -//! Probe visible Windows terminal colors without consuming startup typeahead. +//! Inspect Windows console input and probe visible colors without consuming startup typeahead. use super::DefaultColors; use super::windows_replay::terminal_color_response_ranges; @@ -19,6 +19,7 @@ use windows_sys::Win32::System::Console::GetNumberOfConsoleInputEvents; use windows_sys::Win32::System::Console::GetStdHandle; use windows_sys::Win32::System::Console::INPUT_RECORD; use windows_sys::Win32::System::Console::KEY_EVENT; +use windows_sys::Win32::System::Console::PeekConsoleInputW; use windows_sys::Win32::System::Console::ReadConsoleInputW; use windows_sys::Win32::System::Console::STD_INPUT_HANDLE; use windows_sys::Win32::System::Console::STD_OUTPUT_HANDLE; @@ -29,6 +30,20 @@ use windows_sys::Win32::UI::WindowsAndMessaging::GetClassNameW; const MAX_WINDOWS_PROBE_RECORDS: usize = 64 * 1_024; const WINDOWS_PROBE_READ_RECORDS: usize = 64; +/// Peek at the console queue. If the peek fails, keep the held-key guard active. +pub(crate) fn release_may_be_queued(input: HANDLE) -> bool { + let mut record = INPUT_RECORD::default(); + let mut count = 0; + // SAFETY: Both output pointers have space for the single requested record and count. + if unsafe { PeekConsoleInputW(input, &mut record, 1, &mut count) } == 0 { + return true; + } + // SAFETY: EventType identifies the active member of the returned record. + count == 1 + && record.EventType == KEY_EVENT as u16 + && unsafe { record.Event.KeyEvent.bKeyDown == 0 } +} + /// Prefer OSC colors; use native colors only when the renderer shares the console palette. /// /// Windows Terminal and xterm.js can render a theme unrelated to ConPTY's console color table. diff --git a/codex-rs/tui/src/tui.rs b/codex-rs/tui/src/tui.rs index b9d9f4d6be..3ca78bb4d0 100644 --- a/codex-rs/tui/src/tui.rs +++ b/codex-rs/tui/src/tui.rs @@ -71,6 +71,9 @@ mod input_boundary; #[cfg(unix)] mod job_control; mod link_pointer; +#[cfg(all(test, windows))] +#[path = "tui/windows_console_tests.rs"] +mod windows_console_tests; pub(crate) use link_pointer::PointerShape; #[cfg(test)] #[path = "tui/inline_image_history_tests.rs"] diff --git a/codex-rs/tui/src/tui/alternate_screen.rs b/codex-rs/tui/src/tui/alternate_screen.rs index d10f3b3c6a..d30f88f3ed 100644 --- a/codex-rs/tui/src/tui/alternate_screen.rs +++ b/codex-rs/tui/src/tui/alternate_screen.rs @@ -297,7 +297,3 @@ impl super::MouseCapture { #[cfg(test)] #[path = "alternate_screen_tests.rs"] mod tests; - -#[cfg(all(test, windows))] -#[path = "alternate_screen_windows_tests.rs"] -mod windows_tests; diff --git a/codex-rs/tui/src/tui/alternate_screen_windows_tests.rs b/codex-rs/tui/src/tui/windows_console_tests.rs similarity index 54% rename from codex-rs/tui/src/tui/alternate_screen_windows_tests.rs rename to codex-rs/tui/src/tui/windows_console_tests.rs index 6ae454c0a9..4bfa40bb18 100644 --- a/codex-rs/tui/src/tui/alternate_screen_windows_tests.rs +++ b/codex-rs/tui/src/tui/windows_console_tests.rs @@ -1,18 +1,27 @@ -//! Exercise Windows console mouse capture in a separate process with its own console. +#![cfg(test)] +//! Exercise native input handling in a separate process with its own Windows console. -use super::AlternateScreen; +use super::alternate_screen::AlternateScreen; +use crate::terminal_capabilities::terminal_probe::release_may_be_queued; use pretty_assertions::assert_eq; use std::fs::File; use std::fs::OpenOptions; use std::os::windows::io::AsRawHandle; use std::os::windows::process::CommandExt; use std::process::Command; +use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE; use windows_sys::Win32::System::Console::ENABLE_MOUSE_INPUT; +use windows_sys::Win32::System::Console::FOCUS_EVENT; +use windows_sys::Win32::System::Console::FlushConsoleInputBuffer; use windows_sys::Win32::System::Console::GetConsoleMode; +use windows_sys::Win32::System::Console::GetNumberOfConsoleInputEvents; +use windows_sys::Win32::System::Console::INPUT_RECORD; +use windows_sys::Win32::System::Console::KEY_EVENT; use windows_sys::Win32::System::Console::SetConsoleMode; +use windows_sys::Win32::System::Console::WriteConsoleInputW; use windows_sys::Win32::System::Threading::CREATE_NEW_CONSOLE; -const CHILD_ENV: &str = "CODEX_TUI_MOUSE_CAPTURE_TEST_CHILD"; +const CHILD_ENV: &str = "CODEX_TUI_CONSOLE_TEST_CHILD"; fn console_mode(input: &File) -> u32 { let mut mode = 0; @@ -22,13 +31,12 @@ fn console_mode(input: &File) -> u32 { mode } -#[test] -fn mouse_capture_restores_console_mode_and_encoding() { +fn private_console(test: &str) -> Option { if std::env::var_os(CHILD_ENV).is_none() { let output = Command::new(std::env::current_exe().expect("test binary")) .args([ "--exact", - "tui::alternate_screen::windows_tests::mouse_capture_restores_console_mode_and_encoding", + &format!("tui::windows_console_tests::{test}"), "--nocapture", ]) .env(CHILD_ENV, "1") @@ -41,7 +49,7 @@ fn mouse_capture_restores_console_mode_and_encoding() { String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr), ); - return; + return None; } let input = OpenOptions::new() @@ -49,6 +57,54 @@ fn mouse_capture_restores_console_mode_and_encoding() { .write(true) .open("CONIN$") .expect("open console input"); + Some(input) +} + +#[test] +fn release_probe_preserves_console_input() { + let Some(input) = private_console("release_probe_preserves_console_input") else { + return; + }; + let handle = input.as_raw_handle(); + let mut release = INPUT_RECORD { + EventType: KEY_EVENT as u16, + ..Default::default() + }; + release.Event.KeyEvent.wRepeatCount = 1; + release.Event.KeyEvent.wVirtualKeyCode = u16::from(b'X'); + release.Event.KeyEvent.uChar.UnicodeChar = u16::from(b'x'); + let mut press = release; + press.Event.KeyEvent.bKeyDown = 1; + let focus = INPUT_RECORD { + EventType: FOCUS_EVENT as u16, + ..Default::default() + }; + + assert!(release_may_be_queued(INVALID_HANDLE_VALUE)); + for (record, expected) in [(release, true), (press, false), (focus, false)] { + // SAFETY: This test owns the console. All output parameters are writable. + assert_ne!(unsafe { FlushConsoleInputBuffer(handle) }, 0); + assert!(!release_may_be_queued(handle)); + let mut count = 0; + assert_ne!( + unsafe { WriteConsoleInputW(handle, &record, 1, &mut count) }, + 0 + ); + assert_eq!(count, 1); + let detected = release_may_be_queued(handle); + assert_ne!( + unsafe { GetNumberOfConsoleInputEvents(handle, &mut count) }, + 0 + ); + assert_eq!((detected, count), (expected, 1)); + } +} + +#[test] +fn mouse_capture_restores_console_mode_and_encoding() { + let Some(input) = private_console("mouse_capture_restores_console_mode_and_encoding") else { + return; + }; let initial_mode = console_mode(&input) & !ENABLE_MOUSE_INPUT; // SAFETY: input is an open console handle and initial_mode is a valid console input mode. let result = unsafe { SetConsoleMode(input.as_raw_handle(), initial_mode) };