devsandbox 0.8.0

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
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
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
//! The dashboard's link to the host daemon (docs/architecture/daemon/client-server.md, docs/reference/api.md): one
//! worker thread that owns the [`Conn`], so the UI thread never waits on the
//! socket or on a lazy start (up to 5 s).
//!
//! It connects lazily, subscribes to `inbox`, `instances` and `forwards`,
//! and forwards what the daemon says as [`DaemonUpdate`]s the event loop
//! drains. Holding the connection makes the dashboard a holder, so the worker
//! reconnects after a `closing`, an EOF or an error, on the [`Backoff`]
//! schedule; after a version handoff it first waits for the successor
//! without starting one (see [`open`]).
//!
//! The tree: the dashboard is an observer of the daemon's one poll. Every
//! (re)connect watches the dashboard's config root (`instances.watch`, a
//! watch doesn't survive the connection), and each `instances.snapshot`
//! push (every collection, ~2 s, the daemon's Disk → Listing → Full walk
//! first) is a [`DaemonUpdate::Snapshot`]. A lost connection, or one that
//! can't be made, is a [`DaemonUpdate::Down`]: the tree keeps its last
//! snapshot, marked stale with why, until the next push.
//!
//! Inbox writes: the event loop hands the worker its `Op`s while
//! [`DaemonWorker::connected`]; each goes out as its API method
//! ([`op_call`]). Without a daemon the loop applies them itself through
//! `inbox::ops::apply`, and so does the worker for ops it gets after losing
//! the connection: the API runs the same ops code, so the owner's events are
//! the same either way. Reads stay local (the store file is the truth): an
//! `inbox.changed` only makes the loop reload at once.
//!
//! Ports tab: the daemon owns every forward (`serve::forwards`), so they
//! outlive the dashboard. The worker subscribes to `forwards` too and, on
//! `forwards.changed` and after every (re)connect, fetches `forwards.list`
//! for the dashboard's config root ([`DaemonUpdate::Ports`]); `forwards.status`
//! lines are status lines. Adds and stops go out as `forwards.add` /
//! `forwards.rm` ([`Cmd::ForwardAdd`], [`Cmd::ForwardRm`]). Disconnected, the
//! tab has no rows and an add says the daemon is needed.
//!
//! Machines tab: `a` is `machines.set {name, agent}` ([`Cmd::MachineSet`]),
//! answered by a status line; the row shows the new `agent` with the next
//! snapshot push (the daemon's reload re-publishes). Disconnected, the
//! line says it needs devsandbox serve.
//!
//! Builds: `d` on an in-flight row is `instances.cancel` ([`Cmd::Cancel`]),
//! whoever started the build; the answer is a status line. The verbs
//! themselves don't go through here: each holds its own connection until
//! it's answered (`tui::spawn_verb`).
//!
//! One-shot reads and writes: the logs modal (`containers.logs`), the config
//! view (`sandboxes.get`/`services.get`, `containers.inspect`), the build
//! log (`instances.buildLog`), process signals (`instances.signal`),
//! `:rename` (`instances.rename`) and done/undone (`instances.done`) are
//! quick, so they share this connection ([`Cmd::Fetch`], [`Cmd::Signal`],
//! [`Cmd::Rename`], [`Cmd::Done`]). Each is answered by one
//! [`DaemonUpdate`] naming its target; disconnected, that answer says the
//! dashboard needs devsandbox serve ([`needs_serve`]), as `cancel`'s does.
//!
//! A command channel plus a short-joining `Drop`; nothing is ever written to
//! stderr, failures are [`DaemonUpdate::Status`] lines.

use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender};
use std::thread::JoinHandle;
use std::time::{Duration, Instant};

use anyhow::Result;
use serde_json::{Value, json};

use super::app::{ConfigKind, Fetch, PendingDone, PendingSignal, PortRequest, PortRow};
use crate::build_log::Tail;
use crate::config::SandboxText;
use crate::inbox::{self, Op};
use crate::serve::api::InstancesList;
use crate::serve::client::{self, Conn};
use crate::serve::forwards::{Added, ForwardRow};
use crate::serve::endpoint;
use crate::serve::proto::{Response, Version};
use crate::serve::snapshots::SnapshotMachine;
use super::remote::{Route, split};

/// How long one wait for a notification blocks while connected: the
/// latency of an inbox write queued meanwhile, and of the worker noticing
/// it was dropped.
const POLL: Duration = Duration::from_millis(100);
/// How long [`Drop`] waits for the worker before detaching it (it may be
/// mid-connect): the terminal restore mustn't hang on the daemon.
const JOIN_TIMEOUT: Duration = Duration::from_millis(300);

/// From the worker to the event loop.
#[derive(Debug)]
pub enum DaemonUpdate {
    /// The store changed (`inbox.changed`, or ops the worker applied): reload.
    InboxChanged,
    /// The running containers changed (`instances.changed`): the pushes that
    /// follow show it; the processes want a refetch after the next one.
    InstancesChanged,
    /// The watched root's latest snapshot (`instances.snapshot`), with every
    /// registered machine's rows, and the machines' link states.
    Snapshot(InstancesList, Vec<SnapshotMachine>),
    /// No connection (lost, or the connect failed): why. The snapshot is
    /// stale until the next [`Snapshot`](Self::Snapshot).
    Down(String),
    /// A container message's status line (`inbox.shown`).
    Shown(String),
    /// The Ports tab's rows: this config root's forwards, or none while
    /// disconnected.
    Ports(Vec<PortRow>),
    /// A one-line status: the daemon is unavailable, a write failed.
    Status(String),
    /// [`Fetch::Logs`]'s answer: the modal body.
    Logs { container: String, body: String },
    /// [`Fetch::Config`]'s answer (`Err`: the message both bodies show).
    Config { kind: ConfigKind, name: String, text: Result<SandboxText, String> },
    /// [`Fetch::Inspect`]'s answer: the inspect pane's body.
    Inspect { container: String, body: String },
    /// [`Cmd::BuildLog`]'s answer, for `App::set_build_log`.
    BuildLog { instance: String, read: Result<Option<Tail>, String> },
    /// A process signal's status line; the process rows are stale.
    Signalled(String),
    /// A rename's status line; the renamed row arrives with a push.
    Renamed(String),
    /// A done-flag write's status line, `failed` or not, and the request's
    /// `report` (`PendingDone`).
    Done { status: String, failed: bool, report: bool },
}

/// From the event loop to the worker.
#[derive(Debug, PartialEq)]
enum Cmd {
    /// Inbox writes, in order (see the module doc).
    Inbox(Vec<Op>),
    /// `forwards.add` in the dashboard's config root.
    ForwardAdd(PortRequest),
    /// `forwards.rm`.
    ForwardRm(u64),
    /// `machines.set`: machine `name`'s `agent`.
    MachineSet { name: String, agent: bool },
    /// `instances.cancel` for `instance` (a state key).
    Cancel(String),
    /// A modal's read, and where its target is (a remote sandbox's root).
    Fetch(Fetch, Route),
    /// `instances.buildLog` for an instance id.
    BuildLog(String),
    /// `instances.signal`.
    Signal(PendingSignal),
    /// `instances.rename`.
    Rename { instance: String, new_name: String },
    /// `instances.done`.
    Done(PendingDone),
}

/// Handle to the daemon worker. Never blocks the UI thread; dropping it
/// closes the channel and joins briefly (see [`JOIN_TIMEOUT`]).
pub struct DaemonWorker {
    tx: Option<Sender<Cmd>>,
    updates: Receiver<DaemonUpdate>,
    connected: Arc<AtomicBool>,
    handle: Option<JoinHandle<()>>,
}

impl DaemonWorker {
    /// Spawn the worker for the dashboard of config root `dir` (whose
    /// forwards the Ports tab lists).
    pub fn spawn(dir: PathBuf) -> DaemonWorker {
        let (tx, rx) = mpsc::channel();
        let (utx, updates) = mpsc::channel();
        let connected = Arc::new(AtomicBool::new(false));
        let flag = Arc::clone(&connected);
        let handle = std::thread::Builder::new()
            .name("tui-daemon".into())
            .spawn(move || run(&root_dir(dir), &connect, rx, utx, &flag))
            .ok();
        DaemonWorker { tx: Some(tx), updates, connected, handle }
    }

    /// Whether inbox writes should go through [`apply`](Self::apply). A
    /// connection lost after this said yes is the worker's to handle.
    pub fn connected(&self) -> bool {
        self.handle.is_some() && self.connected.load(Ordering::Acquire)
    }

    /// Send inbox ops to the daemon, in order. Never blocks.
    pub fn apply(&self, ops: Vec<Op>) {
        self.send(Cmd::Inbox(ops));
    }

    /// Ask the daemon to start a forward. Never blocks; the outcome is a
    /// status line.
    pub fn forward_add(&self, req: PortRequest) {
        self.send(Cmd::ForwardAdd(req));
    }

