computer-use-linux 0.7.43

Native Linux desktop control over MCP and CLI — semantic AT-SPI accessibility trees, multi-compositor window targeting (GNOME, KDE/KWin, Hyprland, niri, COSMIC, i3, X11), bounded screenshots, Wayland/X11 input, and an on-screen agent activity indicator.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
use crate::windowing::registry::{self, WINDOW_PERMISSION_HINT};
use crate::windowing::types::{WindowFocusResult, WindowInfo, WindowTarget};
use anyhow::{bail, Result};
use std::future::Future;
use tokio::time::{sleep_until, timeout_at, Duration, Instant};

/// How long focus may take to land, for example across a workspace switch.
const FOCUS_VERIFY_TRANSITION_TIMEOUT: Duration = Duration::from_secs(1);
/// Upper bound for one focused-window query. Some backends run several
/// bounded commands per query (Hyprland runs two `hyprctl` calls of up to
/// 2 s each), so a query can outlast the transition allowance.
const FOCUS_VERIFY_QUERY_TIMEOUT: Duration = Duration::from_secs(5);
const FOCUS_VERIFY_DELAY: Duration = Duration::from_millis(50);

pub async fn list_windows() -> Result<Vec<WindowInfo>> {
    registry::list_windows().await
}

pub async fn focused_window() -> Result<Option<WindowInfo>> {
    Ok(focused_window_with_backend().await?.1)
}

/// The focused window together with the backend that answered, which is known
/// even when no window has focus.
pub async fn focused_window_with_backend() -> Result<(String, Option<WindowInfo>)> {
    if let Some(window) = registry::focused_window_override().await {
        return Ok((window.backend.clone(), Some(window)));
    }

    Ok(focused_in(list_windows().await?))
}

pub(crate) fn focused_in(windows: Vec<WindowInfo>) -> (String, Option<WindowInfo>) {
    let backend = windows
        .first()
        .map(|window| window.backend.clone())
        .unwrap_or_else(|| registry::UNAVAILABLE_BACKEND.to_string());
    (backend, windows.into_iter().find(|window| window.focused))
}

pub async fn focus_window_target(target: &WindowTarget) -> Result<WindowFocusResult> {
    if !target.has_target() {
        bail!("Pass window_id, pid, app_id, wm_class, title, tty, terminal_pid, terminal_command, or terminal_cwd to target a window.");
    }

    let windows = list_windows().await?;
    let requested_window = resolve_window_target(&windows, target)?.clone();
    ensure_backend_can_focus_target(target, &requested_window)?;

    // GNOME Shell's FocusApp selects an icon in the overview, not a window.
    // Introspect can safely verify an already focused app, but cannot raise it.
    let passive = requested_window.backend == registry::GNOME_SHELL_INTROSPECT_BACKEND;
    let focused_window = if passive {
        windows.into_iter().find(|window| window.focused)
    } else {
        registry::activate_window(&requested_window).await?;
        wait_for_focused_window(&requested_window).await
    };
    let exact_window_focused = focused_window
        .as_ref()
        .is_some_and(|window| window.window_id == requested_window.window_id);
    let app_focused = focused_window
        .as_ref()
        .is_some_and(|window| same_optional_string(&window.app_id, &requested_window.app_id));

    Ok(WindowFocusResult {
        backend: requested_window.backend.clone(),
        requested_window,
        focused_window,
        exact_window_focused,
        app_focused,
        note: if passive {
            "GNOME Introspect only verifies current app focus. Focus the target manually or install the GNOME Shell extension to activate windows."
        } else {
            "Computer Use activated the requested window through the available window backend, then verified focus through a fresh window query."
        }.to_string(),
    })
}

pub(crate) fn ensure_backend_can_focus_target(
    target: &WindowTarget,
    window: &WindowInfo,
) -> Result<()> {
    if target.requires_exact_focus() && !registry::backend_can_exact_focus(&window.backend) {
        bail!(
            "Exact window targeting requires an exact-focus window backend; {} can list the matched window but cannot activate a specific window safely.",
            window.backend
        );
    }
    Ok(())
}

