Skip to main content

agentmux_srv/server/app_api/
desktop.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The routes behind `Desktop` (docs/specs/SPEC_DESKTOP_DRIVING_2026_10_20.md
5//! §5.4–5.10, §6). srv is the single gate: the MCP tool asks `authorize`
6//! before it looks at or touches a native app, and srv answers from the
7//! grants, the blocklist, the limits and the Stop flag in
8//! `backend::desktop_gate`. The user's answers (a prompt, Stop) come only
9//! through the host (`/api/v1/host/desktop_request`, `/desktop_stop`), which
10//! agents can't impersonate.
11
12use std::sync::{Arc, Mutex};
13
14use axum::extract::State;
15use axum::http::StatusCode;
16use axum::response::{IntoResponse, Response};
17use axum::Json;
18use serde_json::{json, Value};
19
20use agentmux_common::time::now_ms_u64;
21use agentmux_common::api_types::{
22    DesktopAuthorizeRequest, DesktopPolicyRequest, DesktopRecordRequest, DesktopReleaseRequest, DesktopWindowRef,
23};
24
25use crate::backend::desktop_gate::{self as gate, Check, DesktopEvent};
26use crate::backend::rpc_types::*;
27use crate::backend::wconfig::SettingsType;
28use crate::server::AppState;
29
30use super::desktop_group::{self as group, Settled};
31use super::*;
32
33/// Actions `authorize` is asked about.
34const ACTIONS: &[&str] = &["look", "click", "scroll", "drag", "type", "key", "wait"];
35
36static ASKING: Mutex<Option<crate::backend::user_attention::Asking>> = Mutex::new(None);
37
38/// What a desktop-control request was filed for, by the request's id: the agent, its pane, the app
39/// and the minutes, which the countdown's end turns into the grant.
40#[derive(Debug, Clone, PartialEq, Eq)]
41pub(crate) struct GrantTarget {
42    /// The asking agent's uid, to leave out one that withdrew its ask.
43    pub uid: String,
44    pub agent: String,
45    pub block_id: String,
46    pub app: String,
47    pub minutes: u64,
48}
49
50static TARGETS: Mutex<Vec<(String, GrantTarget)>> = Mutex::new(Vec::new());
51
52/// The most targets remembered at once.
53const MAX_TARGETS: usize = 64;
54
55/// Remember that `request_id` was asked for by this agent in this pane. Agents that join the
56/// request each leave their own, so each gets its grant when the countdown ends.
57pub(crate) fn remember_target(request_id: &str, target: GrantTarget) {
58    let mut t = TARGETS.lock().unwrap_or_else(|e| e.into_inner());
59    // A request that ended without running (denied, vetoed, withdrawn) leaves no use for its entries.
60    t.retain(|(id, _)| crate::backend::sensitive_requests::registry().get(id).is_some_and(|r| r.status.is_open()));
61    if t.iter().any(|(id, x)| id == request_id && x.agent == target.agent && x.block_id == target.block_id) {
62        return;
63    }
64    if t.len() >= MAX_TARGETS {
65        t.remove(0);
66    }
67    t.push((request_id.to_string(), target));
68}
69
70/// The person pressed Stop on the agent in `block_id`: nothing already asked for may bring its
71/// access back.
72fn forget_pane(block_id: &str) {
73    TARGETS.lock().unwrap_or_else(|e| e.into_inner()).retain(|(_, t)| t.block_id != block_id);
74}
75
76/// Everything remembered for `request_id`, taken.
77pub(crate) fn take_targets(request_id: &str) -> Vec<GrantTarget> {
78    let mut t = TARGETS.lock().unwrap_or_else(|e| e.into_inner());
79    let (mine, rest): (Vec<_>, Vec<_>) = std::mem::take(&mut *t).into_iter().partition(|(id, _)| id == request_id);
80    *t = rest;
81    mine.into_iter().map(|(_, x)| x).collect()
82}
83
84/// The open request this agent already asked for to control `app` from this pane, if it still waits.
85/// Asking again while it does answers the same, without a new audit row for each call.
86fn open_ask(uid: &str, agent: &str, block_id: &str, app: &str) -> Option<String> {
87    let t = TARGETS.lock().unwrap_or_else(|e| e.into_inner());
88    t.iter()
89        .filter(|(_, x)| x.uid == uid && x.agent == agent && x.block_id == block_id && x.app == app)
90        .map(|(id, _)| id)
91        .find(|id| crate::backend::sensitive_requests::registry().get(id).is_some_and(|r| r.status.is_open() && r.asked_by(uid)))
92        .cloned()
93}
94
95/// The targets of agents that still ask: one that withdrew while the others' request went on is
96/// left out.
97fn still_asking(targets: Vec<GrantTarget>, request: Option<&crate::backend::sensitive_requests::Request>) -> Vec<GrantTarget> {
98    let askers = request.map(|r| r.askers()).unwrap_or_default();
99    targets.into_iter().filter(|t| askers.contains(&t.uid.as_str())).collect()
100}
101
102/// The grants a countdown that ended unvetoed makes (one for each agent that asked), and the audit
103/// lines saying who approved them.
104pub(crate) fn grant_after_countdown(state: &AppState, request_id: &str, approver: Option<&str>) -> Result<(), String> {
105    let targets = take_targets(request_id);
106    if targets.is_empty() {
107        return Err("the app this request was for is no longer known; ask again".to_string());
108    }
109    // The person's master switch and their Stop still win: nothing is granted while it is off.
110    if !policy(state).enabled {
111        return Err(OFF.to_string());
112    }
113    let targets = still_asking(targets, crate::backend::sensitive_requests::registry().get(request_id).as_ref());
114    if targets.is_empty() {
115        return Err("everyone who asked has withdrawn or been stopped".to_string());
116    }
117    for t in targets {
118        gate::with_gate(|g| g.grant(&t.agent, &t.block_id, &t.app, Some(t.minutes), now_ms_u64()));
119        gate::audit(&json!({
120            "ts_ms": now_ms_u64(),
121            "agent": t.agent,
122            "app": t.app,
123            "action": "grant",
124            "decision": "granted",
125            "details": { "by": approver.map_or_else(|| "no super agent".to_string(), |a| crate::backend::rpc::actor::Actor::Agent(a.to_string()).label()), "minutes": t.minutes, "request": request_id },
126        }));
127    }
128    publish(state);
129    Ok(())
130}
131
132pub fn register(engine: &Arc<WshRpcEngine>, _state: &AppState) {
133    engine.register_typed(COMMAND_APP_DESKTOP, move |_req: Option<NoArgsReq>, _ctx| async move {
134        Ok::<_, String>(snapshot())
135    });
136}
137
138fn snapshot() -> DesktopEvent {
139    gate::with_gate(|g| g.event(now_ms_u64()))
140}
141
142/// Tell every window what is waiting and what is granted, and ask for the
143/// user's attention while a prompt is open.
144fn publish(state: &AppState) {
145    let event = snapshot();
146    let mut asking = ASKING.lock().unwrap_or_else(|e| e.into_inner());
147    *asking = event.requests.first().map(|r| {
148        crate::backend::user_attention::Asking::start(
149            &state.broker,
150            &state.mstore,
151            "",
152            "desktop",
153            &format!("{} asks to control {}", r.agent, r.app),
154        )
155    });
156    drop(asking);
157    state.broker.publish_event::<crate::backend::mps_events::AppDesktop>(&event, vec![], 0);
158}
159
160/// The uid of the agent that is calling: from its token, else from the running agent of that name.
161fn asker_uid(caller: Option<&axum::Extension<crate::server::caller::Caller>>, agent: &str) -> String {
162    caller
163        .map(|c| &c.0)
164        .and_then(crate::server::caller::Caller::uid)
165        .map(str::to_string)
166        .or_else(|| crate::backend::reactive::get_global_handler().get_agent(agent).and_then(|r| r.uid))
167        .unwrap_or_default()
168}
169
170/// A request of a call that asked for several apps has ended. Records how, and returns whether the
171/// request belongs to such a call, so its own note is not sent: when the last one ends, the agent is
172/// told once about all of them.
173pub(crate) fn settled(request: &crate::backend::sensitive_requests::Request, outcome: Settled) -> bool {
174    // A request that another agent joined, or that the call's agent withdrew, sends its own note to every asker.
175    let (held, done) = group::settle_member(&request.id, outcome, &request.askers(), &group::request_is_open);
176    if let Some((block_id, said)) = done {
177        tell(&block_id, &said);
178    }
179    held
180}
181
182/// Whether the notes about this request's progress (approved, counting down) are left out, because
183/// its call asked for several apps and says it once at the end.
184pub(crate) fn holds_progress_notes(request: &crate::backend::sensitive_requests::Request) -> bool {
185    group::holds(request)
186}
187
188/// Tell the agent in pane `block_id` something, as an `[AgentMux]` note.
189fn tell(block_id: &str, text: &str) {
190    let handler = crate::backend::reactive::get_global_handler();
191    let Some(target) = handler
192        .list_agents()
193        .into_iter()
194        .find(|r| r.block_id == block_id)
195        .map(|r| r.uid.unwrap_or(r.agent_id))
196    else {
197        return;
198    };
199    let _ = handler.deliver_system_note(&target, text);
200}
201
202struct Policy {
203    enabled: bool,
204    added: Vec<String>,
205    allowed: Vec<String>,
206    grant_minutes: u64,
207}
208
209fn names(settings: &SettingsType, key: &str) -> Vec<String> {
210    settings
211        .extra
212        .get(key)
213        .and_then(Value::as_array)
214        .map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect())
215        .unwrap_or_default()
216}
217
218fn policy(state: &AppState) -> Policy {
219    let settings = state.config_watcher.get_settings();
220    Policy {
221        enabled: settings.extra.get(gate::SETTING_ENABLED).and_then(Value::as_bool).unwrap_or(false),
222        added: names(&settings, gate::SETTING_BLOCKLIST),
223        allowed: names(&settings, gate::SETTING_ALLOWLIST),
224        grant_minutes: settings
225            .extra
226            .get(gate::SETTING_GRANT_MINUTES)
227            .and_then(Value::as_u64)
228            .filter(|m| (1..=24 * 60).contains(m))
229            .unwrap_or(gate::DEFAULT_GRANT_MINUTES),
230    }
231}
232
233const OFF: &str = "Desktop driving is off. The user turns it on in Settings > Agents > Desktop driving; until they do, nothing is captured or controlled.";
234
235fn caller_block(
236    state: &AppState,
237    caller: Option<&axum::Extension<crate::server::caller::Caller>>,
238    auth: &agentmux_common::api_types::UiAutomationAuth,
239) -> Result<String, Response> {
240    crate::server::ui_handlers::verified_block_id(state, caller.map(|c| &c.0), auth)
241        .map_err(|e| (StatusCode::UNAUTHORIZED, Json(json!({ "error": e }))).into_response())
242}
243
244fn audit_line(agent: &str, w: &DesktopWindowRef, action: &str, decision: &str, extra: Value) {
245    gate::audit(&json!({
246        "ts_ms": now_ms_u64(),
247        "agent": agent,
248        "app": gate::app_key(&w.app),
249        "window": w.id,
250        "action": action,
251        "decision": decision,
252        "details": extra,
253    }));
254}
255
256fn reply(status: &str, message: &str) -> Response {
257    Json(json!({ "status": status, "message": message })).into_response()
258}
259
260/// `POST /api/v1/agent/desktop/policy`: whether `Desktop` is on, and each
261/// listed window's state (`blocked` with a reason, or `granted`).
262pub(crate) async fn handle_policy(
263    State(state): State<AppState>,
264    caller: Option<axum::Extension<crate::server::caller::Caller>>,
265    Json(req): Json<DesktopPolicyRequest>,
266) -> Response {
267    let block_id = match caller_block(&state, caller.as_ref(), &req.auth) {
268        Ok(b) => b,
269        Err(r) => return r,
270    };
271    let p = policy(&state);
272    let agent = req.auth.agent_id.as_str();
273    let now = now_ms_u64();
274    let windows: Vec<Value> = req
275        .windows
276        .iter()
277        .map(|w| {
278            let blocked = gate::blocked_reason(&w.app, &w.title, &p.added, &p.allowed);
279            let granted = blocked.is_none() && gate::with_gate(|g| g.has_grant(agent, &block_id, &gate::app_key(&w.app), now));
280            // The skill for this app, if the catalog has one: a pointer for the agent to read, never a grant.
281            let skill = crate::backend::computer_use_skill::skill_for_executable(&state.identity_store, "windows", &w.app);
282            json!({ "id": w.id, "blocked": blocked, "granted": granted, "skill": skill })
283        })
284        .collect();
285    Json(json!({ "enabled": p.enabled, "windows": windows })).into_response()
286}
287
288/// `POST /api/v1/agent/desktop/authorize`: may this agent do `action` on that
289/// window now? Waits while the user is asked.
290pub(crate) async fn handle_authorize(
291    State(state): State<AppState>,
292    caller: Option<axum::Extension<crate::server::caller::Caller>>,
293    Json(req): Json<DesktopAuthorizeRequest>,
294) -> Response {
295    let block_id = match caller_block(&state, caller.as_ref(), &req.auth) {
296        Ok(b) => b,
297        Err(r) => return r,
298    };
299    let agent = req.auth.agent_id.clone();
300    let w = &req.window;
301    if req.action == "seal" {
302        let Some(call) = req.group.as_deref().filter(|c| !c.is_empty() && c.len() <= 64) else {
303            return (StatusCode::BAD_REQUEST, Json(json!({ "error": "seal needs the call's group id" }))).into_response();
304        };
305        let uid = asker_uid(caller.as_ref(), &agent);
306        if let Some((pane, said)) = group::seal(&group::key(&uid, &block_id, call), &group::request_is_open) {
307            tell(&pane, &said);
308        }
309        return reply("sealed", "");
310    }
311    if !ACTIONS.contains(&req.action.as_str()) {
312        return (StatusCode::BAD_REQUEST, Json(json!({ "error": format!("unknown desktop action {:?}", req.action) }))).into_response();
313    }
314    let p = policy(&state);
315    if !p.enabled {
316        return reply("refused", OFF);
317    }
318    if let Some(why) = gate::blocked_reason(&w.app, &w.title, &p.added, &p.allowed) {
319        audit_line(&agent, w, &req.action, "refused:blocked", json!({ "why": why }));
320        return reply("refused", &format!("{} can't be controlled: {why}.", gate::app_key(&w.app)));
321    }
322    let app = gate::app_key(&w.app);
323    // At most a few spins, while TooFast waits half a second. Ask never waits
324    // for the user here: the call answers `pending` at once, so the agent stays
325    // free for the user's messages, and the answer comes as an [AgentMux] note.
326    for _ in 0..8 {
327        match gate::with_gate(|g| g.check(&agent, &block_id, &app, now_ms_u64())) {
328            Check::Allow { grant_id } => {
329                return Json(json!({ "status": "allow", "grant_id": grant_id, "message": "" })).into_response();
330            }
331            Check::Stopped => {
332                audit_line(&agent, w, &req.action, "stopped", Value::Null);
333                return reply("stopped", "The user pressed Stop. Don't carry on with this app; ask them what they want.");
334            }
335            Check::Denied => {
336                audit_line(&agent, w, &req.action, "denied", Value::Null);
337                return reply("denied", &format!("The user said no to controlling {app}. Don't ask again this session."));
338            }
339            Check::TooFast { wait_ms } => tokio::time::sleep(std::time::Duration::from_millis(wait_ms)).await,
340            Check::Ask => {
341                // Asked for like any sensitive operation: the super agent decides and the person
342                // can veto the countdown. Asking again for the same thing joins the open request.
343                let uid = asker_uid(caller.as_ref(), &agent);
344                if uid.is_empty() {
345                    return reply("refused", "This needs the agent's own token to ask for.");
346                }
347                // The grant is for the app, not a window, so the request is too: asking again for
348                // another window, or after its title changed, joins it. The title is only context.
349                if let Some(open) = open_ask(&uid, &agent, &block_id, &app) {
350                    // Another window of an app this call already asked for: its answer is in the call's one note.
351                    let in_call = req.group.as_deref().is_some_and(|call| group::in_group(&group::key(&uid, &block_id, call), &open));
352                    let message = pending_message(&app, if in_call { "it is already asked for in this call" } else { "it is already asked for" });
353                    return Json(json!({ "status": "pending", "message": message, "grouped": in_call })).into_response();
354                }
355                let title: String = w.title.chars().take(80).collect();
356                let scope = format!("{app} for {} minutes", p.grant_minutes);
357                let facts = std::collections::BTreeMap::from([("scope".to_string(), scope)]);
358                let reason = format!("control {app} (window: {title}) for the user");
359                return match crate::server::sensitive_handlers::file_request(&state, &uid, &agent, "desktop_control_grant", &facts, &reason).await {
360                    Ok(filed) => {
361                        let id = filed["id"].as_str().unwrap_or_default().to_string();
362                        remember_target(&id, GrantTarget { uid: uid.clone(), agent: agent.clone(), block_id: block_id.clone(), app: app.clone(), minutes: p.grant_minutes });
363                        audit_line(&agent, w, &req.action, "asked", json!({ "request": id }));
364                        let review = filed["review"].as_str().unwrap_or("");
365                        // A request another agent already asked for, and that this one joined, keeps its notes to
366                        // every asker: it is not part of this call's group.
367                        let joined = filed["joined"].as_bool() == Some(true);
368                        let added = req.group.as_deref().filter(|_| !joined).map(|call| {
369                            let key = group::key(&uid, &block_id, call);
370                            let added = group::add(&key, &block_id, &id, &app);
371                            (key, added)
372                        });
373                        let grouped = added.as_ref().is_some_and(|(_, a)| a.grouped());
374                        if let Some((key, group::Added::Created)) = added {
375                            start_group_deadline(state.clone(), key);
376                        }
377                        let message = if grouped { grouped_pending_message(&app, review) } else { pending_message(&app, review) };
378                        Json(json!({ "status": "pending", "message": message, "grouped": grouped })).into_response()
379                    }
380                    Err(e) => reply("refused", &e),
381                };
382            }
383        }
384    }
385    reply("refused", "Couldn't get a slot to act; try again.")
386}
387
388/// What a call that asked answers.
389fn pending_message(app: &str, review: &str) -> String {
390    format!(
391        "Asked for permission to control {app} as a sensitive operation ({review}); nothing was done yet. If the \
392         super agent approves, the person sees a countdown and can veto it. Don't wait for it: carry on with other \
393         work or end your turn. An [AgentMux] note brings the answer, then call Desktop again."
394    )
395}
396
397/// End a call's group when its time is up, so a request that ends in a way nothing reported can't
398/// hold its agent's notes back: the agent is told what is known, and what is still waiting sends its
399/// own note.
400fn start_group_deadline(_state: AppState, key: String) {
401    tokio::spawn(async move {
402        tokio::time::sleep(group::GROUP_TTL).await;
403        if let Some((block_id, said)) = group::flush(&key, &group::request_is_open) {
404            tell(&block_id, &said);
405        }
406    });
407}
408
409/// What a call that asked for several apps answers for each app that had to be asked.
410fn grouped_pending_message(app: &str, review: &str) -> String {
411    format!("Asked for permission to control {app} as a sensitive operation ({review}); nothing was done yet.")
412}
413
414/// `POST /api/v1/agent/desktop/record`: what an authorized action did.
415pub(crate) async fn handle_record(
416    State(state): State<AppState>,
417    caller: Option<axum::Extension<crate::server::caller::Caller>>,
418    Json(req): Json<DesktopRecordRequest>,
419) -> Response {
420    if let Err(r) = caller_block(&state, caller.as_ref(), &req.auth) {
421        return r;
422    }
423    gate::audit(&json!({
424        "ts_ms": now_ms_u64(),
425        "agent": req.auth.agent_id,
426        "app": gate::app_key(&req.window.app),
427        "window": req.window.id,
428        "action": req.action,
429        "grant": req.grant_id,
430        "result": req.result,
431        "details": req.details,
432    }));
433    publish(&state);
434    // A grant's `active` ("Driving", not "May drive") is decided when the event
435    // is published, so publish again once it lapses; nothing else would until
436    // the next action (#5334). Extra ones from a burst of
437    // actions are harmless: each reads the gate as it is then.
438    let later = state.clone();
439    tokio::spawn(async move {
440        tokio::time::sleep(std::time::Duration::from_millis(gate::DRIVING_SHOWN_MS + 250)).await;
441        publish(&later);
442    });
443    Json(json!({ "ok": true })).into_response()
444}
445
446/// `POST /api/v1/agent/desktop/release`: the agent gives its grant back.
447pub(crate) async fn handle_release(
448    State(state): State<AppState>,
449    caller: Option<axum::Extension<crate::server::caller::Caller>>,
450    Json(req): Json<DesktopReleaseRequest>,
451) -> Response {
452    let block_id = match caller_block(&state, caller.as_ref(), &req.auth) {
453        Ok(b) => b,
454        Err(r) => return r,
455    };
456    let app = gate::app_key(&req.window.app);
457    let released = gate::with_gate(|g| g.release(&req.auth.agent_id, &block_id, &app));
458    if released {
459        audit_line(&req.auth.agent_id, &req.window, "release", "released", Value::Null);
460        publish(&state);
461    }
462    Json(json!({ "released": released })).into_response()
463}
464
465#[derive(Debug, serde::Deserialize)]
466pub(crate) struct HostDesktopStop {
467    block_id: String,
468}
469
470fn host_only() -> Response {
471    (StatusCode::FORBIDDEN, Json(json!({ "ok": false, "error": "only the AgentMux host can answer a desktop request" }))).into_response()
472}
473
474/// `POST /api/v1/host/desktop_request`: the user's answer to a prompt, relayed
475/// by the CEF host with its own token. The instance auth key, which every
476/// agent has, isn't enough.
477pub(crate) async fn handle_host_request(
478    State(state): State<AppState>,
479    headers: axum::http::HeaderMap,
480    Json(body): Json<gate::DesktopAnswer>,
481) -> Response {
482    if !crate::server::ui_handlers::from_host(&state, &headers).await {
483        return host_only();
484    }
485    let minutes = policy(&state).grant_minutes;
486    match gate::with_gate(|g| g.answer(&body.id, body.choice, now_ms_u64(), minutes)) {
487        Ok(()) => {
488            publish(&state);
489            Json(json!({ "ok": true })).into_response()
490        }
491        Err(e) => (StatusCode::CONFLICT, Json(json!({ "ok": false, "error": e }))).into_response(),
492    }
493}
494
495/// `POST /api/v1/host/desktop_stop`: the user's Stop on the agent in a pane.
496pub(crate) async fn handle_host_stop(
497    State(state): State<AppState>,
498    headers: axum::http::HeaderMap,
499    Json(body): Json<HostDesktopStop>,
500) -> Response {
501    if !crate::server::ui_handlers::from_host(&state, &headers).await {
502        return host_only();
503    }
504    let revoked = gate::with_gate(|g| g.stop(&body.block_id));
505    forget_pane(&body.block_id);
506    publish(&state);
507    gate::audit(&json!({ "ts_ms": now_ms_u64(), "action": "stop", "decision": "stopped", "block": body.block_id, "revoked": revoked }));
508    tell(&body.block_id, "[AgentMux] The user pressed Stop on your desktop control. Your grants are gone; ask them before controlling an app again.");
509    Json(json!({ "ok": true, "revoked": revoked })).into_response()
510}
511
512#[cfg(test)]
513mod tests {
514    use axum::body::Body;
515    use axum::http::{Request, StatusCode};
516    use serde_json::json;
517    use tower::ServiceExt;
518
519    async fn post(app: &axum::Router, uri: &str, host_token: Option<&str>, body: serde_json::Value) -> (StatusCode, serde_json::Value) {
520        let mut b = Request::builder()
521            .uri(uri)
522            .method("POST")
523            .header("X-AuthKey", "test-secret-key")
524            .header("Content-Type", "application/json");
525        if let Some(token) = host_token {
526            b = b.header("X-Host-Token", token);
527        }
528        let resp = app.clone().oneshot(b.body(Body::from(body.to_string())).unwrap()).await.unwrap();
529        let status = resp.status();
530        let body = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
531        (status, serde_json::from_slice(&body).unwrap_or_default())
532    }
533
534    async fn router() -> axum::Router {
535        let state = crate::server::tests::test_state();
536        *state.host_ipc.lock().await = Some(crate::server::state::HostIpc { port: 1, token: "host-ipc-token".into() });
537        crate::server::build_router(state)
538    }
539
540    #[test]
541    fn a_request_remembers_each_asker_once_and_forgets_requests_that_ended() {
542        use crate::backend::sensitive_requests::registry;
543        let now = agentmux_common::time::now_ms();
544        let scope = |name: &str| -> std::collections::BTreeMap<String, String> { [("scope".to_string(), format!("{name}-{}", uuid::Uuid::new_v4().simple()))].into_iter().collect() };
545        let open = registry().request("u-d", "d", "desktop_control_grant", &scope("notepad"), "", now).unwrap().id;
546        let t = super::GrantTarget { uid: "u-d".into(), agent: "a".into(), block_id: "b".into(), app: "notepad".into(), minutes: 30 };
547        super::remember_target(&open, t.clone());
548        super::remember_target(&open, t.clone());
549        // An agent in another pane that joined the request is remembered too.
550        let joiner = super::GrantTarget { uid: "u-j".into(), agent: "c".into(), block_id: "b2".into(), ..t.clone() };
551        super::remember_target(&open, joiner.clone());
552        let ended = registry().request("u-d", "d", "desktop_control_grant", &scope("word"), "", now).unwrap().id;
553        super::remember_target(&ended, t.clone());
554        registry().deny(&ended, "boss", "no", now).unwrap();
555        super::remember_target("a-later-request", t.clone());
556        assert_eq!(super::take_targets(&ended), vec![], "ended without running: forgotten");
557        assert_eq!(super::take_targets(&open), vec![t, joiner], "each asker once, in order");
558        assert_eq!(super::take_targets(&open), vec![], "used once");
559    }
560
561    #[test]
562    fn an_agent_that_asks_again_while_its_request_waits_is_recognised() {
563        use crate::backend::sensitive_requests::registry;
564        let now = agentmux_common::time::now_ms();
565        let scope = [("scope".to_string(), format!("notepad-{}", uuid::Uuid::new_v4().simple()))].into_iter().collect();
566        let id = registry().request("u-r", "r", "desktop_control_grant", &scope, "", now).unwrap().id;
567        let t = super::GrantTarget { uid: "u-r".into(), agent: "r".into(), block_id: "repeat-pane".into(), app: "notepad".into(), minutes: 30 };
568        assert_eq!(super::open_ask("u-r", "r", "repeat-pane", "notepad"), None, "nothing asked yet");
569        super::remember_target(&id, t);
570        assert_eq!(super::open_ask("u-r", "r", "repeat-pane", "notepad"), Some(id.clone()));
571        assert_eq!(super::open_ask("u-r", "r", "repeat-pane", "word"), None, "another app is a new ask");
572        assert_eq!(super::open_ask("u-r", "r", "other-pane", "notepad"), None, "another pane is a new ask");
573        registry().deny(&id, "boss", "no", now).unwrap();
574        assert_eq!(super::open_ask("u-r", "r", "repeat-pane", "notepad"), None, "an ended request is asked afresh");
575    }
576
577    #[test]
578    fn pressing_stop_on_a_pane_forgets_what_was_asked_for_it() {
579        use crate::backend::sensitive_requests::registry;
580        let scope = [("scope".to_string(), format!("notepad-{}", uuid::Uuid::new_v4().simple()))].into_iter().collect();
581        let id = registry().request("u-d", "d", "desktop_control_grant", &scope, "", agentmux_common::time::now_ms()).unwrap().id;
582        let t = super::GrantTarget { uid: "u-d".into(), agent: "a".into(), block_id: "stopped-pane".into(), app: "notepad".into(), minutes: 30 };
583        let other = super::GrantTarget { uid: "u-d".into(), agent: "c".into(), block_id: "other-pane".into(), ..t.clone() };
584        super::remember_target(&id, t);
585        super::remember_target(&id, other.clone());
586        super::forget_pane("stopped-pane");
587        assert_eq!(super::take_targets(&id), vec![other], "only the stopped pane's ask is gone");
588    }
589
590    #[test]
591    fn an_agent_that_withdrew_is_left_out_of_the_grant() {
592        use crate::backend::sensitive_requests::registry;
593        let now = agentmux_common::time::now_ms();
594        let scope = [("scope".to_string(), format!("notepad-{}", uuid::Uuid::new_v4().simple()))].into_iter().collect();
595        let id = registry().request("u-first", "first", "desktop_control_grant", &scope, "", now).unwrap().id;
596        registry().request("u-second", "second", "desktop_control_grant", &scope, "", now).unwrap();
597        let mk = |uid: &str, block: &str| super::GrantTarget { uid: uid.into(), agent: uid.into(), block_id: block.into(), app: "notepad".into(), minutes: 30 };
598        let both = vec![mk("u-first", "b1"), mk("u-second", "b2")];
599        assert_eq!(super::still_asking(both.clone(), registry().get(&id).as_ref()), both, "both still ask");
600        registry().cancel(&id, "u-first", now).unwrap();
601        assert_eq!(super::still_asking(both.clone(), registry().get(&id).as_ref()), vec![mk("u-second", "b2")], "the one that withdrew is left out");
602        assert_eq!(super::still_asking(both, None), vec![], "no request, no grant");
603    }
604
605    #[tokio::test]
606    async fn nothing_is_granted_while_desktop_driving_is_off() {
607        let state = crate::server::tests::test_state();
608        let scope = [("scope".to_string(), format!("notepad-{}", uuid::Uuid::new_v4().simple()))].into_iter().collect();
609        let id = crate::backend::sensitive_requests::registry().request("u-d", "d", "desktop_control_grant", &scope, "", agentmux_common::time::now_ms()).unwrap().id;
610        super::remember_target(&id, super::GrantTarget { uid: "u-d".into(), agent: "a".into(), block_id: "b".into(), app: "notepad".into(), minutes: 30 });
611        let err = super::grant_after_countdown(&state, &id, Some("boss")).unwrap_err();
612        assert!(err.contains("Desktop driving is off") && err.contains("Settings > Agents > Desktop driving"), "{err}");
613        assert!(!crate::backend::desktop_gate::with_gate(|g| g.has_grant("a", "b", "notepad", agentmux_common::time::now_ms_u64())));
614        let gone = super::grant_after_countdown(&state, &id, None).unwrap_err();
615        assert!(gone.contains("no longer known"), "the targets were taken: {gone}");
616    }
617
618    // §5.4: the user's answer and Stop come only through the host. The
619    // instance auth key, which every agent has, isn't enough.
620    #[tokio::test]
621    async fn only_the_host_can_answer_a_prompt_or_press_stop() {
622        let app = router().await;
623        for (uri, body) in [
624            ("/api/v1/host/desktop_request", json!({ "id": "r1", "choice": "timed" })),
625            ("/api/v1/host/desktop_stop", json!({ "block_id": "b1" })),
626        ] {
627            let (s, out) = post(&app, uri, None, body.clone()).await;
628            assert_eq!(s, StatusCode::FORBIDDEN, "{uri}: {out}");
629            let (s, _) = post(&app, uri, Some("not-the-token"), body).await;
630            assert_eq!(s, StatusCode::FORBIDDEN, "{uri}");
631        }
632    }
633
634    #[tokio::test]
635    async fn the_host_gets_through_and_an_unknown_prompt_is_a_conflict() {
636        let app = router().await;
637        let (s, out) = post(&app, "/api/v1/host/desktop_request", Some("host-ipc-token"), json!({ "id": "nope", "choice": "timed" })).await;
638        assert_eq!(s, StatusCode::CONFLICT, "{out}");
639        let (s, out) = post(&app, "/api/v1/host/desktop_stop", Some("host-ipc-token"), json!({ "block_id": "no-such-pane" })).await;
640        assert_eq!(s, StatusCode::OK, "{out}");
641        assert_eq!(out["revoked"], 0);
642    }
643
644    // An agent whose signature doesn't check out never reaches the gate.
645    #[tokio::test]
646    async fn an_agent_route_without_a_valid_signature_is_refused() {
647        let app = router().await;
648        let window = json!({ "id": 1, "app": "notepad.exe", "title": "t" });
649        for (uri, body) in [
650            ("/api/v1/agent/desktop/authorize", json!({ "agent_id": "x", "ts_secs": 1, "sig": "bad", "action": "look", "window": window })),
651            ("/api/v1/agent/desktop/policy", json!({ "agent_id": "x", "ts_secs": 1, "sig": "bad", "windows": [] })),
652            ("/api/v1/agent/desktop/release", json!({ "agent_id": "x", "ts_secs": 1, "sig": "bad", "window": window })),
653        ] {
654            let (s, out) = post(&app, uri, None, body).await;
655            assert_eq!(s, StatusCode::UNAUTHORIZED, "{uri}: {out}");
656        }
657    }
658}