devsandbox 0.11.1

Manage devcontainer-style sandboxes on docker, podman, or Apple container — many throwaway instances per repo from one TOML config.
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
//! The live host side the daemon runs (docs/architecture/daemon/host-poll.md
//! "Bridges"): one bridge per running instance with a helper
//! (`devsbd::bridge::Bridges`, with the notify sink and the control handler),
//! so outboxes drain, popups fire and control ops answer with the dashboard
//! closed; plus the once-per-boot `autostart = true` pass at start and the
//! scheduled feature updates (`updates.rs`).
//!
//! Threading: a `serve-poll` thread is the daemon's one container poll. Each
//! tick it lists every devsandbox container once; from the running ones it
//! counts the live-instance holders, hands the list to the bridge worker
//! (`Bridges::spawn_worker`, its own thread, which owns every bridge), bumps
//! [`Host::changes`] when the list moved (the API's `instances.changed`),
//! and hands the list to the forward registry too (`forwards.rs`: configured
//! `forwardPorts` follow it). Then, while a dashboard watches a config root
//! ([`Observers`], `instances.watch`), it asks for stats when due and joins
//! every watched root against that one listing (`snapshots.rs`), each
//! snapshot handed to the daemon to push, with this host's capacity report
//! (`capacity.rs`: the runtime's `info` at most every
//! `capacity::ENGINE_TTL`, free memory and disk, the running instances,
//! `member.toml`'s caps). The poll also owns the runtime's
//! event stream ([`EventWatcher`], `events.rs`): each relevant container
//! event wakes it at once. The sleep is [`tick`]:
//! [`snapshots::LISTING_INTERVAL`] while anything is watched, else
//! [`QUIET_POLL`] while the event stream is live (or no runtime is
//! installed: then nothing is asked of one, [`poll`]) and every bridge is
//! settled, else [`POLL`]. A [`Waker`] (the API's `bridges.ensure`) cuts the poll's sleep
//! short and marks its container urgent, so a CLI command or a dashboard
//! terminal gets its bridge now rather than within [`POLL`]; the bridges are
//! handed their list before any stats or snapshot work.
//! [`Waker::refresh`] (and a container event) cuts it short with no container
//! urgent (a `state.toml` write, a new watch). A `serve-autostart` thread runs the autostart pass
//! once per config root recorded in `state.toml`; a `serve-updates` thread
//! runs `updates::pass` at start and every `updates::CHECK_EVERY`. Dropping
//! [`Host`] stops the poll, which drops the event watcher (killing its
//! child) and the worker (killing every bridge's `exec`), kills a running
//! update, and joins the threads.

use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, Condvar, Mutex};
use std::thread::JoinHandle;
use std::time::{Duration, Instant};

use serde_json::Value;

use super::capacity::{HostCapacity, InstalledFn};
use super::events::{EVENTS_RETRY, EventWatcher};
use super::capacity::Own;
use super::snapshots::{self, Join, Snapshots};
use crate::devsbd::bridge::{self, BridgeBoard, Bridges, Readiness, SinkHooks};
use crate::runtime::{ContainerRow, NAME_PREFIX};
use crate::snapshot::RuntimeView;
use crate::state::State;

/// How often the daemon re-lists the running containers. A new instance gets
/// its bridge (and counts as a holder) within this; bridge deaths are retried
/// on their own gaps (`bridge::RETRY`), checked on each poll.
pub const POLL: Duration = Duration::from_secs(5);

/// The poll's sleep while the runtime's event stream is live (nothing
/// watched, bridges settled): a safety net, since events wake it. It catches
/// what nothing announces: a missed event, a host agent appearing without a
/// `bridges.ensure`. (Config edits wake the poll through `serve-watch`.)
pub const QUIET_POLL: Duration = Duration::from_secs(60);

/// Called with each successful poll's running container names.
pub type OnRunning = Box<dyn Fn(&[String]) + Send>;

/// The watched roots' side of the poll, from the daemon.
pub struct Observers {
    /// The config roots some connection watches now.
    pub watched: Box<dyn Fn() -> BTreeSet<PathBuf> + Send>,
    pub cache: Arc<Snapshots>,
    pub join: Join,
    /// Each watched root's snapshot (`instances.snapshot` params), every
    /// tick; it must not block.
    pub on_snapshot: Box<dyn Fn(&Path, Arc<Value>) + Send>,
    /// `member.toml`'s caps now, for the capacity report.
    pub own: Box<dyn Fn() -> Own + Send>,
    /// This host's capacity: the poll keeps its running count, and asks it
    /// for the report while a root is watched (the daemon asks it too).
    pub capacity: Arc<HostCapacity>,
    /// Whether a container runtime is installed, asked each pass
    /// (`runtime::installed::installed`, cached there): without one the
    /// poll asks no runtime ([`poll`]).
    pub installed: InstalledFn,
}

