Skip to main content

rightkit_browser/
session.rs

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