mirror of
https://github.com/openai/codex.git
synced 2026-12-03 00:41:03 +00:00
Expose Codex lifecycle status in iTerm2 sessions (#52203)
## What changed Emit `Idle`, `Working`, or `Waiting` with colored indicators through iTerm2's `OSC 21337` session status protocol. Pending user action takes precedence over running tasks and background processes. Limit emission to direct iTerm2 TTY sessions without a terminal multiplexer. Deduplicate successful writes, refresh status after terminal handoffs and resume, and clear status on suspension and exit. ## Testing Add coverage for lifecycle transitions, protocol encoding, terminal detection, write retries, deduplication, and re-emission after terminal handoffs. GitOrigin-RevId: 750e9ec92aeefc57651886a08ef6aea07675d175
This commit is contained in:
@@ -349,6 +349,12 @@ impl App {
|
||||
/// source of truth for the active cell and its cache invalidation key, and because `App` owns
|
||||
/// overlay lifecycle and frame scheduling for animations.
|
||||
fn overlay_forward_event(&mut self, tui: &mut tui::Tui, event: TuiEvent) -> Result<()> {
|
||||
if matches!(
|
||||
&event,
|
||||
TuiEvent::Draw | TuiEvent::Resume | TuiEvent::Resize(_) | TuiEvent::FocusGained
|
||||
) {
|
||||
self.chat_widget.refresh_iterm_session_status();
|
||||
}
|
||||
let width = tui.terminal.last_known_screen_size.width.max(/*other*/ 1);
|
||||
let footer = self.prompt_navigation_footer(width.saturating_sub(/*rhs*/ 2));
|
||||
if let Some(Overlay::Transcript(overlay)) = &mut self.overlay {
|
||||
|
||||
@@ -1181,6 +1181,15 @@ impl ChatWidget {
|
||||
}
|
||||
self.refresh_status_line_if_workspace_headline_due();
|
||||
self.refresh_thread_usage_if_settlement_due();
|
||||
self.refresh_iterm_session_status();
|
||||
}
|
||||
|
||||
pub(crate) fn refresh_iterm_session_status(&self) {
|
||||
if let Err(err) = crate::iterm_session_status::set_iterm_session_status(
|
||||
self.desired_iterm_session_status(),
|
||||
) {
|
||||
tracing::debug!(error = %err, "failed to set iTerm2 session status");
|
||||
}
|
||||
}
|
||||
|
||||
fn flush_active_cell(&mut self) {
|
||||
|
||||
@@ -8,6 +8,7 @@ use crate::bottom_pane::status_line_from_segments;
|
||||
use crate::branch_summary;
|
||||
use crate::chatwidget::limit_label_for_window;
|
||||
use crate::chatwidget::rate_limits::get_limits_duration;
|
||||
use crate::iterm_session_status::ItermSessionStatus;
|
||||
use crate::legacy_core::config::Config;
|
||||
use crate::model_catalog::LUNA_RESERVE_MODEL;
|
||||
use crate::status::format_credit_micros;
|
||||
@@ -321,6 +322,16 @@ impl ChatWidget {
|
||||
self.bottom_pane.terminal_title_requires_action()
|
||||
}
|
||||
|
||||
pub(super) fn desired_iterm_session_status(&self) -> ItermSessionStatus {
|
||||
if self.terminal_title_requires_action() {
|
||||
ItermSessionStatus::Waiting
|
||||
} else if self.bottom_pane.is_task_running() || !self.unified_exec_processes.is_empty() {
|
||||
ItermSessionStatus::Working
|
||||
} else {
|
||||
ItermSessionStatus::Idle
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn terminal_title_shows_action_required(&self) -> bool {
|
||||
self.terminal_title_requires_action() && self.terminal_title_uses_activity()
|
||||
}
|
||||
|
||||
@@ -257,6 +257,8 @@ mod history_projection;
|
||||
mod history_replay;
|
||||
#[path = "tests/home_cleanup_tests.rs"]
|
||||
mod home_cleanup_tests;
|
||||
#[path = "tests/iterm_session_status.rs"]
|
||||
mod iterm_session_status;
|
||||
#[path = "tests/luna_reserve_usage_tests.rs"]
|
||||
mod luna_reserve_usage_tests;
|
||||
mod mcp_startup;
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
use super::*;
|
||||
use crate::iterm_session_status::ItermSessionStatus::Idle;
|
||||
use crate::iterm_session_status::ItermSessionStatus::Waiting;
|
||||
use crate::iterm_session_status::ItermSessionStatus::Working;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[tokio::test]
|
||||
async fn session_status_follows_existing_lifecycle_state() {
|
||||
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||
let mut states = vec![chat.desired_iterm_session_status()];
|
||||
|
||||
chat.bottom_pane.set_task_running(/*running*/ true);
|
||||
states.push(chat.desired_iterm_session_status());
|
||||
|
||||
handle_exec_approval_request(
|
||||
&mut chat,
|
||||
"session-status-approval",
|
||||
ExecApprovalRequestEvent {
|
||||
kind: Default::default(),
|
||||
call_id: "session-status-call".to_string(),
|
||||
approval_id: Some("session-status-call".to_string()),
|
||||
turn_id: "session-status-turn".to_string(),
|
||||
environment_id: None,
|
||||
command: vec!["echo".to_string(), "hello".to_string()],
|
||||
cwd: AbsolutePathBuf::current_dir().expect("current dir"),
|
||||
reason: Some("need confirmation".to_string()),
|
||||
network_approval_context: None,
|
||||
proposed_execpolicy_amendment: None,
|
||||
proposed_network_policy_amendments: None,
|
||||
additional_permissions: None,
|
||||
available_decisions: None,
|
||||
},
|
||||
);
|
||||
states.push(chat.desired_iterm_session_status());
|
||||
|
||||
chat.handle_key_event(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::NONE));
|
||||
states.push(chat.desired_iterm_session_status());
|
||||
|
||||
chat.bottom_pane.set_task_running(/*running*/ false);
|
||||
states.push(chat.desired_iterm_session_status());
|
||||
|
||||
chat.unified_exec_processes.push(UnifiedExecProcessSummary {
|
||||
key: "background-process".to_string(),
|
||||
call_id: "background-call".to_string(),
|
||||
command_display: "sleep 5".to_string(),
|
||||
recent_chunks: Vec::new(),
|
||||
});
|
||||
states.push(chat.desired_iterm_session_status());
|
||||
chat.unified_exec_processes.clear();
|
||||
states.push(chat.desired_iterm_session_status());
|
||||
|
||||
assert_eq!(
|
||||
states,
|
||||
[Idle, Working, Waiting, Working, Idle, Working, Idle]
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
//! Emits coarse Codex lifecycle state through iTerm2's OSC 21337 protocol.
|
||||
//!
|
||||
//! This first integration is intentionally limited to direct iTerm2 sessions.
|
||||
//! The payload uses fixed strings, so it needs no dynamic text escaping or
|
||||
//! throttling. A process-wide cache matches the terminal session's ownership
|
||||
//! and prevents stale per-thread state when the active chat changes.
|
||||
|
||||
use std::fmt;
|
||||
use std::io;
|
||||
use std::io::IsTerminal;
|
||||
use std::io::stdout;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use codex_terminal_detection::TerminalInfo;
|
||||
use codex_terminal_detection::TerminalName;
|
||||
use codex_terminal_detection::terminal_info;
|
||||
use crossterm::Command;
|
||||
use ratatui::crossterm::execute;
|
||||
|
||||
const NO_EMITTED_STATUS: u8 = 0;
|
||||
const INVALIDATED_EMITTED_STATUS: u8 = u8::MAX;
|
||||
static SESSION_STATUS_STATE: SessionStatusState = SessionStatusState::new();
|
||||
static ITERM_SESSION_STATUS_SUPPORTED: OnceLock<bool> = OnceLock::new();
|
||||
|
||||
struct SessionStatusState {
|
||||
last_emitted: Mutex<u8>,
|
||||
}
|
||||
|
||||
impl SessionStatusState {
|
||||
const fn new() -> Self {
|
||||
Self {
|
||||
last_emitted: Mutex::new(NO_EMITTED_STATUS),
|
||||
}
|
||||
}
|
||||
|
||||
fn update(&self, status: u8, emit: impl FnOnce() -> io::Result<()>) -> io::Result<()> {
|
||||
// Keep the terminal write and cache mutation together so panic-hook cleanup cannot
|
||||
// interleave with a draw from another thread.
|
||||
let mut last_emitted = self
|
||||
.last_emitted
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if *last_emitted == status {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
emit()?;
|
||||
*last_emitted = status;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn invalidate(&self) {
|
||||
let mut last_emitted = self
|
||||
.last_emitted
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if *last_emitted != NO_EMITTED_STATUS {
|
||||
*last_emitted = INVALIDATED_EMITTED_STATUS;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
#[repr(u8)]
|
||||
pub(crate) enum ItermSessionStatus {
|
||||
Idle = 1,
|
||||
Working = 2,
|
||||
Waiting = 3,
|
||||
}
|
||||
|
||||
impl ItermSessionStatus {
|
||||
fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::Idle => "Idle",
|
||||
Self::Working => "Working",
|
||||
Self::Waiting => "Waiting",
|
||||
}
|
||||
}
|
||||
|
||||
fn indicator(self) -> &'static str {
|
||||
match self {
|
||||
Self::Idle => "#00d75f",
|
||||
Self::Working => "#ff9500",
|
||||
Self::Waiting => "#5f87ff",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn set_iterm_session_status(status: ItermSessionStatus) -> io::Result<()> {
|
||||
if cfg!(test) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if !*ITERM_SESSION_STATUS_SUPPORTED.get_or_init(|| {
|
||||
iterm_session_status_supported(
|
||||
&terminal_info(),
|
||||
/*stdout_is_terminal*/ stdout().is_terminal(),
|
||||
/*screen_active*/ std::env::var_os("STY").is_some(),
|
||||
)
|
||||
}) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
SESSION_STATUS_STATE.update(status as u8, || {
|
||||
execute!(stdout(), SetItermSessionStatus(status))
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn clear_iterm_session_status() -> io::Result<()> {
|
||||
SESSION_STATUS_STATE.update(NO_EMITTED_STATUS, || {
|
||||
execute!(stdout(), ClearItermSessionStatus)
|
||||
})
|
||||
}
|
||||
|
||||
/// Forgets the cached state after another process has owned the terminal.
|
||||
///
|
||||
/// The next active draw will re-emit Codex's current status even if its
|
||||
/// lifecycle state did not change during the handoff.
|
||||
pub(crate) fn invalidate_iterm_session_status() {
|
||||
SESSION_STATUS_STATE.invalidate();
|
||||
}
|
||||
|
||||
fn iterm_session_status_supported(
|
||||
terminal: &TerminalInfo,
|
||||
stdout_is_terminal: bool,
|
||||
screen_active: bool,
|
||||
) -> bool {
|
||||
stdout_is_terminal
|
||||
&& terminal.name == TerminalName::Iterm2
|
||||
&& terminal.multiplexer.is_none()
|
||||
&& !screen_active
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct SetItermSessionStatus(ItermSessionStatus);
|
||||
|
||||
impl Command for SetItermSessionStatus {
|
||||
fn write_ansi(&self, f: &mut impl fmt::Write) -> fmt::Result {
|
||||
write!(
|
||||
f,
|
||||
"\x1b]21337;status={};indicator={};status-color=;detail=\x07",
|
||||
self.0.label(),
|
||||
self.0.indicator(),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn execute_winapi(&self) -> io::Result<()> {
|
||||
Err(io::Error::other(
|
||||
"tried to set iTerm2 session status using WinAPI; use ANSI instead",
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn is_ansi_code_supported(&self) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct ClearItermSessionStatus;
|
||||
|
||||
impl Command for ClearItermSessionStatus {
|
||||
fn write_ansi(&self, f: &mut impl fmt::Write) -> fmt::Result {
|
||||
write!(f, "\x1b]21337;status=;indicator=;status-color=;detail=\x07")
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn execute_winapi(&self) -> io::Result<()> {
|
||||
Err(io::Error::other(
|
||||
"tried to clear iTerm2 session status using WinAPI; use ANSI instead",
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn is_ansi_code_supported(&self) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "iterm_session_status_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,140 @@
|
||||
use std::io;
|
||||
|
||||
use codex_terminal_detection::Multiplexer;
|
||||
use codex_terminal_detection::TerminalInfo;
|
||||
use codex_terminal_detection::TerminalName;
|
||||
use crossterm::Command;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::ClearItermSessionStatus;
|
||||
use super::ItermSessionStatus;
|
||||
use super::NO_EMITTED_STATUS;
|
||||
use super::SessionStatusState;
|
||||
use super::SetItermSessionStatus;
|
||||
use super::iterm_session_status_supported;
|
||||
|
||||
#[test]
|
||||
fn encodes_session_status_fields() {
|
||||
let mut encoded = Vec::new();
|
||||
for status in [
|
||||
ItermSessionStatus::Idle,
|
||||
ItermSessionStatus::Working,
|
||||
ItermSessionStatus::Waiting,
|
||||
] {
|
||||
let mut value = String::new();
|
||||
SetItermSessionStatus(status)
|
||||
.write_ansi(&mut value)
|
||||
.expect("encode iTerm2 session status");
|
||||
encoded.push(value);
|
||||
}
|
||||
|
||||
let snapshot = encoded
|
||||
.iter()
|
||||
.map(|value| value.escape_debug().to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
insta::assert_snapshot!("iterm_session_status_fields", snapshot);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clear_empties_every_owned_field() {
|
||||
let mut encoded = String::new();
|
||||
ClearItermSessionStatus
|
||||
.write_ansi(&mut encoded)
|
||||
.expect("encode iTerm2 session status clear");
|
||||
|
||||
assert_eq!(
|
||||
encoded,
|
||||
"\x1b]21337;status=;indicator=;status-color=;detail=\x07"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cache_changes_only_after_a_successful_write() {
|
||||
let state = SessionStatusState::new();
|
||||
let mut emitted = Vec::new();
|
||||
|
||||
state
|
||||
.update(ItermSessionStatus::Working as u8, || {
|
||||
Err(io::Error::other("write failed"))
|
||||
})
|
||||
.expect_err("failed write should be returned");
|
||||
|
||||
state
|
||||
.update(ItermSessionStatus::Working as u8, || {
|
||||
emitted.push(ItermSessionStatus::Working as u8);
|
||||
Ok(())
|
||||
})
|
||||
.expect("retry status write");
|
||||
state
|
||||
.update(ItermSessionStatus::Working as u8, || {
|
||||
emitted.push(ItermSessionStatus::Waiting as u8);
|
||||
Ok(())
|
||||
})
|
||||
.expect("deduplicate status write");
|
||||
state.invalidate();
|
||||
state
|
||||
.update(ItermSessionStatus::Working as u8, || {
|
||||
emitted.push(ItermSessionStatus::Working as u8);
|
||||
Ok(())
|
||||
})
|
||||
.expect("re-emit status after terminal handoff");
|
||||
state
|
||||
.update(NO_EMITTED_STATUS, || {
|
||||
emitted.push(NO_EMITTED_STATUS);
|
||||
Ok(())
|
||||
})
|
||||
.expect("clear status");
|
||||
|
||||
assert_eq!(
|
||||
emitted,
|
||||
[
|
||||
ItermSessionStatus::Working as u8,
|
||||
ItermSessionStatus::Working as u8,
|
||||
NO_EMITTED_STATUS,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn supports_only_direct_iterm_ttys() {
|
||||
let direct_iterm = TerminalInfo {
|
||||
name: TerminalName::Iterm2,
|
||||
term_program: Some("iTerm.app".to_string()),
|
||||
version: Some("3.7.0".to_string()),
|
||||
term: None,
|
||||
multiplexer: None,
|
||||
};
|
||||
assert!(iterm_session_status_supported(
|
||||
&direct_iterm,
|
||||
/*stdout_is_terminal*/ true,
|
||||
/*screen_active*/ false,
|
||||
));
|
||||
assert!(!iterm_session_status_supported(
|
||||
&direct_iterm,
|
||||
/*stdout_is_terminal*/ false,
|
||||
/*screen_active*/ false,
|
||||
));
|
||||
assert!(!iterm_session_status_supported(
|
||||
&direct_iterm,
|
||||
/*stdout_is_terminal*/ true,
|
||||
/*screen_active*/ true,
|
||||
));
|
||||
|
||||
assert!(!iterm_session_status_supported(
|
||||
&TerminalInfo {
|
||||
multiplexer: Some(Multiplexer::Tmux { version: None }),
|
||||
..direct_iterm.clone()
|
||||
},
|
||||
/*stdout_is_terminal*/ true,
|
||||
/*screen_active*/ false,
|
||||
));
|
||||
assert!(!iterm_session_status_supported(
|
||||
&TerminalInfo {
|
||||
name: TerminalName::Ghostty,
|
||||
..direct_iterm
|
||||
},
|
||||
/*stdout_is_terminal*/ true,
|
||||
/*screen_active*/ false,
|
||||
));
|
||||
}
|
||||
@@ -162,6 +162,7 @@ mod hooks_rpc;
|
||||
mod ide_context;
|
||||
mod inline_visualization;
|
||||
pub(crate) mod insert_history;
|
||||
mod iterm_session_status;
|
||||
mod managed_worktree_tool_specs;
|
||||
mod managed_worktree_tools;
|
||||
pub use insert_history::insert_history_lines;
|
||||
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
---
|
||||
source: tui/src/iterm_session_status_tests.rs
|
||||
assertion_line: 36
|
||||
expression: snapshot
|
||||
---
|
||||
\u{1b}]21337;status=Idle;indicator=#00d75f;status-color=;detail=\u{7}
|
||||
\u{1b}]21337;status=Working;indicator=#ff9500;status-color=;detail=\u{7}
|
||||
\u{1b}]21337;status=Waiting;indicator=#5f87ff;status-color=;detail=\u{7}
|
||||
@@ -408,6 +408,9 @@ pub fn restore_after_exit() -> Result<()> {
|
||||
if let Err(err) = terminal_stderr::finish() {
|
||||
first_error.get_or_insert(err);
|
||||
}
|
||||
if let Err(err) = crate::iterm_session_status::clear_iterm_session_status() {
|
||||
first_error.get_or_insert(err);
|
||||
}
|
||||
|
||||
match first_error {
|
||||
Some(err) => Err(err),
|
||||
@@ -996,6 +999,7 @@ impl Tui {
|
||||
let _ = self.enter_alt_screen();
|
||||
}
|
||||
|
||||
crate::iterm_session_status::invalidate_iterm_session_status();
|
||||
self.resume_events();
|
||||
self.schedule_screen_size_recheck(Duration::ZERO);
|
||||
output
|
||||
|
||||
@@ -69,7 +69,12 @@ impl SuspendContext {
|
||||
}
|
||||
let y = self.suspend_cursor_y.load(Ordering::Relaxed);
|
||||
let _ = execute!(stdout(), MoveTo(0, y), Show);
|
||||
suspend_process()?;
|
||||
if let Err(err) = crate::iterm_session_status::clear_iterm_session_status() {
|
||||
tracing::debug!(error = %err, "failed to clear iTerm2 session status before suspend");
|
||||
}
|
||||
let suspend_result = suspend_process();
|
||||
crate::iterm_session_status::invalidate_iterm_session_status();
|
||||
suspend_result?;
|
||||
super::reapply_raw_mode_after_resume()?;
|
||||
|
||||
// The shell writes its job-control status and the resumed command after `fg`, so the
|
||||
|
||||
Reference in New Issue
Block a user