Skip to main content

agentmux_srv_core/backend/container/
mount_source.rs

1//! Comparing a bind mount's source as Docker reports it with the host path it was asked for.
2
3use super::normalize_host_path;
4
5/// Canonical form of a mount source for comparison.
6///
7/// Only Windows is folded, deliberately (#2933): Docker on Windows can report a
8/// differently-cased drive letter than we asked for, and a case-sensitive compare there
9/// produces phantom drift and a needless recreate. Folding unconditionally is the opposite bug:
10/// on a case-sensitive host, switching an agent's workspace from `/work/Foo` to the genuinely
11/// different `/work/foo` would look like a match, `ensure_running` would skip the recreate, and
12/// `/workspace` would keep serving the old directory. Elsewhere only the slashes are normalized.
13pub(super) fn fold_mount_source(source: &str) -> String {
14    if cfg!(windows) {
15        windows_source_key(source)
16    } else {
17        normalize_host_path(source)
18    }
19}
20
21/// What a Windows host path, and the form Docker reports it in, have in common. Docker Desktop
22/// runs containers in a VM and reports a bind source there (`/run/desktop/mnt/host/c/Users/x`;
23/// `/mnt/c/...` and `/host_mnt/c/...` under WSL and older builds), while the source asked for is
24/// the host's (`C:\Users\x`, `C:/Users/x`, or `\\?\C:\Users\x`). Without folding them together
25/// every start reads as drift and recreates the container. Drive letters and case are folded
26/// (NTFS is case-insensitive) and a trailing slash is dropped; a path that is no drive stays as
27/// it is.
28pub(super) fn windows_source_key(source: &str) -> String {
29    let mut path = normalize_host_path(source);
30    if let Some(rest) = path.strip_prefix("//?/") {
31        path = rest.to_string();
32    }
33    for prefix in ["/run/desktop/mnt/host/", "/mnt/host/", "/host_mnt/", "/mnt/"] {
34        let Some(rest) = path.strip_prefix(prefix) else { continue };
35        let (drive, tail) = rest.split_once('/').unwrap_or((rest, ""));
36        if drive.len() == 1 && drive.chars().all(|c| c.is_ascii_alphabetic()) {
37            path = format!("{drive}:/{tail}");
38            break;
39        }
40    }
41    let mut key = path.to_lowercase();
42    while key.len() > 1 && key.ends_with('/') && !key.ends_with(":/") {
43        key.pop();
44    }
45    key
46}
47
48#[cfg(test)]
49mod tests {
50    use super::*;
51
52    #[test]
53    fn a_windows_path_and_every_form_docker_desktop_reports_it_in_are_one_source() {
54        let want = windows_source_key(r"C:\Users\me\dir");
55        for form in [
56            "C:/Users/me/dir",
57            "c:/users/me/dir",
58            r"C:\Users\me/dir",
59            r"\\?\C:\Users\me\dir",
60            "/run/desktop/mnt/host/c/Users/me/dir",
61            "/run/desktop/mnt/host/C/Users/me/dir",
62            "/mnt/host/c/Users/me/dir",
63            "/mnt/c/Users/me/dir",
64            "/host_mnt/c/Users/me/dir",
65            "C:/Users/me/dir/",
66            r"C:\Users\me\dir\",
67            "/run/desktop/mnt/host/c/Users/me/dir/",
68        ] {
69            assert_eq!(windows_source_key(form), want, "{form}");
70        }
71        assert_eq!(want, "c:/users/me/dir");
72    }
73
74    #[test]
75    fn different_directories_and_drives_stay_different() {
76        let base = windows_source_key("C:/Users/me/dir");
77        for other in ["C:/Users/me/other", "D:/Users/me/dir", "/run/desktop/mnt/host/d/Users/me/dir", "/mnt/d/Users/me/dir", "C:/Users/me"] {
78            assert_ne!(windows_source_key(other), base, "{other}");
79        }
80    }
81
82    #[test]
83    fn a_drive_root_and_a_path_that_is_no_drive_keep_their_shape() {
84        assert_eq!(windows_source_key(r"C:\"), "c:/");
85        assert_eq!(windows_source_key("/run/desktop/mnt/host/c"), "c:/");
86        assert_eq!(windows_source_key("/run/desktop/mnt/host/c/"), "c:/");
87        // `/mnt/<x>` that is a folder, not a drive letter.
88        assert_eq!(windows_source_key("/mnt/data/x"), "/mnt/data/x");
89        assert_eq!(windows_source_key("/mnt/ab/x"), "/mnt/ab/x");
90        assert_eq!(windows_source_key("/"), "/");
91        // A named volume's name passes through.
92        assert_eq!(windows_source_key("agentmux-claude-agentmux-abc"), "agentmux-claude-agentmux-abc");
93    }
94
95    /// Case folding must be Windows-only: on a case-sensitive host `/work/Foo` and `/work/foo` are
96    /// different directories, and folding them together would hide real drift and leave /workspace
97    /// on the stale one. Docker Desktop's path form is not rewritten there either.
98    #[test]
99    fn mount_source_is_folded_only_where_the_host_is_windows() {
100        let (a, b) = (fold_mount_source("/work/Foo"), fold_mount_source("/work/foo"));
101        let (vm, host) = (fold_mount_source("/run/desktop/mnt/host/c/x"), fold_mount_source("C:/x"));
102        if cfg!(windows) {
103            assert_eq!(a, b, "windows paths are case-insensitive");
104            assert_eq!(vm, host, "Docker Desktop's form is the host's path");
105        } else {
106            assert_ne!(a, b, "a case-sensitive host must see these as different mounts");
107            assert_ne!(vm, host);
108        }
109        // Slash normalization is unconditional either way.
110        assert_eq!(fold_mount_source(r"C:\a\b"), fold_mount_source("C:/a/b"));
111    }
112
113    /// The container Docker Desktop made for a Windows host's agent is the one `mounts_match` must accept,
114    /// with its sources reported as the VM sees them.
115    #[cfg(windows)]
116    #[test]
117    fn a_container_docker_desktop_made_for_this_spec_has_no_drift() {
118        use super::super::{ContainerManager, ContainerMountSpec};
119        use bollard::models::{ContainerInspectResponse, MountPoint};
120        let spec = ContainerMountSpec {
121            claude_config_host_dir: Some(r"C:\Users\me\.agentmux\shared\claude".to_string()),
122            workspace_host_dir: Some(r"C:\Users\me\.agentmux/agents/a-1".to_string()),
123            memory_host_dir: None,
124            mcp_config_host_dir: None,
125            github_hooks_host_dir: None,
126            aws_config_host_dir: None,
127            aws_tools_host_dir: None,
128            staged_login_config_dir: None,
129            limits: Default::default(),
130        };
131        let reported = |source: &str| match source.split_once(":/") {
132            Some((drive, rest)) if drive.len() == 1 => format!("/run/desktop/mnt/host/{}/{rest}", drive.to_lowercase()),
133            _ => source.to_string(),
134        };
135        let mounts = ContainerManager::desired_owned_mounts("agentmux-a-1", &spec)
136            .into_iter()
137            .map(|(target, source)| {
138                let named = !source.contains('/');
139                MountPoint {
140                    destination: Some(target),
141                    name: named.then(|| source.clone()),
142                    source: Some(if named { format!("/var/lib/docker/volumes/{source}/_data") } else { reported(&source) }),
143                    ..Default::default()
144                }
145            })
146            .collect();
147        let details = ContainerInspectResponse { mounts: Some(mounts), ..Default::default() };
148        assert!(ContainerManager::mounts_match(&details, "agentmux-a-1", &spec));
149        // A workspace that really changed is still drift.
150        let moved = ContainerMountSpec { workspace_host_dir: Some(r"C:\Users\me\.agentmux/agents/a-2".to_string()), ..spec };
151        assert!(!ContainerManager::mounts_match(&details, "agentmux-a-1", &moved));
152    }
153}