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
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
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
//! The worker's end of a fleet link's `PTY` stream
//! (docs/architecture/daemon/fleet.md, *PTY*): a terminal into a lent
//! instance, as a session attach through its helper's `session.attach`
//! (`HelperClient::call_with_input`, decision 13 of
//! docs/plans/active/fleet.md: no `exec -it`, no in-container client).
//!
//! The stream carries `rpc` records (`src/devsbd/rpc.rs`). The control plane's first
//! is a `call` of [`METHOD`] whose params are the [`Header`]; then its
//! `stdin`, `resize` and `stdin-eof` records go into the attach, and the
//! helper's records come back unchanged: `stdout`…, then one end record,
//! `exit` or `error`. A stream refused before the attach gets one `error`
//! record ([`code`]). The control plane closing the stream detaches (the call is
//! cancelled; the session runs on in the container); an attach that ends
//! without an end record is [`code::LOST`].
//!
//! A header with `pipe` instead of `session` is a piped exec ([`Mode::Pipe`],
//! a non-tty `exec`): no session and no helper, a `<runtime> exec` without
//! `-t` on this host ([`runtime_exec`]) with its stdio piped. The control plane's
//! `stdin` records go to its stdin (`stdin-eof` closes it; only when
//! `interactive`, else its stdin is empty); its stdout and stderr come back
//! as `stdout` and `stderr` records, then one `exit` once both are drained
//! and it was reaped ([`exit_record`]). The control plane closing the stream first
//! kills and reaps it, and nothing more is written.
//!
//! A session header for an instance whose helper's daemon doesn't offer
//! `session.attach` (not root, or older) runs the helper's session client
//! instead ([`decide`], [`Terminal::Client`]): `<runtime> exec -it …
//! devsbd session new|attach` under a host pty ([`run_tty`]), what a local
//! tty exec runs ([`client_command`]), so it is resumable too; its
//! `no-session` / `detached` / `version` exits end the stream as the
//! attach's error records do ([`client_exit_record`]). One without a helper
//! runs a plain tty exec when it creates ([`Terminal::Tty`]): `<runtime>
//! exec -it` under a host pty, not resumable (one `stderr` note says so
//! first, [`TTY_NOTE`]); an attach-only one gets `no-session`. A header
//! with `service` ([`Mode::Service`]) is the same plain tty exec into a
//! service container the instance uses ([`service_container`]). The pty's
//! output comes back as `stdout` records, the control plane's `stdin` and
//! `resize` go into it, its exit is one `exit` record; the control plane
//! closing first kills and reaps the runtime's exec client (a session
//! client it leaves in the container is displaced by the next attach).
//!
//! [`parse_header`], [`gate`], [`decide`], [`attach_params`],
//! [`client_command`], [`exit_record`], [`tty_exit_record`] and
//! [`client_exit_record`] are pure (`gate` canonicalizes the header's
//! root); [`serve`] is the I/O.

use std::io::{Read, Write};
use std::net::Shutdown;
use std::path::PathBuf;
use std::process::{Child, ExitStatus, Stdio};
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;

use super::lent::{self, Files, Peer, Reach};
use crate::commands::exec::{SHELL_FALLBACK_CMD, exec_argv_with, exec_context, session_attach_command, session_new_command};
use crate::devsbd::control::valid_run_id;
use crate::devsbd::rpc::{self, Exit, Json, Obj, Record};
use crate::serve::attaches::{Attaches, Origin};
use crate::serve::endpoint::Stream;
use crate::serve::helper::{Call, CallError, Cancel, HelperClient, Input};
use crate::serve::machines::cli::{DETACHED_EXIT, NO_SESSION_EXIT, VERSION_EXIT};
use crate::state::{Instance, State};

/// The header's method, and the helper's.
pub const METHOD: &str = "session.attach";

/// The `error` codes a `PTY` stream ends with besides the helper's own
/// (`rpc::code`: `no-session`, `detached`, `version`, `bad-request`,
/// `failed`), which are relayed as it sent them. The worker's refusals use
/// `bad-request` and `failed` too.
pub mod code {
    pub use crate::devsbd::rpc::code::{BAD_REQUEST, FAILED};
    /// The header's root is outside the fleet root, or not this control plane's to
    /// reach.
    pub const DENIED: &str = "denied";
    /// No such root, or no lent instance by that name or id in it.
    pub const NOT_FOUND: &str = "not-found";
    /// The instance isn't running (no live bridge to its helper).
    pub const NOT_RUNNING: &str = "not-running";
    /// The helper stopped offering `session.attach` between the check
    /// ([`super::decide`]) and the call.
    pub const UNSUPPORTED: &str = "unsupported";
    /// The attach ended without an end record (the bridge to the instance
    /// was lost): neither an exit nor a refusal; the session may live on.
    pub const LOST: &str = "lost";
}

/// How long the control plane has to send the header once it opened the stream.
const HEADER_WAIT: Duration = Duration::from_secs(30);

/// How often a piped exec is checked for its exit and the control plane's hang-up.
const PIPE_TICK: Duration = Duration::from_millis(100);

/// The most bytes one `stdout` / `stderr` record of a piped exec carries.
const PIPE_CHUNK: usize = 64 * 1024;

/// What the control plane asks: `{"root", "instance", "session", "create"?:
/// {"argv"?}}`, `{"root", "instance", "pipe": {"argv",
/// "interactive"?}}`, or `{"root", "instance", "service", "create":
/// {"argv"?}}`.
#[derive(Debug, Clone, PartialEq)]
pub struct Header {
    /// The instance's config root (absolute, under the fleet root).
    pub root: PathBuf,
    /// An exact instance name or instance id.
    pub instance: String,
    pub mode: Mode,
}

/// A session attach, a piped exec, or a service terminal.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Mode {
    /// Session `id` (`control::valid_run_id`). `create`: `None`, attach
    /// only; `Some(argv)`, create it running `argv` (empty: the login shell,
    /// `SHELL_FALLBACK_CMD`) unless it exists, then attach.
    Session { id: String, create: Option<Vec<String>> },
    /// A non-tty exec of `argv` (never empty: the control plane sends the login shell
    /// itself), the control plane's stdin forwarded when `interactive` (`exec -i`).
    Pipe { argv: Vec<String>, interactive: bool },
    /// A tty exec of `argv` (empty: the login shell) in the container of
    /// service `name` that the header's instance uses; always a new
    /// terminal (no sessions).
    Service { name: String, argv: Vec<String> },
}

fn bad(message: impl Into<String>) -> Record {
    Record::error(code::BAD_REQUEST, message)
}

/// A record's name, for a refusal.
fn kind(rec: &Record) -> &'static str {
    match rec {
        Record::Call(_) => "call",
        Record::Stdin(_) => "stdin",
        Record::StdinEof => "stdin-eof",
        Record::Resize { .. } => "resize",
        Record::Signal(_) => "signal",
        Record::Stdout(_) => "stdout",
        Record::Stderr(_) => "stderr",
        Record::Event(_) => "event",
        Record::Result(_) => "result",
        Record::Error { .. } => "error",
        Record::Exit(_) => "exit",
    }
}

/// The control plane's first record as a [`Header`], or the `bad-request` to end the
/// stream with.
pub fn parse_header(rec: Record) -> Result<Header, Record> {
    let call = match rec {
        Record::Call(call) => call,
        other => return Err(bad(format!("a PTY stream starts with a `{METHOD}` call, not a `{}` record", kind(&other)))),
    };
    if call.method != METHOD {
        return Err(bad(format!("a PTY stream's call is `{METHOD}`, not `{}`", call.method)));
    }
    let p = &call.params;
    let text = |key: &str| p.str(key).filter(|s| !s.is_empty()).ok_or_else(|| bad(format!("the PTY header needs `{key}`")));
    let root = PathBuf::from(text("root")?);
    let instance = text("instance")?.to_string();
    let present = |key: &str| !matches!(p.get(key), None | Some(Json::Null));
    let create_argv = |c: &Obj| match c.get("argv") {
        None | Some(Json::Null) => Ok(Vec::new()),
        Some(Json::Strs(argv)) => Ok(argv.clone()),
        Some(_) => Err(bad("`create.argv` must be an array of strings")),
    };
    if present("service") {
        if present("session") || present("pipe") {
            return Err(bad("the PTY header takes one of `session`, `pipe` and `service`"));
        }
        let name = text("service")?.to_string();
        let argv = match p.get("create") {
            Some(Json::Obj(c)) => create_argv(c)?,
            None | Some(Json::Null) => return Err(bad("a service terminal needs `create` (there are no service sessions)")),
            Some(_) => return Err(bad("`create` must be an object")),
        };
        return Ok(Header { root, instance, mode: Mode::Service { name, argv } });
    }
    if present("pipe") {
        if present("session") || present("create") {
            return Err(bad("the PTY header takes `pipe` or `session`, not both"));
        }
        let Some(Json::Obj(pipe)) = p.get("pipe") else { return Err(bad("`pipe` must be an object")) };
        let argv = match pipe.get("argv") {
            Some(Json::Strs(argv)) if !argv.is_empty() => argv.clone(),
            Some(Json::Strs(_)) | None | Some(Json::Null) => return Err(bad("`pipe.argv` needs a command")),
            Some(_) => return Err(bad("`pipe.argv` must be an array of strings")),
        };
        let interactive = match pipe.get("interactive") {
            None | Some(Json::Null) => false,
            Some(Json::Bool(b)) => *b,
            Some(_) => return Err(bad("`pipe.interactive` must be a boolean")),
        };
        return Ok(Header { root, instance, mode: Mode::Pipe { argv, interactive } });
    }
    let id = text("session")?.to_string();
    if !valid_run_id(&id) {
        return Err(bad(format!("bad session id `{id}`")));
    }
    let create = match p.get("create") {
        None | Some(Json::Null) => None,
        Some(Json::Obj(c)) => Some(create_argv(c)?),
        Some(_) => return Err(bad("`create` must be an object")),
    };
    Ok(Header { root, instance, mode: Mode::Session { id, create } })
}

