Skip to main content

agentmux_srv_core/backend/
drone_approval.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The approvals a Drone run is waiting for (`SPEC_DRONE_REAL_WORLD_JOBS_2026_11_11.md` §4.2 and §6.4).
5//!
6//! An Approval block stops its run and shows a person the proposed action and the inputs it was made from, the
7//! ones that came from outside text marked as such. Each open approval is kept here, with the key of the wait the
8//! run holds. The key never leaves AgentMux: an answer names the run and the block, and this finds the key. That
9//! is what keeps an agent, which can read a run's events, from answering for the person: the answering route
10//! accepts only the person's own client (`server::drone_approval_handlers`).
11//!
12//! It lives in the core, beside `drone_wait`, so the handlers can answer without reaching up into `drone/`.
13
14use std::collections::HashMap;
15use std::sync::{LazyLock, Mutex};
16
17use serde::{Deserialize, Serialize};
18use serde_json::json;
19
20/// One thing the card shows: a label, the text, and whether it came from outside text.
21#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)]
22#[ts(export, export_to = "../../../frontend/types/rpc/")]
23pub struct ApprovalItem {
24    pub label: String,
25    pub text: String,
26    /// Outside text (an event, an API body, an agent's reply): marked on the card.
27    pub tainted: bool,
28}
29
30/// An approval a run waits on.
31#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)]
32#[ts(export, export_to = "../../../frontend/types/rpc/")]
33pub struct DroneApproval {
34    pub run_id: String,
35    pub block_id: String,
36    pub drone_id: String,
37    /// The proposed action, in the graph's own words.
38    pub title: String,
39    pub items: Vec<ApprovalItem>,
40    /// When silence rejects it, in milliseconds since 1970.
41    #[ts(type = "number")]
42    pub deadline_ms: i64,
43}
44
45struct Open {
46    approval: DroneApproval,
47    key: String,
48}
49
50static OPEN: LazyLock<Mutex<HashMap<(String, String), Open>>> = LazyLock::new(Mutex::default);
51
52fn open_map() -> std::sync::MutexGuard<'static, HashMap<(String, String), Open>> {
53    OPEN.lock().unwrap_or_else(|e| e.into_inner())
54}
55
56/// The run holds this approval, waiting on `key`. A block run again (a restart took the wait up) replaces its entry.
57pub fn register(approval: DroneApproval, key: &str) {
58    let id = (approval.run_id.clone(), approval.block_id.clone());
59    open_map().insert(id, Open { approval, key: key.to_string() });
60}
61
62/// The approval is over, however it ended.
63pub fn forget(run_id: &str, block_id: &str) {
64    open_map().remove(&(run_id.to_string(), block_id.to_string()));
65}
66
67/// The approvals open now, of `drone_id` when it is named, newest deadline last.
68pub fn list(drone_id: &str) -> Vec<DroneApproval> {
69    let mut out: Vec<DroneApproval> = open_map().values().map(|o| o.approval.clone()).filter(|a| drone_id.is_empty() || a.drone_id == drone_id).collect();
70    out.sort_by(|a, b| (a.deadline_ms, &a.run_id, &a.block_id).cmp(&(b.deadline_ms, &b.run_id, &b.block_id)));
71    out
72}
73
74/// Answer the approval of `block_id` in `run_id`: yes or no, by `by` (who the record says answered). `Err` when none
75/// is open (it was answered, it timed out, or the run ended).
76pub fn answer(run_id: &str, block_id: &str, approve: bool, by: &str) -> Result<(), String> {
77    let key = {
78        let all = open_map();
79        match all.get(&(run_id.to_string(), block_id.to_string())) {
80            Some(o) => o.key.clone(),
81            None => return Err("nothing is waiting for an answer there: it was answered, it timed out, or the run ended".to_string()),
82        }
83    };
84    crate::backend::drone_wait::signal(&key, json!({ "approve": approve, "by": by }))
85}
86
87#[cfg(test)]
88mod tests {
89    use super::*;
90
91    fn card(run: &str, block: &str, drone: &str, deadline: i64) -> DroneApproval {
92        DroneApproval { run_id: run.into(), block_id: block.into(), drone_id: drone.into(), title: "Merge it".into(), items: vec![], deadline_ms: deadline }
93    }
94
95    #[tokio::test]
96    async fn an_answer_reaches_the_wait_the_run_holds_and_only_once() {
97        let key = crate::backend::drone_wait::new_key();
98        let rx = crate::backend::drone_wait::open(&key);
99        register(card("r1", "b", "d1", 5), &key);
100        answer("r1", "b", true, "operator").unwrap();
101        assert_eq!(rx.await.unwrap(), json!({ "approve": true, "by": "operator" }));
102        assert!(answer("r1", "b", false, "operator").is_err(), "a second answer finds nothing waiting");
103        forget("r1", "b");
104        assert!(answer("r1", "b", true, "operator").unwrap_err().contains("nothing is waiting"));
105    }
106
107    #[test]
108    fn the_list_is_by_drone_and_oldest_deadline_first_and_forgetting_removes() {
109        register(card("r-a", "b", "list-d1", 20), "k1");
110        register(card("r-b", "b", "list-d1", 10), "k2");
111        register(card("r-c", "b", "list-d2", 1), "k3");
112        let mine: Vec<String> = list("list-d1").into_iter().map(|a| a.run_id).collect();
113        assert_eq!(mine, ["r-b", "r-a"]);
114        assert!(list("").iter().any(|a| a.run_id == "r-c"), "no drone named lists every one");
115        forget("r-b", "b");
116        assert_eq!(list("list-d1").len(), 1);
117        for r in ["r-a", "r-c"] {
118            forget(r, "b");
119        }
120    }
121}