/// What the poll thread sleeps on: stop, containers a client asked a
/// bridge for, or a snapshot refresh.
#[derive(Default)]
struct Signal {
    stop: bool,
    /// `(container, ticket)`: see `bridge::BridgeBoard`.
    urgent: Vec<(String, u64)>,
    refresh: bool,
}

type Shared = Arc<(Mutex<Signal>, Condvar)>;

/// Wakes the poll thread for one container: it re-lists at once and the
/// bridge worker reconciles with that container urgent
/// (`Bridges::reconcile`). Cloneable; outlives nothing (a wake after the
/// poll stopped is ignored). Carries the bridges' [`BridgeBoard`], so the
/// API can wait for a bridge without touching the worker.
#[derive(Clone)]
pub struct Waker(Shared, BridgeBoard);

impl Waker {
    /// Queue `container` urgent; returns its ticket on the board.
    pub fn wake(&self, container: String) -> u64 {
        let ticket = self.1.ticket();
        let (lock, cvar) = &*self.0;
        lock.lock().unwrap_or_else(|e| e.into_inner()).urgent.push((container, ticket));
        cvar.notify_all();
        ticket
    }

    /// Poll now, no container urgent: a `state.toml` write, a new watch (the
    /// watched roots' snapshots); a container event takes the same path.
    pub fn refresh(&self) {
        refresh(&self.0);
    }
}

/// Cut the poll's sleep short for a full pass (re-list, reconcile, snapshots).
fn refresh(shared: &Shared) {
    let (lock, cvar) = &**shared;
    lock.lock().unwrap_or_else(|e| e.into_inner()).refresh = true;
    cvar.notify_all();
}

/// `bridges.ensure` against the real state and this daemon's bridges.
impl super::api::Bridging for Waker {
    fn container(&self, instance: &str) -> anyhow::Result<Option<String>> {
        Ok(State::load()?.instances.get(instance).map(|i| i.container.clone()))
    }

    fn report_agent(&self, path: PathBuf) {
        bridge::report_agent(path);
    }

    fn reconcile_now(&self, container: String) -> u64 {
        self.wake(container)
    }

    fn wait_ready(&self, container: &str, ticket: u64, timeout: Duration) -> Readiness {
        self.1.wait(container, ticket, timeout)
    }
}

pub struct Host {
    stop: Shared,
    board: BridgeBoard,
    live: Arc<AtomicUsize>,
    autostarting: Arc<AtomicUsize>,
    updating: Arc<AtomicUsize>,
    changes: Arc<AtomicU64>,
    threads: Vec<JoinHandle<()>>,
}