    /// Ask the daemon to stop forward `id`. Never blocks.
    pub fn forward_rm(&self, id: u64) {
        self.send(Cmd::ForwardRm(id));
    }

    /// Ask the daemon to set machine `name`'s `agent`. Never blocks; the
    /// outcome is a status line.
    pub fn machine_set(&self, name: String, agent: bool) {
        self.send(Cmd::MachineSet { name, agent });
    }

    /// Ask the daemon to cancel `instance`'s build. Never blocks; the
    /// outcome is a status line.
    pub fn cancel(&self, instance: String) {
        self.send(Cmd::Cancel(instance));
    }

    /// Ask for a modal's read (`route`: where a remote target is). Never
    /// blocks; answered by its update.
    pub fn fetch(&self, fetch: Fetch, route: Route) {
        self.send(Cmd::Fetch(fetch, route));
    }

    /// Ask for instance `id`'s build log. Never blocks; answered by
    /// [`DaemonUpdate::BuildLog`].
    pub fn build_log(&self, id: String) {
        self.send(Cmd::BuildLog(id));
    }

    /// Send a process signal. Never blocks; answered by
    /// [`DaemonUpdate::Signalled`].
    pub fn signal(&self, sig: PendingSignal) {
        self.send(Cmd::Signal(sig));
    }

    /// Rename an instance. Never blocks; answered by
    /// [`DaemonUpdate::Renamed`].
    pub fn rename(&self, instance: String, new_name: String) {
        self.send(Cmd::Rename { instance, new_name });
    }

    /// Set or clear a done flag. Never blocks; answered by
    /// [`DaemonUpdate::Done`].
    pub fn set_done(&self, req: PendingDone) {
        self.send(Cmd::Done(req));
    }

    fn send(&self, cmd: Cmd) {
        if let Some(tx) = &self.tx {
            let _ = tx.send(cmd);
        }
    }

    /// Next pending update, or `None`. Non-blocking.
    pub fn try_recv(&self) -> Option<DaemonUpdate> {
        self.updates.try_recv().ok()
    }
}

impl Drop for DaemonWorker {
    fn drop(&mut self) {
        // Closing the channel ends the worker within `POLL` unless it's
        // mid-connect; then it's left to die with the process, which closes
        // the socket.
        self.tx.take();
        if let Some(handle) = self.handle.take() {
            let deadline = Instant::now() + JOIN_TIMEOUT;
            while !handle.is_finished() && Instant::now() < deadline {
                std::thread::sleep(Duration::from_millis(10));
            }
            if handle.is_finished() {
                let _ = handle.join();
            }
        }
    }
}

/// Reconnect delays: right away after a connection is lost (the first
/// retry), then 1 s, 2 s, 4 s … capped at [`Backoff::CAP`] while connects
/// keep failing. A success resets it.
#[derive(Debug, Default)]
struct Backoff {
    failures: u32,
}

impl Backoff {
    const CAP: Duration = Duration::from_secs(30);

    /// The delay before the next attempt, counting one more failure.
    fn next(&mut self) -> Duration {
        let delay = match self.failures {
            0 => Duration::ZERO,
            n => Duration::from_secs(1u64 << (n - 1).min(5)).min(Self::CAP),
        };
        self.failures = self.failures.saturating_add(1);
        delay
    }

    fn reset(&mut self) {
        self.failures = 0;
    }
}

/// The API call for a dashboard [`Op`], by store id. `RemoveThread` is
/// only ever a notification (the dashboard dismisses nothing else).
fn op_call(op: &Op) -> (&'static str, Value) {
    match op {
        Op::MarkRead(id) => ("inbox.thread.markRead", json!({ "thread": id })),
        Op::MarkNotifyRead => ("inbox.notify.markRead", json!({ "all": true })),
        Op::RemoveThread(id) => ("inbox.notify.dismiss", json!({ "thread": id })),
        Op::ClearNotify => ("inbox.notify.dismiss", json!({ "all": true })),
        Op::Act { thread, action } => ("inbox.thread.act", json!({ "thread": thread, "action": action })),
        Op::Reply { thread, text } => ("inbox.thread.reply", json!({ "thread": thread, "text": text })),
        Op::MarkDone(id) => ("inbox.thread.done", json!({ "thread": id })),
        Op::Reopen(id) => ("inbox.thread.reopen", json!({ "thread": id })),
        Op::SaveDraft { thread, message, answers } => (
            "inbox.form.saveDraft",
            json!({ "thread": thread, "message": message, "answers": inbox::form::partial_json(answers) }),
        ),
        Op::Submit { thread, message, answers } => (
            "inbox.form.submit",
            json!({ "thread": thread, "message": message, "answers": inbox::form::partial_json(answers) }),
        ),
    }
}

/// The config root as the daemon keys it: canonical (what `run` records),
/// else at least absolute (the API refuses relative dirs).
pub(super) fn root_dir(dir: PathBuf) -> PathBuf {
    dir.canonicalize().or_else(|_| std::path::absolute(&dir)).unwrap_or(dir)
}

/// `call` sent to `machine` (docs/architecture/daemon/machines.md, *Forwarded requests*): its `machine` param,
/// only for a remote target, so a local call is what it was.
fn on_machine((method, mut params): (&'static str, Value), machine: Option<&str>) -> (&'static str, Value) {
    if let (Some(m), Some(obj)) = (machine, params.as_object_mut()) {
        obj.insert("machine".into(), m.into());
    }
    (method, params)
}

/// The API call for [`Cmd::Cancel`], by instance key (`box/web-2` on a
/// machine, `remote::qualify`).
fn cancel_call(key: &str) -> (&'static str, Value) {
    let (machine, instance) = split(key);
    on_machine(("instances.cancel", json!({ "instance": instance })), machine)
}

/// The status line for an `instances.cancel` answer: the pid it SIGINTed,
/// or why not (not building any more, no such instance).
fn cancel_status(instance: &str, r: Response) -> String {
    match (r.result, r.error) {
        (_, Some(e)) => format!("cancel {instance}: {}", e.message),
        (result, None) => match result.as_ref().and_then(|v| v.get("pid")).and_then(Value::as_u64) {
            Some(pid) => format!("cancelling {instance} (SIGINT to pid {pid})"),
            None => format!("cancelling {instance}"),
        },
    }
}

/// What a one-shot call came back with.
#[derive(Debug, PartialEq)]
enum Answer {
    /// The result (`null` when the response had none).
    Ok(Value),
    /// The daemon's error message.
    Refused(String),
    /// The daemon couldn't be asked: the whole line ([`needs_serve`]).
    Unreachable(String),
}

impl Answer {
    fn from_response(r: Response) -> Answer {
        match (r.result, r.error) {
            (_, Some(e)) => Answer::Refused(e.message),
            (result, None) => Answer::Ok(result.unwrap_or(Value::Null)),
        }
    }

    /// The result as `T`, else the line to show (an answer that doesn't
    /// parse is a newer or broken daemon: say so under `what`).
    fn parse<T: serde::de::DeserializeOwned>(self, what: &str) -> Result<T, String> {
        match self {
            Answer::Ok(v) => serde_json::from_value(v).map_err(|e| format!("{what}: unexpected answer: {e}")),
            Answer::Refused(msg) | Answer::Unreachable(msg) => Err(msg),
        }
    }
}

/// The line for a request the daemon couldn't be asked (`why`: the last
/// connect error, when known), as `cancel`'s.
fn needs_serve(what: &str, why: Option<&str>) -> String {
    match why {
        Some(why) => format!("{what}: needs devsandbox serve ({why})"),
        None => format!("{what}: needs devsandbox serve"),
    }
}

/// The API call for a modal's read in config root `root`, and what its
/// failures are called. Its target is a key (`remote::qualify`): a remote
/// one goes to its machine, a remote config read in `route`'s root there.
fn fetch_call(root: &Path, fetch: &Fetch, route: &Route) -> (&'static str, (&'static str, Value)) {
    match fetch {
        Fetch::Logs { container } => {
            let (machine, container) = split(container);
            let call = ("containers.logs", json!({ "container": container, "lines": super::app::LOG_LINES }));
            ("logs", on_machine(call, machine))
        }
        Fetch::Inspect { container } => {
            let (machine, container) = split(container);
            ("inspect", on_machine(("containers.inspect", json!({ "container": container })), machine))
        }
        Fetch::Config { kind, name } => {
            let method = match kind {
                ConfigKind::Sandbox => "sandboxes.get",
                ConfigKind::Service => "services.get",
            };
            let (machine, name) = split(name);
            let root = match (machine, &route.root) {
                (Some(_), Some(remote)) => remote.clone(),
                _ => root.to_string_lossy().into_owned(),
            };
            ("config", on_machine((method, json!({ "root": root, "name": name })), machine))
        }
    }
}

