Skip to main content

agentmux_mcp/tools/
desktop.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Desktop: look at and control a native app, with the user's consent for
5//! each app (docs/specs/SPEC_DESKTOP_DRIVING_2026_10_20.md §5.1).
6//!
7//! The last rung of the ladder: connectors, an app's own API, `Browser`,
8//! `Terminal` and `UI` come first. Every action but `apps` and `wait` asks
9//! srv's gate (`/api/v1/agent/desktop/authorize`) first; srv answers from the
10//! grants, the blocklist, the limits and Stop, and asks the user in the app
11//! when there is no grant. The tool then acts (`desktop_input`) and tells srv
12//! what happened, for the audit log.
13
14use agentmux_common::api_types::{
15    DesktopAuthorizeRequest, DesktopPolicyRequest, DesktopRecordRequest, DesktopReleaseRequest, DesktopWindowRef,
16};
17
18use super::*;
19use crate::desktop_input::{self as input, Look, Rect};
20use crate::window_capture::{
21    capture_window_dir, enumerate_agentmux_windows, prune_old_captures, sha256_file, AgentMuxWindowInfo, CaptureTier,
22};
23
24/// Windows `apps` lists at most.
25const MAX_LISTED: usize = 40;
26
27pub(super) async fn call(name: &str, arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
28    match name {
29        "Desktop" => {
30            require_agent_env(cx.local_url, cx.auth_key, cx.block_id)?;
31            match str_arg(arguments, "action").as_deref() {
32                Some("apps") => apps(cx).await,
33                Some("look") => look(arguments, cx).await,
34                Some(a @ ("click" | "scroll" | "drag" | "type" | "key")) => {
35                    let said = match a {
36                        "click" => click(arguments, cx).await?,
37                        "scroll" => scroll(arguments, cx).await?,
38                        "drag" => drag(arguments, cx).await?,
39                        "type" => type_text(arguments, cx).await?,
40                        _ => key(arguments, cx).await?,
41                    };
42                    Ok(with_look(arguments, cx, said).await)
43                }
44                Some("wait") => wait(arguments).await,
45                Some("request") => request_many(arguments, cx).await,
46                Some("release") => release(arguments, cx).await,
47                other => anyhow::bail!(
48                    "Desktop: unknown action {other:?}; use apps, request, look, click, scroll, drag, type, key, wait or release"
49                ),
50            }
51        }
52        _ => Err(not_in_family()),
53    }
54}
55
56fn int_arg(args: &Value, key: &str) -> Option<i64> {
57    args.get(key).and_then(|v| v.as_i64().or_else(|| v.as_f64().map(|f| f.round() as i64)))
58}
59
60fn window_id(args: &Value) -> Result<u32> {
61    let id = int_arg(args, "window").ok_or_else(|| anyhow::anyhow!("window is required: the id `apps` listed"))?;
62    u32::try_from(id).map_err(|_| anyhow::anyhow!("window {id} is not a window id from `apps`"))
63}
64
65/// The app's name as shown: the executable's file name without `.exe`.
66fn app_label(exe_or_name: &str) -> String {
67    let name = exe_or_name.rsplit(['\\', '/']).next().unwrap_or(exe_or_name);
68    name.strip_suffix(".exe").unwrap_or(name).to_string()
69}
70
71/// The process that hosts every Windows Store (UWP) app's window.
72const FRAME_HOST: &str = "ApplicationFrameHost";
73
74/// Why a Windows Store app's window can't be used right now.
75const UNIDENTIFIED_STORE_APP: &str =
76    "this is a Windows Store app whose app can't be identified while its window is minimised; ask the user to restore it, then call apps again";
77
78/// The window as srv names it. The app is what grants, denials and the
79/// blocklist key on, so a Windows Store app is named by its own executable,
80/// not by `ApplicationFrameHost.exe`, which hosts all of them: a grant for
81/// Calculator must not cover every other Store app, and a Store password
82/// manager must stay blockable by name. When the hosted app can't be found
83/// (it is suspended while minimised), the window is refused, never keyed on
84/// the frame host.
85fn window_ref(w: &AgentMuxWindowInfo, id: u32) -> Result<DesktopWindowRef> {
86    let app = if w.exe_path.is_empty() { w.window.app_name().unwrap_or_default() } else { w.exe_path.clone() };
87    let app = if app_label(&app).eq_ignore_ascii_case(FRAME_HOST) {
88        input::win::hosted_app_exe(id).ok_or_else(|| anyhow::anyhow!("{UNIDENTIFIED_STORE_APP}"))?
89    } else {
90        app
91    };
92    Ok(DesktopWindowRef { id, app, title: w.title.clone() })
93}
94
95/// A window by the id `apps` gave. Only a foreign app of the user's own can
96/// be driven (spec §5.3); the others are refused with where to go instead.
97fn find_window(id: u32) -> Result<AgentMuxWindowInfo> {
98    let w = enumerate_agentmux_windows()?
99        .into_iter()
100        .find(|w| w.window.id().ok() == Some(id))
101        .ok_or_else(|| anyhow::anyhow!("window {id} is gone; call apps for the current list"))?;
102    match w.tier {
103        CaptureTier::ForeignApp => Ok(w),
104        CaptureTier::SameInstance | CaptureTier::OtherInstance => {
105            anyhow::bail!("that is AgentMux itself; Desktop doesn't drive it. Use the UI tool")
106        }
107        CaptureTier::OtherUser => anyhow::bail!("that window belongs to another user; it can't be controlled"),
108    }
109}
110
111async fn post(cx: &ToolCtx<'_>, path: &str, body: &impl serde::Serialize, secs: u64) -> Result<Value> {
112    let url = format!("{}{path}", cx.local_url.trim_end_matches('/'));
113    let resp = cx
114        .client
115        .post(&url)
116        .header(AUTH_KEY_HEADER, cx.auth_key)
117        .json(body)
118        .timeout(std::time::Duration::from_secs(secs))
119        .send()
120        .await
121        .map_err(|e| anyhow::anyhow!("request failed: {e}"))?;
122    let status = resp.status();
123    let json: Value = resp.json().await.unwrap_or(Value::Null);
124    if !status.is_success() {
125        anyhow::bail!("Desktop: srv answered {status}: {}", json["error"].as_str().unwrap_or(&json.to_string()));
126    }
127    Ok(json)
128}
129
130/// Ask srv whether `action` on `w` may go ahead. Returns the grant's id, or
131/// srv's reason as an error. It never waits for the user: with no grant srv
132/// asks them and answers `pending` at once, and their answer reaches the agent
133/// as an [AgentMux] note.
134async fn authorize(cx: &ToolCtx<'_>, action: &str, w: &AgentMuxWindowInfo, id: u32) -> Result<String> {
135    let body = DesktopAuthorizeRequest { auth: sign_ui_automation_auth()?, action: action.to_string(), window: window_ref(w, id)?, group: None };
136    let answer = post(cx, "/api/v1/agent/desktop/authorize", &body, 30).await?;
137    match answer["status"].as_str() {
138        Some("allow") => Ok(answer["grant_id"].as_str().unwrap_or("").to_string()),
139        _ => anyhow::bail!("{}", answer["message"].as_str().unwrap_or("Desktop refused this")),
140    }
141}
142
143/// What srv answered about one window in a call that asks for several.
144#[derive(Debug, PartialEq, Eq)]
145enum Asked {
146    /// A grant is live already.
147    Granted,
148    /// The user is being asked. `grouped`: the answer comes in the one note for the whole call;
149    /// otherwise this app's own note comes by itself.
150    Pending { grouped: bool },
151    /// Not now, and why (refused, blocked, denied, stopped, off).
152    No(String),
153}
154
155/// Sort srv's answer to one window of a `request` call.
156fn read_answer(answer: &Value) -> Asked {
157    let message = answer["message"].as_str().unwrap_or("Desktop refused this").to_string();
158    match answer["status"].as_str() {
159        Some("allow") => Asked::Granted,
160        Some("pending") => Asked::Pending { grouped: answer["grouped"].as_bool() == Some(true) },
161        _ => Asked::No(message),
162    }
163}
164
165/// The windows a `request` call names, without repeats, at most [`MAX_REQUEST_WINDOWS`].
166fn request_windows(args: &Value) -> Result<Vec<u32>> {
167    let list = args
168        .get("windows")
169        .and_then(Value::as_array)
170        .ok_or_else(|| anyhow::anyhow!("request needs windows: the ids `apps` listed, for the apps you need"))?;
171    let mut ids: Vec<u32> = Vec::new();
172    for v in list {
173        let id = v
174            .as_i64()
175            .and_then(|n| u32::try_from(n).ok())
176            .ok_or_else(|| anyhow::anyhow!("windows holds window ids from `apps`; {v} is not one"))?;
177        if !ids.contains(&id) {
178            ids.push(id);
179        }
180    }
181    if ids.is_empty() {
182        anyhow::bail!("request needs at least one window id from `apps`");
183    }
184    if ids.len() > MAX_REQUEST_WINDOWS {
185        anyhow::bail!("request asks for at most {MAX_REQUEST_WINDOWS} windows at once; you named {}", ids.len());
186    }
187    Ok(ids)
188}
189
190/// Windows one `request` call may name.
191const MAX_REQUEST_WINDOWS: usize = 8;
192
193/// Ask for several apps in one call. Each app is its own request to the user, with its own card,
194/// countdown, veto and grant; nothing about one decides another. What is shared is the answer: one
195/// `[AgentMux]` note names every app as allowed, declined or vetoed once all have been decided.
196async fn request_many(args: &Value, cx: &ToolCtx<'_>) -> Result<String> {
197    let ids = request_windows(args)?;
198    input::win::ensure_dpi_aware();
199    let call = uuid::Uuid::new_v4().to_string();
200    let mut lines = Vec::new();
201    let mut grouped = 0usize;
202    let mut alone = 0usize;
203    let mut first: Option<DesktopWindowRef> = None;
204    for id in ids {
205        let w = match find_window(id) {
206            Ok(w) => w,
207            Err(e) => {
208                lines.push(format!("{id}: {e}"));
209                continue;
210            }
211        };
212        let window = match window_ref(&w, id) {
213            Ok(r) => r,
214            Err(e) => {
215                lines.push(format!("{id}: {e}"));
216                continue;
217            }
218        };
219        let app = app_label(&window.app);
220        first.get_or_insert_with(|| window.clone());
221        // A request that can't be signed is that app's line; the others are still asked.
222        let auth = match sign_ui_automation_auth() {
223            Ok(a) => a,
224            Err(e) => {
225                lines.push(format!("{id} {app}: couldn't ask: {e}"));
226                continue;
227            }
228        };
229        let body = DesktopAuthorizeRequest { auth, action: "look".into(), window, group: Some(call.clone()) };
230        let answer = post(cx, "/api/v1/agent/desktop/authorize", &body, 30).await;
231        lines.push(match answer.as_ref().map(read_answer) {
232            Ok(Asked::Granted) => format!("{id} {app}: allowed already; you may use it now"),
233            Ok(Asked::Pending { grouped: true }) => {
234                grouped += 1;
235                format!("{id} {app}: asked; the user decides")
236            }
237            Ok(Asked::Pending { grouped: false }) => {
238                alone += 1;
239                format!("{id} {app}: asked; the user decides, and its own note will come by itself")
240            }
241            Ok(Asked::No(why)) => format!("{id} {app}: {why}"),
242            Err(e) => format!("{id} {app}: {e}"),
243        });
244    }
245    // Every request is filed: from here the call's answer may be sent. Tried twice; a group the seal
246    // never reached is ended by srv's own deadline.
247    if let (true, Some(window)) = (grouped > 0, first) {
248        for _ in 0..2 {
249            let Ok(auth) = sign_ui_automation_auth() else { continue };
250            let seal = DesktopAuthorizeRequest { auth, action: "seal".into(), window: window.clone(), group: Some(call.clone()) };
251            if post(cx, "/api/v1/agent/desktop/authorize", &seal, 30).await.is_ok() {
252                break;
253            }
254        }
255    }
256    let mut tail = String::new();
257    if grouped > 0 {
258        tail.push_str(" The asked apps are each their own request, with their own card and answer. One [AgentMux] note will name every one of them as allowed, declined or vetoed when all are decided: don't wait for it or ask again; carry on with other work or end your turn.");
259    }
260    if alone > 0 {
261        tail.push_str(" An app that was already asked for sends its own note.");
262    }
263    Ok(format!("{}\n{tail}", lines.join("\n")).trim_end().to_string())
264}
265
266/// Tell srv what an authorized action did. Best effort: the action has
267/// happened (or failed) either way.
268async fn record(cx: &ToolCtx<'_>, grant: &str, action: &str, w: &AgentMuxWindowInfo, id: u32, details: Value, result: &str) {
269    let Ok(auth) = sign_ui_automation_auth() else { return };
270    // Authorized a moment ago, so the window was identified then.
271    let Ok(window) = window_ref(w, id) else { return };
272    let body = DesktopRecordRequest {
273        auth,
274        grant_id: Some(grant.to_string()).filter(|g| !g.is_empty()),
275        action: action.to_string(),
276        window,
277        details,
278        result: result.to_string(),
279    };
280    let _ = post(cx, "/api/v1/agent/desktop/record", &body, 10).await;
281}
282
283async fn apps(cx: &ToolCtx<'_>) -> Result<String> {
284    let mut candidates: Vec<AgentMuxWindowInfo> = enumerate_agentmux_windows()?
285        .into_iter()
286        .filter(|w| w.tier == CaptureTier::ForeignApp && !w.title.trim().is_empty())
287        .collect();
288    candidates.truncate(MAX_LISTED);
289    // A Store app that can't be identified is listed, not offered (window_ref).
290    let mut refs: Vec<DesktopWindowRef> = Vec::new();
291    let mut unidentified: Vec<u32> = Vec::new();
292    for w in &candidates {
293        let Ok(id) = w.window.id() else { continue };
294        match window_ref(w, id) {
295            Ok(r) => refs.push(r),
296            Err(_) => unidentified.push(id),
297        }
298    }
299    let body = DesktopPolicyRequest { auth: sign_ui_automation_auth()?, windows: refs.clone() };
300    let policy = post(cx, "/api/v1/agent/desktop/policy", &body, 30).await?;
301    if policy["enabled"].as_bool() != Some(true) {
302        return Ok("Desktop driving is off. The user turns it on in Settings > Agents > Desktop driving; until they do, nothing is captured or controlled.".into());
303    }
304    let state_of = |id: u32| policy["windows"].as_array().and_then(|a| a.iter().find(|w| w["id"].as_u64() == Some(id as u64)));
305    let mut lines = Vec::new();
306    for r in &refs {
307        let st = state_of(r.id);
308        let app = app_label(&r.app);
309        // A blocked window's title is not shown: it could be a password
310        // manager's, and the listing is not the place to leak it.
311        match st.and_then(|s| s["blocked"].as_str()) {
312            Some(why) => lines.push(format!("{:>10}  {app} — blocked: {why}", r.id)),
313            None => {
314                let granted = st.map(|s| s["granted"].as_bool() == Some(true)).unwrap_or(false);
315                let note = if granted { "you may drive it" } else { "the user is asked on first use" };
316                let title: String = r.title.chars().take(80).collect();
317                // A skill for this app, when the catalog has one. Reading it grants nothing.
318                let skill = st.and_then(|s| s["skill"].as_object()).map(|k| {
319                    let seen = if k.get("verified_here").and_then(Value::as_bool) == Some(true) { "tested here" } else { "not tested here" };
320                    format!(" — skill: {} {} ({seen}); Skills get skill_id={}", k.get("name").and_then(Value::as_str).unwrap_or(""), k.get("version").and_then(Value::as_str).unwrap_or(""), k.get("id").and_then(Value::as_str).unwrap_or(""))
321                });
322                lines.push(format!("{:>10}  {app} — {title:?} — {note}{}", r.id, skill.unwrap_or_default()));
323            }
324        }
325    }
326    for id in unidentified {
327        lines.push(format!("{id:>10}  a Windows Store app — minimised, so it can't be identified; it can be used once the user restores it"));
328    }
329    if lines.is_empty() {
330        return Ok("No app windows other than AgentMux are open.".into());
331    }
332    Ok(format!(
333        "Windows you could control (pass the id as window). Use a connector, Browser, Terminal or the app's own API first; Desktop is for apps with no other way in.\n{}",
334        lines.join("\n")
335    ))
336}
337
338/// `region` of a `look`: x, y, w, h in the pixels of the last look.
339fn parse_region(args: &Value) -> Result<Option<(i64, i64, i64, i64)>> {
340    let Some(r) = args.get("region").filter(|r| !r.is_null()) else { return Ok(None) };
341    let g = |k: &str| int_arg(r, k).ok_or_else(|| anyhow::anyhow!("region needs x, y, w and h (pixels of your last look); {k} is missing"));
342    Ok(Some((g("x")?, g("y")?, g("w")?, g("h")?)))
343}
344
345/// What a `look` made: the image's path and hash, and either the whole
346/// window's look or the zoom of a region.
347struct Captured {
348    path: String,
349    sha: Option<String>,
350    kind: CaptureKind,
351}
352
353enum CaptureKind {
354    Whole(Look),
355    Zoom { of: Look, region: input::Region, zoom: f64, w: u32, h: u32 },
356}
357
358async fn look(args: &Value, cx: &ToolCtx<'_>) -> Result<String> {
359    let id = window_id(args)?;
360    let region = parse_region(args)?;
361    input::win::ensure_dpi_aware();
362    let w = find_window(id)?;
363    // A region is of the last look, so it needs one.
364    let prior = input::last_look(id);
365    if region.is_some() && prior.is_none() {
366        anyhow::bail!("look at the whole window first: a region is in the pixels of that look");
367    }
368    let grant = authorize(cx, "look", &w, id).await?;
369    // Look at the window as it is after the user answered.
370    let w = find_window(id)?;
371    let restored = input::win::restore_if_minimized(id);
372    let result = (|| -> Result<Captured> {
373        let rect = input::win::window_rect(id).ok_or_else(|| anyhow::anyhow!("couldn't read the window's size"))?;
374        let image = w.window.capture_image().map_err(|e| anyhow::anyhow!("capture failed: {e}"))?;
375        if image.width() == 0 || image.height() == 0 {
376            anyhow::bail!("the window has no size to capture (it may be minimised or hidden); call look again, and ask the user to restore it if this repeats");
377        }
378        let dir = capture_window_dir().map_err(|e| anyhow::anyhow!("cannot resolve the AgentMux root for captures: {e}"))?;
379        std::fs::create_dir_all(&dir)?;
380        let path = dir.join(format!("{}.png", uuid::Uuid::new_v4()));
381        let kind = if let Some((x, y, rw, rh)) = region {
382            let of = prior.ok_or_else(|| anyhow::anyhow!("look at the whole window first"))?;
383            if of.rect != rect {
384                anyhow::bail!("the window moved or resized since look #{}; take a whole look first, then a region of it", of.n);
385            }
386            let r = input::check_region(&of, x, y, rw, rh).map_err(|e| anyhow::anyhow!("{e}"))?;
387            // The look was scaled down from the capture: cut the same region from the capture itself.
388            let (fx, fy) = (image.width() as f64 / of.image_w as f64, image.height() as f64 / of.image_h as f64);
389            let (cx0, cy0) = ((r.x as f64 * fx).round() as u32, (r.y as f64 * fy).round() as u32);
390            let cw = ((r.w as f64 * fx).round() as u32).clamp(1, image.width().saturating_sub(cx0).max(1));
391            let ch = ((r.h as f64 * fy).round() as u32).clamp(1, image.height().saturating_sub(cy0).max(1));
392            let cut = image::imageops::crop_imm(&image, cx0, cy0, cw, ch).to_image();
393            let zoom = input::zoom_for(r.w, r.h);
394            let (ow, oh) = (((r.w as f64 * zoom).round() as u32).max(1), ((r.h as f64 * zoom).round() as u32).max(1));
395            let shown = image::imageops::resize(&cut, ow, oh, image::imageops::FilterType::CatmullRom);
396            shown.save(&path).map_err(|e| anyhow::anyhow!("failed to save the capture: {e}"))?;
397            CaptureKind::Zoom { of, region: r, zoom, w: ow, h: oh }
398        } else {
399            let (tw, th) = input::scaled_size(image.width(), image.height());
400            let shown = if (tw, th) == (image.width(), image.height()) {
401                image
402            } else {
403                image::imageops::resize(&image, tw, th, image::imageops::FilterType::Triangle)
404            };
405            shown.save(&path).map_err(|e| anyhow::anyhow!("failed to save the capture: {e}"))?;
406            CaptureKind::Whole(Look { rect, image_w: shown.width(), image_h: shown.height(), n: 0 })
407        };
408        prune_old_captures(&dir);
409        Ok(Captured { sha: sha256_file(&path), path: path.display().to_string(), kind })
410    })();
411    match result {
412        Ok(c) => {
413            let woke = if restored { " The window was minimised; it has been restored." } else { "" };
414            let said = match c.kind {
415                CaptureKind::Whole(look0) => {
416                    let (look, before) = input::remember_look(id, look0);
417                    record(cx, &grant, "look", &w, id, json!({ "image": [look.image_w, look.image_h], "look": look.n, "sha256": c.sha }), "ok").await;
418                    format!(
419                        "Looked at {:?}: {} — use Read on that path to see it. {} click, scroll, drag and the other actions take x and y in the pixels of this image (pass of_look {} to be told if they are from an older look). Look again after anything changes, or if the window moves.{woke}",
420                        w.title,
421                        c.path,
422                        input::describe_scale(&look, before.as_ref()),
423                        look.n
424                    )
425                }
426                CaptureKind::Zoom { of, region: r, zoom, w: zw, h: zh } => {
427                    record(cx, &grant, "look", &w, id, json!({ "region": [r.x, r.y, r.w, r.h], "of_look": of.n, "sha256": c.sha }), "ok").await;
428                    format!(
429                        "Looked at region ({}, {}, {}×{}) of look #{} in {:?}, enlarged ×{zoom:.1}: {} — use Read on that path to see it. The image is {zw}×{zh} pixels. It does not replace look #{}: keep clicking in look #{}'s pixels (a point (zx, zy) in this zoom is at x = {} + zx×{}/{zw}, y = {} + zy×{}/{zh} in look #{}).{woke}",
430                        r.x, r.y, r.w, r.h, of.n, w.title, c.path, of.n, of.n, r.x, r.w, r.y, r.h, of.n
431                    )
432                }
433            };
434            Ok(said)
435        }
436        Err(e) => {
437            record(cx, &grant, "look", &w, id, Value::Null, &format!("error: {e}")).await;
438            Err(e)
439        }
440    }
441}
442
443/// After an action that asked for it (`look: true`), the fresh look at the
444/// window, appended to what the action said: one call instead of three. A look
445/// that fails doesn't fail the action, which has happened.
446async fn with_look(args: &Value, cx: &ToolCtx<'_>, said: String) -> String {
447    if args.get("look").and_then(Value::as_bool) != Some(true) {
448        return said;
449    }
450    let Ok(id) = window_id(args) else { return said };
451    // Give the app a moment to draw what the action did.
452    tokio::time::sleep(std::time::Duration::from_millis(300)).await;
453    match look(&json!({ "window": id }), cx).await {
454        Ok(l) => format!("{said}\nThe window now: {l}"),
455        Err(e) => format!("{said}\n(The look afterwards failed: {e})"),
456    }
457}
458
459/// The screen point for image point (x, y) of window `id`, from its last
460/// look. Errors say what to do (look again, stay inside the image).
461fn screen_point(id: u32, x: i64, y: i64) -> Result<(i32, i32)> {
462    let look = input::last_look(id).ok_or_else(|| anyhow::anyhow!("look at the window first: x and y are pixels of that image"))?;
463    let now: Rect = input::win::window_rect(id).ok_or_else(|| anyhow::anyhow!("the window is gone; call apps"))?;
464    input::to_screen(&look, now, x, y).map_err(|e| anyhow::anyhow!("{e}"))
465}
466
467/// What every input action does after the gate: bring the window forward and
468/// check every point isn't covered, run `act` with the points' screen
469/// positions, and record the outcome.
470async fn drive(
471    cx: &ToolCtx<'_>,
472    action: &str,
473    id: u32,
474    points: &[(i64, i64)],
475    of_look: Option<i64>,
476    details: Value,
477    act: impl FnOnce(&[(i32, i32)]) -> Result<(), String>,
478) -> Result<AgentMuxWindowInfo> {
479    input::win::ensure_dpi_aware();
480    let w = find_window(id)?;
481    // Coordinates the agent says are from an older look than the latest are stale.
482    if let (Some(of), false) = (of_look, points.is_empty()) {
483        let latest = input::last_look(id).ok_or_else(|| anyhow::anyhow!("look at the window first: x and y are pixels of that image"))?;
484        input::check_of_look(&latest, of).map_err(|e| anyhow::anyhow!("{e}"))?;
485    }
486    // Check the points before asking, so a bad one doesn't use up a slot.
487    for (x, y) in points {
488        screen_point(id, *x, *y)?;
489    }
490    let grant = authorize(cx, action, &w, id).await?;
491    // The user may have taken a while to answer: read the window again.
492    let w = find_window(id)?;
493    let outcome = (|| -> Result<(), String> {
494        let screen = points
495            .iter()
496            .map(|(x, y)| screen_point(id, *x, *y).map_err(|e| e.to_string()))
497            .collect::<Result<Vec<_>, _>>()?;
498        input::win::bring_to_front(id)?;
499        for (sx, sy) in &screen {
500            input::win::point_belongs_to(id, *sx, *sy)?;
501        }
502        act(&screen)
503    })();
504    match &outcome {
505        Ok(()) => record(cx, &grant, action, &w, id, details, "ok").await,
506        Err(e) => record(cx, &grant, action, &w, id, details, &format!("error: {e}")).await,
507    }
508    outcome.map_err(|e| anyhow::anyhow!("{e}"))?;
509    Ok(w)
510}
511
512async fn click(args: &Value, cx: &ToolCtx<'_>) -> Result<String> {
513    let id = window_id(args)?;
514    let x = int_arg(args, "x").ok_or_else(|| anyhow::anyhow!("click needs x and y: pixels of your last look"))?;
515    let y = int_arg(args, "y").ok_or_else(|| anyhow::anyhow!("click needs x and y: pixels of your last look"))?;
516    let button = str_arg(args, "button").unwrap_or_else(|| "left".into());
517    let count = int_arg(args, "count").unwrap_or(1).clamp(1, 3) as u32;
518    let details = json!({ "x": x, "y": y, "button": button, "count": count });
519    let b = button.clone();
520    let w = drive(cx, "click", id, &[(x, y)], int_arg(args, "of_look"), details, move |p| {
521        let (sx, sy) = *p.first().ok_or("no point")?;
522        input::win::click(sx, sy, &b, count)
523    })
524    .await?;
525    Ok(format!("Clicked ({x}, {y}) in {:?} ({button}{}). Look again to see the result.", w.title, if count > 1 { format!(" ×{count}") } else { String::new() }))
526}
527
528async fn scroll(args: &Value, cx: &ToolCtx<'_>) -> Result<String> {
529    let id = window_id(args)?;
530    let x = int_arg(args, "x").ok_or_else(|| anyhow::anyhow!("scroll needs x and y: where in your last look"))?;
531    let y = int_arg(args, "y").ok_or_else(|| anyhow::anyhow!("scroll needs x and y: where in your last look"))?;
532    let dx = int_arg(args, "dx").unwrap_or(0).clamp(-50, 50) as i32;
533    let dy = int_arg(args, "dy").unwrap_or(0).clamp(-50, 50) as i32;
534    if dx == 0 && dy == 0 {
535        anyhow::bail!("scroll needs dy (notches, positive is up) or dx (positive is right)");
536    }
537    let w = drive(cx, "scroll", id, &[(x, y)], int_arg(args, "of_look"), json!({ "x": x, "y": y, "dx": dx, "dy": dy }), move |p| {
538        let (sx, sy) = *p.first().ok_or("no point")?;
539        input::win::scroll(sx, sy, dx, dy)
540    })
541    .await?;
542    Ok(format!("Scrolled at ({x}, {y}) in {:?} (dx {dx}, dy {dy}). Look again to see the result.", w.title))
543}
544
545/// A drag's two ends, the points it passes through, and what it holds, read
546/// from the call's arguments.
547#[derive(Debug, PartialEq, Eq)]
548struct DragArgs {
549    /// Where it presses, each `via` point in order, and where it lets go.
550    points: Vec<(i64, i64)>,
551    button: String,
552    hold: Vec<u16>,
553    hold_text: String,
554}
555
556/// Read a drag's arguments. Refuses what can't be a drag, with the fix.
557fn parse_drag(args: &Value) -> Result<DragArgs> {
558    let need = |k: &str| {
559        int_arg(args, k).ok_or_else(|| {
560            anyhow::anyhow!(
561                "drag needs x, y (where to press) and x2, y2 (where to let go): pixels of your last look; {k} is missing"
562            )
563        })
564    };
565    let (x, y, x2, y2) = (need("x")?, need("y")?, need("x2")?, need("y2")?);
566    let mut via = Vec::new();
567    if let Some(v) = args.get("via") {
568        let list = v.as_array().ok_or_else(|| anyhow::anyhow!("via is a list of {{x, y}} points to pass through"))?;
569        if list.len() > input::MAX_DRAG_WAYPOINTS {
570            anyhow::bail!("via has {} points; a drag passes through at most {}", list.len(), input::MAX_DRAG_WAYPOINTS);
571        }
572        for p in list {
573            let (Some(vx), Some(vy)) = (int_arg(p, "x"), int_arg(p, "y")) else {
574                anyhow::bail!("every via point needs x and y")
575            };
576            via.push((vx, vy));
577        }
578    }
579    let mut points = vec![(x, y)];
580    points.extend(via);
581    points.push((x2, y2));
582    if points.windows(2).all(|w| w[0] == w[1]) {
583        anyhow::bail!("the drag starts and ends at the same point; use click for that");
584    }
585    let button = str_arg(args, "button").unwrap_or_else(|| "left".into());
586    if !["left", "right", "middle"].contains(&button.as_str()) {
587        anyhow::bail!("unknown button {button:?}; use left, right or middle");
588    }
589    let hold_text = str_arg(args, "hold").unwrap_or_default();
590    let hold = input::parse_hold(&hold_text).map_err(|e| anyhow::anyhow!("{e}"))?;
591    Ok(DragArgs { points, button, hold, hold_text })
592}
593
594async fn drag(args: &Value, cx: &ToolCtx<'_>) -> Result<String> {
595    let id = window_id(args)?;
596    let d = parse_drag(args)?;
597    let (from, to) = (d.points[0], d.points[d.points.len() - 1]);
598    let details = json!({
599        "from": [from.0, from.1],
600        "to": [to.0, to.1],
601        "via": d.points.len() - 2,
602        "button": d.button,
603        "hold": d.hold_text,
604    });
605    let (button, hold) = (d.button.clone(), d.hold.clone());
606    let w = drive(cx, "drag", id, &d.points, int_arg(args, "of_look"), details, move |screen| {
607        let last = screen.len() - 1;
608        input::win::drag(&input::drag_path(screen[0], &screen[1..last], screen[last]), &button, &hold)
609    })
610    .await?;
611    let held = if d.hold_text.is_empty() { String::new() } else { format!(", holding {}", d.hold_text) };
612    Ok(format!(
613        "Dragged from ({}, {}) to ({}, {}) in {:?} ({}{held}); the button is let go. Look again to see the result.",
614        from.0, from.1, to.0, to.1, w.title, d.button
615    ))
616}
617
618async fn type_text(args: &Value, cx: &ToolCtx<'_>) -> Result<String> {
619    let id = window_id(args)?;
620    let text = args.get("text").and_then(|v| v.as_str()).unwrap_or_default().to_string();
621    input::check_text(&text).map_err(|e| anyhow::anyhow!("{e}"))?;
622    let chars = text.chars().count();
623    // The log gets the length, never the text.
624    let w = drive(cx, "type", id, &[], None, json!({ "chars": chars }), move |_| input::win::type_text(&text)).await?;
625    Ok(format!("Typed {chars} characters into {:?}. Don't type passwords: ask the user to. Look again to see the result.", w.title))
626}
627
628async fn key(args: &Value, cx: &ToolCtx<'_>) -> Result<String> {
629    let id = window_id(args)?;
630    let keys = str_arg(args, "keys").ok_or_else(|| anyhow::anyhow!("key needs keys, such as \"enter\" or \"ctrl+s\""))?;
631    let chord = input::parse_keys(&keys).map_err(|e| anyhow::anyhow!("{e}"))?;
632    let w = drive(cx, "key", id, &[], None, json!({ "keys": keys }), move |_| input::win::press(&chord)).await?;
633    Ok(format!("Pressed {keys} in {:?}. Look again to see the result.", w.title))
634}
635
636async fn wait(args: &Value) -> Result<String> {
637    let ms = int_arg(args, "ms").ok_or_else(|| anyhow::anyhow!("wait needs ms"))?;
638    let ms = ms.clamp(0, input::MAX_WAIT_MS as i64) as u64;
639    tokio::time::sleep(std::time::Duration::from_millis(ms)).await;
640    Ok(format!("Waited {ms} ms."))
641}
642
643async fn release(args: &Value, cx: &ToolCtx<'_>) -> Result<String> {
644    let id = window_id(args)?;
645    let w = find_window(id)?;
646    let window = window_ref(&w, id)?;
647    let app = app_label(&window.app);
648    let body = DesktopReleaseRequest { auth: sign_ui_automation_auth()?, window };
649    let answer = post(cx, "/api/v1/agent/desktop/release", &body, 30).await?;
650    Ok(if answer["released"].as_bool() == Some(true) {
651        format!("Gave back your access to {app}.")
652    } else {
653        "You had no access to give back.".into()
654    })
655}
656
657#[cfg(test)]
658mod tests {
659    use super::*;
660
661    #[test]
662    fn an_app_is_shown_by_its_executable_name() {
663        assert_eq!(app_label(r"C:\Windows\System32\notepad.exe"), "notepad");
664        assert_eq!(app_label("/usr/bin/gedit"), "gedit");
665        assert_eq!(app_label("calc"), "calc");
666        // The frame host is recognised whatever the path's case, so a Store
667        // app is never keyed on it (window_ref).
668        assert!(app_label(r"C:\WINDOWS\system32\ApplicationFrameHost.exe").eq_ignore_ascii_case(FRAME_HOST));
669    }
670
671    #[test]
672    fn window_ids_are_integers_from_apps() {
673        assert_eq!(window_id(&json!({ "window": 66052 })).unwrap(), 66052);
674        assert!(window_id(&json!({})).is_err());
675        assert!(window_id(&json!({ "window": -1 })).is_err());
676        assert!(window_id(&json!({ "window": "x" })).is_err());
677    }
678
679    #[test]
680    fn numbers_may_arrive_as_floats() {
681        assert_eq!(int_arg(&json!({ "x": 10.0 }), "x"), Some(10));
682        assert_eq!(int_arg(&json!({ "x": "10" }), "x"), None);
683    }
684
685    #[test]
686    fn a_drag_is_read_from_its_ends_and_waypoints() {
687        let d = parse_drag(&json!({ "x": 1, "y": 2, "x2": 30, "y2": 40, "via": [{ "x": 10, "y": 10 }], "hold": "ctrl+shift" })).unwrap();
688        assert_eq!(d.points, vec![(1, 2), (10, 10), (30, 40)]);
689        assert_eq!(d.button, "left");
690        assert_eq!(d.hold.len(), 2);
691    }
692
693    #[test]
694    fn a_drag_that_cannot_be_one_is_refused_with_the_fix() {
695        let err = |v: Value| parse_drag(&v).unwrap_err().to_string();
696        assert!(err(json!({ "x": 1, "y": 2, "x2": 3 })).contains("y2 is missing"));
697        assert!(err(json!({ "x": 5, "y": 5, "x2": 5, "y2": 5 })).contains("use click"));
698        assert!(err(json!({ "x": 1, "y": 2, "x2": 3, "y2": 4, "button": "back" })).contains("unknown button"));
699        assert!(err(json!({ "x": 1, "y": 2, "x2": 3, "y2": 4, "hold": "win" })).contains("not allowed"));
700        assert!(err(json!({ "x": 1, "y": 2, "x2": 3, "y2": 4, "via": "nope" })).contains("list"));
701        assert!(err(json!({ "x": 1, "y": 2, "x2": 3, "y2": 4, "via": [{ "x": 1 }] })).contains("x and y"));
702        let many: Vec<Value> = (0..9).map(|i| json!({ "x": i, "y": i })).collect();
703        assert!(err(json!({ "x": 1, "y": 2, "x2": 3, "y2": 4, "via": many })).contains("at most 8"));
704    }
705
706    #[test]
707    fn a_drag_that_returns_to_its_start_by_way_of_a_waypoint_is_allowed() {
708        let d = parse_drag(&json!({ "x": 5, "y": 5, "x2": 5, "y2": 5, "via": [{ "x": 50, "y": 5 }] })).unwrap();
709        assert_eq!(d.points, vec![(5, 5), (50, 5), (5, 5)]);
710    }
711
712    #[test]
713    fn a_region_is_read_from_the_call() {
714        assert_eq!(parse_region(&json!({})).unwrap(), None);
715        assert_eq!(parse_region(&json!({ "region": null })).unwrap(), None);
716        assert_eq!(parse_region(&json!({ "region": { "x": 1, "y": 2, "w": 30, "h": 40 } })).unwrap(), Some((1, 2, 30, 40)));
717        assert!(parse_region(&json!({ "region": { "x": 1, "y": 2, "w": 30 } })).unwrap_err().to_string().contains("h is missing"));
718    }
719
720    #[test]
721    fn an_answer_is_sorted_into_granted_asked_or_no() {
722        assert_eq!(read_answer(&json!({ "status": "allow", "message": "" })), Asked::Granted);
723        assert_eq!(read_answer(&json!({ "status": "pending", "message": "asked" })), Asked::Pending { grouped: false });
724        assert_eq!(read_answer(&json!({ "status": "pending", "message": "asked", "grouped": true })), Asked::Pending { grouped: true });
725        assert_eq!(read_answer(&json!({ "status": "denied", "message": "no" })), Asked::No("no".into()));
726        assert_eq!(read_answer(&json!({ "status": "refused", "message": "blocked" })), Asked::No("blocked".into()));
727        assert_eq!(read_answer(&json!({ "status": "stopped" })), Asked::No("Desktop refused this".into()));
728    }
729
730    #[test]
731    fn a_request_names_a_few_window_ids_once_each() {
732        assert_eq!(request_windows(&json!({ "windows": [3, 5, 3] })).unwrap(), vec![3, 5]);
733        assert!(request_windows(&json!({})).is_err());
734        assert!(request_windows(&json!({ "windows": [] })).is_err());
735        assert!(request_windows(&json!({ "windows": [-1] })).is_err());
736        assert!(request_windows(&json!({ "windows": ["x"] })).is_err());
737        let nine: Vec<i64> = (1..=9).collect();
738        assert!(request_windows(&json!({ "windows": nine })).unwrap_err().to_string().contains("at most 8"));
739    }
740}