Merge branch 'etraut/next-turn-state-core' into etraut/next-turn-state-app-server

# Conflicts:
#	codex-rs/app-server-protocol/src/protocol/common.rs
#	codex-rs/app-server-protocol/src/protocol/v2/thread.rs
#	codex-rs/app-server/src/request_processors/turn_processor.rs
This commit is contained in:
Eric Traut
2026-05-18 19:26:52 -07:00
285 changed files with 11488 additions and 3987 deletions
+71 -30
View File
@@ -410,17 +410,18 @@ fn session_summary(
rollout_path: Option<&Path>,
) -> Option<SessionSummary> {
let usage_line = (!token_usage.is_zero()).then(|| token_usage.to_string());
let thread_id =
resumable_thread(thread_id, thread_name, rollout_path).map(|thread| thread.thread_id);
let resume_command = codex_utils_cli::resume_command(/*thread_name*/ None, thread_id);
let resumable_thread = resumable_thread(thread_id, thread_name, rollout_path);
let resume_hint = resumable_thread.as_ref().and_then(|thread| {
codex_utils_cli::resume_hint(thread.thread_name.as_deref(), Some(thread.thread_id))
});
if usage_line.is_none() && resume_command.is_none() {
if usage_line.is_none() && resume_hint.is_none() {
return None;
}
Some(SessionSummary {
usage_line,
resume_command,
resume_hint,
})
}
@@ -459,7 +460,7 @@ fn errors_for_cwd(cwd: &Path, response: &SkillsListResponse) -> Vec<SkillErrorIn
#[derive(Debug, Clone, PartialEq, Eq)]
struct SessionSummary {
usage_line: Option<String>,
resume_command: Option<String>,
resume_hint: Option<String>,
}
#[derive(Debug, Default)]
@@ -660,6 +661,7 @@ impl App {
startup_hooks_browser: Option<HooksListEntry>,
) -> Result<AppExitInfo> {
use tokio_stream::StreamExt;
let startup_started_at = Instant::now();
let (app_event_tx, mut app_event_rx) = unbounded_channel();
let app_event_tx = AppEventSender::new(app_event_tx);
emit_project_config_warnings(&app_event_tx, &config);
@@ -703,7 +705,9 @@ impl App {
});
}
};
let bootstrap_started_at = Instant::now();
let bootstrap = app_server.bootstrap(&config).await?;
let bootstrap_ms = bootstrap_started_at.elapsed().as_millis();
let mut model = bootstrap.default_model;
let available_models = bootstrap.available_models;
let exit_info = handle_model_migration_prompt_if_needed(
@@ -760,8 +764,10 @@ impl App {
let workspace_command_runner: WorkspaceCommandRunner = Arc::new(
AppServerWorkspaceCommandRunner::new(app_server.request_handle()),
);
let runtime_model_provider_started_at = Instant::now();
let runtime_model_provider_base_url =
resolve_runtime_model_provider_base_url(&config.model_provider).await;
let runtime_model_provider_ms = runtime_model_provider_started_at.elapsed().as_millis();
let enhanced_keys_supported = tui.enhanced_keys_supported();
let wait_for_initial_session_configured =
@@ -772,6 +778,7 @@ impl App {
&initial_prompt,
&initial_images,
);
let thread_and_widget_started_at = Instant::now();
let (mut chat_widget, initial_started_thread) = match session_selection {
SessionSelection::StartFresh | SessionSelection::Exit => {
let started = app_server.start_thread(&config).await?;
@@ -888,6 +895,7 @@ impl App {
(ChatWidget::new_with_app_event(init), Some(forked))
}
};
let thread_and_widget_ms = thread_and_widget_started_at.elapsed().as_millis();
if let Some(message) = external_agent_config_migration_message {
chat_widget.add_info_message(message, /*hint*/ None);
}
@@ -958,6 +966,7 @@ See the Codex keymap documentation for supported actions and examples."
if let Some(entry) = startup_hooks_browser {
app.chat_widget.open_hooks_browser(entry);
}
let initial_session_started_at = Instant::now();
if let Some(started) = initial_started_thread {
let thread_id = started.session.thread_id;
app.enqueue_primary_thread_session(started.session, started.turns)
@@ -967,6 +976,7 @@ See the Codex keymap documentation for supported actions and examples."
.await;
}
}
let initial_session_ms = initial_session_started_at.elapsed().as_millis();
// On startup, if a managed filesystem sandbox is active, warn about
// world-writable dirs on Windows.
@@ -996,10 +1006,20 @@ See the Codex keymap documentation for supported actions and examples."
}
}
let event_stream_started_at = Instant::now();
let tui_events = tui.event_stream();
tokio::pin!(tui_events);
tui.frame_requester().schedule_frame();
tracing::info!(
duration_ms = %startup_started_at.elapsed().as_millis(),
bootstrap_ms = %bootstrap_ms,
runtime_model_provider_ms = %runtime_model_provider_ms,
thread_and_widget_ms = %thread_and_widget_ms,
initial_session_ms = %initial_session_ms,
event_stream_ms = %event_stream_started_at.elapsed().as_millis(),
"tui startup initial frame scheduled"
);
app.refresh_startup_skills(&app_server);
// Kick off a non-blocking rate-limit prefetch so the first `/status`
// already has data, without delaying the initial frame render.
@@ -1176,30 +1196,8 @@ See the Codex keymap documentation for supported actions and examples."
}
// Allow widgets to process any pending timers before rendering.
self.chat_widget.pre_draw_tick();
let desired_height =
self.chat_widget.desired_height(tui.terminal.size()?.width);
let mut rendered_area = Rect::default();
if terminal_resize_reflow_enabled {
tui.draw_with_resize_reflow(desired_height, |frame| {
let area = frame.area();
rendered_area = area;
self.chat_widget.render(area, frame.buffer);
if let Some((x, y)) = self.chat_widget.cursor_pos(area) {
frame.set_cursor_style(self.chat_widget.cursor_style(area));
frame.set_cursor_position((x, y));
}
})?;
} else {
tui.draw(desired_height, |frame| {
let area = frame.area();
rendered_area = area;
self.chat_widget.render(area, frame.buffer);
if let Some((x, y)) = self.chat_widget.cursor_pos(area) {
frame.set_cursor_style(self.chat_widget.cursor_style(area));
frame.set_cursor_position((x, y));
}
})?;
}
let rendered_area =
self.render_chat_widget_frame(tui, terminal_resize_reflow_enabled)?;
if self.chat_widget.ambient_pet_image_enabled() {
let terminal_size = tui.terminal.size()?;
let ambient_pet_area = Rect::new(
@@ -1234,6 +1232,49 @@ See the Codex keymap documentation for supported actions and examples."
}
Ok(AppRunControl::Continue)
}
pub(super) fn show_shutdown_feedback(&mut self, tui: &mut tui::Tui) -> Result<()> {
self.disable_ambient_pet_before_shutdown(tui)?;
self.chat_widget.show_shutdown_in_progress();
let terminal_resize_reflow_enabled = self.terminal_resize_reflow_enabled();
if terminal_resize_reflow_enabled {
self.handle_draw_pre_render(tui)?;
}
self.chat_widget.pre_draw_tick();
self.render_chat_widget_frame(tui, terminal_resize_reflow_enabled)?;
Ok(())
}
fn render_chat_widget_frame(
&mut self,
tui: &mut tui::Tui,
terminal_resize_reflow_enabled: bool,
) -> Result<Rect> {
let desired_height = self.chat_widget.desired_height(tui.terminal.size()?.width);
let mut rendered_area = Rect::default();
if terminal_resize_reflow_enabled {
tui.draw_with_resize_reflow(desired_height, |frame| {
let area = frame.area();
rendered_area = area;
self.chat_widget.render(area, frame.buffer);
if let Some((x, y)) = self.chat_widget.cursor_pos(area) {
frame.set_cursor_style(self.chat_widget.cursor_style(area));
frame.set_cursor_position((x, y));
}
})?;
} else {
tui.draw(desired_height, |frame| {
let area = frame.area();
rendered_area = area;
self.chat_widget.render(area, frame.buffer);
if let Some((x, y)) = self.chat_widget.cursor_pos(area) {
frame.set_cursor_style(self.chat_widget.cursor_style(area));
frame.set_cursor_position((x, y));
}
})?;
}
Ok(rendered_area)
}
}
impl Drop for App {
+8 -2
View File
@@ -152,7 +152,7 @@ impl App {
if let Some(usage_line) = summary.usage_line {
lines.push(usage_line.into());
}
if let Some(command) = summary.resume_command {
if let Some(command) = summary.resume_hint {
let spans = vec![
"To continue this session, run ".into(),
command.cyan(),
@@ -296,10 +296,14 @@ impl App {
self.chat_widget.on_commit_tick();
}
AppEvent::Exit(mode) => {
if mode == ExitMode::ShutdownFirst {
self.show_shutdown_feedback(tui)?;
}
return Ok(self.handle_exit_mode(app_server, mode).await);
}
AppEvent::Logout => match app_server.logout_account().await {
Ok(()) => {
self.show_shutdown_feedback(tui)?;
return Ok(self
.handle_exit_mode(app_server, ExitMode::ShutdownFirst)
.await);
@@ -1303,8 +1307,10 @@ impl App {
}
AppEvent::PersistServiceTierSelection { service_tier } => {
self.refresh_status_line();
let profile = self.active_profile.as_deref();
self.config.service_tier = service_tier.clone();
self.sync_active_thread_service_tier_to_cached_session()
.await;
let profile = self.active_profile.as_deref();
let edits = crate::config_update::build_service_tier_selection_edits(
profile,
service_tier.as_deref(),
+16
View File
@@ -3,6 +3,22 @@
use super::*;
impl App {
pub(super) fn disable_ambient_pet_before_shutdown(&mut self, tui: &mut tui::Tui) -> Result<()> {
self.chat_widget.disable_ambient_pet_for_session();
if let Err(clear_err) = tui.clear_ambient_pet_image() {
match clear_err {
crate::pets::PetImageRenderError::Terminal(err) => return Err(err.into()),
crate::pets::PetImageRenderError::Asset(err) => {
tracing::warn!(
error = %err,
"failed to clear ambient pet image before shutdown feedback"
);
}
}
}
Ok(())
}
pub(super) fn handle_ambient_pet_image_render_error(
&mut self,
tui: &mut tui::Tui,
+2 -2
View File
@@ -473,7 +473,7 @@ impl App {
if let Some(usage_line) = summary.usage_line {
lines.push(usage_line.into());
}
if let Some(command) = summary.resume_command {
if let Some(command) = summary.resume_hint {
let spans = vec!["To continue this session, run ".into(), command.cyan()];
lines.push(spans.into());
}
@@ -701,7 +701,7 @@ impl App {
if let Some(usage_line) = summary.usage_line {
lines.push(usage_line.into());
}
if let Some(command) = summary.resume_command {
if let Some(command) = summary.resume_hint {
let spans =
vec!["To continue this session, run ".into(), command.cyan()];
lines.push(spans.into());
@@ -57,13 +57,13 @@ async fn session_summary_includes_resume_hint_for_persisted_rollout() {
Some("Token usage: total=12 input=10 output=2".to_string())
);
assert_eq!(
summary.resume_command,
summary.resume_hint,
Some("codex resume 123e4567-e89b-12d3-a456-426614174000".to_string())
);
}
#[tokio::test]
async fn session_summary_uses_id_even_when_thread_has_name() {
async fn session_summary_names_picker_item_when_thread_has_name() {
let usage = TokenUsage {
input_tokens: 10,
output_tokens: 2,
@@ -83,7 +83,10 @@ async fn session_summary_uses_id_even_when_thread_has_name() {
)
.expect("summary");
assert_eq!(
summary.resume_command,
Some("codex resume 123e4567-e89b-12d3-a456-426614174000".to_string())
summary.resume_hint,
Some(
"codex resume, then select my-session (123e4567-e89b-12d3-a456-426614174000)"
.to_string()
)
);
}
+4 -1
View File
@@ -63,7 +63,10 @@ impl App {
let Some(goal) = response.goal else {
return;
};
if goal.status == ThreadGoalStatus::Paused {
if matches!(
goal.status,
ThreadGoalStatus::Paused | ThreadGoalStatus::Blocked | ThreadGoalStatus::UsageLimited
) {
self.chat_widget
.show_resume_paused_goal_prompt(thread_id, goal.objective);
}
@@ -8,6 +8,30 @@ use codex_protocol::models::ActivePermissionProfile;
use codex_protocol::models::PermissionProfile;
impl App {
pub(super) async fn sync_active_thread_service_tier_to_cached_session(&mut self) {
let Some(active_thread_id) = self.active_thread_id else {
return;
};
let service_tier = self.chat_widget.current_service_tier().map(str::to_string);
let update_session = |session: &mut ThreadSessionState| {
session.service_tier = service_tier.clone();
};
if self.primary_thread_id == Some(active_thread_id)
&& let Some(session) = self.primary_session_configured.as_mut()
{
update_session(session);
}
if let Some(channel) = self.thread_event_channels.get(&active_thread_id) {
let mut store = channel.store.lock().await;
if let Some(session) = store.session.as_mut() {
update_session(session);
}
}
}
pub(super) async fn sync_active_thread_permission_settings_to_cached_session(&mut self) {
let Some(active_thread_id) = self.active_thread_id else {
return;
@@ -125,6 +149,7 @@ mod tests {
use crate::test_support::test_path_buf;
use codex_app_server_protocol::AskForApproval;
use codex_config::types::ApprovalsReviewer;
use codex_protocol::config_types::ServiceTier;
use codex_protocol::models::BUILT_IN_PERMISSION_PROFILE_WORKSPACE;
use codex_protocol::models::ManagedFileSystemPermissions;
use codex_protocol::models::PermissionProfile;
@@ -316,6 +341,50 @@ mod tests {
assert_eq!(store_session, Some(expected_session));
}
#[tokio::test]
async fn service_tier_sync_updates_active_cached_session() {
let mut app = make_test_app().await;
let thread_id =
ThreadId::from_string("00000000-0000-0000-0000-000000000406").expect("valid thread");
let session = ThreadSessionState {
service_tier: Some(ServiceTier::Fast.request_value().to_string()),
..test_thread_session(thread_id, test_path_buf("/tmp/main"))
};
app.primary_thread_id = Some(thread_id);
app.active_thread_id = Some(thread_id);
app.primary_session_configured = Some(session.clone());
app.thread_event_channels.insert(
thread_id,
ThreadEventChannel::new_with_session(/*capacity*/ 4, session.clone(), Vec::new()),
);
app.chat_widget.handle_thread_session(session);
app.chat_widget.set_service_tier(/*service_tier*/ None);
app.sync_active_thread_service_tier_to_cached_session()
.await;
let expected_session = ThreadSessionState {
service_tier: None,
..test_thread_session(thread_id, test_path_buf("/tmp/main"))
};
assert_eq!(
app.primary_session_configured,
Some(expected_session.clone())
);
let store_session = app
.thread_event_channels
.get(&thread_id)
.expect("thread channel")
.store
.lock()
.await
.session
.clone();
assert_eq!(store_session, Some(expected_session));
}
#[tokio::test]
async fn thread_read_fallback_uses_active_permission_settings() {
let mut app = make_test_app().await;
+10 -15
View File
@@ -34,7 +34,6 @@ use codex_app_server_protocol::MemoryResetResponse;
use codex_app_server_protocol::Model as ApiModel;
use codex_app_server_protocol::ModelListParams;
use codex_app_server_protocol::ModelListResponse;
use codex_app_server_protocol::PermissionProfileSelectionParams;
use codex_app_server_protocol::RateLimitSnapshot;
use codex_app_server_protocol::RequestId;
use codex_app_server_protocol::ReviewDelivery;
@@ -1182,10 +1181,8 @@ fn sandbox_mode_from_permission_profile(
}
}
fn permissions_selection_from_active_profile(
active: ActivePermissionProfile,
) -> PermissionProfileSelectionParams {
PermissionProfileSelectionParams::new(active.id)
fn permission_profile_id_from_active_profile(active: ActivePermissionProfile) -> String {
active.id
}
fn turn_permissions_overrides(
@@ -1193,13 +1190,13 @@ fn turn_permissions_overrides(
cwd: &std::path::Path,
) -> (
Option<codex_app_server_protocol::SandboxPolicy>,
Option<PermissionProfileSelectionParams>,
Option<String>,
) {
match permissions_override {
TurnPermissionsOverride::Preserve => (None, None),
TurnPermissionsOverride::ActiveProfile(active_permission_profile) => (
None,
Some(permissions_selection_from_active_profile(
Some(permission_profile_id_from_active_profile(
active_permission_profile,
)),
),
@@ -1220,7 +1217,7 @@ fn turn_permissions_overrides(
fn permissions_selection_from_config(
config: &Config,
thread_params_mode: ThreadParamsMode,
) -> Option<PermissionProfileSelectionParams> {
) -> Option<String> {
if matches!(thread_params_mode, ThreadParamsMode::Remote) {
return None;
}
@@ -1228,7 +1225,7 @@ fn permissions_selection_from_config(
config
.permissions
.active_permission_profile()
.map(permissions_selection_from_active_profile)
.map(permission_profile_id_from_active_profile)
}
fn thread_start_params_from_config(
@@ -1671,7 +1668,7 @@ mod tests {
config
.permissions
.active_permission_profile()
.map(permissions_selection_from_active_profile)
.map(permission_profile_id_from_active_profile)
);
assert_eq!(params.model_provider, Some(config.model_provider_id));
assert_eq!(params.thread_source, Some(ThreadSource::User));
@@ -1698,7 +1695,7 @@ mod tests {
let active_permission_profile =
ActivePermissionProfile::new(BUILT_IN_PERMISSION_PROFILE_WORKSPACE);
let expected_permissions =
permissions_selection_from_active_profile(active_permission_profile.clone());
permission_profile_id_from_active_profile(active_permission_profile.clone());
let (sandbox_policy, permissions) = turn_permissions_overrides(
TurnPermissionsOverride::ActiveProfile(active_permission_profile),
@@ -1723,9 +1720,7 @@ mod tests {
assert_eq!(sandbox_policy, None);
assert_eq!(
permissions,
Some(PermissionProfileSelectionParams::new(
BUILT_IN_PERMISSION_PROFILE_WORKSPACE
))
Some(BUILT_IN_PERMISSION_PROFILE_WORKSPACE.to_string())
);
}
@@ -1763,7 +1758,7 @@ mod tests {
let cwd = test_path_buf("/workspace/project").abs();
let active_permission_profile = ActivePermissionProfile::new("strict");
let expected_permissions =
permissions_selection_from_active_profile(active_permission_profile.clone());
permission_profile_id_from_active_profile(active_permission_profile.clone());
let (sandbox_policy, permissions) = turn_permissions_overrides(
TurnPermissionsOverride::ActiveProfile(active_permission_profile),
+75 -27
View File
@@ -4130,6 +4130,15 @@ impl ChatComposer {
}
}
pub(crate) fn show_shutdown_in_progress(&mut self) {
self.set_input_enabled(/*enabled*/ false, Some("Shutting down...".to_string()));
self.footer.quit_shortcut_expires_at = None;
self.footer.mode = FooterMode::ComposerEmpty;
self.footer.hint_override = Some(Vec::new());
self.footer.plan_mode_nudge_visible = false;
self.footer.flash = None;
}
pub fn set_task_running(&mut self, running: bool) {
self.is_task_running = running;
}
@@ -4627,36 +4636,38 @@ impl ChatComposer {
let mut state = self.draft.textarea_state.borrow_mut();
let textarea_is_empty = self.draft.textarea.text().is_empty() && !self.draft.is_bash_mode;
if let Some(mask_char) = mask_char {
self.draft
.textarea
.render_ref_masked(textarea_rect, buf, &mut state, mask_char);
} else {
let highlight_ranges = self.history_search_highlight_ranges();
if highlight_ranges.is_empty() {
StatefulWidgetRef::render_ref(
&(&self.draft.textarea),
textarea_rect,
buf,
&mut state,
);
if self.draft.input_enabled {
if let Some(mask_char) = mask_char {
self.draft
.textarea
.render_ref_masked(textarea_rect, buf, &mut state, mask_char);
} else {
let highlight_style =
Style::default().add_modifier(Modifier::REVERSED | Modifier::BOLD);
let highlights = highlight_ranges
.into_iter()
.map(|range| (range, highlight_style))
.collect::<Vec<_>>();
self.draft.textarea.render_ref_styled_with_highlights(
textarea_rect,
buf,
&mut state,
Style::default(),
&highlights,
);
let highlight_ranges = self.history_search_highlight_ranges();
if highlight_ranges.is_empty() {
StatefulWidgetRef::render_ref(
&(&self.draft.textarea),
textarea_rect,
buf,
&mut state,
);
} else {
let highlight_style =
Style::default().add_modifier(Modifier::REVERSED | Modifier::BOLD);
let highlights = highlight_ranges
.into_iter()
.map(|range| (range, highlight_style))
.collect::<Vec<_>>();
self.draft.textarea.render_ref_styled_with_highlights(
textarea_rect,
buf,
&mut state,
Style::default(),
&highlights,
);
}
}
}
if textarea_is_empty {
if !self.draft.input_enabled || textarea_is_empty {
let text = if self.draft.input_enabled {
self.placeholder_text.as_str().to_string()
} else {
@@ -10684,4 +10695,41 @@ mod tests {
};
assert_eq!(composer.cursor_pos(area), None);
}
#[test]
fn shutdown_in_progress_disables_input_and_uses_hint_without_footer() {
use ratatui::Terminal;
use ratatui::backend::TestBackend;
let (tx, _rx) = unbounded_channel::<AppEvent>();
let sender = AppEventSender::new(tx);
let mut composer = ChatComposer::new(
/*has_input_focus*/ true,
sender,
/*enhanced_keys_supported*/ false,
"Ask Codex to do anything".to_string(),
/*disable_paste_burst*/ false,
);
composer.set_text_content("hello".to_string(), Vec::new(), Vec::new());
composer.show_shutdown_in_progress();
assert!(!composer.input_enabled());
assert_eq!(composer.current_text(), "hello");
assert_eq!(composer.custom_footer_height(), Some(0));
let area = Rect {
x: 0,
y: 0,
width: 40,
height: 5,
};
assert_eq!(composer.cursor_pos(area), None);
let mut terminal = Terminal::new(TestBackend::new(40, 5)).expect("terminal");
terminal
.draw(|f| composer.render(f.area(), f.buffer_mut()))
.unwrap();
insta::assert_snapshot!("shutdown_in_progress", terminal.backend());
}
}
+4
View File
@@ -98,6 +98,8 @@ pub(crate) enum CollaborationModeIndicator {
pub(crate) enum GoalStatusIndicator {
Active { usage: Option<String> },
Paused,
Blocked,
UsageLimited,
BudgetLimited { usage: Option<String> },
Complete { usage: Option<String> },
}
@@ -547,6 +549,8 @@ pub(crate) fn goal_status_indicator_line(
}
}
GoalStatusIndicator::Paused => "Goal paused (/goal resume)".to_string(),
GoalStatusIndicator::Blocked => "Goal blocked (/goal resume)".to_string(),
GoalStatusIndicator::UsageLimited => "Goal hit usage limits (/goal resume)".to_string(),
GoalStatusIndicator::BudgetLimited { usage } => {
if let Some(usage) = usage {
format!("Goal unmet ({usage})")
+6
View File
@@ -789,6 +789,12 @@ impl BottomPane {
self.request_redraw();
}
pub(crate) fn show_shutdown_in_progress(&mut self) {
self.view_stack.clear();
self.composer.show_shutdown_in_progress();
self.request_redraw();
}
pub(crate) fn clear_composer_for_ctrl_c(&mut self) {
if let Some(text) = self.composer.clear_for_ctrl_c() {
if let Some(thread_id) = self.thread_id {
@@ -0,0 +1,9 @@
---
source: tui/src/bottom_pane/chat_composer.rs
expression: terminal.backend()
---
" "
"› Shutting down... "
" "
" "
" "
+10 -8
View File
@@ -166,7 +166,7 @@ use codex_terminal_detection::TerminalInfo;
use codex_terminal_detection::TerminalName;
use codex_terminal_detection::terminal_info;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_cli::resume_command;
use codex_utils_cli::resume_hint;
use crossterm::event::KeyCode;
use crossterm::event::KeyEvent;
use crossterm::event::KeyEventKind;
@@ -1277,6 +1277,10 @@ impl ChatWidget {
.send(AppEvent::Exit(ExitMode::ShutdownFirst));
}
pub(crate) fn show_shutdown_in_progress(&mut self) {
self.bottom_pane.show_shutdown_in_progress();
}
fn request_redraw(&mut self) {
self.frame_requester.schedule_frame();
}
@@ -1436,16 +1440,14 @@ impl ChatWidget {
}
fn rename_confirmation_cell(name: &str, thread_id: Option<ThreadId>) -> PlainHistoryCell {
let resume_cmd =
resume_command(Some(name), thread_id).unwrap_or_else(|| format!("codex resume {name}"));
let name = name.to_string();
let line = vec![
let mut line = vec![
"• ".into(),
"Thread renamed to ".into(),
name.cyan(),
", to resume this thread run ".into(),
resume_cmd.cyan(),
name.to_string().cyan(),
];
if let Some(hint) = resume_hint(Some(name), thread_id) {
line.extend([". To resume this thread run ".into(), hint.cyan()]);
}
PlainHistoryCell::new(vec![line.into()])
}
+8 -2
View File
@@ -103,7 +103,9 @@ fn goal_summary_lines(goal: &AppThreadGoal) -> Vec<Line<'static>> {
}
let command_hint = match goal.status {
AppThreadGoalStatus::Active => "Commands: /goal edit, /goal pause, /goal clear",
AppThreadGoalStatus::Paused => "Commands: /goal edit, /goal resume, /goal clear",
AppThreadGoalStatus::Paused
| AppThreadGoalStatus::Blocked
| AppThreadGoalStatus::UsageLimited => "Commands: /goal edit, /goal resume, /goal clear",
AppThreadGoalStatus::BudgetLimited | AppThreadGoalStatus::Complete => {
"Commands: /goal edit, /goal clear"
}
@@ -117,6 +119,8 @@ fn goal_status_label(status: AppThreadGoalStatus) -> &'static str {
match status {
AppThreadGoalStatus::Active => "active",
AppThreadGoalStatus::Paused => "paused",
AppThreadGoalStatus::Blocked => "blocked",
AppThreadGoalStatus::UsageLimited => "usage limited",
AppThreadGoalStatus::BudgetLimited => "limited by budget",
AppThreadGoalStatus::Complete => "complete",
}
@@ -125,7 +129,9 @@ fn goal_status_label(status: AppThreadGoalStatus) -> &'static str {
fn edited_goal_status(status: AppThreadGoalStatus) -> AppThreadGoalStatus {
match status {
AppThreadGoalStatus::Active => AppThreadGoalStatus::Active,
AppThreadGoalStatus::Paused => AppThreadGoalStatus::Paused,
AppThreadGoalStatus::Paused
| AppThreadGoalStatus::Blocked
| AppThreadGoalStatus::UsageLimited => status,
AppThreadGoalStatus::BudgetLimited | AppThreadGoalStatus::Complete => {
AppThreadGoalStatus::Active
}
@@ -50,6 +50,8 @@ pub(super) fn goal_status_indicator_from_app_goal(
usage: active_goal_usage(goal.token_budget, goal.tokens_used, goal.time_used_seconds),
}),
AppThreadGoalStatus::Paused => Some(GoalStatusIndicator::Paused),
AppThreadGoalStatus::Blocked => Some(GoalStatusIndicator::Blocked),
AppThreadGoalStatus::UsageLimited => Some(GoalStatusIndicator::UsageLimited),
AppThreadGoalStatus::BudgetLimited => Some(GoalStatusIndicator::BudgetLimited {
usage: stopped_goal_budget_usage(goal.token_budget, goal.tokens_used),
}),
@@ -375,6 +375,7 @@ impl ChatWidget {
self.quit_shortcut_expires_at = None;
self.quit_shortcut_key = None;
self.bottom_pane.clear_quit_shortcut_hint();
self.pause_active_goal_for_interrupt();
self.submit_op(AppCommand::interrupt());
} else {
self.request_quit_without_confirmation();
@@ -392,6 +393,7 @@ impl ChatWidget {
self.arm_quit_shortcut(key);
if self.is_cancellable_work_active() {
self.pause_active_goal_for_interrupt();
self.submit_op(AppCommand::interrupt());
}
}
@@ -452,4 +454,24 @@ impl ChatWidget {
fn is_cancellable_work_active(&self) -> bool {
self.bottom_pane.is_task_running() || self.review.is_review_mode
}
fn pause_active_goal_for_interrupt(&self) {
if !self.turn_lifecycle.agent_turn_running {
return;
}
if !self
.current_goal_status
.as_ref()
.is_some_and(GoalStatusState::is_active)
{
return;
}
let Some(thread_id) = self.thread_id else {
return;
};
self.app_event_tx.send(AppEvent::SetThreadGoalStatus {
thread_id,
status: AppThreadGoalStatus::Paused,
});
}
}
+4
View File
@@ -133,6 +133,10 @@ impl ChatWidget {
..
} => {}
item @ ThreadItem::FileChange { .. } => self.on_file_change_completed(item),
item @ ThreadItem::McpToolCall {
status: codex_app_server_protocol::McpToolCallStatus::InProgress,
..
} => self.on_mcp_tool_call_started(item),
item @ ThreadItem::McpToolCall { .. } => self.on_mcp_tool_call_completed(item),
ThreadItem::WebSearch { id, query, action } => {
self.on_web_search_begin(id.clone());
@@ -0,0 +1,11 @@
---
source: tui/src/chatwidget/tests/goal_menu.rs
expression: rendered_goal_summary(&mut rx)
---
Goal
Status: blocked
Objective: Keep improving the bare goal command until it feels calm and useful.
Time used: 1m
Tokens used: 12.5K
Commands: /goal edit, /goal resume, /goal clear
@@ -0,0 +1,11 @@
---
source: tui/src/chatwidget/tests/goal_menu.rs
expression: rendered_goal_summary(&mut rx)
---
Goal
Status: usage limited
Objective: Keep improving the bare goal command until it feels calm and useful.
Time used: 1m
Tokens used: 12.5K
Commands: /goal edit, /goal resume, /goal clear
@@ -0,0 +1,5 @@
---
source: tui/src/chatwidget/tests/app_server.rs
expression: rendered
---
• Thread renamed to review-fix. To resume this thread run codex resume, then select review-fix (123e4567-e89b-12d3-a456-426614174000)
@@ -4,13 +4,14 @@ use pretty_assertions::assert_eq;
#[tokio::test]
async fn invalid_url_elicitation_is_declined() {
let (mut chat, _app_event_tx, mut rx, _op_rx) = make_chatwidget_manual_with_sender().await;
let thread_id = ThreadId::new();
chat.thread_id = Some(thread_id);
let visible_thread_id = ThreadId::new();
let request_thread_id = ThreadId::new();
chat.thread_id = Some(visible_thread_id);
chat.handle_elicitation_request_now(
codex_app_server_protocol::RequestId::Integer(9),
codex_app_server_protocol::McpServerElicitationRequestParams {
thread_id: thread_id.to_string(),
thread_id: request_thread_id.to_string(),
turn_id: Some("turn-auth".to_string()),
server_name: "payments".to_string(),
request: codex_app_server_protocol::McpServerElicitationRequest::Url {
@@ -33,7 +34,7 @@ async fn invalid_url_elicitation_is_declined() {
content: None,
meta: None,
},
}) if op_thread_id == thread_id && server_name == "payments"
}) if op_thread_id == request_thread_id && server_name == "payments"
);
}
@@ -636,6 +637,40 @@ async fn live_app_server_failed_turn_does_not_duplicate_error_history() {
assert!(!chat.bottom_pane.is_task_running());
}
#[tokio::test]
async fn live_app_server_failed_turn_consolidates_streamed_answer() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
handle_turn_started(&mut chat, "turn-1");
while rx.try_recv().is_ok() {}
handle_agent_message_delta(&mut chat, "```diff\n+ streamed patch\n```\n");
chat.run_commit_tick();
while rx.try_recv().is_ok() {}
handle_error(
&mut chat,
"stream disconnected before completion",
/*codex_error_info*/ None,
);
let mut saw_consolidate = false;
while let Ok(event) = rx.try_recv() {
if let AppEvent::ConsolidateAgentMessage { source, .. } = event {
saw_consolidate = true;
assert!(
source.contains("streamed patch"),
"expected partial stream source to be consolidated, got {source:?}"
);
}
}
assert!(
saw_consolidate,
"failed turn should consolidate streamed cells before clearing the stream controller"
);
}
#[tokio::test]
async fn live_app_server_stream_recovery_restores_previous_status_header() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
@@ -827,7 +862,8 @@ async fn live_app_server_invalid_thread_name_update_is_ignored() {
#[tokio::test]
async fn live_app_server_thread_name_update_shows_resume_hint() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
let thread_id = ThreadId::new();
let thread_id =
ThreadId::from_string("123e4567-e89b-12d3-a456-426614174000").expect("thread id");
chat.thread_id = Some(thread_id);
chat.handle_server_notification(
@@ -844,8 +880,7 @@ async fn live_app_server_thread_name_update_shows_resume_hint() {
let cells = drain_insert_history(&mut rx);
assert_eq!(cells.len(), 1);
let rendered = lines_to_single_string(&cells[0]);
assert!(rendered.contains("Thread renamed to review-fix"));
assert!(rendered.contains("codex resume review-fix"));
assert_chatwidget_snapshot!("thread_name_update_resume_hint", rendered);
}
#[tokio::test]
@@ -28,6 +28,34 @@ async fn goal_menu_paused_snapshot() {
assert_chatwidget_snapshot!("goal_menu_paused", rendered_goal_summary(&mut rx));
}
#[tokio::test]
async fn goal_menu_blocked_snapshot() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
let thread_id = ThreadId::new();
chat.show_goal_summary(test_goal(
thread_id,
AppThreadGoalStatus::Blocked,
/*token_budget*/ None,
));
assert_chatwidget_snapshot!("goal_menu_blocked", rendered_goal_summary(&mut rx));
}
#[tokio::test]
async fn goal_menu_usage_limited_snapshot() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
let thread_id = ThreadId::new();
chat.show_goal_summary(test_goal(
thread_id,
AppThreadGoalStatus::UsageLimited,
/*token_budget*/ None,
));
assert_chatwidget_snapshot!("goal_menu_usage_limited", rendered_goal_summary(&mut rx));
}
#[tokio::test]
async fn goal_menu_budget_limited_snapshot() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
@@ -117,6 +145,42 @@ async fn goal_edit_prompt_submits_preserved_status_and_budget() {
assert!(chat.no_modal_or_popup_active());
}
#[tokio::test]
async fn goal_edit_prompt_preserves_resumable_stopped_statuses() {
for stopped_status in [
AppThreadGoalStatus::Blocked,
AppThreadGoalStatus::UsageLimited,
] {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
let thread_id = ThreadId::new();
chat.show_goal_edit_prompt(
thread_id,
test_goal(
thread_id,
stopped_status,
/*token_budget*/ Some(80_000),
),
);
chat.handle_key_event(KeyEvent::from(KeyCode::Enter));
match rx.try_recv() {
Ok(AppEvent::SetThreadGoalObjective {
mode:
crate::app_event::ThreadGoalSetMode::UpdateExisting {
status,
token_budget,
},
..
}) => {
assert_eq!(status, stopped_status);
assert_eq!(token_budget, Some(80_000));
}
other => panic!("expected SetThreadGoalObjective event, got {other:?}"),
}
}
}
#[tokio::test]
async fn goal_edit_prompt_resets_terminal_status_to_active() {
let cases = [
@@ -826,6 +826,33 @@ async fn replayed_reasoning_item_shows_raw_reasoning_when_enabled() {
assert!(rendered.contains("Raw reasoning"));
}
#[tokio::test]
async fn replayed_in_progress_mcp_tool_call_stays_active() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
let _ = drain_insert_history(&mut rx);
chat.replay_thread_item(
AppServerThreadItem::McpToolCall {
id: "mcp-1".to_string(),
server: "copilot-bridge".to_string(),
tool: "copilot".to_string(),
status: codex_app_server_protocol::McpToolCallStatus::InProgress,
arguments: json!({"action": "wait"}),
mcp_app_resource_uri: None,
result: None,
error: None,
duration_ms: None,
},
"turn-1".to_string(),
ReplayKind::ThreadSnapshot,
);
assert!(drain_insert_history(&mut rx).is_empty());
let active = active_blob(&chat);
assert!(active.contains("Calling"));
assert!(!active.contains("MCP tool call completed without a result"));
}
#[tokio::test]
async fn live_reasoning_summary_is_not_rendered_twice_when_item_completes() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
@@ -15,6 +15,18 @@ fn force_tmux_pet_image_unsupported(chat: &mut ChatWidget) {
));
}
fn force_terminal_pet_image_unsupported(chat: &mut ChatWidget) {
chat.set_pet_image_support_for_tests(crate::pets::PetImageSupport::Unsupported(
crate::pets::PetImageUnsupportedReason::Terminal,
));
}
fn force_old_iterm2_pet_image_unsupported(chat: &mut ChatWidget) {
chat.set_pet_image_support_for_tests(crate::pets::PetImageSupport::Unsupported(
crate::pets::PetImageUnsupportedReason::Iterm2TooOld,
));
}
fn fast_tier_command() -> ServiceTierCommand {
ServiceTierCommand {
id: ServiceTier::Fast.request_value().to_string(),
@@ -1934,6 +1946,44 @@ async fn slash_pets_with_arg_on_unsupported_terminal_warns_without_selection() {
assert_matches!(op_rx.try_recv(), Err(TryRecvError::Empty));
}
#[tokio::test]
#[serial]
async fn slash_pets_on_unsupported_terminal_shows_terminal_warning() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
force_terminal_pet_image_unsupported(&mut chat);
chat.dispatch_command(SlashCommand::Pets);
assert!(!chat.bottom_pane.has_active_view());
let cells = drain_insert_history(&mut rx);
let rendered = cells
.iter()
.map(|lines| lines_to_single_string(lines))
.collect::<Vec<_>>()
.join("\n");
assert!(rendered.contains("Pets aren’t available in this terminal."));
assert!(rendered.contains("Kitty graphics or Sixel support"));
}
#[tokio::test]
#[serial]
async fn slash_pets_on_old_iterm2_shows_upgrade_warning() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
force_old_iterm2_pet_image_unsupported(&mut chat);
chat.dispatch_command(SlashCommand::Pets);
assert!(!chat.bottom_pane.has_active_view());
let cells = drain_insert_history(&mut rx);
let rendered = cells
.iter()
.map(|lines| lines_to_single_string(lines))
.collect::<Vec<_>>()
.join("\n");
assert!(rendered.contains("Pets require iTerm2 3.6 or newer."));
assert!(rendered.contains("Upgrade iTerm2 to use terminal pets."));
}
#[tokio::test]
async fn slash_fork_requests_current_fork() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
@@ -1136,6 +1136,45 @@ async fn streaming_final_answer_keeps_task_running_state() {
assert!(!chat.bottom_pane.quit_shortcut_hint_visible());
}
#[tokio::test]
async fn ctrl_c_interrupt_pauses_active_goal_turn() {
let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
let thread_id = ThreadId::new();
chat.set_feature_enabled(Feature::Goals, /*enabled*/ true);
chat.thread_id = Some(thread_id);
let mut goal = test_thread_goal(
codex_app_server_protocol::ThreadGoalStatus::Active,
/*token_budget*/ Some(50_000),
/*tokens_used*/ 40_000,
);
goal.thread_id = thread_id.to_string();
chat.handle_server_notification(
ServerNotification::ThreadGoalUpdated(
codex_app_server_protocol::ThreadGoalUpdatedNotification {
thread_id: thread_id.to_string(),
turn_id: None,
goal,
},
),
/*replay_kind*/ None,
);
chat.on_task_started();
chat.handle_key_event(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL));
match op_rx.try_recv() {
Ok(Op::Interrupt) => {}
other => panic!("expected Op::Interrupt, got {other:?}"),
}
assert_matches!(
rx.try_recv(),
Ok(AppEvent::SetThreadGoalStatus {
thread_id: event_thread_id,
status: AppThreadGoalStatus::Paused,
}) if event_thread_id == thread_id
);
}
#[tokio::test]
async fn idle_commit_ticks_do_not_restore_status_without_commentary_completion() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
@@ -2293,6 +2332,22 @@ fn goal_status_indicator_formats_statuses_and_budgets() {
usage: Some("30m".to_string()),
})
);
assert_eq!(
goal_status_indicator_from_app_goal(&test_thread_goal(
codex_app_server_protocol::ThreadGoalStatus::Blocked,
/*token_budget*/ None,
/*tokens_used*/ 0,
)),
Some(GoalStatusIndicator::Blocked)
);
assert_eq!(
goal_status_indicator_from_app_goal(&test_thread_goal(
codex_app_server_protocol::ThreadGoalStatus::UsageLimited,
/*token_budget*/ None,
/*tokens_used*/ 0,
)),
Some(GoalStatusIndicator::UsageLimited)
);
assert_eq!(
goal_status_indicator_from_app_goal(&test_thread_goal(
codex_app_server_protocol::ThreadGoalStatus::BudgetLimited,
@@ -2339,6 +2394,11 @@ fn goal_status_indicator_line_formats_goal_text() {
"Goal unmet (4K / 5K tokens)",
),
(GoalStatusIndicator::Paused, "Goal paused (/goal resume)"),
(GoalStatusIndicator::Blocked, "Goal blocked (/goal resume)"),
(
GoalStatusIndicator::UsageLimited,
"Goal hit usage limits (/goal resume)",
),
(
GoalStatusIndicator::BudgetLimited { usage: None },
"Goal abandoned",
+2 -1
View File
@@ -341,7 +341,8 @@ impl ChatWidget {
server_name: params.server_name.clone(),
});
let thread_id = self.thread_id.unwrap_or_default();
let thread_id = ThreadId::from_string(&params.thread_id)
.unwrap_or_else(|_| self.thread_id.unwrap_or_default());
if let Some(params) = crate::bottom_pane::AppLinkViewParams::from_url_app_server_request(
thread_id,
&params.server_name,
@@ -339,6 +339,7 @@ impl ChatWidget {
pub(super) fn on_error(&mut self, message: String) {
self.input_queue.submit_pending_steers_after_interrupt = false;
self.flush_answer_stream_with_separator();
self.finalize_turn();
self.add_to_history(history_cell::new_error_event(message));
self.set_ambient_pet_notification(
+2
View File
@@ -32,6 +32,8 @@ pub(crate) fn goal_status_label(status: ThreadGoalStatus) -> &'static str {
match status {
ThreadGoalStatus::Active => "active",
ThreadGoalStatus::Paused => "paused",
ThreadGoalStatus::Blocked => "blocked",
ThreadGoalStatus::UsageLimited => "usage limited",
ThreadGoalStatus::BudgetLimited => "limited by budget",
ThreadGoalStatus::Complete => "complete",
}
+6 -3
View File
@@ -1219,10 +1219,13 @@ async fn run_ratatui_app(
tracing::error!("panic: {info}");
prev_hook(info);
}));
let mut terminal = tui::init()?;
terminal.clear()?;
let mut initialized_terminal = tui::init()?;
initialized_terminal.terminal.clear()?;
let mut tui = Tui::new(terminal);
let mut tui = Tui::new(
initialized_terminal.terminal,
initialized_terminal.enhanced_keys_supported,
);
let mut terminal_restore_guard = TerminalRestoreGuard::new();
#[cfg(not(debug_assertions))]
+3 -2
View File
@@ -7,13 +7,14 @@ use codex_tui::Cli;
use codex_tui::ExitReason;
use codex_tui::run_main;
use codex_utils_cli::CliConfigOverrides;
use codex_utils_cli::resume_command;
use codex_utils_cli::resume_hint;
use supports_color::Stream;
fn format_exit_messages(exit_info: AppExitInfo, color_enabled: bool) -> Vec<String> {
let AppExitInfo {
token_usage,
thread_id,
thread_name,
..
} = exit_info;
@@ -22,7 +23,7 @@ fn format_exit_messages(exit_info: AppExitInfo, color_enabled: bool) -> Vec<Stri
lines.push(token_usage.to_string());
}
if let Some(resume_cmd) = resume_command(/*thread_name*/ None, thread_id) {
if let Some(resume_cmd) = resume_hint(thread_name.as_deref(), thread_id) {
let command = if color_enabled {
format!("\u{1b}[36m{resume_cmd}\u{1b}[39m")
} else {
+109 -3
View File
@@ -21,6 +21,7 @@ const ESC: &str = "\x1b";
const ST: &str = "\x1b\\";
const KITTY_CHUNK_SIZE: usize = 4096;
const SIXEL_CACHE_VERSION: &str = "v2";
const ITERM2_KITTY_MIN_VERSION: (u64, u64, u64) = (3, 6, 0);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ImageProtocol {
@@ -55,6 +56,7 @@ impl PetImageSupport {
pub(crate) enum PetImageUnsupportedReason {
Tmux,
Zellij,
Iterm2TooOld,
Terminal,
}
@@ -67,6 +69,9 @@ impl PetImageUnsupportedReason {
Self::Zellij => {
"Pets are disabled in Zellij. Terminal images don’t stay reliably pane-local in Zellij. Run Codex outside Zellij to use pets."
}
Self::Iterm2TooOld => {
"Pets require iTerm2 3.6 or newer. Upgrade iTerm2 to use terminal pets."
}
Self::Terminal => {
"Pets aren’t available in this terminal. Terminal pets need image support, and this terminal environment doesn’t expose a supported image protocol. Try a terminal with Kitty graphics or Sixel support, or run Codex outside tmux."
}
@@ -142,6 +147,10 @@ fn pet_image_support_for_terminal(info: &TerminalInfo) -> PetImageSupport {
return PetImageSupport::Supported(ImageProtocol::KittyLocalFile);
}
if is_iterm2_terminal(info) {
return PetImageSupport::Unsupported(PetImageUnsupportedReason::Iterm2TooOld);
}
if supports_kitty_graphics(info) {
return PetImageSupport::Supported(ImageProtocol::Kitty);
}
@@ -154,6 +163,14 @@ fn pet_image_support_for_terminal(info: &TerminalInfo) -> PetImageSupport {
}
fn supports_iterm2_kitty_graphics(info: &TerminalInfo) -> bool {
is_iterm2_terminal(info)
&& version_is_at_least(
info.version.as_deref(),
/*minimum*/ ITERM2_KITTY_MIN_VERSION,
)
}
fn is_iterm2_terminal(info: &TerminalInfo) -> bool {
matches!(info.name, TerminalName::Iterm2)
|| terminal_field_contains(info.term_program.as_deref(), "iterm")
}
@@ -181,6 +198,24 @@ fn terminal_field_contains(value: Option<&str>, needle: &str) -> bool {
value.is_some_and(|value| value.to_ascii_lowercase().contains(needle))
}
fn version_is_at_least(version: Option<&str>, minimum: (u64, u64, u64)) -> bool {
parse_dotted_version(version).is_some_and(|version| version >= minimum)
}
fn parse_dotted_version(version: Option<&str>) -> Option<(u64, u64, u64)> {
let version = version?;
let mut parts = version.split('.');
let major = parts.next()?.parse().ok()?;
let minor = parts.next().unwrap_or("0").parse().ok()?;
let patch = parts.next().unwrap_or("0").parse().ok()?;
if parts.next().is_some() {
return None;
}
Some((major, minor, patch))
}
pub fn kitty_delete_image(image_id: u32) -> String {
wrap_for_tmux_if_needed(&format!("{ESC}_Ga=d,d=I,i={image_id},q=2;{ST}"))
}
@@ -400,16 +435,18 @@ mod tests {
#[test]
fn pet_image_support_detects_iterm2_kitty_file_graphics() {
for info in [
terminal_info_for_test(
terminal_info_with_version_for_test(
TerminalName::Iterm2,
/*multiplexer*/ None,
Some("iTerm.app"),
Some("3.6.10"),
/*term*/ None,
),
terminal_info_for_test(
terminal_info_with_version_for_test(
TerminalName::Unknown,
/*multiplexer*/ None,
Some("iTerm.app"),
Some("3.6.10"),
Some("xterm-256color"),
),
] {
@@ -420,6 +457,49 @@ mod tests {
}
}
#[test]
fn pet_image_support_rejects_old_iterm2_versions() {
for info in [
terminal_info_with_version_for_test(
TerminalName::Iterm2,
/*multiplexer*/ None,
Some("iTerm.app"),
Some("3.5.14"),
/*term*/ None,
),
terminal_info_with_version_for_test(
TerminalName::Unknown,
/*multiplexer*/ None,
Some("iTerm.app"),
/*version*/ None,
Some("xterm-256color"),
),
terminal_info_with_version_for_test(
TerminalName::Iterm2,
/*multiplexer*/ None,
Some("iTerm.app"),
Some("3.5"),
/*term*/ None,
),
] {
assert_eq!(
pet_image_support_for_terminal(&info),
PetImageSupport::Unsupported(PetImageUnsupportedReason::Iterm2TooOld)
);
}
}
#[test]
fn pet_image_support_old_iterm2_message_mentions_upgrade() {
let message = PetImageSupport::Unsupported(PetImageUnsupportedReason::Iterm2TooOld)
.unsupported_message();
assert_eq!(
message,
Some("Pets require iTerm2 3.6 or newer. Upgrade iTerm2 to use terminal pets.")
);
}
#[test]
fn pet_image_support_detects_kitty_graphics_terminals() {
for info in [
@@ -538,16 +618,42 @@ mod tests {
multiplexer: Option<Multiplexer>,
term_program: Option<&str>,
term: Option<&str>,
) -> TerminalInfo {
terminal_info_with_version_for_test(
name,
multiplexer,
term_program,
/*version*/ None,
term,
)
}
fn terminal_info_with_version_for_test(
name: TerminalName,
multiplexer: Option<Multiplexer>,
term_program: Option<&str>,
version: Option<&str>,
term: Option<&str>,
) -> TerminalInfo {
TerminalInfo {
name,
term_program: term_program.map(str::to_string),
version: /*version*/ None,
version: version.map(str::to_string),
term: term.map(str::to_string),
multiplexer,
}
}
#[test]
fn parse_dotted_version_requires_simple_numeric_components() {
assert_eq!(parse_dotted_version(Some("3.6.10")), Some((3, 6, 10)));
assert_eq!(parse_dotted_version(Some("3.6")), Some((3, 6, 0)));
assert_eq!(parse_dotted_version(Some("3")), Some((3, 0, 0)));
assert_eq!(parse_dotted_version(Some("3.6.10.1")), None);
assert_eq!(parse_dotted_version(Some("3.6beta")), None);
assert_eq!(parse_dotted_version(/*version*/ None), None);
}
#[test]
fn sixel_frame_encodes_without_external_crate() {
let dir = tempfile::tempdir().unwrap();
+113 -8
View File
@@ -477,6 +477,9 @@ async fn run_session_picker_with_loader(
return Ok(sel);
}
}
TuiEvent::Paste(pasted) => {
state.handle_paste(pasted);
}
TuiEvent::Draw | TuiEvent::Resize => {
if let Ok(size) = alt.tui.terminal.size() {
let list_height =
@@ -489,7 +492,6 @@ async fn run_session_picker_with_loader(
state.open_pending_transcript_if_ready();
}
}
_ => {}
}
}
Some(event) = background_events.next() => {
@@ -543,6 +545,11 @@ fn picker_cwd_filter(
}
}
fn normalize_pasted_query(pasted: &str) -> Option<String> {
let normalized = pasted.split_whitespace().collect::<Vec<_>>().join(" ");
(!normalized.is_empty()).then_some(normalized)
}
fn spawn_app_server_page_loader(
app_server: AppServerSession,
include_non_interactive: bool,
@@ -1227,6 +1234,21 @@ impl PickerState {
Ok(None)
}
fn handle_paste(&mut self, pasted: String) {
if self.is_transcript_loading() {
return;
}
let Some(pasted) = normalize_pasted_query(&pasted) else {
return;
};
let mut new_query = self.query.clone();
if !new_query.is_empty() && !new_query.ends_with(char::is_whitespace) {
new_query.push(' ');
}
new_query.push_str(&pasted);
self.set_query(new_query);
}
fn start_initial_load(&mut self) {
self.relative_time_reference = Some(Utc::now());
self.reset_pagination();
@@ -2929,12 +2951,12 @@ fn render_expanded_session_details(
width: u16,
) -> Vec<Line<'static>> {
let reference = state.relative_time_reference.unwrap_or_else(Utc::now);
let session = row
.thread_name
.as_deref()
.map(str::to_string)
.or_else(|| row.thread_id.map(|thread_id| thread_id.to_string()))
.unwrap_or_else(|| "-".to_string());
let session = match (row.thread_name.as_deref(), row.thread_id) {
(Some(thread_name), Some(thread_id)) => format!("{thread_name} ({thread_id})"),
(Some(thread_name), None) => thread_name.to_string(),
(None, Some(thread_id)) => thread_id.to_string(),
(None, None) => "-".to_string(),
};
let directory = row
.cwd
.as_ref()
@@ -3387,7 +3409,9 @@ mod tests {
let expected_directory =
format_directory_display(row.cwd.as_deref().expect("cwd"), /*max_width*/ None);
assert!(rendered.contains("Session: feat(tui): add raw scrollback mode"));
assert!(rendered.contains(
"Session: feat(tui): add raw scrollback mode (019dabc1-0ef5-7431-b81c-03037f51f62c)"
));
assert!(rendered.contains("Created: 17 minutes ago · 2026-05-02 14:31:08"));
assert!(rendered.contains("Updated: now · 2026-05-02 14:48:19"));
assert!(rendered.contains(&format!("Directory: {expected_directory}")));
@@ -6216,6 +6240,87 @@ session_picker_view = "dense"
assert!(state.pagination.reached_scan_cap);
}
#[tokio::test]
async fn paste_appends_to_existing_query() {
let loader = page_only_loader(|_| {});
let mut state = PickerState::new(
FrameRequester::test_dummy(),
loader,
ProviderFilter::MatchDefault(String::from("openai")),
/*show_all*/ true,
/*filter_cwd*/ None,
SessionPickerAction::Resume,
);
state.query = String::from("resize");
state.handle_paste(String::from("results"));
assert_eq!(state.query, "resize results");
}
#[test]
fn normalize_pasted_query_collapses_whitespace() {
assert_eq!(
normalize_pasted_query(" alpha\n\tbeta\r\n gamma "),
Some(String::from("alpha beta gamma"))
);
}
#[tokio::test]
async fn whitespace_only_paste_is_ignored() {
let loader = page_only_loader(|_| {});
let mut state = PickerState::new(
FrameRequester::test_dummy(),
loader,
ProviderFilter::MatchDefault(String::from("openai")),
/*show_all*/ true,
/*filter_cwd*/ None,
SessionPickerAction::Resume,
);
state.query = String::from("resize");
state.handle_paste(String::from(" \n\t "));
assert_eq!(state.query, "resize");
}
#[tokio::test]
async fn paste_uses_existing_search_loading_path() {
let recorded_requests: Arc<Mutex<Vec<PageLoadRequest>>> = Arc::new(Mutex::new(Vec::new()));
let request_sink = recorded_requests.clone();
let loader = page_only_loader(move |req: PageLoadRequest| {
request_sink.lock().unwrap().push(req);
});
let mut state = PickerState::new(
FrameRequester::test_dummy(),
loader,
ProviderFilter::MatchDefault(String::from("openai")),
/*show_all*/ true,
/*filter_cwd*/ None,
SessionPickerAction::Resume,
);
state.reset_pagination();
state.ingest_page(page(
vec![make_row(
"/tmp/start.jsonl",
"2025-01-01T00:00:00Z",
"alpha",
)],
Some("2025-01-02T00:00:00Z"),
/*num_scanned_files*/ 1,
/*reached_scan_cap*/ false,
));
recorded_requests.lock().unwrap().clear();
state.handle_paste(String::from("target"));
let guard = recorded_requests.lock().unwrap();
assert_eq!(state.query, "target");
assert_eq!(guard.len(), 1);
assert!(guard[0].search_token.is_some());
}
#[tokio::test]
async fn esc_with_empty_query_starts_fresh() {
let loader = page_only_loader(|_| {});
+9 -2
View File
@@ -106,6 +106,7 @@ struct StatusHistoryCell {
agents_summary: Arc<RwLock<String>>,
collaboration_mode: Option<String>,
model_provider: Option<String>,
show_chatgpt_usage_link: bool,
account: Option<StatusAccountDisplay>,
thread_name: Option<String>,
session_id: Option<String>,
@@ -308,6 +309,7 @@ impl StatusHistoryCell {
workspace_root_suffix.as_deref(),
);
let model_provider = format_model_provider(config, runtime_model_provider_base_url);
let show_chatgpt_usage_link = config.model_provider.requires_openai_auth;
let account = compose_account_display(account_display);
let session_id = session_id.as_ref().map(std::string::ToString::to_string);
let forked_from = forked_from.map(|id| id.to_string());
@@ -347,6 +349,7 @@ impl StatusHistoryCell {
permissions,
collaboration_mode: collaboration_mode.map(ToString::to_string),
model_provider,
show_chatgpt_usage_link,
account,
thread_name,
session_id,
@@ -765,8 +768,12 @@ impl HistoryCell for StatusHistoryCell {
[note_first_line, note_second_line],
RtOptions::new(available_inner_width),
);
lines.extend(note_lines);
lines.push(Line::from(Vec::<Span<'static>>::new()));
// The ChatGPT usage page only applies to providers backed by OpenAI auth;
// providers like Bedrock manage limits and billing elsewhere.
if self.show_chatgpt_usage_link {
lines.extend(note_lines);
lines.push(Line::from(Vec::<Span<'static>>::new()));
}
let mut model_spans = vec![Span::from(self.model_name.clone())];
if !self.model_details.is_empty() {
+37 -1
View File
@@ -582,7 +582,7 @@ async fn status_snapshot_shows_active_user_defined_profile() {
}
#[tokio::test]
async fn status_model_provider_uses_bedrock_runtime_base_url() {
async fn status_model_provider_uses_bedrock_runtime_base_url_and_gates_usage_link() {
let temp_home = TempDir::new().expect("temp home");
let mut config = test_config(&temp_home).await;
config.model_provider_id = "amazon-bedrock".to_string();
@@ -629,6 +629,42 @@ async fn status_model_provider_uses_bedrock_runtime_base_url() {
!rendered.contains("bedrock-mantle.us-east-1"),
"expected /status to ignore configured Bedrock base URL, got: {rendered}"
);
assert!(
!rendered.contains("https://chatgpt.com/codex/settings/usage"),
"expected /status to hide ChatGPT usage link for Bedrock, got: {rendered}"
);
config.model_provider_id = "openai-proxy".to_string();
config.model_provider = ModelProviderInfo {
name: "OpenAI Proxy".to_string(),
base_url: Some("https://openai-proxy.example/v1".to_string()),
requires_openai_auth: true,
..ModelProviderInfo::default()
};
let (composite, _handle) = new_status_output_with_rate_limits_handle(
&config,
/*runtime_model_provider_base_url*/ None,
test_status_account_display().as_ref(),
/*token_info*/ None,
&usage,
&None,
/*thread_name*/ None,
/*forked_from*/ None,
/*rate_limits*/ &[],
None,
captured_at,
&model_slug,
/*collaboration_mode*/ None,
/*reasoning_effort_override*/ None,
"<none>".to_string(),
/*refreshing_rate_limits*/ false,
);
let rendered = render_lines(&composite.display_lines(/*width*/ 120)).join("\n");
assert!(
rendered.contains("https://chatgpt.com/codex/settings/usage"),
"expected /status to show ChatGPT usage link for OpenAI-auth proxy, got: {rendered}"
);
}
#[tokio::test]
+25
View File
@@ -68,6 +68,13 @@ pub fn default_bg() -> Option<(u8, u8, u8)> {
default_colors().map(|c| c.bg)
}
#[cfg(unix)]
pub(crate) fn set_default_colors_from_startup_probe(
colors: Option<crate::terminal_probe::DefaultColors>,
) {
imp::set_default_colors_from_startup_probe(colors);
}
#[cfg(all(unix, not(test)))]
mod imp {
use super::DefaultColors;
@@ -112,6 +119,18 @@ mod imp {
cache.get_or_init_with(query_default_colors)
}
pub(super) fn set_default_colors_from_startup_probe(
colors: Option<crate::terminal_probe::DefaultColors>,
) {
if let Ok(mut cache) = default_colors_cache().lock() {
cache.value = colors.map(|colors| DefaultColors {
fg: colors.fg,
bg: colors.bg,
});
cache.attempted = true;
}
}
pub(super) fn requery_default_colors() {
if let Ok(mut cache) = default_colors_cache().lock() {
// Don't try to refresh if the cache is already attempted and failed.
@@ -166,6 +185,12 @@ mod imp {
None
}
#[cfg(unix)]
pub(super) fn set_default_colors_from_startup_probe(
_colors: Option<crate::terminal_probe::DefaultColors>,
) {
}
pub(super) fn requery_default_colors() {}
}
+143 -47
View File
@@ -39,6 +39,21 @@ mod imp {
pub(crate) bg: (u8, u8, u8),
}
/// Results from the TUI's one-shot startup terminal probe.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub(crate) struct StartupProbe {
pub(crate) cursor_position: Option<Position>,
pub(crate) default_colors: Option<DefaultColors>,
pub(crate) keyboard_enhancement_supported: Option<bool>,
}
/// Whether the startup probe should query keyboard enhancement support.
#[derive(Clone, Copy, Eq, PartialEq)]
pub(crate) enum StartupKeyboardEnhancementProbe {
Query,
Skip,
}
/// Temporary terminal handle used while a startup probe owns terminal input.
///
/// The preferred path is duplicated stdin/stdout, because terminal replies are delivered to the
@@ -198,19 +213,6 @@ mod imp {
Ok(unsafe { File::from_raw_fd(duplicated) })
}
/// Queries the current cursor position and returns a zero-based Ratatui position.
///
/// A timeout or a non-CPR response is not fatal. Callers should treat `Ok(None)` as "terminal
/// did not answer this optional query" and choose a conservative fallback.
pub(crate) fn cursor_position(timeout: Duration) -> io::Result<Option<Position>> {
let mut tty = Tty::open()?;
tty.write_all(b"\x1B[6n")?;
let Some(response) = read_until(&mut tty, timeout, parse_cursor_position)? else {
return Ok(None);
};
Ok(Some(response))
}
/// Queries OSC 10 and OSC 11 default colors under one shared deadline.
///
/// Foreground and background are only useful as a pair for palette calculations, so a missing
@@ -226,16 +228,24 @@ mod imp {
Ok(Some(colors))
}
/// Checks whether the terminal reports support for keyboard enhancement flags.
/// Runs the optional terminal queries needed during TUI startup under one shared deadline.
///
/// The probe sends the kitty keyboard-status query followed by primary-device-attributes as a
/// fallback. A PDA response proves that the terminal answered but does not prove that keyboard
/// enhancement is unsupported until the bounded wait has expired; flags that arrive later in
/// the same deadline must still win.
pub(crate) fn keyboard_enhancement_supported(timeout: Duration) -> io::Result<Option<bool>> {
/// Keeping these queries batched avoids paying one timeout per unsupported capability before
/// the first frame can render.
pub(crate) fn startup(
timeout: Duration,
keyboard_probe: StartupKeyboardEnhancementProbe,
) -> io::Result<StartupProbe> {
let mut tty = Tty::open()?;
tty.write_all(b"\x1B[?u\x1B[c")?;
read_keyboard_enhancement_supported(&mut tty, timeout)
match keyboard_probe {
StartupKeyboardEnhancementProbe::Query => {
tty.write_all(b"\x1B[6n\x1B]10;?\x1B\\\x1B]11;?\x1B\\\x1B[?u\x1B[c")?;
}
StartupKeyboardEnhancementProbe::Skip => {
tty.write_all(b"\x1B[6n\x1B]10;?\x1B\\\x1B]11;?\x1B\\")?;
}
}
read_startup_probe(&mut tty, timeout, keyboard_probe)
}
/// Reads available terminal bytes until `parse` recognizes a probe response or time expires.
@@ -265,42 +275,95 @@ mod imp {
}
}
/// Reads keyboard-enhancement responses while giving flags the full bounded window to arrive.
fn read_keyboard_enhancement_supported(
fn read_startup_probe(
tty: &mut Tty,
timeout: Duration,
) -> io::Result<Option<bool>> {
keyboard_probe: StartupKeyboardEnhancementProbe,
) -> io::Result<StartupProbe> {
let deadline = Instant::now() + timeout;
let mut buffer = Vec::new();
let mut saw_supported = false;
let mut saw_unsupported_fallback = false;
let mut probe = StartupProbe {
cursor_position: None,
default_colors: None,
keyboard_enhancement_supported: None,
};
let mut saw_supported_keyboard = false;
loop {
tty.read_available(&mut buffer)?;
match parse_keyboard_enhancement_support(&buffer) {
KeyboardProbeState::SupportedAndFallback => return Ok(Some(true)),
KeyboardProbeState::Supported => saw_supported = true,
KeyboardProbeState::UnsupportedFallback => saw_unsupported_fallback = true,
KeyboardProbeState::Pending => {}
}
if saw_supported && saw_unsupported_fallback {
return Ok(Some(true));
update_startup_probe(
&mut probe,
&mut saw_supported_keyboard,
&buffer,
keyboard_probe,
);
if startup_probe_complete(&probe, keyboard_probe) {
return Ok(probe);
}
let now = Instant::now();
if now >= deadline {
if saw_supported {
return Ok(Some(true));
}
return Ok(saw_unsupported_fallback.then_some(false));
finish_startup_probe(&mut probe, keyboard_probe, saw_supported_keyboard);
return Ok(probe);
}
if !tty.poll_readable(deadline.saturating_duration_since(now))? {
if saw_supported {
return Ok(Some(true));
}
return Ok(saw_unsupported_fallback.then_some(false));
finish_startup_probe(&mut probe, keyboard_probe, saw_supported_keyboard);
return Ok(probe);
}
}
}
fn update_startup_probe(
probe: &mut StartupProbe,
saw_supported_keyboard: &mut bool,
buffer: &[u8],
keyboard_probe: StartupKeyboardEnhancementProbe,
) {
if probe.cursor_position.is_none() {
probe.cursor_position = parse_cursor_position(buffer);
}
if probe.default_colors.is_none() {
probe.default_colors = parse_default_colors(buffer);
}
if keyboard_probe == StartupKeyboardEnhancementProbe::Skip
|| probe.keyboard_enhancement_supported.is_some()
{
return;
}
match parse_keyboard_enhancement_support(buffer) {
KeyboardProbeState::SupportedAndFallback => {
probe.keyboard_enhancement_supported = Some(true);
}
KeyboardProbeState::Supported => {
*saw_supported_keyboard = true;
}
KeyboardProbeState::UnsupportedFallback => {
probe.keyboard_enhancement_supported = Some(false);
}
KeyboardProbeState::Pending => {}
}
}
fn startup_probe_complete(
probe: &StartupProbe,
keyboard_probe: StartupKeyboardEnhancementProbe,
) -> bool {
probe.cursor_position.is_some()
&& probe.default_colors.is_some()
&& (keyboard_probe == StartupKeyboardEnhancementProbe::Skip
|| probe.keyboard_enhancement_supported.is_some())
}
fn finish_startup_probe(
probe: &mut StartupProbe,
keyboard_probe: StartupKeyboardEnhancementProbe,
saw_supported_keyboard: bool,
) {
if keyboard_probe == StartupKeyboardEnhancementProbe::Query
&& probe.keyboard_enhancement_supported.is_none()
{
probe.keyboard_enhancement_supported = saw_supported_keyboard.then_some(true);
}
}
fn parse_cursor_position(buffer: &[u8]) -> Option<Position> {
for start in find_all_subslices(buffer, b"\x1B[") {
let rest = &buffer[start + 2..];
@@ -382,11 +445,12 @@ mod imp {
/// Parser state for the keyboard enhancement probe.
///
/// `UnsupportedFallback` records that a primary-device-attributes response arrived, but the
/// caller should keep waiting until the deadline because a later keyboard-flags response is
/// more specific. `Supported` records that keyboard flags arrived, but the caller should still
/// drain the PDA fallback response if it arrives before the deadline so those bytes do not leak
/// into the normal event stream.
/// `UnsupportedFallback` records that a primary-device-attributes response arrived without
/// keyboard flags. Startup treats that as unsupported immediately, matching crossterm's
/// previous behavior and avoiding a fixed delay in terminals without the keyboard protocol.
/// `Supported` records that keyboard flags arrived, but the caller should still drain the PDA
/// fallback response if it arrives before the deadline so those bytes do not leak into the
/// normal event stream.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
enum KeyboardProbeState {
Pending,
@@ -556,6 +620,38 @@ mod imp {
KeyboardProbeState::Pending
);
}
#[test]
fn startup_probe_parses_batched_terminal_responses() {
let mut probe = StartupProbe {
cursor_position: None,
default_colors: None,
keyboard_enhancement_supported: None,
};
let mut saw_supported_keyboard = false;
update_startup_probe(
&mut probe,
&mut saw_supported_keyboard,
b"\x1B[20;10R\x1B]11;rgb:1111/1111/1111\x07\x1B[?64;1;2c\x1B]10;rgb:eeee/eeee/eeee\x1B\\\x1B[?7u",
StartupKeyboardEnhancementProbe::Query,
);
assert_eq!(
probe,
StartupProbe {
cursor_position: Some(Position { x: 9, y: 19 }),
default_colors: Some(DefaultColors {
fg: (238, 238, 238),
bg: (17, 17, 17),
}),
keyboard_enhancement_supported: Some(true),
}
);
assert!(startup_probe_complete(
&probe,
StartupKeyboardEnhancementProbe::Query
));
}
}
}
+61 -23
View File
@@ -63,6 +63,11 @@ pub(crate) const TARGET_FRAME_INTERVAL: Duration = frame_rate_limiter::MIN_FRAME
/// A type alias for the terminal type used in this application
pub type Terminal = CustomTerminal<CrosstermBackend<Stdout>>;
pub(crate) struct InitializedTerminal {
pub(crate) terminal: Terminal,
pub(crate) enhanced_keys_supported: bool,
}
pub(crate) fn running_in_vscode_terminal() -> bool {
keyboard_modes::running_in_vscode_terminal()
}
@@ -334,7 +339,7 @@ fn flush_terminal_input_buffer() {
pub(crate) fn flush_terminal_input_buffer() {}
/// Initialize the terminal (inline viewport; history stays in normal scrollback)
pub fn init() -> Result<Terminal> {
pub(crate) fn init() -> Result<InitializedTerminal> {
if !stdin().is_terminal() {
return Err(std::io::Error::other("stdin is not a terminal"));
}
@@ -351,20 +356,57 @@ pub fn init() -> Result<Terminal> {
let backend = CrosstermBackend::new(stdout());
#[cfg(unix)]
let cursor_pos =
match crate::terminal_probe::cursor_position(crate::terminal_probe::DEFAULT_TIMEOUT) {
Ok(Some(pos)) => pos,
Ok(None) => {
tracing::warn!("initial cursor position probe timed out; defaulting to origin");
Position { x: 0, y: 0 }
let startup_probe = {
use crate::terminal_probe::StartupKeyboardEnhancementProbe;
let started_at = std::time::Instant::now();
let keyboard_probe = if keyboard_modes::keyboard_enhancement_disabled() {
StartupKeyboardEnhancementProbe::Skip
} else {
StartupKeyboardEnhancementProbe::Query
};
match crate::terminal_probe::startup(crate::terminal_probe::DEFAULT_TIMEOUT, keyboard_probe)
{
Ok(probe) => {
tracing::info!(
duration_ms = %started_at.elapsed().as_millis(),
cursor_position = probe.cursor_position.is_some(),
default_colors = probe.default_colors.is_some(),
keyboard_enhancement_supported = ?probe.keyboard_enhancement_supported,
"terminal startup probes completed"
);
probe
}
Err(err) => {
tracing::warn!(
"failed to read initial cursor position; defaulting to origin: {err}"
duration_ms = %started_at.elapsed().as_millis(),
"terminal startup probes failed: {err}"
);
Position { x: 0, y: 0 }
crate::terminal_probe::StartupProbe {
cursor_position: None,
default_colors: None,
keyboard_enhancement_supported: None,
}
}
};
}
};
#[cfg(unix)]
crate::terminal_palette::set_default_colors_from_startup_probe(startup_probe.default_colors);
#[cfg(unix)]
let cursor_pos = match startup_probe.cursor_position {
Some(pos) => pos,
None => {
tracing::warn!("initial cursor position probe timed out; defaulting to origin");
Position { x: 0, y: 0 }
}
};
#[cfg(unix)]
let enhanced_keys_supported = startup_probe
.keyboard_enhancement_supported
.unwrap_or(/*default*/ false);
#[cfg(not(unix))]
let mut backend = CrosstermBackend::new(stdout());
@@ -372,8 +414,15 @@ pub fn init() -> Result<Terminal> {
#[cfg(not(unix))]
let cursor_pos = cursor_position_with_crossterm(&mut backend);
#[cfg(not(unix))]
let enhanced_keys_supported =
!keyboard_modes::keyboard_enhancement_disabled() && detect_keyboard_enhancement_supported();
let tui = CustomTerminal::with_options_and_cursor_position(backend, cursor_pos)?;
Ok(tui)
Ok(InitializedTerminal {
terminal: tui,
enhanced_keys_supported,
})
}
#[cfg(not(unix))]
@@ -384,13 +433,6 @@ fn cursor_position_with_crossterm(backend: &mut CrosstermBackend<Stdout>) -> Pos
})
}
#[cfg(unix)]
fn detect_keyboard_enhancement_supported() -> bool {
crate::terminal_probe::keyboard_enhancement_supported(crate::terminal_probe::DEFAULT_TIMEOUT)
.unwrap_or(/*default*/ None)
.unwrap_or(/*default*/ false)
}
#[cfg(not(unix))]
fn detect_keyboard_enhancement_supported() -> bool {
// Non-Unix startup keeps the existing crossterm path because the bounded probe implementation
@@ -461,14 +503,10 @@ where
}
impl Tui {
pub fn new(terminal: Terminal) -> Self {
pub fn new(terminal: Terminal, enhanced_keys_supported: bool) -> Self {
let (draw_tx, _) = broadcast::channel(1);
let frame_requester = FrameRequester::new(draw_tx.clone());
// Detect keyboard enhancement support before any EventStream is created so the
// crossterm poller can acquire its lock without contention.
let enhanced_keys_supported = !keyboard_modes::keyboard_enhancement_disabled()
&& detect_keyboard_enhancement_supported();
// Cache this to avoid contention with the event reader.
supports_color::on_cached(supports_color::Stream::Stdout);
let _ = crate::terminal_palette::default_colors();