Add a one-time composer starfield for new Astra tasks (#46096)

## What changed

Show a brief starfield in the empty composer when a new task starts with Astra or the user selects Astra through `/model` before entering ordinary prompt content.

- Respect `tui.animations`, `tui.whimsy`, and true-color support; protect the placeholder and cursor and fade out by 15 seconds.
- Preserve eligibility through recognized slash commands, but permanently dismiss it after ordinary draft content, attachments, or work. Carry draft eligibility through startup and disconnected editing.
- Exclude resumed and forked tasks, and verify model-picker changes against the originating task and effective model when applied.
- Hide the effect during overlays or focus loss without restarting its deadline or scheduling hidden animation frames.

## Testing

Add regression tests and snapshots for task eligibility, model-picker transitions, draft and paste handling, history search, overlays, submissions, rendering protection, and animation expiry.

GitOrigin-RevId: 832705543e9cae1d561125ece853a16c4eefe627
This commit is contained in:
Ian MacLeod authored and copyberry committed 2026-09-17 03:27:21 +00:00
1 parent 787823cf95
commit f3da3861c5
45 files changed
+3244 -171

No files matched your search

+4
View File
@@ -897,6 +897,8 @@ impl App {
match &event { match &event {
TuiEvent::FocusLost => { TuiEvent::FocusLost => {
self.chat_widget
.set_sparkle_terminal_focus(/*focused*/ false);
let now = Instant::now(); let now = Instant::now();
let thread_id = self.current_displayed_thread_id(); 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<Rect> { fn render_chat_widget_frame(&mut self, tui: &mut tui::Tui, screen_size: Size) -> Result<Rect> {
self.sync_thread_title_progress(); self.sync_thread_title_progress();
self.chat_widget
.set_sparkle_terminal_focus(tui.is_terminal_focused());
let dashboard_visible = self let dashboard_visible = self
.chat_widget .chat_widget
.selected_index_for_present_view(AGENTS_OVERVIEW_VIEW_ID) .selected_index_for_present_view(AGENTS_OVERVIEW_VIEW_ID)
+8 -1
View File
@@ -1,5 +1,6 @@
//! Daemon-wide overview of recent and locally retained sessions and their subagents. //! 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. //! 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"] #[path = "agents_overview_new.rs"]
mod new; mod new;
@@ -14,6 +15,7 @@ mod loading;
use super::agents_overview_view::AgentsOverviewGroup; use super::agents_overview_view::AgentsOverviewGroup;
use super::agents_overview_view::AgentsOverviewRow; use super::agents_overview_view::AgentsOverviewRow;
use super::agents_overview_view::AgentsOverviewView; use super::agents_overview_view::AgentsOverviewView;
use super::session_lifecycle::ThreadAttachPresentation;
use super::*; use super::*;
use crate::app_event::AgentsOverviewThreadRefresh; use crate::app_event::AgentsOverviewThreadRefresh;
use crate::bottom_pane::SelectionDescriptionLayout; use crate::bottom_pane::SelectionDescriptionLayout;
@@ -511,6 +513,11 @@ impl App {
} }
}; };
let mut history_notice = None; 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 { let (resumed, read_only) = if let Some((_, started)) = started {
(started, false) (started, false)
} else if !unloaded } else if !unloaded
@@ -637,7 +644,7 @@ impl App {
.replace_chat_widget_with_app_server_thread( .replace_chat_widget_with_app_server_thread(
tui, tui,
resumed, resumed,
super::session_lifecycle::ThreadAttachPresentation::SessionLineage, presentation,
/*initial_user_message*/ None, /*initial_user_message*/ None,
) )
.await .await
+16
View File
@@ -1805,6 +1805,22 @@ impl App {
.await; .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 { AppEvent::RealtimeWebrtcOfferCreated {
thread_id, thread_id,
attempt_id, attempt_id,
+1
View File
@@ -469,6 +469,7 @@ impl App {
// Esc so the active UI (e.g. status indicator, modals, popups) // Esc so the active UI (e.g. status indicator, modals, popups)
// handles it. // handles it.
if self.should_handle_backtrack_esc(key_event) { if self.should_handle_backtrack_esc(key_event) {
self.chat_widget.prepare_composer_sparkle_key(key_event);
self.handle_backtrack_esc_key(tui); self.handle_backtrack_esc_key(tui);
} else if self.should_reject_side_backtrack_esc(key_event) { } else if self.should_reject_side_backtrack_esc(key_event) {
self.reject_side_backtrack_esc(); self.reject_side_backtrack_esc();
+7 -1
View File
@@ -18,6 +18,8 @@ use std::collections::HashSet;
#[derive(Clone, Copy)] #[derive(Clone, Copy)]
pub(super) enum ThreadAttachPresentation { pub(super) enum ThreadAttachPresentation {
/// A primary thread created by thread/start, without inherited history.
Fresh,
SessionLineage, SessionLineage,
} }
@@ -834,6 +836,7 @@ impl App {
.set_queue_submissions_until_session_configured(/*queue*/ false); .set_queue_submissions_until_session_configured(/*queue*/ false);
match result { match result {
Ok(started) => { Ok(started) => {
self.chat_widget.mark_fresh_task_for_sparkle(&started);
let thread_id = started.session.thread_id; let thread_id = started.session.thread_id;
if started.task_tools_available { if started.task_tools_available {
app_server.remember_task_tool_thread(thread_id); app_server.remember_task_tool_thread(thread_id);
@@ -997,7 +1000,7 @@ impl App {
.replace_chat_widget_with_app_server_thread( .replace_chat_widget_with_app_server_thread(
tui, tui,
started, started,
ThreadAttachPresentation::SessionLineage, ThreadAttachPresentation::Fresh,
initial_user_message, initial_user_message,
) )
.await .await
@@ -1056,6 +1059,9 @@ impl App {
initial_user_message, initial_user_message,
); );
self.replace_chat_widget(ChatWidget::new_with_app_event(init)); 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 self.chat_widget
.set_task_mentions_enabled(started.task_tools_available); .set_task_mentions_enabled(started.task_tools_available);
self.chat_widget self.chat_widget
+2
View File
@@ -27,6 +27,8 @@ mod buffered_replay;
mod connector_policy; mod connector_policy;
#[path = "tests/disconnect_tests.rs"] #[path = "tests/disconnect_tests.rs"]
mod disconnect; mod disconnect;
#[path = "tests/fresh_sparkle_tests.rs"]
mod fresh_sparkle_tests;
#[path = "tests/key_chords.rs"] #[path = "tests/key_chords.rs"]
mod key_chords; mod key_chords;
#[path = "tests/luna_reserve_recovery_tests.rs"] #[path = "tests/luna_reserve_recovery_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); 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::<Vec<_>>()
.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] #[tokio::test]
async fn command_center_new_reads_server_defaults_for_actual_destination() -> Result<()> { async fn command_center_new_reads_server_defaults_for_actual_destination() -> Result<()> {
let mut tui = make_test_tui()?; let mut tui = make_test_tui()?;
@@ -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<AppEvent>,
model: &str,
key: KeyCode,
) -> Result<usize> {
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::<Vec<_>>();
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::<Vec<_>>();
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(())
}
@@ -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
@@ -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 ⠈ ⠁
⢀ ⠠ ⠄ ⠠ ⢀ ⠠ ⡀
@@ -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
+1 -1
View File
@@ -1565,7 +1565,7 @@ impl App {
self.chat_widget.set_token_info(/*info*/ None); self.chat_widget.set_token_info(/*info*/ None);
} }
match presentation { match presentation {
ThreadAttachPresentation::SessionLineage => { ThreadAttachPresentation::Fresh | ThreadAttachPresentation::SessionLineage => {
self.chat_widget.handle_thread_session(session); self.chat_widget.handle_thread_session(session);
} }
} }
+9
View File
@@ -51,6 +51,7 @@ use crate::app_server_session::AppServerStartedThread;
use crate::bottom_pane::ApprovalRequest; use crate::bottom_pane::ApprovalRequest;
use crate::bottom_pane::StatusLineItem; use crate::bottom_pane::StatusLineItem;
use crate::bottom_pane::TerminalTitleItem; use crate::bottom_pane::TerminalTitleItem;
use crate::chatwidget::AstraModelPickerAction;
use crate::chatwidget::ConnectorScopeGeneration; use crate::chatwidget::ConnectorScopeGeneration;
use crate::chatwidget::ThreadUsageOutcome; use crate::chatwidget::ThreadUsageOutcome;
use crate::chatwidget::UserMessage; use crate::chatwidget::UserMessage;
@@ -1118,6 +1119,14 @@ pub(crate) enum AppEvent {
/// Update the current model slug in the running app and widget. /// Update the current model slug in the running app and widget.
UpdateModel(String), 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. /// Result of creating a TUI-owned WebRTC offer for an active thread.
RealtimeWebrtcOfferCreated { RealtimeWebrtcOfferCreated {
thread_id: ThreadId, thread_id: ThreadId,
+95 -133
View File
@@ -4,7 +4,7 @@
//! completed slash commands to atomic elements, and handles Enter submission/newlines. //! 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 //! It also shows Luna Reserve's yellow prompt arrow and detects unbracketed paste bursts
//! from raw key streams, particularly on Windows. //! 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 //! The plain-text preset keeps command prefixes literal, including `!`, so Enter and Tab
//! submit ordinary text without enabling shell mode. //! 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 //! navigation slash commands remain available so users can leave or manage the view. Transcript
//! exports also remain available, including an explicit destination filename. //! exports also remain available, including an explicit destination filename.
//! //!
//! During reconnection, `handle_disconnected_key` edits the draft directly without //! During reconnection, `handle_disconnected_key` edits the draft directly without popup dispatch,
//! popup dispatch or submission. Enter and Tab leave the draft intact until reconnection succeeds. //! 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. //! Collapsed pastes expand into editable text so the full draft can be copied before quitting.
//! //!
//! # Reasoning Effort Animations //! # Reasoning Effort Animations
@@ -134,6 +135,36 @@
//! restoration clears any transition queued while replaying the saved session. Rendering advances //! restoration clears any transition queued while replaying the saved session. Rendering advances
//! active transitions through the frame requester until they finish. //! 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 Paste Placeholders
//! //!
//! Large pastes insert an element placeholder in the buffer and store the full text in //! 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. //! - 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. //! 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 //! - [`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 //! from UI ticks to integrate a pending burst via [`ChatComposer::apply_paste`] or insert a
//! normal typed character. //! held single character. Explicit terminal paste events use [`ChatComposer::handle_paste`] to
//! classify input first; buffered keys have already been classified.
//! //!
//! # Input Disabled Mode //! # Input Disabled Mode
//! //!
@@ -287,7 +319,6 @@ use super::skill_popup::SkillPopup;
use super::slash_commands::ServiceTierCommand; use super::slash_commands::ServiceTierCommand;
use super::slash_commands::SlashCommandItem; use super::slash_commands::SlashCommandItem;
use super::voice_strip::VoiceStrip; use super::voice_strip::VoiceStrip;
use crate::bottom_pane::paste_burst::FlushResult;
use crate::history_cell::sanitize_user_text; use crate::history_cell::sanitize_user_text;
use crate::key_hint::KeyBindingListExt; use crate::key_hint::KeyBindingListExt;
use crate::keymap::EditorKeymap; use crate::keymap::EditorKeymap;
@@ -319,6 +350,7 @@ mod paste_input;
mod popup_state; mod popup_state;
mod reconnect; mod reconnect;
mod slash_input; mod slash_input;
mod sparkle;
mod vim_history; mod vim_history;
mod vim_search; mod vim_search;
@@ -531,6 +563,7 @@ pub(crate) struct ChatComposer {
footer: FooterState, footer: FooterState,
has_focus: bool, has_focus: bool,
frame_requester: Option<FrameRequester>, frame_requester: Option<FrameRequester>,
sparkle: sparkle::Sparkle,
effort_tier: Option<EffortTier>, effort_tier: Option<EffortTier>,
effort_animation_style: Option<IgnitionStyle>, effort_animation_style: Option<IgnitionStyle>,
effort_ignition: Option<EffortIgnition>, effort_ignition: Option<EffortIgnition>,
@@ -605,6 +638,7 @@ pub(crate) struct ComposerDraftSnapshot {
pub(crate) pending_pastes: Vec<(String, String)>, pub(crate) pending_pastes: Vec<(String, String)>,
pub(crate) startup_local_history: Vec<HistoryEntry>, pub(crate) startup_local_history: Vec<HistoryEntry>,
pub(crate) last_composer_activity_at: Option<Instant>, pub(crate) last_composer_activity_at: Option<Instant>,
pub(crate) sparkle_draft: sparkle::SparkleDraft,
} }
const FOOTER_SPACING_HEIGHT: u16 = 0; const FOOTER_SPACING_HEIGHT: u16 = 0;
@@ -699,6 +733,7 @@ impl ChatComposer {
}, },
has_focus: has_input_focus, has_focus: has_input_focus,
frame_requester: None, frame_requester: None,
sparkle: sparkle::Sparkle::default(),
effort_tier: None, effort_tier: None,
effort_animation_style: None, effort_animation_style: None,
effort_ignition: None, effort_ignition: None,
@@ -1203,64 +1238,6 @@ impl ChatComposer {
self.history.record_replayed_submission(entry); 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 { pub fn handle_paste_image_path(&mut self, pasted: &str) -> bool {
let Some(path_buf) = normalize_pasted_path(pasted) else { let Some(path_buf) = normalize_pasted_path(pasted) else {
return false; 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. /// Replace the composer content with text from an external editor.
/// Clears pending paste placeholders and keeps only attachments whose /// Clears pending paste placeholders and keeps only attachments whose
/// placeholder labels still appear in the new text. Image placeholders /// placeholder labels still appear in the new text. Image placeholders
/// are renumbered to `[Image #M+1]..[Image #N]` (where `M` is the number of /// 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. /// remote images). Cursor is placed at the end after rebuilding elements.
pub(crate) fn apply_external_edit(&mut self, text: String) { pub(crate) fn apply_external_edit(&mut self, text: String) {
self.note_sparkle_replaced_text(&text);
self.vim_history = VimHistory::default(); self.vim_history = VimHistory::default();
self.draft.pending_pastes.clear(); self.draft.pending_pastes.clear();
let (text, _) = self.imported_text_for_textarea(text, Vec::new()); 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. /// footer mode so the visible hints match the new editing surface.
pub(crate) fn set_vim_enabled(&mut self, enabled: bool) { pub(crate) fn set_vim_enabled(&mut self, enabled: bool) {
if let Some(pasted) = self.draft.paste_burst.flush_before_modified_input() { 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.enable_vim_search();
self.draft.textarea.set_vim_enabled(enabled); self.draft.textarea.set_vim_enabled(enabled);
@@ -1550,6 +1499,9 @@ impl ChatComposer {
} }
pub(crate) fn set_remote_image_urls(&mut self, urls: Vec<String>) { pub(crate) fn set_remote_image_urls(&mut self, urls: Vec<String>) {
if !self.sparkle.history_preview && !urls.is_empty() {
self.dismiss_sparkle();
}
self.attachments self.attachments
.set_remote_image_urls(urls, &mut self.draft.textarea); .set_remote_image_urls(urls, &mut self.draft.textarea);
self.sync_popups(); self.sync_popups();
@@ -1595,6 +1547,13 @@ impl ChatComposer {
local_image_paths: Vec<PathBuf>, local_image_paths: Vec<PathBuf>,
mention_bindings: Vec<MentionBinding>, mention_bindings: Vec<MentionBinding>,
) { ) {
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. // Clear any existing content, placeholders, and attachments first.
self.footer.flash = None; self.footer.flash = None;
self.vim_history = VimHistory::default(); self.vim_history = VimHistory::default();
@@ -1759,7 +1718,7 @@ impl ChatComposer {
/// Flush buffered typing before clearing so cancellation preserves the complete draft in history. /// Flush buffered typing before clearing so cancellation preserves the complete draft in history.
pub(crate) fn clear_for_ctrl_c(&mut self) -> Option<String> { pub(crate) fn clear_for_ctrl_c(&mut self) -> Option<String> {
if let Some(pasted) = self.draft.paste_burst.flush_before_modified_input() { if let Some(pasted) = self.draft.paste_burst.flush_before_modified_input() {
self.handle_paste(pasted); self.apply_paste(pasted);
} }
if self.is_empty() { if self.is_empty() {
return None; return None;
@@ -1844,6 +1803,7 @@ impl ChatComposer {
pending_pastes: self.pending_pastes(), pending_pastes: self.pending_pastes(),
startup_local_history: self.history.startup_local_history().to_vec(), startup_local_history: self.history.startup_local_history().to_vec(),
last_composer_activity_at: None, 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. /// Insert an attachment placeholder and track it for the next submission.
pub fn attach_image(&mut self, path: PathBuf) { pub fn attach_image(&mut self, path: PathBuf) {
self.dismiss_sparkle();
let started_vim_edit = self.begin_direct_vim_edit(); let started_vim_edit = self.begin_direct_vim_edit();
self.attachments self.attachments
.attach_image(&mut self.draft.textarea, path); .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: /// 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 /// - If only the first ASCII char was held (flicker suppression) and no burst followed, emit it
/// as normal typed input. /// as normal typed input.
/// ///
@@ -2012,6 +1974,9 @@ impl ChatComposer {
} }
pub(crate) fn insert_str(&mut self, text: &str) { 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(); let started_vim_edit = self.begin_direct_vim_edit();
self.draft.textarea.insert_str(text); self.draft.textarea.insert_str(text);
self.sync_bash_mode_from_text(); self.sync_bash_mode_from_text();
@@ -2031,6 +1996,13 @@ impl ChatComposer {
return (InputResult::None, false); 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() if self.history_search.is_none()
&& !self.popups.active() && !self.popups.active()
&& self.draft.textarea.wants_vim_search_key(key_event) && 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 // any existing burst buffer (including a pending first char from the ASCII path) so
// we don't carry that transient state forward. // we don't carry that transient state forward.
if let Some(pasted) = self.draft.paste_burst.flush_before_modified_input() { 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) { if let Some(decision) = self.draft.paste_burst.on_plain_char_no_hold(now) {
match decision { match decision {
@@ -2165,7 +2137,7 @@ impl ChatComposer {
} }
} }
if let Some(pasted) = self.draft.paste_burst.flush_before_modified_input() { 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); self.draft.textarea.input(input);
@@ -3232,7 +3204,7 @@ impl ChatComposer {
} }
if should_queue { if should_queue {
if let Some(pasted) = self.draft.paste_burst.flush_before_modified_input() { 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 visible_shell_command = self.is_bang_shell_command();
let original_input = self.current_text(); let original_input = self.current_text();
@@ -3532,7 +3504,7 @@ impl ChatComposer {
} }
if self.draft.is_bash_mode && key_event.code == KeyCode::Esc { if self.draft.is_bash_mode && key_event.code == KeyCode::Esc {
if let Some(pasted) = self.draft.paste_burst.flush_before_modified_input() { 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() { if self.draft.textarea.is_empty() {
self.draft.is_bash_mode = false; self.draft.is_bash_mode = false;
@@ -3643,28 +3615,6 @@ impl ChatComposer {
.map(|_| Line::from(vec![Span::from("Shell mode").light_red()])) .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. /// 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 /// 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() { 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) if !matches!(input.code, KeyCode::Char(_) | KeyCode::Enter)
&& let Some(pasted) = self.draft.paste_burst.flush_before_modified_input() && 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. // For non-char inputs (or after flushing), handle normally.
// Track element removals so we can drop any corresponding placeholders without scanning // Track element removals so we can drop any corresponding placeholders without scanning
@@ -3887,23 +3837,29 @@ impl ChatComposer {
return true; return true;
} }
let toggles = self.footer.hint_override.is_none() let Some(next) = self.empty_prompt_shortcut_toggle(key_event) else {
&& self.toggle_shortcuts_keys.is_pressed(*key_event)
&& self.is_empty()
&& !self.is_in_paste_burst();
if !toggles {
return false; return false;
};
self.footer.mode = next;
true
} }
fn empty_prompt_shortcut_toggle(&self, key_event: &KeyEvent) -> Option<FooterMode> {
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()
{
let next = toggle_shortcut_mode( let next = toggle_shortcut_mode(
self.footer.mode, self.footer.mode,
self.quit_shortcut_hint_visible(), self.quit_shortcut_hint_visible(),
self.is_empty(), self.is_empty(),
); );
let changed = next != self.footer.mode; (next != self.footer.mode).then_some(next)
self.footer.mode = next; } else {
changed None
}
} }
fn footer_props(&self) -> FooterProps { fn footer_props(&self) -> FooterProps {
@@ -5075,6 +5031,12 @@ impl ChatComposer {
} }
drop(state); drop(state);
self.render_voice_strip(composer_rect, buf); 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,
);
} }
} }
@@ -16,7 +16,8 @@
//! latest history entry by itself. Typing or pasting a query restarts traversal from newest to oldest, //! 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 //! 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 //! 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; use std::ops::Range;
@@ -110,14 +111,14 @@ impl ChatComposer {
/// Opens footer-owned reverse history search without previewing history yet. /// Opens footer-owned reverse history search without previewing history yet.
/// ///
/// Entering search mode first flushes pending paste-burst text, then snapshots the full /// Entering search mode first integrates already-classified paste-burst text with
/// composer draft, clears any file/search popup state, and resets history traversal. The first /// [`Self::apply_paste`], then snapshots the full composer draft, clears any file/search popup
/// visible match is produced only after the footer query becomes non-empty, which keeps Ctrl+R /// state, and resets history traversal. The first visible match is produced only after the
/// from replacing an empty composer with the latest prompt before the user has searched for /// footer query becomes non-empty, which keeps Ctrl+R from replacing an empty composer with
/// anything. /// the latest prompt before the user has searched for anything.
pub(super) fn begin_history_search(&mut self) -> (InputResult, bool) { pub(super) fn begin_history_search(&mut self) -> (InputResult, bool) {
if let Some(pasted) = self.draft.paste_burst.flush_before_modified_input() { 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(); self.draft.paste_burst.clear_window_after_non_char();
@@ -206,6 +207,9 @@ impl ChatComposer {
.is_some_and(|search| matches!(search.status, HistorySearchStatus::Match)) .is_some_and(|search| matches!(search.status, HistorySearchStatus::Match))
{ {
self.history_search = None; self.history_search = None;
if !self.is_empty() {
self.dismiss_sparkle();
}
self.history.reset_search(); self.history.reset_search();
self.footer.mode = reset_mode_after_activity(self.footer.mode); self.footer.mode = reset_mode_after_activity(self.footer.mode);
self.move_cursor_to_end(); self.move_cursor_to_end();
@@ -259,7 +263,7 @@ impl ChatComposer {
if let Some(search) = self.history_search.as_mut() { if let Some(search) = self.history_search.as_mut() {
search.status = HistorySearchStatus::Idle; search.status = HistorySearchStatus::Idle;
} }
self.restore_draft(original_draft); self.with_sparkle_history_preview(|composer| composer.restore_draft(original_draft));
return InputResult::None; return InputResult::None;
} }
let result = self.history.search( let result = self.history.search(
@@ -282,7 +286,7 @@ impl ChatComposer {
search.status = HistorySearchStatus::Searching; search.status = HistorySearchStatus::Searching;
let query = search.query.clone(); let query = search.query.clone();
let original_draft = search.original_draft.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() { if query.is_empty() {
self.history.reset_search(); self.history.reset_search();
if let Some(search) = self.history_search.as_mut() { if let Some(search) = self.history_search.as_mut() {
@@ -311,7 +315,7 @@ impl ChatComposer {
}; };
self.history.reset_navigation(); self.history.reset_navigation();
self.footer.mode = reset_mode_after_activity(self.footer.mode); 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.vim_history = search.original_vim_history;
self.draft self.draft
.textarea .textarea
@@ -333,7 +337,7 @@ impl ChatComposer {
if let Some(search) = self.history_search.as_mut() { if let Some(search) = self.history_search.as_mut() {
search.status = HistorySearchStatus::Match; search.status = HistorySearchStatus::Match;
} }
self.apply_history_entry(entry); self.with_sparkle_history_preview(|composer| composer.apply_history_entry(entry));
} }
HistorySearchResult::Pending => { HistorySearchResult::Pending => {
if let Some(search) = self.history_search.as_mut() { if let Some(search) = self.history_search.as_mut() {
@@ -358,12 +362,21 @@ impl ChatComposer {
}; };
} }
if let Some(original_draft) = original_draft { 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. /// 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 /// The footer displays the query as the editable field and uses the status to decide whether
@@ -66,10 +66,10 @@ impl ChatComposer {
|| self.vim_normal_keymap.move_down.is_pressed(key))) || 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) { pub(crate) fn flush_pending_input(&mut self) {
if let Some(text) = self.draft.paste_burst.flush_before_modified_input() { 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(); self.draft.paste_burst.clear_after_explicit_paste();
} }
@@ -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 super::*;
use crate::bottom_pane::paste_burst::FlushResult;
impl ChatComposer { 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 { pub(super) fn handle_paste_tab(&mut self, key: KeyEvent, now: Instant) -> bool {
if key.code != KeyCode::Tab if key.code != KeyCode::Tab
|| !key.modifiers.is_empty() || !key.modifiers.is_empty()
@@ -1,5 +1,6 @@
//! Offline editing retains the draft in place. //! Offline editing retains the draft in place.
//! Paste Enter handling is shared with normal submission so buffered newlines survive both paths. //! 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::*; use super::*;
@@ -66,7 +67,14 @@ impl ChatComposer {
if !matches!(key.code, KeyCode::Enter | KeyCode::Tab) if !matches!(key.code, KeyCode::Enter | KeyCode::Tab)
&& matches!(key.kind, KeyEventKind::Press | KeyEventKind::Repeat) && 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);
} }
} }
} }
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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<SparkleDraft>,
/// Scoped to history's own replacements; other draft changes still count while search is open.
pub(super) history_preview: bool,
command_input: RefCell<String>,
phase: Cell<Phase>,
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<SparkleEditorState> {
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<SparkleEditorState> {
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<SparkleEditorState>,
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;
@@ -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<Rect>,
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)));
}
}
}
File diff suppressed because it is too large. Load diff
@@ -64,21 +64,21 @@ impl VimHistory {
} }
impl ChatComposer { 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. /// 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 { pub(super) fn handle_vim_history_key(&mut self, event: KeyEvent) -> bool {
if !self.draft.textarea.is_vim_normal_mode() if !self.wants_vim_history_key(event) {
|| self.draft.textarea.is_vim_operator_pending()
|| self.popups.active()
{
return false; return false;
} }
let redo = self.vim_normal_keymap.redo.is_pressed(event); 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 { let snapshot = if redo {
self.vim_history.redo.pop_back() self.vim_history.redo.pop_back()
} else { } else {
+1
View File
@@ -382,6 +382,7 @@ mod model_popups;
mod notifications; mod notifications;
mod session_model_selection; mod session_model_selection;
use self::notifications::Notification; use self::notifications::Notification;
pub(crate) use self::session_model_selection::AstraModelPickerAction;
mod permission_discovery; mod permission_discovery;
mod permission_popups; mod permission_popups;
mod permission_shortcuts; mod permission_shortcuts;
@@ -19,6 +19,8 @@ impl ChatWidget {
/// Restore the exact draft entered before the fully initialized composer became available. /// Restore the exact draft entered before the fully initialized composer became available.
pub(crate) fn restore_startup_draft(&mut self, draft: ComposerDraftSnapshot) { 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_draft = self.bottom_pane.composer_draft_snapshot();
let existing_cursor = existing_draft.cursor; let existing_cursor = existing_draft.cursor;
let existing_message = UserMessage { let existing_message = UserMessage {
@@ -106,6 +108,10 @@ impl ChatWidget {
&mut self, &mut self,
pending_draft: &mut Option<ComposerDraftSnapshot>, pending_draft: &mut Option<ComposerDraftSnapshot>,
) { ) {
if let Some(draft) = pending_draft.as_ref() {
self.bottom_pane
.inherit_startup_sparkle(draft.sparkle_draft);
}
if self.has_active_view() if self.has_active_view()
|| self || self
.bottom_pane .bottom_pane
@@ -134,6 +134,7 @@ impl ChatWidget {
source: UserMessageSource, source: UserMessageSource,
prepared_images: Option<Vec<UserInput>>, prepared_images: Option<Vec<UserInput>>,
) -> (bool, Option<AppCommand>) { ) -> (bool, Option<AppCommand>) {
self.bottom_pane.dismiss_composer_sparkle();
if self.has_misalignment_policy_violation() { if self.has_misalignment_policy_violation() {
return (false, None); return (false, None);
} }
+19 -6
View File
@@ -292,6 +292,7 @@ impl ChatWidget {
.as_ref() .as_ref()
.and_then(|effort| self.ultra_reasoning_concurrency_warning(effort)); .and_then(|effort| self.ultra_reasoning_concurrency_warning(effort));
let thread_id = self.thread_id(); let thread_id = self.thread_id();
let sparkle_thread = self.sparkle_thread_for_picker_action(&model_for_action);
vec![Box::new(move |tx| { vec![Box::new(move |tx| {
if model_for_action == LUNA_RESERVE_MODEL { if model_for_action == LUNA_RESERVE_MODEL {
// Reserve is temporary: update the active task without persisting a model default. // 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) { } else if effort_for_action == Some(ReasoningEffortConfig::Ultra) {
tx.send(AppEvent::ApplyAdvancedReasoning { tx.send(
model: model_for_action.clone(), AstraModelPickerAction::ApplyAdvancedReasoning {
effort: ReasoningEffortConfig::Ultra, effort: ReasoningEffortConfig::Ultra,
}); }
.into_picker_event(sparkle_thread, model_for_action.clone()),
);
} else if should_prompt_plan_mode_scope { } else if should_prompt_plan_mode_scope {
tx.send(AppEvent::OpenPlanReasoningScopePrompt { tx.send(AppEvent::OpenPlanReasoningScopePrompt {
model: model_for_action.clone(), model: model_for_action.clone(),
effort: effort_for_action.clone(), effort: effort_for_action.clone(),
}); });
} else { } 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::UpdateReasoningEffort(effort_for_action.clone()));
tx.send(AppEvent::PersistModelSelection { tx.send(AppEvent::PersistModelSelection {
model: model_for_action.clone(), model: model_for_action.clone(),
@@ -394,13 +400,17 @@ impl ChatWidget {
let warning = effort let warning = effort
.as_ref() .as_ref()
.and_then(|effort| self.ultra_reasoning_concurrency_warning(effort)); .and_then(|effort| self.ultra_reasoning_concurrency_warning(effort));
let sparkle_thread = self.sparkle_thread_for_picker_action(&model);
let plan_only_actions: Vec<SelectionAction> = vec![Box::new({ let plan_only_actions: Vec<SelectionAction> = vec![Box::new({
let model = model.clone(); let model = model.clone();
let effort = effort.clone(); let effort = effort.clone();
let warning = warning.clone(); let warning = warning.clone();
move |tx| { 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::UpdatePlanModeReasoningEffort(effort.clone()));
tx.send(AppEvent::PersistPlanModeReasoningEffort(effort.clone())); tx.send(AppEvent::PersistPlanModeReasoningEffort(effort.clone()));
if let Some(warning) = warning.clone() { if let Some(warning) = warning.clone() {
@@ -411,7 +421,10 @@ impl ChatWidget {
} }
})]; })];
let all_modes_actions: Vec<SelectionAction> = vec![Box::new(move |tx| { let all_modes_actions: Vec<SelectionAction> = 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::UpdateReasoningEffort(effort.clone()));
tx.send(AppEvent::UpdatePlanModeReasoningEffort(effort.clone())); tx.send(AppEvent::UpdatePlanModeReasoningEffort(effort.clone()));
tx.send(AppEvent::PersistPlanModeReasoningEffort(effort.clone())); tx.send(AppEvent::PersistPlanModeReasoningEffort(effort.clone()));
+3
View File
@@ -102,6 +102,9 @@ impl ChatWidget {
/// avoid triggering side effects. Event ids are passed as `None` to /// avoid triggering side effects. Event ids are passed as `None` to
/// distinguish replayed events from live ones. /// distinguish replayed events from live ones.
pub(crate) fn replay_thread_turns(&mut self, turns: Vec<Turn>, replay_kind: ReplayKind) { pub(crate) fn replay_thread_turns(&mut self, turns: Vec<Turn>, 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() { if matches!(replay_kind, ReplayKind::ThreadSnapshot) && !turns.is_empty() {
self.warning_display_state.startup_complete = true; self.warning_display_state.startup_complete = true;
} }
@@ -4,6 +4,7 @@ use super::*;
impl ChatWidget { impl ChatWidget {
pub(crate) fn on_review_started(&mut self) { pub(crate) fn on_review_started(&mut self) {
self.bottom_pane.dismiss_composer_sparkle();
self.bottom_pane.clear_pending_questions(); self.bottom_pane.clear_pending_questions();
} }
@@ -1,8 +1,48 @@
//! Session configuration and thread-header orchestration for `ChatWidget`. //! 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::*; use super::*;
impl ChatWidget { 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<ThreadId> {
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( fn on_session_configured_with_display_and_fork_parent_title(
&mut self, &mut self,
session: ThreadSessionState, session: ThreadSessionState,
@@ -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 super::*;
use crate::bottom_pane::SelectionSecondaryAction; use crate::bottom_pane::SelectionSecondaryAction;
use crate::keymap::ListAction; use crate::keymap::ListAction;
use crate::model_catalog::LUNA_RESERVE_MODEL; 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<ReasoningEffortConfig>,
},
}
impl AstraModelPickerAction {
pub(super) fn into_picker_event(self, thread_id: Option<ThreadId>, 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 { impl ChatWidget {
pub(super) fn session_model_selection_action( pub(super) fn session_model_selection_action(
&self, &self,
@@ -33,14 +69,17 @@ impl ChatWidget {
let warning = effort let warning = effort
.as_ref() .as_ref()
.and_then(|effort| self.ultra_reasoning_concurrency_warning(effort)); .and_then(|effort| self.ultra_reasoning_concurrency_warning(effort));
let sparkle_thread = self.sparkle_thread_for_picker_action(&model);
Some(SelectionSecondaryAction { Some(SelectionSecondaryAction {
key, key,
footer_hint: hints.into(), footer_hint: hints.into(),
action: Box::new(move |tx| { action: Box::new(move |tx| {
tx.send(AppEvent::SelectSessionModel { tx.send(
model: model.clone(), AstraModelPickerAction::SelectSessionModel {
effort: effort.clone(), effort: effort.clone(),
}); }
.into_picker_event(sparkle_thread, model.clone()),
);
if let Some(warning) = warning.clone() { if let Some(warning) = warning.clone() {
tx.send(AppEvent::InsertHistoryCell(Box::new( tx.send(AppEvent::InsertHistoryCell(Box::new(
history_cell::new_warning_event(warning), history_cell::new_warning_event(warning),
+2
View File
@@ -415,6 +415,8 @@ impl ChatWidget {
pub(super) fn refresh_model_display(&mut self) { pub(super) fn refresh_model_display(&mut self) {
let effective = self.effective_collaboration_mode(); 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()); self.session_header.set_model(effective.model());
// Keep composer paste affordances aligned with the currently effective model. // Keep composer paste affordances aligned with the currently effective model.
self.sync_image_paste_enabled(); self.sync_image_paste_enabled();
+2
View File
@@ -276,6 +276,8 @@ mod review_mode;
mod session_model_selection_tests; mod session_model_selection_tests;
mod side; mod side;
mod slash_commands; mod slash_commands;
#[path = "tests/sparkle_submission_tests.rs"]
mod sparkle_submission_tests;
mod status_and_layout; mod status_and_layout;
mod status_command_tests; mod status_command_tests;
mod status_surface_previews; mod status_surface_previews;
@@ -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] #[tokio::test]
async fn session_model_selection_hides_conflicting_shortcut() { async fn session_model_selection_hides_conflicting_shortcut() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.5")).await; let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.5")).await;
@@ -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);
}
}
@@ -74,6 +74,7 @@ impl ChatWidget {
// Raw reasoning uses the same flow as summarized reasoning // Raw reasoning uses the same flow as summarized reasoning
pub(super) fn on_task_started(&mut self) { pub(super) fn on_task_started(&mut self) {
self.bottom_pane.dismiss_composer_sparkle();
self.clear_context_compaction(); self.clear_context_compaction();
self.input_queue.user_turn_pending_start = false; self.input_queue.user_turn_pending_start = false;
self.reset_safety_buffering_for_turn_start(); self.reset_safety_buffering_for_turn_start();