diff --git a/codex-rs/config/src/types.rs b/codex-rs/config/src/types.rs index 50a24db534..cb4b589ea9 100644 --- a/codex-rs/config/src/types.rs +++ b/codex-rs/config/src/types.rs @@ -532,6 +532,26 @@ pub struct ModelAvailabilityNuxConfig { pub shown_count: HashMap, } +pub const DEFAULT_TERMINAL_RESIZE_REFLOW_SLOW_THRESHOLD_MS: u64 = 400; +pub const DEFAULT_TERMINAL_RESIZE_REFLOW_MAX_ROWS: usize = 12_000; + +/// Experimental terminal resize-reflow tuning knobs. +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct TerminalResizeReflowToml { + /// Disable resize reflow for the current transcript when a reflow operation exceeds this many + /// milliseconds. Set to `0` to disable the slow-reflow time limit. + #[serde(default)] + #[schemars(range(min = 0))] + pub slow_threshold_ms: Option, + + /// Trim resize-reflow replay to the most recent rendered terminal rows when the transcript + /// exceeds this cap. + #[serde(default)] + #[schemars(range(min = 1))] + pub max_rows: Option, +} + /// Collection of settings that are specific to the TUI. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)] #[schemars(deny_unknown_fields)] @@ -584,6 +604,10 @@ pub struct Tui { /// Startup tooltip availability NUX state persisted by the TUI. #[serde(default)] pub model_availability_nux: ModelAvailabilityNuxConfig, + + /// Experimental terminal resize-reflow tuning knobs. + #[serde(default)] + pub terminal_resize_reflow: TerminalResizeReflowToml, } const fn default_true() -> bool { diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index 3f97359917..c9eb1b17fa 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -497,6 +497,9 @@ "telepathy": { "type": "boolean" }, + "terminal_resize_reflow": { + "type": "boolean" + }, "tool_call_mcp_elicitation": { "type": "boolean" }, @@ -1930,6 +1933,27 @@ }, "type": "object" }, + "TerminalResizeReflowToml": { + "additionalProperties": false, + "description": "Experimental terminal resize-reflow tuning knobs.", + "properties": { + "max_rows": { + "default": null, + "description": "Trim resize-reflow replay to the most recent rendered terminal rows when the transcript exceeds this cap.", + "format": "uint", + "minimum": 1.0, + "type": "integer" + }, + "slow_threshold_ms": { + "default": null, + "description": "Disable resize reflow for the current transcript when a reflow operation exceeds this many milliseconds. Set to `0` to disable the slow-reflow time limit.", + "format": "uint64", + "minimum": 0.0, + "type": "integer" + } + }, + "type": "object" + }, "ToolSuggestConfig": { "additionalProperties": false, "properties": { @@ -2060,6 +2084,18 @@ }, "type": "array" }, + "terminal_resize_reflow": { + "allOf": [ + { + "$ref": "#/definitions/TerminalResizeReflowToml" + } + ], + "default": { + "max_rows": null, + "slow_threshold_ms": null + }, + "description": "Experimental terminal resize-reflow tuning knobs." + }, "terminal_title": { "default": null, "description": "Ordered list of terminal title item identifiers.\n\nWhen set, the TUI renders the selected items into the terminal window/tab title. When unset, the TUI defaults to: `spinner` and `project`.", @@ -2493,6 +2529,9 @@ "telepathy": { "type": "boolean" }, + "terminal_resize_reflow": { + "type": "boolean" + }, "tool_call_mcp_elicitation": { "type": "boolean" }, diff --git a/codex-rs/core/src/config/config_tests.rs b/codex-rs/core/src/config/config_tests.rs index e7c7aa31dd..b02aec9b39 100644 --- a/codex-rs/core/src/config/config_tests.rs +++ b/codex-rs/core/src/config/config_tests.rs @@ -43,6 +43,7 @@ use codex_config::types::NotificationMethod; use codex_config::types::Notifications; use codex_config::types::SandboxWorkspaceWrite; use codex_config::types::SkillsConfig; +use codex_config::types::TerminalResizeReflowToml; use codex_config::types::ToolSuggestDiscoverableType; use codex_config::types::Tui; use codex_config::types::TuiNotificationSettings; @@ -497,6 +498,28 @@ fn config_toml_deserializes_model_availability_nux() { ("gpt-foo".to_string(), 2), ]), }, + terminal_resize_reflow: TerminalResizeReflowToml::default(), + } + ); +} + +#[test] +fn config_toml_deserializes_terminal_resize_reflow_config() { + let toml = r#" +[tui.terminal_resize_reflow] +slow_threshold_ms = 350 +max_rows = 9000 +"#; + let cfg: ConfigToml = + toml::from_str(toml).expect("TOML deserialization should succeed for resize reflow config"); + + assert_eq!( + cfg.tui + .expect("tui config should deserialize") + .terminal_resize_reflow, + TerminalResizeReflowToml { + slow_threshold_ms: Some(350), + max_rows: Some(9000), } ); } @@ -1295,10 +1318,73 @@ fn tui_config_missing_notifications_field_defaults_to_enabled() { terminal_title: None, theme: None, model_availability_nux: ModelAvailabilityNuxConfig::default(), + terminal_resize_reflow: TerminalResizeReflowToml::default(), } ); } +#[tokio::test] +async fn runtime_config_resolves_terminal_resize_reflow_defaults_and_overrides() { + let cfg = Config::load_from_base_config_with_overrides( + ConfigToml::default(), + ConfigOverrides::default(), + tempdir().expect("tempdir").abs(), + ) + .await + .expect("load default config"); + + assert_eq!( + cfg.terminal_resize_reflow, + TerminalResizeReflowConfig::default() + ); + + let cfg = Config::load_from_base_config_with_overrides( + ConfigToml { + tui: Some(Tui { + terminal_resize_reflow: TerminalResizeReflowToml { + slow_threshold_ms: Some(350), + max_rows: Some(9000), + }, + ..Default::default() + }), + ..Default::default() + }, + ConfigOverrides::default(), + tempdir().expect("tempdir").abs(), + ) + .await + .expect("load overridden config"); + + assert_eq!( + cfg.terminal_resize_reflow.slow_threshold, + Some(Duration::from_millis(/*millis*/ 350)) + ); + assert_eq!(cfg.terminal_resize_reflow.max_rows, 9000); + + let cfg = Config::load_from_base_config_with_overrides( + ConfigToml { + tui: Some(Tui { + terminal_resize_reflow: TerminalResizeReflowToml { + slow_threshold_ms: Some(0), + max_rows: None, + }, + ..Default::default() + }), + ..Default::default() + }, + ConfigOverrides::default(), + tempdir().expect("tempdir").abs(), + ) + .await + .expect("load config with disabled slow threshold"); + + assert_eq!(cfg.terminal_resize_reflow.slow_threshold, None); + assert_eq!( + cfg.terminal_resize_reflow.max_rows, + TerminalResizeReflowConfig::default().max_rows + ); +} + #[tokio::test] async fn test_sandbox_config_parsing() { let sandbox_full_access = r#" diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index 995c2008c5..d47b93ef29 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -32,6 +32,8 @@ use codex_config::profile_toml::ConfigProfile; use codex_config::types::ApprovalsReviewer; use codex_config::types::AuthCredentialsStoreMode; use codex_config::types::DEFAULT_OTEL_ENVIRONMENT; +use codex_config::types::DEFAULT_TERMINAL_RESIZE_REFLOW_MAX_ROWS; +use codex_config::types::DEFAULT_TERMINAL_RESIZE_REFLOW_SLOW_THRESHOLD_MS; use codex_config::types::History; use codex_config::types::McpServerConfig; use codex_config::types::McpServerDisabledReason; @@ -93,6 +95,7 @@ use std::io::ErrorKind; use std::path::Path; use std::path::PathBuf; use std::sync::Arc; +use std::time::Duration; use crate::config::permissions::compile_permission_profile; use crate::config::permissions::get_readable_roots_required_for_codex_runtime; @@ -366,6 +369,9 @@ pub struct Config { /// Syntax highlighting theme override (kebab-case name). pub tui_theme: Option, + /// Experimental terminal resize-reflow tuning knobs. + pub terminal_resize_reflow: TerminalResizeReflowConfig, + /// The absolute directory that should be treated as the current working /// directory for the session. All relative paths inside the business-logic /// layer are resolved against this path. @@ -622,6 +628,23 @@ impl Default for MultiAgentV2Config { } } +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct TerminalResizeReflowConfig { + pub slow_threshold: Option, + pub max_rows: usize, +} + +impl Default for TerminalResizeReflowConfig { + fn default() -> Self { + Self { + slow_threshold: Some(Duration::from_millis( + DEFAULT_TERMINAL_RESIZE_REFLOW_SLOW_THRESHOLD_MS, + )), + max_rows: DEFAULT_TERMINAL_RESIZE_REFLOW_MAX_ROWS, + } + } +} + impl AuthManagerConfig for Config { fn codex_home(&self) -> PathBuf { self.codex_home.to_path_buf() @@ -1479,6 +1502,32 @@ fn resolve_multi_agent_v2_config( } } +fn resolve_terminal_resize_reflow_config(config_toml: &ConfigToml) -> TerminalResizeReflowConfig { + let defaults = TerminalResizeReflowConfig::default(); + let Some(tui) = config_toml.tui.as_ref() else { + return defaults; + }; + + TerminalResizeReflowConfig { + slow_threshold: tui + .terminal_resize_reflow + .slow_threshold_ms + .map(|millis| { + if millis == 0 { + None + } else { + Some(Duration::from_millis(millis)) + } + }) + .unwrap_or(defaults.slow_threshold), + max_rows: tui + .terminal_resize_reflow + .max_rows + .filter(|rows| *rows > 0) + .unwrap_or(defaults.max_rows), + } +} + fn multi_agent_v2_toml_config(features: Option<&FeaturesToml>) -> Option<&MultiAgentV2ConfigToml> { match features?.multi_agent_v2.as_ref()? { FeatureToml::Enabled(_) => None, @@ -1833,6 +1882,7 @@ impl Config { .unwrap_or(WebSearchMode::Cached); let web_search_config = resolve_web_search_config(&cfg, &config_profile); let multi_agent_v2 = resolve_multi_agent_v2_config(&cfg, &config_profile); + let terminal_resize_reflow = resolve_terminal_resize_reflow_config(&cfg); let agent_roles = agent_roles::load_agent_roles(fs, &cfg, &config_layer_stack, &mut startup_warnings) @@ -2365,6 +2415,7 @@ impl Config { tui_status_line: cfg.tui.as_ref().and_then(|t| t.status_line.clone()), tui_terminal_title: cfg.tui.as_ref().and_then(|t| t.terminal_title.clone()), tui_theme: cfg.tui.as_ref().and_then(|t| t.theme.clone()), + terminal_resize_reflow, otel: { let t: OtelConfigToml = cfg.otel.unwrap_or_default(); let log_user_prompt = t.log_user_prompt.unwrap_or(false); diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index 5d95aabeb2..6f85debe67 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -1110,8 +1110,8 @@ impl App { app_server: &mut AppServerSession, event: TuiEvent, ) -> Result { - let terminal_resize_reflow_enabled = self.terminal_resize_reflow_enabled(); - if terminal_resize_reflow_enabled && matches!(event, TuiEvent::Draw | TuiEvent::Resize) { + let terminal_resize_reflow_active = self.terminal_resize_reflow_active(); + if terminal_resize_reflow_active && matches!(event, TuiEvent::Draw | TuiEvent::Resize) { self.handle_draw_pre_render(tui)?; } else if matches!(event, TuiEvent::Draw | TuiEvent::Resize) { let size = tui.terminal.size()?; @@ -1151,13 +1151,14 @@ impl App { self.chat_widget.pre_draw_tick(); let desired_height = self.chat_widget.desired_height(tui.terminal.size()?.width); - if terminal_resize_reflow_enabled { - tui.draw_with_resize_reflow(desired_height, |frame| { + if terminal_resize_reflow_active { + let stats = tui.draw_with_resize_reflow(desired_height, |frame| { self.chat_widget.render(frame.area(), frame.buffer); if let Some((x, y)) = self.chat_widget.cursor_pos(frame.area()) { frame.set_cursor_position((x, y)); } })?; + self.maybe_disable_slow_resize_reflow_flush(stats); } else { tui.draw(desired_height, |frame| { self.chat_widget.render(frame.area(), frame.buffer); diff --git a/codex-rs/tui/src/app/config_persistence.rs b/codex-rs/tui/src/app/config_persistence.rs index edfde7ceeb..f83c6ca48d 100644 --- a/codex-rs/tui/src/app/config_persistence.rs +++ b/codex-rs/tui/src/app/config_persistence.rs @@ -21,11 +21,17 @@ impl App { } pub(super) async fn refresh_in_memory_config_from_disk(&mut self) -> Result<()> { + let previous_resize_reflow_config = self.config.terminal_resize_reflow; let mut config = self .rebuild_config_for_cwd(self.chat_widget.config_ref().cwd.to_path_buf()) .await?; self.apply_runtime_policy_overrides(&mut config); + let resize_reflow_config_changed = + previous_resize_reflow_config != config.terminal_resize_reflow; self.config = config; + if resize_reflow_config_changed { + self.transcript_reflow.clear_runtime_disable(); + } self.chat_widget.sync_plugin_mentions_config(&self.config); Ok(()) } @@ -548,6 +554,7 @@ mod tests { use codex_protocol::protocol::EventMsg; use codex_protocol::protocol::SessionConfiguredEvent; use pretty_assertions::assert_eq; + use std::time::Duration; use tempfile::tempdir; #[tokio::test] @@ -661,6 +668,37 @@ mod tests { Ok(()) } + #[tokio::test] + async fn refresh_in_memory_config_from_disk_updates_resize_reflow_config_and_clears_disable() + -> Result<()> { + let mut app = make_test_app().await; + let codex_home = tempdir()?; + app.config.codex_home = codex_home.path().to_path_buf().abs(); + app.transcript_reflow.record_elapsed( + crate::transcript_reflow::ResizeReflowDisableReason::RenderSlow, + Duration::from_millis(/*millis*/ 251), + Duration::from_millis(/*millis*/ 250), + ); + std::fs::write( + codex_home.path().join("config.toml"), + r#" +[tui.terminal_resize_reflow] +slow_threshold_ms = 350 +max_rows = 9000 +"#, + )?; + + app.refresh_in_memory_config_from_disk().await?; + + assert_eq!( + app.config.terminal_resize_reflow.slow_threshold, + Some(Duration::from_millis(/*millis*/ 350)) + ); + assert_eq!(app.config.terminal_resize_reflow.max_rows, 9000); + assert!(!app.transcript_reflow.is_runtime_disabled()); + Ok(()) + } + #[tokio::test] async fn rebuild_config_for_resume_or_fallback_uses_current_config_on_same_cwd_error() -> Result<()> { diff --git a/codex-rs/tui/src/app/event_dispatch.rs b/codex-rs/tui/src/app/event_dispatch.rs index 6a1dbba38a..99677f9651 100644 --- a/codex-rs/tui/src/app/event_dispatch.rs +++ b/codex-rs/tui/src/app/event_dispatch.rs @@ -194,6 +194,9 @@ impl App { self.transcript_reflow.clear(); return Ok(AppRunControl::Continue); } + if !self.terminal_resize_reflow_active() { + return Ok(AppRunControl::Continue); + } let end = self.transcript_cells.len(); tracing::debug!( "ConsolidateAgentMessage: transcript_cells.len()={end}, source_len={}", @@ -228,6 +231,9 @@ impl App { self.transcript_reflow.clear(); return Ok(AppRunControl::Continue); } + if !self.terminal_resize_reflow_active() { + return Ok(AppRunControl::Continue); + } let end = self.transcript_cells.len(); let start = trailing_run_start::( &self.transcript_cells, diff --git a/codex-rs/tui/src/app/history_ui.rs b/codex-rs/tui/src/app/history_ui.rs index 703cc38c3d..3eeb315cbc 100644 --- a/codex-rs/tui/src/app/history_ui.rs +++ b/codex-rs/tui/src/app/history_ui.rs @@ -83,10 +83,15 @@ impl App { } pub(super) fn reset_app_ui_state_after_clear(&mut self) { + self.reset_transcript_state_after_clear(); + } + + pub(super) fn reset_transcript_state_after_clear(&mut self) { self.overlay = None; self.transcript_cells.clear(); self.deferred_history_lines.clear(); self.has_emitted_history_lines = false; + self.transcript_reflow.clear(); self.backtrack = BacktrackState::default(); self.backtrack_render_pending = false; } diff --git a/codex-rs/tui/src/app/resize_reflow.rs b/codex-rs/tui/src/app/resize_reflow.rs index 06e306f30d..4208918f65 100644 --- a/codex-rs/tui/src/app/resize_reflow.rs +++ b/codex-rs/tui/src/app/resize_reflow.rs @@ -10,6 +10,8 @@ //! before consolidation is marked as stream-time work so consolidation can force one final rebuild //! from the finalized source. +use std::collections::VecDeque; +use std::time::Duration; use std::time::Instant; use codex_features::Feature; @@ -20,10 +22,31 @@ use super::App; use super::trailing_run_start; use crate::history_cell; use crate::history_cell::HistoryCell; +use crate::transcript_reflow::ResizeReflowDisableReason; use crate::transcript_reflow::TRANSCRIPT_REFLOW_DEBOUNCE; use crate::transcript_reflow::TranscriptReflowKind; use crate::tui; +#[derive(Debug, Clone, Copy)] +pub(super) struct ResizeReflowRunStats { + kind: TranscriptReflowKind, + width: u16, + cell_count: usize, + rendered_line_count: usize, + row_cap_limited: bool, +} + +struct ReflowCellDisplay { + lines: Vec>, + is_stream_continuation: bool, +} + +pub(super) struct ReflowRenderResult { + pub(super) lines: Vec>, + pub(super) rendered_cell_count: usize, + pub(super) row_cap_limited: bool, +} + impl App { pub(super) fn reset_history_emission_state(&mut self) { self.has_emitted_history_lines = false; @@ -63,22 +86,151 @@ impl App { } } - pub(super) fn append_history_cell_lines_for_insert( - &mut self, - lines: &mut Vec>, - cell: &dyn HistoryCell, - width: u16, - ) { - lines.extend(self.display_lines_for_history_insert(cell, width)); - } - pub(super) fn terminal_resize_reflow_enabled(&self) -> bool { self.config.features.enabled(Feature::TerminalResizeReflow) } - fn schedule_resize_reflow(&mut self, kind: TranscriptReflowKind) -> bool { - debug_assert!(self.terminal_resize_reflow_enabled()); - self.transcript_reflow.schedule_debounced(kind) + pub(super) fn terminal_resize_reflow_active(&self) -> bool { + self.terminal_resize_reflow_enabled() && !self.transcript_reflow.is_runtime_disabled() + } + + fn schedule_resize_reflow( + &mut self, + kind: TranscriptReflowKind, + target_width: Option, + ) -> bool { + debug_assert!(self.terminal_resize_reflow_active()); + self.transcript_reflow + .schedule_debounced(kind, target_width) + } + + fn resize_reflow_slow_threshold(&self) -> Option { + self.config.terminal_resize_reflow.slow_threshold + } + + fn resize_reflow_max_rows(&self) -> usize { + self.config.terminal_resize_reflow.max_rows + } + + pub(super) fn maybe_disable_slow_resize_reflow_flush( + &mut self, + stats: tui::ResizeReflowDrawStats, + ) { + let Some(threshold) = self.resize_reflow_slow_threshold() else { + return; + }; + if !stats.flushed_reflow_history + || !self.transcript_reflow.record_elapsed( + ResizeReflowDisableReason::FlushSlow, + stats.reflow_flush_elapsed, + threshold, + ) + { + return; + } + + tracing::warn!( + elapsed_ms = stats.reflow_flush_elapsed.as_millis(), + threshold_ms = threshold.as_millis(), + reason = ?self.transcript_reflow.runtime_disabled_reason(), + "terminal resize reflow disabled for current transcript after slow terminal flush" + ); + self.maybe_show_slow_resize_reflow_disabled_warning(stats.reflow_flush_elapsed, threshold); + } + + fn maybe_disable_slow_resize_reflow_render( + &mut self, + elapsed: Duration, + stats: ResizeReflowRunStats, + ) { + let Some(threshold) = self.resize_reflow_slow_threshold() else { + return; + }; + if !self.transcript_reflow.record_elapsed( + ResizeReflowDisableReason::RenderSlow, + elapsed, + threshold, + ) { + return; + } + + tracing::warn!( + elapsed_ms = elapsed.as_millis(), + threshold_ms = threshold.as_millis(), + kind = ?stats.kind, + width = stats.width, + cell_count = stats.cell_count, + rendered_line_count = stats.rendered_line_count, + reason = ?self.transcript_reflow.runtime_disabled_reason(), + "terminal resize reflow disabled for current transcript after slow render" + ); + self.maybe_show_slow_resize_reflow_disabled_warning(elapsed, threshold); + } + + fn maybe_note_row_cap_limited_reflow(&mut self, stats: ResizeReflowRunStats) { + if !stats.row_cap_limited { + return; + } + + let max_rows = self.resize_reflow_max_rows(); + tracing::warn!( + max_rows, + kind = ?stats.kind, + width = stats.width, + cell_count = stats.cell_count, + rendered_line_count = stats.rendered_line_count, + "terminal resize reflow limited scrollback with rendered row cap" + ); + self.maybe_show_row_cap_resize_reflow_trimmed_warning(stats.rendered_line_count); + } + + fn maybe_show_slow_resize_reflow_disabled_warning( + &mut self, + elapsed: Duration, + threshold: Duration, + ) { + if self.transcript_reflow.take_runtime_disable_warning_needed() { + self.chat_widget.add_info_message( + format!( + "Terminal resize reflow paused for this session because resizing took {}ms, above the {}ms limit. Future resizes will use legacy terminal behavior until the transcript is cleared.", + elapsed.as_millis(), + threshold.as_millis() + ), + /*hint*/ None, + ); + } + } + + fn maybe_show_row_cap_resize_reflow_trimmed_warning(&mut self, kept_line_count: usize) { + if self.transcript_reflow.take_row_cap_trim_warning_needed() { + self.chat_widget.add_info_message( + format!( + "Terminal resize reflow limited scrollback to the most recent {kept_line_count} rows before rendering because the row cap is {}.", + self.resize_reflow_max_rows(), + ), + /*hint*/ None, + ); + } + } + + fn show_resize_reflow_timing_debug_message( + &mut self, + elapsed: Duration, + stats: ResizeReflowRunStats, + ) { + let kind = match stats.kind { + TranscriptReflowKind::VisibleRows => "visible-row", + TranscriptReflowKind::Full => "full", + }; + self.chat_widget.add_info_message( + format!( + "Terminal resize reflow {kind} pass took {}ms ({} rows from {} cells).", + elapsed.as_millis(), + stats.rendered_line_count, + stats.cell_count + ), + /*hint*/ None, + ); } /// Finish stream consolidation by repairing any resize work that happened during streaming. @@ -93,6 +245,9 @@ impl App { self.transcript_reflow.clear(); return Ok(()); } + if !self.terminal_resize_reflow_active() { + return Ok(()); + } if self.transcript_reflow.take_stream_finish_reflow_needed() { self.schedule_immediate_resize_reflow(tui); @@ -108,6 +263,9 @@ impl App { self.transcript_reflow.clear(); return; } + if !self.terminal_resize_reflow_active() { + return; + } self.transcript_reflow .schedule_immediate(TranscriptReflowKind::Full); tui.frame_requester().schedule_frame(); @@ -123,6 +281,9 @@ impl App { self.transcript_reflow.clear(); return Ok(()); } + if !self.terminal_resize_reflow_active() { + return Ok(()); + } self.schedule_immediate_resize_reflow(tui); self.maybe_run_resize_reflow(tui)?; if !self.transcript_reflow.has_pending_reflow() { @@ -145,14 +306,17 @@ impl App { frame_requester: &tui::FrameRequester, ) -> bool { let width = self.transcript_reflow.note_width(size.width); + let full_reflow_needed = self + .transcript_reflow + .full_reflow_needed_for_width(size.width); let height_growth_exposes_rows = size.height > last_known_screen_size.height; - let should_rebuild_transcript = width.changed || height_growth_exposes_rows; + let should_rebuild_transcript = full_reflow_needed || height_growth_exposes_rows; if width.changed || width.initialized { self.chat_widget.on_terminal_resize(size.width); } if should_rebuild_transcript { - if self.terminal_resize_reflow_enabled() { - let reflow_kind = if width.changed { + if self.terminal_resize_reflow_active() { + let reflow_kind = if full_reflow_needed { TranscriptReflowKind::Full } else { TranscriptReflowKind::VisibleRows @@ -162,19 +326,23 @@ impl App { { self.transcript_reflow.mark_resize_requested_during_stream(); } - if self.schedule_resize_reflow(reflow_kind) { + let target_width = match reflow_kind { + TranscriptReflowKind::Full => Some(size.width), + TranscriptReflowKind::VisibleRows => None, + }; + if self.schedule_resize_reflow(reflow_kind, target_width) { frame_requester.schedule_frame(); } else { frame_requester.schedule_frame_in(TRANSCRIPT_REFLOW_DEBOUNCE); } - } else if width.changed { + } else if !self.terminal_resize_reflow_enabled() && width.changed { self.transcript_reflow.clear(); } } if size != last_known_screen_size { self.refresh_status_line(); } - if self.terminal_resize_reflow_enabled() { + if self.terminal_resize_reflow_active() { self.maybe_clear_resize_reflow_without_terminal(); } should_rebuild_transcript @@ -185,6 +353,9 @@ impl App { self.transcript_reflow.clear(); return; } + if !self.terminal_resize_reflow_active() { + return; + } let Some(deadline) = self.transcript_reflow.pending_until() else { return; }; @@ -204,7 +375,7 @@ impl App { tui.terminal.last_known_screen_size, &tui.frame_requester(), ); - if should_rebuild_transcript && self.terminal_resize_reflow_enabled() { + if should_rebuild_transcript && self.terminal_resize_reflow_active() { // Resize-sensitive history inserts queued before this frame may be wrapped for the old // viewport or targeted at rows no longer visible. Drop them and let resize reflow // rebuild from transcript cells. @@ -225,10 +396,22 @@ impl App { self.transcript_reflow.clear(); return Ok(()); } + if !self.terminal_resize_reflow_active() { + return Ok(()); + } let Some(deadline) = self.transcript_reflow.pending_until() else { return Ok(()); }; - if Instant::now() < deadline || self.overlay.is_some() { + let now = Instant::now(); + if now < deadline { + // Later resize events push the reflow deadline out, while the frame scheduler coalesces + // delayed draws to the earliest requested instant. If an early draw arrives before the + // latest quiet-period deadline, re-arm the draw so the pending reflow cannot get stuck + // until the next keypress. + tui.frame_requester().schedule_frame_in(deadline - now); + return Ok(()); + } + if self.overlay.is_some() { return Ok(()); } @@ -244,69 +427,181 @@ impl App { let reflow_ran_during_stream = !self.transcript_cells.is_empty() && self.should_mark_reflow_as_stream_time(); - match reflow_kind { - TranscriptReflowKind::Full => self.reflow_transcript_now(tui)?, - TranscriptReflowKind::VisibleRows => self.repaint_visible_transcript_rows(tui)?, - } + let started = Instant::now(); + let stats = match reflow_kind { + TranscriptReflowKind::Full => self.reflow_transcript_now(tui, reflow_kind)?, + TranscriptReflowKind::VisibleRows => { + self.repaint_visible_transcript_rows(tui, reflow_kind)? + } + }; + let elapsed = started.elapsed(); + self.show_resize_reflow_timing_debug_message(elapsed, stats); + self.maybe_disable_slow_resize_reflow_render(elapsed, stats); + self.transcript_reflow.mark_reflowed_width(stats.width); - if reflow_ran_during_stream { + if reflow_ran_during_stream && !self.transcript_reflow.is_runtime_disabled() { self.transcript_reflow.mark_ran_during_stream(); } + if !self.transcript_reflow.is_runtime_disabled() { + // Some terminals settle their final reported width after the repaint that handled the + // last resize event. Request one cheap follow-up draw so `handle_draw_pre_render` can + // sample that width and schedule a final reflow if needed. + tui.frame_requester() + .schedule_frame_in(TRANSCRIPT_REFLOW_DEBOUNCE); + } Ok(()) } - fn reflow_transcript_now(&mut self, tui: &mut tui::Tui) -> Result<()> { - // Drop any queued pre-resize/pre-consolidation inserts before rebuilding from cells. - tui.clear_pending_history_lines(); + fn reflow_transcript_now( + &mut self, + tui: &mut tui::Tui, + kind: TranscriptReflowKind, + ) -> Result { + let width = tui.terminal.size()?.width; + let cell_count = self.transcript_cells.len(); if self.transcript_cells.is_empty() { + // Drop any queued pre-resize/pre-consolidation inserts before rebuilding from cells. + tui.clear_pending_history_lines(); self.reset_history_emission_state(); - return Ok(()); + return Ok(ResizeReflowRunStats { + kind, + width, + cell_count, + rendered_line_count: 0, + row_cap_limited: false, + }); } + let reflow_result = self.render_transcript_lines_for_reflow(width); + let reflowed_lines = reflow_result.lines; + let stats = ResizeReflowRunStats { + kind, + width, + cell_count: reflow_result.rendered_cell_count, + rendered_line_count: reflowed_lines.len(), + row_cap_limited: reflow_result.row_cap_limited, + }; + self.maybe_note_row_cap_limited_reflow(stats); + + // Drop any queued pre-resize/pre-consolidation inserts before rebuilding from cells. + tui.clear_pending_history_lines(); if tui.is_alt_screen_active() { tui.terminal.clear_visible_screen()?; } else { tui.terminal.clear_scrollback_and_visible_screen_ansi()?; } - self.reset_history_emission_state(); - - let width = tui.terminal.size()?.width; - let mut reflowed_lines = Vec::new(); - // Iterate by index to avoid cloning the Vec and bumping Arc refcounts. - for i in 0..self.transcript_cells.len() { - let cell = self.transcript_cells[i].clone(); - self.append_history_cell_lines_for_insert(&mut reflowed_lines, cell.as_ref(), width); - } + self.deferred_history_lines.clear(); if !reflowed_lines.is_empty() { tui.insert_reflowed_history_lines(reflowed_lines); } - Ok(()) + Ok(stats) } - fn repaint_visible_transcript_rows(&mut self, tui: &mut tui::Tui) -> Result<()> { - tui.clear_pending_history_lines(); - if self.transcript_cells.is_empty() { - self.reset_history_emission_state(); - return Ok(()); - } - - tui.terminal.clear_visible_screen()?; - self.reset_history_emission_state(); - + fn repaint_visible_transcript_rows( + &mut self, + tui: &mut tui::Tui, + kind: TranscriptReflowKind, + ) -> Result { let width = tui.terminal.size()?.width; - let mut reflowed_lines = Vec::new(); - for i in 0..self.transcript_cells.len() { - let cell = self.transcript_cells[i].clone(); - self.append_history_cell_lines_for_insert(&mut reflowed_lines, cell.as_ref(), width); + let cell_count = self.transcript_cells.len(); + if self.transcript_cells.is_empty() { + tui.clear_pending_history_lines(); + self.reset_history_emission_state(); + return Ok(ResizeReflowRunStats { + kind, + width, + cell_count, + rendered_line_count: 0, + row_cap_limited: false, + }); } + + let reflow_result = self.render_transcript_lines_for_reflow(width); + let reflowed_lines = reflow_result.lines; + let stats = ResizeReflowRunStats { + kind, + width, + cell_count: reflow_result.rendered_cell_count, + rendered_line_count: reflowed_lines.len(), + row_cap_limited: reflow_result.row_cap_limited, + }; + self.maybe_note_row_cap_limited_reflow(stats); + + tui.clear_pending_history_lines(); + tui.terminal.clear_visible_screen()?; + self.deferred_history_lines.clear(); if !reflowed_lines.is_empty() { tui.insert_reflowed_history_lines(reflowed_lines); } - Ok(()) + Ok(stats) + } + + pub(super) fn render_transcript_lines_for_reflow(&mut self, width: u16) -> ReflowRenderResult { + let row_cap = (self.resize_reflow_max_rows() > 0).then_some(self.resize_reflow_max_rows()); + let mut cell_displays = VecDeque::new(); + let mut rendered_rows = 0usize; + let mut start = self.transcript_cells.len(); + + while start > 0 { + start -= 1; + let cell = self.transcript_cells[start].clone(); + let lines = cell.display_lines(width); + rendered_rows += lines.len(); + cell_displays.push_front(ReflowCellDisplay { + lines, + is_stream_continuation: cell.is_stream_continuation(), + }); + + if row_cap.is_some_and(|max_rows| rendered_rows > max_rows) { + break; + } + } + + while start > 0 + && cell_displays + .front() + .is_some_and(|display| display.is_stream_continuation) + { + start -= 1; + let cell = self.transcript_cells[start].clone(); + cell_displays.push_front(ReflowCellDisplay { + lines: cell.display_lines(width), + is_stream_continuation: cell.is_stream_continuation(), + }); + } + + let rendered_cell_count = cell_displays.len(); + let mut has_emitted_history_lines = false; + let mut reflowed_lines = Vec::new(); + for display in cell_displays { + if !display.lines.is_empty() && !display.is_stream_continuation { + if has_emitted_history_lines { + reflowed_lines.push(Line::from("")); + } else { + has_emitted_history_lines = true; + } + } + reflowed_lines.extend(display.lines); + } + let row_cap_limited = + row_cap.is_some_and(|max_rows| start > 0 || reflowed_lines.len() > max_rows); + if let Some(max_rows) = row_cap + && reflowed_lines.len() > max_rows + { + let trimmed_line_count = reflowed_lines.len() - max_rows; + reflowed_lines = reflowed_lines.split_off(trimmed_line_count); + } + self.has_emitted_history_lines = !reflowed_lines.is_empty(); + + ReflowRenderResult { + lines: reflowed_lines, + rendered_cell_count, + row_cap_limited, + } } /// Return whether current transcript state should be treated as stream-time resize state. diff --git a/codex-rs/tui/src/app/session_lifecycle.rs b/codex-rs/tui/src/app/session_lifecycle.rs index 89d5e1d43e..98f8c6ec58 100644 --- a/codex-rs/tui/src/app/session_lifecycle.rs +++ b/codex-rs/tui/src/app/session_lifecycle.rs @@ -385,13 +385,8 @@ impl App { } pub(super) fn reset_for_thread_switch(&mut self, tui: &mut tui::Tui) -> Result<()> { - self.overlay = None; - self.transcript_cells.clear(); - self.deferred_history_lines.clear(); + self.reset_transcript_state_after_clear(); tui.clear_pending_history_lines(); - self.has_emitted_history_lines = false; - self.backtrack = BacktrackState::default(); - self.backtrack_render_pending = false; Self::clear_terminal_for_thread_switch(&mut tui.terminal)?; Ok(()) } diff --git a/codex-rs/tui/src/app/tests.rs b/codex-rs/tui/src/app/tests.rs index 5c7416bad5..b6c95fb667 100644 --- a/codex-rs/tui/src/app/tests.rs +++ b/codex-rs/tui/src/app/tests.rs @@ -15,6 +15,7 @@ use crate::chatwidget::tests::set_fast_mode_test_catalog; use crate::file_search::FileSearchManager; use crate::history_cell::AgentMessageCell; use crate::history_cell::HistoryCell; +use crate::history_cell::PlainHistoryCell; use crate::history_cell::UserHistoryCell; use crate::history_cell::new_session_info; use crate::multi_agents::AgentPickerThreadEntry; @@ -3681,6 +3682,92 @@ fn test_thread_session(thread_id: ThreadId, cwd: PathBuf) -> ThreadSessionState } } +fn enable_terminal_resize_reflow(app: &mut App) { + app.config + .features + .set_enabled(Feature::TerminalResizeReflow, /*enabled*/ true) + .expect("feature should be configurable"); +} + +fn disable_resize_reflow_for_test(app: &mut App) { + assert!(app.transcript_reflow.record_elapsed( + crate::transcript_reflow::ResizeReflowDisableReason::RenderSlow, + std::time::Duration::from_millis(/*millis*/ 251), + std::time::Duration::from_millis(/*millis*/ 250), + )); +} + +fn plain_line_cell(text: impl Into) -> Arc { + Arc::new(PlainHistoryCell::new(vec![Line::from(text.into())])) as Arc +} + +fn rendered_line_text(line: &Line<'static>) -> String { + line.spans + .iter() + .map(|span| span.content.as_ref()) + .collect() +} + +#[tokio::test] +async fn capped_resize_reflow_renders_recent_suffix_only() { + let (mut app, _rx, _op_rx) = make_test_app_with_channels().await; + app.config.terminal_resize_reflow.max_rows = 5; + app.transcript_cells = (0..20) + .map(|i| plain_line_cell(format!("cell {i}"))) + .collect(); + + let rendered = app.render_transcript_lines_for_reflow(/*width*/ 80); + + assert!(rendered.row_cap_limited); + assert!( + rendered.rendered_cell_count < app.transcript_cells.len(), + "row-capped reflow should not render the whole transcript" + ); + assert_eq!(rendered.lines.len(), 5); + assert_eq!( + rendered + .lines + .iter() + .map(rendered_line_text) + .collect::>(), + vec![ + "cell 17".to_string(), + String::new(), + "cell 18".to_string(), + String::new(), + "cell 19".to_string(), + ] + ); +} + +#[tokio::test] +async fn uncapped_resize_reflow_renders_all_cells_under_row_limit() { + let (mut app, _rx, _op_rx) = make_test_app_with_channels().await; + app.config.terminal_resize_reflow.max_rows = 100; + app.transcript_cells = (0..3) + .map(|i| plain_line_cell(format!("cell {i}"))) + .collect(); + + let rendered = app.render_transcript_lines_for_reflow(/*width*/ 80); + + assert!(!rendered.row_cap_limited); + assert_eq!(rendered.rendered_cell_count, app.transcript_cells.len()); + assert_eq!( + rendered + .lines + .iter() + .map(rendered_line_text) + .collect::>(), + vec![ + "cell 0".to_string(), + String::new(), + "cell 1".to_string(), + String::new(), + "cell 2".to_string(), + ] + ); +} + fn test_turn(turn_id: &str, status: TurnStatus, items: Vec) -> Turn { Turn { id: turn_id.to_string(), @@ -4400,6 +4487,37 @@ async fn replace_chat_widget_reseeds_collab_agent_metadata_for_replay() { ); } +#[tokio::test] +async fn replace_chat_widget_preserves_resize_reflow_runtime_disable() { + let (mut app, _app_event_rx, _op_rx) = make_test_app_with_channels().await; + enable_terminal_resize_reflow(&mut app); + disable_resize_reflow_for_test(&mut app); + + let replacement = ChatWidget::new_with_app_event(ChatWidgetInit { + config: app.config.clone(), + frame_requester: crate::tui::FrameRequester::test_dummy(), + app_event_tx: app.app_event_tx.clone(), + initial_user_message: None, + enhanced_keys_supported: app.enhanced_keys_supported, + has_chatgpt_account: app.chat_widget.has_chatgpt_account(), + model_catalog: app.model_catalog.clone(), + feedback: app.feedback.clone(), + is_first_run: false, + status_account_display: app.chat_widget.status_account_display().cloned(), + initial_plan_type: app.chat_widget.current_plan_type(), + model: Some(app.chat_widget.current_model().to_string()), + startup_tooltip_override: None, + status_line_invalid_items_warned: app.status_line_invalid_items_warned.clone(), + terminal_title_invalid_items_warned: app.terminal_title_invalid_items_warned.clone(), + session_telemetry: app.session_telemetry.clone(), + }); + + app.replace_chat_widget(replacement); + + assert!(app.transcript_reflow.is_runtime_disabled()); + assert!(!app.terminal_resize_reflow_active()); +} + #[tokio::test] async fn refreshed_snapshot_session_persists_resumed_turns() { let mut app = make_test_app().await; @@ -4732,6 +4850,44 @@ async fn clear_only_ui_reset_preserves_chat_session_state() { assert_eq!(app.chat_widget.composer_text_with_pending(), "draft prompt"); } +#[tokio::test] +async fn runtime_disabled_resize_reflow_is_inactive_even_when_feature_enabled() { + let mut app = make_test_app().await; + enable_terminal_resize_reflow(&mut app); + + assert!(app.terminal_resize_reflow_enabled()); + assert!(app.terminal_resize_reflow_active()); + + disable_resize_reflow_for_test(&mut app); + + assert!(app.terminal_resize_reflow_enabled()); + assert!(!app.terminal_resize_reflow_active()); +} + +#[tokio::test] +async fn reset_app_ui_state_after_clear_resets_resize_reflow_runtime_disable() { + let mut app = make_test_app().await; + enable_terminal_resize_reflow(&mut app); + disable_resize_reflow_for_test(&mut app); + + app.reset_app_ui_state_after_clear(); + + assert!(!app.transcript_reflow.is_runtime_disabled()); + assert!(app.terminal_resize_reflow_active()); +} + +#[tokio::test] +async fn reset_transcript_state_after_clear_resets_resize_reflow_runtime_disable() { + let mut app = make_test_app().await; + enable_terminal_resize_reflow(&mut app); + disable_resize_reflow_for_test(&mut app); + + app.reset_transcript_state_after_clear(); + + assert!(!app.transcript_reflow.is_runtime_disabled()); + assert!(app.terminal_resize_reflow_active()); +} + #[tokio::test] async fn session_summary_skips_when_no_usage_or_resume_hint() { assert!( diff --git a/codex-rs/tui/src/app/thread_routing.rs b/codex-rs/tui/src/app/thread_routing.rs index 11f7638f9d..f6a4513d65 100644 --- a/codex-rs/tui/src/app/thread_routing.rs +++ b/codex-rs/tui/src/app/thread_routing.rs @@ -669,6 +669,7 @@ impl App { } AppCommandView::ReloadUserConfig => { app_server.reload_user_config().await?; + self.refresh_in_memory_config_from_disk().await?; Ok(true) } AppCommandView::OverrideTurnContext { .. } => Ok(true), diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index edfa39891c..00db8202f1 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -11095,6 +11095,7 @@ impl ChatWidget { self.config.config_layer_stack = config.config_layer_stack.clone(); self.config.realtime = config.realtime.clone(); self.config.memories = config.memories.clone(); + self.config.terminal_resize_reflow = config.terminal_resize_reflow; } pub(crate) fn open_review_popup(&mut self) { diff --git a/codex-rs/tui/src/insert_history.rs b/codex-rs/tui/src/insert_history.rs index 13fbcfdc3e..bf4ad4bad4 100644 --- a/codex-rs/tui/src/insert_history.rs +++ b/codex-rs/tui/src/insert_history.rs @@ -1,10 +1,9 @@ //! Inserts finalized history rows into terminal scrollback. //! //! Codex uses the terminal scrollback itself for finalized chat history, so inserting a history -//! cell is an escape-sequence operation rather than a normal ratatui render. The legacy insertion -//! path may move the inline viewport when new history arrives. The resize-reflow insertion path is -//! deliberately separate because it is replaying already-owned transcript rows after a resize and -//! must preserve the viewport position chosen by the reflow draw path. +//! cell is an escape-sequence operation rather than a normal ratatui render. The mode determines +//! whether new history may move the inline viewport or whether resize reflow should replay rows +//! through full-screen scrolling while preserving the viewport chosen by the reflow draw path. use std::fmt; use std::io; @@ -47,6 +46,7 @@ use ratatui::text::Span; pub enum InsertHistoryMode { Standard, Zellij, + FullScreenReplay, } impl InsertHistoryMode { @@ -59,86 +59,6 @@ impl InsertHistoryMode { } } -/// Insert `lines` above the viewport without changing the viewport's logical row. -/// -/// This is used by terminal resize reflow after Codex has cleared and rebuilt its owned -/// scrollback from transcript source. Keep this path separate from `insert_history_lines_with_mode` -/// so the default history insertion behavior remains the pre-reflow implementation. -pub fn insert_history_lines_preserving_viewport( - terminal: &mut crate::custom_terminal::Terminal, - lines: Vec, - is_zellij: bool, -) -> io::Result<()> -where - B: Backend + Write, -{ - let area = terminal.viewport_area; - let last_cursor_pos = terminal.last_known_cursor_pos; - let writer = terminal.backend_mut(); - - let wrap_width = area.width.max(1) as usize; - let mut wrapped = Vec::new(); - let mut wrapped_rows = 0usize; - - for line in &lines { - let line_wrapped = - if line_contains_url_like(line) && !line_has_mixed_url_and_non_url_tokens(line) { - vec![line.clone()] - } else { - adaptive_wrap_line(line, RtOptions::new(wrap_width)) - }; - wrapped_rows += line_wrapped - .iter() - .map(|wrapped_line| wrapped_line.width().max(1).div_ceil(wrap_width)) - .sum::(); - wrapped.extend(line_wrapped); - } - let wrapped_lines = wrapped_rows as u16; - - if is_zellij { - let zellij_start = wrapped.len().saturating_sub(area.top() as usize); - let zellij_lines = &wrapped[zellij_start..]; - let cursor_top = area.top().saturating_sub(zellij_lines.len() as u16); - queue!(writer, MoveTo(0, cursor_top))?; - - for (i, line) in zellij_lines.iter().enumerate() { - if i > 0 { - queue!(writer, Print("\r\n"))?; - } - write_history_line(writer, line, wrap_width)?; - } - } else if area.top() > 0 { - let cursor_top = area.top().saturating_sub(1); - - // Limit the scroll region to rows above the viewport, then write the rebuilt transcript - // into that region without treating free space below the viewport as room for live output. - queue!(writer, SetScrollRegion(1..area.top()))?; - queue!(writer, MoveTo(0, cursor_top))?; - - let scroll_bottom = area.top().saturating_sub(1); - let mut advance_row = cursor_top; - for line in &wrapped { - // Anchor each advance to avoid wrap-pending drift when the previous row reached the - // right edge while replaying source-backed history. - queue!(writer, MoveTo(0, advance_row), Print("\n"))?; - if advance_row < scroll_bottom { - advance_row += 1; - } - write_history_line(writer, line, wrap_width)?; - } - - queue!(writer, ResetScrollRegion)?; - } - - queue!(writer, MoveTo(last_cursor_pos.x, last_cursor_pos.y))?; - - let _ = writer; - if wrapped_lines > 0 { - terminal.note_history_rows_inserted(wrapped_lines); - } - Ok(()) -} - /// Insert `lines` above the viewport using the terminal's backend writer /// (avoids direct stdout references). pub fn insert_history_lines( @@ -158,7 +78,9 @@ where /// emits newlines at the screen bottom to create space (since Zellij ignores scroll /// region escapes) and writes lines at computed absolute positions. Both modes /// update `terminal.viewport_area` so subsequent draw passes know where the -/// viewport moved to. +/// viewport moved to. In `FullScreenReplay` mode every line is replayed through +/// normal full-screen scrolling so terminals that drop scroll-region output from +/// scrollback can still rebuild deep history after a resize. pub fn insert_history_lines_with_mode( terminal: &mut crate::custom_terminal::Terminal, lines: Vec, @@ -204,9 +126,16 @@ where } let wrapped_lines = wrapped_rows as u16; - if matches!(mode, InsertHistoryMode::Zellij) { + if matches!( + mode, + InsertHistoryMode::Zellij | InsertHistoryMode::FullScreenReplay + ) { let space_below = screen_size.height.saturating_sub(area.bottom()); - let shift_down = wrapped_lines.min(space_below); + let shift_down = if matches!(mode, InsertHistoryMode::Zellij) { + wrapped_lines.min(space_below) + } else { + 0 + }; let scroll_up_amount = wrapped_lines.saturating_sub(shift_down); if scroll_up_amount > 0 { @@ -894,14 +823,20 @@ mod tests { let height: u16 = 8; let backend = VT100Backend::new(width, height); let mut term = crate::custom_terminal::Terminal::with_options(backend).expect("terminal"); - let viewport = Rect::new(0, 4, width, 2); + let viewport = Rect::new(/*x*/ 0, /*y*/ 4, width, /*height*/ 2); term.set_viewport_area(viewport); let line: Line<'static> = Line::from("zellij history"); insert_history_lines_with_mode(&mut term, vec![line], InsertHistoryMode::Zellij) .expect("insert zellij history"); - let rows: Vec = term.backend().vt100().screen().rows(0, width).collect(); + let start_row = 0; + let rows: Vec = term + .backend() + .vt100() + .screen() + .rows(start_row, width) + .collect(); assert!( rows.iter().any(|row| row.contains("zellij history")), "expected zellij history row in screen output, rows: {rows:?}" @@ -909,4 +844,34 @@ mod tests { assert_eq!(term.viewport_area, Rect::new(0, 5, width, 2)); assert_eq!(term.visible_history_rows(), 1); } + + #[test] + fn vt100_full_screen_replay_preserves_viewport() { + let width: u16 = 32; + let height: u16 = 8; + let backend = VT100Backend::new(width, height); + let mut term = crate::custom_terminal::Terminal::with_options(backend).expect("terminal"); + let viewport = Rect::new(/*x*/ 0, /*y*/ 4, width, /*height*/ 2); + term.set_viewport_area(viewport); + + let lines: Vec> = (0..12) + .map(|idx| Line::from(format!("reflow line {idx:02}"))) + .collect(); + insert_history_lines_with_mode(&mut term, lines, InsertHistoryMode::FullScreenReplay) + .expect("insert reflow history"); + + let start_row = 0; + let rows: Vec = term + .backend() + .vt100() + .screen() + .rows(start_row, width) + .collect(); + assert!( + rows.iter().any(|row| row.contains("reflow line 11")), + "expected replayed history tail in screen output, rows: {rows:?}" + ); + assert_eq!(term.viewport_area, viewport); + assert_eq!(term.visible_history_rows(), viewport.top()); + } } diff --git a/codex-rs/tui/src/transcript_reflow.rs b/codex-rs/tui/src/transcript_reflow.rs index 340e95cc56..1d7454ade1 100644 --- a/codex-rs/tui/src/transcript_reflow.rs +++ b/codex-rs/tui/src/transcript_reflow.rs @@ -19,11 +19,16 @@ pub(crate) const TRANSCRIPT_REFLOW_DEBOUNCE: Duration = Duration::from_millis(75 #[derive(Debug, Default)] pub(crate) struct TranscriptReflowState { - last_render_width: Option, + last_observed_width: Option, + last_reflow_width: Option, + pending_full_reflow_width: Option, pending_until: Option, pending_kind: Option, ran_during_stream: bool, resize_requested_during_stream: bool, + runtime_disabled: Option, + runtime_disable_warning_shown: bool, + row_cap_trim_warning_shown: bool, } /// Describes how much terminal history repair is needed for a pending resize. @@ -35,6 +40,15 @@ pub(crate) enum TranscriptReflowKind { Full, } +/// Describes why resize reflow was disabled for the current transcript lifetime. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum ResizeReflowDisableReason { + /// Re-rendering transcript cells exceeded the slow-reflow threshold. + RenderSlow, + /// Writing reflowed rows back into the terminal exceeded the slow-reflow threshold. + FlushSlow, +} + impl TranscriptReflowState { /// Reset all width, pending deadline, and stream repair state. /// @@ -51,25 +65,44 @@ impl TranscriptReflowState { /// old-width transcript has been emitted yet. Treating initialization as a real resize would /// make the first draw do redundant scrollback work. pub(crate) fn note_width(&mut self, width: u16) -> TranscriptWidthChange { - let previous_width = self.last_render_width.replace(width); + let previous_width = self.last_observed_width.replace(width); + if previous_width.is_none() { + self.last_reflow_width = Some(width); + } TranscriptWidthChange { changed: previous_width.is_some_and(|previous| previous != width), initialized: previous_width.is_none(), } } - /// Schedule a coalesced reflow. Returns true if the pending reflow is already due. + /// Return whether scrollback still needs to be rebuilt at `width`. /// - /// Repeated resize events keep the existing deadline instead of pushing it out, so continuous - /// resizing cannot postpone scrollback repair indefinitely. - pub(crate) fn schedule_debounced(&mut self, kind: TranscriptReflowKind) -> bool { + /// This compares against the width that actually rebuilt scrollback, not just the most recently + /// observed terminal width. A terminal can report the final size after the reflow that handled + /// the resize event, so the follow-up draw must be able to request one more full reflow even if + /// the observed-width tracker already saw that value. + pub(crate) fn full_reflow_needed_for_width(&self, width: u16) -> bool { + self.last_reflow_width != Some(width) && self.pending_full_reflow_width != Some(width) + } + + /// Schedule a trailing-debounced reflow. Returns false because resize events wait for a quiet + /// period before rebuilding terminal scrollback. + /// + /// Repeated resize events push the deadline out so dragging a terminal edge rebuilds scrollback + /// at the final observed width rather than at intermediate widths. + pub(crate) fn schedule_debounced( + &mut self, + kind: TranscriptReflowKind, + target_width: Option, + ) -> bool { + debug_assert!(!self.is_runtime_disabled()); let now = Instant::now(); - let due_now = self.pending_is_due(now); - self.record_pending_kind(kind); - if self.pending_until.is_none() { - self.pending_until = Some(now + TRANSCRIPT_REFLOW_DEBOUNCE); + if matches!(kind, TranscriptReflowKind::Full) { + self.pending_full_reflow_width = target_width; } - due_now + self.record_pending_kind(kind); + self.pending_until = Some(now + TRANSCRIPT_REFLOW_DEBOUNCE); + false } /// Schedule an immediate reflow for the next draw opportunity. @@ -77,6 +110,10 @@ impl TranscriptReflowState { /// This is used after stream consolidation when waiting for the debounce interval would leave /// visible terminal-wrapped stream rows in the finalized transcript. pub(crate) fn schedule_immediate(&mut self, kind: TranscriptReflowKind) { + debug_assert!(!self.is_runtime_disabled()); + if matches!(kind, TranscriptReflowKind::Full) { + self.pending_full_reflow_width = None; + } self.record_pending_kind(kind); self.pending_until = Some(Instant::now()); } @@ -114,6 +151,62 @@ impl TranscriptReflowState { pub(crate) fn clear_pending_reflow(&mut self) { self.pending_until = None; self.pending_kind = None; + self.pending_full_reflow_width = None; + } + + /// Remember the terminal width that actually rebuilt transcript scrollback. + /// + /// Resize scheduling is driven by observed widths, but debounced redraws may run before a + /// terminal emulator has settled on its final size. Keeping the rendered width separate avoids + /// confusing "seen during a draw" with "scrollback has been repaired at this width". + pub(crate) fn mark_reflowed_width(&mut self, width: u16) -> bool { + self.last_reflow_width.replace(width) != Some(width) + } + + pub(crate) fn clear_runtime_disable(&mut self) { + self.runtime_disabled = None; + self.runtime_disable_warning_shown = false; + self.row_cap_trim_warning_shown = false; + } + + pub(crate) fn is_runtime_disabled(&self) -> bool { + self.runtime_disabled.is_some() + } + + pub(crate) fn runtime_disabled_reason(&self) -> Option { + self.runtime_disabled + } + + pub(crate) fn take_runtime_disable_warning_needed(&mut self) -> bool { + if self.runtime_disabled.is_none() || self.runtime_disable_warning_shown { + return false; + } + self.runtime_disable_warning_shown = true; + true + } + + pub(crate) fn take_row_cap_trim_warning_needed(&mut self) -> bool { + if self.row_cap_trim_warning_shown { + return false; + } + self.row_cap_trim_warning_shown = true; + true + } + + pub(crate) fn record_elapsed( + &mut self, + reason: ResizeReflowDisableReason, + elapsed: Duration, + threshold: Duration, + ) -> bool { + if elapsed <= threshold || self.runtime_disabled.is_some() { + return false; + } + + self.runtime_disabled = Some(reason); + self.clear_pending_reflow(); + self.clear_stream_flags(); + true } /// Remember that a reflow actually rebuilt history before stream consolidation completed. @@ -155,10 +248,10 @@ impl TranscriptReflowState { } } -/// Describes how the latest draw width relates to the previous draw width. +/// Describes how the latest draw width relates to the previous observed draw width. /// /// `initialized` means this was the first width observed by the state machine. `changed` means a -/// previously rendered transcript width exists and differs from the new width. +/// previously observed transcript width exists and differs from the new width. pub(crate) struct TranscriptWidthChange { pub(crate) changed: bool, pub(crate) initialized: bool, @@ -169,36 +262,120 @@ mod tests { use super::*; #[test] - fn schedule_debounced_does_not_postpone_existing_reflow() { + fn schedule_debounced_postpones_existing_reflow() { let mut state = TranscriptReflowState::default(); - assert!(!state.schedule_debounced(TranscriptReflowKind::VisibleRows)); + assert!(!state.schedule_debounced( + TranscriptReflowKind::VisibleRows, + /*target_width*/ None + )); let first_deadline = state.pending_until().expect("pending reflow"); std::thread::sleep(Duration::from_millis(1)); - assert!(!state.schedule_debounced(TranscriptReflowKind::VisibleRows)); + assert!(!state.schedule_debounced( + TranscriptReflowKind::VisibleRows, + /*target_width*/ None + )); - assert_eq!(state.pending_until(), Some(first_deadline)); + assert!( + state.pending_until().expect("pending reflow") > first_deadline, + "a later resize should push the debounce deadline out" + ); } #[test] - fn schedule_debounced_reports_due_existing_reflow() { + fn schedule_debounced_postpones_due_existing_reflow() { let mut state = TranscriptReflowState::default(); state.set_due_for_test(); + let before_reschedule = Instant::now(); - assert!(state.schedule_debounced(TranscriptReflowKind::VisibleRows)); + assert!(!state.schedule_debounced( + TranscriptReflowKind::VisibleRows, + /*target_width*/ None + )); + assert!( + state.pending_until().expect("pending reflow") > before_reschedule, + "a resize after the old deadline should start a fresh quiet period" + ); } #[test] fn full_reflow_request_promotes_visible_rows_request() { let mut state = TranscriptReflowState::default(); - state.schedule_debounced(TranscriptReflowKind::VisibleRows); - state.schedule_debounced(TranscriptReflowKind::Full); + state.schedule_debounced( + TranscriptReflowKind::VisibleRows, + /*target_width*/ None, + ); + state.schedule_debounced(TranscriptReflowKind::Full, /*target_width*/ Some(100)); assert_eq!(state.pending_kind(), Some(TranscriptReflowKind::Full)); } + #[test] + fn first_observed_width_marks_reflow_baseline() { + let mut state = TranscriptReflowState::default(); + + let width = state.note_width(/*width*/ 80); + + assert!(width.initialized); + assert_eq!(state.last_observed_width, Some(80)); + assert_eq!(state.last_reflow_width, Some(80)); + assert!(!state.full_reflow_needed_for_width(/*width*/ 80)); + } + + #[test] + fn mark_reflowed_width_records_actual_rebuild_width() { + let mut state = TranscriptReflowState::default(); + state.note_width(/*width*/ 80); + + assert!(state.mark_reflowed_width(/*width*/ 100)); + + assert_eq!(state.last_observed_width, Some(80)); + assert_eq!(state.last_reflow_width, Some(100)); + } + + #[test] + fn full_reflow_needed_compares_against_actual_rebuild_width() { + let mut state = TranscriptReflowState::default(); + state.note_width(/*width*/ 80); + state.mark_reflowed_width(/*width*/ 90); + state.note_width(/*width*/ 100); + + assert!(state.full_reflow_needed_for_width(/*width*/ 100)); + } + + #[test] + fn pending_full_reflow_target_prevents_repeated_reschedule() { + let mut state = TranscriptReflowState::default(); + state.note_width(/*width*/ 80); + + assert!(state.full_reflow_needed_for_width(/*width*/ 100)); + state.schedule_debounced(TranscriptReflowKind::Full, /*target_width*/ Some(100)); + + assert!(!state.full_reflow_needed_for_width(/*width*/ 100)); + } + + #[test] + fn clear_pending_reflow_allows_same_width_to_be_rescheduled() { + let mut state = TranscriptReflowState::default(); + state.note_width(/*width*/ 80); + state.schedule_debounced(TranscriptReflowKind::Full, /*target_width*/ Some(100)); + + state.clear_pending_reflow(); + + assert!(state.full_reflow_needed_for_width(/*width*/ 100)); + } + + #[test] + fn mark_reflowed_width_reports_unchanged_width() { + let mut state = TranscriptReflowState::default(); + assert!(state.mark_reflowed_width(/*width*/ 100)); + + assert!(!state.mark_reflowed_width(/*width*/ 100)); + assert_eq!(state.last_reflow_width, Some(100)); + } + #[test] fn take_stream_finish_reflow_needed_drains_resize_request() { let mut state = TranscriptReflowState::default(); @@ -227,4 +404,125 @@ mod tests { assert!(!state.take_stream_finish_reflow_needed()); } + + #[test] + fn below_threshold_measurement_keeps_reflow_active() { + let mut state = TranscriptReflowState::default(); + + assert!(!state.record_elapsed( + ResizeReflowDisableReason::RenderSlow, + Duration::from_millis(/*millis*/ 249), + Duration::from_millis(/*millis*/ 250), + )); + + assert!(!state.is_runtime_disabled()); + assert_eq!(state.runtime_disabled_reason(), None); + } + + #[test] + fn slow_render_measurement_disables_reflow() { + let mut state = TranscriptReflowState::default(); + + assert!(state.record_elapsed( + ResizeReflowDisableReason::RenderSlow, + Duration::from_millis(/*millis*/ 251), + Duration::from_millis(/*millis*/ 250), + )); + + assert!(state.is_runtime_disabled()); + assert_eq!( + state.runtime_disabled_reason(), + Some(ResizeReflowDisableReason::RenderSlow) + ); + } + + #[test] + fn runtime_disable_warning_is_reported_once() { + let mut state = TranscriptReflowState::default(); + + assert!(!state.take_runtime_disable_warning_needed()); + assert!(state.record_elapsed( + ResizeReflowDisableReason::RenderSlow, + Duration::from_millis(/*millis*/ 251), + Duration::from_millis(/*millis*/ 250), + )); + + assert!(state.take_runtime_disable_warning_needed()); + assert!(!state.take_runtime_disable_warning_needed()); + } + + #[test] + fn slow_flush_measurement_disables_reflow() { + let mut state = TranscriptReflowState::default(); + + assert!(state.record_elapsed( + ResizeReflowDisableReason::FlushSlow, + Duration::from_millis(/*millis*/ 251), + Duration::from_millis(/*millis*/ 250), + )); + + assert!(state.is_runtime_disabled()); + assert_eq!( + state.runtime_disabled_reason(), + Some(ResizeReflowDisableReason::FlushSlow) + ); + } + + #[test] + fn row_cap_trim_warning_is_reported_once() { + let mut state = TranscriptReflowState::default(); + + assert!(state.take_row_cap_trim_warning_needed()); + assert!(!state.take_row_cap_trim_warning_needed()); + } + + #[test] + fn clear_resets_runtime_disable() { + let mut state = TranscriptReflowState::default(); + state.record_elapsed( + ResizeReflowDisableReason::RenderSlow, + Duration::from_millis(/*millis*/ 251), + Duration::from_millis(/*millis*/ 250), + ); + + state.clear(); + + assert!(!state.is_runtime_disabled()); + assert_eq!(state.runtime_disabled_reason(), None); + } + + #[test] + fn clear_runtime_disable_preserves_pending_reflow() { + let mut state = TranscriptReflowState::default(); + state.record_elapsed( + ResizeReflowDisableReason::RenderSlow, + Duration::from_millis(/*millis*/ 251), + Duration::from_millis(/*millis*/ 250), + ); + state.pending_until = Some(Instant::now()); + state.pending_kind = Some(TranscriptReflowKind::Full); + + state.clear_runtime_disable(); + + assert!(!state.is_runtime_disabled()); + assert!(state.has_pending_reflow()); + } + + #[test] + fn clear_pending_reflow_preserves_runtime_disable() { + let mut state = TranscriptReflowState::default(); + state.record_elapsed( + ResizeReflowDisableReason::RenderSlow, + Duration::from_millis(/*millis*/ 251), + Duration::from_millis(/*millis*/ 250), + ); + + state.clear_pending_reflow(); + + assert!(state.is_runtime_disabled()); + assert_eq!( + state.runtime_disabled_reason(), + Some(ResizeReflowDisableReason::RenderSlow) + ); + } } diff --git a/codex-rs/tui/src/tui.rs b/codex-rs/tui/src/tui.rs index 55d0ec0fc1..d23ff732ab 100644 --- a/codex-rs/tui/src/tui.rs +++ b/codex-rs/tui/src/tui.rs @@ -11,6 +11,7 @@ use std::sync::Arc; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering; use std::time::Duration; +use std::time::Instant; use crossterm::Command; use crossterm::SynchronizedUpdate; @@ -481,6 +482,12 @@ pub struct Tui { alt_screen_enabled: bool, } +#[derive(Debug, Default, Clone, Copy)] +pub(crate) struct ResizeReflowDrawStats { + pub(crate) reflow_flush_elapsed: Duration, + pub(crate) flushed_reflow_history: bool, +} + impl Tui { pub fn new(terminal: Terminal) -> Self { let (draw_tx, _) = broadcast::channel(1); @@ -825,16 +832,15 @@ impl Tui { fn flush_pending_reflow_history_lines( terminal: &mut Terminal, pending_reflow_history_lines: &mut Vec>, - is_zellij: bool, ) -> Result { if pending_reflow_history_lines.is_empty() { return Ok(false); } - crate::insert_history::insert_history_lines_preserving_viewport( + crate::insert_history::insert_history_lines_with_mode( terminal, pending_reflow_history_lines.clone(), - is_zellij, + crate::insert_history::InsertHistoryMode::FullScreenReplay, )?; pending_reflow_history_lines.clear(); Ok(true) @@ -909,7 +915,7 @@ impl Tui { &mut self, height: u16, draw_fn: impl FnOnce(&mut custom_terminal::Frame), - ) -> Result<()> { + ) -> Result { // If we are resuming from ^Z, we need to prepare the resume action now so we can apply it // in the synchronized update. #[cfg(unix)] @@ -918,6 +924,7 @@ impl Tui { .prepare_resume_action(&mut self.terminal, &mut self.alt_saved_viewport); stdout().sync_update(|_| { + let mut stats = ResizeReflowDrawStats::default(); #[cfg(unix)] if let Some(prepared) = prepared_resume.take() { prepared.apply(&mut self.terminal)?; @@ -931,11 +938,14 @@ impl Tui { &mut self.pending_history_lines, self.is_zellij, )?; - needs_full_repaint |= Self::flush_pending_reflow_history_lines( + let reflow_flush_start = Instant::now(); + let flushed_reflow_history = Self::flush_pending_reflow_history_lines( terminal, &mut self.pending_reflow_history_lines, - self.is_zellij, )?; + stats.reflow_flush_elapsed = reflow_flush_start.elapsed(); + stats.flushed_reflow_history = flushed_reflow_history; + needs_full_repaint |= flushed_reflow_history; if needs_full_repaint { terminal.clear()?; @@ -958,7 +968,9 @@ impl Tui { terminal.draw(|frame| { draw_fn(frame); - }) + })?; + + Ok(stats) })? }