diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index 314fecc3a8..cb86b5ccd4 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -897,6 +897,8 @@ impl App { match &event { TuiEvent::FocusLost => { + self.chat_widget + .set_sparkle_terminal_focus(/*focused*/ false); let now = Instant::now(); let thread_id = self.current_displayed_thread_id(); @@ -1011,6 +1013,8 @@ impl App { fn render_chat_widget_frame(&mut self, tui: &mut tui::Tui, screen_size: Size) -> Result { self.sync_thread_title_progress(); + self.chat_widget + .set_sparkle_terminal_focus(tui.is_terminal_focused()); let dashboard_visible = self .chat_widget .selected_index_for_present_view(AGENTS_OVERVIEW_VIEW_ID) diff --git a/codex-rs/tui/src/app/agents_overview.rs b/codex-rs/tui/src/app/agents_overview.rs index 65d8442cd9..cc8098bb60 100644 --- a/codex-rs/tui/src/app/agents_overview.rs +++ b/codex-rs/tui/src/app/agents_overview.rs @@ -1,5 +1,6 @@ //! Daemon-wide overview of recent and locally retained sessions and their subagents. //! Tasks owned by another app server open as frozen, read-only history snapshots. +//! Only the immediate attachment of a dashboard-created task is treated as fresh. #[path = "agents_overview_new.rs"] mod new; @@ -14,6 +15,7 @@ mod loading; use super::agents_overview_view::AgentsOverviewGroup; use super::agents_overview_view::AgentsOverviewRow; use super::agents_overview_view::AgentsOverviewView; +use super::session_lifecycle::ThreadAttachPresentation; use super::*; use crate::app_event::AgentsOverviewThreadRefresh; use crate::bottom_pane::SelectionDescriptionLayout; @@ -511,6 +513,11 @@ impl App { } }; let mut history_notice = None; + let presentation = if started.is_some() { + ThreadAttachPresentation::Fresh + } else { + ThreadAttachPresentation::SessionLineage + }; let (resumed, read_only) = if let Some((_, started)) = started { (started, false) } else if !unloaded @@ -637,7 +644,7 @@ impl App { .replace_chat_widget_with_app_server_thread( tui, resumed, - super::session_lifecycle::ThreadAttachPresentation::SessionLineage, + presentation, /*initial_user_message*/ None, ) .await diff --git a/codex-rs/tui/src/app/event_dispatch.rs b/codex-rs/tui/src/app/event_dispatch.rs index 4421e5a1de..e61e76d439 100644 --- a/codex-rs/tui/src/app/event_dispatch.rs +++ b/codex-rs/tui/src/app/event_dispatch.rs @@ -1805,6 +1805,22 @@ impl App { .await; } } + AppEvent::AstraSelectedFromModelPicker { thread_id, model, action } => { + // Check and apply in the same event so a queued backend update cannot turn a + // no-op picker confirmation into a sparkle. + let should_offer = self.chat_widget.current_model() != model + && self.chat_widget.sparkle_thread_for_picker_action(&model) == Some(thread_id); + let control = Box::pin(self.handle_event( + tui, + app_server, + action.into_app_event(model.clone()), + )) + .await?; + if should_offer { + self.chat_widget.on_sparkle_model_selected_from_picker(&model); + } + return Ok(control); + } AppEvent::RealtimeWebrtcOfferCreated { thread_id, attempt_id, diff --git a/codex-rs/tui/src/app/input.rs b/codex-rs/tui/src/app/input.rs index 59718fcd73..7a6de1e70e 100644 --- a/codex-rs/tui/src/app/input.rs +++ b/codex-rs/tui/src/app/input.rs @@ -469,6 +469,7 @@ impl App { // Esc so the active UI (e.g. status indicator, modals, popups) // handles it. if self.should_handle_backtrack_esc(key_event) { + self.chat_widget.prepare_composer_sparkle_key(key_event); self.handle_backtrack_esc_key(tui); } else if self.should_reject_side_backtrack_esc(key_event) { self.reject_side_backtrack_esc(); diff --git a/codex-rs/tui/src/app/session_lifecycle.rs b/codex-rs/tui/src/app/session_lifecycle.rs index 39d0c9cd30..df48cc7f0a 100644 --- a/codex-rs/tui/src/app/session_lifecycle.rs +++ b/codex-rs/tui/src/app/session_lifecycle.rs @@ -18,6 +18,8 @@ use std::collections::HashSet; #[derive(Clone, Copy)] pub(super) enum ThreadAttachPresentation { + /// A primary thread created by thread/start, without inherited history. + Fresh, SessionLineage, } @@ -834,6 +836,7 @@ impl App { .set_queue_submissions_until_session_configured(/*queue*/ false); match result { Ok(started) => { + self.chat_widget.mark_fresh_task_for_sparkle(&started); let thread_id = started.session.thread_id; if started.task_tools_available { app_server.remember_task_tool_thread(thread_id); @@ -997,7 +1000,7 @@ impl App { .replace_chat_widget_with_app_server_thread( tui, started, - ThreadAttachPresentation::SessionLineage, + ThreadAttachPresentation::Fresh, initial_user_message, ) .await @@ -1056,6 +1059,9 @@ impl App { initial_user_message, ); self.replace_chat_widget(ChatWidget::new_with_app_event(init)); + if matches!(presentation, ThreadAttachPresentation::Fresh) { + self.chat_widget.mark_fresh_task_for_sparkle(&started); + } self.chat_widget .set_task_mentions_enabled(started.task_tools_available); self.chat_widget diff --git a/codex-rs/tui/src/app/tests.rs b/codex-rs/tui/src/app/tests.rs index 40d16d6025..6496ea88f4 100644 --- a/codex-rs/tui/src/app/tests.rs +++ b/codex-rs/tui/src/app/tests.rs @@ -27,6 +27,8 @@ mod buffered_replay; mod connector_policy; #[path = "tests/disconnect_tests.rs"] mod disconnect; +#[path = "tests/fresh_sparkle_tests.rs"] +mod fresh_sparkle_tests; #[path = "tests/key_chords.rs"] mod key_chords; #[path = "tests/luna_reserve_recovery_tests.rs"] 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 e2ed7a59ef..8c1ec55dfc 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,71 @@ fn trust_launch_folder(app: &mut App) { app.config.active_project.trust_level = Some(codex_protocol::config_types::TrustLevel::Trusted); } +#[tokio::test] +async fn review_regression_agents_overview_creation_is_fresh_but_returning_is_not() -> Result<()> { + let render = |chat: &ChatWidget| { + crate::terminal_palette::with_test_default_colors( + crate::terminal_probe::DefaultColors { + fg: (230, 216, 255), + bg: (36, 27, 53), + }, + || render_bottom_popup(chat, /*width*/ 80), + ) + }; + let has_stars = |text: &str| text.chars().any(|ch| "⠁⠂⠄⠈⠐⠠⡀⢀".contains(ch)); + for model in ["gpt-6-astra", "gpt-5.5"] { + let (mut app, _events, _ops) = make_test_app_with_channels().await; + trust_launch_folder(&mut app); + app.cli_kv_overrides.extend([ + ("tui.animations".into(), TomlValue::Boolean(true)), + ("tui.whimsy".into(), TomlValue::Boolean(true)), + ]); + app.harness_overrides.model = Some(model.into()); + let mut server = start_config_write_test_app_server(&app).await?; + let mut tui = make_test_tui()?; + app.new_agents_overview_session(&mut tui, &mut server, /*cwd*/ None) + .await?; + let original = app.chat_widget.thread_id().expect("new dashboard task"); + assert_eq!(app.chat_widget.current_model(), model); + let created = render(&app.chat_widget); + assert_eq!(has_stars(&created), model == "gpt-6-astra", "{model}"); + if model != "gpt-6-astra" { + app.chat_widget.set_model("gpt-6-astra"); + app.chat_widget + .on_sparkle_model_selected_from_picker("gpt-6-astra"); + assert!(has_stars(&render(&app.chat_widget))); + } + app.harness_overrides.model = Some("gpt-6-astra".into()); + app.new_agents_overview_session(&mut tui, &mut server, /*cwd*/ None) + .await?; + assert_ne!(app.chat_widget.thread_id(), Some(original)); + app.select_agents_overview_thread(&mut tui, &mut server, original) + .await?; + assert_eq!(app.chat_widget.thread_id(), Some(original)); + let returned = render(&app.chat_widget); + assert!(!has_stars(&returned)); + app.chat_widget + .on_sparkle_model_selected_from_picker("gpt-6-astra"); + assert!(!has_stars(&render(&app.chat_widget))); + if model == "gpt-6-astra" { + let before_footer = |output: &str| { + output + .lines() + .take_while(|line| !line.contains("gpt-6-astra")) + .collect::>() + .join("\n") + }; + insta::assert_snapshot!(format!( + "created from the dashboard:\n{}\nreturned to the existing task:\n{}", + before_footer(&created), + before_footer(&returned) + )); + } + server.shutdown().await?; + } + Ok(()) +} + #[tokio::test] async fn command_center_new_reads_server_defaults_for_actual_destination() -> Result<()> { let mut tui = make_test_tui()?; diff --git a/codex-rs/tui/src/app/tests/fresh_sparkle_tests.rs b/codex-rs/tui/src/app/tests/fresh_sparkle_tests.rs new file mode 100644 index 0000000000..a5647c8a58 --- /dev/null +++ b/codex-rs/tui/src/app/tests/fresh_sparkle_tests.rs @@ -0,0 +1,735 @@ +//! Covers confirmed new tasks, existing attachment paths, and the user model picker. + +use super::*; +use crate::app::session_lifecycle::ThreadAttachPresentation; +use crate::chatwidget::AstraModelPickerAction; +use crate::terminal_palette::with_test_default_colors; +use crate::terminal_probe::DefaultColors; +use codex_protocol::openai_models::ReasoningEffortPreset; +use pretty_assertions::assert_eq; + +fn started(model: &str) -> AppServerStartedThread { + let mut session = test_thread_session(ThreadId::new(), test_path_buf("/tmp/project")); + session.model = model.into(); + AppServerStartedThread { + session, + turns: Vec::new(), + blocks_direct_input: false, + task_tools_available: false, + } +} + +fn render_with_sparkle_palette(chat: &ChatWidget) -> String { + with_test_default_colors( + DefaultColors { + fg: (230, 216, 255), + bg: (36, 27, 53), + }, + || render_bottom_popup(chat, /*width*/ 80), + ) +} + +fn visible(chat: &ChatWidget) -> bool { + render_with_sparkle_palette(chat) + .chars() + .any(|ch| "⠁⠂⠄⠈⠐⠠⡀⢀".contains(ch)) +} + +fn type_into(chat: &mut ChatWidget, text: &str) { + for ch in text.chars() { + chat.handle_key_event(KeyEvent::new(KeyCode::Char(ch), KeyModifiers::NONE)); + } +} + +async fn choose_model( + app: &mut App, + tui: &mut crate::tui::Tui, + server: &mut AppServerSession, + events: &mut tokio::sync::mpsc::UnboundedReceiver, + model: &str, + key: KeyCode, +) -> Result { + let mut preset = crate::test_support::TEST_MODEL_PRESETS[0].clone(); + preset.model = model.into(); + preset.display_name = model.into(); + preset.show_in_picker = true; + preset.supported_reasoning_efforts.truncate(/*len*/ 1); + preset.default_reasoning_effort = preset.supported_reasoning_efforts[0].effort.clone(); + app.chat_widget.open_model_popup_with_presets(vec![preset]); + app.chat_widget + .handle_key_event(KeyEvent::new(key, KeyModifiers::NONE)); + + let mut sparkle_offers = 0; + while let Ok(event) = events.try_recv() { + if matches!( + &event, + AppEvent::OpenReasoningPopup { .. } + | AppEvent::UpdateModel(_) + | AppEvent::SelectSessionModel { .. } + | AppEvent::AstraSelectedFromModelPicker { .. } + ) { + if let AppEvent::AstraSelectedFromModelPicker { thread_id, .. } = &event { + assert_eq!(Some(*thread_id), app.chat_widget.thread_id()); + } + let changes_model = matches!(&event, AppEvent::AstraSelectedFromModelPicker { model, .. } + if app.chat_widget.current_model() != model); + app.handle_event(tui, server, event).await?; + if changes_model && app.chat_widget.current_model() == model { + sparkle_offers += 1; + } + } + } + assert!(!app.chat_widget.has_active_view()); + Ok(sparkle_offers) +} + +#[tokio::test] +async fn only_a_confirmed_empty_new_task_shows_the_sparkle() -> Result<()> { + for scenario in [ + "fresh", + "empty_resume", + "fork", + "replay", + "initial_prompt", + "parent_owned", + ] { + let (mut app, _events, _ops) = make_test_app_with_channels().await; + app.local_settings.tui.animations = true; + app.local_settings.tui.whimsy = true; + let mut tui = crate::tui::test_support::make_test_tui()?; + let mut thread = started("gpt-6-astra"); + let presentation = if scenario == "empty_resume" { + ThreadAttachPresentation::SessionLineage + } else { + ThreadAttachPresentation::Fresh + }; + if scenario == "fork" { + thread.session.forked_from_id = Some(ThreadId::new()); + } + if scenario == "replay" { + thread + .turns + .push(test_turn("existing", TurnStatus::Completed, Vec::new())); + } + if scenario == "parent_owned" { + thread.blocks_direct_input = true; + } + let initial_message = (scenario == "initial_prompt") + .then(|| create_initial_user_message(Some("hello".into()), Vec::new(), Vec::new())) + .flatten(); + app.replace_chat_widget_with_app_server_thread( + &mut tui, + thread, + presentation, + initial_message, + ) + .await?; + assert_eq!(visible(&app.chat_widget), scenario == "fresh", "{scenario}"); + app.chat_widget.set_model("gpt-5.5"); + app.chat_widget.set_model("gpt-6-astra"); + assert!( + !visible(&app.chat_widget), + "automatic model update: {scenario}" + ); + } + Ok(()) +} + +#[tokio::test] +async fn disconnected_sparkle_input_routed_by_app_consumes_the_opportunity_without_drawing() +-> Result<()> { + for model in ["gpt-5.5", "gpt-6-astra"] { + for edited in [false, true] { + let (mut app, _events, _ops) = make_test_app_with_channels().await; + app.local_settings.tui.animations = true; + app.local_settings.tui.whimsy = true; + let mut server = start_config_write_test_app_server(&app).await?; + let mut tui = crate::tui::test_support::make_test_tui()?; + app.replace_chat_widget_with_app_server_thread( + &mut tui, + started(model), + ThreadAttachPresentation::Fresh, + /*initial_user_message*/ None, + ) + .await?; + assert_eq!(visible(&app.chat_widget), model == "gpt-6-astra"); + app.app_server_target = AppServerTarget::Remote { + endpoint: crate::resolve_remote_addr("ws://127.0.0.1:9")?, + }; + assert!(app.begin_reconnect()); + if edited { + for code in [KeyCode::Char('?'), KeyCode::Backspace] { + app.handle_tui_event( + &mut tui, + &mut server, + TuiEvent::Key(KeyEvent::new(code, KeyModifiers::NONE)), + ) + .await?; + } + } + assert_eq!(app.chat_widget.composer_text_with_pending(), ""); + app.chat_widget.set_footer_hint_override(/*items*/ None); + app.chat_widget.pause_unavailable_thread(); + app.chat_widget.set_model("gpt-6-astra"); + app.chat_widget + .on_sparkle_model_selected_from_picker("gpt-6-astra"); + assert_eq!( + visible(&app.chat_widget), + !edited, + "{model}, edited: {edited}" + ); + } + } + Ok(()) +} + +#[tokio::test] +async fn commands_can_precede_the_sparkle_but_inserted_or_typed_drafts_cannot() -> Result<()> { + for earlier_input in [ + "", + "commands", + "shortcut_help", + "mention", + "typed", + "paste", + "paste_question_mark", + "cancel_picker", + ] { + let (mut app, mut events, _ops) = make_test_app_with_channels().await; + app.local_settings.tui.animations = true; + app.local_settings.tui.whimsy = true; + app.local_settings.tui.disable_paste_burst = Some(true); + let mut server = start_config_write_test_app_server(&app).await?; + let mut tui = crate::tui::test_support::make_test_tui()?; + app.replace_chat_widget_with_app_server_thread( + &mut tui, + started("gpt-5.5"), + ThreadAttachPresentation::Fresh, + /*initial_user_message*/ None, + ) + .await?; + assert!(!visible(&app.chat_widget)); + match earlier_input { + "typed" => { + type_into(&mut app.chat_widget, "x"); + app.chat_widget + .handle_key_event(KeyEvent::new(KeyCode::Backspace, KeyModifiers::NONE)); + } + "paste" | "paste_question_mark" => { + let pasted = if earlier_input == "paste" { "x" } else { "?" }; + app.chat_widget.handle_paste(pasted.into()); + app.chat_widget + .handle_key_event(KeyEvent::new(KeyCode::Backspace, KeyModifiers::NONE)); + } + "shortcut_help" => { + app.chat_widget + .handle_key_event(KeyEvent::new(KeyCode::Char('?'), KeyModifiers::SHIFT)); + assert!( + render_bottom_popup(&app.chat_widget, /*width*/ 80) + .contains("customize shortcuts with /keymap") + ); + } + "commands" => { + for command in ["/status", "/pwd"] { + type_into(&mut app.chat_widget, command); + app.chat_widget + .handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + } + } + "mention" => { + type_into(&mut app.chat_widget, "/mention"); + app.chat_widget + .handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + app.chat_widget + .handle_key_event(KeyEvent::new(KeyCode::Backspace, KeyModifiers::NONE)); + } + "" | "cancel_picker" => {} + _ => unreachable!(), + } + type_into(&mut app.chat_widget, "/model"); + app.chat_widget + .handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + if earlier_input == "cancel_picker" { + assert!(app.chat_widget.has_active_view()); + app.chat_widget + .handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); + app.chat_widget.set_model("gpt-6-astra"); + } else { + assert_eq!( + choose_model( + &mut app, + &mut tui, + &mut server, + &mut events, + "gpt-6-astra", + KeyCode::Enter, + ) + .await?, + 1 + ); + } + assert_eq!( + visible(&app.chat_widget), + matches!(earlier_input, "" | "commands" | "shortcut_help"), + "{earlier_input}" + ); + } + Ok(()) +} + +#[tokio::test] +async fn overlays_shortcuts_and_key_chords_leave_the_main_sparkle_untouched() -> Result<()> { + let (mut app, _events, _ops) = make_test_app_with_channels().await; + app.local_settings.tui.animations = true; + app.local_settings.tui.whimsy = true; + let mut server = start_config_write_test_app_server(&app).await?; + let mut tui = crate::tui::test_support::make_test_tui()?; + app.replace_chat_widget_with_app_server_thread( + &mut tui, + started("gpt-6-astra"), + ThreadAttachPresentation::Fresh, + /*initial_user_message*/ None, + ) + .await?; + let keymap_config = toml::from_str("[global]\ntoggle_raw_output = [\"ctrl-x r\"]")?; + app.keymap = RuntimeKeymap::from_config(&keymap_config).expect("valid app chord"); + app.chat_widget + .apply_keymap_update(keymap_config, &app.keymap); + assert!(visible(&app.chat_widget)); + + let ctrl = |ch| KeyEvent::new(KeyCode::Char(ch), KeyModifiers::CONTROL); + for (event, pending, raw) in [ + (ctrl('x'), true, false), + (KeyCode::Char('r').into(), false, true), + (ctrl('x'), true, true), + (KeyCode::Esc.into(), false, true), + ] { + app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(event)) + .await?; + assert_eq!( + ( + app.key_chord_matcher.is_pending(), + app.chat_widget.raw_output_mode(), + visible(&app.chat_widget) + ), + (pending, raw, true) + ); + } + + app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(ctrl('t'))) + .await?; + assert!(app.overlay.is_some()); + for event in [ + TuiEvent::Key(KeyCode::Char('j').into()), + TuiEvent::Paste("overlay input".into()), + TuiEvent::Key(ctrl('t')), + ] { + app.handle_tui_event(&mut tui, &mut server, event).await?; + } + assert!(app.overlay.is_none()); + assert_eq!( + ( + app.chat_widget.composer_is_empty(), + visible(&app.chat_widget) + ), + (true, true) + ); + + app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(KeyCode::Esc.into())) + .await?; + assert!(!visible(&app.chat_widget)); + Ok(()) +} + +#[tokio::test] +async fn a_command_pending_on_fresh_astra_start_can_finish_before_the_sparkle() -> Result<()> { + for (command, visible_after) in [("/status", true), ("/mention", false)] { + let (mut app, _events, _ops) = make_test_app_with_channels().await; + app.chat_widget.local_settings.tui.animations = true; + app.chat_widget.local_settings.tui.whimsy = true; + app.pending_startup_thread_start = true; + app.chat_widget.handle_paste(command.into()); + let mut server = crate::start_embedded_app_server_for_picker(&app.config).await?; + app.handle_startup_thread_started(&mut server, Ok(started("gpt-6-astra"))) + .await?; + assert_eq!( + ( + app.chat_widget.composer_text_with_pending(), + visible(&app.chat_widget) + ), + (command.into(), false) + ); + + app.chat_widget.handle_key_event(KeyCode::Enter.into()); + assert_eq!(visible(&app.chat_widget), visible_after, "{command}"); + } + Ok(()) +} + +#[tokio::test] +async fn only_confirmed_picker_model_changes_can_arm_the_sparkle() -> Result<()> { + for completion in [ + "esc", + "ctrl_c", + "same_model", + "automatic_while_open", + "pick_astra", + "old_task", + ] { + let (mut app, mut events, _ops) = make_test_app_with_channels().await; + app.local_settings.tui.animations = true; + app.local_settings.tui.whimsy = true; + app.local_settings.tui.disable_paste_burst = Some(true); + let mut server = start_config_write_test_app_server(&app).await?; + let mut tui = crate::tui::test_support::make_test_tui()?; + let thread = started("gpt-5.5"); + let original_id = thread.session.thread_id; + app.replace_chat_widget_with_app_server_thread( + &mut tui, + thread, + ThreadAttachPresentation::Fresh, + /*initial_user_message*/ None, + ) + .await?; + assert!(!visible(&app.chat_widget)); + type_into(&mut app.chat_widget, "/model"); + app.chat_widget.handle_key_event(KeyCode::Enter.into()); + assert!(app.chat_widget.has_active_view()); + + match completion { + "esc" | "ctrl_c" => { + let key = if completion == "esc" { + KeyCode::Esc.into() + } else { + KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL) + }; + app.chat_widget.handle_key_event(key); + assert!(!app.chat_widget.has_active_view()); + app.chat_widget.set_model("gpt-6-astra"); + } + "same_model" => { + assert_eq!( + choose_model( + &mut app, + &mut tui, + &mut server, + &mut events, + "gpt-5.5", + KeyCode::Enter, + ) + .await?, + 0 + ); + app.chat_widget.set_model("gpt-6-astra"); + } + "automatic_while_open" => { + app.chat_widget.set_model("gpt-6-astra"); + app.chat_widget + .handle_key_event(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL)); + assert!(!app.chat_widget.has_active_view()); + } + "pick_astra" => { + assert_eq!( + choose_model( + &mut app, + &mut tui, + &mut server, + &mut events, + "gpt-6-astra", + KeyCode::Enter, + ) + .await?, + 1 + ); + } + "old_task" => { + app.replace_chat_widget_with_app_server_thread( + &mut tui, + started("gpt-5.5"), + ThreadAttachPresentation::Fresh, + /*initial_user_message*/ None, + ) + .await?; + app.chat_widget.set_model("gpt-6-astra"); + app.handle_event( + &mut tui, + &mut server, + AppEvent::AstraSelectedFromModelPicker { + thread_id: original_id, + model: "gpt-6-astra".into(), + action: AstraModelPickerAction::UpdateModel, + }, + ) + .await?; + } + _ => unreachable!(), + } + assert_eq!( + visible(&app.chat_widget), + completion == "pick_astra", + "{completion}" + ); + } + Ok(()) +} + +#[tokio::test] +async fn astra_picker_confirms_the_model_at_application_after_an_automatic_update() -> Result<()> { + let mut snapshots = Vec::new(); + for (picker, key, switches_away) in [ + ("default no-op", KeyCode::Enter, false), + ("session no-op", KeyCode::Char('s'), false), + ("advanced no-op", KeyCode::Enter, false), + ("default queued no-op", KeyCode::Enter, false), + ("session queued no-op", KeyCode::Char('s'), false), + ("default changes model", KeyCode::Enter, true), + ("session changes model", KeyCode::Char('s'), true), + ("advanced changes model", KeyCode::Enter, true), + ] { + let (mut app, mut events, _ops) = make_test_app_with_channels().await; + app.config.model = Some("gpt-5.5".into()); + app.local_settings.tui.animations = true; + app.local_settings.tui.whimsy = true; + let mut server = start_config_write_test_app_server(&app).await?; + let mut tui = crate::tui::test_support::make_test_tui()?; + let thread = server.start_thread(&app.config).await?; + app.replace_chat_widget_with_app_server_thread( + &mut tui, + thread, + ThreadAttachPresentation::Fresh, + /*initial_user_message*/ None, + ) + .await?; + if switches_away { + app.chat_widget.set_model("gpt-6-astra"); + } + assert!(!visible(&app.chat_widget)); + + let mut preset = crate::test_support::TEST_MODEL_PRESETS[0].clone(); + preset.model = "gpt-6-astra".into(); + preset.default_reasoning_effort = if picker.starts_with("advanced") { + ReasoningEffortConfig::Ultra + } else { + ReasoningEffortConfig::Medium + }; + preset.supported_reasoning_efforts = vec![ + ReasoningEffortPreset { + effort: preset.default_reasoning_effort.clone(), + description: "Selected effort".into(), + }, + ReasoningEffortPreset { + effort: ReasoningEffortConfig::Low, + description: "Low effort".into(), + }, + ]; + if picker.starts_with("advanced") { + app.chat_widget.open_advanced_reasoning_popup(preset); + } else { + app.chat_widget.open_reasoning_popup(preset); + } + assert!(app.chat_widget.has_active_view()); + if !picker.contains("queued") { + app.chat_widget.set_model(if switches_away { + "gpt-5.5" + } else { + "gpt-6-astra" + }); + assert!(app.chat_widget.has_active_view()); + } + app.chat_widget.handle_key_event(key.into()); + if picker.contains("queued") { + app.chat_widget.set_model("gpt-6-astra"); + } + while let Ok(event) = events.try_recv() { + if matches!( + &event, + AppEvent::UpdateModel(_) + | AppEvent::UpdateReasoningEffort(_) + | AppEvent::SelectSessionModel { .. } + | AppEvent::ApplyAdvancedReasoning { .. } + | AppEvent::AstraSelectedFromModelPicker { .. } + ) { + app.handle_event(&mut tui, &mut server, event).await?; + } + } + assert!(!app.chat_widget.has_active_view(), "{picker}"); + assert_eq!(app.chat_widget.current_model(), "gpt-6-astra", "{picker}"); + assert_eq!(visible(&app.chat_widget), switches_away, "{picker}"); + if picker.starts_with("default") && !picker.contains("queued") { + let rendered = render_with_sparkle_palette(&app.chat_widget); + let lines = rendered.lines().collect::>(); + let prompt = lines + .iter() + .position(|line| line.contains("Ask Codex to do anything")) + .expect("empty composer shows its placeholder"); + let composer = lines[prompt.saturating_sub(1)..=prompt + 1].join("\n"); + snapshots.push(format!("{picker}:\n{composer}")); + } + server.shutdown().await?; + } + insta::assert_snapshot!(snapshots.join("\n\n")); + Ok(()) +} + +#[tokio::test] +async fn session_only_astra_picker_shows_stars_only_on_an_untouched_task() -> Result<()> { + let (mut app, mut events, _ops) = make_test_app_with_channels().await; + app.config.model = Some("gpt-5.5".into()); + app.config.model_reasoning_effort = Some(ReasoningEffortConfig::Medium); + app.local_settings.tui.animations = true; + app.local_settings.tui.whimsy = true; + app.local_settings.tui.disable_paste_burst = Some(true); + let config_path = app.config.codex_home.join("config.toml"); + let defaults = "model = 'gpt-5.5'\nmodel_reasoning_effort = 'medium'\n"; + std::fs::write(&config_path, defaults)?; + let mut server = start_config_write_test_app_server(&app).await?; + let mut tui = crate::tui::test_support::make_test_tui()?; + let mut snapshots = Vec::new(); + + for scenario in ["untouched", "typed then erased"] { + let thread = server.start_thread(&app.config).await?; + assert_eq!(thread.session.model, "gpt-5.5"); + app.replace_chat_widget_with_app_server_thread( + &mut tui, + thread, + ThreadAttachPresentation::Fresh, + /*initial_user_message*/ None, + ) + .await?; + assert!(!visible(&app.chat_widget)); + if scenario == "typed then erased" { + type_into(&mut app.chat_widget, "x"); + app.chat_widget.handle_key_event(KeyCode::Backspace.into()); + } + type_into(&mut app.chat_widget, "/model"); + app.chat_widget.handle_key_event(KeyCode::Enter.into()); + assert!(app.chat_widget.has_active_view()); + assert_eq!( + choose_model( + &mut app, + &mut tui, + &mut server, + &mut events, + "gpt-6-astra", + KeyCode::Char('s'), + ) + .await?, + 1 + ); + assert_eq!(app.chat_widget.current_model(), "gpt-6-astra"); + + let rendered = render_with_sparkle_palette(&app.chat_widget); + let lines = rendered.lines().collect::>(); + let prompt = lines + .iter() + .position(|line| line.contains("Ask Codex to do anything")) + .expect("empty composer shows its placeholder"); + let composer = lines[prompt.saturating_sub(1)..=prompt + 1].join("\n"); + assert_eq!( + composer.chars().any(|ch| "⠁⠂⠄⠈⠐⠠⡀⢀".contains(ch)), + scenario == "untouched" + ); + snapshots.push(format!("{scenario}:\n{composer}")); + assert_eq!(std::fs::read(&config_path)?, defaults.as_bytes()); + assert_eq!( + (&app.config.model, &app.config.model_reasoning_effort), + ( + &Some("gpt-5.5".into()), + &Some(ReasoningEffortConfig::Medium), + ) + ); + + type_into(&mut app.chat_widget, "x"); + app.chat_widget.handle_key_event(KeyCode::Backspace.into()); + assert_eq!( + choose_model( + &mut app, + &mut tui, + &mut server, + &mut events, + "gpt-6-astra", + KeyCode::Char('s'), + ) + .await?, + 0 + ); + assert!(!visible(&app.chat_widget)); + } + + insta::assert_snapshot!(snapshots.join("\n\n")); + server.shutdown().await?; + Ok(()) +} + +#[tokio::test] +async fn a_read_only_command_can_return_to_active_stars_but_mention_ends_them() -> Result<()> { + let (mut app, _events, _ops) = make_test_app_with_channels().await; + app.local_settings.tui.animations = true; + app.local_settings.tui.whimsy = true; + app.local_settings.tui.disable_paste_burst = Some(true); + let mut tui = crate::tui::test_support::make_test_tui()?; + app.replace_chat_widget_with_app_server_thread( + &mut tui, + started("gpt-6-astra"), + ThreadAttachPresentation::Fresh, + /*initial_user_message*/ None, + ) + .await?; + assert!(visible(&app.chat_widget)); + type_into(&mut app.chat_widget, "/status"); + assert!(!visible(&app.chat_widget)); + app.chat_widget + .handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + assert!(visible(&app.chat_widget)); + type_into(&mut app.chat_widget, "/mention"); + app.chat_widget + .handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + app.chat_widget + .handle_key_event(KeyEvent::new(KeyCode::Backspace, KeyModifiers::NONE)); + assert!(!visible(&app.chat_widget)); + Ok(()) +} + +#[tokio::test] +async fn early_input_and_real_work_consume_the_sparkle() -> Result<()> { + for scenario in ["untouched", "typed_then_erased", "paste", "turn", "review"] { + let (mut app, _events, _ops) = make_test_app_with_channels().await; + app.chat_widget.local_settings.tui.animations = true; + app.chat_widget.local_settings.tui.whimsy = true; + app.pending_startup_thread_start = true; + match scenario { + "typed_then_erased" => { + app.chat_widget.handle_paste("x".into()); + app.chat_widget + .handle_key_event(KeyEvent::new(KeyCode::Backspace, KeyModifiers::NONE)); + } + "paste" => app.chat_widget.handle_paste("draft".into()), + "untouched" | "turn" | "review" => {} + _ => unreachable!(), + } + let mut server = crate::start_embedded_app_server_for_picker(&app.config).await?; + let thread = started("gpt-6-astra"); + let thread_id = thread.session.thread_id; + app.handle_startup_thread_started(&mut server, Ok(thread)) + .await?; + if scenario == "turn" { + app.handle_app_server_event( + &server, + codex_app_server_client::AppServerEvent::ServerNotification(Box::new( + turn_started_notification(thread_id, "work"), + )), + ) + .await; + let mut tui = crate::tui::test_support::make_test_tui()?; + app.drain_active_thread_events(&mut tui).await?; + } else if scenario == "review" { + app.chat_widget.on_review_started(); + } + assert_eq!( + visible(&app.chat_widget), + scenario == "untouched", + "{scenario}" + ); + } + Ok(()) +} diff --git a/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__background_task_defaults_tests__review_regression_agents_overview_creation_is_fresh_but_returning_is_not.snap b/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__background_task_defaults_tests__review_regression_agents_overview_creation_is_fresh_but_returning_is_not.snap new file mode 100644 index 0000000000..c249adfe8a --- /dev/null +++ b/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__background_task_defaults_tests__review_regression_agents_overview_creation_is_fresh_but_returning_is_not.snap @@ -0,0 +1,10 @@ +--- +source: tui/src/app/tests/background_task_defaults_tests.rs +expression: "format!(\"created from the dashboard:\\n{}\\nreturned to the existing task:\\n{}\",\nbefore_footer(&created), before_footer(&returned))" +--- +created from the dashboard: + ⠈ ⢀ ⠁ ⠂ +›⠁Ask Codex to do anything ⠈ ⠁ + ⢀ ⠠ ⠄ ⠠ ⢀ ⠠ ⡀ +returned to the existing task: +› Ask Codex to do anything diff --git a/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__fresh_sparkle_tests__astra_picker_confirms_the_model_at_application_after_an_automatic_update.snap b/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__fresh_sparkle_tests__astra_picker_confirms_the_model_at_application_after_an_automatic_update.snap new file mode 100644 index 0000000000..243ad7ae65 --- /dev/null +++ b/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__fresh_sparkle_tests__astra_picker_confirms_the_model_at_application_after_an_automatic_update.snap @@ -0,0 +1,12 @@ +--- +source: tui/src/app/tests/fresh_sparkle_tests.rs +expression: "snapshots.join(\"\\n\\n\")" +--- +default no-op: +› Ask Codex to do anything + + +default changes model: + ⠈ ⢀ ⠁ ⠂ +›⠁Ask Codex to do anything ⠈ ⠁ + ⢀ ⠠ ⠄ ⠠ ⢀ ⠠ ⡀ diff --git a/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__fresh_sparkle_tests__session_only_astra_picker_shows_stars_only_on_an_untouched_task.snap b/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__fresh_sparkle_tests__session_only_astra_picker_shows_stars_only_on_an_untouched_task.snap new file mode 100644 index 0000000000..eaaa3418dc --- /dev/null +++ b/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__fresh_sparkle_tests__session_only_astra_picker_shows_stars_only_on_an_untouched_task.snap @@ -0,0 +1,11 @@ +--- +source: tui/src/app/tests/fresh_sparkle_tests.rs +expression: "snapshots.join(\"\\n\\n\")" +--- +untouched: + ⠈ ⢀ ⠁ ⠂ +›⠁Ask Codex to do anything ⠈ ⠁ + ⢀ ⠠ ⠄ ⠠ ⢀ ⠠ ⡀ + +typed then erased: +› Ask Codex to do anything diff --git a/codex-rs/tui/src/app/thread_routing.rs b/codex-rs/tui/src/app/thread_routing.rs index 93258432e8..9d719edbd6 100644 --- a/codex-rs/tui/src/app/thread_routing.rs +++ b/codex-rs/tui/src/app/thread_routing.rs @@ -1565,7 +1565,7 @@ impl App { self.chat_widget.set_token_info(/*info*/ None); } match presentation { - ThreadAttachPresentation::SessionLineage => { + ThreadAttachPresentation::Fresh | 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 f29095ada9..e4529c4d65 100644 --- a/codex-rs/tui/src/app_event.rs +++ b/codex-rs/tui/src/app_event.rs @@ -51,6 +51,7 @@ use crate::app_server_session::AppServerStartedThread; use crate::bottom_pane::ApprovalRequest; use crate::bottom_pane::StatusLineItem; use crate::bottom_pane::TerminalTitleItem; +use crate::chatwidget::AstraModelPickerAction; use crate::chatwidget::ConnectorScopeGeneration; use crate::chatwidget::ThreadUsageOutcome; use crate::chatwidget::UserMessage; @@ -1118,6 +1119,14 @@ pub(crate) enum AppEvent { /// Update the current model slug in the running app and widget. UpdateModel(String), + /// Apply a final Astra picker action and offer the flourish only if it changed the model on + /// its original task. Automatic model updates do not use this event. + AstraSelectedFromModelPicker { + thread_id: ThreadId, + model: String, + action: AstraModelPickerAction, + }, + /// Result of creating a TUI-owned WebRTC offer for an active thread. RealtimeWebrtcOfferCreated { thread_id: ThreadId, diff --git a/codex-rs/tui/src/bottom_pane/chat_composer.rs b/codex-rs/tui/src/bottom_pane/chat_composer.rs index 2b86759a67..9bfe443e23 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer.rs @@ -4,7 +4,7 @@ //! completed slash commands to atomic elements, and handles Enter submission/newlines. //! It also shows Luna Reserve's yellow prompt arrow and detects unbracketed paste bursts //! from raw key streams, particularly on Windows. -//! The live voice strip renders after effort ignition. +//! The live voice strip renders after effort ignition, followed by the Astra sparkle when eligible. //! //! The plain-text preset keeps command prefixes literal, including `!`, so Enter and Tab //! submit ordinary text without enabling shell mode. @@ -120,8 +120,9 @@ //! navigation slash commands remain available so users can leave or manage the view. Transcript //! exports also remain available, including an explicit destination filename. //! -//! During reconnection, `handle_disconnected_key` edits the draft directly without -//! popup dispatch or submission. Enter and Tab leave the draft intact until reconnection succeeds. +//! During reconnection, `handle_disconnected_key` edits the draft directly without popup dispatch, +//! composer shortcuts, or submission; `?` becomes literal input. Enter and Tab leave the draft +//! intact until reconnection succeeds. //! Collapsed pastes expand into editable text so the full draft can be copied before quitting. //! //! # Reasoning Effort Animations @@ -134,6 +135,36 @@ //! restoration clears any transition queued while replaying the saved session. Rendering advances //! active transitions through the frame requester until they finish. //! +//! # Astra Sparkle Eligibility +//! +//! A confirmed new task can offer one flourish when it starts with Astra or the user switches to +//! Astra through `/model` before entering ordinary prompt content. The draft tracks whether it is +//! untouched, contains a recognized slash command, or is permanently dismissed. An eligible slash +//! command keeps the opportunity while being typed, dispatched, or erased; a fresh Astra response +//! can arm the effect while the command is still pending. Stars stay hidden until the composer is +//! empty. Commands that insert draft content, ordinary typed, pasted, or restored drafts, +//! attachments, and real work dismiss the opportunity even if that content is later cleared. +//! Ordinary disconnected edits also dismiss it immediately, even when erased before rendering; +//! a recognized command typed and erased offline still preserves the opportunity. +//! Opening history search, typing or pasting its query, and canceling it with `Esc` or `Ctrl+C` +//! temporarily hide an active field without restarting its deadline. Any buffered keys are +//! integrated into the original draft without being classified again. A preview does not count +//! as a draft until the user accepts a nonempty match. +//! Toggling shortcut help on an empty composer also hides an active field until help closes, +//! without restarting its deadline, and leaves an unused opportunity intact. A literal `?` is +//! ordinary prompt content. +//! Startup draft snapshots carry this distinction so erased ordinary input does not become +//! untouched on handoff. +//! +//! Sparkle key and paste handling runs only for input routed to the composer; ordinary characters +//! are observed before the paste-burst buffer can hide the first edit. An edit that flushes and +//! erases a held slash also clears the tracked command. An empty main-composer `Esc` +//! can stop the active flourish. Once shown, it fades out by 15 seconds; command entry, popups, and +//! focus loss hide the field without restarting that deadline. Rendering runs after the textarea, +//! placeholder, effort ignition, and voice strip, and draws only in eligible blank cells without +//! overwriting the placeholder or normal cursor. Hidden frames do not schedule animation redraws; +//! motion settings, whimsy settings, and true-color support also gate the effect. +//! //! # Large Paste Placeholders //! //! Large pastes insert an element placeholder in the buffer and store the full text in @@ -201,8 +232,9 @@ //! - Unmodified Tab joins detected bursts, including short Unicode prefixes, before popup dispatch. //! Expired bursts are flushed first so manual Tab keeps its normal shortcut behavior. //! - [`ChatComposer::flush_paste_burst_if_due`]/[`ChatComposer::handle_paste_burst_flush`]: called -//! from UI ticks to turn a pending burst into either an explicit paste (`handle_paste`) or a -//! normal typed character. +//! from UI ticks to integrate a pending burst via [`ChatComposer::apply_paste`] or insert a +//! held single character. Explicit terminal paste events use [`ChatComposer::handle_paste`] to +//! classify input first; buffered keys have already been classified. //! //! # Input Disabled Mode //! @@ -287,7 +319,6 @@ use super::skill_popup::SkillPopup; use super::slash_commands::ServiceTierCommand; use super::slash_commands::SlashCommandItem; use super::voice_strip::VoiceStrip; -use crate::bottom_pane::paste_burst::FlushResult; use crate::history_cell::sanitize_user_text; use crate::key_hint::KeyBindingListExt; use crate::keymap::EditorKeymap; @@ -319,6 +350,7 @@ mod paste_input; mod popup_state; mod reconnect; mod slash_input; +mod sparkle; mod vim_history; mod vim_search; @@ -531,6 +563,7 @@ pub(crate) struct ChatComposer { footer: FooterState, has_focus: bool, frame_requester: Option, + sparkle: sparkle::Sparkle, effort_tier: Option, effort_animation_style: Option, effort_ignition: Option, @@ -605,6 +638,7 @@ pub(crate) struct ComposerDraftSnapshot { pub(crate) pending_pastes: Vec<(String, String)>, pub(crate) startup_local_history: Vec, pub(crate) last_composer_activity_at: Option, + pub(crate) sparkle_draft: sparkle::SparkleDraft, } const FOOTER_SPACING_HEIGHT: u16 = 0; @@ -699,6 +733,7 @@ impl ChatComposer { }, has_focus: has_input_focus, frame_requester: None, + sparkle: sparkle::Sparkle::default(), effort_tier: None, effort_animation_style: None, effort_ignition: None, @@ -1203,64 +1238,6 @@ impl ChatComposer { self.history.record_replayed_submission(entry); } - /// Integrate pasted text into the composer. - /// - /// Acts as the only place where paste text is integrated, both for: - /// - /// - Real/explicit paste events surfaced by the terminal, and - /// - Non-bracketed "paste bursts" that [`PasteBurst`](super::paste_burst::PasteBurst) buffers - /// and later flushes here. - /// - /// Behavior: - /// - /// - If history search is active, inserts nonempty text into its query and ignores empty pastes. - /// - If Vim search is active, inserts text into its query. - /// - Otherwise, if the paste is larger than `LARGE_PASTE_CHAR_THRESHOLD` chars, inserts a - /// placeholder element (expanded on submit) and stores the full text in `pending_pastes`. - /// - Otherwise, if the paste looks like an image path, attaches the image and inserts a - /// trailing space so the user can keep typing naturally. - /// - Otherwise, inserts the pasted text directly into the textarea. - /// - /// For composer edits, clears any paste-burst Enter suppression state so a real paste cannot - /// affect the next user Enter key, then syncs popup state. - pub fn handle_paste(&mut self, pasted: String) -> bool { - let pasted = pasted.replace("\r\n", "\n").replace('\r', "\n"); - let pasted = sanitize_user_text(pasted.into()); - if self.history_search.is_some() { - if !pasted.is_empty() { - self.update_history_search_query(|query| query.push_str(&pasted)); - } - return true; - } - if let Some(query) = self.draft.textarea.vim_query_mut() { - query.editor.insert_str(&pasted); - return true; - } - let started_vim_edit = self.begin_direct_vim_edit(); - let char_count = pasted.chars().count(); - if char_count > LARGE_PASTE_CHAR_THRESHOLD { - let placeholder = self.next_large_paste_placeholder(char_count); - self.draft.textarea.insert_element(&placeholder); - self.draft - .pending_pastes - .push((placeholder, pasted.into_owned())); - } else if char_count > 1 - && self.image_paste_enabled() - && self.handle_paste_image_path(&pasted) - { - let cursor = self.draft.textarea.cursor(); - self.draft.textarea.insert_str_at(cursor, " "); - } else { - self.insert_str(&pasted); - } - self.draft.paste_burst.clear_after_explicit_paste(); - self.sync_popups(); - if started_vim_edit { - self.finish_vim_edit(); - } - true - } - pub fn handle_paste_image_path(&mut self, pasted: &str) -> bool { let Some(path_buf) = normalize_pasted_path(pasted) else { return false; @@ -1284,41 +1261,13 @@ impl ChatComposer { } } - /// Enable or disable paste-burst handling. - /// - /// `disable_paste_burst` is an escape hatch for terminals/platforms where the burst heuristic - /// is unwanted or has already been handled elsewhere. - /// - /// When transitioning from enabled → disabled, we "defuse" any in-flight burst state so it - /// cannot affect subsequent normal typing: - /// - /// - First, flush any held/buffered text immediately via - /// [`PasteBurst::flush_before_modified_input`], and feed it through `handle_paste(String)`. - /// This preserves user input and routes it through the same integration path as explicit - /// pastes (large-paste placeholders, image-path detection, and popup sync). - /// - Then clear the burst timing and Enter-suppression window via - /// [`PasteBurst::clear_after_explicit_paste`]. - /// - /// We intentionally do not use `clear_window_after_non_char()` here: it clears timing state - /// without emitting any buffered text, which can leave a non-empty buffer unable to flush - /// later (because `flush_if_due()` relies on `last_plain_char_time` to time out). - pub(crate) fn set_disable_paste_burst(&mut self, disabled: bool) { - let was_disabled = self.draft.disable_paste_burst; - self.draft.disable_paste_burst = disabled; - if disabled && !was_disabled { - if let Some(pasted) = self.draft.paste_burst.flush_before_modified_input() { - self.handle_paste(pasted); - } - self.draft.paste_burst.clear_after_explicit_paste(); - } - } - /// Replace the composer content with text from an external editor. /// Clears pending paste placeholders and keeps only attachments whose /// placeholder labels still appear in the new text. Image placeholders /// are renumbered to `[Image #M+1]..[Image #N]` (where `M` is the number of /// remote images). Cursor is placed at the end after rebuilding elements. pub(crate) fn apply_external_edit(&mut self, text: String) { + self.note_sparkle_replaced_text(&text); self.vim_history = VimHistory::default(); self.draft.pending_pastes.clear(); let (text, _) = self.imported_text_for_textarea(text, Vec::new()); @@ -1404,7 +1353,7 @@ impl ChatComposer { /// footer mode so the visible hints match the new editing surface. pub(crate) fn set_vim_enabled(&mut self, enabled: bool) { if let Some(pasted) = self.draft.paste_burst.flush_before_modified_input() { - self.handle_paste(pasted); + self.apply_paste(pasted); } self.draft.textarea.enable_vim_search(); self.draft.textarea.set_vim_enabled(enabled); @@ -1550,6 +1499,9 @@ impl ChatComposer { } pub(crate) fn set_remote_image_urls(&mut self, urls: Vec) { + if !self.sparkle.history_preview && !urls.is_empty() { + self.dismiss_sparkle(); + } self.attachments .set_remote_image_urls(urls, &mut self.draft.textarea); self.sync_popups(); @@ -1595,6 +1547,13 @@ impl ChatComposer { local_image_paths: Vec, mention_bindings: Vec, ) { + if !self.sparkle.history_preview { + if local_image_paths.is_empty() { + self.note_sparkle_replaced_text(&text); + } else { + self.dismiss_sparkle(); + } + } // Clear any existing content, placeholders, and attachments first. self.footer.flash = None; self.vim_history = VimHistory::default(); @@ -1759,7 +1718,7 @@ impl ChatComposer { /// Flush buffered typing before clearing so cancellation preserves the complete draft in history. pub(crate) fn clear_for_ctrl_c(&mut self) -> Option { if let Some(pasted) = self.draft.paste_burst.flush_before_modified_input() { - self.handle_paste(pasted); + self.apply_paste(pasted); } if self.is_empty() { return None; @@ -1844,6 +1803,7 @@ impl ChatComposer { pending_pastes: self.pending_pastes(), startup_local_history: self.history.startup_local_history().to_vec(), last_composer_activity_at: None, + sparkle_draft: self.sparkle.draft.get(), } } @@ -1881,6 +1841,7 @@ impl ChatComposer { /// Insert an attachment placeholder and track it for the next submission. pub fn attach_image(&mut self, path: PathBuf) { + self.dismiss_sparkle(); let started_vim_edit = self.begin_direct_vim_edit(); self.attachments .attach_image(&mut self.draft.textarea, path); @@ -1903,7 +1864,8 @@ impl ChatComposer { /// /// Call this from a UI tick to turn paste-burst transient state into explicit textarea edits: /// - /// - If a burst times out, flush it via `handle_paste(String)`. + /// - If a burst times out, integrate it via [`Self::apply_paste`]. Its key events have already + /// been classified; [`Self::handle_paste`] classifies explicit terminal pastes instead. /// - If only the first ASCII char was held (flicker suppression) and no burst followed, emit it /// as normal typed input. /// @@ -2012,6 +1974,9 @@ impl ChatComposer { } pub(crate) fn insert_str(&mut self, text: &str) { + if !text.is_empty() && self.sparkle.draft.get() == sparkle::SparkleDraft::Untouched { + self.dismiss_sparkle(); + } let started_vim_edit = self.begin_direct_vim_edit(); self.draft.textarea.insert_str(text); self.sync_bash_mode_from_text(); @@ -2031,6 +1996,13 @@ impl ChatComposer { return (InputResult::None, false); } + let before = self.before_sparkle_key(key_event); + let result = self.handle_key_event_inner(key_event); + self.after_sparkle_key(before, &result.0); + result + } + + fn handle_key_event_inner(&mut self, key_event: KeyEvent) -> (InputResult, bool) { if self.history_search.is_none() && !self.popups.active() && self.draft.textarea.wants_vim_search_key(key_event) @@ -2128,7 +2100,7 @@ impl ChatComposer { // any existing burst buffer (including a pending first char from the ASCII path) so // we don't carry that transient state forward. if let Some(pasted) = self.draft.paste_burst.flush_before_modified_input() { - self.handle_paste(pasted); + self.apply_paste(pasted); } if let Some(decision) = self.draft.paste_burst.on_plain_char_no_hold(now) { match decision { @@ -2165,7 +2137,7 @@ impl ChatComposer { } } if let Some(pasted) = self.draft.paste_burst.flush_before_modified_input() { - self.handle_paste(pasted); + self.apply_paste(pasted); } self.draft.textarea.input(input); @@ -3232,7 +3204,7 @@ impl ChatComposer { } if should_queue { if let Some(pasted) = self.draft.paste_burst.flush_before_modified_input() { - self.handle_paste(pasted); + self.apply_paste(pasted); } let visible_shell_command = self.is_bang_shell_command(); let original_input = self.current_text(); @@ -3532,7 +3504,7 @@ impl ChatComposer { } if self.draft.is_bash_mode && key_event.code == KeyCode::Esc { if let Some(pasted) = self.draft.paste_burst.flush_before_modified_input() { - self.handle_paste(pasted); + self.apply_paste(pasted); } if self.draft.textarea.is_empty() { self.draft.is_bash_mode = false; @@ -3643,28 +3615,6 @@ impl ChatComposer { .map(|_| Line::from(vec![Span::from("Shell mode").light_red()])) } - /// Applies any due `PasteBurst` flush at time `now`. - /// - /// Converts [`PasteBurst::flush_if_due`] results into concrete textarea mutations. - /// - /// Callers: - /// - /// - UI ticks via [`ChatComposer::flush_paste_burst_if_due`], so held first-chars can render. - /// - Input handling via [`ChatComposer::handle_input_basic`], so a due burst does not lag. - fn handle_paste_burst_flush(&mut self, now: Instant) -> bool { - match self.draft.paste_burst.flush_if_due(now) { - FlushResult::Paste(pasted) => { - self.handle_paste(pasted); - true - } - FlushResult::Typed(ch) => { - self.insert_str(ch.to_string().as_str()); - true - } - FlushResult::None => false, - } - } - /// Handles keys that mutate the textarea, including paste-burst detection. /// /// Acts as the lowest-level keypath for keys that mutate the textarea. It is also where plain @@ -3779,7 +3729,7 @@ impl ChatComposer { } } if let Some(pasted) = self.draft.paste_burst.flush_before_modified_input() { - self.handle_paste(pasted); + self.apply_paste(pasted); } } @@ -3792,7 +3742,7 @@ impl ChatComposer { if !matches!(input.code, KeyCode::Char(_) | KeyCode::Enter) && let Some(pasted) = self.draft.paste_burst.flush_before_modified_input() { - self.handle_paste(pasted); + self.apply_paste(pasted); } // For non-char inputs (or after flushing), handle normally. // Track element removals so we can drop any corresponding placeholders without scanning @@ -3887,23 +3837,29 @@ impl ChatComposer { return true; } - let toggles = self.footer.hint_override.is_none() + let Some(next) = self.empty_prompt_shortcut_toggle(key_event) else { + return false; + }; + self.footer.mode = next; + true + } + + fn empty_prompt_shortcut_toggle(&self, key_event: &KeyEvent) -> Option { + if key_event.kind == KeyEventKind::Press + && self.footer.hint_override.is_none() && self.toggle_shortcuts_keys.is_pressed(*key_event) && self.is_empty() - && !self.is_in_paste_burst(); - - if !toggles { - return false; + && !self.is_in_paste_burst() + { + let next = toggle_shortcut_mode( + self.footer.mode, + self.quit_shortcut_hint_visible(), + self.is_empty(), + ); + (next != self.footer.mode).then_some(next) + } else { + None } - - let next = toggle_shortcut_mode( - self.footer.mode, - self.quit_shortcut_hint_visible(), - self.is_empty(), - ); - let changed = next != self.footer.mode; - self.footer.mode = next; - changed } fn footer_props(&self) -> FooterProps { @@ -5075,6 +5031,12 @@ impl ChatComposer { } drop(state); self.render_voice_strip(composer_rect, buf); + self.render_sparkle( + composer_rect, + textarea_rect, + self.cursor_pos_with_textarea_right_reserve(area, textarea_right_reserve), + buf, + ); } } diff --git a/codex-rs/tui/src/bottom_pane/chat_composer/history_search.rs b/codex-rs/tui/src/bottom_pane/chat_composer/history_search.rs index 419a3b6f25..5ce24e7392 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer/history_search.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer/history_search.rs @@ -16,7 +16,8 @@ //! latest history entry by itself. Typing or pasting a query restarts traversal from newest to oldest, //! repeated Ctrl+R/Up and Ctrl+S/Down move between unique matches, `Enter` accepts the current //! preview as an editable draft, and `Esc` or Ctrl+C restores the exact draft that existed before -//! search started. +//! search started. Buffered keys are integrated before that snapshot without reclassifying them as +//! an explicit paste. Only accepting a nonempty preview dismisses any unused Astra sparkle opportunity. use std::ops::Range; @@ -110,14 +111,14 @@ impl ChatComposer { /// Opens footer-owned reverse history search without previewing history yet. /// - /// Entering search mode first flushes pending paste-burst text, then snapshots the full - /// composer draft, clears any file/search popup state, and resets history traversal. The first - /// visible match is produced only after the footer query becomes non-empty, which keeps Ctrl+R - /// from replacing an empty composer with the latest prompt before the user has searched for - /// anything. + /// Entering search mode first integrates already-classified paste-burst text with + /// [`Self::apply_paste`], then snapshots the full composer draft, clears any file/search popup + /// state, and resets history traversal. The first visible match is produced only after the + /// footer query becomes non-empty, which keeps Ctrl+R from replacing an empty composer with + /// the latest prompt before the user has searched for anything. pub(super) fn begin_history_search(&mut self) -> (InputResult, bool) { if let Some(pasted) = self.draft.paste_burst.flush_before_modified_input() { - self.handle_paste(pasted); + self.apply_paste(pasted); } self.draft.paste_burst.clear_window_after_non_char(); @@ -206,6 +207,9 @@ impl ChatComposer { .is_some_and(|search| matches!(search.status, HistorySearchStatus::Match)) { self.history_search = None; + if !self.is_empty() { + self.dismiss_sparkle(); + } self.history.reset_search(); self.footer.mode = reset_mode_after_activity(self.footer.mode); self.move_cursor_to_end(); @@ -259,7 +263,7 @@ impl ChatComposer { if let Some(search) = self.history_search.as_mut() { search.status = HistorySearchStatus::Idle; } - self.restore_draft(original_draft); + self.with_sparkle_history_preview(|composer| composer.restore_draft(original_draft)); return InputResult::None; } let result = self.history.search( @@ -282,7 +286,7 @@ impl ChatComposer { search.status = HistorySearchStatus::Searching; let query = search.query.clone(); let original_draft = search.original_draft.clone(); - self.restore_draft(original_draft); + self.with_sparkle_history_preview(|composer| composer.restore_draft(original_draft)); if query.is_empty() { self.history.reset_search(); if let Some(search) = self.history_search.as_mut() { @@ -311,7 +315,7 @@ impl ChatComposer { }; self.history.reset_navigation(); self.footer.mode = reset_mode_after_activity(self.footer.mode); - self.restore_draft(search.original_draft); + self.with_sparkle_history_preview(|composer| composer.restore_draft(search.original_draft)); self.vim_history = search.original_vim_history; self.draft .textarea @@ -333,7 +337,7 @@ impl ChatComposer { if let Some(search) = self.history_search.as_mut() { search.status = HistorySearchStatus::Match; } - self.apply_history_entry(entry); + self.with_sparkle_history_preview(|composer| composer.apply_history_entry(entry)); } HistorySearchResult::Pending => { if let Some(search) = self.history_search.as_mut() { @@ -358,12 +362,21 @@ impl ChatComposer { }; } if let Some(original_draft) = original_draft { - self.restore_draft(original_draft); + self.with_sparkle_history_preview(|composer| { + composer.restore_draft(original_draft) + }); } } } } + fn with_sparkle_history_preview(&mut self, preview: impl FnOnce(&mut Self)) { + let previous = self.sparkle.history_preview; + self.sparkle.history_preview = true; + preview(self); + self.sparkle.history_preview = previous; + } + /// Builds the footer line shown while reverse history search is active. /// /// The footer displays the query as the editable field and uses the status to decide whether diff --git a/codex-rs/tui/src/bottom_pane/chat_composer/inline_input.rs b/codex-rs/tui/src/bottom_pane/chat_composer/inline_input.rs index eb348d49c1..643ff56f1e 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer/inline_input.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer/inline_input.rs @@ -66,10 +66,10 @@ impl ChatComposer { || self.vim_normal_keymap.move_down.is_pressed(key))) } - /// Finish buffered typing before another answer takes over this editor. + /// Integrate already-classified buffered typing before another answer takes over this editor. pub(crate) fn flush_pending_input(&mut self) { if let Some(text) = self.draft.paste_burst.flush_before_modified_input() { - self.handle_paste(text); + self.apply_paste(text); } self.draft.paste_burst.clear_after_explicit_paste(); } diff --git a/codex-rs/tui/src/bottom_pane/chat_composer/paste_input.rs b/codex-rs/tui/src/bottom_pane/chat_composer/paste_input.rs index faf6d54fa9..380949f5ae 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer/paste_input.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer/paste_input.rs @@ -1,8 +1,124 @@ -//! Capture raw paste tabs before completion and submission shortcuts see them. +//! Classify and integrate composer pastes and capture raw paste tabs before completion or submission. use super::*; +use crate::bottom_pane::paste_burst::FlushResult; impl ChatComposer { + /// Classify an explicit paste before integrating text shared with the buffered key path. + pub fn handle_paste(&mut self, pasted: String) -> bool { + self.note_sparkle_paste(&pasted); + self.apply_paste(pasted) + } + + /// Enable or disable paste-burst handling. + /// + /// `disable_paste_burst` is an escape hatch for terminals/platforms where the burst heuristic + /// is unwanted or has already been handled elsewhere. + /// + /// When transitioning from enabled → disabled, we "defuse" any in-flight burst state so it + /// cannot affect subsequent normal typing: + /// + /// - First, flush held/buffered text via [`PasteBurst::flush_before_modified_input`] and + /// integrate it with [`Self::apply_paste`]. Its key events have already been classified; + /// [`Self::handle_paste`] classifies explicit terminal pastes before using the same + /// integration path (large-paste placeholders, image-path detection, and popup sync). + /// - Then clear the burst timing and Enter-suppression window via + /// [`PasteBurst::clear_after_explicit_paste`]. + /// + /// We intentionally do not use `clear_window_after_non_char()` here: it clears timing state + /// without emitting any buffered text, which can leave a non-empty buffer unable to flush + /// later (because `flush_if_due()` relies on `last_plain_char_time` to time out). + pub(crate) fn set_disable_paste_burst(&mut self, disabled: bool) { + let was_disabled = self.draft.disable_paste_burst; + self.draft.disable_paste_burst = disabled; + if disabled && !was_disabled { + if let Some(pasted) = self.draft.paste_burst.flush_before_modified_input() { + self.apply_paste(pasted); + } + self.draft.paste_burst.clear_after_explicit_paste(); + } + } + + /// Applies any due `PasteBurst` flush at time `now`. + /// + /// Converts [`PasteBurst::flush_if_due`] results into concrete textarea mutations. + /// Buffered keys have already been classified; paste results use [`Self::apply_paste`]. + /// + /// Callers: + /// + /// - UI ticks via [`ChatComposer::flush_paste_burst_if_due`], so held first-chars can render. + /// - Input handling via [`ChatComposer::handle_input_basic`], so a due burst does not lag. + pub(super) fn handle_paste_burst_flush(&mut self, now: Instant) -> bool { + match self.draft.paste_burst.flush_if_due(now) { + FlushResult::Paste(pasted) => { + self.apply_paste(pasted); + true + } + FlushResult::Typed(ch) => { + self.insert_str(ch.to_string().as_str()); + true + } + FlushResult::None => false, + } + } + + /// Integrate pasted text into the composer. + /// + /// Both input paths integrate their text here: + /// + /// - Real/explicit paste events surfaced by the terminal, and + /// - Non-bracketed "paste bursts" that + /// [`PasteBurst`](crate::bottom_pane::paste_burst::PasteBurst) buffers and later flushes here. + /// + /// Behavior: + /// + /// - If history search is active, inserts nonempty text into its query and ignores empty pastes. + /// - If Vim search is active, inserts text into its query. + /// - Otherwise, if the paste is larger than `LARGE_PASTE_CHAR_THRESHOLD` chars, inserts a + /// placeholder element (expanded on submit) and stores the full text in `pending_pastes`. + /// - Otherwise, if the paste looks like an image path, attaches the image and inserts a + /// trailing space so the user can keep typing naturally. + /// - Otherwise, inserts the pasted text directly into the textarea. + /// + /// Composer edits clear paste-burst Enter suppression and sync popups. + pub(super) fn apply_paste(&mut self, pasted: String) -> bool { + let pasted = pasted.replace("\r\n", "\n").replace('\r', "\n"); + let pasted = sanitize_user_text(pasted.into()); + if self.history_search.is_some() { + if !pasted.is_empty() { + self.update_history_search_query(|query| query.push_str(&pasted)); + } + return true; + } + if let Some(query) = self.draft.textarea.vim_query_mut() { + query.editor.insert_str(&pasted); + return true; + } + let started_vim_edit = self.begin_direct_vim_edit(); + let char_count = pasted.chars().count(); + if char_count > LARGE_PASTE_CHAR_THRESHOLD { + let placeholder = self.next_large_paste_placeholder(char_count); + self.draft.textarea.insert_element(&placeholder); + self.draft + .pending_pastes + .push((placeholder, pasted.into_owned())); + } else if char_count > 1 + && self.image_paste_enabled() + && self.handle_paste_image_path(&pasted) + { + let cursor = self.draft.textarea.cursor(); + self.draft.textarea.insert_str_at(cursor, " "); + } else { + self.insert_str(&pasted); + } + self.draft.paste_burst.clear_after_explicit_paste(); + self.sync_popups(); + if started_vim_edit { + self.finish_vim_edit(); + } + true + } + pub(super) fn handle_paste_tab(&mut self, key: KeyEvent, now: Instant) -> bool { if key.code != KeyCode::Tab || !key.modifiers.is_empty() diff --git a/codex-rs/tui/src/bottom_pane/chat_composer/reconnect.rs b/codex-rs/tui/src/bottom_pane/chat_composer/reconnect.rs index b0166f1fbf..aea6d84580 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer/reconnect.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer/reconnect.rs @@ -1,5 +1,6 @@ //! Offline editing retains the draft in place. //! Paste Enter handling is shared with normal submission so buffered newlines survive both paths. +//! Offline draft edits also consume the Astra sparkle opportunity before rendering. use super::*; @@ -66,7 +67,14 @@ impl ChatComposer { if !matches!(key.code, KeyCode::Enter | KeyCode::Tab) && matches!(key.kind, KeyEventKind::Press | KeyEventKind::Repeat) { - self.handle_input_basic(key); + // Null is sent internally to clean up on disconnect or expand a paste; it isn't an edit. + let before = if key.code == KeyCode::Null { + None + } else { + self.before_sparkle_editor_key(key) + }; + let (result, _) = self.handle_input_basic(key); + self.after_sparkle_key(before, &result); } } } diff --git a/codex-rs/tui/src/bottom_pane/chat_composer/snapshots/codex_tui__bottom_pane__chat_composer__sparkle__tests__a_fresh_astra_response_waits_for_the_pending_command_to_leave.snap b/codex-rs/tui/src/bottom_pane/chat_composer/snapshots/codex_tui__bottom_pane__chat_composer__sparkle__tests__a_fresh_astra_response_waits_for_the_pending_command_to_leave.snap new file mode 100644 index 0000000000..60125b16ac --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/chat_composer/snapshots/codex_tui__bottom_pane__chat_composer__sparkle__tests__a_fresh_astra_response_waits_for_the_pending_command_to_leave.snap @@ -0,0 +1,16 @@ +--- +source: tui/src/bottom_pane/chat_composer/sparkle_tests.rs +expression: "format!(\"command during startup:\\n{}\\n\\nafter command:\\n{}\", text(&pending),\ntext(&completed))" +--- +command during startup: + +› /status + + /status show current session configuration and token usage + /statusline configure which items appear in the status line + +after command: + ⠈ ⢀ ⠁ ⠂ +›⠁Ask Codex to do anything ⠈ ⠁ + ⢀ ⠠ ⠄ ⠠ ⢀ ⠠ ⡀ + ? for shortcuts 100% context left diff --git a/codex-rs/tui/src/bottom_pane/chat_composer/snapshots/codex_tui__bottom_pane__chat_composer__sparkle__tests__canceled_history_search_restores_visible_stars_only_before_the_original_deadline.snap b/codex-rs/tui/src/bottom_pane/chat_composer/snapshots/codex_tui__bottom_pane__chat_composer__sparkle__tests__canceled_history_search_restores_visible_stars_only_before_the_original_deadline.snap new file mode 100644 index 0000000000..baa784f4f9 --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/chat_composer/snapshots/codex_tui__bottom_pane__chat_composer__sparkle__tests__canceled_history_search_restores_visible_stars_only_before_the_original_deadline.snap @@ -0,0 +1,37 @@ +--- +source: tui/src/bottom_pane/chat_composer/sparkle_tests.rs +expression: "snapshots.join(\"\\n\\n\")" +--- +expires while open: false +initial: + ⠈ ⢀ ⠁ ⠂ +›⠁Ask Codex to do anything ⠈ ⠁ + ⢀ ⠠ ⠄ ⠠ ⢀ ⠠ ⡀ + ? for shortcuts 100% context left +searching: + +› stored draft + + reverse-i-search: stored enter accept · esc cancel +after escape: + ⠁ ⡀ ⠄ ⠄ ⠄ +› Ask Codex to do anything ⠈ + ⠠ ⠠ ⢀ ⢀ ⡀ ⠄ + ? for shortcuts 100% context left + +expires while open: true +initial: + ⠈ ⢀ ⠁ ⠂ +›⠁Ask Codex to do anything ⠈ ⠁ + ⢀ ⠠ ⠄ ⠠ ⢀ ⠠ ⡀ + ? for shortcuts 100% context left +searching: + +› stored draft + + reverse-i-search: stored enter accept · esc cancel +after escape: + +› Ask Codex to do anything + + ? for shortcuts 100% context left diff --git a/codex-rs/tui/src/bottom_pane/chat_composer/snapshots/codex_tui__bottom_pane__chat_composer__sparkle__tests__disconnected_sparkle_edits_are_tracked_between_renders.snap b/codex-rs/tui/src/bottom_pane/chat_composer/snapshots/codex_tui__bottom_pane__chat_composer__sparkle__tests__disconnected_sparkle_edits_are_tracked_between_renders.snap new file mode 100644 index 0000000000..0c60de5e7f --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/chat_composer/snapshots/codex_tui__bottom_pane__chat_composer__sparkle__tests__disconnected_sparkle_edits_are_tracked_between_renders.snap @@ -0,0 +1,27 @@ +--- +source: tui/src/bottom_pane/chat_composer/sparkle_tests.rs +expression: "snapshots.join(\"\\n\\n\")" +--- +gpt-6-astra +before disconnect: + ⠈ ⢀ ⠁ ⠂ +›⠁Ask Codex to do anything ⠈ ⠁ + ⢀ ⠠ ⠄ ⠠ ⢀ ⠠ ⡀ + ? for shortcuts 100% context left +after typing and erasing without rendering: + +› Ask Codex to do anything + + ? for shortcuts 100% context left + +gpt-5.5 +before disconnect: + +› Ask Codex to do anything + + ? for shortcuts 100% context left +after typing and erasing without rendering: + +› Ask Codex to do anything + + ? for shortcuts 100% context left diff --git a/codex-rs/tui/src/bottom_pane/chat_composer/snapshots/codex_tui__bottom_pane__chat_composer__sparkle__tests__history_search_acceptance_and_cancellation_update_sparkles_before_rendering.snap b/codex-rs/tui/src/bottom_pane/chat_composer/snapshots/codex_tui__bottom_pane__chat_composer__sparkle__tests__history_search_acceptance_and_cancellation_update_sparkles_before_rendering.snap new file mode 100644 index 0000000000..a671d9f4ad --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/chat_composer/snapshots/codex_tui__bottom_pane__chat_composer__sparkle__tests__history_search_acceptance_and_cancellation_update_sparkles_before_rendering.snap @@ -0,0 +1,15 @@ +--- +source: tui/src/bottom_pane/chat_composer/sparkle_tests.rs +expression: "snapshots.join(\"\\n\\n\")" +--- +accept: + +› Ask Codex to do anything + + ? for shortcuts 100% context left + +escape: + ⠈ ⢀ ⠁ ⠂ +›⠁Ask Codex to do anything ⠈ ⠁ + ⢀ ⠠ ⠄ ⠠ ⢀ ⠠ ⡀ + ? for shortcuts 100% context left diff --git a/codex-rs/tui/src/bottom_pane/chat_composer/snapshots/codex_tui__bottom_pane__chat_composer__sparkle__tests__history_search_preserves_a_held_sparkle_command_without_reclassifying_it.snap b/codex-rs/tui/src/bottom_pane/chat_composer/snapshots/codex_tui__bottom_pane__chat_composer__sparkle__tests__history_search_preserves_a_held_sparkle_command_without_reclassifying_it.snap new file mode 100644 index 0000000000..80bcb14f70 --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/chat_composer/snapshots/codex_tui__bottom_pane__chat_composer__sparkle__tests__history_search_preserves_a_held_sparkle_command_without_reclassifying_it.snap @@ -0,0 +1,37 @@ +--- +source: tui/src/bottom_pane/chat_composer/sparkle_tests.rs +expression: "snapshots.join(\"\\n\\n\")" +--- +gpt-6-astra +searching with an explicit pasted query: + +› history prompt + + reverse-i-search: history enter accept · esc cancel +after canceling and erasing the slash: + ⠁ ⡀ ⠄ ⠄ ⠄ +› Ask Codex to do anything ⠈ + ⠠ ⠠ ⢀ ⢀ ⡀ ⠄ + ? for shortcuts 100% context left +after /model selects Astra: + ⠁ ⡀ ⠄ ⠄ ⠄ +› Ask Codex to do anything ⠈ + ⠠ ⠠ ⢀ ⢀ ⡀ ⠄ + ? for shortcuts 100% context left + +gpt-5.5 +searching with an explicit pasted query: + +› history prompt + + reverse-i-search: history enter accept · esc cancel +after canceling and erasing the slash: + +› Ask Codex to do anything + + ? for shortcuts 100% context left +after /model selects Astra: + ⠈ ⢀ ⠁ ⠂ +›⠁Ask Codex to do anything ⠈ ⠁ + ⢀ ⠠ ⠄ ⠠ ⢀ ⠠ ⡀ + ? for shortcuts 100% context left diff --git a/codex-rs/tui/src/bottom_pane/chat_composer/snapshots/codex_tui__bottom_pane__chat_composer__sparkle__tests__review_regression_canceling_a_held_slash_restores_sparkle_command_tracking.snap b/codex-rs/tui/src/bottom_pane/chat_composer/snapshots/codex_tui__bottom_pane__chat_composer__sparkle__tests__review_regression_canceling_a_held_slash_restores_sparkle_command_tracking.snap new file mode 100644 index 0000000000..0301676391 --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/chat_composer/snapshots/codex_tui__bottom_pane__chat_composer__sparkle__tests__review_regression_canceling_a_held_slash_restores_sparkle_command_tracking.snap @@ -0,0 +1,27 @@ +--- +source: tui/src/bottom_pane/chat_composer/sparkle_tests.rs +expression: "snapshots.join(\"\\n\\n\")" +--- +gpt-6-astra +after immediately canceling the held slash: + ⠈ ⢀ ⠁ ⠂ +›⠁Ask Codex to do anything ⠈ ⠁ + ⢀ ⠠ ⠄ ⠠ ⢀ ⠠ ⡀ + ? for shortcuts 100% context left +after /model: + ⠈ ⢀ ⠁ ⠂ +›⠁Ask Codex to do anything ⠈ ⠁ + ⢀ ⠠ ⠄ ⠠ ⢀ ⠠ ⡀ + ? for shortcuts 100% context left + +gpt-5.5 +after immediately canceling the held slash: + +› Ask Codex to do anything + + ? for shortcuts 100% context left +after /model: + ⠈ ⢀ ⠁ ⠂ +›⠁Ask Codex to do anything ⠈ ⠁ + ⢀ ⠠ ⠄ ⠠ ⢀ ⠠ ⡀ + ? for shortcuts 100% context left diff --git a/codex-rs/tui/src/bottom_pane/chat_composer/snapshots/codex_tui__bottom_pane__chat_composer__sparkle__tests__shortcut_help_hides_visible_sparkles_without_restarting_their_deadline.snap b/codex-rs/tui/src/bottom_pane/chat_composer/snapshots/codex_tui__bottom_pane__chat_composer__sparkle__tests__shortcut_help_hides_visible_sparkles_without_restarting_their_deadline.snap new file mode 100644 index 0000000000..a9ac149b27 --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/chat_composer/snapshots/codex_tui__bottom_pane__chat_composer__sparkle__tests__shortcut_help_hides_visible_sparkles_without_restarting_their_deadline.snap @@ -0,0 +1,53 @@ +--- +source: tui/src/bottom_pane/chat_composer/sparkle_tests.rs +expression: "snapshots.join(\"\\n\\n\")" +--- +expires during help: false +initial: + ⠈ ⢀ ⠁ ⠂ +›⠁Ask Codex to do anything ⠈ ⠁ + ⢀ ⠠ ⠄ ⠠ ⢀ ⠠ ⡀ + ? for shortcuts 100% context left +shortcut help: + +› Ask Codex to do anything + + / for commands ! for shell commands + ctrl + j for newline tab to submit message + @ for file paths ctrl + v to paste images + ctrl + g to edit in external editor esc esc to edit previous message + ctrl + r search history ctrl + c to exit + ⌥ + , reasoning down ⌥ + . reasoning up + ctrl + t to view transcript + + customize shortcuts with /keymap +after closing: + ⠁ ⡀ ⠄ ⠄ ⠄ +› Ask Codex to do anything ⠈ + ⠠ ⠠ ⢀ ⢀ ⡀ ⠄ + ? for shortcuts 100% context left + +expires during help: true +initial: + ⠈ ⢀ ⠁ ⠂ +›⠁Ask Codex to do anything ⠈ ⠁ + ⢀ ⠠ ⠄ ⠠ ⢀ ⠠ ⡀ + ? for shortcuts 100% context left +shortcut help: + +› Ask Codex to do anything + + / for commands ! for shell commands + ctrl + j for newline tab to submit message + @ for file paths ctrl + v to paste images + ctrl + g to edit in external editor esc esc to edit previous message + ctrl + r search history ctrl + c to exit + ⌥ + , reasoning down ⌥ + . reasoning up + ctrl + t to view transcript + + customize shortcuts with /keymap +after closing: + +› Ask Codex to do anything + + ? for shortcuts 100% context left diff --git a/codex-rs/tui/src/bottom_pane/chat_composer/snapshots/codex_tui__bottom_pane__chat_composer__sparkle__tests__shortcut_help_preserves_an_unused_sparkle_but_literal_question_marks_do_not.snap b/codex-rs/tui/src/bottom_pane/chat_composer/snapshots/codex_tui__bottom_pane__chat_composer__sparkle__tests__shortcut_help_preserves_an_unused_sparkle_but_literal_question_marks_do_not.snap new file mode 100644 index 0000000000..69f211f7e9 --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/chat_composer/snapshots/codex_tui__bottom_pane__chat_composer__sparkle__tests__shortcut_help_preserves_an_unused_sparkle_but_literal_question_marks_do_not.snap @@ -0,0 +1,35 @@ +--- +source: tui/src/bottom_pane/chat_composer/sparkle_tests.rs +expression: "snapshots.join(\"\\n\\n\")" +--- +shortcut help: + +› Ask Codex to do anything + + / for commands ! for shell commands + ctrl + j for newline tab to submit message + @ for file paths ctrl + v to paste images + ctrl + g to edit in external editor esc esc to edit previous message + ctrl + r search history ctrl + c to exit + ⌥ + , reasoning down ⌥ + . reasoning up + ctrl + t to view transcript + + customize shortcuts with /keymap + +after /model selects Astra: + ⠈ ⢀ ⠁ ⠂ +›⠁Ask Codex to do anything ⠈ ⠁ + ⢀ ⠠ ⠄ ⠠ ⢀ ⠠ ⡀ + ? for shortcuts 100% context left + +literal pasted question mark: + +› ? + + 100% context left + +after clearing and selecting Astra: + +› Ask Codex to do anything + + ? for shortcuts 100% context left diff --git a/codex-rs/tui/src/bottom_pane/chat_composer/snapshots/codex_tui__bottom_pane__chat_composer__sparkle__tests__sparkle_fades_without_adding_dots_and_finishes_by_fifteen_seconds.snap b/codex-rs/tui/src/bottom_pane/chat_composer/snapshots/codex_tui__bottom_pane__chat_composer__sparkle__tests__sparkle_fades_without_adding_dots_and_finishes_by_fifteen_seconds.snap new file mode 100644 index 0000000000..0cfba1ed13 --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/chat_composer/snapshots/codex_tui__bottom_pane__chat_composer__sparkle__tests__sparkle_fades_without_adding_dots_and_finishes_by_fifteen_seconds.snap @@ -0,0 +1,19 @@ +--- +source: tui/src/bottom_pane/chat_composer/sparkle_tests.rs +expression: "format!(\"before fade:\\n{}\\nfading:\\n{}\\nfinished:\\n{}\", text(&last),\ntext(&fading), text(&finished))" +--- +before fade: +⠁ ⠄ ⢀ ⠈ ⠁ ⡀ ⠂ ⠄ +› Ask Codex to do anything ⠈ ⠈ ⠂ ⠁ ⠂ + ⢀⠐ ⠄ ⠄ ⢀ ⠠ ⠄ + ? for shortcuts 100% context left +fading: +⠁ ⠄ ⢀ ⠈ ⠁ ⡀ ⠂ ⠄ +› Ask Codex to do anything ⠈ ⠈ ⠂ ⠁ + ⠐ ⠄ ⠄ ⢀ ⠠ ⠄ + ? for shortcuts 100% context left +finished: + +› Ask Codex to do anything + + ? for shortcuts 100% context left diff --git a/codex-rs/tui/src/bottom_pane/chat_composer/snapshots/codex_tui__bottom_pane__chat_composer__sparkle__tests__sparkle_matches_the_original_starfield_and_protects_the_placeholder_and_cursor.snap b/codex-rs/tui/src/bottom_pane/chat_composer/snapshots/codex_tui__bottom_pane__chat_composer__sparkle__tests__sparkle_matches_the_original_starfield_and_protects_the_placeholder_and_cursor.snap new file mode 100644 index 0000000000..9edbf115ee --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/chat_composer/snapshots/codex_tui__bottom_pane__chat_composer__sparkle__tests__sparkle_matches_the_original_starfield_and_protects_the_placeholder_and_cursor.snap @@ -0,0 +1,25 @@ +--- +source: tui/src/bottom_pane/chat_composer/sparkle_tests.rs +expression: "snapshots.join(\"\\n\\n\")" +--- +40 columns, cursor Some((2, 1)) + ⠈ ⢀ +›⠁Ask Codex to do anything ⠈ + ⢀ ⠠ ⠄ ⠠ + ? for shortcuts 100% context left +first input: + +› x + + 100% context left + +80 columns, cursor Some((2, 1)) + ⠈ ⢀ ⠁ ⠂ +›⠁Ask Codex to do anything ⠈ ⠁ + ⢀ ⠠ ⠄ ⠠ ⢀ ⠠ ⡀ + ? for shortcuts 100% context left +first input: + +› x + + 100% context left diff --git a/codex-rs/tui/src/bottom_pane/chat_composer/sparkle.rs b/codex-rs/tui/src/bottom_pane/chat_composer/sparkle.rs new file mode 100644 index 0000000000..6e365938a3 --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/chat_composer/sparkle.rs @@ -0,0 +1,426 @@ +//! One short Astra flourish for a confirmed new task with an untouched prompt. +//! +//! Ordinary draft content ends the opportunity permanently; slash commands can still select Astra +//! if the flourish has never started. The original field fills blank composer cells without drawing +//! over the placeholder or normal terminal cursor, and hidden frames do not schedule work. The +//! separate field renderer only paints its buffer and has no input or scheduling state. History +//! search hides an active field while its original deadline continues; its query and previews do +//! not count as input before acceptance. Shortcut help on an empty composer also hides an active +//! field without restarting its deadline and leaves an unused opportunity intact. The disconnected +//! editor shares draft tracking but treats composer-only shortcuts as ordinary editor input. A key +//! that finishes a paste burst reconciles the draft even if it removes a held slash in the same edit. + +use std::cell::Cell; +use std::cell::RefCell; +use std::time::Duration; +use std::time::Instant; + +use codex_config::types::Tui; +use crossterm::event::KeyCode; +use crossterm::event::KeyEvent; +use crossterm::event::KeyModifiers; +use ratatui::buffer::Buffer; +use ratatui::layout::Rect; +use unicode_width::UnicodeWidthStr; + +use super::ChatComposer; +use super::FooterMode; +use super::InputResult; +use crate::bottom_pane::BottomPane; +use crate::terminal_palette::StdoutColorLevel; +use crate::terminal_palette::default_fg; +use crate::terminal_palette::effective_stdout_color_level; + +#[path = "sparkle_field.rs"] +mod field; + +const FRAME_TICK: Duration = Duration::from_millis(/*millis*/ 150); +const IDLE_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 15); +const IDLE_FADE: Duration = Duration::from_secs(/*secs*/ 1); + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) enum SparkleDraft { + #[default] + Untouched, + Command, + Dismissed, +} + +#[derive(Clone, Copy, Default, PartialEq, Eq)] +enum Phase { + #[default] + Unarmed, + Waiting, + Visible(Instant), + Finished, +} + +pub(super) struct SparkleEditorState { + text: String, + paste_burst_active: bool, +} + +pub(super) struct Sparkle { + pub(super) draft: Cell, + /// Scoped to history's own replacements; other draft changes still count while search is open. + pub(super) history_preview: bool, + command_input: RefCell, + phase: Cell, + fresh: bool, + terminal_focused: bool, +} + +impl Default for Sparkle { + fn default() -> Self { + Self { + draft: Cell::new(SparkleDraft::Untouched), + history_preview: false, + command_input: RefCell::new(String::new()), + phase: Cell::new(Phase::Unarmed), + fresh: false, + terminal_focused: true, + } + } +} + +impl BottomPane { + pub(crate) fn is_sparkle_model(model: &str) -> bool { + model + .split(|ch: char| !ch.is_alphanumeric() && ch != '_') + .any(|part| part.eq_ignore_ascii_case("astra")) + } + + pub(crate) fn mark_fresh_task_for_sparkle(&mut self, model: &str, settings: &Tui) { + self.composer.sparkle.fresh = true; + if matches!( + self.composer.sparkle.draft.get(), + SparkleDraft::Untouched | SparkleDraft::Command + ) && self.composer.sparkle.phase.get() == Phase::Unarmed + && settings.animations + && settings.whimsy + && Self::is_sparkle_model(model) + { + self.composer.sparkle.phase.set(Phase::Waiting); + self.request_redraw(); + } + } + + pub(crate) fn select_sparkle_model(&mut self, model: &str, settings: &Tui) { + if self.composer.sparkle.fresh { + self.mark_fresh_task_for_sparkle(model, settings); + } + } + + pub(crate) fn stop_ineligible_sparkle(&self, model: &str, settings: &Tui) { + if !settings.animations || !settings.whimsy || !Self::is_sparkle_model(model) { + self.composer.stop_visible_sparkle(); + } + } + + pub(crate) fn dismiss_composer_sparkle(&self) { + self.composer.dismiss_sparkle(); + } + + pub(crate) fn prepare_composer_sparkle_key(&self, key: KeyEvent) { + if !self.has_active_view() { + self.composer.prepare_sparkle_key(key); + } + } + + pub(crate) fn inherit_startup_sparkle(&self, draft: SparkleDraft) { + if self.composer.sparkle.draft.get() == SparkleDraft::Untouched + && draft != SparkleDraft::Untouched + { + self.composer.sparkle.draft.set(draft); + if draft == SparkleDraft::Dismissed { + self.composer.stop_visible_sparkle(); + } + } + } + + pub(crate) fn set_sparkle_terminal_focus(&mut self, focused: bool) { + if self.composer.sparkle.terminal_focused != focused { + self.composer.sparkle.terminal_focused = focused; + self.request_redraw(); + } + } +} + +impl ChatComposer { + fn prepare_sparkle_key(&self, key: KeyEvent) { + if self.sparkle.draft.get() != SparkleDraft::Command + && !(key.code == KeyCode::Char('/') + && crate::key_hint::is_plain_text_key_event(key) + && self.is_empty() + && self.slash_commands_enabled()) + { + self.stop_visible_sparkle(); + } + } + + fn stop_visible_sparkle(&self) { + if matches!(self.sparkle.phase.get(), Phase::Waiting | Phase::Visible(_)) { + self.sparkle.phase.set(Phase::Finished); + if let Some(requester) = &self.frame_requester { + requester.schedule_frame(); + } + } + } + + pub(super) fn dismiss_sparkle(&self) { + self.sparkle.draft.set(SparkleDraft::Dismissed); + self.sparkle.command_input.borrow_mut().clear(); + self.stop_visible_sparkle(); + } + + pub(super) fn before_sparkle_key(&self, key: KeyEvent) -> Option { + if self.history_search.is_some() + || (Self::is_history_search_key(&key, &self.history_search_previous_keys) + && (self.popups.active() || !self.draft.textarea.wants_vim_search_key(key)) + && !self.wants_vim_history_key(key)) + || self.empty_prompt_shortcut_toggle(&key).is_some() + { + return None; + } + self.before_sparkle_editor_key(key) + } + + pub(super) fn before_sparkle_editor_key(&self, key: KeyEvent) -> Option { + self.prepare_sparkle_key(key); + if self.draft.textarea.vim_query().is_some() { + return None; + } + if let KeyCode::Char(ch) = key.code + && crate::key_hint::is_plain_text_key_event(key) + && !key + .modifiers + .intersects(KeyModifiers::SUPER | KeyModifiers::HYPER | KeyModifiers::META) + && !self.draft.textarea.is_vim_normal_mode() + { + match self.sparkle.draft.get() { + SparkleDraft::Untouched + if ch == '/' && self.is_empty() && self.slash_commands_enabled() => + { + self.sparkle.draft.set(SparkleDraft::Command); + self.sparkle.command_input.replace(ch.to_string()); + } + SparkleDraft::Command => { + let actual = self.current_text(); + let mut projected = self.sparkle.command_input.borrow().clone(); + let cursor = if actual == projected { + self.current_cursor() + } else { + projected.len() + }; + projected.insert(cursor, ch); + if self.is_sparkle_command(&projected) { + self.sparkle.command_input.replace(projected); + } else { + self.dismiss_sparkle(); + } + } + SparkleDraft::Untouched => self.dismiss_sparkle(), + SparkleDraft::Dismissed => {} + } + None + } else { + Some(SparkleEditorState { + text: self.current_text(), + paste_burst_active: self.is_in_paste_burst(), + }) + } + } + + pub(super) fn after_sparkle_key( + &self, + before: Option, + result: &InputResult, + ) { + match result { + InputResult::Command(_) | InputResult::ServiceTierCommand(_) => { + if self.sparkle.draft.get() == SparkleDraft::Command { + self.sparkle.draft.set(SparkleDraft::Untouched); + self.sparkle.command_input.borrow_mut().clear(); + } + } + InputResult::Submitted { .. } + | InputResult::Queued { .. } + | InputResult::ParentOwnedInputBlocked => self.dismiss_sparkle(), + InputResult::CommandWithArgs(_, _, _) | InputResult::None => { + if self.history_search.is_none() && self.draft.textarea.vim_query().is_none() { + let draft = self.current_text(); + if before.is_some_and(|before| { + before.text != draft + || (before.paste_burst_active && !self.is_in_paste_burst()) + }) { + self.note_sparkle_replaced_text(&draft); + } + } + } + } + } + + pub(super) fn note_sparkle_paste(&self, text: &str) { + if self.history_search.is_some() { + return; + } + if self.sparkle.draft.get() != SparkleDraft::Command + && !(self.is_empty() && self.is_sparkle_command(text)) + { + self.stop_visible_sparkle(); + } + if !text.is_empty() && self.draft.textarea.vim_query().is_none() { + match self.sparkle.draft.get() { + SparkleDraft::Untouched if self.is_empty() && self.is_sparkle_command(text) => { + self.sparkle.draft.set(SparkleDraft::Command); + self.sparkle.command_input.replace(text.to_string()); + } + SparkleDraft::Command => { + let mut projected = self.sparkle.command_input.borrow().clone(); + let actual = self.current_text(); + let cursor = if actual == projected { + self.current_cursor() + } else { + projected.len() + }; + projected.insert_str(cursor, text); + if self.is_sparkle_command(&projected) { + self.sparkle.command_input.replace(projected); + } else { + self.dismiss_sparkle(); + } + } + SparkleDraft::Untouched => self.dismiss_sparkle(), + SparkleDraft::Dismissed => {} + } + } + } + + pub(super) fn note_sparkle_replaced_text(&self, text: &str) { + match self.sparkle.draft.get() { + SparkleDraft::Command if text.is_empty() => { + self.sparkle.draft.set(SparkleDraft::Untouched); + self.sparkle.command_input.borrow_mut().clear(); + } + SparkleDraft::Command if self.is_sparkle_command(text) => { + self.sparkle.command_input.replace(text.to_string()); + } + SparkleDraft::Untouched if text.is_empty() => {} + SparkleDraft::Untouched | SparkleDraft::Command => self.dismiss_sparkle(), + SparkleDraft::Dismissed => {} + } + } + + fn is_sparkle_command(&self, text: &str) -> bool { + let Some(body) = text.strip_prefix('/') else { + return false; + }; + if !self.slash_commands_enabled() || self.draft.is_bash_mode || text.contains(['\n', '\r']) + { + return false; + } + let split = body.find(char::is_whitespace).unwrap_or(body.len()); + let (name, rest) = body.split_at(split); + if rest.is_empty() { + self.slash_input().is_editing_command_name(text, text.len()) + || self.slash_input().command(name).is_some() + } else { + self.slash_input() + .command(name) + .is_some_and(|command| rest.trim().is_empty() || command.supports_inline_args()) + } + } + + pub(super) fn render_sparkle( + &self, + area: Rect, + textarea: Rect, + cursor: Option<(u16, u16)>, + buf: &mut Buffer, + ) { + self.render_sparkle_at(area, textarea, cursor, Instant::now(), buf); + } + + fn render_sparkle_at( + &self, + area: Rect, + textarea: Rect, + cursor: Option<(u16, u16)>, + now: Instant, + buf: &mut Buffer, + ) { + if self.history_search.is_none() + && self.draft.textarea.vim_query().is_none() + && !self.is_empty() + { + let is_command = self.sparkle.draft.get() == SparkleDraft::Command + && self.is_sparkle_command(&self.current_text()) + && self.attachments.is_empty(); + if !is_command { + self.dismiss_sparkle(); + } + } + let since = match self.sparkle.phase.get() { + Phase::Visible(since) => Some(since), + Phase::Waiting => None, + Phase::Unarmed | Phase::Finished => return, + }; + let elapsed = since.map_or(Duration::ZERO, |since| now.saturating_duration_since(since)); + if elapsed >= IDLE_TIMEOUT { + self.stop_visible_sparkle(); + return; + } + if !self.has_focus + || !self.sparkle.terminal_focused + || !self.is_empty() + || self.sparkle.draft.get() == SparkleDraft::Command + || self.draft.paste_burst.is_active() + || !self.draft.input_enabled + || self.is_task_running + || self.voice_strip.is_some() + || self.popup_active() + || self.footer_mode() == FooterMode::ShortcutOverlay + || area.height < 3 + || textarea.is_empty() + || effective_stdout_color_level() != StdoutColorLevel::TrueColor + { + return; + } + let Some(foreground) = default_fg() else { + return; + }; + if since.is_none() { + self.sparkle.phase.set(Phase::Visible(now)); + } + let fade_start = IDLE_TIMEOUT - IDLE_FADE; + let visibility = if elapsed > fade_start { + (IDLE_TIMEOUT - elapsed).as_secs_f32() / IDLE_FADE.as_secs_f32() + } else { + 1.0 + }; + let protected = Rect::new( + textarea.x, + textarea.y, + self.placeholder_text + .width() + .min(usize::from(textarea.width)) as u16, + /*height*/ 1, + ); + field::render_stars( + area, + cursor, + Some(protected), + elapsed.min(fade_start), + foreground, + visibility, + buf, + ); + if let Some(requester) = &self.frame_requester { + requester.schedule_frame_in(FRAME_TICK.min(IDLE_TIMEOUT - elapsed)); + } + } +} + +#[cfg(test)] +#[path = "sparkle_tests.rs"] +mod tests; diff --git a/codex-rs/tui/src/bottom_pane/chat_composer/sparkle_field.rs b/codex-rs/tui/src/bottom_pane/chat_composer/sparkle_field.rs new file mode 100644 index 0000000000..7791cc0c0f --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/chat_composer/sparkle_field.rs @@ -0,0 +1,70 @@ +//! Paint the deterministic Astra starfield without owning its eligibility, timer, or redraws. +//! +//! Only blank, unstyled true-color cells outside protected content and the terminal cursor can be +//! decorated. The caller supplies elapsed time and visibility to preserve the original appearance. + +use std::time::Duration; + +use ratatui::buffer::Buffer; +use ratatui::buffer::CellDiffOption; +use ratatui::layout::Position; +use ratatui::layout::Rect; +use ratatui::style::Color; +use unicode_width::UnicodeWidthStr; + +use crate::color::blend; +use crate::terminal_palette::rgb_color; + +pub(super) const DOTS: [&str; 8] = ["⠁", "⠂", "⠄", "⠈", "⠐", "⠠", "⡀", "⢀"]; + +pub(super) fn render_stars( + area: Rect, + cursor: Option<(u16, u16)>, + protected_area: Option, + elapsed: Duration, + foreground: (u8, u8, u8), + visibility: f32, + buf: &mut Buffer, +) { + let time = elapsed.as_secs_f32(); + for y in area.y..area.bottom() { + let mut occupied_until = area.x; + for x in area.x..area.right() { + let cell = &buf[(x, y)]; + if x < occupied_until { + continue; + } + if cell.symbol() != " " { + occupied_until = x.saturating_add(cell.symbol().width() as u16); + continue; + } + if cursor == Some((x, y)) + || protected_area.is_some_and(|protected| protected.contains(Position::new(x, y))) + || !cell.modifier.is_empty() + || cell.diff_option != CellDiffOption::None + { + continue; + } + let Color::Rgb(r, g, b) = cell.bg else { + continue; + }; + let mut hash = u64::from(y - area.y) * 65537 + u64::from(x - area.x); + hash = (hash ^ (hash >> 16)).wrapping_mul(/*rhs*/ 0x45d9f3b); + hash = (hash ^ (hash >> 16)).wrapping_mul(/*rhs*/ 0x45d9f3b); + hash ^= hash >> 16; + if hash % 5 != 0 { + continue; + } + let phase = + (time / (4.0 + (hash % 31) as f32 / 10.0) + (hash % 997) as f32 / 997.0).fract(); + let brightness = + (phase * std::f32::consts::PI).sin().powi(/*n*/ 12) * 0.55 * visibility; + if brightness < 0.04 { + continue; + } + buf[(x, y)] + .set_symbol(DOTS[(hash / 161 % 8) as usize]) + .set_fg(rgb_color(blend(foreground, (r, g, b), brightness))); + } + } +} diff --git a/codex-rs/tui/src/bottom_pane/chat_composer/sparkle_tests.rs b/codex-rs/tui/src/bottom_pane/chat_composer/sparkle_tests.rs new file mode 100644 index 0000000000..9ba12a09d8 --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/chat_composer/sparkle_tests.rs @@ -0,0 +1,1073 @@ +//! Covers the original starfield appearance, protected content, and composer eligibility. + +use super::*; +use crate::app_event_sender::AppEventSender; +use crate::bottom_pane::BottomPaneParams; +use crate::bottom_pane::chat_composer_history::HistoryEntry; +use crate::render::renderable::Renderable; +use crate::slash_command::SlashCommand; +use crate::terminal_palette::with_test_default_colors; +use crate::terminal_probe::DefaultColors; +use crate::tui::FrameRequester; +use pretty_assertions::assert_eq; +use ratatui::layout::Position; +use ratatui::style::Color; + +use super::field::DOTS; + +fn pane() -> BottomPane { + let (tx, _rx) = tokio::sync::mpsc::unbounded_channel(); + BottomPane::new(BottomPaneParams { + app_event_tx: AppEventSender::new(tx), + frame_requester: FrameRequester::test_dummy(), + has_input_focus: true, + enhanced_keys_supported: false, + placeholder_text: "Ask Codex to do anything".into(), + disable_paste_burst: true, + animations_enabled: true, + skills: None, + }) +} + +fn palette(render: impl FnOnce() -> T) -> T { + with_test_default_colors( + DefaultColors { + fg: (230, 216, 255), + bg: (36, 27, 53), + }, + render, + ) +} + +fn enabled() -> Tui { + Tui { + animations: true, + whimsy: true, + ..Tui::default() + } +} + +fn draw(composer: &ChatComposer, width: u16, now: Instant) -> (Buffer, Rect) { + let area = Rect::new( + /*x*/ 0, + /*y*/ 0, + width, + composer.desired_height(width), + ); + let [padding, _, textarea, _] = + composer.layout_areas_with_textarea_right_reserve(area, /*textarea_right_reserve*/ 0); + let phase = composer.sparkle.phase.replace(Phase::Unarmed); + let mut buffer = Buffer::empty(area); + composer.render(area, &mut buffer); + composer.sparkle.phase.set(phase); + composer.render_sparkle_at( + padding, + textarea, + composer.cursor_pos(area), + now, + &mut buffer, + ); + (buffer, textarea) +} + +fn text(buffer: &Buffer) -> String { + buffer + .content + .chunks(usize::from(buffer.area.width)) + .map(|row| { + row.iter() + .map(ratatui::buffer::Cell::symbol) + .collect::() + .trim_end() + .to_string() + }) + .collect::>() + .join("\n") +} + +fn dots(buffer: &Buffer) -> Vec<(u16, u16, String)> { + buffer + .content + .iter() + .enumerate() + .filter(|&(_, cell)| DOTS.contains(&cell.symbol())) + .map(|(index, cell)| { + let (x, y) = buffer.pos_of(index); + (x, y, cell.symbol().to_string()) + }) + .collect() +} + +fn key(pane: &mut BottomPane, key: KeyCode) -> InputResult { + pane.handle_key_event(KeyEvent::new(key, KeyModifiers::NONE)) +} + +fn type_text(pane: &mut BottomPane, text: &str) { + for ch in text.chars() { + key(pane, KeyCode::Char(ch)); + } +} + +#[test] +fn sparkle_matches_the_original_starfield_and_protects_the_placeholder_and_cursor() { + palette(|| { + let now = Instant::now(); + let mut snapshots = Vec::new(); + for width in [40, 80] { + let mut pane = pane(); + let (plain, _) = draw(&pane.composer, width, now); + let cursor = pane.composer.cursor_pos(plain.area); + pane.mark_fresh_task_for_sparkle("gpt-6-astra", &enabled()); + let (active, textarea) = draw(&pane.composer, width, now); + assert_eq!(pane.composer.cursor_pos(active.area), cursor); + let (later, _) = draw(&pane.composer, width, now + Duration::from_secs(/*secs*/ 2)); + let protected = Rect::new( + textarea.x, + textarea.y, + pane.composer.placeholder_text.width() as u16, + /*height*/ 1, + ); + let placeholder = |buffer: &Buffer| { + (protected.x..protected.right()) + .map(|x| buffer[(x, protected.y)].symbol()) + .collect::() + }; + assert_eq!(placeholder(&active), placeholder(&plain)); + assert_eq!(placeholder(&later), placeholder(&plain)); + assert!( + dots(&active) + .iter() + .chain(dots(&later).iter()) + .all(|(x, y, _)| !protected.contains(Position::new(*x, *y)) + && cursor != Some((*x, *y))) + ); + if width == 80 { + assert!(dots(&active).len() > 6); + assert!( + dots(&active) + .iter() + .chain(dots(&later).iter()) + .any(|(x, y, _)| *y == textarea.y && *x >= protected.right()) + ); + } + let (typed, _) = { + key(&mut pane, KeyCode::Char('x')); + draw(&pane.composer, width, now) + }; + assert_eq!( + pane.composer.cursor_pos(active.area), + cursor.map(|(x, y)| (x + 1, y)) + ); + assert!(!dots(&active).is_empty()); + assert!(dots(&typed).is_empty()); + snapshots.push(format!( + "{width} columns, cursor {cursor:?}\n{}\nfirst input:\n{}", + text(&active), + text(&typed) + )); + } + insta::assert_snapshot!(snapshots.join("\n\n")); + }); +} + +#[test] +fn sparkle_fades_without_adding_dots_and_finishes_by_fifteen_seconds() { + palette(|| { + let now = Instant::now(); + let mut pane = pane(); + pane.mark_fresh_task_for_sparkle("astra", &enabled()); + draw(&pane.composer, /*width*/ 80, now); + let (last, _) = draw( + &pane.composer, + /*width*/ 80, + now + IDLE_TIMEOUT - IDLE_FADE, + ); + let (fading, _) = draw( + &pane.composer, + /*width*/ 80, + now + Duration::from_millis(/*millis*/ 14_500), + ); + let (finished, _) = draw(&pane.composer, /*width*/ 80, now + IDLE_TIMEOUT); + assert!(!dots(&fading).is_empty()); + assert!(dots(&fading).iter().all(|dot| dots(&last).contains(dot))); + let contrast = |cell: &ratatui::buffer::Cell| match (cell.fg, cell.bg) { + (Color::Rgb(fr, fg, fb), Color::Rgb(br, bg, bb)) => { + u32::from(fr.abs_diff(br)) + u32::from(fg.abs_diff(bg)) + u32::from(fb.abs_diff(bb)) + } + colors => panic!("expected true color: {colors:?}"), + }; + for (x, y, _) in dots(&fading) { + assert!(contrast(&fading[(x, y)]) < contrast(&last[(x, y)])); + } + assert!(dots(&finished).is_empty()); + pane.select_sparkle_model("astra", &enabled()); + assert!( + dots( + &draw( + &pane.composer, + /*width*/ 80, + now + IDLE_TIMEOUT + IDLE_FADE + ) + .0 + ) + .is_empty() + ); + insta::assert_snapshot!(format!( + "before fade:\n{}\nfading:\n{}\nfinished:\n{}", + text(&last), + text(&fading), + text(&finished) + )); + }); +} + +#[test] +fn the_first_buffered_character_and_empty_escape_clear_visible_stars() { + palette(|| { + let now = Instant::now(); + for input in [ + KeyCode::Char('x'), + KeyCode::Char('?'), + KeyCode::Esc, + KeyCode::Left, + ] { + let mut pane = pane(); + pane.composer.set_disable_paste_burst(/*disabled*/ false); + pane.mark_fresh_task_for_sparkle("astra", &enabled()); + assert!(!dots(&draw(&pane.composer, /*width*/ 80, now).0).is_empty()); + key(&mut pane, input); + assert!(dots(&draw(&pane.composer, /*width*/ 80, now).0).is_empty()); + assert!(pane.composer.current_text().is_empty()); + assert_eq!( + pane.composer.sparkle.draft.get(), + if input == KeyCode::Char('x') { + SparkleDraft::Dismissed + } else { + SparkleDraft::Untouched + } + ); + } + }); +} + +#[test] +fn shortcut_help_preserves_an_unused_sparkle_but_literal_question_marks_do_not() { + palette(|| { + let now = Instant::now(); + let mut snapshots = Vec::new(); + for (scenario, input) in [ + ( + "unmodified", + KeyEvent::new(KeyCode::Char('?'), KeyModifiers::NONE), + ), + ( + "shifted", + KeyEvent::new(KeyCode::Char('?'), KeyModifiers::SHIFT), + ), + ( + "remapped", + KeyEvent::new(KeyCode::Char('q'), KeyModifiers::NONE), + ), + ( + "close", + KeyEvent::new(KeyCode::Char('?'), KeyModifiers::NONE), + ), + ] { + let mut pane = pane(); + if scenario == "remapped" { + pane.composer.toggle_shortcuts_keys = + vec![crate::key_hint::plain(KeyCode::Char('q'))]; + } + pane.mark_fresh_task_for_sparkle("gpt-5.5", &enabled()); + pane.handle_key_event(input); + if scenario == "close" { + pane.handle_key_event(input); + } + assert_eq!( + ( + pane.composer.footer.mode, + pane.composer.current_text(), + pane.composer.sparkle.draft.get() + ), + ( + if scenario == "close" { + super::super::FooterMode::ComposerEmpty + } else { + super::super::FooterMode::ShortcutOverlay + }, + String::new(), + SparkleDraft::Untouched + ), + "{scenario}" + ); + let help = draw(&pane.composer, /*width*/ 80, now).0; + assert!(dots(&help).is_empty()); + type_text(&mut pane, "/model"); + assert!(matches!( + key(&mut pane, KeyCode::Enter), + InputResult::Command(SlashCommand::Model) + )); + pane.select_sparkle_model("gpt-6-astra", &enabled()); + let selected = draw(&pane.composer, /*width*/ 80, now).0; + assert!(!dots(&selected).is_empty(), "{scenario}"); + if scenario == "unmodified" { + snapshots.push(format!( + "shortcut help:\n{}\n\nafter /model selects Astra:\n{}", + text(&help), + text(&selected) + )); + } + } + + for scenario in ["paste", "remapped literal", "quit reminder"] { + let mut pane = pane(); + pane.mark_fresh_task_for_sparkle("gpt-5.5", &enabled()); + if scenario == "paste" { + pane.handle_paste("?".into()); + } else { + if scenario == "remapped literal" { + pane.composer.toggle_shortcuts_keys = + vec![crate::key_hint::plain(KeyCode::Char('q'))]; + } else { + pane.composer.show_quit_shortcut_hint( + crate::key_hint::ctrl(KeyCode::Char('c')), + /*has_focus*/ true, + ); + } + key(&mut pane, KeyCode::Char('?')); + } + assert_eq!( + ( + pane.composer.current_text(), + pane.composer.sparkle.draft.get() + ), + ("?".into(), SparkleDraft::Dismissed), + "{scenario}" + ); + let literal = draw(&pane.composer, /*width*/ 80, now).0; + key(&mut pane, KeyCode::Backspace); + type_text(&mut pane, "/model"); + assert!(matches!( + key(&mut pane, KeyCode::Enter), + InputResult::Command(SlashCommand::Model) + )); + pane.select_sparkle_model("gpt-6-astra", &enabled()); + let selected = draw(&pane.composer, /*width*/ 80, now).0; + assert!(dots(&selected).is_empty(), "{scenario}"); + if scenario == "paste" { + snapshots.push(format!( + "literal pasted question mark:\n{}\n\nafter clearing and selecting Astra:\n{}", + text(&literal), + text(&selected) + )); + } + } + insta::assert_snapshot!(snapshots.join("\n\n")); + }); +} + +#[test] +fn shortcut_help_hides_visible_sparkles_without_restarting_their_deadline() { + palette(|| { + let started = Instant::now(); + let during = started + Duration::from_secs(/*secs*/ 4); + let expired = started + IDLE_TIMEOUT; + let mut snapshots = Vec::new(); + for (scenario, input) in [ + ( + "unmodified", + KeyEvent::new(KeyCode::Char('?'), KeyModifiers::NONE), + ), + ( + "shifted", + KeyEvent::new(KeyCode::Char('?'), KeyModifiers::SHIFT), + ), + ( + "remapped", + KeyEvent::new(KeyCode::Char('q'), KeyModifiers::NONE), + ), + ] { + for close_at in [during, expired] { + let mut pane = pane(); + if scenario == "remapped" { + pane.composer.toggle_shortcuts_keys = + vec![crate::key_hint::plain(KeyCode::Char('q'))]; + } + pane.mark_fresh_task_for_sparkle("gpt-6-astra", &enabled()); + let active = draw(&pane.composer, /*width*/ 80, started).0; + let expected = draw(&pane.composer, /*width*/ 80, during).0; + assert!(!dots(&active).is_empty()); + assert!(!dots(&expected).is_empty()); + pane.handle_key_event(input); + assert!( + matches!(pane.composer.sparkle.phase.get(), Phase::Visible(at) if at == started) + ); + assert_eq!(pane.composer.current_text(), ""); + let help = draw(&pane.composer, /*width*/ 80, during).0; + assert!(dots(&help).is_empty(), "{scenario}"); + if close_at == expired { + let still_open = draw(&pane.composer, /*width*/ 80, expired).0; + assert!(dots(&still_open).is_empty()); + assert!(pane.composer.sparkle.phase.get() == Phase::Finished); + } + pane.handle_key_event(input); + let closed = draw(&pane.composer, /*width*/ 80, close_at).0; + assert_eq!( + dots(&closed), + if close_at == expired { + Vec::new() + } else { + dots(&expected) + }, + "{scenario}" + ); + if scenario == "unmodified" { + snapshots.push(format!( + "expires during help: {}\ninitial:\n{}\nshortcut help:\n{}\nafter closing:\n{}", + close_at == expired, + text(&active), + text(&help), + text(&closed) + )); + } + } + } + + let mut waiting = pane(); + waiting.mark_fresh_task_for_sparkle("gpt-6-astra", &enabled()); + key(&mut waiting, KeyCode::Char('?')); + let help = draw(&waiting.composer, /*width*/ 80, expired).0; + assert!(dots(&help).is_empty()); + assert!(waiting.composer.sparkle.phase.get() == Phase::Waiting); + key(&mut waiting, KeyCode::Char('?')); + assert!(!dots(&draw(&waiting.composer, /*width*/ 80, expired).0).is_empty()); + + let mut literal = pane(); + literal.mark_fresh_task_for_sparkle("gpt-6-astra", &enabled()); + assert!(!dots(&draw(&literal.composer, /*width*/ 80, started).0).is_empty()); + literal.handle_paste("?".into()); + assert_eq!(literal.composer.current_text(), "?"); + key(&mut literal, KeyCode::Backspace); + assert!(dots(&draw(&literal.composer, /*width*/ 80, during).0).is_empty()); + insta::assert_snapshot!(snapshots.join("\n\n")); + }); +} + +#[test] +fn disconnected_sparkle_edits_are_tracked_between_renders() { + palette(|| { + let now = Instant::now(); + let mut snapshots = Vec::new(); + for model in ["gpt-6-astra", "gpt-5.5"] { + for (scenario, input, draft) in [ + ("ordinary", "x", SparkleDraft::Dismissed), + ("offline question mark", "?", SparkleDraft::Dismissed), + ("recognized command", "/status", SparkleDraft::Command), + ("unknown command", "/xyz", SparkleDraft::Dismissed), + ] { + let mut pane = pane(); + pane.mark_fresh_task_for_sparkle(model, &enabled()); + let initial = draw(&pane.composer, /*width*/ 80, now).0; + assert_eq!(dots(&initial).is_empty(), model == "gpt-5.5"); + for key in [KeyCode::Null, KeyCode::Enter, KeyCode::Tab] { + pane.handle_disconnected_key(KeyEvent::new(key, KeyModifiers::NONE)); + } + pane.handle_disconnected_key(KeyEvent::new_with_kind( + KeyCode::Char('x'), + KeyModifiers::NONE, + crossterm::event::KeyEventKind::Release, + )); + assert_eq!(pane.composer.sparkle.draft.get(), SparkleDraft::Untouched); + assert_eq!( + dots(&draw(&pane.composer, /*width*/ 80, now).0), + dots(&initial) + ); + for ch in input.chars() { + pane.handle_disconnected_key(KeyEvent::new( + KeyCode::Char(ch), + KeyModifiers::NONE, + )); + } + assert_eq!(pane.composer.current_text(), input, "{scenario}"); + assert_eq!(pane.composer.sparkle.draft.get(), draft, "{scenario}"); + for _ in input.chars() { + pane.handle_disconnected_key(KeyEvent::new( + KeyCode::Backspace, + KeyModifiers::NONE, + )); + } + assert_eq!(pane.composer.current_text(), ""); + pane.select_sparkle_model("gpt-6-astra", &enabled()); + let after = draw(&pane.composer, /*width*/ 80, now).0; + assert_eq!( + dots(&after).is_empty(), + draft == SparkleDraft::Dismissed, + "{scenario}" + ); + if scenario == "ordinary" { + snapshots.push(format!( + "{model}\nbefore disconnect:\n{}\nafter typing and erasing without rendering:\n{}", + text(&initial), + text(&after) + )); + } + } + } + insta::assert_snapshot!(snapshots.join("\n\n")); + }); +} + +#[test] +fn a_fresh_astra_response_waits_for_the_pending_command_to_leave() { + palette(|| { + let now = Instant::now(); + for completion in ["submit", "erase", "draft"] { + let mut pane = pane(); + type_text(&mut pane, "/status"); + pane.mark_fresh_task_for_sparkle("astra", &enabled()); + let pending = draw(&pane.composer, /*width*/ 80, now).0; + assert!(dots(&pending).is_empty()); + + match completion { + "submit" => assert!(matches!( + key(&mut pane, KeyCode::Enter), + InputResult::Command(SlashCommand::Status) + )), + "erase" => { + for _ in "/status".chars() { + key(&mut pane, KeyCode::Backspace); + } + } + "draft" => { + type_text(&mut pane, "-draft"); + pane.composer + .set_text_content(String::new(), Vec::new(), Vec::new()); + } + _ => unreachable!(), + } + let completed = draw(&pane.composer, /*width*/ 80, now).0; + assert_eq!( + dots(&completed).is_empty(), + completion == "draft", + "{completion}" + ); + if completion == "submit" { + insta::assert_snapshot!(format!( + "command during startup:\n{}\n\nafter command:\n{}", + text(&pending), + text(&completed) + )); + } + } + }); +} + +#[test] +fn an_attachment_ends_the_sparkle_even_after_the_composer_is_cleared() { + palette(|| { + let now = Instant::now(); + let mut pane = pane(); + pane.mark_fresh_task_for_sparkle("astra", &enabled()); + assert!(!dots(&draw(&pane.composer, /*width*/ 80, now).0).is_empty()); + pane.attach_image(crate::test_support::test_path_buf("/tmp/image.png")); + assert!(!pane.composer.is_empty()); + assert!(dots(&draw(&pane.composer, /*width*/ 80, now).0).is_empty()); + pane.on_ctrl_c(); + assert!(pane.composer.is_empty()); + pane.select_sparkle_model("astra", &enabled()); + assert!(dots(&draw(&pane.composer, /*width*/ 80, now).0).is_empty()); + }); +} + +#[test] +fn history_search_acceptance_and_cancellation_update_sparkles_before_rendering() { + palette(|| { + let now = Instant::now(); + let mut snapshots = Vec::new(); + for (entry, query) in [("git status", "git"), ("/status", "status")] { + for completion in ["accept", "escape", "control-c"] { + let mut pane = pane(); + pane.mark_fresh_task_for_sparkle("gpt-5.5", &enabled()); + pane.composer + .history + .record_local_submission(HistoryEntry::new(entry.into())); + pane.handle_key_event(KeyEvent::new(KeyCode::Char('r'), KeyModifiers::CONTROL)); + type_text(&mut pane, query); + assert!(pane.composer.history_search_active()); + assert_eq!(pane.composer.current_text(), entry); + assert_eq!(pane.composer.sparkle.draft.get(), SparkleDraft::Untouched); + + match completion { + "accept" => { + key(&mut pane, KeyCode::Enter); + assert_eq!(pane.composer.sparkle.draft.get(), SparkleDraft::Dismissed); + pane.on_ctrl_c(); + } + "escape" => { + key(&mut pane, KeyCode::Esc); + } + "control-c" => { + pane.on_ctrl_c(); + } + _ => unreachable!(), + } + assert!(!pane.composer.history_search_active()); + assert!(pane.composer.is_empty()); + pane.select_sparkle_model("astra", &enabled()); + let buffer = draw(&pane.composer, /*width*/ 80, now).0; + assert_eq!(dots(&buffer).is_empty(), completion == "accept"); + if entry == "git status" && completion != "control-c" { + snapshots.push(format!("{completion}:\n{}", text(&buffer))); + } + } + } + insta::assert_snapshot!(snapshots.join("\n\n")); + }); +} + +#[test] +fn canceled_history_search_restores_visible_stars_only_before_the_original_deadline() { + palette(|| { + let started = Instant::now(); + let during = started + Duration::from_secs(/*secs*/ 4); + let expired = started + IDLE_TIMEOUT; + let mut snapshots = Vec::new(); + for (cancel, expires_while_open) in [ + ("escape", false), + ("control-c", false), + ("escape", true), + ("accept", false), + ] { + let mut pane = pane(); + pane.mark_fresh_task_for_sparkle("gpt-6-astra", &enabled()); + pane.composer + .history + .record_local_submission(HistoryEntry::new("stored draft".into())); + let active = draw(&pane.composer, /*width*/ 80, started).0; + let expected = draw(&pane.composer, /*width*/ 80, during).0; + assert!(!dots(&active).is_empty()); + pane.handle_key_event(KeyEvent::new(KeyCode::Char('r'), KeyModifiers::CONTROL)); + type_text(&mut pane, "st"); + pane.handle_paste("ored".into()); + assert_eq!(pane.composer.current_text(), "stored draft"); + assert!(pane.composer.sparkle.phase.get() == Phase::Visible(started)); + let searching = draw(&pane.composer, /*width*/ 80, during).0; + assert!(dots(&searching).is_empty()); + if expires_while_open { + assert!(dots(&draw(&pane.composer, /*width*/ 80, expired).0).is_empty()); + } + + if cancel == "escape" { + key(&mut pane, KeyCode::Esc); + } else if cancel == "accept" { + key(&mut pane, KeyCode::Enter); + } else { + pane.on_ctrl_c(); + } + assert_eq!(pane.composer.is_empty(), cancel != "accept"); + let at = if expires_while_open { expired } else { during }; + let restored = draw(&pane.composer, /*width*/ 80, at).0; + assert_eq!( + dots(&restored), + if expires_while_open || cancel == "accept" { + Vec::new() + } else { + dots(&expected) + }, + "{cancel}, expires while open: {expires_while_open}", + ); + if cancel == "escape" { + snapshots.push(format!( + "expires while open: {expires_while_open}\ninitial:\n{}\nsearching:\n{}\nafter escape:\n{}", + text(&active), + text(&searching), + text(&restored), + )); + } + } + insta::assert_snapshot!(snapshots.join("\n\n")); + }); +} + +#[test] +fn history_search_preserves_a_held_sparkle_command_without_reclassifying_it() { + palette(|| { + let now = Instant::now(); + let during = now + Duration::from_secs(/*secs*/ 4); + let mut snapshots = Vec::new(); + for model in ["gpt-6-astra", "gpt-5.5"] { + for cancel in ["escape", "control-c"] { + let mut pane = pane(); + pane.composer.set_disable_paste_burst(/*disabled*/ false); + pane.mark_fresh_task_for_sparkle(model, &enabled()); + pane.composer + .history + .record_local_submission(HistoryEntry::new("history prompt".into())); + let initial = draw(&pane.composer, /*width*/ 80, now).0; + let expected = draw(&pane.composer, /*width*/ 80, during).0; + assert_eq!(dots(&initial).is_empty(), model == "gpt-5.5"); + key(&mut pane, KeyCode::Char('/')); + assert!(pane.composer.is_in_paste_burst()); + assert_eq!(pane.composer.current_text(), ""); + assert_eq!(pane.composer.sparkle.draft.get(), SparkleDraft::Command); + pane.handle_key_event(KeyEvent::new(KeyCode::Char('r'), KeyModifiers::CONTROL)); + assert!(pane.composer.history_search_active()); + assert_eq!(pane.composer.current_text(), "/"); + assert_eq!(pane.composer.sparkle.draft.get(), SparkleDraft::Command); + pane.handle_paste("history".into()); + assert_eq!(pane.composer.current_text(), "history prompt"); + assert_eq!(pane.composer.sparkle.draft.get(), SparkleDraft::Command); + let searching = draw(&pane.composer, /*width*/ 80, during).0; + assert!(dots(&searching).is_empty()); + + if cancel == "escape" { + key(&mut pane, KeyCode::Esc); + } else { + pane.on_ctrl_c(); + } + assert_eq!(pane.composer.current_text(), "/"); + key(&mut pane, KeyCode::Backspace); + assert_eq!(pane.composer.sparkle.draft.get(), SparkleDraft::Untouched); + let erased = draw(&pane.composer, /*width*/ 80, during).0; + assert_eq!(dots(&erased), dots(&expected)); + type_text(&mut pane, "/model"); + pane.composer + .handle_paste_burst_flush(now + Duration::from_secs(/*secs*/ 1)); + assert!(matches!( + key(&mut pane, KeyCode::Enter), + InputResult::Command(SlashCommand::Model) + )); + pane.select_sparkle_model("gpt-6-astra", &enabled()); + let selected = draw(&pane.composer, /*width*/ 80, during).0; + assert!(!dots(&selected).is_empty()); + if cancel == "escape" { + snapshots.push(format!("{model}\nsearching with an explicit pasted query:\n{}\nafter canceling and erasing the slash:\n{}\nafter /model selects Astra:\n{}", text(&searching), text(&erased), text(&selected))); + } + } + } + insta::assert_snapshot!(snapshots.join("\n\n")); + }); +} + +#[test] +fn cancelling_history_search_preserves_a_typed_command_despite_attachment_previews() { + palette(|| { + let now = Instant::now(); + let mut pane = pane(); + pane.mark_fresh_task_for_sparkle("gpt-5.5", &enabled()); + type_text(&mut pane, "/status"); + let mut entry = HistoryEntry::new("history attachment".into()); + entry.local_image_paths = vec![crate::test_support::test_path_buf("/tmp/image.png")]; + entry.remote_image_urls = vec!["https://example.com/image.png".into()]; + pane.composer.history.record_local_submission(entry); + pane.handle_key_event(KeyEvent::new(KeyCode::Char('r'), KeyModifiers::CONTROL)); + type_text(&mut pane, "history"); + assert!(!pane.composer.local_image_paths().is_empty()); + assert!(!pane.composer.remote_image_urls().is_empty()); + assert_eq!(pane.composer.sparkle.draft.get(), SparkleDraft::Command); + key(&mut pane, KeyCode::Esc); + assert_eq!(pane.composer.current_text(), "/status"); + assert!(pane.composer.local_image_paths().is_empty()); + assert!(pane.composer.remote_image_urls().is_empty()); + assert!(matches!( + key(&mut pane, KeyCode::Enter), + InputResult::Command(SlashCommand::Status) + )); + pane.select_sparkle_model("astra", &enabled()); + assert!(!dots(&draw(&pane.composer, /*width*/ 80, now).0).is_empty()); + }); +} + +#[test] +fn replacing_a_draft_outside_the_history_preview_dismisses_sparkles_during_search() { + let mut pane = pane(); + pane.mark_fresh_task_for_sparkle("gpt-5.5", &enabled()); + pane.handle_key_event(KeyEvent::new(KeyCode::Char('r'), KeyModifiers::CONTROL)); + assert!(pane.composer.history_search_active()); + pane.composer + .set_text_content("external draft".into(), Vec::new(), Vec::new()); + assert_eq!(pane.composer.sparkle.draft.get(), SparkleDraft::Dismissed); + key(&mut pane, KeyCode::Esc); + assert!(pane.composer.is_empty()); + assert_eq!(pane.composer.sparkle.draft.get(), SparkleDraft::Dismissed); +} + +#[test] +fn arbitrary_commands_preserve_a_never_used_fresh_opportunity() { + palette(|| { + let now = Instant::now(); + for completion in [false, true] { + let mut pane = pane(); + pane.mark_fresh_task_for_sparkle("gpt-5.5", &enabled()); + assert!(dots(&draw(&pane.composer, /*width*/ 80, now).0).is_empty()); + for command in ["/status", "/diff", "/pwd"] { + type_text(&mut pane, command); + assert!(matches!( + key(&mut pane, KeyCode::Enter), + InputResult::Command(_) + )); + assert_eq!(pane.composer.sparkle.draft.get(), SparkleDraft::Untouched); + } + type_text(&mut pane, if completion { "/mo" } else { "/model" }); + if completion { + key(&mut pane, KeyCode::Tab); + } + assert!(matches!( + key(&mut pane, KeyCode::Enter), + InputResult::Command(SlashCommand::Model) + )); + assert_eq!(pane.composer.sparkle.draft.get(), SparkleDraft::Untouched); + pane.select_sparkle_model("gpt-6-astra", &enabled()); + assert!(!dots(&draw(&pane.composer, /*width*/ 80, now).0).is_empty()); + } + for input in ["hello", "/model extra", "/other", "漢", "/tmp/file"] { + let mut pane = pane(); + pane.mark_fresh_task_for_sparkle("gpt-5.5", &enabled()); + type_text(&mut pane, input); + pane.composer + .set_text_content(String::new(), Vec::new(), Vec::new()); + pane.select_sparkle_model("gpt-6-astra", &enabled()); + assert_eq!( + pane.composer.sparkle.draft.get(), + SparkleDraft::Dismissed, + "{input}" + ); + assert!( + dots(&draw(&pane.composer, /*width*/ 80, now).0).is_empty(), + "{input}" + ); + } + }); +} + +#[test] +fn canceled_commands_remain_eligible_but_inserted_content_and_ordinary_paste_do_not() { + palette(|| { + let now = Instant::now(); + let mut provisional = pane(); + type_text(&mut provisional, "x"); + key(&mut provisional, KeyCode::Backspace); + let snapshot = provisional.composer.draft_snapshot(); + assert!(snapshot.text.is_empty()); + let mut initialized = pane(); + initialized.mark_fresh_task_for_sparkle("astra", &enabled()); + initialized.inherit_startup_sparkle(snapshot.sparkle_draft); + assert!(dots(&draw(&initialized.composer, /*width*/ 80, now).0).is_empty()); + + let mut canceled = pane(); + canceled.mark_fresh_task_for_sparkle("gpt-5.5", &enabled()); + type_text(&mut canceled, "/sta"); + for _ in 0..4 { + key(&mut canceled, KeyCode::Backspace); + } + assert_eq!( + canceled.composer.sparkle.draft.get(), + SparkleDraft::Untouched + ); + canceled.select_sparkle_model("astra", &enabled()); + assert!(!dots(&draw(&canceled.composer, /*width*/ 80, now).0).is_empty()); + + for input in ["paste draft", "inserted"] { + let mut pane = pane(); + pane.mark_fresh_task_for_sparkle("gpt-5.5", &enabled()); + if input == "inserted" { + type_text(&mut pane, "/mention"); + assert!(matches!( + key(&mut pane, KeyCode::Enter), + InputResult::Command(SlashCommand::Mention) + )); + pane.composer.insert_str("@"); + } else { + pane.handle_paste(input.to_string()); + } + pane.composer + .set_text_content(String::new(), Vec::new(), Vec::new()); + pane.select_sparkle_model("astra", &enabled()); + assert_eq!(pane.composer.sparkle.draft.get(), SparkleDraft::Dismissed); + assert!(dots(&draw(&pane.composer, /*width*/ 80, now).0).is_empty()); + } + }); +} + +#[test] +fn review_regression_canceling_a_held_slash_restores_sparkle_command_tracking() { + palette(|| { + let now = Instant::now(); + let mut snapshots = Vec::new(); + for model in ["gpt-6-astra", "gpt-5.5"] { + let mut pane = pane(); + pane.composer.set_disable_paste_burst(/*disabled*/ false); + pane.mark_fresh_task_for_sparkle(model, &enabled()); + let initial = draw(&pane.composer, /*width*/ 80, now).0; + key(&mut pane, KeyCode::Char('/')); + assert!(pane.composer.is_in_paste_burst()); + assert_eq!(pane.composer.current_text(), ""); + assert_eq!(pane.composer.sparkle.draft.get(), SparkleDraft::Command); + key(&mut pane, KeyCode::Backspace); + assert!(!pane.composer.is_in_paste_burst()); + assert_eq!(pane.composer.current_text(), ""); + assert_eq!(pane.composer.sparkle.draft.get(), SparkleDraft::Untouched); + let canceled = draw(&pane.composer, /*width*/ 80, now).0; + assert_eq!(dots(&canceled), dots(&initial)); + + type_text(&mut pane, "/model"); + pane.composer + .handle_paste_burst_flush(now + Duration::from_secs(/*secs*/ 1)); + assert!(matches!( + key(&mut pane, KeyCode::Enter), + InputResult::Command(SlashCommand::Model) + )); + pane.select_sparkle_model("gpt-6-astra", &enabled()); + let selected = draw(&pane.composer, /*width*/ 80, now).0; + assert!(!dots(&selected).is_empty()); + snapshots.push(format!( + "{model}\nafter immediately canceling the held slash:\n{}\nafter /model:\n{}", + text(&canceled), + text(&selected) + )); + } + insta::assert_snapshot!(snapshots.join("\n\n")); + }); +} + +#[test] +fn buffered_commands_and_read_only_inline_arguments_preserve_eligibility() { + palette(|| { + let now = Instant::now(); + let mut buffered = pane(); + buffered + .composer + .set_disable_paste_burst(/*disabled*/ false); + buffered.mark_fresh_task_for_sparkle("gpt-5.5", &enabled()); + type_text(&mut buffered, "/status"); + buffered + .composer + .handle_paste_burst_flush(now + Duration::from_secs(/*secs*/ 1)); + assert!(matches!( + key(&mut buffered, KeyCode::Enter), + InputResult::Command(SlashCommand::Status) + )); + assert_eq!( + buffered.composer.sparkle.draft.get(), + SparkleDraft::Untouched + ); + + let mut inline = pane(); + inline.mark_fresh_task_for_sparkle("gpt-5.5", &enabled()); + type_text(&mut inline, "/rename task name"); + assert_eq!(inline.composer.sparkle.draft.get(), SparkleDraft::Command); + assert!(matches!( + key(&mut inline, KeyCode::Enter), + InputResult::CommandWithArgs(SlashCommand::Rename, _, _) + )); + inline + .composer + .set_text_content(String::new(), Vec::new(), Vec::new()); + inline.select_sparkle_model("astra", &enabled()); + assert!(!dots(&draw(&inline.composer, /*width*/ 80, now).0).is_empty()); + }); +} + +#[test] +fn commands_hide_a_started_sparkle_without_restarting_its_deadline() { + palette(|| { + let now = Instant::now(); + let mut pane = pane(); + pane.mark_fresh_task_for_sparkle("astra", &enabled()); + assert!(!dots(&draw(&pane.composer, /*width*/ 80, now).0).is_empty()); + type_text(&mut pane, "/status"); + assert!( + dots( + &draw( + &pane.composer, + /*width*/ 80, + now + Duration::from_secs(/*secs*/ 5) + ) + .0 + ) + .is_empty() + ); + assert!(matches!( + key(&mut pane, KeyCode::Enter), + InputResult::Command(SlashCommand::Status) + )); + assert!( + !dots( + &draw( + &pane.composer, + /*width*/ 80, + now + Duration::from_secs(/*secs*/ 6) + ) + .0 + ) + .is_empty() + ); + type_text(&mut pane, "/diff"); + assert!(dots(&draw(&pane.composer, /*width*/ 80, now + IDLE_TIMEOUT).0).is_empty()); + assert!(matches!( + key(&mut pane, KeyCode::Enter), + InputResult::Command(SlashCommand::Diff) + )); + assert!( + dots( + &draw( + &pane.composer, + /*width*/ 80, + now + IDLE_TIMEOUT + IDLE_FADE + ) + .0 + ) + .is_empty() + ); + }); +} + +#[test] +fn focus_startup_work_and_configuration_do_not_extend_a_started_deadline() { + palette(|| { + let now = Instant::now(); + let mut pane = pane(); + pane.mark_fresh_task_for_sparkle("astra", &enabled()); + pane.composer.set_task_running(/*running*/ true); + assert!(dots(&draw(&pane.composer, /*width*/ 80, now).0).is_empty()); + pane.composer.set_task_running(/*running*/ false); + assert!(!dots(&draw(&pane.composer, /*width*/ 80, now + IDLE_TIMEOUT).0).is_empty()); + pane.set_sparkle_terminal_focus(/*focused*/ false); + assert!( + dots( + &draw( + &pane.composer, + /*width*/ 80, + now + IDLE_TIMEOUT + Duration::from_secs(/*secs*/ 1) + ) + .0 + ) + .is_empty() + ); + pane.set_sparkle_terminal_focus(/*focused*/ true); + assert!(dots(&draw(&pane.composer, /*width*/ 80, now + IDLE_TIMEOUT * 2).0).is_empty()); + + for settings in [ + Tui { + whimsy: false, + ..enabled() + }, + Tui { + animations: false, + ..enabled() + }, + ] { + let mut pane = super::tests::pane(); + pane.mark_fresh_task_for_sparkle("astra", &settings); + assert!(dots(&draw(&pane.composer, /*width*/ 80, now).0).is_empty()); + } + let mut narrow = super::tests::pane(); + narrow.mark_fresh_task_for_sparkle("astra", &enabled()); + let (buffer, textarea) = draw(&narrow.composer, /*width*/ 25, now); + assert!( + dots(&buffer) + .iter() + .all(|(x, y, _)| !textarea.contains(Position::new(*x, *y))) + ); + }); +} diff --git a/codex-rs/tui/src/bottom_pane/chat_composer/vim_history.rs b/codex-rs/tui/src/bottom_pane/chat_composer/vim_history.rs index 9cd4e27110..cbe8b5a961 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer/vim_history.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer/vim_history.rs @@ -64,21 +64,21 @@ impl VimHistory { } impl ChatComposer { + pub(super) fn wants_vim_history_key(&self, event: KeyEvent) -> bool { + self.draft.textarea.is_vim_normal_mode() + && !self.draft.textarea.is_vim_operator_pending() + && !self.popups.active() + && (self.vim_normal_keymap.redo.is_pressed(event) + || self.vim_normal_keymap.undo.is_pressed(event)) + } + /// Consume undo and redo before normal-mode commands, even when their history is empty. pub(super) fn handle_vim_history_key(&mut self, event: KeyEvent) -> bool { - if !self.draft.textarea.is_vim_normal_mode() - || self.draft.textarea.is_vim_operator_pending() - || self.popups.active() - { + if !self.wants_vim_history_key(event) { return false; } let redo = self.vim_normal_keymap.redo.is_pressed(event); - let undo = self.vim_normal_keymap.undo.is_pressed(event); - if !undo && !redo { - return false; - } - let snapshot = if redo { self.vim_history.redo.pop_back() } else { diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 4dcfd3affb..6fa3681480 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -382,6 +382,7 @@ mod model_popups; mod notifications; mod session_model_selection; use self::notifications::Notification; +pub(crate) use self::session_model_selection::AstraModelPickerAction; mod permission_discovery; mod permission_popups; mod permission_shortcuts; diff --git a/codex-rs/tui/src/chatwidget/input_restore.rs b/codex-rs/tui/src/chatwidget/input_restore.rs index c33af45117..f6b702c49f 100644 --- a/codex-rs/tui/src/chatwidget/input_restore.rs +++ b/codex-rs/tui/src/chatwidget/input_restore.rs @@ -19,6 +19,8 @@ impl ChatWidget { /// Restore the exact draft entered before the fully initialized composer became available. pub(crate) fn restore_startup_draft(&mut self, draft: ComposerDraftSnapshot) { + self.bottom_pane + .inherit_startup_sparkle(draft.sparkle_draft); let existing_draft = self.bottom_pane.composer_draft_snapshot(); let existing_cursor = existing_draft.cursor; let existing_message = UserMessage { @@ -106,6 +108,10 @@ impl ChatWidget { &mut self, pending_draft: &mut Option, ) { + if let Some(draft) = pending_draft.as_ref() { + self.bottom_pane + .inherit_startup_sparkle(draft.sparkle_draft); + } if self.has_active_view() || self .bottom_pane diff --git a/codex-rs/tui/src/chatwidget/input_submission.rs b/codex-rs/tui/src/chatwidget/input_submission.rs index d4567b6be9..211b66ed54 100644 --- a/codex-rs/tui/src/chatwidget/input_submission.rs +++ b/codex-rs/tui/src/chatwidget/input_submission.rs @@ -134,6 +134,7 @@ impl ChatWidget { source: UserMessageSource, prepared_images: Option>, ) -> (bool, Option) { + self.bottom_pane.dismiss_composer_sparkle(); if self.has_misalignment_policy_violation() { return (false, None); } diff --git a/codex-rs/tui/src/chatwidget/model_popups.rs b/codex-rs/tui/src/chatwidget/model_popups.rs index fbb8f40e6e..0f9ca10ec4 100644 --- a/codex-rs/tui/src/chatwidget/model_popups.rs +++ b/codex-rs/tui/src/chatwidget/model_popups.rs @@ -292,6 +292,7 @@ impl ChatWidget { .as_ref() .and_then(|effort| self.ultra_reasoning_concurrency_warning(effort)); let thread_id = self.thread_id(); + let sparkle_thread = self.sparkle_thread_for_picker_action(&model_for_action); vec![Box::new(move |tx| { if model_for_action == LUNA_RESERVE_MODEL { // Reserve is temporary: update the active task without persisting a model default. @@ -302,17 +303,22 @@ impl ChatWidget { }); } } else if effort_for_action == Some(ReasoningEffortConfig::Ultra) { - tx.send(AppEvent::ApplyAdvancedReasoning { - model: model_for_action.clone(), - effort: ReasoningEffortConfig::Ultra, - }); + tx.send( + AstraModelPickerAction::ApplyAdvancedReasoning { + effort: ReasoningEffortConfig::Ultra, + } + .into_picker_event(sparkle_thread, model_for_action.clone()), + ); } else if should_prompt_plan_mode_scope { tx.send(AppEvent::OpenPlanReasoningScopePrompt { model: model_for_action.clone(), effort: effort_for_action.clone(), }); } else { - tx.send(AppEvent::UpdateModel(model_for_action.clone())); + tx.send( + AstraModelPickerAction::UpdateModel + .into_picker_event(sparkle_thread, model_for_action.clone()), + ); tx.send(AppEvent::UpdateReasoningEffort(effort_for_action.clone())); tx.send(AppEvent::PersistModelSelection { model: model_for_action.clone(), @@ -394,13 +400,17 @@ impl ChatWidget { let warning = effort .as_ref() .and_then(|effort| self.ultra_reasoning_concurrency_warning(effort)); + let sparkle_thread = self.sparkle_thread_for_picker_action(&model); let plan_only_actions: Vec = vec![Box::new({ let model = model.clone(); let effort = effort.clone(); let warning = warning.clone(); move |tx| { - tx.send(AppEvent::UpdateModel(model.clone())); + tx.send( + AstraModelPickerAction::UpdateModel + .into_picker_event(sparkle_thread, model.clone()), + ); tx.send(AppEvent::UpdatePlanModeReasoningEffort(effort.clone())); tx.send(AppEvent::PersistPlanModeReasoningEffort(effort.clone())); if let Some(warning) = warning.clone() { @@ -411,7 +421,10 @@ impl ChatWidget { } })]; let all_modes_actions: Vec = vec![Box::new(move |tx| { - tx.send(AppEvent::UpdateModel(model.clone())); + tx.send( + AstraModelPickerAction::UpdateModel + .into_picker_event(sparkle_thread, model.clone()), + ); tx.send(AppEvent::UpdateReasoningEffort(effort.clone())); tx.send(AppEvent::UpdatePlanModeReasoningEffort(effort.clone())); tx.send(AppEvent::PersistPlanModeReasoningEffort(effort.clone())); diff --git a/codex-rs/tui/src/chatwidget/replay.rs b/codex-rs/tui/src/chatwidget/replay.rs index 72aea0090f..49e9f0bf0c 100644 --- a/codex-rs/tui/src/chatwidget/replay.rs +++ b/codex-rs/tui/src/chatwidget/replay.rs @@ -102,6 +102,9 @@ impl ChatWidget { /// avoid triggering side effects. Event ids are passed as `None` to /// distinguish replayed events from live ones. pub(crate) fn replay_thread_turns(&mut self, turns: Vec, replay_kind: ReplayKind) { + if !turns.is_empty() || matches!(replay_kind, ReplayKind::ThreadSnapshot) { + self.bottom_pane.dismiss_composer_sparkle(); + } if matches!(replay_kind, ReplayKind::ThreadSnapshot) && !turns.is_empty() { self.warning_display_state.startup_complete = true; } diff --git a/codex-rs/tui/src/chatwidget/review_popups.rs b/codex-rs/tui/src/chatwidget/review_popups.rs index 7185e735b6..15edd4cff7 100644 --- a/codex-rs/tui/src/chatwidget/review_popups.rs +++ b/codex-rs/tui/src/chatwidget/review_popups.rs @@ -4,6 +4,7 @@ use super::*; impl ChatWidget { pub(crate) fn on_review_started(&mut self) { + self.bottom_pane.dismiss_composer_sparkle(); self.bottom_pane.clear_pending_questions(); } diff --git a/codex-rs/tui/src/chatwidget/session_flow.rs b/codex-rs/tui/src/chatwidget/session_flow.rs index 68d4b702b6..d930015e4d 100644 --- a/codex-rs/tui/src/chatwidget/session_flow.rs +++ b/codex-rs/tui/src/chatwidget/session_flow.rs @@ -1,8 +1,48 @@ //! Session configuration and thread-header orchestration for `ChatWidget`. +//! Confirmed model-picker changes can offer the flourish only on their original task; the app +//! checks the previous model when it applies the final selection. use super::*; impl ChatWidget { + /// Offer the flourish only for a successful primary thread/start without initial work. + pub(crate) fn mark_fresh_task_for_sparkle( + &mut self, + started: &crate::app_server_session::AppServerStartedThread, + ) { + if started.turns.is_empty() + && started.session.forked_from_id.is_none() + && !started.blocks_direct_input + && self.initial_user_message.is_none() + && !self.is_user_turn_pending_or_running() + { + self.bottom_pane + .mark_fresh_task_for_sparkle(&started.session.model, &self.local_settings.tui); + } else { + self.bottom_pane.dismiss_composer_sparkle(); + } + } + + pub(crate) fn set_sparkle_terminal_focus(&mut self, focused: bool) { + self.bottom_pane.set_sparkle_terminal_focus(focused); + } + + pub(crate) fn prepare_composer_sparkle_key(&self, key: KeyEvent) { + self.bottom_pane.prepare_composer_sparkle_key(key); + } + + pub(crate) fn sparkle_thread_for_picker_action(&self, model: &str) -> Option { + self.thread_id() + .filter(|_| BottomPane::is_sparkle_model(model)) + } + + pub(crate) fn on_sparkle_model_selected_from_picker(&mut self, model: &str) { + if self.current_model() == model { + self.bottom_pane + .select_sparkle_model(model, &self.local_settings.tui); + } + } + fn on_session_configured_with_display_and_fork_parent_title( &mut self, session: ThreadSessionState, diff --git a/codex-rs/tui/src/chatwidget/session_model_selection.rs b/codex-rs/tui/src/chatwidget/session_model_selection.rs index 6c4cee214f..20a362c329 100644 --- a/codex-rs/tui/src/chatwidget/session_model_selection.rs +++ b/codex-rs/tui/src/chatwidget/session_model_selection.rs @@ -1,10 +1,46 @@ -//! Session-only model picker actions leave durable defaults untouched. +//! Session-only model picker actions leave durable defaults untouched. Astra picker actions retain +//! their originating task and are checked against its effective model when the app applies them. use super::*; use crate::bottom_pane::SelectionSecondaryAction; use crate::keymap::ListAction; use crate::model_catalog::LUNA_RESERVE_MODEL; +/// A final Astra selection whose model transition must be checked while the app applies it. +#[derive(Debug)] +pub(crate) enum AstraModelPickerAction { + UpdateModel, + ApplyAdvancedReasoning { + effort: ReasoningEffortConfig, + }, + SelectSessionModel { + effort: Option, + }, +} + +impl AstraModelPickerAction { + pub(super) fn into_picker_event(self, thread_id: Option, model: String) -> AppEvent { + match thread_id { + Some(thread_id) => AppEvent::AstraSelectedFromModelPicker { + thread_id, + model, + action: self, + }, + None => self.into_app_event(model), + } + } + + pub(crate) fn into_app_event(self, model: String) -> AppEvent { + match self { + Self::UpdateModel => AppEvent::UpdateModel(model), + Self::ApplyAdvancedReasoning { effort } => { + AppEvent::ApplyAdvancedReasoning { model, effort } + } + Self::SelectSessionModel { effort } => AppEvent::SelectSessionModel { model, effort }, + } + } +} + impl ChatWidget { pub(super) fn session_model_selection_action( &self, @@ -33,14 +69,17 @@ impl ChatWidget { let warning = effort .as_ref() .and_then(|effort| self.ultra_reasoning_concurrency_warning(effort)); + let sparkle_thread = self.sparkle_thread_for_picker_action(&model); Some(SelectionSecondaryAction { key, footer_hint: hints.into(), action: Box::new(move |tx| { - tx.send(AppEvent::SelectSessionModel { - model: model.clone(), - effort: effort.clone(), - }); + tx.send( + AstraModelPickerAction::SelectSessionModel { + effort: effort.clone(), + } + .into_picker_event(sparkle_thread, model.clone()), + ); if let Some(warning) = warning.clone() { tx.send(AppEvent::InsertHistoryCell(Box::new( history_cell::new_warning_event(warning), diff --git a/codex-rs/tui/src/chatwidget/settings.rs b/codex-rs/tui/src/chatwidget/settings.rs index 2f8bf9495e..1e20308aba 100644 --- a/codex-rs/tui/src/chatwidget/settings.rs +++ b/codex-rs/tui/src/chatwidget/settings.rs @@ -415,6 +415,8 @@ impl ChatWidget { pub(super) fn refresh_model_display(&mut self) { let effective = self.effective_collaboration_mode(); + self.bottom_pane + .stop_ineligible_sparkle(effective.model(), &self.local_settings.tui); self.session_header.set_model(effective.model()); // Keep composer paste affordances aligned with the currently effective model. self.sync_image_paste_enabled(); diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs index 9a68c6e61a..6d5ead9c5e 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -276,6 +276,8 @@ mod review_mode; mod session_model_selection_tests; mod side; mod slash_commands; +#[path = "tests/sparkle_submission_tests.rs"] +mod sparkle_submission_tests; mod status_and_layout; mod status_command_tests; mod status_surface_previews; diff --git a/codex-rs/tui/src/chatwidget/tests/session_model_selection_tests.rs b/codex-rs/tui/src/chatwidget/tests/session_model_selection_tests.rs index dd77afed7b..38bf0165bd 100644 --- a/codex-rs/tui/src/chatwidget/tests/session_model_selection_tests.rs +++ b/codex-rs/tui/src/chatwidget/tests/session_model_selection_tests.rs @@ -62,6 +62,56 @@ async fn session_model_selection_accepts_final_choices_without_saving() { } } +#[tokio::test] +async fn session_model_selection_notifies_the_original_task_after_each_final_astra_choice() { + for picker in ["model", "reasoning", "advanced"] { + let (mut chat, mut events, _ops) = make_chatwidget_manual(Some("gpt-5.5")).await; + let thread_id = ThreadId::new(); + chat.thread_id = Some(thread_id); + let mut preset = get_available_model(&chat, "gpt-5.5"); + preset.model = "gpt-6-astra".into(); + let effort = if picker == "advanced" { + ReasoningEffortConfig::Max + } else { + ReasoningEffortConfig::High + }; + preset.default_reasoning_effort = effort.clone(); + preset.supported_reasoning_efforts = vec![ReasoningEffortPreset { + effort: effort.clone(), + description: "Selected effort".into(), + }]; + match picker { + "model" => chat.open_model_popup_with_presets(vec![preset]), + "reasoning" => { + preset + .supported_reasoning_efforts + .push(ReasoningEffortPreset { + effort: ReasoningEffortConfig::Low, + description: "Low effort".into(), + }); + chat.open_reasoning_popup(preset); + } + "advanced" => chat.open_advanced_reasoning_popup(preset), + _ => unreachable!(), + } + while events.try_recv().is_ok() {} + chat.handle_key_event(KeyCode::Char('s').into()); + + assert_matches!(events.try_recv(), Ok(AppEvent::AstraSelectedFromModelPicker { + thread_id: selected_thread, + model, + action: AstraModelPickerAction::SelectSessionModel { effort: selected_effort }, + }) if selected_thread == thread_id && model == "gpt-6-astra" && selected_effort == Some(effort)); + assert!( + std::iter::from_fn(|| events.try_recv().ok()).all(|event| matches!( + event, + AppEvent::InsertHistoryCell(_) | AppEvent::SettingsSelectionClosed + )) + ); + assert!(chat.bottom_pane.no_modal_or_popup_active(), "{picker}"); + } +} + #[tokio::test] async fn session_model_selection_hides_conflicting_shortcut() { let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.5")).await; diff --git a/codex-rs/tui/src/chatwidget/tests/sparkle_submission_tests.rs b/codex-rs/tui/src/chatwidget/tests/sparkle_submission_tests.rs new file mode 100644 index 0000000000..01bbafae44 --- /dev/null +++ b/codex-rs/tui/src/chatwidget/tests/sparkle_submission_tests.rs @@ -0,0 +1,77 @@ +//! Covers sparkle dismissal across ordinary and prepared-image user submissions. + +use super::*; +use crate::terminal_palette::with_test_default_colors; +use crate::terminal_probe::DefaultColors; +use codex_app_server_protocol::ImageReference; +use pretty_assertions::assert_eq; +use pretty_assertions::assert_ne; + +#[tokio::test] +async fn ordinary_and_prepared_image_submissions_consume_the_sparkle_before_rendering() { + let image = UserInput::Image { + image: ImageReference::Inline { + url: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/lFkAAAAASUVORK5CYII=".into(), + }, + detail: None, + }; + let text = "describe"; + let visible = |chat: &ChatWidget| { + with_test_default_colors( + DefaultColors { + fg: (230, 216, 255), + bg: (36, 27, 53), + }, + || { + render_bottom_popup(chat, /*width*/ 80) + .chars() + .any(|ch| "⠁⠂⠄⠈⠐⠠⡀⢀".contains(ch)) + }, + ) + }; + + for prepared_images in [None, Some(vec![image])] { + let (mut chat, _events, mut ops) = make_chatwidget_manual(Some("gpt-6-astra")).await; + chat.thread_id = Some(ThreadId::new()); + chat.local_settings.tui.animations = true; + chat.local_settings.tui.whimsy = true; + chat.bottom_pane + .mark_fresh_task_for_sparkle("gpt-6-astra", &chat.local_settings.tui); + let untouched = chat.bottom_pane.composer_draft_snapshot().sparkle_draft; + assert_eq!(untouched, Default::default()); + assert!(visible(&chat)); + + let mut expected_items = prepared_images.clone().unwrap_or_default(); + expected_items.push(UserInput::Text { + text: text.into(), + text_elements: Vec::new(), + }); + let message = UserMessage::from(text); + let (accepted, _command) = match prepared_images { + Some(images) => chat.submit_user_message_with_prepared_images( + message, + UserMessageHistoryRecord::UserMessageText, + ShellEscapePolicy::Disallow, + UserMessageSource::Prompt, + Some(images), + ), + None => chat.submit_user_message_with_history_and_shell_escape_policy( + message, + UserMessageHistoryRecord::UserMessageText, + ShellEscapePolicy::Disallow, + UserMessageSource::Prompt, + ), + }; + + assert!(accepted); + assert_ne!( + chat.bottom_pane.composer_draft_snapshot().sparkle_draft, + untouched + ); + assert!(!visible(&chat)); + let Op::UserTurn { items, .. } = next_submit_op(&mut ops) else { + unreachable!("next_submit_op only returns UserTurn") + }; + assert_eq!(items, expected_items); + } +} diff --git a/codex-rs/tui/src/chatwidget/turn_runtime.rs b/codex-rs/tui/src/chatwidget/turn_runtime.rs index 6d7c32cecc..412baa6219 100644 --- a/codex-rs/tui/src/chatwidget/turn_runtime.rs +++ b/codex-rs/tui/src/chatwidget/turn_runtime.rs @@ -74,6 +74,7 @@ impl ChatWidget { // Raw reasoning uses the same flow as summarized reasoning pub(super) fn on_task_started(&mut self) { + self.bottom_pane.dismiss_composer_sparkle(); self.clear_context_compaction(); self.input_queue.user_turn_pending_start = false; self.reset_safety_buffering_for_turn_start();