diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index 266bafca57..7f89755fcc 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -872,6 +872,9 @@ impl App { event: TuiEvent, ) -> Result { self.transcript_view.document_links = self.document_preview_available(tui, app_server); + crate::markdown_render::preferences::set_document_links( + self.transcript_view.document_links, + ); self.transcript_view .sync_patch_approval(self.chat_widget.current_patch_approval()); // A chooser action must never decide a modal that has not been painted yet. @@ -899,7 +902,9 @@ impl App { tui.link_hover.observe(&event); let current = tui.link_hover.position(); if previous != current - && self.hovered_sidebar_target(previous) != self.hovered_sidebar_target(current) + && (self.hovered_sidebar_target(previous) != self.hovered_sidebar_target(current) + || previous.is_some_and(|point| self.transcript_view.has_document_link_at(point)) + || current.is_some_and(|point| self.transcript_view.has_document_link_at(point))) { tui.frame_requester().schedule_frame(); } diff --git a/codex-rs/tui/src/app/backend_selection.rs b/codex-rs/tui/src/app/backend_selection.rs index de7a81160e..e2dae94478 100644 --- a/codex-rs/tui/src/app/backend_selection.rs +++ b/codex-rs/tui/src/app/backend_selection.rs @@ -470,6 +470,7 @@ impl App { self.app_event_tx = AppEventSender::new(self.app_event_tx.app_event_tx.clone()); self.app_server_backend_id = Some(destination.backend_id()); self.app_server_target = target; + self.refresh_transcript_document_links(); self.reconnect = Default::default(); if let Ok(mut state) = self.agents_overview.view_state.lock() { state.connection_notice = None; diff --git a/codex-rs/tui/src/app/config_persistence.rs b/codex-rs/tui/src/app/config_persistence.rs index e0c78f9ea1..eb66db2468 100644 --- a/codex-rs/tui/src/app/config_persistence.rs +++ b/codex-rs/tui/src/app/config_persistence.rs @@ -511,6 +511,7 @@ impl App { self.chat_widget.local_settings.tui.status_line_provider = self.local_settings.tui.status_line_provider.clone(); self.config = config; + self.refresh_transcript_document_links(); self.chat_widget.sync_plugin_mentions_config(&self.config); Ok(()) } diff --git a/codex-rs/tui/src/app/event_dispatch.rs b/codex-rs/tui/src/app/event_dispatch.rs index 2b023bcddf..893e475d4f 100644 --- a/codex-rs/tui/src/app/event_dispatch.rs +++ b/codex-rs/tui/src/app/event_dispatch.rs @@ -3583,15 +3583,15 @@ impl App { Box::pin(self.open_saved_chat(tui, app_server, target)).await?; } } - AppEvent::OpenSidebarDocument { backend_id, source, path } => { + AppEvent::OpenSidebarDocument { backend_id, source, link } => { if app_server.backend_id() == backend_id && self.current_displayed_thread_id() == Some(source) && self.document_preview_available(tui, app_server) { - Box::pin(self.open_document(tui, app_server, source, path)).await?; + Box::pin(self.open_document(tui, app_server, source, link)).await?; } } - AppEvent::SidebarDocumentResolved { backend_id, parent, source, request, original_path, path, } => { + AppEvent::SidebarDocumentResolved { backend_id, parent, source, request, original_path, path, location, } => { if backend_id == app_server.backend_id() && self.sidebar_parent() == Some(parent) && let Some(pane) = self.sidebars.get_mut(&Some(parent)) @@ -3605,7 +3605,7 @@ impl App { && self.current_displayed_thread_id() == Some(source) && self.document_preview_available(tui, app_server); match path { - Ok(path) => Box::pin(self.open_resolved_document(tui, app_server, source, original_path, path, focus)).await?, + Ok(path) => Box::pin(self.open_resolved_document(tui, app_server, source, original_path, path, location, focus)).await?, Err(error) if focus => self.chat_widget.add_error_message(format!("Could not open file: {error}")), Err(_) => {} } diff --git a/codex-rs/tui/src/app/owned_transcript.rs b/codex-rs/tui/src/app/owned_transcript.rs index 42863f634f..2026c7c448 100644 --- a/codex-rs/tui/src/app/owned_transcript.rs +++ b/codex-rs/tui/src/app/owned_transcript.rs @@ -302,6 +302,15 @@ impl App { .mouse .filter(|mouse| self.pane_resize.is_none() && !tui.shortcut_hud_contains(*mouse)) .map(|mouse| (mouse.column, mouse.row).into()); + let tui_link_position = pointer.filter(|_| { + tui.link_hover.mouse.is_some_and(|mouse| { + mouse.modifiers.is_empty() + || mouse.modifiers.intersects( + crossterm::event::KeyModifiers::CONTROL + | crossterm::event::KeyModifiers::SUPER, + ) + }) + }); let sidebar_parent = self.sidebar_parent(); let sidebar_motion = MotionMode::from_animations_enabled(self.local_settings.tui.animations); @@ -342,6 +351,10 @@ impl App { .or(self.app_server_backend_id) .map(|owner| self.backend_registry.thread_label_style(owner)) .unwrap_or_default(); + let link_pointer = + tui_link_position.filter(|_| self.chat_widget.no_modal_or_popup_active()); + self.transcript_view + .paint_document_links(frame.buffer, link_pointer); match &self.conversation_frame.sidebar { Some(sidebar::SidebarLayout::Chat(panes)) => { if let Some(companion) = self.side_companions.get_mut(&panes.passive_thread) { @@ -1252,19 +1265,15 @@ impl App { } } } else if let ViewAction::OpenLink(url) = action { - if url.starts_with("file://") - || crate::terminal_hyperlinks::web_destination(&url).is_some() - { - self.open_url_in_browser(url); - } else if self.transcript_view.document_links - && let Some(source) = self.current_displayed_thread_id() - { - self.app_event_tx.send(AppEvent::OpenSidebarDocument { - backend_id: app_server.backend_id(), - source, - path: codex_app_server_client::AppServerPath::from_app_server(url), - }); - } + self.open_url_in_browser(url); + } else if let ViewAction::OpenDocument(link) = action + && let Some(source) = self.current_displayed_thread_id() + { + self.app_event_tx.send(AppEvent::OpenSidebarDocument { + backend_id: app_server.backend_id(), + source, + link, + }); } } if was_select_mode && !self.transcript_view.is_select_mode() { diff --git a/codex-rs/tui/src/app/session_lifecycle.rs b/codex-rs/tui/src/app/session_lifecycle.rs index c1fd975798..9f12b333b5 100644 --- a/codex-rs/tui/src/app/session_lifecycle.rs +++ b/codex-rs/tui/src/app/session_lifecycle.rs @@ -1554,6 +1554,7 @@ impl App { self.drain_outgoing_thread_events().await; } self.store_active_thread_receiver().await; + self.refresh_transcript_document_links(); self.reset_transcript_state_after_clear(); tui.clear_pending_history_lines(); let presentation = match presentation { diff --git a/codex-rs/tui/src/app/side_pane.rs b/codex-rs/tui/src/app/side_pane.rs index e6405d0f91..6679f0ddd1 100644 --- a/codex-rs/tui/src/app/side_pane.rs +++ b/codex-rs/tui/src/app/side_pane.rs @@ -484,14 +484,16 @@ impl SidePaneLayout { frames.schedule_frame_in(Duration::from_secs(1)); } } - companion.view.render_parked( - transcript, - frame.buffer, - &companion.cells, - companion.display.active.as_deref(), - &companion.display.auxiliary, - collapse_turn_details, - ); + crate::markdown_render::preferences::with_visible_local_paths(|| { + companion.view.render_parked( + transcript, + frame.buffer, + &companion.cells, + companion.display.active.as_deref(), + &companion.display.auxiliary, + collapse_turn_details, + ); + }); frame .image_placements .extend(companion.view.image_placements()); diff --git a/codex-rs/tui/src/app/sidebar_document.rs b/codex-rs/tui/src/app/sidebar_document.rs index ca8be176dc..809fc56ce7 100644 --- a/codex-rs/tui/src/app/sidebar_document.rs +++ b/codex-rs/tui/src/app/sidebar_document.rs @@ -6,6 +6,8 @@ use super::*; use crate::key_hint::KeyBinding; use crate::keymap::KeymapContext; use crate::keymap::RuntimeKeymap; +use crate::markdown_render::FileLink; +use crate::markdown_render::SourceLocation; use crate::motion::MotionMode; use crate::sidebar_tab_strip::SidebarTab; use crate::terminal_hyperlinks::HyperlinkLine; @@ -18,10 +20,12 @@ use codex_utils_path_uri::PathUri; use ratatui::buffer::Buffer; use ratatui::layout::Position; use ratatui::widgets::Widget; +use unicode_segmentation::UnicodeSegmentation; #[derive(Debug)] struct FileCell { source: String, + language: Option, } impl HistoryCell for FileCell { @@ -38,6 +42,12 @@ impl HistoryCell for FileCell { } fn display_hyperlink_lines(&self, width: u16) -> Vec { + if let Some(language) = &self.language { + return crate::render::highlight::highlight_code_to_lines(&self.source, language) + .into_iter() + .map(HyperlinkLine::new) + .collect(); + } crate::markdown_render::render_markdown_lines_with_width_cwd_and_hidden_link_destinations( &self.source, Some(width.into()), @@ -56,6 +66,7 @@ pub(super) struct Document { pub(super) path: PathUri, pub(super) backend: crate::backend_id::BackendId, link: Option, + location: Option, state: State, } @@ -65,6 +76,8 @@ enum State { Ready { view: Box, cells: [Arc; 1], + line_starts: Vec, + target: Option<(usize, usize)>, }, } @@ -83,8 +96,9 @@ impl Document { 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()) + State::Ready { view, target, .. } => { + !view.has_active_interaction() + && (key.code != KeyCode::Esc || (self.link.is_none() && target.is_none())) } _ => true, } @@ -105,6 +119,10 @@ impl Document { } } + fn title(&self) -> String { + self.path.basename().unwrap_or_default() + } + 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()); @@ -114,17 +132,92 @@ impl Document { pub(super) fn loaded(&mut self, result: Result) { self.state = match result { Ok(source) => { - let cells: [Arc; 1] = [Arc::new(FileCell { source })]; + let title = self.title(); + let code = + self.location.is_some() || !crate::markdown_render::is_markdown_file(&title); + const MAX_SOURCE_BYTES: usize = 1024 * 1024; + if code && source.len() > MAX_SOURCE_BYTES { + self.state = State::Failed("Source preview limit is 1 MiB".into()); + return; + } + // Like the transcript layout, count one LF per logical line, including CRLF input. + let mut start = 0; + let line_starts = if code { + source + .lines() + .map(|line| { + let offset = start; + start += line.len() + 1; + offset + }) + .collect::>() + } else { + Vec::new() + }; + const MAX_SOURCE_LINES: usize = 10_000; + if line_starts.len() > MAX_SOURCE_LINES { + self.state = + State::Failed(format!("Source preview limit is {MAX_SOURCE_LINES} lines")); + return; + } + let language = code.then(|| { + title + .rsplit_once('.') + .map_or(title.as_str(), |(_, ext)| ext) + .to_owned() + }); + let target = self + .location + .and_then(|loc| source_target(&source, &line_starts, loc)); + let cells: [Arc; 1] = [Arc::new(FileCell { source, language })]; let mut view = Box::::default(); view.document_links = true; view.show_follow_control = false; - view.jump_to_beginning(&cells); - State::Ready { view, cells } + view.jump_to_offset(&cells, target.map_or(0, |(_, offset)| offset)); + State::Ready { + view, + cells, + line_starts, + target, + } } Err(error) => State::Failed(error), }; } + fn go_to(&mut self, location: Option) { + let was_located = self.location.is_some(); + let restore_markdown = location.is_none() + && was_located + && crate::markdown_render::is_markdown_file(&self.title()); + self.location = location; + self.link = None; + let State::Ready { + view, + cells, + line_starts, + target, + } = &mut self.state + else { + return; + }; + let Some(source) = cells[0].copy_source() else { + return; + }; + if restore_markdown || (location.is_some() && line_starts.is_empty()) { + // Coordinate links show source. Plain Markdown links restore rendering. + let source = source.to_owned(); + self.loaded(Ok(source)); + } else { + *target = location.and_then(|location| source_target(source, line_starts, location)); + if let Some((_, offset)) = target { + view.cancel_search(); + view.end_selection(cells); + view.jump_to_offset(cells, *offset); + } + } + } + pub(super) fn paint( &mut self, area: Rect, @@ -151,7 +244,12 @@ impl Document { .wrap(ratatui::widgets::Wrap { trim: false }) .render(body, buf); } - State::Ready { view, cells } => { + State::Ready { + view, + cells, + line_starts, + target, + } => { view.set_keymap_bindings(keymap); if view.tick_selection(cells) { frames.schedule_frame_in(std::time::Duration::from_millis(45)); @@ -177,7 +275,14 @@ impl Document { .map(|hint| { crate::footer_hint::shortcut(&hint.display_label(), "select") }), - Some(crate::footer_hint::shortcut("Esc", "close")), + Some(crate::footer_hint::shortcut( + "Esc", + if target.is_some() { + "clear highlight" + } else { + "close" + }, + )), ] .into_iter() .flatten(), @@ -203,7 +308,13 @@ impl Document { if content.width > 2 { viewport.width -= 1; } - view.render(viewport, buf, cells); + view.render_document( + viewport, + buf, + cells, + line_starts, + target.filter(|_| !view.has_active_interaction()), + ); if let Some(index) = self.link { view.paint_document_link(cells, index, buf); } @@ -236,6 +347,29 @@ impl Document { } } +fn source_target( + source: &str, + starts: &[usize], + location: SourceLocation, +) -> Option<(usize, usize)> { + let index = (location.line - 1).min(starts.len().saturating_sub(1)); + let start = *starts.get(index)?; + let line = source.lines().nth(index)?; + let column = line + .char_indices() + .nth(location.column - 1) + .map_or(line.len(), |(byte, _)| byte); + let column = if column == line.len() { + column + } else { + line.grapheme_indices(/*is_extended*/ true) + .take_while(|(byte, _)| *byte <= column) + .last() + .map_or(0, |(byte, _)| byte) + }; + Some((index + 1, start + column)) +} + impl App { pub(super) fn cancel_hidden_sidebar_primary(&mut self, tui: &tui::Tui) { let parent = self.sidebar_parent(); @@ -267,16 +401,27 @@ impl App { self.conversation_focus_available(tui) && self.sidebar_chooser_available() && server.thread_params_mode() != crate::app_server_session::ThreadParamsMode::Cloud + && server.app_server_platform_family() != Some("windows") + && (server.uses_remote_workspace() || !cfg!(windows)) && self.current_displayed_thread_id().is_some() } + pub(super) fn refresh_transcript_document_links(&self) { + crate::markdown_render::preferences::set_document_links( + self.local_settings.workspace_enabled(&self.config) + && self.app_server_target.thread_params_mode() != crate::ThreadParamsMode::Cloud, + ); + } + pub(super) async fn open_document( &mut self, tui: &mut tui::Tui, server: &mut AppServerSession, source: ThreadId, - path: AppServerPath, + link: FileLink, ) -> Result<()> { + let location = link.location; + let path = AppServerPath::from_app_server(link.path); let Some(parent) = self.sidebar_parent() else { return Ok(()); }; @@ -297,12 +442,17 @@ impl App { request, original_path: path, path: resolved, + location, }); }); tui.frame_requester().schedule_frame(); Ok(()) } + #[allow( + clippy::too_many_arguments, + reason = "The safe read needs both paths, and the caller supplies navigation and focus." + )] pub(super) async fn open_resolved_document( &mut self, tui: &mut tui::Tui, @@ -310,6 +460,7 @@ impl App { source: ThreadId, original_path: AppServerPath, path: PathUri, + location: Option, focus: bool, ) -> Result<()> { let Some(parent) = self.sidebar_parent() else { @@ -327,6 +478,9 @@ impl App { return Ok(()); } if !failed { + if let Some(doc) = self.sidebar_mut().documents.get_mut(&id) { + doc.go_to(location); + } return self .activate_sidebar_tab(tui, server, SidebarTab::Document(id)) .await; @@ -342,6 +496,7 @@ impl App { path: path.clone(), backend: backend_id, link: None, + location, state: State::Loading(Instant::now()), }, ); @@ -387,7 +542,7 @@ impl App { && mouse.kind == MouseEventKind::Moved { if let Some(Document { - state: State::Ready { view, cells }, + state: State::Ready { view, cells, .. }, .. }) = pane.documents.get_mut(&id) && view.handle_mouse(*mouse, cells).is_some() @@ -411,12 +566,21 @@ impl App { if key.kind != KeyEventKind::Press && (escape || key.code == KeyCode::Enter) { return true; } - if let State::Ready { view, cells } = &mut doc.state { + if let State::Ready { + view, + cells, + target, + .. + } = &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() { + } else if escape + && (doc.link.take().is_some() + || (!view.has_active_interaction() && target.take().is_some())) + { None } else if !view.is_search_editing() && (self.keymap.app.find_transcript.is_pressed(*key) @@ -446,7 +610,7 @@ impl App { } 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) + view.document_link(cells, index).map(ViewAction::from) } else { doc.link = None; if view.has_active_interaction() { @@ -493,7 +657,7 @@ impl App { return false; } if let Some(Document { - state: State::Ready { view, cells }, + state: State::Ready { view, cells, .. }, link, .. }) = pane.documents.get_mut(&id) @@ -504,7 +668,14 @@ impl App { 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) + let mut mouse = *mouse; + if matches!( + mouse.kind, + MouseEventKind::ScrollUp | MouseEventKind::ScrollDown + ) { + mouse.column = mouse.column.max(view.remaining_area().x); + } + view.handle_mouse(mouse, cells) } else { None } @@ -512,25 +683,24 @@ impl App { _ => 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) + Some(ViewAction::OpenDocument(link)) => { + if let Some(doc) = pane.documents.get(&id) && let Some(parent) = doc.path.parent() { - let result = match LegacyAppPathString::from_string(url) + let result = match LegacyAppPathString::from_string(link.path) .resolve_against(&parent, /*user_home_dir*/ None) { Ok(path) if !path.to_url().has_host() => { + let source = doc.source; 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, + link.location, /*focus*/ true, ) .await @@ -543,6 +713,11 @@ impl App { } } } + Some(ViewAction::OpenLink(url)) => { + if let Some(url) = crate::terminal_hyperlinks::web_destination(&url) { + self.open_url_in_browser(url); + } + } Some(action) => { if let Some((view, cells)) = pane.documents.get_mut(&id).and_then(Document::reader) && let Some((count, result)) = view.copy_action( diff --git a/codex-rs/tui/src/app/sidebar_document_tests.rs b/codex-rs/tui/src/app/sidebar_document_tests.rs index f9ce7a80b2..bb4ba26f52 100644 --- a/codex-rs/tui/src/app/sidebar_document_tests.rs +++ b/codex-rs/tui/src/app/sidebar_document_tests.rs @@ -54,21 +54,24 @@ async fn document_preview_scenario() -> Result<()> { size, Default::default(), ); - let screen = side_frame(&mut app, &mut tui, size)?; - let (column, row) = screen - .lines() - .enumerate() - .find_map(|(row, line)| { - let byte = line.find("guide.md")?; - Some((line[..byte].width() as u16, row as u16)) - }) - .expect("the local link's path is visible"); - let press = MouseEvent { - kind: MouseEventKind::Down(MouseButton::Left), - column, - row, - modifiers: KeyModifiers::NONE, + let link_press = |screen: &str, label: &str| { + let (column, row) = screen + .lines() + .enumerate() + .find_map(|(row, line)| { + let byte = line.find(label)?; + Some((line[..byte].width() as u16, row as u16)) + }) + .expect("the local link is visible"); + MouseEvent { + kind: MouseEventKind::Down(MouseButton::Left), + column, + row, + modifiers: KeyModifiers::NONE, + } }; + let screen = side_frame(&mut app, &mut tui, size)?; + let press = link_press(&screen, "guide.md"); let modified_press = MouseEvent { modifiers: KeyModifiers::CONTROL, ..press @@ -85,11 +88,10 @@ async fn document_preview_scenario() -> Result<()> { app.local_settings.tui.keymap.global.select_transcript = Some(KeybindingsSpec::One(KeybindingSpec("ctrl-x [".into()))); enable_side_retention(&mut app)?; + crate::markdown_render::preferences::set_document_links(/*enabled*/ true); let enabled = side_frame(&mut app, &mut tui, size)?; - assert_eq!( - enabled.lines().nth(row as usize), - screen.lines().nth(row as usize) - ); + assert!(!enabled.contains("guide.md")); + let press = link_press(&enabled, "Guide"); let release = MouseEvent { kind: MouseEventKind::Up(MouseButton::Left), ..press @@ -128,7 +130,10 @@ async fn document_preview_scenario() -> Result<()> { "Middle.\n\n".repeat(12) ), )?; - let path = AppServerPath::from_app_server("guide.md"); + let path = FileLink { + path: "guide.md".into(), + location: None, + }; app.open_document(&mut tui, &mut server, parent, path.clone()) .await?; Box::pin(app.handle_event(&mut tui, &mut server, next_document_event(true).await)).await?; @@ -327,7 +332,7 @@ async fn document_preview_scenario() -> Result<()> { 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())) + Box::pin(app.handle_document_input(&mut tui, &mut server, &TuiEvent::Key(key.into()))) .await ); } @@ -337,8 +342,12 @@ async fn document_preview_scenario() -> Result<()> { 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_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?; @@ -379,7 +388,10 @@ async fn document_preview_scenario() -> Result<()> { &mut tui, &mut server, parent, - AppServerPath::from_app_server("closed.md"), + FileLink { + path: "closed.md".into(), + location: None, + }, ) .await?; Box::pin(app.handle_event(&mut tui, &mut server, next_document_event(true).await)).await?; @@ -397,11 +409,98 @@ async fn document_preview_scenario() -> Result<()> { .await?; Box::pin(app.handle_event(&mut tui, &mut server, next_document_event(false).await)).await?; assert_eq!(app.sidebar().unwrap().documents.len(), 1); + std::fs::write( + dir.path().join("main.rs"), + "// first\r\n// second\r\nlet value = 3;\r\n", + )?; + for location in [None, Some(SourceLocation { line: 3, column: 5 })] { + app.open_document( + &mut tui, + &mut server, + parent, + FileLink { + path: "./main.rs".into(), + location, + }, + ) + .await?; + Box::pin(app.handle_event(&mut tui, &mut server, next_document_event(true).await)).await?; + if location.is_none() { + Box::pin(app.handle_event(&mut tui, &mut server, next_document_event(false).await)) + .await?; + let Some(SidebarContent::Document(id)) = app.sidebar().unwrap().visible_content() + else { + panic!("the source tab should be visible"); + }; + app.sidebar_mut() + .documents + .get_mut(&id) + .unwrap() + .reader() + .unwrap() + .0 + .begin_search(); + } + } + let source = side_frame(&mut app, &mut tui, Size::new(200, 15))?; + let preview = source + .lines() + .filter_map(|line| line.rsplit_once('│')) + .map(|(_, sidebar)| sidebar.trim()) + .filter(|line| !line.is_empty()) + .collect::>() + .join("\n"); + insta::assert_snapshot!(preview, @" + guide.md × main.rs × + + 3 let value = 3; ↑ + ↑/↓ read · f3 find · Tab link · f8 select · Esc clear highlight + "); + let panel = app.conversation_frame.panel_area().unwrap(); + let buffer = tui.terminal.previous_buffer(); + let target_cell = &buffer[(panel.x + 7, panel.y + 1)]; + let adjacent = &buffer[(panel.x + 8, panel.y + 1)]; + assert_eq!(target_cell.symbol(), "v"); + assert_ne!( + target_cell + .modifier + .contains(ratatui::style::Modifier::REVERSED), + adjacent + .modifier + .contains(ratatui::style::Modifier::REVERSED), + ); + assert_eq!(app.sidebar().unwrap().documents.len(), 2); + let Some(SidebarContent::Document(id)) = app.sidebar().unwrap().visible_content() else { + panic!("the source tab should be visible"); + }; + let (view, cells) = app + .sidebar_mut() + .documents + .get_mut(&id) + .unwrap() + .reader() + .unwrap(); + assert!(view.begin_select_mode(cells)); + Box::pin(app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(KeyCode::Esc.into()))) + .await?; + let State::Ready { view, target, .. } = &app.sidebar().unwrap().documents[&id].state else { + panic!("the source tab should be ready"); + }; + assert!(!view.is_select_mode()); + assert!(target.is_some()); + assert!(!view.has_active_interaction()); + for remaining in [2, 1] { + Box::pin(app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(KeyCode::Esc.into()))) + .await?; + assert_eq!(app.sidebar().unwrap().documents.len(), remaining); + } app.open_document( &mut tui, &mut server, parent, - AppServerPath::from_app_server("notes.md"), + FileLink { + path: "notes.md".into(), + location: None, + }, ) .await?; app.overlay = Some(crate::pager_overlay::Overlay::Transcript( @@ -439,7 +538,10 @@ async fn document_preview_scenario() -> Result<()> { &mut tui, &mut server, parent, - AppServerPath::from_app_server(format!("{directory}/shared/guide.md")), + FileLink { + path: format!("{directory}/shared/guide.md"), + location: None, + }, )) .await?; Box::pin(app.handle_event(&mut tui, &mut server, next_document_event(true).await)).await?; @@ -478,7 +580,10 @@ async fn document_preview_scenario() -> Result<()> { &mut tui, &mut server, parent, - AppServerPath::from_app_server(format!("{directory}/guide.md")), + FileLink { + path: format!("{directory}/guide.md"), + location: None, + }, )) .await?; Box::pin(app.handle_event(&mut tui, &mut server, next_document_event(true).await)).await?; diff --git a/codex-rs/tui/src/app_event.rs b/codex-rs/tui/src/app_event.rs index 9bbf8b08bd..5d8b330dad 100644 --- a/codex-rs/tui/src/app_event.rs +++ b/codex-rs/tui/src/app_event.rs @@ -525,7 +525,7 @@ pub(crate) enum AppEvent { OpenSidebarDocument { backend_id: crate::backend_id::BackendId, source: ThreadId, - path: codex_app_server_client::AppServerPath, + link: crate::markdown_render::FileLink, }, SidebarDocumentResolved { backend_id: crate::backend_id::BackendId, @@ -534,6 +534,7 @@ pub(crate) enum AppEvent { request: uuid::Uuid, original_path: codex_app_server_client::AppServerPath, path: std::result::Result, + location: Option, }, SidebarDocumentLoaded { backend_id: crate::backend_id::BackendId, diff --git a/codex-rs/tui/src/history_cell/markdown_render_cache.rs b/codex-rs/tui/src/history_cell/markdown_render_cache.rs index 39b1ff7c6f..2ae55e45e0 100644 --- a/codex-rs/tui/src/history_cell/markdown_render_cache.rs +++ b/codex-rs/tui/src/history_cell/markdown_render_cache.rs @@ -18,6 +18,7 @@ pub(super) struct MarkdownRenderCacheKey { pub(super) terminal_fg: Option<(u8, u8, u8)>, pub(super) terminal_bg: Option<(u8, u8, u8)>, pub(super) color_level: crate::terminal_palette::StdoutColorLevel, + pub(super) document_links: bool, } impl MarkdownRenderCache { @@ -38,6 +39,7 @@ impl MarkdownRenderCache { terminal_fg: crate::terminal_palette::default_fg(), terminal_bg: crate::terminal_palette::default_bg(), color_level: crate::terminal_palette::stdout_color_level(), + document_links: crate::markdown_render::preferences::document_links_enabled(), }; let mut cached = self.cached.lock().unwrap_or_else(PoisonError::into_inner); if let Some((cached_key, lines)) = cached.as_ref() diff --git a/codex-rs/tui/src/lib.rs b/codex-rs/tui/src/lib.rs index 042fa72dff..f038d87855 100644 --- a/codex-rs/tui/src/lib.rs +++ b/codex-rs/tui/src/lib.rs @@ -2105,6 +2105,10 @@ async fn run_ratatui_app( let local_settings = crate::local_settings::LocalSettings::for_tui(&config, &tui); crate::markdown_render::preferences::init(local_settings.tui.rendering); + crate::markdown_render::preferences::set_document_links( + local_settings.workspace_enabled(&config) + && app_server_target.thread_params_mode() != ThreadParamsMode::Cloud, + ); // Configure syntax highlighting theme from the final config — onboarding // and resume/fork can both reload config with a different tui_theme, so // this must happen after the last possible reload. diff --git a/codex-rs/tui/src/markdown.rs b/codex-rs/tui/src/markdown.rs index 97ece6e64f..9673c72605 100644 --- a/codex-rs/tui/src/markdown.rs +++ b/codex-rs/tui/src/markdown.rs @@ -140,7 +140,7 @@ pub(crate) fn render_markdown_agent_with_list_spacing( }; let is_hidden_link_destination = |destination: &str| { rewritten.trusted_file_links.contains_key(destination) - || crate::markdown_render::hide_web_link_destination(destination) + || crate::markdown_render::preferences::hide_transcript_destination(destination) }; let mut lines = crate::markdown_render::render_with_copy_sources( &normalized, @@ -175,7 +175,7 @@ pub(crate) fn render_streaming_markdown_agent_with_links_and_cwd( &normalized, width, cwd, - &crate::markdown_render::hide_web_link_destination, + &crate::markdown_render::preferences::hide_transcript_destination, list_spacing, ); if normalized != markdown_source { diff --git a/codex-rs/tui/src/markdown_render.rs b/codex-rs/tui/src/markdown_render.rs index b4f1f47789..ee5497df56 100644 --- a/codex-rs/tui/src/markdown_render.rs +++ b/codex-rs/tui/src/markdown_render.rs @@ -81,6 +81,9 @@ use unicode_segmentation::UnicodeSegmentation; mod inline_directives; mod list_spacing; mod local_links; +pub(crate) use local_links::FileLink; +pub(crate) use local_links::SourceLocation; +pub(crate) use local_links::is_markdown_file; mod math; mod mermaid; pub(crate) mod preferences; @@ -2411,12 +2414,12 @@ impl<'a, 'policy> Writer<'a, 'policy> { } } - fn label_document_path(&self) -> Option { + 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 { + fn document_label_span(&self, span: Span<'static>, path: FileLink) -> HyperlinkLine { let width = span_width(&span); let mut line = HyperlinkLine::new(Line::from(span)); let mut link = TerminalHyperlink::document(0..width, path); @@ -2427,12 +2430,12 @@ impl<'a, 'policy> Writer<'a, 'policy> { 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) { + if let Some(link) = local_links::sidebar_file_link(destination) { let width = span_width(&span); target.line.push_span(span); target .hyperlinks - .push(TerminalHyperlink::document(0..width, path)); + .push(TerminalHyperlink::document(0..width, link)); } else { target.push_span(span, Some(destination)); } diff --git a/codex-rs/tui/src/markdown_render/local_links.rs b/codex-rs/tui/src/markdown_render/local_links.rs index 6ff2f30e6a..0c6919f047 100644 --- a/codex-rs/tui/src/markdown_render/local_links.rs +++ b/codex-rs/tui/src/markdown_render/local_links.rs @@ -27,24 +27,53 @@ static HASH_LOCATION_SUFFIX_RE: LazyLock = Err(error) => panic!("invalid hash location regex: {error}"), }); -pub(crate) fn sidebar_file_link(destination: &str) -> Option { - if destination.len() > 8192 || destination.contains(['#', '?']) { +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub(crate) struct SourceLocation { + pub(crate) line: usize, + pub(crate) column: usize, +} + +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub(crate) struct FileLink { + pub(crate) path: String, + pub(crate) location: Option, +} + +pub(crate) fn is_markdown_file(path: &str) -> bool { + path.rsplit_once('.').is_some_and(|(_, ext)| { + ext.eq_ignore_ascii_case("md") || ext.eq_ignore_ascii_case("markdown") + }) +} + +pub(crate) fn sidebar_file_link(destination: &str) -> Option { + if destination.len() > 8192 || destination.contains('?') { return None; } if destination.starts_with("file://") && Url::parse(destination).ok()?.has_host() { return None; } let (path, location) = parse_local_link_target(destination)?; - let extension = path.rsplit_once('.')?.1; - (location.is_none() - && (extension.eq_ignore_ascii_case("md") || extension.eq_ignore_ascii_case("markdown")) + if destination.contains('#') && location.is_none() { + return None; + } + let location = if let Some(suffix) = location { + let start = suffix.strip_prefix(':')?.split(['-', '–']).next()?; + let (line, column) = start.split_once(':').unwrap_or((start, "1")); + Some(SourceLocation { + line: line.parse::().ok()?.max(1), + column: column.parse::().ok()?.max(1), + }) + } else { + None + }; + (!path.is_empty() + && !path.ends_with('/') && path.len() <= 4096 && !path.starts_with('~') && !path.starts_with("//") && !path.chars().any(char::is_control) - && (is_absolute_local_link_path(&path) || Url::parse(&path).is_err()) - && (is_local_path_like_link(destination) || Url::parse(destination).is_err())) - .then_some(path) + && (is_absolute_local_link_path(&path) || Url::parse(&path).is_err())) + .then_some(FileLink { path, location }) } pub(super) fn is_local_path_like_link(dest_url: &str) -> bool { diff --git a/codex-rs/tui/src/markdown_render/local_links_tests.rs b/codex-rs/tui/src/markdown_render/local_links_tests.rs index c6ed70bfc9..57b66793f8 100644 --- a/codex-rs/tui/src/markdown_render/local_links_tests.rs +++ b/codex-rs/tui/src/markdown_render/local_links_tests.rs @@ -1,5 +1,8 @@ //! Tests for local-link parsing and root-preserving separator normalization. +use super::FileLink; +use super::SourceLocation; +use super::sidebar_file_link; use super::trim_trailing_local_path_separator; use pretty_assertions::assert_eq; @@ -11,3 +14,27 @@ fn trailing_separator_trimming_preserves_local_roots() { ["/", "//", "C:/", "dir", "//server/share", "C:/dir"] ); } + +#[test] +fn sidebar_keeps_line_and_column_for_extensionless_source_links() { + assert_eq!( + sidebar_file_link("./Makefile#L12C3"), + Some(FileLink { + path: "./Makefile".into(), + location: Some(SourceLocation { + line: 12, + column: 3 + }), + }), + ); + for path in ["Makefile", "build/Makefile"] { + assert_eq!( + sidebar_file_link(path), + Some(FileLink { + path: path.into(), + location: None, + }), + ); + } + assert_eq!(sidebar_file_link("https://example.org/Makefile#L12"), None); +} diff --git a/codex-rs/tui/src/markdown_render/preferences.rs b/codex-rs/tui/src/markdown_render/preferences.rs index 464b13ace1..28163f92ec 100644 --- a/codex-rs/tui/src/markdown_render/preferences.rs +++ b/codex-rs/tui/src/markdown_render/preferences.rs @@ -41,3 +41,52 @@ pub(crate) fn current() -> TuiRendering { #[cfg(test)] #[path = "preferences_tests.rs"] mod tests; +// Shared by the streaming and replay renderers for this TUI session. +#[cfg(not(test))] +static DOCUMENT_LINKS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +#[cfg(test)] +thread_local! { + static DOCUMENT_LINKS: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +pub(crate) fn set_document_links(enabled: bool) { + #[cfg(not(test))] + DOCUMENT_LINKS.store(enabled, std::sync::atomic::Ordering::Relaxed); + #[cfg(test)] + DOCUMENT_LINKS.set(enabled); +} + +thread_local! { + static SHOW_LOCAL_PATHS: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +pub(crate) fn with_visible_local_paths(render: impl FnOnce() -> T) -> T { + struct Restore<'a>(&'a std::cell::Cell, bool); + + impl Drop for Restore<'_> { + fn drop(&mut self) { + self.0.set(self.1); + } + } + + SHOW_LOCAL_PATHS.with(|show| { + let _restore = Restore(show, show.replace(true)); + render() + }) +} + +pub(crate) fn hide_transcript_destination(destination: &str) -> bool { + if document_links_enabled() { + super::hide_reader_link_destination(destination) + } else { + super::hide_web_link_destination(destination) + } +} + +pub(crate) fn document_links_enabled() -> bool { + #[cfg(not(test))] + let documents = DOCUMENT_LINKS.load(std::sync::atomic::Ordering::Relaxed); + #[cfg(test)] + let documents = DOCUMENT_LINKS.get(); + documents && !SHOW_LOCAL_PATHS.get() +} 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 a9b4db31f7..0e682444b8 100644 --- a/codex-rs/tui/src/markdown_render/web_links_tests.rs +++ b/codex-rs/tui/src/markdown_render/web_links_tests.rs @@ -201,6 +201,7 @@ fn empty_reader_local_links_keep_a_visible_destination() { for markdown in [ "[](empty.md)", "[](./empty.md)", + "[](src/empty.md#L42)", "[ ](./empty.md)", "[\u{200d}](./empty.md)", ] { diff --git a/codex-rs/tui/src/streaming/render_tests.rs b/codex-rs/tui/src/streaming/render_tests.rs index 255399bc00..794e81ddfe 100644 --- a/codex-rs/tui/src/streaming/render_tests.rs +++ b/codex-rs/tui/src/streaming/render_tests.rs @@ -138,7 +138,23 @@ fn incremental_file_citations_preserve_metadata_unicode_and_markdown() { render.lines }); - assert_debug_snapshot!("incremental_file_citations", rendered_cases); + assert_eq!( + rendered_cases.each_ref().map(|lines| lines + .iter() + .flat_map(|line| &line.hyperlinks) + .map(|link| link.reader_destination(/*documents*/ true)) + .collect::>()), + ["Quarterly Report.xlsx", "Résumé *final* ✨.xlsx"].map(|name| vec![Some( + crate::terminal_hyperlinks::ReaderLink::Document(crate::markdown_render::FileLink { + path: cwd.join(name).to_string_lossy().replace('\\', "/"), + location: None, + }) + )]) + ); + assert_debug_snapshot!( + "incremental_file_citations", + rendered_cases.map(visible_lines) + ); } #[test] diff --git a/codex-rs/tui/src/streaming/snapshots/codex_tui__streaming__render__tests__incremental_file_citations.snap b/codex-rs/tui/src/streaming/snapshots/codex_tui__streaming__render__tests__incremental_file_citations.snap index 8b48d83117..c416a72c8e 100644 --- a/codex-rs/tui/src/streaming/snapshots/codex_tui__streaming__render__tests__incremental_file_citations.snap +++ b/codex-rs/tui/src/streaming/snapshots/codex_tui__streaming__render__tests__incremental_file_citations.snap @@ -1,62 +1,32 @@ --- source: tui/src/streaming/render_tests.rs -expression: rendered_cases +expression: rendered_cases.map(visible_lines) --- [ [ - HyperlinkLine { - line: Line::from_iter([ - Span::from("# ").fg(Color::Rgb(243, 139, 168)).bold().underlined(), - Span::from("Output").fg(Color::Rgb(243, 139, 168)).bold().underlined(), - ]), - hyperlinks: [], - }, - HyperlinkLine { - line: Line::default(), - hyperlinks: [], - }, - HyperlinkLine { - line: Line::from_iter([ - Span::from("• ").fg(Color::Rgb(148, 226, 213)), - Span::from("Quarterly Report.xlsx").fg(Color::Rgb(166, 227, 161)), - ]), - hyperlinks: [], - }, - HyperlinkLine { - line: Line::default(), - hyperlinks: [], - }, - HyperlinkLine { - line: Line::from("Continue."), - hyperlinks: [], - }, + Line::from_iter([ + Span::from("# ").fg(Color::Rgb(243, 139, 168)).bold().underlined(), + Span::from("Output").fg(Color::Rgb(243, 139, 168)).bold().underlined(), + ]), + Line::default(), + Line::from_iter([ + Span::from("• ").fg(Color::Rgb(148, 226, 213)), + Span::from("Quarterly Report.xlsx").fg(Color::Rgb(166, 227, 161)), + ]), + Line::default(), + Line::from("Continue."), ], [ - HyperlinkLine { - line: Line::from_iter([ - Span::from("# ").fg(Color::Rgb(243, 139, 168)).bold().underlined(), - Span::from("Output").fg(Color::Rgb(243, 139, 168)).bold().underlined(), - ]), - hyperlinks: [], - }, - HyperlinkLine { - line: Line::default(), - hyperlinks: [], - }, - HyperlinkLine { - line: Line::from_iter([ - Span::from("• ").fg(Color::Rgb(148, 226, 213)), - Span::from("Résumé *final* ✨.xlsx").fg(Color::Rgb(166, 227, 161)), - ]), - hyperlinks: [], - }, - HyperlinkLine { - line: Line::default(), - hyperlinks: [], - }, - HyperlinkLine { - line: Line::from("Continue."), - hyperlinks: [], - }, + Line::from_iter([ + Span::from("# ").fg(Color::Rgb(243, 139, 168)).bold().underlined(), + Span::from("Output").fg(Color::Rgb(243, 139, 168)).bold().underlined(), + ]), + Line::default(), + Line::from_iter([ + Span::from("• ").fg(Color::Rgb(148, 226, 213)), + Span::from("Résumé *final* ✨.xlsx").fg(Color::Rgb(166, 227, 161)), + ]), + Line::default(), + Line::from("Continue."), ], ] diff --git a/codex-rs/tui/src/terminal_hyperlinks.rs b/codex-rs/tui/src/terminal_hyperlinks.rs index 3d59f2e139..682d6d503b 100644 --- a/codex-rs/tui/src/terminal_hyperlinks.rs +++ b/codex-rs/tui/src/terminal_hyperlinks.rs @@ -33,6 +33,8 @@ use unicode_segmentation::UnicodeSegmentation; use url::Url; use crate::line_truncation::line_width; +use crate::markdown_render::FileLink; +use crate::markdown_render::SourceLocation; use crate::render::line_utils::line_to_borrowed; use crate::render::line_utils::line_to_static; use crate::width::display_width; @@ -76,7 +78,22 @@ enum DestinationKind { /// A generated visualization, validated workspace artifact, or locally viewed image. TrustedFile, /// A local document target used only by an enabled workspace transcript. - Document, + Document(Option), +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub(crate) enum ReaderLink { + External(String), + Document(FileLink), +} + +impl ReaderLink { + pub(crate) fn into_destination(self) -> String { + match self { + Self::External(url) => url, + Self::Document(link) => link.path, + } + } } /// An existing, inert source file proven to remain inside its session workspace. @@ -185,24 +202,27 @@ impl TerminalHyperlink { } } - pub(crate) fn document(columns: Range, path: String) -> Self { + pub(crate) fn document(columns: Range, link: FileLink) -> Self { Self { columns, - destination: path, - destination_kind: DestinationKind::Document, + destination: link.path, + destination_kind: DestinationKind::Document(link.location), markdown_source: None, } } pub(crate) fn is_document(&self) -> bool { - self.destination_kind == DestinationKind::Document + matches!(self.destination_kind, DestinationKind::Document(_)) } - pub(crate) fn reader_destination(&self, documents: bool) -> Option { - if documents && self.is_document() { - Some(self.destination.clone()) + pub(crate) fn reader_destination(&self, documents: bool) -> Option { + if documents && let DestinationKind::Document(location) = self.destination_kind { + Some(ReaderLink::Document(FileLink { + path: self.destination.clone(), + location, + })) } else { - self.terminal_destination() + self.terminal_destination().map(ReaderLink::External) } } @@ -217,7 +237,7 @@ impl TerminalHyperlink { pub(crate) fn terminal_destination(&self) -> Option { match self.destination_kind { - DestinationKind::Document => None, + DestinationKind::Document(_) => None, DestinationKind::Web => web_destination(&self.destination), DestinationKind::TrustedFile => trusted_file_destination(&self.destination), } diff --git a/codex-rs/tui/src/transcript_view.rs b/codex-rs/tui/src/transcript_view.rs index 05b9cf2cba..51565637b0 100644 --- a/codex-rs/tui/src/transcript_view.rs +++ b/codex-rs/tui/src/transcript_view.rs @@ -10,6 +10,7 @@ mod bookmark; mod composer_gap; mod copy_mode; mod disclosure; +mod document; mod follow_control; mod footer; mod input; @@ -31,8 +32,10 @@ use crate::history_cell::HistoryCell; use crate::history_cell::HistoryRenderMode; use crate::pager_overlay::TranscriptHistoryState; use crate::terminal_hyperlinks::HyperlinkLine; +use crate::terminal_hyperlinks::TerminalHyperlink; use crate::tui::SelectionCopy; use ratatui::buffer::Buffer; +use ratatui::layout::Position as ScreenPosition; use ratatui::layout::Rect; use ratatui::style::Stylize; use ratatui::text::Line; @@ -345,24 +348,58 @@ 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; + pub(crate) fn has_document_link_at(&self, pointer: ScreenPosition) -> bool { + self.document_links + && self + .raw_link_at(pointer) + .is_some_and(|(_, link)| link.is_document()) + } + + fn raw_link_at(&self, pointer: ScreenPosition) -> Option<(&VisibleRow, &TerminalHyperlink)> { + if !self.area.contains(pointer) { + return None; } - 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()); + let row = self.visible.get(usize::from(pointer.y - self.area.y))?; + let link = row.layout.raw_link_at(row.row, pointer.x - self.area.x)?; + Some((row, link)) + } + + pub(crate) fn paint_document_links(&self, buf: &mut Buffer, pointer: Option) { + let Some((hit_row, hit_link)) = pointer + .filter(|_| self.document_links && !self.has_active_interaction()) + .and_then(|pointer| self.raw_link_at(pointer)) + .filter(|(_, link)| link.is_document()) + else { + return; + }; + for (y, row) in (self.area.top()..self.area.bottom()).zip(&self.visible) { + if row.key != hit_row.key { + continue; + } + let Some((inset, links)) = row.layout.row_links(row.row) else { + continue; + }; + for link in links.iter().filter(|link| link.is_document()) { + if !(std::ptr::eq(hit_link, link) && hit_row.row == row.row + || hit_link.markdown_source.is_some() + && hit_link.markdown_source == link.markdown_source + && hit_link.destination == link.destination) + { + continue; + } + let columns = (inset + link.columns.start) + ..(inset + link.columns.end).min(usize::from(self.area.width)); + if !columns.is_empty() { + buf.set_style( + Rect::new( + self.area.x + columns.start as u16, + y, + columns.len() as u16, + 1, + ), + ratatui::style::Style::default().bold(), + ); + } } } } diff --git a/codex-rs/tui/src/transcript_view/document.rs b/codex-rs/tui/src/transcript_view/document.rs new file mode 100644 index 0000000000..24727a7cdc --- /dev/null +++ b/codex-rs/tui/src/transcript_view/document.rs @@ -0,0 +1,89 @@ +//! Render source locations in the file reader using the transcript's wrapped rows. + +use ratatui::style::Modifier; +use ratatui::style::Stylize; +use ratatui::text::Line; +use ratatui::widgets::Widget; + +use super::*; + +impl TranscriptView { + pub(crate) fn render_document( + &mut self, + area: Rect, + buf: &mut Buffer, + cells: &[Arc], + line_starts: &[usize], + target: Option<(usize, usize)>, + ) { + let digits = line_starts + .len() + .checked_ilog10() + .map_or(0, |n| n as u16 + 1); + let gutter = if digits > 0 && area.width > 40 + digits { + digits + 1 + } else { + 0 + }; + let text = Rect::new(area.x + gutter, area.y, area.width - gutter, area.height); + self.render(text, buf, cells); + if line_starts.is_empty() { + return; + } + for (y, visible) in (area.top()..area.bottom()).zip(&self.visible) { + let offset = visible.layout.position_at(visible.row, /*column*/ 0); + let line = line_starts.partition_point(|start| *start <= offset); + if gutter > 0 && line > 0 && line_starts[line - 1] == offset { + Line::from(line.to_string()) + .dim() + .right_aligned() + .render(Rect::new(area.x, y, digits, /*height*/ 1), buf); + } + if let Some((target_line, target_offset)) = target + && line == target_line + { + let mut style = crate::style::user_message_style(); + if style.bg.is_none() { + style = crate::style::selection_style(); + } + buf.set_style(Rect::new(text.x, y, text.width, /*height*/ 1), style); + if visible.row == visible.layout.row_for_offset(target_offset) { + let x = text + .x + .saturating_add(visible.layout.column_for_offset(target_offset)); + if x < text.right() { + let cell = &mut buf[(x, y)]; + let style = cell.style(); + cell.set_style(if style.add_modifier.contains(Modifier::REVERSED) { + style.not_reversed() + } else { + style.reversed() + }); + } + } + } + } + } + + 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()); + } + } + } +} diff --git a/codex-rs/tui/src/transcript_view/input.rs b/codex-rs/tui/src/transcript_view/input.rs index 53d191b3a6..7598b5e769 100644 --- a/codex-rs/tui/src/transcript_view/input.rs +++ b/codex-rs/tui/src/transcript_view/input.rs @@ -18,6 +18,8 @@ use crossterm::event::MouseEventKind; use ratatui::layout::Position as ScreenPosition; use super::*; +use crate::markdown_render::FileLink; +use crate::terminal_hyperlinks::ReaderLink; pub(crate) enum ViewAction { Changed, @@ -27,6 +29,16 @@ pub(crate) enum ViewAction { PrimarySelection(String), CopyAndFollow(String), OpenLink(String), + OpenDocument(FileLink), +} + +impl From for ViewAction { + fn from(link: ReaderLink) -> Self { + match link { + ReaderLink::External(url) => Self::OpenLink(url), + ReaderLink::Document(link) => Self::OpenDocument(link), + } + } } #[derive(Clone, Copy, PartialEq, Eq)] @@ -106,19 +118,20 @@ impl TranscriptView { | ViewAction::ExitSelectMode | ViewAction::Copy(_) | ViewAction::CopyAndFollow(_) + | ViewAction::OpenDocument(_) | ViewAction::OpenLink(_) => SelectionCopy::EXPLICIT, } } /// 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, self.document_links) + self.reader_link_at(column, row) + .map(ReaderLink::into_destination) + } + + fn reader_link_at(&self, column: u16, row: u16) -> Option { + let (_, link) = self.raw_link_at(ScreenPosition::new(column, row))?; + link.reader_destination(self.document_links) } pub(crate) fn cycle_document_link( @@ -155,7 +168,7 @@ impl TranscriptView { &mut self, cells: &[Arc], index: usize, - ) -> Option { + ) -> Option { self.layout(cells, /*index*/ 0)? .document_links() .into_iter() @@ -477,7 +490,7 @@ impl TranscriptView { None }; let link = link.filter(|destination| { - self.link_at(event.column, event.row).as_ref() == Some(destination) + self.reader_link_at(event.column, event.row).as_ref() == Some(destination) }); if self .selection @@ -492,7 +505,7 @@ impl TranscriptView { self.end_selection(cells); } if let Some(link) = link { - return Some(ViewAction::OpenLink(link)); + return Some(link.into()); } if let Some(text) = selected.filter(|text| !text.is_empty()) { if self.copy_on_select { @@ -605,8 +618,8 @@ impl TranscriptView { .intersects(KeyModifiers::CONTROL | KeyModifiers::SUPER) { return self - .link_at(event.column, event.row) - .map(ViewAction::OpenLink); + .reader_link_at(event.column, event.row) + .map(ViewAction::from); } if event.modifiers == KeyModifiers::SHIFT && self.has_selection_range() { self.last_click = None; @@ -633,7 +646,7 @@ impl TranscriptView { } } let link = (mode == MouseMode::Interactive && clicks == 1 && event.modifiers.is_empty()) - .then(|| self.link_at(event.column, event.row)) + .then(|| self.reader_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 802f45d962..396112392b 100644 --- a/codex-rs/tui/src/transcript_view/input_tests.rs +++ b/codex-rs/tui/src/transcript_view/input_tests.rs @@ -174,6 +174,63 @@ fn hover_links_match_wrapped_click_targets_and_refresh_after_scrolling() { ); } +#[test] +fn workspace_file_links_show_the_title_with_subtle_hover_and_open_the_same_location() { + use crate::markdown_render::FileLink; + use crate::markdown_render::SourceLocation; + use ratatui::style::Modifier; + + crate::markdown_render::preferences::set_document_links(/*enabled*/ true); + let (mut view, cells) = transcript( + "[Guide](./guide.md#L3C2) and [](./guide.md#L3C2)", + /*width*/ 32, + ); + view.document_links = true; + let area = view.area; + let mut idle = Buffer::empty(area); + view.render(area, &mut idle, &cells); + let title = ScreenPosition::new(area.x + 3, area.y); + let path = ScreenPosition::new(area.x + 13, area.y); + let mut observations = vec![ + crate::transcript_view::tests::text(&idle) + .trim() + .to_string(), + ]; + + for (name, point) in [("title", title), ("filename", path)] { + let mut hovered = idle.clone(); + view.paint_document_links(&mut hovered, Some(point)); + observations.push(format!( + "{name}: underline={}, hover bold={}, background unchanged={}", + hovered[point].modifier.contains(Modifier::UNDERLINED), + hovered[point].modifier.contains(Modifier::BOLD), + hovered[point].bg == idle[point].bg, + )); + view.handle_mouse( + mouse(MouseEventKind::Down(MouseButton::Left), point.x, point.y), + &cells, + ); + let Some(ViewAction::OpenDocument(link)) = view.handle_mouse( + mouse(MouseEventKind::Up(MouseButton::Left), point.x, point.y), + &cells, + ) else { + panic!("{name} click should open a document"); + }; + assert_eq!( + link, + FileLink { + path: "./guide.md".to_string(), + location: Some(SourceLocation { line: 3, column: 2 }), + }, + ); + } + insta::assert_snapshot!(observations.join("\n"), @" + • Guide and ./guide.md:3:2 + title: underline=true, hover bold=true, background unchanged=true + filename: underline=false, hover bold=true, background unchanged=true + "); +} + #[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/transcript_view/layout.rs b/codex-rs/tui/src/transcript_view/layout.rs index 1edbd6ee45..6a371b2731 100644 --- a/codex-rs/tui/src/transcript_view/layout.rs +++ b/codex-rs/tui/src/transcript_view/layout.rs @@ -110,6 +110,7 @@ pub(super) struct LayoutCache { #[derive(PartialEq, Eq)] struct RenderState { theme: u64, + document_links: bool, foreground: Option<(u8, u8, u8)>, background: Option<(u8, u8, u8)>, color_level: crate::terminal_palette::StdoutColorLevel, @@ -318,6 +319,7 @@ impl LayoutCache { self.frame = self.frame.wrapping_add(/*rhs*/ 1); let state = RenderState { theme: crate::render::highlight::syntax_theme_revision(), + document_links: crate::markdown_render::preferences::document_links_enabled(), foreground: crate::terminal_palette::default_fg(), background: crate::terminal_palette::default_bg(), color_level: crate::terminal_palette::stdout_color_level(), diff --git a/codex-rs/tui/src/transcript_view/selection.rs b/codex-rs/tui/src/transcript_view/selection.rs index ccfe3475d6..9d05c1c12f 100644 --- a/codex-rs/tui/src/transcript_view/selection.rs +++ b/codex-rs/tui/src/transcript_view/selection.rs @@ -117,7 +117,7 @@ pub(super) struct Selection { pointer_origin_row: u16, pub(super) resume_on_empty: bool, pub(super) pointer: Option, - pub(super) pressed_link: Option, + pub(super) pressed_link: Option, origin: (Anchor, Anchor), table_cell: Option, unit: SelectionUnit, @@ -661,7 +661,10 @@ impl TranscriptView { | ViewAction::CopyOnSelect(text) | ViewAction::PrimarySelection(text) | ViewAction::CopyAndFollow(text) => text.as_str(), - ViewAction::Changed | ViewAction::ExitSelectMode | ViewAction::OpenLink(_) => { + ViewAction::Changed + | ViewAction::ExitSelectMode + | ViewAction::OpenLink(_) + | ViewAction::OpenDocument(_) => { return None; } }; diff --git a/codex-rs/tui/src/transcript_view/text.rs b/codex-rs/tui/src/transcript_view/text.rs index 7ca817fac3..3ab2157758 100644 --- a/codex-rs/tui/src/transcript_view/text.rs +++ b/codex-rs/tui/src/transcript_view/text.rs @@ -32,6 +32,8 @@ use crate::terminal_hyperlinks::HyperlinkLine; use crate::terminal_hyperlinks::HyperlinkParagraph; use crate::terminal_hyperlinks::LineWrapPolicy; use crate::terminal_hyperlinks::LogicalLineSource; +use crate::terminal_hyperlinks::ReaderLink; +use crate::terminal_hyperlinks::TerminalHyperlink; use crate::terminal_hyperlinks::remap_source_wrapped_line; use crate::width::display_width; use crate::wrapping::RtOptions; @@ -847,8 +849,8 @@ impl TextLayout { } } - pub(super) fn document_links(&self) -> Vec<(Range, String)> { - let mut stops: Vec<(Range, String)> = Vec::new(); + pub(super) fn document_links(&self) -> Vec<(Range, ReaderLink)> { + let mut stops: Vec<(Range, ReaderLink)> = Vec::new(); let mut previous_source = None; for (index, row) in self.rows.iter().enumerate() { let inset = row.first_column - row.prefix_columns; @@ -884,14 +886,25 @@ impl TextLayout { } /// 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 { + #[cfg(test)] + pub(super) fn reader_link_at( + &self, + row: usize, + column: u16, + documents: bool, + ) -> Option { + self.raw_link_at(row, column)?.reader_destination(documents) + } + + pub(super) fn raw_link_at(&self, row: usize, column: u16) -> Option<&TerminalHyperlink> { + let (inset, links) = self.row_links(row)?; + let column = usize::from(column).checked_sub(inset)?; + links.iter().find(|link| link.columns.contains(&column)) + } + + pub(super) fn row_links(&self, row: usize) -> Option<(usize, &[TerminalHyperlink])> { let row = self.rows.get(row)?; - let column = usize::from(column).checked_sub(row.first_column - row.prefix_columns)?; - row.line - .hyperlinks - .iter() - .find(|link| link.columns.contains(&column))? - .reader_destination(documents) + Some((row.first_column - row.prefix_columns, &row.line.hyperlinks)) } fn visible_rows(&self, area: Rect, start_row: usize) -> impl Iterator { diff --git a/codex-rs/tui/src/transcript_view/text_tabs_tests.rs b/codex-rs/tui/src/transcript_view/text_tabs_tests.rs index b6b84d3917..f933fc2ac0 100644 --- a/codex-rs/tui/src/transcript_view/text_tabs_tests.rs +++ b/codex-rs/tui/src/transcript_view/text_tabs_tests.rs @@ -36,13 +36,16 @@ fn styled_tabs_use_row_stops_including_the_gutter() { assert_eq!( ( layout - .link_at(/*row*/ 0, /*column*/ 16, /*documents*/ false) + .reader_link_at(/*row*/ 0, /*column*/ 16, /*documents*/ false) + .map(crate::terminal_hyperlinks::ReaderLink::into_destination) .as_deref(), layout - .link_at(/*row*/ 0, /*column*/ 24, /*documents*/ false) + .reader_link_at(/*row*/ 0, /*column*/ 24, /*documents*/ false) + .map(crate::terminal_hyperlinks::ReaderLink::into_destination) .as_deref(), layout - .link_at(/*row*/ 0, /*column*/ 13, /*documents*/ false) + .reader_link_at(/*row*/ 0, /*column*/ 13, /*documents*/ false) + .map(crate::terminal_hyperlinks::ReaderLink::into_destination) .as_deref() ), ( @@ -94,7 +97,8 @@ fn tab_stops_restart_after_wrapping_and_resize_preserves_source_and_links() { ); assert_eq!( layout - .link_at(/*row*/ 1, /*column*/ 8, /*documents*/ false) + .reader_link_at(/*row*/ 1, /*column*/ 8, /*documents*/ false) + .map(crate::terminal_hyperlinks::ReaderLink::into_destination) .as_deref(), Some("https://example.com/x") ); diff --git a/codex-rs/tui/src/transcript_view/text_tests.rs b/codex-rs/tui/src/transcript_view/text_tests.rs index df178e8785..565d24b049 100644 --- a/codex-rs/tui/src/transcript_view/text_tests.rs +++ b/codex-rs/tui/src/transcript_view/text_tests.rs @@ -192,12 +192,13 @@ fn aligned_text_excludes_synthetic_leading_columns() { line.push_span("wide".into(), Some("https://example.com")); let layout = TextLayout::new(vec![line], /*width*/ 8); assert_eq!( - layout.link_at(/*row*/ 0, /*column*/ 3, /*documents*/ false), + layout.reader_link_at(/*row*/ 0, /*column*/ 3, /*documents*/ false), None ); assert_eq!( layout - .link_at(/*row*/ 0, /*column*/ 4, /*documents*/ false) + .reader_link_at(/*row*/ 0, /*column*/ 4, /*documents*/ false) + .map(crate::terminal_hyperlinks::ReaderLink::into_destination) .as_deref(), Some("https://example.com") ); @@ -271,7 +272,8 @@ fn selected_revision_rewraps_both_directions_with_styles_and_indents() { restored.render(narrow_area, &mut restored_buffer, /*start_row*/ 0); assert_eq!(restored_buffer, original_buffer); assert_eq!( - wide.link_at(/*row*/ 0, /*column*/ 8, /*documents*/ false) + wide.reader_link_at(/*row*/ 0, /*column*/ 8, /*documents*/ false) + .map(crate::terminal_hyperlinks::ReaderLink::into_destination) .as_deref(), Some("https://example.com") ); @@ -445,7 +447,11 @@ fn rendered_markdown_file_targets_are_only_interactive_in_the_workspace() { let layout = &layout; (0..layout.row_count()) .flat_map(|row| { - (0..40).filter_map(move |column| layout.link_at(row, column, documents)) + (0..40).filter_map(move |column| { + layout + .reader_link_at(row, column, documents) + .map(crate::terminal_hyperlinks::ReaderLink::into_destination) + }) }) .collect::>() };