From 3da5a55b5b0b78ce71b2e610113e7509f4105845 Mon Sep 17 00:00:00 2001 From: jif Date: Tue, 1 Dec 2026 16:38:42 +0000 Subject: [PATCH] Abort pending terminal writes when their turn is cancelled (#65036) ## Why A `write_stdin` call can resume after its turn is cancelled if approval was still pending. It can then send stale input to a running terminal or consume the final output of a remote process that has already exited. ## What changed After approval, check both tool-call and turn cancellation before a non-empty `write_stdin` request can send input or drain output. Report cancelled writes as aborted and surface the abort as an error to Code Mode cells that are still running. Empty polls can still collect buffered output. ## Testing Regression tests cover cancellation during stdin approval for direct and Code Mode calls, reuse of the same terminal on the next turn, and retrieval of final remote output after a cancelled write. GitOrigin-RevId: 735bdd7ed0e892467647039ba72eb9a4d177a560 --- codex-rs/core/src/tools/code_mode/mod.rs | 18 +- codex-rs/core/src/tools/context.rs | 6 + .../handlers/unified_exec/write_stdin.rs | 35 ++-- codex-rs/core/src/tools/parallel.rs | 12 +- .../core/src/unified_exec/process_manager.rs | 18 +- .../src/unified_exec/process_manager_tests.rs | 29 ++- .../suite/network_approval_completion.rs | 195 +++++++++++++++++- 7 files changed, 281 insertions(+), 32 deletions(-) diff --git a/codex-rs/core/src/tools/code_mode/mod.rs b/codex-rs/core/src/tools/code_mode/mod.rs index 4bbc55c3f2..5b4c45a0c7 100644 --- a/codex-rs/core/src/tools/code_mode/mod.rs +++ b/codex-rs/core/src/tools/code_mode/mod.rs @@ -430,6 +430,8 @@ fn submit_nested_tool( .config .features .enabled(Feature::CodeModeMcpResultDedup); + let is_write_stdin = + call.tool_name.is_default_namespace() && call.tool_name.name == "write_stdin"; let result = tool_runtime.handle_tool_call_with_source( step_context, call, @@ -441,12 +443,18 @@ fn submit_nested_tool( Arc::default(), ); Ok(async move { - Ok(match result.await?.code_mode_result() { - CodeModeToolResult::McpCallToolResult(value) if !dedup_mcp_result => { - CodeModeToolResult::Json(value) + let output = result.await?; + let stdin_aborted = is_write_stdin && output.result.was_aborted(); + match output.code_mode_result() { + // A surviving cell must not treat the abort message as a successful write. + CodeModeToolResult::Json(JsonValue::String(message)) if stdin_aborted => { + Err(FunctionCallError::RespondToModel(message)) } - result => result, - }) + CodeModeToolResult::McpCallToolResult(value) if !dedup_mcp_result => { + Ok(CodeModeToolResult::Json(value)) + } + result => Ok(result), + } }) } diff --git a/codex-rs/core/src/tools/context.rs b/codex-rs/core/src/tools/context.rs index 419d2362f8..1963b2ec27 100644 --- a/codex-rs/core/src/tools/context.rs +++ b/codex-rs/core/src/tools/context.rs @@ -421,6 +421,12 @@ pub struct AbortedToolOutput { } impl AbortedToolOutput { + pub(crate) fn user(secs: f32) -> Self { + Self { + message: format!("aborted by user after {secs:.1}s"), + } + } + pub(crate) fn exec_command(secs: f32) -> Self { Self { message: format!("Wall time: {secs:.1} seconds\naborted by user"), diff --git a/codex-rs/core/src/tools/handlers/unified_exec/write_stdin.rs b/codex-rs/core/src/tools/handlers/unified_exec/write_stdin.rs index 22db0569dc..40c7e323a4 100644 --- a/codex-rs/core/src/tools/handlers/unified_exec/write_stdin.rs +++ b/codex-rs/core/src/tools/handlers/unified_exec/write_stdin.rs @@ -1,4 +1,5 @@ use crate::function_tool::FunctionCallError; +use crate::tools::context::AbortedToolOutput; use crate::tools::context::ToolEnvironments; use crate::tools::context::ToolInvocation; use crate::tools::context::ToolPayload; @@ -84,13 +85,14 @@ impl WriteStdinHandler { )); }; let args = WriteStdinArgs::parse(&payload)?; + let started = std::time::Instant::now(); let context = UnifiedExecContext::new( session.clone(), step_context, cancellation_token, call_id.into(), ); - let response = session + let result = session .services .unified_exec_manager .write_stdin( @@ -112,21 +114,22 @@ impl WriteStdinHandler { }), }, ) - .await - .map_err(|err| { - let message = match err { - UnifiedExecError::StdinApproval(ToolError::Rejected(reason)) => { - format!("write_stdin rejected: {reason}") - } - UnifiedExecError::StdinApproval(ToolError::Codex(err)) => { - format!("write_stdin approval failed: {err}") - } - err => format!("write_stdin failed: {err}"), - }; - FunctionCallError::RespondToModel(message) - })?; - - Ok(boxed_tool_output(response)) + .await; + let message = match result { + Ok(response) => return Ok(boxed_tool_output(response)), + Err(UnifiedExecError::Cancelled) => { + let secs = started.elapsed().as_secs_f32().max(0.1); + return Ok(boxed_tool_output(AbortedToolOutput::user(secs))); + } + Err(UnifiedExecError::StdinApproval(ToolError::Rejected(reason))) => { + format!("write_stdin rejected: {reason}") + } + Err(UnifiedExecError::StdinApproval(ToolError::Codex(err))) => { + format!("write_stdin approval failed: {err}") + } + Err(err) => format!("write_stdin failed: {err}"), + }; + Err(FunctionCallError::RespondToModel(message)) } } diff --git a/codex-rs/core/src/tools/parallel.rs b/codex-rs/core/src/tools/parallel.rs index ba539d99e7..2592f35d40 100644 --- a/codex-rs/core/src/tools/parallel.rs +++ b/codex-rs/core/src/tools/parallel.rs @@ -528,20 +528,22 @@ impl ToolCallRuntime { } fn stopped_response(call: &ToolCall, stop: ToolAbort) -> AnyToolResult { - let message = match stop { - ToolAbort::BeforeDispatch => "aborted before dispatch".to_string(), + let output = match stop { + ToolAbort::BeforeDispatch => AbortedToolOutput { + message: "aborted before dispatch".to_string(), + }, ToolAbort::User(secs) if call.tool_name.is_default_namespace() && call.tool_name.name == "exec_command" => { - AbortedToolOutput::exec_command(secs).message + AbortedToolOutput::exec_command(secs) } - ToolAbort::User(secs) => format!("aborted by user after {secs:.1}s"), + ToolAbort::User(secs) => AbortedToolOutput::user(secs), }; AnyToolResult { call_id: call.call_id.clone(), payload: call.payload.clone(), - result: Box::new(AbortedToolOutput { message }), + result: Box::new(output), post_tool_use_payload: None, } } diff --git a/codex-rs/core/src/unified_exec/process_manager.rs b/codex-rs/core/src/unified_exec/process_manager.rs index 4d485215c2..43689f4422 100644 --- a/codex-rs/core/src/unified_exec/process_manager.rs +++ b/codex-rs/core/src/unified_exec/process_manager.rs @@ -940,6 +940,7 @@ impl UnifiedExecProcessManager { let outcome = match &result { Ok(output) if output.process_id.is_some() => "yielded", Ok(_) => "exited", + Err(UnifiedExecError::Cancelled) => "cancelled", Err(_) if context.cancellation_token.is_cancelled() => "cancelled", Err(_) => "failed", }; @@ -1056,10 +1057,19 @@ impl UnifiedExecProcessManager { &context.call_id, &call_id, ); + // A Code Mode callback can outlive its turn while approval is pending. + // Cancel before a write can consume the final output of an exited remote process. + let has_input = !request.input.is_empty(); + if has_input + && (context.cancellation_token.is_cancelled() + || context.step_context.turn_cancellation.is_cancelled()) + { + return Err(UnifiedExecError::Cancelled); + } + let remote_exited = process.has_exited() && output.drain_policy == OutputDrainPolicy::WaitForOutputClosure; - // A write racing with remote exit still collects the final output. - if !request.input.is_empty() && !remote_exited { + if has_input && !remote_exited { if !tty { if request.input == INTERRUPT { process.interrupt().await?; @@ -1090,7 +1100,7 @@ impl UnifiedExecProcessManager { // Empty polls use configurable background timeout bounds. Non-empty // writes keep a fixed max cap so interactive stdin remains responsive. let time_ms = request.yield_time_ms.max(MIN_YIELD_TIME_MS); - if request.input.is_empty() { + if !has_input { time_ms.clamp(MIN_EMPTY_YIELD_TIME_MS, self.max_write_stdin_yield_time_ms) } else { time_ms.min(MAX_YIELD_TIME_MS) @@ -1167,7 +1177,7 @@ impl UnifiedExecProcessManager { tool_cwd, }; - let should_emit_interaction = !request.input.is_empty() || response.process_id.is_some(); + let should_emit_interaction = has_input || response.process_id.is_some(); if should_emit_interaction && let Some(WriteStdinInteractionEvent { session, turn }) = request.interaction_event { diff --git a/codex-rs/core/src/unified_exec/process_manager_tests.rs b/codex-rs/core/src/unified_exec/process_manager_tests.rs index 5b71b00afb..9997e3bcfb 100644 --- a/codex-rs/core/src/unified_exec/process_manager_tests.rs +++ b/codex-rs/core/src/unified_exec/process_manager_tests.rs @@ -581,7 +581,7 @@ async fn late_network_denial_grace_observes_cancellation_after_exit() -> anyhow: } #[tokio::test(start_paused = true)] -async fn dropping_a_registered_remote_process_uses_normal_termination() { +async fn cancelled_write_after_remote_exit_preserves_output_and_normal_cleanup() { let (session, turn, _events) = crate::session::tests::make_session_and_context_with_rx().await; let manager = &session.services.unified_exec_manager; let context = UnifiedExecContext::new( @@ -637,6 +637,33 @@ async fn dropping_a_registered_remote_process_uses_normal_termination() { process.write(b"input").await, Err(UnifiedExecError::WriteToStdin) )); + process + .output_handles() + .output_buffer + .lock() + .await + .push_chunk(ExecOutputStream::Stdout, b"final output"); + + // A surviving Code Mode call still has a live call token after its turn is cancelled. + let terminal = manager.resolve_terminal(process_id).await.unwrap(); + let request = |input| WriteStdinRequest { + terminal: &terminal, + input, + yield_time_ms: MIN_YIELD_TIME_MS, + max_output_tokens: None, + truncation_policy: turn.model_info().truncation_policy.into(), + interaction_event: None, + }; + context.step_context.turn_cancellation.cancel(); + let write = manager.write_stdin(&context, request("stale")).await; + assert!( + matches!(write, Err(UnifiedExecError::Cancelled)), + "{write:?}" + ); + let poll = manager.write_stdin(&context, request("")).await.unwrap(); + assert_eq!(poll.raw_output, CapturedStream::from("final output")); + + drop(terminal); drop(process); manager.release_process_id(process_id).await; assert_eq!(observed.recv().await, Some(Cleanup::Terminate)); diff --git a/codex-rs/core/tests/suite/network_approval_completion.rs b/codex-rs/core/tests/suite/network_approval_completion.rs index 5492020390..474641938d 100644 --- a/codex-rs/core/tests/suite/network_approval_completion.rs +++ b/codex-rs/core/tests/suite/network_approval_completion.rs @@ -1,4 +1,4 @@ -//! Exercises remote network launch policy and approval cleanup at process exit. +//! Exercises network approval cleanup and interruption while command history is pending. use super::accept_initialized_exec_server; use super::read_exec_server_json; @@ -13,6 +13,8 @@ use codex_exec_server::ExecParams; use codex_extension_api::ExtensionData; use codex_extension_api::ExtensionFuture; use codex_extension_api::ExtensionRegistryBuilder; +use codex_extension_api::ToolCallOutcome; +use codex_extension_api::ToolCallSource; use codex_extension_api::ToolFinishInput; use codex_extension_api::ToolLifecycleContributor; use codex_extension_api::ToolLifecycleFuture; @@ -463,6 +465,7 @@ struct HistoryGate { decline: tokio_util::sync::CancellationToken, release: tokio_util::sync::CancellationToken, finished: Notify, + stdin_finished: tokio::sync::watch::Sender>, } impl ToolLifecycleContributor for HistoryGate { @@ -470,6 +473,9 @@ impl ToolLifecycleContributor for HistoryGate { Box::pin(async move { if input.call_id == "interrupted-startup" { self.finished.notify_one(); + } else if input.tool_name.name == "write_stdin" { + self.stdin_finished + .send_replace(Some((input.outcome, input.source))); } }) } @@ -495,6 +501,193 @@ impl TurnLifecycleContributor for HistoryGate { } } +#[test_case(false; "direct")] +#[test_case(true; "code_mode")] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn cancel_during_stdin_review_preserves_the_terminal(code_mode: bool) -> Result<()> { + use codex_features::Feature; + use core_test_support::fs_wait::wait_for_path_exists; + use core_test_support::responses::ev_custom_tool_call; + use core_test_support::responses::mount_sse_sequence; + + core_test_support::skip_if_host_windows!(Ok(())); + core_test_support::skip_if_no_network!(Ok(())); + core_test_support::skip_if_sandbox!(Ok(())); + let gate = Arc::new(HistoryGate::default()); + let mut stdin_finished = gate.stdin_finished.subscribe(); + let mut extensions = ExtensionRegistryBuilder::new(); + extensions.turn_lifecycle_contributor(gate.clone()); + extensions.tool_lifecycle_contributor(gate.clone()); + let server = start_mock_server().await; + let hook = TcpListener::bind("127.0.0.1:0").await?; + let port = hook.local_addr()?.port(); + let test = test_codex() + .with_extensions(Arc::new(extensions.build())) + .with_history_mode(ThreadHistoryMode::Paginated) + .with_pre_build_hook(move |home| { + let command = format!( + r#"python3 -c 'import socket, sys +sys.stdin.read() +with socket.create_connection(("127.0.0.1", {port})) as gate: + print(gate.makefile().read())'"# + ); + let hooks = json!({"PermissionRequest": [{ + "matcher": "^write_stdin$", + "hooks": [{"type": "command", "command": command}], + }]}); + fs::write(home.join("hooks.json"), json!({"hooks": hooks}).to_string()) + .expect("install stdin permission hook"); + }) + .with_config(move |config| { + core_test_support::hooks::trust_discovered_hooks(config); + config.approvals_reviewer = ApprovalsReviewer::User; + if code_mode { + config + .features + .enable(Feature::CodeMode) + .expect("enable Code Mode"); + // Keep the callback live after the originating turn is cancelled. + config + .features + .disable(Feature::CodeModeInterrupt) + .expect("disable cell interruption"); + } + }) + // The permission hook connects to the test's loopback listener. + .build(&server) + .await?; + + // Publish the first line atomically, even if history is still blocked. + let terminal = ev_exec_command_call_with_args( + "shell", + &json!({ + "cmd": r#"read -r line && echo "$line" > first.tmp && mv first.tmp first-line"#, + "tty": true, + "yield_time_ms": 250, + }), + ); + let stdin = |chars: &str| { + json!({"session_id": 1000, "chars": chars, "yield_time_ms": 5000}).to_string() + }; + let stale = stdin("stale\n"); + let mut responses = vec![ + sse(vec![terminal, ev_completed("open")]), + sse(vec![ev_completed("opened")]), + ]; + let mut batch = Vec::new(); + if code_mode { + // Let exec yield its exclusive dispatch lock before the sibling can ask for approval. + responses.push(sse(vec![ + ev_custom_tool_call( + "nested", + "exec", + &format!("yield_control(); await tools.write_stdin({stale});"), + ), + ev_completed("yielded"), + ])); + } else { + batch.push(ev_function_call("write", "write_stdin", &stale)); + } + batch.push(ev_exec_command_call_with_args( + "prompt", + &json!({ + "cmd": "echo pending", + "sandbox_permissions": "require_escalated", + "justification": "Run outside the sandbox?", + }), + )); + batch.push(ev_assistant_message("third", "Commands submitted.")); + batch.push(ev_completed("batch")); + responses.push(sse(batch)); + mount_sse_sequence(&server, responses).await; + + test.submit_turn("open a terminal").await?; + // Narrow the next turn's permissions so writing to the existing terminal needs approval. + test.codex + .start_or_steer_turn( + TurnInputRequest::user_input(vec![UserInput::Text { + text: "send input".into(), + text_elements: Vec::new(), + }]) + .with_thread_settings(ThreadSettingsOverrides { + approval_policy: Some(AskForApproval::OnRequest), + permission_profile: Some(PermissionProfile::workspace_write()), + ..Default::default() + }), + ) + .await?; + let prompt = wait_for_event_match(&test.codex, |event| match event { + EventMsg::ExecApprovalRequest(prompt) if prompt.starts_command() => Some(prompt.clone()), + _ => None, + }) + .await; + let (mut hook, _) = timeout(STARTUP_TIMEOUT, hook.accept()) + .await + .context("stdin permission hook did not start")??; + // Hold the collector so it cannot drop the pending write before the hook returns. + timeout(STARTUP_TIMEOUT, gate.recording.notified()).await?; + test.codex + .submit(Op::ExecApproval { + id: prompt.effective_approval_id(), + turn_id: Some(prompt.turn_id), + decision: ReviewDecision::Abort, + }) + .await?; + timeout(STARTUP_TIMEOUT, gate.decline.cancelled()).await?; + let allow = json!({"hookSpecificOutput": { + "hookEventName": "PermissionRequest", + "decision": {"behavior": "allow"}, + }}); + hook.write_all(allow.to_string().as_bytes()).await?; + hook.shutdown().await?; + let first_line = wait_for_path_exists(test.workspace_path("first-line"), STARTUP_TIMEOUT); + tokio::pin!(first_line); + tokio::select! { + result = stdin_finished.changed() => result?, + path = &mut first_line => anyhow::bail!("terminal received cancelled input: {}", fs::read_to_string(path?)?), + } + gate.release.cancel(); + wait_for_event(&test.codex, |event| { + matches!(event, EventMsg::TurnAborted(_)) + }) + .await; + let (outcome, source) = stdin_finished + .borrow() + .clone() + .context("missing stdin outcome")?; + assert_eq!(outcome, ToolCallOutcome::Aborted); + + let mut retry = Vec::new(); + if code_mode { + let ToolCallSource::CodeMode { cell_id, .. } = source else { + anyhow::bail!("expected a nested stdin call"); + }; + retry.push(ev_function_call( + "observe", + "wait", + &json!({"cell_id": cell_id}).to_string(), + )); + } + retry.push(ev_function_call("retry", "write_stdin", &stdin("fresh\n"))); + retry.push(ev_completed("retry")); + let mock = mount_sse_sequence(&server, vec![sse(retry), sse(vec![ev_completed("done")])]).await; + test.submit_turn("use the same terminal").await?; + assert_eq!(fs::read_to_string(first_line.await?)?, "fresh\n"); + if code_mode { + let output = mock + .last_request() + .context("missing wait result")? + .function_call_output("observe"); + assert!( + output["output"][1]["text"] + .as_str() + .is_some_and(|text| text.starts_with("Script error:\naborted by user")), + "{output}" + ); + } + Ok(()) +} + #[derive(Clone, Copy, PartialEq)] enum BlockedLookup { Metrics,