/// The instance the header names, and its `state.toml` key: `root`
/// confined to `reach` as `lent::confine_path` does (the fleet root or an
/// own root under `worker`, any under `full`); the instance by exact name,
/// else by id, among those lent (`lent::lent_instances`) whose config root
/// is under `root`. Neither the helper nor running is checked here: a
/// session's helper is asked ([`decide`]); a runtime exec (a pipe, a tty)
/// says so itself.
pub fn gate<'a>(h: &Header, state: &'a State, reach: &Reach) -> Result<(&'a str, &'a Instance), Record> {
    let root = lent::confine_path(reach, &h.root, true).map_err(|e| match e.code {
        "invalid" => bad(e.message),
        code => Record::error(code, e.message),
    })?;
    let lent = lent::lent_instances(state, reach);
    let by_name = state.instances.get_key_value(&h.instance);
    let found = by_name
        .or_else(|| state.instances.iter().find(|(_, i)| i.instance_id == h.instance))
        .filter(|(name, i)| lent.names.contains(*name) && i.config_dir.as_deref().is_some_and(|d| lent::root_under(d, &root)));
    let Some((name, instance)) = found else {
        return Err(Record::error(code::NOT_FOUND, format!("no instance `{}` in {}", h.instance, root.display())));
    };
    Ok((name.as_str(), instance))
}

/// How a session header's terminal runs ([`decide`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Terminal {
    /// A session attach through the helper's daemon (`session.attach`).
    Attach,
    /// The helper's session client through a tty exec under a host pty
    /// ([`client_command`], [`run_tty`]): a session as a local tty exec
    /// makes one, which needs no root daemon. For a helper whose daemon
    /// doesn't offer `session.attach` (decision 13: it is root only; a
    /// `containerUser` instance, or an older helper).
    Client,
    /// A plain tty exec under a host pty ([`run_tty`]): no helper, not
    /// resumable ([`TTY_NOTE`]).
    Tty,
}

/// The `stderr` record's text a [`Terminal::Tty`] starts with (`\r\n`: the
/// control plane's terminal is raw by then).
pub const TTY_NOTE: &str = "this terminal isn't resumable (no helper): a dropped link ends it\r\n";

/// The terminal a session header for instance `name` gets: `create`
/// whether it creates one; `offers` the helper's answer to whether it
/// offers `session.attach` (`HelperClient::offers`), `None` without a
/// helper. A helper that takes it: [`Terminal::Attach`]; one that doesn't:
/// [`Terminal::Client`], creating or not. Without a helper a creating
/// header falls back to [`Terminal::Tty`], an attach-only one gets
/// `no-session` (nothing resumable exists). No bridge is `not-running`.
pub fn decide(create: bool, offers: Option<Result<bool, CallError>>, name: &str) -> Result<Terminal, Record> {
    match offers {
        Some(Ok(true)) => Ok(Terminal::Attach),
        Some(Ok(false) | Err(CallError::Unsupported(_))) => Ok(Terminal::Client),
        Some(Err(e)) => Err(refusal(e, name)),
        None if create => Ok(Terminal::Tty),
        None => Err(Record::error(
            rpc::code::NO_SESSION,
            format!("`{name}`'s terminals over the fleet link aren't resumable (no helper): no session to attach to"),
        )),
    }
}

/// The in-container command of a [`Terminal::Client`] for session `id`:
/// with `create`, the helper's `session new` running it (empty: the login
/// shell), which attaches instead to a live `id`; without, `session
/// attach`. What a local tty exec runs (`exec::session_new_command`).
pub fn client_command(id: &str, create: Option<&[String]>) -> Vec<String> {
    match create {
        Some(argv) => session_new_command(id, &or_shell(argv)),
        None => session_attach_command(id),
    }
}

/// The refusal for a helper call that couldn't be made.
fn refusal(e: CallError, name: &str) -> Record {
    match e {
        CallError::NoBridge(_) => {
            Record::error(code::NOT_RUNNING, format!("`{name}` isn't running (or its helper's bridge isn't up yet)"))
        }
        CallError::Unsupported(_) => Record::error(code::UNSUPPORTED, format!("`{name}`'s helper no longer offers `{METHOD}`")),
        e => Record::error(code::FAILED, format!("cannot ask `{name}`'s helper: {e}")),
    }
}

/// The container of service `service` that lent instance `name` uses: the
/// config read from the instance's own config root (`gate` put it under
/// the header's), named as the forwards name it
/// (`port::service_container_for`), never by the control plane.
pub fn service_container(instance: &Instance, name: &str, state: &State, service: &str) -> Result<String, Record> {
    let failed = |e: anyhow::Error| Record::error(code::FAILED, format!("{e:#}"));
    let dir = instance
        .config_dir
        .as_deref()
        .ok_or_else(|| Record::error(code::NOT_FOUND, format!("`{name}` has no config root recorded")))?;
    let config = crate::config::Config::load(dir).map_err(failed)?;
    let project = crate::commands::services::project_id(dir).map_err(failed)?;
    crate::commands::port::service_container_for(&config, state, &project, name, service)
        .map_err(|e| Record::error(code::NOT_FOUND, e))
}

/// `session.attach`'s params (devsbd's `rpc_sessions`) for session `id`:
/// `{id, create?: {argv, cwd, env, user?}}`, `create` as an exec into
/// `instance` runs (`exec::exec_context`: workspace, remote user, env with
/// `SSH_AUTH_SOCK`; `host_agent` as there).
pub fn attach_params(id: &str, create: Option<&[String]>, instance: &Instance, host_agent: bool) -> Obj {
    let params = Obj::new().with("id", id);
    let Some(argv) = create else { return params };
    let argv = if argv.is_empty() { SHELL_FALLBACK_CMD.iter().map(|s| s.to_string()).collect() } else { argv.to_vec() };
    let ctx = exec_context(instance, host_agent);
    // `with` replaces a repeated name (the decoder refuses repeats), the
    // later one winning as with repeated `-e`s.
    let env = ctx.env.iter().fold(Obj::new(), |env, (k, v)| env.with(k, v.as_str()));
    let mut create = Obj::new().with("argv", argv).with("cwd", ctx.cwd).with("env", env);
    if let Some(user) = ctx.user {
        create = create.with("user", user);
    }
    params.with("create", create)
}

/// What a worker's exec runs in.
pub enum Target<'a> {
    /// Instance `instance`, as a local `exec` (`-i` when `interactive`, `-t`
    /// when `tty`; `host_agent` as `exec_argv_with` takes it).
    Instance { instance: &'a Instance, interactive: bool, tty: bool, argv: &'a [String], host_agent: bool },
    /// A service container, as the dashboard's local service tab: `-i -t`.
    Service { container: &'a str, argv: &'a [String] },
}

/// The argv (program first) of an exec into a [`Target`]: a piped exec's
/// and a tty one's. [`runtime_exec`] in the daemon; tests run a program of
/// their own.
pub type ExecCommand = fn(&Target) -> Vec<String>;

/// The runtime's `exec` into `t`: for an instance, the argv a local `exec`
/// builds (`exec::exec_argv_with`); for a service, `exec -i -t <container>
/// <argv…>`.
pub fn runtime_exec(t: &Target) -> Vec<String> {
    let mut argv = vec![crate::runtime::backend().bin().to_string()];
    match t {
        Target::Instance { instance, interactive, tty, argv: command, host_agent } => {
            argv.extend(exec_argv_with(instance, *interactive, *tty, command, *host_agent));
        }
        Target::Service { container, argv: command } => {
            argv.extend(["exec", "-i", "-t", container].map(String::from));
            argv.extend(command.iter().cloned());
        }
    }
    argv
}

/// `argv`, or the login shell (`SHELL_FALLBACK_CMD`) when it is empty.
fn or_shell(argv: &[String]) -> Vec<String> {
    if argv.is_empty() { SHELL_FALLBACK_CMD.iter().map(|s| s.to_string()).collect() } else { argv.to_vec() }
}

/// The `exit` record of a piped exec that ended with `status`: its code, or
/// the signal that killed it.
pub fn exit_record(status: ExitStatus) -> Record {
    use std::os::unix::process::ExitStatusExt;
    Record::Exit(match (status.code(), status.signal()) {
        (Some(code), _) => Exit::Code(code),
        (None, Some(signal)) => Exit::Signal(signal),
        (None, None) => Exit::Code(1),
    })
}

/// The `exit` record of a tty exec that ended with `status`: its code, or
/// the signal that killed it (portable-pty keeps only the signal's
/// `strsignal` name, [`signal_number`] maps it back).
pub fn tty_exit_record(status: &portable_pty::ExitStatus) -> Record {
    Record::Exit(match status.signal() {
        Some(name) => signal_number(name).map(Exit::Signal).unwrap_or(Exit::Code(i32::try_from(status.exit_code()).unwrap_or(1))),
        None => Exit::Code(i32::try_from(status.exit_code()).unwrap_or(i32::MAX)),
    })
}

/// The last record of a [`Terminal::Client`] that ended with `status`: the
/// session client's `NO_SESSION_EXIT` / `DETACHED_EXIT` / `VERSION_EXIT`
/// as the `no-session` / `detached` / `version` error a
/// [`Terminal::Attach`] ends with, so the caller (`pty_client::exit_of`)
/// treats both alike; anything else as [`tty_exit_record`]. The message is
/// empty: the client already printed its note into the pty, which the
/// caller got as `stdout`. A program's own 250-252 read as those, as for a
/// local session exec.
pub fn client_exit_record(status: &portable_pty::ExitStatus) -> Record {
    let code = match i32::try_from(status.exit_code()) {
        _ if status.signal().is_some() => None,
        Ok(NO_SESSION_EXIT) => Some(rpc::code::NO_SESSION),
        Ok(DETACHED_EXIT) => Some(rpc::code::DETACHED),
        Ok(VERSION_EXIT) => Some(rpc::code::VERSION),
        _ => None,
    };
    match code {
        Some(code) => Record::error(code, ""),
        None => tty_exit_record(status),
    }
}

/// The signal `strsignal` names `name` (portable-pty's `Signal <n>` for one
/// it doesn't).
fn signal_number(name: &str) -> Option<i32> {
    if let Some(n) = name.strip_prefix("Signal ") {
        return n.parse().ok();
    }
    (1..65).find(|&n| {
        // SAFETY: `strsignal` returns a NUL-terminated string (or null),
        // read at once, before another call could reuse its buffer.
        let s = unsafe { libc::strsignal(n) };
        !s.is_null() && unsafe { std::ffi::CStr::from_ptr(s) }.to_string_lossy() == name
    })
}

