Skip to content

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

fix(desktop): retain denied confirmation until cancellation completes

Steven Enamakel2cc862642d54
diff --git a/crates/openhuman-core/src/desktop/control/confirmation.rs b/crates/openhuman-core/src/desktop/control/confirmation.rs
index be9be5691b..4f47d66d40 100644
--- a/crates/openhuman-core/src/desktop/control/confirmation.rs
+++ b/crates/openhuman-core/src/desktop/control/confirmation.rs
@@ -1,12 +1,13 @@
//! One-use user decisions for Jev goal stops, separate from autonomy auto-approval.
use std::collections::HashMap;
+use std::future::Future;
use std::sync::{Mutex, OnceLock};
use std::time::{Duration, Instant};
use serde::Serialize;
use serde_json::{json, Value};
-use tinydesktop_bus::names;
+use tinydesktop_bus::{names, DesktopResponse};
use crate::config::Config;
@@ -26,6 +27,7 @@ struct Pending {
expires_at: String,
created: Instant,
approved: bool,
+ cancellation_in_flight: bool,
}
#[derive(Serialize)]
@@ -114,6 +116,7 @@ pub(super) fn record(app: &str, goal: &str, thread_id: &str, data: &Value) {
expires_at,
created: Instant::now(),
approved: false,
+ cancellation_in_flight: false,
},
);
}
@@ -145,10 +148,27 @@ pub fn pending() -> Vec<PendingDesktopConfirmation> {
/// Called only by a trusted RPC client carrying the core launch bearer.
pub async fn confirm(config: &Config, id: &str, approve: bool) -> Result<Value, String> {
+ confirm_with(id, approve, |app, goal, confirmation_id| async move {
+ crate::modules::desktop::call(
+ config,
+ names::methods::RUN_GOAL,
+ json!({"app":app,"goal":goal,
+ "continuation":{"id":confirmation_id,"approve":false}}),
+ )
+ .await
+ })
+ .await
+}
+
+async fn confirm_with<F, Fut>(id: &str, approve: bool, cancel: F) -> Result<Value, String>
+where
+ F: FnOnce(String, String, String) -> Fut,
+ Fut: Future<Output = Result<DesktopResponse, String>>,
+{
if !super::ops::listener_is_loopback() {
return Err("desktop confirmation requires a loopback core listener".to_owned());
}
- let entry = {
+ let (app, goal, created) = {
let mut guard = table()
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
@@ -156,25 +176,49 @@ pub async fn confirm(config: &Config, id: &str, approve: bool) -> Result<Value,
let item = guard
.get_mut(id)
.ok_or("desktop confirmation is missing or expired")?;
+ if item.cancellation_in_flight {
+ return Err("desktop cancellation is already in progress".to_owned());
+ }
if approve {
item.approved = true;
return Ok(json!({"confirmation_id":id,"approve":true}));
}
- guard.remove(id).expect("checked above")
+ item.approved = false;
+ item.cancellation_in_flight = true;
+ (item.app.clone(), item.goal.clone(), item.created)
};
- let reply = crate::modules::desktop::call(
- config,
- names::methods::RUN_GOAL,
- json!({"app":entry.app,"goal":entry.goal,
- "continuation":{"id":id,"approve":false}}),
- )
- .await?;
+ let result = cancel(app, goal, id.to_owned()).await;
+ let succeeded = result.as_ref().is_ok_and(|reply| {
+ reply.ok
+ && reply
+ .data
+ .as_ref()
+ .and_then(|data| data.get("stop"))
+ .and_then(Value::as_str)
+ == Some("cancelled")
+ });
+ {
+ let mut guard = table()
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ if guard.get(id).is_some_and(|item| item.created == created) {
+ if succeeded {
+ guard.remove(id);
+ } else if let Some(item) = guard.get_mut(id) {
+ item.cancellation_in_flight = false;
+ }
+ }
+ }
+ let reply = result?;
if !reply.ok {
return Err(reply.error.map_or_else(
|| "desktop cancellation failed".to_owned(),
|error| error.message,
));
}
+ if !succeeded {
+ return Err("desktop cancellation was not confirmed".to_owned());
+ }
Ok(json!({"confirmation_id":id,"approve":false}))
}
@@ -193,6 +237,9 @@ pub(super) fn take_approved(id: &str, thread_id: Option<&str>) -> Result<(String
guard.remove(id);
return Err("desktop confirmation expired".to_owned());
}
+ if item.cancellation_in_flight {
+ return Err("desktop cancellation is already in progress".to_owned());
+ }
if !item.approved {
return Err("desktop action needs the user's explicit confirmation".to_owned());
}
diff --git a/crates/openhuman-core/src/desktop/control/confirmation_tests.rs b/crates/openhuman-core/src/desktop/control/confirmation_tests.rs
index 942d9643e5..e0cb1c2318 100644
--- a/crates/openhuman-core/src/desktop/control/confirmation_tests.rs
+++ b/crates/openhuman-core/src/desktop/control/confirmation_tests.rs
@@ -1,9 +1,7 @@
use super::*;
+use tinydesktop_bus::DesktopError;
-#[tokio::test]
-async fn confirmation_requires_trusted_one_use_decision_for_same_goal() {
- super::super::ops::set_listener_is_loopback(true);
- let id = uuid::Uuid::new_v4().to_string();
+fn record_save_prompt(id: &str) {
record(
"TextEdit",
"make a note",
@@ -14,6 +12,13 @@ async fn confirmation_requires_trusted_one_use_decision_for_same_goal() {
"target":{"ref_id":"@s1:e2", "name":"Save", "role":"button"}}
}),
);
+}
+
+#[tokio::test]
+async fn confirmation_requires_trusted_one_use_decision_for_same_goal() {
+ let _loopback = super::super::ops::test_loopback_guard();
+ let id = uuid::Uuid::new_v4().to_string();
+ record_save_prompt(&id);
assert!(take_approved(&id, Some("thread-a")).is_err());
let listed = pending();
let item = listed
@@ -43,7 +48,7 @@ async fn confirmation_requires_trusted_one_use_decision_for_same_goal() {
#[test]
fn unnamed_target_cannot_be_approved() {
- super::super::ops::set_listener_is_loopback(true);
+ let _loopback = super::super::ops::test_loopback_guard();
let id = uuid::Uuid::new_v4().to_string();
record(
"TextEdit",
@@ -56,3 +61,102 @@ fn unnamed_target_cannot_be_approved() {
);
assert!(!pending().iter().any(|item| item.confirmation_id == id));
}
+
+#[tokio::test]
+async fn failed_denial_keeps_the_handle_retryable_until_module_confirms_cancellation() {
+ let _loopback = super::super::ops::test_loopback_guard();
+ let id = uuid::Uuid::new_v4().to_string();
+ record_save_prompt(&id);
+ confirm_with(&id, true, |_app, _goal, _handle| async {
+ panic!("approval must not call the desktop module")
+ })
+ .await
+ .unwrap();
+
+ let expected_id = id.clone();
+ let transport_error = confirm_with(&id, false, move |app, goal, handle| async move {
+ assert_eq!(
+ (app.as_str(), goal.as_str(), handle.as_str()),
+ ("TextEdit", "make a note", expected_id.as_str())
+ );
+ Err("transport lost".to_owned())
+ })
+ .await
+ .unwrap_err();
+ assert_eq!(transport_error, "transport lost");
+ assert!(pending().iter().any(|item| item.confirmation_id == id));
+ assert!(
+ take_approved(&id, Some("thread-a")).is_err(),
+ "a later denial must revoke earlier approval even when transport fails"
+ );
+
+ let module_error = confirm_with(&id, false, |_app, _goal, _handle| async {
+ Ok(DesktopResponse::err(
+ "run-goal",
+ DesktopError::new("CANCEL_FAILED", "still waiting"),
+ ))
+ })
+ .await
+ .unwrap_err();
+ assert_eq!(module_error, "still waiting");
+ assert!(pending().iter().any(|item| item.confirmation_id == id));
+
+ let wrong_stop = confirm_with(&id, false, |_app, _goal, _handle| async {
+ Ok(DesktopResponse::ok(
+ "run-goal",
+ json!({"stop":"confirmation_required"}),
+ ))
+ })
+ .await
+ .unwrap_err();
+ assert_eq!(wrong_stop, "desktop cancellation was not confirmed");
+ assert!(pending().iter().any(|item| item.confirmation_id == id));
+
+ let denied = confirm_with(&id, false, |_app, _goal, _handle| async {
+ Ok(DesktopResponse::ok("run-goal", json!({"stop":"cancelled"})))
+ })
+ .await
+ .unwrap();
+ assert_eq!(denied["approve"], false);
+ assert!(!pending().iter().any(|item| item.confirmation_id == id));
+}
+
+#[tokio::test]
+async fn denial_in_flight_cannot_be_approved_or_sent_twice() {
+ let _loopback = super::super::ops::test_loopback_guard();
+ let id = uuid::Uuid::new_v4().to_string();
+ record_save_prompt(&id);
+ let (started_tx, started_rx) = tokio::sync::oneshot::channel();
+ let (release_tx, release_rx) = tokio::sync::oneshot::channel();
+ let task_id = id.clone();
+ let task = tokio::spawn(async move {
+ confirm_with(&task_id, false, |_app, _goal, _handle| async move {
+ let _ = started_tx.send(());
+ let _ = release_rx.await;
+ Ok(DesktopResponse::ok("run-goal", json!({"stop":"cancelled"})))
+ })
+ .await
+ });
+ started_rx.await.unwrap();
+ let reject = "desktop cancellation is already in progress";
+ assert_eq!(
+ confirm_with(&id, true, |_app, _goal, _handle| async {
+ panic!("approval must not reach module while denial is in flight")
+ })
+ .await
+ .unwrap_err(),
+ reject
+ );
+ assert_eq!(
+ confirm_with(&id, false, |_app, _goal, _handle| async {
+ panic!("a second denial must not reach module")
+ })
+ .await
+ .unwrap_err(),
+ reject
+ );
+ assert_eq!(take_approved(&id, Some("thread-a")).unwrap_err(), reject);
+ release_tx.send(()).unwrap();
+ assert_eq!(task.await.unwrap().unwrap()["approve"], false);
+ assert!(!pending().iter().any(|item| item.confirmation_id == id));
+}