cbf-chrome 0.1.0-alpha.4

Chromium-specific safe API layer for CBF.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
//! Chromium process launch and startup wiring for `cbf-chrome`.
//!
//! This module resolves the runtime executable, prepares bridge startup state,
//! launches the Chromium child process, and connects it to
//! [`crate::backend::ChromiumBackend`]. It owns process-level concerns such as
//! runtime selection, command-line startup options, and initial IPC session
//! establishment.

use async_process::{Child, Command};
use cbf::{
    browser::{BrowserHandle, BrowserSession, EventStream},
    delegate::BackendDelegate,
    error::Error,
};
use cbf_chrome_sys::{
    bridge::{BridgeLoadError, bridge},
    ffi::CbfBridgeClientHandle,
};
use futures_lite::future::block_on;
use signal_hook::iterator::Signals;
use std::{
    collections::BTreeSet,
    env,
    path::PathBuf,
    process::ExitStatus,
    sync::{
        Arc,
        atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering},
    },
    thread,
    time::{Duration, Instant},
};

use crate::{
    backend::{ChromiumBackend, ChromiumBackendOptions},
    bridge::{BridgeError, IpcClient},
    data::custom_scheme::ChromeCustomSchemeRegistration,
};

/// Resolves Chromium executable path for CBF applications.
///
/// Resolution order:
/// 1. Explicit path (for example CLI argument)
/// 2. `CBF_CHROMIUM_EXECUTABLE` environment variable
/// 3. Path relative to current app bundle:
///    `../CBF Runtime/<RuntimeName>.app/Contents/MacOS/<RuntimeName>`
///
/// Returns `None` when no candidate can be resolved.
pub fn resolve_chromium_executable(explicit_path: Option<PathBuf>) -> Option<PathBuf> {
    explicit_path
        .or_else(|| env::var_os("CBF_CHROMIUM_EXECUTABLE").map(PathBuf::from))
        .or_else(resolve_chromium_executable_from_bundle)
}

fn resolve_chromium_executable_from_bundle() -> Option<PathBuf> {
    let current_exe = env::current_exe().ok()?;
    let macos_dir = current_exe.parent()?;
    let contents_dir = macos_dir.parent()?;

    if contents_dir.file_name()?.to_str()? != "Contents" {
        return None;
    }

    resolve_chromium_executable_from_runtime_dir(contents_dir.join("CBF Runtime"))
}

fn resolve_chromium_executable_from_runtime_dir(runtime_dir: PathBuf) -> Option<PathBuf> {
    let mut candidates = std::fs::read_dir(runtime_dir)
        .ok()?
        .filter_map(|entry| entry.ok())
        .map(|entry| entry.path())
        .filter(|path| path.extension().and_then(|ext| ext.to_str()) == Some("app"))
        .filter_map(|app_path| {
            let app_name = app_path.file_stem()?.to_str()?.to_owned();
            let executable_path = app_path.join("Contents").join("MacOS").join(app_name);
            executable_path.is_file().then_some(executable_path)
        });

    let first = candidates.next()?;
    if candidates.next().is_some() {
        return None;
    }

    Some(first)
}

/// Runtime selection for Chromium-backed startup.
///
/// `Chrome` is the only currently supported runtime. `Alloy` is reserved as an
/// explicit future selection target, but remains unavailable in this phase.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum RuntimeSelection {
    /// Chrome-backed runtime path used by current CBF integration.
    #[default]
    Chrome,
    /// Reserved for future Alloy runtime work. Selecting this currently fails.
    Alloy,
}

impl RuntimeSelection {
    /// Stable string form for config surfaces and diagnostics.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Chrome => "chrome",
            Self::Alloy => "alloy",
        }
    }
}

impl std::fmt::Display for RuntimeSelection {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

impl std::str::FromStr for RuntimeSelection {
    type Err = String;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        match value {
            "chrome" => Ok(Self::Chrome),
            "alloy" => Ok(Self::Alloy),
            _ => Err(format!(
                "unsupported runtime '{value}': expected 'chrome' or 'alloy'"
            )),
        }
    }
}

