From a35fb9d877dbc77c088bc906713dc9b2cb427694 Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Wed, 3 Sep 2025 23:44:02 -0700 Subject: [PATCH] fix: add callback to map before sending request to fix race condition --- codex-rs/core/src/codex.rs | 32 ++++++++++++++++++++++---------- 1 file changed, 22 insertions(+), 10 deletions(-) diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 3b3d43bf2e..36c48020bc 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -568,9 +568,19 @@ impl Session { cwd: PathBuf, reason: Option, ) -> oneshot::Receiver { + // Add the tx_approve callback to the map before sending the request. let (tx_approve, rx_approve) = oneshot::channel(); + let event_id = sub_id.clone(); + let prev_entry = { + let mut state = self.state.lock_unchecked(); + state.pending_approvals.insert(sub_id, tx_approve) + }; + if prev_entry.is_some() { + warn!("Overwriting existing pending approval for sub_id: {event_id}"); + } + let event = Event { - id: sub_id.clone(), + id: event_id, msg: EventMsg::ExecApprovalRequest(ExecApprovalRequestEvent { call_id, command, @@ -579,10 +589,6 @@ impl Session { }), }; let _ = self.tx_event.send(event).await; - { - let mut state = self.state.lock_unchecked(); - state.pending_approvals.insert(sub_id, tx_approve); - } rx_approve } @@ -594,9 +600,19 @@ impl Session { reason: Option, grant_root: Option, ) -> oneshot::Receiver { + // Add the tx_approve callback to the map before sending the request. let (tx_approve, rx_approve) = oneshot::channel(); + let event_id = sub_id.clone(); + let prev_entry = { + let mut state = self.state.lock_unchecked(); + state.pending_approvals.insert(sub_id, tx_approve) + }; + if prev_entry.is_some() { + warn!("Overwriting existing pending approval for sub_id: {event_id}"); + } + let event = Event { - id: sub_id.clone(), + id: event_id, msg: EventMsg::ApplyPatchApprovalRequest(ApplyPatchApprovalRequestEvent { call_id, changes: convert_apply_patch_to_protocol(action), @@ -605,10 +621,6 @@ impl Session { }), }; let _ = self.tx_event.send(event).await; - { - let mut state = self.state.lock_unchecked(); - state.pending_approvals.insert(sub_id, tx_approve); - } rx_approve }