Suppress repeated turn diffs in codex exec human output (#53444)

## Why

Repeated turn diff notifications can print the same file changes multiple times, including after an unrelated command.

## What changed

Track the last diff and print nonempty updates only when they differ from the previous notification. Remember empty updates so a restored diff prints again, and reset the tracked diff when a new turn starts.

## Testing

Add a stderr snapshot test covering repeated, changed, empty, restored, and new-turn diffs. Add an integration test that applies one edit, runs an unrelated command, and verifies that the diff appears exactly once.

GitOrigin-RevId: db0a2aa8b77b800ca661e7d1314ed1e571743e74
This commit is contained in:
Felipe Coury
2026-10-12 18:21:10 +00:00
committed by copyberry
parent 3ece80b784
commit c308e127e0
5 changed files with 227 additions and 2 deletions
+1
View File
@@ -3197,6 +3197,7 @@ dependencies = [
"codex-utils-sandbox-summary",
"codex-worktree",
"core_test_support",
"insta",
"libc",
"opentelemetry",
"opentelemetry_sdk",
+1
View File
@@ -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 }
@@ -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,
}
}
@@ -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(
+107
View File
@@ -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",
"user.email=reproducer@example.invalid",
"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<()> {