/// Errors that can occur while launching Chromium and completing initial
/// bridge/session setup.
#[derive(Debug, thiserror::Error)]
pub enum StartChromiumError {
    /// The requested runtime is recognized but not currently supported for startup.
    #[error("unsupported chromium runtime '{runtime}': use 'chrome'")]
    UnsupportedRuntime { runtime: RuntimeSelection },
    /// Custom scheme registrations contained invalid launch-time input.
    #[error("invalid custom scheme registration: {detail}")]
    InvalidCustomScheme { detail: String },
    /// The runtime bridge library or one of its required symbols could not be loaded.
    #[error("failed to load cbf bridge: {0}")]
    BridgeLoad(#[from] BridgeLoadError),
    /// The bridge loaded but failed to allocate a client handle.
    #[error("cbf_bridge_client_create returned null")]
    BridgeClientCreateReturnedNull,
    /// Preparing the inherited IPC channel for the child process failed.
    #[error("failed to prepare IPC channel: {0}")]
    PrepareChannel(#[source] BridgeError),
    /// Random session-token generation failed before launch.
    #[error("failed to generate session token: {0}")]
    TokenGeneration(#[source] getrandom::Error),
    /// Spawning the Chromium child process failed at the OS process layer.
    #[error("failed to spawn chromium process: {0}")]
    ProcessSpawn(#[source] std::io::Error),
    /// The bridge client could not bind the inherited IPC endpoint after spawn.
    #[error("failed to connect inherited IPC channel: {0}")]
    ConnectInherited(#[source] BridgeError),
    /// Bridge session authentication failed after the IPC connection was established.
    #[error("failed to authenticate chromium bridge session: {0}")]
    Authenticate(#[source] BridgeError),
    /// The backend connected, but the higher-level browser session setup failed.
    #[error("failed to initialize browser session: {0}")]
    SessionConnect(#[source] Error),
}

fn validate_runtime_selection(runtime: RuntimeSelection) -> Result<(), StartChromiumError> {
    if matches!(runtime, RuntimeSelection::Chrome) {
        return Ok(());
    }

    Err(StartChromiumError::UnsupportedRuntime { runtime })
}

/// Options for launching the Chromium process.
#[derive(Debug, Clone)]
pub struct ChromiumProcessOptions {
    /// Runtime path to use for startup.
    ///
    /// The default is `chrome`. `alloy` is currently reserved and will be
    /// rejected by `start_chromium` until that runtime exists.
    pub runtime: RuntimeSelection,
    /// Path to the browser executable (e.g. "<Runtime>.app/Contents/MacOS/<Runtime>").
    pub executable_path: PathBuf,
    /// Path to the user data directory.
    /// If provided, passed as `--user-data-dir=<path>`.
    /// Crashpad dump storage is also redirected under
    /// `<path>/Crashpad` via `--breakpad-dump-location=<path>/Crashpad`
    /// so crash-related artifacts stay within the same app data root.
    /// Prefer setting this explicitly unless you have a strong reason not to.
    /// If `None`, Chromium may use a default profile location, which can conflict
    /// with normal Chromium usage and risk profile data issues (for example,
    /// profile/schema version mismatch).
    pub user_data_dir: Option<String>,
    /// Whether to enable logging.
    /// If provided, passed as `--enable-logging=<stream>`.
    /// e.g. "--enable-logging=stderr"
    pub enable_logging: Option<String>,
    /// Path to the log file.
    /// If provided, passed as `--log-file=<path>`.
    pub log_file: Option<String>,
    /// Chromium VLOG verbosity.
    /// If provided, passed as `--v=<level>`.
    pub v: Option<i32>,
    /// Per-module VLOG verbosity.
    /// If provided, passed as `--vmodule=<pattern1=N,...>`.
    pub vmodule: Option<String>,
    /// Allow Chromium to create its default startup window.
    ///
    /// By default, CBF passes `--no-startup-window` to prevent Chromium's
    /// built-in initial window from being created unexpectedly.
    ///
    /// This option is intentionally marked unsafe because enabling it can
    /// interfere with CBF-controlled window lifecycle behavior.
    pub unsafe_enable_startup_default_window: bool,
    /// Additional arguments to pass to the browser process.
    pub extra_args: Vec<String>,
}

/// Combined options for launching Chromium and connecting the backend.
#[derive(Debug, Clone)]
pub struct StartChromiumOptions {
    /// Options for the Chromium child process.
    pub process: ChromiumProcessOptions,
    /// Options for backend IPC connection behavior.
    pub backend: ChromiumBackendOptions,
}

fn build_custom_schemes_switch_value(
    registrations: &[ChromeCustomSchemeRegistration],
) -> Result<Option<String>, StartChromiumError> {
    let mut scheme_names = BTreeSet::new();
    for registration in registrations {
        let scheme = registration.scheme.trim().to_ascii_lowercase();
        if scheme.is_empty() {
            return Err(StartChromiumError::InvalidCustomScheme {
                detail: "custom scheme registration contains an empty scheme".to_owned(),
            });
        }
        scheme_names.insert(scheme);
    }

    if scheme_names.is_empty() {
        Ok(None)
    } else {
        Ok(Some(scheme_names.into_iter().collect::<Vec<_>>().join(",")))
    }
}

/// A handle to the running Chromium process.
///
/// This struct holds the `std::process::Child` and allows managing its lifecycle.
#[derive(Debug)]
pub struct ChromiumProcess {
    child: Child,
}

impl ChromiumProcess {
    const WAIT_POLL_INTERVAL: Duration = Duration::from_millis(50);

    /// Returns the process id of the browser process.
    pub fn pid(&self) -> u32 {
        self.child.id()
    }

    /// Forcefully kills the browser process.
    pub fn kill(&mut self) -> std::io::Result<()> {
        self.child.kill()
    }

    /// Requests browser process termination with `SIGTERM`.
    #[cfg(unix)]
    pub fn terminate(&self) -> std::io::Result<()> {
        send_signal(self.pid(), libc::SIGTERM)
    }

    /// Waits for the browser process to exit.
    pub fn wait_blocking(&mut self) -> std::io::Result<ExitStatus> {
        block_on(self.child.status())
    }

    /// Attempts to check if the browser process has exited without blocking.
    pub fn try_wait(&mut self) -> std::io::Result<Option<ExitStatus>> {
        self.child.try_status()
    }

    /// Await the browser process exit status asynchronously.
    pub async fn wait(&mut self) -> std::io::Result<ExitStatus> {
        self.child.status().await
    }

    /// Polls for process exit until `timeout` elapses.
    pub fn wait_for_exit_timeout(
        &mut self,
        timeout: Duration,
    ) -> std::io::Result<Option<ExitStatus>> {
        let deadline = Instant::now() + timeout;
        loop {
            if let Some(status) = self.try_wait()? {
                return Ok(Some(status));
            }
            if Instant::now() >= deadline {
                return Ok(None);
            }
            thread::sleep(
                Self::WAIT_POLL_INTERVAL.min(deadline.saturating_duration_since(Instant::now())),
            );
        }
    }
}

/// Shutdown strategy used when terminating a running Chromium runtime.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ShutdownMode {
    /// Request orderly shutdown through the browser session before escalating.
    Graceful,
    /// Skip orderly teardown and force the runtime toward immediate exit.
    Force,
}

/// Current shutdown status tracked by the runtime's shared shutdown controller.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChromiumRuntimeShutdownState {
    /// No shutdown has started.
    Idle,
    /// Graceful shutdown has started.
    Graceful,
    /// Forced shutdown has started.
    Force,
}

impl ChromiumRuntimeShutdownState {
    fn as_u8(self) -> u8 {
        match self {
            Self::Idle => 0,
            Self::Graceful => 1,
            Self::Force => 2,
        }
    }

    fn from_u8(value: u8) -> Self {
        match value {
            1 => Self::Graceful,
            2 => Self::Force,
            _ => Self::Idle,
        }
    }

    fn from_mode(mode: ShutdownMode) -> Self {
        match mode {
            ShutdownMode::Graceful => Self::Graceful,
            ShutdownMode::Force => Self::Force,
        }
    }
}

/// Cloneable reader for observing runtime shutdown state from other threads.
#[derive(Debug, Clone)]
pub struct ChromiumRuntimeShutdownStateReader {
    state: Arc<AtomicU8>,
}

impl ChromiumRuntimeShutdownStateReader {
    /// Returns the latest shutdown state recorded by the runtime controller.
    pub fn shutdown_state(&self) -> ChromiumRuntimeShutdownState {
        ChromiumRuntimeShutdownState::from_u8(self.state.load(Ordering::Acquire))
    }
}

/// Errors returned when installing process-wide signal handlers for a runtime.
#[derive(Debug, thiserror::Error)]
pub enum InstallSignalHandlersError {
    #[error("signal handlers are already installed for a Chromium runtime")]
    AlreadyInstalled,
    #[error("failed to install signal handlers: {0}")]
    Io(#[from] std::io::Error),
}

#[derive(Debug)]
struct ShutdownController {
    browser: BrowserHandle<ChromiumBackend>,
    pid: u32,
    next_shutdown_request_id: AtomicU64,
    shutdown_state: Arc<AtomicU8>,
    shutdown_started: AtomicBool,
}

impl ShutdownController {
    const FORCE_WAIT_TIMEOUT: Duration = Duration::from_secs(3);
    const TERM_WAIT_TIMEOUT: Duration = Duration::from_secs(1);

    fn new(browser: BrowserHandle<ChromiumBackend>, pid: u32) -> Self {
        Self {
            browser,
            pid,
            next_shutdown_request_id: AtomicU64::new(1),
            shutdown_state: Arc::new(AtomicU8::new(ChromiumRuntimeShutdownState::Idle.as_u8())),
            shutdown_started: AtomicBool::new(false),
        }
    }

    fn begin_shutdown(&self, mode: ShutdownMode) -> bool {
        if self
            .shutdown_started
            .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
            .is_ok()
        {
            self.shutdown_state.store(
                ChromiumRuntimeShutdownState::from_mode(mode).as_u8(),
                Ordering::Release,
            );
            true
        } else {
            false
        }
    }

    fn shutdown_state(&self) -> ChromiumRuntimeShutdownState {
        ChromiumRuntimeShutdownState::from_u8(self.shutdown_state.load(Ordering::Acquire))
    }

    fn shutdown_state_reader(&self) -> ChromiumRuntimeShutdownStateReader {
        ChromiumRuntimeShutdownStateReader {
            state: Arc::clone(&self.shutdown_state),
        }
    }

    fn shutdown_via_pid(&self, mode: ShutdownMode) {
        if !self.begin_shutdown(mode) {
            return;
        }

        _ = match mode {
            ShutdownMode::Graceful => self.browser.request_shutdown(
                self.next_shutdown_request_id
                    .fetch_add(1, Ordering::Relaxed),
            ),
            ShutdownMode::Force => self.browser.force_shutdown(),
        };

        if wait_for_pid_exit(self.pid, Self::FORCE_WAIT_TIMEOUT) {
            return;
        }

        #[cfg(unix)]
        {
            let _ = send_signal(self.pid, libc::SIGTERM);
        }

        if wait_for_pid_exit(self.pid, Self::TERM_WAIT_TIMEOUT) {
            return;
        }

        #[cfg(unix)]
        {
            let _ = send_signal(self.pid, libc::SIGKILL);
        }
    }
}

static SIGNAL_HANDLERS_INSTALLED: AtomicBool = AtomicBool::new(false);

/// Owns a live Chromium session, its event stream, and the spawned child process.
///
/// `ChromiumRuntime` coordinates shutdown across the `cbf` session layer and
/// the OS process, and can optionally install signal handlers that trigger
/// forced termination on `SIGINT` or `SIGTERM`.
#[derive(Debug)]
pub struct ChromiumRuntime {
    session: BrowserSession<ChromiumBackend>,
    events: EventStream<ChromiumBackend>,
    process: ChromiumProcess,
    shutdown_controller: Arc<ShutdownController>,
}

impl ChromiumRuntime {
    /// Wraps an already connected session, event stream, and child process into
    /// a single runtime owner.
    ///
    /// This is typically constructed from the tuple returned by
    /// [`start_chromium`].
    pub fn new(
        session: BrowserSession<ChromiumBackend>,
        events: EventStream<ChromiumBackend>,
        process: ChromiumProcess,
    ) -> Self {
        let shutdown_controller =
            Arc::new(ShutdownController::new(session.handle(), process.pid()));
        Self {
            session,
            events,
            process,
            shutdown_controller,
        }
    }

    /// Returns the owned browser session for issuing commands and obtaining
    /// backend handles.
    pub fn session(&self) -> &BrowserSession<ChromiumBackend> {
        &self.session
    }

    /// Returns a cloned event stream handle for receiving backend events.
    ///
    /// Callers commonly move this clone to a dedicated forwarding thread while
    /// retaining the runtime itself for lifecycle management.
    pub fn events(&self) -> EventStream<ChromiumBackend> {
        self.events.clone()
    }

    /// Returns a shared reference to the spawned Chromium process handle.
    pub fn process(&self) -> &ChromiumProcess {
        &self.process
    }

    /// Returns a mutable reference to the spawned Chromium process handle.
    ///
    /// This is intended for advanced process-level operations such as waiting
    /// for exit or inspecting process state directly.
    pub fn process_mut(&mut self) -> &mut ChromiumProcess {
        &mut self.process
    }

    /// Returns the current runtime shutdown state tracked by the shutdown
    /// controller.
    pub fn shutdown_state(&self) -> ChromiumRuntimeShutdownState {
        self.shutdown_controller.shutdown_state()
    }

    /// Returns a cloneable reader that can observe shutdown progress from other
    /// threads without borrowing the runtime.
    pub fn shutdown_state_reader(&self) -> ChromiumRuntimeShutdownStateReader {
        self.shutdown_controller.shutdown_state_reader()
    }

    /// Installs process-wide `SIGINT`/`SIGTERM` handlers that force runtime
    /// shutdown when either signal is received.
    ///
    /// Handlers can only be installed once per process. A received signal uses
    /// PID-based termination fallback so shutdown can continue even if the
    /// normal event-processing path is stalled.
    pub fn install_signal_handlers(&self) -> Result<(), InstallSignalHandlersError> {
        if SIGNAL_HANDLERS_INSTALLED
            .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
            .is_err()
        {
            return Err(InstallSignalHandlersError::AlreadyInstalled);
        }

        let controller = Arc::clone(&self.shutdown_controller);
        let signals = Signals::new([signal_hook::consts::SIGINT, signal_hook::consts::SIGTERM])
            .inspect_err(|_| {
                SIGNAL_HANDLERS_INSTALLED.store(false, Ordering::Release);
            })?;

        thread::spawn(move || {
            let mut signals = signals;
            if signals.forever().next().is_some() {
                controller.shutdown_via_pid(ShutdownMode::Force);
            }
        });

        Ok(())
    }

    /// Starts runtime shutdown using the requested mode and waits for the child
    /// process to exit, escalating to OS-level termination if needed.
    ///
    /// Repeated calls after shutdown has already started are treated as no-ops.
    /// On drop, the runtime automatically invokes this with
    /// [`ShutdownMode::Force`].
    pub fn shutdown(&mut self, mode: ShutdownMode) -> std::io::Result<()> {
        if !self.shutdown_controller.begin_shutdown(mode) {
            return Ok(());
        }

        let _ = match mode {
            ShutdownMode::Graceful => self.session.close(),
            ShutdownMode::Force => self.session.force_close(),
        };

        if self
            .process
            .wait_for_exit_timeout(ShutdownController::FORCE_WAIT_TIMEOUT)?
            .is_some()
        {
            return Ok(());
        }

        #[cfg(unix)]
        self.process.terminate()?;

        if self
            .process
            .wait_for_exit_timeout(ShutdownController::TERM_WAIT_TIMEOUT)?
            .is_some()
        {
            return Ok(());
        }

        match self.process.kill() {
            Ok(()) => Ok(()),
            Err(err) if err.kind() == std::io::ErrorKind::InvalidInput => Ok(()),
            Err(err) => Err(err),
        }
    }
}

impl Drop for ChromiumRuntime {
    fn drop(&mut self) {
        let _ = self.shutdown(ShutdownMode::Force);
    }
}

#[cfg(unix)]
fn send_signal(pid: u32, signal: libc::c_int) -> std::io::Result<()> {
    let result = unsafe { libc::kill(pid as libc::pid_t, signal) };
    if result == 0 {
        return Ok(());
    }

    let err = std::io::Error::last_os_error();
    if matches!(err.raw_os_error(), Some(libc::ESRCH)) {
        return Ok(());
    }
    Err(err)
}

#[cfg(unix)]
fn process_exists(pid: u32) -> bool {
    let result = unsafe { libc::kill(pid as libc::pid_t, 0) };
    if result == 0 {
        return true;
    }

    let err = std::io::Error::last_os_error();
    !matches!(err.raw_os_error(), Some(libc::ESRCH))
}

#[cfg(not(unix))]
fn process_exists(_pid: u32) -> bool {
    false
}

fn wait_for_pid_exit(pid: u32, timeout: Duration) -> bool {
    let deadline = Instant::now() + timeout;
    while Instant::now() < deadline {
        if !process_exists(pid) {
            return true;
        }
        thread::sleep(
            ChromiumProcess::WAIT_POLL_INTERVAL
                .min(deadline.saturating_duration_since(Instant::now())),
        );
    }
    !process_exists(pid)
}

/// Launches the Chromium process and connects to it via an inherited Mojo endpoint.
///
/// This function prepares the IPC channel, spawns the browser process with the
/// channel handle argument, completes the Mojo connection, and authenticates with
/// a freshly generated per-session token before returning a ready backend session.
pub fn start_chromium(
    options: StartChromiumOptions,
    delegate: impl BackendDelegate,
) -> Result<
    (
        BrowserSession<ChromiumBackend>,
        EventStream<ChromiumBackend>,
        ChromiumProcess,
    ),
    StartChromiumError,
> {
    let StartChromiumOptions { process, backend } = options;
    let custom_schemes_switch_value =
        build_custom_schemes_switch_value(&backend.custom_scheme_registrations)?;

    let ChromiumProcessOptions {
        runtime,
        executable_path,
        user_data_dir,
        enable_logging,
        log_file,
        v,
        vmodule,
        unsafe_enable_startup_default_window,
        extra_args,
    } = process;

    validate_runtime_selection(runtime)?;

    // Production bundles launch the Chromium runtime from a separate app bundle.
    // Align the host-side base bundle ID with that runtime bundle so Mach
    // rendezvous uses the same bootstrap name on both sides.
    #[cfg(target_os = "macos")]
    if let Some(app_path) = executable_path
        .parent()
        .and_then(|p| p.parent())
        .and_then(|p| p.parent())
    {
        let plist_path = app_path.join("Contents").join("Info.plist");
        if let Ok(info) = plist::Value::from_file(&plist_path)
            && let Some(bundle_id) = info
                .as_dictionary()
                .and_then(|d| d.get("CFBundleIdentifier"))
                .and_then(|v| v.as_string())
        {
            tracing::debug!(bundle_id = %bundle_id, "overriding base bundle id for mach rendezvous");
            _ = IpcClient::set_base_bundle_id(bundle_id);
        }
    }

    // Create the bridge client handle and prepare the Mojo channel pair.
    let inner = bridge().map(|bridge| unsafe { bridge.cbf_bridge_client_create() })?;
    if inner.is_null() {
        return Err(StartChromiumError::BridgeClientCreateReturnedNull);
    }

    let (remote_fd, switch_arg) = IpcClient::prepare_channel_and_lock().map_err(|error| {
        cleanup_bridge_destroy(inner);
        StartChromiumError::PrepareChannel(error)
    })?;

    // Generate a per-session token.
    let mut token_bytes = [0u8; 32];
    if let Err(error) = getrandom::fill(&mut token_bytes) {
        IpcClient::abort_channel_launch();
        cleanup_bridge_destroy(inner);
        return Err(StartChromiumError::TokenGeneration(error));
    }
    let session_token: String = token_bytes.iter().map(|b| format!("{b:02x}")).collect();

    let mut command = Command::new(&executable_path);

    command.arg("--enable-features=Cbf");
    command.arg(&switch_arg);
    command.arg(format!("--cbf-session-token={session_token}"));
    if let Some(custom_schemes_switch_value) = custom_schemes_switch_value {
        command.arg(format!(
            "--cbf-custom-schemes={custom_schemes_switch_value}"
        ));
    }

    // Clear FD_CLOEXEC on the remote endpoint fd so it is inherited by the child.
    #[cfg(unix)]
    {
        use std::os::unix::io::RawFd;
        if remote_fd >= 0 {
            unsafe { libc::fcntl(remote_fd as RawFd, libc::F_SETFD, 0) };
        }
    }

    if let Some(user_data_dir) = &user_data_dir {
        command.arg(format!("--user-data-dir={}", user_data_dir));
        let crashpad_dir = PathBuf::from(user_data_dir).join("Crashpad");
        command.arg(format!(
            "--breakpad-dump-location={}",
            crashpad_dir.to_string_lossy()
        ));
    }

    if let Some(ref enable_logging) = enable_logging {
        command.arg(format!("--enable-logging={}", enable_logging));
    }

    if let Some(log_file) = &log_file {
        command.arg(format!("--log-file={}", log_file));
    }

    if let Some(v) = v {
        command.arg(format!("--v={}", v));
    }

    if let Some(vmodule) = &vmodule {
        command.arg(format!("--vmodule={}", vmodule));
    }

    if !unsafe_enable_startup_default_window {
        command.arg("--no-startup-window");
    }

    command.args(&extra_args);

    let child = match command.spawn() {
        Ok(child) => child,
        Err(error) => {
            IpcClient::abort_channel_launch();
            cleanup_bridge_destroy(inner);
            return Err(StartChromiumError::ProcessSpawn(error));
        }
    };
    let child_pid = child.id();

    // Notify the bridge of the child PID: on macOS this registers the Mach
    // port with the rendezvous server; on other platforms it is bookkeeping.
    IpcClient::pass_child_pid_and_unlock(child_pid);

    // Close the parent's copy of the remote fd after spawning.
    #[cfg(unix)]
    {
        use std::os::unix::io::RawFd;
        if remote_fd >= 0 {
            unsafe { libc::close(remote_fd as RawFd) };
        }
    }

    // Complete the Mojo handshake: send the OutgoingInvitation and bind the remote.
    let client = match unsafe { IpcClient::connect_inherited(inner) } {
        Ok(client) => client,
        Err(error) => return Err(StartChromiumError::ConnectInherited(error)),
    };

    // Authenticate and set up the browser observer.
    if let Err(error) = client.authenticate(&session_token) {
        return Err(StartChromiumError::Authenticate(error));
    }

    let backend = ChromiumBackend::new(backend, client);
    let (session, events) = BrowserSession::connect(backend, delegate, None)
        .map_err(StartChromiumError::SessionConnect)?;

    Ok((session, events, ChromiumProcess { child }))
}

fn cleanup_bridge_destroy(inner: *mut CbfBridgeClientHandle) {
    if let Err(error) = bridge().map(|bridge| unsafe { bridge.cbf_bridge_client_destroy(inner) }) {
        tracing::warn!(error = ?error, "failed to destroy bridge client after startup error");
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::data::custom_scheme::ChromeCustomSchemeRegistration;
    use async_process::Command;

    #[test]
    fn runtime_selection_defaults_to_chrome() {
        assert_eq!(RuntimeSelection::default(), RuntimeSelection::Chrome);
        assert_eq!(RuntimeSelection::default().to_string(), "chrome");
    }

    #[test]
    fn runtime_selection_rejects_alloy_until_implemented() {
        let err = validate_runtime_selection(RuntimeSelection::Alloy).unwrap_err();

        match err {
            StartChromiumError::UnsupportedRuntime { runtime } => {
                assert_eq!(runtime, RuntimeSelection::Alloy);
            }
            other => panic!("unexpected error: {other:?}"),
        }
    }

    #[test]
    fn runtime_selection_parses_known_values() {
        assert_eq!("chrome".parse(), Ok(RuntimeSelection::Chrome));
        assert_eq!("alloy".parse(), Ok(RuntimeSelection::Alloy));
    }

    #[test]
    fn build_custom_schemes_switch_value_dedupes_and_normalizes() {
        let registrations = vec![
            ChromeCustomSchemeRegistration {
                scheme: "App".to_string(),
                host: "simpleapp".to_string(),
            },
            ChromeCustomSchemeRegistration {
                scheme: " app ".to_string(),
                host: "other".to_string(),
            },
            ChromeCustomSchemeRegistration {
                scheme: "Tool".to_string(),
                host: "simpleapp".to_string(),
            },
        ];

        let value = build_custom_schemes_switch_value(&registrations)
            .expect("switch value should be built");

        assert_eq!(value.as_deref(), Some("app,tool"));
    }

    #[test]
    fn build_custom_schemes_switch_value_rejects_empty_scheme() {
        let registrations = vec![ChromeCustomSchemeRegistration {
            scheme: "   ".to_string(),
            host: "simpleapp".to_string(),
        }];

        let err = build_custom_schemes_switch_value(&registrations).unwrap_err();

        match err {
            StartChromiumError::InvalidCustomScheme { detail } => {
                assert_eq!(
                    detail,
                    "custom scheme registration contains an empty scheme"
                );
            }
            other => panic!("unexpected error: {other:?}"),
        }
    }

    #[cfg(unix)]
    fn spawn_sleeping_process() -> ChromiumProcess {
        let child = Command::new("sh")
            .arg("-c")
            .arg("sleep 30")
            .spawn()
            .expect("spawn sleeping process");
        ChromiumProcess { child }
    }

    #[cfg(unix)]
    #[test]
    fn wait_for_exit_timeout_returns_none_while_process_is_alive() {
        let mut process = spawn_sleeping_process();

        let result = process
            .wait_for_exit_timeout(Duration::from_millis(10))
            .unwrap();

        assert!(result.is_none());
        process.kill().unwrap();
        process.wait_blocking().unwrap();
    }

    #[cfg(unix)]
    #[test]
    fn terminate_requests_process_exit() {
        let mut process = spawn_sleeping_process();

        process.terminate().unwrap();

        let status = process
            .wait_for_exit_timeout(Duration::from_secs(2))
            .unwrap()
            .expect("terminated process should exit");
        assert!(!status.success());
    }

    fn temp_path(name: &str) -> std::path::PathBuf {
        let unique = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        std::env::temp_dir().join(format!("cbf-chrome-{name}-{unique}"))
    }

    #[test]
    fn resolve_chromium_executable_from_runtime_dir_finds_single_runtime() {
        let runtime_dir = temp_path("single-runtime");
        let executable_path = runtime_dir
            .join("Sample Engine.app")
            .join("Contents")
            .join("MacOS")
            .join("Sample Engine");
        std::fs::create_dir_all(executable_path.parent().unwrap()).unwrap();
        std::fs::write(&executable_path, b"binary").unwrap();

        let resolved = resolve_chromium_executable_from_runtime_dir(runtime_dir.clone());
        assert_eq!(resolved.as_deref(), Some(executable_path.as_path()));

        let _ = std::fs::remove_dir_all(runtime_dir);
    }

    #[test]
    fn resolve_chromium_executable_from_runtime_dir_rejects_multiple_runtimes() {
        let runtime_dir = temp_path("multiple-runtimes");
        for name in ["One Engine", "Two Engine"] {
            let executable_path = runtime_dir
                .join(format!("{name}.app"))
                .join("Contents")
                .join("MacOS")
                .join(name);
            std::fs::create_dir_all(executable_path.parent().unwrap()).unwrap();
            std::fs::write(executable_path, b"binary").unwrap();
        }

        assert!(resolve_chromium_executable_from_runtime_dir(runtime_dir.clone()).is_none());

        let _ = std::fs::remove_dir_all(runtime_dir);
    }
}