/// A program on a host pty: the master (for `resize`), the child, the
/// pty's read half and write half.
pub struct Tty {
    master: Box<dyn portable_pty::MasterPty + Send>,
    child: Box<dyn portable_pty::Child + Send + Sync>,
    reader: Box<dyn Read + Send>,
    writer: Box<dyn Write + Send>,
}

/// Spawn `argv` on a fresh host pty (80×24 until the control plane's first `resize`),
/// as the dashboard's terminal tabs do (`tui::term`).
pub fn spawn_tty(argv: Vec<String>) -> anyhow::Result<Tty> {
    use portable_pty::{CommandBuilder, PtySize, native_pty_system};
    let pair = native_pty_system().openpty(PtySize { rows: 24, cols: 80, pixel_width: 0, pixel_height: 0 })?;
    let mut cmd = CommandBuilder::from_argv(argv.into_iter().map(Into::into).collect());
    // Only the runtime client sees it, as in a dashboard tab.
    cmd.env("TERM", "xterm-256color");
    let child = pair.slave.spawn_command(cmd)?;
    // Only the child holds the slave: its exit ends the reader.
    drop(pair.slave);
    let reader = pair.master.try_clone_reader()?;
    let writer = pair.master.take_writer()?;
    Ok(Tty { master: pair.master, child, reader, writer })
}

/// What a stream's header started.
enum Started {
    Attach(Call, Input),
    Pipe(Child),
    /// A tty exec, the note to send before its output, and its last
    /// record ([`tty_exit_record`], [`client_exit_record`]).
    Tty(Tty, Option<String>, EndOf),
}

/// Serve one `PTY` stream, `link` the worker's end, to its end (see the
/// module doc). `files` are this host's (its `state.toml`, and what the
/// peer's [`Reach`] is read from), `peer` the link's;
/// `host_agent` probes for a host ssh-agent (`exec::has_host_agent`);
/// `exec` builds a piped or tty exec's argv ([`runtime_exec`]). Refusals
/// with `denied` are logged. A stream that started (any mode, a service
/// terminal's through its instance) is its instance's latest attach in
/// `attaches`, from `peer` (the proven origin of a routed stream), until it
/// ends: where that instance's opens go.
#[allow(clippy::too_many_arguments)]
pub fn serve(
    link: Stream,
    helper: &HelperClient,
    files: &Files,
    peer: &Peer,
    attaches: &Attaches,
    host_agent: fn() -> bool,
    exec: ExecCommand,
    log: fn(&str),
) {
    let caller = format!("fleet control plane {}", peer.name);
    let _ = link.set_read_timeout(Some(HEADER_WAIT));
    let first = rpc::read_record(&mut &link);
    let _ = link.set_read_timeout(None);
    let started = match first {
        Ok(Some(rec)) => start(rec, &link, helper, files, peer, host_agent, exec, &caller, log),
        Ok(None) => return,
        Err(e) => Err(bad(format!("no PTY header: {e}"))),
    };
    match started {
        Ok((started, instance_id)) => {
            // A terminal only: a piped exec (a script's, an agent's) is no
            // user at the instance, and its origin records no attach of its
            // own (`machines::cli::records_attach`), so it would only route
            // opens to a member that refuses them.
            let _attach = (!matches!(started, Started::Pipe(_)))
                .then(|| attaches.begin_in(&instance_id, Origin::Member(peer.name.clone())));
            match started {
                Started::Attach(call, input) => pump(&link, call, input),
                Started::Pipe(child) => run_pipe(&link, child),
                Started::Tty(tty, note, end) => run_tty(&link, tty, note.as_deref(), end),
            }
        }
        Err(rec) => {
            if let Record::Error { code: c, message } = &rec
                && c == code::DENIED
            {
                log(&format!("fleet: refused a PTY stream from {}: {message}", peer.name));
            }
            let _ = rpc::write_record(&mut &link, &rec);
        }
    }
    let _ = link.shutdown(Shutdown::Both);
}

/// Header, gate, then the call (the attach and its input), the piped
/// exec's spawn or the tty exec's, with the instance's `instance_id`; or
/// the `error` to end the stream with.
#[allow(clippy::too_many_arguments)]
fn start(
    first: Record,
    link: &Stream,
    helper: &HelperClient,
    files: &Files,
    peer: &Peer,
    host_agent: fn() -> bool,
    exec: ExecCommand,
    caller: &str,
    log: fn(&str),
) -> Result<(Started, String), Record> {
    let h = parse_header(first)?;
    let state = State::load_at(&files.state).map_err(|e| Record::error(code::FAILED, format!("{e:#}")))?;
    let (reach, warning) = Reach::load(files, peer.fleet_root.as_deref());
    if let Some(w) = warning {
        log(&format!("fleet: a PTY stream from {}: {w}", peer.name));
    }
    let (name, instance) = gate(&h, &state, &reach)?;
    let id = instance.instance_id.clone();
    start_in(&h, &state, name, instance, link, helper, host_agent, exec, caller).map(|s| (s, id))
}

/// [`start`] past the gate: what instance `name` runs for header `h`.
#[allow(clippy::too_many_arguments)]
fn start_in(
    h: &Header,
    state: &State,
    name: &str,
    instance: &Instance,
    link: &Stream,
    helper: &HelperClient,
    host_agent: fn() -> bool,
    exec: ExecCommand,
    caller: &str,
) -> Result<Started, Record> {
    let tty = |argv: Vec<String>, note: Option<String>, end: EndOf| {
        spawn_tty(argv)
            .map(|t| Started::Tty(t, note, end))
            .map_err(|e| Record::error(code::FAILED, format!("cannot run a terminal in `{name}`: {e:#}")))
    };
    let (id, create) = match &h.mode {
        Mode::Pipe { argv, interactive } => {
            let target = Target::Instance { instance, interactive: *interactive, tty: false, argv, host_agent: host_agent() };
            let argv = exec(&target);
            let (program, args) = argv.split_first().ok_or_else(|| Record::error(code::FAILED, "an empty exec"))?;
            let mut command = std::process::Command::new(program);
            command
                .args(args)
                .stdin(if *interactive { Stdio::piped() } else { Stdio::null() })
                .stdout(Stdio::piped())
                .stderr(Stdio::piped());
            return command
                .spawn()
                .map(Started::Pipe)
                .map_err(|e| Record::error(code::FAILED, format!("cannot run an exec in `{name}`: {e}")));
        }
        Mode::Service { name: service, argv } => {
            let container = service_container(instance, name, state, service)?;
            return tty(exec(&Target::Service { container: &container, argv: &or_shell(argv) }), None, tty_exit_record);
        }
        Mode::Session { id, create } => (id, create),
    };
    let offers = instance.devsbd_arch.is_some().then(|| helper.offers(&instance.container, METHOD, caller));
    let (argv, note, end): (_, _, EndOf) = match decide(create.is_some(), offers, name)? {
        Terminal::Attach => (None, None, tty_exit_record),
        Terminal::Client => (Some(client_command(id, create.as_deref())), None, client_exit_record),
        Terminal::Tty => (Some(or_shell(create.as_deref().unwrap_or_default())), Some(TTY_NOTE.to_string()), tty_exit_record),
    };
    if let Some(argv) = argv {
        let target = Target::Instance { instance, interactive: true, tty: true, argv: &argv, host_agent: host_agent() };
        return tty(exec(&target), note, end);
    }
    let params = attach_params(id, create.as_deref(), instance, host_agent());
    // While it queues: whether the control plane closed its end.
    let abandoned = || crate::serve::daemon::hung_up(link, Duration::ZERO);
    let (call, input) = helper.call_with_input(&instance.container, METHOD, params, Obj::new(), caller, &abandoned).map_err(|e| match e {
        CallError::NoBridge(_) | CallError::Unsupported(_) => refusal(e, name),
        CallError::Abandoned => Record::error(code::FAILED, "the caller hung up while the attach queued"),
        CallError::Io(e) => Record::error(code::LOST, format!("cannot reach `{name}`'s helper: {e}")),
    })?;
    Ok(Started::Attach(call, input))
}

/// A piped exec to its end: the control plane's input into its stdin and its stdout
/// and stderr out as records, each on a thread of its own; once it exited
/// and both pipes are drained, its `exit` record. The control plane hanging up first
/// (`feed_pipe` reads the stream's end, or a peek between waits does)
/// kills and reaps it, and nothing more is written.
fn run_pipe(link: &Stream, mut child: Child) {
    let (stdin, stdout, stderr) = (child.stdin.take(), child.stdout.take(), child.stderr.take());
    // One writer at a time: a record is one write, never interleaved.
    let writer = Mutex::new(());
    let send = |rec: &Record| {
        let _turn = writer.lock().unwrap_or_else(|e| e.into_inner());
        rpc::write_record(&mut &*link, rec).is_ok()
    };
    let done = AtomicBool::new(false);
    let gone = AtomicBool::new(false);
    std::thread::scope(|s| {
        let send = &send;
        let out = stdout.map(|r| s.spawn(move || drain(r, Record::Stdout, send)));
        let err = stderr.map(|r| s.spawn(move || drain(r, Record::Stderr, send)));
        if let Ok(reader) = link.try_clone() {
            let (done, gone) = (&done, &gone);
            s.spawn(move || feed_pipe(reader, stdin, done, gone));
        }
        let ended = loop {
            match child.try_wait() {
                Ok(Some(status)) => break Ok(status),
                Ok(None) => {}
                Err(e) => break Err(e),
            }
            if gone.load(Ordering::SeqCst) || crate::serve::daemon::hung_up(link, PIPE_TICK) {
                gone.store(true, Ordering::SeqCst);
                let _ = child.kill();
                let _ = child.wait();
                break Err(std::io::Error::other("the caller hung up"));
            }
        };
        for drained in [out, err].into_iter().flatten() {
            let _ = drained.join();
        }
        if !gone.load(Ordering::SeqCst) {
            let last = match ended {
                Ok(status) => exit_record(status),
                Err(e) => {
                    let _ = child.kill();
                    let _ = child.wait();
                    Record::error(code::FAILED, format!("cannot wait for the exec: {e}"))
                }
            };
            send(&last);
        }
        done.store(true, Ordering::SeqCst);
        // Ends `feed_pipe`'s read.
        let _ = link.shutdown(Shutdown::Both);
    });
}

/// How a tty exec's exit becomes its last record.
type EndOf = fn(&portable_pty::ExitStatus) -> Record;

