fix(tui): make startup header handoff atomic

This commit is contained in:
Felipe Coury
2026-05-30 16:30:18 -03:00
parent 6374ba543d
commit d6f18dbd20
8 changed files with 215 additions and 5 deletions
+9
View File
@@ -1211,6 +1211,10 @@ See the Codex keymap documentation for supported actions and examples."
app_server: &mut AppServerSession,
event: TuiEvent,
) -> Result<AppRunControl> {
if self.should_defer_draw_for_session_header_commit(&event) {
return Ok(AppRunControl::Continue);
}
let terminal_resize_reflow_enabled = self.terminal_resize_reflow_enabled();
if terminal_resize_reflow_enabled && matches!(event, TuiEvent::Draw | TuiEvent::Resize) {
self.handle_draw_pre_render(tui)?;
@@ -1287,6 +1291,11 @@ See the Codex keymap documentation for supported actions and examples."
Ok(AppRunControl::Continue)
}
fn should_defer_draw_for_session_header_commit(&self, event: &TuiEvent) -> bool {
self.chat_widget.is_session_header_commit_pending()
&& matches!(event, TuiEvent::Draw | TuiEvent::Resize)
}
pub(super) fn show_shutdown_feedback(&mut self, tui: &mut tui::Tui) -> Result<()> {
self.disable_ambient_pet_before_shutdown(tui)?;
self.chat_widget.show_shutdown_in_progress();
+2
View File
@@ -197,6 +197,8 @@ impl App {
self.begin_thread_switch_history_replay_buffer();
}
AppEvent::InsertHistoryCell(cell) => {
self.chat_widget
.complete_session_header_commit_if_pending(cell.as_ref());
let cell: Arc<dyn HistoryCell> = cell.into();
if let Some(Overlay::Transcript(t)) = &mut self.overlay {
t.insert_cell(cell.clone());
+72
View File
@@ -135,6 +135,78 @@ fn startup_waiting_gate_not_applied_for_resume_or_fork_session_selection() {
);
}
fn install_startup_placeholder_widget(app: &mut App) {
let config = app.config.clone();
let model = crate::legacy_core::test_support::get_model_offline(config.model.as_deref());
app.chat_widget = ChatWidget::new_with_app_event(ChatWidgetInit {
config,
frame_requester: crate::tui::FrameRequester::test_dummy(),
app_event_tx: app.app_event_tx.clone(),
workspace_command_runner: None,
initial_user_message: None,
enhanced_keys_supported: false,
has_chatgpt_account: false,
model_catalog: app.model_catalog.clone(),
feedback: codex_feedback::CodexFeedback::new(),
is_first_run: false,
status_account_display: None,
runtime_model_provider_base_url: None,
initial_plan_type: None,
model: Some(model),
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(),
});
}
#[tokio::test]
async fn startup_header_commit_defers_draw_until_session_info_is_committed() {
let (mut app, mut app_event_rx, _op_rx) = make_test_app_with_channels().await;
install_startup_placeholder_widget(&mut app);
app.chat_widget.handle_thread_session(test_thread_session(
ThreadId::new(),
test_path_buf("/tmp/project"),
));
assert!(app.chat_widget.is_session_header_commit_pending());
assert!(app.should_defer_draw_for_session_header_commit(&crate::tui::TuiEvent::Draw));
assert!(app.should_defer_draw_for_session_header_commit(&crate::tui::TuiEvent::Resize));
let header = loop {
match app_event_rx.try_recv() {
Ok(AppEvent::InsertHistoryCell(cell))
if cell.as_any().is::<crate::history_cell::SessionInfoCell>() =>
{
break cell;
}
Ok(_) => continue,
other => panic!("expected queued configured header, got {other:?}"),
}
};
app.chat_widget
.complete_session_header_commit_if_pending(header.as_ref());
assert!(!app.chat_widget.is_session_header_commit_pending());
assert!(!app.should_defer_draw_for_session_header_commit(&crate::tui::TuiEvent::Draw));
}
#[tokio::test]
async fn quiet_session_configuration_does_not_defer_draw_for_header_commit() {
let (mut app, _app_event_rx, _op_rx) = make_test_app_with_channels().await;
install_startup_placeholder_widget(&mut app);
app.chat_widget
.handle_thread_session_quiet(test_thread_session(
ThreadId::new(),
test_path_buf("/tmp/project"),
));
assert!(!app.chat_widget.is_session_header_commit_pending());
assert!(!app.should_defer_draw_for_session_header_commit(&crate::tui::TuiEvent::Draw));
}
#[tokio::test]
async fn startup_thread_started_submits_queued_startup_input() {
let (mut app, _app_event_rx, mut op_rx) = make_test_app_with_channels().await;
+17 -3
View File
@@ -636,9 +636,9 @@ pub(crate) struct ChatWidget {
show_welcome_banner: bool,
// One-shot tooltip override for the primary startup session.
startup_tooltip_override: Option<String>,
// When resuming an existing session (selected via resume picker), avoid an
// immediate redraw on SessionConfigured to prevent a gratuitous UI flicker.
suppress_session_configured_redraw: bool,
// A replacement for the provisional session header has been queued for terminal history.
// Until it is committed, drawing would expose a transient composer-only frame.
session_header_commit_pending: bool,
// During snapshot restore, defer startup prompt submission until replayed
// history has been rendered so resumed/forked prompts keep chronological
// order.
@@ -1485,6 +1485,9 @@ impl ChatWidget {
false
};
if merged_header {
self.session_header_commit_pending = true;
}
self.flush_active_cell();
if !merged_header && let Some(cell) = session_info_cell {
@@ -1492,6 +1495,17 @@ impl ChatWidget {
}
}
pub(crate) fn is_session_header_commit_pending(&self) -> bool {
self.session_header_commit_pending
}
pub(crate) fn complete_session_header_commit_if_pending(&mut self, cell: &dyn HistoryCell) {
if self.session_header_commit_pending && cell.as_any().is::<history_cell::SessionInfoCell>()
{
self.session_header_commit_pending = false;
}
}
pub(crate) fn add_info_message(&mut self, message: String, hint: Option<String>) {
self.add_to_history(history_cell::new_info_event(message, hint));
self.request_redraw();
+1 -1
View File
@@ -186,7 +186,7 @@ impl ChatWidget {
queued_message_edit_hint_binding,
show_welcome_banner: is_first_run,
startup_tooltip_override,
suppress_session_configured_redraw: false,
session_header_commit_pending: false,
suppress_initial_user_message_submit: false,
pending_notification: None,
quit_shortcut_expires_at: None,
+4 -1
View File
@@ -141,7 +141,10 @@ impl ChatWidget {
{
self.emit_forked_thread_event(forked_from_id, fork_parent_title);
}
if !self.suppress_session_configured_redraw {
// Normal display queues session info into terminal history, which schedules the frame
// that commits the header and repaints the composer atomically. Redrawing before that
// history insert is processed can briefly show the composer without its header.
if display != SessionConfiguredDisplay::Normal {
self.request_redraw();
}
}
@@ -0,0 +1,28 @@
---
source: tui/src/chatwidget/tests/status_and_layout.rs
expression: "format!(\"provisional live frame:\\n{placeholder}\\n\\ncommitted history:\\n{committed_header}\")"
---
provisional live frame:
" "
"╭───────────────────────────────────────╮ "
"│ >_ OpenAI Codex (v0.0.0) │ "
"│ │ "
"│ model: loading /model to change │ "
"│ directory: /tmp/project │ "
"╰───────────────────────────────────────╯ "
" "
" "
"› Explain this codebase "
" "
" gpt-5.5 default · /tmp/project "
committed history:
╭────────────────────────────────────────────────╮
│ >_ OpenAI Codex (v0.0.0) │
│ │
│ model: configured-model /model to change │
│ directory: /tmp/project │
╰────────────────────────────────────────────────╯
Tip: This is a test announcement
@@ -1579,6 +1579,88 @@ async fn ui_snapshots_small_heights_task_running() {
}
}
#[tokio::test]
async fn startup_header_handoff_visible_states_snapshot() {
let (tx_raw, mut rx) = unbounded_channel::<AppEvent>();
let tx = AppEventSender::new(tx_raw);
let cfg = test_config().await;
let resolved_model = crate::legacy_core::test_support::get_model_offline(cfg.model.as_deref());
let init = ChatWidgetInit {
config: cfg.clone(),
frame_requester: FrameRequester::test_dummy(),
app_event_tx: tx,
workspace_command_runner: None,
initial_user_message: None,
enhanced_keys_supported: false,
has_chatgpt_account: false,
model_catalog: test_model_catalog(&cfg),
feedback: codex_feedback::CodexFeedback::new(),
is_first_run: false,
status_account_display: None,
runtime_model_provider_base_url: None,
initial_plan_type: None,
model: Some(resolved_model.clone()),
startup_tooltip_override: Some("This is a test announcement".to_string()),
status_line_invalid_items_warned: Arc::new(AtomicBool::new(false)),
terminal_title_invalid_items_warned: Arc::new(AtomicBool::new(false)),
session_telemetry: test_session_telemetry(&cfg, resolved_model.as_str()),
};
let mut chat = ChatWidget::new_with_app_event(init);
chat.normal_placeholder_text = "Explain this codebase".to_string();
chat.bottom_pane
.set_placeholder_text(chat.normal_placeholder_text.clone());
let width = 80;
let height = chat.desired_height(width);
let mut terminal =
ratatui::Terminal::new(TestBackend::new(width, height)).expect("create terminal");
terminal
.draw(|f| chat.render(f.area(), f.buffer_mut()))
.expect("draw placeholder header");
let placeholder = normalized_backend_snapshot(terminal.backend());
let rollout_file = NamedTempFile::new().expect("rollout file");
chat.handle_thread_session(crate::session_state::ThreadSessionState {
thread_id: ThreadId::new(),
forked_from_id: None,
fork_parent_title: None,
thread_name: None,
model: "configured-model".to_string(),
model_provider_id: "test-provider".to_string(),
service_tier: None,
approval_policy: AskForApproval::Never,
approvals_reviewer: ApprovalsReviewer::User,
permission_profile: PermissionProfile::read_only(),
active_permission_profile: None,
cwd: test_path_buf("/tmp/project").abs(),
runtime_workspace_roots: Vec::new(),
instruction_source_paths: Vec::new(),
reasoning_effort: None,
collaboration_mode: None,
personality: None,
message_history: None,
network_proxy: None,
rollout_path: Some(rollout_file.path().to_path_buf()),
});
assert!(chat.is_session_header_commit_pending());
let committed_header = loop {
match rx.try_recv() {
Ok(AppEvent::InsertHistoryCell(cell))
if cell.as_any().is::<history_cell::SessionInfoCell>() =>
{
break lines_to_single_string(&cell.display_lines(width));
}
Ok(_) => continue,
other => panic!("expected queued configured header, got {other:?}"),
}
};
assert_chatwidget_snapshot!(
"startup_header_handoff_visible_states",
format!("provisional live frame:\n{placeholder}\n\ncommitted history:\n{committed_header}")
);
}
#[tokio::test]
#[serial]
async fn ambient_pet_stays_hidden_until_a_pet_is_selected() {