diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index 69dd396284..de47e41f7b 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -225,6 +225,7 @@ mod file_change_approvals; mod history_pagination; mod history_ui; mod input; +mod link_hover; mod loaded_threads; mod managed_worktree_creation; mod misalignment_policy; @@ -834,6 +835,8 @@ impl App { app_server: &mut AppServerSession, event: TuiEvent, ) -> Result { + tui.link_hover.observe(&event); + self.refresh_link_hover(tui)?; self.invalidate_right_click_paste(&event); self.finish_clipboard(tui); let event = self.finish_right_click_paste(tui, event); diff --git a/codex-rs/tui/src/app/link_hover.rs b/codex-rs/tui/src/app/link_hover.rs new file mode 100644 index 0000000000..ded238824e --- /dev/null +++ b/codex-rs/tui/src/app/link_hover.rs @@ -0,0 +1,26 @@ +//! Match transcript hover to the links Codex opens while terminal mouse input is captured. +//! Recheck after painting so scrolling and live output cannot leave a hand over stale content. + +use crossterm::event::KeyModifiers; + +use super::App; +use crate::tui::Tui; + +impl App { + pub(super) fn refresh_link_hover(&self, tui: &mut Tui) -> std::io::Result<()> { + let over_link = tui.is_owned_screen() + && self.overlay.is_none() + && self.chat_widget.no_modal_or_popup_active() + && tui.link_hover.mouse.is_some_and(|mouse| { + (mouse.modifiers.is_empty() + || mouse + .modifiers + .intersects(KeyModifiers::CONTROL | KeyModifiers::SUPER)) + && self + .transcript_view + .link_at(mouse.column, mouse.row) + .is_some() + }); + tui.set_link_pointer(over_link) + } +} diff --git a/codex-rs/tui/src/app/owned_transcript.rs b/codex-rs/tui/src/app/owned_transcript.rs index f8fd7db1e1..2e07262b2c 100644 --- a/codex-rs/tui/src/app/owned_transcript.rs +++ b/codex-rs/tui/src/app/owned_transcript.rs @@ -280,6 +280,7 @@ impl App { tui.frame_requester() .schedule_frame_in(Duration::from_millis(/*millis*/ 50)); } + self.refresh_link_hover(tui)?; Ok(bottom_area) } diff --git a/codex-rs/tui/src/transcript_view/input.rs b/codex-rs/tui/src/transcript_view/input.rs index f92a319bb7..83c7cc052d 100644 --- a/codex-rs/tui/src/transcript_view/input.rs +++ b/codex-rs/tui/src/transcript_view/input.rs @@ -80,6 +80,15 @@ impl JumpTarget { } impl TranscriptView { + /// Resolve links in the last rendered transcript, sharing geometry with click activation. + pub(crate) fn link_at(&self, column: u16, row: u16) -> Option { + if !self.area.contains(ScreenPosition::new(column, row)) { + return None; + } + let visible = self.visible.get(usize::from(row - self.area.y))?; + visible.layout.link_at(visible.row, column - self.area.x) + } + pub(crate) fn navigate_pager( &mut self, key: KeyEvent, @@ -243,15 +252,7 @@ impl TranscriptView { .flatten() }); let link = link.filter(|destination| { - self.visible - .get(usize::from(event.row - self.area.y)) - .and_then(|visible| { - visible - .layout - .link_at(visible.row, event.column - self.area.x) - }) - .as_ref() - == Some(destination) + self.link_at(event.column, event.row).as_ref() == Some(destination) }); if self .selection @@ -358,9 +359,8 @@ impl TranscriptView { .modifiers .intersects(KeyModifiers::CONTROL | KeyModifiers::SUPER) { - return visible - .layout - .link_at(visible.row, event.column.saturating_sub(self.area.x)) + return self + .link_at(event.column, event.row) .map(ViewAction::OpenLink); } if event.modifiers == KeyModifiers::SHIFT && self.has_selection_range() { @@ -383,11 +383,7 @@ impl TranscriptView { return None; } let link = (clicks == 1 && event.modifiers.is_empty()) - .then(|| { - visible - .layout - .link_at(visible.row, event.column.saturating_sub(self.area.x)) - }) + .then(|| self.link_at(event.column, event.row)) .flatten(); self.begin_selection(cells, event.column, event.row, clicks); if let Some(selection) = &mut self.selection { diff --git a/codex-rs/tui/src/transcript_view/input_tests.rs b/codex-rs/tui/src/transcript_view/input_tests.rs index 92e0719ce2..45f408cce4 100644 --- a/codex-rs/tui/src/transcript_view/input_tests.rs +++ b/codex-rs/tui/src/transcript_view/input_tests.rs @@ -24,6 +24,50 @@ fn mouse(kind: MouseEventKind, column: u16, row: u16) -> MouseEvent { } } +#[test] +fn hover_links_match_wrapped_click_targets_and_refresh_after_scrolling() { + let (mut view, cells) = transcript( + "before [wide 界 wrapped label](https://example.com) after\n\nplain\n\nmore\n\nlast", + /*width*/ 12, + ); + let area = view.area; + view.jump_to_beginning(&cells); + view.render(area, &mut Buffer::empty(area), &cells); + let mut targets = Vec::new(); + for row in area.y..area.bottom() { + for column in area.x..area.right() { + if let Some(url) = view.link_at(column, row) { + targets.push((column, row, url)); + } + } + } + assert!(!targets.is_empty()); + assert!(targets.iter().any(|(_, row, _)| *row != targets[0].1)); + for (column, row, url) in &targets { + let action = view.handle_mouse( + MouseEvent { + modifiers: KeyModifiers::CONTROL, + ..mouse(MouseEventKind::Down(MouseButton::Left), *column, *row) + }, + &cells, + ); + let actual = match action { + Some(ViewAction::OpenLink(url)) => Some(url), + _ => None, + }; + assert_eq!(actual.as_ref(), Some(url)); + } + assert_eq!(view.link_at(area.x - 1, area.y), None); + assert_eq!(view.link_at(area.right(), area.y), None); + view.scroll(&cells, /*rows*/ 20); + view.render(area, &mut Buffer::empty(area), &cells); + assert!( + targets + .iter() + .any(|(column, row, _)| view.link_at(*column, *row).is_none()) + ); +} + #[test] fn shift_click_extends_a_double_clicked_word_in_both_directions() { let (mut view, cells) = transcript("alpha beta gamma", /*width*/ 24); diff --git a/codex-rs/tui/src/tui.rs b/codex-rs/tui/src/tui.rs index 27b1950d0a..50b4e80e76 100644 --- a/codex-rs/tui/src/tui.rs +++ b/codex-rs/tui/src/tui.rs @@ -70,6 +70,7 @@ mod input_boundary; #[cfg(unix)] mod job_control; mod keyboard_modes; +mod link_pointer; #[cfg(test)] #[path = "tui/owned_screen_tests.rs"] mod owned_screen_tests; @@ -651,6 +652,7 @@ impl OverlayInput { } pub struct Tui { + pub(crate) link_hover: link_pointer::LinkHover, frame_requester: FrameRequester, draw_tx: broadcast::Sender<()>, event_broker: Arc, @@ -727,6 +729,7 @@ impl Tui { ); Self { + link_hover: link_pointer::LinkHover::default(), frame_requester, draw_tx, event_broker: Arc::new(event_broker), @@ -855,6 +858,7 @@ impl Tui { // Drop crossterm EventStream to avoid stdin conflicts with other processes. pub fn pause_events(&mut self) { + self.link_hover.mouse = None; self.event_broker.pause_events(); } diff --git a/codex-rs/tui/src/tui/alternate_screen.rs b/codex-rs/tui/src/tui/alternate_screen.rs index 2d5e94f083..2313da69df 100644 --- a/codex-rs/tui/src/tui/alternate_screen.rs +++ b/codex-rs/tui/src/tui/alternate_screen.rs @@ -33,10 +33,12 @@ pub(super) static ALTERNATE_SCREEN: AlternateScreen = AlternateScreen { mouse_capture_disabled: AtomicBool::new(/*v*/ false), input_configured: AtomicBool::new(/*v*/ false), keyboard_active: AtomicBool::new(/*v*/ false), + link_pointer: super::link_pointer::LinkPointer::new(), }; #[derive(Default)] pub(super) struct AlternateScreen { + link_pointer: super::link_pointer::LinkPointer, active: AtomicBool, mouse_active: AtomicBool, // Refresh alongside keyboard modes whenever this screen is entered or restored. @@ -67,6 +69,15 @@ impl Command for EnablePointerCapture { } impl AlternateScreen { + pub(super) fn set_link_pointer(&self, writer: &mut impl Write, over_link: bool) -> Result<()> { + if self.mouse_active.load(Ordering::Relaxed) { + self.link_pointer.update(writer, over_link) + } else { + self.link_pointer + .restore(writer, codex_terminal_detection::terminal_info().name) + } + } + pub(super) fn is_active(&self) -> bool { self.active.load(Ordering::Relaxed) } @@ -116,6 +127,9 @@ impl AlternateScreen { } fn disable_mouse(&self, writer: &mut impl Write) -> Result<()> { + let pointer_result = self + .link_pointer + .restore(writer, codex_terminal_detection::terminal_info().name); if self.mouse_active.load(Ordering::Relaxed) { let result = execute!(writer, DisableMouseCapture); #[cfg(windows)] @@ -144,7 +158,7 @@ impl AlternateScreen { self.mouse_active.store(/*val*/ false, Ordering::Relaxed); } - Ok(()) + pointer_result } /// Release input modes without changing the screen, so an editor can take it over. diff --git a/codex-rs/tui/src/tui/link_pointer.rs b/codex-rs/tui/src/tui/link_pointer.rs new file mode 100644 index 0000000000..b10ee5b87f --- /dev/null +++ b/codex-rs/tui/src/tui/link_pointer.rs @@ -0,0 +1,110 @@ +//! Link hover owns the mouse shape only while Codex captures pointer input. +//! Remember motion across repaints, but discard coordinates across focus and geometry changes. +//! Cleanup is independent of Tui so panic, suspend, and editor handoffs also restore the shape. +//! Kitty releases its override; Ghostty retains its existing text-cursor fallback. + +use std::io::Write; +use std::sync::atomic::AtomicU8; +use std::sync::atomic::Ordering; + +use codex_terminal_detection::TerminalName; +use crossterm::event::MouseEvent; +use crossterm::event::MouseEventKind; + +use super::Tui; +use super::TuiEvent; + +#[derive(Default)] +pub(crate) struct LinkHover { + pub(crate) mouse: Option, +} + +impl LinkHover { + pub(crate) fn observe(&mut self, event: &TuiEvent) { + match event { + TuiEvent::Mouse(mouse) => { + self.mouse = (!matches!( + mouse.kind, + MouseEventKind::Down(_) | MouseEventKind::Drag(_) + )) + .then_some(*mouse); + } + TuiEvent::Key(key) => { + if let Some(mouse) = &mut self.mouse { + mouse.modifiers = key.modifiers; + } + } + TuiEvent::FocusLost | TuiEvent::Resize(_) | TuiEvent::Resume => self.mouse = None, + _ => {} + } + } +} + +// 0: untouched/restored, 1: captured arrow, 2: link hand, 3: uncertain after a write failure. +// Keep cleanup armed until flush succeeds. +#[derive(Default)] +pub(super) struct LinkPointer(AtomicU8); + +impl LinkPointer { + pub(super) const fn new() -> Self { + Self(AtomicU8::new(/*v*/ 0)) + } + + pub(super) fn update(&self, writer: &mut impl Write, over_link: bool) -> std::io::Result<()> { + let previous = self.0.load(Ordering::Relaxed); + let next = if over_link { 2 } else { 1 }; + if previous == next || (previous == 0 && !over_link) { + return Ok(()); + } + self.0.store(next, Ordering::Relaxed); + let result = writer + .write_all(if over_link { + b"\x1b]22;pointer\x1b\\" + } else { + b"\x1b]22;default\x1b\\" + }) + .and_then(|()| writer.flush()); + if result.is_err() { + self.0.store(/*val*/ 3, Ordering::Relaxed); + } + result + } + + pub(super) fn restore( + &self, + writer: &mut impl Write, + terminal: TerminalName, + ) -> std::io::Result<()> { + if self.0.load(Ordering::Relaxed) != 0 { + // In Kitty, a named shape persists across mouse capture and screen changes. + // An empty OSC 22 releases that override back to the terminal's default policy. + writer.write_all(if terminal == TerminalName::Kitty { + b"\x1b]22;\x1b\\" + } else { + b"\x1b]22;text\x1b\\" + })?; + writer.flush()?; + self.0.store(/*val*/ 0, Ordering::Relaxed); + } + Ok(()) + } +} + +impl Tui { + pub(crate) fn set_link_pointer(&mut self, over_link: bool) -> std::io::Result<()> { + // OSC 22 names differ between terminals. Restrict CSS names to known implementations; + // multiplexers may consume OSC 22 and do not promise pointer-shape passthrough. + let info = codex_terminal_detection::terminal_info(); + if info.multiplexer.is_none() + && matches!(info.name, TerminalName::Ghostty | TerminalName::Kitty) + { + super::alternate_screen::ALTERNATE_SCREEN + .set_link_pointer(self.terminal.backend_mut(), over_link)?; + } + Ok(()) + } +} + +#[cfg(test)] +#[path = "link_pointer_tests.rs"] +mod tests; diff --git a/codex-rs/tui/src/tui/link_pointer_tests.rs b/codex-rs/tui/src/tui/link_pointer_tests.rs new file mode 100644 index 0000000000..2529747cf0 --- /dev/null +++ b/codex-rs/tui/src/tui/link_pointer_tests.rs @@ -0,0 +1,129 @@ +use super::*; +use crossterm::event::KeyModifiers; +use crossterm::event::MouseButton; +use pretty_assertions::assert_eq; + +#[test] +fn hover_transitions_are_deduplicated_and_restore_after_leaving_a_link() { + let mut frames = Vec::new(); + for terminal in [TerminalName::Ghostty, TerminalName::Kitty] { + let pointer = LinkPointer::default(); + let mut output = Vec::new(); + for over_link in [false, true, true, false, false, true] { + pointer.update(&mut output, over_link).unwrap(); + frames.push(String::from_utf8(std::mem::take(&mut output)).unwrap()); + } + pointer.restore(&mut output, terminal).unwrap(); + frames.push(String::from_utf8(std::mem::take(&mut output)).unwrap()); + pointer.restore(&mut output, terminal).unwrap(); + // Re-entering capture off a link must preserve the restored terminal policy. + pointer.update(&mut output, /*over_link*/ false).unwrap(); + assert_eq!(output, Vec::::new()); + pointer.update(&mut output, /*over_link*/ true).unwrap(); + frames.push(String::from_utf8(output).unwrap()); + } + insta::assert_debug_snapshot!(frames, @r#" + [ + "", + "\u{1b}]22;pointer\u{1b}\\", + "", + "\u{1b}]22;default\u{1b}\\", + "", + "\u{1b}]22;pointer\u{1b}\\", + "\u{1b}]22;text\u{1b}\\", + "\u{1b}]22;pointer\u{1b}\\", + "", + "\u{1b}]22;pointer\u{1b}\\", + "", + "\u{1b}]22;default\u{1b}\\", + "", + "\u{1b}]22;pointer\u{1b}\\", + "\u{1b}]22;\u{1b}\\", + "\u{1b}]22;pointer\u{1b}\\", + ] + "#); +} + +#[test] +#[cfg(unix)] +fn capture_release_restores_pointer_even_after_moving_off_link() { + for over_link in [true, false] { + let screen = super::super::alternate_screen::AlternateScreen::default(); + let mut output = Vec::new(); + screen + .configure_input(&mut output, /*capture_mouse*/ true) + .unwrap(); + screen + .set_link_pointer(&mut output, /*over_link*/ true) + .unwrap(); + screen.set_link_pointer(&mut output, over_link).unwrap(); + output.clear(); + screen.release_input(&mut output).unwrap(); + let expected = if codex_terminal_detection::terminal_info().name == TerminalName::Kitty { + b"\x1b]22;\x1b\\".as_slice() + } else { + b"\x1b]22;text\x1b\\".as_slice() + }; + assert!(output.starts_with(expected)); + output.clear(); + screen + .set_link_pointer(&mut output, /*over_link*/ true) + .unwrap(); + assert_eq!(output, Vec::::new()); + } +} + +#[test] +fn failed_write_is_retried_and_cleanup_remains_armed() { + struct Fails; + impl Write for Fails { + fn write(&mut self, _: &[u8]) -> std::io::Result { + Err(std::io::Error::other("write failed")) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + for (terminal, expected) in [ + (TerminalName::Ghostty, b"\x1b]22;text\x1b\\".as_slice()), + (TerminalName::Kitty, b"\x1b]22;\x1b\\".as_slice()), + ] { + let pointer = LinkPointer::default(); + assert!(pointer.update(&mut Fails, /*over_link*/ true).is_err()); + let mut output = Vec::new(); + pointer.update(&mut output, /*over_link*/ true).unwrap(); + assert_eq!(output, b"\x1b]22;pointer\x1b\\"); + assert!(pointer.restore(&mut Fails, terminal).is_err()); + output.clear(); + pointer.restore(&mut output, terminal).unwrap(); + assert_eq!(output, expected); + } +} + +#[test] +fn motion_survives_repaint_but_not_drag_focus_loss_resize_or_resume() { + let mouse = MouseEvent { + kind: MouseEventKind::Moved, + column: 8, + row: 3, + modifiers: KeyModifiers::NONE, + }; + for event in [ + TuiEvent::Mouse(MouseEvent { + kind: MouseEventKind::Drag(MouseButton::Left), + ..mouse + }), + TuiEvent::FocusLost, + TuiEvent::Resize(ratatui::layout::Size::new( + /*width*/ 80, /*height*/ 24, + )), + TuiEvent::Resume, + ] { + let mut hover = LinkHover::default(); + hover.observe(&TuiEvent::Mouse(mouse)); + hover.observe(&TuiEvent::Draw); + assert_eq!(hover.mouse, Some(mouse)); + hover.observe(&event); + assert_eq!(hover.mouse, None); + } +}