rho-coding-agent 3.12.0

A fast Rust agent harness with a small footprint and opinionated defaults
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
//! The daemon's browser, shared by its sessions: one [`Manager`] keyed by
//! session, so each session has a browser context of its own, its cookies
//! and tabs out of the others' reach.
//!
//! The manager follows `[browser]` as the config is at each browser call.
//! When the table changed, the browser closes and the call starts the one
//! it now names, so the fix a failed start suggests, such as
//! `sandbox = false`, works without restarting the daemon.

use super::config::BrowserConfig;
use super::drive::{PersonTabs, Refused};
use super::view::{BrowserState, BrowserView, Driver};
use super::watch::{Pointer, Watches};
use super::{start, ReadConfig, VIEWPORT};
use crate::daemon::DaemonPaths;
use moves::Moves;
use rho_browser::cdp::{BrowserContextId, TargetId};
use rho_browser::manager::{Context, Manager, ManagerOptions};
use rho_browser::screencast::Fit;
use rho_browser::tab::Viewport;
use rho_browser::{CloseReason, Connection};
use rho_protocol::{
    BrowserDestination, BrowserFrames, BrowserTabAction, BrowserWatchId, BrowserWatchResponse,
    ConnectionId,
};
use rho_sdk::SessionId;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, PoisonError, Weak};
use tokio::sync::watch;

/// The daemon's browser service.
pub(crate) struct Browsers {
    rho_home: PathBuf,
    read_config: ReadConfig,
    current: tokio::sync::Mutex<Service>,
    watches: Watches,
}

/// What a browser call answers once the daemon is stopping.
const STOPPING: &str = "the daemon is stopping";

/// Where the service stands.
enum Service {
    /// No browser call has come yet.
    NotStarted,
    Running(Current),
    /// The daemon is stopping: no browser starts again.
    Closed,
}

/// The manager, and the config it was built from.
struct Current {
    config: BrowserConfig,
    manager: Manager<SessionId>,
}

impl Browsers {
    /// The service of a daemon in `home` whose `[browser]` is `config`, as
    /// a test sets it up.
    #[cfg(test)]
    pub(crate) fn for_tests(home: &Path, config: BrowserConfig) -> Arc<Self> {
        Self::for_daemon(
            home,
            Box::new(move || Box::pin(std::future::ready(config.clone()))),
        )
        .expect("a daemon built with the browser has a browser service")
    }

    /// The service of the daemon of `rho_home`, its canonical path, which
    /// reads `[browser]` with `read_config`. Nothing starts until a session
    /// asks for its context.
    pub(crate) fn for_daemon(rho_home: &Path, read_config: ReadConfig) -> Option<Arc<Self>> {
        Some(Arc::new(Self {
            rho_home: rho_home.to_path_buf(),
            read_config,
            current: tokio::sync::Mutex::new(Service::NotStarted),
            watches: Watches::default(),
        }))
    }

    /// The handle `session`'s browser tools use, when the daemon has a
    /// browser service. Its clones share the session's [`BrowserView`].
    pub(crate) fn session(this: Option<&Arc<Self>>, session: &SessionId) -> Option<SessionBrowser> {
        this.map(|browsers| SessionBrowser {
            browsers: Arc::clone(browsers),
            session: session.clone(),
            view: Arc::new(watch::Sender::new(BrowserView::default())),
            watched: Arc::default(),
            control: Arc::default(),
            person_tabs: Arc::default(),
            following: Arc::default(),
            moves: Arc::default(),
            pointer: Arc::new(watch::Sender::new(None)),
        })
    }

    /// Records that `watch`'s client drew frame `seq` and those before it,
    /// returning whether the watch runs.
    pub(crate) fn ack_frame(&self, watch: &BrowserWatchId, seq: u64) -> bool {
        self.watches.ack(watch, seq)
    }

    /// Ends `watch`, if it runs.
    pub(crate) fn unwatch(&self, watch: &BrowserWatchId) {
        self.watches.unwatch(watch);
    }

    /// Closes the browser, if it is running, as the daemon stops. No
    /// browser starts after this: a call still running gets an error.
    pub(crate) async fn close(&self) {
        let service = std::mem::replace(&mut *self.current.lock().await, Service::Closed);
        if let Service::Running(current) = service {
            current.manager.close().await;
        }
    }

