diff --git a/codex-rs/app-server-daemon/src/backend/pid_start.rs b/codex-rs/app-server-daemon/src/backend/pid_start.rs index 11fdd3495b..1c286a8b14 100644 --- a/codex-rs/app-server-daemon/src/backend/pid_start.rs +++ b/codex-rs/app-server-daemon/src/backend/pid_start.rs @@ -235,7 +235,11 @@ impl PidBackend { } } - let child = match command.spawn() { + #[cfg(windows)] + let child = super::super::windows::spawn_without_inheriting_stdio(&mut command); + #[cfg(not(windows))] + let child = command.spawn().map_err(anyhow::Error::from); + let child = match child { Ok(child) => child, Err(err) => { if replacement.is_none() { @@ -258,10 +262,6 @@ impl PidBackend { .id() .context("spawned app-server process has no pid")?; let record = match async { - #[cfg(windows)] - super::super::windows::Process::open(pid)? - .context("daemon exited during launch")? - .ensure_detached()?; let process_start_time = read_process_start_time(pid).await?; #[cfg(any(target_os = "linux", target_os = "macos"))] let process_identity = super::identity::read_process_details(pid) diff --git a/codex-rs/app-server-daemon/src/backend/windows.rs b/codex-rs/app-server-daemon/src/backend/windows.rs index 157bf3343a..53603afe2b 100644 --- a/codex-rs/app-server-daemon/src/backend/windows.rs +++ b/codex-rs/app-server-daemon/src/backend/windows.rs @@ -2,7 +2,10 @@ //! so PID reuse can never redirect forced termination to a different process. //! Managed servers must not elevate ordinary clients sharing the account's socket. //! Installer jobs contain extraction processes when an update is cancelled. +//! Detached launches stop the launcher's original stdio handles from propagating. +//! Launch probes distinguish job restrictions from other failures without running the binary. +use std::fmt; use std::io; use std::os::windows::io::AsRawHandle; use std::os::windows::io::FromRawHandle; @@ -14,9 +17,14 @@ use std::process::Stdio; use anyhow::Context; use anyhow::Result; +use windows_sys::Win32::Foundation::ERROR_ACCESS_DENIED; +use windows_sys::Win32::Foundation::ERROR_INVALID_HANDLE; use windows_sys::Win32::Foundation::ERROR_INVALID_PARAMETER; use windows_sys::Win32::Foundation::ERROR_LOCK_VIOLATION; use windows_sys::Win32::Foundation::FILETIME; +use windows_sys::Win32::Foundation::HANDLE_FLAG_INHERIT; +use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE; +use windows_sys::Win32::Foundation::SetHandleInformation; use windows_sys::Win32::Foundation::WAIT_OBJECT_0; use windows_sys::Win32::Foundation::WAIT_TIMEOUT; use windows_sys::Win32::Security::GetTokenInformation; @@ -28,7 +36,6 @@ use windows_sys::Win32::Storage::FileSystem::LOCKFILE_FAIL_IMMEDIATELY; use windows_sys::Win32::Storage::FileSystem::LockFileEx; use windows_sys::Win32::System::JobObjects::AssignProcessToJobObject; use windows_sys::Win32::System::JobObjects::CreateJobObjectW; -use windows_sys::Win32::System::JobObjects::IsProcessInJob; use windows_sys::Win32::System::JobObjects::JOB_OBJECT_LIMIT_BREAKAWAY_OK; use windows_sys::Win32::System::JobObjects::JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; use windows_sys::Win32::System::JobObjects::JOBOBJECT_EXTENDED_LIMIT_INFORMATION; @@ -49,6 +56,38 @@ use windows_sys::Win32::System::Threading::PROCESS_TERMINATE; use windows_sys::Win32::System::Threading::TerminateProcess; use windows_sys::Win32::System::Threading::WaitForSingleObject; +pub(super) fn spawn_without_inheriting_stdio( + command: &mut tokio::process::Command, +) -> Result { + // The daemon must not inherit the launcher's output pipes: callers wait for + // them to close after the launcher exits. Leave the flags cleared so concurrent + // launches cannot inherit them either; Rust duplicates the child's chosen stdio. + for (name, handle) in [ + ("stdin", io::stdin().as_raw_handle()), + ("stdout", io::stdout().as_raw_handle()), + ("stderr", io::stderr().as_raw_handle()), + ] { + if handle.is_null() || handle as isize == INVALID_HANDLE_VALUE { + continue; + } + // SAFETY: these are borrowed standard handles; changing the inherit + // flag neither closes them nor changes their read/write access. + if unsafe { + SetHandleInformation(handle as _, HANDLE_FLAG_INHERIT, /*dwflags*/ 0) + } == 0 + { + let error = io::Error::last_os_error(); + // An already-closed handle cannot be inherited. + if error.raw_os_error() == Some(ERROR_INVALID_HANDLE as i32) { + continue; + } + return Err(error) + .with_context(|| format!("failed to clear launcher {name} inheritance")); + } + } + Ok(command.spawn()?) +} + pub(crate) fn ensure_not_elevated() -> Result<()> { let mut token = 0; if unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) } == 0 { @@ -77,32 +116,44 @@ pub(crate) fn ensure_not_elevated() -> Result<()> { Ok(()) } -// Probe the actual child association: escaping an inner job can leave an outer -// job attached. Suspend the image so no application code runs before cleanup. +/// A launch that only fails when asked to leave the launcher's Windows job. +/// Automatic CLI startup may use its embedded server; lifecycle operations +/// must still return this error before stopping an existing daemon. +#[derive(Debug)] +pub struct DetachedLaunchRestricted; + +impl fmt::Display for DetachedLaunchRestricted { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str( + "this Windows launcher prevents background processes from outliving it (for example, cargo run); build and run codex.exe directly to use the background server", + ) + } +} + +// Check that breakaway launch is permitted before stopping an existing daemon. +// An outer system job may remain attached; membership alone does not establish +// whether it will terminate the daemon. Suspend the probe before cleanup. pub(crate) fn ensure_detached_launch(executable: &Path) -> Result<()> { - let mut child = Command::new(executable) - .creation_flags(CREATE_SUSPENDED | DETACHED_PROCESS | CREATE_BREAKAWAY_FROM_JOB) + let mut command = Command::new(executable); + command .stdin(Stdio::null()) .stdout(Stdio::null()) .stderr(Stdio::null()) - .spawn() - .context("cannot launch detached daemon; existing daemon was not stopped")?; - let mut in_job = 0; - let result = if unsafe { - IsProcessInJob( - child.as_raw_handle() as _, - /*jobhandle*/ 0, - &mut in_job, - ) - } == 0 - { - Err(io::Error::last_os_error()).context("failed to verify daemon launch capability") - } else if in_job != 0 { - Err(anyhow::anyhow!( - "host Job Object prevents daemon detachment; start from a host that allows breakaway" - )) - } else { - Ok(()) + .creation_flags(CREATE_SUSPENDED | DETACHED_PROCESS | CREATE_BREAKAWAY_FROM_JOB); + let (mut child, launch_result) = match command.spawn() { + Ok(child) => (child, Ok(())), + Err(err) if err.raw_os_error() == Some(ERROR_ACCESS_DENIED as i32) => { + // Access denied can also mean the file cannot be executed. Only + // classify a job restriction if removing breakaway makes it work. + // This diagnostic child stays suspended and is always reaped. + command.creation_flags(CREATE_SUSPENDED | DETACHED_PROCESS); + let child = match command.spawn() { + Ok(child) => child, + Err(_) => return Err(err).context("cannot launch detached daemon"), + }; + (child, Err(err).context(DetachedLaunchRestricted)) + } + Err(err) => return Err(err).context("cannot launch detached daemon"), }; child .kill() @@ -110,7 +161,7 @@ pub(crate) fn ensure_detached_launch(executable: &Path) -> Result<()> { child .wait() .context("failed to reap suspended launch probe")?; - result + launch_result } pub(super) struct Process(OwnedHandle); @@ -170,29 +221,6 @@ impl Process { } } - pub(super) fn ensure_detached(&self) -> Result<()> { - let mut in_job = 0; - if unsafe { - IsProcessInJob( - self.0.as_raw_handle() as _, - /*jobhandle*/ 0, - &mut in_job, - ) - } == 0 - { - let error = io::Error::last_os_error(); - self.terminate()?; - return Err(error).context("failed to verify daemon detachment"); - } - if in_job != 0 { - self.terminate()?; - anyhow::bail!( - "host Job Object prevents daemon detachment; start from a host that allows breakaway" - ); - } - Ok(()) - } - pub(super) fn terminate(&self) -> Result<()> { if !self.is_running()? { return Ok(()); diff --git a/codex-rs/app-server-daemon/src/backend/windows_tests.rs b/codex-rs/app-server-daemon/src/backend/windows_tests.rs index 7ce59b332b..1910b2c96f 100644 --- a/codex-rs/app-server-daemon/src/backend/windows_tests.rs +++ b/codex-rs/app-server-daemon/src/backend/windows_tests.rs @@ -1,10 +1,136 @@ use super::Process; use pretty_assertions::assert_eq; use std::os::windows::io::AsRawHandle; +use std::os::windows::io::FromRawHandle; +use std::os::windows::io::OwnedHandle; +use std::os::windows::process::CommandExt; +use std::process::Stdio; +use std::time::Duration; +use tokio::io::AsyncReadExt; use windows_sys::Win32::Foundation::ERROR_ACCESS_DENIED; +use windows_sys::Win32::Foundation::HANDLE_FLAG_INHERIT; +use windows_sys::Win32::Foundation::SetHandleInformation; +use windows_sys::Win32::System::JobObjects::IsProcessInJob; use windows_sys::Win32::System::Threading::CREATE_NO_WINDOW; +use windows_sys::Win32::System::Threading::DETACHED_PROCESS; use windows_sys::Win32::System::Threading::TerminateProcess; +#[tokio::test] +async fn captured_stdio_closes_while_child_is_alive() { + const TEST: &str = "backend::windows::tests::captured_stdio_closes_while_child_is_alive"; + const ROLE: &str = "CODEX_TEST_STDIO_ROLE"; + const HOME: &str = "CODEX_TEST_STDIO_HOME"; + let executable = std::env::current_exe().expect("test executable"); + + if let Ok(role) = std::env::var(ROLE) { + let home = std::path::PathBuf::from(std::env::var_os(HOME).expect("test home")); + if role == "child" { + eprintln!("child stderr"); + std::fs::write(home.join("ready"), []).unwrap(); + tokio::time::sleep(Duration::from_secs(30)).await; + return; + } + + let handles = [ + std::io::stdout().as_raw_handle() as _, + std::io::stderr().as_raw_handle() as _, + ]; + for handle in handles { + assert_ne!( + unsafe { SetHandleInformation(handle, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT) }, + 0 + ); + } + let mut command = tokio::process::Command::new(executable); + command + .args(["--exact", TEST, "--nocapture"]) + .env(ROLE, "child") + // The CI job may forbid breakaway; it does not affect stdio inheritance. + .creation_flags(DETACHED_PROCESS) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(std::fs::File::create(home.join("child.log")).unwrap()); + let child = super::spawn_without_inheriting_stdio(&mut command).unwrap(); + let pid = child.id().unwrap(); + let started = Process::open(pid).unwrap().unwrap().start_time().unwrap(); + std::fs::write( + home.join("pid"), + serde_json::to_vec(&(pid, started)).unwrap(), + ) + .unwrap(); + println!("launcher stdout"); + eprintln!("launcher stderr"); + return; + } + + let home = tempfile::tempdir().unwrap(); + let mut launcher = tokio::process::Command::new(executable) + .args(["--exact", TEST, "--nocapture"]) + .env(ROLE, "launcher") + .env(HOME, home.path()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .kill_on_drop(true) + .spawn() + .unwrap(); + let status = tokio::time::timeout(Duration::from_secs(10), launcher.wait()) + .await + .expect("launcher exit") + .unwrap(); + let (pid, started): (u32, String) = + serde_json::from_slice(&std::fs::read(home.path().join("pid")).unwrap()).unwrap(); + let child = Process::open(pid).unwrap().expect("live child"); + assert_eq!( + child.start_time().unwrap(), + started, + "fixture PID was reused" + ); + let mut stdout = String::new(); + let mut stderr = String::new(); + let captured = tokio::time::timeout(Duration::from_secs(5), async { + let ready = home.path().join("ready"); + while !ready.exists() { + tokio::time::sleep(Duration::from_millis(25)).await; + } + tokio::try_join!( + launcher + .stdout + .as_mut() + .unwrap() + .read_to_string(&mut stdout), + launcher + .stderr + .as_mut() + .unwrap() + .read_to_string(&mut stderr), + ) + }) + .await; + let still_running = child.is_running(); + child.terminate().expect("cleanup child"); + tokio::time::timeout(Duration::from_secs(5), async { + while child.is_running().unwrap() { + tokio::time::sleep(Duration::from_millis(25)).await; + } + }) + .await + .expect("child exit after cleanup"); + + captured.expect("launcher output must close").unwrap(); + assert!(status.success(), "{stderr}"); + assert!( + still_running.unwrap(), + "child exited before its launcher output closed" + ); + assert!(stdout.contains("launcher stdout")); + assert!(stderr.contains("launcher stderr")); + assert!( + std::fs::read_to_string(home.path().join("child.log")) + .unwrap() + .contains("child stderr") + ); +} + #[test] fn detached_launch_preflight_rejects_restrictive_job() { const CHILD: &str = "CODEX_TEST_RESTRICTIVE_LAUNCH_JOB"; @@ -25,7 +151,17 @@ fn detached_launch_preflight_rejects_restrictive_job() { 0 ); // A new job does not permit breakaway. Reject before any lifecycle mutation. - assert!(super::ensure_detached_launch(&executable).is_err()); + let err = super::ensure_detached_launch(&executable).expect_err("breakaway forbidden"); + assert!( + err.is::(), + "expected a classified job restriction: {err:#}" + ); + // File access failures must still fail normally, even in a restricted + // job: a CLI must not hide corrupt or inaccessible installations. + let temp = tempfile::tempdir().expect("test directory"); + let err = + super::ensure_detached_launch(temp.path()).expect_err("directory is not an executable"); + assert!(!err.is::(), "{err:#}"); return; } let output = std::process::Command::new(executable) @@ -45,6 +181,154 @@ fn detached_launch_preflight_rejects_restrictive_job() { assert!(String::from_utf8_lossy(&output.stdout).contains("1 passed")); } +#[test] +fn detached_launch_preflight_allows_residual_job() { + const CHILD: &str = "CODEX_TEST_RESIDUAL_LAUNCH_JOB"; + let executable = std::env::current_exe().expect("test executable"); + if std::env::var_os(CHILD).is_some() { + let mut jobs = Vec::new(); + for inner in [false, true] { + let job = unsafe { super::CreateJobObjectW(std::ptr::null(), std::ptr::null()) }; + assert_ne!(job, 0); + let job = unsafe { OwnedHandle::from_raw_handle(job as _) }; + if inner { + let mut limits: super::JOBOBJECT_EXTENDED_LIMIT_INFORMATION = + unsafe { std::mem::zeroed() }; + limits.BasicLimitInformation.LimitFlags = super::JOB_OBJECT_LIMIT_BREAKAWAY_OK; + assert_ne!( + unsafe { + super::SetInformationJobObject( + job.as_raw_handle() as _, + super::JobObjectExtendedLimitInformation, + (&limits as *const super::JOBOBJECT_EXTENDED_LIMIT_INFORMATION).cast(), + std::mem::size_of_val(&limits) as u32, + ) + }, + 0 + ); + } + assert_ne!( + unsafe { + super::AssignProcessToJobObject( + job.as_raw_handle() as _, + super::GetCurrentProcess(), + ) + }, + 0 + ); + jobs.push(job); + } + + let mut probe = std::process::Command::new(&executable) + .creation_flags( + super::CREATE_SUSPENDED + | super::DETACHED_PROCESS + | super::CREATE_BREAKAWAY_FROM_JOB, + ) + .spawn() + .expect("breakaway probe"); + let mut in_outer = 0; + let mut in_inner = 0; + let outer_checked = unsafe { + IsProcessInJob( + probe.as_raw_handle() as _, + jobs[0].as_raw_handle() as _, + &mut in_outer, + ) + }; + let inner_checked = unsafe { + IsProcessInJob( + probe.as_raw_handle() as _, + jobs[1].as_raw_handle() as _, + &mut in_inner, + ) + }; + probe.kill().expect("terminate probe"); + probe.wait().expect("reap probe"); + assert_ne!(outer_checked, 0); + assert_ne!(inner_checked, 0); + assert_ne!(in_outer, 0, "probe must retain its outer job"); + assert_eq!(in_inner, 0, "probe must leave its inner job"); + super::ensure_detached_launch(&executable).expect("residual job must be accepted"); + + if let Err(err) = super::ensure_not_elevated() { + assert!(err.to_string().contains("non-elevated terminal")); + return; + } + let temp = tempfile::tempdir().expect("temp dir"); + let script = temp.path().join("codex.cmd"); + std::fs::write( + &script, + "@echo off\r\nif \"%3\"==\"--help\" exit /b 1\r\necho ready > \"%~dp0ready\"\r\nfor /l %%i in (1,1,10000000) do @rem\r\n", + ) + .expect("write daemon fixture"); + let backend = crate::backend::pid::PidBackend::new( + script, + temp.path().join("state").join("daemon.pid"), + /*remote_control_enabled*/ false, + ); + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("runtime"); + let pid = runtime + .block_on(backend.start()) + .expect("daemon launch") + .expect("new daemon pid"); + let process = Process::open(pid) + .expect("open daemon") + .expect("live daemon"); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + while !temp.path().join("ready").exists() && std::time::Instant::now() < deadline { + std::thread::sleep(std::time::Duration::from_millis(50)); + } + let ready = temp.path().join("ready").exists(); + let outer_checked = unsafe { + IsProcessInJob( + process.0.as_raw_handle() as _, + jobs[0].as_raw_handle() as _, + &mut in_outer, + ) + }; + let inner_checked = unsafe { + IsProcessInJob( + process.0.as_raw_handle() as _, + jobs[1].as_raw_handle() as _, + &mut in_inner, + ) + }; + process.terminate().expect("terminate daemon fixture"); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + while process.is_running().expect("daemon liveness") && std::time::Instant::now() < deadline + { + std::thread::sleep(std::time::Duration::from_millis(50)); + } + assert!(!process.is_running().expect("daemon liveness")); + assert!(ready, "daemon fixture did not start"); + assert_ne!(outer_checked, 0); + assert_ne!(inner_checked, 0); + assert_ne!(in_outer, 0, "daemon must retain its outer job"); + assert_eq!(in_inner, 0, "daemon must leave its inner job"); + return; + } + let output = std::process::Command::new(executable) + .args([ + "--exact", + "backend::windows::tests::detached_launch_preflight_allows_residual_job", + "--nocapture", + ]) + .env(CHILD, "1") + .output() + .expect("isolated job test"); + assert!( + output.status.success(), + "{}\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + assert!(String::from_utf8_lossy(&output.stdout).contains("1 passed")); +} + #[tokio::test] async fn identity_queries_do_not_require_termination_access() { let mut child = tokio::process::Command::new("powershell.exe") diff --git a/codex-rs/app-server-daemon/src/launch.rs b/codex-rs/app-server-daemon/src/launch.rs index 04d58401a6..cd283a3c97 100644 --- a/codex-rs/app-server-daemon/src/launch.rs +++ b/codex-rs/app-server-daemon/src/launch.rs @@ -11,11 +11,13 @@ use std::collections::BTreeMap; /// Start a missing daemon with these features, preserving other saved overrides, /// or leave a running daemon unchanged. /// Callers must check the running server's configuration before using it. +/// Startup diagnostics go to tracing, so a caller with a live TUI can keep rendering. pub async fn start_with_features(features: &BTreeMap) -> Result { ensure_supported_platform()?; #[cfg(windows)] crate::backend::windows::ensure_not_elevated()?; - let daemon = Daemon::from_environment()?; + let mut daemon = Daemon::from_environment()?; + daemon.log_diagnostics = true; let _operation_lock = daemon.acquire_operation_lock().await?; let selected = daemon.current_installation()?; let mut overrides = selected.load_settings().await?.feature_overrides; diff --git a/codex-rs/app-server-daemon/src/lib.rs b/codex-rs/app-server-daemon/src/lib.rs index 755a0ebd82..15ba7692b9 100644 --- a/codex-rs/app-server-daemon/src/lib.rs +++ b/codex-rs/app-server-daemon/src/lib.rs @@ -2,6 +2,8 @@ mod backend; #[cfg(windows)] +pub use backend::windows::DetachedLaunchRestricted; +#[cfg(windows)] use backend::windows::try_lock_file; mod client; mod install_lock; @@ -304,6 +306,9 @@ fn ensure_supported_platform() -> Result<()> { #[derive(Clone)] struct Daemon { + // Feature-aware TUI startup owns a live terminal. Direct lifecycle commands + // must still report their diagnostics to stderr. + log_diagnostics: bool, socket_path: PathBuf, pid_file: PathBuf, update_pid_file: PathBuf, @@ -328,6 +333,7 @@ impl Daemon { (DAEMON_PID_FILE_NAME, DAEMON_UPDATE_PID_FILE_NAME) }; Ok(Self { + log_diagnostics: false, socket_path, pid_file: state_dir.join(pid_file), update_pid_file: state_dir.join(update_pid_file), @@ -337,6 +343,14 @@ impl Daemon { }) } + fn diagnostic(&self, message: std::fmt::Arguments<'_>) { + if self.log_diagnostics { + tracing::info!("{message}"); + } else { + eprintln!("{message}"); + } + } + fn recovery_file(&self) -> Result { Ok(codex_app_server_transport::daemon_recovery_file_path( self.settings_file @@ -409,7 +423,9 @@ impl Daemon { } else { // A fresh start must ignore snapshots left by older stop clients. if let Err(err) = thread_recovery::discard_pending(self) { - eprintln!("warning: failed to clear stale daemon recovery before start: {err}"); + self.diagnostic(format_args!( + "warning: failed to clear stale daemon recovery before start: {err}" + )); } prepare_install::prepare(self, &settings).await?; managed.managed_codex_bin = self.current_managed_codex_bin()?; @@ -431,7 +447,9 @@ impl Daemon { if backend.is_some() && let Err(err) = managed.ensure_managed_updater(&settings).await { - eprintln!("warning: failed to ensure managed updater after app-server start: {err:#}"); + self.diagnostic(format_args!( + "warning: failed to ensure managed updater after app-server start: {err:#}" + )); } Ok(managed .output(status, backend, pid, Some(info.app_server_version)) @@ -1250,6 +1268,7 @@ mod tests { let legacy = home.path().join("packages/standalone/current"); std::fs::create_dir_all(&legacy).expect("legacy selection"); let daemon = Daemon { + log_diagnostics: false, socket_path: home.path().join("server.sock"), pid_file: state.join(super::LEGACY_PID_FILE_NAME), update_pid_file: state.join(super::LEGACY_UPDATE_PID_FILE_NAME), @@ -1283,6 +1302,7 @@ mod tests { let temp = TempDir::new().expect("temp dir"); let state = temp.path().join("missing-home").join("daemon-state"); let daemon = Daemon { + log_diagnostics: false, socket_path: state.join("server.sock"), pid_file: state.join("server.pid"), update_pid_file: state.join("updater.pid"), @@ -1308,6 +1328,7 @@ mod tests { .await .expect("private state directory"); let daemon = Daemon { + log_diagnostics: false, socket_path: home.path().join("server.sock"), pid_file: state.join("server.pid"), update_pid_file: state.join("updater.pid"), @@ -1362,6 +1383,7 @@ mod tests { .expect("current local build"); let state = home.path().join("app-server-daemon"); let daemon = Daemon { + log_diagnostics: false, socket_path: home .path() .join("app-server-control/app-server-control.sock"), @@ -1389,6 +1411,7 @@ mod tests { async fn not_ready_context_reports_daemon_app_server_before_stderr() { let temp_dir = TempDir::new().expect("temp dir"); let daemon = Daemon { + log_diagnostics: false, socket_path: temp_dir.path().join("app-server-control.sock"), pid_file: temp_dir.path().join("app-server.pid"), update_pid_file: temp_dir.path().join("app-server-updater.pid"), diff --git a/codex-rs/app-server-daemon/src/prepare_install.rs b/codex-rs/app-server-daemon/src/prepare_install.rs index 290ceae25d..ecf2501d22 100644 --- a/codex-rs/app-server-daemon/src/prepare_install.rs +++ b/codex-rs/app-server-daemon/src/prepare_install.rs @@ -184,10 +184,10 @@ async fn prepare_from_package( return Ok(false); } } else { - eprintln!( + daemon.diagnostic(format_args!( "Installing daemon from CLI version {version} into {}...", root.display() - ); + )); } // Confirmation must not block lifecycle commands. Recheck the approved // selection and running state once this operation owns both locks. diff --git a/codex-rs/app-server-daemon/src/prepare_install_tests.rs b/codex-rs/app-server-daemon/src/prepare_install_tests.rs index 45cfee41f7..810a45b433 100644 --- a/codex-rs/app-server-daemon/src/prepare_install_tests.rs +++ b/codex-rs/app-server-daemon/src/prepare_install_tests.rs @@ -12,6 +12,7 @@ use std::path::PathBuf; fn daemon(home: &std::path::Path) -> crate::Daemon { let state = home.join("app-server-daemon"); crate::Daemon { + log_diagnostics: false, socket_path: state.join("app-server.sock"), pid_file: state.join("app-server.pid"), update_pid_file: state.join("app-server-updater.pid"), diff --git a/codex-rs/app-server-daemon/src/update_loop_tests.rs b/codex-rs/app-server-daemon/src/update_loop_tests.rs index 6dcabe53fe..d932742371 100644 --- a/codex-rs/app-server-daemon/src/update_loop_tests.rs +++ b/codex-rs/app-server-daemon/src/update_loop_tests.rs @@ -301,6 +301,7 @@ fn manual_update_daemon(home: &TempDir) -> (Daemon, String) { std::fs::write(state.join("app-server.stderr.log"), b"").unwrap(); ( Daemon { + log_diagnostics: false, socket_path: home.path().join("app-server-control/server.sock"), pid_file: state.join("app-server.pid"), update_pid_file: state.join("app-server-updater.pid"), diff --git a/codex-rs/cli/tests/daemon_startup.rs b/codex-rs/cli/tests/daemon_startup.rs index 828ccf1d11..be8752836e 100644 --- a/codex-rs/cli/tests/daemon_startup.rs +++ b/codex-rs/cli/tests/daemon_startup.rs @@ -59,6 +59,28 @@ async fn daemon_auto_start_preserves_bedrock_onboarding() -> Result<()> { daemon_startup("bedrock").await } +#[tokio::test] +#[cfg(windows)] +async fn restrictive_launcher_uses_embedded_if_daemon_cannot_start() -> Result<()> { + const CHILD: &str = "CODEX_TEST_RESTRICTIVE_DAEMON_START"; + if std::env::var_os(CHILD).is_some() { + // The PTY creates its own breakaway-permitted job. Add Cargo's + // restriction *inside* the PTY so it is the CLI's innermost job. + let job = codex_utils_pty::JobObject::create_without_breakaway()?; + let codex = codex_utils_cargo_bin::cargo_bin("codex")?; + let mut command = tokio::process::Command::new(codex); + command + .arg("--no-alt-screen") + .stdin(std::process::Stdio::inherit()) + .stdout(std::process::Stdio::inherit()) + .stderr(std::process::Stdio::inherit()); + let status = job.spawn_contained(&mut command)?.wait().await?; + ensure!(status.success(), "CLI exited: {status}"); + return Ok(()); + } + daemon_startup("restrictive-job").await +} + #[tokio::test] #[cfg(unix)] async fn bedrock_onboarding_leaves_a_running_daemon_untouched() -> Result<()> { @@ -129,26 +151,29 @@ async fn daemon_startup(command: &str) -> Result<()> { env.insert("TERM".into(), "xterm-256color".into()); let mut args = vec!["--no-alt-screen".to_string()]; let mut steps: VecDeque<(&str, &[u8])> = VecDeque::new(); - if matches!(command, "start" | "bedrock-running") || mismatch { + if matches!(command, "start" | "bedrock-running" | "restrictive-job") || mismatch { // A selected package with a stopped daemon avoids installing a release. let managed = home .path() - .join("packages/app-server-daemon/current/bin/codex"); + .join("packages/app-server-daemon/current/bin") + .join(if cfg!(windows) { "codex.exe" } else { "codex" }); fs::create_dir_all(home.path().join("packages/app-server-daemon/current/bin"))?; // Hard links change the executable's ctime and invalidate Rosetta's translation cache. #[cfg(unix)] std::os::unix::fs::symlink(&codex, &managed)?; #[cfg(not(unix))] fs::hard_link(&codex, &managed).or_else(|_| fs::copy(&codex, &managed).map(|_| ()))?; - fs::create_dir(home.path().join("app-server-daemon"))?; - fs::write( - home.path().join("app-server-daemon/settings.json"), - if persisted { - r#"{"shutdownGraceSeconds":0,"updater":{"autoUpdateEnabled":false},"featureOverrides":{"api_key_model_discovery":true}}"# - } else { - r#"{"shutdownGraceSeconds":0,"updater":{"autoUpdateEnabled":false}}"# - }, - )?; + if command != "restrictive-job" { + fs::create_dir(home.path().join("app-server-daemon"))?; + fs::write( + home.path().join("app-server-daemon/settings.json"), + if persisted { + r#"{"shutdownGraceSeconds":0,"updater":{"autoUpdateEnabled":false},"featureOverrides":{"api_key_model_discovery":true}}"# + } else { + r#"{"shutdownGraceSeconds":0,"updater":{"autoUpdateEnabled":false}}"# + }, + )?; + } } let pid_file = home.path().join("app-server-daemon/daemon.pid"); let result = async { @@ -172,6 +197,9 @@ async fn daemon_startup(command: &str) -> Result<()> { // The draft header is visible before the session's command composer is ready. steps.push_back(("GPT-5.6-Terra", b"/status\r")); "Server:Localbackgroundserver" + } else if command == "restrictive-job" { + steps.push_back(("GPT-5.6-Terra", b"\x14")); + "Runningwithoutthesharedbackgroundserver:thisWindowslauncher" } else if mismatch { args.extend(if persisted { ["--disable".into(), "api_key_model_discovery".into()] @@ -201,8 +229,19 @@ async fn daemon_startup(command: &str) -> Result<()> { steps.push_back(("GPT-5.6-Terra", b"\x14")); "Runningwithoutthesharedbackgroundserver:--strict-config" }; + let program = if cfg!(windows) && command == "restrictive-job" { + env.insert("CODEX_TEST_RESTRICTIVE_DAEMON_START".into(), "1".into()); + args = vec![ + "--exact".into(), + "restrictive_launcher_uses_embedded_if_daemon_cannot_start".into(), + "--nocapture".into(), + ]; + std::env::current_exe()? + } else { + codex.clone() + }; let spawned = codex_utils_pty::spawn_pty_process( - &codex.to_string_lossy(), + &program.to_string_lossy(), &args, &workspace_path, &env, @@ -214,7 +253,7 @@ async fn daemon_startup(command: &str) -> Result<()> { codex_utils_pty::ChildFds::Inherited(&[]), ) .await?; - let exit = spawned.exit_rx; + let mut exit = spawned.exit_rx; let session = spawned.session; let writer = session.writer_sender(); let mut stdout = spawned.stdout_rx; @@ -247,6 +286,16 @@ async fn daemon_startup(command: &str) -> Result<()> { .chars() .filter(|c| !c.is_whitespace()) .collect(); + if command == "restrictive-job" + && text.contains("starttheWindowsdaemonfromanon-elevatedterminal") + { + // Elevated runners must still reject startup before the job probe. + ensure!(!pid_file.exists()); + let status = tokio::time::timeout(Duration::from_secs(/*secs*/ 5), &mut exit) + .await??; + ensure!(status != 0, "elevated daemon launch must fail"); + return Ok::<_, anyhow::Error>(()); + } if let Some((ready, input)) = steps.front() && text.contains(ready) { @@ -276,8 +325,15 @@ async fn daemon_startup(command: &str) -> Result<()> { ensure!(home.path().join("app-server-daemon/daemon.pid").exists()); } else if let Some(existing_daemon) = &existing_daemon { ensure!(fs::read(&pid_file)? == *existing_daemon); - } else if bedrock_onboarding { + } else if bedrock_onboarding || command == "restrictive-job" { ensure!(!pid_file.exists()); + if command == "restrictive-job" { + let contents = screen.screen().contents(); + let warning = contents.lines() + .find(|line| line.contains("Running without the shared background server:")) + .context("missing rendered fallback warning")?; + insta::assert_snapshot!("restrictive_launcher_warning", warning.trim()); + } } return Ok::<_, anyhow::Error>(()); } diff --git a/codex-rs/cli/tests/snapshots/daemon_startup__restrictive_launcher_warning.snap b/codex-rs/cli/tests/snapshots/daemon_startup__restrictive_launcher_warning.snap new file mode 100644 index 0000000000..ae68754df2 --- /dev/null +++ b/codex-rs/cli/tests/snapshots/daemon_startup__restrictive_launcher_warning.snap @@ -0,0 +1,6 @@ +--- +source: cli/tests/daemon_startup.rs +assertion_line: 325 +expression: warning.trim() +--- +⚠ Running without the shared background server: this Windows launcher requires embedded mode. diff --git a/codex-rs/code-mode/src/remote_session/connection.rs b/codex-rs/code-mode/src/remote_session/connection.rs index 48345d506c..ed5a22074b 100644 --- a/codex-rs/code-mode/src/remote_session/connection.rs +++ b/codex-rs/code-mode/src/remote_session/connection.rs @@ -158,6 +158,8 @@ impl Connection { let mut command = Command::new(host_program); #[cfg(unix)] command.process_group(0); + #[cfg(windows)] + command.creation_flags(/*flags*/ 0x0800_0000); // CREATE_NO_WINDOW command .stdin(Stdio::piped()) .stdout(Stdio::piped()) diff --git a/codex-rs/config/src/types.rs b/codex-rs/config/src/types.rs index 5b2a8c740c..81c953dc6f 100644 --- a/codex-rs/config/src/types.rs +++ b/codex-rs/config/src/types.rs @@ -865,8 +865,9 @@ pub struct Tui { pub fullscreen_transcript: bool, /// Copy selected transcript text when the mouse button is released. - /// Defaults to `auto`: enabled in tmux/Zellij and in direct macOS terminals except Ghostty/Kitty. - /// On other platforms, direct terminals default off except iTerm2/Terminal.app. + /// Defaults to `auto`: enabled except in direct terminals known to forward their native + /// copy shortcut (Ghostty 1.2+, Kitty on macOS, Windows Terminal, and VS Code on Windows). + /// Unknown terminals, Ghostty without a recognized version, and tmux/Zellij default to copying. #[serde(default)] pub copy_on_select: CopyOnSelect, diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index c8ad1a3194..5e0a8f1587 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -4359,7 +4359,7 @@ } ], "default": "auto", - "description": "Copy selected transcript text when the mouse button is released. Defaults to `auto`: enabled in tmux/Zellij and in direct macOS terminals except Ghostty/Kitty. On other platforms, direct terminals default off except iTerm2/Terminal.app." + "description": "Copy selected transcript text when the mouse button is released. Defaults to `auto`: enabled except in direct terminals known to forward their native copy shortcut (Ghostty 1.2+, Kitty on macOS, Windows Terminal, and VS Code on Windows). Unknown terminals, Ghostty without a recognized version, and tmux/Zellij default to copying." }, "disable_paste_burst": { "description": "When true, disables burst-paste detection for typed input entirely. All characters are inserted as they are received, and no buffering or placeholder replacement will occur for fast keypress bursts. Overrides the legacy top-level `disable_paste_burst` setting. Defaults to `false`.", diff --git a/codex-rs/core/tests/suite/mcp_optional_startup_grace.rs b/codex-rs/core/tests/suite/mcp_optional_startup_grace.rs index 0dbc563edd..d366b75f41 100644 --- a/codex-rs/core/tests/suite/mcp_optional_startup_grace.rs +++ b/codex-rs/core/tests/suite/mcp_optional_startup_grace.rs @@ -14,6 +14,9 @@ use test_case::test_case; const SERVER_NAME: &str = "optional_startup"; const TOOL_NAMESPACE: &str = "mcp__optional_startup"; const TOOL_NAME: &str = "calendar_create_event"; +// Allow the whole turn to finish on slow runners without reaching the server's own timeout. +const TURN_TIMEOUT: Duration = Duration::from_secs(5); +const PENDING_SERVER_TIMEOUT: Duration = Duration::from_secs(30); #[derive(Clone, Copy)] enum StartupGraceScenario { @@ -46,9 +49,9 @@ async fn optional_mcp_startup_grace_controls_initial_turn_tool_catalog( | StartupGraceScenario::DisabledGraceRespectsStartupTimeout => Duration::ZERO, }; let startup_timeout = match scenario { + StartupGraceScenario::ShortGraceOmitsPending => PENDING_SERVER_TIMEOUT, StartupGraceScenario::DisabledGraceRespectsStartupTimeout => Duration::from_millis(250), - StartupGraceScenario::ShortGraceOmitsPending - | StartupGraceScenario::CustomGraceIncludesReady + StartupGraceScenario::CustomGraceIncludesReady | StartupGraceScenario::DisabledGraceWaitsForStartup => Duration::from_secs(1), }; let responses_server = responses::start_mock_server().await; @@ -101,7 +104,7 @@ async fn optional_mcp_startup_grace_controls_initial_turn_tool_catalog( let mut turn = Box::pin(fixture.submit_turn("show optional MCP tools")); match scenario { StartupGraceScenario::ShortGraceOmitsPending => { - tokio::time::timeout(Duration::from_millis(500), &mut turn) + tokio::time::timeout(TURN_TIMEOUT, &mut turn) .await .context("the configured grace should omit the pending server")??; release_startup @@ -206,7 +209,7 @@ async fn running_thread_uses_refreshed_optional_mcp_startup_grace( "url": server_url, "http_headers": { "Authorization": "Bearer synthetic-test-token" }, "enabled_tools": [TOOL_NAME], - "startup_timeout_sec": 5, + "startup_timeout_sec": PENDING_SERVER_TIMEOUT.as_secs(), })) .expect("synthetic optional MCP server configuration"), ); @@ -227,9 +230,9 @@ async fn running_thread_uses_refreshed_optional_mcp_startup_grace( .context("optional MCP initialization should begin before the initial turn")?; // Allow for turn setup on remote workers while still finishing before the - // five-second MCP startup timeout. The server remains gated throughout. + // pending MCP startup timeout. The server remains gated throughout. tokio::time::timeout( - Duration::from_secs(2), + TURN_TIMEOUT, fixture.submit_turn("show initial optional MCP tools"), ) .await diff --git a/codex-rs/rmcp-client/src/bin/test_stdio_server.rs b/codex-rs/rmcp-client/src/bin/test_stdio_server.rs index 79a2e1c066..8bf0845d1a 100644 --- a/codex-rs/rmcp-client/src/bin/test_stdio_server.rs +++ b/codex-rs/rmcp-client/src/bin/test_stdio_server.rs @@ -1003,6 +1003,15 @@ async fn main() -> Result<(), Box> { std::fs::write(pid_file, std::process::id().to_string())?; } #[cfg(windows)] + if let Ok(console_state_file) = std::env::var("MCP_TEST_CONSOLE_STATE_FILE") { + #[link(name = "kernel32")] + unsafe extern "system" { + fn GetConsoleWindow() -> *mut std::ffi::c_void; + } + let has_console = unsafe { !GetConsoleWindow().is_null() }; + std::fs::write(console_state_file, has_console.to_string())?; + } + #[cfg(windows)] if let Ok(marker_file) = std::env::var("MCP_TEST_BREAKAWAY_DENIED_FILE") { use std::os::windows::process::CommandExt; diff --git a/codex-rs/rmcp-client/src/stdio_server_launcher.rs b/codex-rs/rmcp-client/src/stdio_server_launcher.rs index 433f532a13..13fabc46d9 100644 --- a/codex-rs/rmcp-client/src/stdio_server_launcher.rs +++ b/codex-rs/rmcp-client/src/stdio_server_launcher.rs @@ -214,6 +214,11 @@ impl StdioServerLauncher for LocalStdioServerLauncher { // Local private implementation. +#[cfg(windows)] +const CREATE_NO_WINDOW: u32 = 0x0800_0000; +#[cfg(windows)] +const CREATE_SUSPENDED: u32 = 0x0000_0004; + #[cfg(unix)] const PROCESS_GROUP_TERM_GRACE_PERIOD: Duration = Duration::from_secs(2); @@ -288,6 +293,8 @@ impl LocalStdioServerLauncher { // handles and needs a handle allowlist in the shared spawn backend. #[cfg(unix)] command.descriptor_policy(DescriptorPolicy::Explicit); + #[cfg(windows)] + command.creation_flags(CREATE_NO_WINDOW); command }; #[cfg(windows)] @@ -298,6 +305,8 @@ impl LocalStdioServerLauncher { let job = match codex_utils_pty::JobObject::create_without_breakaway() { Ok(job) => { command.prepare_suspended_spawn(&job); + // The helper replaces creation flags; retain suspension and suppress the console. + command.creation_flags(CREATE_SUSPENDED | CREATE_NO_WINDOW); Some(job) } Err(error) => { diff --git a/codex-rs/rmcp-client/tests/stdio_message_limits.rs b/codex-rs/rmcp-client/tests/stdio_message_limits.rs index 7c8ec6102b..cbfeceae4b 100644 --- a/codex-rs/rmcp-client/tests/stdio_message_limits.rs +++ b/codex-rs/rmcp-client/tests/stdio_message_limits.rs @@ -134,6 +134,90 @@ async fn stdio_message_limits_preserve_legacy_local_compatibility() -> anyhow::R Ok(()) } +#[cfg(windows)] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn local_stdio_initializes_without_a_console_directly_and_through_cmd() -> anyhow::Result<()> +{ + let server = codex_utils_cargo_bin::cargo_bin("test_stdio_server")?; + let temp_dir = tempfile::tempdir()?; + let console_state_file = temp_dir.path().join("console-state"); + let server_pid_file = temp_dir.path().join("server.pid"); + std::fs::write( + temp_dir.path().join("launch.cmd"), + "@echo off\r\n\"%MCP_TEST_SERVER_BINARY%\"\r\n", + )?; + let env = HashMap::from([ + ( + OsString::from("MCP_TEST_CONSOLE_STATE_FILE"), + console_state_file.clone().into_os_string(), + ), + ( + OsString::from("MCP_TEST_PID_FILE"), + server_pid_file.clone().into_os_string(), + ), + ( + OsString::from("MCP_TEST_SERVER_BINARY"), + server.clone().into(), + ), + ]); + + for (program, args) in [ + (server.into(), Vec::new()), + ( + OsString::from("cmd.exe"), + ["/d", "/s", "/c", "call", ".\\launch.cmd"] + .map(OsString::from) + .to_vec(), + ), + ] { + let client = RmcpClient::new_stdio_client( + program, + args, + Some(env.clone()), + &[], + Some(temp_dir.path().to_string_lossy().into_owned()), + Arc::new(LocalStdioServerLauncher::new(temp_dir.path().to_path_buf())), + ) + .await?; + client + .initialize( + InitializeRequestParams::new( + ClientCapabilities::default(), + Implementation::new("stdio-console-test", "1.0.0"), + ) + .with_protocol_version(ProtocolVersion::V_2025_06_18), + Some(Duration::from_secs(10)), + Box::new(|_, _| { + async { + Ok(ElicitationResponse { + action: ElicitationAction::Decline, + content: None, + meta: None, + }) + } + .boxed() + }), + ) + .await?; + let console_state = std::fs::read_to_string(&console_state_file)?; + let server_pid = std::fs::read_to_string(&server_pid_file)? + .trim() + .parse::()?; + let server_process = open_process_for_wait(server_pid)?; + let tools = client + .list_tools(/*params*/ None, Some(Duration::from_secs(10))) + .await; + client.shutdown().await; + wait_for_process_exit(&server_process)?; + + pretty_assertions::assert_eq!(console_state, "false"); + assert!(!tools?.tools.is_empty()); + std::fs::remove_file(&console_state_file)?; + std::fs::remove_file(&server_pid_file)?; + } + Ok(()) +} + #[cfg(windows)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn local_stdio_shutdown_terminates_descendants_after_server_exit() -> anyhow::Result<()> { diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index 7868caa193..25c6f2c732 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -230,6 +230,7 @@ mod managed_worktree_creation; mod misalignment_policy; mod model_defaults; mod new_session; +mod turn_tips; pub(crate) use new_session::has_launch_setting; mod clipboard; mod native_history; @@ -581,6 +582,7 @@ pub(crate) struct App { pub(crate) transcript_cells: Vec>, native_history: native_history::NativeHistory, + turn_tips: turn_tips::TurnTips, pub(crate) transcript_view: crate::transcript_view::TranscriptView, last_rendered_history_tail: Option, last_thread_usage_status_cell: Option, diff --git a/codex-rs/tui/src/app/agents_overview_new.rs b/codex-rs/tui/src/app/agents_overview_new.rs index 7a4aa8aa20..d422598d5a 100644 --- a/codex-rs/tui/src/app/agents_overview_new.rs +++ b/codex-rs/tui/src/app/agents_overview_new.rs @@ -74,6 +74,10 @@ impl App { .await; if self.current_displayed_thread_id() != previous_thread { draft.flush_pending_paste_newline(tui).await?; + self.chat_widget + .empty_state_animation + .borrow_mut() + .continue_from(&mut draft.blossom.borrow_mut()); self.chat_widget.restore_startup_draft(draft.take_draft()); } else { // Retain edits if setup fails so retrying `n` does not lose the draft. diff --git a/codex-rs/tui/src/app/empty_state_animation_tests.rs b/codex-rs/tui/src/app/empty_state_animation_tests.rs index a7b53d490f..f8195f1266 100644 --- a/codex-rs/tui/src/app/empty_state_animation_tests.rs +++ b/codex-rs/tui/src/app/empty_state_animation_tests.rs @@ -5,18 +5,12 @@ use super::*; use pretty_assertions::assert_eq; use ratatui::buffer::Buffer; -fn animation_is_eligible(app: &App) -> bool { - app.empty_state_presentation( - crate::motion::MotionMode::from_animations_enabled( - app.local_settings.tui.animations && app.local_settings.tui.effects.welcome, - ), - /*focused*/ true, - ) == crate::empty_state_animation::Presentation::Animated - && app - .chat_widget - .empty_state_animation - .borrow() - .is_eligible_for_test() +fn has_blossom(tui: &tui::Tui) -> bool { + text(crate::custom_terminal::test_support::last_rendered_buffer( + &tui.terminal, + )) + .chars() + .any(|ch| ('\u{2801}'..='\u{28ff}').contains(&ch)) } fn text(buffer: &Buffer) -> String { @@ -56,37 +50,37 @@ async fn fresh_logo_returns_only_to_the_ordinary_composer() -> Result<()> { .start_fresh(); draw(&mut app, &mut tui, size)?; let cursor = tui.terminal.last_known_cursor_pos; - assert!(animation_is_eligible(&app)); + assert!(has_blossom(&tui)); app.open_transcript_overlay(&mut tui); draw(&mut app, &mut tui, size)?; - assert!(!animation_is_eligible(&app)); + assert!(!has_blossom(&tui)); assert_eq!(tui.terminal.last_known_cursor_pos, cursor); app.close_transcript_overlay(&mut tui); draw(&mut app, &mut tui, size)?; - assert!(animation_is_eligible(&app)); + assert!(has_blossom(&tui)); app.transcript_view.begin_search(); draw(&mut app, &mut tui, size)?; - assert!(!animation_is_eligible(&app)); + assert!(!has_blossom(&tui)); app.transcript_view.handle_key( KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE), &app.transcript_cells, ); draw(&mut app, &mut tui, size)?; - assert!(animation_is_eligible(&app)); + assert!(has_blossom(&tui)); for enabled in [true, false] { app.apply_raw_output_mode(&mut tui, enabled, /*notify*/ false); draw(&mut app, &mut tui, size)?; - assert_eq!(animation_is_eligible(&app), !enabled); + assert_eq!(has_blossom(&tui), !enabled); } app.chat_widget.apply_external_edit(String::new()); for (key, visible) in [(KeyCode::Char('?'), false), (KeyCode::Right, true)] { app.chat_widget .handle_key_event(KeyEvent::new(key, KeyModifiers::NONE)); draw(&mut app, &mut tui, size)?; - assert_eq!(animation_is_eligible(&app), visible); + assert_eq!(has_blossom(&tui), visible); } tui.set_owned_screen(/*owned*/ false)?; Ok(()) @@ -96,7 +90,8 @@ async fn fresh_logo_returns_only_to_the_ordinary_composer() -> Result<()> { async fn non_startup_history_dismisses_logo_until_a_new_thread() -> Result<()> { let mut app = crate::app::test_support::make_test_app().await; app.local_settings.tui.animations = true; - let size = Size::new(/*width*/ 120, /*height*/ 44); + // Leave room for the full release-note card above the centered logo. + let size = Size::new(/*width*/ 120, /*height*/ 64); let mut tui = crate::tui::test_support::make_test_tui()?; tui.set_owned_screen(/*owned*/ true)?; app.chat_widget @@ -142,7 +137,7 @@ async fn non_startup_history_dismisses_logo_until_a_new_thread() -> Result<()> { )), ); draw(&mut app, &mut tui, size)?; - assert!(animation_is_eligible(&app)); + assert!(has_blossom(&tui)); crate::chatwidget::tests::set_chatgpt_auth(&mut app.chat_widget); let request = app.chat_widget.start_rate_limit_reset_startup_check(); @@ -157,10 +152,10 @@ async fn non_startup_history_dismisses_logo_until_a_new_thread() -> Result<()> { // The same startup notice stays eligible both pending and committed to history. assert!(app.chat_widget.empty_state_composer().is_some()); draw(&mut app, &mut tui, size)?; - assert!(animation_is_eligible(&app)); + assert!(has_blossom(&tui)); app.insert_pending_usage_output_if_ready(&mut tui); draw(&mut app, &mut tui, size)?; - assert!(animation_is_eligible(&app)); + assert!(has_blossom(&tui)); // Even invisible non-startup content ends eligibility before a frame or clear can erase it. app.insert_history_cell( @@ -170,13 +165,13 @@ async fn non_startup_history_dismisses_logo_until_a_new_thread() -> Result<()> { app.reset_transcript_state_after_clear(); app.queue_clear_ui_header(&mut tui); draw(&mut app, &mut tui, size)?; - assert!(!animation_is_eligible(&app)); + assert!(!has_blossom(&tui)); app.chat_widget .empty_state_animation .borrow_mut() .start_fresh(); draw(&mut app, &mut tui, size)?; - assert!(animation_is_eligible(&app)); + assert!(has_blossom(&tui)); tui.set_owned_screen(/*owned*/ false)?; Ok(()) } @@ -188,6 +183,14 @@ async fn empty_state_animation_preserves_header_cursor_and_footer() -> Result<() let size = Size::new(/*width*/ 120, /*height*/ 44); let mut tui = crate::tui::test_support::make_test_tui()?; tui.set_owned_screen(/*owned*/ true)?; + app.chat_widget + .empty_state_animation + .borrow() + .greeting + .set(crate::empty_state_animation::Greeting { + phrase: "Pull up a prompt.", + }) + .expect("initial greeting"); app.queue_clear_ui_header(&mut tui); app.transcript_cells .push(Arc::new(history_cell::StartupWarningsCell::mcp( @@ -199,32 +202,54 @@ async fn empty_state_animation_preserves_header_cursor_and_footer() -> Result<() let history_len = app.transcript_cells.len(); let before = crate::custom_terminal::test_support::last_rendered_buffer(&tui.terminal).clone(); let cursor = tui.terminal.last_known_cursor_pos; - assert!(!animation_is_eligible(&app)); + assert!(!has_blossom(&tui)); app.chat_widget .empty_state_animation .borrow_mut() .start_fresh(); assert_eq!(draw(&mut app, &mut tui, size)?, before_bottom); let after = crate::custom_terminal::test_support::last_rendered_buffer(&tui.terminal); - assert!(animation_is_eligible(&app)); + assert!(has_blossom(&tui)); assert_eq!(tui.terminal.last_known_cursor_pos, cursor); - for (a, b) in before.content.iter().zip(&after.content) { - if a.symbol() != " " { - assert_eq!(a, b); - } - } + assert!(text(&before).contains("Pull up a prompt.")); assert_eq!( &after.content[after.index_of(/*x*/ 0, before_bottom.y)..], &before.content[before.index_of(/*x*/ 0, before_bottom.y)..] ); - insta::assert_snapshot!("fresh_thread_header", text(after)); + insta::assert_snapshot!( + "fresh_thread_header", + format!( + "enabled:\n{}\n---\ndisabled:\n{}", + text(after), + text(&before) + ) + ); + // Editing, clearing, and resizing must never choose another phrase. + let phrase_pos = after + .content + .iter() + .position(|cell| cell.symbol() == "P") + .expect("the phrase is visible above the composer"); + assert_eq!(after.content[phrase_pos].fg, crate::style::accent_color()); + + let short = Size::new(/*width*/ 120, /*height*/ 12); + draw(&mut app, &mut tui, short)?; + assert!(!has_blossom(&tui)); + draw(&mut app, &mut tui, size)?; + assert!(has_blossom(&tui)); app.chat_widget.apply_external_edit("/m".to_string()); draw(&mut app, &mut tui, size)?; - assert!(!animation_is_eligible(&app)); + assert!(!has_blossom(&tui)); app.chat_widget.apply_external_edit(String::new()); draw(&mut app, &mut tui, size)?; - assert!(animation_is_eligible(&app)); + assert!(has_blossom(&tui)); + assert!( + text(crate::custom_terminal::test_support::last_rendered_buffer( + &tui.terminal + )) + .contains("Pull up a prompt.") + ); assert_eq!(app.transcript_cells.len(), history_len); app.local_settings.tui.animations = false; draw(&mut app, &mut tui, size)?; @@ -240,13 +265,13 @@ async fn empty_state_animation_preserves_header_cursor_and_footer() -> Result<() app.local_settings.tui.effects.welcome = true; app.local_settings.tui.effects.shimmer = false; draw(&mut app, &mut tui, size)?; - assert!(animation_is_eligible(&app)); + assert!(has_blossom(&tui)); tui.set_owned_screen(/*owned*/ false)?; Ok(()) } #[tokio::test] -async fn submitting_a_draft_dismisses_logo_even_after_clear() -> Result<()> { +async fn submitting_a_draft_keeps_greeting_and_dismisses_logo_even_after_clear() -> Result<()> { let (mut app, _events, _ops) = crate::app::tests::make_test_app_with_channels().await; app.local_settings.tui.animations = true; let size = Size::new(/*width*/ 120, /*height*/ 44); @@ -258,20 +283,42 @@ async fn submitting_a_draft_dismisses_logo_even_after_clear() -> Result<()> { .borrow_mut() .start_fresh(); draw(&mut app, &mut tui, size)?; - assert!(animation_is_eligible(&app)); + assert!(has_blossom(&tui)); + let greeting = *app + .chat_widget + .empty_state_animation + .borrow() + .greeting + .get() + .expect("choose a greeting for the fresh thread"); app.chat_widget .apply_external_edit("first prompt".to_string()); draw(&mut app, &mut tui, size)?; let drafting = crate::custom_terminal::test_support::last_rendered_buffer(&tui.terminal); - assert!(!animation_is_eligible(&app)); + assert!(!has_blossom(&tui)); assert!(text(drafting).contains("first prompt")); + assert!(text(drafting).contains(greeting.phrase)); + app.chat_widget.apply_external_edit(String::new()); + draw(&mut app, &mut tui, size)?; + assert!(has_blossom(&tui)); + app.chat_widget + .apply_external_edit("first prompt".to_string()); app.chat_widget .handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); draw(&mut app, &mut tui, size)?; - assert!(!animation_is_eligible(&app)); + assert!(!has_blossom(&tui)); + let submitted = crate::custom_terminal::test_support::last_rendered_buffer(&tui.terminal); + assert_eq!(text(submitted).matches(greeting.phrase).count(), 1); + // The header is also stable when it scrolls out and back into the viewport. + let short = Size::new(/*width*/ 120, /*height*/ 8); + draw(&mut app, &mut tui, short)?; + draw(&mut app, &mut tui, size)?; + let restored = crate::custom_terminal::test_support::last_rendered_buffer(&tui.terminal); + assert!(text(restored).contains(greeting.phrase)); + assert!(!has_blossom(&tui)); app.reset_transcript_state_after_clear(); draw(&mut app, &mut tui, size)?; - assert!(!animation_is_eligible(&app)); + assert!(!has_blossom(&tui)); tui.set_owned_screen(/*owned*/ false)?; Ok(()) } @@ -311,7 +358,7 @@ async fn empty_state_animation_survives_plain_transcript_clicks() -> Result<()> &app.transcript_cells, ); draw(&mut app, &mut tui, size)?; - assert_eq!(animation_is_eligible(&app), visible); + assert_eq!(has_blossom(&tui), visible); if visible { assert_eq!(tui.terminal.last_known_cursor_pos, cursor); } @@ -323,7 +370,10 @@ async fn empty_state_animation_survives_plain_transcript_clicks() -> Result<()> ); app.transcript_view.end_selection(&app.transcript_cells); draw(&mut app, &mut tui, size)?; - assert!(animation_is_eligible(&app)); + assert!(!has_blossom(&tui)); + app.transcript_view.jump_to_latest(); + draw(&mut app, &mut tui, size)?; + assert!(has_blossom(&tui)); tui.set_owned_screen(/*owned*/ false)?; Ok(()) } diff --git a/codex-rs/tui/src/app/empty_state_policy.rs b/codex-rs/tui/src/app/empty_state_policy.rs index c134739f70..c579207418 100644 --- a/codex-rs/tui/src/app/empty_state_policy.rs +++ b/codex-rs/tui/src/app/empty_state_policy.rs @@ -2,17 +2,12 @@ //! View changes hide it temporarily; non-startup content dismisses it until a new thread. use super::*; -use crate::empty_state_animation::Presentation; +use crate::empty_state_animation::ComposerState; use crate::empty_state_animation::is_startup_cell; use crate::history_cell::HistoryRenderMode; -use crate::motion::MotionMode; impl App { - pub(super) fn empty_state_presentation( - &self, - motion: MotionMode, - focused: bool, - ) -> Presentation { + pub(super) fn first_screen_composer(&self) -> Option { if !self .transcript_cells .iter() @@ -26,7 +21,7 @@ impl App { // Evaluate live content even while a different view temporarily owns the screen. let composer = self.chat_widget.empty_state_composer(); let view = &self.transcript_view; - let composer = match self.chat_widget.history_render_mode() { + match self.chat_widget.history_render_mode() { HistoryRenderMode::Raw => None, HistoryRenderMode::Rich => match ( self.overlay.as_ref(), @@ -36,10 +31,19 @@ impl App { view.has_selection_range(), ) { // A refocus click without selected text remains an ordinary conversation. - (None, false, false, false, false) => composer, + (None, false, false, false, false) + if (view.is_following() || view.has_pending_latest_selection()) + && self.local_settings.tui.effects.welcome + && self + .chat_widget + .empty_state_animation + .borrow() + .is_eligible() => + { + composer + } _ => None, }, - }; - Presentation::for_composer(composer, motion, focused) + } } } diff --git a/codex-rs/tui/src/app/event_dispatch.rs b/codex-rs/tui/src/app/event_dispatch.rs index 7ea0e3b622..8e4f1f911c 100644 --- a/codex-rs/tui/src/app/event_dispatch.rs +++ b/codex-rs/tui/src/app/event_dispatch.rs @@ -819,6 +819,10 @@ impl App { AppEvent::InsertHistoryCell(cell) => { self.insert_history_cell(tui, cell); } + AppEvent::TurnTipReady { thread_id, turn_id } => { + self.turn_tips.ready(thread_id, &turn_id, self.transcript_cells.last()); + tui.frame_requester().schedule_frame(); + } AppEvent::EndInitialHistoryReplayBuffer => { self.scrollback_has_older_history = self .chat_widget diff --git a/codex-rs/tui/src/app/history_ui.rs b/codex-rs/tui/src/app/history_ui.rs index 1aaf1143e5..270829d2f4 100644 --- a/codex-rs/tui/src/app/history_ui.rs +++ b/codex-rs/tui/src/app/history_ui.rs @@ -315,7 +315,7 @@ impl App { &self, version: &'static str, ) -> history_cell::SessionHeaderHistoryCell { - history_cell::SessionHeaderHistoryCell::new( + let mut header = history_cell::SessionHeaderHistoryCell::new( self.chat_widget.model_display_name().to_string(), self.chat_widget.current_reasoning_effort(), self.chat_widget.should_show_fast_status( @@ -325,7 +325,12 @@ impl App { self.config.cwd.to_path_buf(), version, ) - .with_yolo_mode(history_cell::is_yolo_mode(&self.config)) + .with_yolo_mode(history_cell::is_yolo_mode(&self.config)); + history_cell::set_session_greeting( + &mut header, + &self.chat_widget.empty_state_animation.borrow().greeting, + ); + header } pub(super) fn clear_ui_header_lines(&self, width: u16) -> Vec> { @@ -395,6 +400,7 @@ impl App { pub(super) fn reset_transcript_state_after_clear(&mut self) { self.overlay = None; self.transcript_cells.clear(); + self.turn_tips.dismiss(); self.native_history = Default::default(); self.cancel_pending_key_chord(); self.transcript_view = Default::default(); diff --git a/codex-rs/tui/src/app/owned_transcript.rs b/codex-rs/tui/src/app/owned_transcript.rs index fd6b707a72..91faa302b2 100644 --- a/codex-rs/tui/src/app/owned_transcript.rs +++ b/codex-rs/tui/src/app/owned_transcript.rs @@ -1,9 +1,10 @@ //! Compose the owned transcript above the composer and route their selection gestures. //! Reserve a cleared row below activity and previews, immediately above the composer. //! Slash suggestions overlay already-painted rows so opening or closing them leaves transcript -//! geometry unchanged. +//! geometry unchanged. Turn tips remain separate from selectable transcript text. //! Plain Enter returns an empty composer to latest after transcript interactions and prompt editing. +use super::turn_tips::TipSurface; use super::*; use crate::history_cell::HistoryRenderMode; use crate::keymap::KeymapContext; @@ -71,13 +72,7 @@ impl App { let motion = MotionMode::from_animations_enabled( self.local_settings.tui.animations && self.local_settings.tui.effects.shimmer, ); - let focused = tui.is_terminal_focused(); - self.empty_state_presentation( - MotionMode::from_animations_enabled( - self.local_settings.tui.animations && self.local_settings.tui.effects.welcome, - ), - focused, - ); + let composer = self.first_screen_composer(); let latest_navigation = if self.enter_returns_to_latest() { "enter/esc latest" } else { @@ -86,6 +81,16 @@ impl App { self.sync_owned_transcript(screen_size.width); let transcript_width = self.chat_widget.history_wrap_width(screen_size.width); let composer_hint = self.composer_hint(transcript_width); + let now = Instant::now(); + let turn_tip = self.turn_tip(transcript_width, now, &tui.frame_requester()); + let working_tip = turn_tip + .as_ref() + .filter(|(surface, _)| *surface == TipSurface::Working) + .map(|(_, tip)| tip); + let completion_tip = turn_tip + .as_ref() + .filter(|(surface, _)| *surface == TipSurface::Completion) + .map(|(_, tip)| tip); let mut composer_gap = (!self.chat_widget.has_active_view() && !self.chat_widget.is_external_writer_view()) .then(crate::bottom_pane::ComposerGap::default); @@ -114,6 +119,7 @@ impl App { crate::bottom_pane::CommandPopupPlacement::Overlay }, composer_gap.as_ref(), + working_tip, ); let dashboard_visible = chat_widget .selected_index_for_present_view(AGENTS_OVERVIEW_VIEW_ID) @@ -136,21 +142,23 @@ impl App { let mut rendered_cursor = None; let mut footer_height_changed = false; let mut feedback_tick = None; - let now = Instant::now(); + let mut blossom_tick = None; + let mut transcript_bottom = available.saturating_sub(u16::from(composer_gap.is_none())); tui.draw(screen_size.height, |frame| { ratatui::widgets::Clear.render( Rect::new(/*x*/ 0, /*y*/ 0, screen_size.width, available), frame.buffer, ); - view.render( + let mut completion_tip_area = view.render_with_turn_tip_space( Rect::new( /*x*/ 0, /*y*/ 0, transcript_width, - available.saturating_sub(u16::from(composer_gap.is_none())), + transcript_bottom, ), frame.buffer, &self.transcript_cells, + completion_tip, ); if let Some(gap) = composer_gap.as_mut() { gap.needs_separator = available > 1 @@ -180,6 +188,7 @@ impl App { crate::bottom_pane::CommandPopupPlacement::Overlay }, composer_gap.as_ref(), + working_tip, ); footer_height_changed = !dashboard_visible && bottom @@ -195,14 +204,36 @@ impl App { // Resolve controls with the compact viewport first, then make room for // their separator. Resizing must not preserve a stale return control. ratatui::widgets::Clear.render(bottom_area, frame.buffer); - view.render( - Rect::new(/*x*/ 0, /*y*/ 0, transcript_width, bottom_area.y), + transcript_bottom = bottom_area.y; + completion_tip_area = view.render_with_turn_tip_space( + Rect::new( + /*x*/ 0, + /*y*/ 0, + transcript_width, + transcript_bottom, + ), frame.buffer, &self.transcript_cells, + completion_tip, ); footer_height_changed = false; } + blossom_tick = chat_widget + .empty_state_animation + .borrow_mut() + .render_first_screen( + Rect { + width: screen_size.width, + ..view.remaining_area() + }, + frame.buffer, + composer, + MotionMode::from_animations_enabled(self.local_settings.tui.animations), + ); bottom.render(bottom_area, frame.buffer); + if let (Some(tip), Some(area)) = (completion_tip, completion_tip_area) { + tip.render(area, frame.buffer); + } let follow_area = if let Some(gap) = composer_gap.as_ref() { Some(Rect { width: transcript_width, @@ -228,12 +259,20 @@ impl App { frame.set_cursor_position(position); } })?; + if let Some((surface, tip)) = &turn_tip + && tip.rendered.get() + { + self.turn_tips.acknowledge(*surface); + } if footer_height_changed { tui.frame_requester().schedule_frame(); } if let Some(delay) = feedback_tick { tui.frame_requester().schedule_frame_in(delay); } + if let Some(delay) = blossom_tick { + tui.frame_requester().schedule_frame_in(delay); + } let animating = view.is_following() && active_key.is_some_and(|key| key.animation_tick.is_some()); let loading = view.is_loading_history() && motion == MotionMode::Animated; @@ -268,6 +307,10 @@ impl App { return Ok(false); } if matches!(event, TuiEvent::FocusLost) { + self.chat_widget + .empty_state_animation + .borrow_mut() + .cancel_replay(); // Show the static, faded decoration immediately when the terminal loses focus. tui.frame_requester().schedule_frame(); } @@ -291,6 +334,16 @@ impl App { let size = tui.prepare_draw_size()?; self.render_owned_transcript(tui, size)?; } + if self.chat_widget.no_modal_or_popup_active() + && self + .chat_widget + .empty_state_animation + .borrow_mut() + .handle_mouse(*mouse) + { + tui.frame_requester().schedule_frame(); + return Ok(true); + } if composer_ready && self.handle_composer_copy_event(tui, event, |tui, text| { tui.copy_transcript_selection( @@ -525,7 +578,7 @@ impl App { #[cfg(test)] #[path = "owned_transcript_tests.rs"] -mod tests; +pub(super) mod tests; #[cfg(test)] #[path = "empty_state_animation_tests.rs"] diff --git a/codex-rs/tui/src/app/owned_transcript_tests.rs b/codex-rs/tui/src/app/owned_transcript_tests.rs index 48c247aed9..46c0da6d9e 100644 --- a/codex-rs/tui/src/app/owned_transcript_tests.rs +++ b/codex-rs/tui/src/app/owned_transcript_tests.rs @@ -23,7 +23,7 @@ use crossterm::event::MouseEventKind::Up; use pretty_assertions::assert_eq; use ratatui::buffer::Buffer; -fn user_cell(message: &str) -> Arc { +pub(in crate::app) fn user_cell(message: &str) -> Arc { Arc::new(UserHistoryCell { spoken: false, message: message.to_string(), @@ -33,7 +33,7 @@ fn user_cell(message: &str) -> Arc { }) } -fn attach_thread(app: &mut App, thread_id: ThreadId) { +pub(in crate::app) fn attach_thread(app: &mut App, thread_id: ThreadId) { app.chat_widget.handle_thread_session(ThreadSessionState { windows_sandbox_host: crate::app::WindowsSandboxHost::Local, thread_id, @@ -59,7 +59,7 @@ fn attach_thread(app: &mut App, thread_id: ThreadId) { }); } -pub(super) fn buffer_text(buffer: &Buffer) -> String { +pub(in crate::app) fn buffer_text(buffer: &Buffer) -> String { buffer .content() .chunks(usize::from(buffer.area.width)) @@ -515,6 +515,7 @@ async fn owned_details_keep_the_composer_cursor_and_screen() -> Result<()> { /*footer*/ None, crate::bottom_pane::CommandPopupPlacement::Overlay, Some(&crate::bottom_pane::ComposerGap::default()), + /*working_tip*/ None, ) .cursor_pos(bottom_area) .expect("composer cursor"); diff --git a/codex-rs/tui/src/app/session_lifecycle.rs b/codex-rs/tui/src/app/session_lifecycle.rs index dabf197d30..879c20cef0 100644 --- a/codex-rs/tui/src/app/session_lifecycle.rs +++ b/codex-rs/tui/src/app/session_lifecycle.rs @@ -1097,10 +1097,13 @@ impl App { ThreadAttachPresentation::Fresh | ThreadAttachPresentation::FreshWithDraft ) { self.chat_widget.mark_fresh_task_for_sparkle(&started); - self.chat_widget - .empty_state_animation - .borrow_mut() - .start_fresh(); + // FreshWithDraft inherits its provisional greeting and replay at the handoff. + if matches!(presentation, ThreadAttachPresentation::Fresh) { + self.chat_widget + .empty_state_animation + .borrow_mut() + .start_fresh(); + } } self.chat_widget .set_task_mentions_enabled(started.task_tools_available); diff --git a/codex-rs/tui/src/app/snapshots/codex_tui__app__owned_transcript__empty_state_animation_tests__fresh_thread_header.snap b/codex-rs/tui/src/app/snapshots/codex_tui__app__owned_transcript__empty_state_animation_tests__fresh_thread_header.snap index 03bca75b48..1261499117 100644 --- a/codex-rs/tui/src/app/snapshots/codex_tui__app__owned_transcript__empty_state_animation_tests__fresh_thread_header.snap +++ b/codex-rs/tui/src/app/snapshots/codex_tui__app__owned_transcript__empty_state_animation_tests__fresh_thread_header.snap @@ -1,13 +1,60 @@ --- source: tui/src/app/empty_state_animation_tests.rs -expression: text(after) +expression: "format!(\"enabled:\\n{}\\n---\\ndisabled:\\n{}\", text(after), text(&before))" --- -╭───────────────────────────────────────────╮ -│ >_ OpenAI Codex (v0.0.0) │ -│ │ -│ model: GPT-5.6-Sol /model to change │ -│ directory: /tmp/project │ -╰───────────────────────────────────────────╯ +enabled: + + >_ OpenAI Codex (v0.0.0) + /tmp/project + + Pull up a prompt. + + + + + + + + + ⣀⣤⣤⣤⣀⣀ + ⣠⣶⣿⣿⣿⣿⣿⣿⣿⣿⣦⣤⣤⣤⣤⣤⣤⡀ + ⢀⣾⣿⣿⠿⠋⠉⠉⢉⣭⣿⣿⣿⣿⣿⠿⣿⣿⣿⣿⣷⣄ + ⣀⣾⣿⣿⠃ ⣀⣴⣾⣿⣿⡿⠟⠋ ⣀⡀ ⠈⠙⢿⣿⣿⣧ + ⣀⣶⣿⣿⣿⣿⡇ ⢸⣿⣿⡿⠛⠉⢀⣠⣴⣿⣿⣿⣷⣦⣀⠈⢻⣿⣿⡇ + ⣰⣿⣿⡿⢿⣿⣿⡇ ⢸⣿⣿⢀⣤⣶⣿⣿⣿⠟⠛⠻⣿⣿⣿⣿⣮⣿⣿⡷ + ⢰⣿⣿⡟⠁⢸⣿⣿⡇ ⢸⣿⣿⣿⣿⠿⠿⣿⣿⣿⣦⣄⡀⠈⠛⠿⣿⣿⣿⣧⡀ + ⣾⣿⣿⠃ ⢸⣿⣿⡇ ⢸⣿⣿⠋⠁ ⠈⠙⢻⣿⣿⣿⣶⣤⡀ ⠹⢿⣿⣷⡄ + ⢸⣿⣿⣇ ⠸⣿⣿⣷⣦⣼⣿⣿ ⢸⣿⣿⠻⢿⣿⣿⡇ ⠘⣿⣿⣿ + ⠈⢿⣿⣿⣦⡀⠈⠛⠿⣿⣿⣿⣿⣄⡀ ⢀⣠⣼⣿⣿ ⣿⣿⡇ ⣿⣿⣿⠇ + ⢻⣿⣿⣿⣷⣦⣀⠈⠙⠻⣿⣿⣿⣶⣶⣿⣿⣿⣿⣿ ⣿⣿⡇ ⣠⣿⣿⣿ + ⢸⣿⣿⡿⢿⣿⣿⣿⣦⣠⣴⣿⣿⣿⡿⠟⠋⢸⣿⣿ ⣿⣿⣷⣴⣿⣿⣿⠃ + ⠘⣿⣿⣷ ⠈⠛⢿⣿⣿⣿⠿⠋⠉ ⣠⣴⣿⣿⣿ ⣿⣿⣿⣿⣿⠟⠁ + ⠻⣿⣿⣿⣤⣀ ⠈⠉ ⢀⣤⣶⣿⣿⣿⠿⠟⠁ ⣰⣿⣿⡟⠋⠁ + ⠈⠿⣿⣿⣿⣿⣶⣾⣿⣿⣿⣿⠟⠋⠁ ⣠⣼⣿⣿⡟ + ⠙⠛⠛⠛⠻⠛⢿⣿⣿⣿⣿⣷⣾⣿⣿⣿⡿⠏ + ⠈⠙⠛⠿⠿⠿⠿⠛⠉ + + + + + + + + + + +› Ask Codex to do anything + + GPT-5.6-Sol default · /tmp/project + ? for shortcuts ⚠ 1 warning · f2 to view +--- +disabled: + + >_ OpenAI Codex (v0.0.0) + /tmp/project + + Pull up a prompt. + diff --git a/codex-rs/tui/src/app/snapshots/codex_tui__app__turn_tips__tests__turn_tip_placements.snap b/codex-rs/tui/src/app/snapshots/codex_tui__app__turn_tips__tests__turn_tip_placements.snap new file mode 100644 index 0000000000..d23bcc64e9 --- /dev/null +++ b/codex-rs/tui/src/app/snapshots/codex_tui__app__turn_tips__tests__turn_tip_placements.snap @@ -0,0 +1,110 @@ +--- +source: tui/src/app/turn_tips_tests.rs +assertion_line: 337 +expression: "crate::chatwidget::tests::helpers::normalize_snapshot_paths(screens.join(\"\\n\\n\"))" +--- +working=true, response rows=1, 80x12 + + +Response row 0 + +• Working (0s • esc to interrupt) + └ Tip: Try /help. + + +› Ask Codex to do anything + + gpt-test default · /tmp/project + ? for shortcuts + +working=true, response rows=1, 80x6 +• Working (0s • esc to interrupt) + +› Ask Codex to do anything + + gpt-test default · /tmp/project + ? for shortcuts + +working=false, response rows=1, 80x12 +Show a response. + +• Done. + └ Tip: Try /help. + + [completion time] + + +› Ask Codex to do anything + + gpt-test default · /tmp/project + ? for shortcuts + +working=false, response rows=30, 80x12 +Show a response. + +• Done. + └ Tip: Try /help. + + [completion time] + + +› Ask Codex to do anything + + gpt-test default · /tmp/project + ? for shortcuts + +working=false, response rows=1, 80x9 +• Done. + + [completion time] + + +› Ask Codex to do anything + + gpt-test default · /tmp/project + ? for shortcuts + +working=false, response rows=1, 80x10 +Show a response. +• Done. + + [completion time] + + +› Ask Codex to do anything + + gpt-test default · /tmp/project + ? for shortcuts + +working=false, response rows=1, 80x11 +Show a response. +• Done. + └ Tip: Try /help. + + [completion time] + + +› Ask Codex to do anything + + gpt-test default · /tmp/project + ? for shortcuts + +working=false, response rows=1, 12x12 +Response row +0 + +• Done. + + [completion time] + + +› Ask Codex + + gpt-test … + ? for shor + +working=false, response rows=1, 80x4 + +› Ask Codex to do anything + + ? for shortcuts diff --git a/codex-rs/tui/src/app/startup.rs b/codex-rs/tui/src/app/startup.rs index cb2c77f5db..6b283327a7 100644 --- a/codex-rs/tui/src/app/startup.rs +++ b/codex-rs/tui/src/app/startup.rs @@ -698,7 +698,10 @@ impl App { } chat_widget.note_rendered_width(tui.terminal.last_known_screen_size.width); if pending_startup_thread_start && !start_in_agents_overview { - chat_widget.empty_state_animation.borrow_mut().start_fresh(); + chat_widget + .empty_state_animation + .borrow_mut() + .continue_from(&mut startup_draft.blossom.borrow_mut()); } chat_widget.remote_connection = remote_connection; chat_widget.snapshot_local_images = app_server_target.uses_remote_workspace(); @@ -765,6 +768,7 @@ See the Codex keymap documentation for supported actions and examples." key_chord_matcher: KeyChordMatcher::default(), transcript_cells: Vec::new(), native_history: Default::default(), + turn_tips: Default::default(), transcript_view: Default::default(), last_rendered_history_tail: None, last_thread_usage_status_cell: None, diff --git a/codex-rs/tui/src/app/test_support.rs b/codex-rs/tui/src/app/test_support.rs index 93c33b7257..c88edb3b50 100644 --- a/codex-rs/tui/src/app/test_support.rs +++ b/codex-rs/tui/src/app/test_support.rs @@ -39,6 +39,7 @@ pub(crate) async fn make_test_app() -> App { file_search, transcript_cells: Vec::new(), native_history: Default::default(), + turn_tips: Default::default(), transcript_view: Default::default(), last_rendered_history_tail: None, last_thread_usage_status_cell: None, diff --git a/codex-rs/tui/src/app/tests.rs b/codex-rs/tui/src/app/tests.rs index 31a785431b..aaf745c149 100644 --- a/codex-rs/tui/src/app/tests.rs +++ b/codex-rs/tui/src/app/tests.rs @@ -6012,6 +6012,7 @@ async fn make_test_app() -> Box { file_search, transcript_cells: Vec::new(), native_history: Default::default(), + turn_tips: Default::default(), transcript_view: Default::default(), last_rendered_history_tail: None, last_thread_usage_status_cell: None, @@ -6127,6 +6128,7 @@ pub(super) async fn make_test_app_with_channels() -> ( file_search, transcript_cells: Vec::new(), native_history: Default::default(), + turn_tips: Default::default(), transcript_view: Default::default(), last_rendered_history_tail: None, last_thread_usage_status_cell: None, diff --git a/codex-rs/tui/src/app/tests/background_task_defaults_tests.rs b/codex-rs/tui/src/app/tests/background_task_defaults_tests.rs index f0f7b943af..2a17d7aeec 100644 --- a/codex-rs/tui/src/app/tests/background_task_defaults_tests.rs +++ b/codex-rs/tui/src/app/tests/background_task_defaults_tests.rs @@ -75,6 +75,16 @@ async fn command_center_new_keeps_startup_draft_visible_through_handoff() -> Res app.chat_widget.composer_text_with_pending(), "draft during startup" ); + assert_eq!( + app.chat_widget + .empty_state_animation + .borrow() + .greeting + .get() + .unwrap() + .phrase, + "Pull up a prompt." + ); while let Ok(event) = events.try_recv() { Box::pin(app.handle_event(&mut tui, &mut server, event)).await?; diff --git a/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__startup_frame_tests__startup_tip_in_transcript.snap b/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__startup_frame_tests__startup_tip_in_transcript.snap index 5a78a900ac..8ed7c18cff 100644 --- a/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__startup_frame_tests__startup_tip_in_transcript.snap +++ b/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__startup_frame_tests__startup_tip_in_transcript.snap @@ -1,16 +1,14 @@ --- source: tui/src/app/tests/startup_frame_tests.rs +assertion_line: 72 expression: "normalize_snapshot_paths(normalize_agent_center_snapshot(snapshots.join(\"\\n\\n\")))" --- 80 columns -╭────────────────────────────────────────╮ -│ >_ OpenAI Codex (v0.0.0) │ -│ │ -│ model: gpt-test /model to change │ -│ directory: /tmp/project │ -╰────────────────────────────────────────╯ - Tip: Use /mcp to list configured MCP tools. + >_ OpenAI Codex (v0.0.0) + /tmp/project + + Pull up a prompt. • Conversation continues here. @@ -19,21 +17,20 @@ expression: "normalize_snapshot_paths(normalize_agent_center_snapshot(snapshots. + + + › Ask Codex to do anything GPT-5.6-Sol default · /tmp/project ? for shortcuts 32 columns -╭──────────────────────────────╮ -│ >_ OpenAI Codex (v0.0.0) │ -│ │ -│ model: gpt-test /mode… │ -│ directory: /tmp/project │ -╰──────────────────────────────╯ - Tip: Use /mcp to list - configured MCP tools. + >_ OpenAI Codex (v0.0.0) + /tmp/project + + Pull up a prompt. • Conversation continues here. @@ -41,6 +38,10 @@ expression: "normalize_snapshot_paths(normalize_agent_center_snapshot(snapshots. + + + + › Ask Codex to do anything GPT-5.6-Sol default · /tmp/pr… diff --git a/codex-rs/tui/src/app/tests/startup_frame_tests.rs b/codex-rs/tui/src/app/tests/startup_frame_tests.rs index e9f983be54..97a99c04df 100644 --- a/codex-rs/tui/src/app/tests/startup_frame_tests.rs +++ b/codex-rs/tui/src/app/tests/startup_frame_tests.rs @@ -4,6 +4,7 @@ use super::*; use crate::chatwidget::tests::helpers::normalize_agent_center_snapshot; use crate::chatwidget::tests::helpers::normalize_snapshot_paths; use crate::custom_terminal::test_support::last_rendered_buffer; +use crate::history_cell::HistoryRenderMode; use crate::startup_draft::tests::quiet_startup_test_pump; use pretty_assertions::assert_eq; @@ -16,23 +17,31 @@ fn frame_text(tui: &tui::Tui) -> String { } #[tokio::test] -async fn owned_startup_tip_follows_splash_in_transcript() -> Result<()> { +async fn owned_startup_hides_tip_in_transcript() -> Result<()> { let mut app = crate::app::test_support::make_test_app().await; app.local_settings.tui.show_tooltips = true; app.local_settings.tui.animations = false; + let greeting = Arc::new(std::sync::OnceLock::new()); + greeting + .set(crate::empty_state_animation::Greeting { + phrase: "Pull up a prompt.", + }) + .unwrap(); let session = test_thread_session(ThreadId::new(), app.config.cwd.to_path_buf()); + let mut session_info = new_session_info( + &app.config, + &app.local_settings, + &session.model, + &session.model, + &session, + /*is_first_event*/ false, + Some("Use /mcp to list configured MCP tools.".into()), + /*auth_plan*/ None, + /*show_fast_status*/ false, + ); + history_cell::set_session_greeting(&mut session_info, &greeting); app.transcript_cells = vec![ - Arc::new(new_session_info( - &app.config, - &app.local_settings, - &session.model, - &session.model, - &session, - /*is_first_event*/ false, - Some("Use /mcp to list configured MCP tools.".into()), - /*auth_plan*/ None, - /*show_fast_status*/ false, - )), + Arc::new(session_info), Arc::new(AgentMessageCell::new( vec!["Conversation continues here.".into()], /*is_first_line*/ true, @@ -64,6 +73,28 @@ async fn owned_startup_tip_follows_splash_in_transcript() -> Result<()> { "startup_tip_in_transcript", normalize_snapshot_paths(normalize_agent_center_snapshot(snapshots.join("\n\n"))), ); + // The source remains available to terminal scrollback in both presentation modes. + for mode in [HistoryRenderMode::Rich, HistoryRenderMode::Raw] { + let lines = app.transcript_cells[0].display_lines_for_mode(/*width*/ 80, mode); + let text = lines + .iter() + .map(ToString::to_string) + .collect::>() + .join("\n"); + assert!(text.contains("Pull up a prompt.")); + assert!(text.contains("Use /mcp")); + assert!(!text.contains("model:")); + assert!(!text.contains('╭')); + } + app.transcript_view.begin_search(); + app.render_owned_transcript(&mut tui, Size::new(/*width*/ 80, /*height*/ 20))?; + assert!(!frame_text(&tui).contains("Use /mcp")); + app.open_transcript_overlay(&mut tui); + app.render_owned_transcript(&mut tui, Size::new(/*width*/ 80, /*height*/ 20))?; + assert!(!frame_text(&tui).contains("Use /mcp")); + app.apply_raw_output_mode(&mut tui, /*enabled*/ true, /*notify*/ false); + app.render_owned_transcript(&mut tui, Size::new(/*width*/ 80, /*height*/ 20))?; + assert!(!frame_text(&tui).contains("Use /mcp")); tui.set_owned_screen(/*owned*/ false)?; Ok(()) } diff --git a/codex-rs/tui/src/app/tests/transcript_selection.rs b/codex-rs/tui/src/app/tests/transcript_selection.rs index 735a7db672..29f2782ef3 100644 --- a/codex-rs/tui/src/app/tests/transcript_selection.rs +++ b/codex-rs/tui/src/app/tests/transcript_selection.rs @@ -72,8 +72,8 @@ async fn text_selection_temporarily_replaces_the_rendered_backtrack_highlight() .await?; } let (_, highlighted) = render(&mut app); - // The selected leading newline paints one blank cell before the first prompt character. - assert_eq!(highlighted, " S"); + // The selected leading newline does not paint an empty cell. + assert_eq!(highlighted, "S"); app.handle_tui_event( &mut tui, diff --git a/codex-rs/tui/src/app/thread_routing.rs b/codex-rs/tui/src/app/thread_routing.rs index 21c420b7a0..a3501c3a1b 100644 --- a/codex-rs/tui/src/app/thread_routing.rs +++ b/codex-rs/tui/src/app/thread_routing.rs @@ -2023,8 +2023,13 @@ impl App { match event { ThreadBufferedEvent::Notification(notification) => { self.cache_collab_receiver_threads_for_notification(notification.as_ref()); + let tip_ready = self.turn_tips.observe(¬ification, Instant::now()); self.chat_widget .handle_server_notification(*notification, /*replay_kind*/ None); + // History cells queued by completion must be applied before anchoring its tip. + if let Some(event) = tip_ready { + self.app_event_tx.send(event); + } } ThreadBufferedEvent::Request(request) => { if self @@ -2056,6 +2061,7 @@ impl App { } pub(super) fn handle_thread_event_replay(&mut self, event: ThreadBufferedEvent) { + self.turn_tips.dismiss(); match event { ThreadBufferedEvent::Notification(notification) => self .chat_widget diff --git a/codex-rs/tui/src/app/turn_tips.rs b/codex-rs/tui/src/app/turn_tips.rs new file mode 100644 index 0000000000..868f9552c6 --- /dev/null +++ b/codex-rs/tui/src/app/turn_tips.rs @@ -0,0 +1,235 @@ +//! Random foreground-turn tips with separate working and completion frequency rules. +//! A FIFO completion event anchors the tip after queued history; replay never creates tips. + +use super::*; +use crate::terminal_hyperlinks::prefix_hyperlink_lines; +use crate::turn_tip::TurnTip; +use codex_protocol::models::MessagePhase; +use rand::seq::SliceRandom; +use std::sync::Weak; + +const WORKING_DELAY: Duration = Duration::from_secs(/*secs*/ 30); +const COMPLETION_INTERVAL: usize = 3; +const COMPLETION_LIMIT: usize = 2; + +#[derive(Default)] +pub(super) struct TurnTips { + starts: usize, + completions_shown: usize, + next_completion: usize, + previous: Option<&'static str>, + current: Option, +} + +struct TurnTipState { + thread_id: ThreadId, + turn_id: String, + started_at: Instant, + phase: Phase, + has_final_answer: bool, + template: Option<&'static str>, + shown: bool, +} + +enum Phase { + Working, + WaitingForHistory, + Complete(Weak), + Finished, +} + +#[derive(Clone, Copy, PartialEq, Eq)] +pub(super) enum TipSurface { + Working, + Completion, +} + +fn is_final_answer(item: &ThreadItem) -> bool { + matches!(item, ThreadItem::AgentMessage { text, phase: Some(MessagePhase::FinalAnswer) | None, .. } + if !text.trim().is_empty()) +} + +impl TurnTips { + pub(super) fn dismiss(&mut self) { + self.current = None; + } + + pub(super) fn observe( + &mut self, + notification: &ServerNotification, + now: Instant, + ) -> Option { + if let ServerNotification::TurnStarted(started) = notification { + let thread_id = ThreadId::from_string(&started.thread_id).ok()?; + if self.current.as_ref().is_some_and(|current| { + current.thread_id == thread_id && current.turn_id == started.turn.id + }) { + return None; + } + self.starts = self.starts.saturating_add(/*rhs*/ 1); + self.current = Some(TurnTipState { + thread_id, + turn_id: started.turn.id.clone(), + started_at: now, + phase: Phase::Working, + has_final_answer: false, + template: None, + shown: false, + }); + return None; + } + let current = self.current.as_mut()?; + match notification { + ServerNotification::ItemCompleted(item) + if item.thread_id == current.thread_id.to_string() + && item.turn_id == current.turn_id => + { + current.has_final_answer |= is_final_answer(&item.item); + } + ServerNotification::TurnCompleted(completed) + if completed.thread_id == current.thread_id.to_string() + && completed.turn.id == current.turn_id + && matches!(current.phase, Phase::Working) => + { + current.has_final_answer |= completed.turn.items.iter().any(is_final_answer); + if completed.turn.status == TurnStatus::Completed + && current.has_final_answer + && !current.shown + && self.completions_shown < COMPLETION_LIMIT + && self.starts >= self.next_completion.max(COMPLETION_INTERVAL) + { + current.phase = Phase::WaitingForHistory; + return Some(AppEvent::TurnTipReady { + thread_id: current.thread_id, + turn_id: current.turn_id.clone(), + }); + } + current.phase = Phase::Finished; + } + _ => {} + } + None + } + + pub(super) fn ready( + &mut self, + thread_id: ThreadId, + turn_id: &str, + tail: Option<&Arc>, + ) { + if let Some(current) = self.current.as_mut() + && current.thread_id == thread_id + && current.turn_id == turn_id + && matches!(current.phase, Phase::WaitingForHistory) + { + current.phase = tail.map_or(Phase::Finished, |tail| { + Phase::Complete(Arc::downgrade(tail)) + }); + } + } + + pub(super) fn acknowledge(&mut self, surface: TipSurface) { + if let Some(current) = self.current.as_mut() + && !current.shown + { + current.shown = true; + self.previous = current.template; + if surface == TipSurface::Completion { + self.completions_shown += 1; + self.next_completion = self.starts.saturating_add(COMPLETION_INTERVAL); + } + } + } +} + +impl App { + pub(super) fn turn_tip( + &mut self, + width: u16, + now: Instant, + frame_requester: &tui::FrameRequester, + ) -> Option<(TipSurface, TurnTip)> { + if !self.local_settings.tui.show_tooltips + || !self.chat_widget.no_modal_or_popup_active() + || !self.chat_widget.composer_is_empty() + || self.chat_widget.is_external_writer_view() + || self.chat_widget.has_queued_follow_up_messages() + || !self.transcript_view.is_following() + || self.transcript_view.has_active_interaction() + || self.backtrack.primed + || self.backtrack.overlay_preview_active + || self.composer_hint(width).is_some() + { + return None; + } + let current = self.turn_tips.current.as_mut()?; + if self.chat_widget.thread_id() != Some(current.thread_id) { + return None; + } + let surface = match ¤t.phase { + Phase::Working if self.chat_widget.is_agent_turn_running() => { + let remaining = + WORKING_DELAY.saturating_sub(now.saturating_duration_since(current.started_at)); + if !remaining.is_zero() { + frame_requester.schedule_frame_in(remaining); + return None; + } + TipSurface::Working + } + Phase::Complete(tail) if !self.chat_widget.is_user_turn_pending_or_running() => { + if !self + .transcript_cells + .last() + .is_some_and(|last| tail.ptr_eq(&Arc::downgrade(last))) + { + current.phase = Phase::Finished; + return None; + } + TipSurface::Completion + } + _ => return None, + }; + let content_width = usize::from(width.checked_sub(/*rhs*/ 4)?); + let render = |template| { + let text = crate::tooltips::render_tooltip(template, Some(&self.keymap))?; + let lines = crate::tooltips::render_tooltip_lines( + &text, + content_width, + self.config.cwd.as_path(), + ); + match lines.as_slice() { + [line] if line.width() <= content_width => Some(line.clone()), + _ => None, + } + }; + if current.template.is_none() { + let mut templates = crate::tooltips::tooltip_templates().collect::>(); + templates.shuffle(&mut rand::rng()); + current.template = templates + .iter() + .copied() + .filter(|template| Some(*template) != self.turn_tips.previous) + .find(|template| render(template).is_some()) + .or_else(|| { + templates + .into_iter() + .find(|template| render(template).is_some()) + }); + } + let line = render(current.template?)?; + let line = prefix_hyperlink_lines(vec![line], " └ ".dim(), " ".dim()) + .pop()? + .style(crate::style::secondary_text_style()); + Some(( + surface, + TurnTip { + line, + rendered: Default::default(), + }, + )) + } +} + +#[cfg(test)] +#[path = "turn_tips_tests.rs"] +mod tests; diff --git a/codex-rs/tui/src/app/turn_tips_tests.rs b/codex-rs/tui/src/app/turn_tips_tests.rs new file mode 100644 index 0000000000..5e17648c15 --- /dev/null +++ b/codex-rs/tui/src/app/turn_tips_tests.rs @@ -0,0 +1,347 @@ +//! Foreground lifecycle, actual exposure, and dedicated-row geometry. + +use super::*; +use crate::app::owned_transcript::tests::attach_thread; +use crate::app::owned_transcript::tests::buffer_text; +use crate::app::owned_transcript::tests::user_cell; +use pretty_assertions::assert_eq; + +fn notification(method: &str, thread: ThreadId, turn: usize, status: &str) -> ServerNotification { + serde_json::from_value(serde_json::json!({ + "method": method, + "params": { "threadId": thread.to_string(), "turn": { + "id": turn.to_string(), "items": [], "itemsView": "full", "status": status, + "error": null, "startedAt": null, "completedAt": null, "durationMs": null, + }}, + })) + .unwrap() +} + +fn answer(thread: ThreadId, turn: usize) -> ServerNotification { + serde_json::from_value(serde_json::json!({ + "method": "item/completed", "params": { + "threadId": thread.to_string(), "turnId": turn.to_string(), "completedAtMs": 0, + "item": {"type": "agentMessage", "id": "answer", "text": "Done.", + "phase": "final_answer", "memoryCitation": null, "delivery": null, "questions": null}, + }, + })).unwrap() +} + +fn deliver(app: &mut App, notification: ServerNotification) { + app.handle_thread_event_now(ThreadBufferedEvent::Notification(Box::new(notification))); +} + +#[test] +fn completion_cadence_counts_exposure_and_ignores_duplicate_or_failed_turns() { + let thread = ThreadId::new(); + let now = Instant::now(); + let mut tips = TurnTips::default(); + let mut candidates = Vec::new(); + for turn in 1..=12 { + let start = notification("turn/started", thread, turn, "inProgress"); + tips.observe(&start, now); + tips.observe(&start, now); + assert_eq!(tips.starts, turn); + if turn == 3 { + tips.acknowledge(TipSurface::Working); + } + tips.observe(&answer(thread, turn), now); + let status = match turn { + 4 => "failed", + 5 => "interrupted", + _ => "completed", + }; + let completed = notification("turn/completed", thread, turn, status); + if tips.observe(&completed, now).is_some() { + candidates.push(turn); + // A hidden candidate spends nothing; two painted frames spend only once. + if turn != 6 { + tips.acknowledge(TipSurface::Completion); + tips.acknowledge(TipSurface::Completion); + } + } + assert!(tips.observe(&completed, now).is_none()); + } + assert_eq!( + (candidates, tips.completions_shown, tips.next_completion), + (vec![6, 7, 10], 2, 13) + ); + tips.dismiss(); + assert!( + tips.observe( + ¬ification("turn/completed", thread, /*turn*/ 12, "completed"), + now + ) + .is_none() + ); + assert_eq!(tips.starts, 12); +} + +#[tokio::test] +async fn working_deadline_rearms_and_hidden_rows_do_not_spend_exposure() { + let (mut app, _events, _ops) = crate::app::tests::make_test_app_with_channels().await; + let thread = ThreadId::new(); + attach_thread(&mut app, thread); + app.local_settings.tui.animations = false; + app.local_settings.tui.show_tooltips = true; + let now = Instant::now(); + deliver( + &mut app, + notification("turn/started", thread, /*turn*/ 1, "inProgress"), + ); + app.turn_tips.current.as_mut().unwrap().started_at = now; + let (frames, mut requests) = tui::FrameRequester::test_channel(); + for elapsed in [0, 10, 29] { + assert!( + app.turn_tip( + /*width*/ 100, + now + Duration::from_secs(elapsed), + &frames + ) + .is_none() + ); + let remaining = requests + .try_recv() + .unwrap() + .saturating_duration_since(Instant::now()); + assert!(remaining <= WORKING_DELAY - Duration::from_secs(elapsed)); + assert!(remaining > WORKING_DELAY - Duration::from_secs(elapsed + 1)); + } + let current = app.turn_tips.current.as_mut().unwrap(); + // Use a catalog-independent key-free fixture for width and visibility. + current.template = Some("Try /help."); + assert!( + app.turn_tip(/*width*/ 8, now + WORKING_DELAY, &frames) + .is_none() + ); + assert!(!app.turn_tips.current.as_ref().unwrap().shown); + app.chat_widget.apply_external_edit("draft".into()); + assert!( + app.turn_tip(/*width*/ 100, now + WORKING_DELAY, &frames) + .is_none() + ); + app.chat_widget.apply_external_edit(String::new()); + app.local_settings.tui.show_tooltips = false; + assert!( + app.turn_tip(/*width*/ 100, now + WORKING_DELAY, &frames) + .is_none() + ); + app.local_settings.tui.show_tooltips = true; + assert!( + app.turn_tip(/*width*/ 100, now + WORKING_DELAY, &frames) + .is_some() + ); + assert!(requests.try_recv().is_err()); + + app.handle_thread_event_replay(ThreadBufferedEvent::Notification(Box::new(notification( + "turn/started", + thread, + /*turn*/ 1, + "inProgress", + )))); + assert!(app.turn_tips.current.is_none()); + assert_eq!( + (app.turn_tips.starts, app.turn_tips.completions_shown), + (1, 0) + ); + app.turn_tips.starts = 2; + deliver( + &mut app, + notification("turn/started", thread, /*turn*/ 3, "inProgress"), + ); + app.chat_widget + .apply_external_edit("queued follow-up".into()); + app.chat_widget + .handle_key_event(KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE)); + deliver(&mut app, answer(thread, /*turn*/ 3)); + deliver( + &mut app, + notification("turn/completed", thread, /*turn*/ 3, "completed"), + ); + app.transcript_cells + .push(Arc::new(history_cell::PlainHistoryCell::new(vec![ + "Done.".into(), + ]))); + app.turn_tips + .ready(thread, "3", app.transcript_cells.last()); + assert!(app.chat_widget.is_user_turn_pending_or_running()); + assert!( + app.turn_tip(/*width*/ 100, now + WORKING_DELAY, &frames) + .is_none() + ); + app.reset_transcript_state_after_clear(); + assert!(app.turn_tips.current.is_none()); + assert_eq!( + (app.turn_tips.starts, app.turn_tips.completions_shown), + (3, 0) + ); +} + +#[tokio::test] +async fn turn_tip_placements_and_completion_barrier() -> Result<()> { + let mut screens = Vec::new(); + for (working, rows, width, height) in [ + (true, 1, 80, 12), + (true, 1, 80, 6), + (false, 1, 80, 12), + (false, 30, 80, 12), + (false, 1, 80, 9), + (false, 1, 80, 10), + (false, 1, 80, 11), + (false, 1, 12, 12), + (false, 1, 80, 4), + ] { + let (mut app, mut events, _ops) = crate::app::tests::make_test_app_with_channels().await; + let thread = ThreadId::new(); + attach_thread(&mut app, thread); + app.local_settings.tui.show_tooltips = true; + app.local_settings.tui.animations = false; + app.turn_tips.starts = 2; + let mut tui = crate::tui::test_support::make_test_tui()?; + tui.set_owned_screen(/*owned*/ true)?; + let size = Size::new(width, height); + tui.terminal.resize(size)?; + while events.try_recv().is_ok() {} + app.transcript_cells = vec![ + user_cell("Show a response."), + Arc::new(history_cell::PlainHistoryCell::new( + (0..rows) + .map(|row| format!("Response row {row}").into()) + .collect(), + )), + ]; + deliver( + &mut app, + notification("turn/started", thread, /*turn*/ 3, "inProgress"), + ); + app.turn_tips.current.as_mut().unwrap().started_at = Instant::now() - WORKING_DELAY; + app.turn_tips.current.as_mut().unwrap().template = Some("Try /help."); + if !working { + deliver(&mut app, answer(thread, /*turn*/ 3)); + deliver( + &mut app, + notification("turn/completed", thread, /*turn*/ 3, "completed"), + ); + app.render_owned_transcript(&mut tui, size)?; + assert!(!app.turn_tips.current.as_ref().unwrap().shown); + } + let mut saw_barrier = false; + while let Ok(event) = events.try_recv() { + match event { + AppEvent::InsertHistoryCell(cell) => { + assert!(!saw_barrier); + app.insert_history_cell(&mut tui, cell); + } + AppEvent::TurnTipReady { thread_id, turn_id } => { + app.turn_tips + .ready(thread_id, &turn_id, app.transcript_cells.last()); + saw_barrier = true; + } + _ => {} + } + } + assert_eq!(saw_barrier, !working); + app.render_owned_transcript(&mut tui, size)?; + let screen = crate::chatwidget::tests::helpers::normalize_completion_timestamps( + app.transcript_cells.last().unwrap().as_ref(), + buffer_text(crate::custom_terminal::test_support::last_rendered_buffer( + &tui.terminal, + )), + ); + let shown = screen.contains("└ Tip:"); + if shown && !working { + assert!(screen.contains("• Done."), "{screen}"); + } + assert_eq!(app.turn_tips.current.as_ref().unwrap().shown, shown); + assert_eq!( + app.turn_tips.completions_shown, + usize::from(!working && shown) + ); + screens.push(format!( + "working={working}, response rows={rows}, {width}x{height}\n{screen}" + )); + if shown { + let narrow = Size::new(/*width*/ 8, height); + tui.terminal.resize(narrow)?; + app.render_owned_transcript(&mut tui, narrow)?; + assert!( + !buffer_text(crate::custom_terminal::test_support::last_rendered_buffer( + &tui.terminal + )) + .contains("Tip:") + ); + tui.terminal.resize(size)?; + app.render_owned_transcript(&mut tui, size)?; + assert_eq!(app.turn_tips.completions_shown, usize::from(!working)); + } + if !working && shown { + assert!( + !app.transcript_cells + .iter() + .flat_map(|cell| cell.raw_lines()) + .any(|line| line.to_string().contains("Try /help")) + ); + let response_row = screen + .lines() + .position(|line| line.contains("• Done.")) + .unwrap() as u16; + for (kind, column, row) in [ + ( + crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left), + 0, + response_row, + ), + ( + crossterm::event::MouseEventKind::Drag(crossterm::event::MouseButton::Left), + width - 1, + height - 1, + ), + ] { + app.transcript_view.handle_mouse( + crossterm::event::MouseEvent { + kind, + column, + row, + modifiers: KeyModifiers::NONE, + }, + &app.transcript_cells, + ); + } + let selected = app + .transcript_view + .selected_text(&app.transcript_cells) + .unwrap(); + assert!(selected.contains("Done.")); + assert!( + selected.contains(&app.transcript_cells.last().unwrap().raw_lines()[0].to_string()) + ); + assert!(!selected.contains("Try /help")); + app.transcript_view.end_selection(&app.transcript_cells); + app.transcript_view.begin_search(); + app.transcript_view.paste_search("Try /help"); + while app.transcript_view.advance_search(&app.transcript_cells) {} + app.render_owned_transcript(&mut tui, size)?; + assert!( + buffer_text(crate::custom_terminal::test_support::last_rendered_buffer( + &tui.terminal + )) + .contains("No matches") + ); + app.transcript_view.cancel_search(); + app.transcript_cells + .push(Arc::new(history_cell::PlainHistoryCell::new(vec![ + "Unrelated output".into(), + ]))); + assert!( + app.turn_tip(width, Instant::now(), &tui.frame_requester()) + .is_none() + ); + } + tui.set_owned_screen(/*owned*/ false)?; + } + insta::assert_snapshot!( + "turn_tip_placements", + crate::chatwidget::tests::helpers::normalize_snapshot_paths(screens.join("\n\n")) + ); + Ok(()) +} diff --git a/codex-rs/tui/src/app_event.rs b/codex-rs/tui/src/app_event.rs index 784e763c14..8b7f24245b 100644 --- a/codex-rs/tui/src/app_event.rs +++ b/codex-rs/tui/src/app_event.rs @@ -1100,6 +1100,11 @@ pub(crate) enum AppEvent { FollowTranscript, InsertHistoryCell(Box), + /// FIFO barrier after the completed turn's history insertions. + TurnTipReady { + thread_id: ThreadId, + turn_id: String, + }, /// Move visible completed voice captions into history in one app event. CommitRealtimeTranscriptHistory, diff --git a/codex-rs/tui/src/bottom_pane/chat_composer/footer_state.rs b/codex-rs/tui/src/bottom_pane/chat_composer/footer_state.rs index c734ccad7d..1a22fd5ed2 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer/footer_state.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer/footer_state.rs @@ -65,6 +65,7 @@ pub(crate) enum CommandPopupPlacement { pub(crate) struct ComposerRenderOptions<'a> { /// Reserve a shared hint row independently of whether it currently contains a notice. pub(crate) composer_gap: Option<&'a crate::bottom_pane::ComposerGap>, + pub(crate) working_tip: Option<&'a crate::turn_tip::TurnTip>, pub(crate) warning_count: usize, pub(crate) textarea_right_reserve: u16, /// Keep configured status below the composer while hints occupy the final row. @@ -80,6 +81,7 @@ impl super::ChatComposer { use crate::empty_state_animation::ComposerState; let composer = match self.footer_mode() { + FooterMode::ComposerEmpty if self.is_in_paste_burst() => Some(ComposerState::Draft), FooterMode::ComposerEmpty => Some(ComposerState::Empty), FooterMode::ComposerHasDraft => Some(ComposerState::Draft), FooterMode::HistorySearch diff --git a/codex-rs/tui/src/bottom_pane/mod.rs b/codex-rs/tui/src/bottom_pane/mod.rs index f3382db2da..2ac4553b68 100644 --- a/codex-rs/tui/src/bottom_pane/mod.rs +++ b/codex-rs/tui/src/bottom_pane/mod.rs @@ -2240,6 +2240,12 @@ impl BottomPane { || self.hook_status_message.is_some() || !self.unified_exec_footer.is_empty(); let has_inline_previews = has_pending_thread_approvals || has_pending_input; + if !has_inline_previews + && self.status_widget().is_some() + && let Some(tip) = options.working_tip + { + flex.push(/*flex*/ 1, RenderableItem::Borrowed(tip)); + } if has_inline_previews && has_status_or_footer { flex.push(/*flex*/ 0, RenderableItem::Owned("".into())); } diff --git a/codex-rs/tui/src/chatwidget/activity_presentation.rs b/codex-rs/tui/src/chatwidget/activity_presentation.rs index 55c11ccd6d..bbafee3f0b 100644 --- a/codex-rs/tui/src/chatwidget/activity_presentation.rs +++ b/codex-rs/tui/src/chatwidget/activity_presentation.rs @@ -21,7 +21,9 @@ impl ChatWidget { let active = self.transcript.active_cell.as_deref(); let mode = self.history_render_mode(); let render_compact = |cell: &dyn HistoryCell, width| { - if mode == HistoryRenderMode::Raw { + if cell.as_any().is::() { + history_cell::fullscreen_session_lines(cell, width, /*detailed*/ false, mode) + } else if mode == HistoryRenderMode::Raw { cell.display_hyperlink_lines_for_mode(width, mode) } else { cell.compact_hyperlink_lines(width) diff --git a/codex-rs/tui/src/chatwidget/constructor.rs b/codex-rs/tui/src/chatwidget/constructor.rs index aee46661dc..dcfb96e8b3 100644 --- a/codex-rs/tui/src/chatwidget/constructor.rs +++ b/codex-rs/tui/src/chatwidget/constructor.rs @@ -63,7 +63,10 @@ impl ChatWidget { settings: fallback_default, }; - let active_cell = Some(Self::placeholder_session_header_cell(&config)); + let empty_state_animation = crate::empty_state_animation::EmptyStateAnimation::default(); + let mut header = Self::placeholder_session_header_cell(&config); + history_cell::set_session_greeting(header.as_mut(), &empty_state_animation.greeting); + let active_cell = Some(header); let current_cwd = Some(config.cwd.to_path_buf()); let effective_service_tier = crate::service_tier_resolution::effective_service_tier( @@ -94,7 +97,7 @@ impl ChatWidget { pet_http_client.clone(), ); let mut widget = Self { - empty_state_animation: Default::default(), + empty_state_animation: std::cell::RefCell::new(empty_state_animation), cyber_policy_notice: Default::default(), app_event_tx: app_event_tx.clone(), frame_requester: frame_requester.clone(), diff --git a/codex-rs/tui/src/chatwidget/rendering.rs b/codex-rs/tui/src/chatwidget/rendering.rs index 345146fadb..36c873351f 100644 --- a/codex-rs/tui/src/chatwidget/rendering.rs +++ b/codex-rs/tui/src/chatwidget/rendering.rs @@ -136,6 +136,7 @@ impl ChatWidget { /*footer*/ None, crate::bottom_pane::CommandPopupPlacement::AboveComposer, /*composer_gap*/ None, + /*working_tip*/ None, ); } @@ -201,6 +202,7 @@ impl ChatWidget { /*footer*/ None, crate::bottom_pane::CommandPopupPlacement::AboveComposer, /*composer_gap*/ None, + /*working_tip*/ None, ) .inset(Insets::tlbr( /*top*/ 1, /*left*/ 0, /*bottom*/ 0, /*right*/ 0, @@ -218,6 +220,7 @@ impl ChatWidget { footer: Option<&'a crate::bottom_pane::TranscriptFooter>, command_popup_placement: crate::bottom_pane::CommandPopupPlacement, composer_gap: Option<&'a crate::bottom_pane::ComposerGap>, + working_tip: Option<&'a crate::turn_tip::TurnTip>, ) -> RenderableItem<'a> { if self.fork_in_progress { RenderableItem::Owned(Box::new( @@ -244,6 +247,7 @@ impl ChatWidget { self.bottom_pane .as_renderable_with_options(crate::bottom_pane::ComposerRenderOptions { composer_gap, + working_tip, warning_count: self.warning_display_state.count, textarea_right_reserve: right_reserve, separate_status_line: command_popup_placement diff --git a/codex-rs/tui/src/chatwidget/rendering_tests.rs b/codex-rs/tui/src/chatwidget/rendering_tests.rs index aef12d6f6c..dc483a41b8 100644 --- a/codex-rs/tui/src/chatwidget/rendering_tests.rs +++ b/codex-rs/tui/src/chatwidget/rendering_tests.rs @@ -87,6 +87,7 @@ async fn owned_bottom_pane_preserves_draft_cursor_and_read_only_notice() { /*footer*/ None, crate::bottom_pane::CommandPopupPlacement::Overlay, /*composer_gap*/ None, + /*working_tip*/ None, ); let mut buffer = Buffer::empty(area); bottom.render(area, &mut buffer); diff --git a/codex-rs/tui/src/chatwidget/session_flow.rs b/codex-rs/tui/src/chatwidget/session_flow.rs index e170150768..3a3a68c304 100644 --- a/codex-rs/tui/src/chatwidget/session_flow.rs +++ b/codex-rs/tui/src/chatwidget/session_flow.rs @@ -203,7 +203,7 @@ impl ChatWidget { let startup_tooltip_override = self.startup_tooltip_override.take(); let show_fast_status = self .should_show_fast_status(&model_for_header, self.effective_service_tier.as_deref()); - let session_info_cell = history_cell::new_session_info( + let mut session_info_cell = history_cell::new_session_info( &self.config, &self.local_settings, &model_for_header, @@ -214,6 +214,10 @@ impl ChatWidget { self.plan_type, show_fast_status, ); + history_cell::set_session_greeting( + &mut session_info_cell, + &self.empty_state_animation.borrow().greeting, + ); self.apply_session_info_cell(session_info_cell); } else if self .transcript diff --git a/codex-rs/tui/src/chatwidget/tests/copy_export_picker_tests.rs b/codex-rs/tui/src/chatwidget/tests/copy_export_picker_tests.rs index c26fbe6849..58e4fb6257 100644 --- a/codex-rs/tui/src/chatwidget/tests/copy_export_picker_tests.rs +++ b/codex-rs/tui/src/chatwidget/tests/copy_export_picker_tests.rs @@ -5,6 +5,28 @@ use crate::app_event::TranscriptExportDestination; use crate::clipboard_copy::CopyFormat; use pretty_assertions::assert_eq; +#[tokio::test] +async fn completed_response_copy_preserves_markdown_line_endings() { + let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; + let markdown = "Hard break: \nstarts a new line.\n\n```text\ncode with trailing spaces \n```"; + replay_agent_message( + &mut chat, + "hard-break", + format!("{markdown}\n\n::git-stage{{cwd=\"/repo\"}}"), + ReplayKind::ThreadSnapshot, + ); + chat.show_copy_picker(); + chat.handle_key_event(KeyEvent::from(KeyCode::Enter)); + let copied = std::iter::from_fn(|| rx.try_recv().ok()).find_map(|event| match event { + AppEvent::CopySelection { text, format, .. } => Some((text.to_string(), format)), + _ => None, + }); + assert_eq!(copied, Some((markdown.to_string(), CopyFormat::Markdown))); + insta::assert_debug_snapshot!(crate::clipboard_html::render_markdown( + chat.transcript.last_agent_markdown.as_deref().unwrap() + ), @r#""

Hard break:
\nstarts a new line.

\n
code with trailing spaces  \n
\n""#); +} + #[tokio::test] async fn copy_export_picker_custom_keys_preserve_payloads_and_composer_draft() { let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; diff --git a/codex-rs/tui/src/chatwidget/tests/slash_commands.rs b/codex-rs/tui/src/chatwidget/tests/slash_commands.rs index 1392e14ec4..e8e5b4c459 100644 --- a/codex-rs/tui/src/chatwidget/tests/slash_commands.rs +++ b/codex-rs/tui/src/chatwidget/tests/slash_commands.rs @@ -1665,7 +1665,7 @@ async fn slash_copy_picker_preserves_completed_source_whitespace_and_hides_direc for (key, expected, label) in [ ( '1', - "Intro\n\n```powershell\nWrite-Output value\nWrite-Output done\n```\n\n> Keep **formatting**\n> > Nested quote\n> hidden\n\n>", + "Intro\n\n```powershell\nWrite-Output value \nWrite-Output done\t\n```\n\n> Keep **formatting** \n> > Nested quote\n> hidden\n\n>", "Whole response", ), ( diff --git a/codex-rs/tui/src/daemon_startup.rs b/codex-rs/tui/src/daemon_startup.rs index 9ce454fc9e..ba6de532fb 100644 --- a/codex-rs/tui/src/daemon_startup.rs +++ b/codex-rs/tui/src/daemon_startup.rs @@ -1,6 +1,7 @@ //! Local daemon launch policy. Explicit embedded launches never discover or start a daemon; //! optional attachment may fall back to embedded mode, while automatic launches -//! require a compatible shared server and a successful connection. +//! require a compatible shared server and a successful connection, except when +//! the Windows launcher forbids detaching a missing server. use super::*; use std::collections::BTreeMap; diff --git a/codex-rs/tui/src/empty_state_animation.rs b/codex-rs/tui/src/empty_state_animation.rs index 192bd230dc..a51264be5f 100644 --- a/codex-rs/tui/src/empty_state_animation.rs +++ b/codex-rs/tui/src/empty_state_animation.rs @@ -1,22 +1,30 @@ //! The blossom welcome animation for onboarding, with a full-color final pose. -//! Visible time pauses while hidden; conversation lifecycle tracking is retained for the header. +//! Visible time pauses while hidden. Fresh conversations start settled and can replay on a click. mod geometry; +mod greetings; mod lighting; mod paths; mod policy; mod renderer; mod sequence; +use std::sync::Arc; use std::sync::OnceLock; use std::time::Duration; use std::time::Instant; +use crossterm::event::MouseButton; +use crossterm::event::MouseEvent; +use crossterm::event::MouseEventKind; use ratatui::buffer::Buffer; +use ratatui::layout::Position; use ratatui::layout::Rect; use ratatui::style::Color; +use crate::motion::MotionMode; use crate::terminal_palette; +pub(crate) use greetings::Greeting; use lighting::Lighting; pub(crate) use policy::Presentation; pub(crate) use policy::is_startup_cell; @@ -25,6 +33,8 @@ use renderer::MAX_ROWS; use renderer::Renderer; pub(crate) const FRAME_INTERVAL: Duration = Duration::from_millis(/*millis*/ 50); +// The preview's first visible pose (10.8s / 7.2s), also the start of an idle-screen replay. +const SETTLED_BLOSSOM: f64 = 0.5; #[derive(Clone, Copy, PartialEq, Eq)] pub(crate) enum ComposerState { @@ -35,6 +45,9 @@ pub(crate) enum ComposerState { #[derive(Default)] pub(crate) struct EmptyStateAnimation { eligible: bool, + // Initialized once for fresh threads; never initialized for a resumed or forked thread. + // Headers retain the selection after the temporary blossom is dismissed. + pub(crate) greeting: Arc>, spin_elapsed: Duration, last_frame: Option, fade_elapsed: Duration, @@ -42,11 +55,19 @@ pub(crate) struct EmptyStateAnimation { opacity: f32, fade_from: f32, renderer: Option, + stage: Option, + replaying: bool, } impl EmptyStateAnimation { + pub(crate) fn is_eligible(&self) -> bool { + self.eligible + } + pub(crate) fn start_fresh(&mut self) { + self.cancel_replay(); self.eligible = true; + self.greeting.get_or_init(Greeting::choose); self.spin_elapsed = Duration::ZERO; self.last_frame = None; self.fade_elapsed = Duration::ZERO; @@ -54,8 +75,48 @@ impl EmptyStateAnimation { self.opacity = 1.0; } + /// Keep the provisional pose and phrase in headers already bound to the live thread. + pub(crate) fn continue_from(&mut self, source: &mut Self) { + let mut previous = std::mem::take(source); + if !previous.is_eligible() { + previous.start_fresh(); + } + if let Some(greeting) = previous.greeting.get() { + let _ = self.greeting.set(*greeting); + } + previous.greeting = Arc::clone(&self.greeting); + *self = previous; + } + pub(crate) fn dismiss(&mut self) { self.eligible = false; + self.cancel_replay(); + } + + pub(crate) fn cancel_replay(&mut self) { + self.stage = None; + self.replaying = false; + self.pause_clock(); + } + + /// Replay only on the drawn blossom; unrelated gestures keep their normal owner. + pub(crate) fn handle_mouse(&mut self, mouse: MouseEvent) -> bool { + let inside = self + .stage + .is_some_and(|stage| stage.contains(Position::new(mouse.column, mouse.row))) + && mouse.modifiers.is_empty(); + match mouse.kind { + MouseEventKind::Down(MouseButton::Left) if inside => { + self.start_fresh(); + self.spin_elapsed = + Duration::from_secs_f64(SETTLED_BLOSSOM * sequence::LOOP_SECONDS); + self.opacity = sequence::STATIC_OPACITY; + self.static_mark = Some(true); + self.replaying = true; + true + } + _ => false, + } } /// Stop visible time at the last painted frame, including when no hidden frame was drawn. @@ -126,6 +187,55 @@ impl EmptyStateAnimation { + (self.opacity - self.fade_from) * sequence::progress(self.fade_elapsed, sequence::STATIC_FADE) as f32; } + self.paint_frame(area, buffer, phase, self.opacity); + (!finished && (!static_mark || settling)).then_some(FRAME_INTERVAL) + } + + /// Draw only in space the caller has cleared and owns. The centered blossom returns + /// on clear, without restarting or scheduling animation. + pub(crate) fn render_first_screen( + &mut self, + available: Rect, + buffer: &mut Buffer, + composer: Option, + motion: MotionMode, + ) -> Option { + const STAGE_ROWS: u16 = 21; + const MIN_STAGE_ROWS: u16 = 14; + let screen = buffer.area; + let width = screen.width.saturating_sub(/*rhs*/ 4).min(MAX_COLUMNS); + let height = width * STAGE_ROWS / MAX_COLUMNS; + if motion == MotionMode::Reduced + || composer != Some(ComposerState::Empty) + || height < MIN_STAGE_ROWS + || height > screen.height + { + self.cancel_replay(); + return None; + } + let stage = Rect::new( + screen.x + (screen.width - width) / 2, + screen.y + (screen.height - height) / 2, + width, + height, + ); + if stage.intersection(available) != stage { + self.cancel_replay(); + return None; + } + self.stage = Some(stage); + if self.replaying { + if let Some(delay) = self.render_in(stage, buffer, Presentation::Animated) { + return Some(delay); + } + // Paint the idle pose over the final full-color frame in the same update. + self.replaying = false; + } + self.paint_frame(stage, buffer, SETTLED_BLOSSOM, sequence::STATIC_OPACITY); + None + } + + fn paint_frame(&mut self, area: Rect, buffer: &mut Buffer, phase: f64, opacity: f32) { let background = terminal_palette::default_bg(); let color_level = if background.is_some() { terminal_palette::effective_stdout_color_level() @@ -150,7 +260,7 @@ impl EmptyStateAnimation { area.y + i as u16 / area.width, )]; target.set_char(char::from_u32(0x2800 + u32::from(cell.dots)).unwrap_or(' ')); - let color = crate::color::blend((r, g, b), background, self.opacity); + let color = crate::color::blend((r, g, b), background, opacity); let color = if color_level == terminal_palette::StdoutColorLevel::Ansi256 { // Four bits per channel bound the cache and avoid palette searches each frame. static COLORS: [OnceLock; 4096] = [const { OnceLock::new() }; 4096]; @@ -167,7 +277,7 @@ impl EmptyStateAnimation { }; target.set_fg(color); // Default-color terminals can only step between normal and dim intensity. - if self.opacity < 0.5 + if opacity < 0.5 && matches!( color_level, terminal_palette::StdoutColorLevel::Ansi16 @@ -177,7 +287,6 @@ impl EmptyStateAnimation { target.set_style(target.style().dim()); } } - (!finished && (!static_mark || settling)).then_some(FRAME_INTERVAL) } } diff --git a/codex-rs/tui/src/empty_state_animation/greetings.rs b/codex-rs/tui/src/empty_state_animation/greetings.rs new file mode 100644 index 0000000000..6dce8f65bd --- /dev/null +++ b/codex-rs/tui/src/empty_state_animation/greetings.rs @@ -0,0 +1,108 @@ +//! Startup phrases retained from the approved greeting list (PR #10248). +//! One selection is shared by the provisional, live, and committed session headers. + +use rand::Rng; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Greeting { + pub(crate) phrase: &'static str, +} + +impl Greeting { + pub(super) fn choose() -> Self { + Self { + phrase: GREETINGS[rand::rng().random_range(0..GREETINGS.len())], + } + } +} + +const GREETINGS: &[&str] = &[ + "Whoa, fancy meeting you here!", + "Look who’s at the keyboard.", + "Hello, you. Got an idea?", + "Nice to see you in these parts.", + "Pull up a prompt.", + "What brings you to this corner of the terminal?", + "Hey there. Big plans or little fixes?", + "What are we getting into today?", + "Got something you want to try?", + "What’s today’s little adventure?", + "Anything interesting on the docket?", + "Take your time. The cursor can wait.", + "A half-formed idea will do.", + "Come on in. There’s room for an idea.", + "You, me, and a blinking cursor.", + "It takes two to tango. What’s our first step?", + "You bring the idea. I’ll bring the brackets.", + "Your move, teammate.", + "What are we cooking up?", + "Shall we turn “what if” into something?", + "What’s the first thing on our napkin sketch?", + "Bring your unfinished thoughts.", + "You set the direction. We’ll work out the steps.", + "Ah, the terminal. A classic meeting spot.", + "Nice place you’ve got here. Very monospace.", + "Welcome to our little rectangle of possibility.", + "A cursor blinks. The plot thickens.", + "The prompt is yours.", + "Fancy a little quality terminal time?", + "How’s life between the brackets?", + "Shall we give this cursor a purpose?", + "A fresh prompt. An open question.", + "Your keyboard has entered the chat.", + "Hello, world. Hello, you.", + "Welcome to the blinking edge of possibility.", + "Any loose ends? Semicolons count.", + "Shall we make this terminal earn its keep?", + "Got an itch to fix a thing?", + "Show me the bit that’s being weird.", + "Greetings, fellow tinkerer.", + "Well, well, well. An idea approaches.", + "What’s today’s side quest?", + "Is this a plan day or a poke-around day?", + "Practical, peculiar, or a little of both?", + "Rough sketches welcome.", + "Shall we see where this goes?", + "All right. What have you got?", + "Back for another round?", + "Same terminal, new possibilities.", + "Welcome back. Familiar territory or a fresh adventure?", + "Follow the white cursor.", + "Welcome to the command line, Neo.", + "A glitch in the Matrix, or just a missing semicolon?", + "How deep does this codebase go?", + "Speak, friend, and enter a prompt.", + "One prompt to begin the journey.", + "May the source be with you.", + "These might be the bugs you’re looking for.", + "A new prompt awakens.", + "Forty-two is an answer. What’s the question?", + "It’s dangerous to code alone. Take a prompt.", + "The code must flow.", + "You rang? Metaphorically. You typed.", + "Hello again, carbon-based collaborator.", + "This looks like the start of a perfectly reasonable rabbit hole.", + "Shall we turn “huh?” into “aha!”?", + "Well, this terminal just got interesting.", + "The source is strong with this one.", + "There’s a perfectly good prompt with your name on it.", + "Here for a quick fix or the extended edition?", + "What’s the latest from your side of the keyboard?", + "Got a minute and a mildly unreasonable idea?", + "A hunch is a perfectly respectable starting point.", + "Hello again. What’s the plot this time?", + "Shall we make a little something out of nothing?", + "Welcome to the neighborhood. Lots of characters here.", + "Nice terminal. Does it come in widescreen?", + "Your cursor called. It wants a plot.", + "Shall we put some verbs after that cursor?", + "Welcome. There’s no dress code, just code.", + "This terminal has excellent conversational potential.", + "Got an idea that won’t stay on the napkin?", + "What are we building in this episode?", + "Bring a question. Bonus points if it’s a weird one.", + "What are we poking with a metaphorical stick?", + "Shall we make the thing that makes the other thing easier?", + "Welcome to the part where the idea gets interesting.", + "A long time ago, in a directory not so far away…", +]; diff --git a/codex-rs/tui/src/empty_state_animation/policy.rs b/codex-rs/tui/src/empty_state_animation/policy.rs index 63b3c9ae9c..2a02496079 100644 --- a/codex-rs/tui/src/empty_state_animation/policy.rs +++ b/codex-rs/tui/src/empty_state_animation/policy.rs @@ -1,10 +1,8 @@ //! Positive eligibility for the fresh-conversation decoration. //! Unknown history cell types are activity, even when they render no visible text. -use super::ComposerState; use crate::history_cell; use crate::history_cell::HistoryCell; -use crate::motion::MotionMode; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum Presentation { @@ -13,22 +11,6 @@ pub(crate) enum Presentation { Faded, } -impl Presentation { - /// Only an explicitly available ordinary composer may display a fresh-thread logo. - pub(crate) fn for_composer( - composer: Option, - motion: MotionMode, - focused: bool, - ) -> Self { - match (composer, motion, focused) { - (None, _, _) | (_, MotionMode::Reduced, _) => Self::Hidden, - (Some(ComposerState::Empty), MotionMode::Animated, true) => Self::Animated, - (Some(ComposerState::Empty), MotionMode::Animated, false) - | (Some(ComposerState::Draft), MotionMode::Animated, _) => Self::Faded, - } - } -} - /// Startup metadata is the entire allowlist; new content types opt out by default. pub(crate) fn is_startup_cell(cell: &dyn HistoryCell) -> bool { cell.as_any().is::() diff --git a/codex-rs/tui/src/empty_state_animation_tests.rs b/codex-rs/tui/src/empty_state_animation_tests.rs index cfa12959ba..2769ea9ba0 100644 --- a/codex-rs/tui/src/empty_state_animation_tests.rs +++ b/codex-rs/tui/src/empty_state_animation_tests.rs @@ -1,13 +1,159 @@ //! Logo visibility, theme contrast, placement, and redraw lifecycle tests. use super::*; +use crossterm::event::KeyModifiers; use pretty_assertions::assert_eq; -impl EmptyStateAnimation { - // App integration tests inspect lifecycle eligibility without advancing the render clock. - pub(crate) fn is_eligible_for_test(&self) -> bool { - self.eligible +#[test] +fn first_screen_stage_ignores_notices_and_hides_instead_of_shrinking() { + let mut animation = EmptyStateAnimation::default(); + animation.start_fresh(); + let screen = Rect::new( + /*x*/ 7, /*y*/ 3, /*width*/ 80, /*height*/ 44, + ); + let mut buffer = Buffer::empty(screen); + for header_rows in [5, 7, 11] { + buffer.reset(); + let free = Rect::new( + screen.x, + screen.y + header_rows, + screen.width, + screen.height - header_rows - 3, + ); + assert_eq!( + animation.render_first_screen( + free, + &mut buffer, + Some(ComposerState::Empty), + MotionMode::Animated + ), + None + ); + assert_eq!( + animation.stage, + Some(Rect::new( + /*x*/ 17, /*y*/ 14, /*width*/ 60, /*height*/ 21 + )) + ); } + // Content which reaches the center must win; it must not move the stage down. + let free = Rect::new(screen.x, /*y*/ 20, screen.width, /*height*/ 24); + animation.render_first_screen( + free, + &mut buffer, + Some(ComposerState::Empty), + MotionMode::Animated, + ); + assert_eq!(animation.stage, None); + // Both sides of the minimum size, and a terminal that is too short for the full logo. + for (width, height, expected) in [(44, 36, true), (43, 36, false), (80, 20, false)] { + let screen = Rect::new(/*x*/ 7, /*y*/ 3, width, height); + let mut buffer = Buffer::empty(screen); + animation.render_first_screen( + screen, + &mut buffer, + Some(ComposerState::Empty), + MotionMode::Animated, + ); + assert_eq!(animation.stage.is_some(), expected); + } +} + +#[test] +fn first_screen_single_click_replays_the_visible_blossom() { + let mut animation = EmptyStateAnimation::default(); + animation.start_fresh(); + let screen = Rect::new( + /*x*/ 0, /*y*/ 0, /*width*/ 80, /*height*/ 44, + ); + let mut buffer = Buffer::empty(screen); + let click = MouseEvent { + kind: MouseEventKind::Down(MouseButton::Left), + column: 40, + row: 22, + modifiers: KeyModifiers::NONE, + }; + let draw = |animation: &mut EmptyStateAnimation, buffer: &mut Buffer, composer| { + buffer.reset(); + animation.render_first_screen(screen, buffer, composer, MotionMode::Animated) + }; + assert_eq!( + draw(&mut animation, &mut buffer, Some(ComposerState::Empty)), + None + ); + let static_frame = buffer.clone(); + for other in [ + MouseEvent { + column: 0, + row: 0, + ..click + }, + MouseEvent { + modifiers: KeyModifiers::CONTROL, + ..click + }, + MouseEvent { + kind: MouseEventKind::Down(MouseButton::Right), + ..click + }, + ] { + assert!(!animation.handle_mouse(other)); + } + assert_eq!( + draw(&mut animation, &mut buffer, Some(ComposerState::Empty)), + None + ); + assert_eq!(buffer, static_frame); + assert!(animation.handle_mouse(click)); + // Release belongs to the transcript if it started a selection outside the logo. + assert!(!animation.handle_mouse(MouseEvent { + kind: MouseEventKind::Up(MouseButton::Left), + ..click + })); + assert_eq!( + draw(&mut animation, &mut buffer, Some(ComposerState::Empty)), + Some(FRAME_INTERVAL) + ); + assert_eq!(buffer, static_frame); + let started = animation.last_frame.unwrap(); + let stage = animation.stage.unwrap(); + buffer.reset(); + assert_eq!( + animation.render_in_at( + stage, + &mut buffer, + Presentation::Animated, + started + sequence::STATIC_FADE, + ), + Some(FRAME_INTERVAL) + ); + assert_ne!(buffer, static_frame); + assert!(animation.handle_mouse(click)); + assert_eq!( + draw(&mut animation, &mut buffer, Some(ComposerState::Empty)), + Some(FRAME_INTERVAL) + ); + assert_eq!(buffer, static_frame); + assert_eq!( + draw(&mut animation, &mut buffer, Some(ComposerState::Draft)), + None + ); + assert!(!animation.handle_mouse(click)); + assert_eq!( + draw(&mut animation, &mut buffer, Some(ComposerState::Empty)), + None + ); + assert_eq!(buffer, static_frame); + // Disabling motion removes both the logo and its click target. + buffer.reset(); + animation.render_first_screen( + screen, + &mut buffer, + Some(ComposerState::Empty), + MotionMode::Reduced, + ); + assert_eq!(buffer, Buffer::empty(screen)); + assert!(!animation.handle_mouse(click)); } #[test] diff --git a/codex-rs/tui/src/git_action_directives.rs b/codex-rs/tui/src/git_action_directives.rs index 7477d7053b..2d86284cbc 100644 --- a/codex-rs/tui/src/git_action_directives.rs +++ b/codex-rs/tui/src/git_action_directives.rs @@ -1,4 +1,6 @@ //! Codex App directives embedded in assistant markdown. +//! +//! Preserve whitespace on unchanged lines: Markdown hard breaks and code can depend on it. use crate::assistant_directives::AssistantDirective; use crate::assistant_directives::QuoteEscaping; @@ -67,12 +69,16 @@ pub(crate) fn parse_assistant_markdown(markdown: &str, cwd: &Path) -> ParsedAssi git_actions.push(action); } } - visible_lines.push(visible_line.trim_end().to_string()); + visible_lines.push(if visible_line == line { + visible_line + } else { + visible_line.trim_end().to_string() + }); } while visible_lines .last() - .is_some_and(std::string::String::is_empty) + .is_some_and(|line| line.trim().is_empty()) { visible_lines.pop(); } diff --git a/codex-rs/tui/src/history_cell/session.rs b/codex-rs/tui/src/history_cell/session.rs index 3d9c174856..e749c027fc 100644 --- a/codex-rs/tui/src/history_cell/session.rs +++ b/codex-rs/tui/src/history_cell/session.rs @@ -1,6 +1,10 @@ //! Session headers, onboarding guidance, and transcript cards. +use std::sync::Arc; +use std::sync::OnceLock; + use super::*; +use crate::empty_state_animation::Greeting; use crate::line_truncation::line_width; use crate::line_truncation::truncate_line_with_ellipsis_if_overflow; use crate::style::accent_color; @@ -121,6 +125,46 @@ impl HistoryCell for SessionNoticeCell { #[derive(Debug)] pub struct SessionInfoCell(CompositeHistoryCell); +/// Bind provisional and configured banners to the thread's chosen greeting. +pub(crate) fn set_session_greeting(cell: &mut dyn HistoryCell, greeting: &Arc>) { + if let Some(header) = cell.as_any_mut().downcast_mut::() { + header.greeting = Arc::clone(greeting); + } else if let Some(info) = cell.as_any_mut().downcast_mut::() { + for part in &mut info.0.parts { + set_session_greeting(part.as_mut(), greeting); + } + } +} + +/// Fullscreen transcript presentation omits tips; scrollback retains the original cells. +pub(crate) fn fullscreen_session_lines( + cell: &dyn HistoryCell, + width: u16, + detailed: bool, + mode: HistoryRenderMode, +) -> Vec { + if let Some(info) = cell.as_any().downcast_ref::() { + let mut lines = Vec::new(); + for part in &info.0.parts { + if part.as_any().is::() { + continue; + } + let part_lines = fullscreen_session_lines(part.as_ref(), width, detailed, mode); + if !part_lines.is_empty() { + if !lines.is_empty() { + lines.push(HyperlinkLine::from("")); + } + lines.extend(part_lines); + } + } + lines + } else if detailed || mode == HistoryRenderMode::Rich { + cell.retained_hyperlink_lines(width, detailed) + } else { + cell.display_hyperlink_lines_for_mode(width, mode) + } +} + impl HistoryCell for SessionInfoCell { fn compact_hyperlink_lines(&self, width: u16) -> Vec { self.0.compact_hyperlink_lines(width) @@ -269,6 +313,7 @@ pub(crate) struct SessionHeaderHistoryCell { show_fast_status: bool, directory: PathBuf, yolo_mode: bool, + greeting: Arc>, } impl SessionHeaderHistoryCell { @@ -305,6 +350,7 @@ impl SessionHeaderHistoryCell { show_fast_status, directory, yolo_mode: false, + greeting: Default::default(), } } @@ -348,7 +394,50 @@ impl SessionHeaderHistoryCell { } impl HistoryCell for SessionHeaderHistoryCell { + fn compact_hyperlink_lines(&self, width: u16) -> Vec { + if self.greeting.get().is_none() { + return self.display_hyperlink_lines(width); + } + let width = usize::from(width); + let mut lines = vec![ + Line::default(), + Line::from(vec![ + " ".into(), + ">_ ".fg(accent_color()), + "OpenAI Codex".bold(), + format!(" (v{})", self.version).dim(), + ]), + Line::from(vec![ + " ".into(), + self.format_directory(Some(width.saturating_sub(/*rhs*/ 5))) + .dim(), + ]), + ]; + if self.yolo_mode { + lines.push(Line::from(vec![ + " permissions: ".dim(), + "YOLO mode".magenta().bold(), + ])); + } + if let Some(greeting) = self.greeting.get() { + // The tip/help that follows has its own normal composite separator. + lines.extend([ + Line::default(), + Line::from(vec![" ".into(), greeting.phrase.fg(accent_color())]), + ]); + } + plain_hyperlink_lines( + lines + .into_iter() + .map(|line| truncate_line_with_ellipsis_if_overflow(line, width)) + .collect(), + ) + } + fn display_lines(&self, width: u16) -> Vec> { + if self.greeting.get().is_some() { + return visible_lines(self.compact_hyperlink_lines(width)); + } let Some(inner_width) = card_inner_width(width, SESSION_HEADER_MAX_INNER_WIDTH) else { return Vec::new(); }; @@ -428,6 +517,12 @@ impl HistoryCell for SessionHeaderHistoryCell { } fn raw_lines(&self) -> Vec> { + if self.greeting.get().is_some() { + return visible_lines(self.compact_hyperlink_lines(u16::MAX)) + .into_iter() + .map(|line| Line::from(line.to_string())) + .collect(); + } let mut lines = vec![ Line::from(format!("OpenAI Codex (v{})", self.version)), Line::from(format!( diff --git a/codex-rs/tui/src/lib.rs b/codex-rs/tui/src/lib.rs index a32dee4e0e..a6a91b0b9f 100644 --- a/codex-rs/tui/src/lib.rs +++ b/codex-rs/tui/src/lib.rs @@ -230,6 +230,7 @@ mod transcript_mode; mod transcript_reflow; mod transcript_view; mod tui; +mod turn_tip; mod ui_consts; mod unarchive_prompt; pub(crate) mod update_action; @@ -1312,6 +1313,7 @@ async fn run_ratatui_app( show_trust_screen: should_show_trust_screen_flag, remote_project_trust: None, login_status, + app_server_target: app_server_target.clone(), app_server_request_handle: app_server .as_ref() .map(AppServerSession::request_handle), diff --git a/codex-rs/tui/src/local_settings.rs b/codex-rs/tui/src/local_settings.rs index d8ac496aaa..4a470de9b4 100644 --- a/codex-rs/tui/src/local_settings.rs +++ b/codex-rs/tui/src/local_settings.rs @@ -14,7 +14,6 @@ use codex_config::types::CopyOnSelect; use codex_config::types::History; use codex_config::types::Notice; use codex_config::types::Tui; -use codex_terminal_detection::Multiplexer; use codex_terminal_detection::TerminalInfo; use codex_terminal_detection::TerminalName; use codex_utils_absolute_path::AbsolutePathBuf; @@ -129,22 +128,47 @@ impl LocalSettings { settings } - /// Prefer explicit overrides; tmux/Zellij always default to copying on release. - /// Direct macOS terminals default on except Ghostty/Kitty, which forward Cmd-C. + /// Copy on release unless a direct terminal is known to forward its default copy shortcut. + /// Multiplexers, unknown terminals and Ghostty without a recognized version default to copying. pub(crate) fn copy_on_select(&self, terminal: &TerminalInfo) -> bool { match self.tui.copy_on_select { CopyOnSelect::Always => true, CopyOnSelect::Never => false, - CopyOnSelect::Auto => match terminal.multiplexer { - Some(Multiplexer::Tmux { .. } | Multiplexer::Zellij { .. }) => true, - None if cfg!(target_os = "macos") => { - !matches!(terminal.name, TerminalName::Ghostty | TerminalName::Kitty) - } - None => matches!( - terminal.name, - TerminalName::Iterm2 | TerminalName::AppleTerminal - ), - }, + CopyOnSelect::Auto => { + terminal.multiplexer.is_some() + || match terminal.name { + // Since 1.2, both Ghostty's Cmd-C and Ctrl-Shift-C bindings are + // "performable": they forward the key if Ghostty has no selection. + TerminalName::Ghostty => !terminal + .version + .as_deref() + .and_then(|version| semver::Version::parse(version).ok()) + .is_some_and(|version| { + version + >= semver::Version::new( + /*major*/ 1, /*minor*/ 2, /*patch*/ 0, + ) + }), + // Kitty's Cmd-C uses copy_or_noop. Its Ctrl-Shift-C consumes the key. + TerminalName::Kitty => !cfg!(target_os = "macos"), + // Windows Terminal's Copy action forwards its key when unselected, + // including when the CLI runs in WSL. + TerminalName::WindowsTerminal => false, + // VS Code gates Copy on native selection. Only Windows' default + // (plain Ctrl-C) is also forwarded by the legacy xterm.js encoder. + TerminalName::VsCode => !cfg!(target_os = "windows"), + TerminalName::AppleTerminal + | TerminalName::Iterm2 + | TerminalName::WarpTerminal + | TerminalName::WezTerm + | TerminalName::Alacritty + | TerminalName::Konsole + | TerminalName::GnomeTerminal + | TerminalName::Vte + | TerminalName::Dumb + | TerminalName::Unknown => true, + } + } } } diff --git a/codex-rs/tui/src/local_settings_tests.rs b/codex-rs/tui/src/local_settings_tests.rs index a5d50e3b96..6afad2d4c4 100644 --- a/codex-rs/tui/src/local_settings_tests.rs +++ b/codex-rs/tui/src/local_settings_tests.rs @@ -231,28 +231,55 @@ async fn copy_on_select_respects_terminal_defaults_and_config_overrides() -> any (config.tui_copy_on_select, local.tui.copy_on_select), (expected, expected), ); - for (name, multiplexer, default_enabled) in [ - (TerminalName::Iterm2, None, true), - (TerminalName::AppleTerminal, None, true), - (TerminalName::Ghostty, None, false), - (TerminalName::Kitty, None, false), - (TerminalName::Unknown, None, cfg!(target_os = "macos")), + for (name, version, multiplexer, default_enabled) in [ + (TerminalName::Iterm2, None, None, true), + (TerminalName::AppleTerminal, None, None, true), + (TerminalName::Ghostty, Some("1.2.0"), None, false), + (TerminalName::Ghostty, Some("1.3.0"), None, false), + (TerminalName::Ghostty, Some("1.1.3"), None, true), + (TerminalName::Ghostty, Some("1.2.0-dev"), None, true), + (TerminalName::Ghostty, Some("invalid"), None, true), + (TerminalName::Ghostty, None, None, true), + (TerminalName::Kitty, None, None, !cfg!(target_os = "macos")), + (TerminalName::WindowsTerminal, None, None, false), + ( + TerminalName::VsCode, + None, + None, + !cfg!(target_os = "windows"), + ), + (TerminalName::Alacritty, None, None, true), + (TerminalName::GnomeTerminal, None, None, true), + (TerminalName::Konsole, None, None, true), + (TerminalName::Vte, None, None, true), + (TerminalName::WarpTerminal, None, None, true), + (TerminalName::WezTerm, None, None, true), + (TerminalName::Dumb, None, None, true), + (TerminalName::Unknown, None, None, true), ( TerminalName::Ghostty, + Some("1.3.0"), Some(Multiplexer::Tmux { version: None }), true, ), ( TerminalName::Kitty, + None, Some(Multiplexer::Zellij { version: None }), true, ), + ( + TerminalName::WindowsTerminal, + None, + Some(Multiplexer::Tmux { version: None }), + true, + ), ] { let terminal = TerminalInfo { name, multiplexer, term_program: None, - version: None, + version: version.map(str::to_owned), term: None, }; assert_eq!( diff --git a/codex-rs/tui/src/markdown_copy.rs b/codex-rs/tui/src/markdown_copy.rs index 62b8b81acc..f70d7639d9 100644 --- a/codex-rs/tui/src/markdown_copy.rs +++ b/codex-rs/tui/src/markdown_copy.rs @@ -14,6 +14,8 @@ use pulldown_cmark::Tag; use crate::clipboard_copy::CopyFormat; use crate::terminal_hyperlinks::LogicalLineSource; +pub(crate) mod table; + // Bound retained inline stacks and container prefixes independently of parser nesting. pub(crate) const MAX_COPY_DEPTH: usize = 64; @@ -56,6 +58,8 @@ pub(crate) struct CopyLine { /// Restore the containing item when a multiline selection starts in its later paragraph. pub(crate) item_prefix: String, pub(crate) code: bool, + pub(crate) table: Option, + table_cell: bool, pub(crate) rule: bool, pub(crate) heading: usize, pub(crate) hard_break: bool, @@ -117,7 +121,12 @@ impl CopyLine { match mark { Some(Inline::Code) => { let content = &text[start..end]; - let fence = fence(content, /*minimum*/ 1); + let content = if self.table_cell { + content.replace('|', "\\|") + } else { + content.to_owned() + }; + let fence = fence(&content, /*minimum*/ 1); let padding = if content.starts_with(['`', ' ']) || content.ends_with(['`', ' ']) { if content.chars().all(|ch| ch == ' ') { @@ -151,6 +160,7 @@ impl CopyLine { .replace('&', "&") .replace('<', "%3C") .replace('>', "%3E") + .replace('|', "%7C") .replace('\n', "%0A") .replace('\r', "%0D"); append_inline(&mut out, &format!("[{trimmed}](<{destination}>)")); @@ -288,7 +298,47 @@ pub(crate) fn selection(lines: &[SelectedLine], plain: &str) -> (String, CopyFor first = false; continue; } - if line.source.copy_as_prose { + if let Some(table) = line + .source + .copy + .as_ref() + .and_then(|copy| copy.table.as_ref()) + { + let mut selected = vec![line]; + while let Some(next) = lines.peek() + && next + .source + .copy + .as_ref() + .and_then(|copy| copy.table.as_ref()) + .is_some_and(|next| Arc::ptr_eq(&next.table, &table.table)) + { + selected.extend(lines.next()); + } + let body = table::render(&selected, table); + let continuation = line + .source + .copy + .as_ref() + .map_or("", |copy| copy.continuation.as_str()); + let continuation = dedent(continuation, indentation.unwrap_or(/*default*/ 0)); + for (index, row) in body.lines().enumerate() { + if index > 0 { + out.push('\n'); + out.push_str(&continuation); + } else { + out.push_str(&prefix); + } + out.push_str(row); + } + if lines + .peek() + .is_some_and(|next| next.separator == "\n" && !next.range.is_empty()) + { + out.push('\n'); + out.push_str(continuation.trim_end()); + } + } else if line.source.copy_as_prose { let text = &line.source.text[line.range.clone()]; push_prose_fragment(&mut out, &escape(text)); } else if let Some(copy) = &line.source.copy diff --git a/codex-rs/tui/src/markdown_copy/table.rs b/codex-rs/tui/src/markdown_copy/table.rs new file mode 100644 index 0000000000..63dfc8a329 --- /dev/null +++ b/codex-rs/tui/src/markdown_copy/table.rs @@ -0,0 +1,209 @@ +//! Copy selected table cells independently of grid padding, wrapping, and record labels. +//! +//! Each visual fragment refers to an original cell line. Only selected fragments are +//! serialized; repeated record labels and whitespace removed by wrapping are reconciled +//! by their shared source identity. Unselected cells never supply hidden text. + +use super::CopyLine; +use super::SelectedLine; +use crate::terminal_hyperlinks::HyperlinkLine; +use crate::terminal_hyperlinks::LogicalLineSource; +use std::collections::BTreeMap; +use std::ops::Range; +use std::sync::Arc; + +#[cfg(test)] +#[path = "table_tests.rs"] +mod tests; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct TableLine { + pub(crate) table: Arc<[&'static str]>, + fragments: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +struct Fragment { + output: Range, + row: usize, + column: usize, + source: LogicalLineSource, +} + +impl TableLine { + pub(crate) fn empty(table: &Arc<[&'static str]>) -> Self { + Self { + table: Arc::clone(table), + fragments: Vec::new(), + } + } +} + +pub(crate) fn annotate_cell( + lines: &mut [HyperlinkLine], + copies: Vec, + table: &Arc<[&'static str]>, + row: usize, + column: usize, +) { + for (line, copy) in lines.iter_mut().zip(copies) { + let mut source = LogicalLineSource::from_line(&line.line); + source.copy = Some(Arc::new(copy)); + attach( + line, + Some(TableLine { + table: Arc::clone(table), + fragments: vec![Fragment { + output: source.range.clone(), + row, + column, + source, + }], + }), + ); + } +} + +pub(crate) fn attach(line: &mut HyperlinkLine, table: Option) { + if let Some(table) = table { + let mut source = LogicalLineSource::from_line(&line.line); + source.copy = Some(Arc::new(CopyLine { + table: Some(table), + ..Default::default() + })); + line.source = Some(source); + } +} + +/// Project a displayed cell fragment into the byte coordinates of its composed row. +pub(crate) fn append(output: &mut Option, source: &LogicalLineSource, offset: usize) { + let Some(table) = source.copy.as_ref().and_then(|copy| copy.table.as_ref()) else { + return; + }; + let output = output.get_or_insert_with(|| TableLine::empty(&table.table)); + for fragment in &table.fragments { + let start = source.range.start.max(fragment.output.start); + let end = source.range.end.min(fragment.output.end); + if start > end || start == end && !fragment.source.text.is_empty() { + continue; + } + let mut cell = fragment.source.clone(); + cell.range = cell.range.start + start - fragment.output.start + ..cell.range.start + end - fragment.output.start; + output.fragments.push(Fragment { + output: offset + source.prefix_bytes + start - source.range.start + ..offset + source.prefix_bytes + end - source.range.start, + row: fragment.row, + column: fragment.column, + source: cell, + }); + } +} + +pub(super) fn render(lines: &[&SelectedLine], table: &TableLine) -> String { + let mut cells: BTreeMap<(usize, usize), Vec> = BTreeMap::new(); + for line in lines { + let Some(copy) = line + .source + .copy + .as_ref() + .and_then(|copy| copy.table.as_ref()) + else { + continue; + }; + for fragment in ©.fragments { + // A selected blank row may have lost all display padding during wrapping. + let blank = line.source.range.is_empty() + && line.source.text.trim().is_empty() + && fragment.source.text.trim().is_empty(); + let start = line.range.start.max(fragment.output.start); + let end = line.range.end.min(fragment.output.end); + if !blank && (start > end || start == end && !fragment.source.text.is_empty()) { + continue; + } + let mut source = fragment.source.clone(); + if !blank { + source.range = source.range.start + start - fragment.output.start + ..source.range.start + end - fragment.output.start; + } + let parts = cells.entry((fragment.row, fragment.column)).or_default(); + let mut insert_at = parts.len(); + while let Some(index) = parts.iter().position(|previous| { + Arc::ptr_eq(&previous.text, &source.text) + && (previous.range.start <= source.range.end + && source.range.start <= previous.range.end + || previous.text[previous.range.end.min(source.range.end) + ..previous.range.start.max(source.range.start)] + .trim() + .is_empty()) + }) { + let previous = parts.remove(index); + insert_at = insert_at.min(index); + source.range.start = previous.range.start.min(source.range.start); + source.range.end = previous.range.end.max(source.range.end); + } + parts.insert(insert_at.min(parts.len()), source); + } + } + let includes_separator = lines.iter().any(|line| { + !line.range.is_empty() + && line + .source + .copy + .as_ref() + .and_then(|copy| copy.table.as_ref()) + .is_some_and(|table| table.fragments.is_empty()) + }); + let standalone = cells.len() == 1 && !includes_separator; + let cells: BTreeMap<_, _> = cells + .into_iter() + .map(|(key, parts)| { + let text = parts + .into_iter() + .map(|source| { + source.copy.as_ref().map_or_else( + || super::escape(&source.text[source.range.clone()]), + |copy| { + let mut copy = (**copy).clone(); + copy.table_cell = !standalone; + copy.render(&source.text, source.range.clone(), /*depth*/ 0) + }, + ) + }) + .collect::>() + .join(" "); + (key, text) + }) + .collect(); + if standalone { + return cells.into_values().next().unwrap_or_default(); + } + if cells.is_empty() { + return lines + .iter() + .map(|line| super::escape(&line.source.text[line.range.clone()])) + .collect::>() + .join("\n"); + } + let mut rows: BTreeMap> = BTreeMap::new(); + rows.insert(/*key*/ 0, vec![""; table.table.len()]); + for ((row, column), text) in &cells { + rows.entry(*row) + .or_insert_with(|| vec![""; table.table.len()])[*column] = text; + } + let mut out = String::new(); + for (row, values) in rows { + if !out.is_empty() { + out.push('\n'); + } + out.push_str(&format!("| {} |", values.join(" | "))); + if row == 0 { + out.push_str("\n|"); + for alignment in table.table.iter() { + out.push_str(alignment); + out.push('|'); + } + } + } + out +} diff --git a/codex-rs/tui/src/markdown_copy/table_tests.rs b/codex-rs/tui/src/markdown_copy/table_tests.rs new file mode 100644 index 0000000000..de29148762 --- /dev/null +++ b/codex-rs/tui/src/markdown_copy/table_tests.rs @@ -0,0 +1,68 @@ +//! Exercise retained cell coordinates, inline styles, and byte ranges through each layout. + +use super::*; +use pretty_assertions::assert_eq; +use std::collections::BTreeMap; + +#[test] +fn table_layouts_preserve_cell_fragments() { + for (markdown, expected) in [ + ( + "| **alpha head** | B |\n|---|---|\n| **one two three four** | `value` |\n| | last |", + BTreeMap::from([ + ((0, 0), "**alpha head**"), + ((0, 1), "B"), + ((1, 0), "**one two three four**"), + ((1, 1), "`value`"), + ((2, 0), ""), + ((2, 1), "last"), + ]), + ), + ( + "| **alpha head** | `a\\|b` |\n|---|---|", + BTreeMap::from([((0, 0), "**alpha head**"), ((0, 1), "`a|b`")]), + ), + ] { + for width in [4, 12, 80] { + let lines = crate::markdown_render::render_markdown_lines_with_width_and_cwd( + markdown, + Some(width), + /*cwd*/ None, + ); + let mut seen = BTreeMap::new(); + let mut identity = None; + for source in lines.into_iter().filter_map(|line| line.source) { + let Some(table) = source.copy.as_ref().and_then(|copy| copy.table.as_ref()) else { + continue; + }; + let identity = identity.get_or_insert_with(|| Arc::clone(&table.table)); + assert!(Arc::ptr_eq(identity, &table.table)); + for fragment in &table.fragments { + let cell = &fragment.source; + assert_eq!( + &source.text[fragment.output.clone()], + &cell.text[cell.range.clone()], + "width {width}, cell ({}, {})", + fragment.row, + fragment.column, + ); + let markdown = cell.copy.as_ref().unwrap().render( + &cell.text, + 0..cell.text.len(), + /*depth*/ 0, + ); + let key = (fragment.row, fragment.column); + assert_eq!(markdown, expected[&key]); + seen.insert(key, markdown); + } + } + assert_eq!( + seen, + expected + .iter() + .map(|(key, value)| (*key, value.to_string())) + .collect() + ); + } + } +} diff --git a/codex-rs/tui/src/markdown_render.rs b/codex-rs/tui/src/markdown_render.rs index d15b95f31a..a7109210a2 100644 --- a/codex-rs/tui/src/markdown_render.rs +++ b/codex-rs/tui/src/markdown_render.rs @@ -193,6 +193,7 @@ impl IndentContext { #[derive(Clone, Debug, Default)] struct TableCell { lines: Vec, + copies: Vec, } // TableCell mutators inlined — called per-span during table event parsing. @@ -201,11 +202,27 @@ impl TableCell { fn ensure_line(&mut self) { if self.lines.is_empty() { self.lines.push(HyperlinkLine::new(Line::default())); + self.copies.push(Default::default()); } } - fn push_annotated(&mut self, mut appended: HyperlinkLine) { + fn push_annotated( + &mut self, + mut appended: HyperlinkLine, + inline: &[crate::markdown_copy::Inline], + ) { self.ensure_line(); + if let Some(copy) = self.copies.last_mut() { + copy.push( + appended + .line + .spans + .iter() + .map(|span| span.content.len()) + .sum(), + inline, + ); + } if let Some(line) = self.lines.last_mut() { let shift = line.width(); line.line.spans.append(&mut appended.line.spans); @@ -220,6 +237,7 @@ impl TableCell { #[inline] fn hard_break(&mut self) { self.lines.push(HyperlinkLine::new(Line::default())); + self.copies.push(Default::default()); } fn plain_text(&self) -> String { @@ -1111,18 +1129,44 @@ impl<'a, 'policy> Writer<'a, 'policy> { return; }; + let table: std::sync::Arc<[&str]> = table_state + .alignments + .iter() + .map(|alignment| match alignment { + Alignment::None => "---", + Alignment::Left => ":---", + Alignment::Center => ":---:", + Alignment::Right => "---:", + }) + .collect(); let RenderedTableLines { table_lines, table_lines_prewrapped, spillover_lines, - } = self.render_table_lines(table_state); + } = self.render_table_lines(table_state, &table); let mut pending_marker_line = self.pending_marker_line; - for line in table_lines { + for mut line in table_lines { + if line + .source + .as_ref() + .and_then(|source| source.copy.as_ref()) + .is_none() + { + crate::markdown_copy::table::attach( + &mut line, + Some(crate::markdown_copy::table::TableLine::empty(&table)), + ); + } if table_lines_prewrapped { self.push_prewrapped_line(line, pending_marker_line); } else { + let table = line + .source + .as_ref() + .and_then(|source| source.copy.as_ref()) + .and_then(|copy| copy.table.clone()); self.push_hyperlink_line(line); - self.copy_line.code = true; + self.copy_line.table = table; self.flush_current_line(); } pending_marker_line = false; @@ -1237,7 +1281,7 @@ impl<'a, 'policy> Writer<'a, 'policy> { if let Some(table_state) = self.table_state.as_mut() && let Some(cell) = table_state.current_cell.as_mut() { - cell.push_annotated(annotated); + cell.push_annotated(annotated, &self.copy_inline); } } @@ -1277,7 +1321,7 @@ impl<'a, 'policy> Writer<'a, 'policy> { if let Some(table_state) = self.table_state.as_mut() && let Some(cell) = table_state.current_cell.as_mut() { - cell.push_annotated(std::mem::take(&mut annotated)); + cell.push_annotated(std::mem::take(&mut annotated), &self.copy_inline); } } @@ -1292,7 +1336,11 @@ impl<'a, 'policy> Writer<'a, 'policy> { /// Falls back to key/value records when body rows cannot fit in the aligned /// grid; header-only tables retain raw pipe output because they contain no /// records to transpose. - fn render_table_lines(&self, mut table_state: TableState) -> RenderedTableLines { + fn render_table_lines( + &self, + mut table_state: TableState, + table: &std::sync::Arc<[&'static str]>, + ) -> RenderedTableLines { let column_count = table_state.alignments.len(); if column_count == 0 { return RenderedTableLines { @@ -1326,6 +1374,21 @@ impl<'a, 'policy> Writer<'a, 'policy> { for row in &mut rows { Self::normalize_row(row, column_count); } + for (row_index, row) in std::iter::once(&mut header) + .chain(rows.iter_mut()) + .enumerate() + { + for (column, cell) in row.iter_mut().enumerate() { + cell.ensure_line(); + crate::markdown_copy::table::annotate_cell( + &mut cell.lines, + std::mem::take(&mut cell.copies), + table, + row_index, + column, + ); + } + } let metrics = Self::collect_table_column_metrics(&header, &rows, column_count); let available_width = self.available_table_width(column_count); @@ -1691,16 +1754,25 @@ impl<'a, 'policy> Writer<'a, 'policy> { .get(row_line) .is_some_and(|line| Self::line_display_width(&line.line) > 0) }) else { - out.push(HyperlinkLine::new(Line::default().style(row_style))); + let mut line = wrapped_cells + .iter() + .find_map(|cell| cell.get(row_line)) + .cloned() + .unwrap_or_default(); + line.line.style = row_style; + out.push(line); continue; }; let mut spans = Vec::new(); + let mut copy = None; + let mut byte_offset = 0; for (column, width) in column_widths .iter() .enumerate() .take(last_visible_column + 1) { spans.push(Span::raw(" ".repeat(TABLE_CELL_PADDING))); + byte_offset += TABLE_CELL_PADDING; let mut line = wrapped_cells[column] .get(row_line) .cloned() @@ -1715,19 +1787,33 @@ impl<'a, 'policy> Writer<'a, 'policy> { if left_padding > 0 { spans.push(Span::raw(" ".repeat(left_padding))); } + byte_offset += left_padding; + if let Some(source) = &line.source { + crate::markdown_copy::table::append(&mut copy, source, byte_offset); + } + byte_offset += line + .line + .spans + .iter() + .map(|span| span.content.len()) + .sum::(); spans.append(&mut line.line.spans); let is_last_column = column == last_visible_column; if right_padding > 0 && !is_last_column { spans.push(Span::raw(" ".repeat(right_padding))); + byte_offset += right_padding; } if !is_last_column { spans.push(Span::raw(" ".repeat(TABLE_CELL_PADDING))); + byte_offset += TABLE_CELL_PADDING; } if !is_last_column { spans.push(Span::raw(" ".repeat(TABLE_COLUMN_GAP))); + byte_offset += TABLE_COLUMN_GAP; } } let mut out_line = HyperlinkLine::new(Line::from(spans).style(row_style)); + crate::markdown_copy::table::attach(&mut out_line, copy); let mut column_start = 0usize; for (column, width) in column_widths .iter() @@ -1779,12 +1865,16 @@ impl<'a, 'policy> Writer<'a, 'policy> { fn row_to_pipe_line(row: &[TableCell]) -> HyperlinkLine { let mut out = HyperlinkLine::new(Line::default()); + let mut copy = None; + let mut byte_offset = 1; out.push_span("|".into(), /*destination*/ None); for cell in row { out.push_span(" ".into(), /*destination*/ None); + byte_offset += 1; for (index, line) in cell.lines.iter().enumerate() { if index > 0 { out.push_span(" ".into(), /*destination*/ None); + byte_offset += 1; } let text = line .line @@ -1802,7 +1892,7 @@ impl<'a, 'policy> Writer<'a, 'policy> { out.push_span(Span::raw(std::mem::take(current_text)), destination); } }; - for ch in text.chars() { + for (byte, ch) in text.char_indices() { let destination = line .hyperlinks .iter() @@ -1814,15 +1904,23 @@ impl<'a, 'policy> Writer<'a, 'policy> { } if ch == '|' { current_text.push_str("\\|"); + byte_offset += 1; } else { current_text.push(ch); } + if let Some(mut source) = line.source.clone() { + source.range = byte..byte + ch.len_utf8(); + crate::markdown_copy::table::append(&mut copy, &source, byte_offset); + } + byte_offset += ch.len_utf8(); column += char_width(ch); } flush(&mut out, &mut current_text, current_destination); } out.push_span(" |".into(), /*destination*/ None); + byte_offset += 2; } + crate::markdown_copy::table::attach(&mut out, copy); out } @@ -1860,7 +1958,7 @@ impl<'a, 'policy> Writer<'a, 'policy> { .map(|line| line_to_static(&line)) .collect::>(); if rendered.is_empty() { - wrapped.push(HyperlinkLine::new(Line::default())); + wrapped.push(source_line.clone()); } else { wrapped.extend(remap_wrapped_line(source_line, rendered)); }; @@ -2057,7 +2155,7 @@ impl<'a, 'policy> Writer<'a, 'policy> { if let Some(table_state) = self.table_state.as_mut() && let Some(cell) = table_state.current_cell.as_mut() { - cell.push_annotated(destination); + cell.push_annotated(destination, &self.copy_inline); } self.push_span_to_table_cell(")".into()); } else { @@ -2087,8 +2185,14 @@ impl<'a, 'policy> Writer<'a, 'policy> { let span = Span::styled(local_target_display, style); if self.in_table_cell() { if show_label { - for label_span in link.local_label_spans { + for (label_span, inline) in link + .local_label_spans + .into_iter() + .zip(link.local_label_inline) + { + let previous = std::mem::replace(&mut self.copy_inline, inline); self.push_span_to_table_cell(label_span); + self.copy_inline = previous; } self.push_span_to_table_cell(" (".into()); } @@ -2218,11 +2322,15 @@ impl<'a, 'policy> Writer<'a, 'policy> { let mut spans = self.prefix_spans(pending_marker_line); let mut source = crate::terminal_hyperlinks::LogicalLineSource::from_line(&line.line); - let mut copy = crate::markdown_copy::CopyLine::default(); + let mut copy = line + .source + .as_ref() + .and_then(|source| source.copy.as_deref()) + .cloned() + .unwrap_or_default(); copy.prefix = self.copy_prefix(pending_marker_line); copy.continuation = self.copy_prefix(/*pending_marker_line*/ false); copy.item_prefix = self.copy_prefix(/*pending_marker_line*/ true); - copy.code = true; source.copy = Some(std::sync::Arc::new(copy)); source.prefix_bytes = spans.iter().map(|span| span.content.len()).sum(); source.continuation_indent = self.prefix_spans(/*pending_marker_line*/ false).into(); @@ -2612,9 +2720,9 @@ mod tests { #[test] fn wrap_cell_preserves_hard_break_lines() { let mut cell = TableCell::default(); - cell.push_annotated(Line::from("first line").into()); + cell.push_annotated(Line::from("first line").into(), &[]); cell.hard_break(); - cell.push_annotated(Line::from("second line").into()); + cell.push_annotated(Line::from("second line").into(), &[]); let writer = W::new( "", @@ -2640,6 +2748,29 @@ mod tests { ); } + #[test] + fn blank_table_continuations_do_not_repeat_the_first_cell() { + let mut cell = make_cell("first"); + cell.hard_break(); + cell.hard_break(); + cell.push_annotated(Line::from("last").into(), &[]); + cell.hard_break(); + let writer = W::new( + "", + /*wrap_width*/ Some(80), + /*cwd*/ None, + &never_hide_link_destination, + ); + let lines = writer.render_table_row( + &[make_cell("short"), cell], + &[5, 5], + &[Alignment::None, Alignment::None], + Style::default(), + ); + let rendered: Vec<_> = lines.iter().map(|line| line.line.to_string()).collect(); + insta::assert_debug_snapshot!(rendered); + } + // --------------------------------------------------------------- // Type alias for calling private associated functions on Writer. // --------------------------------------------------------------- @@ -2648,7 +2779,7 @@ mod tests { /// Build a single-line `TableCell` from plain text. fn make_cell(text: &str) -> TableCell { let mut cell = TableCell::default(); - cell.push_annotated(Line::from(text.to_string()).into()); + cell.push_annotated(Line::from(text.to_string()).into(), &[]); cell } diff --git a/codex-rs/tui/src/markdown_render/table_key_value.rs b/codex-rs/tui/src/markdown_render/table_key_value.rs index 29c0559f77..63bd72d843 100644 --- a/codex-rs/tui/src/markdown_render/table_key_value.rs +++ b/codex-rs/tui/src/markdown_render/table_key_value.rs @@ -163,8 +163,13 @@ fn render_aligned_field( let wrapped_value = wrap_cell(value, value_width); for (line_index, value_line) in wrapped_value.into_iter().enumerate() { let mut spans = Vec::new(); + let mut copy = None; if line_index == 0 { let label = header.plain_text(); + let label_source = label_line(header, label_style); + if let Some(source) = &label_source.source { + crate::markdown_copy::table::append(&mut copy, source, FIELD_LEADING_PADDING); + } spans.push(Span::raw(" ".repeat(FIELD_LEADING_PADDING))); spans.push(Span::styled(label.clone(), label_style)); spans.push(Span::raw(" ".repeat( @@ -173,7 +178,7 @@ fn render_aligned_field( } else { spans.push(Span::raw(" ".repeat(value_indent))); } - push_prefixed_value_line(out, spans, value_line); + push_prefixed_value_line(out, spans, value_line, copy); } } @@ -187,16 +192,22 @@ fn render_stacked_field( let label_width = available_width .map(|width| width.saturating_sub(FIELD_LEADING_PADDING).max(1)) .unwrap_or_else(|| display_width(&header.plain_text()).max(1)); - let label = Line::from(Span::styled(header.plain_text(), label_style)); + let label = label_line(header, label_style); let mut wrapped_labels = Vec::new(); push_owned_lines( - &word_wrap_line(&label, RtOptions::new(label_width)), + &word_wrap_line(&label.line, RtOptions::new(label_width)), &mut wrapped_labels, ); - for label_line in wrapped_labels { + for label_line in remap_wrapped_line(&label, wrapped_labels) { let mut spans = vec![Span::raw(" ".repeat(FIELD_LEADING_PADDING))]; - spans.extend(label_line.spans); - out.push(HyperlinkLine::new(Line::from(spans))); + let mut copy = None; + if let Some(source) = &label_line.source { + crate::markdown_copy::table::append(&mut copy, source, FIELD_LEADING_PADDING); + } + spans.extend(label_line.line.spans); + let mut line = HyperlinkLine::new(Line::from(spans)); + crate::markdown_copy::table::attach(&mut line, copy); + out.push(line); } let value_width = available_width @@ -207,6 +218,7 @@ fn render_stacked_field( out, vec![Span::raw(" ".repeat(STACKED_VALUE_INDENT))], value_line, + /*copy*/ None, ); } } @@ -215,13 +227,19 @@ fn push_prefixed_value_line( out: &mut Vec, mut prefix: Vec>, mut value_line: HyperlinkLine, + mut copy: Option, ) { + let bytes = prefix.iter().map(|span| span.content.len()).sum(); + if let Some(source) = &value_line.source { + crate::markdown_copy::table::append(&mut copy, source, bytes); + } let shift = prefix .iter() .map(|span| display_width(span.content.as_ref())) .sum::(); prefix.append(&mut value_line.line.spans); let mut output_line = HyperlinkLine::new(Line::from(prefix)); + crate::markdown_copy::table::attach(&mut output_line, copy); output_line .hyperlinks .extend(value_line.hyperlinks.into_iter().map(|mut link| { @@ -231,6 +249,26 @@ fn push_prefixed_value_line( out.push(output_line); } +fn label_line(header: &TableCell, style: Style) -> HyperlinkLine { + let mut line = HyperlinkLine::new(Line::from(Span::styled(header.plain_text(), style))); + let mut copy = None; + let mut offset = 0; + for header_line in &header.lines { + if let Some(source) = &header_line.source { + crate::markdown_copy::table::append(&mut copy, source, offset); + } + offset += header_line + .line + .spans + .iter() + .map(|span| span.content.len()) + .sum::() + + 1; + } + crate::markdown_copy::table::attach(&mut line, copy); + line +} + fn wrap_cell(cell: &TableCell, width: usize) -> Vec { if cell.lines.is_empty() { return vec![HyperlinkLine::new(Line::default())]; @@ -243,7 +281,7 @@ fn wrap_cell(cell: &TableCell, width: usize) -> Vec { .map(|line| line_to_static(&line)) .collect::>(); if rendered.is_empty() { - wrapped.push(HyperlinkLine::new(Line::default())); + wrapped.push(source_line.clone()); } else { wrapped.extend(remap_wrapped_line(source_line, rendered)); } diff --git a/codex-rs/tui/src/onboarding/auth.rs b/codex-rs/tui/src/onboarding/auth.rs index 9ad829140a..52a27567f1 100644 --- a/codex-rs/tui/src/onboarding/auth.rs +++ b/codex-rs/tui/src/onboarding/auth.rs @@ -129,8 +129,8 @@ pub(crate) struct ApiKeyInputState { #[derive(Clone)] /// Used to manage the lifecycle of SpawnedLogin and ensure it gets cleaned up. pub(crate) struct ContinueInBrowserState { - login_id: String, - auth_url: String, + pub(super) login_id: String, + pub(super) auth_url: String, } #[derive(Clone)] @@ -256,6 +256,7 @@ pub(crate) struct AuthModeWidget { pub error: Arc>>, pub sign_in_state: Arc>, pub login_status: LoginStatus, + pub app_server_target: crate::AppServerTarget, pub app_server_request_handle: AppServerRequestHandle, pub auth_config: AuthConfig, pub bedrock_setup_enabled: bool, @@ -574,7 +575,14 @@ impl AuthModeWidget { let mut lines = vec![spans.into(), "".into()]; let auth_url = if !state.auth_url.is_empty() { - lines.push(" If the link doesn't open automatically, open the following link to authenticate:".into()); + lines.push(Line::from(vec![ + " If the link doesn't open automatically, press ".into(), + keys::COPY_LINK[0].into(), + " to copy it:".into(), + ])); + if let Some(message) = self.error_message() { + lines.push(format!(" {message}").dim().into()); + } lines.push("".into()); lines.push(Line::from(vec![ " ".into(), @@ -933,6 +941,7 @@ impl AuthModeWidget { } self.set_error(/*message*/ None); + let app_server_target = self.app_server_target.clone(); let request_handle = self.app_server_request_handle.clone(); let sign_in_state = self.sign_in_state.clone(); let error = self.error.clone(); @@ -950,13 +959,14 @@ impl AuthModeWidget { .await { Ok(LoginAccountResponse::Chatgpt { login_id, auth_url }) => { - maybe_open_auth_url_in_browser(&request_handle, &auth_url); *error.write().unwrap() = None; - *sign_in_state.write().unwrap() = - SignInState::ChatGptContinueInBrowser(ContinueInBrowserState { - login_id, - auth_url, - }); + show_chatgpt_login_in_browser( + &app_server_target, + &sign_in_state, + &request_frame, + ContinueInBrowserState { login_id, auth_url }, + webbrowser::open, + ); } Ok(other) => { *sign_in_state.write().unwrap() = SignInState::PickMode; @@ -1085,12 +1095,23 @@ impl WidgetRef for AuthModeWidget { } } -pub(super) fn maybe_open_auth_url_in_browser(request_handle: &AppServerRequestHandle, url: &str) { - if !matches!(request_handle, AppServerRequestHandle::InProcess(_)) { +fn show_chatgpt_login_in_browser( + target: &crate::AppServerTarget, + sign_in_state: &RwLock, + request_frame: &FrameRequester, + login: ContinueInBrowserState, + open: impl FnOnce(&str) -> std::io::Result<()>, +) { + let url = login.auth_url.clone(); + *sign_in_state.write().unwrap() = SignInState::ChatGptContinueInBrowser(login); + request_frame.schedule_frame(); + + // Local daemons use a remote request handle, but their callback is local. + if target.uses_remote_workspace() { return; } - if let Err(err) = webbrowser::open(url) { + if let Err(err) = open(&url) { tracing::warn!("failed to open browser for login URL: {err}"); } } @@ -1103,8 +1124,10 @@ mod tests { use codex_app_server_client::DEFAULT_IN_PROCESS_CHANNEL_CAPACITY; use codex_app_server_client::InProcessAppServerClient; use codex_app_server_client::InProcessClientStartArgs; + use codex_app_server_client::RemoteAppServerEndpoint; use codex_arg0::Arg0DispatchPaths; use codex_cloud_config::cloud_config_bundle_loader_for_storage; + use codex_utils_absolute_path::AbsolutePathBuf; use pretty_assertions::assert_eq; use std::sync::Arc; use tempfile::TempDir; @@ -1124,6 +1147,78 @@ mod tests { "originator=codex_cli_rs" ); + #[test] + fn opens_login_browser_for_local_app_servers() -> color_eyre::Result<()> { + let endpoint = RemoteAppServerEndpoint::UnixSocket { + socket_path: AbsolutePathBuf::relative_to_current_dir("codex.sock")?, + }; + let url = "https://example.test/authorize"; + for (target, expected) in [ + (crate::AppServerTarget::Embedded, true), + ( + crate::AppServerTarget::LocalDaemon { + endpoint: endpoint.clone(), + allow_embedded_fallback: true, + }, + true, + ), + ( + crate::AppServerTarget::LocalDaemon { + endpoint: endpoint.clone(), + allow_embedded_fallback: false, + }, + true, + ), + (crate::AppServerTarget::Remote { endpoint }, false), + ] { + let mut opened_url = None; + show_chatgpt_login_in_browser( + &target, + &RwLock::new(SignInState::PickMode), + &FrameRequester::test_dummy(), + ContinueInBrowserState { + login_id: "login-1".to_string(), + auth_url: url.to_string(), + }, + |url| { + opened_url = Some(url.to_owned()); + Ok(()) + }, + ); + assert_eq!(opened_url.as_deref(), expected.then_some(url)); + } + Ok(()) + } + + #[tokio::test] + async fn login_can_complete_while_browser_is_opening() { + let (mut widget, _tmp) = widget_forced_chatgpt().await; + let sign_in_state = widget.sign_in_state.clone(); + let request_frame = widget.request_frame.clone(); + show_chatgpt_login_in_browser( + &crate::AppServerTarget::Embedded, + &sign_in_state, + &request_frame, + ContinueInBrowserState { + login_id: "login-1".to_string(), + auth_url: "https://example.test/authorize".to_string(), + }, + |_| { + widget.on_account_login_completed(AccountLoginCompletedNotification { + login_id: Some("login-1".to_string()), + success: true, + error: None, + onboarding_entrypoint: None, + }); + Ok(()) + }, + ); + assert!(matches!( + &*sign_in_state.read().unwrap(), + SignInState::ChatGptSuccessMessage + )); + } + async fn widget_forced_chatgpt() -> (AuthModeWidget, TempDir) { let codex_home = TempDir::new().unwrap(); let codex_home_path = codex_home.path().to_path_buf(); @@ -1172,6 +1267,7 @@ mod tests { error: Arc::new(RwLock::new(None)), sign_in_state: Arc::new(RwLock::new(SignInState::PickMode)), login_status: LoginStatus::NotAuthenticated, + app_server_target: crate::AppServerTarget::Embedded, app_server_request_handle: AppServerRequestHandle::InProcess(client.request_handle()), auth_config, bedrock_setup_enabled: false, diff --git a/codex-rs/tui/src/onboarding/keys.rs b/codex-rs/tui/src/onboarding/keys.rs index d573f47d33..ff7eacac44 100644 --- a/codex-rs/tui/src/onboarding/keys.rs +++ b/codex-rs/tui/src/onboarding/keys.rs @@ -26,6 +26,7 @@ pub(crate) const SELECT_THIRD: [KeyBinding; 1] = [key_hint::plain(KeyCode::Char( pub(crate) const SELECT_FOURTH: [KeyBinding; 1] = [key_hint::plain(KeyCode::Char('4'))]; pub(crate) const CONFIRM: [KeyBinding; 1] = [key_hint::plain(KeyCode::Enter)]; pub(crate) const CANCEL: [KeyBinding; 1] = [key_hint::plain(KeyCode::Esc)]; +pub(crate) const COPY_LINK: [KeyBinding; 1] = [key_hint::plain(KeyCode::Char('c'))]; pub(crate) const QUIT: [KeyBinding; 3] = [ key_hint::plain(KeyCode::Char('q')), key_hint::ctrl(KeyCode::Char('c')), diff --git a/codex-rs/tui/src/onboarding/onboarding_screen.rs b/codex-rs/tui/src/onboarding/onboarding_screen.rs index 7db5443681..415c7d6376 100644 --- a/codex-rs/tui/src/onboarding/onboarding_screen.rs +++ b/codex-rs/tui/src/onboarding/onboarding_screen.rs @@ -33,6 +33,8 @@ use codex_protocol::config_types::ForcedLoginMethod; use crate::LoginStatus; use crate::app_server_session::AppServerSession; +use crate::clipboard_copy::CopyFormat; +use crate::clipboard_copy::CopyStatus; use crate::config_update::RemoteProjectTrust; use crate::config_update::format_config_error; use crate::config_update::replace_config_value; @@ -48,6 +50,7 @@ use crate::onboarding::trust_directory::TrustDirectorySelection; use crate::onboarding::trust_directory::TrustDirectoryWidget; use crate::onboarding::welcome::WelcomeWidget; use crate::tui::FrameRequester; +use crate::tui::OverlayInput; use crate::tui::Tui; use crate::tui::TuiEvent; use color_eyre::eyre::Result; @@ -97,6 +100,7 @@ pub(crate) struct OnboardingScreenArgs { pub show_login_screen: bool, pub bedrock_setup_enabled: bool, pub login_status: LoginStatus, + pub app_server_target: crate::AppServerTarget, pub app_server_request_handle: Option, pub config: Config, } @@ -123,6 +127,7 @@ impl OnboardingScreen { show_login_screen, bedrock_setup_enabled, login_status, + app_server_target, app_server_request_handle, config, } = args; @@ -168,6 +173,7 @@ impl OnboardingScreen { error: Arc::new(RwLock::new(None)), sign_in_state: Arc::new(RwLock::new(SignInState::PickMode)), login_status, + app_server_target, app_server_request_handle, auth_config, bedrock_setup_enabled, @@ -540,6 +546,30 @@ pub(crate) async fn run_onboarding_app( } async fn run_onboarding_screen( + onboarding_screen: OnboardingScreen, + app_server_request_handle: Option, + app_server: Option<&mut AppServerSession>, + tui: &mut Tui, +) -> Result { + // Let the terminal select and copy login URLs and device codes, even in fullscreen mode. + let previous_input = tui.overlay_input; + let result = match tui.set_overlay_input(OverlayInput::Onboarding) { + Ok(()) => { + run_onboarding_screen_inner( + onboarding_screen, + app_server_request_handle, + app_server, + tui, + ) + .await + } + Err(error) => Err(error.into()), + }; + let restore = tui.set_overlay_input(previous_input); + result.and_then(|result| restore.map(|()| result).map_err(Into::into)) +} + +async fn run_onboarding_screen_inner( mut onboarding_screen: OnboardingScreen, app_server_request_handle: Option, mut app_server: Option<&mut AppServerSession>, @@ -549,6 +579,7 @@ async fn run_onboarding_screen( let mut directory_trust_persisted = false; // One-time guard to fully clear the screen after ChatGPT login success message is shown let mut did_full_clear_after_success = false; + let mut pending_copy: Option<(u64, String)> = None; tui.draw(u16::MAX, |frame| { frame.render_widget_ref(&onboarding_screen, frame.area()); @@ -566,7 +597,36 @@ async fn run_onboarding_screen( tui.screen_size_for_event(&event)?; match event { TuiEvent::Key(key_event) => { - onboarding_screen.handle_key_event(key_event); + let copy_link = if key_event.kind == KeyEventKind::Press + && keys::COPY_LINK.is_pressed(key_event) + && let Some(Step::Auth(widget)) = onboarding_screen.current_steps().last() + && let Ok(state) = widget.sign_in_state.read() + && let SignInState::ChatGptContinueInBrowser(state) = &*state + && !state.auth_url.is_empty() + { + Some((state.login_id.clone(), Arc::::from(state.auth_url.as_str()))) + } else { + None + }; + if let Some((login_id, url)) = copy_link { + let result = tui.clipboard.copy(url, CopyFormat::PlainText, tui.frame_requester()); + let message = match result { + Ok(CopyStatus::Pending(id)) => { + pending_copy = Some((id, login_id)); + "Copying link…".to_string() + } + Ok(CopyStatus::Busy) => "Clipboard busy; try again".to_string(), + Ok(CopyStatus::Confirmed) => "Copied link to clipboard".to_string(), + Ok(CopyStatus::Unconfirmed) => "Copy requested; check your clipboard".to_string(), + Err(error) => format!("Could not copy link: {error}"), + }; + if let Some(Step::Auth(widget)) = onboarding_screen.current_steps_mut().into_iter().last() { + *widget.error.write().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(message); + } + tui.frame_requester().schedule_frame(); + } else { + onboarding_screen.handle_key_event(key_event); + } if !directory_trust_persisted { directory_trust_persisted = persist_selected_trust( &mut onboarding_screen, @@ -583,6 +643,25 @@ async fn run_onboarding_screen( | TuiEvent::Resize(_) | TuiEvent::FocusGained | TuiEvent::FocusLost => { + if let Some((id, result)) = tui.clipboard.poll().cloned() + && let Some((pending_id, login_id)) = &pending_copy + && id == *pending_id + { + if let Some(Step::Auth(widget)) = onboarding_screen.current_steps_mut().into_iter().last() + && widget.sign_in_state.read().is_ok_and(|state| { + matches!(&*state, SignInState::ChatGptContinueInBrowser(state) if state.login_id == *login_id) + }) + { + let message = match result { + Ok(CopyStatus::Confirmed) => "Copied link to clipboard".to_string(), + Ok(CopyStatus::Unconfirmed) => "Copy requested; check your clipboard".to_string(), + Ok(CopyStatus::Busy | CopyStatus::Pending(_)) => "Clipboard busy; try again".to_string(), + Err(error) => format!("Could not copy link: {error}"), + }; + *widget.error.write().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(message); + } + pending_copy = None; + } for step in &onboarding_screen.steps { if let Step::Welcome(widget) = step { if matches!(&event, TuiEvent::Resume) { diff --git a/codex-rs/tui/src/onboarding/snapshots/codex_tui__onboarding__auth__tests__continue_in_browser_narrow_long_url.snap b/codex-rs/tui/src/onboarding/snapshots/codex_tui__onboarding__auth__tests__continue_in_browser_narrow_long_url.snap index d4262b5386..f8f65e2779 100644 --- a/codex-rs/tui/src/onboarding/snapshots/codex_tui__onboarding__auth__tests__continue_in_browser_narrow_long_url.snap +++ b/codex-rs/tui/src/onboarding/snapshots/codex_tui__onboarding__auth__tests__continue_in_browser_narrow_long_url.snap @@ -5,7 +5,7 @@ expression: contents Finish signing in via your browser If the link doesn't open automatically, -open the following link to authenticate: +press c to copy it: https://auth.openai.com/oauth/authorize?re sponse_type=code&client_id=app_EMoamEEZ73f0C diff --git a/codex-rs/tui/src/snapshots/codex_tui__markdown_render__tests__blank_table_continuations_do_not_repeat_the_first_cell.snap b/codex-rs/tui/src/snapshots/codex_tui__markdown_render__tests__blank_table_continuations_do_not_repeat_the_first_cell.snap new file mode 100644 index 0000000000..45017facb1 --- /dev/null +++ b/codex-rs/tui/src/snapshots/codex_tui__markdown_render__tests__blank_table_continuations_do_not_repeat_the_first_cell.snap @@ -0,0 +1,11 @@ +--- +source: tui/src/markdown_render.rs +assertion_line: 2773 +expression: rendered +--- +[ + " short first", + "", + " last", + "", +] diff --git a/codex-rs/tui/src/snapshots/codex_tui__startup_draft__layout__tests__owned_startup_layout.snap b/codex-rs/tui/src/snapshots/codex_tui__startup_draft__layout__tests__owned_startup_layout.snap index 9de37490a3..957e7539d5 100644 --- a/codex-rs/tui/src/snapshots/codex_tui__startup_draft__layout__tests__owned_startup_layout.snap +++ b/codex-rs/tui/src/snapshots/codex_tui__startup_draft__layout__tests__owned_startup_layout.snap @@ -1,14 +1,14 @@ --- source: tui/src/startup_draft_layout_tests.rs -expression: startup_layout +expression: "format!(\"cursor={:?}\\n{frame}\",\nlayout.cursor_pos(area)).replace(crate::version::CODEX_CLI_VERSION,\n\"\")" --- cursor=Some((13, 12)) -╭───────────────────────────────────────╮ -│ >_ OpenAI Codex (v) │ -│ │ -│ model: loading /model to change │ -│ directory: loading │ -╰───────────────────────────────────────╯ + + >_ OpenAI Codex (v) + loading + + Pull up a prompt. + diff --git a/codex-rs/tui/src/snapshots/codex_tui__startup_draft__tests__startup_draft_fresh_session_transitions.snap b/codex-rs/tui/src/snapshots/codex_tui__startup_draft__tests__startup_draft_fresh_session_transitions.snap index 32f6de9153..fb019c0e58 100644 --- a/codex-rs/tui/src/snapshots/codex_tui__startup_draft__tests__startup_draft_fresh_session_transitions.snap +++ b/codex-rs/tui/src/snapshots/codex_tui__startup_draft__tests__startup_draft_fresh_session_transitions.snap @@ -1,27 +1,26 @@ --- source: tui/src/startup_draft_tests.rs +assertion_line: 285 expression: "snapshots.join(\"\\n---\\n\")" --- resume lookup fallback: before: -╭───────────────────────────────────────╮ -│ >_ OpenAI Codex (v) │ -│ │ -│ model: loading /model to change │ -│ directory: loading │ -╰───────────────────────────────────────╯ + + >_ OpenAI Codex (v) + loading + + Pull up a prompt. Resuming session… › draft while loading after: -╭───────────────────────────────────────╮ -│ >_ OpenAI Codex (v) │ -│ │ -│ model: loading /model to change │ -│ directory: loading │ -╰───────────────────────────────────────╯ + + >_ OpenAI Codex (v) + loading + + Pull up a prompt. › draft while loading @@ -30,24 +29,22 @@ after: --- fork lookup fallback: before: -╭───────────────────────────────────────╮ -│ >_ OpenAI Codex (v) │ -│ │ -│ model: loading /model to change │ -│ directory: loading │ -╰───────────────────────────────────────╯ + + >_ OpenAI Codex (v) + loading + + Pull up a prompt. Forking session… › draft while loading after: -╭───────────────────────────────────────╮ -│ >_ OpenAI Codex (v) │ -│ │ -│ model: loading /model to change │ -│ directory: loading │ -╰───────────────────────────────────────╯ + + >_ OpenAI Codex (v) + loading + + Pull up a prompt. › draft while loading @@ -58,12 +55,11 @@ resume picker cancellation: before: hidden while picker owns input after: -╭───────────────────────────────────────╮ -│ >_ OpenAI Codex (v) │ -│ │ -│ model: loading /model to change │ -│ directory: loading │ -╰───────────────────────────────────────╯ + + >_ OpenAI Codex (v) + loading + + Pull up a prompt. › Ask Codex to do anything @@ -74,12 +70,11 @@ fork picker cancellation: before: hidden while picker owns input after: -╭───────────────────────────────────────╮ -│ >_ OpenAI Codex (v) │ -│ │ -│ model: loading /model to change │ -│ directory: loading │ -╰───────────────────────────────────────╯ + + >_ OpenAI Codex (v) + loading + + Pull up a prompt. › Ask Codex to do anything diff --git a/codex-rs/tui/src/snapshots/codex_tui__startup_draft__tests__startup_draft_full_frames.snap b/codex-rs/tui/src/snapshots/codex_tui__startup_draft__tests__startup_draft_full_frames.snap index 9195af7637..3eb081d7d4 100644 --- a/codex-rs/tui/src/snapshots/codex_tui__startup_draft__tests__startup_draft_full_frames.snap +++ b/codex-rs/tui/src/snapshots/codex_tui__startup_draft__tests__startup_draft_full_frames.snap @@ -1,14 +1,14 @@ --- source: tui/src/startup_draft_tests.rs +assertion_line: 148 expression: "snapshots.join(\"\\n---\\n\")" --- empty (48 columns): -╭───────────────────────────────────────╮ -│ >_ OpenAI Codex (v) │ -│ │ -│ model: loading /model to change │ -│ directory: loading │ -╰───────────────────────────────────────╯ + + >_ OpenAI Codex (v) + loading + + Pull up a prompt. › Ask Codex to do anything @@ -16,12 +16,11 @@ empty (48 columns): ? for shortcuts --- resuming (48 columns): -╭───────────────────────────────────────╮ -│ >_ OpenAI Codex (v) │ -│ │ -│ model: loading /model to change │ -│ directory: loading │ -╰───────────────────────────────────────╯ + + >_ OpenAI Codex (v) + loading + + Pull up a prompt. Resuming session… › Ask Codex to do anything @@ -29,12 +28,11 @@ resuming (48 columns): ? for shortcuts --- forking (48 columns): -╭───────────────────────────────────────╮ -│ >_ OpenAI Codex (v) │ -│ │ -│ model: loading /model to change │ -│ directory: loading │ -╰───────────────────────────────────────╯ + + >_ OpenAI Codex (v) + loading + + Pull up a prompt. Forking session… › draft while loading @@ -42,12 +40,11 @@ forking (48 columns): --- multiline (48 columns): -╭───────────────────────────────────────╮ -│ >_ OpenAI Codex (v) │ -│ │ -│ model: loading /model to change │ -│ directory: loading │ -╰───────────────────────────────────────╯ + + >_ OpenAI Codex (v) + loading + + Pull up a prompt. › first startup line @@ -56,12 +53,11 @@ multiline (48 columns): --- narrow (18 columns): -╭────────────────╮ -│ >_ OpenAI Cod… │ -│ │ -│ model: lo… │ -│ directory: …ng │ -╰────────────────╯ + + >_ OpenAI Codex… + loading + + Pull up a promp… › first startup diff --git a/codex-rs/tui/src/snapshots/codex_tui__startup_draft__tests__startup_draft_onboarding_transition.snap b/codex-rs/tui/src/snapshots/codex_tui__startup_draft__tests__startup_draft_onboarding_transition.snap index 6284b0715e..681cfd873b 100644 --- a/codex-rs/tui/src/snapshots/codex_tui__startup_draft__tests__startup_draft_onboarding_transition.snap +++ b/codex-rs/tui/src/snapshots/codex_tui__startup_draft__tests__startup_draft_onboarding_transition.snap @@ -1,16 +1,16 @@ --- source: tui/src/startup_draft_tests.rs +assertion_line: 802 expression: frames --- before onboarding: hidden (0x0 viewport) --- after onboarding: -╭───────────────────────────────────────╮ -│ >_ OpenAI Codex (v) │ -│ │ -│ model: loading /model to change │ -│ directory: loading │ -╰───────────────────────────────────────╯ + + >_ OpenAI Codex (v) + loading + + Pull up a prompt. › Ask Codex to do anything diff --git a/codex-rs/tui/src/snapshots/codex_tui__startup_draft__tests__terminal_app_ssh_startup.snap b/codex-rs/tui/src/snapshots/codex_tui__startup_draft__tests__terminal_app_ssh_startup.snap index 5d25a1b9ff..2ec0e1e641 100644 --- a/codex-rs/tui/src/snapshots/codex_tui__startup_draft__tests__terminal_app_ssh_startup.snap +++ b/codex-rs/tui/src/snapshots/codex_tui__startup_draft__tests__terminal_app_ssh_startup.snap @@ -1,15 +1,15 @@ --- source: tui/src/startup_draft_tests.rs -assertion_line: 162 +assertion_line: 194 expression: "frames.join(\"\\n---\\n\").replace(crate::version::CODEX_CLI_VERSION, \"\")" --- terminal_app_over_ssh=false, owned=true -╭───────────────────────────────────────╮ -│ >_ OpenAI Codex (v) │ -│ │ -│ model: loading /model to change │ -│ directory: loading │ -╰───────────────────────────────────────╯ + + >_ OpenAI Codex (v) + loading + + Pull up a prompt. + @@ -22,12 +22,11 @@ terminal_app_over_ssh=false, owned=true ? for shortcuts --- terminal_app_over_ssh=true, owned=false -╭───────────────────────────────────────╮ -│ >_ OpenAI Codex (v) │ -│ │ -│ model: loading /model to change │ -│ directory: loading │ -╰───────────────────────────────────────╯ + + >_ OpenAI Codex (v) + loading + + Pull up a prompt. › Ask Codex to do anything diff --git a/codex-rs/tui/src/startup_draft.rs b/codex-rs/tui/src/startup_draft.rs index 6fd83d8b3d..dd6cda869c 100644 --- a/codex-rs/tui/src/startup_draft.rs +++ b/codex-rs/tui/src/startup_draft.rs @@ -59,6 +59,7 @@ pub(crate) struct StartupScreen { pub(crate) use_alt_screen: bool, pub(crate) transcript_mode: crate::transcript_mode::TranscriptMode, pub(crate) status_line_enabled: bool, + pub(crate) welcome_motion: crate::motion::MotionMode, pub(crate) keymap: RuntimeKeymap, pub(crate) disable_paste_burst: bool, } @@ -103,6 +104,8 @@ pub(crate) struct StartupDraft { /// Keeps terminal input responsive and carries one submission intent into the live session. pub(crate) struct StartupDraftPump { header: Box, + pub(crate) blossom: std::cell::RefCell, + motion: crate::motion::MotionMode, bottom_pane: BottomPane, events: Pin + Send>>, app_event_rx: UnboundedReceiver, @@ -135,6 +138,7 @@ impl StartupDraft { tui.terminal_app_over_ssh = initialized_terminal.terminal_app_over_ssh; tui.set_alt_screen_enabled(screen.use_alt_screen); let mut pump = StartupDraftPump::new(&tui, initial_screen, session_action); + pump.motion = screen.welcome_motion; pump.bottom_pane .set_status_line_enabled(screen.status_line_enabled); pump.bottom_pane.set_keymap_bindings(&screen.keymap); @@ -193,8 +197,19 @@ impl StartupDraftPump { session_action: StartupDraftSessionAction, ) -> Self { let (app_event_tx, app_event_rx) = unbounded_channel(); + let mut blossom = crate::empty_state_animation::EmptyStateAnimation::default(); + if matches!( + session_action, + StartupDraftSessionAction::New | StartupDraftSessionAction::NewFromCommandCenter + ) { + blossom.start_fresh(); + } + let mut header = startup_session_header(/*config*/ None); + history_cell::set_session_greeting(header.as_mut(), &blossom.greeting); Self { - header: startup_session_header(/*config*/ None), + header, + blossom: std::cell::RefCell::new(blossom), + motion: crate::system_motion::mode(), bottom_pane: startup_draft_bottom_pane( AppEventSender::new(app_event_tx), tui.frame_requester(), @@ -245,7 +260,11 @@ impl StartupDraftPump { } self.configured_cwd = Some(config.cwd.to_path_buf()); let local_settings = crate::local_settings::LocalSettings::from(config); + self.motion = crate::motion::MotionMode::from_animations_enabled( + local_settings.tui.animations && local_settings.tui.effects.welcome, + ); self.header = startup_session_header(Some(config)); + history_cell::set_session_greeting(self.header.as_mut(), &self.blossom.borrow().greeting); self.bottom_pane.set_status_line_enabled( local_settings .tui @@ -307,6 +326,11 @@ impl StartupDraftPump { } self.resolved_selection = Some(session_selection.clone()); self.session_action = session_action; + if matches!(session_selection, SessionSelection::StartFresh) + && !self.blossom.borrow().is_eligible() + { + self.blossom.borrow_mut().start_fresh(); + } if self.initial_screen == StartupDraftInitialScreen::Composer { self.draw(tui, tui.terminal.last_known_screen_size)?; } @@ -417,8 +441,7 @@ impl StartupDraftPump { } self.bottom_pane.pre_draw_tick(); let owned = tui.is_owned_screen(); - let owned_layout = - layout::OwnedStartupLayout::new(&self.header, &self.bottom_pane, self.session_action); + let owned_layout = layout::OwnedStartupLayout::new(self); let renderable = if owned { RenderableItem::Borrowed(&owned_layout) } else { @@ -437,6 +460,9 @@ impl StartupDraftPump { frame.set_cursor_position((x, y)); } })?; + if let Some(delay) = owned_layout.next_frame.get() { + tui.frame_requester().schedule_frame_in(delay); + } Ok(()) } } diff --git a/codex-rs/tui/src/startup_draft_input.rs b/codex-rs/tui/src/startup_draft_input.rs index 3d398139f1..491b99c7fc 100644 --- a/codex-rs/tui/src/startup_draft_input.rs +++ b/codex-rs/tui/src/startup_draft_input.rs @@ -161,9 +161,26 @@ impl StartupDraftPump { TuiEvent::Draw | TuiEvent::Resize(_) | TuiEvent::Resume | TuiEvent::FocusGained => {} TuiEvent::FocusLost => { self.key_chord_matcher.cancel(); + self.blossom.borrow_mut().cancel_replay(); return Ok(()); } - TuiEvent::Mouse(_) => return Ok(()), + TuiEvent::Mouse(mouse) => { + if !tui.is_owned_screen() + || self.initial_screen != StartupDraftInitialScreen::Composer + || !matches!( + self.session_action, + super::StartupDraftSessionAction::New + | super::StartupDraftSessionAction::NewFromCommandCenter + ) + { + return Ok(()); + } + // Size, composer, and modal ownership must be current before hit testing. + self.draw(tui, screen_size)?; + if !self.blossom.borrow_mut().handle_mouse(mouse) { + return Ok(()); + } + } } crate::startup_recovery::remember(self.bottom_pane.composer_recovery_snapshot()); if self.initial_screen == StartupDraftInitialScreen::Composer { diff --git a/codex-rs/tui/src/startup_draft_layout.rs b/codex-rs/tui/src/startup_draft_layout.rs index ed64e73710..8b77ee5f59 100644 --- a/codex-rs/tui/src/startup_draft_layout.rs +++ b/codex-rs/tui/src/startup_draft_layout.rs @@ -1,38 +1,54 @@ //! First-frame owned layout: the banner stays at the top and the normal composer at the bottom. //! Measurement, paint, and cursor placement use the same bottom rectangle, including both footers. +//! Only a new conversation paints decoration in the unused area, so it cannot enter scrollback. use crossterm::cursor::SetCursorStyle; use ratatui::buffer::Buffer; use ratatui::layout::Rect; +use ratatui::style::Style; use ratatui::style::Stylize; +use ratatui::widgets::Widget; +use std::cell::Cell; +use std::time::Duration; +use super::StartupDraftPump; use super::StartupDraftSessionAction; -use crate::bottom_pane::BottomPane; use crate::bottom_pane::CommandPopupPlacement; use crate::bottom_pane::ComposerRenderOptions; use crate::render::renderable::Renderable; use crate::render::renderable::RenderableItem; +use crate::terminal_hyperlinks::HyperlinkLine; +use crate::terminal_hyperlinks::HyperlinkParagraph; pub(super) struct OwnedStartupLayout<'a> { - header: &'a dyn Renderable, + pump: &'a StartupDraftPump, bottom: RenderableItem<'a>, - session_action: StartupDraftSessionAction, + pub(super) next_frame: Cell>, } impl<'a> OwnedStartupLayout<'a> { - pub(super) fn new( - header: &'a dyn Renderable, - bottom_pane: &'a BottomPane, - session_action: StartupDraftSessionAction, - ) -> Self { + pub(super) fn new(pump: &'a StartupDraftPump) -> Self { Self { - header, - bottom: bottom_pane.as_renderable_with_options(ComposerRenderOptions { - separate_status_line: true, - command_popup_placement: CommandPopupPlacement::Overlay, - ..ComposerRenderOptions::default() - }), - session_action, + pump, + next_frame: Cell::new(/*value*/ None), + bottom: pump + .bottom_pane + .as_renderable_with_options(ComposerRenderOptions { + separate_status_line: true, + command_popup_placement: CommandPopupPlacement::Overlay, + ..ComposerRenderOptions::default() + }), + } + } + + fn header_lines(&self, width: u16) -> Vec { + match self.pump.session_action { + StartupDraftSessionAction::New | StartupDraftSessionAction::NewFromCommandCenter => { + self.pump.header.compact_hyperlink_lines(width) + } + StartupDraftSessionAction::Resume | StartupDraftSessionAction::Fork => { + self.pump.header.display_hyperlink_lines(width) + } } } @@ -49,16 +65,31 @@ impl<'a> OwnedStartupLayout<'a> { impl Renderable for OwnedStartupLayout<'_> { fn render(&self, area: Rect, buf: &mut Buffer) { let bottom = self.bottom_area(area); + let lines = self.header_lines(area.width); + let paragraph = HyperlinkParagraph::new(&lines, Style::default()); let header = Rect { - height: self - .header - .desired_height(area.width) + height: u16::try_from(paragraph.line_count(area.width)) + .unwrap_or(u16::MAX) .min(bottom.y.saturating_sub(area.y)), ..area }; - self.header.render(header, buf); - let message = match self.session_action { + paragraph.render(header, buf); + let message = match self.pump.session_action { StartupDraftSessionAction::New | StartupDraftSessionAction::NewFromCommandCenter => { + let composer = (!self.pump.submission_pending) + .then(|| self.pump.bottom_pane.empty_state_composer()) + .flatten(); + self.next_frame + .set(self.pump.blossom.borrow_mut().render_first_screen( + Rect { + y: header.bottom(), + height: bottom.y.saturating_sub(header.bottom()), + ..area + }, + buf, + composer, + self.pump.motion, + )); None } StartupDraftSessionAction::Resume => Some(" Resuming session…"), @@ -80,8 +111,9 @@ impl Renderable for OwnedStartupLayout<'_> { } fn desired_height(&self, width: u16) -> u16 { - self.header - .desired_height(width) + let lines = self.header_lines(width); + u16::try_from(HyperlinkParagraph::new(&lines, Style::default()).line_count(width)) + .unwrap_or(u16::MAX) .saturating_add(self.bottom.desired_height(width)) } diff --git a/codex-rs/tui/src/startup_draft_layout_tests.rs b/codex-rs/tui/src/startup_draft_layout_tests.rs index b32d9f1e08..1644ad3103 100644 --- a/codex-rs/tui/src/startup_draft_layout_tests.rs +++ b/codex-rs/tui/src/startup_draft_layout_tests.rs @@ -12,11 +12,7 @@ fn owned_startup_keeps_the_live_bottom_geometry() { ("Waiting for startup".into(), String::new()), ("esc".into(), "cancel".into()), ])); - let layout = OwnedStartupLayout::new( - &pump.header, - &pump.bottom_pane, - StartupDraftSessionAction::New, - ); + let layout = OwnedStartupLayout::new(&pump); let area = Rect::new( /*x*/ 0, /*y*/ 0, /*width*/ 48, /*height*/ 16, ); @@ -36,3 +32,106 @@ fn owned_startup_keeps_the_live_bottom_geometry() { .replace(crate::version::CODEX_CLI_VERSION, "") ); } + +#[test] +fn new_startup_decoration_tracks_draft_and_session_action() { + let mut pump = crate::startup_draft::tests::quiet_startup_test_pump(); + let area = Rect::new( + /*x*/ 0, /*y*/ 0, /*width*/ 80, /*height*/ 32, + ); + let mut blossom_visible = Vec::new(); + for (draft, action, pending) in [ + ("", StartupDraftSessionAction::New, false), + (" ", StartupDraftSessionAction::New, false), + ("", StartupDraftSessionAction::New, false), + ("", StartupDraftSessionAction::New, true), + ("", StartupDraftSessionAction::Resume, false), + ("", StartupDraftSessionAction::Fork, false), + ("", StartupDraftSessionAction::NewFromCommandCenter, false), + ] { + pump.session_action = action; + pump.submission_pending = pending; + pump.bottom_pane + .set_composer_text(draft.into(), Vec::new(), Vec::new()); + let layout = OwnedStartupLayout::new(&pump); + let mut buffer = Buffer::empty(area); + layout.render(area, &mut buffer); + blossom_visible.push(buffer.content.iter().any(|cell| { + cell.symbol() + .chars() + .any(|ch| ('\u{2801}'..='\u{28ff}').contains(&ch)) + })); + } + assert_eq!( + blossom_visible, + [true, false, true, false, false, false, true] + ); +} + +#[tokio::test] +async fn configured_welcome_opt_out_disables_blossom_and_clicks() -> anyhow::Result<()> { + use clap::Parser; + use codex_config::LoaderOverrides; + use crossterm::event::KeyModifiers; + use crossterm::event::MouseButton; + use crossterm::event::MouseEvent; + use crossterm::event::MouseEventKind; + let codex_home = tempfile::tempdir()?; + let cli = crate::Cli::try_parse_from(["codex"])?; + let area = Rect::new( + /*x*/ 0, /*y*/ 0, /*width*/ 80, /*height*/ 44, + ); + let click = MouseEvent { + kind: MouseEventKind::Down(MouseButton::Left), + column: 40, + row: 22, + modifiers: KeyModifiers::NONE, + }; + for (settings, enabled) in [ + ("", true), + ("[tui]\nanimations = false\n", false), + ("[tui.effects]\nwelcome = false\n", false), + ( + "[tui]\nanimations = false\n[tui.effects]\nwelcome = false\n", + false, + ), + ] { + std::fs::write(codex_home.path().join("config.toml"), settings)?; + let presentation = crate::startup_presentation::load( + &cli, + codex_home.path(), + LoaderOverrides { + ignore_project_config: true, + ..LoaderOverrides::without_managed_config_for_tests() + }, + Vec::new(), + /*config_cwd*/ None, + ) + .await?; + let config = crate::legacy_core::config::ConfigBuilder::default() + .codex_home(codex_home.path().to_path_buf()) + .build() + .await?; + let mut pump = crate::startup_draft::tests::quiet_startup_test_pump(); + // The provisional frame uses the bootstrap value; subsequent frames use effective config. + pump.motion = presentation.screen.welcome_motion; + for effective in [false, true] { + if effective { + pump.apply_config(&config); + } + let mut buffer = Buffer::empty(area); + OwnedStartupLayout::new(&pump).render(area, &mut buffer); + let visible = buffer.content.iter().any(|cell| { + cell.symbol() + .chars() + .any(|ch| ('\u{2801}'..='\u{28ff}').contains(&ch)) + }); + assert_eq!( + visible, enabled, + "settings: {settings}, effective: {effective}" + ); + assert_eq!(pump.blossom.borrow_mut().handle_mouse(click), enabled); + } + } + Ok(()) +} diff --git a/codex-rs/tui/src/startup_draft_tests.rs b/codex-rs/tui/src/startup_draft_tests.rs index ffb7e6f54b..d89b5d071e 100644 --- a/codex-rs/tui/src/startup_draft_tests.rs +++ b/codex-rs/tui/src/startup_draft_tests.rs @@ -28,8 +28,20 @@ where I: Iterator + Send + 'static, { let (tx, rx) = unbounded_channel(); + let mut blossom = crate::empty_state_animation::EmptyStateAnimation::default(); + blossom + .greeting + .set(crate::empty_state_animation::Greeting { + phrase: "Pull up a prompt.", + }) + .expect("initial greeting"); + blossom.start_fresh(); + let mut header = startup_session_header(/*config*/ None); + crate::history_cell::set_session_greeting(header.as_mut(), &blossom.greeting); StartupDraftPump { - header: startup_session_header(/*config*/ None), + header, + blossom: std::cell::RefCell::new(blossom), + motion: crate::motion::MotionMode::Animated, bottom_pane: startup_draft_bottom_pane( AppEventSender::new(tx), FrameRequester::test_dummy(), @@ -138,11 +150,7 @@ fn startup_draft_renders_full_empty_and_multiline_composer_frames() { #[test] fn terminal_app_ssh_fallback_renders_inline_startup() { let pump = startup_test_pump(std::iter::empty()); - let owned_layout = super::layout::OwnedStartupLayout::new( - &pump.header, - &pump.bottom_pane, - StartupDraftSessionAction::New, - ); + let owned_layout = super::layout::OwnedStartupLayout::new(&pump); let mut frames = Vec::new(); for terminal_app_over_ssh in [false, true] { let owned = crate::determine_alt_screen_mode( @@ -168,6 +176,12 @@ fn terminal_app_ssh_fallback_renders_inline_startup() { let area = Rect::new(/*x*/ 0, /*y*/ 0, width, height); let mut buffer = Buffer::empty(area); renderable.render(area, &mut buffer); + assert!( + buffer + .content + .iter() + .any(|cell| { cell.symbol() == ">" && cell.fg == crate::style::accent_color() }) + ); let frame = (0..height) .map(|y| { (0..width) @@ -243,6 +257,7 @@ async fn startup_draft_clears_loading_status_when_starting_fresh() { let mut pump = startup_test_pump(std::iter::empty()); pump.initial_screen = initial_screen; pump.session_action = session_action; + pump.blossom.borrow_mut().dismiss(); if initial_screen == StartupDraftInitialScreen::Composer { pump.bottom_pane.insert_str("draft while loading"); } @@ -257,6 +272,7 @@ async fn startup_draft_clears_loading_status_when_starting_fresh() { pump.update_session_selection(&mut tui, &SessionSelection::StartFresh) .expect("clear the loading status after a fresh-session selection"); + assert!(pump.blossom.borrow().is_eligible()); if initial_screen == StartupDraftInitialScreen::SessionPicker { assert!(tui.terminal.viewport_area.is_empty()); pump.show(&mut tui) @@ -291,21 +307,15 @@ async fn startup_draft_hydrates_its_header_without_moving_the_composer() { startup_draft_renderable(&pump.header, &pump.bottom_pane, pump.session_action) .desired_height(width); - assert_eq!( - pump.header.raw_lines().last().map(ToString::to_string), - Some("directory: loading".to_string()) - ); + assert_eq!(pump.header.raw_lines()[2].to_string().trim(), "loading"); pump.apply_config(&config); - let expected_directory = format!( - "directory: {}", - crate::history_cell::SessionHeaderHistoryCell::format_directory_inner( - config.cwd.as_path(), - /*max_width*/ None, - ) + let expected_directory = crate::history_cell::SessionHeaderHistoryCell::format_directory_inner( + config.cwd.as_path(), + /*max_width*/ None, ); assert_eq!( - pump.header.raw_lines().last().map(ToString::to_string), - Some(expected_directory) + pump.header.raw_lines()[2].to_string().trim(), + expected_directory ); assert_eq!( startup_draft_renderable(&pump.header, &pump.bottom_pane, pump.session_action) diff --git a/codex-rs/tui/src/startup_orchestration.rs b/codex-rs/tui/src/startup_orchestration.rs index cbba29ac3f..847821d35f 100644 --- a/codex-rs/tui/src/startup_orchestration.rs +++ b/codex-rs/tui/src/startup_orchestration.rs @@ -523,26 +523,37 @@ pub(super) async fn run_main_inner( daemon_features.retain(|_, enabled| *enabled); let mut managed_daemon = false; if auto_start_daemon && daemon_exclusion.is_none() { - startup_draft.flush_pending_events().await?; let output = startup_draft - .tui_mut() - .with_restored(|| async { - // Package installation may print progress; keep ordinary Ctrl+C handling. - crossterm::terminal::disable_raw_mode()?; + .run_until(async { + // Daemon startup needs no terminal input. Keep the composer visible and + // responsive while it checks the running server or prepares an installation. let result = codex_app_server_daemon::start_with_features(&daemon_features).await; daemon_telemetry::record_start(&config, &result).await; - result.map_err(|err| { - std::io::Error::other(format!("{err:#}\n{}", daemon_startup::FAILURE_HINT)) - }) + match result { + Ok(output) => Ok(Some(output)), + #[cfg(windows)] + Err(err) if err.is::() => { + Ok(None) + } + Err(err) => Err(std::io::Error::other(format!( + "{err:#}\n{}", + daemon_startup::FAILURE_HINT + ))), + } }) - .await?; - managed_daemon = output.backend.is_some(); - app_server_target = AppServerTarget::LocalDaemon { - endpoint: RemoteAppServerEndpoint::UnixSocket { - socket_path: AbsolutePathBuf::from_absolute_path_checked(output.socket_path)?, - }, - allow_embedded_fallback: false, - }; + .await??; + if let Some(output) = output { + managed_daemon = output.backend.is_some(); + app_server_target = AppServerTarget::LocalDaemon { + endpoint: RemoteAppServerEndpoint::UnixSocket { + socket_path: AbsolutePathBuf::from_absolute_path_checked(output.socket_path)?, + }, + allow_embedded_fallback: false, + }; + } else { + app_server_target = AppServerTarget::Embedded; + daemon_exclusion = Some("this Windows launcher"); + } } // The overview must inspect the shared server's agents regardless of local settings. let compatibility_warning = if cli.agents_overview { diff --git a/codex-rs/tui/src/startup_presentation.rs b/codex-rs/tui/src/startup_presentation.rs index d718b0cd71..4c431d5227 100644 --- a/codex-rs/tui/src/startup_presentation.rs +++ b/codex-rs/tui/src/startup_presentation.rs @@ -81,6 +81,13 @@ pub(super) async fn load( .disable_paste_burst .or(config_toml.disable_paste_burst) .unwrap_or(/*default*/ false); + let welcome_motion = crate::motion::MotionMode::from_animations_enabled( + config_toml + .tui + .as_ref() + .is_none_or(|tui| tui.animations && tui.effects.welcome) + && crate::system_motion::mode() == crate::motion::MotionMode::Animated, + ); Ok(StartupPresentation { bootstrap_config, config_cwd, @@ -88,6 +95,7 @@ pub(super) async fn load( use_alt_screen, transcript_mode, status_line_enabled, + welcome_motion, keymap, disable_paste_burst, }, diff --git a/codex-rs/tui/src/terminal_hyperlinks.rs b/codex-rs/tui/src/terminal_hyperlinks.rs index 6db9897f3f..bea2472ad1 100644 --- a/codex-rs/tui/src/terminal_hyperlinks.rs +++ b/codex-rs/tui/src/terminal_hyperlinks.rs @@ -426,10 +426,16 @@ pub(crate) fn remap_wrapped_line( wrapped: Vec>, ) -> Vec { let mut out = plain_hyperlink_lines(wrapped); - if source.hyperlinks.is_empty() { + if source.hyperlinks.is_empty() && source.source.is_none() { return out; } let source_text = line_text(&source.line); + if source_text.trim().is_empty() { + for line in &mut out { + line.source = source.source.clone(); + } + return out; + } let mut source_byte = 0usize; let mut source_column = 0usize; let mut link_index = 0usize; @@ -447,6 +453,10 @@ pub(crate) fn remap_wrapped_line( continue; }; let mapped = &rendered[rendered_start..]; + line.source = source + .source + .as_ref() + .map(|source| source.wrapped(source_byte..source_byte + mapped.len(), rendered_start)); let mut output_column = display_width(&rendered[..rendered_start]); for grapheme in mapped.graphemes(/*is_extended*/ true) { let width = display_width(grapheme); diff --git a/codex-rs/tui/src/tooltips.rs b/codex-rs/tui/src/tooltips.rs index 7dff716092..a8cceac303 100644 --- a/codex-rs/tui/src/tooltips.rs +++ b/codex-rs/tui/src/tooltips.rs @@ -205,9 +205,13 @@ pub(crate) fn resolved_tooltips( .filter_map(move |tip| render_tooltip(tip, keymap)) } +pub(crate) fn tooltip_templates() -> impl Iterator { + ALL_TOOLTIPS.iter().copied() +} + /// Substitute `{key:context.action}` with the current primary shortcut in a Markdown code span. /// Skip the tip if a placeholder is invalid or its action has no binding. -fn render_tooltip(mut template: &str, keymap: Option<&RuntimeKeymap>) -> Option { +pub(crate) fn render_tooltip(mut template: &str, keymap: Option<&RuntimeKeymap>) -> Option { let mut rendered = String::new(); while let Some((prefix, rest)) = template.split_once("{key:") { let (action, suffix) = rest.split_once('}')?; diff --git a/codex-rs/tui/src/transcript_view.rs b/codex-rs/tui/src/transcript_view.rs index df77eb16c1..db58338e29 100644 --- a/codex-rs/tui/src/transcript_view.rs +++ b/codex-rs/tui/src/transcript_view.rs @@ -19,6 +19,7 @@ mod search; mod selection; mod snapshot; mod text; +mod turn_tip; use std::sync::Arc; @@ -89,6 +90,7 @@ pub(crate) struct TranscriptView { follow_control: follow_control::FollowControl, copy_feedback: Option, composer_tip: Option<(Rect, HyperlinkLine)>, + turn_tip_key: Option, cache: LayoutCache, live: Option>, live_separated: Option>, @@ -120,6 +122,7 @@ impl Default for TranscriptView { follow_control: follow_control::FollowControl::default(), copy_feedback: None, composer_tip: None, + turn_tip_key: None, cache: LayoutCache::default(), live: None, live_separated: None, @@ -146,6 +149,19 @@ impl Default for TranscriptView { } impl TranscriptView { + /// Rows left after the last render, including all startup notices and live entries. + /// Callers can paint temporary UI here without changing selection or saved history. + pub(crate) fn remaining_area(&self) -> Rect { + let used = u16::try_from(self.visible.len()) + .unwrap_or(u16::MAX) + .min(self.area.height); + Rect { + y: self.area.y + used, + height: self.area.height - used, + ..self.area + } + } + pub(crate) fn render(&mut self, area: Rect, buf: &mut Buffer, cells: &[Arc]) { self.composer_tip = None; self.cache.begin_frame(); @@ -540,6 +556,15 @@ impl TranscriptView { .layout(cells, index) .map_or(/*default*/ 0, |l| l.row_count()); } + // At the beginning, hidden entries are not preceding content. Keep the first + // visible entry at the same position whether it is live or committed. + if index == 0 + && remaining >= row + && let Some(first) = self.next_nonempty(cells, index) + && let Some(layout) = self.layout(cells, first) + { + return (first, usize::from(layout.separated)); + } return (index, row.saturating_sub(remaining)); } let mut remaining = row.saturating_add(rows as usize); diff --git a/codex-rs/tui/src/transcript_view/layout.rs b/codex-rs/tui/src/transcript_view/layout.rs index fe66fb9b91..e2eb210346 100644 --- a/codex-rs/tui/src/transcript_view/layout.rs +++ b/codex-rs/tui/src/transcript_view/layout.rs @@ -70,6 +70,7 @@ struct CachedLayout { #[derive(Clone, Copy, PartialEq, Eq)] pub(super) struct CellPresentation { separated: bool, + turn_tip_space: bool, expanded: bool, disclosure: bool, } @@ -136,6 +137,7 @@ impl TranscriptView { let separated = index > 0 && !cell.is_stream_continuation(); let presentation = CellPresentation { separated, + turn_tip_space: self.turn_tip_key == Some(EntryKey::cell(cell)), expanded, disclosure, }; @@ -154,10 +156,16 @@ impl TranscriptView { width, expanded, ) - } else if detailed || mode == HistoryRenderMode::Rich { - TextLayout::new(cell.retained_hyperlink_lines(width, detailed), width) } else { - TextLayout::new(cell.display_hyperlink_lines_for_mode(width, mode), width) + TextLayout::new( + crate::history_cell::fullscreen_session_lines( + cell.as_ref(), + width, + detailed, + mode, + ), + width, + ) } })) } @@ -203,10 +211,15 @@ impl LayoutCache { return layout; } let layout = render(); - let layout = Arc::new(if presentation.separated { + let layout = if presentation.separated { layout.with_leading_separator() } else { layout + }; + let layout = Arc::new(if presentation.turn_tip_space { + layout.with_leading_spacer() + } else { + layout }); self.entries.retain(|entry| !entry.source.ptr_eq(&source)); self.entries.push(CachedLayout { diff --git a/codex-rs/tui/src/transcript_view/layout_tests.rs b/codex-rs/tui/src/transcript_view/layout_tests.rs index 8cdc12352b..f0b3702043 100644 --- a/codex-rs/tui/src/transcript_view/layout_tests.rs +++ b/codex-rs/tui/src/transcript_view/layout_tests.rs @@ -47,6 +47,7 @@ fn layouts_refresh_for_width_animation_and_mutable_frames() { width, CellPresentation { separated: false, + turn_tip_space: false, expanded: false, disclosure: false, }, @@ -101,6 +102,7 @@ fn recent_entries_are_reused_and_old_entries_are_evicted() { /*width*/ 20, CellPresentation { separated: false, + turn_tip_space: false, expanded: false, disclosure: false, }, @@ -119,6 +121,7 @@ fn recent_entries_are_reused_and_old_entries_are_evicted() { /*width*/ 20, CellPresentation { separated: false, + turn_tip_space: false, expanded: false, disclosure: false, }, diff --git a/codex-rs/tui/src/transcript_view/markdown_copy_tests.rs b/codex-rs/tui/src/transcript_view/markdown_copy_tests.rs index 1ce0b74220..8642e6e366 100644 --- a/codex-rs/tui/src/transcript_view/markdown_copy_tests.rs +++ b/codex-rs/tui/src/transcript_view/markdown_copy_tests.rs @@ -7,6 +7,12 @@ use ratatui::buffer::Buffer; use ratatui::layout::Rect; use std::path::Path; +#[path = "table_copy_tests.rs"] +mod tables; + +#[path = "markdown_element_copy_tests.rs"] +mod elements; + #[test] fn selected_markdown_preserves_lists_and_inline_code() { let cells: Vec> = vec![Arc::new(AgentMarkdownCell::new( @@ -358,7 +364,7 @@ fn task_lists_and_transformed_tables_keep_their_meaning() { ); let copied = payload(&layout, 0..layout.text().len()).0; let html = crate::clipboard_html::render_markdown(&copied); - assert!(html.contains("
"), "{copied}\n{html}");
+    assert!(html.contains(""), "{copied}\n{html}");
 }
 
 #[test]
