Skip to main content

agentmux_cef/
lib.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4// AgentMux Host — Library entry point.
5//
6// This cdylib is the Windows DLL wrapper sandbox target (Phase 3, issue #1374).
7// `bootstrap.exe` (renamed `agentmux-cef.exe`) loads this DLL and calls
8// `RunWinMain` with a pre-initialized `cef_sandbox_info_t *` pointer, which we
9// forward into `run()`.
10//
11// On non-Windows or sandbox-off builds, only the `[[bin]]` target is used;
12// this file must still compile on those platforms.
13
14mod app;
15mod dev_home_check;
16#[cfg(test)]
17mod tls_test_init;
18mod background_audit;
19mod start_hidden;
20mod browser_api;
21mod browser_panes;
22mod cdp_port;
23mod client;
24mod commands;
25mod dev_authfile;
26mod dev_mode;
27mod ipc_forward;
28mod drag_stash;
29mod events;
30mod health_signals;
31mod ipc;
32mod ipc_query;
33mod launcher_event_bridge;
34mod launcher_ipc;
35// Not #[cfg]-gated at the mod-declaration level like macos_compat/macos_menu
36// below — this module deliberately mixes OS-agnostic pure logic (unit tested on
37// any host) with target_os = "linux"-gated OS interaction (gated within the file). See its own doc comment.
38mod linux_sandbox;
39mod logging;
40mod parent_process;
41mod srv_event_bridge;
42mod srv_ipc;
43mod memory_heartbeat;
44mod memory_pressure;
45mod browser_pane;
46mod pane_backend;
47mod credential_broker;
48mod ssh_approval;
49#[cfg(target_os = "windows")]
50mod floating_pane;
51mod input_owner;
52mod reducer;
53mod renderer_map;
54mod saga_dispatch;
55mod side_buttons;
56mod sidecar;
57mod state;
58mod ui_tasks;
59mod wrr;
60#[cfg(target_os = "macos")]
61mod macos_compat;
62#[cfg(target_os = "macos")]
63mod macos_menu;
64
65use std::sync::Arc;
66
67use cef::*;
68
69/// Suppress the Windows "Application Error" / WER crash dialog so an unhandled
70/// fault (a Chromium `LOG(FATAL)`, an `abort()`, a breakpoint) terminates the
71/// process immediately instead of wedging it behind a modal the user must
72/// dismiss. While that dialog is up the process is frozen and cannot be
73/// auto-recovered. No-op off Windows. Spec:
74/// docs/specs/SPEC_SERVICE_SUPERVISION_AND_RECOVERY_2026_05_20.md.
75#[cfg(target_os = "windows")]
76fn suppress_os_crash_dialogs() {
77    use windows_sys::Win32::System::Diagnostics::Debug::{SetErrorMode, SEM_FAILCRITICALERRORS};
78    use windows_sys::Win32::System::ErrorReporting::{WerSetFlags, WER_FAULT_REPORTING_NO_UI};
79    // Process-wide; also covers the CEF subprocesses.
80    unsafe {
81        // Suppress the WER crash-dialog UI WITHOUT disabling WER itself —
82        // SEM_NOGPFAULTERRORBOX would also kill WER/LocalDumps crash-dump
83        // collection, the postmortem diagnostics this stability work needs.
84        // WER_FAULT_REPORTING_NO_UI is the documented "no UI, keep
85        // reports" path.
86        let _ = WerSetFlags(WER_FAULT_REPORTING_NO_UI);
87        // SEM_FAILCRITICALERRORS suppresses the critical-error handler
88        // (e.g. "no disk in drive" popups) — unrelated to crash reporting.
89        SetErrorMode(SEM_FAILCRITICALERRORS);
90    }
91}
92
93#[cfg(not(target_os = "windows"))]
94fn suppress_os_crash_dialogs() {}
95
96/// Resolve CEF's `browser_subprocess_path` (the executable CEF spawns for
97/// renderer / GPU / utility processes).
98///
99/// On a packaged macOS `.app`, return the dedicated `AgentMux Helper`
100/// executable inside `Contents/Frameworks/AgentMux Helper.app` — re-execing
101/// the main bundle binary for subprocesses is rejected by the macOS process
102/// model (every child would inherit the main bundle's identity), which makes
103/// the renderers crash-loop. When no Helper.app is present (dev: a bare binary
104/// with no bundle) fall back to the current exe — self-reexec works there.
105/// Windows/Linux always use the current exe (self-reexec is fine off-bundle).
106#[cfg(target_os = "macos")]
107fn resolve_browser_subprocess_path() -> String {
108    let exe = std::env::current_exe().unwrap();
109    // exe = AgentMux.app/Contents/MacOS/agentmux-cef
110    // → AgentMux.app/Contents/Frameworks/AgentMux Helper.app/Contents/MacOS/AgentMux Helper
111    if let Some(contents) = exe.parent().and_then(|macos| macos.parent()) {
112        let helper = contents
113            .join("Frameworks")
114            .join("AgentMux Helper.app")
115            .join("Contents")
116            .join("MacOS")
117            .join("AgentMux Helper");
118        if helper.exists() {
119            return helper.to_string_lossy().into_owned();
120        }
121    }
122    exe.to_string_lossy().into_owned()
123}
124
125#[cfg(not(target_os = "macos"))]
126fn resolve_browser_subprocess_path() -> String {
127    std::env::current_exe()
128        .ok()
129        .and_then(|p| p.to_str().map(|s| s.to_owned()))
130        .unwrap_or_default()
131}
132
133/// True when a launcher is THIS host's actual parent process this run.
134///
135/// The launcher (which spawns the host directly) stamps
136/// `AGENTMUX_LAUNCHER_PID` with its own pid; since we are its direct
137/// child, that pid equals our `getppid()`. This distinguishes a fresh,
138/// authoritative launcher hand-off from a STALE `AGENTMUX_BACKEND_WS`
139/// inherited down the environment from a parent agentmux pane (whose
140/// launcher pid will not match our real parent). Used only to relax the
141/// dev-build "ignore the env hand-off" rule for launcher-driven `task dev`
142/// (macOS/Linux Phase 1 launcher dev integration; Windows since #3868's
143/// follow-up — before that a Windows dev host always spawned a SECOND srv
144/// on the same data dir beside the launcher's).
145#[cfg(unix)]
146fn launcher_is_genuine_parent() -> bool {
147    // SAFETY: getppid() takes no arguments, touches no memory, and is
148    // documented as always succeeding.
149    let ppid = unsafe { libc::getppid() };
150    stamped_pid_is_parent(
151        std::env::var("AGENTMUX_LAUNCHER_PID").ok().as_deref(),
152        u32::try_from(ppid).ok(),
153    )
154}
155
156#[cfg(windows)]
157fn launcher_is_genuine_parent() -> bool {
158    stamped_pid_is_parent(
159        std::env::var("AGENTMUX_LAUNCHER_PID").ok().as_deref(),
160        parent_process::parent_pid(),
161    )
162}
163
164#[cfg(not(any(unix, windows)))]
165fn launcher_is_genuine_parent() -> bool {
166    false
167}
168
169/// `stamp` (the launcher's `AGENTMUX_LAUNCHER_PID`) names our actual
170/// parent. No stamp, an unparsable one, or an unknown parent → false.
171fn stamped_pid_is_parent(stamp: Option<&str>, parent_pid: Option<u32>) -> bool {
172    match (stamp.and_then(|s| s.trim().parse::<u32>().ok()), parent_pid) {
173        (Some(stamped), Some(parent)) => stamped == parent,
174        _ => false,
175    }
176}
177
178#[cfg(test)]
179mod launcher_parent_tests {
180    use super::stamped_pid_is_parent;
181
182    #[test]
183    fn matches_only_the_real_parent() {
184        assert!(stamped_pid_is_parent(Some("4242"), Some(4242)));
185        assert!(stamped_pid_is_parent(Some(" 4242\n"), Some(4242)));
186        // A stamp inherited from a parent agentmux pane names some other process.
187        assert!(!stamped_pid_is_parent(Some("4242"), Some(777)));
188    }
189
190    #[test]
191    fn missing_or_bad_input_is_not_a_launcher_parent() {
192        assert!(!stamped_pid_is_parent(None, Some(4242)));
193        assert!(!stamped_pid_is_parent(Some(""), Some(4242)));
194        assert!(!stamped_pid_is_parent(Some("-1"), Some(4242)));
195        assert!(!stamped_pid_is_parent(Some("abc"), Some(4242)));
196        assert!(!stamped_pid_is_parent(Some("4242"), None));
197    }
198}
199
200/// Write this host's discovery file for test harnesses (see `dev_authfile`): the full `authkey.dev` for a dev build,
201/// `instance.json` without a key or token for any other.
202fn publish_discovery_file(app_state: &state::AppState, ipc_port: u16, is_dev: bool, debug_port: u16) {
203    let endpoints = app_state.backend_endpoints.lock().clone();
204    let auth_key = app_state.auth_key.lock().clone();
205    let data_dir_path = std::path::PathBuf::from(app_state.version_data_dir.lock().clone().unwrap_or_default());
206    let ipc_endpoint = format!("127.0.0.1:{}", ipc_port);
207    let instance = format!("v{}", env!("CARGO_PKG_VERSION"));
208    match dev_authfile::publish_discovery(
209        is_dev,
210        &data_dir_path,
211        &auth_key,
212        &endpoints.web_endpoint,
213        &endpoints.ws_endpoint,
214        &ipc_endpoint,
215        &app_state.ipc_token,
216        &instance,
217        std::process::id(),
218        debug_port,
219    ) {
220        Ok(p) => {
221            if p.removed_leftover {
222                tracing::info!("Removed a leftover authkey.dev from the data folder");
223            }
224            tracing::info!("Wrote discovery file: {}", p.path.display());
225        }
226        Err(e) => tracing::warn!("Failed to write discovery file: {}", e),
227    }
228}
229
230/// Run the AgentMux host.
231///
232/// `windows_sandbox_info` is the `cef_sandbox_info_t *` created by
233/// `bootstrap.exe` before loading this DLL (Windows + sandbox feature), or
234/// `null_mut()` on all other platforms / sandbox-off builds.
235pub fn run(windows_sandbox_info: *mut std::ffi::c_void) -> i32 {
236    agentmux_common::secret_env::stash_startup_secrets(); // first: no child inherits them
237    commands::deeplink_open::stash_launch_link(); // nor the link the launcher started it with
238    agentmux_common::tls_provider::install_ring_provider(); // reqwest 0.13 builds no client without it
239    // Internal self-probe mode (Linux userns-sandbox detection) — must be
240    // the very first check in this function, before anything else: a
241    // probe-mode process does nothing but this one syscall and exits, so
242    // none of the startup work below is relevant to it. See
243    // linux_sandbox::run_internal_userns_probe_and_exit()'s doc comment.
244    #[cfg(target_os = "linux")]
245    if std::env::args().any(|a| a == linux_sandbox::INTERNAL_PROBE_USERNS_FLAG) {
246        linux_sandbox::run_internal_userns_probe_and_exit();
247    }
248    // Same for the GL-renderer probe behind the hw-gl GPU tier: it only makes
249    // a throwaway EGL context and exits (app::gl_probe).
250    #[cfg(target_os = "linux")]
251    if std::env::args().any(|a| a == app::gl_probe::INTERNAL_PROBE_GL_FLAG) {
252        app::gl_probe::run_internal_gl_probe_and_exit();
253    }
254    commands::file_dialog_helper::run_and_exit_if_asked(); // the Linux file-dialog helper: shows one dialog, exits
255    // Phase 0 (service supervision & recovery): suppress the Windows crash
256    // modal so a fault terminates the process immediately instead of freezing
257    // it behind an "Application Error" dialog. Must be the first statement —
258    // set before anything can fault.
259    suppress_os_crash_dialogs();
260    dev_home_check::refuse_hand_started_dev_host(launcher_is_genuine_parent());
261
262    // Set the DLL search path so CEF's runtime LoadLibrary calls (chrome_elf,
263    // libEGL, libGLESv2, d3dcompiler_47, …) resolve against the directory that
264    // actually holds libcef.dll. Two layouts exist:
265    //
266    //   Portable / installed: <root>/runtime/host.exe + libcef.dll alongside.
267    //                         The launcher (agentmux-launcher) already sets
268    //                         the path to <root>/runtime/ before spawning us;
269    //                         this block is a no-op safety net for that mode.
270    //
271    //   Dev (`task dev`):     dist/cef-dev/agentmux-cef.exe + libcef.dll
272    //                         alongside (flat layout). Taskfile launches the
273    //                         host directly with no launcher, so nothing else
274    //                         has set the DLL path. Without it, CEF's internal
275    //                         LoadLibrary chain can fail and `cef::initialize`
276    //                         returns 0 — the empty-chrome_debug.log mode.
277    //
278    // Fall back to the host's own directory whenever a runtime/ subdir isn't
279    // present. Idempotent in portable mode (launcher set it first), correct
280    // in dev mode.
281    #[cfg(target_os = "windows")]
282    {
283        if let Ok(exe) = std::env::current_exe() {
284            if let Some(dir) = exe.parent() {
285                let runtime_dir = dir.join("runtime");
286                let dll_dir = if runtime_dir.exists() {
287                    runtime_dir
288                } else {
289                    dir.to_path_buf()
290                };
291                unsafe {
292                    use std::os::windows::ffi::OsStrExt;
293                    let wide: Vec<u16> = dll_dir.as_os_str().encode_wide().chain(Some(0)).collect();
294                    windows_sys::Win32::System::LibraryLoader::SetDllDirectoryW(wide.as_ptr());
295                }
296            }
297        }
298    }
299
300    // Tracing is initialized after the subprocess check below — browser process
301    // gets dual file+stderr output; subprocesses exit before tracing is needed.
302
303    // Escape hatch — read once here so both macOS subprocess sandbox init
304    // (below) and the browser-process Settings construction share the same
305    // value. Only mutated on the target_os = "linux" branch below.
306    #[cfg_attr(not(target_os = "linux"), allow(unused_mut))]
307    let mut force_no_sandbox = std::env::var("AGENTMUX_UNSAFE_NOSANDBOX")
308        .map(|v| v.trim() == "1")
309        .unwrap_or(false);
310
311    // Linux-only, browser-process-only: proactively probe whether the
312    // kernel-namespace sandbox will actually work BEFORE ever attempting
313    // CefInitialize, and offer a one-time AppArmor fix (or an explicit,
314    // visible downgrade) instead of letting a doomed init attempt trail
315    // into the generic post-init-failure path further down (search this
316    // file for "CEF initialization failed"). Must be skipped for
317    // subprocess roles — CEF re-execs this same binary for every
318    // renderer/GPU/utility process, and showing a dialog from one of
319    // those would be wrong, and would multiply once per subprocess.
320    // `--type=` is the same subprocess-detection pattern already used
321    // twice further down in this function. No-op if the user already
322    // opted out themselves (their explicit choice takes precedence, and
323    // the probe would just be wasted work).
324    // See docs/specs/SPEC_LINUX_SANDBOX_APPARMOR_USERNS_2026_08_23.md.
325    #[cfg(all(target_os = "linux", feature = "sandbox"))]
326    {
327        let is_subprocess = std::env::args().any(|a| a.starts_with("--type="));
328        if !is_subprocess && !force_no_sandbox {
329            use linux_sandbox::SandboxDialogChoice;
330            // Loop rather than a single check-then-act: re-probes at the
331            // top of every iteration (so a successful relaunch — see
332            // FixNow below — falls straight through without a dialog),
333            // and a FAILED fix attempt loops back to re-show the dialog
334            // instead of silently downgrading (reagent P1 on PR #2783 —
335            // the user asked to FIX it, not to run without a sandbox;
336            // never auto-disable on their behalf).
337            while !linux_sandbox::probe_userns_available() {
338                linux_sandbox::stop_if_nobody_can_answer();
339                match linux_sandbox::show_userns_blocked_dialog() {
340                    SandboxDialogChoice::FixNow => {
341                        let helper = linux_sandbox::resolve_helper_script_path();
342                        match linux_sandbox::run_pkexec_fix(&helper) {
343                            Ok(()) => {
344                                // AppArmor confinement attaches at exec()
345                                // time only — this already-running process
346                                // can never benefit from the
347                                // newly-installed profile no matter what
348                                // we do next (reagent P0 on PR #2783).
349                                // Relaunch in place so the ENTIRE process
350                                // tree (this process and every CEF
351                                // subprocess it spawns) starts fresh under
352                                // the new profile.
353                                eprintln!(
354                                    "AgentMux: sandbox fix installed — relaunching to apply it."
355                                );
356                                let exe = std::env::current_exe()
357                                    .unwrap_or_else(|_| std::path::PathBuf::from("agentmux-cef"));
358                                let args: Vec<String> = std::env::args().skip(1).collect();
359                                use std::os::unix::process::CommandExt;
360                                let err = std::process::Command::new(&exe).args(&args).envs(agentmux_common::secret_env::stashed()).exec();
361                                // exec() replaces the process image and
362                                // never returns on success — reaching here
363                                // means it failed.
364                                eprintln!(
365                                    "AgentMux: relaunch failed after installing the fix ({err}) \
366                                     — please start AgentMux again manually."
367                                );
368                                std::process::exit(1);
369                            }
370                            Err(e) => {
371                                eprintln!("AgentMux: sandbox fix failed: {e}");
372                                // Loop back to the dialog rather than
373                                // falling through unsandboxed.
374                            }
375                        }
376                    }
377                    SandboxDialogChoice::ContinueWithoutSandbox => {
378                        // SAFETY: single-threaded at this point in startup —
379                        // before any additional threads (async runtime,
380                        // CEF's own internal threads) have been spawned,
381                        // and gated to the browser process only
382                        // (subprocess roles never reach this branch) — no
383                        // concurrent env reader exists yet for this
384                        // mutation to race with.
385                        unsafe {
386                            std::env::set_var("AGENTMUX_UNSAFE_NOSANDBOX", "1");
387                        }
388                        force_no_sandbox = true;
389                        // Keep the downgrade visible for the rest of the
390                        // session (window title) — reagent/codex P2 on
391                        // PR #2783.
392                        linux_sandbox::RUNNING_UNSANDBOXED
393                            .store(true, std::sync::atomic::Ordering::Relaxed);
394                        break;
395                    }
396                    SandboxDialogChoice::Cancel => {
397                        std::process::exit(1);
398                    }
399                    SandboxDialogChoice::NoDialogToolAvailable => linux_sandbox::exit_no_dialog_tool(),
400                }
401            }
402        }
403    }
404
405    // macOS sandbox availability: probe for libcef_sandbox.dylib to detect
406    // whether we are running inside a packaged .app bundle. Two uses:
407    //   1. Seatbelt init (subprocess only) — skip if dylib not reachable.
408    //   2. no_sandbox flag to CefInitialize — must be 1 when not in bundle,
409    //      otherwise CEF kills GPU/network/renderer with a sandbox error.
410    //
411    // The path is relative to current_exe().parent() and differs by role
412    // because the Host and Helper processes live at different depths:
413    //
414    //   Host   — Contents/MacOS/AgentMux
415    //            → ../Frameworks/Chromium Embedded Framework.framework/…
416    //
417    //   Helper — Contents/Frameworks/AgentMux Helper.app/Contents/MacOS/AgentMux Helper
418    //            → ../../../Chromium Embedded Framework.framework/…
419    //
420    // In task dev neither path exists (flat dist/cef-dev/ tree), so the probe
421    // returns false for both roles → sandbox skipped, no crash.
422    #[cfg(all(target_os = "macos", feature = "sandbox"))]
423    let macos_sandbox_available = {
424        let is_subprocess = std::env::args().any(|a| a.starts_with("--type="));
425        let rel: &str = if is_subprocess {
426            "../../../Chromium Embedded Framework.framework/Libraries/libcef_sandbox.dylib"
427        } else {
428            "../Frameworks/Chromium Embedded Framework.framework/Libraries/libcef_sandbox.dylib"
429        };
430        std::env::current_exe()
431            .ok()
432            .and_then(|p| p.parent().map(|d| d.join(rel)))
433            .map(|p| p.exists())
434            .unwrap_or(false)
435    };
436
437    // Non-macOS / sandbox-off: define macos_sandbox_available as a no-op
438    // placeholder so the no_sandbox computation below compiles on all targets.
439    // On those targets cfg!(all(target_os="macos",feature="sandbox")) is false,
440    // so the `&& !macos_sandbox_available` branch is never reached at runtime.
441    #[cfg(not(all(target_os = "macos", feature = "sandbox")))]
442    let macos_sandbox_available = true; // irrelevant — guarded by cfg!() in no_sandbox
443
444    // macOS: initialize Seatbelt sandbox context BEFORE the CEF framework is
445    // loaded. This is the order required by CEF (cefsimple/process_helper_mac.cc):
446    //   1. cef_sandbox_initialize     ← here, before dlopen
447    //   2. LoadInHelper / _library    ← CEF framework loaded within the sandbox
448    //   3. CefExecuteProcess
449    // Subprocess mode is detected from raw argv (--type=…) because cef::Args
450    // cannot be parsed until after the framework is loaded. Browser process
451    // skips this entirely — the host process is unsandboxed by design.
452    #[cfg(all(target_os = "macos", feature = "sandbox"))]
453    let _macos_sandbox = if std::env::args().any(|a| a.starts_with("--type="))
454        && !force_no_sandbox
455        && macos_sandbox_available
456    {
457        let raw = cef::args::Args::new();
458        let mut s = cef::sandbox::Sandbox::new();
459        s.initialize(raw.as_main_args());
460        Some(s)
461    } else {
462        None
463    };
464
465    // macOS: load the CEF framework library explicitly.
466    // For subprocesses this load happens within the Seatbelt policy established above.
467    //
468    // Timed locally (Instant, not IPC) because this happens before
469    // connect_to_launcher runs — there's no live launcher connection yet
470    // to report through. The duration is sent retroactively as soon as
471    // the connection exists (see the report_startup_stage_* call right
472    // after connect_to_launcher below). Reported for every process role
473    // that reaches here (browser + subprocesses), but only the browser
474    // process ever has a live COMMAND_TX to actually send through —
475    // report_startup_stage_* silently no-ops otherwise, so no extra
476    // role-gating is needed here.
477    #[cfg(target_os = "macos")]
478    let dlopen_started_at = std::time::Instant::now();
479    #[cfg(target_os = "macos")]
480    let _library = {
481        let exe = std::env::current_exe().unwrap();
482        // Inside a packaged .app, renderer/GPU/utility subprocesses run as the
483        // bundled "AgentMux Helper" at
484        // …/Contents/Frameworks/AgentMux Helper.app/Contents/MacOS/AgentMux Helper
485        // — 4 levels below the framework — so it must resolve the framework via
486        // the deeper `../../../../Frameworks/…` path (helper=true). The main
487        // host (Contents/MacOS/) and the bare dev binary use `../Frameworks/…`
488        // (helper=false). Detect the helper by its exe path; the main bundle
489        // binary is never under Contents/Frameworks/. See
490        // docs/specs/SPEC_MACOS_PACKAGING_2026_05_30.md.
491        let is_helper = exe.to_string_lossy().contains(".app/Contents/Frameworks/");
492        let loader = library_loader::LibraryLoader::new(&exe, is_helper);
493        assert!(loader.load(), "Failed to load CEF framework");
494        loader
495    };
496    #[cfg(target_os = "macos")]
497    let dlopen_ms = dlopen_started_at.elapsed().as_millis() as u64;
498
499    // Initialize the CEF API hash for version verification.
500    let _ = api_hash(sys::CEF_API_VERSION_LAST, 0);
501
502    // Parse command-line arguments.
503    let args = cef::args::Args::new();
504    let Some(cmd_line) = args.as_cmd_line() else {
505        eprintln!("agentmux-cef: Failed to parse command line arguments");
506        std::process::exit(1);
507    };
508
509    // Detect subprocess mode: CEF injects --type=renderer|gpu-process|utility
510    // for child processes. If --type is present, this is a subprocess.
511    let type_switch = CefString::from("type");
512    let is_browser_process = cmd_line.has_switch(Some(&type_switch)) != 1;
513
514    // macOS 26 + dev build: ChromeWebAppShortcutCopierMain CHECK-aborts (SIGTRAP)
515    // because the dev binary is not in a signed .app bundle.
516    // --disable-features=MacAppCodeSignClone in on_before_command_line_processing
517    // cannot prevent the spawn because the feature flag is checked before FeatureList
518    // is initialized (same timing problem as MachPortRendezvous). Exit 0 immediately
519    // for this subprocess type so the main process sees a "clean" failure and
520    // continues without the code-sign clone (which is irrelevant for dev builds).
521    // The main process logs "Failed to send Mojo invitation to web_app_shortcut_copier"
522    // (harmless) and continues. This exit must happen BEFORE execute_process() which
523    // calls ChromeWebAppShortcutCopierMain() and SIGTRAP-kills the subprocess.
524    #[cfg(target_os = "macos")]
525    if !is_browser_process {
526        let pt = CefString::from(&cmd_line.switch_value(Some(&type_switch)));
527        let pt_str = pt.to_string();
528        if pt_str == "web-app-shortcut-copier" {
529            eprintln!("agentmux-cef: intercepted web-app-shortcut-copier (dev build, not in .app bundle) — exiting 0");
530            std::process::exit(0);
531        }
532    }
533
534    let ret = execute_process( // runs a subprocess (exiting below); renderer_map.rs says why its app
535        Some(args.as_main_args()),
536        (!is_browser_process).then(renderer_map::SubprocessApp::new).as_mut(),
537        windows_sandbox_info as *mut u8,
538    );
539
540    if is_browser_process {
541        // Browser process: execute_process returns -1, we continue with initialization.
542        assert_eq!(ret, -1, "execute_process should return -1 for browser process");
543    } else {
544        // Subprocess: execute_process returns the exit code.
545        let process_type = CefString::from(&cmd_line.switch_value(Some(&type_switch)));
546        eprintln!("agentmux-cef: subprocess exiting: type={}", process_type);
547        assert!(ret >= 0, "execute_process failed for subprocess");
548        std::process::exit(ret);
549    }
550
551    // -----------------------------------------------------------------------
552    // Browser process initialization
553    // -----------------------------------------------------------------------
554
555    // Set the Application User Model ID before any UI is created. This lets
556    // Windows group our windows under one pinned identity and is required for
557    // the `DeleteTab` + per-HWND AppID treatment used by the full-instance /
558    // sub-window model (see docs/specs/SPEC_MULTIWINDOW_TASKBAR_GROUPING.md).
559    // Use a VERSION-STABLE ID — never embed the patch number or pinning forks.
560    #[cfg(target_os = "windows")]
561    unsafe {
562        use windows_sys::Win32::UI::Shell::SetCurrentProcessExplicitAppUserModelID;
563        let aumid: Vec<u16> = "AgentMuxCorp.AgentMux\0".encode_utf16().collect();
564        let _ = SetCurrentProcessExplicitAppUserModelID(aumid.as_ptr());
565    }
566
567    let version = env!("CARGO_PKG_VERSION");
568
569    // Read paths + mode from the launcher-injected env vars. Two
570    // reachable configurations:
571    //   a) Launcher-managed startup → env vars present, from_env()
572    //      returns Some.
573    //   b) Standalone `task dev` → env absent. We re-derive via
574    //      `RuntimeMode::current` + `DataPaths::resolve` (symmetric
575    //      with sidecar.rs::spawn_backend's fallback so they agree on
576    //      the disk layout).
577    let host_exe_dir = std::env::current_exe()
578        .ok()
579        .and_then(|p| p.parent().map(|d| d.to_path_buf()))
580        .unwrap_or_default();
581    // Dev builds NEVER inherit AGENTMUX_* env vars from a parent process.
582    // `task dev` is routinely launched from inside an AgentMux terminal
583    // pane, which means the child host inherits the parent instance's
584    // AGENTMUX_DATA_DIR pointing at the parent's version-isolated dir.
585    // Without this guard the dev build would resolve its data dir to the
586    // running portable's path and trip CEF's process-singleton lock,
587    // routing every "open" back to the existing window — the user would
588    // never see the dev code run. Path-based detection is authoritative
589    // for dev builds; for installed/portable we still honor the
590    // launcher-provided env (it's the launcher's job to publish them).
591    let common_paths = if agentmux_common::is_dev_build_exe(&host_exe_dir) {
592        let mode = agentmux_common::RuntimeMode::current_path_only(&host_exe_dir);
593        // resolve_path_only mirrors current_path_only's env-isolation:
594        // ignore inherited AGENTMUX_CHANNEL so a dev host launched from
595        // inside a parent agentmux instance doesn't redirect into the
596        // parent's channel (would trip the channel single-instance lock).
597        agentmux_common::DataPaths::resolve_path_only(version, &mode).ok()
598    } else {
599        agentmux_common::DataPaths::from_env().or_else(|| {
600            let mode = agentmux_common::RuntimeMode::current(&host_exe_dir);
601            agentmux_common::DataPaths::resolve(version, &mode).ok()
602        })
603    };
604    let is_dev = match &common_paths {
605        Some(p) => matches!(p.mode, agentmux_common::RuntimeMode::Dev { .. }),
606        None => false,
607    };
608
609    let (data_dir, log_dir) = match &common_paths {
610        Some(p) => (p.cef_cache_dir.clone(), p.logs_dir.clone()),
611        None => {
612            // Both env-read AND fallback resolution failed (no home
613            // dir on disk, or platform unsupported). Use a degraded
614            // path so log init at least works; the runtime-startup
615            // check below will surface the underlying error.
616            (
617                std::path::PathBuf::from("."),
618                dirs::home_dir()
619                    .unwrap_or_default()
620                    .join(".agentmux")
621                    .join("logs"),
622            )
623        }
624    };
625    std::fs::create_dir_all(&data_dir).ok();
626
627    // Initialize dual-output tracing: rolling log file + stderr.
628    // The log file guard must live for the entire process to ensure flushing.
629    let _log_guard = logging::init_logging(&log_dir);
630    commands::store_restart::at_startup(common_paths.as_ref());
631
632    tracing::info!(
633        version,
634        runtime_mode = ?common_paths.as_ref().map(|p| p.mode.to_env_string()),
635        data_dir = %data_dir.display(),
636        log_dir = %log_dir.display(),
637        "Initializing CEF browser process"
638    );
639
640    // macOS 26 Tahoe compat: CEF 146 calls private NSApplication selectors
641    // (e.g. `isHandlingSendEvent`, `isSendingEvent`) during NSDraggingSession
642    // setup. Apple removed them in macOS 26, so the calls go through
643    // `___forwarding___`, find nothing, and `objc_exception_throw` fires —
644    // AppKit's default uncaught-exception handler then calls `_objc_terminate`
645    // and the host dies (EXC_BREAKPOINT / SIGTRAP on CrBrowserMain). Inject
646    // `+[NSApplication resolveInstanceMethod:]` to add typed stubs *before*
647    // the forwarding machinery is entered. Must run before `cef::initialize`.
648    // See docs/specs/SPEC_MACOS_TEAROFF_STABILITY_2026_05_29.md and PR #403.
649    #[cfg(target_os = "macos")]
650    unsafe { macos_compat::patch_nsapp_unrecognized_selector() };
651
652    // macOS tear-off polish: suppress AppKit's native drag slide-back
653    // ("poof" / fly-back-to-origin) animation. When a pane/tab is torn
654    // off, the pointer is released OUTSIDE any DOM drop target (the new
655    // floating window is created on mouseup), so blink hands AppKit
656    // NSDragOperationNone and AppKit animates the drag image sliding
657    // back into the source window — the very "rejection" animation the
658    // tear-off is trying to avoid. `preventUnhandled` (PR #1186) only
659    // covers in-document drops, not this out-of-window case. Disable the
660    // session-level animation flag globally; we never want a
661    // drop-rejected slide-back anywhere in the app.
662    #[cfg(target_os = "macos")]
663    unsafe { macos_compat::disable_macos_drag_slideback() };
664
665    // Name the app early (sets CFBundleName on the main bundle, which AppKit
666    // may read when it first builds a menu). Also re-run post-init below, since
667    // Chromium can reset the process name during cef::initialize.
668    // NOTE: CFBundleIdentifier is NOT set here (pre-init) — setting it before
669    // cef::initialize triggers MacAppCodeSignClone which SIGTRAP-crashes dev builds.
670    #[cfg(target_os = "macos")]
671    unsafe { macos_compat::set_macos_app_display_name_pre_init() };
672
673    // Phase B.6 (post-fix): the named-pipe bind in the launcher is
674    // the AUTHORITATIVE single-instance lock — a second launcher
675    // hits ERROR_ACCESS_DENIED and never reaches the host. We still
676    // publish `<launcher-shared-data-dir>/ipc-port` (port:token) so
677    // the second launcher can FORWARD an `open_new_window` request
678    // to the existing instance over HTTP and exit silently — the
679    // legacy forwarding UX users expect when double-clicking the
680    // exe twice. The pipe-bind-first ordering closes the stale-state
681    // defect (gap #8 in
682    // docs/specs/ANALYSIS_WINDOW_PROCESS_STATE_INVENTORY_2026_04_27.md):
683    // a stale ipc-port file from a hard crash is irrelevant on the
684    // FIRST-instance path because pipe-bind succeeds and the file is
685    // overwritten; on the SECOND-instance path the live first
686    // instance wrote a fresh port:token, so forwarding lands.
687    //
688    // CRITICAL: write the port file at the LAUNCHER-shared data dir
689    // (`AGENTMUX_DATA_DIR`, == `paths.data_dir` in the launcher), NOT
690    // the host-local CEF cache dir (`<portable>/data/cef/`). The two
691    // diverge in portable mode (cef cache is one level deeper) and
692    // the launcher's `forward_open_new_window` reads the launcher-
693    // shared path. Falls back to the cef cache dir only when the env
694    // is unset (`task dev` mode without launcher), where forwarding
695    // wouldn't be wired anyway.
696    // Dev builds inherit AGENTMUX_DATA_DIR from the parent pane they were
697    // launched from. Writing ipc-port there would overwrite the parent
698    // instance's port:token and break its single-instance forwarding.
699    // That hazard is real ONLY when no launcher spawned us; see
700    // `port_file_dir` for why the launcher's presence is the deciding
701    // factor rather than "is this a dev build".
702    let port_file_dir = port_file_dir(
703        std::env::var_os("AGENTMUX_IPC_HASH").is_some_and(|h| !h.is_empty()),
704        std::env::var_os("AGENTMUX_DATA_DIR").map(std::path::PathBuf::from),
705        agentmux_common::is_dev_build_exe(&host_exe_dir),
706        &data_dir,
707    );
708    let _ = std::fs::create_dir_all(&port_file_dir);
709    // Use a version-scoped filename so two concurrent release versions
710    // don't overwrite each other's port file (codex P1 on #1227).
711    // AGENTMUX_IPC_HASH is set by the launcher to hash(data_dir, version).
712    let port_file_name = std::env::var("AGENTMUX_IPC_HASH")
713        .ok()
714        .filter(|h| !h.is_empty())
715        .map(|h| format!("ipc-port-{}", h))
716        .unwrap_or_else(|| "ipc-port".to_string());
717    let port_file = port_file_dir.join(&port_file_name);
718
719    // Create shared application state.
720    let app_state = Arc::new(state::AppState::default());
721
722    // Start tokio runtime for async operations (IPC server, sidecar management).
723    let runtime = tokio::runtime::Runtime::new().expect("Failed to create tokio runtime");
724
725    // Install the runtime Handle into browser_pane::auth so the
726    // CEF `get_auth_credentials` callback (which runs on CEF's IO
727    // thread) can spawn the parked-auth TTL timer. A bare
728    // `tokio::spawn` there would panic with "there is no reactor
729    // running" because that thread has no `Handle::current()`.
730    browser_pane::auth::set_runtime_handle(runtime.handle().clone());
731
732    // Same rationale, for the credential broker's async orchestration
733    // (and the approval registry's TTL timer, which shares this handle) —
734    // see `credential_broker::set_runtime_handle`'s doc comment.
735    credential_broker::set_runtime_handle(runtime.handle().clone());
736
737    // Lets the approval registry's TTL timer close an expired approval's
738    // subwindow. It holds `window_id` strings and nothing else by design, and
739    // its timer task has neither `AppState` nor a window handle — without
740    // this, a timed-out approval left a dead, unresponsive window open until
741    // the human closed it by hand (reagent P2 on PR #2824).
742    {
743        let closer_state = app_state.clone();
744        credential_broker::set_window_closer(move |window_id: &str| {
745            if let Err(e) = commands::window::close_window_by_label(
746                &closer_state,
747                &serde_json::json!({ "label": window_id }),
748            ) {
749                tracing::warn!("[credential-broker] failed to close approval window {window_id}: {e}");
750            }
751        });
752    }
753
754    // Start the IPC HTTP server and get the assigned port.
755    let ipc_port = runtime.block_on(ipc::start_ipc_server(app_state.clone()));
756    *app_state.ipc_port.lock() = ipc_port;
757
758    tracing::info!("IPC server started on port {}", ipc_port);
759    agentmux_common::test_offscreen::begin("host");
760
761    // Phase B.2: connect to launcher's named-pipe IPC (if launcher
762    // is in the loop) so the launcher can route Commands and Events
763    // through us. The handle is held in main scope for the host's
764    // lifetime — dropping it closes the pipe (logged by launcher).
765    // Failure to connect is non-fatal in B.2 (host can still run);
766    // B.5+ will tighten when the host depends on IPC for state.
767    //
768    // Env-isolation guard: a dev build inheriting
769    // `AGENTMUX_LAUNCHER_PIPE` from a parent AgentMux pane (e.g. a
770    // shell inside an active pane that re-invokes the host directly)
771    // would otherwise connect to that parent's launcher pipe and
772    // route its host events into the parent's launcher state.
773    //
774    // Discriminator: connect when our parent process IS the launcher
775    // (production portable, installed build, OR post-#SPEC_LAUNCHER_DEV_INTEGRATION
776    // `task dev` which spawns the host via the launcher). Skip when
777    // it isn't.
778    //
779    // Older path-only guard (`is_dev_build_exe`) over-fired in dev
780    // mode after launcher integration shipped — see
781    // docs/specs/SPEC_DEV_MODE_LAUNCHER_IPC_2026_05_16.md.
782    let parent_is_launcher = parent_process::parent_is_agentmux_launcher();
783    let should_connect_launcher = match parent_is_launcher {
784        Some(true) => true,
785        Some(false) => false,
786        // Parent detection failed — fall back to the path-based guard
787        // so production builds still connect (they would otherwise
788        // silently lose the launcher IPC) and dev builds still skip.
789        None => !agentmux_common::is_dev_build_exe(&host_exe_dir),
790    };
791    let _launcher_ipc = if should_connect_launcher {
792        runtime.block_on(launcher_ipc::connect_to_launcher(app_state.clone()))
793    } else {
794        None
795    };
796
797    // Report the CEF framework dlopen timing now that a launcher
798    // connection exists (it didn't when dlopen actually happened, above).
799    // Sent as a StageBegin+StageEnd pair with the already-elapsed
800    // duration on the End message — the launcher's splash renders this
801    // like any other completed stage. No-op if _launcher_ipc is None
802    // (dev:standalone, or this is a subprocess role that never connects).
803    #[cfg(target_os = "macos")]
804    {
805        launcher_ipc::report_startup_stage_begin("dlopen", "Load CEF library");
806        launcher_ipc::report_startup_stage_end("dlopen", dlopen_ms, "ok", None);
807    }
808
809    // Phase E.2c.5a — connect to the srv reducer's pipe. Forwards
810    // srv events (workspace / tab / block lifecycle) to every
811    // top-level renderer via the JS bridge. Renderer-side handler
812    // (`window.__agentmux_srv_event`) lands in E.2c.5b. Non-fatal
813    // if absent: `AGENTMUX_SRV_PIPE_PATH` is only set on the srv
814    // child by the launcher (`crates/launcher/src/srv_spawner.rs`),
815    // not on the host spawn — so today the host never has the env
816    // var and `connect_to_srv` (`srv_ipc.rs`) short-circuits to None at
817    // its env-var check. Path-based dev guard is the right gate
818    // for this branch; restoring full srv-IPC parity in dev needs
819    // the launcher to propagate the env var to the host first.
820    // See spec §11 of SPEC_DEV_MODE_LAUNCHER_IPC_2026_05_16.md.
821    let _srv_ipc = if agentmux_common::is_dev_build_exe(&host_exe_dir) {
822        None
823    } else {
824        runtime.block_on(srv_ipc::connect_to_srv(app_state.clone()))
825    };
826
827    // Phase B.1: if launcher already spawned srv (the normal portable
828    // / installed path post-PR-#570 + B.1), populate state from the
829    // env vars launcher set — no need to re-spawn srv. Falls back to
830    // spawn_backend() ONLY when env vars are absent (`task dev` mode
831    // where the host runs without the launcher).
832    //
833    // Spawn the backend sidecar SYNCHRONOUSLY — block until it
834    // signals ready (AGENTMUXSRV-ESTART) before creating the browser
835    // window. This eliminates the race condition where CEF loads the
836    // frontend before the backend is available, which causes a "raw
837    // browser" appearance on slow machines or first launch.
838    let backend_ready = runtime.block_on(async {
839        // Dev builds inherit AGENTMUX_BACKEND_WS from the parent pane.
840        // Consuming it would connect to the parent's srv instead of
841        // spawning our own, so the dev frontend runs against the wrong
842        // (parent's) backend and no dev-version srv is ever started.
843        //
844        // EXCEPTION (launcher-driven `task dev` on every platform —
845        // SPEC_LAUNCHER_MACOS_DEV_INTEGRATION_2026_05_30 for macOS/Linux,
846        // Windows since #3868's follow-up): when a launcher
847        // is our GENUINE parent this run (it stamped AGENTMUX_LAUNCHER_PID
848        // with its pid == our getppid), the env it set is fresh + ours —
849        // adopt its launcher-owned srv instead of double-spawning. The
850        // getppid match can't be satisfied by a value merely inherited
851        // down the env from a parent pane, so `task dev:standalone`
852        // (direct host invoke) still spawns its own srv.
853        let launcher_provided = if !sidecar::may_adopt_launcher_backend(&host_exe_dir) {
854            None
855        } else {
856            sidecar::use_launcher_endpoints(&app_state)
857        };
858        // Captured before the match below consumes launcher_provided by value.
859        // Phase 0f: distinguishes which path result.pending_migrations came
860        // from, so we know when it's safe to trust a 0.
861        let is_host_owned_spawn = launcher_provided.is_none();
862        let result = match launcher_provided {
863            Some(Ok(r)) => {
864                tracing::info!(
865                    "Using launcher-provided backend endpoints: ws={} web={} pid={}",
866                    r.ws_endpoint,
867                    r.web_endpoint,
868                    r.instance_id
869                );
870                Ok(r)
871            }
872            Some(Err(e)) => {
873                tracing::error!(
874                    "Launcher set AGENTMUX_BACKEND_WS but env was malformed: {} — refusing to fall back to spawn_backend (would fight launcher's srv)",
875                    e
876                );
877                Err(e)
878            }
879            None => {
880                tracing::info!("No launcher-provided backend env (dev mode) — spawning srv ourselves");
881                sidecar::spawn_backend(&app_state).await
882            }
883        };
884        match result {
885            Ok(result) => {
886                {
887                    let mut endpoints = app_state.backend_endpoints.lock();
888                    endpoints.ws_endpoint = result.ws_endpoint.clone();
889                    endpoints.web_endpoint = result.web_endpoint.clone();
890                }
891                // On the host-owned spawn_backend path, result.pending_migrations
892                // is the authoritative signal for THIS spawn — always trust it,
893                // including 0, so a stale nonzero count cached from an earlier
894                // spawn in this process's lifetime (e.g. before a restart) gets
895                // cleared on a clean re-spawn instead of sticking forever
896                // (Phase 0f, docs/specs/SPEC_MIGRATION_SYSTEM_HARDENING_2026_08_03.md
897                // §1.6/F8). On the launcher path use_launcher_endpoints always
898                // returns 0 here (meaningless stub) and the real count was
899                // already seeded into AppState from AGENTMUX_PENDING_MIGRATIONS
900                // at construction time — only ever overwrite it with a
901                // genuinely positive value, never clobber it with this stub 0.
902                if is_host_owned_spawn || result.pending_migrations > 0 {
903                    *app_state.pending_migrations.lock() = result.pending_migrations;
904                }
905                tracing::info!(
906                    "Backend ready: ws={} web={}",
907                    result.ws_endpoint,
908                    result.web_endpoint
909                );
910                true
911            }
912            Err(e) => {
913                tracing::error!("Failed to set up backend: {}", e);
914                false
915            }
916        }
917    });
918
919    if !backend_ready {
920        tracing::error!("Backend failed to start — exiting");
921        std::process::exit(1);
922    }
923
924    // Dev-only: write authkey.dev so external test harnesses can call
925    // the service API without polling logs or driving the UI. Gate is
926    // Pick a FREE remote-debugging port instead of a fixed one: AgentMux runs
927    // many instances in parallel (isolation I1–I6), so a hardcoded port collides
928    // (WSAEADDRINUSE / 0x2740) and the 2nd+ instance gets no DevTools server →
929    // the browser DOM API (`/agentmux/browser/*`) can't connect. Prefer the
930    // conventional port (9223 dev / 9222 release) for muscle memory; fall back to
931    // an OS-assigned free port. Store the ACTUAL port so `browser_api` targets
932    // it. SPEC_CEF_LOG_ROBUSTNESS_2026_06_20.md §2.
933    //
934    // Off entirely in release builds unless AGENTMUX_CDP_PORT opts in
935    // (#3681): the server is unauthenticated on a loopback every local user
936    // shares, and nothing in the app needs it — the browser API is in-process
937    // now. `debug_port == 0` means "no server"; CEF treats a 0
938    // `remote_debugging_port` the same way. See `cdp_port`.
939    let requested = cdp_port::requested_cdp_port(
940        is_dev,
941        std::env::var(cdp_port::CDP_PORT_ENV).ok().as_deref(),
942    );
943    let debug_port: u16 = match requested {
944        None => 0,
945        Some(preferred) => {
946            use std::net::TcpListener;
947            if TcpListener::bind(("127.0.0.1", preferred)).is_ok() {
948                preferred
949            } else {
950                TcpListener::bind(("127.0.0.1", 0))
951                    .and_then(|l| l.local_addr())
952                    .map(|a| a.port())
953                    .unwrap_or(preferred)
954            }
955        }
956    };
957    *app_state.debug_port.lock() = debug_port;
958    match requested {
959        Some(preferred) => tracing::info!("CEF remote-debugging port: {} (preferred {})", debug_port, preferred),
960        None => tracing::info!(
961            "CEF remote-debugging server off (set {}=<port> to enable it)",
962            cdp_port::CDP_PORT_ENV
963        ),
964    }
965
966    // Resolved BEFORE authkey.dev is written, so the file can publish it.
967    // Tooling used to hardcode 9222/9223, which silently targets whichever
968    // instance won the race rather than the one the caller meant — an agent
969    // attached a debugger to a DIFFERENT running instance that way. A
970    // well-known constant cannot identify an instance; the per-instance file
971    // can. See docs/specs/SPEC_INSTANCE_DISCOVERY_FOR_TOOLING_2026_09_17.md.
972    // A dev build writes authkey.dev (instance key and host token) for its test
973    // harnesses; an installed or portable build writes instance.json (endpoints,
974    // pid, version, debug port) and removes a leftover authkey.dev. See dev_authfile.
975    publish_discovery_file(&app_state, ipc_port, is_dev, debug_port);
976
977    // Push this host's ipc_port/ipc_token to srv (host_ipc.Register) so
978    // srv can proxy /api/v1/ui/{screenshot,click,query} (agent-facing UI
979    // automation) to this host's /agentmux/browser/* routes. Must run
980    // after backend_endpoints.web_endpoint is known (just above) — see
981    // SPEC_AGENT_UI_AUTOMATION_CLICK_SCREENSHOT_2026_08_18.md. Runs off
982    // the UI thread via spawn_blocking (raw-TCP, synchronous, same as
983    // every other client::helpers call) so a slow/unreachable srv can't
984    // stall startup.
985    commands::deeplink_open::register_with_srv(&app_state, &runtime, ipc_port);
986
987    // Create the App handler with state.
988    let mut cef_app = app::AgentMuxApp::new(app_state.clone(), ipc_port);
989
990    // Resolve resource directories for portable layout. In portable
991    // mode the CEF host is IN runtime/, so resources are flat
992    // alongside it. In dev mode they are also flat in dist/cef-dev/.
993    // Reuses `host_exe_dir` from the startup mode-detection block.
994    //
995    // macOS is the exception: Chromium ships icudtl.dat + the .pak
996    // files + locales inside the framework bundle's `Resources/`
997    // directory, not flat next to the binary. cef-rs's LibraryLoader
998    // already finds the framework via `../Frameworks/...`; we point
999    // CefSettings at the same place so Chromium's icu_util loader,
1000    // pack loader, and locale loader resolve correctly. See
1001    // docs/specs/SPEC_MACOS_CEF_FRAMEWORK_BUNDLING_2026_05_28.md.
1002    let runtime_dir = host_exe_dir.join("runtime");
1003    let base_dir = if runtime_dir.exists() {
1004        runtime_dir
1005    } else {
1006        host_exe_dir.clone()
1007    };
1008    #[cfg(not(target_os = "macos"))]
1009    let (resources_path, locales_path) = (base_dir.clone(), base_dir.join("locales"));
1010    #[cfg(target_os = "macos")]
1011    let (framework_path, resources_path, locales_path) = {
1012        let framework = base_dir
1013            .join("..")
1014            .join("Frameworks")
1015            .join("Chromium Embedded Framework.framework");
1016        let resources = framework.join("Resources");
1017        (framework, resources.clone(), resources)
1018    };
1019    let resources_dir = CefString::from(resources_path.to_str().unwrap_or(""));
1020    let locales_dir = CefString::from(locales_path.to_str().unwrap_or(""));
1021    #[cfg(target_os = "macos")]
1022    let framework_dir = CefString::from(framework_path.to_str().unwrap_or(""));
1023
1024    // Reuse data_dir from single-instance check as CEF cache path.
1025    // Remove stale lockfile from a previous killed run.
1026    let lockfile = data_dir.join("lockfile");
1027    if lockfile.exists() {
1028        tracing::warn!("Removing stale CEF lockfile: {}", lockfile.display());
1029        let _ = std::fs::remove_file(&lockfile);
1030    }
1031    browser_pane::profile_carry::prepare(&data_dir); // logs it; carries the last version's profiles
1032    let cache_dir = CefString::from(browser_pane::identity::canonical_dir(&data_dir).to_str().unwrap_or("")); // CEF compares it as text with profile folders
1033    // Expose root_cache_path. Secondary windows share the default context
1034    // (`commands::secondary_window_request_context`) and create nothing under
1035    // it, but the legacy-litter sweep below and future consumers still need
1036    // the resolved path.
1037    *app_state.cef_cache_dir.lock() = Some(cache_dir.to_string());
1038    // Remove dirs left by the earlier isolated-context path schemes
1039    // (`browser-contexts/`, `ctx-*`) — labels are per-run UUIDs, so they can
1040    // never be referenced again. SPEC_CEF_LOG_ROBUSTNESS_2026_06_20.md §1.6.
1041    crate::commands::cleanup_legacy_context_dirs(&data_dir.to_string_lossy());
1042
1043    // Configure CEF settings.
1044
1045    // Route CEF's internal Chromium logging into our log dir alongside the
1046    // tracing-subscriber file. Without this, init failures leave an empty
1047    // chrome_debug.log in the cache dir and we have nothing to read. INFO is
1048    // verbose enough to expose load-library / resource problems but quiet
1049    // enough not to swamp the file in normal operation.
1050    let cef_log_path = log_dir.join("cef-debug.log");
1051    let cef_log_file = CefString::from(cef_log_path.to_str().unwrap_or(""));
1052
1053    if force_no_sandbox {
1054        tracing::warn!(
1055            "AGENTMUX_UNSAFE_NOSANDBOX=1: renderer sandbox disabled. \
1056             Only use in environments where namespace/Seatbelt sandbox is known-incompatible."
1057        );
1058    }
1059
1060    // Sandbox active on macOS (Seatbelt via libcef_sandbox.dylib), Linux
1061    // (kernel namespace isolation), and Windows (bootstrap.exe DLL wrapper,
1062    // Phase 3) when built with `--features sandbox` (the default).
1063    // Escape hatch: AGENTMUX_UNSAFE_NOSANDBOX=1 disables on all platforms.
1064    let no_sandbox: i32 = if cfg!(not(feature = "sandbox"))
1065        || force_no_sandbox
1066        || cfg!(all(target_os = "macos", feature = "sandbox")) && !macos_sandbox_available
1067    {
1068        1
1069    } else {
1070        0
1071    };
1072
1073    let settings = Settings {
1074        no_sandbox,
1075        // ARGB: alpha=0 → SK_AlphaTRANSPARENT → triggers the transparency
1076        // cascade in the patched libcef.so (see cef commits b921ffe18 +
1077        // 68e0dc668). The CSS layer's rgba(_,_,_,<1) body bg then composites
1078        // with the desktop instead of being clamped to opaque white.
1079        // Pair: BrowserSettings.background_color must also be 0 (app/mod.rs
1080        // sets it so only for alpha-capable windows).
1081        // Pair: WindowDelegate must return is_frameless=true (already does
1082        // for the main window).
1083        // Spec: docs/research/cef-transparency-research-2026-05-10.md.
1084        background_color: 0x00000000,
1085        remote_debugging_port: debug_port as i32,
1086        root_cache_path: cache_dir,
1087        resources_dir_path: resources_dir,
1088        locales_dir_path: locales_dir,
1089        // macOS-only: tell CEF where the framework bundle lives so it can
1090        // resolve icudtl.dat, *.pak, and helper-process binaries through
1091        // NSBundle. Without this, Chromium's icu_util loader looks via
1092        // [NSBundle mainBundle] (the host exe's pseudo-bundle) which has
1093        // no Resources/ and fails with "icudtl.dat not found in bundle".
1094        #[cfg(target_os = "macos")]
1095        framework_dir_path: framework_dir,
1096        log_file: cef_log_file,
1097        log_severity: LogSeverity::INFO,
1098        // CEF subprocess (renderer, GPU, utility) executable. On a packaged
1099        // macOS .app this is the dedicated "AgentMux Helper" (distinct bundle
1100        // id, LSUIElement) — re-execing the main bundle binary is rejected by
1101        // the macOS process model and the renderers crash-loop. In dev (bare
1102        // binary, no Helper.app) and on Windows/Linux it's the current exe
1103        // (self-reexec, which works there). See
1104        // docs/specs/SPEC_MACOS_PACKAGING_2026_05_30.md.
1105        browser_subprocess_path: CefString::from(resolve_browser_subprocess_path().as_str()),
1106        ..Default::default()
1107    };
1108
1109    // Initialize CEF.
1110    // CefInitialize returns 1 on success and 0 either on real init failure OR
1111    // on "normal early exit" (process singleton, command-line forward, etc).
1112    // We can only tell the two apart by calling cef_get_exit_code() and
1113    // matching against cef_resultcode_t. Treat NORMAL_EXIT* codes as a clean
1114    // exit; everything else is a real failure that we surface via panic.
1115    // Common early-exit codes (cef_resultcode_t):
1116    //   0  CEF_RESULT_CODE_NORMAL_EXIT
1117    //   24 CEF_RESULT_CODE_NORMAL_EXIT_PROCESS_NOTIFIED  ← singleton relaunch
1118    //   36 CEF_RESULT_CODE_NORMAL_EXIT_PACK_EXTENSION_SUCCESS
1119    //   38 CEF_RESULT_CODE_NORMAL_EXIT_AUTO_DE_ELEVATED
1120    // Live-reportable on every platform: connect_to_launcher (above)
1121    // always runs before cef::initialize, so a launcher connection
1122    // exists by this point wherever one exists at all. No-op if it
1123    // doesn't (dev:standalone, subprocess roles).
1124    let cef_init_started_at = std::time::Instant::now();
1125    launcher_ipc::report_startup_stage_begin("cef_init", "CEF initialize");
1126    #[cfg(target_os = "windows")]
1127    commands::drop_source_wrap::install();
1128    let init_result = initialize(
1129        Some(args.as_main_args()),
1130        Some(&settings),
1131        Some(&mut cef_app),
1132        windows_sandbox_info as *mut u8,
1133    );
1134    if init_result != 1 {
1135        let exit_code = get_exit_code();
1136        // Sidecar was spawned before cef_initialize(); std::process::exit()
1137        // bypasses the normal shutdown block, so kill it here first.
1138        {
1139            let mut sidecar = app_state.sidecar_child.lock();
1140            if let Some(ref mut child) = *sidecar {
1141                tracing::info!("CEF early exit: killing backend sidecar before exit");
1142                let _ = child.kill();
1143            }
1144        }
1145        match exit_code {
1146            0 | 24 | 36 | 38 => {
1147                // `data_dir` (logged once already, above, as "CEF cache
1148                // dir") is the CEF profile directory whose own
1149                // SingletonLock is the most common real cause of this path
1150                // (exit_code 24 specifically = NORMAL_EXIT_PROCESS_NOTIFIED,
1151                // i.e. singleton relaunch) — printing it here turns "why did
1152                // this silently exit" into something directly inspectable
1153                // (e.g. `fuser`/`lsof` on this path) instead of requiring a
1154                // source read to rediscover it. See
1155                // docs/specs/SPEC_DEV_INSTANCE_ISOLATION_DIAGNOSTICS_2026_09_19.md.
1156                tracing::info!(
1157                    exit_code,
1158                    data_dir = %data_dir.display(),
1159                    "CEF early exit (process singleton or similar) — exiting cleanly"
1160                );
1161                std::process::exit(0);
1162            }
1163            _ => {
1164                tracing::error!(
1165                    exit_code,
1166                    "CEF initialization failed; see ~/.agentmux/logs/cef-debug.log for details"
1167                );
1168                // Surface a user-facing error instead of a silent splash-then-exit.
1169                // The most common cause is a bundled CEF runtime whose version does
1170                // not match the linked `cef` crate (e.g. a stale libcef.dll) — that
1171                // path logs "Request for unsupported CEF API version NNNNN" to
1172                // cef-debug.log and would otherwise just vanish after the splash.
1173                // See docs/specs/SPEC_WINDOWS_CEF_BUNDLE_VERSION_INTEGRITY_2026_06_03.md.
1174                #[cfg(target_os = "windows")]
1175                {
1176                    use windows_sys::Win32::UI::WindowsAndMessaging::{
1177                        MessageBoxW, MB_ICONERROR, MB_OK,
1178                    };
1179                    let title: Vec<u16> =
1180                        "AgentMux — startup failed\0".encode_utf16().collect();
1181                    let body = format!(
1182                        "AgentMux couldn't start its browser engine (CEF init failed, code {}).\n\n\
1183                         This usually means the bundled browser runtime is incompatible with this \
1184                         build — for example a stale or mismatched libcef.dll from an incomplete build.\n\n\
1185                         Details were written to:\n    %USERPROFILE%\\.agentmux\\logs\\cef-debug.log\n\n\
1186                         If you built this locally, run:  task clean:cef && task build:host",
1187                        exit_code
1188                    );
1189                    let body_w: Vec<u16> =
1190                        body.encode_utf16().chain(std::iter::once(0)).collect();
1191                    // SAFETY: null parent HWND with valid NUL-terminated wide strings.
1192                    unsafe {
1193                        MessageBoxW(
1194                            std::ptr::null_mut(),
1195                            body_w.as_ptr(),
1196                            title.as_ptr(),
1197                            MB_OK | MB_ICONERROR,
1198                        );
1199                    }
1200                }
1201                // Linux sibling of the Windows MessageBoxW block above — same
1202                // reasoning: the web frontend can't render an error here since
1203                // the host itself failed to start. This is the safety net for
1204                // CEF init failures OTHER than the userns-sandbox-blocked case
1205                // (that one is caught proactively, before ever reaching this
1206                // init call — see the probe near the top of this function).
1207                // Uses zenity/kdialog like linux_sandbox's dialog, but this is
1208                // a plain info dialog (no privileged fix to offer here, unlike
1209                // the userns case — this covers genuinely unknown failures).
1210                #[cfg(target_os = "linux")]
1211                {
1212                    let body = format!(
1213                        "AgentMux couldn't start its browser engine (CEF init failed, code {exit_code}).\n\n\
1214                         Details were written to:\n    ~/.agentmux/logs/cef-debug.log\n\n\
1215                         If this mentions a sandbox/userns/AppArmor error, see docs/linux.md."
1216                    );
1217                    let title = "AgentMux — startup failed";
1218                    let shown = std::process::Command::new("zenity")
1219                        .args(["--error", "--title", title, "--text", &body])
1220                        .status()
1221                        .map(|s| s.success() || s.code() == Some(1)) // zenity --error exits 1 on plain dismiss
1222                        .unwrap_or(false)
1223                        || std::process::Command::new("kdialog")
1224                            .args(["--title", title, "--error", &body])
1225                            .status()
1226                            .map(|s| s.success())
1227                            .unwrap_or(false);
1228                    if !shown {
1229                        eprintln!("{title}\n\n{body}");
1230                    }
1231                }
1232                std::process::exit(exit_code);
1233            }
1234        }
1235    }
1236
1237    launcher_ipc::report_startup_stage_end(
1238        "cef_init",
1239        cef_init_started_at.elapsed().as_millis() as u64,
1240        "ok",
1241        None,
1242    );
1243    let denied = agentmux_common::process_hardening::deny_memory_access(false);
1244    tracing::info!("CEF initialized, entering message loop; memory access denied to other processes: {denied}");
1245    // Claim a Dock tile, THEN paint the icon onto it. A bare Mach-O launched
1246    // outside an `.app` bundle (both `task dev` direct-invoke and the launcher
1247    // flat layout) defaults to a background/accessory activation policy — no
1248    // Dock tile, no menu bar — so the AgentMux instance never shows in the
1249    // taskbar and the icon set below has nothing to land on. Force
1250    // NSApplicationActivationPolicyRegular first so the instance is a normal,
1251    // Dock-visible app. macOS-only; no-op elsewhere. Order matters: policy
1252    // before icon.
1253    #[cfg(target_os = "macos")]
1254    unsafe {
1255        // Friendly Dock + app-menu name ("AgentMux DEV" in dev) instead of the
1256        // raw process name "agentmux-cef". Done POST-init: Chromium overwrites
1257        // the process name during cef::initialize, so a pre-init set didn't
1258        // stick — set it here, right before the activation policy + our menu
1259        // bar are established.
1260        macos_compat::set_macos_app_display_name();
1261        macos_compat::set_macos_activation_policy_regular();
1262        macos_compat::set_macos_dock_icon();
1263        // Layer 1 of SPEC_MACOS_ACCESSIBILITY_ROBUSTNESS_2026-06-03: govern
1264        // Chromium's macOS accessibility activation so a window manager / KVM
1265        // poking the AX tree (Magnet, Synergy, …) can't force the crash-prone
1266        // web-content AX mode (CEF #3512). Must run after cef::initialize so
1267        // the CEF NSApplication subclass (which owns the legacy AX setter)
1268        // exists.
1269        macos_compat::install_macos_accessibility_governor();
1270    }
1271
1272    // Native macOS menu bar (File/Edit/View/Window/Help) — Phase 1 of
1273    // SPEC_MACOS_NATIVE_MENU_BAR_2026-06-03. After cef::initialize (NSApplication
1274    // exists) and after set_macos_app_display_name (the app-menu title follows
1275    // the process name). Standard Edit/Window items route to the focused web
1276    // view; custom items dispatch through the frontend command registry.
1277    #[cfg(target_os = "macos")]
1278    macos_menu::install_menu_bar(app_state.clone());
1279
1280    // Reopen handler — a plain re-launch / Finder/Dock double-click of the
1281    // running app opens a new window (Windows-parity) instead of just focusing
1282    // it. Installs an NSApplication delegate (`applicationShouldHandleReopen:`);
1283    // a raw NSAppleEventManager handler was inert because CEF re-registers its
1284    // own. After menu install, NSApplication exists.
1285    // SPEC_MACOS_LAUNCH_COHERENCE_2026_06_18.md.
1286    #[cfg(target_os = "macos")]
1287    macos_menu::install_reopen_handler(app_state.clone());
1288
1289    // Start memory heartbeat — logs system/process memory stats every 20s.
1290    // Provides forensic data if the process later crashes from OOM / VA
1291    // exhaustion, and drives the debounced mem_pressure level + low-memory
1292    // banner (SPEC_MEMORY_PRESSURE_SUPERVISION_2026_06_16 §5.A/§5.F).
1293    memory_heartbeat::start(app_state.clone());
1294
1295    // Phase B.6 (post-fix): publish port:token AFTER CEF init so a
1296    // second launcher only forwards `open_new_window` when we're
1297    // actually ready to handle it. Single-instance enforcement is
1298    // the launcher's named-pipe bind — this file is purely a
1299    // forwarding hint.
1300    ipc_forward::publish_port_file(&port_file, ipc_port);
1301
1302    // Phase B.9.1 (WRR) — install Win32 event hooks. Must come
1303    // AFTER `connect_to_launcher` so the report_hwnd_* sync APIs
1304    // have a live `COMMAND_TX` to push into; AFTER CEF init so
1305    // any HWNDs CEF creates during initialize() are missed
1306    // (acceptable — they predate the user's session and are
1307    // accounted for by main-window startup paths). Idempotent;
1308    // safe to call multiple times. State arg lets the callback
1309    // peek `pending_window_creations` for `label_hint`.
1310    wrr::install_hooks(app_state.clone());
1311
1312    // Run the CEF message loop. This blocks until quit_message_loop() is called
1313    // (triggered when all browser windows are closed in client.rs).
1314    run_message_loop();
1315
1316    tracing::info!("CEF message loop exited, shutting down");
1317    commands::vault::clear_clipboard_on_shutdown();
1318
1319    // Kill the backend sidecar. (The launcher's Job Object also reaps it once
1320    // we exit; kill explicitly for promptness.)
1321    {
1322        let mut sidecar = app_state.sidecar_child.lock();
1323        if let Some(ref mut child) = *sidecar {
1324            tracing::info!("Killing backend sidecar");
1325            let _ = child.kill();
1326        }
1327    }
1328
1329    // Phase B.6 (post-fix): clean up the forwarding hint so a stale file doesn't
1330    // survive a graceful exit. (Hard crashes leave it behind; harmless because
1331    // pipe-bind on next launch is authoritative.)
1332    let _ = std::fs::remove_file(&port_file);
1333
1334    // Reaching here means run_message_loop() returned, which ONLY happens on the
1335    // intended LastWindowClosed quit — so a hard exit(0) is correct here, NOT a
1336    // crash. It is also NECESSARY. After a CEF Views last-window close the
1337    // browsers are HIDDEN/recycled (the close never fires on_before_close), so
1338    // they're still alive at shutdown; CEF's teardown then access-violates on
1339    // Windows (`cef::shutdown()` / `UnhookWinEvent`, exit 0xC0000005) and wedges
1340    // in the tokio runtime drop on macOS. Either way the launcher (which
1341    // classifies host exit) sees an ABNORMAL exit and RELAUNCHES the instance —
1342    // the "reopens on its own" symptom (Discussion #1680). exit(0) gives the
1343    // launcher a clean code-0 shutdown; it reaps the host's children via its Job
1344    // Object (KILL_ON_JOB_CLOSE).
1345    // Unhook the Win32 event hooks before exit (no-op off Windows; a cheap,
1346    // safe UnhookWinEvent — NOT a crash site).
1347    wrr::uninstall_hooks();
1348    #[cfg(target_os = "macos")]
1349    {
1350        // macOS keeps the prior sequence (works): cef::shutdown() then a
1351        // non-blocking runtime teardown (#1268).
1352        shutdown();
1353        runtime.shutdown_background();
1354    }
1355    #[cfg(not(target_os = "macos"))]
1356    {
1357        // Windows/Linux: SKIP cef::shutdown() — the Windows crash site on the
1358        // still-alive recycled browsers. Drop the tokio runtime (safe +
1359        // non-blocking here) before the hard exit.
1360        drop(runtime);
1361    }
1362    tracing::info!("AgentMux host shutdown complete (fast exit)");
1363
1364    // On Windows, hard-terminate so the C-runtime / CEF-DLL static teardown
1365    // (atexit handlers + DLL_PROCESS_DETACH) does NOT run: with the recycled
1366    // browsers still alive, that teardown raises a fail-fast (exit 0xC0000602)
1367    // even though we reached this line, which the launcher classifies as an
1368    // ABNORMAL exit and RELAUNCHES ("reopens on its own"). `std::process::exit`
1369    // still runs that cleanup, so use `TerminateProcess(self, 0)` for an
1370    // immediate, clean code-0 termination; the launcher then shuts down and
1371    // reaps the host's children via its Job Object. See Discussion #1680.
1372    #[cfg(target_os = "windows")]
1373    unsafe {
1374        use windows_sys::Win32::System::Threading::{GetCurrentProcess, TerminateProcess};
1375        TerminateProcess(GetCurrentProcess(), 0);
1376    }
1377    std::process::exit(0)
1378}
1379
1380/// Windows DLL wrapper sandbox entry point (Phase 3, issue #1374).
1381///
1382/// `bootstrap.exe` (renamed `agentmux-cef.exe`) calls this after:
1383///   1. `cef_sandbox_info_create()` → `sandbox_info`
1384///   2. `LoadLibraryW("agentmux-cef.dll")` → this DLL
1385///   3. `GetProcAddress(hDll, "RunWinMain")` → this function
1386///
1387/// We forward `sandbox_info` into `run()` so CEF's `CefExecuteProcess` and
1388/// `CefInitialize` receive the pre-initialized sandbox context.
1389#[cfg(all(target_os = "windows", feature = "sandbox"))]
1390#[no_mangle]
1391pub unsafe extern "system" fn RunWinMain(
1392    _h_instance:   windows_sys::Win32::Foundation::HINSTANCE,
1393    _lp_cmd_line:  *mut u16,
1394    _n_cmd_show:   i32,
1395    sandbox_info:  *mut std::ffi::c_void,
1396    _version_info: *mut std::ffi::c_void,
1397) -> i32 {
1398    run(sandbox_info)
1399}
1400
1401/// Which directory the host publishes its `ipc-port-<hash>` file into.
1402///
1403/// This MUST agree with where the launcher reads it — `paths.data_dir`, used by
1404/// `second_instance::forward_host_cmd` (single-instance window forwarding) and
1405/// by `tray::windows::service_reachable` (the tray's running-indicator). When the
1406/// two diverge the failure is silent: forwarding reports a transient read error
1407/// and the tray icon simply claims the service is down forever.
1408///
1409/// The deciding factor is **whether a launcher spawned us**, not whether this
1410/// is a dev build. `AGENTMUX_IPC_HASH` is set by the launcher and by nothing
1411/// else (`supervisor/windows.rs`, `supervisor/unix.rs`), and whenever it is
1412/// set, `AGENTMUX_DATA_DIR` came from that same launcher via
1413/// `paths.common.to_env_vars()` — so it is that instance's own data dir, not
1414/// some other instance's.
1415///
1416/// Keying on `is_dev_build_exe` instead was wrong, on a premise stated in the
1417/// old comment: "in dev mode there is no launcher". `task dev` DOES run the
1418/// launcher — only `task dev:standalone` bypasses it. So a dev build under a
1419/// launcher wrote the port file to its host-local data dir while the launcher
1420/// looked in the instance data dir, and the tray indicator was stuck at "not
1421/// running" for the whole session. Verified live, not theorised: the file
1422/// landed in `<instance>/cef-cache/` while the tray probed `<instance>/data/`.
1423///
1424/// The parent-pane hazard the old branch guarded against is still guarded:
1425/// with no launcher there is no `AGENTMUX_IPC_HASH`, so a dev build falls
1426/// through to its own data dir and cannot clobber the port file of the parent
1427/// AgentMux instance whose env it inherited.
1428fn port_file_dir(
1429    launcher_managed: bool,
1430    env_data_dir: Option<std::path::PathBuf>,
1431    is_dev_build: bool,
1432    host_data_dir: &std::path::Path,
1433) -> std::path::PathBuf {
1434    match (launcher_managed, env_data_dir) {
1435        // A launcher spawned us: its data dir is authoritative, dev or not.
1436        (true, Some(dir)) => dir,
1437        // No launcher (or it told us nothing): a dev build must not touch the
1438        // inherited parent instance's port file.
1439        (_, inherited) => {
1440            if is_dev_build {
1441                host_data_dir.to_path_buf()
1442            } else {
1443                inherited.unwrap_or_else(|| host_data_dir.to_path_buf())
1444            }
1445        }
1446    }
1447}
1448
1449#[cfg(test)]
1450mod port_file_dir_tests {
1451    use super::port_file_dir;
1452    use std::path::{Path, PathBuf};
1453
1454    fn p(s: &str) -> PathBuf {
1455        PathBuf::from(s)
1456    }
1457
1458    /// The bug this function exists to fix. Under `task dev` a launcher IS
1459    /// present, so the port file must go where the launcher reads it —
1460    /// otherwise the tray's running-indicator is stuck false forever.
1461    #[test]
1462    fn a_dev_build_under_a_launcher_writes_where_the_launcher_reads() {
1463        assert_eq!(
1464            port_file_dir(
1465                true,
1466                Some(p("/instance/data")),
1467                true,
1468                Path::new("/instance/cef-cache")
1469            ),
1470            p("/instance/data")
1471        );
1472    }
1473
1474    /// The hazard the old dev branch was protecting against, kept intact:
1475    /// `dev:standalone` inherits the PARENT instance's `AGENTMUX_DATA_DIR`, and
1476    /// writing there would break that parent's single-instance forwarding.
1477    #[test]
1478    fn a_standalone_dev_build_does_not_clobber_the_parent_instances_port_file() {
1479        assert_eq!(
1480            port_file_dir(false, Some(p("/parent/data")), true, Path::new("/dev/cef-cache")),
1481            p("/dev/cef-cache")
1482        );
1483    }
1484
1485    #[test]
1486    fn a_release_build_uses_the_launcher_supplied_data_dir() {
1487        assert_eq!(
1488            port_file_dir(true, Some(p("/prod/data")), false, Path::new("/prod/cef-cache")),
1489            p("/prod/data")
1490        );
1491    }
1492
1493    /// An absent/empty `AGENTMUX_IPC_HASH` means no launcher, so a release
1494    /// build still honours an inherited data dir rather than losing it.
1495    #[test]
1496    fn a_release_build_without_a_launcher_still_honours_the_env_data_dir() {
1497        assert_eq!(
1498            port_file_dir(false, Some(p("/prod/data")), false, Path::new("/prod/cef-cache")),
1499            p("/prod/data")
1500        );
1501    }
1502
1503    #[test]
1504    fn nothing_configured_falls_back_to_the_host_data_dir() {
1505        assert_eq!(port_file_dir(true, None, false, Path::new("/fallback")), p("/fallback"));
1506        assert_eq!(port_file_dir(false, None, true, Path::new("/fallback")), p("/fallback"));
1507    }
1508}