From 31d2caf2b37b4b17b397c1dc8ada4712efb76730 Mon Sep 17 00:00:00 2001 From: Sayan Sisodiya Date: Tue, 23 Jun 2026 03:25:39 -0700 Subject: [PATCH] core: pin yielded code cells to request runtime --- codex-rs/core/src/tools/code_mode/delegate.rs | 143 ++++++++++-------- .../src/tools/code_mode/execute_handler.rs | 3 +- codex-rs/core/src/tools/code_mode/mod.rs | 22 +-- codex-rs/core/tests/suite/code_mode.rs | 47 +++++- 4 files changed, 130 insertions(+), 85 deletions(-) diff --git a/codex-rs/core/src/tools/code_mode/delegate.rs b/codex-rs/core/src/tools/code_mode/delegate.rs index acb4546840..08f6ff38eb 100644 --- a/codex-rs/core/src/tools/code_mode/delegate.rs +++ b/codex-rs/core/src/tools/code_mode/delegate.rs @@ -14,18 +14,23 @@ use tokio::sync::oneshot; use tokio::sync::watch; use tokio_util::sync::CancellationToken; -use super::ExecContext; use super::PUBLIC_TOOL_NAME; use super::call_nested_tool; +use crate::session::session::Session; use crate::session::step_context::StepContext; use crate::tools::ToolRouter; use crate::tools::context::SharedTurnDiffTracker; use crate::tools::parallel::ToolCallRuntime; +type CellHostSender = watch::Sender>>; +type CellHostMap = Mutex>; + pub(super) struct CodeModeDispatchBroker { dispatch_tx: async_channel::Sender, dispatch_rx: async_channel::Receiver, - dispatch_gates: Arc>>>, + dispatch_hosts: Arc, + // New cells copy this host so yielded work keeps the same tools and environment. + active_host: Arc>>>, } impl CodeModeDispatchBroker { @@ -34,30 +39,44 @@ impl CodeModeDispatchBroker { Self { dispatch_tx, dispatch_rx, - dispatch_gates: Arc::new(Mutex::new(HashMap::new())), + dispatch_hosts: Arc::new(Mutex::new(HashMap::new())), + active_host: Arc::new(Mutex::new(None)), } } - pub(super) fn mark_cell_ready_for_dispatch(&self, cell_id: &CellId) { - dispatch_gate(&self.dispatch_gates, cell_id).send_replace(true); + pub(super) fn bind_cell_to_active_host(&self, cell_id: &CellId) -> Result<(), String> { + let host = match self.active_host.lock() { + Ok(active_host) => active_host.clone(), + Err(poisoned) => poisoned.into_inner().clone(), + } + .ok_or_else(|| "code mode tool dispatcher is unavailable".to_string())?; + cell_host(&self.dispatch_hosts, cell_id).send_replace(Some(host)); + Ok(()) } pub(super) fn close_cell(&self, cell_id: &CellId) { - remove_dispatch_gate(&self.dispatch_gates, cell_id); + remove_cell_host(&self.dispatch_hosts, cell_id); } pub(super) fn start_turn_worker( &self, - exec: ExecContext, + session: Arc, router: Arc, step_context: Arc, tracker: SharedTurnDiffTracker, ) -> CodeModeDispatchWorker { let tool_runtime = - ToolCallRuntime::new(router, Arc::clone(&exec.session), step_context, tracker); - let host = Arc::new(CoreTurnHost { exec, tool_runtime }); + ToolCallRuntime::new(router, Arc::clone(&session), step_context, tracker); + let host = Arc::new(CoreRequestHost { + session, + tool_runtime, + }); + match self.active_host.lock() { + Ok(mut active_host) => *active_host = Some(Arc::clone(&host)), + Err(poisoned) => *poisoned.into_inner() = Some(Arc::clone(&host)), + } let dispatch_rx = self.dispatch_rx.clone(); - let dispatch_gates = Arc::clone(&self.dispatch_gates); + let dispatch_hosts = Arc::clone(&self.dispatch_hosts); let (shutdown_tx, mut shutdown_rx) = oneshot::channel(); tokio::spawn(async move { loop { @@ -76,16 +95,12 @@ impl CodeModeDispatchBroker { cancellation_token, response_tx, } => { - let response = if wait_until_cell_ready_for_dispatch( - &dispatch_gates, - &cell_id, - &cancellation_token, - ) - .await + let response = if let Some(host) = + wait_for_cell_host(&dispatch_hosts, &cell_id, &cancellation_token).await { host.notify(call_id, cell_id, text).await } else { - remove_dispatch_gate(&dispatch_gates, &cell_id); + remove_cell_host(&dispatch_hosts, &cell_id); Err("code mode notification cancelled".to_string()) }; let _ = response_tx.send(response); @@ -96,17 +111,13 @@ impl CodeModeDispatchBroker { response_tx, } => { let cell_id = invocation.cell_id.clone(); - if !wait_until_cell_ready_for_dispatch( - &dispatch_gates, - &cell_id, - &cancellation_token, - ) - .await - { - remove_dispatch_gate(&dispatch_gates, &cell_id); + let Some(host) = + wait_for_cell_host(&dispatch_hosts, &cell_id, &cancellation_token) + .await + else { + remove_cell_host(&dispatch_hosts, &cell_id); continue; - } - let host = Arc::clone(&host); + }; tokio::spawn(async move { let response = tokio::select! { response = host.invoke_tool( @@ -123,55 +134,51 @@ impl CodeModeDispatchBroker { }); CodeModeDispatchWorker { shutdown_tx: Some(shutdown_tx), + active_host: Arc::clone(&self.active_host), + host, } } } -fn dispatch_gate( - dispatch_gates: &Mutex>>, - cell_id: &CellId, -) -> watch::Sender { - let mut dispatch_gates = match dispatch_gates.lock() { - Ok(dispatch_gates) => dispatch_gates, +fn cell_host(dispatch_hosts: &CellHostMap, cell_id: &CellId) -> CellHostSender { + let mut dispatch_hosts = match dispatch_hosts.lock() { + Ok(dispatch_hosts) => dispatch_hosts, Err(poisoned) => poisoned.into_inner(), }; - dispatch_gates + dispatch_hosts .entry(cell_id.clone()) - .or_insert_with(|| watch::channel(false).0) + .or_insert_with(|| watch::channel(None).0) .clone() } -fn remove_dispatch_gate( - dispatch_gates: &Mutex>>, - cell_id: &CellId, -) { - let mut dispatch_gates = match dispatch_gates.lock() { - Ok(dispatch_gates) => dispatch_gates, +fn remove_cell_host(dispatch_hosts: &CellHostMap, cell_id: &CellId) { + let mut dispatch_hosts = match dispatch_hosts.lock() { + Ok(dispatch_hosts) => dispatch_hosts, Err(poisoned) => poisoned.into_inner(), }; - dispatch_gates.remove(cell_id); + dispatch_hosts.remove(cell_id); } -async fn wait_until_cell_ready_for_dispatch( - dispatch_gates: &Mutex>>, +async fn wait_for_cell_host( + dispatch_hosts: &CellHostMap, cell_id: &CellId, cancellation_token: &CancellationToken, -) -> bool { +) -> Option> { if cancellation_token.is_cancelled() { - return false; + return None; } - let mut ready_rx = dispatch_gate(dispatch_gates, cell_id).subscribe(); + let mut host_rx = cell_host(dispatch_hosts, cell_id).subscribe(); loop { - if *ready_rx.borrow_and_update() { - return true; + if let Some(host) = host_rx.borrow_and_update().clone() { + return Some(host); } tokio::select! { - changed = ready_rx.changed() => { + changed = host_rx.changed() => { if changed.is_err() { - return false; + return None; } } - _ = cancellation_token.cancelled() => return false, + _ = cancellation_token.cancelled() => return None, } } } @@ -259,43 +266,49 @@ enum DispatchMessage { pub(crate) struct CodeModeDispatchWorker { shutdown_tx: Option>, + active_host: Arc>>>, + host: Arc, } impl Drop for CodeModeDispatchWorker { fn drop(&mut self) { + let mut active_host = match self.active_host.lock() { + Ok(active_host) => active_host, + Err(poisoned) => poisoned.into_inner(), + }; + if active_host + .as_ref() + .is_some_and(|active_host| Arc::ptr_eq(active_host, &self.host)) + { + *active_host = None; + } if let Some(shutdown_tx) = self.shutdown_tx.take() { let _ = shutdown_tx.send(()); } } } -struct CoreTurnHost { - exec: ExecContext, +struct CoreRequestHost { + session: Arc, tool_runtime: ToolCallRuntime, } -impl CoreTurnHost { +impl CoreRequestHost { async fn invoke_tool( &self, invocation: CodeModeNestedToolCall, cancellation_token: CancellationToken, ) -> Result { - call_nested_tool( - self.exec.clone(), - self.tool_runtime.clone(), - invocation, - cancellation_token, - ) - .await - .map_err(|error| error.to_string()) + call_nested_tool(self.tool_runtime.clone(), invocation, cancellation_token) + .await + .map_err(|error| error.to_string()) } async fn notify(&self, call_id: String, cell_id: CellId, text: String) -> Result<(), String> { if text.trim().is_empty() { return Ok(()); } - self.exec - .session + self.session .inject_if_running(vec![ResponseItem::CustomToolCallOutput { id: None, call_id, diff --git a/codex-rs/core/src/tools/code_mode/execute_handler.rs b/codex-rs/core/src/tools/code_mode/execute_handler.rs index 2e46c1bd6b..071c0b3ddf 100644 --- a/codex-rs/core/src/tools/code_mode/execute_handler.rs +++ b/codex-rs/core/src/tools/code_mode/execute_handler.rs @@ -67,7 +67,8 @@ impl CodeModeExecuteHandler { exec.session .services .code_mode_service - .mark_cell_ready_for_dispatch(&cell_id); + .bind_cell_to_active_host(&cell_id) + .map_err(FunctionCallError::RespondToModel)?; let response = started_cell .initial_response() .await diff --git a/codex-rs/core/src/tools/code_mode/mod.rs b/codex-rs/core/src/tools/code_mode/mod.rs index 3828203bb6..8a5822a42e 100644 --- a/codex-rs/core/src/tools/code_mode/mod.rs +++ b/codex-rs/core/src/tools/code_mode/mod.rs @@ -103,8 +103,11 @@ impl CodeModeService { } } - pub(crate) fn mark_cell_ready_for_dispatch(&self, cell_id: &codex_code_mode::CellId) { - self.dispatch_broker.mark_cell_ready_for_dispatch(cell_id); + pub(crate) fn bind_cell_to_active_host( + &self, + cell_id: &codex_code_mode::CellId, + ) -> Result<(), String> { + self.dispatch_broker.bind_cell_to_active_host(cell_id) } pub(crate) fn finish_cell_dispatch(&self, cell_id: &CellId) { @@ -126,14 +129,12 @@ impl CodeModeService { return None; } - let exec = ExecContext { - session: Arc::clone(session), - turn: Arc::clone(turn), - }; - Some( - self.dispatch_broker - .start_turn_worker(exec, router, step_context, tracker), - ) + Some(self.dispatch_broker.start_turn_worker( + Arc::clone(session), + router, + step_context, + tracker, + )) } fn session(&self) -> Result<&Arc, String> { @@ -238,7 +239,6 @@ fn truncate_code_mode_result( } async fn call_nested_tool( - _exec: ExecContext, tool_runtime: ToolCallRuntime, invocation: CodeModeNestedToolCall, cancellation_token: CancellationToken, diff --git a/codex-rs/core/tests/suite/code_mode.rs b/codex-rs/core/tests/suite/code_mode.rs index 14bee0fb8d..79c7f51d83 100644 --- a/codex-rs/core/tests/suite/code_mode.rs +++ b/codex-rs/core/tests/suite/code_mode.rs @@ -25,6 +25,7 @@ use codex_protocol::protocol::EventMsg; use codex_protocol::protocol::Op; use codex_protocol::user_input::UserInput; use codex_web_search_extension::install as install_web_search_extension; +use core_test_support::PathExt; use core_test_support::apps_test_server::AppsTestServer; use core_test_support::apps_test_server::AppsTestToolLoading; use core_test_support::apps_test_server::DIRECT_CALENDAR_APP_ONLY_TOOL; @@ -43,6 +44,7 @@ use core_test_support::skip_if_no_network; use core_test_support::skip_if_wine_exec; use core_test_support::stdio_server_bin; use core_test_support::test_codex::TestCodex; +use core_test_support::test_codex::local; use core_test_support::test_codex::test_codex; use core_test_support::test_codex::turn_permission_fields; use core_test_support::wait_for_event; @@ -2317,15 +2319,24 @@ async fn code_mode_background_keeps_running_on_later_turn_without_wait() -> Resu let _ = config.features.enable(Feature::CodeMode); }); let test = builder.build(&server).await?; - let resumed_file = test.workspace_path("code-mode-yield-resumed.txt"); + let resumed_file_name = "code-mode-yield-resumed.txt"; + let resumed_file = test.workspace_path(resumed_file_name); + let later_workspace = test.workspace_path("later-workspace"); + fs::create_dir_all(&later_workspace)?; + let later_resumed_file = later_workspace.join(resumed_file_name); + let later_turn_gate = test.workspace_path("later-turn-started.ready"); + let wait_for_later_turn = wait_for_file_source(&later_turn_gate)?; + let later_turn_gate_quoted = shlex::try_join([later_turn_gate.to_string_lossy().as_ref()])?; let resumed_file_quoted = shlex::try_join([resumed_file.to_string_lossy().as_ref()])?; - let write_file_command = format!("printf resumed > {resumed_file_quoted}"); - let wait_for_file_command = - format!("while [ ! -f {resumed_file_quoted} ]; do sleep 0.01; done; printf ready"); + let write_file_command = format!("printf resumed > {resumed_file_name}"); + let wait_for_file_command = format!( + "i=0; while [ \"$i\" -lt 500 ]; do [ -f {resumed_file_quoted} ] && {{ printf ready; exit; }}; i=$((i+1)); sleep 0.01; done; printf missing" + ); let code = format!( r#" text("before yield"); yield_control(); +{wait_for_later_turn} await tools.exec_command({{ cmd: {write_file_command:?} }}); text("after yield"); "# @@ -2371,31 +2382,51 @@ text("after yield"); "call-2", "exec_command", &serde_json::to_string(&serde_json::json!({ - "cmd": wait_for_file_command, + "cmd": format!("touch {later_turn_gate_quoted}"), }))?, ), ev_completed("resp-3"), ]), ) .await; + responses::mount_sse_once( + &server, + sse(vec![ + ev_response_created("resp-4"), + responses::ev_function_call( + "call-3", + "exec_command", + &serde_json::to_string(&serde_json::json!({ + "cmd": wait_for_file_command, + }))?, + ), + ev_completed("resp-4"), + ]), + ) + .await; let second_completion = responses::mount_sse_once( &server, sse(vec![ ev_assistant_message("msg-2", "file appeared"), - ev_completed("resp-4"), + ev_completed("resp-5"), ]), ) .await; - test.submit_turn("wait for resumed file").await?; + test.submit_turn_with_environments( + "wait for resumed file", + Some(vec![local(later_workspace.as_path().abs())]), + ) + .await?; let second_request = second_completion.single_request(); assert!( second_request - .function_call_output_text("call-2") + .function_call_output_text("call-3") .is_some_and(|output| output.ends_with("ready")) ); assert_eq!(fs::read_to_string(&resumed_file)?, "resumed"); + assert!(!later_resumed_file.exists()); Ok(()) }