Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(approval): replay a parked approval to a socket that joins the thread room

M3gA-Mind032d8c182d5c
diff --git a/src/core/socketio.rs b/src/core/socketio.rs
index 2efa67f297..a5b92c4c59 100644
--- a/src/core/socketio.rs
+++ b/src/core/socketio.rs
@@ -704,6 +704,13 @@ pub fn attach_socketio() -> (socketioxide::layer::SocketIoLayer, SocketIo) {
// stops queueing the thread for retry and reads on the
// strength of a room it is not in.
let joined = join_room_logged(&socket, &room, &socket.id.to_string());
+ // Hand this socket whatever the approval gate still has
+ // parked on the thread, BEFORE acknowledging the join, so a
+ // client that orders its recovery reads against the ack
+ // already holds the card.
+ if joined {
+ replay_parked_approval(&socket, thread_id);
+ }
ack.send(&ThreadSubscribeAck { joined }).ok();
},
);
@@ -1495,6 +1502,52 @@ fn event_alias(name: &str) -> Option<String> {
None
}
+/// Re-send the approval parked on `thread_id`, if any, to the socket that just
+/// joined that thread's room.
+///
+/// An approval is durable server-side state — the gate holds the parked call
+/// and a `pending_approvals` row — but it reaches the UI as ONE fire-and-forget
+/// emit from [`emit_web_channel_event`]. That emit can miss with no error and
+/// no trace: `io.to(room).emit()` on a room whose only member has gone is a
+/// silent no-op, there is no disconnect handler here so the core never learns a
+/// client died, a socket that reconnects lands in the thread room only for
+/// events emitted *after* it joins, and the bridge drops frames wholesale on
+/// broadcast lag. Any one of those leaves the turn parked forever with no card
+/// on screen and no way for the user to act.
+///
+/// `thread:subscribe` is the one signal that says "this socket is now watching
+/// this thread", which makes it the place to reconcile the two. Replaying is
+/// safe to repeat: the client keys the card by `request_id` and a decided
+/// request is no longer parked, so a socket that already has the card just
+/// re-renders the same one.
+#[cfg(feature = "http-server")]
+fn replay_parked_approval(socket: &SocketRef, thread_id: &str) {
+ let Some(gate) = crate::openhuman::security::approval::ApprovalGate::try_global() else {
+ return;
+ };
+ let Some(row) = gate.parked_request_for_thread(thread_id) else {
+ return;
+ };
+ let client_id = socket.id.to_string();
+ let event = crate::openhuman::web_chat::approval_request_event(
+ &row.request_id,
+ &row.tool_name,
+ &row.action_summary,
+ &row.args_redacted,
+ thread_id,
+ &client_id,
+ );
+ let Ok(payload) = serde_json::to_value(&event) else {
+ return;
+ };
+ log::info!(
+ "[socketio] replaying parked approval_request to joining socket client_id={client_id} thread_id={thread_id} request_id={} tool={}",
+ row.request_id,
+ row.tool_name
+ );
+ emit_with_aliases(socket, "approval_request", &payload);
+}
+
#[cfg(feature = "http-server")]
fn emit_with_aliases(socket: &SocketRef, name: &str, payload: &serde_json::Value) {
let _ = socket.emit(name, payload);
diff --git a/src/openhuman/security/approval/gate_state.rs b/src/openhuman/security/approval/gate_state.rs
index df5f59d0e8..f8adee1725 100644
--- a/src/openhuman/security/approval/gate_state.rs
+++ b/src/openhuman/security/approval/gate_state.rs
@@ -186,6 +186,33 @@ impl ApprovalGate {
self.thread_to_request.lock().get(thread_id).cloned()
}
+ /// The full pending row parked on `thread_id`, if any.
+ ///
+ /// [`Self::pending_for_thread`] answers *which* request is parked; this
+ /// answers *what it is*, which is what a UI needs to rebuild the approval
+ /// card from scratch.
+ ///
+ /// The card reaches the UI as ONE fire-and-forget socket emit. If that emit
+ /// misses — the addressed client's room is empty because the page reloaded,
+ /// a rejoining socket was not yet in the thread room, or the bridge dropped
+ /// the frame on broadcast lag — nothing re-sends it. The request stays
+ /// parked server-side and the user is left with no card and no way to act,
+ /// which is the whole failure: durable state delivered as an ephemeral
+ /// event, with no way to reconcile the two. This lookup is that
+ /// reconciliation, so a socket (re)joining a thread can be handed whatever
+ /// is parked on it.
+ ///
+ /// Reads the routing map first and the durable rows second, so a request
+ /// decided between the two reads simply falls out as `None` rather than
+ /// replaying a card the user has already answered.
+ pub fn parked_request_for_thread(&self, thread_id: &str) -> Option<PendingApproval> {
+ let request_id = self.pending_for_thread(thread_id)?;
+ self.list_pending()
+ .ok()?
+ .into_iter()
+ .find(|row| row.request_id == request_id)
+ }
+
/// Drop the thread → request mapping when it still belongs to this request.
fn clear_thread(&self, thread_id: &Option<String>, request_id: &str) {
if let Some(t) = thread_id {
diff --git a/src/openhuman/security/approval/gate_tests_part_02_tests.rs b/src/openhuman/security/approval/gate_tests_part_02_tests.rs
index 77c8d82496..a70afdae46 100644
--- a/src/openhuman/security/approval/gate_tests_part_02_tests.rs
+++ b/src/openhuman/security/approval/gate_tests_part_02_tests.rs
@@ -633,3 +633,83 @@ async fn intercept_with_workflow_require_approval_persists_and_ttl_denies() {
other => panic!("expected deny, got {other:?}"),
}
}
+
+/// A parked approval must be recoverable from its thread alone.
+///
+/// The card is delivered to the UI as ONE fire-and-forget socket emit
+/// (`web_chat::event_bus` → `core::socketio::emit_web_channel_event`). If that
+/// emit misses — the addressed client's room is empty because it reloaded, the
+/// rejoining socket was not yet in the thread room, or the bridge dropped the
+/// frame on broadcast lag — nothing re-sends it, and the turn stays parked with
+/// no card and no way for the user to act. Recovering the full row from the
+/// thread is what lets a (re)joining socket rebuild the card, so the durable
+/// park stops depending on a single delivery.
+#[tokio::test]
+async fn a_parked_approval_is_recoverable_from_its_thread_for_replay() {
+ let (gate, _dir) = test_gate_with_ttl(Duration::from_secs(10));
+ let gate = Arc::new(gate);
+
+ let g = gate.clone();
+ let ctx = ApprovalChatContext {
+ thread_id: "thread-replay".into(),
+ client_id: "client-that-went-away".into(),
+ };
+ let origin = AgentTurnOrigin::WebChat {
+ thread_id: "thread-replay".into(),
+ client_id: "client-that-went-away".into(),
+ request_id: Some("req-replay".into()),
+ };
+ let handle = tokio::spawn(async move {
+ turn_origin::with_origin(
+ origin,
+ APPROVAL_CHAT_CONTEXT.scope(
+ ctx,
+ g.intercept(
+ "create_workflow",
+ "create a workflow",
+ serde_json::json!({ "name": "nightly" }),
+ ),
+ ),
+ )
+ .await
+ });
+
+ let mut tries = 0;
+ loop {
+ if gate.pending_for_thread("thread-replay").is_some() {
+ break;
+ }
+ tries += 1;
+ assert!(tries < 50, "thread mapping never appeared");
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ }
+
+ let row = gate.parked_request_for_thread("thread-replay").expect(
+ "a parked approval must be recoverable from its thread, or a client that missed the \
+ single live emit can never rebuild the card and the turn stays parked forever",
+ );
+ assert_eq!(
+ row.tool_name, "create_workflow",
+ "the recovered row must carry the payload the card renders"
+ );
+ assert_eq!(
+ gate.pending_for_thread("thread-replay").as_deref(),
+ Some(row.request_id.as_str()),
+ "the recovered row must be the one actually parked on this thread"
+ );
+
+ // Another thread must not inherit it — replay is thread-scoped.
+ assert!(
+ gate.parked_request_for_thread("thread-unrelated").is_none(),
+ "a thread with nothing parked must have nothing to replay"
+ );
+
+ gate.decide(&row.request_id, ApprovalDecision::Deny)
+ .unwrap();
+ let _ = handle.await.unwrap();
+
+ assert!(
+ gate.parked_request_for_thread("thread-replay").is_none(),
+ "a decided approval must not be replayed to the next socket that joins"
+ );
+}
diff --git a/src/openhuman/web_chat/event_bus.rs b/src/openhuman/web_chat/event_bus.rs
index 65821eb949..b7036e7485 100644
--- a/src/openhuman/web_chat/event_bus.rs
+++ b/src/openhuman/web_chat/event_bus.rs
@@ -299,6 +299,33 @@ pub fn fresh_approval_surface_subscription() -> Option<SubscriptionHandle> {
crate::core::bus::BUS.subscribe(Arc::new(ApprovalSurfaceSubscriber))
}
+/// Build the `approval_request` web-channel event for a parked approval.
+///
+/// Shared by the live surface below (on `ApprovalRequested`) and by the replay
+/// path in `core::socketio` (a socket joining a thread room that already has an
+/// approval parked on it). One constructor so a client that missed the live
+/// emit is handed a byte-identical payload rather than a second shape kept in
+/// step by hand.
+pub fn approval_request_event(
+ request_id: &str,
+ tool_name: &str,
+ action_summary: &str,
+ args_redacted: &serde_json::Value,
+ thread_id: &str,
+ client_id: &str,
+) -> WebChannelEvent {
+ WebChannelEvent {
+ event: "approval_request".to_string(),
+ client_id: client_id.to_string(),
+ thread_id: thread_id.to_string(),
+ request_id: request_id.to_string(),
+ tool_name: Some(tool_name.to_string()),
+ message: Some(format!("Run `{tool_name}` — {action_summary}")),
+ args: Some(args_redacted.clone()),
+ ..Default::default()
+ }
+}
+
struct ApprovalSurfaceSubscriber;
#[async_trait]
@@ -324,20 +351,17 @@ impl EventHandler<DomainEvent> for ApprovalSurfaceSubscriber {
{
match (thread_id, client_id) {
(Some(thread_id), Some(client_id)) => {
- let question = format!("Run `{tool_name}` — {action_summary}");
log::info!(
"[web-channel] approval-surface emitting approval_request request_id={request_id} thread_id={thread_id} client_id={client_id} tool={tool_name}"
);
- publish_web_channel_event(WebChannelEvent {
- event: "approval_request".to_string(),
- client_id: client_id.clone(),
- thread_id: thread_id.clone(),
- request_id: request_id.clone(),
- tool_name: Some(tool_name.clone()),
- message: Some(question),
- args: Some(args_redacted.clone()),
- ..Default::default()
- });
+ publish_web_channel_event(approval_request_event(
+ request_id,
+ tool_name,
+ action_summary,
+ args_redacted,
+ thread_id,
+ client_id,
+ ));
}
_ => {
log::warn!(
diff --git a/src/openhuman/web_chat/mod.rs b/src/openhuman/web_chat/mod.rs
index 7e140267ff..b27be80ae6 100644
--- a/src/openhuman/web_chat/mod.rs
+++ b/src/openhuman/web_chat/mod.rs
@@ -22,7 +22,7 @@ pub(crate) use web_errors::{
// Public API — event bus
pub use event_bus::{
- publish_web_channel_event, register_approval_surface_subscriber,
+ approval_request_event, publish_web_channel_event, register_approval_surface_subscriber,
register_artifact_surface_subscriber, register_egress_surface_subscriber,
subscribe_web_channel_events,
};