computer-use-linux 0.7.52

Native Linux desktop control over MCP and CLI: semantic AT-SPI accessibility trees, multi-compositor window targeting (GNOME, KDE/KWin, Hyprland, niri, COSMIC, i3, Sway, labwc and other wlroots compositors, 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
//! Every subcommand of every binary prints its help on `-h`/`--help` and
//! refuses unknown flags before it touches the desktop.
//!
//! Each run gets a private sandbox: recording stand-ins for the desktop
//! commands first on PATH, a D-Bus address with no bus behind it, display and
//! compositor variables that point nowhere, and private HOME and XDG
//! directories. A call to any stand-in, or a file written in the sandbox,
//! counts as a side effect. With no compositor behind WAYLAND_DISPLAY, the
//! indicator can never show anything on screen.
use std::{
    fs,
    os::unix::fs::PermissionsExt,
    path::{Path, PathBuf},
    process::{Command, Output, Stdio},
    time::{Duration, Instant},
};

const BINARY: &str = env!("CARGO_BIN_EXE_computer-use-linux");
const INDICATOR: &str = env!("CARGO_BIN_EXE_computer-use-linux-indicator");
const COSMIC: &str = env!("CARGO_BIN_EXE_computer-use-linux-cosmic");
const COSMIC_SUBCOMMANDS: &[&str] = &[
    "probe",
    "list-windows",
    "focused-window",
    "monitor-layout",
    "activate-window",
];
const SUBCOMMANDS: &[&str] = &[
    "mcp",
    "doctor",
    "setup",
    "guard-accessibility",
    "setup-window-targeting",
    "apps",
    "state",
    "screenshot",
    "windows",
    "abs-test",
];
const RECORDED_COMMANDS: &[&str] = &[
    "busctl",
    "cosmic-screenshot",
    "dbus-send",
    "dconf",
    "gdbus",
    "gnome-extensions",
    "gnome-screenshot",
    "grim",
    "gsettings",
    "hyprctl",
    "i3-msg",
    "import",
    "kdotool",
    "kreadconfig5",
    "kreadconfig6",
    "kwriteconfig5",
    "kwriteconfig6",
    "niri",
    "notify-send",
    "qdbus",
    "qdbus6",
    "spectacle",
    "swaymsg",
    "systemctl",
    "wmctrl",
    "wtype",
    "xdotool",
    "xdpyinfo",
    "xprop",
    "xwd",
    "xwininfo",
    "ydotool",
    "ydotoold",
];
// The old CLI ran `guard-accessibility --help` as the guard, which never
// exits. A run that outlives this is killed and fails the test.
const DEADLINE: Duration = Duration::from_secs(20);
const SANDBOX_DIRS: &[&str] = &["home", "config", "data", "cache", "state", "runtime"];

struct Sandbox {
    root: PathBuf,
}

impl Sandbox {
    fn new(label: &str) -> Self {
        let root = Path::new(env!("CARGO_TARGET_TMPDIR"))
            .join(format!("cli-flags-{label}-{}", getrandom::u64().unwrap()));
        let bin = root.join("bin");
        fs::create_dir_all(&bin).unwrap();
        for dir in SANDBOX_DIRS {
            fs::create_dir_all(root.join(dir)).unwrap();
        }
        fs::set_permissions(root.join("runtime"), fs::Permissions::from_mode(0o700)).unwrap();
        let log = root.join("calls.log");
        for name in RECORDED_COMMANDS {
            let script = bin.join(name);
            fs::write(
                &script,
                format!(
                    "#!/bin/sh\nprintf '%s %s\\n' \"${{0##*/}}\" \"$*\" >> '{}'\nexit 1\n",
                    log.display()
                ),
            )
            .unwrap();
            fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap();
        }
        Self { root }
    }

    /// The main binary's output, or why it failed to finish.
    fn run(&self, arguments: &[&str]) -> Result<Output, String> {
        self.run_binary(BINARY, arguments)
    }

    /// The output of `binary`, or why it failed to finish.
    fn run_binary(&self, binary: &str, arguments: &[&str]) -> Result<Output, String> {
        let dir = |name: &str| self.root.join(name);
        let mut child = Command::new(binary)
            .args(arguments)
            .env_clear()
            .env("PATH", dir("bin"))
            .env("HOME", dir("home"))
            .env("XDG_CONFIG_HOME", dir("config"))
            .env("XDG_DATA_HOME", dir("data"))
            .env("XDG_CACHE_HOME", dir("cache"))
            .env("XDG_STATE_HOME", dir("state"))
            .env("XDG_RUNTIME_DIR", dir("runtime"))
            .env("GSETTINGS_BACKEND", "memory")
            // Every key session discovery fills when it is empty, so nothing
            // is borrowed from the desktop session running the tests.
            .env(
                "DBUS_SESSION_BUS_ADDRESS",
                format!("unix:path={}", dir("no-bus").display()),
            )
            .env("DISPLAY", ":4271")
            .env("WAYLAND_DISPLAY", "cul-test-no-wayland")
            .env("XAUTHORITY", dir("no-xauthority"))
            .env("XDG_SESSION_TYPE", "wayland")
            .env("XDG_CURRENT_DESKTOP", "GNOME")
            .env("XDG_SESSION_DESKTOP", "gnome")
            .env("DESKTOP_SESSION", "gnome")
            .env("HYPRLAND_INSTANCE_SIGNATURE", "cul-test-no-hyprland")
            .env("NIRI_SOCKET", dir("no-niri"))
            .env("YDOTOOL_SOCKET", dir("no-ydotool"))
            .stdin(Stdio::null())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .unwrap();
        let started = Instant::now();
        while child.try_wait().unwrap().is_none() {
            if started.elapsed() > DEADLINE {
                child.kill().unwrap();
                let output = child.wait_with_output().unwrap();
                return Err(format!(
                    "{binary} {arguments:?} still ran after {DEADLINE:?}; side effects: {:?}; stderr: {}",
                    self.side_effects(),
                    String::from_utf8_lossy(&output.stderr)
                ));
            }
            std::thread::sleep(Duration::from_millis(20));
        }
        Ok(child.wait_with_output().unwrap())
    }

    /// Commands the run started and files it wrote, if any.
    fn side_effects(&self) -> Vec<String> {
        let mut effects: Vec<String> = fs::read_to_string(self.root.join("calls.log"))
            .unwrap_or_default()
            .lines()
            .map(|line| format!("ran {line}"))
            .collect();
        for dir in SANDBOX_DIRS {
            let mut pending = vec![self.root.join(dir)];
            while let Some(path) = pending.pop() {
                for entry in fs::read_dir(&path).unwrap() {
                    let entry = entry.unwrap().path();
                    if entry.is_dir() {
                        pending.push(entry.clone());
                    }
                    effects.push(format!(
                        "wrote {}",
                        entry.strip_prefix(&self.root).unwrap().display()
                    ));
                }
            }
        }
        effects
    }
}

impl Drop for Sandbox {
    fn drop(&mut self) {
        let _ = fs::remove_dir_all(&self.root);
    }
}

/// True when a usage line of `text` is `computer-use-linux NAME`, alone or
/// followed by its arguments and summary. A substring match would let
/// `setup-window-targeting` stand in for `setup`.
fn has_usage_line(text: &str, name: &str) -> bool {
    has_usage(text, &format!("computer-use-linux {name}"))
}

/// True when a line of `text` is `usage`, alone or followed by more words.
fn has_usage(text: &str, usage: &str) -> bool {
    text.lines()
        .map(str::trim)
        .any(|line| line == usage || line.starts_with(&format!("{usage} ")))
}

fn binary_name(binary: &str) -> &str {
    Path::new(binary).file_name().unwrap().to_str().unwrap()
}

fn describe(arguments: &[&str], output: &Output, effects: &[String]) -> String {
    format!(
        "{arguments:?}: {}\nside effects: {effects:?}\nstdout: {}\nstderr: {}",
        output.status,
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    )
}

#[test]
fn every_subcommand_prints_help_without_side_effects() {
    let mut failures = Vec::new();
    for subcommand in SUBCOMMANDS {
        for flag in ["--help", "-h"] {
            let sandbox = Sandbox::new("help");
            let arguments = [*subcommand, flag];
            let output = match sandbox.run(&arguments) {
                Ok(output) => output,
                Err(failure) => {
                    failures.push(failure);
                    continue;
                }
            };
            let effects = sandbox.side_effects();
            let stdout = String::from_utf8_lossy(&output.stdout);
            if output.status.code() != Some(0)
                || !effects.is_empty()
                || !stdout.contains("Usage:")
                || !has_usage_line(&stdout, subcommand)
            {
                failures.push(describe(&arguments, &output, &effects));
            }
        }
    }
    assert!(failures.is_empty(), "{}", failures.join("\n\n"));
}

#[test]
fn every_subcommand_refuses_unknown_flags_without_side_effects() {
    let mut failures = Vec::new();
    for subcommand in SUBCOMMANDS {
        let sandbox = Sandbox::new("flag");
        let arguments = [*subcommand, "--cul-no-such-flag"];
        let output = match sandbox.run(&arguments) {
            Ok(output) => output,
            Err(failure) => {
                failures.push(failure);
                continue;
            }
        };
        let effects = sandbox.side_effects();
        let stderr = String::from_utf8_lossy(&output.stderr);
        if output.status.code() != Some(2)
            || !effects.is_empty()
            || !stderr.contains("unknown option '--cul-no-such-flag'")
        {
            failures.push(describe(&arguments, &output, &effects));
        }
    }
    assert!(failures.is_empty(), "{}", failures.join("\n\n"));
}

#[test]
fn top_level_help_lists_every_command_and_bad_lines_exit_2() {
    for arguments in [&[][..], &["--help"][..], &["-h"][..]] {
        let sandbox = Sandbox::new("top");
        let output = sandbox.run(arguments).unwrap();
        let effects = sandbox.side_effects();
        let stdout = String::from_utf8_lossy(&output.stdout);
        assert_eq!(
            output.status.code(),
            Some(0),
            "{}",
            describe(arguments, &output, &effects)
        );
        assert!(
            effects.is_empty(),
            "{}",
            describe(arguments, &output, &effects)
        );
        for subcommand in SUBCOMMANDS.iter().filter(|name| **name != "abs-test") {
            assert!(
                has_usage_line(&stdout, subcommand),
                "usage misses {subcommand}: {stdout}"
            );
        }
    }

    for arguments in [
        &["--cul-no-such-flag"][..],
        &["cul-no-such-command"][..],
        &["state", "one", "two"][..],
        &["doctor", "extra"][..],
        &["abs-test", "10"][..],
        &["abs-test", "ten", "20"][..],
    ] {
        let sandbox = Sandbox::new("bad");
        let output = sandbox.run(arguments).unwrap();
        let effects = sandbox.side_effects();
        assert_eq!(
            output.status.code(),
            Some(2),
            "{}",
            describe(arguments, &output, &effects)
        );
        assert!(
            effects.is_empty(),
            "{}",
            describe(arguments, &output, &effects)
        );
    }
}

/// Runs a helper binary in a fresh sandbox and returns a failure description
/// when `check` rejects the run or it had side effects.
fn check_helper(
    binary: &str,
    arguments: &[&str],
    check: impl Fn(&Output) -> bool,
) -> Option<String> {
    let sandbox = Sandbox::new("helper");
    let shown: Vec<&str> = std::iter::once(binary_name(binary))
        .chain(arguments.iter().copied())
        .collect();
    let output = match sandbox.run_binary(binary, arguments) {
        Ok(output) => output,
        Err(failure) => return Some(failure),
    };
    let effects = sandbox.side_effects();
    (!check(&output) || !effects.is_empty()).then(|| describe(&shown, &output, &effects))
}

#[test]
fn helper_binaries_print_help_without_side_effects() {
    let mut cases: Vec<(&str, Vec<&str>, Vec<String>)> = Vec::new();
    for flag in ["--help", "-h"] {
        cases.push((
            INDICATOR,
            vec![flag],
            vec!["computer-use-linux-indicator".to_string()],
        ));
        let every_command = COSMIC_SUBCOMMANDS
            .iter()
            .map(|name| format!("computer-use-linux-cosmic {name}"))
            .collect::<Vec<_>>();
        cases.push((COSMIC, vec![flag], every_command.clone()));
        if flag == "--help" {
            cases.push((COSMIC, vec![], every_command));
        }
        for name in COSMIC_SUBCOMMANDS {
            cases.push((
                COSMIC,
                vec![name, flag],
                vec![format!("computer-use-linux-cosmic {name}")],
            ));
        }
    }
    cases.push((
        COSMIC,
        vec!["activate-window", "--window-id", "1", "--help"],
        vec!["computer-use-linux-cosmic activate-window --window-id ID".to_string()],
    ));

    let failures: Vec<String> = cases
        .iter()
        .filter_map(|(binary, arguments, usages)| {
            check_helper(binary, arguments, |output| {
                let stdout = String::from_utf8_lossy(&output.stdout);
                output.status.code() == Some(0)
                    && stdout.contains("Usage:")
                    && usages.iter().all(|usage| has_usage(&stdout, usage))
            })
        })
        .collect();
    assert!(failures.is_empty(), "{}", failures.join("\n\n"));
}

#[test]
fn helper_binaries_refuse_bad_command_lines_with_status_2_and_no_side_effects() {
    let mut cases: Vec<(&str, Vec<&str>)> = vec![
        (INDICATOR, vec!["--cul-no-such-flag"]),
        (INDICATOR, vec!["extra"]),
        (INDICATOR, vec!["--", "extra"]),
        (COSMIC, vec!["--cul-no-such-flag"]),
        (COSMIC, vec!["cul-no-such-command"]),
        (COSMIC, vec!["probe", "extra"]),
        (COSMIC, vec!["probe", "--", "--help"]),
        (COSMIC, vec!["activate-window"]),
        (COSMIC, vec!["activate-window", "--window-id"]),
        (COSMIC, vec!["activate-window", "--window-id", "nope"]),
        (COSMIC, vec!["activate-window", "--window-id", "1", "extra"]),
        (
            COSMIC,
            vec!["activate-window", "--window-id", "1", "--window-id", "2"],
        ),
    ];
    for name in COSMIC_SUBCOMMANDS {
        cases.push((COSMIC, vec![name, "--cul-no-such-flag"]));
    }

    let failures: Vec<String> = cases
        .iter()
        .filter_map(|(binary, arguments)| {
            check_helper(binary, arguments, |output| {
                let stderr = String::from_utf8_lossy(&output.stderr);
                let named_flag = !arguments.contains(&"--cul-no-such-flag")
                    || stderr.contains("unknown option '--cul-no-such-flag'");
                output.status.code() == Some(2)
                    && output.stdout.is_empty()
                    && stderr.contains("--help")
                    && named_flag
            })
        })
        .collect();
    assert!(failures.is_empty(), "{}", failures.join("\n\n"));
}