async fn wait_for_focused_window(requested_window: &WindowInfo) -> Option<WindowInfo> {
    wait_for_focused_window_with(
        requested_window,
        FOCUS_VERIFY_TRANSITION_TIMEOUT,
        FOCUS_VERIFY_QUERY_TIMEOUT,
        || registry::focused_window_for_backend(&requested_window.backend),
    )
    .await
}

async fn wait_for_focused_window_with<F, Fut>(
    requested_window: &WindowInfo,
    transition_timeout: Duration,
    query_timeout: Duration,
    mut query: F,
) -> Option<WindowInfo>
where
    F: FnMut() -> Fut,
    Fut: Future<Output = Result<Option<WindowInfo>>>,
{
    // Poll until the transition allowance is over, then run one more query:
    // a query that started before focus moved can return a stale window, so
    // the fresh query after it decides. Each query has its own bound, so a
    // slow backend is not cut off by the transition allowance, while fast
    // queries that keep reporting another window still fail on time.
    let deadline = Instant::now() + transition_timeout;
    let mut last_focused_window = None;
    loop {
        let started = Instant::now();
        match timeout_at(started + query_timeout, query()).await {
            Ok(Ok(focused_window)) => {
                if focused_window
                    .as_ref()
                    .is_some_and(|window| window.window_id == requested_window.window_id)
                {
                    return focused_window;
                }
                if focused_window.is_some() {
                    last_focused_window = focused_window;
                }
            }
            Ok(Err(_)) => {}
            Err(_) => break,
        }

        if started >= deadline {
            break;
        }
        sleep_until((Instant::now() + FOCUS_VERIFY_DELAY).min(deadline)).await;
    }
    last_focused_window
}

pub fn resolve_window_target<'a>(
    windows: &'a [WindowInfo],
    target: &WindowTarget,
) -> Result<&'a WindowInfo> {
    if let Some(window_id) = target.window_id {
        return resolve_window_id_target(windows, window_id);
    }

    if target.has_terminal_target() {
        let matches = windows
            .iter()
            .filter(|window| window_matches_terminal_target(window, target))
            .filter(|window| target.pid.is_none_or(|pid| window.pid == Some(pid)))
            .filter(|window| optional_exact_match(&window.app_id, target.app_id.as_deref()))
            .filter(|window| optional_exact_match(&window.wm_class, target.wm_class.as_deref()))
            .filter(|window| optional_title_match(&window.title, target.title.as_deref()))
            .collect::<Vec<_>>();
        return unique_window_match(matches, "terminal target");
    }

    if let Some(pid) = target.pid {
        let matches = windows
            .iter()
            .filter(|window| window.pid == Some(pid))
            .collect::<Vec<_>>();
        return unique_window_match(matches, &format!("pid {pid}"));
    }

    if let Some(app_id) = normalized_target(target.app_id.as_deref()) {
        return resolve_app_id_target(windows, &app_id);
    }

    if let Some(wm_class) = normalized_target(target.wm_class.as_deref()) {
        if let Some(window) = windows.iter().find(|window| {
            window
                .wm_class
                .as_deref()
                .is_some_and(|value| value.eq_ignore_ascii_case(&wm_class))
        }) {
            return Ok(window);
        }
        bail!("No window matched wm_class {wm_class}.");
    }

    if let Some(title) = normalized_target(target.title.as_deref()) {
        let title_lower = title.to_ascii_lowercase();
        if let Some(window) = windows.iter().find(|window| {
            window
                .title
                .as_deref()
                .is_some_and(|value| value.to_ascii_lowercase().contains(&title_lower))
        }) {
            return Ok(window);
        }
        bail!("No window title contained {title}.");
    }

    bail!("Pass window_id, pid, app_id, wm_class, title, tty, terminal_pid, terminal_command, or terminal_cwd to target a window.");
}

