Skip to main content

agentmux_srv_core/backend/fs_ops/
platform.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The OS-specific half of the Files pane's filesystem layer: path display
5//! form, hidden attributes, a rename that never overwrites, a delete that
6//! never follows a link, and the commands that open or reveal a path.
7//!
8//! Deliberately depends on nothing but `std`, `libc` and `windows-sys`, so
9//! every `cfg` arm can be checked on its own.
10//!
11//! Spec: docs/specs/SPEC_FILE_BROWSER_PANE_2026_10_01.md §9.
12
13use std::io;
14use std::path::Path;
15use std::process::{Command, Stdio};
16
17/// `path` as the frontend should see it. On Windows, `canonicalize` returns
18/// verbatim paths (`\\?\C:\…`, `\\?\UNC\host\share\…`); those are turned
19/// back into their ordinary forms. Elsewhere the path is unchanged.
20///
21/// Stripping the prefix loses nothing the server needs: Rust's `std::fs`
22/// re-adds it on its own for an absolute path too long for the legacy APIs.
23pub fn display_path(path: &Path) -> String {
24    let s = path.to_string_lossy();
25    if cfg!(windows) {
26        strip_verbatim(&s)
27    } else {
28        s.into_owned()
29    }
30}
31
32/// The string half of [`display_path`], separate so it can be tested on any
33/// platform. Only the drive and UNC forms are rewritten; any other verbatim
34/// path (`\\?\Volume{…}\`) has no ordinary spelling and is left alone.
35pub fn strip_verbatim(s: &str) -> String {
36    if let Some(rest) = s.strip_prefix(r"\\?\UNC\") {
37        return format!(r"\\{rest}");
38    }
39    if let Some(rest) = s.strip_prefix(r"\\?\") {
40        let b = rest.as_bytes();
41        if b.len() >= 2 && b[0].is_ascii_alphabetic() && b[1] == b':' {
42            return rest.to_string();
43        }
44    }
45    s.to_string()
46}
47
48/// `FILE_ATTRIBUTE_HIDDEN`.
49#[cfg(any(windows, test))]
50const ATTR_HIDDEN: u32 = 0x2;
51/// `FILE_ATTRIBUTE_SYSTEM`.
52#[cfg(any(windows, test))]
53const ATTR_SYSTEM: u32 = 0x4;
54
55/// Whether Windows file attributes mark an entry hidden. Explorer hides both
56/// hidden and system entries by default, so both count (spec §9).
57#[cfg(any(windows, test))]
58pub fn attributes_mark_hidden(attributes: u32) -> bool {
59    attributes & (ATTR_HIDDEN | ATTR_SYSTEM) != 0
60}
61
62/// Whether `meta` (the entry's own metadata, not a link's target) carries
63/// the hidden or system attribute. Always false off Windows, where hidden
64/// means only a leading dot.
65pub fn has_hidden_attribute(meta: &std::fs::Metadata) -> bool {
66    #[cfg(windows)]
67    {
68        use std::os::windows::fs::MetadataExt;
69        attributes_mark_hidden(meta.file_attributes())
70    }
71    #[cfg(not(windows))]
72    {
73        let _ = meta;
74        false
75    }
76}
77
78/// Whether an access error is macOS's privacy system (TCC) refusing, rather
79/// than ordinary permissions: TCC denials are `EPERM`, ordinary ones `EACCES`
80/// (spec §9.1.1 fact 2). Rust maps both to `PermissionDenied`, so the raw
81/// code decides.
82pub fn is_os_blocked(err: &io::Error) -> bool {
83    #[cfg(target_os = "macos")]
84    {
85        err.raw_os_error() == Some(libc::EPERM)
86    }
87    #[cfg(not(target_os = "macos"))]
88    {
89        let _ = err;
90        false
91    }
92}
93
94/// Rename `from` to `to`, failing with `AlreadyExists` instead of replacing
95/// an existing `to`.
96///
97/// `std::fs::rename` replaces an existing destination on every platform, so
98/// checking first and renaming after would let a file created in between be
99/// silently overwritten. The one implementation is the remote helper's
100/// (`agentmux_remote::rename`), so this computer and an SSH host follow one
101/// rule: each OS's atomic no-replace rename, and where the filesystem has
102/// none, steps whose first one takes the new name and fails if it is taken.
103pub fn rename_no_replace(from: &Path, to: &Path) -> io::Result<()> {
104    agentmux_remote::rename::rename_no_replace(from, to)
105}
106
107/// Permanently remove the entry at `path` without following it: a symlink
108/// (or Windows junction) is unlinked and its target kept, a directory is
109/// removed with its contents, anything else is removed as a file.
110///
111/// Same rule as `deleteeditorfile`, which acts on the link path rather than
112/// the canonical path for exactly this reason. `remove_dir_all` does not
113/// follow links inside the tree either.
114pub fn remove_entry_no_follow(path: &Path) -> io::Result<()> {
115    let file_type = std::fs::symlink_metadata(path)?.file_type();
116    if file_type.is_symlink() {
117        // A directory link on Windows (symlink or junction) needs
118        // RemoveDirectory; DeleteFile refuses it. Elsewhere a link is a file.
119        #[cfg(windows)]
120        {
121            use std::os::windows::fs::FileTypeExt;
122            if file_type.is_symlink_dir() {
123                return std::fs::remove_dir(path);
124            }
125        }
126        return std::fs::remove_file(path);
127    }
128    if file_type.is_dir() {
129        std::fs::remove_dir_all(path)
130    } else {
131        std::fs::remove_file(path)
132    }
133}
134
135/// Open `path` for reading, refusing a symlink where the OS can: a copy
136/// reads the file that was listed, never what a link swapped in since
137/// points at (spec §9: never follow a link when copying).
138///
139/// Unix refuses with `O_NOFOLLOW`. Windows opens normally: the flag that
140/// would refuse a link there (`FILE_FLAG_OPEN_REPARSE_POINT`) also opens a
141/// cloud placeholder (OneDrive) without fetching its contents. The caller
142/// checks the opened file's own type either way.
143pub fn open_no_follow(path: &Path) -> io::Result<std::fs::File> {
144    #[cfg(unix)]
145    {
146        use std::os::unix::fs::OpenOptionsExt;
147        std::fs::OpenOptions::new().read(true).custom_flags(libc::O_NOFOLLOW).open(path)
148    }
149    #[cfg(not(unix))]
150    {
151        std::fs::File::open(path)
152    }
153}
154
155/// Create a symlink at `link` pointing at `target`, of the same kind as
156/// the link being copied (`like`, its own file type). Windows has separate
157/// file and directory links; a junction is recreated as a directory link.
158pub fn create_symlink(target: &Path, link: &Path, like: &std::fs::FileType) -> io::Result<()> {
159    #[cfg(unix)]
160    {
161        let _ = like;
162        std::os::unix::fs::symlink(target, link)
163    }
164    #[cfg(windows)]
165    {
166        use std::os::windows::fs::FileTypeExt;
167        if like.is_symlink_dir() {
168            std::os::windows::fs::symlink_dir(target, link)
169        } else {
170            std::os::windows::fs::symlink_file(target, link)
171        }
172    }
173    #[cfg(not(any(unix, windows)))]
174    {
175        let _ = (target, link, like);
176        Err(io::Error::new(io::ErrorKind::Unsupported, "symlinks aren't supported here"))
177    }
178}
179
180/// Whether creating a symlink failed because Windows requires Developer
181/// Mode or elevation for it (`ERROR_PRIVILEGE_NOT_HELD`).
182pub fn is_symlink_privilege_error(err: &io::Error) -> bool {
183    const ERROR_PRIVILEGE_NOT_HELD: i32 = 1314;
184    cfg!(windows) && err.raw_os_error() == Some(ERROR_PRIVILEGE_NOT_HELD)
185}
186
187/// Remove the regular file at `path`. On Windows a read-only file refuses
188/// deletion, so the attribute is cleared first when that is the refusal:
189/// a moved file's original and a discarded partial copy both have to go.
190pub fn remove_file_force(path: &Path) -> io::Result<()> {
191    match std::fs::remove_file(path) {
192        #[cfg(windows)]
193        Err(e) if e.kind() == io::ErrorKind::PermissionDenied => {
194            let meta = std::fs::symlink_metadata(path)?;
195            if !meta.is_file() || !meta.permissions().readonly() {
196                return Err(e);
197            }
198            let mut perms = meta.permissions();
199            // Windows only: this clears the read-only attribute; there is
200            // no Unix mode to make world-writable.
201            #[allow(clippy::permissions_set_readonly_false)]
202            perms.set_readonly(false);
203            std::fs::set_permissions(path, perms)?;
204            std::fs::remove_file(path)
205        }
206        other => other,
207    }
208}
209
210/// Why `path` can't go to the Recycle Bin, if it can't.
211///
212/// Windows has no Recycle Bin on network shares or removable drives, and
213/// the shell's delete with "allow undo" and no UI then deletes permanently
214/// rather than failing. So those are refused here, and the user is pointed
215/// at the explicit permanent delete (spec §7.3). Always `None` elsewhere.
216pub fn trash_unavailable_reason(path: &Path) -> Option<&'static str> {
217    #[cfg(windows)]
218    {
219        const NETWORK: &str = "Network locations have no Recycle Bin. Use Delete permanently instead.";
220        const REMOVABLE: &str = "This drive has no Recycle Bin. Use Delete permanently instead.";
221        // GetDriveTypeW's answers (winbase.h). Defined here rather than
222        // enabling windows-sys's whole WindowsProgramming feature for two.
223        const DRIVE_REMOVABLE: u32 = 2;
224        const DRIVE_REMOTE: u32 = 4;
225        let display = display_path(path);
226        if display.starts_with(r"\\") {
227            return Some(NETWORK);
228        }
229        let b = display.as_bytes();
230        if b.len() >= 2 && b[0].is_ascii_alphabetic() && b[1] == b':' {
231            let root: Vec<u16> = format!("{}:\\", b[0] as char).encode_utf16().chain(std::iter::once(0)).collect();
232            // SAFETY: `root` is a NUL-terminated UTF-16 string that outlives the call.
233            let kind = unsafe { windows_sys::Win32::Storage::FileSystem::GetDriveTypeW(root.as_ptr()) };
234            return match kind {
235                DRIVE_REMOTE => Some(NETWORK),
236                DRIVE_REMOVABLE => Some(REMOVABLE),
237                _ => None,
238            };
239        }
240        None
241    }
242    #[cfg(not(windows))]
243    {
244        let _ = path;
245        None
246    }
247}
248
249/// `explorer.exe`'s argument for `display`. Windows paths can't contain `"`,
250/// so quoting is unambiguous, and it keeps a path with spaces or commas in
251/// one piece. A trailing backslash would escape the closing quote, so it is
252/// trimmed; a drive root (`C:\`) has no spaces and goes unquoted.
253#[cfg_attr(not(windows), allow(dead_code))]
254pub fn explorer_quote(display: &str) -> String {
255    let b = display.as_bytes();
256    if b.len() == 3 && b[0].is_ascii_alphabetic() && b[1] == b':' && b[2] == b'\\' {
257        return display.to_string();
258    }
259    format!("\"{}\"", display.trim_end_matches('\\'))
260}
261
262/// The command that opens `path` with the OS default application, for
263/// `spawn_detached` (which sanitizes its environment).
264pub fn open_command(path: &Path) -> Command {
265    #[cfg(windows)]
266    {
267        use std::os::windows::process::CommandExt;
268        // explorer.exe hands the path to the already-running shell, which
269        // opens it the way a double-click would. ShellExecuteW from this
270        // process would instead start the application from srv's own
271        // environment.
272        let mut cmd = Command::new("explorer.exe");
273        cmd.raw_arg(explorer_quote(&display_path(path)));
274        cmd
275    }
276    #[cfg(target_os = "macos")]
277    {
278        let mut cmd = Command::new("open");
279        cmd.arg(path);
280        cmd
281    }
282    #[cfg(not(any(windows, target_os = "macos")))]
283    {
284        let mut cmd = Command::new("xdg-open");
285        cmd.arg(path);
286        cmd
287    }
288}
289
290/// The command that shows `path` selected in the OS file manager. On Linux
291/// this is the fallback of [`reveal`]: `xdg-open` has no "select", so it opens
292/// the containing folder.
293pub fn reveal_command(path: &Path) -> Command {
294    #[cfg(windows)]
295    {
296        use std::os::windows::process::CommandExt;
297        let mut cmd = Command::new("explorer.exe");
298        cmd.raw_arg(format!("/select,{}", explorer_quote(&display_path(path))));
299        cmd
300    }
301    #[cfg(target_os = "macos")]
302    {
303        let mut cmd = Command::new("open");
304        cmd.arg("-R").arg(path);
305        cmd
306    }
307    #[cfg(not(any(windows, target_os = "macos")))]
308    {
309        let mut cmd = Command::new("xdg-open");
310        cmd.arg(path.parent().unwrap_or(path));
311        cmd
312    }
313}
314
315/// `path` as a `file://` URI, percent-encoded byte by byte: only letters, digits, `-`, `.`, `_`, `~` and the
316/// `/` separators stay as they are, so a space, `#`, `%`, `,` or a non-ASCII character can't change what the
317/// URI names (and `dbus-send` splits its array values at a `,`).
318pub fn file_uri(path: &Path) -> String {
319    let mut uri = String::from("file://");
320    for &b in path.to_string_lossy().as_bytes() {
321        if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~' | b'/') {
322            uri.push(b as char);
323        } else {
324            uri.push_str(&format!("%{b:02X}"));
325        }
326    }
327    uri
328}
329
330/// The `dbus-send` call that asks the desktop's file manager to show `path` selected: the session bus's
331/// `org.freedesktop.FileManager1.ShowItems`, which Nautilus, Dolphin, Nemo, Thunar and the other file managers
332/// that implement the interface answer. The empty string is the startup id.
333pub fn dbus_show_items_command(path: &Path) -> Command {
334    let mut cmd = Command::new("dbus-send");
335    cmd.args([
336        "--session",
337        "--print-reply",
338        "--dest=org.freedesktop.FileManager1",
339        "--type=method_call",
340        "/org/freedesktop/FileManager1",
341        "org.freedesktop.FileManager1.ShowItems",
342    ])
343    .arg(format!("array:string:{}", file_uri(path)))
344    .arg("string:");
345    cmd
346}
347
348/// How long the file manager gets to answer `ShowItems` before `xdg-open` is tried instead. A file manager that
349/// isn't running is started by the bus, which can take a moment.
350pub const DBUS_REVEAL_LIMIT: std::time::Duration = std::time::Duration::from_secs(2);
351
352/// Runs `cmd` with its stdio discarded and waits up to `limit` for it to exit; true only when it exited with
353/// success. A program that is missing, fails or is still running at the limit (which is then stopped) is false.
354/// The strict external-process policy applies, as in [`spawn_detached`] (invariant I7).
355#[cfg_attr(any(windows, target_os = "macos"), allow(dead_code))]
356fn succeeds_within(mut cmd: Command, limit: std::time::Duration) -> bool {
357    crate::backend::pane_env::sanitize_external_std_command(&mut cmd);
358    let Ok(mut child) = cmd.stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()).spawn() else {
359        return false;
360    };
361    let deadline = std::time::Instant::now() + limit;
362    loop {
363        match child.try_wait() {
364            Ok(Some(status)) => return status.success(),
365            Ok(None) if std::time::Instant::now() < deadline => std::thread::sleep(std::time::Duration::from_millis(20)),
366            _ => {
367                let _ = child.kill();
368                let _ = child.wait();
369                return false;
370            }
371        }
372    }
373}
374
375/// The Linux half of [`reveal`], with its two steps passed in so each can be tested alone: `dbus` runs the
376/// `ShowItems` call and says whether it worked; when it didn't (no `dbus-send`, no session bus, the call
377/// failed or timed out), `fallback` gets the `xdg-open` of the containing folder, which is what Linux did
378/// before the file could be selected. A folder is opened itself (its menu rows read "Open in File Manager"), by
379/// `xdg-open` and without the D-Bus call, which would show its parent with the folder selected.
380pub fn reveal_linux(
381    path: &Path,
382    dbus: impl FnOnce(Command) -> bool,
383    fallback: impl FnOnce(Command) -> io::Result<()>,
384) -> io::Result<()> {
385    let folder = path.is_dir();
386    if !folder && dbus(dbus_show_items_command(path)) {
387        return Ok(());
388    }
389    let mut cmd = Command::new("xdg-open");
390    cmd.arg(if folder { path } else { path.parent().unwrap_or(path) });
391    fallback(cmd)
392}
393
394/// Show `path` selected in the OS file manager, the one function every reveal goes through. Windows and macOS
395/// start their file manager detached ([`reveal_command`]). Linux asks the desktop's file manager to select the
396/// file through D-Bus and, where that isn't there, opens the containing folder ([`reveal_linux`]).
397pub fn reveal(path: &Path) -> io::Result<()> {
398    #[cfg(any(windows, target_os = "macos"))]
399    {
400        spawn_detached(reveal_command(path))
401    }
402    #[cfg(not(any(windows, target_os = "macos")))]
403    {
404        reveal_linux(path, |cmd| succeeds_within(cmd, DBUS_REVEAL_LIMIT), spawn_detached)
405    }
406}
407
408/// Spawn `cmd` detached from srv's own stdio, and reap it on a thread.
409///
410/// Null stdio because srv's stdout may be a pipe its launcher reads; a
411/// reaper because an un-waited child stays a zombie on Unix until srv
412/// exits, and `xdg-open` can run as long as the application it starts.
413///
414/// The program is third-party and long-lived (a file manager, or whatever
415/// application the OS opens the file with), and could launch another
416/// AgentMux build that would adopt this instance's identity: the strict
417/// external-process policy, as `openinshell` uses (invariant I7). Applied
418/// here, where the spawn is, so no caller can skip it.
419pub fn spawn_detached(mut cmd: Command) -> io::Result<()> {
420    crate::backend::pane_env::sanitize_external_std_command(&mut cmd);
421    let mut child = cmd.stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()).spawn()?;
422    std::thread::Builder::new()
423        .name("fs-open-reaper".to_string())
424        .spawn(move || {
425            let _ = child.wait();
426        })?;
427    Ok(())
428}
429
430#[cfg(test)]
431mod tests {
432    use super::*;
433
434    #[test]
435    fn verbatim_prefixes_are_stripped_for_display() {
436        assert_eq!(strip_verbatim(r"\\?\C:\Users\me"), r"C:\Users\me");
437        assert_eq!(strip_verbatim(r"\\?\C:\"), r"C:\");
438        assert_eq!(strip_verbatim(r"\\?\UNC\nas\share\dir"), r"\\nas\share\dir");
439        // No ordinary spelling exists for a volume GUID path; keep it.
440        assert_eq!(strip_verbatim(r"\\?\Volume{abc}\x"), r"\\?\Volume{abc}\x");
441        assert_eq!(strip_verbatim("/home/me"), "/home/me");
442        assert_eq!(strip_verbatim(r"C:\plain"), r"C:\plain");
443    }
444
445    #[test]
446    fn hidden_and_system_attributes_both_hide() {
447        assert!(attributes_mark_hidden(0x2));
448        assert!(attributes_mark_hidden(0x4));
449        assert!(attributes_mark_hidden(0x2 | 0x20));
450        assert!(!attributes_mark_hidden(0x20)); // ARCHIVE
451        assert!(!attributes_mark_hidden(0x10)); // DIRECTORY
452        assert!(!attributes_mark_hidden(0x1)); // READONLY
453    }
454
455    #[test]
456    fn explorer_arguments_stay_in_one_piece() {
457        assert_eq!(explorer_quote(r"C:\a b\c,d.txt"), r#""C:\a b\c,d.txt""#);
458        assert_eq!(explorer_quote(r"C:\"), r"C:\");
459        assert_eq!(explorer_quote(r"\\nas\My Share\"), r#""\\nas\My Share""#);
460    }
461
462    #[test]
463    fn rename_no_replace_refuses_an_existing_destination() {
464        let dir = tempfile::tempdir().unwrap();
465        let (a, b) = (dir.path().join("a.txt"), dir.path().join("b.txt"));
466        std::fs::write(&a, "a").unwrap();
467        std::fs::write(&b, "b").unwrap();
468        let err = rename_no_replace(&a, &b).unwrap_err();
469        assert_eq!(err.kind(), io::ErrorKind::AlreadyExists, "{err}");
470        assert_eq!(std::fs::read_to_string(&b).unwrap(), "b", "the destination must be untouched");
471
472        let c = dir.path().join("c.txt");
473        rename_no_replace(&a, &c).unwrap();
474        assert!(!a.exists());
475        assert_eq!(std::fs::read_to_string(&c).unwrap(), "a");
476    }
477
478    #[test]
479    fn deleting_a_link_keeps_its_target() {
480        let dir = tempfile::tempdir().unwrap();
481        let target = dir.path().join("target");
482        std::fs::create_dir(&target).unwrap();
483        std::fs::write(target.join("keep.txt"), "x").unwrap();
484        let link = dir.path().join("link");
485        #[cfg(unix)]
486        let made = std::os::unix::fs::symlink(&target, &link).is_ok();
487        // Creating a symlink on Windows needs Developer Mode or elevation;
488        // without either there's nothing to test.
489        #[cfg(windows)]
490        let made = std::os::windows::fs::symlink_dir(&target, &link).is_ok();
491        if !made {
492            return;
493        }
494        remove_entry_no_follow(&link).unwrap();
495        assert!(std::fs::symlink_metadata(&link).is_err(), "the link is gone");
496        assert!(target.join("keep.txt").exists(), "the target and its contents remain");
497    }
498
499    #[test]
500    fn deleting_a_directory_removes_its_contents() {
501        let dir = tempfile::tempdir().unwrap();
502        let sub = dir.path().join("sub");
503        std::fs::create_dir_all(sub.join("deeper")).unwrap();
504        std::fs::write(sub.join("deeper").join("f.txt"), "x").unwrap();
505        remove_entry_no_follow(&sub).unwrap();
506        assert!(!sub.exists());
507    }
508
509    #[test]
510    fn a_file_uri_keeps_a_path_in_one_piece() {
511        assert_eq!(file_uri(Path::new("/home/me/a.txt")), "file:///home/me/a.txt");
512        // A space, `#`, `%` and `,` would each change what the URI names, or where dbus-send splits it.
513        assert_eq!(file_uri(Path::new("/home/me/a b#c%d,e.txt")), "file:///home/me/a%20b%23c%25d%2Ce.txt");
514        // Non-ASCII is encoded byte by byte, as UTF-8.
515        assert_eq!(file_uri(Path::new("/home/me/é.txt")), "file:///home/me/%C3%A9.txt");
516        assert_eq!(file_uri(Path::new("/home/me/a-b_c~d.e")), "file:///home/me/a-b_c~d.e");
517    }
518
519    #[test]
520    fn the_dbus_call_names_the_file_managers_show_items_method_and_the_file() {
521        let cmd = dbus_show_items_command(Path::new("/home/me/a b.txt"));
522        assert_eq!(cmd.get_program().to_string_lossy(), "dbus-send");
523        let args: Vec<String> = cmd.get_args().map(|a| a.to_string_lossy().into_owned()).collect();
524        assert_eq!(
525            args,
526            [
527                "--session",
528                "--print-reply",
529                "--dest=org.freedesktop.FileManager1",
530                "--type=method_call",
531                "/org/freedesktop/FileManager1",
532                "org.freedesktop.FileManager1.ShowItems",
533                "array:string:file:///home/me/a%20b.txt",
534                "string:",
535            ]
536        );
537    }
538
539    #[test]
540    fn linux_selects_the_file_through_dbus_and_never_opens_the_folder_when_it_worked() {
541        let asked = std::cell::RefCell::new(Vec::new());
542        let r = reveal_linux(
543            Path::new("/home/me/a.txt"),
544            |cmd| {
545                asked.borrow_mut().push(cmd.get_program().to_string_lossy().into_owned());
546                true
547            },
548            |_| panic!("xdg-open must not run when ShowItems worked"),
549        );
550        assert!(r.is_ok());
551        assert_eq!(*asked.borrow(), ["dbus-send"]);
552    }
553
554    #[test]
555    fn linux_opens_the_containing_folder_when_dbus_did_not_work() {
556        // No dbus-send, no session bus, a failed call and a timeout all reach `reveal_linux` as `false`.
557        let opened = std::cell::RefCell::new(None);
558        let r = reveal_linux(
559            Path::new("/home/me/dir/a.txt"),
560            |_| false,
561            |cmd| {
562                let args: Vec<String> = cmd.get_args().map(|a| a.to_string_lossy().into_owned()).collect();
563                *opened.borrow_mut() = Some((cmd.get_program().to_string_lossy().into_owned(), args));
564                Ok(())
565            },
566        );
567        assert!(r.is_ok());
568        assert_eq!(opened.into_inner(), Some(("xdg-open".to_string(), vec!["/home/me/dir".to_string()])));
569    }
570
571    #[test]
572    fn linux_reports_a_failed_fallback() {
573        let r = reveal_linux(Path::new("/home/me/a.txt"), |_| false, |_| Err(io::Error::new(io::ErrorKind::NotFound, "no xdg-open")));
574        assert_eq!(r.unwrap_err().kind(), io::ErrorKind::NotFound);
575    }
576
577    #[test]
578    fn linux_opens_a_folder_itself_and_never_asks_dbus_to_select_it() {
579        let dir = tempfile::tempdir().unwrap();
580        let opened = std::cell::RefCell::new(Vec::new());
581        let r = reveal_linux(
582            dir.path(),
583            |_| panic!("ShowItems would show the folder's parent"),
584            |cmd| {
585                opened.borrow_mut().push(cmd.get_args().map(|a| a.to_os_string()).collect::<Vec<_>>());
586                Ok(())
587            },
588        );
589        assert!(r.is_ok());
590        assert_eq!(*opened.borrow(), [vec![dir.path().as_os_str().to_os_string()]]);
591    }
592
593    #[test]
594    fn a_missing_program_is_not_a_success() {
595        let cmd = Command::new("agentmux-no-such-program-for-this-test");
596        assert!(!succeeds_within(cmd, std::time::Duration::from_secs(1)));
597    }
598
599    #[cfg(unix)]
600    #[test]
601    fn a_program_that_exits_zero_is_a_success_and_one_that_exits_non_zero_is_not() {
602        assert!(succeeds_within(Command::new("true"), std::time::Duration::from_secs(5)));
603        assert!(!succeeds_within(Command::new("false"), std::time::Duration::from_secs(5)));
604    }
605
606    #[cfg(unix)]
607    #[test]
608    fn a_program_still_running_at_the_limit_is_stopped_and_is_not_a_success() {
609        let mut cmd = Command::new("sleep");
610        cmd.arg("30");
611        let started = std::time::Instant::now();
612        assert!(!succeeds_within(cmd, std::time::Duration::from_millis(150)));
613        assert!(started.elapsed() < std::time::Duration::from_secs(10), "it waited for the program instead of stopping it");
614    }
615}