    /// The manager for `[browser]` as it is now, closing the browser of a
    /// manager built from an older config.
    async fn manager(&self) -> Result<Manager<SessionId>, String> {
        let (manager, replaced) = {
            let mut service = self.current.lock().await;
            // Read under the lock, so calls racing a config edit agree on
            // which config is current instead of swapping it back and forth.
            let config = (self.read_config)().await.launch();
            match &*service {
                Service::Closed => return Err(STOPPING.to_owned()),
                Service::Running(current) if current.config == config => {
                    return Ok(current.manager.clone());
                }
                Service::Running(_) | Service::NotStarted => {}
            }
            let manager = Manager::new(self.options(&config)?);
            let running = Service::Running(Current {
                config,
                manager: manager.clone(),
            });
            (manager, std::mem::replace(&mut *service, running))
        };
        if let Service::Running(replaced) = replaced {
            replaced.manager.close().await;
        }
        Ok(manager)
    }

    fn options(&self, config: &BrowserConfig) -> Result<ManagerOptions, String> {
        // The daemon placed its runtime directory from the same environment.
        let paths = DaemonPaths::resolve(&self.rho_home, |name| std::env::var_os(name))
            .map_err(|error| format!("could not place the browser's profiles: {error}"))?;
        let client = start::download_client()
            .map_err(|error| format!("could not set up the browser download: {error}"))?;
        let executable = start::executable(config, &self.rho_home, client);
        start::manager_options(config, &paths.runtime_dir, executable)
    }
}

/// One session's way to the daemon's browser.
#[derive(Clone)]
pub(crate) struct SessionBrowser {
    browsers: Arc<Browsers>,
    session: SessionId,
    view: Arc<watch::Sender<BrowserView>>,
    /// The context whose browser [`watch_close`] waits on, so one watcher
    /// runs per context, and a watcher whose context was replaced stays
    /// quiet.
    watched: Arc<Mutex<Option<BrowserContextId>>>,
    /// Who controls the browser, kept in step with the view's driver.
    control: Arc<Mutex<Control>>,
    /// The tabs of each tool set the session built that still lives, oldest
    /// first: a person drives the newest. While an agent rebind builds a new
    /// tool set, the session runs on the old one, whose tabs a person
    /// drives again if the new one fails and drops.
    person_tabs: Arc<Mutex<Vec<Weak<dyn PersonTabs>>>>,
    /// Whether the view follows a person's driving
    /// ([`PersonTabs::follow`]).
    following: Arc<AtomicBool>,
    /// A person's input on its way to the tabs, their moves merged.
    moves: Arc<Moves>,
    /// The page's cursor under the person's pointer, which the watches of
    /// its tab send: none until the person's mouse input of their turn to
    /// drive, so every turn sends its first cursor.
    pointer: Arc<watch::Sender<Option<Pointer>>>,
}

/// The person in control of a session's browser, and how often one took
/// it over.
#[derive(Default)]
struct Control {
    /// The connection whose person drives the browser, if one does.
    person: Option<ConnectionId>,
    /// How many times a person has taken the browser over.
    takeovers: u64,
    /// The viewport the person's client views the tabs at, while a person
    /// drives and their client named one; the agent's otherwise. Set with
    /// the driver, so the size never outlives the person it was for.
    person_viewport: Option<Viewport>,
}

impl SessionBrowser {
    /// The session's browser context, starting the browser first if it is
    /// not running. The browser stays open while the context is held. The
    /// error says what to tell the agent, with the fix when rho knows one.
    pub(crate) async fn context(&self) -> Result<Context, String> {
        let before = self.view.borrow().state;
        if before != BrowserState::Running {
            self.show(|view| view.state = BrowserState::Starting);
        }
        let mut starting = Starting {
            view: &self.view,
            before: Some(before),
        };
        let context = self.open_context().await;
        if let Ok(context) = &context {
            starting.before = None;
            self.running(context);
        }
        context
    }

    async fn open_context(&self) -> Result<Context, String> {
        let manager = self.browsers.manager().await?;
        let context = manager
            .context(&self.session)
            .await
            .map_err(|error| start::failure_text(&error))?;
        // The service closed while this call started a browser, after its
        // close had run: close that one too.
        if let Service::Closed = &*self.browsers.current.lock().await {
            drop(context);
            manager.close().await;
            return Err(STOPPING.to_owned());
        }
        Ok(context)
    }

    /// The session's browser as its clients see it, from now on.
    pub(crate) fn view(&self) -> watch::Receiver<BrowserView> {
        self.view.subscribe()
    }

    /// Changes the session's [`BrowserView`] with `change`, telling its
    /// clients only if it changed.
    pub(crate) fn show(&self, change: impl FnOnce(&mut BrowserView)) {
        self.view.send_if_modified(|view| {
            let before = view.clone();
            change(view);
            *view != before
        });
    }

