From 18059127763b49d0624d94c619e9c78ca0c36824 Mon Sep 17 00:00:00 2001 From: Charlie Weems Date: Wed, 2 Dec 2026 06:54:30 +0000 Subject: [PATCH] Add a configurable maximum width for TUI conversations (#65216) ## Why On wide terminals, the transcript and prompt box can span more columns than users want for comfortable reading and editing. ## What changed Set `tui.max_conversation_width` in `config.toml` to cap the transcript and prompt box in fullscreen and inline modes, including the startup composer. ```toml [tui] max_conversation_width = 80 ``` The setting accepts values from 20 to 65,535 terminal columns. When unset, the conversation uses the available width. Raw inline scrollback keeps native terminal wrapping, and wrapped links in formatted history and command previews retain their full destinations. ## Testing Add regression coverage for config validation, startup and live layouts, inline history reflow after a config reload, and links that wrap across rows. GitOrigin-RevId: 91e1856776986fee3b540247c3fbfe5f083b297f --- codex-rs/config/src/types.rs | 19 + codex-rs/config/src/types_tests.rs | 19 + codex-rs/core/config.schema.json | 8 + codex-rs/core/src/config/config_tests.rs | 2 + codex-rs/tui/src/app.rs | 52 +-- codex-rs/tui/src/app/agents_overview.rs | 6 + codex-rs/tui/src/app/agents_overview_tests.rs | 23 +- codex-rs/tui/src/app/config_persistence.rs | 10 + codex-rs/tui/src/app/owned_transcript.rs | 16 +- codex-rs/tui/src/app/resize_reflow.rs | 10 +- codex-rs/tui/src/app/resize_reflow_tests.rs | 6 +- codex-rs/tui/src/app/side_pane.rs | 19 +- codex-rs/tui/src/app/tests.rs | 139 +------- .../src/app/tests/conversation_width_tests.rs | 324 ++++++++++++++++++ ..._dialog_centered_over_capped_backdrop.snap | 16 + codex-rs/tui/src/chatwidget/pets.rs | 3 +- codex-rs/tui/src/chatwidget/rendering.rs | 16 +- codex-rs/tui/src/exec_cell/render.rs | 5 +- codex-rs/tui/src/insert_history.rs | 150 +++++++- codex-rs/tui/src/local_settings.rs | 6 + ..._draft__tests__startup_composer_width.snap | 10 + codex-rs/tui/src/startup_draft.rs | 15 +- codex-rs/tui/src/startup_draft_tests.rs | 65 ++++ codex-rs/tui/src/startup_presentation.rs | 2 + .../tui/src/startup_presentation_tests.rs | 5 +- codex-rs/tui/src/terminal_hyperlinks.rs | 27 ++ codex-rs/tui/src/tool_output.rs | 8 +- codex-rs/tui/src/tool_output_tests.rs | 52 +++ codex-rs/tui/src/transcript_reflow.rs | 4 + codex-rs/tui/src/tui_startup_tests.rs | 1 + 30 files changed, 851 insertions(+), 187 deletions(-) create mode 100644 codex-rs/tui/src/app/tests/conversation_width_tests.rs create mode 100644 codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__conversation_width_tests__max_conversation_width_keeps_full_access_dialog_centered_over_capped_backdrop.snap create mode 100644 codex-rs/tui/src/snapshots/codex_tui__startup_draft__tests__startup_composer_width.snap diff --git a/codex-rs/config/src/types.rs b/codex-rs/config/src/types.rs index 0dffb65de0..2ddcf2f4ca 100644 --- a/codex-rs/config/src/types.rs +++ b/codex-rs/config/src/types.rs @@ -929,6 +929,19 @@ pub enum BuiltinStatusLine { Default, } +fn deserialize_max_conversation_width<'de, D>(deserializer: D) -> Result, D::Error> +where + D: serde::Deserializer<'de>, +{ + let width = Option::::deserialize(deserializer)?; + if width.is_some_and(|width| width < 20) { + return Err(serde::de::Error::custom( + "tui.max_conversation_width must be at least 20 columns", + )); + } + Ok(width) +} + /// Collection of settings that are specific to the TUI. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)] #[schemars(deny_unknown_fields)] @@ -1006,6 +1019,12 @@ pub struct Tui { #[serde(default = "default_true")] pub collapse_turn_details: bool, + /// Maximum width of the conversation and prompt box, in terminal columns. + /// Unset uses the available width. Raw inline scrollback keeps native terminal wrapping. + #[serde(default, deserialize_with = "deserialize_max_conversation_width")] + #[schemars(range(min = 20, max = 65535))] + pub max_conversation_width: Option, + /// Preferred docked sidebar width as a percentage of the terminal. Defaults to one third. #[serde(default)] #[schemars(range(min = 1, max = 99))] diff --git a/codex-rs/config/src/types_tests.rs b/codex-rs/config/src/types_tests.rs index f3bc7758cc..cefa2f3c26 100644 --- a/codex-rs/config/src/types_tests.rs +++ b/codex-rs/config/src/types_tests.rs @@ -60,6 +60,25 @@ auto_provision = true } } +#[test] +fn max_conversation_width_is_optional_and_accepts_columns() { + let default: Tui = toml::from_str("").unwrap(); + assert_eq!(default.max_conversation_width, None); + let configured: Tui = toml::from_str("max_conversation_width = 80").unwrap(); + assert_eq!(configured.max_conversation_width, Some(80)); +} + +#[test] +fn max_conversation_width_rejects_values_below_minimum() { + let error = toml::from_str::("max_conversation_width = 19").unwrap_err(); + assert!( + error + .to_string() + .contains("tui.max_conversation_width must be at least 20 columns"), + "{error}" + ); +} + #[test] fn mouse_scroll_speed_accepts_integer_and_fractional_multipliers() { for (value, expected) in [("1", 1.0), ("0.5", 0.5), ("3.0", 3.0)] { diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index 79526f4bc2..1a3c620677 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -5887,6 +5887,14 @@ }, "description": "Keybinding overrides for the TUI.\n\nThis supports rebinding selected actions globally and by context. Context bindings take precedence over `global` bindings." }, + "max_conversation_width": { + "default": null, + "description": "Maximum width of the conversation and prompt box, in terminal columns. Unset uses the available width. Raw inline scrollback keeps native terminal wrapping.", + "format": "uint16", + "maximum": 65535.0, + "minimum": 20.0, + "type": "integer" + }, "model_availability_nux": { "allOf": [ { diff --git a/codex-rs/core/src/config/config_tests.rs b/codex-rs/core/src/config/config_tests.rs index 4aa7fab9be..bba19f1dc3 100644 --- a/codex-rs/core/src/config/config_tests.rs +++ b/codex-rs/core/src/config/config_tests.rs @@ -1479,6 +1479,7 @@ fn config_toml_deserializes_model_availability_nux() { raw_output_mode: false, fullscreen_transcript: true, collapse_turn_details: true, + max_conversation_width: None, sidebar_width_percent: None, mouse_scroll_speed: None, copy_on_select: Default::default(), @@ -4871,6 +4872,7 @@ fn tui_config_missing_notifications_field_defaults_to_enabled() { raw_output_mode: false, fullscreen_transcript: true, collapse_turn_details: true, + max_conversation_width: None, sidebar_width_percent: None, mouse_scroll_speed: None, copy_on_select: Default::default(), diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index ae686d25bf..8a1dbf0c0b 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -1620,19 +1620,17 @@ impl App { .borrow_mut() .pause_clock(); self.chat_widget.sync_warnings(&self.transcript_cells); - let dashboard_visible = self - .chat_widget - .selected_index_for_present_view(AGENTS_OVERVIEW_VIEW_ID) - .is_some(); + let dashboard_visible = self.agents_overview_present(); let dashboard_was_visible = std::mem::replace( &mut self.agents_overview.rendered_full_screen, dashboard_visible, ); + let width = self.inline_backdrop_width(screen_size.width); // Full-height inline overlays scroll history off screen without a terminal resize. // Rebuild it once when returning to a content-height chat viewport. let restoring_inline_viewport = !tui.is_alt_screen_active() && tui.terminal.viewport_area.height == screen_size.height - && self.with_chat_widget_frame(screen_size.width, |height, _| height) + && self.with_chat_widget_frame(screen_size.width, width, |height, _| height) < screen_size.height; if !dashboard_visible && (dashboard_was_visible || restoring_inline_viewport) { self.schedule_immediate_resize_reflow(tui); @@ -1641,22 +1639,26 @@ impl App { let hud = self.workspace_hud(tui, screen_size.into()); self.chat_widget.begin_steer_hint_draw(); let mut rendered_area = Rect::default(); - self.with_chat_widget_frame(screen_size.width, |desired_height, chat_widget| { + self.with_chat_widget_frame(screen_size.width, width, |desired_height, chat_widget| { let desired_height = if dashboard_visible { screen_size.height } else { desired_height }; tui.draw_with_resize_reflow(desired_height, screen_size, hud, |frame| { - let area = frame.area(); + let area = Rect { + width: frame.area().width.min(width), + ..frame.area() + }; rendered_area = area; - chat_widget.render(area, frame.buffer); + let widget_area = frame.area(); + chat_widget.render(widget_area, frame.buffer); if let Some(previews) = &self.chat_widget.composer_images { frame.image_placements = previews.placements.take(); } self.chat_widget.note_rendered_width(area.width); - if let Some((x, y)) = chat_widget.cursor_pos(area) { - frame.set_cursor_style(chat_widget.cursor_style(area)); + if let Some((x, y)) = chat_widget.cursor_pos(widget_area) { + frame.set_cursor_style(chat_widget.cursor_style(widget_area)); frame.set_cursor_position((x, y)); } }) @@ -1665,23 +1667,33 @@ impl App { Ok(rendered_area) } + fn inline_backdrop_width(&self, viewport_width: u16) -> u16 { + if self.agents_overview_present() { + viewport_width + } else { + self.local_settings.conversation_width(viewport_width) + } + } + fn with_chat_widget_frame( &self, + viewport_width: u16, width: u16, render: impl FnOnce(u16, &dyn Renderable) -> T, ) -> T { let footer = self.scrollback_cycle_footer(width); - let chat_widget = match &footer { - Some(footer) => self.chat_widget.as_renderable_with_options( - crate::bottom_pane::ComposerRenderOptions { - footer: Some(footer), - command_popup_placement: crate::bottom_pane::CommandPopupPlacement::Hidden, - ..Default::default() - }, - ), - None => self.chat_widget.as_renderable(), + let options = match &footer { + Some(footer) => crate::bottom_pane::ComposerRenderOptions { + footer: Some(footer), + command_popup_placement: crate::bottom_pane::CommandPopupPlacement::Hidden, + ..Default::default() + }, + None => Default::default(), }; - render(chat_widget.desired_height(width), &chat_widget) + let chat_widget = self + .chat_widget + .as_renderable_with_options(options, viewport_width.saturating_sub(width)); + render(chat_widget.desired_height(viewport_width), &chat_widget) } } diff --git a/codex-rs/tui/src/app/agents_overview.rs b/codex-rs/tui/src/app/agents_overview.rs index ed9a244fda..eb04a27473 100644 --- a/codex-rs/tui/src/app/agents_overview.rs +++ b/codex-rs/tui/src/app/agents_overview.rs @@ -133,6 +133,12 @@ impl Drop for AgentsOverviewState { } impl App { + pub(super) fn agents_overview_present(&self) -> bool { + self.chat_widget + .selected_index_for_present_view(AGENTS_OVERVIEW_VIEW_ID) + .is_some() + } + /// Read the selected row from its host, even while a dialog has focus. pub(super) fn overview_selected_index(&self) -> Option { let workspace = &self.agents_overview.workspace; diff --git a/codex-rs/tui/src/app/agents_overview_tests.rs b/codex-rs/tui/src/app/agents_overview_tests.rs index e7f6d4ec1c..80b2e57917 100644 --- a/codex-rs/tui/src/app/agents_overview_tests.rs +++ b/codex-rs/tui/src/app/agents_overview_tests.rs @@ -2224,16 +2224,29 @@ async fn shared_overview_shows_only_root_sessions() { "Previous conversation", )]), )); - let mut tui = crate::tui::test_support::make_test_tui().expect("test terminal"); - let screen_size = tui.terminal.last_known_screen_size; - app.render_chat_widget_frame(&mut tui, screen_size) - .expect("render full-screen dashboard"); + let screen_size = Size::new(/*width*/ 200, /*height*/ 24); + let mut tui = + crate::tui::test_support::make_test_tui_with_size(screen_size).expect("test terminal"); + app.local_settings.tui.max_conversation_width = Some(80); + for owned in [true, false] { + tui.set_owned_screen(owned).unwrap(); + let dashboard = super::super::test_support::side_frame(&mut app, &mut tui, screen_size) + .expect("render full-screen dashboard"); + assert!( + dashboard.lines().any(|row| row + .split_once("Task details") + .is_some_and(|(before, _)| before.chars().count() >= 80)), + "{dashboard}" + ); + } assert_eq!(tui.terminal.viewport_area.height, screen_size.height); app.agents_overview.view_state.lock().unwrap().completion = Some(crate::bottom_pane::ViewCompletion::Accepted); app.chat_widget.pre_draw_tick(); - app.render_chat_widget_frame(&mut tui, screen_size) + let chat = app + .render_chat_widget_frame(&mut tui, screen_size) .expect("restore conversation after closing dashboard"); + assert_eq!(chat.width, 80); assert!(tui.terminal.viewport_area.height < screen_size.height); assert!(app.has_emitted_history_lines); } diff --git a/codex-rs/tui/src/app/config_persistence.rs b/codex-rs/tui/src/app/config_persistence.rs index 4f1398b2c7..46de8854e3 100644 --- a/codex-rs/tui/src/app/config_persistence.rs +++ b/codex-rs/tui/src/app/config_persistence.rs @@ -514,6 +514,16 @@ impl App { self.refresh_server_version_overview_notice(CODEX_CLI_VERSION); // Copy preferences read directly by the live widget. Other preferences have runtime // caches and are adopted when the widget is replaced. + let terminal_width = self.transcript_reflow.last_observed_width(); + let previous_width = terminal_width.map(|width| self.chat_widget.history_wrap_width(width)); + self.chat_widget.local_settings.tui.max_conversation_width = + self.local_settings.tui.max_conversation_width; + // A config reload can change the wrap width without a terminal resize. + if previous_width != terminal_width.map(|width| self.chat_widget.history_wrap_width(width)) + { + self.transcript_reflow.schedule_immediate(); + self.chat_widget.request_redraw(); + } self.chat_widget .local_settings .tui diff --git a/codex-rs/tui/src/app/owned_transcript.rs b/codex-rs/tui/src/app/owned_transcript.rs index d190b2853a..304ae35f4f 100644 --- a/codex-rs/tui/src/app/owned_transcript.rs +++ b/codex-rs/tui/src/app/owned_transcript.rs @@ -343,6 +343,7 @@ impl App { ((!main.is_empty()).then_some(*main), None) } None if chat == TabState::Active + && !self.agents_overview_present() && caller_inset.is_none() && self.side_retention_enabled(tui) => { @@ -516,7 +517,7 @@ impl App { panes.paint_companion( companion, frame, - self.local_settings.tui.collapse_turn_details, + &self.local_settings, &frames, watch_only, ); @@ -939,6 +940,7 @@ impl App { } else { self.prompt_navigation_footer(area.width.saturating_sub(/*rhs*/ 2)) }; + let agents_overview_present = self.agents_overview_present(); let unfocused = self.workspace_center_owns_input() || matches!( self.conversation_frame.sidebar, @@ -974,9 +976,6 @@ impl App { composer_gap: composer_gap.as_ref(), ..options(view.has_active_interaction()) }); - let agents_overview_present = chat_widget - .selected_index_for_present_view(AGENTS_OVERVIEW_VIEW_ID) - .is_some(); let measure_bottom = |bottom: &dyn Renderable| { if agents_overview_present { area.height @@ -1280,9 +1279,14 @@ impl App { } pub(super) fn conversation_area(&self, viewport: Rect) -> Rect { - self.conversation_frame + let mut area = self + .conversation_frame .inset - .map_or(viewport, |area| area.intersection(viewport)) + .map_or(viewport, |area| area.intersection(viewport)); + if !self.agents_overview_present() { + area.width = self.local_settings.conversation_width(area.width); + } + area } pub(super) fn refresh_owned_transcript(&mut self, tui: &mut tui::Tui) -> Result<()> { diff --git a/codex-rs/tui/src/app/resize_reflow.rs b/codex-rs/tui/src/app/resize_reflow.rs index d100e2beb5..e5199b0a1b 100644 --- a/codex-rs/tui/src/app/resize_reflow.rs +++ b/codex-rs/tui/src/app/resize_reflow.rs @@ -248,6 +248,8 @@ impl App { pub(crate) fn history_line_wrap_policy(&self) -> HistoryLineWrapPolicy { if self.chat_widget.raw_output_mode() { HistoryLineWrapPolicy::Terminal + } else if let Some(max_width) = self.local_settings.tui.max_conversation_width { + HistoryLineWrapPolicy::PreWrapAtWidth(max_width) } else { HistoryLineWrapPolicy::PreWrap } @@ -281,9 +283,13 @@ impl App { } pub(super) fn update_visible_history_rows(&mut self, screen_size: Size) { - let width = screen_size.width.max(/*other*/ 1); + let viewport_width = screen_size.width.max(1); let viewport_height = self - .with_chat_widget_frame(width, |desired_height, _| desired_height) + .with_chat_widget_frame( + viewport_width, + self.inline_backdrop_width(viewport_width), + |desired_height, _| desired_height, + ) .min(screen_size.height); self.transcript_reflow.set_visible_history_rows( screen_size diff --git a/codex-rs/tui/src/app/resize_reflow_tests.rs b/codex-rs/tui/src/app/resize_reflow_tests.rs index d1cf18a7de..02c5c484b4 100644 --- a/codex-rs/tui/src/app/resize_reflow_tests.rs +++ b/codex-rs/tui/src/app/resize_reflow_tests.rs @@ -27,7 +27,11 @@ async fn resize_reflow_preserves_configured_scrollback_beyond_the_visible_viewpo app.local_settings.tui.terminal_resize_reflow_max_rows = Some(32); app.transcript_cells = plain_history_cells(/*count*/ 64); let screen_size = Size::new(/*width*/ 80, /*height*/ 24); - let chat_height = app.with_chat_widget_frame(screen_size.width, |height, _| height); + let chat_height = app.with_chat_widget_frame( + screen_size.width, + app.inline_backdrop_width(screen_size.width), + |height, _| height, + ); let visible_history_rows = screen_size .height .saturating_sub(chat_height) diff --git a/codex-rs/tui/src/app/side_pane.rs b/codex-rs/tui/src/app/side_pane.rs index 25227b960a..8005ab795f 100644 --- a/codex-rs/tui/src/app/side_pane.rs +++ b/codex-rs/tui/src/app/side_pane.rs @@ -1,7 +1,6 @@ //! Lay out paired conversations and handle pointer resizing for both workspace dividers. use super::App; -use super::agents_overview::AGENTS_OVERVIEW_VIEW_ID; use super::side_companion::SideCompanion; use super::sidebar; use super::sidebar::PaneFocus; @@ -12,6 +11,7 @@ use crate::bottom_pane::StatusLineFocus; use crate::custom_terminal::Frame; use crate::legacy_core::config::edit::ConfigEdit; use crate::legacy_core::config::edit::ConfigEditsBuilder; +use crate::local_settings::LocalSettings; use crate::render::renderable::Renderable; use crate::tui::FrameRequester; use crate::tui::Tui; @@ -170,12 +170,7 @@ pub(super) fn pair_layout( child: ThreadId, [parent, sidebar]: [Rect; 2], ) -> Option { - if parent.is_empty() - || app - .chat_widget - .selected_index_for_present_view(AGENTS_OVERVIEW_VIEW_ID) - .is_some() - { + if parent.is_empty() || app.agents_overview_present() { return None; } let active = app.current_displayed_thread_id()?; @@ -543,12 +538,16 @@ impl SidePaneLayout { &self, companion: &mut SideCompanion, frame: &mut Frame<'_>, - collapse_turn_details: bool, + settings: &LocalSettings, frames: &FrameRequester, watch_only: bool, ) { companion.flush_answer(); - let area = self.passive; + // Only the content is capped; keep the split and focus hit area unchanged. + let area = Rect { + width: settings.conversation_width(self.passive.width), + ..self.passive + }; // Keep the live composer's bottom hint row blank on the inactive side. let hint_rows = 1; let composer_height = if watch_only { @@ -593,7 +592,7 @@ impl SidePaneLayout { &companion.cells, companion.display.active.as_deref(), &companion.display.auxiliary, - collapse_turn_details, + settings.tui.collapse_turn_details, ); }); frame diff --git a/codex-rs/tui/src/app/tests.rs b/codex-rs/tui/src/app/tests.rs index ec355953d5..91d598f1e8 100644 --- a/codex-rs/tui/src/app/tests.rs +++ b/codex-rs/tui/src/app/tests.rs @@ -3,6 +3,9 @@ #[path = "tests/terminal_size_telemetry_tests.rs"] mod terminal_size_telemetry_tests; +#[path = "tests/conversation_width_tests.rs"] +mod conversation_width_tests; + #[path = "tests/copy_mode_tests.rs"] mod copy_mode_tests; #[path = "tests/mcp_login_tests.rs"] @@ -479,14 +482,18 @@ async fn chat_widget_frame_reuses_active_cell_height_across_frame_passes() { }), ); let width = 80; - app.with_chat_widget_frame(width, |desired_height, chat_widget| { - let area = Rect::new(/*x*/ 0, /*y*/ 0, width, desired_height); - let mut buffer = Buffer::empty(area); + app.with_chat_widget_frame( + width, + app.inline_backdrop_width(width), + |desired_height, chat_widget| { + let area = Rect::new(/*x*/ 0, /*y*/ 0, width, desired_height); + let mut buffer = Buffer::empty(area); - chat_widget.render(area, &mut buffer); - assert!(chat_widget.cursor_pos(area).is_some()); - let _ = chat_widget.cursor_style(area); - }); + chat_widget.render(area, &mut buffer); + assert!(chat_widget.cursor_pos(area).is_some()); + let _ = chat_widget.cursor_style(area); + }, + ); assert_eq!(desired_height_calls.load(Ordering::Relaxed), 1); } @@ -5720,119 +5727,6 @@ async fn handle_start_side_seeds_navigation_before_thread_started() -> Result<() Ok(()) } -#[tokio::test] -async fn split_status_lines_reflow_across_focus_switches() -> Result<()> { - use crate::bottom_pane::StatusLineItem; - use ratatui::style::Modifier; - use ratatui::text::Line; - - let (mut app, mut events, _ops) = make_test_app_with_channels().await; - let mut server = Box::pin(crate::start_embedded_app_server_for_picker(&app.config)).await?; - let primary = server.start_thread(&app.config).await?; - let main = primary.session.thread_id; - app.enqueue_primary_thread_session(primary.session, primary.turns) - .await?; - let side = ThreadId::new(); - let channel = ThreadEventChannel::new(/*capacity*/ 1); - channel.store.lock().await.set_session( - test_thread_session(side, app.config.cwd.to_path_buf()), - Vec::new(), - ); - app.thread_event_channels.insert(side, channel); - app.side_threads.insert(side, SideThreadState::new(main)); - app.sidebar_mut().show( - sidebar::SidebarContent::Chat(side), - sidebar::PaneFocus::Main, - ); - let mut tui = crate::tui::test_support::make_test_tui()?; - tui.set_owned_screen(/*owned*/ true)?; - drain_app_events(&mut app, &mut tui, &mut server, &mut events).await?; - - let main_status = "MainStatusSummaryForThePrimaryWorkspaceContext MainStatusDetailsForThePrimaryWorkspaceContext"; - let side_status = "SideStatusSummaryText SideStatusDetails"; - let mut frames = Vec::new(); - for (index, (focused, width, height)) in [ - (main, 100, 24), - (side, 100, 24), - (main, 100, 24), - (main, 130, 24), - ] - .into_iter() - .enumerate() - { - if app.current_displayed_thread_id() != Some(focused) { - app.select_agent_thread(&mut tui, &mut server, focused) - .await?; - drain_app_events(&mut app, &mut tui, &mut server, &mut events).await?; - } - assert_eq!(app.current_displayed_thread_id(), Some(focused)); - enable_side_retention(&mut app)?; - app.local_settings.tui.animations = false; - let size = Size::new(width, height); - // Resize refreshes the active native status, so install the fixture after reflow. - side_frame(&mut app, &mut tui, size)?; - let (name, draft, status) = if focused == main { - ("Main", "main draft", main_status) - } else { - ("Side", "side draft", side_status) - }; - app.chat_widget.setup_status_line( - vec![StatusLineItem::ModelName], - /*use_theme_colors*/ false, - ); - app.chat_widget - .set_status_line(Some(Line::from(status).into())); - app.chat_widget.apply_external_edit(draft.into()); - if index == 0 { - // Seed the main conversation before focusing the side chat. - continue; - } - - let frame = side_frame(&mut app, &mut tui, size)?; - assert!( - frame.contains("main draft") && frame.contains("side draft"), - "{frame}" - ); - let divider = app.conversation_frame.divider_area().expect("split pane"); - let buffer = tui.terminal.previous_buffer(); - let mut rows = vec![format!("{name} focused at {width}x{height}")]; - for (prefix, start, end) in [ - ("MainStatus", 0, divider.x), - ("SideStatus", divider.right(), width), - ] { - for y in 0..height { - let text: String = (start..end).map(|x| buffer[(x, y)].symbol()).collect(); - if text.trim_start().starts_with(prefix) { - let muted = buffer[(start + 2, y)].modifier.contains(Modifier::DIM); - let style = if muted { "muted" } else { "normal" }; - rows.push(format!("{style} {}", text.trim())); - } - } - } - frames.push(rows.join("\n")); - } - insta::assert_snapshot!(frames.join("\n\n"), @" - Side focused at 100x24 - muted MainStatusSummaryForThePrimaryWorkspaceContext - muted MainStatusDetailsForThePrimaryWorkspaceContext - normal SideStatusSummaryText - normal SideStatusDetails - - Main focused at 100x24 - normal MainStatusSummaryForThePrimaryWorkspaceContext - normal MainStatusDetailsForThePrimaryWorkspaceContext - muted SideStatusSummaryText - muted SideStatusDetails - - Main focused at 130x24 - normal MainStatusSummaryForThePrimaryWorkspaceContext - normal MainStatusDetailsForThePrimaryWorkspaceContext - muted SideStatusSummaryText SideStatusDetails - "); - server.shutdown().await?; - Ok(()) -} - #[tokio::test] async fn side_close_key_cannot_accept_a_replacing_approval() -> Result<()> { let mut app = make_test_app().await; @@ -9753,8 +9647,9 @@ async fn owned_stream_reflows_at_allocated_width_without_reporting_activity() -> }; app.chat_widget .handle_server_notification(delta(table), /*replay_kind*/ None); - for width in [80, 44, 80] { - let frame = draw(&mut app, width)?; + app.local_settings.tui.max_conversation_width = Some(64); + for (available, width) in [(80_u16, 64_u16), (44, 44), (70, 64)] { + let frame = draw(&mut app, available)?; let mut expected = Vec::new(); let reserved = if kind == "plan" { 4 } else { 2 }; crate::markdown::append_markdown_agent( diff --git a/codex-rs/tui/src/app/tests/conversation_width_tests.rs b/codex-rs/tui/src/app/tests/conversation_width_tests.rs new file mode 100644 index 0000000000..1ff3448da3 --- /dev/null +++ b/codex-rs/tui/src/app/tests/conversation_width_tests.rs @@ -0,0 +1,324 @@ +#![cfg(test)] + +use super::*; +use pretty_assertions::assert_eq; + +#[tokio::test] +async fn max_conversation_width_caps_the_owned_pane_without_moving_it() { + let mut app = make_test_app().await; + let wide = Rect::new( + /*x*/ 0, /*y*/ 0, /*width*/ 160, /*height*/ 24, + ); + assert_eq!(app.conversation_area(wide), wide); + + app.local_settings.tui.max_conversation_width = Some(80); + assert_eq!(app.conversation_area(wide), Rect { width: 80, ..wide }); + let narrower = Rect { width: 62, ..wide }; + assert_eq!(app.conversation_area(narrower), narrower); + + let inset = Rect::new( + /*x*/ 20, /*y*/ 2, /*width*/ 100, /*height*/ 16, + ); + let tui = crate::tui::test_support::make_test_tui().unwrap(); + app.prepare_conversation(wide, Some(inset), &tui.frame_requester()); + assert_eq!(app.conversation_area(wide), Rect { width: 80, ..inset }); + assert_eq!( + app.conversation_area(narrower), + inset.intersection(narrower) + ); +} + +#[tokio::test] +async fn max_conversation_width_caps_the_inline_frame_without_resizing_the_terminal() -> Result<()> +{ + let mut app = make_test_app().await; + app.local_settings.tui.max_conversation_width = Some(80); + for (width, expected_width) in [(160, 80), (112, 80), (62, 62)] { + let size = Size::new(width, /*height*/ 28); + let mut tui = crate::tui::test_support::make_test_tui_with_size(size)?; + let area = app.render_chat_widget_frame(&mut tui, size)?; + assert_eq!(area.width, expected_width); + assert_eq!(tui.terminal.viewport_area.width, width); + } + Ok(()) +} + +#[tokio::test] +async fn max_conversation_width_keeps_fullscreen_shell_links_on_continuation_rows() -> Result<()> { + use crate::exec_cell::CommandOutput; + use crate::exec_cell::new_active_exec_command; + use codex_app_server_protocol::CommandExecutionSource; + + let url = "https://example.invalid/reports/alpha-bravo-charlie-delta-echo-foxtrot-golf"; + let mut cell = new_active_exec_command( + "shell".into(), + vec!["./link".into()], + Vec::new(), + CommandExecutionSource::UserShell, + /*interaction_input*/ None, + /*animations_enabled*/ false, + ); + cell.complete_call( + "shell", + CommandOutput::new(/*exit_code*/ 0, url.into()), + std::time::Duration::ZERO, + ); + + let mut app = make_test_app().await; + app.local_settings.tui.max_conversation_width = Some(40); + app.transcript_cells = vec![Arc::new(cell)]; + let size = Size::new(/*width*/ 120, /*height*/ 24); + let mut tui = crate::tui::test_support::make_test_tui_with_size(size)?; + tui.set_owned_screen(/*owned*/ true)?; + app.render_owned_transcript(&mut tui, size)?; + let screen = crate::terminal_hyperlinks::strip_osc8(&transcript_composer::buffer_text( + tui.terminal.previous_buffer(), + )); + let (row, continuation) = screen + .lines() + .enumerate() + .skip_while(|(_, line)| !line.contains("https://")) + .nth(1) + .expect("second row of shell URL"); + let column = continuation + .find(|ch: char| !ch.is_whitespace()) + .expect("URL fragment"); + assert_eq!( + app.transcript_view + .link_at(column as u16, row as u16) + .as_deref(), + Some(url), + ); + Ok(()) +} + +#[tokio::test] +async fn split_status_lines_reflow_across_focus_switches() -> Result<()> { + use crate::bottom_pane::StatusLineItem; + use ratatui::style::Modifier; + use ratatui::text::Line; + + let (mut app, mut events, _ops) = make_test_app_with_channels().await; + let mut server = Box::pin(crate::start_embedded_app_server_for_picker(&app.config)).await?; + let primary = server.start_thread(&app.config).await?; + let main = primary.session.thread_id; + app.enqueue_primary_thread_session(primary.session, primary.turns) + .await?; + let side = ThreadId::new(); + let channel = ThreadEventChannel::new(/*capacity*/ 1); + channel.store.lock().await.set_session( + test_thread_session(side, app.config.cwd.to_path_buf()), + Vec::new(), + ); + app.thread_event_channels.insert(side, channel); + app.side_threads.insert(side, SideThreadState::new(main)); + app.sidebar_mut().show( + sidebar::SidebarContent::Chat(side), + sidebar::PaneFocus::Main, + ); + let mut tui = crate::tui::test_support::make_test_tui()?; + tui.set_owned_screen(/*owned*/ true)?; + drain_app_events(&mut app, &mut tui, &mut server, &mut events).await?; + + let main_status = "MainStatusSummaryForThePrimaryWorkspaceContext MainStatusDetailsForThePrimaryWorkspaceContext"; + let side_status = "SideStatusSummaryText SideStatusDetails"; + let mut frames = Vec::new(); + for (index, (focused, width, height)) in [ + (main, 100, 24), + (side, 100, 24), + (main, 100, 24), + (main, 130, 24), + ] + .into_iter() + .enumerate() + { + if app.current_displayed_thread_id() != Some(focused) { + app.select_agent_thread(&mut tui, &mut server, focused) + .await?; + drain_app_events(&mut app, &mut tui, &mut server, &mut events).await?; + } + assert_eq!(app.current_displayed_thread_id(), Some(focused)); + enable_side_retention(&mut app)?; + app.local_settings.tui.animations = false; + let size = Size::new(width, height); + // Resize refreshes the active native status, so install the fixture after reflow. + side_frame(&mut app, &mut tui, size)?; + let (name, draft, status) = if focused == main { + ("Main", "main draft", main_status) + } else { + ("Side", "side draft", side_status) + }; + app.chat_widget.setup_status_line( + vec![StatusLineItem::ModelName], + /*use_theme_colors*/ false, + ); + app.chat_widget + .set_status_line(Some(Line::from(status).into())); + app.chat_widget.apply_external_edit(draft.into()); + if index == 0 { + // Seed the main conversation before focusing the side chat. + continue; + } + + let frame = side_frame(&mut app, &mut tui, size)?; + assert!( + frame.contains("main draft") && frame.contains("side draft"), + "{frame}" + ); + let divider = app.conversation_frame.divider_area().expect("split pane"); + let buffer = tui.terminal.previous_buffer(); + let mut rows = vec![format!("{name} focused at {width}x{height}")]; + for (prefix, start, end) in [ + ("MainStatus", 0, divider.x), + ("SideStatus", divider.right(), width), + ] { + for y in 0..height { + let text: String = (start..end).map(|x| buffer[(x, y)].symbol()).collect(); + if text.trim_start().starts_with(prefix) { + let muted = buffer[(start + 2, y)].modifier.contains(Modifier::DIM); + let style = if muted { "muted" } else { "normal" }; + rows.push(format!("{style} {}", text.trim())); + } + } + } + frames.push(rows.join("\n")); + } + insta::assert_snapshot!(frames.join("\n\n"), @" + Side focused at 100x24 + muted MainStatusSummaryForThePrimaryWorkspaceContext + muted MainStatusDetailsForThePrimaryWorkspaceContext + normal SideStatusSummaryText + normal SideStatusDetails + + Main focused at 100x24 + normal MainStatusSummaryForThePrimaryWorkspaceContext + normal MainStatusDetailsForThePrimaryWorkspaceContext + muted SideStatusSummaryText + muted SideStatusDetails + + Main focused at 130x24 + normal MainStatusSummaryForThePrimaryWorkspaceContext + normal MainStatusDetailsForThePrimaryWorkspaceContext + muted SideStatusSummaryText SideStatusDetails + "); + + app.local_settings.tui.max_conversation_width = Some(40); + app.chat_widget.local_settings.tui.max_conversation_width = Some(40); + app.transcript_cells = vec![Arc::new(AgentMarkdownCell::new( + "The main answer keeps its line breaks when the side chat has focus.".into(), + app.config.cwd.as_path(), + ))]; + let size = Size::new(/*width*/ 130, /*height*/ 24); + let answer = |frame: &str| { + frame + .lines() + .map(|row| row.split_once('│').map_or(row, |(main, _)| main).trim()) + .skip_while(|row| !row.contains("The main answer")) + .take(2) + .collect::>() + .join("\n") + }; + let focused = answer(&side_frame(&mut app, &mut tui, size)?); + insta::assert_snapshot!(focused, @" + • The main answer keeps its line breaks + when the side chat has focus. + "); + app.select_agent_thread(&mut tui, &mut server, side).await?; + drain_app_events(&mut app, &mut tui, &mut server, &mut events).await?; + assert_eq!(app.current_displayed_thread_id(), Some(side)); + assert_eq!(answer(&side_frame(&mut app, &mut tui, size)?), focused); + server.shutdown().await?; + Ok(()) +} + +#[tokio::test] +async fn max_conversation_width_reloads_on_resume_picker_exit() -> Result<()> { + let mut app = make_test_app().await; + let mut server = Box::pin(crate::start_embedded_app_server_for_picker(&app.config)).await?; + let size = Size::new(/*width*/ 160, /*height*/ 24); + let mut tui = crate::tui::test_support::make_test_tui_with_size(size)?; + tui.set_owned_screen(/*owned*/ true)?; + for (config, expected_width) in [ + ("[tui]\nmax_conversation_width = 80\n", 80), + ("[tui]\nmax_conversation_width = 120\n", 120), + ("[tui]\n", 160), + ] { + std::fs::write(app.config.codex_home.join("config.toml"), config)?; + Box::pin(app.apply_resume_picker_selection( + &mut tui, + &mut server, + crate::resume_picker::SessionSelection::Exit, + )) + .await?; + let composer_area = app.render_chat_widget_frame(&mut tui, size)?; + assert_eq!( + ( + composer_area.width, + app.chat_widget.history_wrap_width(size.width), + ), + (expected_width, expected_width), + ); + } + server.shutdown().await?; + Ok(()) +} + +#[tokio::test] +async fn max_conversation_width_keeps_full_access_dialog_centered_over_capped_backdrop() +-> Result<()> { + let mut app = make_test_app().await; + app.local_settings.tui.max_conversation_width = Some(20); + let preset = codex_utils_approval_presets::builtin_approval_presets() + .into_iter() + .find(|preset| preset.id == "full-access") + .unwrap(); + app.chat_widget.open_full_access_confirmation( + preset, /*return_to_permissions*/ true, /*profile_selection*/ None, + ); + let size = Size::new(/*width*/ 120, /*height*/ 20); + let mut tui = crate::tui::test_support::make_test_tui_with_size(size)?; + let area = app.render_chat_widget_frame(&mut tui, size)?; + assert_eq!(area.width, 20); + let mut buffer = + crate::custom_terminal::test_support::last_rendered_buffer(&tui.terminal).clone(); + // Mask the capped backdrop's platform-dependent footer. Everything outside + // it should be blank except for the centered warning. + ratatui::widgets::Widget::render(ratatui::widgets::Clear, area, &mut buffer); + insta::assert_snapshot!(transcript_composer::buffer_text(&buffer)); + Ok(()) +} + +#[tokio::test] +async fn max_conversation_width_replays_inline_history_on_resume_picker_exit() -> Result<()> { + let mut app = make_test_app().await; + let mut server = Box::pin(crate::start_embedded_app_server_for_picker(&app.config)).await?; + let size = Size::new(/*width*/ 100, /*height*/ 24); + let mut tui = crate::tui::test_support::make_test_tui_with_size(size)?; + app.handle_draw_pre_render(&mut tui, size)?; + app.transcript_cells = vec![Arc::new(AgentMarkdownCell::new( + "existing history ".repeat(5), + app.config.cwd.as_path(), + ))]; + let wide = app.render_transcript_lines_for_reflow(size.width).lines; + let narrow = app.render_transcript_lines_for_reflow(/*width*/ 40).lines; + assert!(wide.len() < narrow.len()); + + // A cap above the terminal width changes the preference, but not the layout. + for (cap, expected) in [(120, vec![]), (40, narrow), (120, wide)] { + std::fs::write( + app.config.codex_home.join("config.toml"), + format!("[tui]\nmax_conversation_width = {cap}\n"), + )?; + Box::pin(app.apply_resume_picker_selection( + &mut tui, + &mut server, + crate::resume_picker::SessionSelection::Exit, + )) + .await?; + app.handle_draw_pre_render(&mut tui, size)?; + assert_eq!(tui.pending_history_lines_for_test(), expected); + tui.clear_pending_history_lines(); + } + server.shutdown().await?; + Ok(()) +} diff --git a/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__conversation_width_tests__max_conversation_width_keeps_full_access_dialog_centered_over_capped_backdrop.snap b/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__conversation_width_tests__max_conversation_width_keeps_full_access_dialog_centered_over_capped_backdrop.snap new file mode 100644 index 0000000000..3edf4976b6 --- /dev/null +++ b/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__conversation_width_tests__max_conversation_width_keeps_full_access_dialog_centered_over_capped_backdrop.snap @@ -0,0 +1,16 @@ +--- +source: tui/src/app/tests/conversation_width_tests.rs +expression: "transcript_composer::buffer_text(&buffer)" +--- + + Enable full access? + When Codex runs with full access, it can edit any file on your + computer and run commands with network, without your approval. + Exercise caution when enabling full access. This significantly + increases the risk of data loss, leaks, or unexpected behavior. + + + › 1. Yes, continue anyway Apply full access for this session + 2. Cancel Go back without enabling full access + + enter select · esc back diff --git a/codex-rs/tui/src/chatwidget/pets.rs b/codex-rs/tui/src/chatwidget/pets.rs index 4b862fb4f3..8e64827673 100644 --- a/codex-rs/tui/src/chatwidget/pets.rs +++ b/codex-rs/tui/src/chatwidget/pets.rs @@ -162,7 +162,8 @@ impl ChatWidget { } pub(crate) fn history_wrap_width(&self, width: u16) -> u16 { - width + self.local_settings + .conversation_width(width) .saturating_sub(self.ambient_pet_wrap_reserved_cols()) .max(1) } diff --git a/codex-rs/tui/src/chatwidget/rendering.rs b/codex-rs/tui/src/chatwidget/rendering.rs index 33f0832627..627afa2799 100644 --- a/codex-rs/tui/src/chatwidget/rendering.rs +++ b/codex-rs/tui/src/chatwidget/rendering.rs @@ -239,14 +239,26 @@ impl ChatWidget { } pub(crate) fn as_renderable(&self) -> RenderableItem<'_> { - self.as_renderable_with_options(crate::bottom_pane::ComposerRenderOptions::default()) + self.as_renderable_with_options( + crate::bottom_pane::ComposerRenderOptions::default(), + /*backdrop_right_inset*/ 0, + ) } pub(crate) fn as_renderable_with_options<'a>( &'a self, options: crate::bottom_pane::ComposerRenderOptions<'a>, + backdrop_right_inset: u16, ) -> RenderableItem<'a> { - let backdrop = self.as_backdrop_renderable(options); + let mut backdrop = self.as_backdrop_renderable(options); + if backdrop_right_inset > 0 { + backdrop = backdrop.inset(Insets::tlbr( + /*top*/ 0, + /*left*/ 0, + /*bottom*/ 0, + backdrop_right_inset, + )); + } match self.centered_dialog() { Some(dialog) => RenderableItem::Owned(Box::new(crate::bottom_pane::DialogOverlay { backdrop, diff --git a/codex-rs/tui/src/exec_cell/render.rs b/codex-rs/tui/src/exec_cell/render.rs index 2fa3c942aa..1e3c6fee33 100644 --- a/codex-rs/tui/src/exec_cell/render.rs +++ b/codex-rs/tui/src/exec_cell/render.rs @@ -19,7 +19,7 @@ use crate::style::accent_color; use crate::terminal_hyperlinks::HyperlinkLine; use crate::terminal_hyperlinks::LogicalLineSource; use crate::terminal_hyperlinks::adaptive_wrap_hyperlink_lines; -use crate::terminal_hyperlinks::plain_hyperlink_lines; +use crate::terminal_hyperlinks::annotate_web_urls; use crate::terminal_hyperlinks::prefix_hyperlink_lines; use crate::terminal_hyperlinks::remap_source_wrapped_line; use crate::terminal_hyperlinks::visible_lines; @@ -655,7 +655,7 @@ impl ExecCell { let output_opts = RtOptions::new(output_wrap_width).word_splitter(WordSplitter::NoHyphenation); let wrapped_output = adaptive_wrap_hyperlink_lines( - &plain_hyperlink_lines(raw_output.lines), + &annotate_web_urls(raw_output.lines), output_opts, ); @@ -895,6 +895,7 @@ mod tests { use super::*; use crate::render::line_utils::prefix_lines; use crate::render::line_utils::push_owned_lines; + use crate::terminal_hyperlinks::plain_hyperlink_lines; use crate::wrapping::adaptive_wrap_line; use codex_app_server_protocol::CommandExecutionSource as ExecCommandSource; use pretty_assertions::assert_eq; diff --git a/codex-rs/tui/src/insert_history.rs b/codex-rs/tui/src/insert_history.rs index 2396bfc001..a399335506 100644 --- a/codex-rs/tui/src/insert_history.rs +++ b/codex-rs/tui/src/insert_history.rs @@ -13,10 +13,13 @@ use crate::render::line_utils::line_to_static; use crate::terminal_hyperlinks::HyperlinkLine; use crate::terminal_hyperlinks::decorate_spans; use crate::terminal_hyperlinks::plain_hyperlink_lines; +use crate::terminal_hyperlinks::remap_source_wrapped_line; use crate::terminal_hyperlinks::remap_wrapped_line; +use crate::terminal_hyperlinks::with_detected_web_links; use crate::width::physical_row_count; use crate::wrapping::RtOptions; use crate::wrapping::adaptive_wrap_line; +use crate::wrapping::adaptive_wrap_line_to_width; use crate::wrapping::line_contains_url_like; use crate::wrapping::line_has_mixed_url_and_non_url_tokens; use crossterm::Command; @@ -46,6 +49,7 @@ use ratatui::text::Span; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum HistoryLineWrapPolicy { PreWrap, + PreWrapAtWidth(u16), Terminal, } @@ -263,23 +267,43 @@ pub(crate) fn wrap_history_hyperlink_lines( for line in lines { let line_wrapped = match wrap_policy { HistoryLineWrapPolicy::Terminal => vec![line.clone()], - HistoryLineWrapPolicy::PreWrap + HistoryLineWrapPolicy::PreWrapAtWidth(max_width) + if usize::from(max_width) < wrap_width => + { + let max_width = usize::from(max_width); + if line.width() <= max_width { + vec![line.clone()] + } else { + let indent = leading_whitespace_prefix(&line.line); + let options = if indent.width() < max_width { + RtOptions::new(max_width).subsequent_indent(indent) + } else { + RtOptions::new(max_width) + }; + let rows = adaptive_wrap_line_to_width(&line.line, options); + let source = with_detected_web_links(line, /*truncated*/ false); + remap_source_wrapped_line(&source, rows) + } + } + HistoryLineWrapPolicy::PreWrap | HistoryLineWrapPolicy::PreWrapAtWidth(_) if line_contains_url_like(&line.line) && !line_has_mixed_url_and_non_url_tokens(&line.line) => { vec![line.clone()] } - HistoryLineWrapPolicy::PreWrap => remap_wrapped_line( - line, - adaptive_wrap_line( - &line.line, - RtOptions::new(wrap_width) - .subsequent_indent(leading_whitespace_prefix(&line.line)), + HistoryLineWrapPolicy::PreWrap | HistoryLineWrapPolicy::PreWrapAtWidth(_) => { + remap_wrapped_line( + line, + adaptive_wrap_line( + &line.line, + RtOptions::new(wrap_width) + .subsequent_indent(leading_whitespace_prefix(&line.line)), + ) + .into_iter() + .map(|line| line_to_static(&line)) + .collect(), ) - .into_iter() - .map(|line| line_to_static(&line)) - .collect(), - ), + } }; wrapped_rows += line_wrapped .iter() @@ -457,6 +481,110 @@ mod tests { use ratatui::layout::Rect; use ratatui::style::Color; + #[test] + fn native_history_respects_width_cap_on_a_wider_terminal() { + let long_url = format!("https://example.com/{}", "a".repeat(86)); + let source = [HyperlinkLine::new(Line::from(long_url))]; + let (uncapped, _) = wrap_history_hyperlink_lines( + &source, + /*wrap_width*/ 160, + HistoryLineWrapPolicy::PreWrap, + ); + assert_eq!(uncapped, source); + let (capped, rows) = wrap_history_hyperlink_lines( + &source, + /*wrap_width*/ 160, + HistoryLineWrapPolicy::PreWrapAtWidth(80), + ); + assert!(capped.len() > 1); + assert_eq!(rows, capped.len()); + assert!(capped.iter().all(|line| line.width() <= 80)); + assert_eq!( + capped + .iter() + .map(|line| line.line.to_string()) + .collect::(), + source[0].line.to_string() + ); + let (narrow, _) = wrap_history_hyperlink_lines( + &source, + /*wrap_width*/ 60, + HistoryLineWrapPolicy::PreWrapAtWidth(80), + ); + let (default_narrow, _) = wrap_history_hyperlink_lines( + &source, + /*wrap_width*/ 60, + HistoryLineWrapPolicy::PreWrap, + ); + assert_eq!(narrow, default_narrow); + } + + #[test] + fn capped_history_keeps_a_fitting_hyphenated_url_intact() { + let url = "https://example.test/alpha-bravo"; + let source = HyperlinkLine::new(Line::from(format!("report: {url}"))); + let (rows, _) = wrap_history_hyperlink_lines( + &[source], + /*wrap_width*/ 120, + HistoryLineWrapPolicy::PreWrapAtWidth(36), + ); + pretty_assertions::assert_eq!( + rows.iter() + .map(|row| row.line.to_string()) + .collect::>(), + ["report:", url] + ); + } + + #[test] + fn capped_history_writes_full_targets_on_every_styled_url_fragment() { + use crate::terminal_hyperlinks::TerminalHyperlink; + use ratatui::style::Stylize; + + let url = "https://example.test/reports/alpha-bravo-charlie-delta-echo-foxtrot-golf"; + let mut source = HyperlinkLine::new(Line::from(vec![ + Span::raw(" │ "), + (&url[..12]).red(), + (&url[12..]).blue(), + ])); + let sgr = regex_lite::Regex::new(r"\x1b\[[0-9;]*m").unwrap(); + for target in [url, "https://other.test/explicit"] { + if target != url { + source.hyperlinks.push(TerminalHyperlink::web( + /*columns*/ 4..4 + url.len(), + target.to_string(), + )); + } + let (rows, _) = wrap_history_hyperlink_lines( + std::slice::from_ref(&source), + /*wrap_width*/ 120, + HistoryLineWrapPolicy::PreWrapAtWidth(32), + ); + let open = format!("\x1b]8;;{target}\x07"); + let mut fragments = Vec::new(); + for row in rows { + assert!(row.width() <= 32); + let mut bytes = Vec::new(); + write_history_line(&mut bytes, &row, /*wrap_width*/ 120).unwrap(); + let output = String::from_utf8(bytes).unwrap(); + let linked = output + .split(&open) + .skip(1) + .map(|part| { + part.split_once("\x1b]8;;\x07") + .expect("link closes on same row") + .0 + }) + .collect::(); + if !linked.is_empty() { + fragments.push(sgr.replace_all(&linked, "").into_owned()); + } + } + assert!(fragments.len() > 1); + pretty_assertions::assert_eq!(fragments.concat(), url); + } + } + #[test] fn long_history_batches_newlines_and_restores_the_cursor() { let width = 20; diff --git a/codex-rs/tui/src/local_settings.rs b/codex-rs/tui/src/local_settings.rs index 1cd1de2df5..e7665afa7f 100644 --- a/codex-rs/tui/src/local_settings.rs +++ b/codex-rs/tui/src/local_settings.rs @@ -31,6 +31,12 @@ pub(crate) struct LocalSettings { } impl LocalSettings { + pub(crate) fn conversation_width(&self, available_width: u16) -> u16 { + self.tui + .max_conversation_width + .map_or(available_width, |max_width| available_width.min(max_width)) + } + pub(crate) fn workspace_enabled(&self, config: &Config) -> bool { self.transcript_mode.is_owned() && config diff --git a/codex-rs/tui/src/snapshots/codex_tui__startup_draft__tests__startup_composer_width.snap b/codex-rs/tui/src/snapshots/codex_tui__startup_draft__tests__startup_composer_width.snap new file mode 100644 index 0000000000..15e6acb86f --- /dev/null +++ b/codex-rs/tui/src/snapshots/codex_tui__startup_draft__tests__startup_composer_width.snap @@ -0,0 +1,10 @@ +--- +source: tui/src/startup_draft_tests.rs +expression: "snapshots.join(\"\\n\")" +--- +inline (80/164 shaded): › Ask Codex to do anything +inline (80/164 shaded): › draft draft draft draft draft draft draft draft draft draft draft draft draft +inline (80/164 shaded): draft draft last startup word +owned (80/164 shaded): › Ask Codex to do anything +owned (80/164 shaded): › draft draft draft draft draft draft draft draft draft draft draft draft draft +owned (80/164 shaded): draft draft last startup word diff --git a/codex-rs/tui/src/startup_draft.rs b/codex-rs/tui/src/startup_draft.rs index 6aa7013712..228006e06e 100644 --- a/codex-rs/tui/src/startup_draft.rs +++ b/codex-rs/tui/src/startup_draft.rs @@ -62,6 +62,7 @@ pub(crate) struct StartupScreen { pub(crate) welcome_motion: crate::motion::MotionMode, pub(crate) keymap: RuntimeKeymap, pub(crate) disable_paste_burst: bool, + pub(crate) max_conversation_width: Option, } /// Identifies the first interactive surface expected for the current invocation. @@ -107,6 +108,7 @@ pub(crate) struct StartupDraftPump { header: Box, pub(crate) blossom: std::cell::RefCell, motion: crate::motion::MotionMode, + max_conversation_width: Option, bottom_pane: BottomPane, events: Pin + Send>>, app_event_rx: UnboundedReceiver, @@ -142,6 +144,7 @@ impl StartupDraft { tui.set_alt_screen_enabled(screen.use_alt_screen); let mut pump = StartupDraftPump::new(&tui, initial_screen, session_action); pump.motion = screen.welcome_motion; + pump.max_conversation_width = screen.max_conversation_width; pump.bottom_pane .set_status_line_enabled(screen.status_line_enabled); pump.bottom_pane.set_keymap_bindings(&screen.keymap); @@ -212,6 +215,7 @@ impl StartupDraftPump { header, blossom: std::cell::RefCell::new(blossom), motion: crate::system_motion::mode(), + max_conversation_width: None, bottom_pane: startup_draft_bottom_pane( AppEventSender::new(app_event_tx), tui.frame_requester(), @@ -323,6 +327,7 @@ impl StartupDraftPump { self.cancel_submission(); } self.configured_cwd = Some(cwd.to_path_buf()); + self.max_conversation_width = local_settings.tui.max_conversation_width; self.motion = crate::motion::MotionMode::from_animations_enabled( local_settings.tui.animations && local_settings.tui.effects.welcome, ); @@ -539,10 +544,15 @@ impl StartupDraftPump { } else { startup_draft_renderable(&self.header, &self.bottom_pane, self.session_action) }; + // Paint the startup conversation at the same width as the live one, + // without shrinking the terminal viewport. + let width = screen_size + .width + .min(self.max_conversation_width.unwrap_or(screen_size.width)); let desired_height = if owned { screen_size.height } else { - renderable.desired_height(screen_size.width) + renderable.desired_height(width) }; let hud = self .key_chord_matcher @@ -559,7 +569,8 @@ impl StartupDraftPump { }) }); tui.draw_with_resize_reflow(desired_height, screen_size, hud, |frame| { - let area = frame.area(); + let mut area = frame.area(); + area.width = area.width.min(width); renderable.render(area, frame.buffer); if let Some((x, y)) = renderable.cursor_pos(area) { frame.set_cursor_style(renderable.cursor_style(area)); diff --git a/codex-rs/tui/src/startup_draft_tests.rs b/codex-rs/tui/src/startup_draft_tests.rs index bb19dc3ef9..2cc354978a 100644 --- a/codex-rs/tui/src/startup_draft_tests.rs +++ b/codex-rs/tui/src/startup_draft_tests.rs @@ -35,6 +35,7 @@ where header, blossom: std::cell::RefCell::new(blossom), motion: crate::motion::MotionMode::Animated, + max_conversation_width: None, bottom_pane: startup_draft_bottom_pane( AppEventSender::new(tx), FrameRequester::test_dummy(), @@ -407,6 +408,70 @@ async fn startup_draft_clears_loading_status_when_starting_fresh() { ); } +#[tokio::test] +async fn first_startup_frame_caps_the_draft_without_resizing_the_viewport() -> anyhow::Result<()> { + use ratatui::layout::Size; + use ratatui::style::Color; + + let size = Size::new(/*width*/ 164, /*height*/ 57); + let draft = format!("{}last startup word", "draft ".repeat(15)); + let colors = crate::terminal_probe::DefaultColors { + fg: (225, 225, 225), + bg: (32, 37, 49), + }; + crate::terminal_palette::with_test_default_colors(colors, || { + let composer_bg = crate::style::user_message_bg(colors.bg); + let mut snapshots = Vec::new(); + for (mode, owned) in [("inline", false), ("owned", true)] { + let mut tui = crate::tui::test_support::make_test_tui_with_size(size)?; + tui.set_owned_screen(owned)?; + let mut pump = quiet_startup_test_pump(); + pump.motion = crate::motion::MotionMode::Reduced; + pump.max_conversation_width = Some(80); + for (text, line) in [("", "Ask Codex"), (&draft, "› draft")] { + pump.bottom_pane.insert_str(text); + pump.show(&mut tui)?; + + let buffer = tui.terminal.previous_buffer(); + assert_eq!(buffer.area.width, size.width); + let rows = buffer + .content() + .chunks(usize::from(size.width)) + .collect::>(); + let row_text = |row: &[ratatui::buffer::Cell]| { + row.iter() + .map(ratatui::buffer::Cell::symbol) + .collect::() + }; + let composer_row = rows + .iter() + .position(|row| row_text(row).contains(line)) + .expect("the first frame displays the placeholder or draft"); + assert_eq!(rows[composer_row][79].bg, composer_bg); + assert_eq!(rows[composer_row][80].bg, Color::Reset); + assert!(tui.terminal.last_known_cursor_pos.x < 80); + if !text.is_empty() { + assert!(row_text(rows[composer_row + 1]).contains("last startup word")); + assert_eq!(rows[composer_row + 1][79].bg, composer_bg); + assert_eq!(rows[composer_row + 1][80].bg, Color::Reset); + } + + for row in &rows[composer_row..composer_row + 1 + usize::from(!text.is_empty())] { + let shaded = row.iter().filter(|cell| cell.bg == composer_bg).count(); + snapshots.push(format!( + "{mode} ({shaded}/{} shaded): {}", + row.len(), + row_text(row).trim_end() + )); + } + } + tui.set_owned_screen(/*owned*/ false)?; + } + insta::assert_snapshot!("startup_composer_width", snapshots.join("\n")); + Ok(()) + }) +} + #[tokio::test] async fn startup_draft_hydrates_its_header_without_moving_the_composer() { let codex_home = tempfile::tempdir().expect("create temporary Codex home"); diff --git a/codex-rs/tui/src/startup_presentation.rs b/codex-rs/tui/src/startup_presentation.rs index 8fc0b4799d..0fb8532ede 100644 --- a/codex-rs/tui/src/startup_presentation.rs +++ b/codex-rs/tui/src/startup_presentation.rs @@ -73,6 +73,7 @@ pub(super) async fn load( .is_none_or(|items| !items.is_empty()); let keymap = RuntimeKeymap::from_config(&settings.keymap).map_err(io::Error::other)?; let disable_paste_burst = settings.disable_paste_burst.unwrap_or(false); + let max_conversation_width = settings.max_conversation_width; let welcome_motion = crate::motion::MotionMode::from_animations_enabled( settings.animations && settings.effects.welcome, ); @@ -87,6 +88,7 @@ pub(super) async fn load( welcome_motion, keymap, disable_paste_burst, + max_conversation_width, }, }) } diff --git a/codex-rs/tui/src/startup_presentation_tests.rs b/codex-rs/tui/src/startup_presentation_tests.rs index a4127c947f..127c3bcd93 100644 --- a/codex-rs/tui/src/startup_presentation_tests.rs +++ b/codex-rs/tui/src/startup_presentation_tests.rs @@ -22,7 +22,7 @@ async fn selected_profile_controls_submit_before_the_first_frame() -> anyhow::Re &selected, // Presentation must not compile the local execution profile. format!( - "default_permissions = \"server-only\"\ndisable_paste_burst = true\n[permissions.server-only]\nextends = \"missing-local-parent\"\n[tui.keymap.composer]\nsubmit = {submit}\n" + "default_permissions = \"server-only\"\ndisable_paste_burst = true\n[permissions.server-only]\nextends = \"missing-local-parent\"\n[tui]\nmax_conversation_width = 80\n[tui.keymap.composer]\nsubmit = {submit}\n" ), )?; let presentation = load( @@ -42,8 +42,9 @@ async fn selected_profile_controls_submit_before_the_first_frame() -> anyhow::Re ( presentation.screen.keymap.composer.submit, presentation.screen.disable_paste_burst, + presentation.screen.max_conversation_width, ), - (expected_bindings, true), + (expected_bindings, true, Some(80)), ); } Ok(()) diff --git a/codex-rs/tui/src/terminal_hyperlinks.rs b/codex-rs/tui/src/terminal_hyperlinks.rs index bedbdb7738..c12fe906e0 100644 --- a/codex-rs/tui/src/terminal_hyperlinks.rs +++ b/codex-rs/tui/src/terminal_hyperlinks.rs @@ -565,6 +565,33 @@ pub(crate) fn annotate_web_urls_in_line(line: Line<'static>) -> HyperlinkLine { out } +/// Hard newlines defeat terminal URL detection. Discover destinations on the source +/// before projecting them onto wrapped rows, preserving any explicit link targets. +pub(crate) fn with_detected_web_links( + line: &HyperlinkLine, + truncated: bool, +) -> std::borrow::Cow<'_, HyperlinkLine> { + use std::borrow::Cow; + + let mut text = line_text(&line.line); + if truncated { + // The final whitespace-delimited token may be only a prefix of a URL. + text.truncate(text.rfind(char::is_whitespace).unwrap_or_default()); + } + let mut source = Cow::Borrowed(line); + for link in web_links_in_text(&text) { + if !line.hyperlinks.iter().any(|existing| { + existing.columns.start < link.columns.end && link.columns.start < existing.columns.end + }) { + source.to_mut().hyperlinks.push(link); + } + } + if let Cow::Owned(annotated) = &mut source { + annotated.hyperlinks.sort_by_key(|link| link.columns.start); + } + source +} + /// Project annotations from the exact source slices used by the existing wrapping algorithm. pub(crate) fn remap_source_wrapped_line( source: &HyperlinkLine, diff --git a/codex-rs/tui/src/tool_output.rs b/codex-rs/tui/src/tool_output.rs index 4cdfe816bc..3c1d6ca3a2 100644 --- a/codex-rs/tui/src/tool_output.rs +++ b/codex-rs/tui/src/tool_output.rs @@ -8,6 +8,7 @@ use crate::terminal_hyperlinks::HyperlinkLine; use crate::terminal_hyperlinks::LogicalLineSource; use crate::terminal_hyperlinks::TerminalHyperlink; use crate::terminal_hyperlinks::remap_source_wrapped_line; +use crate::terminal_hyperlinks::with_detected_web_links; use crate::ui_consts::transcript_hint; use crate::wrapping::RtOptions; use crate::wrapping::word_wrap_line_with_source; @@ -104,8 +105,13 @@ impl ToolOutputPreview { self.omitted += 1; self.full = true; } + let source = if wrapped.len() > 1 { + with_detected_web_links(&bounded, truncated) + } else { + std::borrow::Cow::Borrowed(&bounded) + }; self.lines.extend(remap_source_wrapped_line( - &bounded, + &source, wrapped.into_iter().take(remaining).collect(), )); } diff --git a/codex-rs/tui/src/tool_output_tests.rs b/codex-rs/tui/src/tool_output_tests.rs index 0e48bb3e9c..e8c3a04f47 100644 --- a/codex-rs/tui/src/tool_output_tests.rs +++ b/codex-rs/tui/src/tool_output_tests.rs @@ -177,3 +177,55 @@ fn command_preview_matches_streamed_and_completed_output() { .join("\n"), )); } + +#[test] +fn command_preview_links_every_fragment_of_a_bare_url() { + use crate::exec_cell::CommandOutput; + use crate::exec_cell::new_active_exec_command; + use crate::history_cell::HistoryCell; + use codex_app_server_protocol::CommandExecutionSource; + use std::time::Duration; + + let mut cell = new_active_exec_command( + "call-preview".into(), + vec!["bash".into(), "-lc".into(), "echo output".into()], + Vec::new(), + CommandExecutionSource::UnifiedExecStartup, + /*interaction_input*/ None, + /*animations_enabled*/ false, + ); + let url = "https://example.test/reports/alpha-bravo-charlie-delta-echo-foxtrot"; + cell.complete_call( + "call-preview", + CommandOutput::new(/*exit_code*/ 0, url.into()), + Duration::ZERO, + ); + let rows = cell.display_hyperlink_lines(/*width*/ 40); + let mut fragments = Vec::new(); + for row in rows { + for link in row.hyperlinks { + assert_eq!(link.terminal_destination().as_deref(), Some(url)); + fragments.push( + row.line + .to_string() + .chars() + .skip(link.columns.start) + .take(link.columns.len()) + .collect::(), + ); + } + } + assert!(fragments.len() > 1); + assert_eq!(fragments.concat(), url); +} + +#[test] +fn bounded_preview_does_not_invent_a_destination_for_a_partial_url() { + let text = format!("https://example.test/{}", "a".repeat(200)); + let rows = tool_output_hyperlink_preview( + [Line::from(text)], + /*width*/ 40, + /*total_lines*/ 1, + ); + assert!(rows.iter().all(|row| row.hyperlinks.is_empty())); +} diff --git a/codex-rs/tui/src/transcript_reflow.rs b/codex-rs/tui/src/transcript_reflow.rs index c15c742675..89edd00410 100644 --- a/codex-rs/tui/src/transcript_reflow.rs +++ b/codex-rs/tui/src/transcript_reflow.rs @@ -56,6 +56,10 @@ impl TranscriptReflowState { self.visible_history_rows } + pub(crate) fn last_observed_width(&self) -> Option { + self.last_observed_width + } + /// Record the width observed during a draw and report whether it is new or changed. /// /// The first observed width initializes the state without scheduling a rebuild because no diff --git a/codex-rs/tui/src/tui_startup_tests.rs b/codex-rs/tui/src/tui_startup_tests.rs index 73b533ab5c..8952d7bc4f 100644 --- a/codex-rs/tui/src/tui_startup_tests.rs +++ b/codex-rs/tui/src/tui_startup_tests.rs @@ -215,6 +215,7 @@ async fn startup_typeahead_pty_child() { welcome_motion: crate::motion::MotionMode::Animated, keymap: crate::keymap::RuntimeKeymap::defaults(), disable_paste_burst: false, + max_conversation_width: None, }, ) .expect("initialize the real startup composer");