From f0c0f0a14ddd9b05b7a85daddc4360ad8a8d2d2b Mon Sep 17 00:00:00 2001 From: Eric Traut Date: Wed, 25 Nov 2026 02:15:58 +0000 Subject: [PATCH] Render bidirectional transcript text on terminals without native ordering (#63844) ## Why Terminals that leave bidirectional ordering to the application can display Arabic and Hebrew transcript text in the wrong order, especially when it includes URLs, numbers, or inline code. ## What changed Use the terminal's bidirectional mode report when available on a direct connection, with a fallback for Windows Terminal, Ghostty, and Alacritty. Resolve direction before wrapping and reorder graphemes for display in the live transcript and scrollback. Preserve styling, hyperlink destinations, and logical text for copying. Keep URLs and inline literals left to right, and skip reordering for code blocks, tables, and lines with shell syntax that could be misrepresented. Measure hyperlink columns by painted graphemes so Arabic ligatures do not shift clickable ranges in the transcript or composer. ## Testing Cover agreement between streaming and finalized scrollback, preservation of shell command boundaries, startup probe reply handling, and wrapped composer links following Arabic text. GitOrigin-RevId: 9ffa0f491a93c78fef423acfc6a951cb037abd4d --- codex-rs/Cargo.lock | 1 + codex-rs/Cargo.toml | 1 + codex-rs/tui/Cargo.toml | 1 + codex-rs/tui/src/app.rs | 1 + .../src/bottom_pane/textarea/hyperlinks.rs | 6 +- .../bottom_pane/textarea/hyperlinks_tests.rs | 2 +- codex-rs/tui/src/chatwidget.rs | 1 + codex-rs/tui/src/chatwidget/constructor.rs | 1 + codex-rs/tui/src/chatwidget/rendering.rs | 9 +- .../tui/src/chatwidget/rendering_tests.rs | 1 + codex-rs/tui/src/custom_terminal.rs | 2 + codex-rs/tui/src/history_cell/messages.rs | 11 +- codex-rs/tui/src/insert_history.rs | 60 ++++++- codex-rs/tui/src/markdown_copy.rs | 2 +- ...t_stream_matches_finalized_scrollback.snap | 6 + codex-rs/tui/src/terminal_capabilities.rs | 40 ++++- .../terminal_capabilities/terminal_probe.rs | 21 ++- .../terminal_probe/startup_replay.rs | 21 ++- .../terminal_probe/startup_replay_tests.rs | 31 +++- codex-rs/tui/src/terminal_hyperlinks.rs | 68 +++++--- codex-rs/tui/src/terminal_hyperlinks/bidi.rs | 162 ++++++++++++++++++ .../tui/src/terminal_hyperlinks/source.rs | 7 + .../tui/src/transcript_view/text_logical.rs | 8 +- .../tui/src/transcript_view/text_tests.rs | 28 +++ codex-rs/tui/src/tui.rs | 5 + 25 files changed, 442 insertions(+), 54 deletions(-) create mode 100644 codex-rs/tui/src/snapshots/codex_tui__insert_history__tests__rtl_transcript_stream_matches_finalized_scrollback.snap create mode 100644 codex-rs/tui/src/terminal_hyperlinks/bidi.rs diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 4e805e785b..1c7ee1dbb2 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -5444,6 +5444,7 @@ dependencies = [ "dunce", "futures", "http 1.4.0", + "icu_properties", "image", "insta", "itertools 0.14.0", diff --git a/codex-rs/Cargo.toml b/codex-rs/Cargo.toml index b0e7ce617b..4431cecc3b 100644 --- a/codex-rs/Cargo.toml +++ b/codex-rs/Cargo.toml @@ -431,6 +431,7 @@ iana-time-zone = "0.1.64" icu_decimal = "2.1" icu_locale_core = "2.1" icu_provider = { version = "2.1", features = ["sync"] } +icu_properties = "2.2" ignore = "0.4.30" image = { version = "^0.25.9", default-features = false } include_dir = "0.7.4" diff --git a/codex-rs/tui/Cargo.toml b/codex-rs/tui/Cargo.toml index 33a4789ca9..a5269e7d60 100644 --- a/codex-rs/tui/Cargo.toml +++ b/codex-rs/tui/Cargo.toml @@ -88,6 +88,7 @@ diffy = { workspace = true } dirs = { workspace = true } dunce = { workspace = true } http = { workspace = true } +icu_properties = { workspace = true } image = { workspace = true, features = ["jpeg", "png", "gif", "webp"] } itertools = { workspace = true } lazy_static = { workspace = true } diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index 63fc8b10e8..72df94b2bf 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -1600,6 +1600,7 @@ impl App { } fn render_chat_widget_frame(&mut self, tui: &mut tui::Tui, screen_size: Size) -> Result { + self.chat_widget.bidi_layout = tui.terminal.bidi_layout; self.chat_widget .set_sparkle_terminal_focus(tui.is_terminal_focused()); if tui.is_owned_screen() { diff --git a/codex-rs/tui/src/bottom_pane/textarea/hyperlinks.rs b/codex-rs/tui/src/bottom_pane/textarea/hyperlinks.rs index afd1c87820..34e46d063f 100644 --- a/codex-rs/tui/src/bottom_pane/textarea/hyperlinks.rs +++ b/codex-rs/tui/src/bottom_pane/textarea/hyperlinks.rs @@ -5,8 +5,8 @@ use super::wrapping::visible_prefix; use crate::terminal_hyperlinks::HyperlinkLine; use crate::terminal_hyperlinks::TerminalHyperlink; use crate::terminal_hyperlinks::mark_buffer_hyperlinks; +use crate::terminal_hyperlinks::source_text_width; use crate::terminal_hyperlinks::web_links_in_text; -use crate::width::display_width; use ratatui::buffer::Buffer; use ratatui::layout::Rect; use ratatui::text::Line; @@ -33,7 +33,7 @@ impl HyperlinkCache { let source_columns = lines .iter() .map(|line| { - source_column += display_width(&display_text[previous_start..line.start]); + source_column += source_text_width(&display_text[previous_start..line.start]); previous_start = line.start; source_column }) @@ -66,7 +66,7 @@ impl HyperlinkCache { area.width, ); let visible = text_for_display(raw_visible); - let line_end = source_column + display_width(visible.as_ref()); + let line_end = source_column + source_text_width(visible.as_ref()); let first_hyperlink = self .hyperlinks .partition_point(|hyperlink| hyperlink.columns.end <= source_column); diff --git a/codex-rs/tui/src/bottom_pane/textarea/hyperlinks_tests.rs b/codex-rs/tui/src/bottom_pane/textarea/hyperlinks_tests.rs index e9b8c67ba8..a401c4878e 100644 --- a/codex-rs/tui/src/bottom_pane/textarea/hyperlinks_tests.rs +++ b/codex-rs/tui/src/bottom_pane/textarea/hyperlinks_tests.rs @@ -138,7 +138,7 @@ fn composer_wrapped_url_fragments_keep_the_complete_destination() { #[test] fn scrolled_url_fragments_keep_the_offscreen_destination() { let url = "https://example.test/alpha/beta/gamma/delta/epsilon"; - let (_, state, buf) = render(url, /*width*/ 16, /*height*/ 2); + let (_, state, buf) = render(&format!("لا\n{url}"), /*width*/ 16, /*height*/ 2); let visible_url = linked_text(&assert_destination(&buf, url)); assert!(state.scroll > 0); assert_ne!(visible_url, url); diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 4ee4e8b927..5f887a5a9d 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -536,6 +536,7 @@ pub(crate) enum ExternalEditorState { /// (which view gets Ctrl+C), while `ChatWidget` owns process-level decisions such as interrupting /// active work, arming the double-press quit shortcut, and requesting shutdown-first exit. pub(crate) struct ChatWidget { + pub(crate) bidi_layout: bool, pub(crate) empty_state_animation: std::cell::RefCell, pub(crate) daybreak_enabled: bool, diff --git a/codex-rs/tui/src/chatwidget/constructor.rs b/codex-rs/tui/src/chatwidget/constructor.rs index 61ff16af4f..7991c5fc79 100644 --- a/codex-rs/tui/src/chatwidget/constructor.rs +++ b/codex-rs/tui/src/chatwidget/constructor.rs @@ -124,6 +124,7 @@ impl ChatWidget { effects: local_settings.tui.effects, skills: None, }), + bidi_layout: false, transcript: TranscriptState::new(active_cell), raw_output_mode: local_settings.tui.raw_output_mode, config, diff --git a/codex-rs/tui/src/chatwidget/rendering.rs b/codex-rs/tui/src/chatwidget/rendering.rs index 067bf7c440..7b9214a332 100644 --- a/codex-rs/tui/src/chatwidget/rendering.rs +++ b/codex-rs/tui/src/chatwidget/rendering.rs @@ -266,6 +266,7 @@ impl ChatWidget { let active_cell_right_reserve = self.ambient_pet_wrap_reserved_cols(); let active_cell_renderable = match &self.transcript.active_cell { Some(cell) => RenderableItem::Owned(Box::new(TranscriptAreaRenderable { + bidi_layout: self.bidi_layout, child: cell.as_ref(), // The initial header becomes the first history cell, which has no leading separator. top: if cell.as_any().is::() { @@ -300,6 +301,7 @@ impl ChatWidget { flex.push( /*flex*/ 1, RenderableItem::Owned(Box::new(TranscriptAreaRenderable { + bidi_layout: self.bidi_layout, child: cell.as_ref(), top: 1, right: active_cell_right_reserve, @@ -312,6 +314,7 @@ impl ChatWidget { flex.push( /*flex*/ 1, RenderableItem::Owned(Box::new(TranscriptAreaRenderable { + bidi_layout: self.bidi_layout, child: cell, top: 1, right: active_cell_right_reserve, @@ -466,6 +469,7 @@ impl ChatWidget { } struct TranscriptAreaRenderable<'a> { + bidi_layout: bool, child: &'a dyn HistoryCell, top: u16, right: u16, @@ -482,7 +486,10 @@ struct PersistentActiveCellLayout<'a> { impl Renderable for TranscriptAreaRenderable<'_> { fn render(&self, area: Rect, buf: &mut Buffer) { let area = self.child_area(area); - let lines = self.child.display_hyperlink_lines(area.width); + let mut lines = self.child.display_hyperlink_lines(area.width); + if self.bidi_layout { + crate::terminal_hyperlinks::bidi::paint_rows(&mut lines, usize::from(area.width)); + } let paragraph = HyperlinkParagraph::new(&lines, Style::default()); let y = if area.height == 0 { 0 diff --git a/codex-rs/tui/src/chatwidget/rendering_tests.rs b/codex-rs/tui/src/chatwidget/rendering_tests.rs index e29f9c2d48..3231d92da8 100644 --- a/codex-rs/tui/src/chatwidget/rendering_tests.rs +++ b/codex-rs/tui/src/chatwidget/rendering_tests.rs @@ -314,6 +314,7 @@ fn active_transcript_preserves_clipped_markdown_hyperlinks() { std::path::Path::new("/tmp"), ); let renderable = TranscriptAreaRenderable { + bidi_layout: false, child: &cell, top: 1, right: 2, diff --git a/codex-rs/tui/src/custom_terminal.rs b/codex-rs/tui/src/custom_terminal.rs index f75485b37c..edf53a8863 100644 --- a/codex-rs/tui/src/custom_terminal.rs +++ b/codex-rs/tui/src/custom_terminal.rs @@ -147,6 +147,7 @@ where /// The backend used to interface with the terminal backend: B, pub(crate) virtual_image_base: Option, + pub(crate) bidi_layout: bool, /// Holds the results of the current and previous draw calls. The two are compared at the end /// of each draw pass to output the necessary updates to the terminal buffers: [Buffer; 2], @@ -240,6 +241,7 @@ where Self { backend, virtual_image_base: None, + bidi_layout: false, buffers: [Buffer::empty(Rect::ZERO), Buffer::empty(Rect::ZERO)], current: 0, hidden_cursor: false, diff --git a/codex-rs/tui/src/history_cell/messages.rs b/codex-rs/tui/src/history_cell/messages.rs index 7287cd321e..8710029837 100644 --- a/codex-rs/tui/src/history_cell/messages.rs +++ b/codex-rs/tui/src/history_cell/messages.rs @@ -330,6 +330,7 @@ impl HistoryCell for UserHistoryCell { source.right_reserve = 1; source.copy_as_prose |= copy_as_prose; } + crate::terminal_hyperlinks::bidi::prepare_message(&mut lines); lines } @@ -522,7 +523,8 @@ impl AgentMessageCell { } } - pub(crate) fn new_hyperlink_lines(lines: Vec, is_first_line: bool) -> Self { + pub(crate) fn new_hyperlink_lines(mut lines: Vec, is_first_line: bool) -> Self { + crate::terminal_hyperlinks::bidi::prepare_message(&mut lines); Self { lines, is_first_line, @@ -761,7 +763,9 @@ impl AgentMarkdownCell { markdown, ) }; - normalize_whitespace_only_hyperlink_lines(lines) + let mut lines = normalize_whitespace_only_hyperlink_lines(lines); + crate::terminal_hyperlinks::bidi::prepare_message(&mut lines); + lines }; if let Some(rendered_lines) = &self.rendered_lines { @@ -825,7 +829,8 @@ impl PartialEq for StreamingAgentTailCell { } impl StreamingAgentTailCell { - pub(crate) fn new(lines: Vec, is_first_line: bool) -> Self { + pub(crate) fn new(mut lines: Vec, is_first_line: bool) -> Self { + crate::terminal_hyperlinks::bidi::prepare_message(&mut lines); Self { lines, is_first_line, diff --git a/codex-rs/tui/src/insert_history.rs b/codex-rs/tui/src/insert_history.rs index f02e311225..30d0620232 100644 --- a/codex-rs/tui/src/insert_history.rs +++ b/codex-rs/tui/src/insert_history.rs @@ -132,7 +132,10 @@ where // - Non-URL lines also flow through adaptive wrapping; behavior is // equivalent to standard wrapping when no URL is present. let wrap_width = area.width.max(1) as usize; - let (wrapped, wrapped_rows) = wrap_history_hyperlink_lines(lines, wrap_width, wrap_policy); + let (mut wrapped, wrapped_rows) = wrap_history_hyperlink_lines(lines, wrap_width, wrap_policy); + if terminal.bidi_layout { + crate::terminal_hyperlinks::bidi::paint_rows(&mut wrapped, wrap_width); + } let wrapped_lines = wrapped_rows as u16; match mode { InsertHistoryMode::FullScreen => { @@ -951,6 +954,61 @@ mod tests { }); } + #[test] + fn rtl_transcript_stream_matches_finalized_scrollback() { + use crate::history_cell::AgentMarkdownCell; + use crate::history_cell::HistoryCell; + use crate::history_cell::HistoryRenderMode; + use crate::history_cell::StreamingAgentTailCell; + use crate::history_cell::new_user_prompt; + use crate::streaming::controller::StreamController; + use crate::terminal_hyperlinks::bidi; + use pretty_assertions::assert_eq; + let cwd = std::path::Path::new("."); + let width = 48; + let mut stream = + StreamController::new(Some(usize::from(width) - 2), cwd, HistoryRenderMode::Rich); + stream.push("افتح `--file.rs` ثم ش"); + stream.push("غل Codex 123 (مَرْحَبًا)"); + let preview = stream.current_tail_lines(); + let tail = StreamingAgentTailCell::new(preview, stream.tail_starts_stream()); + let mut live = tail.display_hyperlink_lines(width); + bidi::paint_rows(&mut live, width.into()); + let (committed, source) = stream.finalize(); + let finalized = AgentMarkdownCell::new(source.unwrap(), cwd); + let question = "مرحبا https://example.org/?a=1&b=2#help"; + let prompt = new_user_prompt(question.into(), vec![], vec![], vec![]); + let mut lines = prompt.display_hyperlink_lines(width); + lines.extend(committed.unwrap().display_hyperlink_lines(width)); + lines.extend(finalized.display_hyperlink_lines(width)); + let backend = VT100Backend::new(width, /*height*/ 12); + let mut term = crate::custom_terminal::Terminal::with_options(backend).unwrap(); + term.bidi_layout = true; + term.set_viewport_area(Rect::new( + /*x*/ 0, /*y*/ 11, width, /*height*/ 1, + )); + let size = term.last_known_screen_size; + insert_history_hyperlink_lines_with_mode_and_wrap_policy( + &mut term, + &lines, + InsertHistoryMode::Standard, + HistoryLineWrapPolicy::PreWrap, + size, + ) + .unwrap(); + let rows = term + .backend() + .vt100() + .screen() + .rows(/*start*/ 0, width) + .filter(|row| !row.trim().is_empty()) + .collect::>(); + assert_eq!(rows.len(), 3); + assert_eq!(rows[1], rows[2]); + assert_eq!(live[0].line.to_string(), rows[1]); + insta::assert_snapshot!(rows[..2].join("\n")); + } + #[test] fn vt100_user_message_url_wrap_preserves_gutter_and_background() { use crate::history_cell::HistoryCell; diff --git a/codex-rs/tui/src/markdown_copy.rs b/codex-rs/tui/src/markdown_copy.rs index d9539463e5..a30cb045c8 100644 --- a/codex-rs/tui/src/markdown_copy.rs +++ b/codex-rs/tui/src/markdown_copy.rs @@ -136,7 +136,7 @@ pub(crate) struct CopyLine { /// A visual separator inserted between sibling list items, never source content. pub(crate) omit: bool, runs: Vec<(Range, Vec)>, - literal_ranges: Vec>, + pub(crate) literal_ranges: Vec>, } /// Keep literal prompt spacing when parsing only changed whitespace, and retain the source diff --git a/codex-rs/tui/src/snapshots/codex_tui__insert_history__tests__rtl_transcript_stream_matches_finalized_scrollback.snap b/codex-rs/tui/src/snapshots/codex_tui__insert_history__tests__rtl_transcript_stream_matches_finalized_scrollback.snap new file mode 100644 index 0000000000..70c56e043c --- /dev/null +++ b/codex-rs/tui/src/snapshots/codex_tui__insert_history__tests__rtl_transcript_stream_matches_finalized_scrollback.snap @@ -0,0 +1,6 @@ +--- +source: tui/src/insert_history.rs +expression: "rows[..2].join(\"\\n\")" +--- +› ابحرم https://example.org/?a=1&b=2#help +• (ابًحَرْمَ) Codex 123 لغش مث --file.rs حتفا diff --git a/codex-rs/tui/src/terminal_capabilities.rs b/codex-rs/tui/src/terminal_capabilities.rs index c666062313..ab1215caea 100644 --- a/codex-rs/tui/src/terminal_capabilities.rs +++ b/codex-rs/tui/src/terminal_capabilities.rs @@ -85,6 +85,38 @@ fn zellij_session() -> bool { .any(|key| std::env::var_os(key).is_some()) } +fn direct_stdout() -> bool { + std::io::stdout().is_terminal() && !screen_active() +} + +fn is_direct_terminal(terminal: &TerminalInfo, term: Option<&str>) -> bool { + terminal.multiplexer.is_none() + && !term.is_some_and(|term| { + term == "dumb" || term.starts_with("screen") || term.starts_with("tmux") + }) +} + +fn direct_terminal_name() -> Option { + let terminal = terminal_info(); + (direct_stdout() && is_direct_terminal(&terminal, std::env::var("TERM").ok().as_deref())) + .then_some(terminal.name) +} + +/// A terminal's explicit bidi mode overrides assumptions about its renderer. +/// Silence or an unrecognized mode alone cannot rule out native or partial RTL. +pub(crate) fn needs_bidi_layout(implicit_bidi: Option) -> bool { + let Some(name) = direct_terminal_name() else { + return false; + }; + if let Some(implicit) = implicit_bidi { + return !implicit; + } + matches!( + name, + TerminalName::WindowsTerminal | TerminalName::Ghostty | TerminalName::Alacritty + ) +} + #[cfg(unix)] pub(crate) fn should_probe_inline_screen() -> bool { terminal_info().multiplexer.is_none() && is_ssh_session() @@ -282,11 +314,7 @@ pub(crate) enum WebLinkDisplay { } pub(crate) fn web_link_display(terminal: &TerminalInfo, term: Option<&str>) -> WebLinkDisplay { - if terminal.multiplexer.is_some() - || term.is_some_and(|term| { - term == "dumb" || term.starts_with("screen") || term.starts_with("tmux") - }) - { + if !is_direct_terminal(terminal, term) { return WebLinkDisplay::WithDestination; } match terminal.name { @@ -310,7 +338,7 @@ pub(crate) fn web_link_display(terminal: &TerminalInfo, term: Option<&str>) -> W } pub(crate) fn detect_web_link_display() -> WebLinkDisplay { - if !std::io::stdout().is_terminal() || screen_active() { + if !direct_stdout() { return WebLinkDisplay::WithDestination; } web_link_display(&terminal_info(), std::env::var("TERM").ok().as_deref()) diff --git a/codex-rs/tui/src/terminal_capabilities/terminal_probe.rs b/codex-rs/tui/src/terminal_capabilities/terminal_probe.rs index 6f2f379959..a31b083e06 100644 --- a/codex-rs/tui/src/terminal_capabilities/terminal_probe.rs +++ b/codex-rs/tui/src/terminal_capabilities/terminal_probe.rs @@ -73,6 +73,7 @@ mod imp { /// Results from the TUI's one-shot startup terminal probe. #[derive(Debug, Default, Clone, Copy, Eq, PartialEq)] pub(crate) struct StartupProbe { + pub(crate) implicit_bidi: Option, pub(crate) alternate_scroll_enabled: Option, pub(crate) cursor_position: Option, pub(crate) default_colors: Option, @@ -319,6 +320,12 @@ mod imp { if keyboard_probe == StartupKeyboardEnhancementProbe::Query { query.extend_from_slice(b"\x1B[?u"); } + // ECMA-48 mode 8 distinguishes terminal-managed (set) from application-managed + // (reset) ordering. A multiplexer cannot speak for its attached clients. + let probe_bidi = crate::terminal_capabilities::direct_terminal_name().is_some(); + if probe_bidi { + query.extend_from_slice(b"\x1B[8$p"); + } // Query before DA1 so its reply acts as a barrier even if mode 1007 is unsupported. query.extend_from_slice(b"\x1B[?1007$p"); if probe_kitty_graphics { @@ -341,11 +348,13 @@ mod imp { probe_kitty_graphics, &mut buffer, ); - let (replay, kitty_graphics) = parse_startup_input(&buffer, probe_kitty_graphics); + let (replay, kitty_graphics, implicit_bidi) = + parse_startup_input(&buffer, probe_kitty_graphics, probe_bidi); crossterm::event::buffer_input(&replay)?; let saw_da1 = find_primary_device_attributes(&buffer).is_some(); DA1_SUPPORTED.store(saw_da1, Ordering::Relaxed); result.map(|probe| StartupProbe { + implicit_bidi, kitty_graphics, ..probe }) @@ -715,6 +724,7 @@ mod imp { default_colors: None, keyboard_enhancement_supported: None, prefer_inline_screen: Some(false), + implicit_bidi: None, kitty_graphics: false, }; let mut saw_supported_keyboard = false; @@ -750,6 +760,7 @@ mod imp { }), keyboard_enhancement_supported: Some(true), prefer_inline_screen: Some(false), + implicit_bidi: None, kitty_graphics: false, } ); @@ -767,6 +778,7 @@ mod imp { default_colors: None, keyboard_enhancement_supported: None, prefer_inline_screen: None, + implicit_bidi: None, kitty_graphics: false, }; let mut supported_keyboard = false; @@ -847,14 +859,17 @@ mod imp { }), keyboard_enhancement_supported: Some(true), prefer_inline_screen: Some(false), + implicit_bidi: None, kitty_graphics: false, } ); let mut expected_replay = vec![b'x'; 2_048]; expected_replay.extend_from_slice(b"\x1B[20;10R\x1B[?64;1;2c\x1B[?7u"); assert_eq!( - parse_startup_input(&buffer, /*probe_kitty_graphics*/ false), - (expected_replay, false) + parse_startup_input( + &buffer, /*probe_kitty_graphics*/ false, /*probe_bidi*/ false + ), + (expected_replay, false, None) ); } diff --git a/codex-rs/tui/src/terminal_capabilities/terminal_probe/startup_replay.rs b/codex-rs/tui/src/terminal_capabilities/terminal_probe/startup_replay.rs index a24424b7ff..ef08dedd4c 100644 --- a/codex-rs/tui/src/terminal_capabilities/terminal_probe/startup_replay.rs +++ b/codex-rs/tui/src/terminal_capabilities/terminal_probe/startup_replay.rs @@ -2,16 +2,21 @@ const MAX_REPLAYED_OSC_BYTES: usize = 1024; -/// Return the input to replay and whether the terminal acknowledged the Kitty graphics query. +/// Return typeahead, the Kitty graphics acknowledgment, and the reported bidi mode. /// /// Keep bounded incomplete OSC prefixes so unread continuations stay parser-framed. -pub(super) fn parse_startup_input(input: &[u8], probe_kitty_graphics: bool) -> (Vec, bool) { +pub(super) fn parse_startup_input( + input: &[u8], + probe_kitty_graphics: bool, + probe_bidi: bool, +) -> (Vec, bool, Option) { const PASTE_START: &[u8] = b"\x1b[200~"; const PASTE_END: &[u8] = b"\x1b[201~"; const KITTY_REPLY: &[u8] = b"\x1b_Gi=31;"; let mut replay = Vec::with_capacity(input.len()); let mut kitty_graphics = false; + let mut implicit_bidi = None; let mut cursor = 0; let mut inside_paste = false; while cursor < input.len() { @@ -22,6 +27,16 @@ pub(super) fn parse_startup_input(input: &[u8], probe_kitty_graphics: bool) -> ( cursor += 11; continue; } + if probe_bidi + && let Some([0x1b, b'[', b'8', b';', mode @ b'0'..=b'4', b'$', b'y']) = + input.get(cursor..cursor + 7) + { + // DECRPM 0 means unrecognized, 1/3 set, 2/4 reset. + implicit_bidi = (*mode != b'0').then_some(matches!(*mode, b'1' | b'3')); + cursor += 7; + continue; + } + if inside_paste { if input[cursor..].starts_with(PASTE_END) { replay.extend_from_slice(PASTE_END); @@ -78,7 +93,7 @@ pub(super) fn parse_startup_input(input: &[u8], probe_kitty_graphics: bool) -> ( replay.push(input[cursor]); cursor += 1; } - (replay, kitty_graphics) + (replay, kitty_graphics, implicit_bidi) } #[cfg(test)] diff --git a/codex-rs/tui/src/terminal_capabilities/terminal_probe/startup_replay_tests.rs b/codex-rs/tui/src/terminal_capabilities/terminal_probe/startup_replay_tests.rs index fb88c2dae1..f09bf30d18 100644 --- a/codex-rs/tui/src/terminal_capabilities/terminal_probe/startup_replay_tests.rs +++ b/codex-rs/tui/src/terminal_capabilities/terminal_probe/startup_replay_tests.rs @@ -5,7 +5,10 @@ use super::parse_startup_input; use pretty_assertions::assert_eq; fn startup_replay_input(input: &[u8]) -> Vec { - parse_startup_input(input, /*probe_kitty_graphics*/ false).0 + parse_startup_input( + input, /*probe_kitty_graphics*/ false, /*probe_bidi*/ false, + ) + .0 } #[test] @@ -73,8 +76,30 @@ fn herdr_graphics_reply_selects_previews_without_replaying_the_response_as_keys( ] { let input = [paste.as_slice(), reply, b"typed"].concat(); assert_eq!( - parse_startup_input(&input, /*probe_kitty_graphics*/ true), - ([paste.as_slice(), b"typed"].concat(), expected) + parse_startup_input( + &input, /*probe_kitty_graphics*/ true, /*probe_bidi*/ false + ), + ([paste.as_slice(), b"typed"].concat(), expected, None) ); } } + +#[test] +fn bidi_replies_interleaved_with_paste_are_consumed_only_when_queried() { + for (mode, implicit) in [ + (0, None), + (1, Some(true)), + (2, Some(false)), + (3, Some(true)), + (4, Some(false)), + ] { + let input = format!("typed\x1b[200~a\x1b[8;{mode}$yb\x1b[201~").into_bytes(); + assert_eq!( + parse_startup_input( + &input, /*probe_kitty_graphics*/ false, /*probe_bidi*/ true + ), + (b"typed\x1b[200~ab\x1b[201~".to_vec(), false, implicit) + ); + assert_eq!(startup_replay_input(&input), input); + } +} diff --git a/codex-rs/tui/src/terminal_hyperlinks.rs b/codex-rs/tui/src/terminal_hyperlinks.rs index 371366eb97..07c4067fa8 100644 --- a/codex-rs/tui/src/terminal_hyperlinks.rs +++ b/codex-rs/tui/src/terminal_hyperlinks.rs @@ -3,6 +3,7 @@ //! Layout code measures and wraps ordinary ratatui lines. Hyperlink annotations are applied only //! when text reaches a terminal buffer or scrollback writer so OSC 8 bytes never affect geometry. +pub(crate) mod bidi; mod paragraph; mod source; @@ -321,8 +322,16 @@ pub(crate) fn lines_with_sources_eq(left: &[HyperlinkLine], right: &[HyperlinkLi } pub(crate) fn source_span_width(span: &Span<'_>) -> usize { - span.content - .graphemes(/*is_extended*/ true) + source_text_width(&span.content) +} + +/// Link columns count painted graphemes, even when adjacent letters (lam-alef) +/// measure as a single ligature in the whole string. +pub(crate) fn source_text_width(text: &str) -> usize { + if text.is_ascii() { + return display_width(text); + } + text.graphemes(/*is_extended*/ true) .map(display_width) .sum() } @@ -582,18 +591,21 @@ pub(crate) fn remap_source_wrapped_line( .map(|wrapped| { let line = line_to_static(&wrapped.line); let displayed = line_text(&line); - let prefix_columns = display_width(&displayed[..wrapped.prefix_bytes]); + let prefix_columns = source_text_width(&displayed[..wrapped.prefix_bytes]); // Some wrapping paths retain a one-past-the-end cursor sentinel. Span slicing already // clips that sentinel to the visible line; keep hyperlink and source projection on the // same bounded range instead of indexing past the flattened text. let range = wrapped.range.start.min(text.len())..wrapped.range.end.min(text.len()); - source_column += display_width(&text[source_byte..range.start]); - let start = source_column; - let end = start + display_width(&text[range.clone()]); - source_byte = range.end; - source_column = end; - let hyperlinks = - project_hyperlink_columns(&source.hyperlinks, start..end, prefix_columns); + let hyperlinks = if source.hyperlinks.is_empty() { + Vec::new() + } else { + source_column += source_text_width(&text[source_byte..range.start]); + let start = source_column; + let end = start + source_text_width(&text[range.clone()]); + source_byte = range.end; + source_column = end; + project_hyperlink_columns(&source.hyperlinks, start..end, prefix_columns) + }; HyperlinkLine { line, hyperlinks, @@ -720,15 +732,10 @@ fn push_link_range(line: &mut HyperlinkLine, range: Range, link: &Termina line.hyperlinks.push(link.with_columns(range)); } -pub(crate) fn web_links_in_text(text: &str) -> Vec { - let mut links = Vec::new(); - let mut search_from = 0usize; - let mut source_byte = 0usize; - let mut source_column = 0usize; - for raw_token in text.split_whitespace() { - let Some(relative_start) = text[search_from..].find(raw_token) else { - continue; - }; +fn web_link_ranges(text: &str) -> impl Iterator, String)> + '_ { + let mut search_from = 0; + text.split_whitespace().filter_map(move |raw_token| { + let relative_start = text[search_from..].find(raw_token)?; let raw_start = search_from + relative_start; search_from = raw_start + raw_token.len(); let trimmed_start = raw_token @@ -736,17 +743,24 @@ pub(crate) fn web_links_in_text(text: &str) -> Vec { .unwrap_or(raw_token.len()); let trimmed_end = trailing_url_end(&raw_token[trimmed_start..]) + trimmed_start; if trimmed_start >= trimmed_end { - continue; + return None; } - let candidate = &raw_token[trimmed_start..trimmed_end]; - let Some(destination) = web_destination(candidate) else { - continue; - }; - let candidate_start = raw_start + trimmed_start; + let range = raw_start + trimmed_start..raw_start + trimmed_end; + let destination = web_destination(&text[range.clone()])?; + Some((range, destination)) + }) +} + +pub(crate) fn web_links_in_text(text: &str) -> Vec { + let mut links = Vec::new(); + let mut source_byte = 0usize; + let mut source_column = 0usize; + for (range, destination) in web_link_ranges(text) { + let candidate_start = range.start; // Measure disjoint prefixes so scanning a draft with many URLs stays linear. - source_column += display_width(&text[source_byte..candidate_start]); + source_column += source_text_width(&text[source_byte..candidate_start]); source_byte = candidate_start; - let end = source_column + display_width(candidate); + let end = source_column + source_text_width(&text[range]); links.push(TerminalHyperlink::web(source_column..end, destination)); } links diff --git a/codex-rs/tui/src/terminal_hyperlinks/bidi.rs b/codex-rs/tui/src/terminal_hyperlinks/bidi.rs new file mode 100644 index 0000000000..e7ad02dfa5 --- /dev/null +++ b/codex-rs/tui/src/terminal_hyperlinks/bidi.rs @@ -0,0 +1,162 @@ +//! Visual order for message prose on terminals that leave ordering to the application. Resolve direction on +//! the logical paragraph, then permute graphemes only after wrapping. The terminal +//! still supplies glyph shaping. Never use the visual line as a copy or reflow source. + +use super::HyperlinkLine; +use super::line_text; +use super::push_link_range; +use super::push_styled_content; +use crate::text_formatting::contains_rtl_or_arabic_number; +use crate::width::display_width; +use icu_properties::CodePointMapData; +use icu_properties::props::BidiMirroringGlyph; +use ratatui::text::Line; +use std::borrow::Cow; +use std::sync::Arc; +use unicode_bidi::BidiClass; +use unicode_bidi::Level; +use unicode_bidi::ParagraphBidiInfo; +use unicode_bidi::bidi_class; +use unicode_segmentation::UnicodeSegmentation; +use unicode_width::UnicodeWidthChar; + +pub(crate) fn prepare_message(lines: &mut [HyperlinkLine]) { + for source in lines.iter_mut().filter_map(|line| line.source.as_mut()) { + source.message = true; + } +} + +pub(crate) fn resolve_paragraphs(lines: &mut [HyperlinkLine]) { + for group in lines.chunk_by_mut(|a, b| { + matches!( + (&a.source, &b.source), + (Some(a), Some(b)) if Arc::ptr_eq(&a.text, &b.text) + ) + }) { + let Some(source) = &group[0].source else { + continue; + }; + // Invisible direction changes can disguise executable syntax. Allow zero-width + // nonspacing marks and boundary neutrals (e.g. joiners), which set no direction. + if !source.message || source + .copy + .as_ref() + .is_some_and(|copy| copy.code || copy.table.is_some() || copy.code_source.is_some()) + // Do not move text across shell operators or substitution markers. + || source.text.contains(['\t', ';', '|', '<', '>', '$', '`']) + || !contains_rtl_or_arabic_number(&source.text) + || source.text.chars().any(|c| { + c.width() == Some(0) && !matches!(bidi_class(c), BidiClass::NSM | BidiClass::BN) + }) + { + continue; + } + // Treat URLs and literals as strong LTR tokens without changing byte offsets. + let mut text = Cow::Borrowed(source.text.as_ref()); + for (range, _) in super::web_link_ranges(&source.text) { + text.to_mut() + .replace_range(range.clone(), &"a".repeat(range.len())); + } + // Exempt URL fragments and query separators, but keep checking literals. + if text.contains(['#', '&']) { + continue; + } + for range in source.copy.iter().flat_map(|copy| ©.literal_ranges) { + if text.get(range.clone()).is_some() { + text.to_mut() + .replace_range(range.clone(), &"a".repeat(range.len())); + } + } + // An unquoted URL's & is also a shell operator. An LTR base keeps the + // masked URL at level zero, so no text can move across that boundary. + let base = source.text.contains('&').then_some(Level::ltr()); + let levels: Arc<[Level]> = ParagraphBidiInfo::new(&text, base).levels.into(); + for source in group.iter_mut().filter_map(|line| line.source.as_mut()) { + source.bidi = Some(Arc::clone(&levels)); + } + } +} + +pub(crate) fn paint_rows(lines: &mut [HyperlinkLine], width: usize) { + resolve_paragraphs(lines); + for line in lines { + if let Some(source) = &line.source + && let Some(levels) = &source.bidi + && let Some(levels) = levels.get(source.range.clone()) + && let Some(visual) = project(line, levels, width) + { + *line = visual; + } + } +} + +fn project(line: &HyperlinkLine, levels: &[Level], width: usize) -> Option { + let source = line.source.as_ref()?; + // Never reorder across terminal autowrap boundaries (e.g. an oversized URL). + if line.width() > width || levels.len() != source.range.len() { + return None; + } + let text = line_text(&line.line); + let start = source.prefix_bytes; + let body = text.get(start..start + levels.len())?; + if Some(body) != source.text.get(source.range.clone()) { + return None; + } + // Keep synthetic gutters and trailing wrap padding outside the bidi run. + let end = start + body.trim_end().len(); + let mut spans = line.line.spans.iter(); + let mut span = spans.next()?; + let mut span_end = span.content.len(); + let mut column = 0; + let mut links = line.hyperlinks.iter().peekable(); + let mut graphemes = Vec::new(); + let mut row_levels = Vec::new(); + for (byte, grapheme) in text.grapheme_indices(/*is_extended*/ true) { + while byte >= span_end { + span = spans.next()?; + span_end += span.content.len(); + } + let level = if (start..end).contains(&byte) { + levels[byte - start] + } else { + Level::ltr() + }; + row_levels.push(level); + let cells = display_width(grapheme); + while links.peek().is_some_and(|link| link.columns.end <= column) { + links.next(); + } + let link = links + .peek() + .copied() + .filter(|link| link.columns.contains(&column)); + graphemes.push((grapheme, cells, span.style, link)); + column += cells; + } + let mut visual = HyperlinkLine::new(Line::default().style(line.line.style)); + visual.line.alignment = line.line.alignment; + column = 0; + for index in ParagraphBidiInfo::reorder_visual(&row_levels) { + let (grapheme, cells, style, link) = graphemes[index]; + if cells == 0 { + continue; + } + let mut symbol = Cow::Borrowed(grapheme); + if row_levels[index].is_rtl() + && let Some(base) = grapheme.chars().next() + && let Some(mirror) = CodePointMapData::::new() + .get(base) + .mirroring_glyph + { + symbol + .to_mut() + .replace_range(..base.len_utf8(), mirror.encode_utf8(&mut [0; 4])); + } + push_styled_content(&mut visual.line.spans, &symbol, style); + if let Some(link) = link { + push_link_range(&mut visual, column..column + cells, link); + } + column += cells; + } + Some(visual) +} diff --git a/codex-rs/tui/src/terminal_hyperlinks/source.rs b/codex-rs/tui/src/terminal_hyperlinks/source.rs index b4142a3130..40c4fe4895 100644 --- a/codex-rs/tui/src/terminal_hyperlinks/source.rs +++ b/codex-rs/tui/src/terminal_hyperlinks/source.rs @@ -23,6 +23,9 @@ pub(crate) enum LineWrapPolicy { #[derive(Clone, Debug, Eq, PartialEq)] pub(crate) struct LogicalLineSource { pub(crate) text: Arc, + pub(crate) message: bool, + /// Paragraph embedding levels indexed by logical byte, shared across wrapped message rows. + pub(crate) bidi: Option>, pub(crate) copy: Option>, /// Selectable label length and the original body, whose Markdown ranges exclude the label. pub(crate) labelled_body: Option>, @@ -47,6 +50,8 @@ impl LogicalLineSource { let end = text.len(); Self { text: text.into(), + message: false, + bidi: None, copy: None, labelled_body: None, copy_as_prose: false, @@ -108,6 +113,8 @@ impl LogicalLineSource { let end = displayed.end.clamp(source_start, source_end); Self { text: Arc::clone(&self.text), + message: self.message, + bidi: self.bidi.clone(), copy: self.copy.clone(), labelled_body: self.labelled_body.clone(), copy_as_prose: self.copy_as_prose, diff --git a/codex-rs/tui/src/transcript_view/text_logical.rs b/codex-rs/tui/src/transcript_view/text_logical.rs index 0b032dead9..4e4a3006e6 100644 --- a/codex-rs/tui/src/transcript_view/text_logical.rs +++ b/codex-rs/tui/src/transcript_view/text_logical.rs @@ -9,7 +9,7 @@ use ratatui::text::Span; use crate::terminal_hyperlinks::HyperlinkLine; use crate::terminal_hyperlinks::LineWrapPolicy; use crate::terminal_hyperlinks::LogicalLineSource; -use crate::width::display_width; +use crate::terminal_hyperlinks::source_text_width; #[derive(Clone)] pub(super) struct LogicalLine { @@ -66,7 +66,11 @@ impl LogicalLine { ); let prefix = slice_line(&line.line, 0..source.prefix_bytes); let prefix_width = prefix.width(); - let content_width = display_width(&source.text[source.range.clone()]); + let content_width = if line.hyperlinks.is_empty() { + 0 + } else { + source_text_width(&source.text[source.range.clone()]) + }; self.line.line.spans.extend(body.spans); self.line .hyperlinks diff --git a/codex-rs/tui/src/transcript_view/text_tests.rs b/codex-rs/tui/src/transcript_view/text_tests.rs index 565d24b049..c666173c43 100644 --- a/codex-rs/tui/src/transcript_view/text_tests.rs +++ b/codex-rs/tui/src/transcript_view/text_tests.rs @@ -481,3 +481,31 @@ fn document_link_navigation_preserves_occurrences_across_wraps() { assert_eq!(links, ["first link wraps", "second link"]); } } + +#[test] +fn rtl_transcript_preserves_command_boundaries() { + use crate::terminal_hyperlinks::bidi; + let paint = |command: &'static str| { + let mut lines = prefix_hyperlink_lines(vec![command.into()], "".into(), "".into()); + bidi::prepare_message(&mut lines); + bidi::paint_rows(&mut lines, /*width*/ 80); + lines[0].line.to_string() + }; + assert_eq!( + paint(": שלום https://example.org/?x=1&make"), + ": םולש https://example.org/?x=1&make" + ); + for command in [ + "echo SAFE \u{2067}שלום printf PWNED\u{2069}\u{200f}", + ": \u{070f} שלום printf PWNED", + ": שלום; echo SAFE; printf PWNED #", + "שלום; echo SAFE; printf PWNED #", + "שלום & calc.exe & עולם & ::", + "שלום $(touch /tmp/PWNED)", + "שלום https://example.org/?a=1&b=2 #", + "שלום & https://example.org/#help", + "שלום https://example.org/$name#help", + ] { + assert_eq!(paint(command), command); + } +} diff --git a/codex-rs/tui/src/tui.rs b/codex-rs/tui/src/tui.rs index 5e38196615..9826ff1fa2 100644 --- a/codex-rs/tui/src/tui.rs +++ b/codex-rs/tui/src/tui.rs @@ -594,6 +594,11 @@ pub(crate) fn init() -> Result { crate::terminal_palette::set_default_colors_from_startup_probe(/*colors*/ None); let mut tui = CustomTerminal::with_options_and_cursor_position(backend, cursor_pos)?; + #[cfg(unix)] + let implicit_bidi = startup_probe.implicit_bidi; + #[cfg(not(unix))] + let implicit_bidi = None; + tui.bidi_layout = terminal_capabilities::needs_bidi_layout(implicit_bidi); tui.virtual_image_base = session.virtual_image_base(); let stderr_guard = terminal_stderr::TerminalStderrGuard::install()?; let initialized_terminal = InitializedTerminal {