/// A modal read's answer as the update that fills it.
fn fetch_update(fetch: Fetch, answer: Answer) -> DaemonUpdate {
    let body = |answer: Answer, f: fn(Value) -> String| match answer {
        Answer::Ok(v) => f(v),
        Answer::Refused(msg) | Answer::Unreachable(msg) => msg,
    };
    match fetch {
        Fetch::Logs { container } => DaemonUpdate::Logs { container, body: body(answer, logs_body) },
        Fetch::Inspect { container } => DaemonUpdate::Inspect { container, body: body(answer, inspect_body) },
        Fetch::Config { kind: ConfigKind::Sandbox, name } => {
            DaemonUpdate::Config { kind: ConfigKind::Sandbox, name, text: answer.parse("config") }
        }
        Fetch::Config { kind: ConfigKind::Service, name } => {
            let text = answer.parse::<crate::serve::api::ServiceConfig>("config").map(|s| SandboxText {
                resolved: s.original.clone(),
                original: s.original,
                hash: String::new(),
            });
            DaemonUpdate::Config { kind: ConfigKind::Service, name, text }
        }
    }
}

/// `containers.logs`' `{text}` as the modal body.
fn logs_body(result: Value) -> String {
    let text = result.get("text").and_then(Value::as_str).unwrap_or_default();
    if text.trim().is_empty() { "(no log output)".to_string() } else { text.to_string() }
}

/// `containers.inspect`'s JSON, pretty-printed as `devsandbox inspect`
/// prints it (`pretty_inspect`, minus the parse the daemon did).
fn inspect_body(result: Value) -> String {
    serde_json::to_string_pretty(&result).unwrap_or_else(|e| format!("cannot format inspect JSON: {e}"))
}

/// The API call for [`Cmd::BuildLog`]: `ansi`, so the modal can colour it.
fn build_log_call(key: &str) -> (&'static str, Value) {
    let (machine, instance) = split(key);
    let call = ("instances.buildLog", json!({ "instance": instance, "lines": super::app::BUILD_LOG_LINES, "ansi": true }));
    on_machine(call, machine)
}

/// The API call for [`Cmd::Signal`].
fn signal_call(sig: &PendingSignal) -> (&'static str, Value) {
    let (machine, instance) = split(&sig.instance);
    let call = ("instances.signal", json!({ "instance": instance, "pid": sig.pid, "signal": sig.signal.wire() }));
    on_machine(call, machine)
}

/// The status line for an `instances.signal` answer.
fn signal_status(sig: &PendingSignal, answer: Answer) -> String {
    match answer {
        Answer::Ok(_) => format!("sent {} to pid {}", sig.signal.name(), sig.pid),
        Answer::Refused(msg) => format!("{}: {msg}", sig.signal.name()),
        Answer::Unreachable(line) => line,
    }
}

/// The API call for [`Cmd::Rename`].
fn rename_call(key: &str, new_name: &str) -> (&'static str, Value) {
    let (machine, instance) = split(key);
    on_machine(("instances.rename", json!({ "instance": instance, "newName": new_name })), machine)
}

/// The status line for an `instances.rename` answer: the name the daemon
/// settled on (trimmed), or why not.
fn rename_status(instance: &str, new_name: &str, answer: Answer) -> String {
    match answer {
        Answer::Ok(v) => {
            let renamed = v.get("instance").and_then(Value::as_str).unwrap_or(new_name);
            format!("renamed {instance} -> {renamed}")
        }
        Answer::Refused(msg) => format!("rename failed: {msg}"),
        Answer::Unreachable(line) => line,
    }
}

/// The API call for [`Cmd::Done`].
fn done_call(req: &PendingDone) -> (&'static str, Value) {
    let (machine, instance) = split(&req.instance);
    on_machine(("instances.done", json!({ "instance": instance, "done": req.done })), machine)
}

/// The status line for an `instances.done` answer, worded as `devsandbox
/// done|undone` words a change, and whether it failed. The answer doesn't
/// say whether the flag was already so (the CLI's "is already done"): the
/// dashboard only asks for a change.
fn done_status(req: &PendingDone, answer: Answer) -> (String, bool) {
    let verb = if req.done { "done" } else { "undone" };
    match answer {
        Answer::Ok(_) if req.done => (format!("marked {} done", req.instance), false),
        Answer::Ok(_) => (format!("marked {} not done", req.instance), false),
        Answer::Refused(msg) => (format!("{verb}: {msg}"), true),
        Answer::Unreachable(line) => (line, true),
    }
}

/// The API call for `forwards.list` of config root `dir`, plus every
/// forward into a machine (they bind here whatever root they reach).
fn list_call(dir: &Path) -> (&'static str, Value) {
    ("forwards.list", json!({ "dir": dir.to_string_lossy(), "machines": true }))
}

/// The API call for [`Cmd::ForwardAdd`]. An empty instance (a typed
/// `port --service …` without one) is a service-only forward. A machine's
/// forward goes to `dir` = its config root on that machine.
fn add_call(dir: &Path, req: &PortRequest) -> (&'static str, Value) {
    let dir = match (&req.machine, &req.root) {
        (Some(_), Some(root)) => root.clone(),
        _ => dir.to_string_lossy().into_owned(),
    };
    let mut params = json!({
        "dir": dir,
        "instance": (!req.instance.is_empty()).then_some(&req.instance),
        "service": req.service,
        "address": req.address,
        "spec": req.spec,
    });
    if let Some(machine) = &req.machine {
        params["machine"] = json!(machine);
    }
    ("forwards.add", params)
}

/// The API call for [`Cmd::ForwardRm`].
fn rm_call(id: u64) -> (&'static str, Value) {
    ("forwards.rm", json!({ "id": id }))
}

/// The API call for [`Cmd::MachineSet`].
fn machine_set_call(name: &str, agent: bool) -> (&'static str, Value) {
    ("machines.set", json!({ "name": name, "agent": agent }))
}

/// The status line for a `machines.set` that went through.
fn machine_set_status(name: &str, agent: bool) -> String {
    format!("{name}: agent {}", if agent { "on" } else { "off" })
}

/// `forwards.list`'s rows as the Ports tab's.
fn port_rows(result: Value) -> Result<Vec<PortRow>> {
    let rows: Vec<ForwardRow> = serde_json::from_value(result)?;
    Ok(rows
        .into_iter()
        .map(|r| PortRow {
            id: r.id,
            local: r.local,
            target: r.target,
            process: r.process,
            state: r.state,
            conns: r.conns,
            configured: r.configured,
            machine: r.machine,
        })
        .collect())
}

/// The status line for a `forwards.add` answer.
fn added_status(result: Value) -> String {
    match serde_json::from_value::<Added>(result) {
        Ok(a) => format!("forwarding {} -> {}", a.local, a.target),
        Err(_) => "forwarding".into(),
    }
}

/// The status line for a `forwards.rm` answer.
fn removed_status(result: &Value) -> String {
    let local = result.get("local").and_then(Value::as_str).unwrap_or("forward");
    match result.get("configured").and_then(Value::as_bool) {
        Some(true) => format!("stopped {local} (forwardPorts: back when its instance restarts)"),
        _ => format!("stopped {local}"),
    }
}

/// Whether an API error on `op` is worth a status line. A `not-found` on a
/// mark-read or dismiss is a thread another dashboard (or `thread rm`)
/// removed first: the local path ignores it too.
fn reports(op: &Op, code: &str) -> bool {
    !(code == "not-found" && !op.enqueues_event())
}

/// How the worker gets a connection (`after_handoff` or not): [`connect`],
/// or a test daemon's.
type Connector = dyn Fn(bool) -> Result<Conn>;

/// Connect (lazy start). After a handoff, wait for the successor the newer
/// client is starting rather than race it with a daemon of our own (which,
/// older, would win the lock and stall that client); start one only if none
/// shows up.
fn connect(after_handoff: bool) -> Result<Conn> {
    let dir = endpoint::socket_dir()?;
    let waited = after_handoff
        .then(|| client::connect_with(&dir, "tui", &Version::current(), client::START_TIMEOUT, &|_, _| Ok(())).ok())
        .flatten();
    match waited {
        Some(conn) => Ok(conn),
        None => client::connect(&dir, "tui"),
    }
}

/// The API call that watches config root `dir` (its snapshots pushed),
/// with every registered machine's rows (docs/architecture/daemon/machines.md, *Federated snapshots*).
fn watch_call(dir: &Path) -> (&'static str, Value) {
    ("instances.watch", json!({ "dir": dir.to_string_lossy(), "machines": true }))
}

/// Connect, subscribe, and watch config root `dir`: a refused subscribe or
/// watch fails the connect, as a dashboard without its pushes isn't one.
fn open(connect: &Connector, dir: &Path, after_handoff: bool) -> Result<Conn> {
    let mut conn = connect(after_handoff)?;
    let r = conn.call("subscribe", json!({ "topics": ["inbox", "instances", "forwards"] }))?;
    if let Some(e) = r.error {
        anyhow::bail!("subscribe: {} ({})", e.message, e.code);
    }
    let (method, params) = watch_call(dir);
    let r = conn.call(method, params)?;
    if let Some(e) = r.error {
        anyhow::bail!("{method}: {} ({})", e.message, e.code);
    }
    Ok(conn)
}

