From 8fcba7fae90e170345d0a8d0ab68706cb3a33d2c Mon Sep 17 00:00:00 2001 From: Felipe Coury Date: Mon, 9 Nov 2026 01:38:32 +0000 Subject: [PATCH] Improve side-chat discovery and navigation in the TUI (#60319) ## What changed - Show latest user-prompt previews beneath saved side-chat titles, fetching previews only for visible entries when the chooser refreshes. - Keep cached chats available during discovery, show loading and refresh status, and offer an inline retry action on failure. - Preserve the selected chat across list updates and prevent asynchronous changes or held activation keys from opening an unintended entry. Account for preview rows in paging and mouse selection. - Explain that side chats become available after the first main-chat message, and let `Ctrl+C` dismiss the chooser while preserving the main draft. - Separate tabs with noninteractive gaps and improve hover styling for tabs, overflow arrows, and the add button. ## Testing Extend integration tests and snapshots for discovery failures and retries, refreshed prompt previews, activation guards, variable-height paging, draft preservation, and tab hover states across light, dark, and fallback colors. GitOrigin-RevId: 34423f5aeccb566682f7aa219f54ca5c7c8304fb --- codex-rs/tui/src/app.rs | 3 +- codex-rs/tui/src/app/event_dispatch.rs | 25 +- codex-rs/tui/src/app/owned_transcript.rs | 38 +-- codex-rs/tui/src/app/side_focus.rs | 141 ++++++--- codex-rs/tui/src/app/sidebar.rs | 101 ++++++- codex-rs/tui/src/app/sidebar_close.rs | 2 +- ...p__tests__saved_chat_discovery_states.snap | 86 ++++++ codex-rs/tui/src/app/tests.rs | 278 +++++++++++++++--- codex-rs/tui/src/app/tests/key_chords.rs | 53 +++- codex-rs/tui/src/app_event.rs | 8 +- .../app_server_session/side_chat_history.rs | 105 +++++-- codex-rs/tui/src/chatwidget/protocol.rs | 1 + codex-rs/tui/src/chatwidget/replay.rs | 1 + codex-rs/tui/src/chatwidget/session_flow.rs | 3 + codex-rs/tui/src/chatwidget/side.rs | 8 + codex-rs/tui/src/chatwidget/turn_lifecycle.rs | 4 + codex-rs/tui/src/sidebar_chooser.rs | 254 +++++++++++++--- codex-rs/tui/src/sidebar_tab_strip.rs | 67 +++-- ..._tui__app__tests__side_chat_tab_hover.snap | 51 +++- ...codex_tui__app__tests__side_chat_tabs.snap | 2 +- ...ui__app__tests__sidebar_existing_chat.snap | 4 +- codex-rs/tui/src/style.rs | 21 +- 22 files changed, 1023 insertions(+), 233 deletions(-) create mode 100644 codex-rs/tui/src/app/snapshots/codex_tui__app__tests__saved_chat_discovery_states.snap diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index 84a42c3ef4..541062cef5 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -878,7 +878,7 @@ impl App { tui.link_hover.observe(&event); let current = tui.link_hover.position(); if previous != current - && self.hovered_sidebar_tab(previous) != self.hovered_sidebar_tab(current) + && self.hovered_sidebar_target(previous) != self.hovered_sidebar_target(current) { tui.frame_requester().schedule_frame(); } @@ -989,6 +989,7 @@ impl App { } if self.reconnect.offline && !transcript_owns_input + && self.chooser_focus() != Some(sidebar::PaneFocus::Sidebar) && !self.chat_widget.keymap_contexts().is_warnings() && !self .chat_widget diff --git a/codex-rs/tui/src/app/event_dispatch.rs b/codex-rs/tui/src/app/event_dispatch.rs index 4acd12990e..7c11ae7145 100644 --- a/codex-rs/tui/src/app/event_dispatch.rs +++ b/codex-rs/tui/src/app/event_dispatch.rs @@ -1059,8 +1059,8 @@ impl App { tui.clear_pending_history_lines(); let switched_tab = self.conversation_frame.chat_strip.is_some() && self.active_side_parent_thread_id().is_some() - && self.conversation_frame.sidebar_input.is_some_and(|(_, painted_chat, _)| { - painted_chat != self.current_displayed_thread_id() + && self.conversation_frame.sidebar_input.is_some_and(|painted| { + painted.selected_chat != self.current_displayed_thread_id() }); if self.conversation_frame.chooser_area().is_none() && self.chooser_focus().is_none() @@ -3430,16 +3430,21 @@ impl App { } } AppEvent::SavedSideChatsLoaded { backend_id, parent, request, result } => { - let visible = self.current_displayed_thread_id() == Some(parent); + use crate::app_event::SavedSideChatData; + use crate::sidebar_chooser::Discovery; if let Some(pane) = self.sidebars.get_mut(&Some(parent)) - && pane.saved_chats_request == Some(request) + && pane.discovery.request() == Some(request) { - pane.set_saved_chats_request(/*request*/ None); - if backend_id == app_server.backend_id() { - match result { - Ok(chats) => pane.update_saved_chats(chats), - Err(error) if visible => self.chat_widget.add_error_message(error), - Err(error) => tracing::warn!(%parent, %error), + match result { + _ if backend_id != app_server.backend_id() => pane.set_discovery(Discovery::Idle), + Err(error) => pane.set_discovery(Discovery::Failed(error)), + Ok(SavedSideChatData::LatestPrompts(prompts)) => { + pane.latest_prompts = prompts; + pane.set_discovery(Discovery::Idle); + } + Ok(SavedSideChatData::Choices(chats)) => { + pane.update_saved_chats(chats); + self.refresh_visible_side_chat_prompts(tui, app_server, parent, request); } } tui.frame_requester().schedule_frame(); diff --git a/codex-rs/tui/src/app/owned_transcript.rs b/codex-rs/tui/src/app/owned_transcript.rs index 7834b9c675..fc494d7162 100644 --- a/codex-rs/tui/src/app/owned_transcript.rs +++ b/codex-rs/tui/src/app/owned_transcript.rs @@ -36,7 +36,7 @@ pub(super) struct ConversationFrame { inset: Option, pub(super) sidebar: Option, pub(super) chat_strip: Option, - pub(super) sidebar_input: Option<(usize, Option, usize)>, + pub(super) sidebar_input: Option, pub(super) leader_hud: Option, pub(super) close_buttons: [Rect; 2], /// A dialog can obscure neighboring content in the terminal's completed buffer. @@ -295,7 +295,7 @@ impl App { } let highlight_divider = self.pane_resize.is_some() || tui.link_hover.shape == tui::PointerShape::Resize; - let hovered_tab = self.hovered_sidebar_tab(tui.link_hover.position()); + let hovered_target = self.hovered_sidebar_target(tui.link_hover.position()); // An input refresh opens a fresh terminal buffer. Carry the outer owner's // completed cells through it when only the conversation is being redrawn. let backdrop = caller_inset.map(|_| { @@ -372,23 +372,20 @@ impl App { ratatui::widgets::Paragraph::new(text) .wrap(ratatui::widgets::Wrap { trim: false }) .render(body, frame.buffer); - } else if self - .sidebar() - .is_some_and(|pane| pane.saved_chats_request.is_some()) - { - ratatui::widgets::Clear.render(*sidebar, frame.buffer); - Line::from("Loading side chats…").dim().render( - sidebar.inner(ratatui::layout::Margin::new(1, 1)), - frame.buffer, - ); } else if let Some(pane) = self.sidebar() { 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(&self.keymap, *sidebar, pane.choice) - .0 - .line + crate::sidebar_chooser::footer( + &self.keymap, + *sidebar, + pane.choice, + pane.chat_tabs(), + self.chat_widget.side_chat_creation_state(), + ) + .0 + .line }; crate::sidebar_chooser::paint( focused, @@ -397,7 +394,14 @@ impl App { footer, pane.chat_tabs(), pane.choice, - self.local_settings.tui.status_line_use_colors, + &crate::sidebar_chooser::SidebarStyle { + new_chat: self.chat_widget.side_chat_creation_state(), + use_theme_colors: self.local_settings.tui.status_line_use_colors, + motion: MotionMode::from_animations_enabled( + self.local_settings.tui.animations, + ), + frames: &frames, + }, ); let chooser = if focused { TabState::Active @@ -409,7 +413,7 @@ impl App { chooser, TabState::Absent, pane.chat_tabs(), - hovered_tab, + hovered_target, frame.buffer, ); } @@ -430,7 +434,7 @@ impl App { TabState::Absent, chat, pane.chat_tabs(), - hovered_tab, + hovered_target, frame.buffer, ); } diff --git a/codex-rs/tui/src/app/side_focus.rs b/codex-rs/tui/src/app/side_focus.rs index d113da06c3..64afd59b8e 100644 --- a/codex-rs/tui/src/app/side_focus.rs +++ b/codex-rs/tui/src/app/side_focus.rs @@ -12,14 +12,15 @@ use crate::bottom_pane::ScrollState; use crate::keymap::ListAction; use crate::sidebar_chooser; use crate::sidebar_chooser::ChooserAction; +use crate::sidebar_chooser::Discovery; use crate::sidebar_tab_strip::TabTarget; use crate::transcript_view::TranscriptView; impl App { - pub(super) fn hovered_sidebar_tab( + pub(super) fn hovered_sidebar_target( &self, point: Option, - ) -> Option { + ) -> Option> { let point = point?; let strip = self.conversation_frame.sidebar_tab_strip()?; if self.pane_resize.is_some() || !strip.contains(point) { @@ -27,12 +28,18 @@ impl App { } let pane = self.sidebar()?; let tabs = pane.chat_tabs().strip(); - let id = tabs.hit(strip, point)?.0.tab_id()?; - if self.conversation_frame.chat_strip.is_some() { - (tabs.selected != Some(id)).then_some(id) + let target = tabs.hit(strip, point)?.0; + let available = if self.conversation_frame.chat_strip.is_some() { + match target { + TabTarget::Tab(id) | TabTarget::Overflow { tab: id, .. } => { + tabs.selected != Some(id) + } + TabTarget::Add => true, + } } else { - (pane.creation.is_none() && pane.saved_chats_request.is_none()).then_some(id) - } + pane.creation.is_none() + }; + available.then_some(target) } pub(super) fn sidebar_chooser_available(&self) -> bool { @@ -58,36 +65,45 @@ impl App { let parent = self.current_displayed_thread_id(); let pane = self.sidebar_mut(); pane.closing_chats.retain(|_, task| !task.is_finished()); - let was_open = pane.visible_content() == Some(SidebarContent::Chooser); pane.show(SidebarContent::Chooser, PaneFocus::Sidebar); - if !was_open - && pane.creation.is_none() - && pane.saved_chats_request.is_none() + if pane.creation.is_none() && let Some(parent) = parent - && server.can_list_saved_side_chats(parent) { - let request = uuid::Uuid::new_v4(); - pane.set_saved_chats_request(Some(request)); - let codex_home = self.config.codex_home.clone(); - let mut view = server.request_view(); - let tx = self.app_event_tx.clone(); - tokio::spawn(async move { - let result = view - .list_saved_side_chats(parent, codex_home.as_path()) - .await - .map_err(|err| format!("Failed to load saved side chats: {err}")); - tx.send(AppEvent::SavedSideChatsLoaded { - backend_id: view.backend_id(), - parent, - request, - result, - }); - }); + self.refresh_saved_chats(server, parent); } tui.frame_requester().schedule_frame(); Ok(()) } + pub(super) fn refresh_saved_chats(&mut self, server: &AppServerSession, parent: ThreadId) { + let pane = self.sidebar_mut(); + if pane.discovery.request().is_some() || !server.can_list_saved_side_chats(parent) { + return; + } + let request = uuid::Uuid::new_v4(); + pane.set_discovery(Discovery::Loading { + request, + started: Instant::now(), + retry: matches!(pane.discovery, Discovery::Failed(_)), + }); + let codex_home = self.config.codex_home.clone(); + let mut view = server.request_view(); + let tx = self.app_event_tx.clone(); + tokio::spawn(async move { + let result = view + .list_saved_side_chats(parent, codex_home.as_path()) + .await + .map(crate::app_event::SavedSideChatData::Choices) + .map_err(|err| err.to_string()); + tx.send(AppEvent::SavedSideChatsLoaded { + backend_id: view.backend_id(), + parent, + request, + result, + }); + }); + } + async fn activate_sidebar_tab( &mut self, tui: &mut tui::Tui, @@ -154,8 +170,7 @@ impl App { return true; } if let Some(pane) = pane - && (frame.chat_strip.is_some() - || (pane.creation.is_none() && pane.saved_chats_request.is_none())) + && (frame.chat_strip.is_some() || pane.creation.is_none()) && let Some(strip) = frame.sidebar_tab_strip() && strip.contains(point) { @@ -192,6 +207,7 @@ impl App { if self.chooser_focus().is_none() { return false; } + let new_chat = self.chat_widget.side_chat_creation_state(); let (action, activation) = match event { TuiEvent::Mouse(mouse) if mouse.kind == MouseEventKind::Down(MouseButton::Left) => { tui.frame_requester().schedule_frame(); @@ -206,18 +222,23 @@ impl App { }; let pane = self.sidebar_mut(); pane.show(SidebarContent::Chooser, PaneFocus::Sidebar); - if pane.creation.is_some() || pane.saved_chats_request.is_some() { + if pane.creation.is_some() { return true; } + let Some(pane) = self.sidebar() else { + return true; + }; let choice = pane.choice; - let count = pane.chat_tabs().choice_count(); + let tabs = pane.chat_tabs(); let action = if let Some(index) = - crate::sidebar_chooser::choice_at(area, count, choice, mouse.row) + 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); + let (hints, actions) = + sidebar_chooser::footer(&self.keymap, area, choice, tabs, new_chat); let Some(action) = hints .items .into_iter() @@ -239,6 +260,12 @@ impl App { }; let area = self.conversation_frame.chooser_area(); let pane = self.sidebar_mut(); + if new_chat == sidebar_chooser::NewChatState::WaitingForMainMessage + && list_action != ListAction::Cancel + && pane.creation.is_none() + { + return true; + } tui.frame_requester().schedule_frame(); let action = match (list_action, key.kind) { (ListAction::Accept, KeyEventKind::Press) => ChooserAction::Open(pane.choice), @@ -249,15 +276,15 @@ impl App { ChooserAction::Back } _ => { - let count = pane.chat_tabs().choice_count(); + let tabs = pane.chat_tabs(); let visible = area.map_or(1, |area| { - sidebar_chooser::page_size(area, count, pane.choice) + 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, count, visible); + selection.apply_vertical_action(list_action, tabs.choice_count(), visible); pane.choice = selection.selected_idx.unwrap_or_default(); return true; } @@ -272,8 +299,31 @@ impl App { }; let open = matches!(action, ChooserAction::Open(_)); + let frame = &self.conversation_frame; + // Fast keyboard navigation is safe until an asynchronous update changes its target. + if activation.is_some() + && open + && frame.chooser_area().is_some() + && self.sidebar().is_some_and(|pane| { + let current = pane.input_state(); + pane.creation.is_none() + && frame.sidebar_input.is_some_and(|painted| { + painted.revision != current.revision && painted.choice != current.choice + }) + }) + { + self.guard_chooser_key(activation); + return true; + } let pane = self.sidebar_mut(); - if open && pane.saved_chats_request.is_some() { + if let ChooserAction::Open(index) = action + && pane.creation.is_none() + && pane.chat_tabs().retry_row(index) + { + if let Some(parent) = self.current_displayed_thread_id() { + self.refresh_saved_chats(server, parent); + } + self.guard_chooser_key(activation); return true; } if let Some(creation) = &pane.creation { @@ -353,6 +403,11 @@ impl App { } } // Selecting a chat replaces its widget. Guard the composer that will receive repeats. + self.guard_chooser_key(activation); + true + } + + fn guard_chooser_key(&mut self, activation: Option) { if let Some(activation) = activation { self.chat_widget.suppress_current_view_key_until_release( activation, @@ -360,7 +415,6 @@ impl App { ActivationKeySuppression::ViewTransition, ); } - true } pub(super) async fn handle_side_focus_key( @@ -387,7 +441,9 @@ impl App { bindings.focus_main_composer.is_pressed(key) && self.main_composer_shortcut_available(); let sidebar = bindings.focus_sidebar_content.is_pressed(key); let tabs = bindings.focus_sidebar_tabs.is_pressed(key) && self.sidebar_chooser_available(); - let hide = bindings.hide_pane.is_pressed(key); + let hide = bindings.hide_pane.is_pressed(key) + || (self.chooser_focus() == Some(PaneFocus::Sidebar) + && crate::key_hint::ctrl(KeyCode::Char('c')).is_press(key)); let width_change = if bindings.move_divider_left.is_pressed(key) { 2 } else if bindings.move_divider_right.is_pressed(key) { @@ -469,6 +525,7 @@ impl App { Ok(()) } else if chooser.is_some() { if hide || (sidebar && chooser == Some(PaneFocus::Sidebar)) { + self.focus_current_parent_view(tui); self.sidebar_mut().hide(); } else { if main { @@ -514,7 +571,7 @@ impl App { } let view_changed = leaves_transcript || self.current_displayed_thread_id() != previous_thread - || (main && chooser == Some(PaneFocus::Sidebar)); + || ((main || hide) && chooser == Some(PaneFocus::Sidebar)); let suppression = if view_changed && !direct_tab_switch { ActivationKeySuppression::ViewTransition } else { diff --git a/codex-rs/tui/src/app/sidebar.rs b/codex-rs/tui/src/app/sidebar.rs index d2487a97ab..a705008627 100644 --- a/codex-rs/tui/src/app/sidebar.rs +++ b/codex-rs/tui/src/app/sidebar.rs @@ -5,10 +5,14 @@ use super::App; use super::pane_motion::PaneMotion; use super::side_pane; use super::side_pane::SidePaneLayout; +use crate::app_event::AppEvent; +use crate::app_event::SavedSideChatData; +use crate::app_server_session::AppServerSession; 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::Discovery; use crate::tui::Tui; use codex_app_server_protocol::ServerNotification; use codex_app_server_protocol::ThreadItemPayload; @@ -56,6 +60,20 @@ impl SideCreation { } } +#[derive(Clone, Copy, PartialEq, Eq)] +pub(super) enum ChooserSelection { + New, + Chat(ThreadId), + Retry, +} + +#[derive(Clone, Copy, PartialEq, Eq)] +pub(super) struct SidebarInputState { + pub(super) revision: usize, + pub(super) selected_chat: Option, + pub(super) choice: ChooserSelection, +} + #[derive(Default)] pub(super) struct SidebarPane { pub(super) creation: Option, @@ -64,7 +82,9 @@ pub(super) struct SidebarPane { tabs: Vec, // The chooser keeps the same order when an attached chat becomes a live tab. choices: Vec, - pub(super) saved_chats_request: Option, + // A snapshot of the visible rows at the last explicit chooser refresh. + pub(super) latest_prompts: HashMap, + pub(super) discovery: Discovery, pub(super) closing_chats: HashMap>, // Visit order is independent of the order in which tabs appear. visits: Vec, @@ -93,18 +113,26 @@ impl SidebarPane { pub(super) fn chat_tabs(&self) -> ChatTabs<'_> { ChatTabs { + discovery: &self.discovery, ids: &self.tabs, choices: &self.choices, + latest_prompts: &self.latest_prompts, selected: self.selected_chat(), } } - pub(super) fn set_saved_chats_request(&mut self, request: Option) { - self.saved_chats_request = request; + pub(super) fn set_discovery(&mut self, discovery: Discovery) { + if matches!(discovery, Discovery::Failed(_)) && self.choices.is_empty() { + self.choice = 1; + } + self.discovery = discovery; + 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 selection = self.chat_tabs().choice(self.choice); + let keep_new = self.choice == 0 && !self.choices.is_empty(); for chat in &mut self.choices { if !self.tabs.contains(&chat.id) { continue; @@ -123,7 +151,11 @@ impl SidebarPane { self.choices = chats; if reordered { self.tabs_revision += 1; - self.reset_choice(); + if let Some(index) = selection.and_then(|id| self.chat_tabs().choice_index(id)) { + self.choice = index; + } else if !keep_new { + self.reset_choice(); + } } } @@ -149,8 +181,20 @@ impl SidebarPane { self.visits.last().copied() } - pub(super) fn input_state(&self) -> (usize, Option, usize) { - (self.tabs_revision, self.selected_chat(), self.choice) + pub(super) fn input_state(&self) -> SidebarInputState { + let tabs = self.chat_tabs(); + let choice = if let Some(id) = tabs.choice(self.choice) { + ChooserSelection::Chat(id) + } else if tabs.retry_row(self.choice) { + ChooserSelection::Retry + } else { + ChooserSelection::New + }; + SidebarInputState { + revision: self.tabs_revision, + selected_chat: tabs.selected, + choice, + } } fn add_tab(&mut self, id: ThreadId) { @@ -220,6 +264,51 @@ impl SidebarPane { } impl App { + pub(super) fn refresh_visible_side_chat_prompts( + &mut self, + tui: &Tui, + server: &AppServerSession, + 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.chooser_area().or_else(|| { + match side_pane::split_layout(self, tui, screen) { + Some(SidebarLayout::Chooser { sidebar, .. }) => Some(sidebar), + _ if screen.width < 100 && self.chooser_focus() == Some(PaneFocus::Sidebar) => { + Some(screen) + } + _ => None, + } + }) + } else { + None + }; + let Some(pane) = self.sidebars.get_mut(&Some(parent)) else { + return; + }; + let ids = area.map_or_else(Vec::new, |area| { + pane.chat_tabs().visible_chat_ids(area, pane.choice) + }); + if ids.is_empty() { + pane.latest_prompts.clear(); + pane.set_discovery(Discovery::Idle); + return; + } + let view = server.request_view(); + let tx = self.app_event_tx.clone(); + tokio::spawn(async move { + let prompts = view.latest_side_chat_prompts(ids).await; + tx.send(AppEvent::SavedSideChatsLoaded { + backend_id: view.backend_id(), + parent, + request, + result: Ok(SavedSideChatData::LatestPrompts(prompts)), + }); + }); + } + pub(super) fn track_side_chat_title( &mut self, id: ThreadId, diff --git a/codex-rs/tui/src/app/sidebar_close.rs b/codex-rs/tui/src/app/sidebar_close.rs index 010606f17e..0364fc3ffb 100644 --- a/codex-rs/tui/src/app/sidebar_close.rs +++ b/codex-rs/tui/src/app/sidebar_close.rs @@ -314,7 +314,7 @@ pub(super) async fn forget_archived( app.abandoned_side_threads.insert(target); app.discard_thread_local_state(target).await; if let Some(pane) = app.sidebars.get_mut(&Some(parent)) { - pane.set_saved_chats_request(/*request*/ None); + pane.set_discovery(crate::sidebar_chooser::Discovery::Idle); pane.remove_choice(target); if hide { pane.hide(); 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 new file mode 100644 index 0000000000..2d33a4f43f --- /dev/null +++ b/codex-rs/tui/src/app/snapshots/codex_tui__app__tests__saved_chat_discovery_states.snap @@ -0,0 +1,86 @@ +--- +source: tui/src/app/tests.rs +expression: "states.join(\"\\n\\n\")" +--- +Loading + + Open in sidebar + ◌ Loading side chats… + › + New side chat Start from the main chat + +Empty result + + Open in sidebar + + › + New side chat Start from the main chat + +Initial failure + + Open in sidebar + Permission denied by storage + + New side chat + Start from the main chat + + + › Retry loading side chats + +Retry in progress + + Open in sidebar + ◌ Loading side chats… + + New side chat Start from the main chat + + + › Retrying… + +Refreshing cached chats + + Open in sidebar + ◌ Refreshing side chats… + + New side chat Start from the main chat + + Side chats 2 + + › ○ Side chat 1 + ○ Child-only prompt + Child-only prompt + +Cached chats after failure + + Open in sidebar + Refresh failed + + New side chat Start from the main chat + + Side chats 2 + + › ○ Side chat 1 + ○ Child-only prompt + Child-only prompt + Retry loading side chats + +Refreshed chats + + Open in sidebar + + + New side chat + Start from the main chat + + Side chats 2 + + › ○ Named sibling + Latest request with 界 界 界 a… + ○ Child-only prompt + +Readable reply + + Open in sidebar + + + New side chat + Start from the main chat + + Side chats 2 + + › ○ Named sibling + > Which branch? Keep ## My r… + ○ Child-only prompt + Child-only prompt diff --git a/codex-rs/tui/src/app/tests.rs b/codex-rs/tui/src/app/tests.rs index 3ccd26aed3..4864e46ce1 100644 --- a/codex-rs/tui/src/app/tests.rs +++ b/codex-rs/tui/src/app/tests.rs @@ -3330,6 +3330,7 @@ async fn sidebar_reopens_saved_side_chat_after_restart() -> Result<()> { use crate::app_server_session::ResumeModelSettings; use crate::app_server_session::SideChatStorage; use codex_app_server_client::AppServerEvent; + use std::io::Write; let (mut app, mut events, _ops) = make_test_app_with_channels().await; let model = core_test_support::responses::start_mock_server().await; @@ -3385,6 +3386,16 @@ async fn sidebar_reopens_saved_side_chat_after_restart() -> Result<()> { let children = [fork.thread.session.thread_id, child]; server.shutdown().await?; + // The legacy name predates the boundary. Give it a fixed timestamp because the + // index has finer precision than the rollout and both writes can share a millisecond. + writeln!( + std::fs::OpenOptions::new() + .append(true) + .open(config.codex_home.join("session_index.jsonl"))?, + "{}", + serde_json::json!({"id": child, "thread_name": "New name", "updated_at": "2020-01-01T00:00:00Z"}) + )?; + let child_id = child.to_string(); // A cold resume before the first prompt can seed the summary from the parent's history. let mut server = Box::pin(crate::start_embedded_app_server_for_picker(&config)).await?; @@ -3426,49 +3437,194 @@ async fn sidebar_reopens_saved_side_chat_after_restart() -> Result<()> { app.local_settings.tui.animations = false; tui.set_owned_screen(/*owned*/ true)?; - for key in [ + let open_chooser = [ KeyEvent::new(KeyCode::Char('x'), KeyModifiers::CONTROL), KeyCode::Char('t').into(), + ]; + for key in open_chooser { + boxed_future!(app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(key))).await?; + } + let size = Size::new(/*width*/ 208, /*height*/ 14); + let narrow = Size::new(/*width*/ 106, size.height); + let mut states = Vec::new(); + let mut capture = |label: &str, frame: String| { + let sidebar = frame + .lines() + .skip(1) + .take(usize::from(size.height - 2)) + .map(|line| line.split_once('│').expect("sidebar divider").1.trim_end()) + .collect::>() + .join("\n"); + states.push(format!("{label}\n{}", sidebar.trim_end())); + }; + let mut finish_discovery = + async |app: &mut App, tui: &mut tui::Tui, server: &mut AppServerSession| -> Result<()> { + time::timeout(Duration::from_secs(5), async { + while app.sidebar().unwrap().discovery.request().is_some() { + let event = events.recv().await.expect("discovery response"); + boxed_future!(app.handle_event(tui, server, event)).await?; + } + Ok(()) + }) + .await? + }; + let enter = KeyEvent::from(KeyCode::Enter); + let release_enter = + KeyEvent::new_with_kind(KeyCode::Enter, KeyModifiers::NONE, KeyEventKind::Release); + capture("Loading", side_frame(&mut app, &mut tui, size)?); + finish_discovery(&mut app, &mut tui, &mut server).await?; + assert_eq!( + app.sidebar().unwrap().latest_prompts, + HashMap::from([ + (children[0], String::new()), + (child, "Child-only prompt".to_string()) + ]) + ); + assert_eq!(app.sidebar().unwrap().choice, 1); + // The last frame showed New, but the first saved chat is now selected. + boxed_future!(app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(enter))).await?; + assert_eq!(app.current_displayed_thread_id(), Some(parent)); + boxed_future!(app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(release_enter))) + .await?; + app.refresh_saved_chats(&server, parent); + let request = app.sidebar().unwrap().discovery.request().unwrap(); + let empty = AppEvent::SavedSideChatsLoaded { + backend_id: server.backend_id(), + parent, + request, + result: Ok(crate::app_event::SavedSideChatData::Choices(Vec::new())), + }; + boxed_future!(app.handle_event(&mut tui, &mut server, empty)).await?; + capture("Empty result", side_frame(&mut app, &mut tui, size)?); + app.refresh_saved_chats(&server, parent); + let request = app.sidebar().unwrap().discovery.request().unwrap(); + let backend_id = server.backend_id(); + let failure = |request, message: &str| AppEvent::SavedSideChatsLoaded { + backend_id, + parent, + request, + result: Err(message.into()), + }; + let failed = failure(request, "Permission denied by storage"); + boxed_future!(app.handle_event(&mut tui, &mut server, failed)).await?; + capture("Initial failure", side_frame(&mut app, &mut tui, narrow)?); + boxed_future!(app.handle_tui_event( + &mut tui, + &mut server, + TuiEvent::Key(KeyCode::Enter.into()) + )) + .await?; + let retry = app.sidebar().unwrap().discovery.request().unwrap(); + assert_ne!(request, retry); + capture("Retry in progress", side_frame(&mut app, &mut tui, size)?); + finish_discovery(&mut app, &mut tui, &mut server).await?; + side_frame(&mut app, &mut tui, size)?; + // A held Enter can keep producing Press events after the retry row disappears. + for key in [ + KeyEvent::new_with_kind(KeyCode::Enter, KeyModifiers::NONE, KeyEventKind::Repeat), + enter, ] { boxed_future!(app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(key))).await?; } - let size = Size::new(/*width*/ 208, /*height*/ 12); - let loading = side_frame(&mut app, &mut tui, size)?; - let (_, loading) = loading - .lines() - .find_map(|line| { - line.split_once('│') - .filter(|(_, pane)| pane.contains("Loading side chats")) - }) - .expect("pending side-chat discovery"); - insta::assert_snapshot!(loading.trim(), @"Loading side chats…"); - loop { - let event = time::timeout(Duration::from_secs(5), events.recv()) - .await? - .expect("event stream"); - let loaded = matches!(event, AppEvent::SavedSideChatsLoaded { .. }); - boxed_future!(app.handle_event(&mut tui, &mut server, event)).await?; - if loaded { - break; - } + assert_eq!(app.current_displayed_thread_id(), Some(parent)); + boxed_future!(app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(release_enter))) + .await?; + app.sidebar_mut().choice = 1; + app.refresh_saved_chats(&server, parent); + let request = app.sidebar().unwrap().discovery.request().unwrap(); + capture( + "Refreshing cached chats", + side_frame(&mut app, &mut tui, size)?, + ); + let failed = failure(request, "Refresh failed"); + boxed_future!(app.handle_event(&mut tui, &mut server, failed)).await?; + capture( + "Cached chats after failure", + side_frame(&mut app, &mut tui, size)?, + ); + assert_eq!(app.sidebar().unwrap().choice, 1); + + // Another client writes to the first chat while this chooser stays open. + let sibling = children[0]; + server + .resume_thread( + &app.local_settings, + app.config.clone(), + sibling, + ResumeModelSettings::PreserveExistingThread, + ) + .await?; + server + .thread_set_name(sibling, "Named sibling".into()) + .await?; + let latest = "Latest request\nwith 界界界 and enough words to overflow a narrow sidebar"; + for prompt in ["Earlier request", latest] { + side_chat_policy_tests::ask(&mut server, &model, sibling, prompt).await?; } - let frame = side_frame(&mut app, &mut tui, size)?; - let picker = frame - .lines() - .filter_map(|line| line.split_once('│').map(|(_, pane)| pane.trim_end())) - .skip_while(|line| !line.contains("Open in sidebar")) - .take_while(|line| !line.contains(" open · ")) - .collect::>() - .join("\n"); - insta::assert_snapshot!(picker.trim_end(), @" - Open in sidebar + for key in [KeyCode::Char('k'), KeyCode::Char('j')] { + boxed_future!(app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(key.into()))) + .await?; + } + assert!(app.sidebar().unwrap().discovery.request().is_none()); + assert!(app.sidebar().unwrap().latest_prompts[&sibling].is_empty()); + // 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( + MouseEventKind::Down(MouseButton::Left), + 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?; + } + assert_eq!(app.sidebar().unwrap().discovery.request(), Some(request)); + finish_discovery(&mut app, &mut tui, &mut server).await?; + assert_eq!( + app.sidebar().unwrap().latest_prompts, + HashMap::from([(sibling, latest.replace('\n', " "))]) + ); + // One unreadable chat must not discard the other chats' refreshed previews. + let missing = ThreadId::new(); + assert_eq!( + server + .latest_side_chat_prompts(vec![sibling, missing, child]) + .await, + HashMap::from([ + (sibling, latest.replace('\n', " ")), + (missing, String::new()), + (child, "Child-only prompt".to_string()), + ]) + ); + capture("Refreshed chats", side_frame(&mut app, &mut tui, narrow)?); - + New side chat Start from the main chat + let reply = format!( + "{}", + serde_json::json!({"questionItemId": "choice", "question": "Which branch?", "answer": "Keep ## My request for Codex: literal"}) + ); + for (prompt, expected) in [ + ( + "# Context\n## My request for Codex:\nOld context\n## My request for Codex:\nActual request", + "Actual request", + ), + ( + reply.as_str(), + "> Which branch? Keep ## My request for Codex: literal", + ), + ] { + side_chat_policy_tests::ask(&mut server, &model, sibling, prompt).await?; + assert_eq!( + server.latest_side_chat_prompts(vec![sibling]).await, + HashMap::from([(sibling, expected.to_string())]) + ); + } + app.refresh_saved_chats(&server, parent); + finish_discovery(&mut app, &mut tui, &mut server).await?; + capture("Readable reply", side_frame(&mut app, &mut tui, narrow)?); + insta::assert_snapshot!("saved_chat_discovery_states", states.join("\n\n")); - Side chats 2 - › ○ Side chat 1 - ○ Child-only prompt - "); 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')] { @@ -4985,12 +5141,42 @@ async fn handle_start_side_seeds_navigation_before_thread_started() -> Result<() fg: (224, 224, 224), bg: (20, 20, 20), }; + let light = crate::terminal_probe::DefaultColors { + fg: (80, 80, 106), + bg: (238, 241, 246), + }; let mut tab_styles = Vec::new(); let mut redraws = crate::tui::test_support::record_frame_requests(&mut tui); - for (focus, owner) in [("sidebar", sibling), ("main", parent_thread_id)] { + for (focus, owner, key, expected_focus) in [ + ("sidebar", sibling, None, None), + ("main", parent_thread_id, Some(main), None), + ( + "chooser", + parent_thread_id, + Some(chooser_key), + Some(sidebar::PaneFocus::Sidebar), + ), + ( + "chooser main", + parent_thread_id, + Some(main), + Some(sidebar::PaneFocus::Main), + ), + ] { + if let Some(key) = key { + let (code, modifiers) = app.keymap.chords.leader[0].parts(); + keys!(KeyEvent::new(code, modifiers), key); + } assert_eq!(app.current_displayed_thread_id(), Some(owner)); + // The earlier /quit completion leaves a popup on the main composer. + if !app.chat_widget.no_modal_or_popup_active() { + keys!(KeyCode::Esc.into()); + } + assert_eq!(app.chooser_focus(), expected_focus, "{focus}"); side_frame(&mut app, &mut tui, even)?; - let strip = app.conversation_frame.chat_strip.unwrap(); + let strip = app.conversation_frame.sidebar_tab_strip().unwrap(); + let chooser = app.conversation_frame.chat_strip.is_none(); + let add = strip.right() - 3; let tabs = app .sidebar() .unwrap() @@ -4999,17 +5185,24 @@ async fn handle_start_side_seeds_navigation_before_thread_started() -> Result<() .strip_targets(strip); let [inactive, selected] = tabs .filter_map(|(target, area)| { - matches!(target, crate::sidebar_tab_strip::TabTarget::Tab(_)).then_some(area.x + 1) + matches!(target, crate::sidebar_tab_strip::TabTarget::Tab(_)).then_some(area) }) .collect::>() .try_into() .expect("both side-chat tabs are visible"); + assert_eq!(selected.x, inactive.right() + 1); + let [inactive, selected] = [inactive, selected].map(|area| area.x + 1); for (state, column, row, palette, redraw) in [ ("rest", selected, strip.y + 1, Some(colors), None), ("hover", inactive, strip.y, Some(colors), Some(true)), ("fallback", inactive + 1, strip.y, None, Some(false)), ("selected", selected, strip.y, Some(colors), Some(true)), - ("leave", selected, strip.y + 1, Some(colors), Some(false)), + ("leave", selected, strip.y + 1, Some(colors), Some(chooser)), + ("light rest", selected, strip.y + 1, Some(light), None), + ("light hover", inactive, strip.y, Some(light), Some(true)), + ("light add", add, strip.y, Some(light), Some(true)), + ("add", add + 1, strip.y, Some(colors), Some(false)), + ("add fallback", add, strip.y, None, Some(false)), ] { while redraws.try_recv().is_ok() {} let event = mouse(MouseEventKind::Moved, column, row); @@ -5026,9 +5219,10 @@ async fn handle_start_side_seeds_navigation_before_thread_started() -> Result<() format!("{:?}/{:?}/{:?}", cell.fg, cell.bg, cell.modifier) }; tab_styles.push(format!( - "{focus} {state} inactive {} selected {}", + "{focus} {state} inactive {} selected {} add {}", style(inactive), style(selected), + style(add), )); } if owner == sibling { @@ -5036,8 +5230,8 @@ async fn handle_start_side_seeds_navigation_before_thread_started() -> Result<() assert!(app.pane_resize.is_some()); let event = mouse(MouseEventKind::Moved, inactive, strip.y); boxed_future!(app.handle_tui_event(&mut tui, &mut app_server, event)).await?; - assert_eq!(app.hovered_sidebar_tab(tui.link_hover.position()), None); - keys!(KeyCode::Esc.into(), prefix, main); + assert_eq!(app.hovered_sidebar_target(tui.link_hover.position()), None); + keys!(KeyCode::Esc.into()); } } assert_app_snapshot!("side_chat_tab_hover", tab_styles.join("\n")); diff --git a/codex-rs/tui/src/app/tests/key_chords.rs b/codex-rs/tui/src/app/tests/key_chords.rs index 6ba5d7d41a..5c164638e8 100644 --- a/codex-rs/tui/src/app/tests/key_chords.rs +++ b/codex-rs/tui/src/app/tests/key_chords.rs @@ -11,6 +11,7 @@ use super::start_config_write_test_app_server; use super::test_thread_session; use crate::bottom_pane::SelectionItem; use crate::bottom_pane::SelectionViewParams; +use crate::chatwidget::ReplayKind; use crate::chatwidget::tests::helpers::render_bottom_popup; use crate::chatwidget::tests::helpers::set_active_cell; use crate::keymap::KeymapContext; @@ -22,6 +23,7 @@ use codex_app_server_protocol::ThreadHistoryMode; use codex_app_server_protocol::ToolRequestUserInputOption; use codex_app_server_protocol::ToolRequestUserInputParams; use codex_app_server_protocol::ToolRequestUserInputQuestion; +use codex_app_server_protocol::TurnStatus; use codex_config::types::KeybindingSpec; use codex_config::types::KeybindingsSpec; use codex_config::types::TuiKeymap; @@ -1227,6 +1229,33 @@ async fn sidebar_chooser_resize_survives_startup_thread_assignment() -> Result<( .await ); assert!(app.pane_resize.is_none()); + let frame = super::side_frame(&mut app, &mut tui, size)?; + let body = frame + .lines() + .skip(1) + .filter_map(|row| row.split_once('│')) + .map(|(_, sidebar)| sidebar.trim()) + .filter(|row| !row.is_empty()) + .take(3) + .collect::>(); + insta::assert_snapshot!(body.join("\n"), @" + Open in sidebar + You can start a side chat after your first message + in the main chat. + "); + Box::pin(press(&mut app, &mut tui, &mut server, ctrl('x'))).await?; + Box::pin(press( + &mut app, + &mut tui, + &mut server, + KeyCode::Enter.into(), + )) + .await?; + assert_eq!( + app.chooser_focus(), + Some(crate::app::sidebar::PaneFocus::Sidebar) + ); + assert!(app.sidebar().unwrap().creation.is_none()); server.shutdown().await?; Ok(()) } @@ -1243,6 +1272,14 @@ async fn sidebar_chooser_preserves_the_parent_draft_and_starts_a_side_chat() -> server.remember_thread_history_mode(parent, ThreadHistoryMode::Legacy); app.chat_widget .handle_thread_session(test_thread_session(parent, app.config.cwd.to_path_buf())); + app.chat_widget.replay_thread_turns( + vec![super::test_turn( + "parent-turn", + TurnStatus::Completed, + Vec::new(), + )], + ReplayKind::ResumeInitialMessages, + ); app.chat_widget.local_settings.tui.status_line = Some(vec!["model-with-reasoning".into()]); app.chat_widget.refresh_status_line(); app.chat_widget.insert_str("parent draft"); @@ -1443,7 +1480,7 @@ prepared. draft.contains("first prompt") && draft.contains("second prompt"), "{draft}" ); - // The pinned New action leaves room for two scrolling chats. + // A page fits a chat with a subtitle or two title-only chats. let pane = app.sidebar_mut(); for _ in 0..4 { pane.chat_ready(ThreadId::new()); @@ -1453,13 +1490,23 @@ prepared. crate::app::sidebar::PaneFocus::Sidebar, ); pane.choice = 2; - let two_rows = ratatui::layout::Size::new(/*width*/ 120, /*height*/ 11); + let id = pane.chat_tabs().choice(/*index*/ 2).unwrap(); + pane.latest_prompts.insert(id, "Latest request".into()); + let two_rows = ratatui::layout::Size::new(/*width*/ 120, /*height*/ 12); tui.terminal = terminal_at(two_rows); super::side_frame(&mut app, &mut tui, two_rows)?; - for (key, expected) in [(KeyCode::PageDown, 4), (KeyCode::PageUp, 2)] { + for (key, expected) in [ + (KeyCode::PageDown, 3), + (KeyCode::PageDown, 5), + (KeyCode::PageUp, 3), + (KeyCode::PageUp, 2), + ] { Box::pin(press(&mut app, &mut tui, &mut server, key.into())).await?; assert_eq!(app.sidebar().unwrap().choice, expected); } + Box::pin(press(&mut app, &mut tui, &mut server, ctrl('c'))).await?; + assert_eq!(app.chooser_focus(), None); + assert_eq!(app.chat_widget.composer_text_with_pending(), draft); tokio::time::resume(); server.shutdown().await?; Ok(()) diff --git a/codex-rs/tui/src/app_event.rs b/codex-rs/tui/src/app_event.rs index 326457bb8e..bd2c418c2b 100644 --- a/codex-rs/tui/src/app_event.rs +++ b/codex-rs/tui/src/app_event.rs @@ -278,6 +278,12 @@ pub(crate) enum RecapTrigger { Manual, } +#[derive(Debug)] +pub(crate) enum SavedSideChatData { + Choices(Vec), + LatestPrompts(std::collections::HashMap), +} + #[derive(Debug)] pub(crate) struct AgentsOverviewThreadRefresh { pub(crate) cleared_unread: Vec, @@ -503,7 +509,7 @@ pub(crate) enum AppEvent { backend_id: crate::backend_id::BackendId, parent: ThreadId, request: uuid::Uuid, - result: Result, String>, + result: Result, }, /// Submit an op to the specified thread, regardless of current focus. diff --git a/codex-rs/tui/src/app_server_session/side_chat_history.rs b/codex-rs/tui/src/app_server_session/side_chat_history.rs index a7d44a82fd..fd018d5948 100644 --- a/codex-rs/tui/src/app_server_session/side_chat_history.rs +++ b/codex-rs/tui/src/app_server_session/side_chat_history.rs @@ -1,6 +1,7 @@ -//! Discovers local side chats from their own rollouts and reads their visible labels. +//! Discovers local side chats from their own rollouts and reads titles and prompts from child history. use super::*; +use crate::chatwidget::ChatWidget; use codex_app_server_protocol::SortDirection; use codex_app_server_protocol::ThreadItemPayload; use codex_app_server_protocol::ThreadItemsListResponse; @@ -11,6 +12,8 @@ use codex_protocol::models::ContentItem; use codex_rollout::ResponseItemEnvelope; use codex_rollout::RolloutItem; use codex_rollout::read_session_meta_line; +use futures::StreamExt; +use itertools::Itertools; use std::io; use std::path::Path; @@ -66,27 +69,32 @@ impl From for SideChat { } pub(crate) fn side_chat_prompt_preview(content: &[UserInput]) -> Option<&str> { + side_chat_prompt_parts(content)? + .next()? + .lines() + .next() + .map(str::trim) +} + +fn side_chat_prompt_parts(content: &[UserInput]) -> Option> { if crate::chatwidget::realtime_delegation_input(content).is_some() { return None; } - content - .iter() - .find_map(|input| match input { - UserInput::Text { text, .. } => { - codex_protocol::protocol::strip_user_message_prefix(text) - .lines() - .next() - .map(str::trim) - } + let mut text = content.iter().filter_map(|input| { + let UserInput::Text { text, .. } = input else { + return None; + }; + let text = codex_protocol::protocol::strip_user_message_prefix(text); + (!text.is_empty()).then_some(text) + }); + let first = text.next().or_else(|| { + content.iter().find_map(|input| match input { + UserInput::Image { .. } | UserInput::LocalImage { .. } => Some("[Image]"), + UserInput::Audio { .. } | UserInput::LocalAudio { .. } => Some("[Audio]"), _ => None, }) - .or_else(|| { - content.iter().find_map(|input| match input { - UserInput::Image { .. } | UserInput::LocalImage { .. } => Some("[Image]"), - UserInput::Audio { .. } | UserInput::LocalAudio { .. } => Some("[Audio]"), - _ => None, - }) - }) + })?; + Some(std::iter::once(first).chain(text)) } pub(super) fn is_attached_thread_store_unsupported(err: &color_eyre::Report) -> bool { @@ -203,7 +211,7 @@ impl AppServerSession { true }); let preview = if name.is_none() { - self.first_side_chat_prompt(id) + self.side_chat_prompt(id, SortDirection::Asc) .await .unwrap_or_else(|error| { tracing::debug!(%id, %error, "failed to load side-chat prompt"); @@ -289,7 +297,29 @@ impl AppServerSession { } } - async fn first_side_chat_prompt(&mut self, id: ThreadId) -> Result { + pub(crate) async fn latest_side_chat_prompts( + &self, + ids: Vec, + ) -> HashMap { + // Bound the number of paginated reads in flight when a tall chooser shows many chats. + futures::stream::iter(ids) + .map(|id| async move { + let mut view = self.request_view(); + let prompt = view + .side_chat_prompt(id, SortDirection::Desc) + .await + .unwrap_or_else(|error| { + tracing::debug!(%id, %error, "failed to load side-chat prompt"); + String::new() + }); + (id, prompt) + }) + .buffer_unordered(4) + .collect() + .await + } + + async fn side_chat_prompt(&mut self, id: ThreadId, order: SortDirection) -> Result { // The summary preview can come from inherited model context. Item pages only contain // the child's visible history, including for chats saved by older clients. let mut cursor = None; @@ -297,23 +327,48 @@ impl AppServerSession { loop { let mut params = thread_items_page_params(id, /*turn_id*/ None, cursor, /*limit*/ 16); - params.sort_direction = Some(SortDirection::Asc); + params.sort_direction = Some(order); let request_id = self.next_request_id(); let page: ThreadItemsListResponse = self .request_handle .request_typed(ClientRequest::ThreadItemsList { request_id, params }) .await?; - if let Some(preview) = page + if let Some(prompt) = page .data .iter() .find_map(|entry| match &entry.item.payload { - ThreadItemPayload::UserMessage { content, .. } => { - side_chat_prompt_preview(content) - } + ThreadItemPayload::UserMessage { content, .. } => match order { + SortDirection::Asc => side_chat_prompt_preview(content).map(str::to_owned), + SortDirection::Desc => { + if crate::chatwidget::realtime_delegation_input(content).is_some() { + return None; + } + let mut prompt = + ChatWidget::user_message_display_from_inputs(content).message; + if prompt.trim().is_empty() { + prompt = + content + .iter() + .find_map(|input| match input { + UserInput::Image { .. } + | UserInput::LocalImage { .. } => Some("[Image]"), + UserInput::Audio { .. } + | UserInput::LocalAudio { .. } => Some("[Audio]"), + _ => None, + })? + .to_owned(); + } + Some( + crate::history_cell::sanitize_user_text(prompt.into()) + .split_whitespace() + .join(" "), + ) + } + }, _ => None, }) { - return Ok(preview.to_owned()); + return Ok(prompt); } let Some(next) = page.next_cursor else { return Ok(String::new()); diff --git a/codex-rs/tui/src/chatwidget/protocol.rs b/codex-rs/tui/src/chatwidget/protocol.rs index 4f1746eb3d..a085cee8ac 100644 --- a/codex-rs/tui/src/chatwidget/protocol.rs +++ b/codex-rs/tui/src/chatwidget/protocol.rs @@ -87,6 +87,7 @@ impl ChatWidget { self.on_thread_settings_updated(notification); } ServerNotification::TurnStarted(notification) => { + self.turn_lifecycle.has_turn_history = true; if self .bottom_pane .dismiss_view_by_id(safety_recourse::VIEW_ID) diff --git a/codex-rs/tui/src/chatwidget/replay.rs b/codex-rs/tui/src/chatwidget/replay.rs index d6972e1572..62b4645ba2 100644 --- a/codex-rs/tui/src/chatwidget/replay.rs +++ b/codex-rs/tui/src/chatwidget/replay.rs @@ -98,6 +98,7 @@ impl ChatWidget { /// avoid triggering side effects. Event ids are passed as `None` to /// distinguish replayed events from live ones. pub(crate) fn replay_thread_turns(&mut self, turns: Vec, replay_kind: ReplayKind) { + self.turn_lifecycle.has_turn_history |= !turns.is_empty(); if !turns.is_empty() || matches!(replay_kind, ReplayKind::ThreadSnapshot) { self.bottom_pane.dismiss_composer_sparkle(); } diff --git a/codex-rs/tui/src/chatwidget/session_flow.rs b/codex-rs/tui/src/chatwidget/session_flow.rs index 3ce1a25743..57376049a2 100644 --- a/codex-rs/tui/src/chatwidget/session_flow.rs +++ b/codex-rs/tui/src/chatwidget/session_flow.rs @@ -124,7 +124,10 @@ impl ChatWidget { self.review.recent_auto_review_denials = RecentAutoReviewDenials::default(); self.clear_thread_usage_state(); } + let has_turn_history = + previous_thread_id == self.thread_id && self.turn_lifecycle.has_turn_history; self.turn_lifecycle.reset_thread(); + self.turn_lifecycle.has_turn_history = has_turn_history; self.safety_recourse = None; self.clear_safety_buffering(); self.thread_name = session.thread_name.clone(); diff --git a/codex-rs/tui/src/chatwidget/side.rs b/codex-rs/tui/src/chatwidget/side.rs index 7e0726430d..1b1e42549e 100644 --- a/codex-rs/tui/src/chatwidget/side.rs +++ b/codex-rs/tui/src/chatwidget/side.rs @@ -7,6 +7,14 @@ use super::*; impl ChatWidget { + pub(crate) fn side_chat_creation_state(&self) -> crate::sidebar_chooser::NewChatState { + if self.thread_id.is_some() && self.turn_lifecycle.has_turn_history { + crate::sidebar_chooser::NewChatState::Available + } else { + crate::sidebar_chooser::NewChatState::WaitingForMainMessage + } + } + pub(crate) fn submit_user_message_as_plain_user_turn( &mut self, user_message: UserMessage, diff --git a/codex-rs/tui/src/chatwidget/turn_lifecycle.rs b/codex-rs/tui/src/chatwidget/turn_lifecycle.rs index 0562da3a63..9d0215775e 100644 --- a/codex-rs/tui/src/chatwidget/turn_lifecycle.rs +++ b/codex-rs/tui/src/chatwidget/turn_lifecycle.rs @@ -11,6 +11,8 @@ pub(super) struct TurnLifecycleState { /// Tracks whether codex-core currently considers an agent turn to be in progress. pub(super) agent_turn_running: bool, pub(super) last_turn_id: Option, + /// A live or restored turn makes the parent available for side-chat creation. + pub(super) has_turn_history: bool, /// Cloud confirmed admission to a turn whose live start we have yet to process. pub(super) admitted_turn_id: Option, pub(super) budget_limited_turn_ids: HashSet, @@ -25,6 +27,7 @@ impl TurnLifecycleState { sleep_inhibitor: SleepInhibitor::new(prevent_idle_sleep), agent_turn_running: false, last_turn_id: None, + has_turn_history: false, admitted_turn_id: None, budget_limited_turn_ids: HashSet::new(), rendered_completion_turn_ids: HashSet::new(), @@ -58,6 +61,7 @@ impl TurnLifecycleState { pub(super) fn reset_thread(&mut self) { self.finish(); self.last_turn_id = None; + self.has_turn_history = false; self.admitted_turn_id = None; self.budget_limited_turn_ids.clear(); self.rendered_completion_turn_ids.clear(); diff --git a/codex-rs/tui/src/sidebar_chooser.rs b/codex-rs/tui/src/sidebar_chooser.rs index 1eff9671b8..79ed64af27 100644 --- a/codex-rs/tui/src/sidebar_chooser.rs +++ b/codex-rs/tui/src/sidebar_chooser.rs @@ -6,8 +6,10 @@ use crate::keymap::KeymapContext; use crate::keymap::ListAction; use crate::keymap::RuntimeKeymap; use crate::line_truncation::truncate_line_with_ellipsis_if_overflow; +use crate::live_wrap::take_prefix_by_width; use crate::sidebar_tab_strip::TabState; use crate::sidebar_tab_strip::TabStrip; +use crate::sidebar_tab_strip::TabTarget; use codex_protocol::ThreadId; use ratatui::buffer::Buffer; use ratatui::layout::Rect; @@ -16,6 +18,7 @@ use ratatui::text::Line; use ratatui::text::Span; use ratatui::widgets::Clear; use ratatui::widgets::Widget; +use std::collections::HashMap; use std::ops::Range; const WIDE_WIDTH: u16 = 58; @@ -40,6 +43,12 @@ pub(crate) enum ChooserAction { Hide, } +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) enum NewChatState { + WaitingForMainMessage, + Available, +} + fn list_hint(keymap: &RuntimeKeymap, action: ListAction) -> Option { keymap .list @@ -63,10 +72,13 @@ pub(crate) fn footer( keymap: &RuntimeKeymap, area: Rect, choice: usize, + tabs: ChatTabs<'_>, + new_chat: NewChatState, ) -> (footer_hint::HintLine, Vec>) { let hint = |action| list_hint(keymap, action); let movement = [ListAction::MoveUp, ListAction::MoveDown] .into_iter() + .filter(|_| new_chat == NewChatState::Available) .filter_map(hint) .collect::>() .join("/"); @@ -75,8 +87,12 @@ pub(crate) fn footer( .map(super::key_hint::ShortcutHint::display_label); let (hints, actions): (Vec<_>, Vec<_>) = [ ( - hint(ListAction::Accept), - "open", + hint(ListAction::Accept).filter(|_| new_chat == NewChatState::Available), + if tabs.retry_row(choice) { + "retry" + } else { + "open" + }, Some(ChooserAction::Open(choice)), ), (hint(ListAction::Cancel), "back", Some(ChooserAction::Back)), @@ -103,23 +119,81 @@ pub(crate) fn close_cell(tab: Rect) -> Rect { ) } -#[derive(Clone, Copy, Default)] +#[derive(Default)] +pub(crate) enum Discovery { + #[default] + Idle, + Loading { + request: uuid::Uuid, + started: std::time::Instant, + retry: bool, + }, + Failed(String), +} + +impl Discovery { + pub(crate) fn request(&self) -> Option { + match self { + Self::Loading { request, .. } => Some(*request), + Self::Idle | Self::Failed(_) => None, + } + } +} + +#[derive(Clone, Copy)] pub(crate) struct ChatTabs<'a> { + pub(crate) discovery: &'a Discovery, pub(crate) ids: &'a [ThreadId], // Chooser index zero is reserved for New side chat. pub(crate) choices: &'a [SideChat], + pub(crate) latest_prompts: &'a HashMap, pub(crate) selected: Option, } 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) + .filter_map(|(index, _)| self.choice(index)) + .collect() + } + pub(crate) fn choice_count(self) -> usize { - self.choices.len() + 1 + self.choices.len() + 1 + usize::from(self.retry_row(self.choices.len() + 1)) + } + + pub(crate) fn retry_row(self, index: usize) -> bool { + matches!( + self.discovery, + Discovery::Failed(_) | Discovery::Loading { retry: true, .. } + ) && index == self.choices.len() + 1 } pub(crate) fn choice(self, index: usize) -> Option { Some(self.choices.get(index.checked_sub(1)?)?.id) } + fn prompt(self, index: usize) -> Option<&'a str> { + self.latest_prompts + .get(&self.choice(index)?) + .map(String::as_str) + .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() @@ -141,7 +215,7 @@ pub(crate) fn tab_strip( chooser: TabState, chat: TabState, tabs: ChatTabs<'_>, - hovered_tab: Option, + hovered_target: Option>, buf: &mut Buffer, ) { tabs.strip().render( @@ -149,7 +223,7 @@ pub(crate) fn tab_strip( buf, chooser, chat, - hovered_tab, + hovered_target, |id, area, style, buf| { let close = close_cell(area); let label = Rect::new(area.x, area.y, area.width - close.width, area.height); @@ -184,46 +258,88 @@ struct ChoiceRows { wide: bool, new_chat: Range, group: Option, - chat_start: u16, - chats: Range, + chats: Range, } -fn choice_rows(area: Rect, count: usize, choice: usize) -> ChoiceRows { +impl ChoiceRows { + /// Title and subtitle occupy one selectable entry, even when the last line is clipped. + fn visible_chats( + &self, + tabs: ChatTabs<'_>, + 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)) + }) + } +} + +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 group = (count > 1 && footer > new_end + 2).then_some(new_end + 1); + 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 + 1); - let visible = usize::from(footer.saturating_sub(chat_start)); - let first = (choice + 1).saturating_sub(visible).max(1); + let chat_start = group.map_or(new_chat.end, |row| row + after_group); ChoiceRows { wide, new_chat, group, - chat_start, - chats: first..(first + visible).min(count), + chats: chat_start..footer, } } -pub(crate) fn page_size(area: Rect, count: usize, choice: usize) -> usize { - choice_rows(area, count, choice).chats.len().max(1) +pub(crate) fn page_size( + 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, + } + .max(1) } -pub(crate) fn choice_at(area: Rect, count: usize, choice: usize, y: u16) -> Option { - let mut rows = choice_rows(area, count, choice); +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); } - rows.chats - .nth(usize::from(offset.checked_sub(rows.chat_start)?)) + rows.visible_chats(tabs, choice) + .find_map(|(index, lines)| lines.contains(&offset).then_some(index)) +} + +pub(crate) struct SidebarStyle<'a> { + pub(crate) new_chat: NewChatState, + pub(crate) use_theme_colors: bool, + pub(crate) motion: crate::motion::MotionMode, + pub(crate) frames: &'a crate::tui::FrameRequester, } pub(crate) fn paint( @@ -233,7 +349,7 @@ pub(crate) fn paint( footer: Line<'_>, tabs: ChatTabs<'_>, choice: usize, - use_theme_colors: bool, + sidebar_style: &SidebarStyle<'_>, ) { Clear.render(area, buf); if area.is_empty() { @@ -253,60 +369,114 @@ pub(crate) fn paint( } }; paint(2, Line::from("Open in sidebar").bold()); - let count = tabs.choice_count(); - let rows = choice_rows(area, count, choice); + if sidebar_style.new_chat == NewChatState::WaitingForMainMessage { + 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)), + )) { + paint(offset, Line::from(text).dim()); + } + footer.render(row(footer_y), buf); + return; + } + match tabs.discovery { + Discovery::Loading { started, .. } => { + let glyph = + crate::motion::loading_glyph(*started, sidebar_style.motion, sidebar_style.frames); + let label = if tabs.choices.is_empty() { + "Loading side chats…" + } else { + "Refreshing side chats…" + }; + paint(3, Line::from(format!("{glyph} {label}").dim())); + } + Discovery::Failed(error) => paint(3, Line::from(error.as_str().red())), + 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, style.not_bold()) } else { - (' ', Default::default()) + (' ', Default::default(), secondary) } }; - let secondary = crate::style::secondary_text_style(); if !rows.new_chat.is_empty() { let y = rows.new_chat.start; - let (marker, fill) = row_style(0); + let (marker, fill, subtitle) = row_style(0); let title = format!("{marker} + New side chat"); - let detail = "Start from the main chat"; + let detail = Span::styled("Start from the main chat", subtitle); if rows.wide { - let pad = usize::from(row(area.y).width - 1) - detail.len(); - paint(y, Line::from(format!("{title: 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 b211c70800..4244442a6f 100644 --- a/codex-rs/tui/src/sidebar_tab_strip.rs +++ b/codex-rs/tui/src/sidebar_tab_strip.rs @@ -1,5 +1,6 @@ //! Draw sidebar tabs and hit-test the same visible cells. When space runs out, //! keep the selected tab visible and reserve the add button at the right edge. +//! A one-column gap separates tabs and is excluded from their click targets. use ratatui::buffer::Buffer; use ratatui::layout::Position; @@ -9,6 +10,9 @@ use ratatui::style::Style; use ratatui::text::Line; use ratatui::widgets::Widget; +/// Adjacent tabs have one unpainted, noninteractive terminal column between them. +const TAB_GAP: u16 = 1; + #[derive(Clone, Copy, PartialEq, Eq)] pub(crate) enum TabState { Absent, @@ -23,21 +27,13 @@ pub(crate) struct TabStrip<'a, Id> { pub(crate) tab_width: u16, } +#[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum TabTarget { Tab(Id), Overflow { tab: Id, glyph: &'static str }, Add, } -impl TabTarget { - pub(crate) fn tab_id(&self) -> Option { - match self { - Self::Tab(id) | Self::Overflow { tab: id, .. } => Some(*id), - Self::Add => None, - } - } -} - impl<'a, Id: Copy + Eq> TabStrip<'a, Id> { pub(crate) fn selected_index(self) -> Option { self.ids.iter().position(|id| Some(*id) == self.selected) @@ -51,12 +47,17 @@ impl<'a, Id: Copy + Eq> TabStrip<'a, Id> { let plus = width.min(3); let available = width - plus; let height = area.height.min(1); - let overflow = self.ids.len() > usize::from((available / self.tab_width).max(1)); + let stride = self.tab_width.saturating_add(TAB_GAP); + let overflow = self.ids.len() > usize::from(((available + TAB_GAP) / stride).max(1)); // Reserve both arrow gutters so the tabs stay in place while switching. let gutter = if overflow && available >= 7 { 2 } else { 0 }; let space = available - 2 * gutter; let tab_width = space.min(self.tab_width); - let count = usize::from(space.checked_div(tab_width).unwrap_or_default()); + let count = if tab_width == 0 { + 0 + } else { + usize::from((space + TAB_GAP) / (tab_width + TAB_GAP)) + }; let first = self .selected_index() .map_or(0, |index| (index + 1).saturating_sub(count)); @@ -69,7 +70,7 @@ impl<'a, Id: Copy + Eq> TabStrip<'a, Id> { let tabs = self.ids[first..end].iter().enumerate().map(move |(i, id)| { ( TabTarget::Tab(*id), - rect(gutter + i as u16 * tab_width, tab_width), + rect(gutter + i as u16 * (tab_width + TAB_GAP), tab_width), ) }); left.into_iter() @@ -89,35 +90,36 @@ impl<'a, Id: Copy + Eq> TabStrip<'a, Id> { buf: &mut Buffer, add_state: TabState, selected_state: TabState, - hovered_tab: Option, + hovered_target: Option>, paint: impl Fn(Id, Rect, Style, &mut Buffer), ) { let style = |state| match state { TabState::Active => crate::style::selection_style().not_underlined(), - TabState::Inactive => crate::bottom_pane::active_tab_style(), + TabState::Inactive => crate::style::quiet_workspace_style(), TabState::Absent => crate::style::secondary_text_style() .bg(Color::Reset) .not_underlined() .not_reversed(), }; + let rest = style(TabState::Absent).patch(crate::style::user_message_style()); + let rest = rest.fg(crate::style::readable_color_on( + rest.fg.unwrap_or(Color::Reset), + rest.bg, + )); + let hover = crate::style::hover_style(style(TabState::Absent).fg(Color::Reset)); + let selected_style = match selected_state { + TabState::Active => style(selected_state), + TabState::Inactive => hover.bold(), + TabState::Absent => rest, + }; for (target, rect) in self.strip_targets(area) { - let quiet = if hovered_tab.is_some() && target.tab_id() == hovered_tab { - let hover = crate::style::quiet_workspace_style() - .fg(Color::Reset) - .not_dim(); - if hover.bg == Some(Color::Reset) { - hover.underlined() - } else { - hover - } - } else { - style(TabState::Absent) - }; + let hovered = Some(target) == hovered_target; + let quiet = if hovered { hover } else { rest }; match target { TabTarget::Tab(id) => { let tab_style = if Some(id) == self.selected && selected_state != TabState::Absent { - style(selected_state) + selected_style } else { quiet }; @@ -126,7 +128,16 @@ impl<'a, Id: Copy + Eq> TabStrip<'a, Id> { TabTarget::Overflow { glyph, .. } => { Line::from(glyph).style(quiet).render(rect, buf) } - TabTarget::Add => Line::from(" + ").style(style(add_state)).render(rect, buf), + TabTarget::Add => { + let add = match (hovered, add_state) { + (true, TabState::Active) => crate::style::hover_style(style(add_state)), + (true, TabState::Inactive | TabState::Absent) => hover, + (false, TabState::Active | TabState::Inactive | TabState::Absent) => { + style(add_state) + } + }; + Line::from(" + ").style(add).render(rect, buf); + } } } } diff --git a/codex-rs/tui/src/snapshots/codex_tui__app__tests__side_chat_tab_hover.snap b/codex-rs/tui/src/snapshots/codex_tui__app__tests__side_chat_tab_hover.snap index ab706a1664..f8e1e3ed80 100644 --- a/codex-rs/tui/src/snapshots/codex_tui__app__tests__side_chat_tab_hover.snap +++ b/codex-rs/tui/src/snapshots/codex_tui__app__tests__side_chat_tab_hover.snap @@ -1,15 +1,44 @@ --- source: tui/src/app/tests.rs -assertion_line: 4599 expression: "tab_styles.join(\"\\n\")" --- -sidebar rest inactive Rgb(142, 142, 142)/Reset/NONE selected Rgb(0, 0, 46)/Rgb(99, 168, 248)/BOLD -sidebar hover inactive Reset/Rgb(31, 31, 31)/NONE selected Rgb(0, 0, 46)/Rgb(99, 168, 248)/BOLD -sidebar fallback inactive Reset/Reset/UNDERLINED selected Reset/Reset/BOLD | REVERSED -sidebar selected inactive Rgb(142, 142, 142)/Reset/NONE selected Rgb(0, 0, 46)/Rgb(99, 168, 248)/BOLD -sidebar leave inactive Rgb(142, 142, 142)/Reset/NONE selected Rgb(0, 0, 46)/Rgb(99, 168, 248)/BOLD -main rest inactive Rgb(142, 142, 142)/Reset/NONE selected Rgb(224, 224, 224)/Rgb(76, 76, 76)/BOLD -main hover inactive Reset/Rgb(31, 31, 31)/NONE selected Rgb(224, 224, 224)/Rgb(76, 76, 76)/BOLD -main fallback inactive Reset/Reset/UNDERLINED selected Reset/Reset/BOLD | UNDERLINED -main selected inactive Rgb(142, 142, 142)/Reset/NONE selected Rgb(224, 224, 224)/Rgb(76, 76, 76)/BOLD -main leave inactive Rgb(142, 142, 142)/Reset/NONE selected Rgb(224, 224, 224)/Rgb(76, 76, 76)/BOLD +sidebar rest inactive Rgb(151, 151, 151)/Rgb(48, 48, 48)/NONE selected Rgb(0, 0, 46)/Rgb(99, 168, 248)/BOLD add Rgb(142, 142, 142)/Reset/NONE +sidebar hover inactive Rgb(224, 224, 224)/Rgb(72, 72, 72)/NONE selected Rgb(0, 0, 46)/Rgb(99, 168, 248)/BOLD add Rgb(142, 142, 142)/Reset/NONE +sidebar fallback inactive Reset/Reset/UNDERLINED selected Reset/Reset/BOLD | REVERSED add Reset/Reset/NONE +sidebar selected inactive Rgb(151, 151, 151)/Rgb(48, 48, 48)/NONE selected Rgb(0, 0, 46)/Rgb(99, 168, 248)/BOLD add Rgb(142, 142, 142)/Reset/NONE +sidebar leave inactive Rgb(151, 151, 151)/Rgb(48, 48, 48)/NONE selected Rgb(0, 0, 46)/Rgb(99, 168, 248)/BOLD add Rgb(142, 142, 142)/Reset/NONE +sidebar light rest inactive Rgb(102, 103, 117)/Rgb(228, 231, 236)/NONE selected Rgb(0, 0, 46)/Rgb(164, 205, 251)/BOLD add Rgb(108, 109, 123)/Reset/NONE +sidebar light hover inactive Rgb(80, 80, 106)/Rgb(218, 221, 226)/NONE selected Rgb(0, 0, 46)/Rgb(164, 205, 251)/BOLD add Rgb(108, 109, 123)/Reset/NONE +sidebar light add inactive Rgb(102, 103, 117)/Rgb(228, 231, 236)/NONE selected Rgb(0, 0, 46)/Rgb(164, 205, 251)/BOLD add Rgb(80, 80, 106)/Rgb(218, 221, 226)/NONE +sidebar add inactive Rgb(151, 151, 151)/Rgb(48, 48, 48)/NONE selected Rgb(0, 0, 46)/Rgb(99, 168, 248)/BOLD add Rgb(224, 224, 224)/Rgb(72, 72, 72)/NONE +sidebar add fallback inactive Reset/Reset/NONE selected Reset/Reset/BOLD | REVERSED add Reset/Reset/UNDERLINED +main rest inactive Rgb(151, 151, 151)/Rgb(48, 48, 48)/NONE selected Rgb(224, 224, 224)/Rgb(72, 72, 72)/BOLD add Rgb(142, 142, 142)/Reset/NONE +main hover inactive Rgb(224, 224, 224)/Rgb(72, 72, 72)/NONE selected Rgb(224, 224, 224)/Rgb(72, 72, 72)/BOLD add Rgb(142, 142, 142)/Reset/NONE +main fallback inactive Reset/Reset/UNDERLINED selected Reset/Reset/BOLD | UNDERLINED add Reset/Reset/NONE +main selected inactive Rgb(151, 151, 151)/Rgb(48, 48, 48)/NONE selected Rgb(224, 224, 224)/Rgb(72, 72, 72)/BOLD add Rgb(142, 142, 142)/Reset/NONE +main leave inactive Rgb(151, 151, 151)/Rgb(48, 48, 48)/NONE selected Rgb(224, 224, 224)/Rgb(72, 72, 72)/BOLD add Rgb(142, 142, 142)/Reset/NONE +main light rest inactive Rgb(102, 103, 117)/Rgb(228, 231, 236)/NONE selected Rgb(80, 80, 106)/Rgb(218, 221, 226)/BOLD add Rgb(108, 109, 123)/Reset/NONE +main light hover inactive Rgb(80, 80, 106)/Rgb(218, 221, 226)/NONE selected Rgb(80, 80, 106)/Rgb(218, 221, 226)/BOLD add Rgb(108, 109, 123)/Reset/NONE +main light add inactive Rgb(102, 103, 117)/Rgb(228, 231, 236)/NONE selected Rgb(80, 80, 106)/Rgb(218, 221, 226)/BOLD add Rgb(80, 80, 106)/Rgb(218, 221, 226)/NONE +main add inactive Rgb(151, 151, 151)/Rgb(48, 48, 48)/NONE selected Rgb(224, 224, 224)/Rgb(72, 72, 72)/BOLD add Rgb(224, 224, 224)/Rgb(72, 72, 72)/NONE +main add fallback inactive Reset/Reset/NONE selected Reset/Reset/BOLD | UNDERLINED add Reset/Reset/UNDERLINED +chooser rest inactive Rgb(151, 151, 151)/Rgb(48, 48, 48)/NONE selected Rgb(151, 151, 151)/Rgb(48, 48, 48)/NONE add Rgb(0, 0, 46)/Rgb(99, 168, 248)/BOLD +chooser hover inactive Rgb(224, 224, 224)/Rgb(72, 72, 72)/NONE selected Rgb(151, 151, 151)/Rgb(48, 48, 48)/NONE add Rgb(0, 0, 46)/Rgb(99, 168, 248)/BOLD +chooser fallback inactive Reset/Reset/UNDERLINED selected Reset/Reset/NONE add Reset/Reset/BOLD | REVERSED +chooser selected inactive Rgb(151, 151, 151)/Rgb(48, 48, 48)/NONE selected Rgb(224, 224, 224)/Rgb(72, 72, 72)/NONE add Rgb(0, 0, 46)/Rgb(99, 168, 248)/BOLD +chooser leave inactive Rgb(151, 151, 151)/Rgb(48, 48, 48)/NONE selected Rgb(151, 151, 151)/Rgb(48, 48, 48)/NONE add Rgb(0, 0, 46)/Rgb(99, 168, 248)/BOLD +chooser light rest inactive Rgb(102, 103, 117)/Rgb(228, 231, 236)/NONE selected Rgb(102, 103, 117)/Rgb(228, 231, 236)/NONE add Rgb(0, 0, 46)/Rgb(164, 205, 251)/BOLD +chooser light hover inactive Rgb(80, 80, 106)/Rgb(218, 221, 226)/NONE selected Rgb(102, 103, 117)/Rgb(228, 231, 236)/NONE add Rgb(0, 0, 46)/Rgb(164, 205, 251)/BOLD +chooser light add inactive Rgb(102, 103, 117)/Rgb(228, 231, 236)/NONE selected Rgb(102, 103, 117)/Rgb(228, 231, 236)/NONE add Rgb(0, 0, 46)/Rgb(150, 188, 230)/BOLD +chooser add inactive Rgb(151, 151, 151)/Rgb(48, 48, 48)/NONE selected Rgb(151, 151, 151)/Rgb(48, 48, 48)/NONE add Rgb(0, 0, 46)/Rgb(133, 187, 248)/BOLD +chooser add fallback inactive Reset/Reset/NONE selected Reset/Reset/NONE add Reset/Reset/BOLD | UNDERLINED | REVERSED +chooser main rest inactive Rgb(151, 151, 151)/Rgb(48, 48, 48)/NONE selected Rgb(151, 151, 151)/Rgb(48, 48, 48)/NONE add Rgb(154, 154, 154)/Rgb(31, 31, 31)/NONE +chooser main hover inactive Rgb(224, 224, 224)/Rgb(72, 72, 72)/NONE selected Rgb(151, 151, 151)/Rgb(48, 48, 48)/NONE add Rgb(154, 154, 154)/Rgb(31, 31, 31)/NONE +chooser main fallback inactive Reset/Reset/UNDERLINED selected Reset/Reset/NONE add Reset/Reset/DIM +chooser main selected inactive Rgb(151, 151, 151)/Rgb(48, 48, 48)/NONE selected Rgb(224, 224, 224)/Rgb(72, 72, 72)/NONE add Rgb(154, 154, 154)/Rgb(31, 31, 31)/NONE +chooser main leave inactive Rgb(151, 151, 151)/Rgb(48, 48, 48)/NONE selected Rgb(151, 151, 151)/Rgb(48, 48, 48)/NONE add Rgb(154, 154, 154)/Rgb(31, 31, 31)/NONE +chooser main light rest inactive Rgb(102, 103, 117)/Rgb(228, 231, 236)/NONE selected Rgb(102, 103, 117)/Rgb(228, 231, 236)/NONE add Rgb(105, 106, 121)/Rgb(234, 237, 242)/NONE +chooser main light hover inactive Rgb(80, 80, 106)/Rgb(218, 221, 226)/NONE selected Rgb(102, 103, 117)/Rgb(228, 231, 236)/NONE add Rgb(105, 106, 121)/Rgb(234, 237, 242)/NONE +chooser main light add inactive Rgb(102, 103, 117)/Rgb(228, 231, 236)/NONE selected Rgb(102, 103, 117)/Rgb(228, 231, 236)/NONE add Rgb(80, 80, 106)/Rgb(218, 221, 226)/NONE +chooser main add inactive Rgb(151, 151, 151)/Rgb(48, 48, 48)/NONE selected Rgb(151, 151, 151)/Rgb(48, 48, 48)/NONE add Rgb(224, 224, 224)/Rgb(72, 72, 72)/NONE +chooser main add fallback inactive Reset/Reset/NONE selected Reset/Reset/NONE add Reset/Reset/UNDERLINED diff --git a/codex-rs/tui/src/snapshots/codex_tui__app__tests__side_chat_tabs.snap b/codex-rs/tui/src/snapshots/codex_tui__app__tests__side_chat_tabs.snap index 9ef72b59b2..0aeaa8f1e6 100644 --- a/codex-rs/tui/src/snapshots/codex_tui__app__tests__side_chat_tabs.snap +++ b/codex-rs/tui/src/snapshots/codex_tui__app__tests__side_chat_tabs.snap @@ -2,4 +2,4 @@ source: tui/src/app/tests.rs expression: header.trim_end() --- - Investig…× Fix cache× + + Investig…× Fix cache× + 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 024de1128e..3db50a3407 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 @@ -9,7 +9,8 @@ expression: "chooser.lines().filter_map(|line|\nline.split_once('│').map(|(_, + New side chat Start from the main chat - Side chats 1 + Side chats 1 + › ○ Side chat @@ -18,5 +19,4 @@ expression: "chooser.lines().filter_map(|line|\nline.split_once('│').map(|(_, - enter open · esc back … diff --git a/codex-rs/tui/src/style.rs b/codex-rs/tui/src/style.rs index dd73a7ccf2..170ad57c36 100644 --- a/codex-rs/tui/src/style.rs +++ b/codex-rs/tui/src/style.rs @@ -220,6 +220,21 @@ pub(crate) fn selection_style() -> Style { contrast::selection_style(default_bg(), effective_stdout_color_level()) } +/// Strengthen a control's fill using the terminal's surface tint and readable foreground. +pub(crate) fn hover_style(style: Style) -> Style { + let (Some(terminal_bg), Some(surface)) = (default_bg(), background_rgb(style.bg)) else { + return style.underlined(); + }; + let fill = best_color(shade_rgb(shade_rgb(surface, terminal_bg), terminal_bg)); + if fill == Color::Reset || Some(fill) == style.bg { + return style.underlined(); + } + style.bg(fill).fg(readable_color_on( + style.fg.unwrap_or(Color::Reset), + Some(fill), + )) +} + /// Resolve emphasis on the shaded prompt surface, including its quantized background. #[allow(dead_code, reason = "Used by later layers of the TUI refresh stack.")] pub(crate) fn user_message_accent_color() -> Color { @@ -320,12 +335,16 @@ pub fn user_message_bg(terminal_bg: (u8, u8, u8)) -> Color { } pub(crate) fn user_message_bg_rgb(terminal_bg: (u8, u8, u8)) -> (u8, u8, u8) { + shade_rgb(terminal_bg, terminal_bg) +} + +fn shade_rgb(surface: (u8, u8, u8), terminal_bg: (u8, u8, u8)) -> (u8, u8, u8) { let (top, alpha) = if is_light(terminal_bg) { ((0, 0, 0), 0.04) } else { ((255, 255, 255), 0.12) }; - blend(top, terminal_bg, alpha) + blend(top, surface, alpha) } #[allow(clippy::disallowed_methods)]