impl Host {
    /// Start the poll (bridges) and autostart threads. `log` writes one
    /// `serve.log` line; `sink` is the bridges' sink's hooks: `on_shown`
    /// gets each stored container message's status line (the API's
    /// `inbox.shown`), `opener` each admitted `open` record (the daemon's
    /// routes it, `serve::opens`), `on_open_done` each one refused at intake
    /// (`opens.done`); `on_running` gets each poll's running containers (the
    /// forward registry's sync; it must not block); `observers` the watched
    /// roots the poll collects snapshots for; `asks` the permission
    /// requests the broker's held calls wait on.
    pub fn start(
        log: fn(&str),
        sink: SinkHooks,
        on_running: OnRunning,
        observers: Observers,
        asks: Arc<crate::broker::asks::Registry>,
    ) -> Host {
        let stop: Shared = Arc::default();
        let board = BridgeBoard::default();
        // A failed bridge unsettles the board: wake the poll so it drops to
        // `POLL` and acts on the retry. Holds only the signal, not the poll.
        let shared = Arc::clone(&stop);
        board.on_failed(Box::new(move || refresh(&shared)));
        let live = Arc::new(AtomicUsize::new(0));
        // Counted before the thread runs, so the first idle check sees it.
        let autostarting = Arc::new(AtomicUsize::new(1));
        let updating = Arc::new(AtomicUsize::new(1));
        let changes = Arc::new(AtomicU64::new(0));
        let mut threads = Vec::new();
        let spawned = {
            let (stop, live, changes, board) = (Arc::clone(&stop), Arc::clone(&live), Arc::clone(&changes), board.clone());
            std::thread::Builder::new()
                .name("serve-poll".into())
                .spawn(move || poll(&stop, &live, &changes, log, sink, on_running, &observers, board, asks))
        };
        match spawned {
            Ok(t) => threads.push(t),
            Err(e) => log(&format!("cannot start the bridge thread: {e}")),
        }
        let spawned = {
            let autostarting = Arc::clone(&autostarting);
            std::thread::Builder::new().name("serve-autostart".into()).spawn(move || {
                autostart_all();
                autostarting.store(0, Ordering::Release);
            })
        };
        match spawned {
            Ok(t) => threads.push(t),
            Err(e) => {
                autostarting.store(0, Ordering::Release);
                log(&format!("cannot start the autostart thread: {e}"));
            }
        }
        let spawned = {
            let (stop, updating) = (Arc::clone(&stop), Arc::clone(&updating));
            std::thread::Builder::new().name("serve-updates".into()).spawn(move || updates_loop(&stop, &updating, log))
        };
        match spawned {
            Ok(t) => threads.push(t),
            Err(e) => {
                updating.store(0, Ordering::Release);
                log(&format!("cannot start the updates thread: {e}"));
            }
        }
        Host { stop, board, live, autostarting, updating, changes, threads }
    }

    /// The poll's [`Waker`], for the API.
    pub fn waker(&self) -> Waker {
        Waker(Arc::clone(&self.stop), self.board.clone())
    }

    /// The bridges' board: their links, for `serve::helper`.
    pub fn board(&self) -> BridgeBoard {
        self.board.clone()
    }

    /// Bumped each time a poll finds the running containers changed; the
    /// daemon's notification watcher compares it.
    pub fn changes(&self) -> Arc<AtomicU64> {
        Arc::clone(&self.changes)
    }

    /// Running instances that expect a live host, as of the last poll.
    pub fn live_instances(&self) -> usize {
        self.live.load(Ordering::Acquire)
    }

    /// Control requests being served on this daemon's bridges.
    pub fn control(&self) -> usize {
        bridge::control_in_flight()
    }

    /// 1 while the startup autostart pass runs: killing it mid-`run` would
    /// leave a half-made instance, so it holds the daemon.
    pub fn autostarting(&self) -> usize {
        self.autostarting.load(Ordering::Acquire)
    }

    /// 1 while a feature update pass runs: an idle exit would kill its
    /// update.
    pub fn updating(&self) -> usize {
        self.updating.load(Ordering::Acquire)
    }
}

impl Drop for Host {
    fn drop(&mut self) {
        let (lock, cvar) = &*self.stop;
        lock.lock().unwrap_or_else(|e| e.into_inner()).stop = true;
        cvar.notify_all();
        // The poll thread drops the bridge worker, which kills every bridge;
        // autostart is waited out (see `autostarting`); a running update is
        // killed (`updates_loop`), its claim kept: retried after `updates::RETRY`.
        for t in self.threads.drain(..) {
            let _ = t.join();
        }
    }
}