/// An `instances.snapshot`'s params as the tree's snapshot (`dir` aside)
/// and its `machines` (none without any registered).
fn snapshot_update(mut params: Value) -> DaemonUpdate {
    let machines = params.as_object_mut().and_then(|o| o.remove("machines")).unwrap_or(Value::Null);
    let machines = match machines {
        Value::Null => Ok(Vec::new()),
        v => serde_json::from_value::<Vec<SnapshotMachine>>(v),
    };
    match (serde_json::from_value::<InstancesList>(params), machines) {
        (Ok(list), Ok(machines)) => DaemonUpdate::Snapshot(list, machines),
        (Err(e), _) | (_, Err(e)) => DaemonUpdate::Status(format!("bad instances.snapshot: {e}")),
    }
}

struct Worker<'a> {
    /// The dashboard's config root, as [`root_dir`] made it.
    dir: &'a Path,
    connector: &'a Connector,
    utx: Sender<DaemonUpdate>,
    connected: &'a AtomicBool,
    conn: Option<Conn>,
    backoff: Backoff,
    next_attempt: Instant,
    after_handoff: bool,
    /// Last connect error shown, so a daemon that stays down is one line.
    last_error: Option<String>,
    /// Why the last connect failed, for a forward asked for meanwhile.
    down: Option<String>,
}

fn run(dir: &Path, connector: &Connector, rx: Receiver<Cmd>, utx: Sender<DaemonUpdate>, connected: &AtomicBool) {
    let mut w = Worker {
        dir,
        connector,
        utx,
        connected,
        conn: None,
        backoff: Backoff::default(),
        next_attempt: Instant::now(),
        after_handoff: false,
        last_error: None,
        down: None,
    };
    loop {
        if w.conn.is_none() && Instant::now() >= w.next_attempt {
            w.connect();
        }
        let wait = match w.conn {
            Some(_) => Duration::ZERO,
            None => w.next_attempt.saturating_duration_since(Instant::now()).min(POLL),
        };
        match rx.recv_timeout(wait) {
            Ok(Cmd::Inbox(ops)) => w.apply(ops),
            Ok(Cmd::ForwardAdd(req)) => w.forward_add(&req),
            Ok(Cmd::ForwardRm(id)) => w.forward_rm(id),
            Ok(Cmd::MachineSet { name, agent }) => w.machine_set(&name, agent),
            Ok(Cmd::Cancel(instance)) => w.cancel(&instance),
            Ok(Cmd::Fetch(fetch, route)) => w.fetch(fetch, &route),
            Ok(Cmd::BuildLog(id)) => w.build_log(id),
            Ok(Cmd::Signal(sig)) => w.signal(sig),
            Ok(Cmd::Rename { instance, new_name }) => w.rename(&instance, &new_name),
            Ok(Cmd::Done(req)) => w.set_done(req),
            Err(RecvTimeoutError::Timeout) => {}
            Err(RecvTimeoutError::Disconnected) => return,
        }
        w.listen();
    }
}