diff --git a/codex-rs/tui/src/transcript_view/markdown_element_copy_tests.rs b/codex-rs/tui/src/transcript_view/markdown_element_copy_tests.rs
new file mode 100644
index 0000000000..a22d3a8242
--- /dev/null
+++ b/codex-rs/tui/src/transcript_view/markdown_element_copy_tests.rs
@@ -0,0 +1,75 @@
+//! Coverage of the Markdown grammar and visible transformations used by selection copy.
+
+use super::*;
+use pretty_assertions::assert_eq;
+
+#[test]
+fn supported_elements_preserve_structure_at_narrow_and_wide_widths() {
+    let samples = [
+        "# One\n\n## Two\n\n### Three\n\n#### Four\n\n##### Five\n\n###### Six",
+        "Setext heading\n===\n\nSubheading\n---",
+        "**strong** _emphasis_ ~~deleted~~ and `inline_code` with ``a`b``.",
+        "Escaped \\*stars\\*, & entity, café 界, and 👩‍💻.",
+        "- first\n- second\n  - nested\n\n3. third\n4. fourth",
+        "- [ ] pending\n- [x] complete",
+        "> quoted **text**\n>\n> - item\n>   - nested",
+        "First paragraph.\n\nHard break:  \nnext line.\n\n---\n\nLast paragraph.",
+        "Prose\n\n```\nlet x = \"*literal* \";\n```\n\nAfter",
+        "Image ![**alt** text](https://example.com/image.png).",
+        "Literal HTML and unsupported [^footnote].",
+    ];
+    for source in samples {
+        for width in [18, 100] {
+            let layout = markdown_layout(source, width);
+            let copied = payload(&layout, 0..layout.text().len()).0;
+            assert_eq!(
+                crate::clipboard_html::render_markdown(&copied),
+                crate::clipboard_html::render_markdown(source),
+                "width {width}: {source}\n{copied}"
+            );
+        }
+    }
+}
+
+#[test]
+fn transformed_content_copies_visible_text_without_active_html_or_images() {
+    for (source, expected) in [
+        ("Soft break\nsame paragraph.", "Soft break\nsame paragraph."),
+        ("[**local**](/repo/file.rs)", "**local** (repo/file.rs)"),
+        (
+            "[label][reference]\n\n[reference]: https://example.com",
+            "[label (https://example.com)](https://example.com)",
+        ),
+        (
+            "",
+            "[https://example.com (https://example.com)](https://example.com)",
+        ),
+        ("![image alt](https://example.com/image.png)", "image alt"),
+    ] {
+        let layout = markdown_layout(source, /*width*/ 40);
+        let copied = payload(&layout, 0..layout.text().len()).0;
+        assert_eq!(
+            crate::clipboard_html::render_markdown(&copied),
+            crate::clipboard_html::render_markdown(expected),
+            "{source}\n{copied}"
+        );
+    }
+}
+
+#[test]
+fn math_and_mermaid_copy_the_visible_rendering() {
+    for source in [
+        "Inline $\\alpha_1$ and \\(x^{2}\\).",
+        "\\[\n\\frac{a}{b}\n\\]",
+        "```mermaid\nflowchart LR\nA[Start] --> B[Finish]\n```",
+    ] {
+        let layout = markdown_layout(source, /*width*/ 80);
+        let (copied, format) = payload(&layout, 0..layout.text().len());
+        if format == CopyFormat::PlainText {
+            assert_eq!(copied, layout.text());
+        } else {
+            let rendered = markdown_layout(&copied, /*width*/ 80);
+            assert_eq!(rendered.text(), layout.text());
+        }
+    }
+}
diff --git a/codex-rs/tui/src/transcript_view/selection.rs b/codex-rs/tui/src/transcript_view/selection.rs
index db27e05410..95acea4df6 100644
--- a/codex-rs/tui/src/transcript_view/selection.rs
+++ b/codex-rs/tui/src/transcript_view/selection.rs
@@ -319,15 +319,19 @@ impl TranscriptView {
         Some(pending.follow && completion.1 == Ok(crate::clipboard_copy::CopyStatus::Confirmed))
     }
 