/// A tty exec to its end: `note` first (as a `stderr` record), then the
/// pty's output as `stdout` records on a thread of its own, the control plane's
/// `stdin` into the pty and its `resize`s onto it on another; once the
/// child exited and the output is drained, its last record (`end`:
/// [`tty_exit_record`], [`client_exit_record`]). The control plane hanging
/// up first kills (SIGHUP, then SIGKILL: portable-pty's `kill`) and reaps
/// it, and nothing more is written.
fn run_tty(link: &Stream, tty: Tty, note: Option<&str>, end: EndOf) {
    let Tty { master, mut child, reader, writer } = tty;
    let master = Mutex::new(master);
    // One writer at a time: a record is one write, never interleaved.
    let turn = Mutex::new(());
    let send = |rec: &Record| {
        let _turn = turn.lock().unwrap_or_else(|e| e.into_inner());
        rpc::write_record(&mut &*link, rec).is_ok()
    };
    if let Some(note) = note {
        send(&Record::Stderr(note.as_bytes().to_vec()));
    }
    let done = AtomicBool::new(false);
    let gone = AtomicBool::new(false);
    std::thread::scope(|s| {
        let send = &send;
        let out = s.spawn(move || drain(reader, Record::Stdout, send));
        let (m, d, g) = (&master, &done, &gone);
        let feeder = link.try_clone().ok().map(|r| s.spawn(move || feed_tty(r, writer, m, d, g)));
        let ended = loop {
            match child.try_wait() {
                Ok(Some(status)) => break Ok(status),
                Ok(None) => {}
                Err(e) => break Err(e),
            }
            if gone.load(Ordering::SeqCst) || crate::serve::daemon::hung_up(link, PIPE_TICK) {
                gone.store(true, Ordering::SeqCst);
                let _ = child.kill();
                let _ = child.wait();
                break Err(std::io::Error::other("the caller hung up"));
            }
        };
        // The child gone, its pty's last bytes, then the read's end.
        let _ = out.join();
        if !gone.load(Ordering::SeqCst) {
            let last = match ended {
                Ok(status) => end(&status),
                Err(e) => {
                    let _ = child.kill();
                    let _ = child.wait();
                    Record::error(code::FAILED, format!("cannot wait for the terminal: {e}"))
                }
            };
            send(&last);
        }
        done.store(true, Ordering::SeqCst);
        // Ends `feed_tty`'s read.
        let _ = link.shutdown(Shutdown::Both);
        // Only now, the child reaped: dropping the writer types `\n` and
        // EOF into the pty (portable-pty's `UnixMasterWriter`), which the
        // runtime's raw exec client would relay to the program, ending a
        // session's shell on every hang-up.
        if let Some(feeder) = feeder {
            drop(feeder.join());
        }
    });
}

/// The control plane's records into a tty exec until the control plane closes its end, which
/// flags `gone` unless the exec is over (`done`): `stdin` to the pty,
/// `resize` onto it. `stdin-eof` is ignored (a terminal has no end of its
/// own to give), as is anything else. Returns `writer` undropped, for
/// [`run_tty`] to drop once the child is gone.
fn feed_tty(
    mut reader: Stream,
    mut writer: Box<dyn Write + Send>,
    master: &Mutex<Box<dyn portable_pty::MasterPty + Send>>,
    done: &AtomicBool,
    gone: &AtomicBool,
) -> Box<dyn Write + Send> {
    loop {
        match rpc::read_record(&mut reader) {
            Ok(Some(Record::Stdin(bytes))) => {
                let _ = writer.write_all(&bytes).and_then(|()| writer.flush());
            }
            Ok(Some(Record::Resize { cols, rows })) => {
                let size = portable_pty::PtySize { rows, cols, pixel_width: 0, pixel_height: 0 };
                let _ = master.lock().unwrap_or_else(|e| e.into_inner()).resize(size);
            }
            Ok(Some(_)) => {}
            Ok(None) | Err(_) => {
                if !done.load(Ordering::SeqCst) {
                    gone.store(true, Ordering::SeqCst);
                }
                return writer;
            }
        }
    }
}

/// One of a piped exec's outputs to its end, each read as one `wrap`
/// record, until the control plane refuses a write (a tty's too).
fn drain(mut r: impl Read, wrap: fn(Vec<u8>) -> Record, send: &(dyn Fn(&Record) -> bool + Sync)) {
    let mut buf = vec![0u8; PIPE_CHUNK];
    loop {
        match r.read(&mut buf) {
            Ok(0) => return,
            Ok(n) => {
                if !send(&wrap(buf[..n].to_vec())) {
                    return;
                }
            }
            Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
            Err(_) => return,
        }
    }
}

/// The control plane's records into a piped exec's `stdin` (`None`: not interactive,
/// its input ignored) until the control plane closes its end, which flags `gone`
/// unless the exec is over (`done`). `stdin-eof`, or a write the exec
/// refuses, closes its stdin.
fn feed_pipe(mut reader: Stream, mut stdin: Option<std::process::ChildStdin>, done: &AtomicBool, gone: &AtomicBool) {
    loop {
        match rpc::read_record(&mut reader) {
            Ok(Some(Record::Stdin(bytes))) => {
                if let Some(w) = &mut stdin
                    && w.write_all(&bytes).is_err()
                {
                    stdin = None;
                }
            }
            Ok(Some(Record::StdinEof)) => stdin = None,
            Ok(Some(_)) => {}
            Ok(None) | Err(_) => {
                if !done.load(Ordering::SeqCst) {
                    gone.store(true, Ordering::SeqCst);
                }
                return;
            }
        }
    }
}

/// The attach's last record.
fn is_end(rec: &Record) -> bool {
    matches!(rec, Record::Exit(_) | Record::Error { .. } | Record::Result(_))
}

/// Relay until the attach ends: the control plane's records into `input` on a thread
/// of their own, the call's records back to the control plane, unchanged, up to and
/// including its end record. The control plane closing its end cancels the call; a
/// call that ends without an end record is answered with [`code::LOST`].
fn pump(link: &Stream, mut call: Call, input: Input) {
    let done = AtomicBool::new(false);
    let gone = AtomicBool::new(false);
    let cancel = call.canceller();
    std::thread::scope(|s| {
        if let Ok(reader) = link.try_clone() {
            let (done, gone, cancel) = (&done, &gone, &cancel);
            s.spawn(move || feed(reader, input, done, gone, cancel));
        }
        let last = loop {
            match call.next() {
                Ok(Some(rec)) => {
                    let end = is_end(&rec);
                    // A failed write: the control plane is gone; dropping the call
                    // (unfinished) cancels it.
                    if rpc::write_record(&mut &*link, &rec).is_err() || end {
                        break None;
                    }
                }
                Ok(None) => break Some(Record::error(code::LOST, "the attach ended without an end record")),
                Err(_) if gone.load(Ordering::SeqCst) => break None,
                Err(e) => break Some(Record::error(code::LOST, format!("the bridge to the instance was lost: {e}"))),
            }
        };
        if let Some(rec) = last {
            let _ = rpc::write_record(&mut &*link, &rec);
        }
        done.store(true, Ordering::SeqCst);
        // Ends `feed`'s read.
        let _ = link.shutdown(Shutdown::Both);
    });
}

