Files
codex/codex-rs/tui/src/terminal_program_status.rs
T
Eric Traut 372947d936 Report pending startup dialogs through terminal program status (#64384)
## Why

Terminal hosts need to know when Codex is waiting for a startup decision, including while a chat status record is active.

## What changed

Emit a separate `OSC 7501` blocked record while waiting for directory trust, startup hook review, or an update decision. Report trust and hook review as permission prompts and the update prompt as a question.

Clear the dialog record when the prompt closes or Codex suspends. Report it again if Codex resumes waiting for input. Dialog records can coexist with the chat status record.

## Testing

Extend the connected directory trust PTY test to check blocked and clear records for consent and hook review. Exercise Ctrl-Z in a PTY without a controlling terminal and verify that the pending trust record stays active until the prompt is answered.

GitOrigin-RevId: 9801e03b28a19b75f62a09e3e927de0dd59c5448
2026-11-27 20:48:50 +00:00

360 lines
9.9 KiB
Rust

//! Emits Codex lifecycle state through terminal status protocols.
//!
//! OSC 7501 reports lifecycle state and blocking reasons to terminal sessions.
//! Direct iTerm2 sessions also receive OSC 21337 status, including bounded
//! activity text. The process-wide cache is used for exit, panic, and terminal
//! handoff cleanup of the root record. Each dialog owns its child record through
//! the input stream that waits for the decision.
use crate::terminal_capabilities::TerminalProgramStatusSupport;
use crate::terminal_capabilities::detect_terminal_program_status_support;
use crossterm::Command;
use ratatui::crossterm::execute;
use std::fmt;
use std::io;
use std::io::stdout;
use std::sync::Mutex;
use std::sync::OnceLock;
static SESSION_STATUS_STATE: SessionStatusState = SessionStatusState::new();
static TERMINAL_PROGRAM_STATUS_SUPPORT: OnceLock<TerminalProgramStatusSupport> = OnceLock::new();
fn current_terminal_program_status_support() -> TerminalProgramStatusSupport {
*TERMINAL_PROGRAM_STATUS_SUPPORT.get_or_init(detect_terminal_program_status_support)
}
struct SessionStatusState {
last_emitted: Mutex<EmittedSessionStatus>,
}
struct EmittedSessionStatus {
status: CachedStatus,
detail: String,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum CachedStatus {
Cleared,
Reported(ProgramStatus),
Invalidated,
}
impl SessionStatusState {
const fn new() -> Self {
Self {
last_emitted: Mutex::new(EmittedSessionStatus {
status: CachedStatus::Cleared,
detail: String::new(),
}),
}
}
fn update(
&self,
status: CachedStatus,
detail: &str,
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 == status && last_emitted.detail == detail {
return Ok(());
}
emit()?;
last_emitted.status = status;
detail.clone_into(&mut last_emitted.detail);
Ok(())
}
fn invalidate(&self) {
let mut last_emitted = self
.last_emitted
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if last_emitted.status != CachedStatus::Cleared {
last_emitted.status = CachedStatus::Invalidated;
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum ProgramStatus {
Idle,
Working,
Blocked(ProgramStatusKind),
Done,
Error,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum ProgramStatusKind {
Permission,
Question,
Auth,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum StartupDialog {
Trust,
Hooks,
#[cfg(not(debug_assertions))]
Update,
}
impl StartupDialog {
fn record(self) -> (&'static str, ProgramStatusKind) {
match self {
Self::Trust => ("startup/trust", ProgramStatusKind::Permission),
Self::Hooks => ("startup/hooks", ProgramStatusKind::Permission),
#[cfg(not(debug_assertions))]
Self::Update => ("startup/update", ProgramStatusKind::Question),
}
}
}
/// A dialog can coexist with the chat root. Never clear the root or emit iTerm
/// status here, since neither operation is scoped to the dialog.
#[derive(Default)]
pub(crate) struct DialogStatus(Option<StartupDialog>);
impl DialogStatus {
pub(crate) fn clear(&mut self) {
self.set(/*dialog*/ None);
}
pub(crate) fn set(&mut self, dialog: Option<StartupDialog>) {
if self.0 == dialog || cfg!(test) || !current_terminal_program_status_support().osc_7501 {
return;
}
if let Some(previous) = self.0 {
let (id, _) = previous.record();
if let Err(err) = execute!(
stdout(),
ClearTerminalProgramStatus {
id: Some(id),
emit_iterm_status: false,
}
) {
tracing::debug!("failed to clear dialog status: {err}");
return;
}
self.0 = None;
}
if let Some(dialog) = dialog {
let (id, kind) = dialog.record();
if let Err(err) = execute!(
stdout(),
SetTerminalProgramStatus {
id: Some(id),
status: ProgramStatus::Blocked(kind),
iterm_detail: "",
emit_iterm_status: false,
}
) {
tracing::debug!("failed to report dialog status: {err}");
return;
}
self.0 = Some(dialog);
}
}
}
impl Drop for DialogStatus {
fn drop(&mut self) {
self.clear();
}
}
impl ProgramStatus {
fn iterm_label(self) -> &'static str {
match self {
Self::Idle | Self::Done | Self::Error => "Idle",
Self::Working => "Working",
Self::Blocked(_) => "Waiting",
}
}
fn iterm_indicator(self) -> &'static str {
match self {
Self::Idle | Self::Done | Self::Error => "#00d75f",
Self::Working => "#ff9500",
Self::Blocked(_) => "#5f87ff",
}
}
fn protocol_state(self) -> &'static str {
match self {
Self::Idle => "idle",
Self::Working => "working",
Self::Blocked(_) => "blocked",
Self::Done => "done",
Self::Error => "error",
}
}
}
pub(crate) fn set_terminal_program_status(
status: ProgramStatus,
detail: Option<&str>,
) -> io::Result<()> {
if cfg!(test) {
return Ok(());
}
let support = current_terminal_program_status_support();
if !support.osc_7501 {
return Ok(());
}
let detail = if support.osc_21337 {
sanitize_iterm_session_detail(detail.unwrap_or_default())
} else {
String::new()
};
SESSION_STATUS_STATE.update(CachedStatus::Reported(status), &detail, || {
execute!(
stdout(),
SetTerminalProgramStatus {
id: None,
status,
iterm_detail: &detail,
emit_iterm_status: support.osc_21337,
}
)
})
}
pub(crate) fn clear_terminal_program_status() -> io::Result<()> {
if cfg!(test) {
return Ok(());
}
let support = current_terminal_program_status_support();
if !support.osc_7501 {
return Ok(());
}
SESSION_STATUS_STATE.update(CachedStatus::Cleared, "", || {
execute!(
stdout(),
ClearTerminalProgramStatus {
id: None,
emit_iterm_status: support.osc_21337,
}
)
})
}
/// 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_terminal_program_status() {
SESSION_STATUS_STATE.invalidate();
}
fn sanitize_iterm_session_detail(detail: &str) -> String {
let detail = crate::terminal_title::sanitize_terminal_title(
detail,
crate::terminal_title::TitleEncoding::Unicode,
);
let mut escaped = String::with_capacity(detail.len());
for ch in detail.chars() {
if matches!(ch, ';' | '\\') {
escaped.push('\\');
}
escaped.push(ch);
}
escaped
}
#[derive(Clone, Copy, Debug)]
struct SetTerminalProgramStatus<'a> {
id: Option<&'static str>,
status: ProgramStatus,
iterm_detail: &'a str,
emit_iterm_status: bool,
}
impl Command for SetTerminalProgramStatus<'_> {
fn write_ansi(&self, f: &mut impl fmt::Write) -> fmt::Result {
if self.emit_iterm_status {
write!(
f,
"\x1b]21337;status={};indicator={};status-color=;detail={}\x07",
self.status.iterm_label(),
self.status.iterm_indicator(),
self.iterm_detail,
)?;
}
write!(
f,
"\x1b]7501;state={}:app=codex",
self.status.protocol_state()
)?;
if let ProgramStatus::Blocked(kind) = self.status {
let kind = match kind {
ProgramStatusKind::Permission => "permission",
ProgramStatusKind::Question => "question",
ProgramStatusKind::Auth => "auth",
};
write!(f, ":kind={kind}")?;
}
if let Some(id) = self.id {
write!(f, ":id={id}")?;
}
write!(f, "\x1b\\")
}
#[cfg(windows)]
fn execute_winapi(&self) -> io::Result<()> {
Err(io::Error::other(
"tried to set terminal program status using WinAPI; use ANSI instead",
))
}
#[cfg(windows)]
fn is_ansi_code_supported(&self) -> bool {
true
}
}
#[derive(Clone, Copy, Debug)]
struct ClearTerminalProgramStatus {
id: Option<&'static str>,
emit_iterm_status: bool,
}
impl Command for ClearTerminalProgramStatus {
fn write_ansi(&self, f: &mut impl fmt::Write) -> fmt::Result {
if self.emit_iterm_status {
write!(f, "\x1b]21337;status=;indicator=;status-color=;detail=\x07")?;
}
write!(f, "\x1b]7501;state=clear")?;
if let Some(id) = self.id {
write!(f, ":id={id}")?;
}
write!(f, "\x1b\\")
}
#[cfg(windows)]
fn execute_winapi(&self) -> io::Result<()> {
Err(io::Error::other(
"tried to clear terminal program 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;