    /// Changes the session's [`BrowserView`] as [`Self::show`] does, as
    /// long as the browser of `context` has not closed: a call that read
    /// its tabs before the close cannot list them after it.
    pub(crate) fn show_in(
        &self,
        context: &BrowserContextId,
        change: impl FnOnce(&mut BrowserView),
    ) {
        let watched = self.watched.lock().unwrap_or_else(PoisonError::into_inner);
        if watched.as_ref() == Some(context) {
            self.show(change);
        }
    }

    /// Tells the session's clients the browser of `context` runs, and
    /// starts waiting on it, unless a watcher waits on it already, to tell
    /// them when it closes. Under the watcher's lock, so the close of the
    /// context this one replaced cannot overwrite it.
    fn running(&self, context: &Context) {
        let mut watched = self.watched.lock().unwrap_or_else(PoisonError::into_inner);
        self.show(|view| view.state = BrowserState::Running);
        if watched.as_ref() == Some(context.id()) {
            return;
        }
        *watched = Some(context.id().clone());
        tokio::spawn(watch_close(
            context.connection().clone(),
            context.id().clone(),
            Arc::downgrade(&self.view),
            Arc::clone(&self.watched),
        ));
    }

    /// Lets a person drive the session's tabs through `tabs`, as the
    /// session's tool set does once it holds them, whether or not the agent
    /// has the browser tools.
    pub(crate) fn drive_with(&self, tabs: Weak<dyn PersonTabs>) {
        let mut registered = lock(&self.person_tabs);
        registered.retain(|tabs| tabs.strong_count() > 0);
        registered.push(tabs);
    }

    /// The session's tabs, to drive for a person, while a tool set of the
    /// session runs: the newest one's.
    fn person_tabs(&self) -> Option<Arc<dyn PersonTabs>> {
        lock(&self.person_tabs).iter().rev().find_map(Weak::upgrade)
    }

    /// Starts tab `tab` loading `to` for a person.
    pub(crate) async fn person_navigate(
        &self,
        tab: String,
        to: BrowserDestination,
    ) -> Result<(), Refused> {
        let tabs = self.driven_by_person()?;
        tabs.navigate(tab, to).await?;
        self.follow_person();
        Ok(())
    }

    /// Opens, closes or switches to a tab for a person, answering the id of
    /// a tab it opened.
    pub(crate) async fn person_tab(
        &self,
        action: BrowserTabAction,
    ) -> Result<Option<String>, Refused> {
        let tabs = self.driven_by_person()?;
        let opened = tabs.tab(action).await?;
        self.follow_person();
        Ok(opened)
    }

    /// Closes the session's tabs and their browser context, whoever
    /// drives.
    pub(crate) async fn close_tabs(&self) -> Result<(), Refused> {
        self.person_tabs().ok_or(Refused::Closing)?.close().await;
        Ok(())
    }

    /// The session's tabs, while a person drives them.
    fn driven_by_person(&self) -> Result<Arc<dyn PersonTabs>, Refused> {
        if self.driver() != Driver::Person {
            return Err(Refused::NotDriver);
        }
        self.person_tabs().ok_or(Refused::Closing)
    }

    /// Whether the session's view lists tab `id`, as it does every tab of
    /// a running browser.
    pub(crate) fn shows_tab(&self, id: &str) -> bool {
        self.view.borrow().tabs.iter().any(|tab| tab.id == id)
    }

    /// Who drives the session's browser.
    pub(crate) fn driver(&self) -> Driver {
        self.view.borrow().driver
    }

    /// Hands the browser to the person at `connection`, with the tabs at
    /// `viewport` when their client named one, and answers the viewport the
    /// tabs are sized for. Starts the browser first if it is not running
    /// (never started, unloaded or crashed), as an agent's call does, with
    /// the same config and sandbox, so the tabs the person opens there open
    /// at the viewport. Refused, changing nothing, when the session is
    /// closing, its tabs gone, or the browser cannot start.
    pub(crate) async fn take_over(
        &self,
        connection: ConnectionId,
        viewport: Option<Viewport>,
    ) -> Result<Viewport, Refused> {
        self.person_tabs().ok_or(Refused::Closing)?;
        if self.view.borrow().state != BrowserState::Running {
            // The context only needs to open: the browser stays up for its
            // idle time, as after an agent's call.
            self.context().await.map_err(Refused::Browser)?;
        }
        Ok(self.hand_over(Driver::Person, connection, viewport))
    }

