Skip to main content

agentmux_srv_core/backend/
desktop_gate.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The gate in front of `Desktop`: an agent clicking and typing in a native
5//! app (docs/specs/SPEC_DESKTOP_DRIVING_2026_10_20.md §5.4–5.6, §5.9).
6//!
7//! srv decides and remembers; the MCP tool acts. Before any action the tool
8//! asks [`authorize`]-side code (`server/app_api/desktop.rs`), which uses this
9//! module for:
10//! - **grants**: the user allows an agent to drive one app, for a time or for
11//!   the agent's session. They live in memory only, and are tied to the pane
12//!   (`block_id`) that asked, so a new session asks again;
13//! - **the blocklist**: apps that are never driven (password managers, web
14//!   browsers, AgentMux itself, trading and crypto apps), editable in settings;
15//! - **limits**: at most two input actions a second and 200 per grant;
16//! - **Stop**: the user's brake. It revokes an agent's grants, and the agent's
17//!   next action is told so once.
18//!
19//! The user's answer to a prompt comes only through the host
20//! (`POST /api/v1/host/desktop_request`), which agents can't impersonate, so a
21//! prompt-injected agent can't approve its own request.
22//!
23//! [`Gate`] is plain data with the clock passed in, so every rule below is
24//! tested without a UI.
25
26use std::collections::HashSet;
27use std::sync::Mutex;
28use std::time::Duration;
29
30use serde::{Deserialize, Serialize};
31use tokio::sync::oneshot;
32
33/// `desktop:enabled`: the tool is off unless this is true.
34pub const SETTING_ENABLED: &str = "desktop:enabled";
35/// `desktop:blocklist`: app names added to the default blocklist.
36pub const SETTING_BLOCKLIST: &str = "desktop:blocklist";
37/// `desktop:allowlist`: app names removed from the default blocklist.
38pub const SETTING_ALLOWLIST: &str = "desktop:allowlist";
39/// `desktop:grantminutes`: how long "Allow for a while" lasts.
40pub const SETTING_GRANT_MINUTES: &str = "desktop:grantminutes";
41pub const DEFAULT_GRANT_MINUTES: u64 = 30;
42
43/// Input actions allowed per grant before the user is asked again.
44pub const MAX_ACTIONS_PER_GRANT: u32 = 200;
45/// Two input actions a second.
46pub const MIN_ACTION_GAP_MS: u64 = 500;
47/// How long a prompt waits for the user.
48pub const ANSWER_WAIT: Duration = Duration::from_secs(10 * 60);
49/// A grant shows as "Driving" this long after its last action.
50pub const DRIVING_SHOWN_MS: u64 = 10_000;
51
52/// An agent waiting for the user's yes or no on one app.
53#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)]
54#[ts(export, export_to = "../../../frontend/types/rpc/")]
55pub struct DesktopRequest {
56    pub id: String,
57    /// The agent that asked, by name.
58    pub agent: String,
59    /// The app, as its executable's name without the extension.
60    pub app: String,
61    /// The window's title when it asked.
62    pub title: String,
63    #[ts(type = "number")]
64    pub asked_ms: u64,
65    /// The asking agent's pane.
66    pub block_id: String,
67    /// How long "Allow for a while" lasts, for the prompt's button.
68    #[ts(type = "number")]
69    pub grant_minutes: u64,
70}
71
72/// An app an agent may drive right now, for the pane's "Driving" badge.
73#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)]
74#[ts(export, export_to = "../../../frontend/types/rpc/")]
75pub struct DesktopGrantView {
76    pub agent: String,
77    pub app: String,
78    pub block_id: String,
79    /// When a timed grant ends; `None` for "until this session ends".
80    #[ts(type = "number | null")]
81    pub until_ms: Option<u64>,
82    /// Whether an action ran in the last [`DRIVING_SHOWN_MS`].
83    pub active: bool,
84}
85
86/// `app:desktop`: prompts waiting for the user, and the grants in force.
87#[derive(Debug, Clone, Default, Serialize, ts_rs::TS)]
88#[ts(export, export_to = "../../../frontend/types/rpc/")]
89pub struct DesktopEvent {
90    pub requests: Vec<DesktopRequest>,
91    pub grants: Vec<DesktopGrantView>,
92}
93
94/// What the user chose.
95#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
96#[serde(rename_all = "snake_case")]
97pub enum Choice {
98    /// Allow for `desktop:grantminutes`.
99    Timed,
100    /// Allow until this agent's session ends.
101    Session,
102    Deny,
103}
104
105/// The user's answer, relayed by the host (`POST /api/v1/host/desktop_request`).
106#[derive(Debug, Clone, Deserialize)]
107pub struct DesktopAnswer {
108    pub id: String,
109    pub choice: Choice,
110}
111
112#[derive(Debug)]
113struct Grant {
114    id: String,
115    agent: String,
116    app: String,
117    block_id: String,
118    until_ms: Option<u64>,
119    actions: u32,
120    last_action_ms: u64,
121}
122
123struct Pending {
124    request: DesktopRequest,
125    waiters: Vec<oneshot::Sender<Choice>>,
126}
127
128/// What [`Gate::check`] found.
129#[derive(Debug, PartialEq, Eq)]
130pub enum Check {
131    Allow { grant_id: String },
132    /// The user pressed Stop since the agent's last action.
133    Stopped,
134    /// The user said no to this app earlier in this session.
135    Denied,
136    /// Too soon after the last action; try again in `wait_ms`.
137    TooFast { wait_ms: u64 },
138    /// No grant: the user has to be asked.
139    Ask,
140}
141
142#[derive(Default)]
143pub struct Gate {
144    pending: Vec<Pending>,
145    grants: Vec<Grant>,
146    denied: HashSet<(String, String)>,
147    stopped: HashSet<String>,
148}
149
150impl Gate {
151    fn purge(&mut self, now: u64) {
152        self.grants.retain(|g| g.until_ms.map_or(true, |u| u > now));
153    }
154
155    /// Whether `agent` (in pane `block_id`) may act on `app` now, counting
156    /// this as an action when it may.
157    pub fn check(&mut self, agent: &str, block_id: &str, app: &str, now: u64) -> Check {
158        self.purge(now);
159        if self.stopped.remove(agent) {
160            return Check::Stopped;
161        }
162        if self.denied.contains(&(agent.to_string(), app.to_string())) {
163            return Check::Denied;
164        }
165        let Some(pos) = self
166            .grants
167            .iter()
168            .position(|g| g.agent == agent && g.app == app && g.block_id == block_id)
169        else {
170            return Check::Ask;
171        };
172        let g = &mut self.grants[pos];
173        if g.actions >= MAX_ACTIONS_PER_GRANT {
174            self.grants.remove(pos);
175            return Check::Ask;
176        }
177        let since = now.saturating_sub(g.last_action_ms);
178        if g.actions > 0 && since < MIN_ACTION_GAP_MS {
179            return Check::TooFast { wait_ms: MIN_ACTION_GAP_MS - since };
180        }
181        g.actions += 1;
182        g.last_action_ms = now;
183        Check::Allow { grant_id: g.id.clone() }
184    }
185
186    /// Whether the user is already being asked about `app` for this agent and
187    /// pane: a call that finds so answers `pending` without a second prompt.
188    pub fn asking(&self, agent: &str, block_id: &str, app: &str) -> bool {
189        self.pending
190            .iter()
191            .any(|p| p.request.agent == agent && p.request.app == app && p.request.block_id == block_id)
192    }
193
194    /// Queue a prompt for `request`; the answer arrives on the receiver. The
195    /// same agent asking again about the same app joins the prompt it has.
196    pub fn ask(&mut self, request: DesktopRequest) -> oneshot::Receiver<Choice> {
197        let (tx, rx) = oneshot::channel();
198        if let Some(p) = self
199            .pending
200            .iter_mut()
201            .find(|p| p.request.agent == request.agent && p.request.app == request.app && p.request.block_id == request.block_id)
202        {
203            p.waiters.push(tx);
204        } else {
205            self.pending.push(Pending { request, waiters: vec![tx] });
206        }
207        rx
208    }
209
210    /// Let `agent` in pane `block_id` control `app`: for `minutes`, or (`None`) until its session ends.
211    /// It replaces any grant that agent already has for the app.
212    pub fn grant(&mut self, agent: &str, block_id: &str, app: &str, minutes: Option<u64>, now: u64) {
213        self.grants.retain(|g| !(g.agent == agent && g.app == app && g.block_id == block_id));
214        self.grants.push(Grant {
215            id: uuid::Uuid::new_v4().to_string(),
216            agent: agent.to_string(),
217            app: app.to_string(),
218            block_id: block_id.to_string(),
219            until_ms: minutes.map(|m| now + m.max(1) * 60_000),
220            actions: 0,
221            last_action_ms: 0,
222        });
223    }
224
225    /// The user's answer to prompt `id`.
226    pub fn answer(&mut self, id: &str, choice: Choice, now: u64, grant_minutes: u64) -> Result<(), String> {
227        let Some(pos) = self.pending.iter().position(|p| p.request.id == id) else {
228            return Err("that request was already answered".into());
229        };
230        let p = self.pending.remove(pos);
231        let r = &p.request;
232        match choice {
233            Choice::Deny => {
234                self.denied.insert((r.agent.clone(), r.app.clone()));
235            }
236            Choice::Timed | Choice::Session => {
237                self.grant(&r.agent, &r.block_id, &r.app, (choice == Choice::Timed).then_some(grant_minutes), now);
238            }
239        }
240        for tx in p.waiters {
241            let _ = tx.send(choice);
242        }
243        Ok(())
244    }
245
246    /// A prompt nobody answered in time: take it back.
247    pub fn abandon(&mut self, id: &str) {
248        self.pending.retain(|p| p.request.id != id);
249    }
250
251    /// The user's Stop for the agent in pane `block_id`: its grants end and
252    /// its next action hears so. Prompts it has waiting are dropped.
253    pub fn stop(&mut self, block_id: &str) -> usize {
254        let agents: HashSet<String> = self
255            .grants
256            .iter()
257            .filter(|g| g.block_id == block_id)
258            .map(|g| g.agent.clone())
259            .chain(self.pending.iter().filter(|p| p.request.block_id == block_id).map(|p| p.request.agent.clone()))
260            .collect();
261        let before = self.grants.len();
262        self.grants.retain(|g| g.block_id != block_id);
263        self.pending.retain(|p| p.request.block_id != block_id);
264        let revoked = before - self.grants.len();
265        self.stopped.extend(agents);
266        revoked
267    }
268
269    /// Whether `agent` in pane `block_id` holds a grant on `app` right now.
270    pub fn has_grant(&mut self, agent: &str, block_id: &str, app: &str, now: u64) -> bool {
271        self.purge(now);
272        self.grants.iter().any(|g| g.agent == agent && g.app == app && g.block_id == block_id)
273    }
274
275    /// The agent gives its own grant on `app` back.
276    pub fn release(&mut self, agent: &str, block_id: &str, app: &str) -> bool {
277        let before = self.grants.len();
278        self.grants.retain(|g| !(g.agent == agent && g.block_id == block_id && g.app == app));
279        before != self.grants.len()
280    }
281
282    pub fn event(&mut self, now: u64) -> DesktopEvent {
283        self.purge(now);
284        DesktopEvent {
285            requests: self.pending.iter().map(|p| p.request.clone()).collect(),
286            grants: self
287                .grants
288                .iter()
289                .map(|g| DesktopGrantView {
290                    agent: g.agent.clone(),
291                    app: g.app.clone(),
292                    block_id: g.block_id.clone(),
293                    until_ms: g.until_ms,
294                    active: g.actions > 0 && now.saturating_sub(g.last_action_ms) < DRIVING_SHOWN_MS,
295                })
296                .collect(),
297        }
298    }
299}
300
301static GATE: Mutex<Option<Gate>> = Mutex::new(None);
302
303/// Run `f` on the process-wide gate.
304pub fn with_gate<T>(f: impl FnOnce(&mut Gate) -> T) -> T {
305    let mut guard = GATE.lock().unwrap_or_else(|e| e.into_inner());
306    f(guard.get_or_insert_with(Gate::default))
307}
308
309// ---------------------------------------------------------------------------
310// The blocklist (spec §5.5)
311
312/// Apps never driven unless the user takes them off the list. Matched against
313/// an executable's name (no extension, lower case). A convenience, not
314/// coverage: the user's own list sits beside it.
315const DEFAULT_BLOCKED: &[(&str, &str)] = &[
316    // password managers
317    ("keepass", "a password manager"),
318    ("keepassxc", "a password manager"),
319    ("1password", "a password manager"),
320    ("bitwarden", "a password manager"),
321    ("lastpass", "a password manager"),
322    ("dashlane", "a password manager"),
323    ("enpass", "a password manager"),
324    ("nordpass", "a password manager"),
325    ("roboform", "a password manager"),
326    // web browsers: the Browser tool has the guards
327    ("chrome", "a web browser; use the Browser tool"),
328    ("msedge", "a web browser; use the Browser tool"),
329    ("firefox", "a web browser; use the Browser tool"),
330    ("brave", "a web browser; use the Browser tool"),
331    ("opera", "a web browser; use the Browser tool"),
332    ("vivaldi", "a web browser; use the Browser tool"),
333    ("chromium", "a web browser; use the Browser tool"),
334    ("iexplore", "a web browser; use the Browser tool"),
335    ("safari", "a web browser; use the Browser tool"),
336    ("arc", "a web browser; use the Browser tool"),
337    ("librewolf", "a web browser; use the Browser tool"),
338    ("waterfox", "a web browser; use the Browser tool"),
339    // the OS asking the user to confirm something
340    ("consent", "an operating system prompt"),
341    ("credentialuibroker", "an operating system prompt"),
342    ("logonui", "an operating system prompt"),
343    ("sechealthui", "Windows Security"),
344    // trading and crypto
345    ("metatrader", "a trading app"),
346    ("terminal64", "a trading app"),
347    ("tradingview", "a trading app"),
348    ("thinkorswim", "a trading app"),
349    ("tws", "a trading app"),
350    ("ledger live", "a crypto wallet"),
351    ("ledgerlive", "a crypto wallet"),
352    ("exodus", "a crypto wallet"),
353    ("electrum", "a crypto wallet"),
354    ("coinbase", "a crypto app"),
355    ("binance", "a crypto app"),
356];
357
358/// An executable name as the blocklist compares it: file name, no extension,
359/// lower case.
360pub fn app_key(exe: &str) -> String {
361    let name = exe.rsplit(['\\', '/']).next().unwrap_or(exe);
362    let name = name.strip_suffix(".exe").or_else(|| name.strip_suffix(".EXE")).unwrap_or(name);
363    name.trim().to_lowercase()
364}
365
366/// Why `app` (an executable name) with window `title` must not be driven, or
367/// `None`. `added` extends the defaults; `allowed` takes names off them. An
368/// entry matches the app's name exactly, or any part of the window title.
369pub fn blocked_reason(app: &str, title: &str, added: &[String], allowed: &[String]) -> Option<String> {
370    let app = app_key(app);
371    let title = title.to_lowercase();
372    let norm = |s: &String| app_key(s);
373    let allowed: HashSet<String> = allowed.iter().map(norm).collect();
374    if app.starts_with("agentmux") {
375        return Some("AgentMux itself; use the UI tool".into());
376    }
377    if let Some((_, why)) = DEFAULT_BLOCKED.iter().find(|(name, _)| *name == app && !allowed.contains(*name)) {
378        return Some((*why).to_string());
379    }
380    if (title.contains("windows security") || title.contains("user account control")) && !allowed.contains("windowssecurity") {
381        return Some("an operating system prompt".into());
382    }
383    for entry in added {
384        let e = norm(entry);
385        if e.is_empty() {
386            continue;
387        }
388        if e == app || title.contains(&e) {
389            return Some(format!("on your blocklist ({entry})"));
390        }
391    }
392    None
393}
394
395// ---------------------------------------------------------------------------
396// The audit log (spec §5.10)
397
398/// Append one line to `desktop-audit.log`, next to the window-capture audit
399/// log. Best effort: failing to write it never stops the tool. Typed text is
400/// never in an entry, only its length.
401pub fn audit(entry: &serde_json::Value) {
402    let Ok(root) = agentmux_common::data_paths::agentmux_root() else {
403        return;
404    };
405    let dir = root.join("tmp/capture-window");
406    if std::fs::create_dir_all(&dir).is_err() {
407        return;
408    }
409    if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(dir.join("desktop-audit.log")) {
410        use std::io::Write;
411        let _ = f.write_all(format!("{entry}\n").as_bytes());
412    }
413}
414
415#[cfg(test)]
416mod tests {
417    use super::*;
418
419    fn req(id: &str, agent: &str, app: &str, block: &str) -> DesktopRequest {
420        DesktopRequest {
421            id: id.into(),
422            agent: agent.into(),
423            app: app.into(),
424            title: "t".into(),
425            asked_ms: 0,
426            block_id: block.into(),
427            grant_minutes: 30,
428        }
429    }
430
431    /// Ask, answer and return the check that follows.
432    fn grant(g: &mut Gate, choice: Choice, now: u64) {
433        let _rx = g.ask(req("r1", "naki", "notepad", "b1"));
434        g.answer("r1", choice, now, 30).unwrap();
435    }
436
437    #[test]
438    fn with_no_grant_the_user_is_asked() {
439        let mut g = Gate::default();
440        assert_eq!(g.check("naki", "b1", "notepad", 1_000), Check::Ask);
441    }
442
443    /// A second call while the prompt is open answers `pending` instead of
444    /// asking twice; the answer ends it.
445    #[test]
446    fn asking_lasts_until_the_user_answers() {
447        let mut g = Gate::default();
448        assert!(!g.asking("naki", "b1", "notepad"));
449        let _rx = g.ask(req("r1", "naki", "notepad", "b1"));
450        assert!(g.asking("naki", "b1", "notepad"));
451        assert!(!g.asking("naki", "b1", "calc"), "another app is its own prompt");
452        assert!(!g.asking("naki", "b2", "notepad"), "another pane is its own prompt");
453        g.answer("r1", Choice::Deny, 1_000, 30).unwrap();
454        assert!(!g.asking("naki", "b1", "notepad"));
455    }
456
457    #[test]
458    fn a_direct_grant_allows_for_its_minutes_and_replaces_the_one_before() {
459        let mut g = Gate::default();
460        g.grant("naki", "b1", "notepad", Some(5), 0);
461        assert!(matches!(g.check("naki", "b1", "notepad", 1_000), Check::Allow { .. }));
462        g.grant("naki", "b1", "notepad", Some(1), 0);
463        assert_eq!(g.check("naki", "b1", "notepad", 61_000), Check::Ask, "the later grant replaced the longer one");
464        g.grant("naki", "b1", "notepad", None, 0);
465        assert!(matches!(g.check("naki", "b1", "notepad", 999_999_999), Check::Allow { .. }), "no minutes: until the session ends");
466    }
467
468    #[test]
469    fn a_timed_grant_allows_then_expires() {
470        let mut g = Gate::default();
471        grant(&mut g, Choice::Timed, 0);
472        assert!(matches!(g.check("naki", "b1", "notepad", 1_000), Check::Allow { .. }));
473        // 30 minutes on, it is gone.
474        assert_eq!(g.check("naki", "b1", "notepad", 30 * 60_000 + 1), Check::Ask);
475    }
476
477    #[test]
478    fn a_session_grant_does_not_expire_but_is_tied_to_its_pane() {
479        let mut g = Gate::default();
480        grant(&mut g, Choice::Session, 0);
481        assert!(matches!(g.check("naki", "b1", "notepad", 999_999_999), Check::Allow { .. }));
482        // The same agent in a new pane (a new session) is asked again.
483        assert_eq!(g.check("naki", "b2", "notepad", 999_999_999 + 1000), Check::Ask);
484    }
485
486    #[test]
487    fn a_grant_is_for_one_agent_and_one_app() {
488        let mut g = Gate::default();
489        grant(&mut g, Choice::Timed, 0);
490        assert_eq!(g.check("other", "b1", "notepad", 1_000), Check::Ask);
491        assert_eq!(g.check("naki", "b1", "calc", 1_000), Check::Ask);
492    }
493
494    #[test]
495    fn a_denial_is_remembered_so_the_agent_cannot_nag() {
496        let mut g = Gate::default();
497        grant(&mut g, Choice::Deny, 0);
498        assert_eq!(g.check("naki", "b1", "notepad", 1_000), Check::Denied);
499        assert_eq!(g.check("naki", "b1", "notepad", 2_000), Check::Denied);
500    }
501
502    #[test]
503    fn actions_are_at_most_two_a_second() {
504        let mut g = Gate::default();
505        grant(&mut g, Choice::Timed, 0);
506        assert!(matches!(g.check("naki", "b1", "notepad", 10_000), Check::Allow { .. }));
507        assert_eq!(g.check("naki", "b1", "notepad", 10_100), Check::TooFast { wait_ms: 400 });
508        assert!(matches!(g.check("naki", "b1", "notepad", 10_500), Check::Allow { .. }));
509    }
510
511    #[test]
512    fn a_grant_ends_after_its_action_limit() {
513        let mut g = Gate::default();
514        grant(&mut g, Choice::Session, 0);
515        let mut t = 10_000;
516        for _ in 0..MAX_ACTIONS_PER_GRANT {
517            assert!(matches!(g.check("naki", "b1", "notepad", t), Check::Allow { .. }));
518            t += MIN_ACTION_GAP_MS;
519        }
520        assert_eq!(g.check("naki", "b1", "notepad", t), Check::Ask);
521    }
522
523    #[test]
524    fn stop_revokes_and_the_next_action_hears_it_once() {
525        let mut g = Gate::default();
526        grant(&mut g, Choice::Session, 0);
527        assert_eq!(g.stop("b1"), 1);
528        assert_eq!(g.check("naki", "b1", "notepad", 1_000), Check::Stopped);
529        // Heard once; after that the agent is simply asked again.
530        assert_eq!(g.check("naki", "b1", "notepad", 2_000), Check::Ask);
531    }
532
533    #[test]
534    fn stop_also_drops_a_prompt_the_agent_was_waiting_on() {
535        let mut g = Gate::default();
536        let _rx = g.ask(req("r1", "naki", "notepad", "b1"));
537        g.stop("b1");
538        assert!(g.event(0).requests.is_empty());
539        assert!(g.answer("r1", Choice::Timed, 0, 30).is_err());
540    }
541
542    #[test]
543    fn has_grant_says_whether_the_agent_may_drive_the_app() {
544        let mut g = Gate::default();
545        assert!(!g.has_grant("naki", "b1", "notepad", 0));
546        grant(&mut g, Choice::Timed, 0);
547        assert!(g.has_grant("naki", "b1", "notepad", 1_000));
548        assert!(!g.has_grant("naki", "b2", "notepad", 1_000));
549        assert!(!g.has_grant("naki", "b1", "notepad", 30 * 60_000 + 1));
550    }
551
552    #[test]
553    fn release_gives_a_grant_back() {
554        let mut g = Gate::default();
555        grant(&mut g, Choice::Session, 0);
556        assert!(g.release("naki", "b1", "notepad"));
557        assert_eq!(g.check("naki", "b1", "notepad", 1_000), Check::Ask);
558        assert!(!g.release("naki", "b1", "notepad"));
559    }
560
561    #[test]
562    fn asking_twice_about_one_app_is_one_prompt_and_both_hear_the_answer() {
563        let mut g = Gate::default();
564        let mut a = g.ask(req("r1", "naki", "notepad", "b1"));
565        let mut b = g.ask(req("r2", "naki", "notepad", "b1"));
566        assert_eq!(g.event(0).requests.len(), 1);
567        g.answer("r1", Choice::Timed, 0, 30).unwrap();
568        assert_eq!(a.try_recv().unwrap(), Choice::Timed);
569        assert_eq!(b.try_recv().unwrap(), Choice::Timed);
570    }
571
572    #[test]
573    fn an_answered_prompt_cannot_be_answered_again() {
574        let mut g = Gate::default();
575        let _rx = g.ask(req("r1", "naki", "notepad", "b1"));
576        g.answer("r1", Choice::Deny, 0, 30).unwrap();
577        assert!(g.answer("r1", Choice::Timed, 0, 30).is_err());
578    }
579
580    #[test]
581    fn the_event_shows_a_grant_as_driving_only_just_after_an_action() {
582        let mut g = Gate::default();
583        grant(&mut g, Choice::Session, 0);
584        assert!(!g.event(1_000).grants[0].active);
585        g.check("naki", "b1", "notepad", 5_000);
586        assert!(g.event(6_000).grants[0].active);
587        assert!(!g.event(5_000 + DRIVING_SHOWN_MS).grants[0].active);
588    }
589
590    #[test]
591    fn app_names_are_compared_without_path_extension_or_case() {
592        assert_eq!(app_key(r"C:\Program Files\KeePass\KeePass.exe"), "keepass");
593        assert_eq!(app_key("/usr/bin/firefox"), "firefox");
594        assert_eq!(app_key("Notepad.EXE"), "notepad");
595    }
596
597    #[test]
598    fn password_managers_browsers_and_agentmux_are_blocked_by_default() {
599        let none: &[String] = &[];
600        assert!(blocked_reason("KeePass.exe", "", none, none).unwrap().contains("password"));
601        assert!(blocked_reason("chrome.exe", "", none, none).unwrap().contains("Browser tool"));
602        assert!(blocked_reason("agentmux-0.59.35.exe", "", none, none).unwrap().contains("UI tool"));
603        assert!(blocked_reason("consent.exe", "", none, none).unwrap().contains("operating system"));
604        assert!(blocked_reason("notepad.exe", "Untitled - Notepad", none, none).is_none());
605    }
606
607    #[test]
608    fn an_operating_system_prompt_is_recognised_by_its_title() {
609        let none: &[String] = &[];
610        assert!(blocked_reason("somehost.exe", "User Account Control", none, none).is_some());
611    }
612
613    #[test]
614    fn the_user_can_add_to_the_blocklist_by_app_or_by_title() {
615        let added = vec!["Photoshop".to_string(), "bank".to_string()];
616        let none: &[String] = &[];
617        assert!(blocked_reason("photoshop.exe", "x", &added, none).unwrap().contains("blocklist"));
618        assert!(blocked_reason("notepad.exe", "My Bank - Notepad", &added, none).is_some());
619        assert!(blocked_reason("notepad.exe", "notes", &added, none).is_none());
620    }
621
622    #[test]
623    fn the_user_can_take_a_default_off_the_list() {
624        let none: &[String] = &[];
625        let allowed = vec!["chrome".to_string()];
626        assert!(blocked_reason("chrome.exe", "", none, &allowed).is_none());
627        // AgentMux itself can't be taken off.
628        let allowed = vec!["agentmux".to_string()];
629        assert!(blocked_reason("agentmux.exe", "", none, &allowed).is_some());
630    }
631}