From 42248f5ef988883cebce298c2279ce22cb536726 Mon Sep 17 00:00:00 2001 From: Felipe Coury Date: Mon, 16 Nov 2026 23:48:27 +0000 Subject: [PATCH] Add conversation files to the TUI sidebar chooser (#61922) ## What changed - List conversation files alongside side chats and open selected files in the sidebar without jumping to a referenced line. - Show filenames with directory context and add a scrollable full-path view through `p` or the footer action. Show why file previews are unavailable on unsupported hosts. - Support mouse-wheel scrolling independently of selection, keyboard paging, and hover highlighting. Preserve the selected file as the inventory changes. - Activate sidebar rows, tabs, and footer actions only after a matching mouse press and release, rejecting drags and stale targets. ## Testing Add coverage for grouped file rendering, full-path scrolling, selection preservation, and chooser scrolling and keyboard navigation. Update sidebar interaction tests and snapshots. GitOrigin-RevId: aa402b928c09732df4f9a5c982691b97aadb00ca --- codex-rs/tui/src/app.rs | 17 + codex-rs/tui/src/app/event_dispatch.rs | 10 +- codex-rs/tui/src/app/owned_transcript.rs | 132 ++-- codex-rs/tui/src/app/side_focus.rs | 362 +++++++---- codex-rs/tui/src/app/sidebar.rs | 94 ++- .../tui/src/app/sidebar_document_tests.rs | 6 +- codex-rs/tui/src/app/sidebar_files.rs | 62 +- codex-rs/tui/src/app/sidebar_files_tests.rs | 393 ++++++++++++ codex-rs/tui/src/app/sidebar_loading.rs | 1 + ...p__tests__saved_chat_discovery_states.snap | 19 +- codex-rs/tui/src/app/startup.rs | 1 + codex-rs/tui/src/app/test_support.rs | 1 + codex-rs/tui/src/app/tests.rs | 154 +++-- .../src/app/tests/agents_navigation_tests.rs | 25 + codex-rs/tui/src/app/tests/key_chords.rs | 8 +- ...__tests__key_chords__sidebar_new_chat.snap | 3 +- ..._chat_loading__waiting_and_retry_rows.snap | 5 +- codex-rs/tui/src/bottom_pane/mod.rs | 1 - codex-rs/tui/src/sidebar_chooser.rs | 565 ++++++++++++++---- codex-rs/tui/src/sidebar_tab_strip.rs | 16 +- ...ui__app__tests__sidebar_existing_chat.snap | 2 +- 21 files changed, 1469 insertions(+), 408 deletions(-) diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index 2f4d1b18e9..63bb1674df 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -690,6 +690,7 @@ pub(crate) struct App { divider_drag: Option, pane_resize: Option, passive_link_drag: Option<(ThreadId, Rect)>, + sidebar_press: Option, abandoned_side_threads: HashSet, active_thread_id: Option, active_thread_rx: Option>, @@ -872,6 +873,22 @@ impl App { app_server: &mut AppServerSession, event: TuiEvent, ) -> Result { + match &event { + TuiEvent::Draw + | TuiEvent::Mouse(crossterm::event::MouseEvent { + kind: MouseEventKind::Up(_) | MouseEventKind::Moved, + .. + }) => {} + TuiEvent::Mouse(crossterm::event::MouseEvent { + kind: MouseEventKind::Drag(_), + .. + }) => { + if self.sidebar_press.take().is_some() { + return Ok(AppRunControl::Continue); + } + } + _ => self.sidebar_press = None, + } self.transcript_view.document_links = self.document_preview_available(tui, app_server); crate::markdown_render::preferences::set_document_links( self.transcript_view.document_links, diff --git a/codex-rs/tui/src/app/event_dispatch.rs b/codex-rs/tui/src/app/event_dispatch.rs index 7bd9866d57..f1ce22b57b 100644 --- a/codex-rs/tui/src/app/event_dispatch.rs +++ b/codex-rs/tui/src/app/event_dispatch.rs @@ -1095,7 +1095,6 @@ impl App { tui.frame_requester().schedule_frame(); } if finished_current_replay && self.chooser_focus().is_some() - && self.document_preview_available(tui, app_server) { self.refresh_sidebar_files(app_server, id).await; tui.frame_requester().schedule_frame(); @@ -3639,12 +3638,17 @@ impl App { AppEvent::SidebarFilesLoaded { backend_id, parent, request, page } => { if backend_id == app_server.backend_id() && let Some(pane) = self.sidebars.get_mut(&Some(parent)) - && let Some(files) = pane.files.as_mut() - && files.scan.as_ref().is_some_and(|(id, _)| *id == request) + && pane.files.as_ref().and_then(|files| files.scan.as_ref()) + .is_some_and(|(id, _)| *id == request) { + let selected = pane.chat_tabs().file(pane.choice).map(|file| file.path.clone()); + let Some(files) = pane.files.as_mut() else { + return Ok(AppRunControl::Continue); + }; files.scan = None; if let Some(page) = page { if files.apply_page(page) { + pane.restore_file_selection(selected.as_deref()); pane.tabs_revision += 1; } self.start_sidebar_files_scan(app_server, parent); diff --git a/codex-rs/tui/src/app/owned_transcript.rs b/codex-rs/tui/src/app/owned_transcript.rs index 2701fc7e33..cbfba3ee59 100644 --- a/codex-rs/tui/src/app/owned_transcript.rs +++ b/codex-rs/tui/src/app/owned_transcript.rs @@ -7,6 +7,7 @@ //! geometry unchanged. Turn tips remain outside transcript history; their painted rows are selectable. //! Plain Enter returns an empty composer to latest after transcript interactions and prompt editing. +use super::side_focus::SidebarTarget; use super::sidebar::PaneFocus; use super::sidebar_document::DocumentRenderOptions; use super::turn_tips::TipSurface; @@ -30,6 +31,8 @@ use crate::transcript_view::TranscriptView; use crate::transcript_view::ViewAction; use crate::turn_tip::TurnTip; use crossterm::event::MouseEventKind; +use ratatui::style::Styled; +use ratatui::style::Stylize; use ratatui::widgets::Widget; /// Remember the last conversation bounds and neighboring content for input-triggered redraws. @@ -39,6 +42,7 @@ pub(super) struct ConversationFrame { pub(super) sidebar: Option, pub(super) chat_strip: Option, pub(super) sidebar_input: Option, + pub(super) sidebar_targets: Vec<(SidebarTarget, Rect)>, pub(super) close_buttons: [Rect; 2], /// A dialog can obscure neighboring content in the terminal's completed buffer. behind_dialog: Option, @@ -312,6 +316,7 @@ impl App { ) }) }); + let mut sidebar_targets = Vec::new(); let sidebar_parent = self.sidebar_parent(); let sidebar_image_protocol = self.preview_image_protocol(tui); let sidebar_motion = @@ -421,17 +426,21 @@ impl App { self.local_settings.tui.animations, ); let glyph = crate::motion::loading_glyph(*started, mode, &frames); - format!("{glyph} Starting side chat…") + ratatui::text::Text::from(Line::from(vec![ + glyph.set_style(crate::style::accent_style()), + " ".into(), + "Starting side chat…".dim(), + ])) } CreationState::Failed { message, .. } => { - if resize_hint.is_some() { + ratatui::text::Text::from(if resize_hint.is_some() { message.clone() } else { crate::sidebar_chooser::creation_failure_text( message, &self.keymap, ) - } + }) } }; ratatui::widgets::Paragraph::new(text) @@ -442,20 +451,43 @@ impl App { label_style, ..pane.chat_tabs() }; + let new_chat = self.chat_widget.side_chat_creation_state(); + let full_path = tabs + .file(pane.choice) + .filter(|_| pane.showing_file_path) + .map(|file| file.path.as_str()); let footer = if let Some(hint) = resize_hint { let row = crate::sidebar_chooser::body_row(*sidebar, sidebar.y); crate::sidebar_chooser::resize_hint(hint, row.width) } else { - crate::sidebar_chooser::footer( + let (hints, actions) = crate::sidebar_chooser::footer( &self.keymap, *sidebar, pane.choice, tabs, - self.chat_widget.side_chat_creation_state(), - ) - .0 - .line + new_chat, + full_path.is_some(), + ); + sidebar_targets.extend( + crate::sidebar_chooser::footer_targets(*sidebar, &hints, actions) + .map(|(action, area)| (SidebarTarget::Footer(action), area)), + ); + hints.line }; + let mut hovered_choice = None; + if full_path.is_none() && resize_hint.is_none() { + for (index, area) in crate::sidebar_chooser::row_targets( + *sidebar, + tabs, + pane.choice, + new_chat, + ) { + if pointer.is_some_and(|point| area.contains(point)) { + hovered_choice = Some(index); + } + sidebar_targets.push((SidebarTarget::Row(index), area)); + } + } crate::sidebar_chooser::paint( focused, *sidebar, @@ -464,12 +496,15 @@ impl App { tabs, pane.choice, &crate::sidebar_chooser::SidebarStyle { - new_chat: self.chat_widget.side_chat_creation_state(), + new_chat, use_theme_colors: self.local_settings.tui.status_line_use_colors, motion: MotionMode::from_animations_enabled( self.local_settings.tui.animations, ), frames: &frames, + hovered_choice, + full_path, + path_scroll: pane.file_path_scroll, }, ); } @@ -495,25 +530,27 @@ impl App { ratatui::widgets::Clear .render(side_pane::tab_and_body(*sidebar)[0], frame.buffer); } - crate::sidebar_chooser::tab_strip( - *sidebar, - chooser, - if document && focused { - TabState::Active - } else if document { - TabState::Inactive - } else { - TabState::Absent - }, - crate::sidebar_chooser::ChatTabs { - label_style, - ..pane.chat_tabs() - }, - pointer - .and_then(|point| pane.chat_tabs().strip().hit(*sidebar, point)) - .map(|(target, _)| target), - |id, width| pane.document_title(id, width), - frame.buffer, + sidebar_targets.extend( + crate::sidebar_chooser::tab_strip( + *sidebar, + chooser, + if document && focused { + TabState::Active + } else if document { + TabState::Inactive + } else { + TabState::Absent + }, + crate::sidebar_chooser::ChatTabs { + label_style, + ..pane.chat_tabs() + }, + pointer, + |id, width| pane.document_title(id, width), + frame.buffer, + ) + .into_iter() + .map(|(target, area)| (SidebarTarget::Tab(target), area)), ); } } @@ -522,21 +559,34 @@ impl App { if let Some(strip) = strip && let Some(pane) = self.sidebar() { - crate::sidebar_chooser::tab_strip( - strip, - TabState::Absent, - chat, - crate::sidebar_chooser::ChatTabs { - label_style, - ..pane.chat_tabs() - }, - pointer - .and_then(|point| pane.chat_tabs().strip().hit(strip, point)) - .map(|(target, _)| target), - |id, width| pane.document_title(id, width), - frame.buffer, + sidebar_targets.extend( + crate::sidebar_chooser::tab_strip( + strip, + TabState::Absent, + chat, + crate::sidebar_chooser::ChatTabs { + label_style, + ..pane.chat_tabs() + }, + pointer, + |id, width| pane.document_title(id, width), + frame.buffer, + ) + .into_iter() + .map(|(target, area)| (SidebarTarget::Tab(target), area)), ); } + if let Some(point) = pointer { + for &(target, area) in &sidebar_targets { + if matches!(target, SidebarTarget::Footer(_)) && area.contains(point) { + frame.buffer.set_style( + area, + crate::style::hover_style(crate::style::quiet_workspace_style()), + ); + } + } + } + self.conversation_frame.sidebar_targets = std::mem::take(&mut sidebar_targets); if let Some(divider) = divider { side_pane::paint_divider(frame, divider.x, self.divider_drag, highlight_divider); } diff --git a/codex-rs/tui/src/app/side_focus.rs b/codex-rs/tui/src/app/side_focus.rs index 37586652eb..e6a85752eb 100644 --- a/codex-rs/tui/src/app/side_focus.rs +++ b/codex-rs/tui/src/app/side_focus.rs @@ -7,7 +7,6 @@ use super::sidebar_close::Action::CloseTab; use super::*; use crate::activation_key_guard::ActivationKeySuppression; use crate::app_event::SideStartMode; -use crate::bottom_pane::ScrollState; use crate::keymap::ListAction; use crate::sidebar_chooser; use crate::sidebar_chooser::ChooserAction; @@ -16,21 +15,35 @@ use crate::sidebar_tab_strip::SidebarTab; use crate::sidebar_tab_strip::TabTarget; use crate::transcript_view::TranscriptView; +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum SidebarTarget { + Tab(TabTarget), + Row(usize), + Footer(ChooserAction), +} + +#[derive(Clone, Copy, PartialEq, Eq)] +pub(super) struct SidebarPress { + parent: Option, + state: sidebar::SidebarInputState, + target: SidebarTarget, + area: Rect, + button: MouseButton, +} + impl App { pub(super) fn hovered_sidebar_target( &self, point: Option, - ) -> Option> { - let point = point?; - let strip = self.conversation_frame.sidebar_tab_strip()?; - if self.pane_resize.is_some() || !strip.contains(point) { + ) -> Option { + if self.pane_resize.is_some() { return None; } - let pane = self.sidebar()?; - let tabs = pane.chat_tabs().strip(); - let target = tabs.hit(strip, point)?.0; - let available = self.chooser_focus().is_none() || pane.creation.is_none(); - available.then_some(target) + let point = point?; + self.conversation_frame + .sidebar_targets + .iter() + .find_map(|(target, area)| area.contains(point).then_some(*target)) } pub(super) fn sidebar_chooser_available(&self) -> bool { @@ -61,9 +74,7 @@ impl App { && let Some(parent) = parent { self.refresh_saved_chats(server, parent); - if self.document_preview_available(tui, server) { - self.refresh_sidebar_files(server, parent).await; - } + self.refresh_sidebar_files(server, parent).await; } tui.frame_requester().schedule_frame(); Ok(()) @@ -186,67 +197,114 @@ impl App { event: &TuiEvent, ) -> bool { if !self.conversation_focus_available(tui) || !self.sidebar_chooser_available() { + self.sidebar_press = None; return false; } - if let TuiEvent::Mouse(mouse) = event - && matches!( - mouse.kind, - MouseEventKind::Down(MouseButton::Left | MouseButton::Middle) - | MouseEventKind::ScrollUp - | MouseEventKind::ScrollDown - ) - { + let mut pointer_action = None; + if let TuiEvent::Mouse(mouse) = event { let point = (mouse.column, mouse.row).into(); let frame = &self.conversation_frame; + let over_strip = frame + .sidebar_tab_strip() + .is_some_and(|area| area.contains(point)); + let over_chooser = self.chooser_focus().is_some() + && frame.panel_area().is_some_and(|area| area.contains(point)); if tui.shortcut_hud_contains(*mouse) { + self.sidebar_press = None; return false; } - let chooser = frame.panel_area(); - let pane = self.sidebar(); - if ((matches!(mouse.kind, MouseEventKind::Down(_)) - && chooser.is_some_and(|area| area.contains(point))) - || frame - .sidebar_tab_strip() - .is_some_and(|area| area.contains(point))) - && frame.sidebar_input != pane.map(sidebar::SidebarPane::input_state) + if over_strip + && matches!( + mouse.kind, + MouseEventKind::ScrollUp | MouseEventKind::ScrollDown + ) { - // A tab may have closed or the chooser scrolled since this frame was painted. - tui.frame_requester().schedule_frame(); - return true; - } - if let Some(pane) = pane - && (self.chooser_focus().is_none() || pane.creation.is_none()) - && let Some(strip) = frame.sidebar_tab_strip() - && strip.contains(point) - { - let target = pane.chat_tabs().strip().hit(strip, point); - let middle = mouse.kind == MouseEventKind::Down(MouseButton::Middle); - let result = match (mouse.kind, target) { - (MouseEventKind::ScrollUp, _) => { - self.step_sidebar_tab(tui, server, /*step*/ -1).await - } - (MouseEventKind::ScrollDown, _) => { - self.step_sidebar_tab(tui, server, /*step*/ 1).await - } - (_, Some((TabTarget::Close(id), _))) - | (MouseEventKind::Down(MouseButton::Middle), Some((TabTarget::Tab(id), _))) => { - self.close_sidebar_tab(tui, server, id).await - } - (_, Some((TabTarget::Add, _))) if !middle => { - self.open_sidebar_tabs(tui, server).await - } - (_, Some((TabTarget::Tab(id) | TabTarget::Overflow { tab: id, .. }, _))) - if !middle => - { - self.activate_sidebar_tab(tui, server, id).await - } - _ => return true, + let step = if mouse.kind == MouseEventKind::ScrollUp { + -1 + } else { + 1 }; - if let Err(err) = result { + if frame.sidebar_input == self.sidebar().map(sidebar::SidebarPane::input_state) + && frame + .sidebar_targets + .iter() + .any(|(target, _)| matches!(target, SidebarTarget::Tab(_))) + && let Err(err) = self.step_sidebar_tab(tui, server, step).await + { self.chat_widget.add_error_message(err.to_string()); } return true; } + if let MouseEventKind::Down(button @ (MouseButton::Left | MouseButton::Middle)) + | MouseEventKind::Up(button @ (MouseButton::Left | MouseButton::Middle)) = mouse.kind + { + let down = matches!(mouse.kind, MouseEventKind::Down(_)); + let pressed = self.sidebar_press.take(); + if over_strip || over_chooser || pressed.is_some() { + let current = self.sidebar().map(sidebar::SidebarPane::input_state); + let hit = frame + .sidebar_targets + .iter() + .find(|(_, area)| area.contains(point)); + let candidate = if frame.sidebar_input == current && self.pane_resize.is_none() + { + hit.zip(current) + .map(|(&(target, area), state)| SidebarPress { + parent: self.sidebar_parent(), + state, + target, + area, + button, + }) + } else { + None + }; + tui.frame_requester().schedule_frame(); + if down { + self.sidebar_press = candidate; + return true; + } + let Some(press) = candidate.filter(|candidate| Some(*candidate) == pressed) + else { + return true; + }; + match press.target { + SidebarTarget::Tab(target) => { + let result = match (button, target) { + (MouseButton::Left, TabTarget::Close(id)) + | ( + MouseButton::Middle, + TabTarget::Tab(id) | TabTarget::Close(id), + ) => self.close_sidebar_tab(tui, server, id).await, + (MouseButton::Left, TabTarget::Add) => { + self.open_sidebar_tabs(tui, server).await + } + ( + MouseButton::Left, + TabTarget::Tab(id) | TabTarget::Overflow { tab: id, .. }, + ) => self.activate_sidebar_tab(tui, server, id).await, + _ => return true, + }; + if let Err(err) = result { + self.chat_widget.add_error_message(err.to_string()); + } + return true; + } + SidebarTarget::Row(index) if button == MouseButton::Left => { + pointer_action = Some(ChooserAction::Open(index)); + } + SidebarTarget::Footer(action) if button == MouseButton::Left => { + pointer_action = Some(action); + } + _ => return true, + } + self.sidebar_mut() + .show(SidebarContent::Chooser, PaneFocus::Sidebar); + } else if down && button == MouseButton::Left && self.chooser_focus().is_some() { + self.sidebar_mut() + .show(SidebarContent::Chooser, PaneFocus::Main); + } + } } if matches!( self.sidebar() @@ -259,61 +317,92 @@ impl App { return false; } let new_chat = self.chat_widget.side_chat_creation_state(); + let chooser_area = self.chooser_area(tui); + let selection_visible = self.sidebar().is_some_and(|pane| { + chooser_area.is_none_or(|area| { + !pane.chooser_scroll.wheel_scrolled + || sidebar_chooser::choice_is_visible(area, pane.chat_tabs(), pane.choice) + }) + }); let (action, activation) = match event { - TuiEvent::Mouse(mouse) if mouse.kind == MouseEventKind::Down(MouseButton::Left) => { - tui.frame_requester().schedule_frame(); - let Some(area) = self - .conversation_frame - .panel_area() - .filter(|area| area.contains((mouse.column, mouse.row).into())) - else { - self.sidebar_mut() - .show(SidebarContent::Chooser, PaneFocus::Main); - return false; - }; + TuiEvent::Mouse(_) if let Some(action) = pointer_action => (action, None), + TuiEvent::Mouse(mouse) + if matches!( + mouse.kind, + MouseEventKind::ScrollUp | MouseEventKind::ScrollDown + ) && let Some(area) = self.conversation_frame.panel_area() + && area.contains((mouse.column, mouse.row).into()) => + { let pane = self.sidebar_mut(); - pane.show(SidebarContent::Chooser, PaneFocus::Sidebar); - if pane.creation.is_some() { - return true; - } - let Some(pane) = self.sidebar() else { - return true; - }; - let choice = pane.choice; - let tabs = pane.chat_tabs(); - let action = if let Some(index) = - sidebar_chooser::choice_at(area, tabs, choice, mouse.row) - .filter(|_| new_chat == sidebar_chooser::NewChatState::Available) - { - ChooserAction::Open(index) - } else if mouse.row == area.bottom() - 1 && mouse.column > area.x { - let column = mouse.column - area.x - 1; - let (hints, actions) = - sidebar_chooser::footer(&self.keymap, area, choice, tabs, new_chat); - let Some(action) = hints - .items - .into_iter() - .zip(actions) - .find_map(|(range, action)| action.filter(|_| range.contains(&column))) - else { - return true; - }; - action + let delta = if mouse.kind == MouseEventKind::ScrollUp { + -3 } else { - return true; + 3 }; - (action, None) + if pane.showing_file_path { + if let Some(file) = pane.chat_tabs().file(pane.choice) { + let action = if delta < 0 { + ListAction::MoveUp + } else { + ListAction::MoveDown + }; + pane.file_path_scroll = sidebar_chooser::scroll_file_path( + area, + &file.path, + pane.file_path_scroll, + action, + ); + } + tui.frame_requester().schedule_frame(); + } else if pane.creation.is_none() && mouse.row < area.bottom() - 1 { + pane.chooser_scroll = + sidebar_chooser::wheel_scroll(area, pane.chat_tabs(), pane.choice, delta); + tui.frame_requester().schedule_frame(); + } + return true; } _ if self.chooser_focus() != Some(PaneFocus::Sidebar) => return false, TuiEvent::Key(key) => { - let Some(list_action) = self.keymap.list.action_for(*key) else { + let list_action = self.keymap.list.action_for(*key); + if list_action.is_none() + && *key == KeyEvent::new(KeyCode::Char('p'), KeyModifiers::NONE) + && self.sidebar().is_some_and(|pane| { + pane.showing_file_path + || (selection_visible && pane.chat_tabs().file(pane.choice).is_some()) + }) + { + let pane = self.sidebar_mut(); + pane.showing_file_path = !pane.showing_file_path; + pane.file_path_scroll = 0; + tui.frame_requester().schedule_frame(); + return true; + } + if self.sidebar().is_some_and(|pane| pane.showing_file_path) + && list_action != Some(ListAction::Cancel) + { + let pane = self.sidebar_mut(); + if let Some(area) = chooser_area + && let Some(file) = pane.chat_tabs().file(pane.choice) + && let Some(action) = list_action + { + pane.file_path_scroll = sidebar_chooser::scroll_file_path( + area, + &file.path, + pane.file_path_scroll, + action, + ); + tui.frame_requester().schedule_frame(); + } + return true; + } + let Some(list_action) = list_action else { return true; }; - let area = self.conversation_frame.panel_area(); let pane = self.sidebar_mut(); if new_chat == sidebar_chooser::NewChatState::WaitingForMainMessage && list_action != ListAction::Cancel && pane.creation.is_none() + && pane.chat_tabs().files.is_empty() { return true; } @@ -327,16 +416,14 @@ impl App { ChooserAction::Back } _ => { - let tabs = pane.chat_tabs(); - let visible = area.map_or(1, |area| { - sidebar_chooser::page_size(area, tabs, pane.choice, list_action) - }); - let mut selection = ScrollState { - selected_idx: Some(pane.choice), - ..Default::default() - }; - selection.apply_vertical_action(list_action, tabs.choice_count(), visible); - pane.choice = selection.selected_idx.unwrap_or_default(); + let area = chooser_area + .unwrap_or_else(|| tui.terminal.last_known_screen_size.into()); + (pane.choice, pane.chooser_scroll) = sidebar_chooser::navigate( + area, + pane.chat_tabs(), + pane.choice, + list_action, + ); return true; } }; @@ -349,6 +436,38 @@ impl App { _ => return matches!(event, TuiEvent::Paste(_)), }; + if action == ChooserAction::FilePath + || self.sidebar().is_some_and(|pane| pane.showing_file_path) + { + let pane = self.sidebar_mut(); + pane.showing_file_path = action == ChooserAction::FilePath + && selection_visible + && pane.chat_tabs().file(pane.choice).is_some(); + pane.file_path_scroll = 0; + tui.frame_requester().schedule_frame(); + return true; + } + + if let ChooserAction::Open(index) = action + && new_chat == sidebar_chooser::NewChatState::WaitingForMainMessage + && self.sidebar().is_some_and(|pane| { + pane.creation.is_none() && pane.chat_tabs().file(index).is_none() + }) + { + return true; + } + if let ChooserAction::Open(index) = action + && let Some(pane) = self.sidebar() + && pane.creation.is_none() + && (pane.chooser_scroll.wheel_scrolled + && chooser_area.is_some_and(|area| { + !sidebar_chooser::choice_is_visible(area, pane.chat_tabs(), index) + }) + || pane.chat_tabs().file(index).is_some() + && pane.file_preview_unavailable.is_some()) + { + return true; + } let open = matches!(action, ChooserAction::Open(_)); let frame = &self.conversation_frame; // Fast keyboard navigation is safe until an asynchronous update changes its target. @@ -412,10 +531,25 @@ impl App { mode: SideStartMode::New, }); } else { + let pane = self.sidebar_mut(); + pane.choice = 0; + pane.chooser_scroll = Default::default(); self.restore_side_user_message(message); } } } + } else if let ChooserAction::Open(index) = action + && let Some(mut link) = pane.chat_tabs().file(index).cloned() + { + // The chooser opens the file. Transcript and reader links carry coordinates. + link.location = None; + if let Some(source) = self.current_displayed_thread_id() { + self.app_event_tx.send(AppEvent::OpenSidebarDocument { + backend_id: server.backend_id(), + source, + link, + }); + } } else if matches!(action, ChooserAction::Back) && let Some(tab @ SidebarTab::Document(_)) = pane.recent_tab(/*excluding*/ None) { @@ -426,7 +560,7 @@ impl App { let target = match action { ChooserAction::Open(index) => pane.chat_tabs().choice(index), ChooserAction::Back => pane.selected_chat(), - ChooserAction::Hide => None, + ChooserAction::Hide | ChooserAction::FilePath => None, }; if let Some(id) = target { let pane = self.sidebar_mut(); diff --git a/codex-rs/tui/src/app/sidebar.rs b/codex-rs/tui/src/app/sidebar.rs index f294dfe24b..1e3640d37e 100644 --- a/codex-rs/tui/src/app/sidebar.rs +++ b/codex-rs/tui/src/app/sidebar.rs @@ -12,6 +12,7 @@ use crate::app_server_session::SideChat; use crate::app_server_session::SideChatStorage; use crate::app_server_session::side_chat_prompt_preview; use crate::sidebar_chooser::ChatTabs; +use crate::sidebar_chooser::ChooserScroll; use crate::sidebar_chooser::Discovery; use crate::sidebar_tab_strip::SidebarTab; use crate::tui::Tui; @@ -67,6 +68,7 @@ pub(super) enum ChooserSelection { New, Chat(ThreadId), Retry, + File(usize), } #[derive(Clone, Copy, PartialEq, Eq)] @@ -74,6 +76,10 @@ pub(super) struct SidebarInputState { pub(super) revision: usize, pub(super) selected_tab: Option, pub(super) choice: ChooserSelection, + scroll: ChooserScroll, + content: SidebarContent, + showing_file_path: bool, + file_path_scroll: usize, } #[derive(Default)] @@ -96,6 +102,10 @@ pub(super) struct SidebarPane { // Visit order is independent of the order in which tabs appear. visits: Vec, pub(super) choice: usize, + pub(super) chooser_scroll: ChooserScroll, + pub(super) showing_file_path: bool, + pub(super) file_path_scroll: usize, + pub(super) file_preview_unavailable: Option<&'static str>, pub(super) tabs_revision: usize, focus: Option, motion: PaneMotion, @@ -146,12 +156,17 @@ impl SidebarPane { self.cancel_hidden_document_primary(/*visible*/ false); } self.focus_document_request = None; + if self.content != content { + self.showing_file_path = false; + } match content { SidebarContent::Chat(id) => { self.add_tab(id); self.visit(SidebarTab::Chat(id)); } - SidebarContent::Chooser if self.content != content || self.focus.is_none() => { + SidebarContent::Chooser + if self.focus.is_none() || matches!(self.content, SidebarContent::Chat(_)) => + { self.reset_choice(); } SidebarContent::Document(id) => { @@ -174,31 +189,51 @@ impl SidebarPane { } pub(super) fn clear_files(&mut self) { - self.files = None; + if self.files.take().is_some() { + self.showing_file_path = false; + self.choice = self.choice.min(self.chat_tabs().choice_count() - 1); + self.tabs_revision += 1; + } } pub(super) fn chat_tabs(&self) -> ChatTabs<'_> { ChatTabs { label_style: crate::thread_label::ThreadLabelStyle::Plain, discovery: &self.discovery, + scroll: self.chooser_scroll, opening: self.opening.as_ref(), ids: &self.tabs, choices: &self.choices, latest_prompts: &self.latest_prompts, selected: self.visits.last().copied(), + files: self + .files + .as_ref() + .map_or(&[], |files| files.entries.as_slice()), + files_cwd: self.files.as_ref().and_then(|files| files.cwd.as_ref()), + file_preview_unavailable: self.file_preview_unavailable, + files_loading: self + .files + .as_ref() + .is_some_and(|files| files.scan.is_some()), } } pub(super) fn set_discovery(&mut self, discovery: Discovery) { + let file = self.chat_tabs().file_offset(self.choice); if matches!(discovery, Discovery::Failed(_)) && self.choices.is_empty() { self.choice = 1; } self.discovery = discovery; + if let Some(offset) = file { + self.choice = self.chat_tabs().file_start() + offset; + } self.choice = self.choice.min(self.chat_tabs().choice_count() - 1); self.tabs_revision += 1; } pub(super) fn update_saved_chats(&mut self, mut chats: Vec) { + let file = self.chat_tabs().file_offset(self.choice); let selection = self.chat_tabs().choice(self.choice); let keep_new = self.choice == 0 && !self.choices.is_empty(); for chat in &mut self.choices { @@ -219,7 +254,9 @@ impl SidebarPane { self.choices = chats; if reordered { self.tabs_revision += 1; - if let Some(index) = selection.and_then(|id| self.chat_tabs().choice_index(id)) { + if let Some(offset) = file { + self.choice = self.chat_tabs().file_start() + offset; + } else if let Some(index) = selection.and_then(|id| self.chat_tabs().choice_index(id)) { self.choice = index; } else if !keep_new { self.reset_choice(); @@ -228,6 +265,8 @@ impl SidebarPane { } fn reset_choice(&mut self) { + self.showing_file_path = false; + self.chooser_scroll = ChooserScroll::default(); self.choice = self .selected_chat() .and_then(|id| self.chat_tabs().choice_index(id)) @@ -345,6 +384,8 @@ impl SidebarPane { ChooserSelection::Chat(id) } else if tabs.retry_row(self.choice) { ChooserSelection::Retry + } else if let Some(offset) = tabs.file_offset(self.choice) { + ChooserSelection::File(offset) } else { ChooserSelection::New }; @@ -352,12 +393,19 @@ impl SidebarPane { revision: self.tabs_revision, selected_tab: tabs.selected, choice, + scroll: self.chooser_scroll, + content: self.content, + showing_file_path: self.showing_file_path, + file_path_scroll: self.file_path_scroll, } } fn add_tab(&mut self, id: ThreadId) { if !self.tabs.contains(&SidebarTab::Chat(id)) { if self.chat_tabs().choice_index(id).is_none() { + if self.chat_tabs().file_offset(self.choice).is_some() { + self.choice += 1; + } self.choices.push(id.into()); } self.tabs.push(SidebarTab::Chat(id)); @@ -383,6 +431,7 @@ impl SidebarPane { self.cancel_hidden_document_primary(/*visible*/ false); self.focus_document_request = None; self.opening = None; + self.showing_file_path = false; if let Some(files) = &mut self.files { files.scan = None; } @@ -430,7 +479,13 @@ impl SidebarPane { if index < self.choice { self.choice -= 1; } - self.choice = self.choice.min(self.choices.len()); + let last = if self.files.is_some() { + self.chat_tabs().choice_count() - 1 + } else { + self.choices.len() + }; + self.choice = self.choice.min(last); + self.tabs_revision += 1; } } @@ -440,6 +495,20 @@ impl SidebarPane { } impl App { + pub(super) fn chooser_area(&self, tui: &Tui) -> Option { + self.chooser_focus()?; + let screen: Rect = tui.terminal.last_known_screen_size.into(); + self.conversation_frame.panel_area().or_else(|| { + match side_pane::split_layout(self, tui, screen) { + Some(SidebarLayout::Panel { sidebar, .. }) => Some(sidebar), + _ if screen.width < 100 && self.chooser_focus() == Some(PaneFocus::Sidebar) => { + Some(screen) + } + _ => None, + } + }) + } + pub(super) fn refresh_visible_side_chat_prompts( &mut self, tui: &Tui, @@ -447,20 +516,9 @@ impl App { parent: ThreadId, request: uuid::Uuid, ) { - let area = if self.sidebar_parent() == Some(parent) && self.chooser_focus().is_some() { - let screen: Rect = tui.terminal.last_known_screen_size.into(); - self.conversation_frame.panel_area().or_else(|| { - match side_pane::split_layout(self, tui, screen) { - Some(SidebarLayout::Panel { sidebar, .. }) => Some(sidebar), - _ if screen.width < 100 && self.chooser_focus() == Some(PaneFocus::Sidebar) => { - Some(screen) - } - _ => None, - } - }) - } else { - None - }; + let area = (self.sidebar_parent() == Some(parent)) + .then(|| self.chooser_area(tui)) + .flatten(); let Some(pane) = self.sidebars.get_mut(&Some(parent)) else { return; }; diff --git a/codex-rs/tui/src/app/sidebar_document_tests.rs b/codex-rs/tui/src/app/sidebar_document_tests.rs index 0c345e5387..f77cd43f78 100644 --- a/codex-rs/tui/src/app/sidebar_document_tests.rs +++ b/codex-rs/tui/src/app/sidebar_document_tests.rs @@ -451,7 +451,7 @@ async fn document_preview_scenario() -> Result<()> { .collect::>() .join("\n"); insta::assert_snapshot!(preview, @" - guide.md × main.rs × + + guide.md × main.rs × + 3 let value = 3; ↑ ↑/↓ read · f3 find · Tab link · f8 select · Esc clear highlight "); @@ -636,7 +636,7 @@ size 123 .sidebar_tab_strip() .expect("tab strip"); let narrow_labels = visible_sidebar_row(&tui, strip, strip.y); - insta::assert_snapshot!(narrow_labels, @"‹ fe…eA/g….md× fe…eB/g….md× +"); + insta::assert_snapshot!(narrow_labels, @"‹ fe…eA/g…md× fe…eB/g…md× +"); for directory in ["feature-alpha-build", "feature-beta-build"] { std::fs::create_dir_all(dir.path().join(directory))?; std::fs::write(dir.path().join(directory).join("guide.md"), "# Guide")?; @@ -659,7 +659,7 @@ size 123 .sidebar_tab_strip() .expect("tab strip"); let narrow_labels = visible_sidebar_row(&tui, strip, strip.y); - insta::assert_snapshot!(narrow_labels, @"‹ 1:f…ld/g…md× 2:f…ld/g…md× +"); + insta::assert_snapshot!(narrow_labels, @"‹ 1:f…ld/g…d× 2:f…ld/g…d× +"); server.shutdown().await?; Ok(()) } diff --git a/codex-rs/tui/src/app/sidebar_files.rs b/codex-rs/tui/src/app/sidebar_files.rs index 8134b3091a..899fcaab2b 100644 --- a/codex-rs/tui/src/app/sidebar_files.rs +++ b/codex-rs/tui/src/app/sidebar_files.rs @@ -174,6 +174,33 @@ impl Files { } } +fn promote_files( + pane: &mut super::sidebar::SidebarPane, + entries: impl IntoIterator, +) -> bool { + let selected = pane + .chat_tabs() + .file(pane.choice) + .map(|file| file.path.clone()); + let Some(files) = pane.files.as_mut() else { + return false; + }; + if !files.promote(entries) { + return false; + } + pane.restore_file_selection(selected.as_deref()); + pane.tabs_revision += 1; + true +} + +impl super::sidebar::SidebarPane { + pub(super) fn restore_file_selection(&mut self, path: Option<&str>) { + if let Some(index) = path.and_then(|path| self.files.as_ref()?.by_destination.get(path)) { + self.choice = self.chat_tabs().file_start() + index; + } + } +} + fn resolve(cwd: Option<&PathUri>, mut link: FileLink) -> Option { if link.path.is_empty() || link.path.len() > 4096 || link.path.chars().any(char::is_control) { return None; @@ -267,7 +294,8 @@ impl App { parent: ThreadId, ) { // Until replay finishes, the rendered cells can still belong to the previous thread. - if self.pending_thread_switch_resets != 0 + if server.thread_params_mode() == ThreadParamsMode::Cloud + || self.pending_thread_switch_resets != 0 || self.current_displayed_thread_id() != Some(parent) { return; @@ -276,7 +304,7 @@ impl App { return; }; let mut entries = Vec::new(); - let (cwd, inspect_local_paths) = { + let (cwd, inspect_local_paths, file_preview_unavailable) = { let store = channel.store.lock().await; let Some(session) = &store.session else { return; @@ -321,7 +349,19 @@ impl App { } entries.extend(turn_entries.into_iter().rev()); } - (cwd, inspect_local_paths) + let file_preview_unavailable = + if session.windows_sandbox_host != WindowsSandboxHost::Local { + Some("Requires workspace on server host") + } else if server.app_server_platform_family() == Some("windows") + || (cfg!(windows) && !server.uses_remote_workspace()) + || cwd.as_ref().and_then(PathUri::infer_path_convention) + != Some(codex_utils_path_uri::PathConvention::Posix) + { + Some("Preview unavailable on Windows") + } else { + None + }; + (cwd, inspect_local_paths, file_preview_unavailable) }; let active = self .chat_widget @@ -358,6 +398,7 @@ impl App { resolve(cwd.as_ref(), file) }); let pane = self.sidebars.entry(Some(parent)).or_default(); + pane.file_preview_unavailable = file_preview_unavailable; if pane.files.as_ref().is_some_and(|files| files.cwd != cwd) { pane.clear_files(); } @@ -380,9 +421,13 @@ impl App { location: None, }) .collect::>(); - if files.promote(active_links.rev().chain(entries).chain(visible_links.rev())) { - pane.tabs_revision += 1; - } + promote_files( + pane, + active_links.rev().chain(entries).chain(visible_links.rev()), + ); + let Some(files) = pane.files.as_mut() else { + return; + }; if files.extend(opened) { pane.tabs_revision += 1; } @@ -441,12 +486,11 @@ impl App { ThreadItemPayload::FileChange { .. } | ThreadItemPayload::ImageGeneration(_) ) && let Some(pane) = self.sidebars.get_mut(&Some(thread)) - && let Some(files) = pane.files.as_mut() + && let Some(files) = pane.files.as_ref() { let mut entries = Vec::new(); newest_item_entries(files.cwd.as_ref(), &item.item.payload, &mut entries); - if !entries.is_empty() && files.promote(entries) { - pane.tabs_revision += 1; + if !entries.is_empty() && promote_files(pane, entries) { self.chat_widget.request_redraw(); } } diff --git a/codex-rs/tui/src/app/sidebar_files_tests.rs b/codex-rs/tui/src/app/sidebar_files_tests.rs index ac123aa643..4147451e6d 100644 --- a/codex-rs/tui/src/app/sidebar_files_tests.rs +++ b/codex-rs/tui/src/app/sidebar_files_tests.rs @@ -2,7 +2,400 @@ use super::*; use crate::markdown_render::SourceLocation; +use crate::sidebar_chooser; +use crate::sidebar_chooser::NewChatState; +use codex_app_server_protocol::FileUpdateChange; use pretty_assertions::assert_eq; +use ratatui::buffer::Buffer; +use ratatui::buffer::Cell; + +#[test] +fn sidebar_files_chooser_matches_the_grouped_file_inventory() -> color_eyre::eyre::Result<()> { + let workspace = tempfile::tempdir()?; + std::fs::create_dir(workspace.path().join("folder.with-dot"))?; + std::fs::write(workspace.path().join("Makefile"), "")?; + let cwd = PathUri::from_abs_path(&codex_utils_absolute_path::AbsolutePathBuf::try_from( + workspace.path(), + )?); + let mut entries = Vec::new(); + item_entries( + Some(&cwd), + &ThreadItemPayload::FileChange { + id: "patch".into(), + changes: [ + ("src/lib.rs", PatchChangeKind::Update { move_path: None }), + ("./notes/guide.md", PatchChangeKind::Add), + ("removed.md", PatchChangeKind::Delete), + ] + .into_iter() + .map(|(path, kind)| FileUpdateChange { + path: path.into(), + kind, + diff: String::new(), + }) + .collect(), + status: PatchApplyStatus::Completed, + }, + &mut entries, + ); + item_entries( + Some(&cwd), + &ThreadItemPayload::Plan { + id: "plan".into(), + text: "[Guide](./notes/guide.md#L4) [Source](./src/lib.rs#L12C4) \ + [Image](./figure.png) [Folder](./folder.with-dot) [Build](./Makefile) \ + [Reference](https://example.net) https://example.org" + .into(), + }, + &mut entries, + ); + let mut files = Files::new( + Some(cwd), + /*next*/ None, + /*inspect_local_paths*/ true, + ); + files.promote(entries.into_iter().rev()); + let mut pane = super::super::sidebar::SidebarPane::default(); + pane.files = Some(files); + pane.choice = pane.chat_tabs().file_start(); + pane.update_saved_chats(vec![ThreadId::new().into()]); + assert_eq!(pane.chat_tabs().file_offset(pane.choice), Some(0)); + let area = Rect::new( + /*x*/ 0, /*y*/ 0, /*width*/ 50, /*height*/ 23, + ); + let mut buffer = Buffer::empty(area); + sidebar_chooser::paint( + /*focused*/ true, + area, + &mut buffer, + Line::default(), + pane.chat_tabs(), + pane.choice, + &sidebar_chooser::SidebarStyle { + new_chat: NewChatState::Available, + use_theme_colors: false, + motion: crate::motion::MotionMode::Reduced, + frames: &tui::FrameRequester::test_dummy(), + hovered_choice: None, + full_path: None, + path_scroll: 0, + }, + ); + let screen = buffer + .content + .chunks(usize::from(area.width)) + .map(|cells| cells.iter().map(Cell::symbol).collect::()) + .map(|line| line.trim().to_owned()) + .collect::>() + .join("\n"); + insta::assert_snapshot!(screen.trim(), @" + Open in sidebar + + + New side chat + Start from this conversation + + Side chats 1 + + ○ Side chat + + Files 4 + + › · Makefile + Project root + · figure.png + Project root + · lib.rs + src + · guide.md + notes + "); + let long_path = + "/Users/example/workspaces/really-long-project-name/codex-rs/tui/src/app/guide.md"; + pane.files + .as_mut() + .expect("file inventory") + .extend([FileLink { + path: long_path.into(), + location: None, + }]); + let wide = Rect::new( + /*x*/ 0, /*y*/ 0, /*width*/ 75, /*height*/ 20, + ); + let mut wide_buffer = Buffer::empty(wide); + let frames = tui::FrameRequester::test_dummy(); + let style = sidebar_chooser::SidebarStyle { + new_chat: NewChatState::Available, + use_theme_colors: false, + motion: crate::motion::MotionMode::Reduced, + frames: &frames, + hovered_choice: Some(pane.chat_tabs().choice_count() - 1), + full_path: None, + path_scroll: 0, + }; + sidebar_chooser::paint( + /*focused*/ true, + wide, + &mut wide_buffer, + Line::default(), + pane.chat_tabs(), + pane.choice, + &style, + ); + let file_rows = wide_buffer + .content + .chunks(usize::from(wide.width)) + .map(|cells| cells.iter().map(Cell::symbol).collect::()) + .filter(|line| line.contains("guide.md") || line.contains("Makefile")) + .map(|line| line.trim_end().to_owned()) + .collect::>() + .join("\n"); + insta::assert_snapshot!(file_rows, @" + › · Makefile Project root + · guide.md notes + · guide.md /Users/example/workspaces/re…ect-name/codex-rs/tui/src/app + "); + let [selected, hovered]: [_; 2] = wide_buffer + .content + .chunks(usize::from(wide.width)) + .filter(|cells| { + let text = cells.iter().map(Cell::symbol).collect::(); + text.contains("Makefile") || text.contains("/Users/example") + }) + .map(|row| (row[2].bg, row[2].modifier)) + .collect::>() + .try_into() + .expect("selected and hovered files"); + assert_ne!(selected, hovered); + + sidebar_chooser::paint( + /*focused*/ true, + wide, + &mut wide_buffer, + Line::default(), + pane.chat_tabs(), + pane.choice, + &sidebar_chooser::SidebarStyle { + full_path: Some(long_path), + ..style + }, + ); + let path_screen = wide_buffer + .content + .chunks(usize::from(wide.width)) + .map(|row| { + row.iter() + .map(Cell::symbol) + .collect::() + .trim() + .to_owned() + }) + .filter(|row| !row.is_empty()) + .collect::>(); + assert_eq!(path_screen[0], "File path"); + assert_eq!(path_screen[1..].join(""), long_path); + let narrow_path = Rect::new( + /*x*/ 0, /*y*/ 0, /*width*/ 18, /*height*/ 7, + ); + let mut narrow_buffer = Buffer::empty(narrow_path); + let bottom = sidebar_chooser::scroll_file_path( + narrow_path, + long_path, + /*top*/ 0, + crate::keymap::ListAction::JumpBottom, + ); + assert!(bottom > 0); + sidebar_chooser::paint( + /*focused*/ true, + narrow_path, + &mut narrow_buffer, + Line::default(), + pane.chat_tabs(), + pane.choice, + &sidebar_chooser::SidebarStyle { + full_path: Some(long_path), + path_scroll: bottom, + ..style + }, + ); + let rendered = narrow_buffer + .content + .chunks(usize::from(narrow_path.width)) + .map(|line| line.iter().map(Cell::symbol).collect::()) + .map(|line| line.trim_end().to_owned()) + .collect::(); + assert!(rendered.ends_with("guide.md"), "{rendered}"); + + let tabs = pane.chat_tabs(); + let targets: Vec<_> = + sidebar_chooser::row_targets(area, tabs, pane.choice, NewChatState::Available).collect(); + for row in 10..=12 { + assert!( + targets + .iter() + .all(|(_, area)| !area.contains((1, row).into())) + ); + } + assert_eq!( + targets + .iter() + .find(|(_, area)| area.contains((1, 13).into())) + .and_then(|(index, _)| tabs.file(*index)), + tabs.file(pane.choice), + ); + Ok(()) +} + +#[test] +fn sidebar_files_follow_latest_mentions_and_preserve_selection() { + let mut pane = super::super::sidebar::SidebarPane::default(); + pane.files = Some(Files::new( + /*cwd*/ None, /*next*/ None, /*inspect_local_paths*/ false, + )); + let link = |path: &str| FileLink { + path: path.into(), + location: None, + }; + promote_files(&mut pane, [link("dog.png"), link("guide.md")]); + pane.choice = pane.chat_tabs().file_start() + 1; + promote_files(&mut pane, [link("guide.md"), link("new.rs")]); + pane.files + .as_mut() + .unwrap() + .extend([link("dog.png"), link("old.md")]); + assert_eq!( + pane.files.as_ref().unwrap().entries, + vec![ + link("guide.md"), + link("new.rs"), + link("dog.png"), + link("old.md") + ] + ); + assert_eq!(pane.chat_tabs().file(pane.choice), Some(&link("guide.md"))); +} + +#[test] +fn sidebar_files_scrolls_the_body_without_wrapping_or_moving_the_wheel_selection() { + use crate::keymap::ListAction; + + let mut pane = super::super::sidebar::SidebarPane::default(); + let mut files = Files::new( + /*cwd*/ None, /*next*/ None, /*inspect_local_paths*/ false, + ); + files.extend((1..=8).map(|number| FileLink { + path: format!("file{number}.rs"), + location: None, + })); + pane.files = Some(files); + let area = Rect::new( + /*x*/ 0, /*y*/ 0, /*width*/ 72, /*height*/ 8, + ); + let tabs = pane.chat_tabs(); + let (last, bottom) = + sidebar_chooser::navigate(area, tabs, /*choice*/ 0, ListAction::JumpBottom); + pane.chooser_scroll = bottom; + let tabs = pane.chat_tabs(); + assert_eq!( + sidebar_chooser::navigate(area, tabs, last, ListAction::MoveDown), + (last, bottom) + ); + let (above, same_view) = sidebar_chooser::navigate(area, tabs, last, ListAction::MoveUp); + assert_eq!((above, same_view), (last - 1, bottom)); + assert_eq!( + sidebar_chooser::choice_at(area, tabs, above, /*y*/ 1), + Some(4) + ); + let (previous, scrolled_up) = + sidebar_chooser::navigate(area, tabs, /*choice*/ 4, ListAction::MoveUp); + pane.chooser_scroll = scrolled_up; + assert_eq!( + sidebar_chooser::choice_at(area, pane.chat_tabs(), previous, /*y*/ 1), + Some(previous), + ); + + pane.chooser_scroll = Default::default(); + let tabs = pane.chat_tabs(); + assert_eq!( + sidebar_chooser::navigate(area, tabs, /*choice*/ 0, ListAction::MoveUp), + (0, Default::default()) + ); + pane.chooser_scroll = + sidebar_chooser::wheel_scroll(area, tabs, /*choice*/ 0, /*delta*/ 3); + pane.chooser_scroll = + sidebar_chooser::wheel_scroll(area, pane.chat_tabs(), /*choice*/ 0, /*delta*/ 3); + let tabs = pane.chat_tabs(); + assert!(!sidebar_chooser::choice_is_visible( + area, tabs, /*choice*/ 0 + )); + assert_eq!( + sidebar_chooser::choice_at(area, tabs, /*choice*/ 0, /*y*/ 1), + None + ); + assert_eq!( + sidebar_chooser::choice_at(area, tabs, /*choice*/ 0, /*y*/ 2), + Some(1) + ); + let (first, keyboard_scroll) = + sidebar_chooser::navigate(area, tabs, /*choice*/ 0, ListAction::MoveDown); + assert_eq!(first, 1); + assert_eq!( + sidebar_chooser::choice_at( + area, + sidebar_chooser::ChatTabs { + scroll: keyboard_scroll, + ..tabs + }, + first, + /*y*/ 2 + ), + Some(first), + ); + let mut buffer = Buffer::empty(area); + sidebar_chooser::paint( + /*focused*/ true, + area, + &mut buffer, + Line::from("enter open"), + tabs, + /*choice*/ 0, + &sidebar_chooser::SidebarStyle { + new_chat: NewChatState::Available, + use_theme_colors: false, + motion: crate::motion::MotionMode::Reduced, + frames: &tui::FrameRequester::test_dummy(), + hovered_choice: None, + full_path: None, + path_scroll: 0, + }, + ); + let screen = buffer + .content + .chunks(usize::from(area.width)) + .map(|cells| cells.iter().map(Cell::symbol).collect::()) + .map(|line| line.trim().to_owned()) + .collect::>() + .join("\n"); + insta::assert_snapshot!(screen.trim(), @" + ↑ + · file1.rs Project root + · file2.rs Project root + · file3.rs Project root + · file4.rs Project root + ↓ + enter open + "); + pane.chooser_scroll = + sidebar_chooser::wheel_scroll(area, tabs, /*choice*/ 0, /*delta*/ 100); + let tabs = pane.chat_tabs(); + assert_eq!( + sidebar_chooser::wheel_scroll(area, tabs, /*choice*/ 0, /*delta*/ 3), + pane.chooser_scroll + ); + assert_eq!( + sidebar_chooser::choice_at(area, tabs, /*choice*/ 0, /*y*/ 5), + Some(last) + ); +} #[test] fn files_from_missed_pages_precede_older_cached_paths_and_reader_opens() { diff --git a/codex-rs/tui/src/app/sidebar_loading.rs b/codex-rs/tui/src/app/sidebar_loading.rs index 9b170f1faa..7acdec8d4c 100644 --- a/codex-rs/tui/src/app/sidebar_loading.rs +++ b/codex-rs/tui/src/app/sidebar_loading.rs @@ -129,6 +129,7 @@ impl App { if !self.can_select_thread() { return Ok(()); } + self.sidebar_mut().focus_document_request = None; let child = target.child; let flight = self.saved_openings.active.get(&target.key()); let state = if let Some(flight) = flight diff --git a/codex-rs/tui/src/app/snapshots/codex_tui__app__tests__saved_chat_discovery_states.snap b/codex-rs/tui/src/app/snapshots/codex_tui__app__tests__saved_chat_discovery_states.snap index 2d33a4f43f..bba158f96e 100644 --- a/codex-rs/tui/src/app/snapshots/codex_tui__app__tests__saved_chat_discovery_states.snap +++ b/codex-rs/tui/src/app/snapshots/codex_tui__app__tests__saved_chat_discovery_states.snap @@ -1,25 +1,26 @@ --- source: tui/src/app/tests.rs +assertion_line: 3679 expression: "states.join(\"\\n\\n\")" --- Loading Open in sidebar ◌ Loading side chats… - › + New side chat Start from the main chat + › + New side chat Start from this conversation Empty result Open in sidebar - › + New side chat Start from the main chat + › + New side chat Start from this conversation Initial failure Open in sidebar Permission denied by storage + New side chat - Start from the main chat + Start from this conversation › Retry loading side chats @@ -28,7 +29,7 @@ Retry in progress Open in sidebar ◌ Loading side chats… - + New side chat Start from the main chat + + New side chat Start from this conversation › Retrying… @@ -37,7 +38,7 @@ Refreshing cached chats Open in sidebar ◌ Refreshing side chats… - + New side chat Start from the main chat + + New side chat Start from this conversation Side chats 2 @@ -49,7 +50,7 @@ Cached chats after failure Open in sidebar Refresh failed - + New side chat Start from the main chat + + New side chat Start from this conversation Side chats 2 @@ -63,7 +64,7 @@ Refreshed chats Open in sidebar + New side chat - Start from the main chat + Start from this conversation Side chats 2 @@ -76,11 +77,11 @@ Readable reply Open in sidebar + New side chat - Start from the main chat + Start from this conversation Side chats 2 › ○ Named sibling > Which branch? Keep ## My r… ○ Child-only prompt - Child-only prompt + ↓ diff --git a/codex-rs/tui/src/app/startup.rs b/codex-rs/tui/src/app/startup.rs index 8ea64997ba..cb364f2d1f 100644 --- a/codex-rs/tui/src/app/startup.rs +++ b/codex-rs/tui/src/app/startup.rs @@ -1090,6 +1090,7 @@ See the Codex keymap documentation for supported actions and examples." divider_drag: None, pane_resize: None, passive_link_drag: None, + sidebar_press: None, abandoned_side_threads: HashSet::new(), active_thread_id: None, active_thread_rx: None, diff --git a/codex-rs/tui/src/app/test_support.rs b/codex-rs/tui/src/app/test_support.rs index b2f56830ba..dfc253db1e 100644 --- a/codex-rs/tui/src/app/test_support.rs +++ b/codex-rs/tui/src/app/test_support.rs @@ -138,6 +138,7 @@ pub(crate) async fn make_test_app() -> Box { divider_drag: None, pane_resize: None, passive_link_drag: None, + sidebar_press: None, abandoned_side_threads: HashSet::new(), active_thread_id: None, active_thread_rx: None, diff --git a/codex-rs/tui/src/app/tests.rs b/codex-rs/tui/src/app/tests.rs index bc3f00f728..f7e1e720c1 100644 --- a/codex-rs/tui/src/app/tests.rs +++ b/codex-rs/tui/src/app/tests.rs @@ -3219,31 +3219,6 @@ fn attach_live_thread_for_selection_rejects_unmaterialized_fallback_threads() -> }) } -#[tokio::test] -async fn refresh_agent_picker_thread_liveness_prunes_closed_metadata_only_threads() -> Result<()> { - let mut app = Box::pin(make_test_app()).await; - let mut app_server = Box::pin(crate::start_embedded_app_server_for_picker( - app.chat_widget.config_ref(), - )) - .await - .expect("embedded app server"); - let thread_id = ThreadId::new(); - app.agent_navigation.upsert( - thread_id, - Some("Ghost".to_string()), - Some("worker".to_string()), - /*is_closed*/ false, - ); - - let is_available = - Box::pin(app.refresh_agent_picker_thread_liveness(&mut app_server, thread_id)).await; - - assert!(!is_available); - assert_eq!(app.agent_navigation.get(&thread_id), None); - assert!(!app.thread_event_channels.contains_key(&thread_id)); - Ok(()) -} - #[tokio::test] async fn docked_replay_finishes_while_skills_refresh_is_pending() -> Result<()> { let (mut app, mut events, _ops) = make_test_app_with_channels().await; @@ -3622,12 +3597,13 @@ async fn reopen_saved_side_chat(during: DuringOpen) -> Result<()> { // Only the selected sibling fits. + starts the refresh and the chord joins it. side_frame(&mut app, &mut tui, Size::new(size.width, /*height*/ 10))?; let strip = app.conversation_frame.sidebar_tab_strip().unwrap(); - let click = mouse( + for kind in [ MouseEventKind::Down(MouseButton::Left), - strip.right() - 3, - strip.y, - ); - boxed_future!(app.handle_tui_event(&mut tui, &mut server, click)).await?; + MouseEventKind::Up(MouseButton::Left), + ] { + let click = mouse(kind, strip.right() - 3, strip.y); + boxed_future!(app.handle_tui_event(&mut tui, &mut server, click)).await?; + } let request = app.sidebar().unwrap().discovery.request().unwrap(); for key in open_chooser { boxed_future!(app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(key))).await?; @@ -3703,10 +3679,24 @@ async fn reopen_saved_side_chat(during: DuringOpen) -> Result<()> { app.pending_server_profiles.remove(&parent); app.local_settings.tui.keymap = toml::from_str("[list]\naccept = ['f5 g']")?; enable_side_retention(&mut app)?; - for key in [KeyCode::Char('j'), KeyCode::F(5), KeyCode::Char('g')] { + let painted_frame = std::mem::take(&mut app.conversation_frame); + let pane = app.sidebar_mut(); + let child_choice = pane.chat_tabs().choice_index(child).expect("saved child"); + pane.choice = child_choice - 1; + pane.chooser_scroll = Default::default(); + pane.focus_document_request = Some(uuid::Uuid::new_v4()); + for key in [KeyCode::Down, KeyCode::F(5), KeyCode::Char('g')] { boxed_future!(app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(key.into()))) .await?; } + assert_eq!(app.sidebar().expect("sidebar").choice, child_choice); + assert!( + app.sidebar() + .expect("sidebar") + .focus_document_request + .is_none() + ); + app.conversation_frame = painted_frame; let opening = side_frame(&mut app, &mut tui, size)?; let status = opening .lines() @@ -5328,7 +5318,13 @@ async fn handle_start_side_seeds_navigation_before_thread_started() -> Result<() let [up, enter] = [KeyCode::Char('k'), KeyCode::Enter].map(KeyEvent::from); side_frame(&mut app, &mut tui, even)?; let sidebar_x = app.conversation_frame.chat_strip.unwrap().x; - keys!(prefix, chooser_key, up, enter); + keys!(prefix, chooser_key); + side_frame(&mut app, &mut tui, even)?; + keys!(KeyCode::Home.into()); + side_frame(&mut app, &mut tui, even)?; + assert_eq!(app.chooser_focus(), Some(sidebar::PaneFocus::Sidebar)); + assert_eq!(app.sidebar().unwrap().choice, 0); + keys!(enter); app.local_settings.tui.keymap = toml::from_str("[global]\nleader = 'f12'")?; enable_side_retention(&mut app)?; app.local_settings.tui.animations = false; @@ -5427,7 +5423,8 @@ async fn handle_start_side_seeds_navigation_before_thread_started() -> Result<() idle_style ); for (kind, expected) in [ - (MouseEventKind::Down(MouseButton::Left), side_thread_id), + (MouseEventKind::Down(MouseButton::Left), sibling), + (MouseEventKind::Up(MouseButton::Left), side_thread_id), (MouseEventKind::ScrollDown, sibling), ] { let event = mouse(kind, arrow_x, strip.y); @@ -5438,29 +5435,42 @@ async fn handle_start_side_seeds_navigation_before_thread_started() -> Result<() } side_frame(&mut app, &mut tui, even)?; - keys!(prefix, chooser_key, up, enter); + keys!(prefix, chooser_key); + side_frame(&mut app, &mut tui, even)?; + keys!(up); + side_frame(&mut app, &mut tui, even)?; + keys!(enter); assert_eq!(app.current_displayed_thread_id(), Some(side_thread_id)); assert_eq!(app.chat_widget.composer_text_with_pending(), child_draft); assert!(side_frame(&mut app, &mut tui, even)?.contains(child_row)); let strip = app.conversation_frame.chat_strip.unwrap(); let down = MouseEventKind::Down(MouseButton::Left); + let release = MouseEventKind::Up(MouseButton::Left); let sibling_tab = app - .sidebar() - .unwrap() - .chat_tabs() - .strip() - .strip_targets(strip) - .into_iter() + .conversation_frame + .sidebar_targets + .iter() .find_map(|(target, area)| { - (target - == crate::sidebar_tab_strip::TabTarget::Tab( + (*target + == side_focus::SidebarTarget::Tab(crate::sidebar_tab_strip::TabTarget::Tab( crate::sidebar_tab_strip::SidebarTab::Chat(sibling), - )) - .then_some(area) + ))) + .then_some(*area) }) .expect("sibling tab"); - let click = mouse(down, sibling_tab.x, strip.y); - boxed_future!(app.handle_tui_event(&mut tui, &mut app_server, click)).await?; + for (kind, x) in [ + (down, sibling_tab.x), + (release, sibling_tab.right()), + (down, sibling_tab.x), + (release, sibling_tab.x), + ] { + boxed_future!(app.handle_tui_event(&mut tui, &mut app_server, mouse(kind, x, strip.y))) + .await?; + if x == sibling_tab.right() { + assert_eq!(app.current_displayed_thread_id(), Some(side_thread_id)); + assert!(app.sidebar().unwrap().close.is_none()); + } + } drain_app_events(&mut app, &mut tui, &mut app_server, &mut app_event_rx).await?; assert_eq!(app.current_displayed_thread_id(), Some(sibling)); assert!(!tui.has_deferred_thread_switch_clear()); @@ -5544,16 +5554,16 @@ async fn handle_start_side_seeds_navigation_before_thread_started() -> Result<() side_frame(&mut app, &mut tui, even)?; let strip = app.conversation_frame.sidebar_tab_strip().unwrap(); let add = strip.right() - 3; - let tabs = app - .sidebar() - .unwrap() - .chat_tabs() - .strip() - .strip_targets(strip); - let [inactive, selected] = tabs - .into_iter() + let [inactive, selected] = app + .conversation_frame + .sidebar_targets + .iter() .filter_map(|(target, area)| { - matches!(target, crate::sidebar_tab_strip::TabTarget::Tab(_)).then_some(area) + matches!( + target, + side_focus::SidebarTarget::Tab(crate::sidebar_tab_strip::TabTarget::Tab(_)) + ) + .then_some(*area) }) .collect::>() .try_into() @@ -5656,8 +5666,14 @@ async fn handle_start_side_seeds_navigation_before_thread_started() -> Result<() let close_x = (chooser.x..chooser.right()) .rfind(|&x| tui.terminal.previous_buffer()[(x, chooser.y)].symbol() == "×") .expect("close button on the second tab"); - let click_close = mouse(down, close_x, chooser.y); - boxed_future!(app.handle_tui_event(&mut tui, &mut app_server, click_close)).await?; + for kind in [down, release] { + boxed_future!(app.handle_tui_event( + &mut tui, + &mut app_server, + mouse(kind, close_x, chooser.y) + )) + .await?; + } let frame = side_frame(&mut app, &mut tui, even)?; let dialog = frame .lines() @@ -5670,12 +5686,14 @@ async fn handle_start_side_seeds_navigation_before_thread_started() -> Result<() assert_eq!(app.current_displayed_thread_id(), Some(parent_thread_id)); assert_eq!(app.chooser_focus(), chooser_focus); side_frame(&mut app, &mut tui, even)?; - boxed_future!(app.handle_tui_event( - &mut tui, - &mut app_server, - mouse(down, close_x - 1, chooser.y) - )) - .await?; + for kind in [down, release] { + boxed_future!(app.handle_tui_event( + &mut tui, + &mut app_server, + mouse(kind, close_x - 1, chooser.y) + )) + .await?; + } drain_app_events(&mut app, &mut tui, &mut app_server, &mut app_event_rx).await?; assert_eq!( app.chat_widget.composer_text_with_pending(), @@ -5694,8 +5712,14 @@ async fn handle_start_side_seeds_navigation_before_thread_started() -> Result<() )); keys!(prefix, chooser_key); side_frame(&mut app, &mut tui, even)?; - boxed_future!(app.handle_tui_event(&mut tui, &mut app_server, mouse(down, close_x, chooser.y))) + for kind in [down, release] { + boxed_future!(app.handle_tui_event( + &mut tui, + &mut app_server, + mouse(kind, close_x, chooser.y) + )) .await?; + } assert!(side_frame(&mut app, &mut tui, even)?.contains("discard unsent input")); keys!(KeyCode::Esc.into()); app.select_agent_thread(&mut tui, &mut app_server, sibling) @@ -9247,6 +9271,7 @@ async fn make_test_app() -> Box { divider_drag: None, pane_resize: None, passive_link_drag: None, + sidebar_press: None, abandoned_side_threads: HashSet::new(), active_thread_id: None, active_thread_rx: None, @@ -9390,6 +9415,7 @@ pub(super) async fn make_test_app_with_channels() -> ( divider_drag: None, pane_resize: None, passive_link_drag: None, + sidebar_press: None, abandoned_side_threads: HashSet::new(), active_thread_id: None, active_thread_rx: None, diff --git a/codex-rs/tui/src/app/tests/agents_navigation_tests.rs b/codex-rs/tui/src/app/tests/agents_navigation_tests.rs index c7cd96d685..b315751852 100644 --- a/codex-rs/tui/src/app/tests/agents_navigation_tests.rs +++ b/codex-rs/tui/src/app/tests/agents_navigation_tests.rs @@ -183,3 +183,28 @@ async fn pending_windows_sandbox_setup_blocks_thread_replacement() -> Result<()> app_server.shutdown().await?; Ok(()) } + +#[tokio::test] +async fn refresh_agent_picker_thread_liveness_prunes_closed_metadata_only_threads() -> Result<()> { + let mut app = Box::pin(make_test_app()).await; + let mut app_server = Box::pin(crate::start_embedded_app_server_for_picker( + app.chat_widget.config_ref(), + )) + .await + .expect("embedded app server"); + let thread_id = ThreadId::new(); + app.agent_navigation.upsert( + thread_id, + Some("Ghost".to_string()), + Some("worker".to_string()), + /*is_closed*/ false, + ); + + let is_available = + Box::pin(app.refresh_agent_picker_thread_liveness(&mut app_server, thread_id)).await; + + assert!(!is_available); + assert_eq!(app.agent_navigation.get(&thread_id), None); + assert!(!app.thread_event_channels.contains_key(&thread_id)); + Ok(()) +} diff --git a/codex-rs/tui/src/app/tests/key_chords.rs b/codex-rs/tui/src/app/tests/key_chords.rs index 103a6cf0bd..af4af807cd 100644 --- a/codex-rs/tui/src/app/tests/key_chords.rs +++ b/codex-rs/tui/src/app/tests/key_chords.rs @@ -1519,7 +1519,7 @@ prepared. assert!(draft.remote_image_urls.is_empty()); insta::assert_snapshot!(draft.text, @"second prompt parent draft!"); - // A page fits a chat with a subtitle or two title-only chats. + // Page navigation uses the whole chooser viewport and clamps at both ends. let pane = app.sidebar_mut(); for _ in 0..4 { pane.chat_ready(ThreadId::new()); @@ -1535,10 +1535,10 @@ parent draft!"); tui.terminal = terminal_at(two_rows); super::side_frame(&mut app, &mut tui, two_rows)?; for (key, expected) in [ - (KeyCode::PageDown, 3), (KeyCode::PageDown, 5), - (KeyCode::PageUp, 3), - (KeyCode::PageUp, 2), + (KeyCode::PageDown, 5), + (KeyCode::PageUp, 0), + (KeyCode::PageUp, 0), ] { Box::pin(press(&mut app, &mut tui, &mut server, key.into())).await?; assert_eq!(app.sidebar().unwrap().choice, expected); diff --git a/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__key_chords__sidebar_new_chat.snap b/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__key_chords__sidebar_new_chat.snap index 2256e0d92e..a9f851b1be 100644 --- a/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__key_chords__sidebar_new_chat.snap +++ b/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__key_chords__sidebar_new_chat.snap @@ -1,5 +1,6 @@ --- source: tui/src/app/tests/key_chords.rs +assertion_line: 1372 expression: frame --- │ + @@ -7,7 +8,7 @@ expression: frame │ Open in sidebar │ │ › + New side chat - │ Start from the main chat + │ Start from this conversation │ │ › parent draft │ diff --git a/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__saved_chat_loading__waiting_and_retry_rows.snap b/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__saved_chat_loading__waiting_and_retry_rows.snap index 11af494091..352b6ad76b 100644 --- a/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__saved_chat_loading__waiting_and_retry_rows.snap +++ b/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__saved_chat_loading__waiting_and_retry_rows.snap @@ -1,11 +1,12 @@ --- source: tui/src/app/tests/saved_chat_loading_tests.rs +assertion_line: 138 expression: "format!(\"Waiting\\n{waiting}\\n\\nRetry\\n{retry}\")" --- Waiting + Open in sidebar - + New side chat Start from the main chat + + New side chat Start from this conversation Side chats 4 ○ Side chat 1 ○ Side chat 2 @@ -16,7 +17,7 @@ Waiting Retry + Open in sidebar - + New side chat Start from the main chat + + New side chat Start from this conversation Side chats 4 ○ Side chat 1 ○ Side chat 2 diff --git a/codex-rs/tui/src/bottom_pane/mod.rs b/codex-rs/tui/src/bottom_pane/mod.rs index 3b4a836079..29b43bd525 100644 --- a/codex-rs/tui/src/bottom_pane/mod.rs +++ b/codex-rs/tui/src/bottom_pane/mod.rs @@ -223,7 +223,6 @@ pub(crate) use picker_option::picker_option_list; pub(crate) use picker_option::picker_option_row; pub(crate) mod popup_consts; mod scroll_state; -pub(crate) use scroll_state::ScrollState; mod selection_popup_common; pub(crate) use selection_popup_common::menu_surface_padding_height; pub(crate) use selection_popup_common::render_menu_surface; diff --git a/codex-rs/tui/src/sidebar_chooser.rs b/codex-rs/tui/src/sidebar_chooser.rs index fcd76a1615..2b8bdc0ab2 100644 --- a/codex-rs/tui/src/sidebar_chooser.rs +++ b/codex-rs/tui/src/sidebar_chooser.rs @@ -5,16 +5,23 @@ use crate::footer_hint; use crate::keymap::KeymapContext; use crate::keymap::ListAction; use crate::keymap::RuntimeKeymap; +use crate::line_truncation::filename_label; +use crate::line_truncation::middle_label; use crate::line_truncation::truncate_line_with_ellipsis_if_overflow; use crate::live_wrap::take_prefix_by_width; +use crate::markdown_render::FileLink; use crate::sidebar_tab_strip::SidebarTab; use crate::sidebar_tab_strip::TabState; use crate::sidebar_tab_strip::TabStrip; use crate::sidebar_tab_strip::TabTarget; use crate::thread_label::ThreadLabelStyle; use codex_protocol::ThreadId; +use codex_utils_path_uri::LegacyAppPathString; +use codex_utils_path_uri::PathUri; use ratatui::buffer::Buffer; +use ratatui::layout::Position; use ratatui::layout::Rect; +use ratatui::style::Styled; use ratatui::style::Stylize; use ratatui::text::Line; use ratatui::text::Span; @@ -24,7 +31,8 @@ use std::collections::HashMap; use std::ops::Range; const WIDE_WIDTH: u16 = 58; -const FIRST_CHOICE_ROW: u16 = 4; +const FIRST_CHOICE_ROW: usize = 4; +const CHOOSER_BODY_START: usize = 1; pub(crate) fn body_row(area: Rect, y: u16) -> Rect { Rect::new(area.x + 1, y, area.width.saturating_sub(3), 1) @@ -39,10 +47,12 @@ pub(crate) fn resize_hint(full: &str, width: u16) -> Line<'_> { } } +#[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum ChooserAction { Open(usize), Back, Hide, + FilePath, } #[derive(Clone, Copy, PartialEq, Eq)] @@ -76,11 +86,27 @@ pub(crate) fn footer( choice: usize, tabs: ChatTabs<'_>, new_chat: NewChatState, + showing_path: bool, ) -> (footer_hint::HintLine, Vec>) { let hint = |action| list_hint(keymap, action); + if showing_path { + let (hints, actions): (Vec<_>, Vec<_>) = [ + (hint(ListAction::Cancel), "back", Some(ChooserAction::Back)), + (hint(ListAction::MoveDown), "scroll", None), + ] + .into_iter() + .filter_map(|(key, label, action)| Some((footer_hint::shortcut(&key?, label), action))) + .unzip(); + return ( + footer_hint::HintLine::new(hints, body_row(area, area.y).width), + actions, + ); + } + let selected_file = tabs.file(choice); + let visible = choice_is_visible(area, tabs, choice); let movement = [ListAction::MoveUp, ListAction::MoveDown] .into_iter() - .filter(|_| new_chat == NewChatState::Available) + .filter(|_| new_chat == NewChatState::Available || !tabs.files.is_empty()) .filter_map(hint) .collect::>() .join("/"); @@ -89,7 +115,11 @@ pub(crate) fn footer( .map(super::key_hint::ShortcutHint::display_label); let (hints, actions): (Vec<_>, Vec<_>) = [ ( - hint(ListAction::Accept).filter(|_| new_chat == NewChatState::Available), + hint(ListAction::Accept) + .filter(|_| { + visible && (new_chat == NewChatState::Available || selected_file.is_some()) + }) + .filter(|_| selected_file.is_none() || tabs.file_preview_unavailable.is_none()), if tabs.retry_row(choice) || tabs.opening.is_some_and(|o| { Some(o.target.child) == tabs.choice(choice) @@ -114,6 +144,13 @@ pub(crate) fn footer( }, Some(ChooserAction::Back), ), + ( + selected_file + .filter(|_| visible && file_path_key_available(keymap)) + .map(|_| "p".to_owned()), + "path", + Some(ChooserAction::FilePath), + ), ((!movement.is_empty()).then_some(movement), "move", None), (hide, "hide pane", Some(ChooserAction::Hide)), ] @@ -126,8 +163,6 @@ pub(crate) fn footer( ) } -const CHAT_TAB: &str = " Side chat "; - #[derive(Default)] pub(crate) enum Discovery { #[default] @@ -170,20 +205,39 @@ pub(crate) struct ChatTabs<'a> { pub(crate) choices: &'a [SideChat], pub(crate) latest_prompts: &'a HashMap, pub(crate) selected: Option, + pub(crate) files: &'a [FileLink], + pub(crate) files_loading: bool, + pub(crate) files_cwd: Option<&'a PathUri>, + pub(crate) file_preview_unavailable: Option<&'static str>, + pub(crate) scroll: ChooserScroll, } impl<'a> ChatTabs<'a> { pub(crate) fn visible_chat_ids(self, area: Rect, choice: usize) -> Vec { - choice_rows(area, self, choice) - .visible_chats(self, choice) + ChoiceRows::new(area, self) + .visible_choices(self.scroll, choice) .filter_map(|(index, _)| self.choice(index)) .collect() } pub(crate) fn choice_count(self) -> usize { + self.file_start() + self.files.len() + } + + pub(crate) fn file_start(self) -> usize { self.choices.len() + 1 + usize::from(self.retry_row(self.choices.len() + 1)) } + pub(crate) fn file_offset(self, index: usize) -> Option { + index + .checked_sub(self.file_start()) + .filter(|&i| i < self.files.len()) + } + + pub(crate) fn file(self, index: usize) -> Option<&'a FileLink> { + self.files.get(self.file_offset(index)?) + } + pub(crate) fn retry_row(self, index: usize) -> bool { matches!( self.discovery, @@ -202,33 +256,12 @@ impl<'a> ChatTabs<'a> { .filter(|prompt| !prompt.is_empty()) } - fn row_height(self, index: usize) -> u16 { - 1 + u16::from(self.prompt(index).is_some()) - } - - fn fitting_choices(self, indices: impl Iterator, height: usize) -> usize { - let mut used = 0; - indices - .take_while(|&index| { - used += usize::from(self.row_height(index)); - used <= height - }) - .count() - } - pub(crate) fn choice_index(self, id: ThreadId) -> Option { self.choices .iter() .position(|choice| choice.id == id) .map(|index| index + 1) } - - pub(crate) fn strip(self) -> TabStrip<'a, SidebarTab> { - TabStrip { - ids: self.ids, - selected: self.selected, - } - } } pub(crate) fn tab_strip( @@ -236,38 +269,33 @@ pub(crate) fn tab_strip( chooser: TabState, chat: TabState, tabs: ChatTabs<'_>, - hovered_target: Option>, + pointer: Option, document_title: impl Fn(uuid::Uuid, usize) -> String, buf: &mut Buffer, -) { - tabs.strip().render( - area, - buf, - chooser, - chat, - hovered_target, - |id, area, style, buf| { - let title = match id { - SidebarTab::Document(id) => Line::from(document_title(id, usize::from(area.width))), - SidebarTab::Chat(id) => match tabs.choice_index(id) { +) -> Vec<(TabTarget, Rect)> { + TabStrip { + ids: tabs.ids, + selected: tabs.selected, + } + .render(area, buf, chooser, chat, pointer, |id, area, style, buf| { + let width = usize::from(area.width.saturating_sub(1)); + let mut title = match id { + SidebarTab::Document(id) => Line::from(document_title(id, width)), + SidebarTab::Chat(id) => { + let name = match tabs.choice_index(id) { Some(number) => match side_chat_label(&tabs.choices[number - 1]) { - Some(name) => { - let mut title = tabs.label_style.render( - Line::from(name.to_owned()), - usize::from(area.width.saturating_sub(1)), - ); - title.spans.insert(0, " ".into()); - title - } - None if tabs.choices.len() > 1 => Line::from(format!(" Side {number} ")), - None => Line::from(CHAT_TAB), + Some(name) => name.to_owned(), + None if tabs.choices.len() > 1 => format!("Side {number}"), + None => "Side chat".to_owned(), }, - None => Line::from(CHAT_TAB), - }, - }; - title.style(style).render(area, buf); - }, - ); + None => "Side chat".to_owned(), + }; + tabs.label_style.render(Line::from(name), width) + } + }; + title.spans.insert(0, " ".into()); + title.style(style).render(area, buf); + }) } pub(crate) fn side_chat_label(chat: &SideChat) -> Option<&str> { @@ -278,87 +306,259 @@ pub(crate) fn side_chat_label(chat: &SideChat) -> Option<&str> { .lines() .next() .map(str::trim) + .filter(|line| !line.is_empty()) +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct ChooserScroll { + top: usize, + // The wheel can move the viewport away from the keyboard selection. + pub(crate) wheel_scrolled: bool, } struct ChoiceRows { wide: bool, - new_chat: Range, - group: Option, - chats: Range, + height: usize, + chats_header: Option, + files_header: Option, + choices: Vec>, } impl ChoiceRows { - /// Title and subtitle occupy one selectable entry, even when the last line is clipped. - fn visible_chats( + fn new(area: Rect, tabs: ChatTabs<'_>) -> Self { + let wide = body_row(area, area.y).width >= WIDE_WIDTH; + let height = usize::from(area.height.saturating_sub(3)); + let mut row = FIRST_CHOICE_ROW; + let file_start = tabs.file_start(); + let mut chats_header = None; + let mut files_header = None; + let choices = (0..tabs.choice_count()) + .map(|index| { + if index == 1 && !tabs.choices.is_empty() { + chats_header = Some(row + 1); + row += 3; + } else if index == 1 && tabs.retry_row(index) { + row += 2; + } + let file = index >= file_start; + if index == file_start { + files_header = Some(row + 1); + row += 3; + } + let start = row; + let subtitle = if index == 0 || file { + !wide + } else { + tabs.prompt(index).is_some() + }; + row += 1 + usize::from(subtitle); + start..row + }) + .collect(); + Self { + wide, + height, + chats_header, + files_header, + choices, + } + } + + fn max_top(&self) -> usize { + self.choices[self.choices.len() - 1] + .end + .saturating_sub(CHOOSER_BODY_START + self.height) + } + + fn top(&self, scroll: ChooserScroll, choice: usize) -> usize { + let top = scroll.top.min(self.max_top()); + if scroll.wheel_scrolled || self.height == 0 { + return top; + } + if choice == 0 && top == 0 { + return 0; + } + let lines = &self.choices[choice]; + let latest = lines.start - CHOOSER_BODY_START; + let earliest = lines.end.saturating_sub(CHOOSER_BODY_START + self.height); + top.clamp(earliest.min(latest), latest).min(self.max_top()) + } + + fn visible_choices( &self, - tabs: ChatTabs<'_>, + scroll: ChooserScroll, choice: usize, - ) -> impl Iterator)> { - let mut rows = self.chats.clone(); - let selected = choice.max(1); - let spare = rows - .len() - .saturating_sub(usize::from(tabs.row_height(selected))); - let first = selected - tabs.fitting_choices((1..selected).rev(), spare); - (first..tabs.choice_count()).map_while(move |index| { - let start = rows.next()?; - if tabs.prompt(index).is_some() { - rows.next(); - } - Some((index, start..rows.start)) - }) + ) -> impl Iterator)> { + let start = CHOOSER_BODY_START + self.top(scroll, choice); + let end = start + self.height; + let first = self.choices.partition_point(|lines| lines.end <= start); + self.choices + .iter() + .enumerate() + .skip(first) + .take_while(move |(_, lines)| lines.start < end && start < end) } } -fn choice_rows(area: Rect, tabs: ChatTabs<'_>, choice: usize) -> ChoiceRows { - let count = tabs.choice_count(); - let wide = body_row(area, area.y).width >= WIDE_WIDTH; - let new_height = if wide { 1 } else { 2 }; - let footer = area.height.saturating_sub(1); - let new_end = (FIRST_CHOICE_ROW + new_height).min(footer); - let after_group = 1 + u16::from(!tabs.choices.is_empty()); - let group = (count > 1 && footer >= new_end + 1 + after_group + tabs.row_height(choice)) - .then_some(new_end + 1); - // In short panes, let the New row scroll away so the selection remains visible. - let new_chat = FIRST_CHOICE_ROW..if choice == 0 || group.is_some() { - new_end.max(FIRST_CHOICE_ROW) - } else { - FIRST_CHOICE_ROW - }; - let chat_start = group.map_or(new_chat.end, |row| row + after_group); - ChoiceRows { - wide, - new_chat, - group, - chats: chat_start..footer, +pub(crate) fn wheel_scroll( + area: Rect, + tabs: ChatTabs<'_>, + choice: usize, + delta: isize, +) -> ChooserScroll { + let rows = ChoiceRows::new(area, tabs); + ChooserScroll { + top: rows + .top(tabs.scroll, choice) + .saturating_add_signed(delta) + .min(rows.max_top()), + wheel_scrolled: true, } } -pub(crate) fn page_size( +pub(crate) fn navigate( area: Rect, tabs: ChatTabs<'_>, choice: usize, action: ListAction, -) -> usize { - let rows = choice_rows(area, tabs, choice); - let height = rows.chats.len(); - match action { - ListAction::PageUp => tabs.fitting_choices((0..choice).rev(), height), - ListAction::PageDown if choice == 0 => rows.visible_chats(tabs, choice).count(), - ListAction::PageDown => tabs.fitting_choices(choice..tabs.choice_count(), height), - _ => 1, +) -> (usize, ChooserScroll) { + let rows = ChoiceRows::new(area, tabs); + let top = rows.top(tabs.scroll, choice); + let last = rows.choices.len() - 1; + let selected = &rows.choices[choice]; + let height = rows.height.max(1); + let visible = rows.visible_choices(tabs.scroll, choice); + let choice = match action { + ListAction::JumpTop => return (0, ChooserScroll::default()), + ListAction::JumpBottom => last, + ListAction::MoveUp | ListAction::PageUp + if selected.start >= CHOOSER_BODY_START + top + rows.height => + { + visible.last().map_or(choice, |(index, _)| index) + } + ListAction::MoveDown | ListAction::PageDown if selected.end <= CHOOSER_BODY_START + top => { + visible + .into_iter() + .next() + .map_or(choice, |(index, _)| index) + } + ListAction::MoveUp => choice.saturating_sub(1), + ListAction::MoveDown => (choice + 1).min(last), + ListAction::PageUp => rows + .choices + .partition_point(|lines| lines.end <= selected.start.saturating_sub(height)) + .min(choice.saturating_sub(1)), + ListAction::PageDown => rows + .choices + .partition_point(|lines| lines.start <= selected.start + height) + .saturating_sub(1) + .max((choice + 1).min(last)), + _ => return (choice, tabs.scroll), + }; + if choice == 0 { + return (choice, ChooserScroll::default()); } - .max(1) + let mut scroll = ChooserScroll { + top, + wheel_scrolled: false, + }; + scroll.top = rows.top(scroll, choice); + (choice, scroll) } +pub(crate) fn choice_is_visible(area: Rect, tabs: ChatTabs<'_>, choice: usize) -> bool { + ChoiceRows::new(area, tabs) + .visible_choices(tabs.scroll, choice) + .any(|(index, _)| index == choice) +} + +#[cfg(test)] pub(crate) fn choice_at(area: Rect, tabs: ChatTabs<'_>, choice: usize, y: u16) -> Option { - let rows = choice_rows(area, tabs, choice); - let offset = y.checked_sub(area.y)?; - if rows.new_chat.contains(&offset) { - return Some(0); + row_targets(area, tabs, choice, NewChatState::Available) + .find_map(|(index, row)| row.contains((row.x, y).into()).then_some(index)) +} + +pub(crate) fn row_targets( + area: Rect, + tabs: ChatTabs<'_>, + choice: usize, + new_chat: NewChatState, +) -> impl Iterator + '_ { + let rows = ChoiceRows::new(area, tabs); + let top = rows.top(tabs.scroll, choice); + let start = CHOOSER_BODY_START + top; + let end = start + rows.height; + rows.choices + .into_iter() + .enumerate() + .filter_map(move |(index, lines)| { + let first = lines.start.max(start); + let last = lines.end.min(end); + (first < last + && match tabs.file(index) { + Some(_) => tabs.file_preview_unavailable.is_none(), + None => new_chat == NewChatState::Available, + }) + .then(|| Rect { + height: (last - first) as u16, + ..body_row(area, area.y + (first - top) as u16) + }) + .map(|rect| (index, rect)) + }) +} + +pub(crate) fn footer_targets( + area: Rect, + hints: &footer_hint::HintLine, + actions: Vec>, +) -> impl Iterator + '_ { + let row = body_row(area, area.bottom().saturating_sub(1)); + hints + .items + .iter() + .zip(actions) + .filter_map(move |(range, action)| { + if area.height < 2 { + return None; + } + Some(( + action?, + Rect::new(row.x + range.start, row.y, range.end - range.start, 1), + )) + }) +} + +pub(crate) fn file_path_key_available(keymap: &RuntimeKeymap) -> bool { + keymap + .list + .action_for(crossterm::event::KeyCode::Char('p').into()) + .is_none() +} + +pub(crate) fn scroll_file_path(area: Rect, path: &str, top: usize, action: ListAction) -> usize { + let (path_rows, height) = file_path_layout(area, path); + let limit = path_rows.len().saturating_sub(height); + let top = top.min(limit); + match action { + ListAction::MoveUp => top.saturating_sub(1), + ListAction::MoveDown => (top + 1).min(limit), + ListAction::PageUp => top.saturating_sub(height), + ListAction::PageDown => (top + height).min(limit), + ListAction::JumpTop => 0, + ListAction::JumpBottom => limit, + _ => top, } - rows.visible_chats(tabs, choice) - .find_map(|(index, lines)| lines.contains(&offset).then_some(index)) +} + +fn file_path_layout(area: Rect, path: &str) -> (Vec>, usize) { + let body = area + .height + .saturating_sub(u16::from(area.height > 2) * 2 + 1); + let visible = usize::from(body.saturating_sub(u16::from(body > 2) * 2)); + ( + textwrap::wrap(path, usize::from(body_row(area, area.y).width.max(1))), + visible, + ) } pub(crate) struct SidebarStyle<'a> { @@ -366,6 +566,9 @@ pub(crate) struct SidebarStyle<'a> { pub(crate) use_theme_colors: bool, pub(crate) motion: crate::motion::MotionMode, pub(crate) frames: &'a crate::tui::FrameRequester, + pub(crate) hovered_choice: Option, + pub(crate) full_path: Option<&'a str>, + pub(crate) path_scroll: usize, } pub(crate) fn paint( @@ -388,14 +591,41 @@ pub(crate) fn paint( }; let row = |y| body_row(area, y); let footer_y = area.bottom() - 1; - let mut paint = |offset, line: Line<'_>| { - let y = area.y.saturating_add(offset); - if y < footer_y { - line.render(row(y), buf); + if let Some(path) = sidebar_style.full_path { + let mut body = body_row(area, area.y + u16::from(area.height > 2) * 2); + body.height = area + .height + .saturating_sub(u16::from(area.height > 2) * 2 + 1); + let mut lines = Vec::new(); + if body.height > 2 { + lines.extend([Line::from("File path").bold(), Line::default()]); + } + let (path, visible) = file_path_layout(area, path); + let top = sidebar_style + .path_scroll + .min(path.len().saturating_sub(visible)); + lines.extend(path.into_iter().skip(top).take(visible).map(Line::from)); + ratatui::widgets::Paragraph::new(lines).render(body, buf); + footer.render(row(footer_y), buf); + return; + } + let rows = ChoiceRows::new(area, tabs); + let waiting = + sidebar_style.new_chat == NewChatState::WaitingForMainMessage && tabs.files.is_empty(); + let top = if waiting { + 0 + } else { + rows.top(tabs.scroll, choice) + }; + let mut paint = |offset: usize, line: Line<'_>| { + if let Some(y) = offset.checked_sub(top) + && (CHOOSER_BODY_START..CHOOSER_BODY_START + rows.height).contains(&y) + { + line.render(row(area.y + y as u16), buf); } }; paint(2, Line::from("Open in sidebar").bold()); - if sidebar_style.new_chat == NewChatState::WaitingForMainMessage { + if waiting { for (offset, text) in (FIRST_CHOICE_ROW..).zip(textwrap::wrap( "You can start a side chat after your first message in the main chat.", usize::from(row(area.y).width.max(1)), @@ -414,25 +644,39 @@ pub(crate) fn paint( } else { "Refreshing side chats…" }; - paint(3, Line::from(format!("{glyph} {label}").dim())); + paint( + 3, + Line::from(vec![ + glyph.set_style(crate::style::accent_style()), + " ".into(), + label.dim(), + ]), + ); } Discovery::Failed(error) => paint(3, Line::from(error.as_str().red())), + Discovery::Idle if tabs.files_loading => paint(3, Line::from("Loading older files…").dim()), Discovery::Idle => {} } - let rows = choice_rows(area, tabs, choice); let secondary = crate::style::secondary_text_style(); let row_style = |index| { if index == choice { ('›', style, style.not_bold()) + } else if sidebar_style.hovered_choice == Some(index) { + let hover = crate::style::hover_style(crate::style::quiet_workspace_style()); + (' ', hover, hover.not_bold()) } else { (' ', Default::default(), secondary) } }; - if !rows.new_chat.is_empty() { - let y = rows.new_chat.start; + { + let y = FIRST_CHOICE_ROW; let (marker, fill, subtitle) = row_style(0); let title = format!("{marker} + New side chat"); - let detail = Span::styled("Start from the main chat", subtitle); + let detail = match sidebar_style.new_chat { + NewChatState::Available => "Start from this conversation", + NewChatState::WaitingForMainMessage => "Available after your first message", + }; + let detail = Span::styled(detail, subtitle); if rows.wide { let pad = usize::from(row(area.y).width - 1) - detail.width(); paint( @@ -444,17 +688,33 @@ pub(crate) fn paint( paint(y + 1, Line::from(vec![" ".into(), detail]).style(fill)); } } - if let Some(y) = rows.group - && !tabs.choices.is_empty() - { + if let Some(y) = rows.chats_header { let total = tabs.choices.len(); paint( y, Line::from(format!("Side chats {total}")).style(secondary), ); } + if let Some(y) = rows.files_header + && (top + CHOOSER_BODY_START..top + CHOOSER_BODY_START + rows.height).contains(&y) + { + let total = tabs.files.len(); + let group = if tabs + .files + .iter() + .all(|entry| crate::markdown_render::is_markdown_file(&entry.path)) + { + "Markdown files" + } else { + "Files" + }; + paint(y, Line::from(format!("{group} {total}")).style(secondary)); + } let width = usize::from(row(area.y).width); - for (index, lines) in rows.visible_chats(tabs, choice) { + for (index, lines) in rows + .visible_choices(tabs.scroll, choice) + .skip_while(|(index, _)| *index == 0) + { let (marker, fill, subtitle) = row_style(index); if tabs.retry_row(index) { let label = if tabs.discovery.request().is_some() { @@ -468,6 +728,44 @@ pub(crate) fn paint( ); continue; } + if let Some(link) = tabs.file(index) { + let y = lines.start; + let relative = tabs.files_cwd.and_then(|cwd| { + LegacyAppPathString::from_string(&link.path) + .to_inferred_path_uri()? + .relative_path_from(cwd) + }); + let path = relative.as_deref().unwrap_or(&link.path); + let (directory, name) = path + .rsplit_once(['/', '\\']) + .unwrap_or(("Project root", path)); + let directory = tabs.file_preview_unavailable.unwrap_or(directory); + let width = width.saturating_sub(4); + if rows.wide { + let name = filename_label(name, width.saturating_sub(5)); + let directory_width = width.saturating_sub(crate::width::display_width(&name) + 2); + let directory = middle_label(directory, directory_width); + paint( + y, + Line::from(vec![ + format!("{marker} · {name}").into(), + format!(" {directory}").set_style(subtitle), + ]) + .style(fill), + ); + } else { + let name = filename_label(name, width); + paint(y, Line::from(format!("{marker} · {name}")).style(fill)); + if y + 1 < lines.end { + let directory = middle_label(directory, width); + paint( + y + 1, + Line::from(format!(" {directory}")).style(subtitle), + ); + } + } + continue; + } let chat = &tabs.choices[index - 1]; let selected = index == choice && focused; let label = side_chat_label(chat); @@ -492,7 +790,7 @@ pub(crate) fn paint( { Span::styled( crate::motion::loading_glyph(*started, sidebar_style.motion, sidebar_style.frames), - fill, + fill.fg(crate::style::accent_color_on(fill.bg)), ) } else { Span::styled("○", if selected { style } else { secondary }) @@ -539,6 +837,17 @@ pub(crate) fn paint( ); } } + // Keep these in the right margin, outside the clickable list rows. + for (visible, y, glyph) in [ + (top > 0, area.y + 1, "↑"), + (top < rows.max_top(), footer_y.saturating_sub(1), "↓"), + ] { + if visible && rows.height > 0 && area.width >= 3 { + Line::from(glyph) + .style(secondary) + .render(Rect::new(area.right() - 2, y, 1, 1), buf); + } + } if footer_y > area.y { footer.render(row(footer_y), buf); } diff --git a/codex-rs/tui/src/sidebar_tab_strip.rs b/codex-rs/tui/src/sidebar_tab_strip.rs index 7f285de12d..983660fcc6 100644 --- a/codex-rs/tui/src/sidebar_tab_strip.rs +++ b/codex-rs/tui/src/sidebar_tab_strip.rs @@ -101,21 +101,15 @@ impl<'a, Id: Copy + Eq> TabStrip<'a, Id> { targets } - pub(crate) fn hit(self, area: Rect, point: Position) -> Option<(TabTarget, Rect)> { - self.strip_targets(area) - .into_iter() - .find(|(_, rect)| rect.contains(point)) - } - pub(crate) fn render( self, area: Rect, buf: &mut Buffer, add_state: TabState, selected_state: TabState, - hovered_target: Option>, + pointer: Option, paint: impl Fn(Id, Rect, Style, &mut Buffer), - ) { + ) -> Vec<(TabTarget, Rect)> { let style = |state| match state { TabState::Active => crate::style::selection_style().not_underlined(), TabState::Inactive => crate::style::quiet_workspace_style(), @@ -135,8 +129,9 @@ impl<'a, Id: Copy + Eq> TabStrip<'a, Id> { TabState::Inactive => hover.bold(), TabState::Absent => rest, }; - for (target, rect) in self.strip_targets(area) { - let hovered = Some(target) == hovered_target; + let targets = self.strip_targets(area); + for &(target, rect) in &targets { + let hovered = pointer.is_some_and(|point| rect.contains(point)); let quiet = if hovered { hover } else { rest }; match target { TabTarget::Tab(id) => { @@ -184,5 +179,6 @@ impl<'a, Id: Copy + Eq> TabStrip<'a, Id> { } } } + targets } } diff --git a/codex-rs/tui/src/snapshots/codex_tui__app__tests__sidebar_existing_chat.snap b/codex-rs/tui/src/snapshots/codex_tui__app__tests__sidebar_existing_chat.snap index 46b7edefb8..8bb5442608 100644 --- a/codex-rs/tui/src/snapshots/codex_tui__app__tests__sidebar_existing_chat.snap +++ b/codex-rs/tui/src/snapshots/codex_tui__app__tests__sidebar_existing_chat.snap @@ -7,7 +7,7 @@ expression: "chooser.lines().filter_map(|line|\nline.split_once('│').map(|(_, Open in sidebar + New side chat - Start from the main chat + Start from this conversation Side chats 1