/// The poll loop: list, count, reconcile, collect the watched roots'
/// snapshots, sleep (until [`tick`] passes, a [`Waker`] fires or a container
/// event arrives), until stopped. The event watcher lives as long as the
/// loop: its down transition wakes the loop too, so a `live` read just before
/// the stream dies never holds the sleep at [`QUIET_POLL`]. With the runtime unreachable the last list stands (bridges and
/// the holder count are kept, not torn down on a blip); the outage is logged
/// once, and urgent containers wait for the next list. Watched roots still
/// get a snapshot then, saying the runtime is down.
///
/// With no runtime installed ([`Observers::installed`]) the pass asks
/// nothing of one: no listing, version or stats, no event stream (started
/// once one is installed, dropped if it goes), the bridges and forwards
/// left as they are; watched roots get a driver snapshot
/// (`RuntimeView::driver`: no `error`, `no_runtime`), and the sleep is the
/// quiet one ([`tick`]'s `quiet`), as nothing changes but the config.
/// The absence is logged once.
#[allow(clippy::too_many_arguments)]
fn poll(
    stop: &Shared,
    live: &AtomicUsize,
    changes: &AtomicU64,
    log: fn(&str),
    sink: SinkHooks,
    on_running: OnRunning,
    observers: &Observers,
    board: BridgeBoard,
    asks: Arc<crate::broker::asks::Registry>,
) {
    let broker: Option<Arc<dyn bridge::Broker>> = match crate::broker::serve::Service::from_host(log, Arc::clone(&asks)) {
        Ok(service) => Some(Arc::new(service)),
        Err(e) => {
            log(&format!("broker: {e:#}: no credential is brokered"));
            None
        }
    };
    let worker = Bridges::spawn_worker(Some(sink), broker, Some(Arc::clone(&asks)), board.clone());
    let rt = crate::runtime::backend();
    // Declared after `worker`, so it drops (child killed, thread joined)
    // first. Started once a runtime is installed.
    let mut events: Option<EventWatcher> = None;
    let mut down = false;
    let mut absent = false;
    let mut last: Vec<String> = Vec::new();
    let mut urgent: Vec<(String, u64)> = Vec::new();
    loop {
        let installed = (observers.installed)();
        if installed == absent {
            log(&match installed {
                true => "a container runtime is installed".to_string(),
                false => format!(
                    "no container runtime ({}): this host drives other machines and runs nothing",
                    crate::runtime::installed::missing_note()
                ),
            });
            absent = !installed;
        }
        if !installed {
            events = None;
        } else if events.is_none() {
            let argv = rt.events_argv().map(|a| a.into_iter().map(String::from).collect());
            let shared = Arc::clone(stop);
            events = Some(EventWatcher::start(rt.bin(), argv, Box::new(move || refresh(&shared)), log, EVENTS_RETRY));
        }
        // Quiet: the backend captures stderr.
        let listing = installed.then(|| rt.list(true, NAME_PREFIX));
        match listing.as_ref().map(|l| l.as_ref().map(|rows| running(rows))) {
            // No container to bridge: an urgent one waits out its timeout.
            None => urgent.clear(),
            Some(Ok(mut running)) => {
                running.sort();
                if running != last {
                    changes.fetch_add(1, Ordering::Release);
                    last.clone_from(&running);
                }
                if down {
                    log("the container runtime answers again");
                    down = false;
                }
                // A state that won't load keeps the last count, like the
                // runtime being down.
                if let Ok(state) = State::load() {
                    live.store(live_instances(&running, &state, |key| expects_host(&state, key)), Ordering::Release);
                    // Instances running as of the last listing that loaded with its state.
                    observers.capacity.set_running(running_instances(&running, &state));
                }
                on_running(&running);
                worker.send(running, std::mem::take(&mut urgent));
            }
            Some(Err(e)) => {
                if !down {
                    log(&format!("cannot list containers ({e:#}); retrying every {}s", POLL.as_secs()));
                    down = true;
                }
            }
        }
        // After the bridges' hand-off: an urgent bridge never waits on stats.
        let watched = (observers.watched)();
        observers.cache.prune(&watched);
        if !watched.is_empty() {
            let publish = |pushed: Vec<(PathBuf, Arc<Value>)>| {
                for (dir, params) in pushed {
                    (observers.on_snapshot)(&dir, params);
                }
            };
            // The capacity report rides every root's snapshot: only built
            // while someone watches.
            let own = (observers.own)();
            observers.cache.set_capacity(&observers.capacity.report(&own));
            let listed = matches!(listing, Some(Ok(_)));
            let due = listed && observers.cache.stats_due(&watched, Instant::now());
            let mut view = match listing {
                Some(listing) => RuntimeView::from_parts(rt, Some(listing), None),
                None => RuntimeView::driver(),
            };
            if due {
                // A new watch's root shows its statuses before the stats
                // pass (~1.5 s on docker): Disk, Listing, then Full.
                publish(observers.cache.collect(&view, &observers.cache.uncached(&watched), &*observers.join));
                view.add_stats(rt.stats());
            }
            publish(observers.cache.collect(&view, &watched, &*observers.join));
        }
        // A request no call comes back for leaves `access.pending` only
        // when something locks the registry.
        asks.prune();
        // Read before the lock: a stream lost after this read sets `refresh`,
        // which the wait sees at once.
        let quiet = !installed || events.as_ref().is_some_and(EventWatcher::is_live);
        let sleep = tick(!watched.is_empty(), quiet, board.settled());
        let (lock, cvar) = &**stop;
        let guard = lock.lock().unwrap_or_else(|e| e.into_inner());
        let (mut guard, _) = cvar
            .wait_timeout_while(guard, sleep, |s| !s.stop && s.urgent.is_empty() && !s.refresh)
            .unwrap_or_else(|e| e.into_inner());
        if guard.stop {
            break;
        }
        guard.refresh = false;
        urgent.append(&mut guard.urgent);
    }
    // `events` drops here (kills its child, joins), then `worker`: closes its
    // channel and joins, killing every bridge.
}