    /// Sizes the session's tabs for `viewport`, the size the person driving
    /// views them at. The tabs follow without the caller waiting, as soon
    /// as no agent call holds them.
    pub(crate) fn person_resize(&self, viewport: Viewport) -> Result<(), Refused> {
        let mut control = lock(&self.control);
        if control.person.is_none() {
            return Err(Refused::NotDriver);
        }
        self.person_tabs().ok_or(Refused::Closing)?;
        control.person_viewport = Some(viewport);
        drop(control);
        self.fit_tabs();
        Ok(())
    }

    /// The viewport the session's tabs are sized for: the person's while
    /// one drives and their client named it, the agent's [`VIEWPORT`]
    /// otherwise. A tab may lag it until the browser tools fit it.
    pub(crate) fn viewport(&self) -> Viewport {
        lock(&self.control).person_viewport.unwrap_or(VIEWPORT)
    }

    /// Hands the browser to `driver`, for the person at `connection` when
    /// that is a person.
    pub(crate) fn control(&self, driver: Driver, connection: ConnectionId) {
        self.hand_over(driver, connection, /*viewport*/ None);
    }

    /// Hands the browser to `driver`, sizing the tabs for `viewport` when
    /// a person takes it with one, and for the agent's when the agent
    /// does, and answers the viewport they are sized for.
    fn hand_over(
        &self,
        driver: Driver,
        connection: ConnectionId,
        viewport: Option<Viewport>,
    ) -> Viewport {
        let mut control = lock(&self.control);
        match driver {
            Driver::Person => {
                control.person = Some(connection);
                control.takeovers += 1;
                if viewport.is_some() {
                    control.person_viewport = viewport;
                }
            }
            Driver::Agent => {
                control.person = None;
                control.person_viewport = None;
            }
        }
        let sized_for = control.person_viewport.unwrap_or(VIEWPORT);
        self.show_driver(driver);
        drop(control);
        if driver == Driver::Person {
            self.follow_person();
        }
        self.fit_tabs();
        sized_for
    }

    /// Shows `driver` driving, under the control lock: each turn starts
    /// with no cursor, so a watch shows none of the last turn's and the
    /// first of this one goes out.
    fn show_driver(&self, driver: Driver) {
        self.show(|view| view.driver = driver);
        self.pointer.send_replace(None);
    }

    /// Has the browser tools fit the tabs to [`Self::viewport`], without
    /// waiting: they do once no agent call holds the tabs. An agent call
    /// sizes them for the agent itself before it acts.
    fn fit_tabs(&self) {
        if let Some(tabs) = self.person_tabs() {
            tokio::spawn(async move { tabs.fit().await });
        }
    }

    /// While a person drives, has the session's view follow what their
    /// driving does to its tabs, unless it does already. Runs after each of
    /// their actions too: a browser that started since has no follower.
    fn follow_person(&self) {
        if self.driver() != Driver::Person {
            return;
        }
        let Some(tabs) = self.person_tabs() else {
            return;
        };
        if self.following.swap(true, Ordering::AcqRel) {
            return;
        }
        let following = Arc::clone(&self.following);
        tokio::spawn(async move {
            tabs.follow().await;
            following.store(false, Ordering::Release);
        });
    }

    /// Hands the browser back to the agent if the person at `connection`
    /// drives it, as when their client left.
    pub(crate) fn connection_left(&self, connection: ConnectionId) {
        let mut control = lock(&self.control);
        if control.person == Some(connection) {
            control.person = None;
            control.person_viewport = None;
            self.show_driver(Driver::Agent);
            drop(control);
            self.fit_tabs();
        }
    }

    /// The browser's target of tab `id`, if the session's view lists it.
    pub(super) fn target_of(&self, id: &str) -> Option<TargetId> {
        let view = self.view.borrow();
        let tab = view.tabs.iter().find(|tab| tab.id == id)?;
        Some(tab.target.clone())
    }

    /// Waits until the agent drives the browser. A person may take it over
    /// again right after: [`Self::agent_drives`] says for sure.
    pub(crate) async fn agent_turn(&self) {
        // The view lives as long as this handle.
        let _ = self
            .view
            .subscribe()
            .wait_for(|view| view.driver == Driver::Agent)
            .await;
    }

    /// How many times a person has taken the browser over.
    pub(crate) fn takeovers(&self) -> u64 {
        lock(&self.control).takeovers
    }

