Lightweight coding agent that runs in your terminal
Rust
Suppress repeated turn diffs in `codex exec` human output (#53444)
Felipe Couryc308e127e0e8
diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lockindex 945d4c0b42..0b2fcef1f6 100644--- a/codex-rs/Cargo.lock+++ b/codex-rs/Cargo.lock@@ -3197,6 +3197,7 @@ dependencies = ["codex-utils-sandbox-summary","codex-worktree","core_test_support",+ "insta","libc","opentelemetry","opentelemetry_sdk",diff --git a/codex-rs/exec/Cargo.toml b/codex-rs/exec/Cargo.tomlindex 42a75a0532..d5190c2caa 100644--- a/codex-rs/exec/Cargo.toml+++ b/codex-rs/exec/Cargo.toml@@ -71,6 +71,7 @@ assert_cmd = { workspace = true }codex-apply-patch = { workspace = true }codex-utils-cargo-bin = { workspace = true }core_test_support = { workspace = true }+insta = { workspace = true }libc = { workspace = true }opentelemetry = { workspace = true }opentelemetry_sdk = { workspace = true }diff --git a/codex-rs/exec/src/event_processor_with_human_output.rs b/codex-rs/exec/src/event_processor_with_human_output.rsindex 222bc485ab..37f1a04795 100644--- a/codex-rs/exec/src/event_processor_with_human_output.rs+++ b/codex-rs/exec/src/event_processor_with_human_output.rs@@ -37,6 +37,7 @@ pub(crate) struct EventProcessorWithHumanOutput {final_message_rendered: bool,emit_final_message_on_shutdown: bool,last_total_token_usage: Option<ThreadTokenUsage>,+ last_turn_diff: String,}impl EventProcessorWithHumanOutput {@@ -62,6 +63,7 @@ impl EventProcessorWithHumanOutput {final_message_rendered: false,emit_final_message_on_shutdown: false,last_total_token_usage: None,+ last_turn_diff: String::new(),}}@@ -341,9 +343,12 @@ impl EventProcessor for EventProcessorWithHumanOutput {TurnStatus::InProgress => CodexStatus::Running,},ServerNotification::TurnDiffUpdated(notification) => {- if !notification.diff.trim().is_empty() {+ if notification.diff != self.last_turn_diff && !notification.diff.trim().is_empty()+ {eprintln!("{}", notification.diff);}+ // Remember empty updates too, so a restored diff is rendered again.+ self.last_turn_diff = notification.diff;CodexStatus::Running}ServerNotification::TurnPlanUpdated(notification) => {@@ -369,7 +374,10 @@ impl EventProcessor for EventProcessorWithHumanOutput {}CodexStatus::Running}- ServerNotification::TurnStarted(_) => CodexStatus::Running,+ ServerNotification::TurnStarted(_) => {+ self.last_turn_diff.clear();+ CodexStatus::Running+ }_ => CodexStatus::Running,}}diff --git a/codex-rs/exec/src/event_processor_with_human_output_tests.rs b/codex-rs/exec/src/event_processor_with_human_output_tests.rsindex 594cd5b157..c16e505ce0 100644--- a/codex-rs/exec/src/event_processor_with_human_output_tests.rs+++ b/codex-rs/exec/src/event_processor_with_human_output_tests.rs@@ -28,6 +28,109 @@ use super::should_print_final_message_to_stdout;use super::should_print_final_message_to_tty;use crate::event_processor::EventProcessor;+#[test]+fn turn_diff_notifications_render_only_changes() -> anyhow::Result<()> {+ const CHILD: &str = "CODEX_EXEC_TURN_DIFF_TEST_CHILD";+ if std::env::var_os(CHILD).is_none() {+ // Capture stderr in a child so other tests cannot interfere with rendering.+ let output = std::process::Command::new(std::env::current_exe()?)+ .args([+ "--exact",+ "event_processor_with_human_output::tests::turn_diff_notifications_render_only_changes",+ "--nocapture",+ ])+ .env(CHILD, "1")+ .output()?;+ assert!(output.status.success(), "{output:?}");+ assert!(String::from_utf8_lossy(&output.stdout).contains("1 passed"));+ insta::assert_snapshot!(String::from_utf8(output.stderr)?, @r"+ turn-1+ @@ -1 +1 @@+ -value=1+ +value=2+ @@ -1 +1 @@+ -value=1+ +value=3+ @@ -1 +1 @@+ -value=1+ +value=2+ @@ -1 +1 @@+ -value=1+ +value=2+ @@ -1 +1 @@+ -value=1+ +value=2+ turn-2+ @@ -1 +1 @@+ -value=1+ +value=2+ ");+ return Ok(());+ }++ let mut processor = EventProcessorWithHumanOutput {+ bold: Style::new(),+ cyan: Style::new(),+ dimmed: Style::new(),+ green: Style::new(),+ italic: Style::new(),+ magenta: Style::new(),+ red: Style::new(),+ yellow: Style::new(),+ show_agent_reasoning: true,+ show_raw_agent_reasoning: false,+ last_message_path: None,+ final_message: None,+ final_message_rendered: false,+ emit_final_message_on_shutdown: false,+ last_total_token_usage: None,+ last_turn_diff: String::new(),+ };+ let first = "@@ -1 +1 @@\n-value=1\n+value=2";+ let changed = "@@ -1 +1 @@\n-value=1\n+value=3";+ for (turn_id, diffs) in [+ // Repeated updates are quiet, but changed and restored diffs still print.+ (+ "turn-1",+ vec![+ "", " \n", first, first, changed, changed, first, "", first, " \n", first,+ ],+ ),+ ("turn-2", vec![first, first]),+ ] {+ processor.process_server_notification(ServerNotification::TurnStarted(+ codex_app_server_protocol::TurnStartedNotification {+ thread_id: "thread-1".to_string(),+ turn: Turn {+ id: turn_id.to_string(),+ root_turn_id: None,+ items_view: codex_app_server_protocol::TurnItemsView::Full,+ items: Vec::new(),+ status: TurnStatus::InProgress,+ error: None,+ started_at: None,+ completed_at: None,+ duration_ms: None,+ },+ },+ ));+ eprintln!("{turn_id}");+ for diff in diffs {+ assert_eq!(+ processor.process_server_notification(ServerNotification::TurnDiffUpdated(+ codex_app_server_protocol::TurnDiffUpdatedNotification {+ thread_id: "thread-1".to_string(),+ turn_id: turn_id.to_string(),+ diff: diff.to_string(),+ },+ )),+ crate::event_processor::CodexStatus::Running+ );+ }+ }+ Ok(())+}+#[test]fn suppresses_final_stdout_message_when_both_streams_are_terminals() {assert!(!should_print_final_message_to_stdout(@@ -313,6 +416,7 @@ fn turn_completed_recovers_final_message_from_turn_items() {final_message_rendered: false,emit_final_message_on_shutdown: false,last_total_token_usage: None,+ last_turn_diff: String::new(),};let status = processor.process_server_notification(ServerNotification::TurnCompleted(@@ -364,6 +468,7 @@ fn turn_completed_overwrites_stale_final_message_from_turn_items() {final_message_rendered: true,emit_final_message_on_shutdown: false,last_total_token_usage: None,+ last_turn_diff: String::new(),};let status = processor.process_server_notification(ServerNotification::TurnCompleted(@@ -416,6 +521,7 @@ fn turn_completed_preserves_streamed_final_message_when_turn_items_are_empty() {final_message_rendered: false,emit_final_message_on_shutdown: false,last_total_token_usage: None,+ last_turn_diff: String::new(),};let status = processor.process_server_notification(ServerNotification::TurnCompleted(@@ -461,6 +567,7 @@ fn turn_failed_clears_stale_final_message() {final_message_rendered: true,emit_final_message_on_shutdown: true,last_total_token_usage: None,+ last_turn_diff: String::new(),};let status = processor.process_server_notification(ServerNotification::TurnCompleted(@@ -507,6 +614,7 @@ fn turn_interrupted_clears_stale_final_message() {final_message_rendered: true,emit_final_message_on_shutdown: true,last_total_token_usage: None,+ last_turn_diff: String::new(),};let status = processor.process_server_notification(ServerNotification::TurnCompleted(diff --git a/codex-rs/exec/tests/suite/apply_patch.rs b/codex-rs/exec/tests/suite/apply_patch.rsindex 66c485d02b..112e29122b 100644--- a/codex-rs/exec/tests/suite/apply_patch.rs+++ b/codex-rs/exec/tests/suite/apply_patch.rs@@ -4,6 +4,7 @@ use anyhow::Context;use assert_cmd::prelude::*;use codex_apply_patch::CODEX_CORE_APPLY_PATCH_ARG1;use core_test_support::responses::ev_apply_patch_custom_tool_call;+use core_test_support::responses::ev_assistant_message;use core_test_support::responses::ev_completed;use core_test_support::responses::ev_exec_command_call_with_args;use core_test_support::responses::mount_sse_sequence;@@ -94,6 +95,112 @@ async fn test_apply_patch_tool() -> anyhow::Result<()> {Ok(())}+#[cfg(unix)]+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]+async fn human_output_prints_unchanged_turn_diff_once() -> anyhow::Result<()> {+ use core_test_support::skip_if_no_network;+ use core_test_support::test_codex_exec::test_codex_exec;++ skip_if_no_network!(Ok(()));++ let test = test_codex_exec();+ let run_dir = test.cwd_path();+ Command::new("git")+ .args(["init", "--quiet"])+ .current_dir(run_dir)+ .assert()+ .success();+ fs::write(run_dir.join("probe.txt"), "value=1\n")?;+ Command::new("git")+ .args(["add", "probe.txt"])+ .current_dir(run_dir)+ .assert()+ .success();+ Command::new("git")+ .args([+ "-c",+ "user.name=Reproducer",+ "-c",+ "[email protected]",+ "commit",+ "--quiet",+ "-m",+ "baseline",+ ])+ .current_dir(run_dir)+ .assert()+ .success();++ // Replay the reported single edit, unrelated command, and final response.+ let server = start_mock_server().await;+ let mock = mount_sse_sequence(+ &server,+ vec![+ sse(vec![+ ev_apply_patch_custom_tool_call(+ "patch",+ "*** Begin Patch\n*** Update File: probe.txt\n@@\n-value=1\n+value=2\n*** End Patch",+ ),+ ev_completed("response-1"),+ ]),+ sse(vec![+ ev_exec_command_call_with_args(+ "command",+ &serde_json::json!({+ "cmd": "printf 'DIAG_CMD_OK\\n'",+ "shell": "/bin/sh",+ "login": false,+ "yield_time_ms": 10_000,+ }),+ ),+ ev_completed("response-2"),+ ]),+ sse(vec![+ ev_assistant_message("message", "DIAG_DONE"),+ ev_completed("response-3"),+ ]),+ ],+ )+ .await;+ let result = test+ .cmd_with_server(&server)+ .args([+ "--ephemeral",+ "--color",+ "never",+ "-s",+ "danger-full-access",+ "-c",+ "features.hooks=false",+ "-c",+ "features.shell_snapshot=false",+ "-c",+ "features.shell_snapshot_v2=false",+ "Replace value=1 with value=2 once, print DIAG_CMD_OK, then finish with DIAG_DONE.",+ ])+ .assert()+ .success()+ .stdout("DIAG_DONE\n");+ let stderr = String::from_utf8_lossy(&result.get_output().stderr);+ assert_eq!(fs::read_to_string(run_dir.join("probe.txt"))?, "value=2\n");+ assert_eq!(mock.requests().len(), 3);+ assert_eq!(stderr.matches("patch: completed").count(), 1, "{stderr}");+ assert_eq!(+ stderr.lines().filter(|line| *line == "DIAG_CMD_OK").count(),+ 1,+ "{stderr}"+ );+ assert_eq!(+ stderr+ .lines()+ .filter(|line| *line == "diff --git a/probe.txt b/probe.txt")+ .count(),+ 1,+ "{stderr}"+ );+ Ok(())+}+#[cfg(unix)]#[tokio::test(flavor = "multi_thread", worker_threads = 4)]async fn nested_apply_patch_alias_works_with_restricted_reads() -> anyhow::Result<()> {