/// The poll's sleep: the dashboards' cadence while a root is watched; else
/// the long [`QUIET_POLL`] while it's `quiet` (container events wake the
/// poll, or no runtime is installed: nothing to list) and the
/// bridges are settled (`BridgeBoard::settled`), since a pending handshake
/// and a dead bridge's retry (`bridge::retry_decision`, `bridge::RETRY`) are
/// only acted on by a poll pass; else [`POLL`]. A bridge failing during a
/// quiet sleep wakes the poll (`BridgeBoard::on_failed`), so its retry
/// keeps the `POLL` schedule.
fn tick(watched: bool, quiet: bool, bridges_settled: bool) -> Duration {
    if watched {
        snapshots::LISTING_INTERVAL
    } else if quiet && bridges_settled {
        QUIET_POLL
    } else {
        POLL
    }
}

fn running(rows: &[ContainerRow]) -> Vec<String> {
    rows.iter().filter(|r| r.is_running()).map(|r| r.name.clone()).collect()
}

/// Whether instance `key` expects a live host while it runs: it carries a
/// credential claim (the broker serves it), else [`holds_host`], with one
/// state + config load for both of its rules.
fn expects_host(state: &State, key: &str) -> bool {
    state.instances.get(key).is_some_and(|i| !i.claims.is_empty())
        || crate::commands::dispatch::current_sandbox(key).is_some_and(|(info, props)| holds_host(&info, &props))
}

/// The holder rule: the instance declares `dispatcher` (children never count
/// as one) or `inbox = true` (its threads' events need a live host).
fn holds_host(info: &crate::state::Instance, props: &crate::config::SandboxProperties) -> bool {
    use crate::commands::dispatch::{is_dispatcher, is_inbox_owner};
    is_dispatcher(info, props) || is_inbox_owner(props)
}

/// The live-instance holder count: instances in `state` whose container is
/// in `running` and that `expects` a live host.
fn live_instances(running: &[String], state: &State, expects: impl Fn(&str) -> bool) -> usize {
    state
        .instances
        .iter()
        .filter(|(key, info)| running.contains(&info.container) && expects(key))
        .count()
}

/// The capacity report's `running`: instances in `state` whose container is
/// in `running` (services and strays aren't instances).
fn running_instances(running: &[String], state: &State) -> usize {
    live_instances(running, state, |_| true)
}

/// Every distinct config root recorded in `state`, sorted. Instances from
/// before roots were recorded have none and are skipped.
pub(super) fn config_roots(state: &State) -> Vec<PathBuf> {
    let roots: BTreeSet<PathBuf> = state.instances.values().filter_map(|i| i.config_dir.clone()).collect();
    roots.into_iter().collect()
}

/// The scheduled updates: a pass now, then every `CHECK_EVERY` until the
/// host stops (which also cuts a running update short).
fn updates_loop(stop: &Shared, updating: &AtomicUsize, log: fn(&str)) {
    let stopped = || stop.0.lock().unwrap_or_else(|e| e.into_inner()).stop;
    loop {
        updating.store(1, Ordering::Release);
        super::updates::pass(&mut super::updates::Live::new(&stopped), &log);
        updating.store(0, Ordering::Release);
        let deadline = Instant::now() + super::updates::CHECK_EVERY;
        let (lock, cvar) = &**stop;
        let mut signal = lock.lock().unwrap_or_else(|e| e.into_inner());
        while !signal.stop {
            let Some(left) = deadline.checked_duration_since(Instant::now()).filter(|d| !d.is_zero()) else { break };
            signal = cvar.wait_timeout(signal, left).unwrap_or_else(|e| e.into_inner()).0;
        }
        if signal.stop {
            return;
        }
    }
}

