Skip to content

armgit / codex

Public Imported from GitHub
0

Lightweight coding agent that runs in your terminal

Rust

Default TUI animations off when a screen reader is detected (#46040)

Eric Traut515530d9b274
diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock
index f05dbed45d..ecfafd99c2 100644
--- a/codex-rs/Cargo.lock
+++ b/codex-rs/Cargo.lock
@@ -4854,6 +4854,7 @@ dependencies = [
"tokio-tungstenite",
"tokio-util",
"toml 0.9.11+spec-1.1.0",
+ "toml_edit 0.24.0+spec-1.1.0",
"tracing",
"tracing-appender",
"tracing-subscriber",
diff --git a/codex-rs/config/src/types.rs b/codex-rs/config/src/types.rs
index 747061d5ab..a21ad38514 100644
--- a/codex-rs/config/src/types.rs
+++ b/codex-rs/config/src/types.rs
@@ -752,6 +752,9 @@ pub struct Tui {
#[serde(default = "default_true")]
pub animations: bool,
+ /// Records the one-time screen-reader detection attempt. Either value skips detection.
+ pub screen_reader_detection_done: Option<bool>,
+
/// Enable decorative effects such as Astra composer stars. Also requires animations.
/// Defaults to `true`.
#[serde(default = "default_true")]
diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json
index b9c768f6a2..7aa4f94219 100644
--- a/codex-rs/core/config.schema.json
+++ b/codex-rs/core/config.schema.json
@@ -4354,6 +4354,10 @@
"default": null,
"description": "Working directory to use when resuming or forking a session. When unset, prompt if the current and session directories differ."
},
+ "screen_reader_detection_done": {
+ "description": "Records the one-time screen-reader detection attempt. Either value skips detection.",
+ "type": "boolean"
+ },
"session_picker_view": {
"allOf": [
{
diff --git a/codex-rs/core/src/config/config_tests.rs b/codex-rs/core/src/config/config_tests.rs
index da2bf72e8f..7be3235fce 100644
--- a/codex-rs/core/src/config/config_tests.rs
+++ b/codex-rs/core/src/config/config_tests.rs
@@ -1250,6 +1250,7 @@ fn config_toml_deserializes_model_availability_nux() {
Tui {
notification_settings: TuiNotificationSettings::default(),
animations: true,
+ screen_reader_detection_done: None,
whimsy: true,
show_tooltips: true,
show_server_version_notice: true,
@@ -4266,6 +4267,7 @@ fn tui_config_missing_notifications_field_defaults_to_enabled() {
Tui {
notification_settings: TuiNotificationSettings::default(),
animations: true,
+ screen_reader_detection_done: None,
whimsy: true,
show_tooltips: true,
show_server_version_notice: true,
diff --git a/codex-rs/tui/Cargo.toml b/codex-rs/tui/Cargo.toml
index 0fe40e2707..0bbdcd44e8 100644
--- a/codex-rs/tui/Cargo.toml
+++ b/codex-rs/tui/Cargo.toml
@@ -118,6 +118,7 @@ tokio = { workspace = true, features = [
] }
tokio-stream = { workspace = true, features = ["sync"] }
toml = { workspace = true }
+toml_edit = { workspace = true }
tracing = { workspace = true, features = ["log"] }
tracing-appender = { workspace = true }
tracing-subscriber = { workspace = true, features = ["env-filter"] }
@@ -150,6 +151,8 @@ windows-sys = { version = "0.52", features = [
"Win32_Security",
"Win32_Storage_FileSystem",
"Win32_System_Console",
+ "Win32_System_Diagnostics_ToolHelp",
+ "Win32_System_RemoteDesktop",
"Win32_System_IO",
"Win32_System_Pipes",
"Win32_System_Threading",
diff --git a/codex-rs/tui/src/lib.rs b/codex-rs/tui/src/lib.rs
index b87ab02710..b0cc9b5494 100644
--- a/codex-rs/tui/src/lib.rs
+++ b/codex-rs/tui/src/lib.rs
@@ -184,6 +184,7 @@ pub(crate) mod public_widgets;
mod render;
mod resize_reflow_cap;
mod resume_picker;
+mod screen_reader;
mod selection_list;
mod service_tier_resolution;
mod session_archive_commands;
diff --git a/codex-rs/tui/src/local_settings.rs b/codex-rs/tui/src/local_settings.rs
index 3850e0aa0c..b23229074d 100644
--- a/codex-rs/tui/src/local_settings.rs
+++ b/codex-rs/tui/src/local_settings.rs
@@ -24,17 +24,37 @@ pub(crate) struct LocalSettings {
impl From<&Config> for LocalSettings {
fn from(config: &Config) -> Self {
- Self::with_system_motion(config, crate::system_motion::mode())
+ Self::with_accessibility_preferences(
+ config,
+ crate::system_motion::mode(),
+ crate::screen_reader::animation_default(),
+ )
}
}
impl LocalSettings {
- fn with_system_motion(config: &Config, system_motion: crate::motion::MotionMode) -> Self {
+ fn with_accessibility_preferences(
+ config: &Config,
+ system_motion: crate::motion::MotionMode,
+ screen_reader_default: crate::motion::MotionMode,
+ ) -> Self {
+ let animations = if screen_reader_default == crate::motion::MotionMode::Reduced {
+ // Consult the current layers so preferences edited after startup still win.
+ config
+ .config_layer_stack
+ .effective_config()
+ .get("tui")
+ .and_then(|tui| tui.get("animations"))
+ .is_some()
+ && config.animations
+ } else {
+ config.animations
+ };
Self {
tui: Tui {
notification_settings: config.tui_notifications.clone(),
- animations: config.animations
- && system_motion == crate::motion::MotionMode::Animated,
+ animations: animations && system_motion == crate::motion::MotionMode::Animated,
+ screen_reader_detection_done: None,
whimsy: config.tui_whimsy,
show_tooltips: config.show_tooltips,
show_server_version_notice: config.tui_show_server_version_notice,
diff --git a/codex-rs/tui/src/local_settings_tests.rs b/codex-rs/tui/src/local_settings_tests.rs
index 537a1dfc87..d30d67f673 100644
--- a/codex-rs/tui/src/local_settings_tests.rs
+++ b/codex-rs/tui/src/local_settings_tests.rs
@@ -22,8 +22,16 @@ async fn system_motion_suppresses_animations_without_changing_saved_preferences(
})
.build()
.await?;
- let animated = LocalSettings::with_system_motion(&config, MotionMode::Animated);
- let reduced = LocalSettings::with_system_motion(&config, MotionMode::Reduced);
+ let animated = LocalSettings::with_accessibility_preferences(
+ &config,
+ MotionMode::Animated,
+ MotionMode::Animated,
+ );
+ let reduced = LocalSettings::with_accessibility_preferences(
+ &config,
+ MotionMode::Reduced,
+ MotionMode::Animated,
+ );
let mut expected = animated.clone();
expected.tui.animations = false;
assert_eq!(reduced, expected);
@@ -140,3 +148,32 @@ async fn local_writes_preserve_selected_user_file_and_home_destinations() -> any
assert_eq!(home_config["tui"].get("theme"), None);
Ok(())
}
+
+#[tokio::test]
+async fn screen_reader_default_yields_to_preferences_on_reload() -> anyhow::Result<()> {
+ use crate::motion::MotionMode;
+
+ let home = tempfile::tempdir()?;
+ for (config_text, expected) in [
+ ("", false),
+ ("[tui]\nanimations = true\n", true),
+ ("[tui]\nanimations = false\n", false),
+ ] {
+ std::fs::write(home.path().join("config.toml"), config_text)?;
+ let config = ConfigBuilder::default()
+ .codex_home(home.path().to_path_buf())
+ .loader_overrides(LoaderOverrides {
+ ignore_project_config: true,
+ ..LoaderOverrides::without_managed_config_for_tests()
+ })
+ .build()
+ .await?;
+ let local = LocalSettings::with_accessibility_preferences(
+ &config,
+ MotionMode::Animated,
+ MotionMode::Reduced,
+ );
+ assert_eq!(local.tui.animations, expected);
+ }
+ Ok(())
+}
diff --git a/codex-rs/tui/src/screen_reader.rs b/codex-rs/tui/src/screen_reader.rs
new file mode 100644
index 0000000000..e4bc3919b5
--- /dev/null
+++ b/codex-rs/tui/src/screen_reader.rs
@@ -0,0 +1,193 @@
+//! Seeds a persistent animation default from a one-time host screen-reader probe.
+//!
+//! Presence of the completion marker skips detection, including when its value is false.
+//! Detection is bounded; explicit animation preferences and unrelated config are preserved.
+//! A detected reader also supplies a session default if persistence fails.
+
+use crate::motion::MotionMode;
+use codex_config::ConfigLayerStack;
+use codex_utils_path::resolve_symlink_write_paths;
+use codex_utils_path::write_atomically;
+use std::path::Path;
+use std::sync::OnceLock;
+use std::time::Duration;
+use toml_edit::DocumentMut;
+use toml_edit::value;
+
+const DETECTION_TIMEOUT: Duration = Duration::from_millis(/*millis*/ 450);
+static ANIMATION_DEFAULT: OnceLock<MotionMode> = OnceLock::new();
+
+pub(crate) async fn initialize(stack: &ConfigLayerStack) -> anyhow::Result<()> {
+ let (animation_default, result) = initialize_with_probe(stack, detect()).await;
+ let _ = ANIMATION_DEFAULT.set(animation_default);
+ result
+}
+
+pub(crate) fn animation_default() -> MotionMode {
+ ANIMATION_DEFAULT
+ .get()
+ .copied()
+ .unwrap_or(MotionMode::Animated)
+}
+
+async fn initialize_with_probe(
+ stack: &ConfigLayerStack,
+ probe: impl std::future::Future<Output = bool>,
+) -> (MotionMode, anyhow::Result<()>) {
+ let Some(path) = stack.get_user_config_file() else {
+ return (MotionMode::Animated, Ok(()));
+ };
+ let user_config = stack.effective_user_config();
+ let tui = user_config.as_ref().and_then(|config| config.get("tui"));
+ if tui
+ .and_then(|tui| tui.get("screen_reader_detection_done"))
+ .is_some()
+ {
+ return (MotionMode::Animated, Ok(()));
+ }
+ let animations_configured = tui.and_then(|tui| tui.get("animations")).is_some();
+ let mut animation_default = MotionMode::Animated;
+ let result = initialize_file(path.as_path(), animations_configured, async {
+ let detected = probe.await;
+ animation_default = MotionMode::from_animations_enabled(!detected);
+ detected
+ })
+ .await;
+ (animation_default, result)
+}
+
+async fn initialize_file(
+ path: &Path,
+ animations_configured: bool,
+ probe: impl std::future::Future<Output = bool>,
+) -> anyhow::Result<()> {
+ let mut doc = read_config(path)?;
+ if doc
+ .get("tui")
+ .and_then(|tui| tui.get("screen_reader_detection_done"))
+ .is_some()
+ {
+ return Ok(());
+ }
+ let detected = tokio::time::timeout(DETECTION_TIMEOUT, probe)
+ .await
+ .unwrap_or(false);
+ // Re-read after the probe so preferences saved during detection are preserved.
+ doc = read_config(path)?;
+ if doc
+ .get("tui")
+ .and_then(|tui| tui.get("screen_reader_detection_done"))
+ .is_some()
+ {
+ return Ok(());
+ }
+ doc.entry("tui")
+ .or_insert_with(|| toml_edit::Item::Table(toml_edit::Table::new()));
+ if detected
+ && !animations_configured
+ && doc
+ .get("tui")
+ .and_then(|tui| tui.get("animations"))
+ .is_none()
+ {
+ doc["tui"]["animations"] = value(false);
+ }
+ doc["tui"]["screen_reader_detection_done"] = value(true);
+ let paths = resolve_symlink_write_paths(path)?;
+ write_atomically(&paths.write_path, &doc.to_string())?;
+ Ok(())
+}
+
+fn read_config(path: &Path) -> anyhow::Result<DocumentMut> {
+ match std::fs::read_to_string(path) {
+ Ok(contents) => contents
+ .parse()
+ .map_err(|_| anyhow::anyhow!("invalid TOML in user config")),
+ Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(DocumentMut::new()),
+ Err(err) => Err(err.into()),
+ }
+}
+
+#[cfg(any(target_os = "macos", windows))]
+async fn detect() -> bool {
+ let (tx, rx) = tokio::sync::oneshot::channel();
+ // Native calls cannot be cancelled. A detached thread bounds startup and avoids waiting
+ // for a blocked OS probe when the Tokio runtime shuts down.
+ let _ = std::thread::Builder::new()
+ .name("screen-reader".into())
+ .spawn(move || {
+ #[cfg(target_os = "macos")]
+ let detected = objc2_app_kit::NSWorkspace::sharedWorkspace().isVoiceOverEnabled();
+ #[cfg(windows)]
+ let detected = {
+ use windows_sys::Win32::UI::WindowsAndMessaging::SPI_GETSCREENREADER;
+ use windows_sys::Win32::UI::WindowsAndMessaging::SystemParametersInfoW;
+ let mut enabled: windows_sys::Win32::Foundation::BOOL = 0;
+ // SAFETY: SPI_GETSCREENREADER writes one BOOL to this valid, aligned pointer.
+ let success = unsafe {
+ SystemParametersInfoW(
+ SPI_GETSCREENREADER,
+ /*uiparam*/ 0,
+ (&mut enabled as *mut windows_sys::Win32::Foundation::BOOL).cast(),
+ /*fwinini*/ 0,
+ )
+ };
+ (success != 0 && enabled != 0)
+ || windows_screen_reader::narrator_running() == Some(true)
+ };
+ let _ = tx.send(detected);
+ });
+ rx.await.unwrap_or(false)
+}
+
+#[cfg(target_os = "linux")]
+async fn detect() -> bool {
+ let Ok(connection) = zbus::Connection::session().await else {
+ return false;
+ };
+ let atspi = async {
+ let proxy = zbus::Proxy::new(
+ &connection,
+ "org.a11y.Bus",
+ "/org/a11y/bus",
+ "org.a11y.Status",
+ )
+ .await
+ .ok()?;
+ // Prefer the reader-specific signal. Newer AT-SPI only exposes IsEnabled, which can
+ // also indicate other assistive tools, so err on the side of reducing motion.
+ match proxy.get_property::<bool>("ScreenReaderEnabled").await {
+ Ok(enabled) => Some(enabled),
+ Err(_) => proxy.get_property::<bool>("IsEnabled").await.ok(),
+ }
+ };
+ let orca = async {
+ let proxy = zbus::fdo::DBusProxy::new(&connection).await.ok()?;
+ let names = proxy.list_names().await.ok()?;
+ Some(names.iter().any(|name| {
+ matches!(
+ name.as_str(),
+ "org.gnome.Orca.Service" | "org.gnome.Orca1.Service"
+ )
+ }))
+ };
+ tokio::pin!(atspi, orca);
+ // A positive probe wins immediately, even if the other probe is unresponsive.
+ tokio::select! {
+ result = &mut atspi => result == Some(true) || orca.await == Some(true),
+ result = &mut orca => result == Some(true) || atspi.await == Some(true),
+ }
+}
+
+#[cfg(not(any(target_os = "macos", target_os = "linux", windows)))]
+async fn detect() -> bool {
+ false
+}
+
+#[cfg(windows)]
+#[path = "screen_reader_windows.rs"]
+mod windows_screen_reader;
+
+#[cfg(test)]
+#[path = "screen_reader_tests.rs"]
+mod tests;
diff --git a/codex-rs/tui/src/screen_reader_tests.rs b/codex-rs/tui/src/screen_reader_tests.rs
new file mode 100644
index 0000000000..025f5ba77a
--- /dev/null
+++ b/codex-rs/tui/src/screen_reader_tests.rs
@@ -0,0 +1,207 @@
+use super::*;
+use pretty_assertions::assert_eq;
+
+#[tokio::test]
+async fn seeds_only_missing_preferences_and_never_probes_again() -> anyhow::Result<()> {
+ for (input, detected, expected) in [
+ (
+ "",
+ true,
+ "[tui]\nanimations = false\nscreen_reader_detection_done = true\n",
+ ),
+ ("", false, "[tui]\nscreen_reader_detection_done = true\n"),
+ (
+ "[tui]\nanimations = true\n",
+ true,
+ "[tui]\nanimations = true\nscreen_reader_detection_done = true\n",
+ ),
+ (
+ "[tui]\nanimations = false\n",
+ true,
+ "[tui]\nanimations = false\nscreen_reader_detection_done = true\n",
+ ),
+ (
+ "[tui]\nscreen_reader_detection_done = false\n",
+ true,
+ "[tui]\nscreen_reader_detection_done = false\n",
+ ),
+ (
+ "[tui]\nscreen_reader_detection_done = true\n",
+ true,
+ "[tui]\nscreen_reader_detection_done = true\n",
+ ),
+ ] {
+ let home = tempfile::tempdir()?;
+ let path = home.path().join("config.toml");
+ std::fs::write(&path, input)?;
+ initialize_file(
+ &path,
+ /*animations_configured*/ false,
+ std::future::ready(detected),
+ )
+ .await?;
+ initialize_file(
+ &path,
+ /*animations_configured*/ false,
+ async { panic!("repeated detection") },
+ )
+ .await?;
+ assert_eq!(std::fs::read_to_string(&path)?, expected);
+ }
+ Ok(())
+}
+
+#[tokio::test(start_paused = true)]
+async fn timeout_is_recorded_without_changing_animations() -> anyhow::Result<()> {
+ let home = tempfile::tempdir()?;
+ let path = home.path().join("config.toml");
+ let started = tokio::time::Instant::now();
+ initialize_file(
+ &path,
+ /*animations_configured*/ false,
+ std::future::pending(),
+ )
+ .await?;
+ assert_eq!(tokio::time::Instant::now() - started, DETECTION_TIMEOUT);
+ assert_eq!(
+ std::fs::read_to_string(path)?,
+ "[tui]\nscreen_reader_detection_done = true\n"
+ );
+ Ok(())
+}
+
+#[tokio::test]
+async fn preserves_preferences_from_other_layers_and_edits_during_detection() -> anyhow::Result<()>
+{
+ let home = tempfile::tempdir()?;
+ let path = home.path().join("config.toml");
+ initialize_file(
+ &path,
+ /*animations_configured*/ true,
+ std::future::ready(true),
+ )
+ .await?;
+ assert_eq!(
+ std::fs::read_to_string(&path)?,
+ "[tui]\nscreen_reader_detection_done = true\n"
+ );
+ std::fs::write(&path, "")?;
+ initialize_file(&path, /*animations_configured*/ false, async {
+ std::fs::write(
+ &path,
+ "# My preferences\n[tui]\nanimations = true # keep this\n",
+ )
+ .unwrap();
+ true
+ })
+ .await?;
+ assert_eq!(
+ std::fs::read_to_string(path)?,
+ "# My preferences\n[tui]\nanimations = true # keep this\nscreen_reader_detection_done = true\n"
+ );
+ Ok(())
+}
+
+#[tokio::test]
+async fn persisted_default_loads_and_renders_without_animation() -> anyhow::Result<()> {
+ use crate::app_event_sender::AppEventSender;
+ use crate::legacy_core::config::ConfigBuilder;
+ use crate::render::renderable::Renderable;
+ use crate::status_indicator_widget::StatusIndicatorWidget;
+ use crate::status_indicator_widget::StatusTimer;
+ use crate::tui::FrameRequester;
+ use codex_config::LoaderOverrides;
+ use ratatui::Terminal;
+ use ratatui::backend::TestBackend;
+
+ let home = tempfile::tempdir()?;
+ initialize_file(
+ &home.path().join("config.toml"),
+ /*animations_configured*/ false,
+ std::future::ready(true),
+ )
+ .await?;
+ let config = ConfigBuilder::default()
+ .codex_home(home.path().to_path_buf())
+ .loader_overrides(LoaderOverrides::without_managed_config_for_tests())
+ .build()
+ .await?;
+ assert!(!config.animations);
+ let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
+ let (frame_requester, mut frames) = FrameRequester::test_channel();
+ let mut status =
+ StatusIndicatorWidget::new(AppEventSender::new(tx), frame_requester, config.animations);
+ status.update_header("Reading the terminal output".into());
+ let mut timer = StatusTimer::default();
+ timer.pause_at(std::time::Instant::now());
+ let mut terminal = Terminal::new(TestBackend::new(/*width*/ 60, /*height*/ 1))?;
+ terminal.draw(|frame| {
+ status
+ .with_timer(&timer)
+ .render(frame.area(), frame.buffer_mut())
+ })?;
+ assert_eq!(
+ frames.try_recv(),
+ Err(tokio::sync::mpsc::error::TryRecvError::Empty)
+ );
+ insta::assert_snapshot!(terminal.backend());
+ Ok(())
+}
+
+#[tokio::test]
+async fn temporary_cli_override_does_not_suppress_the_saved_default() -> anyhow::Result<()> {
+ use crate::legacy_core::config::ConfigBuilder;
+ use codex_config::LoaderOverrides;
+
+ let home = tempfile::tempdir()?;
+ let config = ConfigBuilder::default()
+ .codex_home(home.path().to_path_buf())
+ .cli_overrides(vec![("tui.animations".into(), toml::Value::Boolean(true))])
+ .loader_overrides(LoaderOverrides::without_managed_config_for_tests())
+ .build()
+ .await?;
+ let (_, result) =
+ initialize_with_probe(&config.config_layer_stack, std::future::ready(true)).await;
+ result?;
+ assert_eq!(
+ std::fs::read_to_string(home.path().join("config.toml"))?,
+ "[tui]\nanimations = false\nscreen_reader_detection_done = true\n"
+ );
+ Ok(())
+}
+
+#[tokio::test]
+async fn detected_preference_survives_failed_persistence() -> anyhow::Result<()> {
+ use crate::legacy_core::config::ConfigBuilder;
+ use codex_config::LoaderOverrides;
+
+ let home = tempfile::tempdir()?;
+ let config = ConfigBuilder::default()
+ .codex_home(home.path().to_path_buf())
+ .loader_overrides(LoaderOverrides::without_managed_config_for_tests())
+ .build()
+ .await?;
+ let (mode, result) = initialize_with_probe(&config.config_layer_stack, async {
+ // Make the destination unwritable after detection has started.
+ std::fs::create_dir(home.path().join("config.toml")).unwrap();
+ true
+ })
+ .await;
+ assert_eq!(mode, MotionMode::Reduced);
+ assert!(result.is_err());
+ Ok(())
+}
+
+#[tokio::test]
+async fn malformed_edit_during_detection_does_not_expose_config_contents() -> anyhow::Result<()> {
+ let home = tempfile::tempdir()?;
+ let path = home.path().join("config.toml");
+ let error = initialize_file(&path, /*animations_configured*/ false, async {
+ std::fs::write(&path, "token = secret-token").unwrap();
+ true
+ })
+ .await
+ .unwrap_err();
+ assert_eq!(error.to_string(), "invalid TOML in user config");
+ Ok(())
+}
diff --git a/codex-rs/tui/src/screen_reader_windows.rs b/codex-rs/tui/src/screen_reader_windows.rs
new file mode 100644
index 0000000000..7e9bcfcd61
--- /dev/null
+++ b/codex-rs/tui/src/screen_reader_windows.rs
@@ -0,0 +1,64 @@
+//! Detects Windows Narrator in the TUI's own login session.
+//!
+//! Narrator does not set the screen-reader flag used by other Windows accessibility aids. Do not
+//! use a Narrator process in another session to change this terminal's behavior.
+
+use windows_sys::Win32::Foundation::CloseHandle;
+use windows_sys::Win32::Foundation::ERROR_NO_MORE_FILES;
+use windows_sys::Win32::Foundation::GetLastError;
+use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE;
+use windows_sys::Win32::System::Diagnostics::ToolHelp::CreateToolhelp32Snapshot;
+use windows_sys::Win32::System::Diagnostics::ToolHelp::PROCESSENTRY32W;
+use windows_sys::Win32::System::Diagnostics::ToolHelp::Process32FirstW;
+use windows_sys::Win32::System::Diagnostics::ToolHelp::Process32NextW;
+use windows_sys::Win32::System::Diagnostics::ToolHelp::TH32CS_SNAPPROCESS;
+use windows_sys::Win32::System::RemoteDesktop::ProcessIdToSessionId;
+
+pub(super) fn narrator_running() -> Option<bool> {
+ let current_session = process_session(std::process::id())?;
+ // SAFETY: This requests a system-wide process snapshot and ignores the process ID.
+ let snapshot = unsafe {
+ CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, /*th32processid*/ 0)
+ };
+ if snapshot == INVALID_HANDLE_VALUE {
+ return None;
+ }
+
+ let result = (|| {
+ // SAFETY: All-zero is valid for this Win32 struct; dwSize must then be set for the API.
+ let mut entry: PROCESSENTRY32W = unsafe { std::mem::zeroed() };
+ entry.dwSize = std::mem::size_of::<PROCESSENTRY32W>() as u32;
+ let mut inaccessible_match = false;
+ // SAFETY: The snapshot is valid and entry is an initialized, correctly sized output.
+ let mut has_entry = unsafe { Process32FirstW(snapshot, &mut entry) };
+ while has_entry != 0 {
+ let name_end = entry
+ .szExeFile
+ .iter()
+ .position(|unit| *unit == 0)
+ .unwrap_or(entry.szExeFile.len());
+ if String::from_utf16_lossy(&entry.szExeFile[..name_end])
+ .eq_ignore_ascii_case("Narrator.exe")
+ {
+ match process_session(entry.th32ProcessID) {
+ Some(session) if session == current_session => return Some(true),
+ Some(_) => {}
+ None => inaccessible_match = true,
+ }
+ }
+ // SAFETY: The snapshot and output remain valid for the duration of the iteration.
+ has_entry = unsafe { Process32NextW(snapshot, &mut entry) };
+ }
+ // SAFETY: This immediately follows the failed enumeration call on this thread.
+ (unsafe { GetLastError() } == ERROR_NO_MORE_FILES && !inaccessible_match).then_some(false)
+ })();
+ // SAFETY: This closes the successful snapshot exactly once, after its last use.
+ unsafe { CloseHandle(snapshot) };
+ result
+}
+
+fn process_session(process_id: u32) -> Option<u32> {
+ let mut session = 0;
+ // SAFETY: The API writes a session ID to this valid output pointer.
+ (unsafe { ProcessIdToSessionId(process_id, &mut session) } != 0).then_some(session)
+}
diff --git a/codex-rs/tui/src/snapshots/codex_tui__screen_reader__tests__persisted_default_loads_and_renders_without_animation.snap b/codex-rs/tui/src/snapshots/codex_tui__screen_reader__tests__persisted_default_loads_and_renders_without_animation.snap
new file mode 100644
index 0000000000..9632a7ab9c
--- /dev/null
+++ b/codex-rs/tui/src/snapshots/codex_tui__screen_reader__tests__persisted_default_loads_and_renders_without_animation.snap
@@ -0,0 +1,5 @@
+---
+source: tui/src/screen_reader_tests.rs
+expression: terminal.backend()
+---
+"Reading the terminal output (0s • esc to interrupt) "
diff --git a/codex-rs/tui/src/startup_orchestration.rs b/codex-rs/tui/src/startup_orchestration.rs
index db0e05f63b..28ecb47046 100644
--- a/codex-rs/tui/src/startup_orchestration.rs
+++ b/codex-rs/tui/src/startup_orchestration.rs
@@ -258,6 +258,15 @@ pub(super) async fn run_main_inner(
CloudConfigBundleLoader::default(),
))
.await?;
+ let screen_reader_result = if !loader_overrides.ignore_user_config {
+ startup_draft
+ .run_until(screen_reader::initialize(
+ &bootstrap_config.config_layer_stack,
+ ))
+ .await?
+ } else {
+ Ok(())
+ };
let cloud_config_bundle = startup_draft
.run_until(cloud_config_bundle_for_app_server_target(
&app_server_target,
@@ -626,6 +635,10 @@ pub(super) async fn run_main_inner(
.with(otel_tracing_layer)
.try_init();
+ if let Err(err) = screen_reader_result {
+ tracing::warn!("Could not save screen-reader detection: {err}");
+ }
+
let app_result = run_ratatui_app(
cli,
arg0_paths,
diff --git a/codex-rs/tui/tests/suite/mod.rs b/codex-rs/tui/tests/suite/mod.rs
index eb2b3e0ba6..3e316c2c33 100644
--- a/codex-rs/tui/tests/suite/mod.rs
+++ b/codex-rs/tui/tests/suite/mod.rs
@@ -6,6 +6,8 @@ mod focus_palette;
#[cfg(unix)]
mod reconnect;
mod resize_reflow;
+#[cfg(unix)]
+mod screen_reader;
mod status_indicator;
mod vt100_history;
mod vt100_live_commit;
diff --git a/codex-rs/tui/tests/suite/screen_reader.rs b/codex-rs/tui/tests/suite/screen_reader.rs
new file mode 100644
index 0000000000..5c6195d499
--- /dev/null
+++ b/codex-rs/tui/tests/suite/screen_reader.rs
@@ -0,0 +1,39 @@
+//! Checks that interactive startup persists detection without replacing a user preference.
+
+use super::focus_palette::PtyCodex;
+use super::focus_palette::write_test_config;
+use anyhow::Result;
+use pretty_assertions::assert_eq;
+use std::time::Duration;
+use std::time::Instant;
+
+#[test]
+fn startup_records_screen_reader_detection() -> Result<()> {
+ let repo_root = codex_utils_cargo_bin::repo_root()?;
+ let home = tempfile::tempdir()?;
+ write_test_config(home.path(), &repo_root)?;
+ let path = home.path().join("config.toml");
+ let contents = std::fs::read_to_string(&path)?;
+ std::fs::write(&path, format!("{contents}\n[tui]\nanimations = true\n"))?;
+ let mut terminal = PtyCodex::start(&repo_root, home, &[])?;
+ terminal.wait_for_startup()?;
+ let deadline = Instant::now() + Duration::from_secs(/*secs*/ 30);
+ loop {
+ let config: toml::Value = toml::from_str(&std::fs::read_to_string(&path)?)?;
+ if config["tui"].get("screen_reader_detection_done").is_some() {
+ assert_eq!(
+ config["tui"],
+ toml::Value::Table(toml::toml! {
+ animations = true
+ screen_reader_detection_done = true
+ })
+ );
+ return Ok(());
+ }
+ anyhow::ensure!(
+ Instant::now() < deadline,
+ "startup did not record detection"
+ );
+ terminal.read_output(Duration::from_millis(/*millis*/ 50))?;
+ }
+}