Skip to content

The agent that grows with you

feat(approval): coalesce identical concurrent gateway approval prompts

Teknium08d982850325
diff --git a/tests/tools/test_approval.py b/tests/tools/test_approval.py
index 1a75403436d..258a991aae2 100644
--- a/tests/tools/test_approval.py
+++ b/tests/tools/test_approval.py
@@ -1369,6 +1369,162 @@ class TestApprovalTimeoutIsNotConsent:
thread.join(timeout=5)
assert result_holder["result"]["approved"] is False
+
+# =========================================================================
+# Coalesce identical concurrent approvals — one prompt, one answer.
+# Port of anomalyco/opencode#40869 (deduplicate websearch consent prompts):
+# parallel tool calls hitting the same dangerous-command gate must produce
+# ONE user-facing prompt; followers adopt the leader's session/always/deny
+# decision, while a single-use "once" makes the follower re-prompt.
+# =========================================================================
+
+
+class TestConcurrentApprovalCoalescing:
+ SESSION_KEY = "test-coalesce-session"
+
+ def setup_method(self):
+ from tools import approval as mod
+ mod._gateway_queues.clear()
+ mod._gateway_notify_cbs.clear()
+ mod._session_approved.clear()
+ mod._permanent_approved.clear()
+
+ teardown_method = setup_method
+
+ def _data(self, command="rm -rf .git"):
+ return {
+ "command": command,
+ "description": "desc",
+ "pattern_key": "dangerous",
+ "pattern_keys": ["dangerous"],
+ }
+
+ def _spawn_waits(self, mod, notified, n=2, command="rm -rf .git"):
+ import threading
+ results = [None] * n
+ threads = []
+ for i in range(n):
+ def _run(idx=i):
+ results[idx] = mod._await_gateway_decision(
+ self.SESSION_KEY, notified.append, self._data(command)
+ )
+ t = threading.Thread(target=_run)
+ t.start()
+ threads.append(t)
+ if i == 0:
+ # Wait for the leader to enqueue AND for its notify_cb to
+ # fire (the pre-approval hook dispatch runs between the
+ # queue append and the notify, and can be slow on first
+ # call) so follower threads deterministically find it and
+ # coalesce against a fully-presented prompt.
+ for _ in range(400):
+ if mod._gateway_queues.get(self.SESSION_KEY) and notified:
+ break
+ time.sleep(0.005)
+ else:
+ # Followers never enqueue; give the thread a beat to reach
+ # the leader wait.
+ time.sleep(0.05)
+ return results, threads
+
+ def test_identical_concurrent_approvals_send_one_prompt(self, monkeypatch):
+ from tools import approval as mod
+ monkeypatch.setattr(mod, "_get_approval_timeout", lambda: 30)
+
+ notified = []
+ results, threads = self._spawn_waits(mod, notified, n=3)
+
+ # Only the leader is in the queue; only one notify fired.
+ assert len(mod._gateway_queues.get(self.SESSION_KEY, [])) == 1
+ assert len(notified) == 1
+
+ # One answer resolves everyone.
+ assert mod.resolve_gateway_approval(self.SESSION_KEY, "session") == 1
+ for t in threads:
+ t.join(timeout=5)
+ for r in results:
+ assert r is not None and r["resolved"] and r["choice"] == "session"
+ # Followers are marked as coalesced adoptions.
+ assert sum(1 for r in results if r.get("coalesced")) == 2
+
+ def test_deny_propagates_to_followers(self, monkeypatch):
+ from tools import approval as mod
+ monkeypatch.setattr(mod, "_get_approval_timeout", lambda: 30)
+
+ notified = []
+ results, threads = self._spawn_waits(mod, notified, n=2)
+ assert len(notified) == 1
+
+ mod.resolve_gateway_approval(self.SESSION_KEY, "deny", reason="nope")
+ for t in threads:
+ t.join(timeout=5)
+ for r in results:
+ assert r is not None and r["choice"] == "deny"
+ follower = next(r for r in results if r.get("coalesced"))
+ assert follower["reason"] == "nope"
+
+ def test_once_makes_follower_reprompt(self, monkeypatch):
+ from tools import approval as mod
+ monkeypatch.setattr(mod, "_get_approval_timeout", lambda: 30)
+
+ notified = []
+ results, threads = self._spawn_waits(mod, notified, n=2)
+ assert len(notified) == 1
+
+ # "once" covers only the leader — the follower must re-prompt.
+ mod.resolve_gateway_approval(self.SESSION_KEY, "once")
+ for _ in range(400):
+ if len(notified) == 2:
+ break
+ time.sleep(0.01)
+ assert len(notified) == 2, "follower did not issue a fresh prompt after 'once'"
+
+ mod.resolve_gateway_approval(self.SESSION_KEY, "once")
+ for t in threads:
+ t.join(timeout=5)
+ assert all(r is not None and r["choice"] == "once" for r in results)
+
+ def test_different_commands_are_not_coalesced(self, monkeypatch):
+ from tools import approval as mod
+ monkeypatch.setattr(mod, "_get_approval_timeout", lambda: 30)
+ import threading
+
+ notified = []
+ results = [None, None]
+
+ def _run(idx, cmd):
+ results[idx] = mod._await_gateway_decision(
+ self.SESSION_KEY, notified.append, self._data(cmd)
+ )
+
+ t1 = threading.Thread(target=_run, args=(0, "rm -rf .git"))
+ t1.start()
+ for _ in range(200):
+ if mod._gateway_queues.get(self.SESSION_KEY):
+ break
+ time.sleep(0.005)
+ t2 = threading.Thread(target=_run, args=(1, "rm -rf /tmp/x"))
+ t2.start()
+ for _ in range(200):
+ if len(mod._gateway_queues.get(self.SESSION_KEY, [])) == 2:
+ break
+ time.sleep(0.005)
+ # notify_cb fires after the queue append (hook dispatch runs in
+ # between and can be slow on first call) — wait for both prompts.
+ for _ in range(1000):
+ if len(notified) == 2:
+ break
+ time.sleep(0.005)
+
+ # Two distinct prompts, two queue entries, two resolutions needed.
+ assert len(notified) == 2
+ assert len(mod._gateway_queues.get(self.SESSION_KEY, [])) == 2
+ mod.resolve_gateway_approval(self.SESSION_KEY, "session", resolve_all=True)
+ t1.join(timeout=5)
+ t2.join(timeout=5)
+ assert all(r is not None and r["choice"] == "session" for r in results)
+
+
class TestTirithImportErrorFailOpenPolicy:
"""Regression guard for #20733.
diff --git a/tools/approval.py b/tools/approval.py
index 592b43f4064..9188f10ed43 100644
--- a/tools/approval.py
+++ b/tools/approval.py
@@ -4007,6 +4007,104 @@ def _transport_denied_result(
}
+def _await_coalesced_leader(session_key: str, leader, approval_data: dict,
+ *, surface: str = "gateway"):
+ """Wait on an already-pending identical approval instead of re-prompting.
+
+ Called by ``_await_gateway_decision`` when an identical approval (same
+ command text + same pattern-key set) is already awaiting the user's
+ answer in this session. Blocks until the leader entry resolves, then
+ adopts its decision:
+
+ * ``session`` / ``always`` → adopted approval (same dict shape as a
+ direct resolution; persistence stays the caller's responsibility and
+ is idempotent across the leader and followers).
+ * ``deny`` → adopted denial, carrying the leader's deny reason.
+ * leader timeout (event set by queue teardown, or our own deadline
+ expiring first) → unresolved, identical to a direct timeout.
+ * ``once`` → returns ``None``: single-use consent covers only the
+ leader's execution, so the caller must issue a fresh prompt.
+
+ Fires the pre/post approval hooks with ``coalesced=True`` so observers
+ see the follower's lifecycle without a duplicate user-facing prompt.
+ """
+ command = approval_data.get("command", "")
+ description = approval_data.get("description", "")
+ primary_key = approval_data.get("pattern_key", "")
+ all_keys = approval_data.get("pattern_keys", [primary_key])
+
+ _fire_approval_hook(
+ "pre_approval_request",
+ command=command,
+ description=description,
+ pattern_key=primary_key,
+ pattern_keys=list(all_keys),
+ session_key=session_key,
+ surface=surface,
+ coalesced=True,
+ )
+
+ timeout = _get_approval_timeout()
+ try:
+ from tools.environments.base import touch_activity_if_due
+ except Exception: # pragma: no cover
+ touch_activity_if_due = None
+
+ _now = time.monotonic()
+ _deadline = _now + max(timeout, 0)
+ _activity_state = {"last_touch": _now, "start": _now}
+ resolved = False
+ with human_wait_window(session_key):
+ while True:
+ if is_interrupted():
+ logger.info(
+ "Coalesced approval wait interrupted by user signal — "
+ "returning deny for session %s",
+ session_key,
+ )
+ # Deny only OUR follower; the leader thread handles its own
+ # interrupt signal.
+ choice = "deny"
+ resolved = True
+ break
+ _remaining = _deadline - time.monotonic()
+ if _remaining <= 0:
+ choice = None
+ break
+ if leader.event.wait(timeout=min(1.0, _remaining)):
+ choice = leader.result
+ resolved = choice is not None
+ break
+ if touch_activity_if_due is not None:
+ touch_activity_if_due(
+ _activity_state, "waiting for user approval"
+ )
+
+ if choice == "once":
+ # Single-use consent — the caller re-prompts. The post hook fires
+ # for the fresh prompt's own lifecycle, not here.
+ return None
+
+ _outcome = "timeout" if not resolved else (choice if choice else "timeout")
+ _fire_approval_hook(
+ "post_approval_response",
+ command=command,
+ description=description,
+ pattern_key=primary_key,
+ pattern_keys=list(all_keys),
+ session_key=session_key,
+ surface=surface,
+ choice=_outcome,
+ coalesced=True,
+ )
+ return {
+ "resolved": resolved,
+ "choice": choice,
+ "reason": getattr(leader, "reason", None),
+ "coalesced": True,
+ }
+
+
def _await_gateway_decision(session_key: str, notify_cb, approval_data: dict,
*, surface: str = "gateway") -> dict:
"""Enqueue *approval_data*, notify the user, and block the calling agent
@@ -4027,6 +4125,41 @@ def _await_gateway_decision(session_key: str, notify_cb, approval_data: dict,
primary_key = approval_data.get("pattern_key", "")
all_keys = approval_data.get("pattern_keys", [primary_key])
+ # ── Coalesce identical concurrent approvals (one prompt, one answer) ──
+ # Parallel tool calls (a parallel terminal batch, execute_code RPC
+ # handlers) can hit the same dangerous-command gate at the same time.
+ # Without coalescing, every thread enqueues its own entry and fires its
+ # own notify_cb — the user gets N identical prompts and must /approve N
+ # times while the agent sits wedged. Follow anomalyco/opencode#40869's
+ # shape: followers wait on the leader's decision and re-check after it
+ # lands instead of prompting again.
+ #
+ # Adoption rules keep the consent contract strict:
+ # session / always → adopt approved (the persistence layer would
+ # auto-pass an identical re-check anyway once the leader persisted).
+ # deny / timeout → adopt the refusal (immediately re-asking the exact
+ # command the user just declined is prompt spam and an evasion path).
+ # once → single-use consent; it covers ONLY the leader's
+ # execution, so the follower falls through to a fresh prompt.
+ leader = None
+ with _lock:
+ for existing in _gateway_queues.get(session_key, []):
+ data = existing.data
+ if (
+ data.get("command") == approval_data.get("command")
+ and list(data.get("pattern_keys") or [])
+ == list(approval_data.get("pattern_keys") or [])
+ ):
+ leader = existing
+ break
+ if leader is not None:
+ adopted = _await_coalesced_leader(
+ session_key, leader, approval_data, surface=surface
+ )
+ if adopted is not None:
+ return adopted
+ # Leader resolved "once" — fall through to a fresh prompt below.
+
entry = _ApprovalEntry(approval_data)
with _lock:
_gateway_queues.setdefault(session_key, []).append(entry)