    /// How many times a person has taken the browser over, if the agent
    /// drives it now, so a caller that remembers the count can tell whether
    /// a person drove since it last looked.
    pub(crate) fn agent_drives(&self) -> Option<u64> {
        let control = lock(&self.control);
        control.person.is_none().then_some(control.takeovers)
    }

    /// Starts a client's watch of tab `tab`, its frames scaled to `fit`.
    /// The watch keeps the browser open while it runs.
    pub(crate) async fn watch(
        &self,
        tab: &str,
        fit: Fit,
    ) -> Result<(BrowserWatchResponse, BrowserFrames), WatchRefused> {
        let target = self.target_of(tab).ok_or(WatchRefused::NoTab)?;
        // A watch never starts the browser: one that closed since the view
        // listed the tab took the tab along.
        let context = self.running_context().await.ok_or(WatchRefused::NoTab)?;
        self.browsers
            .watches
            .start(
                context,
                &target,
                fit,
                self.viewport(),
                self.pointer.subscribe(),
            )
            .await
            .map_err(|error| WatchRefused::Browser(error.to_string()))
    }

    /// The session's browser context, if its browser runs and has one,
    /// without starting either.
    pub(crate) async fn running_context(&self) -> Option<Context> {
        let manager = match &*self.browsers.current.lock().await {
            Service::Running(current) => Some(current.manager.clone()),
            Service::NotStarted | Service::Closed => None,
        };
        manager?.existing_context(&self.session).await
    }

    /// Closes the session's context and its tabs, such as when the session
    /// ends.
    pub(crate) async fn release(&self) {
        let manager = match &*self.browsers.current.lock().await {
            Service::Running(current) => Some(current.manager.clone()),
            Service::NotStarted | Service::Closed => None,
        };
        if let Some(manager) = manager {
            manager.release(&self.session).await;
        }
    }
}

/// Why a watch did not start.
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum WatchRefused {
    /// The session has no such tab.
    NoTab,
    /// The browser failed, as this says.
    Browser(String),
}

/// Waits for the browser of `context` to close, then tells the session's
/// clients, through `view`, whether it closed as rho asked, as when it went
/// unused, or on its own, its tabs gone with it. Holds no context, so it
/// never keeps the browser open, and the view weakly, so it never keeps a
/// gone session's.
async fn watch_close(
    connection: Connection,
    context: BrowserContextId,
    view: Weak<watch::Sender<BrowserView>>,
    watched: Arc<Mutex<Option<BrowserContextId>>>,
) {
    let reason = connection.wait_closed().await;
    let mut watched = watched.lock().unwrap_or_else(PoisonError::into_inner);
    // A later call moved the session to another context.
    if watched.as_ref() != Some(&context) {
        return;
    }
    *watched = None;
    let state = closed_state(&reason);
    tracing::debug!(%reason, ?state, "a session's browser closed");
    if let Some(view) = view.upgrade() {
        // Whoever drove the browser still does, so a person keeps it when it
        // starts again.
        view.send_modify(|view| {
            *view = BrowserView {
                state,
                driver: view.driver,
                ..BrowserView::default()
            };
        });
    }
}

fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
    mutex.lock().unwrap_or_else(PoisonError::into_inner)
}

/// A [`SessionBrowser::context`] call starting the browser. Unless it got
/// the context, it puts the state from before back as it ends, failed or
/// dropped, as when its tool call was cancelled; unless the browser's
/// close was told meanwhile.
struct Starting<'a> {
    view: &'a watch::Sender<BrowserView>,
    /// The state to put back; `None` once the call got the context.
    before: Option<BrowserState>,
}

impl Drop for Starting<'_> {
    fn drop(&mut self) {
        if let Some(before) = self.before {
            self.view.send_if_modified(|view| {
                let starting = view.state == BrowserState::Starting;
                if starting {
                    view.state = before;
                }
                starting && before != BrowserState::Starting
            });
        }
    }
}

/// What a browser that closed for `reason` is to the session's clients.
/// rho closes the browser by asking it, and it exits cleanly; a browser
/// that crashed, was killed, or broke its pipe did not.
fn closed_state(reason: &CloseReason) -> BrowserState {
    match reason {
        CloseReason::Exited(status) if status.success() => BrowserState::Unloaded,
        CloseReason::Exited(_)
        | CloseReason::PipeClosed
        | CloseReason::Io(_)
        | CloseReason::Malformed(_) => BrowserState::Crashed,
    }
}

#[cfg(test)]
#[path = "service_tests.rs"]
mod tests;

#[path = "service_moves.rs"]
mod moves;