fn resolve_app_id_target<'a>(windows: &'a [WindowInfo], app_id: &str) -> Result<&'a WindowInfo> {
    if let Some(window) = windows.iter().find(|window| {
        window
            .app_id
            .as_deref()
            .is_some_and(|value| value.eq_ignore_ascii_case(app_id))
    }) {
        return Ok(window);
    }

    if app_id.contains('.') {
        bail!("No window matched app_id {app_id}.");
    }

    let mut matches = windows.iter().filter(|window| {
        window.app_id.as_deref().is_some_and(|value| {
            crate::windowing::types::app_id_leaf(value).eq_ignore_ascii_case(app_id)
        })
    });
    let Some(first) = matches.next() else {
        bail!("No window matched app_id {app_id}.");
    };
    if matches.any(|window| !same_optional_string(&first.app_id, &window.app_id)) {
        bail!("app_id {app_id} matched multiple applications; use the full app_id.");
    }
    Ok(first)
}

fn resolve_window_id_target(windows: &[WindowInfo], window_id: u64) -> Result<&WindowInfo> {
    windows
        .iter()
        .find(|window| window.window_id == window_id)
        .ok_or_else(|| {
            anyhow::anyhow!(
                "No window matched window_id {window_id}. Re-run list_windows and pass a current window_id."
            )
        })
}

fn unique_window_match<'a>(
    matches: Vec<&'a WindowInfo>,
    description: &str,
) -> Result<&'a WindowInfo> {
    match matches.as_slice() {
        [window] => Ok(*window),
        [] => bail!("No window matched {description}."),
        windows => {
            let ids = windows
                .iter()
                .map(|window| window.window_id.to_string())
                .collect::<Vec<_>>()
                .join(", ");
            bail!(
                "{description} matched multiple windows ({ids}); add window_id, tty, title, or terminal_command to disambiguate."
            );
        }
    }
}

fn window_matches_terminal_target(window: &WindowInfo, target: &WindowTarget) -> bool {
    let Some(terminal) = &window.terminal else {
        return false;
    };

    if let Some(tty) = normalized_target(target.tty.as_deref()) {
        if !tty_matches(&terminal.tty, &tty) {
            return false;
        }
    }

    if let Some(pid) = target.terminal_pid {
        let active_pid = terminal.active_process.as_ref().map(|process| process.pid);
        if active_pid != Some(pid) && terminal.root_process.pid != pid {
            return false;
        }
    }

    if let Some(command) = normalized_target(target.terminal_command.as_deref()) {
        let command = command.to_ascii_lowercase();
        let active_matches = terminal
            .active_process
            .as_ref()
            .is_some_and(|process| terminal_process_matches_command(process, &command));
        if !active_matches && !terminal_process_matches_command(&terminal.root_process, &command) {
            return false;
        }
    }

    if let Some(cwd) = normalized_target(target.terminal_cwd.as_deref()) {
        let active_matches = terminal
            .active_process
            .as_ref()
            .is_some_and(|process| terminal_process_matches_cwd(process, &cwd));
        if !active_matches && !terminal_process_matches_cwd(&terminal.root_process, &cwd) {
            return false;
        }
    }

    true
}

fn terminal_process_matches_command(
    process: &crate::terminal::TerminalProcess,
    command_lower: &str,
) -> bool {
    process
        .command_name
        .to_ascii_lowercase()
        .contains(command_lower)
        || process
            .command_line
            .to_ascii_lowercase()
            .contains(command_lower)
}

fn terminal_process_matches_cwd(process: &crate::terminal::TerminalProcess, cwd: &str) -> bool {
    let requested = cwd.trim_end_matches('/');
    process.cwd.as_deref().is_some_and(|value| {
        let actual = value.trim_end_matches('/');
        actual == requested
            || (!requested.starts_with('/')
                && actual
                    .strip_suffix(requested)
                    .is_some_and(|prefix| prefix.ends_with('/')))
    })
}

fn tty_matches(actual: &str, requested: &str) -> bool {
    actual == requested
        || actual
            .strip_prefix("/dev/")
            .is_some_and(|value| value == requested)
        || actual
            .strip_prefix("/dev/pts/")
            .is_some_and(|value| value == requested)
}

fn optional_exact_match(actual: &Option<String>, requested: Option<&str>) -> bool {
    normalized_target(requested).is_none_or(|requested| {
        actual
            .as_deref()
            .is_some_and(|value| value.eq_ignore_ascii_case(&requested))
    })
}