-    /// End the pointer gesture without discarding selected text when input ownership changes.
-    pub(crate) fn end_drag(&mut self) {
-        self.follow_control = Default::default();
-        if !self.has_selection_range()
+    /// A stationary click begun at Latest still belongs to the fresh screen until it selects text.
+    pub(crate) fn has_pending_latest_selection(&self) -> bool {
+        !self.has_selection_range()
             && self
                 .selection
                 .as_ref()
                 .is_some_and(|selection| selection.dragging && selection.resume_on_empty)
-        {
+    }
+
+    /// End the pointer gesture without discarding selected text when input ownership changes.
+    pub(crate) fn end_drag(&mut self) {
+        self.follow_control = Default::default();
+        if self.has_pending_latest_selection() {
             self.position = Position::Latest;
             self.selection = None;
             self.release_live_reading();
diff --git a/codex-rs/tui/src/transcript_view/snapshots/codex_tui__transcript_view__markdown_copy_tests__nested_tables_keep_their_copy_containers.snap b/codex-rs/tui/src/transcript_view/snapshots/codex_tui__transcript_view__markdown_copy_tests__nested_tables_keep_their_copy_containers.snap
index 63f7c7523e..38fb1d81b2 100644
--- a/codex-rs/tui/src/transcript_view/snapshots/codex_tui__transcript_view__markdown_copy_tests__nested_tables_keep_their_copy_containers.snap
+++ b/codex-rs/tui/src/transcript_view/snapshots/codex_tui__transcript_view__markdown_copy_tests__nested_tables_keep_their_copy_containers.snap
@@ -1,21 +1,18 @@
 ---
 source: tui/src/transcript_view/markdown_copy_tests.rs
-assertion_line: 393
+assertion_line: 460
 expression: "copies.join(\"\\n---\\n\")"
 ---
 Before
 
-> ```
->  A      B
-> ━━━━━  ━━━━━
->  one    two
-> ```
+> | A | B |
+> |---|---|
+> | one | two |
 

Before

-
 A      B
-━━━━━  ━━━━━
- one    two
-
+
+ +
AB
onetwo
--- @@ -23,18 +20,15 @@ Before - intro - ``` - A B - ━━━━━ ━━━━━ - one two - ``` + | A | B | + |---|---| + | one | two |

Before

  • intro

    -
     A      B
    -━━━━━  ━━━━━
    - one    two
    -
    + + +
    AB
    onetwo
diff --git a/codex-rs/tui/src/transcript_view/snapshots/codex_tui__transcript_view__markdown_copy_tests__table_spillover_keeps_prose_outside_the_literal_table.snap b/codex-rs/tui/src/transcript_view/snapshots/codex_tui__transcript_view__markdown_copy_tests__table_spillover_keeps_prose_outside_the_literal_table.snap index 66653c0aa7..543eb1234e 100644 --- a/codex-rs/tui/src/transcript_view/snapshots/codex_tui__transcript_view__markdown_copy_tests__table_spillover_keeps_prose_outside_the_literal_table.snap +++ b/codex-rs/tui/src/transcript_view/snapshots/codex_tui__transcript_view__markdown_copy_tests__table_spillover_keeps_prose_outside_the_literal_table.snap @@ -1,24 +1,22 @@ --- source: tui/src/transcript_view/markdown_copy_tests.rs -assertion_line: 358 +assertion_line: 420 expression: "format!(\"{copied}\\n{}\", crate::clipboard_html::render_markdown(&copied))" --- **Before** -``` - A B -━━━━━ ━━━━━ - one two -``` +| A | B | +|---|---| +| one | two | + HTML block: \Prose after the table.\ After

Before

-
 A      B
-━━━━━  ━━━━━
- one    two
-
+ + +
AB
onetwo

HTML block: <div>Prose after the table.</div>

After

diff --git a/codex-rs/tui/src/transcript_view/snapshots/codex_tui__transcript_view__markdown_copy_tests__tables__empty_selected_rows_keep_copy_spacing_without_newline_highlights.snap b/codex-rs/tui/src/transcript_view/snapshots/codex_tui__transcript_view__markdown_copy_tests__tables__empty_selected_rows_keep_copy_spacing_without_newline_highlights.snap new file mode 100644 index 0000000000..8c83e00fc1 --- /dev/null +++ b/codex-rs/tui/src/transcript_view/snapshots/codex_tui__transcript_view__markdown_copy_tests__tables__empty_selected_rows_keep_copy_spacing_without_newline_highlights.snap @@ -0,0 +1,27 @@ +--- +source: tui/src/transcript_view/table_copy_tests.rs +assertion_line: 108 +expression: "highlighted.join(\"\\n\")" +--- +• Before + ^^^^^^^ + + + Task Status Next step + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + ━━━━━━━━ ━━━━━━━━━━━━━ ━━━━━━━━━━━━━━━━━━━━━━━ + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + Task 1 Complete Review results + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + ──────── ───────────── ─────────────────────── + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + Task 2 In progress Finish implementation + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + ──────── ───────────── ─────────────────────── + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + Task 3 Planned Confirm requirements + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + + After + ^^^^^ diff --git a/codex-rs/tui/src/transcript_view/table_copy_tests.rs b/codex-rs/tui/src/transcript_view/table_copy_tests.rs new file mode 100644 index 0000000000..b792eaa31a --- /dev/null +++ b/codex-rs/tui/src/transcript_view/table_copy_tests.rs @@ -0,0 +1,183 @@ +//! Selection regressions through the real Markdown renderer, layout, and clipboard serializer. + +use super::*; +use pretty_assertions::assert_eq; + +const TABLE: &str = "| Task | Status | Next step |\n|---|---|---|\n| Task 1 | Complete | Review results |\n| Task 2 | In progress | Finish implementation |\n| Task 3 | Planned | Confirm requirements |"; + +#[test] +fn table_copy_preserves_structure_across_grid_and_record_layouts() { + let source = format!( + "The project is moving forward, with one task complete and two still to finish.\n\n{TABLE}\n\nThe next priority is to finish Task 2 while gathering the requirements needed to begin Task 3." + ); + for width in [12, 24, 40, 80, 120] { + let layout = markdown_layout(&source, width); + assert_eq!( + payload(&layout, 0..layout.text().len()), + (source.clone(), CopyFormat::Markdown), + "width {width}" + ); + let rewrapped = layout.rewrap(/*width*/ 17); + assert_eq!( + payload(&rewrapped, 0..rewrapped.text().len()).0, + source, + "rewrapped {width}" + ); + } +} + +#[test] +fn partial_table_selection_never_adds_unselected_cell_text() { + let code = markdown_layout( + "| A | B |\n|---|---|\n| `a\\|b` | value |", + /*width*/ 80, + ); + let start = code.text().find("a|b").unwrap(); + assert_eq!(payload(&code, start..start + 3).0, "`a|b`"); + let repeated = markdown_layout( + "| alpha SECRET omega |\n|---|\n| long_value_one |\n| long_value_two |", + /*width*/ 12, + ); + let start = repeated.text().find("omega").unwrap(); + let end = repeated.text().rfind("alpha").unwrap() + "alpha".len(); + assert!(!payload(&repeated, start..end).0.contains("SECRET")); + assert!( + payload(&repeated, start..repeated.text().len()) + .0 + .starts_with("| alpha SECRET omega |") + ); + let layout = markdown_layout( + "| Label | Value |\n|---|---|\n| **alpha** | beta |\n| gamma | delta |", + /*width*/ 80, + ); + let start = layout.text().find("alpha").unwrap(); + assert_eq!( + payload(&layout, start + 1..start + 4), + ("**lph**".into(), CopyFormat::Markdown) + ); + let end = layout.text().find("delta").unwrap() + "delta".len(); + let copied = payload(&layout, start..end).0; + assert_eq!( + copied, + "| | |\n|---|---|\n| **alpha** | beta |\n| gamma | delta |" + ); +} + +#[test] +fn table_cells_keep_inline_formatting_alignment_and_literal_pipes() { + let source = "| Left | Center | Right |\n|:---|:---:|---:|\n| **bold** _italic_ ~~strike~~ | `a\\|b` | [link]() |\n| café 界 | escaped \\*star\\* | last |"; + let expected_html = crate::clipboard_html::render_markdown( + &source.replace("[link]", "[link (https://example.com/?a=1&b=2)]"), + ); + for width in [16, 48, 120] { + let layout = markdown_layout(source, width); + let copied = payload(&layout, 0..layout.text().len()).0; + assert_eq!( + crate::clipboard_html::render_markdown(&copied), + expected_html, + "width {width}: {copied}" + ); + } +} + +#[test] +fn header_only_and_empty_cells_keep_their_table_positions() { + for source in [ + "| A | B |\n|---|---|", + "| A |\n|---|", + "| A | B |\n|---|---|\n| | right |\n| | |\n| left | |", + "| A | B |\n|---|---|\n| ` ` | value |", + ] { + for width in [4, 80] { + let layout = markdown_layout(source, width); + let copied = payload(&layout, 0..layout.text().len()).0; + assert_eq!( + crate::clipboard_html::render_markdown(&copied), + crate::clipboard_html::render_markdown(source), + "width {width}: {copied}" + ); + } + } +} + +#[test] +fn separate_tables_and_code_remain_separate_blocks() { + let source = "Before\n\n| A | B |\n|---|---|\n| one | two |\n\n```text\n| literal | code |\n```\n\n| C | D |\n|---|---|\n| three | four |\n\nAfter"; + let layout = markdown_layout(source, /*width*/ 80); + let copied = payload(&layout, 0..layout.text().len()).0; + assert_eq!(copied, source.replace("```text", "```")); +} + +#[test] +fn table_separator_only_selection_keeps_visible_text() { + for width in [12, 80] { + let layout = markdown_layout(TABLE, width); + let mut offset = 0; + let mut checked = false; + for line in layout.text().split('\n') { + if line.contains('─') || line.contains('━') { + assert_eq!(payload(&layout, offset..offset + line.len()).0, line); + checked = true; + } + offset += line.len() + 1; + } + assert!(checked, "no separator at width {width}"); + } +} + +#[test] +fn empty_selected_rows_keep_copy_spacing_without_newline_highlights() { + let cells: Vec> = vec![Arc::new(AgentMarkdownCell::new( + format!("Before\n\n{TABLE}\n\nAfter"), + Path::new("/"), + ))]; + let mut view = TranscriptView::default(); + let area = Rect::new( + /*x*/ 0, /*y*/ 0, /*width*/ 80, /*height*/ 20, + ); + let mut buffer = Buffer::empty(area); + view.render(area, &mut buffer, &cells); + view.begin_selection(&cells, /*column*/ 2, /*row*/ 0, /*clicks*/ 1); + view.extend_selection(/*column*/ 79, /*row*/ 19); + view.render(area, &mut buffer, &cells); + let mut highlighted = Vec::new(); + for row in 0..area.height { + let text = (0..area.width) + .map(|column| buffer[(column, row)].symbol()) + .collect::(); + let selected = (0..area.width) + .map(|column| { + if buffer[(column, row)] + .modifier + .contains(ratatui::style::Modifier::REVERSED) + { + '^' + } else { + ' ' + } + }) + .collect::(); + if text.trim().is_empty() { + assert!(selected.trim().is_empty(), "blank row {row}"); + } + highlighted.push(format!("{}\n{}", text.trim_end(), selected.trim_end())); + } + let plain = view.selected_text(&cells).unwrap(); + view.copy_selected_text_with( + &cells, + &plain, + /*clear_selection*/ false, + |text, format| { + assert_eq!( + (text, format), + ( + format!("Before\n\n{TABLE}\n\nAfter").as_str(), + CopyFormat::Markdown + ) + ); + Ok(crate::clipboard_copy::CopyStatus::Confirmed) + }, + ) + .unwrap(); + insta::assert_snapshot!(highlighted.join("\n")); +} diff --git a/codex-rs/tui/src/transcript_view/text.rs b/codex-rs/tui/src/transcript_view/text.rs index 3504047986..44877552ca 100644 --- a/codex-rs/tui/src/transcript_view/text.rs +++ b/codex-rs/tui/src/transcript_view/text.rs @@ -4,7 +4,7 @@ //! lines introduce hard breaks. Display wrapping and synthetic controls never enter `text`. //! Layout offsets use `usize`; terminal coordinates are narrowed only for visible rows. //! Disclosure controls follow their activity's source text without changing its indentation. -//! Selected hard breaks highlight one trailing cell when space permits. +//! Selected hard breaks on nonempty rows highlight one trailing cell when space permits. use std::borrow::Cow; use std::ops::Range; @@ -142,7 +142,16 @@ impl TextLayout { /// Add visual spacing between entries without changing any source position. pub(super) fn with_leading_separator(mut self) -> Self { - if !self.separated && !self.rows.is_empty() { + if !self.separated { + self = self.with_leading_spacer(); + self.separated = !self.rows.is_empty(); + } + self + } + + /// Reserve one presentation-only row before existing spacing and source text. + pub(super) fn with_leading_spacer(mut self) -> Self { + if !self.rows.is_empty() { self.rows.insert( /*index*/ 0, TextRow { @@ -158,7 +167,6 @@ impl TextLayout { if let Some(control) = &mut self.disclosure_control { control.row += 1; } - self.separated = true; } self } @@ -310,7 +318,7 @@ impl TextLayout { } } - /// Add a trailing cell for selected hard breaks, including a copied separator to `next`. + /// Mark selected hard breaks on nonempty rows, including a copied separator to `next`. pub(super) fn highlight_selection( &self, range: Range, @@ -321,6 +329,9 @@ impl TextLayout { ) { self.highlight(range.clone(), area, buf, start_row); for (screen_row, row) in self.visible_rows(area, start_row) { + if row.source.is_empty() { + continue; + } let Some(end) = row.line_end else { continue }; let selected = range.contains(&end) || (end == self.text.len() diff --git a/codex-rs/tui/src/transcript_view/text_tests.rs b/codex-rs/tui/src/transcript_view/text_tests.rs index af220f891e..6b050c00ba 100644 --- a/codex-rs/tui/src/transcript_view/text_tests.rs +++ b/codex-rs/tui/src/transcript_view/text_tests.rs @@ -113,7 +113,7 @@ fn selection_highlights_wide_graphemes_without_trailing_padding() { #[test] fn selected_newlines_respect_wrapping_and_synthetic_rows() { - for (width, expected) in [(8, vec![(2, 2), (6, 5), (2, 6)]), (4, vec![(2, 2), (2, 7)])] { + for (width, expected) in [(8, vec![(6, 5)]), (4, vec![])] { let layout = TextLayout::new( vec!["".into(), "alpha beta ".into(), "".into(), "界".into()], width, diff --git a/codex-rs/tui/src/transcript_view/turn_tip.rs b/codex-rs/tui/src/transcript_view/turn_tip.rs new file mode 100644 index 0000000000..854bef6adf --- /dev/null +++ b/codex-rs/tui/src/transcript_view/turn_tip.rs @@ -0,0 +1,59 @@ +//! Reserve a temporary tip before completion metadata, outside selectable source text. +//! Return its final draw area only when at least one response row remains visible. + +use super::*; +use crate::turn_tip::TurnTip; + +impl TranscriptView { + pub(crate) fn render_with_turn_tip_space( + &mut self, + area: Rect, + buf: &mut Buffer, + cells: &[Arc], + tip: Option<&TurnTip>, + ) -> Option { + let tip = tip.filter(|_| area.height > 1); + self.turn_tip_key = tip.and_then(|_| { + cells + .last() + .filter(|cell| { + cell.as_any() + .is::() + && !cell.display_lines(area.width).is_empty() + }) + .map(EntryKey::cell) + }); + self.render( + Rect { + height: area.height - u16::from(tip.is_some() && self.turn_tip_key.is_none()), + ..area + }, + buf, + cells, + ); + // The final viewport includes prompt-header and footer reservations. Let the tip yield + // rather than leave only completion metadata visible on a short terminal. + if let Some(key) = self.turn_tip_key + && self.visible.first().is_none_or(|row| row.key == key) + { + self.turn_tip_key = None; + self.render(area, buf, cells); + return None; + } + tip?; + let row = match self.turn_tip_key { + Some(key) => self + .visible + .iter() + .position(|row| row.key == key && row.row == 0)?, + None => self.visible.len(), + }; + let y = self.area.y.saturating_add(row as u16); + (self.tail_visible && !self.visible.is_empty() && y < area.bottom()).then_some(Rect::new( + self.area.x, + y, + self.area.width, + /*height*/ 1, + )) + } +} diff --git a/codex-rs/tui/src/transcript_view_tests.rs b/codex-rs/tui/src/transcript_view_tests.rs index c9b68b0dc5..b1e1940847 100644 --- a/codex-rs/tui/src/transcript_view_tests.rs +++ b/codex-rs/tui/src/transcript_view_tests.rs @@ -63,6 +63,60 @@ pub(super) fn text(buffer: &Buffer) -> String { .join("\n") } +#[test] +fn startup_warning_keeps_first_visible_header_in_place() { + let header: Arc = + Arc::new(crate::history_cell::SessionHeaderHistoryCell::new( + "gpt-test".into(), + /*reasoning_effort*/ None, + /*show_fast_status*/ false, + crate::test_support::test_path_buf("/project"), + "test", + )); + let mut view = TranscriptView::default(); + view.sync_live_tail(/*width*/ 80, /*key*/ None, |width| { + Some(header.compact_hyperlink_lines(width)) + }); + let mut cells = Vec::new(); + let before = render(&mut view, &cells, /*width*/ 80, /*height*/ 24); + cells.push(Arc::new(crate::history_cell::StartupWarningsCell::new(vec![ + "Skill manifest is invalid.".into(), + ])) as Arc); + assert_eq!( + render(&mut view, &cells, /*width*/ 80, /*height*/ 24), + before + ); + view.sync_live_tail(/*width*/ 80, /*key*/ None, |_| None); + cells.insert(/*index*/ 0, header); + assert_eq!( + render(&mut view, &cells, /*width*/ 80, /*height*/ 24), + before + ); + assert_eq!(crate::history_cell::warning_count(&cells), 1); +} + +#[test] +fn hidden_initial_entries_do_not_add_a_separator_but_visible_entries_do() { + let cells = vec![cell(""), cell(""), cell("First"), cell(""), cell("Second")]; + let mut view = TranscriptView::default(); + view.sync_live_tail( + /*width*/ 20, + /*key*/ None, + |_| Some(vec![HyperlinkLine::from("Live")]), + ); + let frame = render(&mut view, &cells, /*width*/ 20, /*height*/ 5); + insta::assert_snapshot!(text(&frame), @" + First + + Second + + Live + "); + // Scrolling past the first visible entry must stop at its content, not its separator. + view.scroll(&cells, /*rows*/ -100); + assert_eq!(render(&mut view, &cells, /*width*/ 20, /*height*/ 5), frame); +} + #[test] fn reading_survives_prepend_and_new_output_then_returns_to_latest() { let mut cells = vec![cell("older\nline two"), cell("current\nlast line")]; diff --git a/codex-rs/tui/src/tui.rs b/codex-rs/tui/src/tui.rs index dc14abf35d..6bcd0cd6e4 100644 --- a/codex-rs/tui/src/tui.rs +++ b/codex-rs/tui/src/tui.rs @@ -604,11 +604,12 @@ pub enum TuiEvent { FocusLost, } -/// The overlay requesting pointer reports; ordinary pickers retain alternate-scroll input. +/// The current screen's pointer policy; ordinary pickers retain alternate-scroll input. #[derive(Clone, Copy, Default, PartialEq, Eq)] pub(crate) enum OverlayInput { #[default] Default, + Onboarding, Transcript, StaticPager, Usage, @@ -618,7 +619,7 @@ impl OverlayInput { fn captures_mouse(self, owned_screen: bool) -> bool { match self { Self::Default => owned_screen, - Self::StaticPager => false, + Self::Onboarding | Self::StaticPager => false, Self::Transcript | Self::Usage => true, } } @@ -651,7 +652,7 @@ pub struct Tui { alt_screen_enabled: bool, // Keep the alternate screen alive when an overlay closes. owned_screen: bool, - overlay_input: OverlayInput, + pub(crate) overlay_input: OverlayInput, // Copies and native ownership survive closing an overlay or startup picker. pub(crate) clipboard: crate::clipboard_copy::worker::ClipboardWorker, // Keeps unmanaged process stderr writes out of the inline viewport. diff --git a/codex-rs/tui/src/tui/alternate_screen_tests.rs b/codex-rs/tui/src/tui/alternate_screen_tests.rs index 2be750edd2..28d283e35f 100644 --- a/codex-rs/tui/src/tui/alternate_screen_tests.rs +++ b/codex-rs/tui/src/tui/alternate_screen_tests.rs @@ -35,12 +35,18 @@ fn refreshed_mouse_policy_applies_to_fullscreen_and_overlays() { for next in [ OverlayInput::Transcript, OverlayInput::Usage, - OverlayInput::StaticPager, + OverlayInput::Onboarding, OverlayInput::Default, + OverlayInput::StaticPager, ] { input.apply(&screen, &mut output, next, owned).unwrap(); terminal.process(&std::mem::take(&mut output)); - let expected = if !disabled && next.captures_mouse(owned) { + let capture = match next { + OverlayInput::Default => owned, + OverlayInput::Transcript | OverlayInput::Usage => true, + OverlayInput::StaticPager | OverlayInput::Onboarding => false, + }; + let expected = if !disabled && capture { vt100::MouseProtocolMode::AnyMotion } else { vt100::MouseProtocolMode::None diff --git a/codex-rs/tui/src/tui_startup_tests.rs b/codex-rs/tui/src/tui_startup_tests.rs index a335ca9785..b0e27aa648 100644 --- a/codex-rs/tui/src/tui_startup_tests.rs +++ b/codex-rs/tui/src/tui_startup_tests.rs @@ -211,6 +211,7 @@ async fn startup_typeahead_pty_child() { use_alt_screen: false, transcript_mode: crate::transcript_mode::TranscriptMode::Terminal, status_line_enabled: true, + welcome_motion: crate::motion::MotionMode::Animated, keymap: crate::keymap::RuntimeKeymap::defaults(), disable_paste_burst: false, }, diff --git a/codex-rs/tui/src/turn_tip.rs b/codex-rs/tui/src/turn_tip.rs new file mode 100644 index 0000000000..2005a9a859 --- /dev/null +++ b/codex-rs/tui/src/turn_tip.rs @@ -0,0 +1,32 @@ +//! One expendable tip row shared by working status and completed-response presentation. +//! Drawing records exposure; measuring or clipping the row does not. + +use std::cell::Cell; + +use ratatui::buffer::Buffer; +use ratatui::layout::Rect; +use ratatui::style::Style; +use ratatui::widgets::Widget; + +use crate::render::renderable::Renderable; +use crate::terminal_hyperlinks::HyperlinkLine; +use crate::terminal_hyperlinks::HyperlinkParagraph; + +pub(crate) struct TurnTip { + pub(crate) line: HyperlinkLine, + pub(crate) rendered: Cell, +} + +impl Renderable for TurnTip { + fn render(&self, area: Rect, buf: &mut Buffer) { + if !area.is_empty() && self.line.width() <= usize::from(area.width) { + HyperlinkParagraph::new(std::slice::from_ref(&self.line), Style::default()) + .render(Rect { height: 1, ..area }, buf); + self.rendered.set(/*val*/ true); + } + } + + fn desired_height(&self, width: u16) -> u16 { + u16::from(self.line.width() <= usize::from(width)) + } +} diff --git a/codex-rs/utils/pty/src/child_command.rs b/codex-rs/utils/pty/src/child_command.rs index c245653a95..26d053acca 100644 --- a/codex-rs/utils/pty/src/child_command.rs +++ b/codex-rs/utils/pty/src/child_command.rs @@ -4,6 +4,7 @@ //! change settings that the native backend cannot inspect. Children receive only //! explicitly supplied environment variables and default to kill-on-drop. Stdio, //! descriptor inheritance, and compatibility fallbacks are configured independently. +//! Windows children communicate over pipes and never allocate a console window. //! Original Unix inputs retain their NUL validation even when std replaces them. use std::ffi::OsStr; @@ -12,6 +13,10 @@ use std::ffi::OsString; use std::io; use std::path::Path; use std::process::Stdio as TokioStdio; +#[cfg(windows)] +use winapi::um::winbase::CREATE_NO_WINDOW; +#[cfg(windows)] +use winapi::um::winbase::CREATE_SUSPENDED; use crate::child::Child; use crate::child::ChildKind; @@ -98,6 +103,8 @@ impl Command { .stdin(TokioStdio::piped()) .stdout(TokioStdio::piped()) .stderr(TokioStdio::piped()); + #[cfg(windows)] + inner.creation_flags(CREATE_NO_WINDOW); Self { inner, #[cfg(unix)] @@ -233,10 +240,19 @@ impl Command { self } + /// Set the Windows process creation flags, replacing any previously selected flags. + #[cfg(windows)] + pub fn creation_flags(&mut self, flags: u32) -> &mut Self { + self.inner.creation_flags(flags); + self + } /// Preserve Job Object assignment before the child begins executing on Windows. #[cfg(windows)] pub fn prepare_suspended_spawn(&mut self, job: &crate::JobObject) { job.prepare_suspended_spawn(&mut self.inner); + // Tokio's creation_flags replaces, rather than adds to, the flags. + self.inner + .creation_flags(CREATE_NO_WINDOW | CREATE_SUSPENDED); } /// Reject original inputs that std replaced with a NUL-free placeholder. diff --git a/codex-rs/utils/pty/src/windows_tests.rs b/codex-rs/utils/pty/src/windows_tests.rs index 70c8b269fa..6d6c389b14 100644 --- a/codex-rs/utils/pty/src/windows_tests.rs +++ b/codex-rs/utils/pty/src/windows_tests.rs @@ -5,14 +5,17 @@ use super::wait_for_output_contains; use crate::TerminalSize; use crate::spawn_pipe_process_no_stdin; use crate::spawn_pty_process; +use pretty_assertions::assert_eq; use std::collections::HashMap; use std::os::windows::io::AsRawHandle; use std::os::windows::io::FromRawHandle; use std::os::windows::io::OwnedHandle; +use std::os::windows::process::CommandExt; use std::path::Path; use std::process::Stdio; use std::time::Duration; use tokio::io::AsyncBufReadExt; +use tokio::io::AsyncWriteExt; use tokio::io::BufReader; use tokio::process::Command; use winapi::um::jobapi::IsProcessInJob; @@ -22,6 +25,70 @@ use winapi::um::winnt::PROCESS_QUERY_LIMITED_INFORMATION; const READY_MARKER: &str = "__CODEX_CHILD_READY__"; const VALUE_MARKER: &str = "__CODEX_CHILD_VALUE__"; +#[tokio::test] +async fn piped_child_has_no_console_with_or_without_job_containment() -> anyhow::Result<()> { + // Nextest itself can run without a visible console. Re-execute this test + // detached, like app-server-daemon, so children cannot inherit its console. + if std::env::var_os("CODEX_PTY_DETACHED_CONSOLE_PROBE").is_none() { + let output = std::process::Command::new(std::env::current_exe()?) + .args([ + "--exact", + "tests::windows_tests::piped_child_has_no_console_with_or_without_job_containment", + "--nocapture", + ]) + .env("CODEX_PTY_DETACHED_CONSOLE_PROBE", "1") + .creation_flags(winapi::um::winbase::DETACHED_PROCESS) + .output()?; + anyhow::ensure!( + output.status.success(), + "detached probe failed:\n{}\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr), + ); + return Ok(()); + } + let Some(python) = find_python() else { + eprintln!("python not found; skipping Windows pipe console test"); + return Ok(()); + }; + let job = crate::JobObject::create_without_breakaway()?; + for containment in [None, Some(&job)] { + let mut command = crate::Command::new(&python); + command.envs(std::env::vars()).args([ + "-u", + "-c", + "import ctypes,sys; print(ctypes.windll.kernel32.GetConsoleWindow()); print(sys.stdin.readline().strip())", + ]); + if let Some(job) = containment { + command.prepare_suspended_spawn(job); + } + let mut child = command.spawn()?; + if let Some(job) = containment { + let pid = child + .id() + .ok_or_else(|| anyhow::anyhow!("missing child pid"))?; + anyhow::ensure!(job.assign_and_resume_process(pid)?, "job assignment failed"); + } + child + .stdin + .as_mut() + .unwrap() + .write_all(b"stdio works\n") + .await?; + let output = + tokio::time::timeout(Duration::from_secs(10), child.wait_with_output()).await??; + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!( + String::from_utf8(output.stdout)?.replace("\r\n", "\n"), + "0\nstdio works\n" + ); + } + Ok(()) +} struct WindowsShell { name: &'static str, program: String,