diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index 4e8794d090..5fe9131740 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -168,7 +168,6 @@ use crossterm::event::KeyCode; use crossterm::event::KeyEvent; use crossterm::event::KeyEventKind; use crossterm::event::KeyModifiers; -use ratatui::backend::Backend; use ratatui::layout::Rect; use ratatui::layout::Size; use ratatui::style::Stylize; @@ -179,7 +178,6 @@ use std::collections::BTreeMap; use std::collections::HashMap; use std::collections::HashSet; use std::collections::VecDeque; -use std::io::Write; use std::path::Path; use std::path::PathBuf; use std::sync::Arc; diff --git a/codex-rs/tui/src/app/agents_overview.rs b/codex-rs/tui/src/app/agents_overview.rs index b88f392ffd..a4516cef25 100644 --- a/codex-rs/tui/src/app/agents_overview.rs +++ b/codex-rs/tui/src/app/agents_overview.rs @@ -378,7 +378,9 @@ impl App { if self.reject_pending_permission_root_switch() { return Ok(AppRunControl::Continue); } - loading::draw(tui)?; + if startup_draft.is_none() { + loading::draw(tui)?; + } if self.primary_thread_id != Some(root_thread_id) { let previous_displayed_thread_id = self.current_displayed_thread_id(); if let Some(id) = previous_displayed_thread_id @@ -505,7 +507,9 @@ impl App { local_settings = self.local_settings.reloaded(&resume_config); } // Folder selection and trust prompts can replace or clear the loading frame. - loading::draw(tui)?; + if startup_draft.is_none() { + loading::draw(tui)?; + } let baseline_approval = resume_config.permissions.approval_policy.value(); let baseline_permissions = RuntimePermissionProfileOverride::from_config(&resume_config); @@ -542,7 +546,9 @@ impl App { } }; let mut history_notice = None; - let presentation = if started.is_some() { + let presentation = if startup_draft.is_some() { + ThreadAttachPresentation::FreshWithDraft + } else if started.is_some() { ThreadAttachPresentation::Fresh } else { ThreadAttachPresentation::SessionLineage @@ -691,7 +697,9 @@ impl App { return Ok(AppRunControl::Continue); } // Replacing the widget clears the terminal before the remaining server requests. - loading::draw(tui)?; + if startup_draft.is_none() { + loading::draw(tui)?; + } if read_only { self.ensure_thread_channel(root_thread_id) .mark_external_writer(); diff --git a/codex-rs/tui/src/app/agents_overview_new.rs b/codex-rs/tui/src/app/agents_overview_new.rs index ba1f0f3eaf..7a4aa8aa20 100644 --- a/codex-rs/tui/src/app/agents_overview_new.rs +++ b/codex-rs/tui/src/app/agents_overview_new.rs @@ -62,7 +62,7 @@ impl App { display_config.cwd = cwd.clone(); } draft.apply_config(&display_config); - tui.terminal.clear()?; + draft.show(tui)?; // Keep the large session-start future off the TUI's stack in dev builds. let result = Box::pin(self.start_agents_overview_session( tui, diff --git a/codex-rs/tui/src/app/event_dispatch.rs b/codex-rs/tui/src/app/event_dispatch.rs index fe693a6ab8..7ea0e3b622 100644 --- a/codex-rs/tui/src/app/event_dispatch.rs +++ b/codex-rs/tui/src/app/event_dispatch.rs @@ -47,6 +47,7 @@ impl App { | AppEvent::InsertHistoryCell(_) | AppEvent::CommitRealtimeTranscriptHistory | AppEvent::ResetTranscriptForThreadSwitch + | AppEvent::ResetTranscriptForThreadSwitchPreservingScreen | AppEvent::FinishPromptRevert { .. } | AppEvent::PromptSuggestionStarted { .. } | AppEvent::PromptSuggestionFinished { .. } @@ -800,6 +801,12 @@ impl App { self.reset_for_thread_switch(tui)?; self.pending_thread_switch_resets -= 1; } + AppEvent::ResetTranscriptForThreadSwitchPreservingScreen => { + self.reset_transcript_state_after_clear(); + tui.clear_pending_history_lines(); + tui.defer_thread_switch_clear(); + self.pending_thread_switch_resets -= 1; + } AppEvent::CommitRealtimeTranscriptHistory => { for cell in self.chat_widget.take_realtime_transcript_history() { self.insert_history_cell(tui, cell); diff --git a/codex-rs/tui/src/app/resize_reflow.rs b/codex-rs/tui/src/app/resize_reflow.rs index aa0b775e32..632ac8b4de 100644 --- a/codex-rs/tui/src/app/resize_reflow.rs +++ b/codex-rs/tui/src/app/resize_reflow.rs @@ -290,7 +290,7 @@ impl App { } fn clear_terminal_for_resize_replay(&mut self, tui: &mut tui::Tui) -> Result<()> { - if tui.is_owned_screen() { + if tui.is_owned_screen() || tui.has_deferred_thread_switch_clear() { return Ok(()); } if tui.is_alt_screen_active() { diff --git a/codex-rs/tui/src/app/session_lifecycle.rs b/codex-rs/tui/src/app/session_lifecycle.rs index 88098615b2..dabf197d30 100644 --- a/codex-rs/tui/src/app/session_lifecycle.rs +++ b/codex-rs/tui/src/app/session_lifecycle.rs @@ -4,8 +4,6 @@ //! resuming/forking saved sessions, replacing ChatWidget instances, and maintaining the agent picker //! cache used for multi-agent navigation. -use std::io; - use super::agent_picker::AGENT_PICKER_VIEW_ID; use super::app_server_event_targets::ServerNotificationThreadTarget; use super::app_server_event_targets::server_notification_thread_target; @@ -20,6 +18,8 @@ use std::collections::HashSet; pub(super) enum ThreadAttachPresentation { /// A primary thread created by thread/start, without inherited history. Fresh, + /// A fresh thread whose startup composer is already visible. + FreshWithDraft, SessionLineage, } @@ -775,32 +775,9 @@ impl App { } pub(super) fn reset_for_thread_switch(&mut self, tui: &mut tui::Tui) -> Result<()> { - if tui.is_alt_screen_active() { - tui.leave_alt_screen()?; - } self.reset_transcript_state_after_clear(); tui.clear_pending_history_lines(); - if tui.is_owned_screen() { - tui.terminal.clear()?; - } else { - Self::clear_terminal_for_thread_switch(&mut tui.terminal)?; - } - Ok(()) - } - - pub(super) fn clear_terminal_for_thread_switch( - terminal: &mut crate::custom_terminal::Terminal, - ) -> Result<()> - where - B: Backend + Write, - { - terminal.clear_scrollback_and_visible_screen_ansi()?; - let mut area = terminal.viewport_area; - if area.y > 0 { - area.y = 0; - terminal.set_viewport_area(area); - } - Ok(()) + Ok(tui.clear_for_thread_switch()?) } pub(super) async fn reset_thread_event_state(&mut self) { @@ -1092,10 +1069,21 @@ impl App { self.active_thread_rx = Some(receiver); } self.store_active_thread_receiver().await; - self.reset_for_thread_switch(tui)?; + if matches!(presentation, ThreadAttachPresentation::FreshWithDraft) { + self.reset_transcript_state_after_clear(); + tui.clear_pending_history_lines(); + tui.defer_thread_switch_clear(); + } else { + self.reset_for_thread_switch(tui)?; + } self.pending_thread_switch_resets += 1; - self.app_event_tx - .send(AppEvent::ResetTranscriptForThreadSwitch); + self.app_event_tx.send( + if matches!(presentation, ThreadAttachPresentation::FreshWithDraft) { + AppEvent::ResetTranscriptForThreadSwitchPreservingScreen + } else { + AppEvent::ResetTranscriptForThreadSwitch + }, + ); self.reset_thread_event_state().await; let init = self.chatwidget_init_for_forked_or_resumed_thread( tui, @@ -1104,7 +1092,10 @@ impl App { ); self.replace_chat_widget(ChatWidget::new_with_app_event(init)); self.chat_widget.prompt_suggestion_summary = started.reasoning_summary; - if matches!(presentation, ThreadAttachPresentation::Fresh) { + if matches!( + presentation, + ThreadAttachPresentation::Fresh | ThreadAttachPresentation::FreshWithDraft + ) { self.chat_widget.mark_fresh_task_for_sparkle(&started); self.chat_widget .empty_state_animation diff --git a/codex-rs/tui/src/app/tests/background_task_defaults_tests.rs b/codex-rs/tui/src/app/tests/background_task_defaults_tests.rs index 95c01a05e8..f0f7b943af 100644 --- a/codex-rs/tui/src/app/tests/background_task_defaults_tests.rs +++ b/codex-rs/tui/src/app/tests/background_task_defaults_tests.rs @@ -42,6 +42,82 @@ fn trust_launch_folder(app: &mut App) { app.config.active_project.trust_level = Some(codex_protocol::config_types::TrustLevel::Trusted); } +#[tokio::test] +async fn command_center_new_keeps_startup_draft_visible_through_handoff() -> Result<()> { + use crate::custom_terminal::test_support::last_rendered_buffer; + + let mut snapshots = Vec::new(); + for owned in [false, true] { + let (mut app, mut events, _) = make_test_app_with_channels().await; + trust_launch_folder(&mut app); + app.cli_kv_overrides + .push(("tui.animations".into(), TomlValue::Boolean(false))); + let mut server = start_config_write_test_app_server(&app).await?; + let mut tui = make_test_tui()?; + tui.pause_events(); + tui.set_owned_screen(owned)?; + app.agents_overview.rendered_full_screen = true; + app.agents_overview.new_session_draft = Some(Box::new( + crate::startup_draft::tests::startup_test_pump_with_input("draft during startup"), + )); + + app.new_agents_overview_session(&mut tui, &mut server, /*cwd*/ None) + .await?; + let frame = last_rendered_buffer(&tui.terminal).clone(); + let screen_text: String = frame + .content + .iter() + .map(ratatui::buffer::Cell::symbol) + .collect(); + assert!(screen_text.contains("draft during startup")); + assert!(!screen_text.contains("Loading task")); + assert_eq!( + app.chat_widget.composer_text_with_pending(), + "draft during startup" + ); + + while let Ok(event) = events.try_recv() { + Box::pin(app.handle_event(&mut tui, &mut server, event)).await?; + assert_eq!(last_rendered_buffer(&tui.terminal), &frame); + } + + let size = tui.terminal.last_known_screen_size; + app.render_chat_widget_frame(&mut tui, size)?; + let final_frame = last_rendered_buffer(&tui.terminal); + let footer = |buffer: &ratatui::buffer::Buffer| { + buffer + .content + .chunks(usize::from(buffer.area.width)) + .rev() + .take(5) + .collect::>() + .into_iter() + .rev() + .map(|row| { + row.iter() + .map(ratatui::buffer::Cell::symbol) + .collect::() + .trim_end() + .to_string() + }) + .collect::>() + .join("\n") + }; + snapshots.push(format!( + "owned={owned}\nstartup:\n{}\nattached:\n{}", + footer(&frame), + footer(final_frame) + )); + tui.set_owned_screen(/*owned*/ false)?; + server.shutdown().await?; + } + insta::assert_snapshot!( + "command_center_new_draft_handoff", + crate::chatwidget::tests::helpers::normalize_snapshot_paths(snapshots.join("\n\n")) + ); + Ok(()) +} + #[tokio::test] async fn review_regression_agents_overview_creation_is_fresh_but_returning_is_not() -> Result<()> { let render = |chat: &ChatWidget| { diff --git a/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__background_task_defaults_tests__command_center_new_draft_handoff.snap b/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__background_task_defaults_tests__command_center_new_draft_handoff.snap new file mode 100644 index 0000000000..0005d72de4 --- /dev/null +++ b/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__background_task_defaults_tests__command_center_new_draft_handoff.snap @@ -0,0 +1,30 @@ +--- +source: tui/src/app/tests/background_task_defaults_tests.rs +expression: "snapshots.join(\"\\n\\n\")" +--- +owned=false +startup: + + +› draft during startup + + +attached: + + +› draft during startup + + GPT-6-Astra default · /tmp/project + +owned=true +startup: + +› draft during startup + + + +attached: + +› draft during startup + + GPT-6-Astra default · /tmp/project diff --git a/codex-rs/tui/src/app/thread_routing.rs b/codex-rs/tui/src/app/thread_routing.rs index c134d69228..21c420b7a0 100644 --- a/codex-rs/tui/src/app/thread_routing.rs +++ b/codex-rs/tui/src/app/thread_routing.rs @@ -1580,7 +1580,9 @@ impl App { self.chat_widget.set_token_info(/*info*/ None); } match presentation { - ThreadAttachPresentation::Fresh | ThreadAttachPresentation::SessionLineage => { + ThreadAttachPresentation::Fresh + | ThreadAttachPresentation::FreshWithDraft + | ThreadAttachPresentation::SessionLineage => { self.chat_widget.handle_thread_session(session); } } diff --git a/codex-rs/tui/src/app_event.rs b/codex-rs/tui/src/app_event.rs index a7e383bdae..784e763c14 100644 --- a/codex-rs/tui/src/app_event.rs +++ b/codex-rs/tui/src/app_event.rs @@ -564,6 +564,8 @@ pub(crate) enum AppEvent { /// Clear history queued by the previous thread before the new thread's replay events. ResetTranscriptForThreadSwitch, + /// Reset queued history while keeping the startup draft visible until the next frame. + ResetTranscriptForThreadSwitchPreservingScreen, /// Re-render the transcript using the selected scrollback rendering mode. RawOutputModeChanged { diff --git a/codex-rs/tui/src/startup_draft_tests.rs b/codex-rs/tui/src/startup_draft_tests.rs index 976573dbb4..ffb7e6f54b 100644 --- a/codex-rs/tui/src/startup_draft_tests.rs +++ b/codex-rs/tui/src/startup_draft_tests.rs @@ -7,6 +7,7 @@ use ratatui::buffer::Buffer; use ratatui::layout::Rect; use std::sync::Arc; use tokio::sync::mpsc::unbounded_channel; +use tokio_stream::StreamExt; use super::StartupDraftInitialScreen; use super::StartupDraftPump; @@ -53,6 +54,12 @@ pub(crate) fn quiet_startup_test_pump() -> StartupDraftPump { pump } +pub(crate) fn startup_test_pump_with_input(text: &str) -> StartupDraftPump { + let mut pump = startup_test_pump(std::iter::once(TuiEvent::Paste(text.to_string()))); + pump.events = Box::pin(pump.events.chain(futures::stream::pending())); + pump +} + #[test] fn startup_draft_renders_full_empty_and_multiline_composer_frames() { let mut pump = startup_test_pump(std::iter::empty()); diff --git a/codex-rs/tui/src/tui.rs b/codex-rs/tui/src/tui.rs index ecd00e058a..dc14abf35d 100644 --- a/codex-rs/tui/src/tui.rs +++ b/codex-rs/tui/src/tui.rs @@ -630,6 +630,7 @@ pub struct Tui { event_broker: Arc, pub(crate) terminal: Terminal, pending_history_lines: Vec, + clear_thread_switch_on_draw: bool, screen_size: ScreenSizePolicy, ambient_pet_image_state: crate::pets::PetImageRenderState, pet_picker_preview_image_state: crate::pets::PetImageRenderState, @@ -705,6 +706,7 @@ impl Tui { event_broker: Arc::new(event_broker), terminal, pending_history_lines: vec![], + clear_thread_switch_on_draw: false, screen_size: ScreenSizePolicy::default(), ambient_pet_image_state: crate::pets::PetImageRenderState::default(), pet_picker_preview_image_state: crate::pets::PetImageRenderState::default(), @@ -1093,6 +1095,33 @@ impl Tui { self.pending_history_lines.clear(); } + pub(crate) fn clear_for_thread_switch(&mut self) -> Result<()> { + self.clear_thread_switch_on_draw = false; + if self.is_alt_screen_active() { + self.leave_alt_screen()?; + } + if self.is_owned_screen() { + self.terminal.clear()?; + } else { + self.terminal.clear_scrollback_and_visible_screen_ansi()?; + let mut area = self.terminal.viewport_area; + if area.y > 0 { + area.y = 0; + self.terminal.set_viewport_area(area); + } + } + Ok(()) + } + + /// Keep the current frame visible until the next synchronized draw. + pub(crate) fn defer_thread_switch_clear(&mut self) { + self.clear_thread_switch_on_draw = true; + } + + pub(crate) fn has_deferred_thread_switch_clear(&self) -> bool { + self.clear_thread_switch_on_draw + } + /// Resize the inline viewport for the resize-reflow path. /// /// Unlike the legacy draw path, this path does not scroll rows above the viewport when the @@ -1194,6 +1223,10 @@ impl Tui { )?; } + if self.clear_thread_switch_on_draw { + self.clear_for_thread_switch()?; + pending_viewport_area = None; + } if self.owned_screen && !self.is_alt_screen_active() { self.enter_alt_screen()?; pending_viewport_area = None; @@ -1341,6 +1374,9 @@ impl Tui { )?; } + if self.clear_thread_switch_on_draw { + self.clear_for_thread_switch()?; + } if self.owned_screen && !self.is_alt_screen_active() { self.enter_alt_screen()?; }