Skip to main content

rightkit_browser/
session.rs

1use crate::cdp_ext::{DownloadBehavior, RequestInterceptor};
2use crate::config::{
3    reject_real_browser_profile, resolve_executable, validate_extra_args, validate_profile_dir,
4    validate_profile_name, LaunchOptions, ProfileSpec,
5};
6use crate::error::{cdp, BrowserError, Result};
7use crate::fixture_protocol::FixtureError;
8use crate::page::BrowserPage;
9#[cfg(target_os = "macos")]
10use crate::policy::NetworkPolicy;
11use crate::policy::{Guard, LifecycleKind};
12use crate::proc::ChromeProc;
13use crate::proxy::{FixtureProxyPolicy, PinProxy, PinnedConnection};
14use chromiumoxide::browser::Browser;
15use chromiumoxide::cdp::browser_protocol::browser::{
16    PermissionDescriptor, PermissionSetting, ResetPermissionsParams, SetDownloadBehaviorBehavior,
17    SetDownloadBehaviorParams, SetPermissionParams,
18};
19use chromiumoxide::handler::HandlerConfig;
20use futures::StreamExt;
21use std::collections::HashSet;
22use std::ffi::OsString;
23use std::path::{Path, PathBuf};
24use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
25use std::sync::{Arc, Mutex as StdMutex};
26use std::time::{Duration, Instant};
27use tokio::sync::Mutex;
28use tokio::task::JoinHandle;
29
30static SESSION_SEQ: AtomicU64 = AtomicU64::new(0);
31
32/// Per-step wait before escalating a close (CDP -> SIGTERM -> SIGKILL).
33const GRACE: Duration = Duration::from_secs(5);
34const FIXTURE_STOP_RECEIPT_GRACE: Duration = Duration::from_secs(12);
35
36#[cfg(windows)]
37#[derive(Clone, Copy)]
38enum FixtureBackend {
39    WinAppcontainer,
40}
41
42enum ProfileGuard {
43    Temp(#[allow(dead_code)] tempfile::TempDir),
44    Named {
45        _lock: std::fs::File,
46    },
47    /// Caller-owned directory: dropping this guard has no filesystem effects.
48    Existing,
49    /// Encrypted persistent profile: sealed and the plaintext wiped on release.
50    #[cfg(feature = "profile-vault")]
51    Vault(crate::vault::VaultLease),
52}
53
54struct FixtureLaunchState {
55    process: Arc<StdMutex<Option<ChromeProc>>>,
56    profile: StdMutex<Option<ProfileGuard>>,
57    proxy: StdMutex<Option<PinProxy>>,
58    spawn_complete: tokio::sync::watch::Sender<u8>,
59    armed: AtomicBool,
60    cleanup_started: AtomicBool,
61}
62
63struct FixtureLaunchOwner {
64    state: Arc<FixtureLaunchState>,
65}
66
67struct SpawnCompleteGuard {
68    state: Option<Arc<FixtureLaunchState>>,
69    result: u8,
70}
71
72struct FixtureStopCompletionGuard {
73    status: tokio::sync::watch::Sender<u8>,
74    complete: bool,
75}
76
77impl Drop for SpawnCompleteGuard {
78    fn drop(&mut self) {
79        if let Some(state) = &self.state {
80            state.spawn_complete.send_replace(self.result);
81        }
82    }
83}
84
85impl FixtureStopCompletionGuard {
86    fn stopped(&mut self) {
87        self.status.send_replace(2);
88        self.complete = true;
89    }
90}
91
92impl Drop for FixtureStopCompletionGuard {
93    fn drop(&mut self) {
94        if !self.complete {
95            self.status.send_replace(3);
96        }
97    }
98}
99
100impl FixtureLaunchOwner {
101    fn new(profile: ProfileGuard, proxy: Option<PinProxy>) -> Self {
102        let (spawn_complete, _) = tokio::sync::watch::channel(0u8);
103        Self {
104            state: Arc::new(FixtureLaunchState {
105                process: Arc::new(StdMutex::new(None)),
106                profile: StdMutex::new(Some(profile)),
107                proxy: StdMutex::new(proxy),
108                spawn_complete,
109                armed: AtomicBool::new(true),
110                cleanup_started: AtomicBool::new(false),
111            }),
112        }
113    }
114
115    fn process_slot(&self) -> Arc<StdMutex<Option<ChromeProc>>> {
116        self.state.process.clone()
117    }
118
119    fn spawn_state(&self) -> Arc<FixtureLaunchState> {
120        self.state.clone()
121    }
122
123    fn into_parts(
124        self,
125    ) -> (
126        Arc<StdMutex<Option<ChromeProc>>>,
127        ProfileGuard,
128        Option<PinProxy>,
129    ) {
130        self.state.armed.store(false, Ordering::SeqCst);
131        let profile = self.state.profile.lock().unwrap().take().unwrap();
132        let proxy = self.state.proxy.lock().unwrap().take();
133        (self.state.process.clone(), profile, proxy)
134    }
135}
136
137impl FixtureLaunchState {
138    async fn cleanup(self: Arc<Self>) {
139        let mut complete = self.spawn_complete.subscribe();
140        while *complete.borrow() == 0 {
141            if complete.changed().await.is_err() {
142                self.keep_profile();
143                return;
144            }
145        }
146
147        let process = self
148            .process
149            .lock()
150            .unwrap_or_else(|error| error.into_inner())
151            .take();
152        let spawn_status = *complete.borrow();
153        let process_stopped = match (spawn_status, process) {
154            (_, Some(mut process)) => {
155                process.begin_fixture_transport_shutdown();
156                let terminated = tokio::task::spawn_blocking(move || {
157                    let result = process.terminate_fixture_tree();
158                    (process, result)
159                })
160                .await;
161                let Ok((process, result)) = terminated else {
162                    return self.keep_profile();
163                };
164                if result.is_err() {
165                    *self
166                        .process
167                        .lock()
168                        .unwrap_or_else(|error| error.into_inner()) = Some(process);
169                    false
170                } else {
171                    #[cfg(windows)]
172                    {
173                        let mut process = process;
174                        if process
175                            .finish_fixture_transport_shutdown(Instant::now() + GRACE)
176                            .await
177                            .is_err()
178                        {
179                            *self
180                                .process
181                                .lock()
182                                .unwrap_or_else(|error| error.into_inner()) = Some(process);
183                            false
184                        } else {
185                            true
186                        }
187                    }
188                    #[cfg(not(windows))]
189                    {
190                        true
191                    }
192                }
193            }
194            (2, None) => true,
195            (_, None) => false,
196        };
197        if !process_stopped {
198            self.keep_profile();
199            return;
200        }
201
202        let proxy = self
203            .proxy
204            .lock()
205            .unwrap_or_else(|error| error.into_inner())
206            .take();
207        let proxy_stopped = match proxy {
208            Some(proxy) => proxy.shutdown(GRACE).await.is_ok(),
209            None => true,
210        };
211        if proxy_stopped {
212            let _ = release_profile(
213                self.profile
214                    .lock()
215                    .unwrap_or_else(|error| error.into_inner())
216                    .take(),
217            );
218        } else {
219            self.keep_profile();
220        }
221    }
222
223    fn keep_profile(&self) {
224        if let Some(ProfileGuard::Temp(profile)) = self
225            .profile
226            .lock()
227            .unwrap_or_else(|error| error.into_inner())
228            .take()
229        {
230            let _ = profile.keep();
231        }
232    }
233}
234
235impl Drop for FixtureLaunchOwner {
236    fn drop(&mut self) {
237        if !self.state.armed.load(Ordering::SeqCst)
238            || self.state.cleanup_started.swap(true, Ordering::SeqCst)
239        {
240            return;
241        }
242        let state = self.state.clone();
243        if let Ok(runtime) = tokio::runtime::Handle::try_current() {
244            runtime.spawn(state.cleanup());
245        } else {
246            if *self.state.spawn_complete.subscribe().borrow() == 0 {
247                self.state.keep_profile();
248                return;
249            }
250            let process = self
251                .state
252                .process
253                .lock()
254                .unwrap_or_else(|error| error.into_inner())
255                .take();
256            let spawn_status = *self.state.spawn_complete.subscribe().borrow();
257            let process_stopped = match (spawn_status, process) {
258                (_, Some(mut process)) => process.terminate_fixture_tree().is_ok(),
259                (2, None) => true,
260                (_, None) => false,
261            };
262            if process_stopped {
263                #[cfg(windows)]
264                {
265                    // No async runtime means bridge finalization cannot obtain its
266                    // inertness receipt. Keep profile evidence instead of claiming
267                    // an unverified cleanup path.
268                    self.state.keep_profile();
269                }
270                #[cfg(not(windows))]
271                {
272                    self.state
273                        .proxy
274                        .lock()
275                        .unwrap_or_else(|error| error.into_inner())
276                        .take();
277                    let _ = release_profile(
278                        self.state
279                            .profile
280                            .lock()
281                            .unwrap_or_else(|error| error.into_inner())
282                            .take(),
283                    );
284                }
285            } else {
286                self.state.keep_profile();
287            }
288        }
289    }
290}
291
292/// Remove the session's profile. A temporary profile is deleted with bounded retries:
293/// on Windows a just-terminated helper can hold a handle for a moment after its job ends.
294///
295/// An encrypted profile is sealed and its plaintext working directory wiped; the result says
296/// whether that succeeded (on failure the tree stays for the next start's recovery).
297fn release_profile(guard: Option<ProfileGuard>) -> Result<()> {
298    match guard {
299        Some(ProfileGuard::Temp(dir)) => {
300            let path = dir.path().to_path_buf();
301            drop(dir);
302            let deadline = std::time::Instant::now() + Duration::from_secs(3);
303            while path.exists()
304                && std::fs::remove_dir_all(&path).is_err()
305                && std::time::Instant::now() < deadline
306            {
307                std::thread::sleep(Duration::from_millis(100));
308            }
309            if path.exists() {
310                return Err(BrowserError::Profile(format!(
311                    "temporary profile still exists after removal: {}",
312                    path.display()
313                )));
314            }
315            Ok(())
316        }
317        #[cfg(feature = "profile-vault")]
318        Some(ProfileGuard::Vault(mut lease)) => lease.seal_and_wipe().map_err(BrowserError::from),
319        _ => Ok(()),
320    }
321}
322
323fn lock_named_profile(root: &Path, name: &str) -> Result<(ProfileGuard, PathBuf, PathBuf)> {
324    validate_profile_name(name)?;
325    reject_real_browser_profile(root)?;
326    let dir = root.join(name);
327    std::fs::create_dir_all(&dir)?;
328    let lock = std::fs::OpenOptions::new()
329        .create(true)
330        .write(true)
331        .truncate(false)
332        .open(dir.join(".rightkit-browser.lock"))?;
333    match lock.try_lock() {
334        Ok(()) => {}
335        Err(std::fs::TryLockError::WouldBlock) => {
336            return Err(BrowserError::ProfileInUse(name.to_string()));
337        }
338        Err(std::fs::TryLockError::Error(e)) => return Err(e.into()),
339    }
340    let dl = dir.join("rightkit-downloads");
341    Ok((ProfileGuard::Named { _lock: lock }, dir, dl))
342}
343
344fn prepare_profile(profile: &ProfileSpec) -> Result<(ProfileGuard, PathBuf, PathBuf)> {
345    match profile {
346        ProfileSpec::Temporary => {
347            let t = tempfile::tempdir()?;
348            let p = t.path().to_path_buf();
349            let dl = p.join("downloads");
350            Ok((ProfileGuard::Temp(t), p, dl))
351        }
352        ProfileSpec::Named { root, name } => lock_named_profile(root, name),
353        ProfileSpec::ImportedFrom { root, name, import } => {
354            // Consent is checked before any directory is created or browser data is read.
355            import.validate()?;
356            let locked = lock_named_profile(root, name)?;
357            crate::real_session::import_if_needed(import, &locked.1)?;
358            Ok(locked)
359        }
360        #[cfg(feature = "profile-vault")]
361        ProfileSpec::Encrypted(vault) => {
362            let lease = vault.open()?;
363            let dir = lease.work_dir().to_path_buf();
364            Ok((ProfileGuard::Vault(lease), dir, vault.downloads_dir()))
365        }
366        ProfileSpec::Directory(path) => {
367            validate_profile_dir(path)?;
368            Ok((
369                ProfileGuard::Existing,
370                path.clone(),
371                path.join("rightkit-downloads"),
372            ))
373        }
374    }
375}
376
377/// What to install on a page before its first navigation; see `BrowserSession::new_page_with`.
378#[derive(Default)]
379pub struct PageSetup {
380    /// Request interceptor (see `BrowserPage::set_request_interceptor`).
381    pub interceptor: Option<RequestInterceptor>,
382    /// Download behaviour (see `BrowserPage::set_download_behavior`).
383    pub download: Option<DownloadBehavior>,
384}
385
386/// One Chrome process with any number of pages.
387pub struct BrowserSession {
388    id: String,
389    browser: Mutex<Browser>,
390    pages: StdMutex<Vec<Arc<BrowserPage>>>,
391    current: StdMutex<Option<String>>,
392    page_seq: AtomicU64,
393    handler: StdMutex<Option<JoinHandle<()>>>,
394    watcher: StdMutex<Option<JoinHandle<()>>>,
395    /// Released (temporary profile deleted) once Chrome has exited, on shutdown or drop.
396    profile_guard: StdMutex<Option<ProfileGuard>>,
397    profile_dir: PathBuf,
398    fixture_profile_path: Option<PathBuf>,
399    download_dir: PathBuf,
400    upload_root: Option<PathBuf>,
401    headless: bool,
402    guard: Arc<Guard>,
403    pid: Option<u32>,
404    proc: Arc<StdMutex<Option<ChromeProc>>>,
405    fixture_stop_status: tokio::sync::watch::Sender<u8>,
406    fixture_stop_failure: Arc<StdMutex<Option<String>>>,
407    fixture_stop_lock: Mutex<()>,
408    proxy: Option<PinProxy>,
409    /// Set before an intentional stop so the CDP pump does not report a crash.
410    stopping: Arc<AtomicBool>,
411    stopped: AtomicBool,
412    fixture_mode: bool,
413    #[cfg(windows)]
414    fixture_backend: Option<FixtureBackend>,
415}
416
417/// Internal terminal outcome of stopping a session; see [`StopReport`].
418struct Stopped {
419    process_error: Option<String>,
420    profile: Result<()>,
421}
422
423impl Stopped {
424    fn into_report(self) -> StopReport {
425        StopReport {
426            process_stopped: self.process_error.is_none(),
427            process_error: self.process_error,
428            profile_released: self.profile.is_ok(),
429            profile_error: self.profile.err().map(|error| error.to_string()),
430        }
431    }
432}
433
434/// What stopping a session actually achieved, step by step (see
435/// [`BrowserSession::shutdown_report`]).
436#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
437#[serde(rename_all = "camelCase")]
438pub struct StopReport {
439    /// Chrome's process tree (and, on Unix, its watchdog) terminated without error.
440    pub process_stopped: bool,
441    pub process_error: Option<String>,
442    /// The profile was released: temporary profile deleted, encrypted profile sealed and its
443    /// plaintext wiped. Also true when there was nothing to release (named or caller-owned
444    /// directory, or already released).
445    pub profile_released: bool,
446    pub profile_error: Option<String>,
447}
448
449/// Flags every session launch starts from, before profile, viewport, proxy and caller flags.
450const BASE_CHROME_ARGS: &[&str] = &[
451    "--remote-debugging-port=0",
452    "--no-first-run",
453    "--no-default-browser-check",
454    "--disable-background-networking",
455    // Chrome's own traffic: the component updater (clients2.google.com) still runs
456    // with background networking off, and a session must see only its pages' requests.
457    "--disable-component-update",
458    "--disable-domain-reliability",
459    "--no-pings",
460    "--disable-background-timer-throttling",
461    "--disable-backgrounding-occluded-windows",
462    "--disable-breakpad",
463    "--disable-client-side-phishing-detection",
464    "--disable-component-extensions-with-background-pages",
465    "--disable-default-apps",
466    "--disable-dev-shm-usage",
467    "--disable-extensions",
468    "--disable-hang-monitor",
469    "--disable-ipc-flooding-protection",
470    "--disable-prompt-on-repost",
471    "--disable-renderer-backgrounding",
472    "--disable-sync",
473    "--force-color-profile=srgb",
474    "--metrics-recording-only",
475    // No `--use-mock-keychain` and no `--password-store=basic` (rightkit#1306, Adrian: no mocks,
476    // real data): Chrome uses the real OS credential store for its own cookie and password
477    // encryption.
478    // No unmanaged windows: a pop-up would be a page the policy never saw.
479    "--block-new-web-contents",
480];
481
482impl BrowserSession {
483    pub async fn launch(opts: LaunchOptions) -> Result<Self> {
484        Self::launch_inner(opts, None).await
485    }
486
487    /// Start a visible session that reuses the user's own browser sign-ins, with consent.
488    ///
489    /// Chrome 136+ ignores a debugging port on the browser's default user-data directory and a
490    /// profile in use is locked, so the user's running browser is not driven in place: the
491    /// consented profile's sign-in files are copied into a private RightKit profile under `root`
492    /// and the same browser (same executable, so its sign-in key applies) is launched on that
493    /// copy over a debugging pipe. The consented domains confine every action, passwords are
494    /// refused, and `consent` is checked at launch and before each action.
495    ///
496    /// Chromium-family browsers only (Chrome, Edge, Brave, Chromium); Safari and Firefox return
497    /// [`BrowserError::Unsupported`]. `opts` supplies timeouts, network policy and the admission
498    /// hook (which runs after the consent check); its profile, executable and window mode are
499    /// replaced.
500    pub async fn attach_user_browser(
501        consent: crate::real_session::UserConsentReceipt,
502        root: impl Into<PathBuf>,
503        opts: LaunchOptions,
504    ) -> Result<Self> {
505        Self::attach_user_browser_revocable(
506            consent,
507            crate::real_session::ConsentRevocation::new(),
508            root,
509            opts,
510        )
511        .await
512    }
513
514    /// [`Self::attach_user_browser`] with a live [`crate::ConsentRevocation`]: revoking it
515    /// makes the session's next action fail.
516    pub async fn attach_user_browser_revocable(
517        consent: crate::real_session::UserConsentReceipt,
518        revocation: crate::real_session::ConsentRevocation,
519        root: impl Into<PathBuf>,
520        mut opts: LaunchOptions,
521    ) -> Result<Self> {
522        use crate::real_session::{
523            attach_profile_name, browser_executable, BrowserKind, BrowserSource, ImportSpec,
524        };
525        consent.check_active()?;
526        let source = match consent.browser {
527            BrowserKind::Chrome => BrowserSource::Chrome,
528            BrowserKind::Edge => BrowserSource::Edge,
529            BrowserKind::Safari | BrowserKind::Firefox => {
530                return Err(BrowserError::Unsupported(format!(
531                    "{} cannot be attached over CDP; drive it through rightkit-automation",
532                    consent.browser.name()
533                )));
534            }
535            other => {
536                return Err(BrowserError::Unsupported(format!(
537                    "attach supports Chrome and Edge; {} is not covered yet",
538                    other.name()
539                )));
540            }
541        };
542        let exe = browser_executable(consent.browser).ok_or(BrowserError::ChromeNotFound)?;
543        let name = attach_profile_name(&consent);
544        let import = ImportSpec {
545            browser: source,
546            source_profile: Some(consent.profile.clone()),
547            domains: consent.domains.clone(),
548            consent,
549            revocation,
550            reimport: false,
551        };
552        opts.chrome_path = Some(exe);
553        opts.use_system_chrome_only = false;
554        opts.allow_system_chrome = false;
555        opts.headless = false;
556        opts.profile = ProfileSpec::ImportedFrom {
557            root: root.into(),
558            name,
559            import,
560        };
561        Self::launch(opts).await
562    }
563
564    /// Launch the sealed source-only fixture browser. This private constructor fixes every
565    /// option that could widen authority and installs the fixture-only network policy.
566    pub(crate) async fn launch_fixture(
567        policy: FixtureProxyPolicy,
568    ) -> std::result::Result<Self, FixtureError> {
569        #[cfg(not(any(target_os = "macos", windows)))]
570        #[allow(clippy::needless_return)]
571        {
572            let _ = policy;
573            return Err(FixtureError::ConfinementUnsupported(
574                "source-only browser fixtures require macOS Seatbelt confinement".into(),
575            ));
576        }
577        #[cfg(target_os = "macos")]
578        {
579            use crate::policy::{AddressClass, PolicyDecision};
580            let permitted_urls = policy.permitted_urls.clone();
581            let remaining = policy.expires_at.saturating_duration_since(Instant::now());
582            if remaining.is_zero() {
583                return Err(FixtureError::Revoked(
584                    "fixture lease expired before browser launch".into(),
585                ));
586            }
587            let opts = LaunchOptions {
588                headless: true,
589                mute_audio: true,
590                profile: ProfileSpec::Temporary,
591                chrome_path: None,
592                allow_system_chrome: false,
593                use_system_chrome_only: false,
594                extra_args: Vec::new(),
595                download_dir: None,
596                upload_root: None,
597                network: NetworkPolicy::default()
598                    .allow_class(AddressClass::Loopback)
599                    .allow_with(move |request| {
600                        if permitted_urls.contains(&request.url) {
601                            PolicyDecision::Allow
602                        } else {
603                            PolicyDecision::Deny(
604                                "fixture URL is outside the immutable bundle".into(),
605                            )
606                        }
607                    }),
608                launch_timeout: remaining,
609                request_timeout: remaining.min(Duration::from_secs(5)),
610                ..Default::default()
611            };
612            Self::launch_inner(opts, Some(policy))
613                .await
614                .map_err(|error| FixtureError::ConfinementUnavailable(error.to_string()))
615        }
616        #[cfg(windows)]
617        {
618            let remaining = policy.expires_at.saturating_duration_since(Instant::now());
619            if remaining.is_zero() {
620                return Err(FixtureError::Revoked(
621                    "fixture lease expired before browser launch".into(),
622                ));
623            }
624            // AppContainer denies all network. CDP uses inherited pipes, while
625            // Fetch fulfills immutable fixture bytes without a TCP proxy.
626            let opts = LaunchOptions {
627                headless: true,
628                mute_audio: true,
629                profile: ProfileSpec::Temporary,
630                chrome_path: None,
631                allow_system_chrome: false,
632                use_system_chrome_only: false,
633                extra_args: Vec::new(),
634                download_dir: None,
635                upload_root: None,
636                network: crate::policy::NetworkPolicy::unrestricted(),
637                launch_timeout: remaining,
638                request_timeout: remaining.min(Duration::from_secs(5)),
639                ..Default::default()
640            };
641            Self::launch_inner(opts, Some(policy))
642                .await
643                .map_err(|error| FixtureError::ConfinementUnavailable(error.to_string()))
644        }
645    }
646
647    async fn launch_inner(
648        #[cfg_attr(not(windows), allow(unused_mut))] mut opts: LaunchOptions,
649        fixture_proxy_policy: Option<FixtureProxyPolicy>,
650    ) -> Result<Self> {
651        validate_extra_args(&opts.extra_args)?;
652        let exe = resolve_executable(&opts)?;
653        // A sandbox that cannot read its own browser crashes the network service at startup;
654        // refuse that launch with the directory and the fix instead of a browser that hangs.
655        let sandboxed = !opts
656            .extra_args
657            .iter()
658            .any(|arg| arg.trim_start_matches('-') == "no-sandbox");
659        if sandboxed {
660            if let Some(missing) = crate::sandbox_access::missing_access(&exe) {
661                return Err(BrowserError::ChromeSandboxAccess {
662                    fix: crate::sandbox_access::grant_command(&missing.directory),
663                    directory: missing.directory,
664                    principals: missing.principals,
665                });
666            }
667        }
668        let (profile, profile_dir, default_dl) = prepare_profile(&opts.profile)?;
669        // A consented real-session profile confines every action to the consented domains.
670        let admission = match &opts.profile {
671            ProfileSpec::ImportedFrom { import, .. } => Some(
672                crate::real_session::scoped_admission(import, opts.admission.clone())?,
673            ),
674            _ => opts.admission.clone(),
675        };
676        let mut profile_guard = Some(profile);
677        let download_dir = opts.download_dir.clone().unwrap_or(default_dl);
678        std::fs::create_dir_all(&download_dir)?;
679
680        let id = format!("bs-{}", SESSION_SEQ.fetch_add(1, Ordering::Relaxed));
681        let guard = Arc::new(Guard {
682            session_id: id.clone(),
683            admission,
684            network: opts.network.clone(),
685            events: opts.on_event.clone(),
686            page_allowed: StdMutex::default(),
687        });
688        let fixture_mode = fixture_proxy_policy.is_some();
689        #[cfg(windows)]
690        let fixture_backend = fixture_mode.then_some(FixtureBackend::WinAppcontainer);
691        #[cfg(windows)]
692        let windows_fixture = matches!(fixture_backend, Some(FixtureBackend::WinAppcontainer));
693        #[cfg(not(windows))]
694        let windows_fixture = false;
695        let mut proxy = if let Some(policy) = fixture_proxy_policy {
696            if windows_fixture {
697                None
698            } else {
699                Some(
700                    PinProxy::start_fixture(guard.clone(), policy)
701                        .await
702                        .map_err(|error| {
703                            BrowserError::Launch(format!("fixture proxy unavailable: {error}"))
704                        })?,
705                )
706            }
707        } else if opts.network.unrestricted {
708            None
709        } else {
710            Some(PinProxy::start(guard.clone()).await?)
711        };
712
713        let mut args: Vec<OsString> = BASE_CHROME_ARGS.iter().map(OsString::from).collect();
714        args.push(crate::proc::profile_arg(&profile_dir));
715        args.push(format!("--window-size={},{}", opts.viewport.0, opts.viewport.1).into());
716        args.push(if opts.headless {
717            "--headless=new".into()
718        } else {
719            "--hide-crash-restore-bubble".into()
720        });
721        if opts.mute_audio {
722            args.push("--mute-audio".into());
723        }
724        if let Some(p) = &proxy {
725            // Every connection, loopback included, goes through the pinning proxy;
726            // Chrome itself resolves nothing but the proxy address.
727            args.push(format!("--proxy-server=http://{}", p.addr).into());
728            args.push("--proxy-bypass-list=<-loopback>".into());
729            args.push("--host-resolver-rules=MAP * ~NOTFOUND , EXCLUDE 127.0.0.1".into());
730            // Keep cross-site frames in the page process so interception covers them.
731            args.push("--disable-site-isolation-trials".into());
732            // No UDP path around the proxy: WebRTC only over proxied routes, no QUIC.
733            args.push("--force-webrtc-ip-handling-policy=disable_non_proxied_udp".into());
734            args.push("--disable-quic".into());
735        }
736        for a in &opts.extra_args {
737            args.push(format!("--{}", a.trim_start_matches('-')).into());
738        }
739        args.push("about:blank".into());
740        let launch_timeout = opts.launch_timeout;
741        let request_timeout = opts.request_timeout;
742        let fixture_profile_dir = fixture_mode.then(|| profile_dir.clone());
743        let fixture_proxy_addr = fixture_mode
744            .then(|| proxy.as_ref().map(|proxy| proxy.addr))
745            .flatten();
746        let fixture_owner = if fixture_mode {
747            Some(FixtureLaunchOwner::new(
748                profile_guard.take().expect("fixture profile is owned"),
749                proxy.take(),
750            ))
751        } else {
752            None
753        };
754        let proc = fixture_owner
755            .as_ref()
756            .map(FixtureLaunchOwner::process_slot)
757            .unwrap_or_else(|| Arc::new(StdMutex::new(None)));
758        let spawn_owner = fixture_owner.as_ref().map(FixtureLaunchOwner::spawn_state);
759        #[cfg(windows)]
760        let job = opts.windows_job.take();
761        #[cfg(not(windows))]
762        let job = None;
763        let spawn_proc_slot = proc.clone();
764        let spawn_proc = tokio::task::spawn_blocking(move || {
765            let mut completion = SpawnCompleteGuard {
766                state: spawn_owner.clone(),
767                result: 3,
768            };
769            let spawned = if fixture_profile_dir.is_some() && windows_fixture {
770                #[cfg(windows)]
771                {
772                    args.retain(|arg| {
773                        !arg.to_string_lossy()
774                            .starts_with("--remote-debugging-port=")
775                    });
776                    args.push("--remote-debugging-pipe".into());
777                    // Chrome's browser process always starts the crashpad handler, which cannot
778                    // create its pipe in an AppContainer; the fixture runs the headless shell.
779                    crate::config::chrome_headless_shell_path(&exe).and_then(|shell| {
780                        crate::proc::spawn_chrome_fixture_windows(
781                            &shell,
782                            &args,
783                            fixture_profile_dir.as_deref().expect("fixture profile"),
784                        )
785                    })
786                }
787                #[cfg(not(windows))]
788                unreachable!("windows fixture is cfg-gated")
789            } else if let (Some(profile), Some(proxy_addr)) =
790                (fixture_profile_dir.as_deref(), fixture_proxy_addr)
791            {
792                #[cfg(target_os = "macos")]
793                {
794                    crate::proc::spawn_chrome_fixture(
795                        &exe,
796                        &args,
797                        launch_timeout,
798                        profile,
799                        proxy_addr,
800                    )
801                }
802                #[cfg(not(target_os = "macos"))]
803                {
804                    let _ = (profile, proxy_addr);
805                    Err(BrowserError::Launch(
806                        "fixture confinement is unsupported on this platform".into(),
807                    ))
808                }
809            } else {
810                crate::proc::spawn_chrome(&exe, &args, launch_timeout, job)
811            };
812            match spawned {
813                Ok(process) => {
814                    let info = (process.id(), process.ws_url.clone());
815                    *spawn_proc_slot
816                        .lock()
817                        .unwrap_or_else(|error| error.into_inner()) = Some(process);
818                    completion.result = 1;
819                    Ok(info)
820                }
821                Err(error) => {
822                    completion.result = 2;
823                    Err(error)
824                }
825            }
826        })
827        .await;
828        let spawn_info = match spawn_proc {
829            Ok(Ok(info)) => info,
830            Ok(Err(error)) => return Err(error),
831            Err(error) => {
832                if let Some(owner) = &fixture_owner {
833                    owner.state.spawn_complete.send_replace(3);
834                }
835                return Err(BrowserError::Launch(error.to_string()));
836            }
837        };
838        let pid = Some(spawn_info.0);
839        #[cfg(windows)]
840        let connect_url = if windows_fixture {
841            let deadline = Instant::now() + launch_timeout;
842            let mut process = proc.lock().unwrap_or_else(|error| error.into_inner());
843            process
844                .as_mut()
845                .ok_or_else(|| {
846                    BrowserError::Launch("Windows fixture process ownership is absent".into())
847                })?
848                .start_fixture_pipe_bridge(deadline)?
849        } else {
850            spawn_info.1
851        };
852        #[cfg(not(windows))]
853        let connect_url = spawn_info.1;
854        let config = HandlerConfig {
855            request_timeout,
856            ..HandlerConfig::default()
857        };
858        let (browser, mut handler) = Browser::connect_with_config(connect_url, config)
859            .await
860            .map_err(|e| {
861                #[cfg(windows)]
862                if windows_fixture {
863                    let diagnostics = proc
864                        .lock()
865                        .unwrap_or_else(|error| error.into_inner())
866                        .as_ref()
867                        .map(ChromeProc::fixture_diagnostics)
868                        .unwrap_or_else(|| {
869                            "windows fixture diagnostic process ownership absent".into()
870                        });
871                    return BrowserError::Launch(format!(
872                        "Windows fixture CDP connection failed: {e}; {diagnostics}"
873                    ));
874                }
875                BrowserError::Launch(e.to_string())
876            })?;
877        let (fixture_stop_status, _) = tokio::sync::watch::channel(0u8);
878        let stopping = Arc::new(AtomicBool::new(false));
879        let crashed = Arc::new(AtomicBool::new(false));
880        let (pump_proc, pump_stopping, pump_guard, pump_crashed) = (
881            proc.clone(),
882            stopping.clone(),
883            guard.clone(),
884            crashed.clone(),
885        );
886        let pump_fixture_mode = fixture_mode;
887        let pump = tokio::spawn(async move {
888            // Transient handler errors are tolerated while Chrome is alive; the
889            // stream ending (or Chrome exiting) ends the session.
890            let mut errors = 0u32;
891            while let Some(ev) = handler.next().await {
892                if ev.is_err() {
893                    errors += 1;
894                    if errors > 50
895                        || if pump_fixture_mode {
896                            chrome_has_exited(&pump_proc)
897                        } else {
898                            chrome_exit(&pump_proc).is_some()
899                        }
900                    {
901                        break;
902                    }
903                } else {
904                    errors = 0;
905                }
906            }
907            // Give the OS a moment to reap so the reason carries the exit status.
908            let mut status = None;
909            for _ in 0..25 {
910                status = if pump_fixture_mode {
911                    None
912                } else {
913                    chrome_exit(&pump_proc)
914                };
915                if (pump_fixture_mode && chrome_has_exited(&pump_proc))
916                    || status.is_some()
917                    || pump_stopping.load(Ordering::SeqCst)
918                {
919                    break;
920                }
921                tokio::time::sleep(Duration::from_millis(20)).await;
922            }
923            report_crash(&pump_guard, &pump_stopping, &pump_crashed, status, pid);
924        });
925        // The CDP stream does not always end when Chrome dies, so also watch the process.
926        let (w_proc, w_stopping, w_crashed, w_guard) = (
927            proc.clone(),
928            stopping.clone(),
929            crashed.clone(),
930            guard.clone(),
931        );
932        let watcher_fixture_mode = fixture_mode;
933        let watcher = tokio::spawn(async move {
934            loop {
935                tokio::time::sleep(Duration::from_millis(200)).await;
936                if w_stopping.load(Ordering::SeqCst) || w_crashed.load(Ordering::SeqCst) {
937                    return;
938                }
939                if watcher_fixture_mode && chrome_has_exited(&w_proc) {
940                    report_crash(&w_guard, &w_stopping, &w_crashed, None, pid);
941                    return;
942                }
943                if let Some(status) = (!watcher_fixture_mode)
944                    .then(|| chrome_exit(&w_proc))
945                    .flatten()
946                {
947                    report_crash(&w_guard, &w_stopping, &w_crashed, Some(status), pid);
948                    return;
949                }
950            }
951        });
952        let (proc, profile_guard, proxy) = match fixture_owner {
953            Some(owner) => {
954                let (proc, profile, proxy) = owner.into_parts();
955                (proc, Some(profile), proxy)
956            }
957            None => (proc, profile_guard.take(), proxy),
958        };
959        let fixture_profile_path = fixture_mode.then(|| profile_dir.clone());
960        let session = Self {
961            id,
962            browser: Mutex::new(browser),
963            pages: StdMutex::new(Vec::new()),
964            current: StdMutex::new(None),
965            page_seq: AtomicU64::new(0),
966            handler: StdMutex::new(Some(pump)),
967            watcher: StdMutex::new(Some(watcher)),
968            profile_guard: StdMutex::new(profile_guard),
969            profile_dir,
970            fixture_profile_path,
971            download_dir,
972            upload_root: opts.upload_root,
973            headless: opts.headless,
974            guard,
975            pid,
976            proc,
977            fixture_stop_status,
978            fixture_stop_failure: Arc::new(StdMutex::new(None)),
979            fixture_stop_lock: Mutex::new(()),
980            proxy,
981            stopping,
982            stopped: AtomicBool::new(false),
983            fixture_mode,
984            #[cfg(windows)]
985            fixture_backend,
986        };
987        if !fixture_mode {
988            let download_setup = session
989                .browser
990                .lock()
991                .await
992                .execute(
993                    SetDownloadBehaviorParams::builder()
994                        .behavior(SetDownloadBehaviorBehavior::Allow)
995                        .download_path(session.download_dir.to_string_lossy().to_string())
996                        .build()
997                        .map_err(BrowserError::Launch)?,
998                )
999                .await
1000                .map_err(cdp);
1001            if let Err(error) = download_setup {
1002                let _ = session.stop(false).await;
1003                return Err(BrowserError::Launch(error.to_string()));
1004            }
1005        }
1006
1007        let mode = if opts.headless { "headless" } else { "headed" };
1008        session
1009            .guard
1010            .emit_kind(LifecycleKind::Start, format!("launched ({mode})"), |e| {
1011                e.pid = pid
1012            });
1013        Ok(session)
1014    }
1015
1016    pub fn id(&self) -> &str {
1017        &self.id
1018    }
1019
1020    pub(crate) async fn configure_fixture_downloads(
1021        &self,
1022    ) -> std::result::Result<(), FixtureError> {
1023        let configured = self
1024            .browser
1025            .lock()
1026            .await
1027            .execute(
1028                SetDownloadBehaviorParams::builder()
1029                    .behavior(SetDownloadBehaviorBehavior::Deny)
1030                    .download_path(self.download_dir.to_string_lossy().to_string())
1031                    .build()
1032                    .map_err(|error| FixtureError::Browser(error.to_string()))?,
1033            )
1034            .await
1035            .map_err(|error| FixtureError::Browser(error.to_string()));
1036        #[cfg(windows)]
1037        if let Err(error) = configured {
1038            return Err(FixtureError::Browser(format!(
1039                "{error}; {}",
1040                self.fixture_cdp_diagnostics()
1041            )));
1042        }
1043        #[cfg(not(windows))]
1044        configured?;
1045        Ok(())
1046    }
1047
1048    #[cfg(windows)]
1049    fn fixture_cdp_diagnostics(&self) -> String {
1050        self.proc
1051            .lock()
1052            .unwrap_or_else(|error| error.into_inner())
1053            .as_ref()
1054            .map(ChromeProc::fixture_diagnostics)
1055            .unwrap_or_else(|| "windows fixture diagnostic process ownership absent".into())
1056    }
1057    /// OS process id of the Chrome child this session owns.
1058    pub fn process_id(&self) -> Option<u32> {
1059        self.pid
1060    }
1061    /// Connections the pinning proxy made, with the address it pinned for each.
1062    pub fn pinned_connections(&self) -> Vec<PinnedConnection> {
1063        self.proxy
1064            .as_ref()
1065            .map(|p| p.log.lock().unwrap().clone())
1066            .unwrap_or_default()
1067    }
1068    pub fn is_headless(&self) -> bool {
1069        self.headless
1070    }
1071    pub fn profile_dir(&self) -> &Path {
1072        &self.profile_dir
1073    }
1074    pub fn download_dir(&self) -> &Path {
1075        &self.download_dir
1076    }
1077
1078    /// Open a new page (tab), make it current, and navigate to `url`.
1079    pub async fn new_page(&self, url: &str) -> Result<Arc<BrowserPage>> {
1080        let page = self.open_tab().await?;
1081        if url != "about:blank" {
1082            // The tab's own about:blank must have committed, or it discards this navigation.
1083            page.settle_initial_document().await;
1084            self.navigate_new_page(&page, url).await?;
1085        }
1086        Ok(page)
1087    }
1088
1089    /// Open a new page, install `setup` (request interceptor, download behaviour) before its
1090    /// first navigation, then navigate to `url`. Unlike `new_page` followed by `goto`, the
1091    /// interceptor sees the very first request: the tab's own about:blank commit is waited out
1092    /// first, and `url` is only requested once the setup is in place. `about:blank` opens a
1093    /// page with the setup installed and no navigation.
1094    pub async fn new_page_with(&self, url: &str, setup: PageSetup) -> Result<Arc<BrowserPage>> {
1095        let page = self.open_tab().await?;
1096        page.settle_initial_document().await;
1097        if let Some(hook) = setup.interceptor {
1098            page.set_request_interceptor(Some(hook)).await?;
1099        }
1100        if let Some(behavior) = setup.download {
1101            page.set_download_behavior(&behavior).await?;
1102        }
1103        if url != "about:blank" {
1104            self.navigate_new_page(&page, url).await?;
1105        }
1106        Ok(page)
1107    }
1108
1109    /// Create the tab at about:blank, register it and make it current.
1110    async fn open_tab(&self) -> Result<Arc<BrowserPage>> {
1111        let inner = self
1112            .browser
1113            .lock()
1114            .await
1115            .new_page("about:blank")
1116            .await
1117            .map_err(cdp)?;
1118        let id = format!("p{}", self.page_seq.fetch_add(1, Ordering::Relaxed) + 1);
1119        let page = Arc::new(
1120            BrowserPage::attach(
1121                id.clone(),
1122                inner,
1123                self.upload_root.clone(),
1124                self.guard.clone(),
1125                {
1126                    #[cfg(windows)]
1127                    {
1128                        matches!(self.fixture_backend, Some(FixtureBackend::WinAppcontainer))
1129                    }
1130                    #[cfg(not(windows))]
1131                    {
1132                        false
1133                    }
1134                },
1135            )
1136            .await?,
1137        );
1138        self.pages.lock().unwrap().push(page.clone());
1139        *self.current.lock().unwrap() = Some(id);
1140        Ok(page)
1141    }
1142
1143    async fn navigate_new_page(&self, page: &BrowserPage, url: &str) -> Result<()> {
1144        if let Err(error) = page.goto(url).await {
1145            // What Chrome itself said, when it said anything: a navigation that fails
1146            // inside the browser leaves no other trace on this side.
1147            return Err(match error {
1148                crate::error::BrowserError::Cdp(text) => {
1149                    let stderr = self
1150                        .proc
1151                        .lock()
1152                        .unwrap()
1153                        .as_ref()
1154                        .map(|chrome| chrome.stderr_tail.text())
1155                        .unwrap_or_default();
1156                    crate::error::BrowserError::Cdp(format!("{text}; chrome stderr: {stderr}"))
1157                }
1158                other => other,
1159            });
1160        }
1161        Ok(())
1162    }
1163
1164    pub fn pages(&self) -> Vec<Arc<BrowserPage>> {
1165        self.pages.lock().unwrap().clone()
1166    }
1167
1168    pub fn page(&self, id: &str) -> Result<Arc<BrowserPage>> {
1169        self.pages
1170            .lock()
1171            .unwrap()
1172            .iter()
1173            .find(|p| p.id() == id)
1174            .cloned()
1175            .ok_or_else(|| BrowserError::UnknownPage(id.into()))
1176    }
1177
1178    /// The page actions default to.
1179    pub fn current(&self) -> Result<Arc<BrowserPage>> {
1180        let id = self
1181            .current
1182            .lock()
1183            .unwrap()
1184            .clone()
1185            .ok_or_else(|| BrowserError::UnknownPage("<none>".into()))?;
1186        self.page(&id)
1187    }
1188
1189    /// Make `id` current and bring it to the front.
1190    pub async fn select_page(&self, id: &str) -> Result<Arc<BrowserPage>> {
1191        let p = self.page(id)?;
1192        p.bring_to_front().await?;
1193        *self.current.lock().unwrap() = Some(id.into());
1194        Ok(p)
1195    }
1196
1197    pub async fn close_page(&self, id: &str) -> Result<()> {
1198        let p = self.page(id)?;
1199        self.pages.lock().unwrap().retain(|x| x.id() != id);
1200        {
1201            let mut cur = self.current.lock().unwrap();
1202            if cur.as_deref() == Some(id) {
1203                *cur = self
1204                    .pages
1205                    .lock()
1206                    .unwrap()
1207                    .last()
1208                    .map(|p| p.id().to_string());
1209            }
1210        }
1211        p.close_inner().await
1212    }
1213
1214    /// Completed files currently in the download directory.
1215    pub fn downloads(&self) -> HashSet<PathBuf> {
1216        completed_files(&self.download_dir)
1217    }
1218
1219    /// Wait for a download not in `before` to finish (no `.crdownload`, stable size).
1220    pub async fn wait_download(
1221        &self,
1222        before: &HashSet<PathBuf>,
1223        timeout: Duration,
1224    ) -> Result<PathBuf> {
1225        let deadline = Instant::now() + timeout;
1226        loop {
1227            let now = completed_files(&self.download_dir);
1228            if let Some(p) = now.difference(before).next() {
1229                let size = std::fs::metadata(p).map(|m| m.len()).unwrap_or(0);
1230                tokio::time::sleep(Duration::from_millis(100)).await;
1231                if std::fs::metadata(p).map(|m| m.len()).unwrap_or(1) == size {
1232                    return Ok(p.clone());
1233                }
1234            }
1235            if Instant::now() >= deadline {
1236                return Err(BrowserError::Timeout("download did not complete".into()));
1237            }
1238            tokio::time::sleep(Duration::from_millis(100)).await;
1239        }
1240    }
1241
1242    /// Set a W3C permission (`geolocation`, `notifications`, `clipboard-read`,
1243    /// `midi`, ...) to granted or denied for `origin`, or every origin when `None`.
1244    pub async fn set_permission(
1245        &self,
1246        origin: Option<&str>,
1247        name: &str,
1248        granted: bool,
1249    ) -> Result<()> {
1250        let mut params = SetPermissionParams::new(
1251            PermissionDescriptor::new(name),
1252            if granted {
1253                PermissionSetting::Granted
1254            } else {
1255                PermissionSetting::Denied
1256            },
1257        );
1258        params.origin = origin.map(str::to_string);
1259        self.browser
1260            .lock()
1261            .await
1262            .execute(params)
1263            .await
1264            .map_err(cdp)?;
1265        Ok(())
1266    }
1267
1268    pub async fn reset_permissions(&self) -> Result<()> {
1269        self.browser
1270            .lock()
1271            .await
1272            .execute(ResetPermissionsParams::default())
1273            .await
1274            .map_err(cdp)?;
1275        Ok(())
1276    }
1277
1278    /// Close Chrome gracefully: CDP `Browser.close` and up to 5 s for exit, then SIGTERM to
1279    /// the process group and up to 5 s more, then SIGKILL (job termination on Windows).
1280    /// Safe to call twice. A temporary profile is deleted once Chrome has exited.
1281    pub async fn shutdown(&self) {
1282        let _ = self.stop(false).await;
1283    }
1284
1285    /// [`Self::shutdown`] that reports failure. `Err` when Chrome's process tree did not stop
1286    /// cleanly ([`BrowserError::Stop`]) or the profile was not released: a temporary profile that
1287    /// still exists, or an encrypted profile (`ProfileSpec::Encrypted`, feature `profile-vault`)
1288    /// that could not be sealed or whose plaintext working directory could not be wiped (the tree
1289    /// is then left in place and the next start recovers it). A profile failure is reported first.
1290    pub async fn close(&self) -> Result<()> {
1291        let stopped = self.stop(false).await;
1292        stopped.profile?;
1293        match stopped.process_error {
1294            Some(error) => Err(BrowserError::Stop(error)),
1295            None => Ok(()),
1296        }
1297    }
1298
1299    /// Stop the fixture browser process tree while retaining its profile until the fixture
1300    /// proxy and immutable source server have both been shut down.
1301    pub(crate) async fn stop_fixture_process(&self) -> std::result::Result<(), FixtureError> {
1302        self.stopping.store(true, Ordering::SeqCst);
1303        let mut status = self.fixture_stop_status.subscribe();
1304        let stop_result = loop {
1305            let lock = self.fixture_stop_lock.lock().await;
1306            let current = *status.borrow();
1307            match current {
1308                2 => break Ok(()),
1309                3 => {
1310                    let detail = self
1311                        .fixture_stop_failure
1312                        .lock()
1313                        .unwrap_or_else(|error| error.into_inner())
1314                        .clone()
1315                        .unwrap_or_else(|| "terminal stop worker gave no detail".into());
1316                    break Err(FixtureError::Cleanup(format!(
1317                        "browser termination previously failed without a stop receipt: {detail}"
1318                    )));
1319                }
1320                1 => {
1321                    drop(lock);
1322                    tokio::time::timeout(FIXTURE_STOP_RECEIPT_GRACE, status.changed())
1323                        .await
1324                        .map_err(|_| {
1325                            FixtureError::Cleanup(
1326                                "browser termination receipt did not arrive before deadline".into(),
1327                            )
1328                        })?
1329                        .map_err(|_| {
1330                            FixtureError::Cleanup(
1331                                "browser termination status channel closed".into(),
1332                            )
1333                        })?;
1334                }
1335                _ => {
1336                    self.fixture_stop_status.send_replace(1);
1337                    let process = self.proc.lock().unwrap().take();
1338                    let Some(mut process) = process else {
1339                        *self
1340                            .fixture_stop_failure
1341                            .lock()
1342                            .unwrap_or_else(|error| error.into_inner()) = Some(
1343                            "browser process ownership is absent without a stop receipt".into(),
1344                        );
1345                        self.fixture_stop_status.send_replace(3);
1346                        break Err(FixtureError::Cleanup(
1347                            "browser process ownership is absent without a stop receipt".into(),
1348                        ));
1349                    };
1350                    process.begin_fixture_transport_shutdown();
1351                    // This transaction owns Chrome until it publishes a terminal
1352                    // receipt. The caller can time out or cancel during terminal
1353                    // fencing without abandoning status=1 or the process handle.
1354                    let process_slot = self.proc.clone();
1355                    let status_sender = self.fixture_stop_status.clone();
1356                    let failure_slot = self.fixture_stop_failure.clone();
1357                    tokio::spawn(async move {
1358                        let mut completion = FixtureStopCompletionGuard {
1359                            status: status_sender,
1360                            complete: false,
1361                        };
1362                        let terminated = tokio::task::spawn_blocking(move || {
1363                            let result = process.terminate_fixture_tree();
1364                            (process, result)
1365                        })
1366                        .await;
1367                        let (process, result) = match terminated {
1368                            Ok(result) => result,
1369                            Err(error) => {
1370                                *failure_slot
1371                                    .lock()
1372                                    .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(
1373                                    format!("fixture browser termination worker failed: {error}"),
1374                                );
1375                                return;
1376                            }
1377                        };
1378                        if let Err(error) = result {
1379                            *failure_slot
1380                                .lock()
1381                                .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(format!(
1382                                "fixture browser process tree termination failed: {error}"
1383                            ));
1384                            *process_slot
1385                                .lock()
1386                                .unwrap_or_else(|error| error.into_inner()) = Some(process);
1387                            return;
1388                        }
1389                        #[cfg(windows)]
1390                        {
1391                            let mut process = process;
1392                            if let Err(error) = process
1393                                .finish_fixture_transport_shutdown(Instant::now() + GRACE)
1394                                .await
1395                            {
1396                                *failure_slot
1397                                    .lock()
1398                                    .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(
1399                                    format!("fixture CDP bridge finalization failed: {error}"),
1400                                );
1401                                *process_slot
1402                                    .lock()
1403                                    .unwrap_or_else(|error| error.into_inner()) = Some(process);
1404                                return;
1405                            }
1406                        }
1407                        completion.stopped();
1408                    });
1409                    drop(lock);
1410                    tokio::time::timeout(FIXTURE_STOP_RECEIPT_GRACE, status.changed())
1411                        .await
1412                        .map_err(|_| {
1413                            FixtureError::Cleanup(
1414                                "browser termination receipt did not arrive before deadline".into(),
1415                            )
1416                        })?
1417                        .map_err(|_| {
1418                            FixtureError::Cleanup(
1419                                "browser termination status channel closed".into(),
1420                            )
1421                        })?;
1422                }
1423            }
1424        };
1425        stop_result?;
1426        for page in self.pages.lock().unwrap().drain(..) {
1427            page.abort_pumps();
1428        }
1429        if let Some(handler) = self.handler.lock().unwrap().take() {
1430            handler.abort();
1431        }
1432        if let Some(watcher) = self.watcher.lock().unwrap().take() {
1433            watcher.abort();
1434        }
1435        self.emit_stopped("fixture shutdown");
1436        Ok(())
1437    }
1438
1439    pub(crate) fn process_alive(&self) -> bool {
1440        let Ok(mut process) = self.proc.lock() else {
1441            return false;
1442        };
1443        process
1444            .as_mut()
1445            .is_some_and(|process| process.has_exited().is_ok_and(|exited| !exited))
1446    }
1447
1448    pub(crate) async fn stop_fixture_proxy(&self) -> std::result::Result<(), FixtureError> {
1449        if let Some(proxy) = &self.proxy {
1450            proxy
1451                .shutdown(GRACE)
1452                .await
1453                .map_err(|error| FixtureError::Cleanup(format!("fixture proxy: {error}")))?;
1454        }
1455        Ok(())
1456    }
1457
1458    pub(crate) fn remove_fixture_profile(&self) -> std::result::Result<(), FixtureError> {
1459        let path = self.fixture_profile_path.as_ref().ok_or_else(|| {
1460            FixtureError::Cleanup("fixture browser did not own a disposable profile".into())
1461        })?;
1462        match self.profile_guard.lock().unwrap().take() {
1463            Some(ProfileGuard::Temp(dir)) => drop(dir),
1464            Some(_) => {
1465                return Err(FixtureError::Cleanup(
1466                    "fixture browser did not own a disposable profile".into(),
1467                ))
1468            }
1469            None => {}
1470        }
1471        let deadline = std::time::Instant::now() + Duration::from_secs(3);
1472        while path.exists()
1473            && std::fs::remove_dir_all(path).is_err()
1474            && std::time::Instant::now() < deadline
1475        {
1476            std::thread::sleep(Duration::from_millis(100));
1477        }
1478        if path.exists() {
1479            Err(FixtureError::Cleanup(
1480                "disposable browser profile still exists after cleanup".into(),
1481            ))
1482        } else {
1483            Ok(())
1484        }
1485    }
1486
1487    /// Cancel: kill the owned Chrome now and wait for it to exit. Helper
1488    /// processes exit with their parent; none are detached.
1489    pub async fn cancel(&self) {
1490        let _ = self.stop(true).await;
1491    }
1492
1493    /// [`Self::shutdown`] that returns the terminal outcome of every cleanup step instead of
1494    /// discarding it: whether Chrome's process tree stopped without error and whether the profile
1495    /// was released (temporary profile deleted, encrypted profile sealed and wiped). A `Stop`
1496    /// lifecycle event is not evidence of either; this report is.
1497    pub async fn shutdown_report(&self) -> StopReport {
1498        self.stop(false).await.into_report()
1499    }
1500
1501    /// [`Self::cancel`] with the same terminal [`StopReport`].
1502    pub async fn cancel_report(&self) -> StopReport {
1503        self.stop(true).await.into_report()
1504    }
1505
1506    async fn stop(&self, hard: bool) -> Stopped {
1507        self.stop_inner(hard, true).await
1508    }
1509
1510    async fn stop_inner(&self, hard: bool, release_profile_dir: bool) -> Stopped {
1511        self.stopping.store(true, Ordering::SeqCst);
1512        if !hard {
1513            let graceful = async {
1514                let _ = self.browser.lock().await.close().await;
1515                let end = Instant::now() + GRACE;
1516                loop {
1517                    let done = match self.proc.lock().unwrap().as_mut() {
1518                        Some(p) => matches!(p.try_wait(), Ok(Some(_)) | Err(_)),
1519                        None => true,
1520                    };
1521                    if done || Instant::now() >= end {
1522                        break;
1523                    }
1524                    tokio::time::sleep(Duration::from_millis(20)).await;
1525                }
1526            };
1527            let _ = tokio::time::timeout(Duration::from_secs(6), graceful).await;
1528        }
1529        // Whatever is left: SIGTERM the process group with a bounded wait, SIGKILL last
1530        // (cancel kills at once). Windows: the job object takes the whole tree.
1531        let taken = self.proc.lock().unwrap().take();
1532        let mut process_error = None;
1533        if let Some(mut p) = taken {
1534            let grace = if hard { Duration::ZERO } else { GRACE };
1535            match tokio::task::spawn_blocking(move || p.terminate_gracefully(grace)).await {
1536                Ok(Ok(())) => {}
1537                Ok(Err(error)) => process_error = Some(error.to_string()),
1538                Err(error) => {
1539                    process_error = Some(format!("termination task did not finish: {error}"))
1540                }
1541            }
1542        }
1543        let released = if release_profile_dir {
1544            let guard = self.profile_guard.lock().unwrap().take();
1545            // Sealing a large profile is blocking work; keep it off the async worker.
1546            match tokio::task::spawn_blocking(move || release_profile(guard)).await {
1547                Ok(result) => result,
1548                Err(error) => Err(BrowserError::Profile(format!(
1549                    "profile release did not finish: {error}"
1550                ))),
1551            }
1552        } else {
1553            Ok(())
1554        };
1555        for p in self.pages.lock().unwrap().drain(..) {
1556            p.abort_pumps();
1557        }
1558        if let Some(h) = self.handler.lock().unwrap().take() {
1559            h.abort();
1560        }
1561        if let Some(w) = self.watcher.lock().unwrap().take() {
1562            w.abort();
1563        }
1564        let reason = if hard { "cancelled" } else { "shutdown" };
1565        self.emit_stopped(reason);
1566        Stopped {
1567            process_error,
1568            profile: released,
1569        }
1570    }
1571
1572    fn emit_stopped(&self, reason: &str) {
1573        if !self.stopped.swap(true, Ordering::SeqCst) {
1574            let pid = self.pid;
1575            self.guard
1576                .emit_kind(LifecycleKind::Stop, reason, |e| e.pid = pid);
1577        }
1578    }
1579}
1580
1581/// Emit at most one `Crash` per session, never during an intentional stop.
1582fn report_crash(
1583    guard: &Guard,
1584    stopping: &AtomicBool,
1585    crashed: &AtomicBool,
1586    status: Option<std::process::ExitStatus>,
1587    pid: Option<u32>,
1588) {
1589    if stopping.load(Ordering::SeqCst) || crashed.swap(true, Ordering::SeqCst) {
1590        return;
1591    }
1592    let reason = match status {
1593        Some(s) => format!("chrome exited unexpectedly ({s})"),
1594        None => "devtools connection lost".to_string(),
1595    };
1596    guard.emit_kind(LifecycleKind::Crash, reason, |e| e.pid = pid);
1597}
1598
1599/// Exit status of the owned Chrome, if it has exited.
1600fn chrome_exit(proc: &StdMutex<Option<ChromeProc>>) -> Option<std::process::ExitStatus> {
1601    proc.lock()
1602        .ok()?
1603        .as_mut()
1604        .and_then(|p| p.try_wait().ok().flatten())
1605}
1606
1607/// Fixture monitoring observes exit without reaping the process-group leader; cleanup must
1608/// retain that identity until `terminate_tree_bounded` has killed every descendant.
1609fn chrome_has_exited(proc: &StdMutex<Option<ChromeProc>>) -> bool {
1610    proc.lock()
1611        .ok()
1612        .and_then(|guard| guard.as_ref().map(|p| p.has_exited()))
1613        .and_then(std::result::Result::ok)
1614        .unwrap_or(true)
1615}
1616
1617impl Drop for BrowserSession {
1618    fn drop(&mut self) {
1619        self.stopping.store(true, Ordering::SeqCst);
1620        for p in self.pages.lock().unwrap().iter() {
1621            p.abort_pumps();
1622        }
1623        if let Some(h) = self.handler.lock().unwrap().take() {
1624            h.abort();
1625        }
1626        if let Some(w) = self.watcher.lock().unwrap().take() {
1627            w.abort();
1628        }
1629        if self.fixture_mode {
1630            if let Some(mut process) = self.proc.lock().unwrap().take() {
1631                let _ = process.terminate_fixture_tree();
1632            }
1633            if let Some(ProfileGuard::Temp(profile)) = self.profile_guard.lock().unwrap().take() {
1634                let _ = profile.keep();
1635            }
1636            return;
1637        }
1638        // An abandoned session (cancelled caller, panic, early return) still closes
1639        // gracefully: SIGTERM to Chrome's process group, a bounded wait, SIGKILL last.
1640        if let Some(mut p) = self.proc.lock().unwrap().take() {
1641            let _ = p.terminate_gracefully(GRACE);
1642        }
1643        // Chrome has exited: now the temporary profile can go.
1644        let _ = release_profile(self.profile_guard.lock().unwrap().take());
1645        self.emit_stopped("dropped");
1646    }
1647}
1648
1649fn completed_files(dir: &Path) -> HashSet<PathBuf> {
1650    std::fs::read_dir(dir)
1651        .map(|rd| {
1652            rd.filter_map(|e| e.ok())
1653                .map(|e| e.path())
1654                .filter(|p| {
1655                    p.is_file()
1656                        && !p
1657                            .extension()
1658                            .is_some_and(|e| e == "crdownload" || e == "tmp")
1659                })
1660                .collect()
1661        })
1662        .unwrap_or_default()
1663}