/// The `autostart = true` pass for every known config root. Idempotent per
/// boot (`State.autostart_boot`), so the clients that still call it too are
/// harmless. Its notes go to stderr/stdout, i.e. `serve.log`.
fn autostart_all() {
    let Ok(state) = State::load() else { return };
    for root in config_roots(&state) {
        crate::commands::autostart::autostart(&root);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn state(text: &str) -> State {
        toml::from_str(text).unwrap()
    }

    const STATE: &str = r#"
        [instance.disp]
        sandbox = "disp"
        container = "devsandbox-disp"
        folder = "/w/disp"
        workspace = "/workspaces/disp"
        created_unix = 0
        config_dir = "/cfg/a"

        [instance.disp-pr-1]
        sandbox = "web"
        container = "devsandbox-disp-pr-1"
        folder = "/w/web"
        workspace = "/workspaces/web"
        created_unix = 0
        dispatcher = "disp"
        config_dir = "/cfg/a"

        [instance.other]
        sandbox = "disp"
        container = "devsandbox-other"
        folder = "/w/disp"
        workspace = "/workspaces/disp"
        created_unix = 0
        config_dir = "/cfg/b"

        [instance.old]
        sandbox = "web"
        container = "devsandbox-old"
        folder = "/w/web"
        workspace = "/workspaces/web"
        created_unix = 0
    "#;

    #[test]
    fn holders_declare_dispatcher_or_inbox() {
        let s = state(STATE);
        let props = |toml: &str| {
            let config = crate::config::Config::parse(&format!("[sandbox.x]\n{toml}")).unwrap();
            config.resolve_sandbox("x").unwrap().properties
        };
        let (top, child) = (&s.instances["disp"], &s.instances["disp-pr-1"]);
        let dispatcher = props("dispatcher = { spawn = [] }\n");
        let inbox = props("inbox = true\n");
        assert!(holds_host(top, &dispatcher));
        assert!(holds_host(top, &inbox));
        assert!(!holds_host(top, &props("inbox = false\n")));
        assert!(!holds_host(top, &props("")));
        // A child is never a dispatcher, but may own threads.
        assert!(!holds_host(child, &dispatcher));
        assert!(holds_host(child, &inbox));
    }

    #[test]
    fn an_instance_with_a_claim_holds_the_host() {
        let s = state(&format!(
            "{STATE}\n[[instance.old.claims]]\nkind = \"sentry\"\nfeature = \"./s\"\nversion = \"v\"\nclaim = \"{{}}\"\nphantom = \"p\"\n"
        ));
        assert!(expects_host(&s, "old"));
        assert_eq!(live_instances(&["devsandbox-old".to_string()], &s, |k| expects_host(&s, k)), 1);
    }

    #[test]
    fn live_instances_are_running_ones_that_expect_a_host() {
        let s = state(STATE);
        let dispatchers = |k: &str| k == "disp" || k == "other";
        let running = |names: &[&str]| names.iter().map(|n| n.to_string()).collect::<Vec<_>>();
        assert_eq!(live_instances(&running(&[]), &s, dispatchers), 0);
        assert_eq!(live_instances(&running(&["devsandbox-disp", "devsandbox-disp-pr-1"]), &s, dispatchers), 1);
        assert_eq!(live_instances(&running(&["devsandbox-disp", "devsandbox-other"]), &s, dispatchers), 2);
        // Running but not a dispatcher (a child, a plain sandbox): not a holder.
        assert_eq!(live_instances(&running(&["devsandbox-disp-pr-1", "devsandbox-old"]), &s, dispatchers), 0);
        // A running container no state entry knows: not a holder.
        assert_eq!(live_instances(&running(&["devsandbox-stray"]), &s, |_| true), 0);
        // The capacity report counts every running instance.
        let all = running(&["devsandbox-disp", "devsandbox-disp-pr-1", "devsandbox-old", "devsandbox-svc-pg"]);
        assert_eq!(running_instances(&all, &s), 3);
    }

    #[test]
    fn one_listing_feeds_the_running_list_and_the_tick_follows_watches() {
        let row = |name: &str, state: &str| ContainerRow { name: name.into(), state: state.into(), ..Default::default() };
        let rows = [row("devsandbox-a", "running"), row("devsandbox-b", "exited"), row("devsandbox-c", "running")];
        assert_eq!(running(&rows), ["devsandbox-a", "devsandbox-c"]);
        for (live, settled) in [(false, false), (false, true), (true, false), (true, true)] {
            assert_eq!(tick(true, live, settled), snapshots::LISTING_INTERVAL, "watched wins");
        }
        assert_eq!(tick(false, true, true), QUIET_POLL, "events live, or no runtime installed");
        assert_eq!(tick(false, false, true), POLL, "no event stream");
        assert_eq!(tick(false, true, false), POLL, "a bridge pending or failed");
        assert_eq!(tick(false, false, false), POLL);
    }

    static LOGGED: Mutex<Vec<String>> = Mutex::new(Vec::new());

    fn logged(line: &str) {
        LOGGED.lock().unwrap().push(line.to_string());
    }

    /// No runtime installed: the poll lists nothing (no running list, no
    /// bridge hand-off), asks no `info`, and a watched root's snapshot
    /// carries `no_runtime`, no `error` and `runtime: false`; the absence
    /// is logged once.
    #[test]
    fn without_a_runtime_the_poll_asks_none() {
        use serde_json::json;
        use std::sync::atomic::AtomicBool;
        let stop: Shared = Arc::default();
        let (live, changes) = (AtomicUsize::new(0), AtomicU64::new(0));
        let listed = Arc::new(AtomicBool::new(false));
        let on_running: OnRunning = {
            let listed = Arc::clone(&listed);
            Box::new(move |_| listed.store(true, Ordering::SeqCst))
        };
        let asked = Arc::new(AtomicUsize::new(0));
        let pushed: Arc<Mutex<Vec<Arc<Value>>>> = Arc::default();
        let observers = {
            let (asked, pushed) = (Arc::clone(&asked), Arc::clone(&pushed));
            Observers {
                watched: Box::new(|| BTreeSet::from([PathBuf::from("/r")])),
                cache: Arc::default(),
                join: Arc::new(|_, view: &RuntimeView| super::super::api::InstancesList {
                    snapshot: {
                        let mut s = snapshots::tests::snapshot(Vec::new(), view.depth == crate::snapshot::Depth::Full);
                        s.no_runtime = view.no_runtime;
                        s.error = (!view.errors.is_empty()).then(|| view.errors.join("; "));
                        s
                    },
                    thread_children: Default::default(),
                }),
                on_snapshot: Box::new(move |_, params| pushed.lock().unwrap().push(params)),
                own: Box::new(Own::default),
                capacity: Arc::new(HostCapacity::new(Arc::new(|| panic!("info asked")), Arc::new(|| panic!("gpu asked")), Arc::new(|| false))),
                installed: Arc::new(move || {
                    asked.fetch_add(1, Ordering::SeqCst);
                    false
                }),
            }
        };
        let sink = SinkHooks { on_shown: None, opener: Arc::new(|_, _, _| {}), on_open_done: None, log: logged };
        let thread = {
            let stop = Arc::clone(&stop);
            std::thread::spawn(move || poll(&stop, &live, &changes, logged, sink, on_running, &observers, BridgeBoard::default(), Arc::new(crate::broker::asks::Registry::new(std::env::temp_dir()))))
        };
        // Two passes: a refresh cuts the 2 s sleep short.
        let deadline = Instant::now() + Duration::from_secs(10);
        while pushed.lock().unwrap().len() < 2 && Instant::now() < deadline {
            refresh(&stop);
            std::thread::sleep(Duration::from_millis(20));
        }
        {
            let (lock, cvar) = &*stop;
            lock.lock().unwrap().stop = true;
            cvar.notify_all();
        }
        thread.join().unwrap();
        let pushed = pushed.lock().unwrap();
        assert!(pushed.len() >= 2, "{pushed:?}");
        for p in pushed.iter() {
            assert_eq!((&p["no_runtime"], &p["error"], &p["capacity"]["runtime"]), (&json!(true), &Value::Null, &json!(false)), "{p}");
        }
        assert!(!listed.load(Ordering::SeqCst), "nothing listed");
        assert!(asked.load(Ordering::SeqCst) >= 2, "asked each pass");
        let lines = LOGGED.lock().unwrap();
        assert_eq!(lines.iter().filter(|l| l.starts_with("no container runtime")).count(), 1, "{lines:?}");
    }

    #[test]
    fn config_roots_are_distinct_and_skip_unrecorded() {
        let roots = config_roots(&state(STATE));
        assert_eq!(roots, [PathBuf::from("/cfg/a"), PathBuf::from("/cfg/b")]);
        assert!(config_roots(&State::default()).is_empty());
    }
}