Keep startup drafts visible during command center session handoff (#48121)

## Why

Starting a new session from the command center could clear the startup composer or replace it with `Loading task` before the attached chat was ready to render.

## What changed

Show the startup draft immediately and skip loading frames while it is present. Reset transcript state without clearing the visible draft, deferring the terminal clear until the next synchronized draw. Preserve this behavior during resize reflow as well.

## Testing

Add a regression test and snapshot covering inline and owned-screen modes. Verify that draft text survives the handoff, queued events leave the startup frame intact, and the attached composer retains the draft.

GitOrigin-RevId: 26a7ba2929a3b46537da960cbb7201b21b5dc61f
This commit is contained in:
Eric Traut
2026-09-25 15:34:02 +00:00
committed by copyberry
parent 68e0c9f5d8
commit 66c4e5a20d
12 changed files with 196 additions and 39 deletions
-2
View File
@@ -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;
+12 -4
View File
@@ -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();
+1 -1
View File
@@ -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,
+7
View File
@@ -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);
+1 -1
View File
@@ -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() {
+21 -30
View File
@@ -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<B>(
terminal: &mut crate::custom_terminal::Terminal<B>,
) -> Result<()>
where
B: Backend<Error = io::Error> + 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
@@ -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::<Vec<_>>()
.into_iter()
.rev()
.map(|row| {
row.iter()
.map(ratatui::buffer::Cell::symbol)
.collect::<String>()
.trim_end()
.to_string()
})
.collect::<Vec<_>>()
.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| {
@@ -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
+3 -1
View File
@@ -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);
}
}
+2
View File
@@ -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 {
+7
View File
@@ -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());
+36
View File
@@ -630,6 +630,7 @@ pub struct Tui {
event_broker: Arc<EventBroker>,
pub(crate) terminal: Terminal,
pending_history_lines: Vec<PendingHistoryLines>,
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()?;
}