impl Worker<'_> {
    fn send(&self, update: DaemonUpdate) {
        let _ = self.utx.send(update);
    }

    fn connect(&mut self) {
        match open(self.connector, self.dir, std::mem::take(&mut self.after_handoff)) {
            Ok(conn) => {
                self.conn = Some(conn);
                self.connected.store(true, Ordering::Release);
                self.backoff.reset();
                self.last_error = None;
                self.down = None;
                // Changes while disconnected only reached us by the stamp.
                self.send(DaemonUpdate::InboxChanged);
                // A new daemon may hold other forwards than the last one.
                self.fetch_ports();
            }
            Err(e) => {
                self.down = Some(format!("{e:#}"));
                self.send(DaemonUpdate::Down(format!("{e:#}")));
                let msg = format!("host daemon unavailable: {e:#}");
                if self.last_error.as_ref() != Some(&msg) {
                    self.send(DaemonUpdate::Status(msg.clone()));
                    self.last_error = Some(msg);
                }
                // Failure 0's zero delay is for a lost connection; a failed
                // connect waits at least the next step.
                if self.backoff.failures == 0 {
                    self.backoff.next();
                }
                self.next_attempt = Instant::now() + self.backoff.next();
            }
        }
    }

    /// The connection is gone: schedule the reconnect.
    fn lost(&mut self, after_handoff: bool) {
        self.conn = None;
        self.connected.store(false, Ordering::Release);
        // No live rows without the daemon that holds them.
        self.send(DaemonUpdate::Ports(Vec::new()));
        self.send(DaemonUpdate::Down("connection lost".into()));
        self.after_handoff = after_handoff;
        self.next_attempt = Instant::now() + self.backoff.next();
    }

    /// Wait up to [`POLL`] for one notification and pass it on.
    fn listen(&mut self) {
        let Some(conn) = self.conn.as_mut() else { return };
        let note = match conn.next_notification(POLL) {
            Ok(Some(note)) => note,
            Ok(None) => return,
            Err(_) => return self.lost(false),
        };
        match note.method.as_str() {
            "inbox.changed" => self.send(DaemonUpdate::InboxChanged),
            "instances.snapshot" => self.send(snapshot_update(note.params)),
            "instances.changed" => self.send(DaemonUpdate::InstancesChanged),
            "forwards.changed" => self.fetch_ports(),
            "forwards.status" => {
                if let Some(line) = note.params.get("line").and_then(Value::as_str) {
                    self.send(DaemonUpdate::Status(line.to_string()));
                }
            }
            "inbox.shown" => {
                if let Some(line) = note.params.get("line").and_then(Value::as_str) {
                    self.send(DaemonUpdate::Shown(line.to_string()));
                }
            }
            "closing" => {
                let handoff = note.params.get("reason").and_then(Value::as_str) == Some("handoff");
                self.lost(handoff);
            }
            // Newer notifications this build doesn't know.
            _ => {}
        }
    }

    /// `forwards.list` for this root, into the Ports tab.
    fn fetch_ports(&mut self) {
        let Some(conn) = self.conn.as_mut() else { return };
        let (method, params) = list_call(self.dir);
        match conn.call(method, params) {
            Ok(r) => match (r.result, r.error) {
                (_, Some(e)) => self.send(DaemonUpdate::Status(format!("ports: {}", e.message))),
                (Some(result), None) => match port_rows(result) {
                    Ok(rows) => self.send(DaemonUpdate::Ports(rows)),
                    Err(e) => self.send(DaemonUpdate::Status(format!("ports: {e:#}"))),
                },
                (None, None) => {}
            },
            Err(_) => self.lost(false),
        }
    }

    /// `forwards.add`; the answer (or why there's none) is a status line. The
    /// row arrives with the `forwards.changed` that follows.
    fn forward_add(&mut self, req: &PortRequest) {
        let Some(conn) = self.conn.as_mut() else {
            let why = self.down.as_deref().unwrap_or("not connected");
            return self.send(DaemonUpdate::Status(format!("port forwarding needs the host daemon: {why}")));
        };
        let (method, params) = add_call(self.dir, req);
        match conn.call(method, params) {
            Ok(r) => self.send(DaemonUpdate::Status(match (r.result, r.error) {
                (_, Some(e)) => e.message,
                (result, None) => added_status(result.unwrap_or_default()),
            })),
            Err(e) => {
                self.lost(false);
                self.send(DaemonUpdate::Status(format!("port forwarding needs the host daemon: {e:#}")));
            }
        }
    }

    /// `forwards.rm`. Disconnected there are no rows to stop. A `not-found`
    /// is a forward another client stopped first: quiet.
    fn forward_rm(&mut self, id: u64) {
        let Some(conn) = self.conn.as_mut() else { return };
        let (method, params) = rm_call(id);
        match conn.call(method, params) {
            Ok(r) => match (r.result, r.error) {
                (_, Some(e)) if e.code == "not-found" => {}
                (_, Some(e)) => self.send(DaemonUpdate::Status(e.message)),
                (result, None) => self.send(DaemonUpdate::Status(removed_status(&result.unwrap_or_default()))),
            },
            Err(_) => self.lost(false),
        }
    }

    /// `machines.set`; the answer (or why there's none) is a status line.
    /// No local fallback: the daemon owns the registry.
    fn machine_set(&mut self, name: &str, agent: bool) {
        let Some(conn) = self.conn.as_mut() else {
            let line = needs_serve(&machine_set_status(name, agent), self.down.as_deref());
            return self.send(DaemonUpdate::Status(line));
        };
        let (method, params) = machine_set_call(name, agent);
        match conn.call(method, params) {
            Ok(r) => match r.error {
                Some(e) => self.send(DaemonUpdate::Status(e.message)),
                None => self.send(DaemonUpdate::Status(machine_set_status(name, agent))),
            },
            Err(_) => self.lost(false),
        }
    }

    /// `instances.cancel`; the answer (or why there's none) is a status
    /// line. No local fallback: the daemon runs the dashboard's builds.
    fn cancel(&mut self, instance: &str) {
        let Some(conn) = self.conn.as_mut() else {
            let line = match &self.down {
                Some(why) => format!("cancel {instance}: needs devsandbox serve ({why})"),
                None => format!("cancel {instance}: needs devsandbox serve"),
            };
            return self.send(DaemonUpdate::Status(line));
        };
        let (method, params) = cancel_call(instance);
        match conn.call(method, params) {
            Ok(r) => self.send(DaemonUpdate::Status(cancel_status(instance, r))),
            Err(e) => {
                self.lost(false);
                self.send(DaemonUpdate::Status(format!("cancel {instance}: needs devsandbox serve ({e:#})")));
            }
        }
    }

    /// One call while connected; disconnected (or the call breaking the
    /// connection) it's [`Answer::Unreachable`] with `what`'s line.
    fn one_shot(&mut self, what: &str, (method, params): (&str, Value)) -> Answer {
        let Some(conn) = self.conn.as_mut() else {
            return Answer::Unreachable(needs_serve(what, self.down.as_deref()));
        };
        match conn.call(method, params) {
            Ok(r) => Answer::from_response(r),
            Err(e) => {
                self.lost(false);
                Answer::Unreachable(needs_serve(what, Some(&format!("{e:#}"))))
            }
        }
    }

    fn fetch(&mut self, fetch: Fetch, route: &Route) {
        let (what, call) = fetch_call(self.dir, &fetch, route);
        let answer = self.one_shot(what, call);
        self.send(fetch_update(fetch, answer));
    }

    fn build_log(&mut self, instance: String) {
        let read = self.one_shot("build log", build_log_call(&instance)).parse("build log");
        self.send(DaemonUpdate::BuildLog { instance, read });
    }

    fn signal(&mut self, sig: PendingSignal) {
        let answer = self.one_shot(sig.signal.name(), signal_call(&sig));
        self.send(DaemonUpdate::Signalled(signal_status(&sig, answer)));
    }

    fn rename(&mut self, instance: &str, new_name: &str) {
        let answer = self.one_shot("rename", rename_call(instance, new_name));
        self.send(DaemonUpdate::Renamed(rename_status(instance, new_name, answer)));
    }

    fn set_done(&mut self, req: PendingDone) {
        let what = if req.done { "done" } else { "undone" };
        let answer = self.one_shot(what, done_call(&req));
        let (status, failed) = done_status(&req, answer);
        self.send(DaemonUpdate::Done { status, failed, report: req.report });
    }

    /// One batch of ops, in order: through the daemon while connected, the
    /// rest straight to the store. An op whose call broke the connection may
    /// or may not have landed: an idempotent one is applied locally, an
    /// event-enqueuing one is reported, never sent twice.
    fn apply(&mut self, ops: Vec<Op>) {
        let mut local = Vec::new();
        for op in ops {
            let Some(conn) = self.conn.as_mut() else {
                local.push(op);
                continue;
            };
            let (method, params) = op_call(&op);
            match conn.call(method, params) {
                Ok(r) => {
                    if let Some(e) = r.error.filter(|e| reports(&op, &e.code)) {
                        self.send(DaemonUpdate::Status(format!("inbox not saved: {}", e.message)));
                    }
                }
                Err(e) => {
                    self.lost(false);
                    if op.enqueues_event() {
                        self.send(DaemonUpdate::Status(format!("inbox: may not be saved, check the thread: {e:#}")));
                    } else {
                        local.push(op);
                    }
                }
            }
        }
        if !local.is_empty() {
            if let Err(e) = inbox::store::path().and_then(|p| inbox::ops::apply(&p, &local, "tui")) {
                self.send(DaemonUpdate::Status(format!("inbox not saved: {e:#}")));
            }
        }
        self.send(DaemonUpdate::InboxChanged);
    }
}

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

    #[test]
    fn ops_map_to_their_api_methods() {
        let cases = [
            (Op::MarkRead(3), "inbox.thread.markRead", json!({"thread": 3})),
            (Op::MarkNotifyRead, "inbox.notify.markRead", json!({"all": true})),
            (Op::RemoveThread(4), "inbox.notify.dismiss", json!({"thread": 4})),
            (Op::ClearNotify, "inbox.notify.dismiss", json!({"all": true})),
            (Op::Act { thread: 5, action: "go".into() }, "inbox.thread.act", json!({"thread": 5, "action": "go"})),
            (Op::Reply { thread: 6, text: "hi".into() }, "inbox.thread.reply", json!({"thread": 6, "text": "hi"})),
            (Op::MarkDone(7), "inbox.thread.done", json!({"thread": 7})),
            (Op::Reopen(8), "inbox.thread.reopen", json!({"thread": 8})),
            (
                Op::SaveDraft { thread: 9, message: "m".into(), answers: [("q".to_string(), inbox::Answer::Choices(vec!["a".into()]))].into() },
                "inbox.form.saveDraft",
                json!({"thread": 9, "message": "m", "answers": {"q": ["a"]}}),
            ),
            (
                Op::Submit { thread: 9, message: "m".into(), answers: [("q".to_string(), inbox::Answer::Confirm(true))].into() },
                "inbox.form.submit",
                json!({"thread": 9, "message": "m", "answers": {"q": true}}),
            ),
        ];
        for (op, method, params) in cases {
            assert_eq!(op_call(&op), (method, params), "{op:?}");
        }
    }

    /// Every method `op_call` names exists, and each one, run against a
    /// store, does what `ops::apply` of the op does.
    #[test]
    fn mapped_calls_match_the_local_path() {
        use crate::devsbd::notify::{Level, Record};
        use crate::inbox::{Action, Compose, State, ThreadPut, store};
        use crate::serve::api::{self, Ctx};

        let seed = |path: &std::path::Path| {
            let put = ThreadPut {
                key: "k".into(),
                title: "t".into(),
                state: State::NeedsYou,
                compose: Some(Compose::default()),
                actions: vec![Action { id: "go".into(), label: "Go".into(), ..Action::default() }],
                ..ThreadPut::default()
            };
            store::update_at(path, |i| i.put("d-id", "d", 1, put)).unwrap();
            let blocks = vec![inbox::Block::Form(inbox::form::tests::mixed())];
            let send = inbox::MessageSend { thread: "k".into(), id: "m".into(), blocks };
            store::update_at(path, |i| i.send("d-id", 1, send)).unwrap();
            let record = Record { level: Level::Info, key: None, link: None, msg: "n".into(), at: 1 };
            store::update_at(path, |i| i.push("w-id".into(), "w".into(), record, true)).unwrap();
        };
        let dir = std::env::temp_dir().join(format!("devsandbox-tui-daemon-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let (via_api, via_ops) = (dir.join("api.json"), dir.join("ops.json"));
        seed(&via_api);
        seed(&via_ops);
        let inbox = inbox::ops::load(&via_api).unwrap();
        let thread = inbox.threads.iter().find(|t| t.kind == inbox::Kind::Thread).unwrap().id;
        let note = inbox.threads.iter().find(|t| t.kind == inbox::Kind::Notify).unwrap().id;
        let ops = [
            Op::MarkRead(thread),
            Op::Act { thread, action: "go".into() },
            Op::Reply { thread, text: "hi".into() },
            Op::MarkDone(thread),
            Op::Reopen(thread),
            Op::SaveDraft { thread, message: "m".into(), answers: [("pick".to_string(), inbox::Answer::Choice("a".into()))].into() },
            Op::Submit { thread, message: "m".into(), answers: [("note".to_string(), inbox::Answer::Text("hi".into()))].into() },
            Op::MarkNotifyRead,
            Op::RemoveThread(note),
            Op::ClearNotify,
        ];
        for op in &ops {
            let (method, params) = op_call(op);
            api::call(method, params, &Ctx { inbox: &via_api, client: "tui", bridges: None, forwards: None, host: None }).unwrap_or_else(|e| panic!("{op:?}: {e:?}"));
            inbox::ops::apply(&via_ops, std::slice::from_ref(op), "tui").unwrap();
        }
        // Ids and times aside (minted at apply time): threads, then events.
        let strip = |path: &std::path::Path| -> String {
            let i = inbox::ops::load(path).unwrap();
            let events = inbox::ops::events(path, "d-id").unwrap();
            let t: Vec<_> = i.threads.iter().map(|t| (t.id, t.kind, t.state, t.unread, t.feed.iter().map(|f| f.kind.clone()).collect::<Vec<_>>())).collect();
            let e: Vec<_> = events.into_iter().map(|(_, e)| (e.kind.as_str().to_string(), e.action, e.text, e.message, e.form, e.answers)).collect();
            format!("{t:?} {e:?}")
        };
        assert_eq!(strip(&via_api), strip(&via_ops));
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn commands_map_to_their_api_methods() {
        // The handle queues each request as its command, in order.
        let (tx, rx) = mpsc::channel();
        let (_utx, updates) = mpsc::channel();
        let worker = DaemonWorker { tx: Some(tx), updates, connected: Arc::default(), handle: None };
        worker.apply(vec![Op::MarkRead(1)]);
        worker.cancel("web".into());
        assert_eq!(rx.try_recv().unwrap(), Cmd::Inbox(vec![Op::MarkRead(1)]));
        assert_eq!(rx.try_recv().unwrap(), Cmd::Cancel("web".into()));
    }

    fn port_req(instance: &str, service: Option<&str>) -> PortRequest {
        PortRequest { instance: instance.into(), service: service.map(String::from), spec: "8080:3000".into(), ..Default::default() }
    }

    fn remote_req(instance: &str, service: Option<&str>) -> PortRequest {
        PortRequest { machine: Some("box".into()), root: Some("/r/one".into()), ..port_req(instance, service) }
    }

    #[test]
    fn forward_commands_queue_and_map_to_their_api_methods() {
        let (tx, rx) = mpsc::channel();
        let (_utx, updates) = mpsc::channel();
        let worker = DaemonWorker { tx: Some(tx), updates, connected: Arc::default(), handle: None };
        worker.forward_add(port_req("web", None));
        worker.forward_rm(4);
        assert_eq!(rx.try_recv().unwrap(), Cmd::ForwardAdd(port_req("web", None)));
        assert_eq!(rx.try_recv().unwrap(), Cmd::ForwardRm(4));

        let dir = Path::new("/cfg");
        assert_eq!(list_call(dir), ("forwards.list", json!({"dir": "/cfg", "machines": true})));
        assert_eq!(rm_call(4), ("forwards.rm", json!({"id": 4})));
        worker.machine_set("box".into(), true);
        assert_eq!(rx.try_recv().unwrap(), Cmd::MachineSet { name: "box".into(), agent: true });
        assert_eq!(machine_set_call("box", true), ("machines.set", json!({"name": "box", "agent": true})));
        assert_eq!(machine_set_call("box", false).1["agent"], json!(false));
        assert_eq!(machine_set_status("box", true), "box: agent on");
        assert_eq!(machine_set_status("box", false), "box: agent off");
        assert_eq!(
            needs_serve(&machine_set_status("box", true), Some("no socket")),
            "box: agent on: needs devsandbox serve (no socket)"
        );
        assert_eq!(
            add_call(dir, &port_req("web", None)),
            (
                "forwards.add",
                json!({"dir": "/cfg", "instance": "web", "service": null, "address": null, "spec": "8080:3000"})
            )
        );
        // No instance typed: a service-only forward.
        assert_eq!(add_call(dir, &port_req("", Some("db"))).1["instance"], Value::Null);
        // A machine's: its root there as `dir`, and the machine.
        assert_eq!(
            add_call(dir, &remote_req("web", Some("db"))),
            (
                "forwards.add",
                json!({"dir": "/r/one", "instance": "web", "service": "db", "address": null, "spec": "8080:3000", "machine": "box"})
            )
        );
        assert!(root_dir(PathBuf::from("rel/dir")).is_absolute());
    }

    /// The calls are what the API takes, and its answers become rows and
    /// status lines.
    #[test]
    fn forward_calls_are_accepted_by_the_api_and_answers_render() {
        use crate::serve::api::{self, ApiError, Ctx, Forwarding};
        use crate::serve::forwards::{AddRequest, Removed};
        struct Fake;
        impl Forwarding for Fake {
            fn list(&self, dir: Option<PathBuf>, machines: bool) -> Result<Vec<ForwardRow>, ApiError> {
                assert_eq!(dir.as_deref(), Some(Path::new("/cfg")));
                assert!(machines);
                let remote = ForwardRow {
                    id: 4,
                    dir: "/r/one".into(),
                    local: "127.0.0.1:8081".into(),
                    target: "box/web:3000".into(),
                    process: None,
                    state: "connecting".into(),
                    conns: 0,
                    configured: false,
                    machine: Some("box".into()),
                };
                Ok(vec![ForwardRow {
                    id: 3,
                    dir: "/cfg".into(),
                    local: "127.0.0.1:8080".into(),
                    target: "web:3000".into(),
                    process: Some("node (pid 1)".into()),
                    state: "active".into(),
                    conns: 2,
                    configured: true,
                    machine: None,
                }, remote])
            }
            fn add(&self, req: AddRequest) -> Result<Added, ApiError> {
                assert_eq!(req.instance.as_deref(), Some("web"));
                if let Some(m) = &req.machine {
                    assert_eq!((m.as_str(), req.dir.as_path()), ("box", Path::new("/r/one")));
                    return Ok(Added { id: 4, local: "127.0.0.1:8081".into(), target: "box/web:3000".into() });
                }
                Ok(Added { id: 3, local: "127.0.0.1:8080".into(), target: "web:3000".into() })
            }
            fn rm(&self, _: u64) -> Result<Removed, ApiError> {
                Ok(Removed { local: "127.0.0.1:8080".into(), configured: true })
            }
        }
        let path = std::env::temp_dir().join(format!("devsandbox-tui-fwd-{}", std::process::id())).join("inbox.json");
        let ctx = Ctx { inbox: &path, client: "tui", bridges: None, forwards: Some(&Fake), host: None };
        let dir = Path::new("/cfg");

        let (method, params) = list_call(dir);
        let rows = port_rows(api::call(method, params, &ctx).unwrap()).unwrap();
        assert_eq!(
            rows,
            [
                PortRow {
                    id: 3,
                    local: "127.0.0.1:8080".into(),
                    target: "web:3000".into(),
                    process: Some("node (pid 1)".into()),
                    state: "active".into(),
                    conns: 2,
                    configured: true,
                    machine: None,
                },
                PortRow {
                    id: 4,
                    local: "127.0.0.1:8081".into(),
                    target: "box/web:3000".into(),
                    process: None,
                    state: "connecting".into(),
                    conns: 0,
                    configured: false,
                    machine: Some("box".into()),
                },
            ]
        );
        let (method, params) = add_call(dir, &port_req("web", None));
        assert_eq!(added_status(api::call(method, params, &ctx).unwrap()), "forwarding 127.0.0.1:8080 -> web:3000");
        let (method, params) = add_call(dir, &remote_req("web", None));
        assert_eq!(added_status(api::call(method, params, &ctx).unwrap()), "forwarding 127.0.0.1:8081 -> box/web:3000");
        let (method, params) = rm_call(3);
        assert_eq!(
            removed_status(&api::call(method, params, &ctx).unwrap()),
            "stopped 127.0.0.1:8080 (forwardPorts: back when its instance restarts)"
        );
        assert_eq!(removed_status(&json!({"ok": true, "local": "127.0.0.1:1", "configured": false})), "stopped 127.0.0.1:1");
    }

    /// `d`'s cancel queues as its command, its call is what the API's
    /// `instances.cancel` parses (not run: that would read the user's
    /// state), and each answer kind reads as a status line.
    #[test]
    fn cancel_queues_maps_to_the_api_and_answers_render() {
        use crate::serve::api::{self, CancelParams};
        use crate::serve::proto::ErrorBody;
        let (tx, rx) = mpsc::channel();
        let (_utx, updates) = mpsc::channel();
        let worker = DaemonWorker { tx: Some(tx), updates, connected: Arc::default(), handle: None };
        worker.cancel("web-2".into());
        assert_eq!(rx.try_recv().unwrap(), Cmd::Cancel("web-2".into()));

        let (method, params) = cancel_call("web-2");
        assert_eq!((method, &params), ("instances.cancel", &json!({"instance": "web-2"})));
        let parsed: CancelParams = api::parse(params).unwrap();
        assert_eq!(parsed.instance, "web-2");

        let ok = |v: Value| Response { id: Some(1), result: Some(v), error: None };
        let err = |code: &str, message: &str| Response {
            id: Some(1),
            result: None,
            error: Some(ErrorBody { code: code.into(), message: message.into(), data: None }),
        };
        assert_eq!(cancel_status("web-2", ok(json!({"ok": true, "pid": 42}))), "cancelling web-2 (SIGINT to pid 42)");
        assert_eq!(
            cancel_status("web-2", err("invalid", "`web-2` is not building any more")),
            "cancel web-2: `web-2` is not building any more"
        );
        assert_eq!(cancel_status("x", err("not-found", "no instance `x`")), "cancel x: no instance `x`");
    }

    fn sig(pid: &str) -> PendingSignal {
        PendingSignal { instance: "web-2".into(), pid: pid.into(), signal: super::super::app::Signal::Term }
    }

    fn response(result: Option<Value>, error: Option<(&str, &str)>) -> Response {
        use crate::serve::proto::ErrorBody;
        let error = error.map(|(code, message)| ErrorBody { code: code.into(), message: message.into(), data: None });
        Response { id: Some(1), result, error }
    }

    /// The one-shot requests queue as their commands, in order.
    #[test]
    fn one_shot_requests_queue_as_their_commands() {
        let (tx, rx) = mpsc::channel();
        let (_utx, updates) = mpsc::channel();
        let worker = DaemonWorker { tx: Some(tx), updates, connected: Arc::default(), handle: None };
        let logs = Fetch::Logs { container: "devsandbox-web".into() };
        let done = PendingDone { instance: "web".into(), done: true, report: false };
        worker.fetch(logs.clone(), Route::default());
        worker.build_log("id0".into());
        worker.signal(sig("42"));
        worker.rename("a".into(), "b".into());
        worker.set_done(done.clone());
        assert_eq!(rx.try_recv().unwrap(), Cmd::Fetch(logs, Route::default()));
        assert_eq!(rx.try_recv().unwrap(), Cmd::BuildLog("id0".into()));
        assert_eq!(rx.try_recv().unwrap(), Cmd::Signal(sig("42")));
        assert_eq!(rx.try_recv().unwrap(), Cmd::Rename { instance: "a".into(), new_name: "b".into() });
        assert_eq!(rx.try_recv().unwrap(), Cmd::Done(done));
    }

    #[test]
    fn one_shot_calls_name_their_methods_and_params() {
        let root = Path::new("/cfg");
        let fetch = |f: Fetch| fetch_call(root, &f, &Route::default());
        assert_eq!(
            fetch(Fetch::Logs { container: "devsandbox-web".into() }),
            ("logs", ("containers.logs", json!({"container": "devsandbox-web", "lines": 50})))
        );
        assert_eq!(
            fetch(Fetch::Inspect { container: "devsandbox-web".into() }),
            ("inspect", ("containers.inspect", json!({"container": "devsandbox-web"})))
        );
        assert_eq!(
            fetch(Fetch::Config { kind: ConfigKind::Sandbox, name: "web".into() }),
            ("config", ("sandboxes.get", json!({"root": "/cfg", "name": "web"})))
        );
        assert_eq!(
            fetch(Fetch::Config { kind: ConfigKind::Service, name: "db".into() }),
            ("config", ("services.get", json!({"root": "/cfg", "name": "db"})))
        );
        assert_eq!(build_log_call("id0"), ("instances.buildLog", json!({"instance": "id0", "lines": 500, "ansi": true})));
        assert_eq!(
            signal_call(&PendingSignal { signal: super::super::app::Signal::Kill, ..sig("42") }),
            ("instances.signal", json!({"instance": "web-2", "pid": "42", "signal": "KILL"}))
        );
        assert_eq!(rename_call("a", "b"), ("instances.rename", json!({"instance": "a", "newName": "b"})));
        assert_eq!(
            done_call(&PendingDone { instance: "a".into(), done: false, report: true }),
            ("instances.done", json!({"instance": "a", "done": false}))
        );
    }

    /// A remote target's key (`box/…`) goes out as the bare name plus
    /// `machine`; a remote config read in the row's root there.
    #[test]
    fn remote_targets_carry_their_machine() {
        let root = Path::new("/cfg");
        let remote = Route { machine: Some("box".into()), root: Some("/r/one".into()) };
        assert_eq!(
            fetch_call(root, &Fetch::Config { kind: ConfigKind::Sandbox, name: "box/web".into() }, &remote),
            ("config", ("sandboxes.get", json!({"root": "/r/one", "name": "web", "machine": "box"})))
        );
        assert_eq!(
            fetch_call(root, &Fetch::Config { kind: ConfigKind::Service, name: "box/db".into() }, &remote).1,
            ("services.get", json!({"root": "/r/one", "name": "db", "machine": "box"}))
        );
        assert_eq!(
            fetch_call(root, &Fetch::Logs { container: "box/devsandbox-web".into() }, &Route::default()).1,
            ("containers.logs", json!({"container": "devsandbox-web", "lines": 50, "machine": "box"}))
        );
        assert_eq!(
            fetch_call(root, &Fetch::Inspect { container: "box/devsandbox-web".into() }, &Route::default()).1,
            ("containers.inspect", json!({"container": "devsandbox-web", "machine": "box"}))
        );
        assert_eq!(cancel_call("box/web-2"), ("instances.cancel", json!({"instance": "web-2", "machine": "box"})));
        assert_eq!(build_log_call("box/id0").1, json!({"instance": "id0", "lines": 500, "ansi": true, "machine": "box"}));
        assert_eq!(signal_call(&sig("42")).1["machine"], Value::Null, "local");
        let remote_sig = PendingSignal { instance: "box/web-2".into(), ..sig("42") };
        assert_eq!(signal_call(&remote_sig).1, json!({"instance": "web-2", "pid": "42", "signal": "TERM", "machine": "box"}));
        assert_eq!(rename_call("box/a", "b").1, json!({"instance": "a", "newName": "b", "machine": "box"}));
        let done = PendingDone { instance: "box/a".into(), done: true, report: false };
        assert_eq!(done_call(&done).1, json!({"instance": "a", "done": true, "machine": "box"}));
    }

    /// The calls the API can run here without docker or the user's state:
    /// the config reads end to end, the rest as far as their param checks.
    #[test]
    fn one_shot_calls_are_accepted_by_the_api() {
        use crate::serve::api::{self, Ctx};
        let dir = std::env::temp_dir().join(format!("devsandbox-tui-oneshot-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(
            dir.join(crate::config::CONFIG_FILE),
            "[sandbox.web]\nimage = \"alpine\"\n[services.db]\nimage = \"postgres\"\n",
        )
        .unwrap();
        let inbox = dir.join("inbox.json");
        let ctx = Ctx { inbox: &inbox, client: "tui", bridges: None, forwards: None, host: None };
        let ask = |(method, params): (&str, Value)| match api::call(method, params, &ctx) {
            Ok(v) => Answer::Ok(v),
            Err(e) => Answer::Refused(e.message),
        };

        let (_, call) = fetch_call(&dir, &Fetch::Config { kind: ConfigKind::Sandbox, name: "web".into() }, &Route::default());
        let update = fetch_update(Fetch::Config { kind: ConfigKind::Sandbox, name: "web".into() }, ask(call));
        let DaemonUpdate::Config { kind: ConfigKind::Sandbox, name, text: Ok(text) } = update else { panic!("{update:?}") };
        assert_eq!((name.as_str(), text.original.as_str()), ("web", "image = \"alpine\"\n"));
        assert!(!text.hash.is_empty());
        let service = Fetch::Config { kind: ConfigKind::Service, name: "db".into() };
        let (_, call) = fetch_call(&dir, &service, &Route::default());
        let DaemonUpdate::Config { kind: ConfigKind::Service, name, text } = fetch_update(service, ask(call)) else { panic!() };
        assert_eq!(name, "db");
        assert_eq!(
            text,
            Ok(SandboxText {
                original: "image = \"postgres\"\n".into(),
                resolved: "image = \"postgres\"\n".into(),
                hash: String::new()
            })
        );
        let unknown = Fetch::Config { kind: ConfigKind::Sandbox, name: "nope".into() };
        let (_, call) = fetch_call(&dir, &unknown, &Route::default());
        let DaemonUpdate::Config { text: Err(msg), .. } = fetch_update(unknown, ask(call)) else { panic!() };
        assert!(msg.contains("no sandbox `nope`"), "{msg}");
        // Parsed and checked before any state or runtime is touched.
        let not_ours = Fetch::Logs { container: "web".into() };
        let (_, call) = fetch_call(&dir, &not_ours, &Route::default());
        let DaemonUpdate::Logs { body, .. } = fetch_update(not_ours, ask(call)) else { panic!() };
        assert!(body.contains("not a devsandbox container"), "{body}");
        let (_, call) = fetch_call(&dir, &Fetch::Inspect { container: "web".into() }, &Route::default());
        assert!(matches!(ask(call), Answer::Refused(m) if m.contains("not a devsandbox container")));
        assert!(matches!(ask(signal_call(&sig("0"))), Answer::Refused(m) if m.contains("`pid` must be a process id")));
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn one_shot_answers_render() {
        // Responses: a result (none is `null`), or the daemon's message.
        assert_eq!(Answer::from_response(response(Some(json!({"ok": true})), None)), Answer::Ok(json!({"ok": true})));
        assert_eq!(Answer::from_response(response(None, None)), Answer::Ok(Value::Null));
        assert_eq!(Answer::from_response(response(None, Some(("not-found", "no instance `x`")))), Answer::Refused("no instance `x`".into()));
        assert_eq!(needs_serve("logs", Some("refused")), "logs: needs devsandbox serve (refused)");
        assert_eq!(needs_serve("logs", None), "logs: needs devsandbox serve");
        let down = || Answer::Unreachable(needs_serve("x", Some("down")));

        // Logs and inspect: the body, empty output said, errors as is.
        let logs = |a| match fetch_update(Fetch::Logs { container: "devsandbox-a".into() }, a) {
            DaemonUpdate::Logs { container, body } if container == "devsandbox-a" => body,
            other => panic!("{other:?}"),
        };
        assert_eq!(logs(Answer::Ok(json!({"text": "l1\nl2\n"}))), "l1\nl2\n");
        assert_eq!(logs(Answer::Ok(json!({"text": " \n"}))), "(no log output)");
        assert_eq!(logs(Answer::Refused("No such container".into())), "No such container");
        assert_eq!(logs(down()), "x: needs devsandbox serve (down)");
        let inspect = |a| match fetch_update(Fetch::Inspect { container: "devsandbox-a".into() }, a) {
            DaemonUpdate::Inspect { body, .. } => body,
            other => panic!("{other:?}"),
        };
        // As `devsandbox inspect` prints it.
        let raw = r#"[{"Id":"abc","State":{"Running":true}}]"#;
        assert_eq!(inspect(Answer::Ok(serde_json::from_str(raw).unwrap())), crate::commands::inspect::pretty_inspect(raw));
        assert_eq!(inspect(down()), "x: needs devsandbox serve (down)");
        let config = |a| match fetch_update(Fetch::Config { kind: ConfigKind::Sandbox, name: "web".into() }, a) {
            DaemonUpdate::Config { text, .. } => text,
            other => panic!("{other:?}"),
        };
        assert_eq!(config(down()), Err("x: needs devsandbox serve (down)".into()));
        assert!(config(Answer::Ok(json!({"surprise": 1}))).unwrap_err().starts_with("config: unexpected answer"));

        // The build log: `null` is none yet.
        let read = |a: Answer| a.parse::<Option<Tail>>("build log");
        assert_eq!(read(Answer::Ok(Value::Null)), Ok(None));
        assert_eq!(read(Answer::Ok(json!({"text": "x", "cut": true}))), Ok(Some(Tail { text: "x".into(), cut: true })));
        assert_eq!(read(Answer::Refused("no instance `id0`".into())), Err("no instance `id0`".into()));

        // Status lines, as the in-process paths worded them.
        assert_eq!(signal_status(&sig("42"), Answer::Ok(json!({"ok": true}))), "sent SIGTERM to pid 42");
        assert_eq!(signal_status(&sig("42"), Answer::Refused("no instance `web-2`".into())), "SIGTERM: no instance `web-2`");
        assert_eq!(signal_status(&sig("42"), down()), "x: needs devsandbox serve (down)");
        assert_eq!(rename_status("a", " b ", Answer::Ok(json!({"instance": "b"}))), "renamed a -> b");
        assert_eq!(rename_status("a", "b", Answer::Refused("`b` is taken".into())), "rename failed: `b` is taken");
        assert_eq!(rename_status("a", "b", down()), "x: needs devsandbox serve (down)");
        let done = |done| PendingDone { instance: "a".into(), done, report: true };
        let ok = || Answer::Ok(json!({"instance": "a", "done": true}));
        assert_eq!(done_status(&done(true), ok()), ("marked a done".into(), false));
        assert_eq!(done_status(&done(false), ok()), ("marked a not done".into(), false));
        assert_eq!(done_status(&done(false), Answer::Refused("no instance `a`".into())), ("undone: no instance `a`".into(), true));
        assert_eq!(done_status(&done(true), down()), ("x: needs devsandbox serve (down)".into(), true));
    }

    #[test]
    fn stale_targets_are_quiet_but_lost_events_are_not() {
        assert!(!reports(&Op::MarkRead(1), "not-found"));
        assert!(!reports(&Op::RemoveThread(1), "not-found"));
        assert!(!reports(&Op::MarkNotifyRead, "not-found"));
        assert!(reports(&Op::MarkDone(1), "not-found"));
        assert!(reports(&Op::Act { thread: 1, action: "a".into() }, "not-found"));
        assert!(reports(&Op::MarkRead(1), "internal"));
        assert!(reports(&Op::Reply { thread: 1, text: "x".into() }, "denied"));
    }

    /// Against a test daemon (no host: a watch's one push is its Disk
    /// snapshot): the worker watches its root and relays the push; a lost
    /// daemon is a `Down`, and the next daemon is watched again.
    #[test]
    fn the_worker_watches_its_root_and_again_after_a_reconnect() {
        use crate::serve::daemon::tests::{opts, scratch, spawn_daemon};
        let sock = scratch("tui-watch");
        let root = scratch("tui-watch-root");
        std::fs::create_dir_all(&root).unwrap();
        let o = opts(1, 2000);
        let version = o.version.clone();
        let daemon = spawn_daemon(&sock, o);
        let (tx, rx) = mpsc::channel();
        let (utx, updates) = mpsc::channel();
        let (s, r) = (sock.clone(), root.clone());
        let ver = version.clone();
        let worker = std::thread::spawn(move || {
            let connector = move |_| client::connect_with(&s, "tui", &ver, Duration::from_secs(5), &|_, _| Ok(()));
            run(&r, &connector, rx, utx, &AtomicBool::new(false));
        });
        let next = |want: fn(&DaemonUpdate) -> bool| -> DaemonUpdate {
            loop {
                let u = updates.recv_timeout(Duration::from_secs(10)).expect("no update");
                if want(&u) {
                    return u;
                }
            }
        };
        let is_snapshot = |u: &DaemonUpdate| matches!(u, DaemonUpdate::Snapshot(..));
        let DaemonUpdate::Snapshot(first, machines) = next(is_snapshot) else { unreachable!() };
        assert_eq!(first.snapshot.runtime_name, "Disk", "a new watch's first push");
        assert!(machines.is_empty(), "a machines watch, none registered");

        let mut other = client::connect_with(&sock, "test", &version, Duration::from_secs(5), &|_, _| Ok(())).unwrap();
        assert!(other.call("shutdown", json!({})).unwrap().error.is_none());
        drop(other);
        let _ = daemon.join();
        let DaemonUpdate::Down(_) = next(|u| matches!(u, DaemonUpdate::Down(_))) else { unreachable!() };

        let daemon = spawn_daemon(&sock, opts(1, 2000));
        let DaemonUpdate::Snapshot(again, _) = next(is_snapshot) else { unreachable!() };
        assert_eq!(again.snapshot.runtime_name, "Disk", "watched again");
        drop(tx);
        worker.join().unwrap();
        let _ = daemon.join();
        let _ = std::fs::remove_dir_all(&sock);
        let _ = std::fs::remove_dir_all(&root);
    }

    #[test]
    fn snapshot_pushes_parse_or_say_why() {
        let wire = json!({
            "dir": "/cfg", "instances": [], "sandboxes": [], "services": [], "sandbox_count": 2,
            "runtime_name": "docker", "runtime_version": "24", "error": null,
            "thread_children": {"d-id": {"k": "web-k"}},
        });
        let DaemonUpdate::Snapshot(list, machines) = snapshot_update(wire) else { panic!("not parsed") };
        assert!(machines.is_empty());
        assert_eq!(list.snapshot.sandbox_count, 2);
        assert!(!list.snapshot.stats);
        assert_eq!(list.thread_children["d-id"]["k"], "web-k");
        let DaemonUpdate::Status(line) = snapshot_update(json!([1])) else { panic!("parsed") };
        assert!(line.starts_with("bad instances.snapshot"), "{line}");
        assert_eq!(watch_call(Path::new("/cfg")), ("instances.watch", json!({"dir": "/cfg", "machines": true})));
        let federated = json!({
            "dir": "/cfg", "instances": [], "sandboxes": [], "services": [], "sandbox_count": 0,
            "runtime_name": "docker", "runtime_version": null, "error": null,
            "machines": [{"name": "box", "target": "me@box", "state": "unreachable", "error": "refused",
                "version": null, "runtime": null, "command": null, "agent": false}],
        });
        let DaemonUpdate::Snapshot(_, machines) = snapshot_update(federated) else { panic!("not parsed") };
        assert_eq!((machines[0].name.as_str(), machines[0].error.as_deref()), ("box", Some("refused")));
    }

    #[test]
    fn backoff_retries_at_once_then_doubles_to_the_cap() {
        let mut b = Backoff::default();
        let secs: Vec<u64> = (0..9).map(|_| b.next().as_secs()).collect();
        assert_eq!(secs, [0, 1, 2, 4, 8, 16, 30, 30, 30]);
        b.reset();
        assert_eq!(b.next(), Duration::ZERO);
        assert_eq!(b.next(), Duration::from_secs(1));
        // Never overflows, however long the daemon stays down.
        let mut b = Backoff { failures: u32::MAX - 1 };
        assert_eq!((b.next(), b.next()), (Backoff::CAP, Backoff::CAP));
    }
}