/// The control plane's records into the attach until the control plane closes its end (or
/// sends something undecodable), which cancels the call unless it is over.
/// Records other than input are ignored, as the helper ignores them.
fn feed(mut reader: Stream, mut input: Input, done: &AtomicBool, gone: &AtomicBool, cancel: &Cancel) {
    loop {
        let sent = match rpc::read_record(&mut reader) {
            Ok(Some(Record::Stdin(bytes))) => input.stdin(&bytes),
            Ok(Some(Record::Resize { cols, rows })) => input.resize(cols, rows),
            Ok(Some(Record::StdinEof)) => input.stdin_eof(),
            Ok(Some(_)) => Ok(()),
            Ok(None) | Err(_) => {
                if !done.load(Ordering::SeqCst) {
                    gone.store(true, Ordering::SeqCst);
                    cancel.cancel();
                }
                return;
            }
        };
        // The call's stream is gone: it's ending, `pump` answers.
        if sent.is_err() {
            return;
        }
    }
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeMap;
    use std::os::unix::net::UnixStream;
    use std::path::Path;

    use super::*;
    use crate::devsbd::proto::caps;
    use crate::devsbd::rpc::{Call as RpcCall, Exit};
    use crate::serve::helper::tests::{Fake, log, logged};

    fn scratch(tag: &str) -> PathBuf {
        let dir = std::env::temp_dir().join(format!("dsv-pty-{tag}-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::canonicalize(&dir).unwrap()
    }

    const SESSION: &str = "1700000000-ab12";

    fn header(params: Obj) -> Record {
        Record::Call(RpcCall { method: METHOD.into(), params, meta: Obj::new() })
    }

    fn base(root: &str) -> Obj {
        Obj::new().with("root", root).with("instance", "web-1").with("session", SESSION)
    }

    #[test]
    fn the_header_parses_and_is_checked() {
        let h = parse_header(header(base("/f/cfg"))).unwrap();
        assert_eq!(h, Header { root: "/f/cfg".into(), instance: "web-1".into(), mode: session(None) });
        let shell = parse_header(header(base("/f").with("create", Obj::new()))).unwrap();
        assert_eq!(shell.mode, session(Some(Vec::new())), "no argv: the login shell");
        let argv = parse_header(header(base("/f").with("create", Obj::new().with("argv", vec!["htop".to_string()])))).unwrap();
        assert_eq!(argv.mode, session(Some(vec!["htop".to_string()])));
        assert_eq!(parse_header(header(base("/f").with("create", Json::Null))).unwrap().mode, session(None));

        let refused = |rec: Record| match parse_header(rec) {
            Err(Record::Error { code, message }) => (code, message),
            other => panic!("{other:?}"),
        };
        let (c, m) = refused(Record::Stdin(b"x".to_vec()));
        assert_eq!((c.as_str(), m.contains("not a `stdin` record")), (code::BAD_REQUEST, true));
        let wrong = Record::Call(RpcCall { method: "run.start".into(), params: base("/f"), meta: Obj::new() });
        assert!(refused(wrong).1.contains("not `run.start`"));
        assert!(refused(header(base("/f").with("session", "nope"))).1.contains("bad session id"));
        assert!(refused(header(base("/f").with("instance", ""))).1.contains("needs `instance`"));
        assert!(refused(header(Obj::new().with("instance", "a").with("session", SESSION))).1.contains("needs `root`"));
        assert!(refused(header(base("/f").with("create", "sh"))).1.contains("`create` must be"));
        assert!(refused(header(base("/f").with("create", Obj::new().with("argv", "sh")))).1.contains("`create.argv`"));
    }

    fn session(create: Option<Vec<String>>) -> Mode {
        Mode::Session { id: SESSION.into(), create }
    }

    fn pipe_base(root: &str) -> Obj {
        Obj::new().with("root", root).with("instance", "web-1")
    }

    #[test]
    fn a_pipe_header_parses_and_excludes_a_session() {
        let ls = || Obj::new().with("argv", vec!["ls".to_string(), "-l".into()]);
        let h = parse_header(header(pipe_base("/f").with("pipe", ls()))).unwrap();
        assert_eq!(h.mode, Mode::Pipe { argv: vec!["ls".into(), "-l".into()], interactive: false }, "no session needed");
        let i = parse_header(header(pipe_base("/f").with("pipe", ls().with("interactive", true)))).unwrap();
        assert_eq!(i.mode, Mode::Pipe { argv: vec!["ls".into(), "-l".into()], interactive: true });

        let refused = |params: Obj| match parse_header(header(params)) {
            Err(Record::Error { code, message }) => {
                assert_eq!(code, code::BAD_REQUEST);
                message
            }
            other => panic!("{other:?}"),
        };
        assert!(refused(base("/f").with("pipe", ls())).contains("not both"), "with a session");
        assert!(refused(pipe_base("/f").with("pipe", ls()).with("create", Obj::new())).contains("not both"));
        assert!(refused(pipe_base("/f").with("pipe", Obj::new())).contains("needs a command"));
        assert!(refused(pipe_base("/f").with("pipe", Obj::new().with("argv", Vec::<String>::new()))).contains("needs a command"));
        assert!(refused(pipe_base("/f").with("pipe", Obj::new().with("argv", "ls"))).contains("array of strings"));
        assert!(refused(pipe_base("/f").with("pipe", ls().with("interactive", "yes"))).contains("boolean"));
        assert!(refused(pipe_base("/f").with("pipe", "ls")).contains("must be an object"));
        assert!(refused(pipe_base("/f")).contains("needs `session`"), "neither");
    }

    #[test]
    fn a_service_header_parses_creates_and_excludes_the_others() {
        let svc = || pipe_base("/f").with("service", "db");
        let h = parse_header(header(svc().with("create", Obj::new()))).unwrap();
        assert_eq!(h, Header { root: "/f".into(), instance: "web-1".into(), mode: Mode::Service { name: "db".into(), argv: vec![] } });
        let psql = parse_header(header(svc().with("create", Obj::new().with("argv", vec!["psql".to_string()])))).unwrap();
        assert_eq!(psql.mode, Mode::Service { name: "db".into(), argv: vec!["psql".into()] });

        let refused = |params: Obj| match parse_header(header(params)) {
            Err(Record::Error { code, message }) => {
                assert_eq!(code, code::BAD_REQUEST);
                message
            }
            other => panic!("{other:?}"),
        };
        assert!(refused(svc()).contains("needs `create`"), "no attach-only service terminal");
        assert!(refused(svc().with("create", "sh")).contains("`create` must be"));
        assert!(refused(svc().with("create", Obj::new()).with("session", SESSION)).contains("one of"));
        let ls = Obj::new().with("argv", vec!["ls".to_string()]);
        assert!(refused(svc().with("create", Obj::new()).with("pipe", ls)).contains("one of"));
        assert!(refused(pipe_base("/f").with("service", "").with("create", Obj::new())).contains("needs `service`"));
        assert!(refused(svc().with("create", Obj::new().with("argv", "sh"))).contains("`create.argv`"));
    }

    #[test]
    fn exits_encode_a_code_or_a_signal() {
        use std::os::unix::process::ExitStatusExt;
        assert_eq!(exit_record(ExitStatus::from_raw(3 << 8)), Record::Exit(Exit::Code(3)));
        assert_eq!(exit_record(ExitStatus::from_raw(0)), Record::Exit(Exit::Code(0)));
        assert_eq!(exit_record(ExitStatus::from_raw(9)), Record::Exit(Exit::Signal(9)));
        let rec = exit_record(ExitStatus::from_raw(15));
        assert_eq!(rpc::read_record(&mut &rec.encode()[..]).unwrap(), Some(rec), "as rpc carries it");
    }

    /// `state.toml` text: `web-1` lent (under `cfg`, with a helper), `bare`
    /// lent without one, `own` outside the fleet root.
    fn state_with(base: &Path, root: &Path) -> State {
        let inst = |name: &str, dir: &Path, helper: bool| {
            format!(
                "[instance.{name}]\ninstance_id = \"id-{name}\"\nsandbox = \"web\"\ncontainer = \"devsandbox-{name}\"\n\
                 folder = \"/w\"\nworkspace = \"/workspaces/{name}\"\ncreated_unix = 1\nconfig_dir = {:?}\n{}",
                dir.to_str().unwrap(),
                if helper { "devsbd_arch = \"x86_64\"\n" } else { "" }
            )
        };
        let text = inst("web-1", &root.join("cfg"), true) + &inst("bare", &root.join("cfg"), false) + &inst("own", &base.join("mine"), true);
        let path = base.join("state.toml");
        std::fs::write(&path, text).unwrap();
        State::load_at(&path).unwrap()
    }

    fn code_of(r: Result<impl std::fmt::Debug, Record>) -> String {
        match r {
            Err(Record::Error { code, .. }) => code,
            other => panic!("{other:?}"),
        }
    }

    #[test]
    fn the_gate_takes_lent_instances_with_a_helper() {
        let b = scratch("gate");
        let root = b.join("fleet/control_plane");
        std::fs::create_dir_all(root.join("cfg")).unwrap();
        std::fs::create_dir_all(root.join("other")).unwrap();
        std::fs::create_dir_all(b.join("mine")).unwrap();
        let state = state_with(&b, &root);
        let cfg = root.join("cfg");
        let h = |root: &Path, instance: &str| Header { root: root.to_path_buf(), instance: instance.into(), mode: session(None) };
        let reach = |own: &[PathBuf]| Reach { trust: crate::worker_policy::Trust::Worker, fleet_root: Some(root.clone()), own: own.iter().cloned().collect() };
        // An own root reaches its instances, exactly.
        let mine = b.join("mine");
        std::fs::create_dir_all(mine.join("nested")).unwrap();
        let with_own = reach(&[mine.clone()]);
        assert_eq!(gate(&h(&mine, "own"), &state, &with_own).unwrap().0, "own", "an own root's");
        assert_eq!(gate(&h(&mine, "id-own"), &state, &with_own).unwrap().0, "own", "by id");
        assert_eq!(code_of(gate(&h(&mine.join("nested"), "own"), &state, &with_own)), code::DENIED, "not what's nested in it");
        assert_eq!(code_of(gate(&h(&cfg, "own"), &state, &with_own)), code::NOT_FOUND, "not another root's");
        let full = Reach { trust: crate::worker_policy::Trust::Full, ..reach(&[]) };
        assert_eq!(gate(&h(&mine, "own"), &state, &full).unwrap().0, "own", "`full`: any root");
        let r = reach(&[]);
        let (name, i) = gate(&h(&cfg, "web-1"), &state, &r).unwrap();
        assert_eq!((name, i.container.as_str()), ("web-1", "devsandbox-web-1"));
        assert_eq!(gate(&h(&cfg, "id-web-1"), &state, &r).unwrap().0, "web-1", "by id");
        assert_eq!(gate(&h(&root, "web-1"), &state, &r).unwrap().0, "web-1", "the fleet root holds it too");
        assert_eq!(code_of(gate(&h(&cfg, "web"), &state, &r)), code::NOT_FOUND, "exact names only");
        assert_eq!(code_of(gate(&h(&cfg, "own"), &state, &r)), code::NOT_FOUND, "not lent");
        assert_eq!(code_of(gate(&h(&root.join("other"), "web-1"), &state, &r)), code::NOT_FOUND, "another root's");
        assert_eq!(code_of(gate(&h(&b.join("mine"), "own"), &state, &r)), code::DENIED, "outside the fleet root");
        assert_eq!(code_of(gate(&h(&root.join("gone"), "web-1"), &state, &r)), code::NOT_FOUND);
        assert_eq!(code_of(gate(&h(Path::new("rel"), "web-1"), &state, &r)), code::BAD_REQUEST);
        assert_eq!(gate(&h(&cfg, "bare"), &state, &r).unwrap().0, "bare", "no helper: `decide`'s to say");
        let pipe = |instance: &str| Header { mode: Mode::Pipe { argv: vec!["ls".into()], interactive: false }, ..h(&cfg, instance) };
        assert_eq!(gate(&pipe("bare"), &state, &r).unwrap().0, "bare", "a pipe needs no helper");
        assert_eq!(code_of(gate(&pipe("own"), &state, &r)), code::NOT_FOUND, "but the same reach");
        let _ = std::fs::remove_dir_all(&b);
    }

    #[test]
    fn a_helper_that_cant_attach_runs_its_session_client() {
        assert_eq!(decide(true, Some(Ok(true)), "w"), Ok(Terminal::Attach));
        assert_eq!(decide(false, Some(Ok(true)), "w"), Ok(Terminal::Attach), "an attach is the helper's");
        // Not root (or an older helper): the session client, creating or not.
        for create in [true, false] {
            assert_eq!(decide(create, Some(Ok(false)), "w"), Ok(Terminal::Client));
            assert_eq!(decide(create, Some(Err(CallError::Unsupported("c".into()))), "w"), Ok(Terminal::Client), "an older helper");
        }
        // No helper: a plain tty; attach only, nothing resumable exists.
        assert_eq!(decide(true, None, "w"), Ok(Terminal::Tty));
        let Err(Record::Error { code, message }) = decide(false, None, "w") else { panic!() };
        assert_eq!(code, rpc::code::NO_SESSION);
        assert!(message.contains("aren't resumable (no helper)"), "{message}");
        assert_eq!(code_of(decide(true, Some(Err(CallError::NoBridge("c".into()))), "w")), code::NOT_RUNNING);
        assert_eq!(code_of(decide(true, Some(Err(CallError::Io(std::io::Error::other("x")))), "w")), code::FAILED);
    }

    #[test]
    fn session_client_ends_read_as_an_attachs() {
        use std::os::unix::process::ExitStatusExt;
        let of = |raw| client_exit_record(&portable_pty::ExitStatus::from(ExitStatus::from_raw(raw)));
        assert_eq!(of(250 << 8), Record::error(rpc::code::NO_SESSION, ""));
        assert_eq!(of(251 << 8), Record::error(rpc::code::DETACHED, ""));
        assert_eq!(of(252 << 8), Record::error(rpc::code::VERSION, ""));
        assert_eq!(of(0), Record::Exit(Exit::Code(0)));
        assert_eq!(of(3 << 8), Record::Exit(Exit::Code(3)));
        assert_eq!(of(253 << 8), Record::Exit(Exit::Code(253)));
        assert_eq!(of(9), Record::Exit(Exit::Signal(9)), "a signal stays one");
    }

    #[test]
    fn tty_exits_keep_the_signal_number() {
        use std::os::unix::process::ExitStatusExt;
        let of = |raw| tty_exit_record(&portable_pty::ExitStatus::from(ExitStatus::from_raw(raw)));
        assert_eq!(of(3 << 8), Record::Exit(Exit::Code(3)));
        assert_eq!(of(9), Record::Exit(Exit::Signal(9)));
        assert_eq!(of(1), Record::Exit(Exit::Signal(1)));
        assert_eq!(tty_exit_record(&portable_pty::ExitStatus::with_signal("Signal 50")), Record::Exit(Exit::Signal(50)));
    }

    #[test]
    fn the_exec_argv_is_a_local_execs() {
        let b = scratch("argv");
        let root = b.join("fleet/control_plane");
        std::fs::create_dir_all(root.join("cfg")).unwrap();
        let state = state_with(&b, &root);
        let bin = crate::runtime::backend().bin().to_string();
        let argv = vec!["ls".to_string()];
        let inst = &state.instances["web-1"];
        let tty = runtime_exec(&Target::Instance { instance: inst, interactive: true, tty: true, argv: &argv, host_agent: false });
        assert_eq!(tty[0], bin);
        assert_eq!(tty[1..], exec_argv_with(inst, true, true, &argv, false));
        let svc = runtime_exec(&Target::Service { container: "devsandbox-svc-p-db", argv: &argv });
        assert_eq!(svc, [bin.as_str(), "exec", "-i", "-t", "devsandbox-svc-p-db", "ls"]);
        assert_eq!(or_shell(&[]), SHELL_FALLBACK_CMD);

        // A session client's: what a local tty exec of a session runs.
        let client = |create: Option<&[String]>| {
            runtime_exec(&Target::Instance { instance: inst, interactive: true, tty: true, argv: &client_command(SESSION, create), host_agent: false })
        };
        let shell: Vec<String> = SHELL_FALLBACK_CMD.iter().map(|s| s.to_string()).collect();
        assert_eq!(client(Some(&[]))[1..], exec_argv_with(inst, true, true, &session_new_command(SESSION, &shell), false), "the login shell");
        assert_eq!(client(Some(&argv))[1..], exec_argv_with(inst, true, true, &session_new_command(SESSION, &argv), false));
        assert_eq!(client(None)[1..], exec_argv_with(inst, true, true, &session_attach_command(SESSION), false), "attach only");
        let _ = std::fs::remove_dir_all(&b);
    }

    #[test]
    fn create_runs_as_an_exec_would() {
        let b = scratch("params");
        let root = b.join("fleet/control_plane");
        std::fs::create_dir_all(root.join("cfg")).unwrap();
        let state = state_with(&b, &root);
        let mut inst = state.instances["web-1"].clone();
        assert_eq!(attach_params(SESSION, None, &inst, false), Obj::new().with("id", SESSION), "attach only");

        inst.remote_user = Some("vscode".into());
        inst.remote_env = BTreeMap::from([("A".into(), "1".into()), ("SSH_AUTH_SOCK".into(), "/mine".into())]);
        inst.ssh_auth_sock = Some("/ssh-agent".into());
        let p = attach_params(SESSION, Some(&[]), &inst, false);
        let c = p.obj("create").unwrap();
        let shell: Vec<String> = SHELL_FALLBACK_CMD.iter().map(|s| s.to_string()).collect();
        assert_eq!(c.strs("argv"), Some(shell.as_slice()), "empty argv: the login shell");
        assert_eq!(c.str("cwd"), Some("/workspaces/web-1"));
        assert_eq!(c.str("user"), Some("vscode"));
        assert_eq!(c.map("env").unwrap(), [("A".to_string(), "1".to_string()), ("SSH_AUTH_SOCK".into(), "/ssh-agent".into())], "one each, the agent's last");
        // What the helper decodes: env sits at the RPC JSON's depth cap.
        let rec = Record::Call(RpcCall { method: METHOD.into(), params: p, meta: Obj::new() });
        assert_eq!(rpc::read_record(&mut &rec.encode()[..]).unwrap(), Some(rec));

        inst.remote_user = None;
        let c = attach_params(SESSION, Some(&["htop".to_string()]), &inst, false).obj("create").unwrap().clone();
        assert_eq!((c.strs("argv"), c.str("user")), (Some(&["htop".to_string()][..]), None), "no user: the container's");
        let _ = std::fs::remove_dir_all(&b);
    }

    /// A container's helper for [`serve`]: `rpc.methods` offering
    /// `session.attach`; the attach sends its params' `id` and `create`'s
    /// `cwd` as `stdout`, then `stdin` back as `stdout`, a `resize` as
    /// `stdout` `<cols>x<rows>`, `exit 7` at `stdin-eof`. Session
    /// `1700000000-0105` (lost) sends one `stdout` and closes without an end.
    fn sessions(s: UnixStream) {
        let mut r = &s;
        let Ok(Some(Record::Call(call))) = rpc::read_record(&mut r) else { return };
        let mut w = &s;
        let mut send = |rec: Record| rpc::write_record(&mut w, &rec);
        match call.method.as_str() {
            "rpc.methods" => {
                let _ = send(Record::Result(Obj::new().with("methods", vec!["session.attach@1".to_string()])));
            }
            "session.attach" => {
                let id = call.params.str("id").unwrap_or_default().to_string();
                let cwd = call.params.obj("create").and_then(|c| c.str("cwd")).unwrap_or("-").to_string();
                let _ = send(Record::Stdout(format!("{id} {cwd}\n").into_bytes()));
                if id == "1700000000-0105" {
                    let _ = s.shutdown(Shutdown::Both);
                    return;
                }
                loop {
                    let rec = match rpc::read_record(&mut r) {
                        Ok(Some(Record::Stdin(b))) => Record::Stdout(b),
                        Ok(Some(Record::Resize { cols, rows })) => Record::Stdout(format!("{cols}x{rows}").into_bytes()),
                        Ok(Some(Record::StdinEof)) => Record::Exit(Exit::Code(7)),
                        Ok(Some(_)) => continue,
                        // The caller hung up: detached.
                        _ => return,
                    };
                    let last = matches!(rec, Record::Exit(_));
                    let _ = send(rec);
                    if last {
                        break;
                    }
                }
            }
            m => {
                let _ = send(Record::error(rpc::code::UNKNOWN_METHOD, format!("no method `{m}`")));
            }
        }
        let _ = s.shutdown(Shutdown::Write);
        let _ = std::io::copy(&mut r, &mut std::io::sink());
    }

    /// A non-root helper: offers nothing of the sessions.
    fn not_root(s: UnixStream) {
        let mut r = &s;
        let Ok(Some(Record::Call(_))) = rpc::read_record(&mut r) else { return };
        let _ = rpc::write_record(&mut &s, &Record::Result(Obj::new().with("methods", vec!["rpc.methods@1".to_string()])));
    }

    struct World {
        base: PathBuf,
        root: PathBuf,
        state: PathBuf,
        helper: HelperClient,
        attaches: Attaches,
    }

    impl Drop for World {
        fn drop(&mut self) {
            let _ = std::fs::remove_dir_all(&self.base);
        }
    }

    /// The config at `cfg`: sandbox `web` (every instance's) uses `db`.
    const CONFIG: &str = "[services.db]\nimage = \"postgres\"\nscope = \"isolated\"\n\n\
                          [services.cache]\nimage = \"redis\"\nscope = \"global\"\n\n\
                          [sandbox.web]\nimage = \"node\"\nservices = [\"db\"]\n";

    fn world(tag: &str) -> World {
        let base = scratch(tag);
        let root = base.join("fleet/control_plane");
        std::fs::create_dir_all(root.join("cfg")).unwrap();
        std::fs::write(root.join("cfg").join(crate::config::CONFIG_FILE), CONFIG).unwrap();
        state_with(&base, &root);
        let fake = Fake::default();
        fake.add("devsandbox-web-1", caps::RPC, 1, sessions);
        let helper = HelperClient::new(fake.clone(), log);
        // `bare` has no helper in `state.toml`; `own` isn't lent.
        World { state: base.join("state.toml"), base, root, helper, attaches: Attaches::default() }
    }

    /// The control plane's end of a stream served on a thread, its header sent.
    fn open(w: &World, header: Record, helper: HelperClient) -> (UnixStream, std::thread::JoinHandle<()>) {
        let (control_plane, ours) = UnixStream::pair().unwrap();
        let peer = Peer { name: "me@control_plane".into(), fleet_root: Some(w.root.clone()), env: None, agent: None, key: None, introduced_by: None };
        let files = Files { state: w.state.clone(), member: None, home: None };
        let attaches = w.attaches.clone();
        let t = std::thread::spawn(move || serve(ours, &helper, &files, &peer, &attaches, || false, sh, log));
        rpc::write_record(&mut &control_plane, &header).unwrap();
        control_plane.set_read_timeout(Some(Duration::from_secs(10))).unwrap();
        (control_plane, t)
    }

    fn rest(mut control_plane: &UnixStream) -> Vec<Record> {
        let mut recs = Vec::new();
        while let Ok(Some(rec)) = rpc::read_record(&mut control_plane) {
            recs.push(rec);
        }
        recs
    }

    fn create_header(w: &World, session: &str) -> Record {
        let cfg = w.root.join("cfg");
        header(base(cfg.to_str().unwrap()).with("session", session).with("create", Obj::new()))
    }

    #[test]
    fn a_stream_relays_input_and_output_to_the_end_record() {
        let w = world("relay");
        let (control_plane, t) = open(&w, create_header(&w, SESSION), w.helper.clone());
        let mut out = &control_plane;
        rpc::write_record(&mut out, &Record::Stdin(b"ls\n".to_vec())).unwrap();
        rpc::write_record(&mut out, &Record::Resize { cols: 120, rows: 40 }).unwrap();
        rpc::write_record(&mut out, &Record::Signal(2)).unwrap();
        rpc::write_record(&mut out, &Record::StdinEof).unwrap();
        let recs = rest(&control_plane);
        t.join().unwrap();
        let stdout = |s: &str| Record::Stdout(s.as_bytes().to_vec());
        assert_eq!(
            recs,
            [stdout(&format!("{SESSION} /workspaces/web-1\n")), stdout("ls\n"), stdout("120x40"), Record::Exit(Exit::Code(7))],
            "the helper's records, unchanged, then nothing"
        );
    }

    fn attached(w: &World, id: &str) -> Option<Origin> {
        w.attaches.latest(id, std::time::Instant::now())
    }

    #[test]
    fn a_stream_is_its_instances_latest_attach_from_its_origin() {
        let w = world("attach");
        assert_eq!(attached(&w, "id-web-1"), None);
        let (control_plane, t) = open(&w, create_header(&w, SESSION), w.helper.clone());
        assert!(matches!(rpc::read_record(&mut &control_plane), Ok(Some(Record::Stdout(_)))), "attached");
        assert_eq!(attached(&w, "id-web-1"), Some(Origin::Member("me@control_plane".into())), "during the stream");
        assert!(w.attaches.live_in("id-web-1"));
        // A local attach begins later: the latest, and the stream's end
        // doesn't clobber it.
        let here = w.attaches.begin_in("id-web-1", Origin::Here);
        rpc::write_record(&mut &control_plane, &Record::StdinEof).unwrap();
        rest(&control_plane);
        t.join().unwrap();
        assert_eq!(attached(&w, "id-web-1"), Some(Origin::Here));
        drop(here);

        // A service terminal counts too; a pipe and a refusal don't.
        let (control_plane, t) = open(&w, pipe_header(&w, "bare", "exit 0", false), w.helper.clone());
        rest(&control_plane);
        t.join().unwrap();
        assert_eq!(attached(&w, "id-bare"), None, "a pipe: no attach");
        let cfg = w.root.join("cfg");
        let create = Obj::new().with("argv", vec!["exit 0".to_string()]);
        let h = header(pipe_base(cfg.to_str().unwrap()).with("service", "db").with("create", create));
        let _ = w.attaches.begin_in("id-web-1", Origin::Here);
        let (control_plane, t) = open(&w, h, w.helper.clone());
        rest(&control_plane);
        t.join().unwrap();
        assert_eq!(attached(&w, "id-web-1"), Some(Origin::Member("me@control_plane".into())), "a service terminal: its instance's");
        let (control_plane, t) = open(&w, header(base(cfg.to_str().unwrap()).with("instance", "own")), w.helper.clone());
        rest(&control_plane);
        t.join().unwrap();
        assert_eq!(attached(&w, "id-own"), None, "refused: no attach");
    }

    #[test]
    fn a_lost_bridge_ends_with_lost_and_a_hang_up_cancels() {
        let w = world("lost");
        let (control_plane, t) = open(&w, create_header(&w, "1700000000-0105"), w.helper.clone());
        let recs = rest(&control_plane);
        t.join().unwrap();
        assert_eq!(recs.len(), 2, "{recs:?}");
        assert!(matches!(&recs[1], Record::Error { code, .. } if code == code::LOST), "{recs:?}");

        // The control plane closes mid-attach: the call is cancelled (the session
        // detaches and runs on), nothing more is written.
        let (control_plane, t) = open(&w, create_header(&w, "1700000000-0106"), w.helper.clone());
        assert!(matches!(rpc::read_record(&mut &control_plane), Ok(Some(Record::Stdout(_)))));
        drop(control_plane);
        t.join().unwrap();
        assert!(logged("helper devsandbox-web-1: session.attach from fleet control plane me@control_plane: cancelled ("));
    }

    /// The tests' exec: `sh -c <argv[0]>` on this host; into a service,
    /// its container's name echoed first. A session client: `session new`
    /// runs its command's `argv[0]` (after a `new <id>` line), `session
    /// attach` says `attach <id>` and exits `DETACHED_EXIT`.
    fn sh(t: &Target) -> Vec<String> {
        let script = match t {
            Target::Instance { argv, .. } if argv[0] == crate::devsbd::BIN => match &argv[1..] {
                [_, new, _, id, _, command, ..] if new == "new" => format!("echo new {id}; {command}"),
                [_, attach, id] if attach == "attach" => format!("echo attach {id}; exit {DETACHED_EXIT}"),
                other => panic!("{other:?}"),
            },
            Target::Instance { argv, .. } => argv[0].clone(),
            Target::Service { container, argv } => format!("echo {container}; {}", argv[0]),
        };
        vec!["sh".into(), "-c".into(), script]
    }

    fn pipe_header(w: &World, instance: &str, script: &str, interactive: bool) -> Record {
        let cfg = w.root.join("cfg");
        let pipe = Obj::new().with("argv", vec![script.to_string()]).with("interactive", interactive);
        header(Obj::new().with("root", cfg.to_str().unwrap()).with("instance", instance).with("pipe", pipe))
    }

    /// The `stdout` and `stderr` bytes of `recs`, and their last record.
    fn split(recs: &[Record]) -> (String, String, Option<Record>) {
        let (mut out, mut err) = (Vec::new(), Vec::new());
        for rec in recs {
            match rec {
                Record::Stdout(b) => out.extend_from_slice(b),
                Record::Stderr(b) => err.extend_from_slice(b),
                _ => {}
            }
        }
        (String::from_utf8(out).unwrap(), String::from_utf8(err).unwrap(), recs.last().cloned())
    }

    #[test]
    fn a_pipe_splits_its_outputs_and_ends_with_its_exit() {
        let w = world("pipe-out");
        // `bare` has no helper: a pipe doesn't need one.
        let (control_plane, t) = open(&w, pipe_header(&w, "bare", "echo out; echo err >&2; cat; exit 5", false), w.helper.clone());
        // It may be over already: the write's outcome doesn't matter.
        let _ = rpc::write_record(&mut &control_plane, &Record::Stdin(b"ignored\n".to_vec()));
        let recs = rest(&control_plane);
        t.join().unwrap();
        assert_eq!(split(&recs), ("out\n".into(), "err\n".into(), Some(Record::Exit(Exit::Code(5)))), "not interactive: empty stdin");
        assert_eq!(recs.iter().filter(|r| matches!(r, Record::Exit(_))).count(), 1);

        let (control_plane, t) = open(&w, pipe_header(&w, "web-1", "kill -9 $$", false), w.helper.clone());
        let recs = rest(&control_plane);
        t.join().unwrap();
        assert_eq!(recs, [Record::Exit(Exit::Signal(9))]);
    }

    #[test]
    fn a_pipe_forwards_stdin_to_its_eof() {
        let w = world("pipe-in");
        let (control_plane, t) = open(&w, pipe_header(&w, "web-1", "cat; echo done", true), w.helper.clone());
        rpc::write_record(&mut &control_plane, &Record::Stdin(b"abc".to_vec())).unwrap();
        rpc::write_record(&mut &control_plane, &Record::Resize { cols: 80, rows: 24 }).unwrap();
        rpc::write_record(&mut &control_plane, &Record::Stdin(b"def\n".to_vec())).unwrap();
        rpc::write_record(&mut &control_plane, &Record::StdinEof).unwrap();
        let recs = rest(&control_plane);
        t.join().unwrap();
        assert_eq!(split(&recs), ("abcdef\ndone\n".into(), String::new(), Some(Record::Exit(Exit::Code(0)))));
    }

    #[test]
    fn a_hang_up_kills_the_pipe() {
        let w = world("pipe-hup");
        let (control_plane, t) = open(&w, pipe_header(&w, "web-1", "echo $$; exec sleep 30", true), w.helper.clone());
        let Ok(Some(Record::Stdout(pid))) = rpc::read_record(&mut &control_plane) else { panic!("no pid") };
        let pid = String::from_utf8(pid).unwrap();
        let pid: libc::pid_t = pid.trim().parse().unwrap_or_else(|_| panic!("{pid:?}"));
        let started = std::time::Instant::now();
        drop(control_plane);
        t.join().unwrap();
        assert!(started.elapsed() < Duration::from_secs(10), "killed, not waited out");
        // SAFETY: signal 0 only checks the pid; reaped, it's gone.
        assert_eq!(unsafe { libc::kill(pid, 0) }, -1, "killed and reaped");
    }

    #[test]
    fn refusals_are_one_error_record() {
        let w = world("refuse");
        let refusal = |header: Record, helper: HelperClient| {
            let (control_plane, t) = open(&w, header, helper);
            let recs = rest(&control_plane);
            t.join().unwrap();
            match recs.as_slice() {
                [Record::Error { code, .. }] => code.clone(),
                other => panic!("{other:?}"),
            }
        };
        let cfg = w.root.join("cfg");
        let cfg = cfg.to_str().unwrap();
        assert_eq!(refusal(Record::StdinEof, w.helper.clone()), code::BAD_REQUEST);
        assert_eq!(refusal(header(base(cfg).with("instance", "own")), w.helper.clone()), code::NOT_FOUND);
        let other = w.base.join("other");
        std::fs::create_dir_all(&other).unwrap();
        assert_eq!(refusal(header(base(other.to_str().unwrap()).with("instance", "own")), w.helper.clone()), code::DENIED);
        assert!(logged("fleet: refused a PTY stream from me@control_plane"));
        // An own root's instance is reached (its helper isn't running here).
        let mine = w.base.join("mine");
        std::fs::create_dir_all(&mine).unwrap();
        assert_eq!(refusal(header(base(mine.to_str().unwrap()).with("instance", "own")), w.helper.clone()), code::NOT_RUNNING);
        // Attach only, without a helper that attaches: nothing to resume.
        assert_eq!(refusal(header(base(cfg).with("instance", "bare")), w.helper.clone()), rpc::code::NO_SESSION);

        // Not running: no bridge.
        let none = HelperClient::new(Fake::default(), log);
        assert_eq!(refusal(header(base(cfg)), none), code::NOT_RUNNING);

        let svc = |service: &str| header(pipe_base(cfg).with("service", service).with("create", Obj::new()));
        assert_eq!(refusal(svc("cache"), w.helper.clone()), code::NOT_FOUND, "not one `web-1` uses");
        assert_eq!(refusal(svc("nope"), w.helper.clone()), code::NOT_FOUND);
        let own = header(base(cfg).with("instance", "own").with("session", Json::Null).with("service", "db").with("create", Obj::new()));
        assert_eq!(refusal(own, w.helper.clone()), code::NOT_FOUND, "the instance gates the service");
    }

    fn tty_header(w: &World, instance: &str, script: &str) -> Record {
        let cfg = w.root.join("cfg");
        let create = Obj::new().with("argv", vec![script.to_string()]);
        header(base(cfg.to_str().unwrap()).with("instance", instance).with("create", create))
    }

    #[test]
    fn a_helperless_instance_gets_a_tty_that_says_it_isnt_resumable() {
        let w = world("tty");
        let (control_plane, t) = open(&w, tty_header(&w, "bare", "read x; stty size; echo got $x; exit 3"), w.helper.clone());
        rpc::write_record(&mut &control_plane, &Record::Resize { cols: 100, rows: 30 }).unwrap();
        rpc::write_record(&mut &control_plane, &Record::Stdin(b"hi\n".to_vec())).unwrap();
        let recs = rest(&control_plane);
        t.join().unwrap();
        assert_eq!(recs[0], Record::Stderr(TTY_NOTE.as_bytes().to_vec()), "the note first: {recs:?}");
        let (out, err, last) = split(&recs);
        assert_eq!(err, TTY_NOTE, "only the note");
        assert!(out.contains("30 100"), "the resize reached the pty: {out:?}");
        assert!(out.contains("got hi"), "{out:?}");
        assert_eq!(last, Some(Record::Exit(Exit::Code(3))));

        let (control_plane, t) = open(&w, tty_header(&w, "bare", "kill -9 $$"), w.helper.clone());
        let recs = rest(&control_plane);
        t.join().unwrap();
        assert_eq!(recs.last(), Some(&Record::Exit(Exit::Signal(9))));
    }

    #[test]
    fn a_non_root_helper_runs_its_session_client() {
        let w = world("tty-root");
        let not_root = || {
            let fake = Fake::default();
            fake.add("devsandbox-web-1", caps::RPC, 1, not_root);
            HelperClient::new(fake, log)
        };
        let run = |header: Record| {
            let (control_plane, t) = open(&w, header, not_root());
            let recs = rest(&control_plane);
            t.join().unwrap();
            split(&recs)
        };
        let (out, err, last) = run(tty_header(&w, "web-1", "echo ok"));
        assert!(out.contains(&format!("new {SESSION}")) && out.contains("ok"), "{out:?}");
        assert_eq!((err.as_str(), last), ("", Some(Record::Exit(Exit::Code(0)))), "no note: it is a session");
        // The client's own codes end it as an attach would.
        let (_, _, last) = run(tty_header(&w, "web-1", &format!("exit {VERSION_EXIT}")));
        assert_eq!(last, Some(Record::error(rpc::code::VERSION, "")));
        // Attach only: the client's `session attach`, not a refusal.
        let (out, _, last) = run(header(base(w.root.join("cfg").to_str().unwrap())));
        assert!(out.contains(&format!("attach {SESSION}")), "{out:?}");
        assert_eq!(last, Some(Record::error(rpc::code::DETACHED, "")));
    }

    #[test]
    fn a_hang_up_kills_the_tty() {
        let w = world("tty-hup");
        // `read` ends only if the hang-up types a line or EOF into the pty,
        // which a session client would relay to its program. HUP ignored:
        // only the SIGKILL after portable-pty's grace ends it, time enough
        // for `touch`.
        let typed = w.base.join("typed");
        let script = format!("trap '' HUP; echo $$; read x; touch {}; exec sleep 30", typed.display());
        let (control_plane, t) = open(&w, tty_header(&w, "bare", &script), w.helper.clone());
        let mut out = String::new();
        let pid: libc::pid_t = loop {
            match rpc::read_record(&mut &control_plane) {
                Ok(Some(Record::Stdout(b))) => out.push_str(&String::from_utf8_lossy(&b)),
                Ok(Some(Record::Stderr(_))) => {}
                other => panic!("{other:?} after {out:?}"),
            }
            if let Some(line) = out.lines().next().filter(|_| out.contains('\n')) {
                break line.trim().parse().unwrap_or_else(|_| panic!("{out:?}"));
            }
        };
        let started = std::time::Instant::now();
        drop(control_plane);
        t.join().unwrap();
        assert!(started.elapsed() < Duration::from_secs(10), "killed, not waited out");
        // SAFETY: signal 0 only checks the pid; reaped, it's gone.
        assert_eq!(unsafe { libc::kill(pid, 0) }, -1, "killed and reaped");
        assert!(!typed.exists(), "nothing typed into the pty on the hang-up");
    }

    #[test]
    fn a_service_terminal_runs_in_the_container_the_worker_names() {
        let w = world("svc");
        let cfg = w.root.join("cfg");
        let create = Obj::new().with("argv", vec!["exit 4".to_string()]);
        let h = header(pipe_base(cfg.to_str().unwrap()).with("service", "db").with("create", create));
        let (control_plane, t) = open(&w, h, w.helper.clone());
        let recs = rest(&control_plane);
        t.join().unwrap();
        let (out, err, last) = split(&recs);
        let project = crate::commands::services::project_id(&cfg).unwrap();
        let container = crate::commands::services::isolated_service_container(&project, "id-web-1", "db");
        assert!(out.contains(&container), "{out:?}");
        assert_eq!(err, "", "no note: a service terminal was never a session");
        assert_eq!(last, Some(Record::Exit(Exit::Code(4))));
    }

    /// A [`Terminal::Client`] for real, as a worker runs it for a
    /// `containerUser` instance: the helper installed in an alpine container,
    /// the session client run as `nobody` (no root daemon involved) through
    /// `runtime_exec` under a host pty ([`run_tty`]). The caller hanging up
    /// kills the runtime's exec client; an attach-only one reaches the same
    /// program (its pid), a second attach takes over (`detached`, the
    /// client's own note as output), and the program's exit ends the last.
    #[test_utils::docker_test(helper)]
    fn a_session_client_outlives_its_callers_hang_up_with_docker() -> Result<(), &'static str> {
        let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
        let name = format!("devsandbox-pty-client-test-{stamp}");
        let up = crate::test_support::runtime_cmd()
            .args(["run", "-d", "--rm", "--name", &name, "alpine:3.20", "sleep", "300"])
            .output()
            .unwrap();
        assert!(up.status.success(), "{}", String::from_utf8_lossy(&up.stderr));
        let cleanup = || {
            let _ = crate::test_support::runtime_cmd().args(["rm", "-f", &name]).output();
        };
        crate::test_support::with_cleanup(cleanup, || {
            crate::devsbd::install(&name, None).unwrap();
            let base = scratch("client-docker");
            let text = format!(
                "[instance.c]\ninstance_id = \"id-c\"\nsandbox = \"c\"\ncontainer = {name:?}\nfolder = \"/w\"\n\
                 workspace = \"/\"\ncreated_unix = 1\nremote_user = \"nobody\"\ndevsbd_arch = \"x86_64\"\n"
            );
            std::fs::write(base.join("state.toml"), text).unwrap();
            let state = State::load_at(&base.join("state.toml")).unwrap();
            let inst = state.instances["c"].clone();
            const ID: &str = "1700000000-c11e";
            let open = |create: Option<&[String]>| {
                let argv = client_command(ID, create);
                let argv = runtime_exec(&Target::Instance { instance: &inst, interactive: true, tty: true, argv: &argv, host_agent: false });
                let tty = spawn_tty(argv).unwrap();
                let (control_plane, ours) = UnixStream::pair().unwrap();
                let t = std::thread::spawn(move || run_tty(&ours, tty, None, client_exit_record));
                control_plane.set_read_timeout(Some(Duration::from_secs(30))).unwrap();
                (control_plane, t)
            };
            // The pty's output until it holds `needle`.
            let until = |mut s: &UnixStream, needle: &str| {
                let mut out = String::new();
                while !out.contains(needle) {
                    match rpc::read_record(&mut s) {
                        Ok(Some(Record::Stdout(b))) => out.push_str(&String::from_utf8_lossy(&b)),
                        other => panic!("{other:?} before {needle:?}, after {out:?}"),
                    }
                }
                out
            };
            let say = |s: &UnixStream, text: &str| rpc::write_record(&mut &*s, &Record::Stdin(text.as_bytes().to_vec())).unwrap();

            // Answers each line with its pid, so later attaches can tell they
            // reached the same program.
            let program = vec!["sh".to_string(), "-c".into(), "while read l; do echo \"got $l $$.\"; done".into()];
            let (first, t) = open(Some(&program));
            say(&first, "zero\n");
            // The hang-up must type nothing into the pty: an EOF would
            // reach the program through the raw client and end it.
            let out = until(&first, ".\r\n");
            let pid = out.split("got zero ").nth(1).and_then(|r| r.split('.').next()).unwrap_or_else(|| panic!("{out:?}")).to_string();
            let started = std::time::Instant::now();
            drop(first);
            t.join().unwrap();
            assert!(started.elapsed() < Duration::from_secs(10), "the runtime's exec client killed, not waited out");

            let (a, ta) = open(None);
            say(&a, "one\n");
            until(&a, &format!("got one {pid}."));
            let (b, tb) = open(None);
            let rest_a = rest(&a);
            ta.join().unwrap();
            let (out, _, last) = split(&rest_a);
            assert_eq!(last, Some(Record::error(rpc::code::DETACHED, "")), "{rest_a:?}");
            assert!(out.contains("attached elsewhere"), "the client's own note, as output: {out:?}");

            say(&b, "two\n");
            until(&b, &format!("got two {pid}."));
            // Ctrl-D: `read` sees its end, the program exits 0.
            say(&b, "\x04");
            let rest_b = rest(&b);
            tb.join().unwrap();
            assert_eq!(rest_b.last(), Some(&Record::Exit(Exit::Code(0))), "{rest_b:?}");
            let _ = std::fs::remove_dir_all(&base);
        });
        Ok(())
    }
}