Skip to main content

agentmux_common/
runtime_mode.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Runtime mode detection — single source of truth.
5//!
6//! The launcher computes [`RuntimeMode::current`] once at startup and
7//! propagates the result to host + srv via the `AGENTMUX_RUNTIME_MODE`
8//! environment variable. No binary should call [`current`] more than
9//! once per process; downstream binaries read the env var via
10//! [`from_env`] instead.
11//!
12//! Replaces the legacy mix of `cfg!(debug_assertions)`, `env::var
13//! ("AGENTMUX_DEV").is_ok()`, and `== Ok("1")` checks across launcher,
14//! host, and sidecar — which were each correct in isolation but
15//! desynchronized in combination (see docs/specs/
16//! SPEC_DATA_DIR_UNIFICATION_2026-05-05.md §2.1).
17//!
18//! # Detection priority
19//!
20//! 1. `AGENTMUX_RUNTIME_MODE` env override (testing, CI).
21//! 2. Marker-based portable detection: an `agentmux-portable.marker` file
22//!    written by `scripts/package-portable.sh`. Looked for next to the
23//!    detecting exe, one level down in `runtime/` (the packaging puts it
24//!    there to keep the extract root clean; the launcher is at the root and
25//!    the host/srv run from `runtime/`), and two levels up for macOS .app
26//!    bundles.
27//! 3. Path-based dev detection: exe is under a known dev-build dir
28//!    (`dist/cef-dev*/`, `target/debug/`, `target/release/`).
29//! 4. `AGENTMUX_DEV_BRANCH` env override (CI override for dev mode).
30//! 5. Default: `Installed`.
31
32#[cfg(windows)]
33use crate::win32::NoWindow;
34use std::path::{Path, PathBuf};
35use std::process::Command;
36
37/// Where this AgentMux binary is running from. Determines data path
38/// layout (see [`crate::DataPaths`]).
39#[derive(Debug, Clone, PartialEq, Eq)]
40pub enum RuntimeMode {
41    /// Installed via the platform installer (msi/dmg/deb). State lives
42    /// in `~/.agentmux/versions/<v>/`.
43    Installed,
44    /// Running from an extracted portable ZIP. State STILL lives in
45    /// `~/.agentmux/versions/<v>/` (not under the portable folder) —
46    /// portable binaries are stateless on disk.
47    Portable,
48    /// Running from a source-tree build. State lives in
49    /// `~/.agentmux/dev/<branch>/<clone_id>/` so different branches
50    /// AND different clones of the same branch don't share state.
51    ///
52    /// `clone_id` is a 16-char hex hash of the clone's workspace-root
53    /// path, derived by [`derive_clone_id`] when the launcher detects
54    /// Dev mode. `None` is permitted for backward compatibility with
55    /// callers that construct `RuntimeMode::Dev` directly (tests, the
56    /// `dev:branch` env-string parser that pre-dates this field): in
57    /// that case path resolution falls back to the old two-level
58    /// `dev/<branch>/` layout. See
59    /// `docs/analysis/ANALYSIS_MULTI_CLONE_TASK_DEV_ISOLATION_2026-05-26.md`.
60    Dev {
61        branch: String,
62        clone_id: Option<String>,
63    },
64}
65
66impl RuntimeMode {
67    /// Detect runtime mode from the launcher's vantage point. Call
68    /// ONCE at process startup. Subsequent processes read the
69    /// `AGENTMUX_RUNTIME_MODE` env var via [`Self::from_env`].
70    ///
71    /// `exe_dir` should be `current_exe().parent()` of the binary
72    /// doing the detection (typically the launcher).
73    pub fn current(exe_dir: &Path) -> Self {
74        // 1. Explicit AGENTMUX_RUNTIME_MODE override (tests, CI, ops).
75        if let Ok(s) = std::env::var("AGENTMUX_RUNTIME_MODE") {
76            if let Some(mode) = parse_mode_string(&s) {
77                return mode;
78            }
79        }
80
81        // 2. Portable: marker file written next to the launcher by
82        //    `scripts/package-portable.sh`. The presence of a
83        //    `runtime/` subdir is NOT a discriminator — installed
84        //    builds ship it too — so we require the explicit marker.
85        if is_portable_marker_present(exe_dir) {
86            return Self::Portable;
87        }
88
89        // 3. Path-based dev detection: exe lives under a known
90        //    build-output dir.
91        if exe_dir_is_dev_build(exe_dir) {
92            let branch = detect_branch(exe_dir);
93            let clone_id = derive_clone_id(exe_dir);
94            return Self::Dev { branch, clone_id };
95        }
96
97        // 4. AGENTMUX_DEV_BRANCH override. The env-var IS the branch
98        //    source at this step; sanitize it directly, do NOT call
99        //    detect_branch (which has its own git fallback that would
100        //    take over when the env-var sanitizes to empty — and could
101        //    then return a real branch name from an unrelated .git
102        //    ancestor of `exe_dir`, silently routing installed runs
103        //    into Dev when the user only had a typo'd env var).
104        //
105        //    If the env value is unusable (empty after trim, or
106        //    sanitizes to empty via path-traversal stripping), fall
107        //    through to Installed instead of inventing a branch.
108        if let Ok(b) = std::env::var("AGENTMUX_DEV_BRANCH") {
109            let slug = sanitize_branch_slug(&b);
110            if !slug.is_empty() {
111                let clone_id = derive_clone_id(exe_dir);
112                return Self::Dev {
113                    branch: slug,
114                    clone_id,
115                };
116            }
117        }
118
119        // 5. Default.
120        Self::Installed
121    }
122
123    /// Read mode from the `AGENTMUX_RUNTIME_MODE` env var the launcher
124    /// set. Used by host + srv to consume the launcher's decision
125    /// without re-detecting (which would re-introduce the desync risk
126    /// the legacy code had).
127    pub fn from_env() -> Option<Self> {
128        std::env::var("AGENTMUX_RUNTIME_MODE")
129            .ok()
130            .and_then(|s| parse_mode_string(&s))
131    }
132
133    /// Path-only detection — skips the `AGENTMUX_RUNTIME_MODE` env step.
134    /// Use when the env can't be trusted (e.g., the binary was launched
135    /// as a child of a different AgentMux process that set its own
136    /// `AGENTMUX_*` vars). Mirrors the rest of [`Self::current`]'s
137    /// priority order (portable marker → dev exe path → installed).
138    pub fn current_path_only(exe_dir: &Path) -> Self {
139        if is_portable_marker_present(exe_dir) {
140            return Self::Portable;
141        }
142        if exe_dir_is_dev_build(exe_dir) {
143            let branch = detect_branch(exe_dir);
144            let clone_id = derive_clone_id(exe_dir);
145            return Self::Dev { branch, clone_id };
146        }
147        Self::Installed
148    }
149
150    /// Encode for the `AGENTMUX_RUNTIME_MODE` env var. Round-trips
151    /// with [`parse_mode_string`].
152    pub fn to_env_string(&self) -> String {
153        match self {
154            Self::Installed => "installed".to_string(),
155            Self::Portable => "portable".to_string(),
156            // clone_id is intentionally NOT encoded here; it round-trips
157            // via a dedicated `AGENTMUX_CLONE_ID` env var so the existing
158            // `dev:<branch>` wire format stays backward-compatible with
159            // older launchers / parsers.
160            Self::Dev { branch, .. } => format!("dev:{}", branch),
161        }
162    }
163
164    /// Slug used inside `~/.agentmux/` to separate state by mode.
165    /// Stable across releases of the same major mode + branch.
166    pub fn dir_slug(&self) -> String {
167        match self {
168            // Versioned modes don't include the version here — that's
169            // appended separately in DataPaths so callers can re-use
170            // RuntimeMode across version queries.
171            Self::Installed | Self::Portable => "versions".to_string(),
172            // Defense in depth: branch is sanitized at parse time, but
173            // a Dev variant constructed directly (e.g. via tests) might
174            // still hold an unsafe value. Slug-on-format ensures the
175            // returned string is always exactly two segments — `dev/`
176            // followed by a single-segment branch slug — so callers
177            // splitting on `/` see the expected shape and the resulting
178            // filesystem path is always a child of `dev/`.
179            // Slug includes the clone_id when present so two clones of
180            // the same branch land in distinct subdirs. When clone_id
181            // is None (env-roundtrip or direct test construction), fall
182            // back to the legacy two-level layout for compatibility.
183            Self::Dev { branch, clone_id } => {
184                let b = sanitize_branch_slug(branch);
185                match clone_id.as_deref().map(sanitize_clone_id) {
186                    Some(c) if !c.is_empty() => format!("dev/{}/{}", b, c),
187                    _ => format!("dev/{}", b),
188                }
189            }
190        }
191    }
192
193    /// Read the runtime mode AND clone_id from the env vars exported
194    /// by the parent process. Pairs `AGENTMUX_RUNTIME_MODE` (variant +
195    /// branch) with `AGENTMUX_CLONE_ID` (Dev-only clone discriminator).
196    /// This is the version every child process (host, srv) should
197    /// call — [`Self::from_env`] is the legacy single-var form kept
198    /// for callers that don't care about clone isolation.
199    pub fn from_env_with_clone() -> Option<Self> {
200        let mode = Self::from_env()?;
201        if let Self::Dev { branch, .. } = mode {
202            let clone_id = std::env::var("AGENTMUX_CLONE_ID")
203                .ok()
204                .map(|s| sanitize_clone_id(&s))
205                .filter(|s| !s.is_empty());
206            return Some(Self::Dev { branch, clone_id });
207        }
208        Some(mode)
209    }
210}
211
212/// True when this binary is running from one of our known dev-build
213/// output directories (`dist/cef-dev*/`, `target/debug/`, `target/release/`).
214/// Walks ancestors to handle nested cases (CEF subprocesses run from a
215/// `runtime/` subdir even in dev). Path-only — does not read env.
216pub fn is_dev_build_exe(exe_dir: &Path) -> bool {
217    exe_dir_is_dev_build(exe_dir)
218}
219
220/// True iff THIS binary is a source-tree / `task dev` build, determined from
221/// the binary's path + portable marker via [`RuntimeMode::current_path_only`]
222/// — NOT from `AGENTMUX_RUNTIME_MODE`. A running `task dev` AgentMux exports
223/// `AGENTMUX_RUNTIME_MODE=dev:<branch>` into its environment, which every
224/// descendant process inherits; a packaged build launched from a terminal /
225/// agent pane inside a dev instance would otherwise mis-identify as Dev (e.g.
226/// the "DEV" status-bar badge on a release build). Build identity is a
227/// property of the binary on disk, not of whoever launched it.
228///
229/// Use for **build-identity** self-checks (the DEV badge, the "AgentMux DEV"
230/// menu name, the dev-only frontend fallback). For intra-instance plumbing
231/// that must agree with the launcher's already-made decision, use
232/// [`RuntimeMode::from_env`] instead.
233///
234/// Answered from the path alone and read once: the binary does not move under
235/// a running process. It must stay cheap, because the host asks it on its UI
236/// thread at every page load ([`exe_dir_is_dev`] says what it used to cost).
237pub fn is_dev_self() -> bool {
238    static IS_DEV: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
239    *IS_DEV.get_or_init(|| {
240        std::env::current_exe()
241            .ok()
242            .and_then(|p| p.parent().map(|d| d.to_path_buf()))
243            .is_some_and(|d| exe_dir_is_dev(&d))
244    })
245}
246
247/// Whether the binary in `exe_dir` is a source-tree build: what
248/// [`RuntimeMode::current_path_only`] answers `Dev` for, without building the
249/// mode. Building it finds the branch, which starts `git` and waits for it. A
250/// caller that only needs the yes or no must not pay for a process: the host
251/// asked through `current_path_only` on its UI thread at every page load, and
252/// a dev build froze for as long as `git` took to start (task #47585).
253pub fn exe_dir_is_dev(exe_dir: &Path) -> bool {
254    !is_portable_marker_present(exe_dir) && exe_dir_is_dev_build(exe_dir)
255}
256
257/// How many times the calling thread has started `git` to find a branch. For
258/// tests that a path stays free of process starts; per thread, so tests that
259/// run side by side do not count each other.
260pub fn git_branch_lookups() -> usize {
261    GIT_BRANCH_LOOKUPS.with(|n| n.get())
262}
263
264thread_local! {
265    static GIT_BRANCH_LOOKUPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
266}
267
268fn parse_mode_string(s: &str) -> Option<RuntimeMode> {
269    let trimmed = s.trim();
270    if trimmed.eq_ignore_ascii_case("installed") {
271        return Some(RuntimeMode::Installed);
272    }
273    if trimmed.eq_ignore_ascii_case("portable") {
274        return Some(RuntimeMode::Portable);
275    }
276    if let Some(raw_branch) = trimmed.strip_prefix("dev:") {
277        // Slugify at parse time — the branch then flows through
278        // DataPaths::resolve into a `~/.agentmux/dev/<branch>/` path,
279        // and we must not let `/`, `..`, or shell-meta chars in the
280        // env override (`AGENTMUX_RUNTIME_MODE=dev:../versions/x`)
281        // escape the dev/ subtree.
282        let slug = sanitize_branch_slug(raw_branch);
283        if slug.is_empty() {
284            return None;
285        }
286        // clone_id is not encoded in this wire format — callers that
287        // care about clone isolation should use [`RuntimeMode::from_env_with_clone`]
288        // which pairs this with `AGENTMUX_CLONE_ID`.
289        return Some(RuntimeMode::Dev {
290            branch: slug,
291            clone_id: None,
292        });
293    }
294    if trimmed.eq_ignore_ascii_case("dev") {
295        return Some(RuntimeMode::Dev {
296            branch: "default".to_string(),
297            clone_id: None,
298        });
299    }
300    None
301}
302
303// ── Clone-id derivation ────────────────────────────────────────────────
304
305/// Walk up from `exe_dir` looking for a workspace-root marker, then
306/// hash that absolute (canonical) path with FNV-1a and return a 16-char
307/// hex string. Used as the per-clone discriminator in
308/// `~/.agentmux/dev/<branch>/<clone_id>/`. Returns `None` if no marker
309/// is found (extreme edge case — `task dev` always runs from inside a
310/// clone with `.git`/`Cargo.toml`/`Taskfile.yml`).
311///
312/// Recognized markers (any one suffices, in priority order):
313/// `.git` (dir or file — supports git worktrees), `Cargo.toml`,
314/// `Taskfile.yml`. We prefer `.git` because it identifies the literal
315/// clone, but Cargo.toml is a safe fallback (the workspace root has
316/// a `[workspace]` Cargo.toml).
317pub fn derive_clone_id(exe_dir: &Path) -> Option<String> {
318    let root = find_clone_root(exe_dir)?;
319    // Canonicalize to absorb mixed casing on Windows and resolve `..`
320    // segments. Falls back to the raw path if canonicalize fails
321    // (rare on real filesystems but possible on transient mounts).
322    let canonical = root.canonicalize().unwrap_or(root);
323    let s = canonical.to_string_lossy().to_lowercase();
324    Some(format!("{:016x}", fnv1a_64(s.as_bytes())))
325}
326
327fn find_clone_root(start: &Path) -> Option<std::path::PathBuf> {
328    let mut cur = Some(start);
329    while let Some(p) = cur {
330        if p.join(".git").exists()
331            || p.join("Cargo.toml").is_file()
332            || p.join("Taskfile.yml").is_file()
333        {
334            return Some(p.to_path_buf());
335        }
336        cur = p.parent();
337    }
338    None
339}
340
341/// Lenient sanitization for a clone_id received via env. The launcher
342/// produces a clean 16-hex string, but env vars survive process hops
343/// and could be tampered with — refuse anything that contains path
344/// separators or `..` segments before it lands in a filesystem path.
345fn sanitize_clone_id(s: &str) -> String {
346    let trimmed = s.trim();
347    if trimmed.is_empty()
348        || trimmed.contains('/')
349        || trimmed.contains('\\')
350        || trimmed.contains("..")
351        || trimmed.contains('\0')
352    {
353        return String::new();
354    }
355    trimmed.to_string()
356}
357
358// Tiny FNV-1a-64 kept inline so agentmux-common doesn't have to depend
359// on agentmux-launcher. Matches `crates/launcher/src/hash.rs`
360// byte-for-byte so hashes are interchangeable.
361const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325;
362const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;
363
364pub fn fnv1a_64(bytes: &[u8]) -> u64 {
365    let mut hash = FNV_OFFSET_BASIS;
366    for b in bytes {
367        hash ^= *b as u64;
368        hash = hash.wrapping_mul(FNV_PRIME);
369    }
370    hash
371}
372
373/// True when `exe_dir` (or its parent on macOS app bundles) contains
374/// the `agentmux-portable.marker` marker file written by
375/// `scripts/package-portable.sh` at packaging time. Installed builds
376/// NEVER write this marker.
377///
378/// Falls back to `false` (i.e., not portable) if the dir isn't readable
379/// — installed-mode default is the safer guess when unsure.
380fn is_portable_marker_present(exe_dir: &Path) -> bool {
381    // Next to the detecting binary. Covers the host/srv (which live in
382    // `runtime/`, so `exe_dir` IS `runtime/`) and legacy portables that wrote
383    // the marker at the extract root next to the launcher.
384    if exe_dir.join("agentmux-portable.marker").is_file() {
385        return true;
386    }
387    // The launcher sits at the extract root with the marker one level down in
388    // `runtime/` (the packaging keeps the root clean: just agentmux.exe +
389    // README + runtime/). Check there so root-level detection still works.
390    if exe_dir.join("runtime").join("agentmux-portable.marker").is_file() {
391        return true;
392    }
393    // On macOS the launcher exe is at <Bundle>.app/Contents/MacOS/<exe>;
394    // a portable .app would put the marker at the bundle root, two
395    // levels up.
396    if let Some(bundle_root) = exe_dir.parent().and_then(|p| p.parent()) {
397        if bundle_root.join("agentmux-portable.marker").is_file() {
398            return true;
399        }
400    }
401    false
402}
403
404/// The ephemeral build label of a local portable, from the marker
405/// `scripts/package-portable.sh` writes into `runtime/`:
406/// `AgentMux portable build <label>`, e.g.
407/// `0.59.16+g2a5424fe2.20261008T234046.81801`. Read at runtime, not baked,
408/// because it changes every build and a binary that wasn't rebuilt would
409/// carry a stale one. `exe_dir` is the running binary's directory: the
410/// marker sits next to the host and srv (both in `runtime/`), or one level
411/// up for older portables. `None` for released, installed and dev builds.
412pub fn portable_build_label(exe_dir: &Path) -> Option<String> {
413    let candidates = [Some(exe_dir.join("agentmux-portable.marker")), exe_dir.parent().map(|p| p.join("agentmux-portable.marker"))];
414    candidates.into_iter().flatten().find_map(|path| {
415        let contents = std::fs::read_to_string(path).ok()?;
416        let label = contents.trim().strip_prefix("AgentMux portable build ")?.trim();
417        (!label.is_empty()).then(|| label.to_string())
418    })
419}
420
421/// The file in a portable's `runtime/` that names its data channel, when an
422/// upgrade carried one over (srv `update/download.rs`): a local build's
423/// `local-…` channel, kept by the release it upgraded to, so the upgrade
424/// continues with that build's windows, agents and settings.
425pub const RECORDED_CHANNEL_FILE: &str = "agentmux-channel";
426
427/// The channel named in the record file `path`, if it names one.
428pub(crate) fn read_channel_file(path: &Path) -> Option<String> {
429    std::fs::read_to_string(path).ok().map(|s| s.trim().to_string()).filter(|s| !s.is_empty())
430}
431
432/// The data channel the portable folder at or above `exe_dir` records: next to
433/// the host and srv (Windows: both in `runtime/`), in `runtime/` below the
434/// launcher, or at the top of a Linux portable (`AgentMux/`, two levels above
435/// the binaries' `usr/bin/`).
436pub fn recorded_channel_in(exe_dir: &Path) -> Option<String> {
437    let mut candidates = vec![exe_dir.join(RECORDED_CHANNEL_FILE), exe_dir.join("runtime").join(RECORDED_CHANNEL_FILE)];
438    if exe_dir.ends_with("usr/bin") {
439        candidates.extend(exe_dir.parent().and_then(Path::parent).map(|top| top.join(RECORDED_CHANNEL_FILE)));
440    }
441    candidates.iter().find_map(|p| read_channel_file(p))
442}
443
444/// Where an upgrade records the data channel of an AppImage: beside it, as
445/// `<file>.agentmux-channel`, since the AppImage itself can't be written.
446pub fn appimage_channel_file(appimage: &Path) -> PathBuf {
447    let name = appimage.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
448    appimage.with_file_name(format!("{name}.{RECORDED_CHANNEL_FILE}"))
449}
450
451/// The `.app` bundle the binary at `path` (or its `Contents/MacOS` folder)
452/// belongs to, by the bundle layout rather than by name: the innermost
453/// `*.app` whose `Contents/MacOS` holds `path`, and, for a helper app nested in
454/// another app's `Contents/Helpers` or `Contents/Frameworks` (srv, the CEF
455/// helpers), the app above it. A folder that merely ends in `.app` around the
456/// install is never taken for it.
457pub fn app_bundle_of(path: &Path) -> Option<PathBuf> {
458    let is_app = |p: &Path| p.extension().is_some_and(|e| e.eq_ignore_ascii_case("app"));
459    let mut bundle = path.ancestors().find(|a| is_app(a) && path.starts_with(a.join("Contents").join("MacOS")))?;
460    let nested_in = bundle.parent().filter(|p| p.file_name().is_some_and(|n| n == "Helpers" || n == "Frameworks"));
461    if let Some(outer) = nested_in
462        .and_then(Path::parent)
463        .filter(|c| c.file_name().is_some_and(|n| n == "Contents"))
464        .and_then(Path::parent)
465        .filter(|o| is_app(o))
466    {
467        bundle = outer;
468    }
469    Some(bundle.to_path_buf())
470}
471
472/// Why an account other than this user, root or the `admin` group (whose
473/// members can become root anyway) could change the entries of the folder
474/// that holds an app, or `None` when none can. An in-place upgrade creates,
475/// checks and renames entries there, so anyone else who can rename them
476/// could swap a checked bundle for another. macOS also checks every folder
477/// above it, since renaming one of those moves the whole path.
478pub fn folder_others_can_change(dir: &Path) -> Option<String> {
479    #[cfg(target_os = "macos")]
480    {
481        dir.ancestors().find_map(one_folder_others_can_change)
482    }
483    #[cfg(not(target_os = "macos"))]
484    {
485        one_folder_others_can_change(dir)
486    }
487}
488
489#[cfg(unix)]
490fn one_folder_others_can_change(dir: &Path) -> Option<String> {
491    use std::os::unix::fs::MetadataExt;
492    let Ok(meta) = std::fs::metadata(dir) else {
493        return Some(format!("{} can't be read", dir.display()));
494    };
495    // SAFETY: geteuid has no preconditions.
496    let me = unsafe { libc::geteuid() };
497    let mode = meta.mode();
498    if meta.uid() != me && meta.uid() != 0 {
499        return Some(format!("{} belongs to another account", dir.display()));
500    }
501    if mode & 0o002 != 0 {
502        return Some(format!("every account can change {}", dir.display()));
503    }
504    if mode & 0o020 != 0 && Some(meta.gid()) != admin_gid() {
505        return Some(format!("the accounts in its group can change {}", dir.display()));
506    }
507    acl_allows_changes(dir).then(|| format!("an access list lets other accounts change {}", dir.display()))
508}
509
510#[cfg(not(unix))]
511fn one_folder_others_can_change(_dir: &Path) -> Option<String> {
512    None
513}
514
515/// The `admin` group's id, if there is one.
516#[cfg(unix)]
517fn admin_gid() -> Option<u32> {
518    // SAFETY: a NUL-terminated name; the entry is read before any other call.
519    let group = unsafe { libc::getgrnam(c"admin".as_ptr()) };
520    (!group.is_null()).then(|| unsafe { (*group).gr_gid })
521}
522
523/// Whether `dir` has an extended ACL with an `allow` entry that lets someone
524/// add, remove or rename its entries (macOS: `chmod +a`).
525#[cfg(target_os = "macos")]
526fn acl_allows_changes(dir: &Path) -> bool {
527    use std::os::raw::{c_char, c_int, c_void};
528    use std::os::unix::ffi::OsStrExt;
529    extern "C" {
530        fn acl_get_file(path: *const c_char, ty: c_int) -> *mut c_void;
531        fn acl_to_text(acl: *mut c_void, len: *mut isize) -> *mut c_char;
532        fn acl_free(obj: *mut c_void) -> c_int;
533    }
534    const ACL_TYPE_EXTENDED: c_int = 0x0000_0100;
535    let Ok(path) = std::ffi::CString::new(dir.as_os_str().as_bytes()) else { return true };
536    // SAFETY: a NUL-terminated path; every object acl_* returns is freed once.
537    unsafe {
538        let acl = acl_get_file(path.as_ptr(), ACL_TYPE_EXTENDED);
539        if acl.is_null() {
540            return false; // no ACL
541        }
542        let text = acl_to_text(acl, std::ptr::null_mut());
543        let changes = !text.is_null() && acl_text_allows_changes(&std::ffi::CStr::from_ptr(text).to_string_lossy());
544        if !text.is_null() {
545            acl_free(text.cast());
546        }
547        acl_free(acl);
548        changes
549    }
550}
551
552#[cfg(all(unix, not(target_os = "macos")))]
553fn acl_allows_changes(_dir: &Path) -> bool {
554    false
555}
556
557/// [`acl_allows_changes`] on `acl_to_text`'s text: one entry a line,
558/// `<who>:…:allow|deny:<perm>,<perm>`.
559#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
560fn acl_text_allows_changes(text: &str) -> bool {
561    const CHANGES: &[&str] = &["add_file", "add_subdirectory", "delete_child", "write", "delete", "writesecurity", "chown"];
562    text.lines().any(|line| {
563        let mut parts = line.split(':');
564        parts.any(|p| p == "allow") && line.rsplit(':').next().is_some_and(|perms| perms.split(',').any(|p| CHANGES.contains(&p.trim())))
565    })
566}
567
568/// Where a macOS upgrade records the data channel of an `.app`: beside it,
569/// hidden, as `.<name>.app.agentmux-channel`, since writing inside the bundle
570/// would break its code signature.
571pub fn mac_app_channel_file(app: &Path) -> PathBuf {
572    let name = app.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
573    app.with_file_name(format!(".{name}.{RECORDED_CHANNEL_FILE}"))
574}
575
576/// The AppImage the binary at `exe` runs from: `$APPIMAGE`, when `exe` is
577/// inside that AppImage's mount (`$APPDIR`) or the folder AppRun extracted it
578/// to (`$AGENTMUX_EXTRACTED_RUN`). `APPIMAGE` alone isn't enough: any other
579/// build started from an AppImage instance's pane inherits it.
580pub fn running_appimage(exe: &Path) -> Option<PathBuf> {
581    let appimage = std::env::var_os("APPIMAGE").filter(|v| !v.is_empty())?;
582    let roots: Vec<_> = ["APPDIR", "AGENTMUX_EXTRACTED_RUN"].iter().filter_map(std::env::var_os).collect();
583    inside_appimage(exe, &roots).then(|| PathBuf::from(appimage))
584}
585
586/// Whether `exe` is under one of the AppImage `roots` (`$APPDIR`, the extraction).
587pub fn inside_appimage(exe: &Path, roots: &[std::ffi::OsString]) -> bool {
588    roots.iter().any(|root| !root.is_empty() && exe.starts_with(root))
589}
590
591/// The data channel the running binary's install records: beside the AppImage
592/// it runs from, beside its `.app` on macOS, else in its portable folder
593/// ([`recorded_channel_in`]).
594pub fn recorded_channel() -> Option<String> {
595    let exe = std::env::current_exe().ok()?;
596    if let Some(appimage) = running_appimage(&exe) {
597        // Beside the file; else the channel kept for this same file by a start from where it was, when a
598        // move or a rename left that record behind (`appimage_record`).
599        return read_channel_file(&appimage_channel_file(&appimage)).or_else(|| crate::appimage_record::moved_channel(&appimage));
600    }
601    // macOS: beside the `.app` an upgrade replaced.
602    if cfg!(target_os = "macos") {
603        if let Some(channel) = app_bundle_of(&exe).and_then(|app| read_channel_file(&mac_app_channel_file(&app))) {
604            return Some(channel);
605        }
606    }
607    recorded_channel_in(exe.parent()?)
608}
609
610/// True when `exe_dir` is one of our known dev-build output dirs.
611/// Walks parents to handle nested cases (CEF subprocesses run from
612/// `runtime/` even in dev).
613fn exe_dir_is_dev_build(exe_dir: &Path) -> bool {
614    // Match any ancestor of exe_dir that ends in a known build dir name.
615    // We accept: dist/cef-dev/<...>, target/debug/<...>, target/release/<...>
616    let mut cur = Some(exe_dir);
617    while let Some(p) = cur {
618        let name = p.file_name().and_then(|n| n.to_str()).unwrap_or("");
619        let parent_name = p
620            .parent()
621            .and_then(|pp| pp.file_name())
622            .and_then(|n| n.to_str())
623            .unwrap_or("");
624
625        if (parent_name == "dist" && name.starts_with("cef-dev"))
626            || (parent_name == "target" && (name == "debug" || name == "release"))
627        {
628            return true;
629        }
630        cur = p.parent();
631    }
632    false
633}
634
635/// Detect the current git branch slug for dev mode. Walks up from
636/// `exe_dir` to find a git repo, runs `git rev-parse --abbrev-ref
637/// HEAD`, and slugifies. Falls back to `"default"` if anything fails.
638/// `AGENTMUX_DEV_BRANCH` env override always wins.
639fn detect_branch(exe_dir: &Path) -> String {
640    if let Ok(b) = std::env::var("AGENTMUX_DEV_BRANCH") {
641        let slug = sanitize_branch_slug(&b);
642        if !slug.is_empty() {
643            return slug;
644        }
645    }
646    // Find a git repo by walking up from exe_dir.
647    let mut cur = Some(exe_dir);
648    while let Some(p) = cur {
649        if p.join(".git").exists() {
650            return run_git_branch(p).unwrap_or_else(|| "default".to_string());
651        }
652        cur = p.parent();
653    }
654    "default".to_string()
655}
656
657fn run_git_branch(repo_dir: &Path) -> Option<String> {
658    GIT_BRANCH_LOOKUPS.with(|n| n.set(n.get() + 1));
659    let mut cmd = Command::new("git");
660    cmd.args(["rev-parse", "--abbrev-ref", "HEAD"])
661        .current_dir(repo_dir)
662        // A read of what is on the disk: fetch nothing, allow no transport.
663        .env("GIT_NO_LAZY_FETCH", "1")
664        .env("GIT_ALLOW_PROTOCOL", "");
665    #[cfg(windows)]
666    {
667        // CREATE_NO_WINDOW: console-flash suppression.
668        cmd.no_window();
669    }
670    let output = cmd.output().ok()?;
671    if !output.status.success() {
672        return None;
673    }
674    let s = String::from_utf8(output.stdout).ok()?;
675    let trimmed = s.trim();
676    if trimmed.is_empty() || trimmed == "HEAD" {
677        // Detached state; not useful for branch keying.
678        return None;
679    }
680    Some(slugify_branch(trimmed))
681}
682
683/// Convert a git branch into a filesystem-safe slug.
684/// `agenta/feature-x` → `agenta-feature-x`.
685///
686/// Use [`sanitize_branch_slug`] for any value that originates from an
687/// env var or other untrusted source — it additionally strips `..` and
688/// leading dots that could escape the dev/ subtree.
689fn slugify_branch(b: &str) -> String {
690    b.replace(['/', '\\', ':', '*', '?', '"', '<', '>', '|'], "-")
691}
692
693/// Stricter sanitization for branch values that came from outside the
694/// trusted slugify path (env overrides, CI inputs). Strips parent-dir
695/// segments, leading dots, and any whitespace that survived earlier
696/// trimming. Returns an empty string if nothing usable remains, which
697/// callers should treat as "reject this input."
698fn sanitize_branch_slug(b: &str) -> String {
699    // Step 1: replace shell + filesystem-meta characters (same as
700    // slugify_branch — git-valid chars get a "-").
701    let replaced = slugify_branch(b);
702    // Step 2: drop `..` segments (now dash-separated, so "-..-"-style
703    // sequences too) and any leading/trailing dots/dashes/whitespace
704    // that would resolve up out of the dev/ subdir.
705    let cleaned: String = replaced
706        .split('-')
707        .filter(|seg| !seg.is_empty() && *seg != "." && *seg != "..")
708        .collect::<Vec<_>>()
709        .join("-");
710    cleaned
711        .trim_matches(|c: char| c == '.' || c == '-' || c.is_whitespace())
712        .to_string()
713}
714
715#[cfg(test)]
716mod tests {
717    use super::*;
718    use crate::TEST_ENV_LOCK;
719    use std::path::PathBuf;
720    // tempfile is a dev-dep used here for the marker-detection test.
721
722    /// `with_env` does NOT take `TEST_ENV_LOCK` — callers must hold
723    /// it. This avoids the re-entrant-locking problem when a test
724    /// nests `with_env` calls. The lock is shared across the whole
725    /// crate (defined in lib.rs) so tests in this module also
726    /// serialize against `data_paths::tests` which touches the same
727    /// process-global env vars.
728    ///
729    /// Uses a Drop guard so the previous env value is restored even
730    /// if `f` panics — without it, a panicking test would leave the
731    /// env var modified and any subsequent test in the same process
732    /// would see the wrong value.
733    fn with_env<F: FnOnce()>(key: &str, val: Option<&str>, f: F) {
734        struct EnvGuard {
735            key: String,
736            prev: Option<String>,
737        }
738        impl Drop for EnvGuard {
739            fn drop(&mut self) {
740                match &self.prev {
741                    Some(v) => std::env::set_var(&self.key, v),
742                    None => std::env::remove_var(&self.key),
743                }
744            }
745        }
746
747        let prev = std::env::var(key).ok();
748        let _guard = EnvGuard {
749            key: key.to_string(),
750            prev,
751        };
752        match val {
753            Some(v) => std::env::set_var(key, v),
754            None => std::env::remove_var(key),
755        }
756        f();
757        // _guard drops here (also runs on panic).
758    }
759
760    #[test]
761    fn parses_env_strings_round_trip() {
762        for mode in [
763            RuntimeMode::Installed,
764            RuntimeMode::Portable,
765            RuntimeMode::Dev {
766                branch: "main".into(),
767                clone_id: None,
768            },
769            RuntimeMode::Dev {
770                branch: "agenta-feature-x".into(),
771                clone_id: None,
772            },
773        ] {
774            let s = mode.to_env_string();
775            let back = parse_mode_string(&s).expect("round-trip");
776            assert_eq!(back, mode);
777        }
778    }
779
780    #[test]
781    fn parse_accepts_bare_dev() {
782        assert_eq!(
783            parse_mode_string("dev"),
784            Some(RuntimeMode::Dev {
785                branch: "default".into(),
786                clone_id: None,
787            })
788        );
789        assert_eq!(
790            parse_mode_string("DEV"),
791            Some(RuntimeMode::Dev {
792                branch: "default".into(),
793                clone_id: None,
794            })
795        );
796    }
797
798    #[test]
799    fn env_override_wins_over_path_detection() {
800        let _g = TEST_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
801        // Even if exe_dir looks portable (has `runtime/`), env override wins.
802        // We simulate by passing a path that doesn't exist (so .is_dir()
803        // returns false), but we also force the env override.
804        with_env("AGENTMUX_RUNTIME_MODE", Some("dev:main"), || {
805            with_env("AGENTMUX_DEV_BRANCH", None, || {
806                let mode = RuntimeMode::current(&PathBuf::from("/nonexistent"));
807                assert_eq!(
808                    mode,
809                    RuntimeMode::Dev {
810                        branch: "main".into(),
811                        clone_id: None,
812                    }
813                );
814            });
815        });
816    }
817
818    #[test]
819    fn dev_build_path_pattern() {
820        // Match dist/cef-dev/... (fixed name)
821        assert!(exe_dir_is_dev_build(&PathBuf::from(
822            "/c/Systems/agentmux/dist/cef-dev"
823        )));
824        // Match dist/cef-dev-<epoch>/... (timestamp-stamped, Windows re-launch fix)
825        assert!(exe_dir_is_dev_build(&PathBuf::from(
826            "/c/Systems/agentmux/dist/cef-dev-1719100000"
827        )));
828        assert!(exe_dir_is_dev_build(&PathBuf::from(
829            "/c/Systems/agentmux/dist/cef-dev-1719100000/runtime"
830        )));
831        // Match target/debug/...
832        assert!(exe_dir_is_dev_build(&PathBuf::from(
833            "/c/Systems/agentmux/target/debug"
834        )));
835        // Match target/release/...
836        assert!(exe_dir_is_dev_build(&PathBuf::from(
837            "/c/Systems/agentmux/target/release"
838        )));
839        // Don't match an installed path.
840        assert!(!exe_dir_is_dev_build(&PathBuf::from(
841            "/c/Program Files/AgentMux"
842        )));
843        // Don't match a portable path.
844        assert!(!exe_dir_is_dev_build(&PathBuf::from(
845            "/Users/me/Desktop/agentmux-portable"
846        )));
847    }
848
849    #[test]
850    fn slugify_branch_replaces_unsafe_chars() {
851        assert_eq!(slugify_branch("agenta/feature-x"), "agenta-feature-x");
852        assert_eq!(slugify_branch("feat:foo*bar"), "feat-foo-bar");
853        assert_eq!(slugify_branch("plain"), "plain");
854    }
855
856    #[test]
857    fn dir_slug_per_mode() {
858        assert_eq!(RuntimeMode::Installed.dir_slug(), "versions");
859        assert_eq!(RuntimeMode::Portable.dir_slug(), "versions");
860        assert_eq!(
861            RuntimeMode::Dev {
862                branch: "main".into(),
863                clone_id: None,
864            }
865            .dir_slug(),
866            "dev/main"
867        );
868        assert_eq!(
869            RuntimeMode::Dev {
870                branch: "agenta/x".into(),
871                clone_id: None,
872            }
873            .dir_slug(),
874            "dev/agenta-x"
875        );
876        // With a clone_id, the slug nests one level deeper so two
877        // clones on the same branch land in distinct subdirs.
878        assert_eq!(
879            RuntimeMode::Dev {
880                branch: "main".into(),
881                clone_id: Some("abcdef1234567890".into()),
882            }
883            .dir_slug(),
884            "dev/main/abcdef1234567890"
885        );
886    }
887
888    #[test]
889    fn invalid_env_string_falls_through() {
890        assert!(parse_mode_string("garbage").is_none());
891        assert!(parse_mode_string("").is_none());
892    }
893
894    #[test]
895    fn parse_dev_branch_rejects_traversal_attempts() {
896        // `..` resolves out of the dev/ subdir on disk — the slug must
897        // either reject it or strip it. We choose strip; if nothing
898        // usable remains, parse fails (returns None).
899        assert_eq!(parse_mode_string("dev:.."), None);
900        assert_eq!(parse_mode_string("dev:."), None);
901        assert_eq!(parse_mode_string("dev:"), None);
902        // `dev:../versions/x` slugifies to `versions-x` (the slashes
903        // are replaced and `..` segment is dropped).
904        let m = parse_mode_string("dev:../versions/x").expect("parses");
905        match m {
906            RuntimeMode::Dev { branch, .. } => {
907                assert!(!branch.contains(".."));
908                assert!(!branch.contains('/'));
909                assert!(!branch.contains('\\'));
910            }
911            _ => panic!("expected Dev variant"),
912        }
913    }
914
915    #[test]
916    fn dev_branch_env_with_unusable_value_falls_through() {
917        // AGENTMUX_DEV_BRANCH=`..` sanitizes to empty.
918        // With the fix, an unusable value falls through to Installed
919        // when no other dev signal applies — even when exe_dir has
920        // a .git ancestor that detect_branch could have grabbed.
921        let _g = TEST_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
922        let tmp = tempfile::TempDir::new().expect("tempdir");
923        // Plant a .git directory so a buggy implementation that called
924        // detect_branch as a fallback would find a real branch name and
925        // wrongly classify as Dev. Step 4 now sanitizes the env var
926        // directly without invoking the git lookup — verifying that.
927        std::fs::create_dir_all(tmp.path().join(".git")).unwrap();
928        let exe_dir = tmp.path().join("subdir");
929        std::fs::create_dir_all(&exe_dir).unwrap();
930
931        std::env::remove_var("AGENTMUX_RUNTIME_MODE");
932        std::env::set_var("AGENTMUX_DEV_BRANCH", "..");
933        let mode = RuntimeMode::current(&exe_dir);
934        std::env::remove_var("AGENTMUX_DEV_BRANCH");
935
936        // Even with the .git ancestor, an unusable env value must
937        // fall through to Installed (NOT to Dev with a git-detected
938        // branch). The env var is the source-of-truth at step 4.
939        assert_eq!(mode, RuntimeMode::Installed);
940    }
941
942    #[test]
943    fn a_portable_build_label_is_read_next_to_the_binary_or_one_level_up() {
944        let tmp = tempfile::TempDir::new().expect("tempdir");
945        let runtime = tmp.path().join("runtime");
946        std::fs::create_dir_all(&runtime).unwrap();
947        assert_eq!(portable_build_label(&runtime), None, "no marker: not a local portable");
948
949        std::fs::write(tmp.path().join("agentmux-portable.marker"), "AgentMux portable build 0.59.1+gabc.old\n").unwrap();
950        assert_eq!(portable_build_label(&runtime).as_deref(), Some("0.59.1+gabc.old"), "an older portable's root marker");
951
952        std::fs::write(runtime.join("agentmux-portable.marker"), "AgentMux portable build 0.59.16+g2a5424fe2.20261008T234046.81801\r\n").unwrap();
953        assert_eq!(portable_build_label(&runtime).as_deref(), Some("0.59.16+g2a5424fe2.20261008T234046.81801"), "next to the binary wins");
954
955        std::fs::write(runtime.join("agentmux-portable.marker"), "something else\n").unwrap();
956        assert_eq!(portable_build_label(&runtime).as_deref(), Some("0.59.1+gabc.old"), "an unreadable marker is skipped");
957    }
958
959    #[test]
960    fn portable_marker_detection() {
961        let _g = TEST_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
962        let tmp = tempfile::TempDir::new().expect("tempdir");
963        let exe_dir = tmp.path();
964
965        // No marker → not portable.
966        assert!(!is_portable_marker_present(exe_dir));
967
968        // With marker next to the exe → portable (host/srv in runtime/, or a
969        // legacy portable with the marker at the root).
970        std::fs::write(exe_dir.join("agentmux-portable.marker"), b"").unwrap();
971        assert!(is_portable_marker_present(exe_dir));
972        std::fs::remove_file(exe_dir.join("agentmux-portable.marker")).unwrap();
973
974        // Marker inside runtime/ → portable (the launcher sits at the root and
975        // the marker lives one level down in runtime/). An empty runtime/ with
976        // no marker must NOT count (covered by
977        // current_with_only_runtime_subdir_is_not_portable).
978        std::fs::create_dir_all(exe_dir.join("runtime")).unwrap();
979        assert!(!is_portable_marker_present(exe_dir));
980        std::fs::write(exe_dir.join("runtime").join("agentmux-portable.marker"), b"").unwrap();
981        assert!(is_portable_marker_present(exe_dir));
982        std::fs::remove_file(exe_dir.join("runtime").join("agentmux-portable.marker")).unwrap();
983
984        // Marker two levels up (macOS .app bundle case). All markers are
985        // already removed above, so the bundle exe dir starts clean.
986        let nested = exe_dir.join("Contents/MacOS");
987        std::fs::create_dir_all(&nested).unwrap();
988        assert!(!is_portable_marker_present(&nested));
989        std::fs::write(exe_dir.join("agentmux-portable.marker"), b"").unwrap();
990        assert!(is_portable_marker_present(&nested));
991    }
992
993    #[test]
994    fn current_with_only_runtime_subdir_is_not_portable() {
995        // Regression: prior implementation returned Portable whenever
996        // <exe>/runtime/ existed, but installed builds also co-locate
997        // runtime/ (per the launcher unconditionally requiring it).
998        // Without a marker, we must NOT classify as Portable.
999        let _g = TEST_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
1000        let tmp = tempfile::TempDir::new().expect("tempdir");
1001        let exe_dir = tmp.path();
1002        std::fs::create_dir_all(exe_dir.join("runtime")).unwrap();
1003        // No agentmux-portable.marker marker — must be Installed (or whatever
1004        // the fall-through is, but specifically NOT Portable).
1005        std::env::remove_var("AGENTMUX_RUNTIME_MODE");
1006        std::env::remove_var("AGENTMUX_DEV_BRANCH");
1007        let mode = RuntimeMode::current(exe_dir);
1008        assert_ne!(mode, RuntimeMode::Portable);
1009    }
1010
1011    #[test]
1012    fn sanitize_branch_slug_strips_traversal() {
1013        assert_eq!(sanitize_branch_slug(".."), "");
1014        assert_eq!(sanitize_branch_slug("../foo"), "foo");
1015        assert_eq!(sanitize_branch_slug("foo/../bar"), "foo-bar");
1016        assert_eq!(sanitize_branch_slug(".hidden"), "hidden");
1017        assert_eq!(sanitize_branch_slug("ok-branch"), "ok-branch");
1018    }
1019
1020    // ── derive_clone_id ─────────────────────────────────────────────
1021
1022    #[test]
1023    fn derive_clone_id_returns_16_hex_chars_when_marker_present() {
1024        let tmp = tempfile::TempDir::new().expect("tempdir");
1025        // Plant a Cargo.toml at the root to act as the clone-root marker.
1026        std::fs::write(tmp.path().join("Cargo.toml"), b"[workspace]").unwrap();
1027        let nested = tmp.path().join("target/release");
1028        std::fs::create_dir_all(&nested).unwrap();
1029        let id = derive_clone_id(&nested).expect("found");
1030        assert_eq!(id.len(), 16);
1031        assert!(id.chars().all(|c| c.is_ascii_hexdigit()));
1032    }
1033
1034    #[test]
1035    fn derive_clone_id_is_stable_for_same_clone() {
1036        let tmp = tempfile::TempDir::new().expect("tempdir");
1037        std::fs::write(tmp.path().join("Taskfile.yml"), b"version: 3").unwrap();
1038        let exe = tmp.path().join("dist/cef-dev");
1039        std::fs::create_dir_all(&exe).unwrap();
1040        let a = derive_clone_id(&exe).unwrap();
1041        let b = derive_clone_id(&exe).unwrap();
1042        assert_eq!(a, b);
1043    }
1044
1045    #[test]
1046    fn derive_clone_id_differs_between_clones() {
1047        let tmp1 = tempfile::TempDir::new().expect("tempdir1");
1048        let tmp2 = tempfile::TempDir::new().expect("tempdir2");
1049        for t in [&tmp1, &tmp2] {
1050            std::fs::write(t.path().join("Cargo.toml"), b"[workspace]").unwrap();
1051        }
1052        let id1 = derive_clone_id(tmp1.path()).unwrap();
1053        let id2 = derive_clone_id(tmp2.path()).unwrap();
1054        assert_ne!(
1055            id1, id2,
1056            "two clones at different paths must hash to different ids"
1057        );
1058    }
1059
1060    #[test]
1061    fn derive_clone_id_returns_none_without_marker() {
1062        let tmp = tempfile::TempDir::new().expect("tempdir");
1063        // No marker at all — caller has no clone root to anchor to.
1064        let id = derive_clone_id(tmp.path());
1065        assert!(id.is_none());
1066    }
1067
1068    #[test]
1069    fn derive_clone_id_walks_up_to_find_marker() {
1070        let tmp = tempfile::TempDir::new().expect("tempdir");
1071        std::fs::create_dir_all(tmp.path().join(".git")).unwrap();
1072        let deep = tmp.path().join("a/b/c/d");
1073        std::fs::create_dir_all(&deep).unwrap();
1074        // From a deeply nested subdir, we should still find the .git marker.
1075        assert!(derive_clone_id(&deep).is_some());
1076    }
1077
1078    #[test]
1079    fn sanitize_clone_id_rejects_traversal() {
1080        assert_eq!(sanitize_clone_id("../foo"), "");
1081        assert_eq!(sanitize_clone_id("a/b"), "");
1082        assert_eq!(sanitize_clone_id("a\\b"), "");
1083        assert_eq!(sanitize_clone_id("a..b"), "");
1084        assert_eq!(sanitize_clone_id(""), "");
1085        assert_eq!(sanitize_clone_id("abcdef1234567890"), "abcdef1234567890");
1086    }
1087
1088    #[test]
1089    fn from_env_with_clone_populates_clone_id_for_dev() {
1090        let _g = TEST_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
1091        with_env("AGENTMUX_RUNTIME_MODE", Some("dev:main"), || {
1092            with_env("AGENTMUX_CLONE_ID", Some("deadbeefcafebabe"), || {
1093                let m = RuntimeMode::from_env_with_clone().unwrap();
1094                assert_eq!(
1095                    m,
1096                    RuntimeMode::Dev {
1097                        branch: "main".into(),
1098                        clone_id: Some("deadbeefcafebabe".into()),
1099                    }
1100                );
1101            });
1102        });
1103    }
1104
1105    #[test]
1106    fn from_env_with_clone_leaves_clone_id_none_when_unset() {
1107        let _g = TEST_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
1108        with_env("AGENTMUX_RUNTIME_MODE", Some("dev:main"), || {
1109            with_env("AGENTMUX_CLONE_ID", None, || {
1110                let m = RuntimeMode::from_env_with_clone().unwrap();
1111                assert_eq!(
1112                    m,
1113                    RuntimeMode::Dev {
1114                        branch: "main".into(),
1115                        clone_id: None,
1116                    }
1117                );
1118            });
1119        });
1120    }
1121
1122    /// The host asks this on its UI thread at every page load (task #47585): it
1123    /// must come from the path alone, where building the mode starts `git`.
1124    #[test]
1125    fn asking_whether_a_build_is_dev_starts_no_process() {
1126        let _g = TEST_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
1127        with_env("AGENTMUX_DEV_BRANCH", None, || {
1128            let repo = tempfile::tempdir().unwrap();
1129            std::fs::create_dir_all(repo.path().join(".git")).unwrap();
1130            let dev = repo.path().join("dist").join("cef-dev-1").join("runtime");
1131            std::fs::create_dir_all(&dev).unwrap();
1132            let installed = repo.path().join("Programs").join("AgentMux").join("runtime");
1133            std::fs::create_dir_all(&installed).unwrap();
1134            let portable = repo.path().join("target").join("release");
1135            std::fs::create_dir_all(&portable).unwrap();
1136            std::fs::write(portable.join("agentmux-portable.marker"), "").unwrap();
1137
1138            let before = git_branch_lookups();
1139            assert!(exe_dir_is_dev(&dev));
1140            assert!(!exe_dir_is_dev(&installed));
1141            assert!(!exe_dir_is_dev(&portable), "a portable folder is not a dev build, wherever it sits");
1142            let _ = is_dev_self();
1143            let _ = is_dev_self();
1144            assert_eq!(git_branch_lookups(), before, "the yes or no must not start git");
1145
1146            // The same answers as the mode itself, which does look the branch up.
1147            assert!(matches!(RuntimeMode::current_path_only(&dev), RuntimeMode::Dev { .. }));
1148            assert_eq!(git_branch_lookups(), before + 1, "building the mode is what starts git");
1149            assert!(matches!(RuntimeMode::current_path_only(&installed), RuntimeMode::Installed));
1150            assert!(matches!(RuntimeMode::current_path_only(&portable), RuntimeMode::Portable));
1151        });
1152    }
1153
1154    /// Regression for "DEV badge on every build": a packaged build launched as
1155    /// a descendant of a `task dev` AgentMux inherits
1156    /// `AGENTMUX_RUNTIME_MODE=dev:main`. Build identity (badge, menu name,
1157    /// dev-frontend fallback) goes through `current_path_only` / `is_dev_self`,
1158    /// which must ignore that env and classify purely by the binary's path.
1159    #[test]
1160    fn current_path_only_ignores_leaked_dev_env() {
1161        let _g = TEST_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
1162        with_env("AGENTMUX_RUNTIME_MODE", Some("dev:main"), || {
1163            // A non-dev exe dir: no portable marker, not a dev-build path.
1164            let installed = std::path::Path::new("/Applications/AgentMux.app/Contents/MacOS");
1165            assert!(
1166                matches!(
1167                    RuntimeMode::current_path_only(installed),
1168                    RuntimeMode::Installed
1169                ),
1170                "current_path_only must ignore a leaked AGENTMUX_RUNTIME_MODE=dev:main"
1171            );
1172            // Contrast: current() DOES still honor an explicit env override.
1173            assert!(
1174                matches!(RuntimeMode::current(installed), RuntimeMode::Dev { .. }),
1175                "current() still honors an explicit AGENTMUX_RUNTIME_MODE override"
1176            );
1177        });
1178    }
1179
1180    #[test]
1181    fn a_portable_folder_records_its_channel_for_every_binary_in_it() {
1182        let dir = tempfile::tempdir().unwrap();
1183        let runtime = dir.path().join("runtime");
1184        std::fs::create_dir_all(&runtime).unwrap();
1185        assert_eq!(recorded_channel_in(dir.path()), None);
1186        std::fs::write(runtime.join(RECORDED_CHANNEL_FILE), "local-main-b28b7a-f62415cd\n").unwrap();
1187        // The launcher, at the root, and the host and srv, in `runtime/`.
1188        assert_eq!(recorded_channel_in(dir.path()).as_deref(), Some("local-main-b28b7a-f62415cd"));
1189        assert_eq!(recorded_channel_in(&runtime).as_deref(), Some("local-main-b28b7a-f62415cd"));
1190        std::fs::write(runtime.join(RECORDED_CHANNEL_FILE), "  \n").unwrap();
1191        assert_eq!(recorded_channel_in(&runtime), None);
1192    }
1193
1194    #[test]
1195    fn a_linux_portable_records_its_channel_at_its_top() {
1196        let dir = tempfile::tempdir().unwrap();
1197        let bin = dir.path().join("AgentMux/usr/bin");
1198        std::fs::create_dir_all(&bin).unwrap();
1199        std::fs::write(dir.path().join("AgentMux").join(RECORDED_CHANNEL_FILE), "local-main-1\n").unwrap();
1200        assert_eq!(recorded_channel_in(&bin).as_deref(), Some("local-main-1"));
1201        // Only from `usr/bin`: two levels above another folder isn't its install.
1202        let other = dir.path().join("AgentMux/usr/lib");
1203        std::fs::create_dir_all(&other).unwrap();
1204        assert_eq!(recorded_channel_in(&other), None);
1205    }
1206
1207    #[test]
1208    fn an_appimage_records_its_channel_beside_it_and_only_its_own_binaries_read_it() {
1209        let file = Path::new("/home/u/Apps/AgentMux_0.59.30_amd64.AppImage");
1210        assert_eq!(appimage_channel_file(file), Path::new("/home/u/Apps/AgentMux_0.59.30_amd64.AppImage.agentmux-channel"));
1211        let extracted = std::ffi::OsString::from("/home/u/.local/share/agentmux/extracted/0.59.30");
1212        let inside = Path::new("/home/u/.local/share/agentmux/extracted/0.59.30/usr/bin/agentmux-launcher");
1213        let elsewhere = Path::new("/home/u/AgentMux/usr/bin/agentmux-launcher");
1214        assert!(inside_appimage(inside, &[extracted.clone()]));
1215        assert!(!inside_appimage(elsewhere, &[extracted]), "another build that only inherited APPIMAGE");
1216        assert!(!inside_appimage(inside, &[std::ffi::OsString::new()]));
1217    }
1218
1219    #[test]
1220    fn a_macos_app_records_its_channel_beside_it() {
1221        let app = Path::new("/Applications/AgentMux.app");
1222        assert_eq!(mac_app_channel_file(app), Path::new("/Applications/.AgentMux.app.agentmux-channel"));
1223        let srv = Path::new("/Applications/AgentMux.app/Contents/Helpers/AgentMux Server.app/Contents/MacOS/srv");
1224        assert_eq!(app_bundle_of(srv).as_deref(), Some(app));
1225        assert_eq!(app_bundle_of(Path::new("/Applications/AgentMux.app/Contents/MacOS")).as_deref(), Some(app));
1226        let gpu = Path::new("/Applications/AgentMux.app/Contents/Frameworks/AgentMux Helper (GPU).app/Contents/MacOS/AgentMux Helper (GPU)");
1227        assert_eq!(app_bundle_of(gpu).as_deref(), Some(app));
1228        // A folder that only ends in .app around the install is not the app.
1229        let archived = Path::new("/Users/u/Archive.app/AgentMux.app/Contents/MacOS/agentmux-launcher");
1230        assert_eq!(app_bundle_of(archived).as_deref(), Some(Path::new("/Users/u/Archive.app/AgentMux.app")));
1231        let in_resources = Path::new("/Users/u/Foo.app/Resources/AgentMux.app/Contents/Helpers/AgentMux Server.app/Contents/MacOS/srv");
1232        assert_eq!(app_bundle_of(in_resources).as_deref(), Some(Path::new("/Users/u/Foo.app/Resources/AgentMux.app")));
1233        assert_eq!(app_bundle_of(Path::new("/usr/bin/agentmux-srv")), None);
1234        assert_eq!(app_bundle_of(Path::new("/Users/u/Foo.app/srv")), None, "not in a bundle's Contents/MacOS");
1235    }
1236
1237    #[test]
1238    fn an_access_list_that_lets_others_change_a_folder_is_seen() {
1239        assert!(acl_text_allows_changes("!#acl 1\ngroup:ABC:staff:20:allow:add_file,search\n"));
1240        assert!(acl_text_allows_changes("user:XYZ:bob:501:allow:list,delete_child\n"));
1241        // The usual /Applications-style entry only denies.
1242        assert!(!acl_text_allows_changes("!#acl 1\ngroup:ABCDEFAB-CDEF-ABCD-EFAB-CDEF0000000C:everyone:12:deny:delete\n"));
1243        assert!(!acl_text_allows_changes("group:ABC:staff:20:allow:list,search,readattr\n"));
1244    }
1245
1246    #[cfg(unix)]
1247    #[test]
1248    fn a_folder_only_this_user_can_change_passes_and_a_shared_one_does_not() {
1249        use std::os::unix::fs::PermissionsExt;
1250        let dir = tempfile::tempdir().unwrap();
1251        let folder = dir.path().join("Apps");
1252        std::fs::create_dir(&folder).unwrap();
1253        std::fs::set_permissions(&folder, std::fs::Permissions::from_mode(0o755)).unwrap();
1254        assert_eq!(one_folder_others_can_change(&folder), None);
1255        std::fs::set_permissions(&folder, std::fs::Permissions::from_mode(0o1777)).unwrap();
1256        assert!(one_folder_others_can_change(&folder).unwrap().contains("every account"));
1257        // Group-writable passes only when the folder's group is admin.
1258        std::fs::set_permissions(&folder, std::fs::Permissions::from_mode(0o775)).unwrap();
1259        let group_ok = {
1260            use std::os::unix::fs::MetadataExt;
1261            Some(std::fs::metadata(&folder).unwrap().gid()) == admin_gid()
1262        };
1263        assert_eq!(one_folder_others_can_change(&folder).is_none(), group_ok);
1264    }
1265}