diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index ebb4c680e9..266bafca57 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -927,7 +927,10 @@ impl App { self.refresh_link_hover(tui)?; self.invalidate_right_click_paste(&event); self.finish_clipboard(tui, &event); + // Clipboard reads started by the composer already have a validated target. + let composer_paste = matches!(event, TuiEvent::Draw); let event = self.finish_right_click_paste(tui, event); + let composer_paste = composer_paste && matches!(&event, TuiEvent::Paste(_)); if self.startup_protected_input_boundary && self.startup_pending_protected_request && self.chat_widget.has_active_modal() @@ -983,6 +986,18 @@ impl App { .borrow_mut() .pause_clock(); } + if self.reconnect.offline + && self.conversation_focus_available(tui) + && let TuiEvent::Key(key) = &event + && crate::text_selection::is_copy_key(*key) + && self.focused_document().is_some_and(|doc| { + doc.backend == app_server.backend_id() && doc.owns_interaction_key(*key) + }) + { + self.cancel_pending_key_chord(); + Box::pin(self.handle_document_input(tui, app_server, &event)).await; + return Ok(AppRunControl::Continue); + } let transcript_owns_input = match (&event, &self.overlay) { (TuiEvent::Key(key), Some(Overlay::Transcript(overlay))) => { overlay.owns_interaction_key(*key) @@ -1089,7 +1104,7 @@ impl App { { return Ok(AppRunControl::Continue); } - if Box::pin(self.handle_sidebar_input(tui, app_server, &event)).await { + if !composer_paste && Box::pin(self.handle_sidebar_input(tui, app_server, &event)).await { return Ok(AppRunControl::Continue); } if let TuiEvent::Mouse(press) = &event @@ -1158,6 +1173,7 @@ impl App { if voice_toggle(self, *key) && (!self.transcript_view.owns_interaction_key(*key) || self.transcript_view.is_select_mode())) + && !composer_paste && self.handle_owned_transcript_event(tui, app_server, &event)? { return Ok(AppRunControl::Continue); @@ -1401,6 +1417,7 @@ impl App { } // Both transcript owners must consume completions before automatic work advances. if idle_draw { + self.cancel_hidden_sidebar_primary(tui); tui.clipboard.advance(tui.frame_requester()); } Ok(AppRunControl::Continue) diff --git a/codex-rs/tui/src/app/clipboard.rs b/codex-rs/tui/src/app/clipboard.rs index ef1ceadfa4..f453d2f359 100644 --- a/codex-rs/tui/src/app/clipboard.rs +++ b/codex-rs/tui/src/app/clipboard.rs @@ -83,6 +83,11 @@ impl App { companion.view.jump_to_latest(); } } + let parent = self.sidebar_parent(); + let panel_visible = current && self.conversation_frame.panel_area().is_some(); + for (owner, pane) in &mut self.sidebars { + pane.finish_document_copy(completion, panel_visible && parent == *owner); + } let follow = self.transcript_view .finish_copy(&self.transcript_cells, completion, current); @@ -105,6 +110,9 @@ impl App { for companion in self.side_companions.values_mut() { companion.view.cancel_primary(); } + for pane in self.sidebars.values_mut() { + pane.cancel_hidden_document_primary(/*visible*/ false); + } self.chat_widget.cancel_composer_primary(); self.chat_widget .rendered_selection diff --git a/codex-rs/tui/src/app/cloud_switch_wait.rs b/codex-rs/tui/src/app/cloud_switch_wait.rs index 5365da8ce5..5802d6d618 100644 --- a/codex-rs/tui/src/app/cloud_switch_wait.rs +++ b/codex-rs/tui/src/app/cloud_switch_wait.rs @@ -48,12 +48,18 @@ fn handle_cloud_switch_event( }; // Clipboard text is delivered on Draw after ordinary input invalidation and target checks. app.invalidate_right_click_paste(&event); + if matches!(event, tui::TuiEvent::FocusLost | tui::TuiEvent::Resume) { + for pane in app.sidebars.values_mut() { + pane.cancel_hidden_document_primary(/*visible*/ false); + } + } // Polling retains copy feedback for the ordinary event loop. tui.clipboard.poll(); let event = app.finish_right_click_paste(tui, event); if app.pending_right_click_paste.is_some() { if matches!(event, tui::TuiEvent::Draw) { // A PRIMARY read may be waiting for an earlier copy or publication. + app.cancel_hidden_sidebar_primary(tui); tui.clipboard.advance(tui.frame_requester()); } else if matches!(event, tui::TuiEvent::Resize(_)) { // A size change can consume the worker's completion frame. diff --git a/codex-rs/tui/src/app/input.rs b/codex-rs/tui/src/app/input.rs index 1873be4047..8a0b91d524 100644 --- a/codex-rs/tui/src/app/input.rs +++ b/codex-rs/tui/src/app/input.rs @@ -107,10 +107,21 @@ impl App { && self.overlay.is_none() && !self.focused_sidebar_chooser(tui) && self.chat_widget.no_modal_or_popup_active() - && self.transcript_view.owns_interaction_key(key_event) - && (self.transcript_view.has_active_interaction() - || self.backtrack.overlay_preview_active - || crate::transcript_view::JumpTarget::from_key(key_event).is_none()))) + && self.focused_document().map_or_else( + || { + self.transcript_view.owns_interaction_key(key_event) + && (self.transcript_view.has_active_interaction() + || self.backtrack.overlay_preview_active + || crate::transcript_view::JumpTarget::from_key(key_event) + .is_none()) + }, + |document| { + document.owns_interaction_key(key_event) + && (!document.allows_tab_shortcut(key_event) + || crate::transcript_view::JumpTarget::from_key(key_event) + .is_none()) + }, + ))) && !select_mode_chord { let close = tui.is_owned_screen() @@ -287,15 +298,15 @@ impl App { }; return contexts.with_voice_toggle(&self.keymap); } - if self.panel_focus() == Some(super::sidebar::PaneFocus::Sidebar) - && self.chat_widget.no_modal_or_popup_active() - && matches!( - self.sidebar() - .and_then(sidebar::SidebarPane::visible_content), - Some(sidebar::SidebarContent::Document(_)) - ) + if self.chat_widget.no_modal_or_popup_active() + && let Some(doc) = self.focused_document() { - return KeymapContextSet::new(KeymapContext::Pager).with_voice_toggle(&self.keymap); + return if doc.is_search_editing() { + KeymapContextSet::new(KeymapContext::Editor) + } else { + KeymapContextSet::transcript() + } + .with_voice_toggle(&self.keymap); } if self.transcript_view.is_search_editing() && self.chat_widget.no_modal_or_popup_active() { return KeymapContextSet::new(KeymapContext::Editor).with_voice_toggle(&self.keymap); diff --git a/codex-rs/tui/src/app/input/select_mode.rs b/codex-rs/tui/src/app/input/select_mode.rs index 7ace4c0b77..4b6836b12d 100644 --- a/codex-rs/tui/src/app/input/select_mode.rs +++ b/codex-rs/tui/src/app/input/select_mode.rs @@ -20,7 +20,10 @@ impl App { Some(Overlay::Transcript(overlay)) if overlay.is_select_mode() ) || (tui.is_owned_screen() && self.overlay.is_none() - && self.transcript_view.is_select_mode()); + && (self.focused_document().map_or_else( + || self.transcript_view.is_select_mode(), + super::super::sidebar_document::Document::is_select_mode, + ))); if !select_mode { return false; } @@ -29,7 +32,10 @@ impl App { &self.overlay, Some(Overlay::Transcript(overlay)) if overlay.is_search_editing() ) || (self.overlay.is_none() - && self.transcript_view.is_search_editing()); + && self.focused_document().map_or_else( + || self.transcript_view.is_search_editing(), + super::super::sidebar_document::Document::is_search_editing, + )); let (code, modifiers) = crate::key_hint::normalize_key_parts(key_event.code, key_event.modifiers); let fixed_search_control = search_editing diff --git a/codex-rs/tui/src/app/link_hover.rs b/codex-rs/tui/src/app/link_hover.rs index 7e8e776c10..c2a24193c7 100644 --- a/codex-rs/tui/src/app/link_hover.rs +++ b/codex-rs/tui/src/app/link_hover.rs @@ -26,6 +26,12 @@ impl App { { return None; } + if let Some(area) = self.conversation_frame.panel_area() + && area.contains((mouse.column, mouse.row).into()) + && let Some(pane) = self.sidebar() + { + return pane.visible_link_at(mouse.column, mouse.row); + } let view = if let Some(panes) = self.conversation_frame.side_pane() && panes.passive.contains((mouse.column, mouse.row).into()) { diff --git a/codex-rs/tui/src/app/owned_transcript.rs b/codex-rs/tui/src/app/owned_transcript.rs index 3841d3d882..42863f634f 100644 --- a/codex-rs/tui/src/app/owned_transcript.rs +++ b/codex-rs/tui/src/app/owned_transcript.rs @@ -366,7 +366,17 @@ impl App { .and_then(|pane| pane.active_document()) { let [_, body] = side_pane::tab_and_body(*sidebar); - doc.paint(body, frame.buffer, sidebar_motion, &frames, resize_hint); + if let Some(cursor) = doc.paint( + body, + frame.buffer, + sidebar_motion, + &frames, + &self.keymap, + resize_hint, + ) && focused + { + frame.cursor_position = Some(cursor); + } } else if let Some(creation) = self.sidebar().and_then(|pane| pane.creation.as_ref()) { @@ -481,7 +491,7 @@ impl App { pointer .and_then(|point| pane.chat_tabs().strip().hit(*sidebar, point)) .map(|(target, _)| target), - |id| pane.document_title(id), + |id, width| pane.document_title(id, width), frame.buffer, ); } @@ -505,7 +515,7 @@ impl App { pointer .and_then(|point| pane.chat_tabs().strip().hit(strip, point)) .map(|(target, _)| target), - |id| pane.document_title(id), + |id, width| pane.document_title(id, width), frame.buffer, ); } diff --git a/codex-rs/tui/src/app/side.rs b/codex-rs/tui/src/app/side.rs index de438142c0..2b9a9deaaf 100644 --- a/codex-rs/tui/src/app/side.rs +++ b/codex-rs/tui/src/app/side.rs @@ -315,6 +315,14 @@ impl App { /// Zoom follows the displayed conversation even when its peer cannot be selected offline. pub(super) fn open_pane_focus(&self) -> Option { let focused = self.current_displayed_thread_id()?; + if self.panel_focus() == Some(sidebar::PaneFocus::Sidebar) + && matches!( + self.sidebar()?.visible_content(), + Some(sidebar::SidebarContent::Document(_)) + ) + { + return Some(focused); + } let child = self.side_pair_key(focused)?; (self.sidebar()?.visible_content() == Some(sidebar::SidebarContent::Chat(child))) .then_some(focused) diff --git a/codex-rs/tui/src/app/side_focus.rs b/codex-rs/tui/src/app/side_focus.rs index ac461dfe7b..fe1f26542a 100644 --- a/codex-rs/tui/src/app/side_focus.rs +++ b/codex-rs/tui/src/app/side_focus.rs @@ -251,7 +251,7 @@ impl App { .and_then(sidebar::SidebarPane::visible_content), Some(SidebarContent::Document(_)) ) { - return self.handle_document_input(tui, event); + return self.handle_document_input(tui, server, event).await; } if self.chooser_focus().is_none() { return false; @@ -499,9 +499,14 @@ impl App { } else { None }; + let document_shortcut = document.is_some_and(|id| { + self.sidebar() + .and_then(|pane| pane.documents.get(&id)) + .is_some_and(|doc| doc.allows_tab_shortcut(key)) + }); let close = if let Some(id) = document { (bindings.close_sidebar_tab.is_pressed(key) - || crate::key_hint::plain(KeyCode::Esc).is_press(key)) + || (document_shortcut && crate::key_hint::plain(KeyCode::Esc).is_press(key))) .then_some(SidebarTab::Document(id)) } else { self.current_displayed_thread_id() @@ -512,11 +517,11 @@ impl App { }; let left = bindings.focus_pane_left.is_pressed(key); let tab_step = if bindings.sidebar_up.is_pressed(key) - || (document.is_some() && crate::key_hint::plain(KeyCode::Left).is_press(key)) + || (document_shortcut && crate::key_hint::plain(KeyCode::Left).is_press(key)) { Some(-1) } else if bindings.sidebar_down.is_pressed(key) - || (document.is_some() && crate::key_hint::plain(KeyCode::Right).is_press(key)) + || (document_shortcut && crate::key_hint::plain(KeyCode::Right).is_press(key)) { Some(1) } else { @@ -623,6 +628,15 @@ impl App { } else { PaneFocus::Sidebar }; + if focus == PaneFocus::Main + && matches!( + self.sidebar() + .and_then(sidebar::SidebarPane::visible_content), + Some(SidebarContent::Document(_)) + ) + { + self.zoomed_thread = None; + } let pane = self.sidebar_mut(); if let Some(content) = pane.visible_content() { pane.show(content, focus); diff --git a/codex-rs/tui/src/app/sidebar.rs b/codex-rs/tui/src/app/sidebar.rs index e92c8505d0..8d7ae84866 100644 --- a/codex-rs/tui/src/app/sidebar.rs +++ b/codex-rs/tui/src/app/sidebar.rs @@ -100,7 +100,49 @@ pub(super) struct SidebarPane { } impl SidebarPane { + pub(super) fn visible_link_at(&self, column: u16, row: u16) -> Option { + let SidebarContent::Document(id) = self.visible_content()? else { + return None; + }; + self.documents.get(&id)?.link_at(column, row) + } + + pub(super) fn finish_document_copy( + &mut self, + completion: &(u64, crate::clipboard_copy::worker::CopyResult), + visible: bool, + ) { + let selected = self.visible_content(); + let visible = visible && self.close.is_none(); + for (&id, doc) in &mut self.documents { + if let Some((view, cells)) = doc.reader() + && view.finish_copy( + cells, + completion, + visible && selected == Some(SidebarContent::Document(id)), + ) == Some(true) + { + view.jump_to_latest(); + } + } + } + + pub(super) fn cancel_hidden_document_primary(&mut self, visible: bool) { + let selected = self.visible_content(); + let visible = visible && self.close.is_none(); + for (&id, doc) in &mut self.documents { + if (!visible || selected != Some(SidebarContent::Document(id))) + && let Some((view, _)) = doc.reader() + { + view.cancel_primary(); + } + } + } + pub(super) fn show(&mut self, content: SidebarContent, focus: PaneFocus) { + if self.content != content { + self.cancel_hidden_document_primary(/*visible*/ false); + } self.focus_document_request = None; match content { SidebarContent::Chat(id) => { @@ -221,12 +263,53 @@ impl SidebarPane { self.documents.get_mut(&id) } - pub(super) fn document_title(&self, id: uuid::Uuid) -> String { + pub(super) fn document_title(&self, id: uuid::Uuid, width: usize) -> String { let Some(document) = self.documents.get(&id) else { return String::new(); }; let path = document.path.inferred_native_path_string(); - path.rsplit(['/', '\\']).next().unwrap_or(&path).to_owned() + let parts: Vec<_> = path.rsplit(['/', '\\']).collect(); + let depth = self + .documents + .values() + .filter(|other| other.path != document.path) + .map(|other| { + parts + .iter() + .copied() + .zip(other.path.inferred_native_path_string().rsplit(['/', '\\'])) + .take_while(|(left, right)| left == right) + .count() + + 1 + }) + .max() + .unwrap_or(1) + .min(parts.len()); + let label = crate::line_truncation::document_label(&parts[..depth], width); + let mut index = 1; + let mut collision = false; + for (&other_id, other) in &self.documents { + if other_id == id { + continue; + } + let other_path = other.path.inferred_native_path_string(); + let other_parts: Vec<_> = other_path.rsplit(['/', '\\']).take(depth).collect(); + if crate::line_truncation::document_label(&other_parts, width) == label { + collision = true; + index += usize::from(other_path < path); + } + } + if !collision { + return label; + } + let prefix = format!("{index}:"); + if prefix.len() > width { + return label; + } + format!( + "{prefix}{}", + crate::line_truncation::document_label(&parts[..depth], width - prefix.len()) + ) } pub(super) fn add_document_tab(&mut self, id: uuid::Uuid) { @@ -286,6 +369,7 @@ impl SidebarPane { } pub(super) fn hide(&mut self) { + self.cancel_hidden_document_primary(/*visible*/ false); self.focus_document_request = None; self.opening = None; self.focus = None; @@ -511,8 +595,15 @@ impl SidebarLayout { pub(super) fn paint_layout(app: &mut App, tui: &Tui, area: Rect) -> Option { let zoomed = app.zoomed_thread.is_some() && app.zoomed_thread == app.current_displayed_thread_id(); - let allowed = - !zoomed && app.side_retention_enabled(tui) && !app.conversation_frame.has_caller_inset(); + let zoomed_document = zoomed + && app.panel_focus() == Some(PaneFocus::Sidebar) + && matches!( + app.sidebar().and_then(SidebarPane::visible_content), + Some(SidebarContent::Document(_)) + ); + let allowed = (!zoomed || zoomed_document) + && app.side_retention_enabled(tui) + && !app.conversation_frame.has_caller_inset(); let animate = allowed && area.width >= 100 && app.local_settings.tui.animations @@ -529,7 +620,7 @@ pub(super) fn paint_layout(app: &mut App, tui: &Tui, area: Rect) -> Option "Close", Action::Archive => "Archive", }; - app.sidebar_mut().close = Some(Confirmation { + let pane = app.sidebar_mut(); + pane.cancel_hidden_document_primary(/*visible*/ false); + pane.close = Some(Confirmation { target, action, message: format!( diff --git a/codex-rs/tui/src/app/sidebar_document.rs b/codex-rs/tui/src/app/sidebar_document.rs index 4827e600dc..ca8be176dc 100644 --- a/codex-rs/tui/src/app/sidebar_document.rs +++ b/codex-rs/tui/src/app/sidebar_document.rs @@ -3,12 +3,17 @@ use super::sidebar::PaneFocus; use super::sidebar::SidebarContent; use super::*; +use crate::key_hint::KeyBinding; +use crate::keymap::KeymapContext; +use crate::keymap::RuntimeKeymap; use crate::motion::MotionMode; use crate::sidebar_tab_strip::SidebarTab; use crate::terminal_hyperlinks::HyperlinkLine; use crate::terminal_hyperlinks::visible_lines; use crate::transcript_view::TranscriptView; +use crate::transcript_view::ViewAction; use codex_app_server_client::AppServerPath; +use codex_utils_path_uri::LegacyAppPathString; use codex_utils_path_uri::PathUri; use ratatui::buffer::Buffer; use ratatui::layout::Position; @@ -20,8 +25,8 @@ struct FileCell { } impl HistoryCell for FileCell { - fn raw_lines(&self) -> Vec> { - crate::history_cell::raw_lines_from_source(&self.source) + fn copy_source(&self) -> Option<&str> { + Some(&self.source) } fn display_lines(&self, width: u16) -> Vec> { @@ -37,14 +42,20 @@ impl HistoryCell for FileCell { &self.source, Some(width.into()), /*cwd*/ None, - &crate::markdown_render::hide_web_link_destination, + &crate::markdown_render::hide_reader_link_destination, ) } + + fn raw_lines(&self) -> Vec> { + crate::history_cell::raw_lines_from_source(&self.source) + } } pub(super) struct Document { + source: ThreadId, pub(super) path: PathUri, pub(super) backend: crate::backend_id::BackendId, + link: Option, state: State, } @@ -58,6 +69,42 @@ enum State { } impl Document { + pub(super) fn link_at(&self, column: u16, row: u16) -> Option { + match &self.state { + State::Ready { view, .. } if !view.is_select_mode() => view.link_at(column, row), + _ => None, + } + } + + pub(super) fn owns_interaction_key(&self, key: KeyEvent) -> bool { + matches!(&self.state, State::Ready { view, .. } + if view.has_active_interaction() && view.owns_interaction_key(key)) + } + + pub(super) fn allows_tab_shortcut(&self, key: KeyEvent) -> bool { + match &self.state { + State::Ready { view, .. } => { + !view.has_active_interaction() && (key.code != KeyCode::Esc || self.link.is_none()) + } + _ => true, + } + } + + pub(super) fn is_select_mode(&self) -> bool { + matches!(&self.state, State::Ready { view, .. } if view.is_select_mode()) + } + + pub(super) fn is_search_editing(&self) -> bool { + matches!(&self.state, State::Ready { view, .. } if view.is_search_editing()) + } + + pub(super) fn reader(&mut self) -> Option<(&mut TranscriptView, &[Arc])> { + match &mut self.state { + State::Ready { view, cells, .. } => Some((view, cells)), + _ => None, + } + } + pub(super) fn connection_replaced(&mut self) { if matches!(self.state, State::Loading(_)) { self.state = State::Failed("Connection changed. Reopen this file to try again.".into()); @@ -69,6 +116,8 @@ impl Document { Ok(source) => { let cells: [Arc; 1] = [Arc::new(FileCell { source })]; let mut view = Box::::default(); + view.document_links = true; + view.show_follow_control = false; view.jump_to_beginning(&cells); State::Ready { view, cells } } @@ -82,23 +131,11 @@ impl Document { buf: &mut Buffer, motion: MotionMode, frames: &tui::FrameRequester, + keymap: &RuntimeKeymap, resize_hint: Option<&str>, - ) { + ) -> Option { ratatui::widgets::Clear.render(area, buf); - let mut body = area.inner(ratatui::layout::Margin::new(1, 0)); - if let Some(hint) = resize_hint - && body.height > 1 - { - body.height -= 1; - crate::sidebar_chooser::resize_hint(hint, body.width).render( - Rect { - y: body.bottom(), - height: 1, - ..body - }, - buf, - ); - } + let body = area.inner(ratatui::layout::Margin::new(1, 0)); match &mut self.state { State::Loading(started) => { let glyph = crate::motion::loading_glyph(*started, motion, frames); @@ -114,12 +151,114 @@ impl Document { .wrap(ratatui::widgets::Wrap { trim: false }) .render(body, buf); } - State::Ready { view, cells } => view.render(body, buf, cells), + State::Ready { view, cells } => { + view.set_keymap_bindings(keymap); + if view.tick_selection(cells) { + frames.schedule_frame_in(std::time::Duration::from_millis(45)); + } + if view.advance_search(cells) { + frames.schedule_frame(); + } + let footer = view.footer_with_navigation(body.width, motion, "Esc close"); + let hints = crate::footer_hint::HintLine::new( + [ + Some(crate::footer_hint::shortcut("↑/↓", "read")), + Some(crate::footer_hint::shortcut( + &keymap + .pager + .find + .first() + .map_or_else(|| "F3".to_owned(), KeyBinding::display_label), + "find", + )), + Some(crate::footer_hint::shortcut("Tab", "link")), + keymap + .primary_hint(KeymapContext::Global, "select_transcript") + .map(|hint| { + crate::footer_hint::shortcut(&hint.display_label(), "select") + }), + Some(crate::footer_hint::shortcut("Esc", "close")), + ] + .into_iter() + .flatten(), + body.width, + ); + let text: ratatui::text::Text<'_> = if let Some(hint) = resize_hint { + crate::sidebar_chooser::resize_hint(hint, body.width).into() + } else if let Some(footer) = &footer + && view.has_active_interaction() + { + footer.text.clone() + } else { + hints.line.into() + }; + let now = Instant::now(); + let height = (text.height() as u16).min(body.height.saturating_sub(1)); + let gap_height = u16::from(height > 0 && body.height - height > 1); + let content = Rect { + height: body.height - height - gap_height, + ..body + }; + let mut viewport = content; + if content.width > 2 { + viewport.width -= 1; + } + view.render(viewport, buf, cells); + if let Some(index) = self.link { + view.paint_document_link(cells, index, buf); + } + let gap = + (gap_height > 0).then(|| Rect::new(body.x, content.bottom(), body.width, 1)); + view.paint_document_scroll_indicators(content, buf, cells); + if let Some(delay) = view.render_composer_gap(gap, /*hint*/ None, buf, now) { + frames.schedule_frame_in(delay); + } + if height > 0 { + let footer_area = + Rect::new(body.x, content.bottom() + gap_height, body.width, height); + Paragraph::new(text).render(footer_area, buf); + if resize_hint.is_none() + && let Some(column) = footer.and_then(|footer| footer.cursor_column) + { + return Some(Position::new(body.x + column, footer_area.y)); + } + } + } } + if !matches!(self.state, State::Ready { .. }) + && body.height > 0 + && let Some(hint) = resize_hint + { + crate::sidebar_chooser::resize_hint(hint, body.width) + .render(Rect::new(body.x, body.bottom() - 1, body.width, 1), buf); + } + None } } impl App { + pub(super) fn cancel_hidden_sidebar_primary(&mut self, tui: &tui::Tui) { + let parent = self.sidebar_parent(); + let visible = tui.is_owned_screen() + && tui.is_terminal_focused() + && self.overlay.is_none() + && self.conversation_frame.panel_area().is_some(); + for (owner, pane) in &mut self.sidebars { + pane.cancel_hidden_document_primary(visible && *owner == parent); + } + } + + pub(super) fn focused_document(&self) -> Option<&Document> { + if self.panel_focus() != Some(PaneFocus::Sidebar) { + return None; + } + let pane = self.sidebar()?; + let SidebarContent::Document(id) = pane.visible_content()? else { + return None; + }; + pane.documents.get(&id) + } + pub(super) fn document_preview_available( &self, tui: &tui::Tui, @@ -199,8 +338,10 @@ impl App { pane.documents.insert( request, Document { + source, path: path.clone(), backend: backend_id, + link: None, state: State::Loading(Instant::now()), }, ); @@ -228,7 +369,12 @@ impl App { Ok(()) } - pub(super) fn handle_document_input(&mut self, tui: &mut tui::Tui, event: &TuiEvent) -> bool { + pub(super) async fn handle_document_input( + &mut self, + tui: &mut tui::Tui, + server: &mut AppServerSession, + event: &TuiEvent, + ) -> bool { let focused = self.panel_focus() == Some(PaneFocus::Sidebar); let area = self.conversation_frame.panel_area(); let Some(pane) = self.sidebars.get_mut(&self.sidebar_parent()) else { @@ -237,18 +383,95 @@ impl App { let Some(SidebarContent::Document(id)) = pane.visible_content() else { return false; }; - match event { + if let TuiEvent::Mouse(mouse) = event + && mouse.kind == MouseEventKind::Moved + { + if let Some(Document { + state: State::Ready { view, cells }, + .. + }) = pane.documents.get_mut(&id) + && view.handle_mouse(*mouse, cells).is_some() + { + tui.frame_requester().schedule_frame(); + } + return false; + } + let action = match event { TuiEvent::Key(key) if focused => { - if key.kind != KeyEventKind::Release - && let Some(Document { - state: State::Ready { view, cells }, - .. - }) = pane.documents.get_mut(&id) - { - view.navigate_pager(*key, cells, &self.keymap.pager); + if key.kind == KeyEventKind::Release { + return true; + } + let Some(doc) = pane.documents.get_mut(&id) else { + return true; + }; + if doc.backend != server.backend_id() { + return true; + } + let escape = crate::key_hint::plain(KeyCode::Esc).is_press(*key); + if key.kind != KeyEventKind::Press && (escape || key.code == KeyCode::Enter) { + return true; + } + if let State::Ready { view, cells } = &mut doc.state { + if escape && view.has_active_interaction() && !view.is_select_mode() { + view.cancel_search(); + view.end_selection(cells); + None + } else if escape && doc.link.take().is_some() { + None + } else if !view.is_search_editing() + && (self.keymap.app.find_transcript.is_pressed(*key) + || self.keymap.pager.find.is_pressed(*key)) + { + view.begin_search(); + doc.link = None; + None + } else if !view.is_select_mode() + && self.keymap.app.select_transcript.is_pressed(*key) + { + view.begin_select_mode(cells); + doc.link = None; + None + } else if !view.has_active_interaction() + && view.navigate_pager(*key, cells, &self.keymap.pager) + { + doc.link = None; + Some(ViewAction::Changed) + } else if !view.has_active_interaction() + && let (code @ (KeyCode::Tab | KeyCode::BackTab), KeyModifiers::NONE) = + crate::key_hint::normalize_key_parts(key.code, key.modifiers) + { + let forward = code == KeyCode::Tab; + doc.link = view.cycle_document_link(cells, doc.link, forward); + None + } else if crate::key_hint::plain(KeyCode::Enter).is_press(*key) + && let Some(index) = doc.link.take() + { + view.document_link(cells, index).map(ViewAction::OpenLink) + } else { + doc.link = None; + if view.has_active_interaction() { + view.handle_key(*key, cells).or_else(|| { + view.navigate_pager(*key, cells, &self.keymap.pager) + .then_some(ViewAction::Changed) + }) + } else { + None + } + } + } else { + None } } - TuiEvent::Paste(_) if focused => {} + TuiEvent::Paste(text) if focused => { + if let Some(Document { + state: State::Ready { view, .. }, + .. + }) = pane.documents.get_mut(&id) + { + view.paste_search(text); + } + None + } TuiEvent::Mouse(mouse) if mouse.kind != MouseEventKind::Moved => { let inside = area.is_some_and(|area| area.contains(Position::new(mouse.column, mouse.row))); @@ -262,23 +485,77 @@ impl App { }, ); } - if !inside { + let selection_motion = matches!( + mouse.kind, + MouseEventKind::Drag(MouseButton::Left) | MouseEventKind::Up(MouseButton::Left) + ); + if (selection_motion && !focused) || (!selection_motion && !inside) { return false; } if let Some(Document { state: State::Ready { view, cells }, + link, .. }) = pane.documents.get_mut(&id) - && matches!( - mouse.kind, - MouseEventKind::ScrollUp | MouseEventKind::ScrollDown - ) { + *link = None; view.mouse_scroll_speed = self.transcript_view.mouse_scroll_speed; - let _ = view.handle_mouse(*mouse, cells); + view.copy_on_select = self.transcript_view.copy_on_select; + view.copy_on_select_clear_selection = + self.transcript_view.copy_on_select_clear_selection; + view.primary_selection = self.transcript_view.primary_selection; + view.handle_mouse(*mouse, cells) + } else { + None } } _ => return false, + }; + match action { + Some(ViewAction::OpenLink(url)) => { + if let Some(url) = crate::terminal_hyperlinks::web_destination(&url) { + self.open_url_in_browser(url); + } else if let Some(doc) = pane.documents.get(&id) + && let Some(parent) = doc.path.parent() + { + let result = match LegacyAppPathString::from_string(url) + .resolve_against(&parent, /*user_home_dir*/ None) + { + Ok(path) if !path.to_url().has_host() => { + let original_path = + AppServerPath::from_app_server(path.inferred_native_path_string()); + let source = doc.source; + self.open_resolved_document( + tui, + server, + source, + original_path, + path, + /*focus*/ true, + ) + .await + } + Ok(_) => Ok(()), + Err(error) => Err(error.into()), + }; + if let Err(error) = result { + self.chat_widget.add_error_message(error.to_string()); + } + } + } + Some(action) => { + if let Some((view, cells)) = pane.documents.get_mut(&id).and_then(Document::reader) + && let Some((count, result)) = view.copy_action( + tui, + cells, + &action, + crate::clipboard_copy::CopyFormat::Markdown, + ) + { + view.show_copy_feedback(&result, count); + } + } + None => {} } tui.frame_requester().schedule_frame(); true diff --git a/codex-rs/tui/src/app/sidebar_document_tests.rs b/codex-rs/tui/src/app/sidebar_document_tests.rs index 435d5dbecf..f9ce7a80b2 100644 --- a/codex-rs/tui/src/app/sidebar_document_tests.rs +++ b/codex-rs/tui/src/app/sidebar_document_tests.rs @@ -12,10 +12,25 @@ use codex_config::types::KeybindingsSpec; use crossterm::event::MouseEvent; use pretty_assertions::assert_eq; use ratatui::layout::Size; +use ratatui::style::Modifier; use unicode_width::UnicodeWidthStr; -#[tokio::test] -async fn focused_markdown_link_opens_read_only_preview_only_with_workspace() -> Result<()> { +#[test] +fn focused_markdown_link_opens_read_only_preview_only_with_workspace() -> Result<()> { + // The reader and embedded app server load full configurations on this thread. + std::thread::Builder::new() + .stack_size(16 * 1024 * 1024) + .spawn(|| { + tokio::runtime::Builder::new_current_thread() + .enable_all() + .build()? + .block_on(Box::pin(document_preview_scenario())) + })? + .join() + .expect("document preview test thread panicked") +} + +async fn document_preview_scenario() -> Result<()> { let (mut app, mut events, _ops) = make_test_app_with_channels().await; app.local_settings.transcript_mode = crate::transcript_mode::TranscriptMode::Owned; app.config.features.disable(Feature::TuiWorkspace)?; @@ -67,6 +82,8 @@ async fn focused_markdown_link_opens_read_only_preview_only_with_workspace() -> app.local_settings.tui.keymap.pager.jump_bottom = Some(KeybindingsSpec::One(KeybindingSpec("ctrl-x end".into()))); + app.local_settings.tui.keymap.global.select_transcript = + Some(KeybindingsSpec::One(KeybindingSpec("ctrl-x [".into()))); enable_side_retention(&mut app)?; let enabled = side_frame(&mut app, &mut tui, size)?; assert_eq!( @@ -150,6 +167,143 @@ async fn focused_markdown_link_opens_read_only_preview_only_with_workspace() -> # Guide First section. "); + let sidebar = app.conversation_frame.panel_area().expect("document panel"); + assert!(!screen.contains("Back to bottom"), "{screen}"); + let gap = visible_sidebar_row(&tui, sidebar, sidebar.bottom() - 2); + let hints = visible_sidebar_row(&tui, sidebar, sidebar.bottom() - 1); + insta::assert_snapshot!(format!("{gap:?}\n{hints}"), @r#" + "" + ↑/↓ read · f3 find · Tab link · ⌃x [ select · Esc close + "#); + let original_scroll = app.keymap.pager.scroll_down.clone(); + for key in [ + KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE), + KeyEvent::new(KeyCode::Home, KeyModifiers::CONTROL), + ] { + app.keymap.pager.scroll_down = vec![KeyBinding::from_event(key)]; + Box::pin(app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(key))).await?; + let scrolled = side_frame(&mut app, &mut tui, size)?; + assert!(!scrolled.contains("# Guide"), "{scrolled}"); + assert!(!scrolled.contains("Back to bottom"), "{scrolled}"); + Box::pin(app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(KeyCode::Home.into()))) + .await?; + side_frame(&mut app, &mut tui, size)?; + } + app.keymap.pager.scroll_down = original_scroll; + Box::pin(app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(KeyCode::Down.into()))) + .await?; + let before_jump = side_frame(&mut app, &mut tui, size)?; + let jump_top = std::mem::take(&mut app.keymap.pager.jump_top); + let jump_bottom = std::mem::take(&mut app.keymap.pager.jump_bottom); + for key in [ + KeyEvent::new(KeyCode::Home, KeyModifiers::CONTROL), + KeyEvent::new(KeyCode::End, KeyModifiers::CONTROL), + ] { + Box::pin(app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(key))).await?; + assert_eq!(side_frame(&mut app, &mut tui, size)?, before_jump); + } + app.keymap.pager.jump_top = jump_top; + app.keymap.pager.jump_bottom = jump_bottom; + for key in [ + KeyCode::F(3), + KeyCode::Char('e'), + KeyCode::Char('g'), + KeyCode::Char('g'), + ] { + Box::pin(app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(key.into()))).await?; + } + let find = side_frame(&mut app, &mut tui, size)?; + let footer = find + .lines() + .find_map(|line| line.find("Find: ").map(|start| line[start..].trim_end())) + .expect("document Find editor"); + insta::assert_snapshot!(footer, @"Find: egg"); + Box::pin(app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(KeyCode::Esc.into()))) + .await?; + let select = crossterm::event::KeyEvent::new(KeyCode::F(8), KeyModifiers::NONE); + app.local_settings.tui.keymap.global.select_transcript = + Some(KeybindingsSpec::One(KeybindingSpec("f8".into()))); + enable_side_retention(&mut app)?; + Box::pin(app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(select))).await?; + side_frame(&mut app, &mut tui, size)?; + let sidebar = app.conversation_frame.panel_area().expect("document panel"); + let footer = visible_sidebar_row(&tui, sidebar, sidebar.bottom() - 1); + insta::assert_snapshot!(footer, @"v mark · enter/q close"); + for key in [KeyCode::Char('v'), KeyCode::Right] { + Box::pin(app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(key.into()))).await?; + } + app.reconnect.offline = true; + let copy = crossterm::event::KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL); + assert!(matches!( + Box::pin(app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(copy))).await?, + AppRunControl::Continue + )); + assert!(tui.clipboard.is_busy()); + let pane = app.sidebar_mut(); + let document = match pane.visible_content().unwrap() { + sidebar::SidebarContent::Document(id) => id, + _ => unreachable!(), + }; + pane.documents + .get_mut(&document) + .unwrap() + .reader() + .unwrap() + .0 + .publish_primary(&mut tui, "visible preview"); + pane.show( + sidebar::SidebarContent::Document(document), + sidebar::PaneFocus::Main, + ); + tokio::time::timeout(std::time::Duration::from_secs(5), async { + loop { + if tui.clipboard.poll().is_some() { + break; + } + tokio::task::yield_now().await; + } + }) + .await + .expect("active copy completes"); + tui.clipboard.advance(tui.frame_requester()); + assert!(tui.clipboard.is_busy(), "visible preview publishes PRIMARY"); + let pane = app.sidebar_mut(); + pane.documents + .get_mut(&document) + .unwrap() + .reader() + .unwrap() + .0 + .publish_primary(&mut tui, "hidden preview"); + pane.show( + sidebar::SidebarContent::Chooser, + sidebar::PaneFocus::Sidebar, + ); + tokio::time::timeout(std::time::Duration::from_secs(5), async { + while tui.clipboard.is_busy() { + tui.clipboard.poll(); + tokio::task::yield_now().await; + } + }) + .await + .expect("PRIMARY publication completes"); + tui.clipboard.advance(tui.frame_requester()); + assert!( + !tui.clipboard.is_busy(), + "hidden preview must not publish PRIMARY" + ); + app.sidebar_mut().show( + sidebar::SidebarContent::Document(document), + sidebar::PaneFocus::Sidebar, + ); + app.reconnect.offline = false; + Box::pin(app.handle_tui_event( + &mut tui, + &mut server, + TuiEvent::Key(KeyCode::Char('q').into()), + )) + .await?; + assert!(app.transcript_view.begin_select_mode(&app.transcript_cells)); for key in [ KeyEvent::new(KeyCode::Char('x'), KeyModifiers::CONTROL), KeyCode::End.into(), @@ -160,14 +314,34 @@ async fn focused_markdown_link_opens_read_only_preview_only_with_workspace() -> assert!(end.contains("Last section."), "{end}"); std::fs::write(dir.path().join("notes.md"), "# Notes")?; - app.open_document( - &mut tui, - &mut server, - parent, - AppServerPath::from_app_server("notes.md"), - ) - .await?; - Box::pin(app.handle_event(&mut tui, &mut server, next_document_event(true).await)).await?; + Box::pin(app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(KeyCode::Tab.into()))) + .await?; + side_frame(&mut app, &mut tui, size)?; + let sidebar = app.conversation_frame.panel_area().expect("document panel"); + let buffer = tui.terminal.previous_buffer(); + let highlighted = (sidebar.y + 1..sidebar.bottom() - 1) + .flat_map(|y| (sidebar.x..sidebar.right()).map(move |x| &buffer[(x, y)])) + .filter(|cell| cell.modifier.contains(Modifier::REVERSED)) + .map(ratatui::buffer::Cell::symbol) + .collect::(); + insta::assert_snapshot!(highlighted, @"Next"); + for key in [KeyCode::Home, KeyCode::Enter] { + assert!( + app.handle_document_input(&mut tui, &mut server, &TuiEvent::Key(key.into())) + .await + ); + } + assert_eq!(app.sidebar().unwrap().documents.len(), 1); + let document = app.sidebar_mut().active_document().unwrap(); + let (view, _) = document.reader().unwrap(); + view.jump_to_latest(); + side_frame(&mut app, &mut tui, size)?; + assert!( + app.handle_document_input(&mut tui, &mut server, &TuiEvent::Key(KeyCode::Tab.into())) + .await + ); + Box::pin(app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(KeyCode::Enter.into()))) + .await?; Box::pin(app.handle_event(&mut tui, &mut server, next_document_event(false).await)).await?; let two = side_frame(&mut app, &mut tui, size)?; assert!( @@ -211,6 +385,16 @@ async fn focused_markdown_link_opens_read_only_preview_only_with_workspace() -> Box::pin(app.handle_event(&mut tui, &mut server, next_document_event(true).await)).await?; Box::pin(app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(KeyCode::Esc.into()))) .await?; + Box::pin(app.handle_tui_event( + &mut tui, + &mut server, + TuiEvent::Key(KeyEvent::new_with_kind( + KeyCode::Esc, + KeyModifiers::NONE, + KeyEventKind::Release, + )), + )) + .await?; Box::pin(app.handle_event(&mut tui, &mut server, next_document_event(false).await)).await?; assert_eq!(app.sidebar().unwrap().documents.len(), 1); app.open_document( @@ -245,6 +429,77 @@ async fn focused_markdown_link_opens_read_only_preview_only_with_workspace() -> )) .await?; assert!(!app.side_companions[&parent].view.document_links); + for directory in ["featureA", "featureB"] { + std::fs::create_dir_all(dir.path().join(directory).join("shared"))?; + std::fs::write( + dir.path().join(directory).join("shared/guide.md"), + "# Guide", + )?; + Box::pin(app.open_document( + &mut tui, + &mut server, + parent, + AppServerPath::from_app_server(format!("{directory}/shared/guide.md")), + )) + .await?; + Box::pin(app.handle_event(&mut tui, &mut server, next_document_event(true).await)).await?; + Box::pin(app.handle_event(&mut tui, &mut server, next_document_event(false).await)).await?; + } + let _ = side_frame(&mut app, &mut tui, Size::new(76, 12))?; + let strip = app + .conversation_frame + .sidebar_tab_strip() + .expect("tab strip"); + let buffer = tui.terminal.previous_buffer(); + let labels = (strip.x..strip.right()) + .map(|x| buffer[(x, strip.y)].symbol()) + .collect::(); + let duplicate_labels = labels + .split('×') + .map(|label| label.trim_start_matches('‹').trim()) + .filter(|label| label.starts_with("featureA/") || label.starts_with("featureB/")) + .collect::>() + .join("\n"); + insta::assert_snapshot!(duplicate_labels, @" + featureA/guide.md + featureB/guide.md + "); + side_frame(&mut app, &mut tui, Size::new(/*width*/ 33, /*height*/ 12))?; + let strip = app + .conversation_frame + .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× +"); + 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")?; + Box::pin(app.open_document( + &mut tui, + &mut server, + parent, + AppServerPath::from_app_server(format!("{directory}/guide.md")), + )) + .await?; + Box::pin(app.handle_event(&mut tui, &mut server, next_document_event(true).await)).await?; + Box::pin(app.handle_event(&mut tui, &mut server, next_document_event(false).await)).await?; + } + side_frame(&mut app, &mut tui, Size::new(/*width*/ 33, /*height*/ 12))?; + let strip = app + .conversation_frame + .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× +"); server.shutdown().await?; Ok(()) } + +fn visible_sidebar_row(tui: &crate::tui::Tui, sidebar: Rect, row: u16) -> String { + let buffer = tui.terminal.previous_buffer(); + (sidebar.x..sidebar.right()) + .map(|column| buffer[(column, row)].symbol()) + .collect::() + .trim() + .to_owned() +} diff --git a/codex-rs/tui/src/app/thread_routing.rs b/codex-rs/tui/src/app/thread_routing.rs index 013c336d95..bd0c00454b 100644 --- a/codex-rs/tui/src/app/thread_routing.rs +++ b/codex-rs/tui/src/app/thread_routing.rs @@ -147,6 +147,7 @@ impl App { }; if let Some(pane) = self.sidebars.get_mut(&Some(active_id)) { pane.opening = None; + pane.cancel_hidden_document_primary(/*visible*/ false); } let input_state = self.chat_widget.capture_thread_input_state(); let recap_progress = self.recap.progress(); diff --git a/codex-rs/tui/src/line_truncation.rs b/codex-rs/tui/src/line_truncation.rs index f815c0f9de..da19a2d37e 100644 --- a/codex-rs/tui/src/line_truncation.rs +++ b/codex-rs/tui/src/line_truncation.rs @@ -113,6 +113,26 @@ pub(crate) fn truncate_line_with_ellipsis(line: Line<'static>, max_width: usize) #[path = "line_truncation_tests.rs"] mod tests; +/// Format a document tab from path components ordered from filename toward root. +/// Keep the distinguishing directory suffix when the tab is too narrow for the path. +pub(crate) fn document_label(parts: &[&str], width: usize) -> String { + let name = parts.iter().rev().copied().collect::>().join("/"); + if crate::width::display_width(&name) <= width { + return name; + } + if parts.len() < 2 || width < 4 { + return filename_label(&name, width); + } + let directory = parts[parts.len() - 1]; + let budget = (width / 2).min(crate::width::display_width(directory)); + let directory = middle_label(directory, budget); + let filename = filename_label( + parts[0], + width.saturating_sub(crate::width::display_width(&directory) + 1), + ); + format!("{directory}/{filename}") +} + pub(crate) fn filename_label(name: &str, width: usize) -> String { let extension = name .rsplit_once('.') @@ -121,6 +141,11 @@ pub(crate) fn filename_label(name: &str, width: usize) -> String { middle_label_with_suffix(name, width, extension) } +/// Keep both ends of a label, measuring terminal cells and preserving grapheme boundaries. +pub(crate) fn middle_label(text: &str, width: usize) -> String { + middle_label_with_suffix(text, width, /*suffix_width*/ 0) +} + fn middle_label_with_suffix(text: &str, width: usize, suffix_width: usize) -> String { use crate::width::display_width; use unicode_segmentation::UnicodeSegmentation; diff --git a/codex-rs/tui/src/markdown_render.rs b/codex-rs/tui/src/markdown_render.rs index 82e9f274cf..b4f1f47789 100644 --- a/codex-rs/tui/src/markdown_render.rs +++ b/codex-rs/tui/src/markdown_render.rs @@ -106,6 +106,10 @@ mod list_spacing_tests; #[path = "markdown_render/task_list_tests.rs"] mod task_list_tests; pub(crate) use web_links::hide_web_link_destination; + +pub(crate) fn hide_reader_link_destination(destination: &str) -> bool { + hide_web_link_destination(destination) || local_links::sidebar_file_link(destination).is_some() +} use web_links::style_bare_web_urls; const TABLE_COLUMN_GAP: usize = 2; @@ -482,6 +486,7 @@ pub(crate) fn render_markdown_lines_with_list_spacing( #[derive(Clone, Debug)] struct LinkState { destination: String, + source: usize, show_destination: bool, style_label: bool, has_visible_label: bool, @@ -765,7 +770,7 @@ impl<'a, 'policy> Writer<'a, 'policy> { Tag::Emphasis => self.push_inline_style(self.styles.emphasis), Tag::Strong => self.push_inline_style(self.styles.strong), Tag::Strikethrough => self.push_inline_style(self.styles.strikethrough), - Tag::Link { dest_url, .. } => self.push_link(dest_url.to_string()), + Tag::Link { dest_url, .. } => self.push_link(dest_url.to_string(), range.start), Tag::Table(alignments) => self.start_table(alignments), Tag::TableHead => self.start_table_head(), Tag::TableRow => self.start_table_row(range), @@ -1404,11 +1409,19 @@ impl<'a, 'policy> Writer<'a, 'policy> { fn push_span_to_table_cell(&mut self, span: Span<'static>) { let span = self.style_link_label(span); - let mut annotated = HyperlinkLine::new(Line::default()); - annotated.push_span( - span, - self.link.as_ref().map(|link| link.destination.as_str()), - ); + let annotated = if let Some(path) = self.label_document_path() { + self.document_label_span(span, path) + } else { + let mut annotated = HyperlinkLine::default(); + annotated.push_span( + span, + self.link.as_ref().map(|link| link.destination.as_str()), + ); + if let Some(link) = annotated.hyperlinks.last_mut() { + link.markdown_source = self.link.as_ref().map(|link| link.source); + } + annotated + }; if let Some(table_state) = self.table_state.as_mut() && let Some(cell) = table_state.current_cell.as_mut() { @@ -1430,29 +1443,12 @@ impl<'a, 'policy> Writer<'a, 'policy> { if i > 0 { self.push_table_cell_hard_break(); } - self.push_text_spans_to_table_cell(line, style); - } - } - - fn push_text_spans_to_table_cell(&mut self, text: &str, style: Style) { - let span = self.style_link_label(Span::styled(text.to_string(), style)); - let destination = self - .link - .as_ref() - .and_then(|link| web_destination(&link.destination)); - let mut annotated = if let Some(destination) = destination { - let mut annotated = HyperlinkLine::new(Line::default()); - annotated.push_span(span, Some(&destination)); - annotated - } else if self.link.is_some() || self.in_code_block { - HyperlinkLine::new(Line::from(span)) - } else { - style_bare_web_urls(span, self.styles.link) - }; - if let Some(table_state) = self.table_state.as_mut() - && let Some(cell) = table_state.current_cell.as_mut() - { - cell.push_annotated(std::mem::take(&mut annotated), &self.copy_inline); + let annotated = self.annotate_text_span(line, style); + if let Some(table_state) = self.table_state.as_mut() + && let Some(cell) = table_state.current_cell.as_mut() + { + cell.push_annotated(annotated, &self.copy_inline); + } } } @@ -2292,7 +2288,7 @@ impl<'a, 'policy> Writer<'a, 'policy> { fn style_link_label(&mut self, mut span: Span<'static>) -> Span<'static> { if let Some(link) = self.link.as_mut() - && web_destination(&link.destination).is_some() + && (link.style_label || web_destination(&link.destination).is_some()) { link.has_visible_label |= !span.content.trim().is_empty() && display_width(&span.content) > 0; @@ -2301,17 +2297,18 @@ impl<'a, 'policy> Writer<'a, 'policy> { span } - fn push_link(&mut self, dest_url: String) { + fn push_link(&mut self, dest_url: String, source: usize) { let style_label = (self.is_hidden_link_destination)(&dest_url); if style_label { self.push_inline_style(self.styles.link); } let show_destination = !style_label && should_render_link_destination(&dest_url); self.link = Some(LinkState { + source, show_destination, style_label, has_visible_label: false, - local_target_display: if is_local_path_like_link(&dest_url) { + local_target_display: if !style_label && is_local_path_like_link(&dest_url) { Some( render_local_link_target(&dest_url, self.cwd.as_deref()) .unwrap_or_else(|| dest_url.clone()), @@ -2326,7 +2323,16 @@ impl<'a, 'policy> Writer<'a, 'policy> { } fn pop_link(&mut self) { - if let Some(link) = self.link.take() { + if let Some(mut link) = self.link.take() { + if link.style_label + && !link.has_visible_label + && local_links::sidebar_file_link(&link.destination).is_some() + { + link.local_target_display = Some( + render_local_link_target(&link.destination, self.cwd.as_deref()) + .unwrap_or_else(|| link.destination.clone()), + ); + } if link.style_label { self.pop_inline_style(); } @@ -2339,11 +2345,11 @@ impl<'a, 'policy> Writer<'a, 'policy> { let span = Span::styled(link.destination.clone(), self.styles.link); if self.in_table_cell() { self.push_span_to_table_cell(" (".into()); - self.push_link_target(span, &link.destination); + self.push_link_target(span, &link.destination, link.source); self.push_span_to_table_cell(")".into()); } else { self.push_span(" (".into()); - self.push_link_target(span, &link.destination); + self.push_link_target(span, &link.destination, link.source); self.push_span(")".into()); } } else if let Some(local_target_display) = link.local_target_display { @@ -2372,7 +2378,7 @@ impl<'a, 'policy> Writer<'a, 'policy> { self.push_span_to_table_cell(" (".into()); } self.copy_inline.push(crate::markdown_copy::Inline::Literal); - self.push_link_target(span, &link.destination); + self.push_link_target(span, &link.destination, link.source); self.copy_inline.pop(); if show_label { self.push_span_to_table_cell(")".into()); @@ -2394,7 +2400,7 @@ impl<'a, 'policy> Writer<'a, 'policy> { self.push_span(" (".into()); } self.copy_inline.push(crate::markdown_copy::Inline::Literal); - self.push_link_target(span, &link.destination); + self.push_link_target(span, &link.destination, link.source); self.copy_inline.pop(); if show_label { self.push_span(")".into()); @@ -2405,7 +2411,21 @@ impl<'a, 'policy> Writer<'a, 'policy> { } } - fn push_link_target(&mut self, span: Span<'static>, destination: &str) { + fn label_document_path(&self) -> Option { + let link = self.link.as_ref().filter(|link| link.style_label)?; + local_links::sidebar_file_link(&link.destination) + } + + fn document_label_span(&self, span: Span<'static>, path: String) -> HyperlinkLine { + let width = span_width(&span); + let mut line = HyperlinkLine::new(Line::from(span)); + let mut link = TerminalHyperlink::document(0..width, path); + link.markdown_source = self.link.as_ref().map(|link| link.source); + line.hyperlinks.push(link); + line + } + + fn push_link_target(&mut self, span: Span<'static>, destination: &str, source: usize) { let mut target = HyperlinkLine::default(); if let Some(path) = local_links::sidebar_file_link(destination) { let width = span_width(&span); @@ -2416,6 +2436,9 @@ impl<'a, 'policy> Writer<'a, 'policy> { } else { target.push_span(span, Some(destination)); } + if let Some(link) = target.hyperlinks.last_mut() { + link.markdown_source = Some(source); + } if let Some(cell) = self .table_state .as_mut() @@ -2597,6 +2620,10 @@ impl<'a, 'policy> Writer<'a, 'policy> { if self.current_line_content.is_none() { self.push_line(Line::default()); } + if let Some(path) = self.label_document_path() { + self.push_annotated(self.document_label_span(span, path)); + return; + } if let Some(line) = self.current_line_content.as_mut() { self.copy_line.push(span.content.len(), &self.copy_inline); if let Some(destination) = self @@ -2606,7 +2633,11 @@ impl<'a, 'policy> Writer<'a, 'policy> { { // Inline code and HTML retain source columns until the transcript expands tabs. let start = self.source_columns.measure(line, source_span_width); + let previous = line.hyperlinks.len(); line.push_linked_span(span, start, destination); + if let Some(link) = line.hyperlinks.get_mut(previous) { + link.markdown_source = self.link.as_ref().map(|link| link.source); + } } else { line.line.push_span(span); } @@ -2632,21 +2663,30 @@ impl<'a, 'policy> Writer<'a, 'policy> { } fn push_text_spans(&mut self, text: &str, style: Style) { + let annotated = self.annotate_text_span(text, style); + self.push_annotated(annotated); + } + + fn annotate_text_span(&mut self, text: &str, style: Style) -> HyperlinkLine { let span = self.style_link_label(Span::styled(text.to_string(), style)); let destination = self .link .as_ref() .and_then(|link| web_destination(&link.destination)); - let annotated = if let Some(destination) = destination { + if let Some(path) = self.label_document_path() { + self.document_label_span(span, path) + } else if let Some(destination) = destination { let mut annotated = HyperlinkLine::new(Line::default()); annotated.push_span(span, Some(&destination)); + if let Some(link) = annotated.hyperlinks.last_mut() { + link.markdown_source = self.link.as_ref().map(|link| link.source); + } annotated } else if self.link.is_some() || self.in_code_block { HyperlinkLine::new(Line::from(span)) } else { style_bare_web_urls(span, self.styles.link) - }; - self.push_annotated(annotated); + } } fn push_blank_line(&mut self) { diff --git a/codex-rs/tui/src/markdown_render/web_links_tests.rs b/codex-rs/tui/src/markdown_render/web_links_tests.rs index f4c0ae8f5e..a9b4db31f7 100644 --- a/codex-rs/tui/src/markdown_render/web_links_tests.rs +++ b/codex-rs/tui/src/markdown_render/web_links_tests.rs @@ -196,6 +196,34 @@ fn empty_web_link_labels_keep_a_visible_destination() { } } +#[test] +fn empty_reader_local_links_keep_a_visible_destination() { + for markdown in [ + "[](empty.md)", + "[](./empty.md)", + "[ ](./empty.md)", + "[\u{200d}](./empty.md)", + ] { + let lines = render_markdown_lines_with_width_cwd_and_hidden_link_destinations( + markdown, + Some(80), + /*cwd*/ None, + &crate::markdown_render::hide_reader_link_destination, + ); + assert!( + lines + .iter() + .any(|line| line.line.to_string().contains("empty.md")) + ); + assert!( + lines + .iter() + .flat_map(|line| &line.hyperlinks) + .any(|link| link.destination.contains("empty.md")) + ); + } +} + #[test] fn label_only_web_links_keep_targets_after_prose_and_table_wrapping() { let links = "[plain label](https://example.com/plain) [`code label`](https://example.com/code) [](https://example.com/html)"; diff --git a/codex-rs/tui/src/sidebar_chooser.rs b/codex-rs/tui/src/sidebar_chooser.rs index a5171d84eb..fcd76a1615 100644 --- a/codex-rs/tui/src/sidebar_chooser.rs +++ b/codex-rs/tui/src/sidebar_chooser.rs @@ -237,7 +237,7 @@ pub(crate) fn tab_strip( chat: TabState, tabs: ChatTabs<'_>, hovered_target: Option>, - document_title: impl Fn(uuid::Uuid) -> String, + document_title: impl Fn(uuid::Uuid, usize) -> String, buf: &mut Buffer, ) { tabs.strip().render( @@ -248,10 +248,7 @@ pub(crate) fn tab_strip( hovered_target, |id, area, style, buf| { let title = match id { - SidebarTab::Document(id) => Line::from(crate::line_truncation::filename_label( - &document_title(id), - usize::from(area.width), - )), + SidebarTab::Document(id) => Line::from(document_title(id, usize::from(area.width))), SidebarTab::Chat(id) => match tabs.choice_index(id) { Some(number) => match side_chat_label(&tabs.choices[number - 1]) { Some(name) => { diff --git a/codex-rs/tui/src/terminal_hyperlinks.rs b/codex-rs/tui/src/terminal_hyperlinks.rs index d875bc6a54..3d59f2e139 100644 --- a/codex-rs/tui/src/terminal_hyperlinks.rs +++ b/codex-rs/tui/src/terminal_hyperlinks.rs @@ -41,11 +41,33 @@ use crate::wrapping::RtOptions; // Destinations are repeated in every linked buffer cell. Leave oversized URLs as plain text. const MAX_HYPERLINK_DESTINATION_BYTES: usize = 8 * 1024; -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Eq)] pub(crate) struct TerminalHyperlink { pub(crate) columns: Range, pub(crate) destination: String, destination_kind: DestinationKind, + /// Byte offset of an explicit Markdown link, preserved through wrapping. + pub(crate) markdown_source: Option, +} + +// Rendering equality excludes source provenance, which can differ between streaming and full renders. +impl PartialEq for TerminalHyperlink { + fn eq(&self, other: &Self) -> bool { + self.columns == other.columns + && self.destination == other.destination + && self.destination_kind == other.destination_kind + } +} + +// The link offset is layout metadata, like HyperlinkLine source provenance. +impl std::fmt::Debug for TerminalHyperlink { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("TerminalHyperlink") + .field("columns", &self.columns) + .field("destination", &self.destination) + .field("destination_kind", &self.destination_kind) + .finish() + } } #[derive(Clone, Copy, Debug, Eq, PartialEq)] @@ -105,6 +127,7 @@ impl TerminalHyperlink { columns, destination, destination_kind: DestinationKind::Web, + markdown_source: None, } } @@ -146,6 +169,7 @@ impl TerminalHyperlink { columns, destination: url.into(), destination_kind: DestinationKind::TrustedFile, + markdown_source: None, }) } @@ -157,6 +181,7 @@ impl TerminalHyperlink { columns, destination: file.0.to_string(), destination_kind: DestinationKind::TrustedFile, + markdown_source: None, } } @@ -165,6 +190,7 @@ impl TerminalHyperlink { columns, destination: path, destination_kind: DestinationKind::Document, + markdown_source: None, } } @@ -185,6 +211,7 @@ impl TerminalHyperlink { columns, destination: self.destination.clone(), destination_kind: self.destination_kind, + markdown_source: self.markdown_source, } } @@ -227,10 +254,14 @@ impl Eq for HyperlinkLine {} /// Cache equality also tracks source whitespace hidden by display wrapping. pub(crate) fn lines_with_sources_eq(left: &[HyperlinkLine], right: &[HyperlinkLine]) -> bool { left == right - && left - .iter() - .map(|line| &line.source) - .eq(right.iter().map(|line| &line.source)) + && left.iter().zip(right).all(|(left, right)| { + left.source == right.source + && left + .hyperlinks + .iter() + .zip(&right.hyperlinks) + .all(|(left, right)| left.markdown_source == right.markdown_source) + }) } pub(crate) fn source_span_width(span: &Span<'_>) -> usize { @@ -624,6 +655,7 @@ fn push_link_range(line: &mut HyperlinkLine, range: Range, link: &Termina if let Some(previous) = line.hyperlinks.last_mut() && previous.destination == link.destination && previous.destination_kind == link.destination_kind + && previous.markdown_source == link.markdown_source && previous.columns.end == range.start { previous.columns.end = range.end; diff --git a/codex-rs/tui/src/transcript_view.rs b/codex-rs/tui/src/transcript_view.rs index fa384afc32..05b9cf2cba 100644 --- a/codex-rs/tui/src/transcript_view.rs +++ b/codex-rs/tui/src/transcript_view.rs @@ -99,6 +99,7 @@ pub(crate) struct TranscriptView { pub(crate) primary_selection: bool, position: Position, follow_control: follow_control::FollowControl, + pub(crate) show_follow_control: bool, copy_feedback: Option, composer_tip: Option<(Rect, HyperlinkLine)>, turn_tip_key: Option, @@ -141,6 +142,7 @@ impl Default for TranscriptView { primary_selection: false, position: Position::Latest, follow_control: follow_control::FollowControl::default(), + show_follow_control: true, copy_feedback: None, composer_tip: None, turn_tip_key: None, @@ -343,6 +345,28 @@ impl TranscriptView { self.render_search(buf); } + pub(crate) fn paint_document_scroll_indicators( + &mut self, + area: Rect, + buf: &mut Buffer, + cells: &[Arc], + ) { + if area.height < 2 || area.width < 3 { + return; + } + let start = self.start(cells); + for (visible, row, arrow) in [ + (start > (0, 0), area.top(), "↑"), + (start < self.bottom_start(cells), area.bottom() - 1, "↓"), + ] { + if visible { + buf[(area.right() - 1, row)] + .set_symbol(arrow) + .set_style(crate::style::secondary_text_style()); + } + } + } + /// Persist the clamped reading position after the last paint at the final viewport height. pub(crate) fn finish_collapse_layout(&mut self, cells: &[Arc]) { if self.area.is_empty() @@ -570,6 +594,15 @@ impl TranscriptView { } } + pub(crate) fn jump_to_offset(&mut self, cells: &[Arc], offset: usize) { + self.position = Position::Reading(Anchor { + key: self.entry_key(cells, /*index*/ 0), + index: 0, + offset, + row_bias: 0, + }); + } + pub(crate) fn jump_to_latest(&mut self) { self.disclosure.resume_after_approval = None; self.cancel_search(); diff --git a/codex-rs/tui/src/transcript_view/follow_control.rs b/codex-rs/tui/src/transcript_view/follow_control.rs index cfc52dd8ac..67ccf3428d 100644 --- a/codex-rs/tui/src/transcript_view/follow_control.rs +++ b/codex-rs/tui/src/transcript_view/follow_control.rs @@ -50,7 +50,8 @@ impl TranscriptView { } pub(super) fn follow_control_label(&self, width: u16) -> Option<&'static str> { - if self.area.is_empty() + if !self.show_follow_control + || self.area.is_empty() || self.tail_visible || self.highlight.is_some() || self.selection.is_some() diff --git a/codex-rs/tui/src/transcript_view/input.rs b/codex-rs/tui/src/transcript_view/input.rs index b08b365a07..53d191b3a6 100644 --- a/codex-rs/tui/src/transcript_view/input.rs +++ b/codex-rs/tui/src/transcript_view/input.rs @@ -121,6 +121,72 @@ impl TranscriptView { .link_at(visible.row, column - self.area.x, self.document_links) } + pub(crate) fn cycle_document_link( + &mut self, + cells: &[Arc], + selected: Option, + forward: bool, + ) -> Option { + let layout = self.layout(cells, /*index*/ 0)?; + let links = layout.document_links(); + let count = links.len(); + if count == 0 { + return None; + } + let index = match selected { + Some(index) if forward => (index + 1) % count, + Some(index) => (index + count - 1) % count, + None if forward => 0, + None => count - 1, + }; + let offset = links[index].0.start; + let row = layout.row_for_offset(offset); + if !self + .visible + .iter() + .any(|visible| visible.index == 0 && visible.row == row) + { + self.jump_to_offset(cells, offset); + } + Some(index) + } + + pub(crate) fn document_link( + &mut self, + cells: &[Arc], + index: usize, + ) -> Option { + self.layout(cells, /*index*/ 0)? + .document_links() + .into_iter() + .nth(index) + .map(|(_, link)| link) + } + + pub(crate) fn paint_document_link( + &mut self, + cells: &[Arc], + index: usize, + buf: &mut ratatui::buffer::Buffer, + ) { + let Some(layout) = self.layout(cells, /*index*/ 0) else { + return; + }; + let Some((range, _)) = layout.document_links().into_iter().nth(index) else { + return; + }; + for (row, visible) in self.visible.iter().enumerate() { + if visible.index == 0 { + visible.layout.highlight( + range.clone(), + Rect::new(self.area.x, self.area.y + row as u16, self.area.width, 1), + buf, + visible.row, + ); + } + } + } + pub(crate) fn navigate_pager( &mut self, key: KeyEvent, diff --git a/codex-rs/tui/src/transcript_view/select_mode.rs b/codex-rs/tui/src/transcript_view/select_mode.rs index 8b637bf9b2..6265ff3b90 100644 --- a/codex-rs/tui/src/transcript_view/select_mode.rs +++ b/codex-rs/tui/src/transcript_view/select_mode.rs @@ -439,7 +439,7 @@ impl TranscriptView { /*width*/ 1, /*height*/ 1, ); - buf.set_style(area, crate::style::selection_style().underlined()); + buf.set_style(area, crate::style::selection_style().not_underlined()); } } diff --git a/codex-rs/tui/src/transcript_view/select_mode_tests.rs b/codex-rs/tui/src/transcript_view/select_mode_tests.rs index 5a1f1da434..f39fb1b814 100644 --- a/codex-rs/tui/src/transcript_view/select_mode_tests.rs +++ b/codex-rs/tui/src/transcript_view/select_mode_tests.rs @@ -864,7 +864,7 @@ fn keyboard_table_mark_selects_cells_and_swaps_rectangle_corners() { row.iter() .map(|cell| { use ratatui::style::Modifier; - if cell.modifier.contains(Modifier::UNDERLINED) { + if cell.modifier.contains(Modifier::BOLD | Modifier::REVERSED) { "@" } else if cell.modifier.contains(Modifier::REVERSED) { cell.symbol() diff --git a/codex-rs/tui/src/transcript_view/snapshots/codex_tui__transcript_view__select_mode__tests__select_mode_renders_cursor_and_scannable_footer_hints.snap b/codex-rs/tui/src/transcript_view/snapshots/codex_tui__transcript_view__select_mode__tests__select_mode_renders_cursor_and_scannable_footer_hints.snap index 2c0e63cbf1..2d9121d54a 100644 --- a/codex-rs/tui/src/transcript_view/snapshots/codex_tui__transcript_view__select_mode__tests__select_mode_renders_cursor_and_scannable_footer_hints.snap +++ b/codex-rs/tui/src/transcript_view/snapshots/codex_tui__transcript_view__select_mode__tests__select_mode_renders_cursor_and_scannable_footer_hints.snap @@ -1,7 +1,6 @@ --- source: tui/src/transcript_view/select_mode_tests.rs -assertion_line: 627 -expression: "format!(\"{buffer:?}\\nunmarked wide: {}\\nunmarked:\\n{footer_buffer:?}\\nunmarked narrow: {}\\nmarked:\\n{marked_buffer:?}\\nmarked wide: {}\\nmarked: {}\\nfind:\\n{find_buffer:?}\\nfind footer: {}\\nfind cursor: {:?}\\nfind marked:\\n{find_marked_buffer:?}\",\nunmarked_wide.text, unmarked_narrow.text, marked_wide.text, marked.text,\nfind_footer.text, find_footer.cursor_column,)" +expression: "format!(\"{buffer:?}\\nunmarked wide: {}\\nunmarked:\\n{footer_buffer:?}\\nunmarked narrow: {}\\nmarked:\\n{marked_buffer:?}\\nmarked wide: {}\\nmarked: {}\\nfind:\\n{find_buffer:?}\\nfind footer: {}\\nfind cursor: {:?}\\nfind marked:\\n{find_marked_buffer:?}\",\nunmarked_wide.text, unmarked_narrow.text, marked_wide.text, marked.text,\nfind_footer_text, find_footer.cursor_column,)" --- Buffer { area: Rect { x: 0, y: 0, width: 32, height: 6 }, @@ -15,7 +14,7 @@ Buffer { ], styles: [ x: 0, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: NONE, - x: 0, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: BOLD | UNDERLINED | REVERSED, + x: 0, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: BOLD | REVERSED, x: 1, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: NONE, ] } @@ -52,7 +51,7 @@ Buffer { ], styles: [ x: 0, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: REVERSED, - x: 5, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: BOLD | UNDERLINED | REVERSED, + x: 5, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: BOLD | REVERSED, x: 6, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: NONE, ] } @@ -71,7 +70,7 @@ Buffer { ], styles: [ x: 0, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: NONE, - x: 5, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: BOLD | UNDERLINED | REVERSED, + x: 5, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: BOLD | REVERSED, x: 6, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: REVERSED, x: 10, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: NONE, ] @@ -93,7 +92,7 @@ Buffer { styles: [ x: 0, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: NONE, x: 6, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: REVERSED, - x: 7, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: BOLD | UNDERLINED | REVERSED, + x: 7, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: BOLD | REVERSED, x: 8, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: NONE, ] } diff --git a/codex-rs/tui/src/transcript_view/text.rs b/codex-rs/tui/src/transcript_view/text.rs index be983c8b8f..7ca817fac3 100644 --- a/codex-rs/tui/src/transcript_view/text.rs +++ b/codex-rs/tui/src/transcript_view/text.rs @@ -847,6 +847,42 @@ impl TextLayout { } } + pub(super) fn document_links(&self) -> Vec<(Range, String)> { + let mut stops: Vec<(Range, String)> = Vec::new(); + let mut previous_source = None; + for (index, row) in self.rows.iter().enumerate() { + let inset = row.first_column - row.prefix_columns; + for link in &row.line.hyperlinks { + let Some(destination) = link.reader_destination(/*documents*/ true) else { + continue; + }; + let offset = |column: usize| { + self.position_at(index, (inset + column).min(usize::from(u16::MAX)) as u16) + }; + let range = offset(link.columns.start)..offset(link.columns.end); + if range.is_empty() { + continue; + } + if let Some((previous, previous_destination)) = stops.last_mut() + && *previous_destination == destination + && previous_source == link.markdown_source + && (previous.end == range.start + || (previous_source.is_some() + && self + .text + .get(previous.end..range.start) + .is_some_and(|gap| gap.chars().all(char::is_whitespace)))) + { + previous.end = range.end; + } else { + previous_source = link.markdown_source; + stops.push((range, destination)); + } + } + } + stops + } + /// Resolve an OSC-8 destination or a document target when the workspace enables previews. pub(super) fn link_at(&self, row: usize, column: u16, documents: bool) -> Option { let row = self.rows.get(row)?; diff --git a/codex-rs/tui/src/transcript_view/text_tests.rs b/codex-rs/tui/src/transcript_view/text_tests.rs index e8da56b51a..df178e8785 100644 --- a/codex-rs/tui/src/transcript_view/text_tests.rs +++ b/codex-rs/tui/src/transcript_view/text_tests.rs @@ -455,3 +455,23 @@ fn rendered_markdown_file_targets_are_only_interactive_in_the_workspace() { ["./guide.md".to_owned(), "./notes.md".to_owned()].into() ); } + +#[test] +fn document_link_navigation_preserves_occurrences_across_wraps() { + let markdown = "[first **link** wraps](./guide.md) [second link](./guide.md)"; + for width in [10_u16, 17, 100] { + let lines = crate::markdown_render::render_markdown_lines_with_width_cwd_and_hidden_link_destinations( + markdown, + Some(usize::from(width)), + /*cwd*/ None, + &crate::markdown_render::hide_reader_link_destination, + ); + let layout = TextLayout::new(lines, width); + let links = layout + .document_links() + .into_iter() + .map(|(range, _)| &layout.text()[range]) + .collect::>(); + assert_eq!(links, ["first link wraps", "second link"]); + } +}