fn optional_title_match(actual: &Option<String>, requested: Option<&str>) -> bool {
    normalized_target(requested).is_none_or(|requested| {
        let requested = requested.to_ascii_lowercase();
        actual
            .as_deref()
            .is_some_and(|value| value.to_ascii_lowercase().contains(&requested))
    })
}

pub fn window_permission_hint(error: &str) -> Option<String> {
    let lower = error.to_ascii_lowercase();
    if lower.contains("accessdenied")
        || lower.contains("access denied")
        || lower.contains("not allowed")
        || lower.contains("operation not permitted")
        || lower.contains("failed to connect to session bus")
    {
        Some(WINDOW_PERMISSION_HINT.to_string())
    } else {
        None
    }
}

fn normalized_target(value: Option<&str>) -> Option<String> {
    value
        .map(str::trim)
        .filter(|value| !value.is_empty())
        .map(ToOwned::to_owned)
}

fn same_optional_string(left: &Option<String>, right: &Option<String>) -> bool {
    match (left.as_deref(), right.as_deref()) {
        (Some(left), Some(right)) => left.eq_ignore_ascii_case(right),
        _ => false,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn focus_verification_allows_workspace_transition_latency() {
        assert!(FOCUS_VERIFY_TRANSITION_TIMEOUT >= Duration::from_secs(1));
        assert!(FOCUS_VERIFY_QUERY_TIMEOUT >= Duration::from_secs(4));
    }

    #[tokio::test]
    async fn slow_focus_query_is_cut_off_at_its_own_bound() {
        let requested_window = WindowInfo {
            window_id: 1,
            title: None,
            app_id: None,
            wm_class: None,
            pid: None,
            bounds: None,
            workspace: None,
            focused: false,
            hidden: false,
            client_type: None,
            backend: "test".to_string(),
            terminal: None,
        };
        let started = Instant::now();

        let focused = wait_for_focused_window_with(
            &requested_window,
            Duration::from_millis(20),
            Duration::from_millis(20),
            || async {
                tokio::time::sleep(Duration::from_secs(1)).await;
                Ok::<_, anyhow::Error>(None)
            },
        )
        .await;

        assert!(focused.is_none());
        assert!(started.elapsed() < Duration::from_millis(500));
    }

    fn focused_test_window(window_id: u64) -> WindowInfo {
        WindowInfo {
            window_id,
            title: None,
            app_id: None,
            wm_class: None,
            pid: None,
            bounds: None,
            workspace: None,
            focused: true,
            hidden: false,
            client_type: None,
            backend: "test".to_string(),
            terminal: None,
        }
    }

    #[tokio::test]
    async fn slow_fresh_query_verifies_after_a_stale_one() {
        // Each query takes longer than the whole transition allowance. The
        // first one started before focus moved and reports the old window;
        // the next one must still run and see the target.
        let requested_window = WindowInfo {
            focused: false,
            ..focused_test_window(1)
        };
        let attempts = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));

        let focused = wait_for_focused_window_with(
            &requested_window,
            Duration::from_millis(20),
            Duration::from_millis(500),
            || {
                let attempts = std::sync::Arc::clone(&attempts);
                async move {
                    tokio::time::sleep(Duration::from_millis(60)).await;
                    let first = attempts.fetch_add(1, std::sync::atomic::Ordering::SeqCst) == 0;
                    Ok::<_, anyhow::Error>(Some(focused_test_window(if first { 2 } else { 1 })))
                }
            },
        )
        .await;

        assert_eq!(focused.map(|window| window.window_id), Some(1));
    }

    #[tokio::test]
    async fn stale_focus_still_fails_after_the_transition_allowance() {
        // Fast queries that keep reporting another window stop once the
        // transition allowance is over; the longer query bound does not
        // stretch a real focus failure.
        let requested_window = WindowInfo {
            focused: false,
            ..focused_test_window(1)
        };
        let started = Instant::now();

        let focused = wait_for_focused_window_with(
            &requested_window,
            Duration::from_millis(100),
            Duration::from_secs(5),
            || async { Ok::<_, anyhow::Error>(Some(focused_test_window(2))) },
        )
        .await;

        assert_eq!(focused.map(|window| window.window_id), Some(2));
        assert!(started.elapsed() < Duration::from_millis(400));
    }
}