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
1640
1641
1642
1643
//! Integrated terminal panel: opening/targeting sessions, focus, and
//! key/mouse routing into the active PTY.

use std::path::PathBuf;
use std::sync::{Arc, Weak};
use std::time::Instant;

use crossterm::event::{KeyCode, KeyEvent, KeyModifiers, MouseButton, MouseEvent, MouseEventKind};
use ratatui::layout::Rect;
use ratatui::widgets::Block;

use crate::runtime::NAME_PREFIX;
use crate::tui::data::{ContainerStatus, InstanceRow, Node};
use crate::tui::kitty;
use crate::tui::remote::{self, instance_key, qualify, service_key};
use crate::commands::exec::SHELL_FALLBACK_CMD;
use crate::tui::select;
use crate::serve::machines::cli::{Next, Reconnect};
use crate::tui::term::{encode_key, encode_mouse, encode_wheel, TermSession};

use super::view::{point_in, session_lines, ConfirmModal, Confirmed, Fetch, Modal};
use super::{App, Focus, Tab};

/// Lines one wheel notch scrolls, as scrollback or as arrow keys.
const WHEEL_LINES: i16 = 3;

/// The `devsandbox exec` an instance's terminal tab and `:exec` run: this
/// executable, against the dashboard's config root. The CLI's `exec` owns
/// the runtime argv, the in-flight guard and the ssh-agent relay
/// (`bridges.ensure`, held for the command's life), so the dashboard reads
/// no state for it, and a remote instance only needs its qualified name
/// (`tui/remote.rs`).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ExecCli {
    /// `None` in production: the devsandbox binary, re-resolved per spawn
    /// ([`crate::exe::devsandbox`]) so tabs opened after an upgrade run the
    /// new one. Tests pin a path.
    pub exe: Option<PathBuf>,
    /// Absolute: a PTY child starts in `$HOME`, not the dashboard's cwd.
    pub root: PathBuf,
}

impl ExecCli {
    /// `devsandbox -C <root> exec -i -t -- <instance> [command…]`. Always
    /// `-i -t`: both callers host it on a terminal, and with a command the
    /// CLI takes the flags as given (without one it would pick the same).
    /// `--` so an instance name can't read as a flag.
    pub fn argv(&self, instance: &str, command: &[String]) -> Result<Vec<String>, String> {
        let mut argv = vec![
            self.exe()?,
            "-C".into(),
            self.root.to_string_lossy().into_owned(),
            "exec".into(),
            "-i".into(),
            "-t".into(),
            "--".into(),
            instance.into(),
        ];
        argv.extend(command.iter().cloned());
        Ok(argv)
    }

    /// `devsandbox -C <root> exec --attach=<id> -- <instance>`: an attach tab
    /// (`a`) on helper session `id`. No `-i -t`, which `--attach` doesn't
    /// take (the session already has its pty); the `=` form, as
    /// `--attach`'s value is optional and the name comes after `--`.
    pub fn attach_argv(&self, instance: &str, id: &str) -> Result<Vec<String>, String> {
        Ok(vec![
            self.exe()?,
            "-C".into(),
            self.root.to_string_lossy().into_owned(),
            "exec".into(),
            format!("--attach={id}"),
            "--".into(),
            instance.into(),
        ])
    }

    /// The devsandbox executable these argvs start with (also a machine's
    /// tabs', `remote::exec_argv`).
    pub fn exe(&self) -> Result<String, String> {
        let exe = match &self.exe {
            Some(exe) => exe.clone(),
            None => crate::exe::devsandbox().map_err(|e| format!("can't find the devsandbox executable: {e}"))?,
        };
        Ok(exe.to_string_lossy().into_owned())
    }
}

/// A remote instance tab's reconnect (docs/architecture/dashboard/terminal.md,
/// *Remote tabs reconnect*): the tab's first dial runs its shell in helper
/// session `id` (`remote::session_exec_argv`); each time its dial exits,
/// [`Reconnect`] (the CLI's rule) says whether to re-dial `attach`
/// (`remote::attach_argv`) into the same tab after a backoff, or end. Pure
/// over the exit codes and the `Instant`s it's given.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Redial {
    attach: Vec<String>,
    state: Reconnect,
    /// When the current dial started (its run time decides a 255).
    dialed: Instant,
    phase: Phase,
}

#[derive(Clone, Debug, PartialEq, Eq)]
enum Phase {
    /// A dial is running (or just ended, its code not read yet).
    Live,
    /// Lost: re-dial at `until`.
    Waiting { until: Instant, attempt: u32 },
    /// No more dials: the tab is `(exited)`.
    Ended,
}

impl Redial {
    /// A tab whose first dial started at `now`, re-dialing with `attach`.
    pub fn new(attach: Vec<String>, now: Instant) -> Self {
        Self { attach, state: Reconnect::default(), dialed: now, phase: Phase::Live }
    }

    /// Whether the current dial's exit code is wanted ([`Self::step`]).
    pub fn live(&self) -> bool {
        self.phase == Phase::Live
    }

    pub fn ended(&self) -> bool {
        self.phase == Phase::Ended
    }

    /// One look at the tab at `now`, `exit` the current dial's code once it
    /// ended: the argv to re-dial now, if it's time (then [`Self::dialed`]
    /// or [`Self::end`]).
    pub fn step(&mut self, exit: Option<i32>, now: Instant) -> Option<&[String]> {
        match self.phase {
            Phase::Live => {
                let code = exit?;
                self.phase = match self.state.after(code, now.saturating_duration_since(self.dialed)) {
                    Next::Retry { wait, attempt } => Phase::Waiting { until: now + wait, attempt },
                    Next::Done { .. } => Phase::Ended,
                };
                None
            }
            Phase::Waiting { until, .. } if now >= until => Some(&self.attach),
            Phase::Waiting { .. } | Phase::Ended => None,
        }
    }

    /// The re-dial [`Self::step`] asked for started at `now`.
    pub fn dialed(&mut self, now: Instant) {
        self.dialed = now;
        self.phase = Phase::Live;
    }

    /// No more dials (a re-dial that couldn't spawn).
    pub fn end(&mut self) {
        self.phase = Phase::Ended;
    }

    /// The re-dial a waiting tab is on (from 1), for its label.
    pub fn attempt(&self) -> Option<u32> {
        match self.phase {
            Phase::Waiting { attempt, .. } => Some(attempt),
            _ => None,
        }
    }
}

impl App {
    /// Step every remote instance tab's [`Redial`] at `now` (the event loop,
    /// each pass): read an ended dial's exit code, and respawn the attach
    /// into the tab when its wait is over. A respawn that fails ends the tab,
    /// the reason written into its screen. Like [`Self::open_terminal`]'s
    /// spawn, the PTY work is `TermSession`'s.
    pub fn redial_terminals(&mut self, now: Instant) {
        for session in self.terms.sessions_mut() {
            let Some(mut redial) = session.redial.take() else { continue };
            let exit = if redial.live() { session.exit_code() } else { None };
            if let Some(argv) = redial.step(exit, now).map(<[String]>::to_vec) {
                match session.respawn(argv) {
                    Ok(()) => redial.dialed(now),
                    Err(e) => {
                        redial.end();
                        session.note(&format!("terminal: {e:#}"));
                    }
                }
            }
            session.redial = Some(redial);
        }
    }

    /// The OSC 52 copy (tab title, base64) the event loop should relay from
    /// the integrated terminals to the outer clipboard: the last of this
    /// frame's (it would overwrite the others there anyway), and only with
    /// the `terminal_clipboard` setting on. Every session's queue is drained
    /// either way, so a copy made while it's off isn't sent later on.
    pub fn take_terminal_clipboard(&mut self) -> Option<(String, Vec<u8>)> {
        let last = self.terms.take_clipboards().pop();
        last.filter(|_| self.settings.terminal_clipboard)
    }

    /// Route a key to the active terminal. Only reached with `focus ==
    /// Terminal`. `ctrl-]` / `F12` leave; on an exited session every other key
    /// is swallowed; otherwise the key is encoded (honoring the shell's
    /// application-cursor mode and kitty keyboard flags) and written to the PTY.
    pub(super) fn on_key_terminal(&mut self, key: KeyEvent) {
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
        if matches!(key.code, KeyCode::Char(']') if ctrl) || key.code == KeyCode::F(12) {
            self.focus = Focus::Dashboard;
            return;
        }
        // The session can vanish (closed elsewhere); fall back to the dashboard
        // rather than forward into nothing.
        let Some(session) = self.terms.active_session_mut() else {
            self.focus = Focus::Dashboard;
            return;
        };
        // An exited shell has nothing to receive keys; swallow them (leave keys
        // above still work). `x` closes it in place, mirroring the dashboard
        // binding; fall back to the dashboard once no sessions remain.
        if session.exited() {
            if key.code == KeyCode::Char('x') && key.modifiers.is_empty() {
                self.terms.close_active();
                if self.terms.is_empty() {
                    self.focus = Focus::Dashboard;
                }
            }
            return;
        }
        // DECCKM: the parser tracks whether the shell wants SS3 cursor keys;
        // its callbacks track the kitty flags of the screen the app is on.
        let (application_cursor, kitty_flags) = session
            .parser()
            .lock()
            .map(|p| {
                let screen = p.screen();
                (screen.application_cursor(), p.callbacks().flags(screen.alternate_screen()))
            })
            .unwrap_or((false, 0));
        let bytes =
            kitty::encode_key(key, kitty_flags).or_else(|| encode_key(key, application_cursor));
        if let Some(bytes) = bytes {
            session.write_key_bytes(&bytes);
        }
    }

    /// Focus the active terminal, or leave a status hint when none are open.
    pub(super) fn enter_terminal(&mut self) {
        if self.terms.is_empty() {
            self.status = Some("no terminal open — press t".into());
        } else {
            self.focus = Focus::Terminal;
        }
    }

    /// Mouse routing for the integrated-terminal panel, active only when no
    /// modal is open (it hides the panel) and at least one terminal exists.
    /// Left-click inside the panel focuses the terminal; a click on the title
    /// row's tab labels activates that tab; a left-click outside the panel
    /// while the terminal is focused returns focus to the dashboard. The wheel
    /// goes to the active session (see [`Self::wheel_active_terminal`]), and
    /// so do the buttons while its child tracks the mouse
    /// ([`Self::forward_terminal_mouse`]), and hover when it asked for any
    /// motion ([`Self::hover_terminal`]). All layout math is borrowed from
    /// `ui` so it tracks exactly what the draw path lays out. I/O-free.
    pub(super) fn terminal_mouse(&mut self, ev: &MouseEvent, area: Rect) {
        if self.terms.is_empty() || !matches!(self.modal, Modal::None) {
            return;
        }
        let prompt_open = self.prompt.is_some();
        let panel = crate::tui::ui::terminal_panel_rect(area, prompt_open);
        let inside = point_in(panel, ev.column, ev.row);
        if let MouseEventKind::Down(_) = ev.kind {
            // The press (or the drag after it) moves the child's idea of the
            // pointer: the next hover is news even on the old cell.
            self.term_hover = None;
        }
        self.forward_terminal_mouse(ev, panel);
        match ev.kind {
            MouseEventKind::Down(MouseButton::Left) => {
                if inside {
                    let focused = self.focus == Focus::Terminal;
                    // Title row: hit-test the tab labels; a hit activates that tab.
                    if let Some(i) =
                        crate::tui::ui::terminal_tab_hit(self, panel, focused, ev.column, ev.row)
                    {
                        self.terms.set_active(i);
                    }
                    self.focus = Focus::Terminal;
                } else if self.focus == Focus::Terminal {
                    // Click-away unfocuses; dashboard click handling is out of scope.
                    self.focus = Focus::Dashboard;
                }
            }
            MouseEventKind::ScrollUp if inside => self.wheel_active_terminal(true, ev, panel),
            MouseEventKind::ScrollDown if inside => self.wheel_active_terminal(false, ev, panel),
            MouseEventKind::Moved => self.hover_terminal(ev, panel),
            _ => {}
        }
    }

    /// Button-less motion over the active session's body, reported to a
    /// live child in `AnyMotion` (`?1003`: hover highlights, tooltips) at the
    /// pane-relative cell, once per cell ([`App::term_hover`]). Off the body
    /// (border, title row, elsewhere) nothing is sent, not even clamped as a
    /// drag is: the protocol has no leave event, and a fake edge position
    /// would be a lie. Leaving clears the dedupe so coming back reports. Any
    /// other mode, or an exited session, gets nothing: [`encode_mouse`]
    /// drops `Moved` outside `AnyMotion`. Never touches the local selection
    /// (`selection_mouse` ignores `Moved`).
    fn hover_terminal(&mut self, ev: &MouseEvent, panel: Rect) {
        let body = Block::bordered().inner(panel);
        if !point_in(body, ev.column, ev.row) {
            self.term_hover = None;
            return;
        }
        let Some(session) = self.terms.active_session_mut() else {
            return;
        };
        if session.exited() {
            return;
        }
        let cell = body_cell(body, ev);
        let same_session = |w: &Weak<_>| w.upgrade().is_some_and(|p| Arc::ptr_eq(&p, session.parser()));
        if matches!(&self.term_hover, Some((w, c)) if *c == cell && same_session(w)) {
            return;
        }
        let Some((mode, encoding)) = session.parser().lock().ok().map(|p| {
            let screen = p.screen();
            (screen.mouse_protocol_mode(), screen.mouse_protocol_encoding())
        }) else {
            return;
        };
        let Some(bytes) = encode_mouse(ev.kind, ev.modifiers, cell.0, cell.1, mode, encoding) else {
            return;
        };
        session.write_key_bytes(&bytes);
        self.term_hover = Some((Arc::downgrade(session.parser()), cell));
    }

    /// Buttons for a child that enabled mouse tracking (zidane, vim
    /// `mouse=a`, tmux), so it can do its own selection: a press on the body
    /// is reported at its pane-relative cell, and from then on that button's
    /// drags and release, clamped to the body when the pointer left it, so a
    /// child that saw the press always sees the release. The report is in the
    /// child's mode and encoding ([`encode_mouse`] drops what the mode doesn't
    /// ask for); [`Self::selection_press`] forms no selection under a
    /// forwarded press. A child not tracking, or an exited session, gets
    /// nothing: the body is a local selection region then (`ui`).
    fn forward_terminal_mouse(&mut self, ev: &MouseEvent, panel: Rect) {
        let body = Block::bordered().inner(panel);
        let button = match ev.kind {
            MouseEventKind::Down(b) if point_in(body, ev.column, ev.row) => b,
            MouseEventKind::Down(_) => {
                self.term_mouse_down = None;
                return;
            }
            MouseEventKind::Drag(b) | MouseEventKind::Up(b) if self.term_mouse_down == Some(b) => b,
            _ => return,
        };
        if let MouseEventKind::Up(_) = ev.kind {
            self.term_mouse_down = None;
        }
        let Some(session) = self.terms.active_session_mut() else {
            return;
        };
        let modes = session.parser().lock().ok().map(|p| {
            let screen = p.screen();
            (screen.mouse_protocol_mode(), screen.mouse_protocol_encoding())
        });
        let Some((mode, encoding)) = modes.filter(|(m, _)| *m != vt100::MouseProtocolMode::None && !session.exited())
        else {
            return;
        };
        if let MouseEventKind::Down(_) = ev.kind {
            self.term_mouse_down = Some(button);
        }
        let (col, row) = body_cell(body, ev);
        if let Some(bytes) = encode_mouse(ev.kind, ev.modifiers, col, row, mode, encoding) {
            session.write_key_bytes(&bytes);
        }
    }

    /// Autoscroll of a terminal selection: scroll the active session's
    /// scrollback by `delta` lines (positive: older) and return the
    /// [`Source::Terminal`](crate::tui::select::Source) row now at the top.
    pub(super) fn scroll_terminal_selection(&mut self, delta: i16) -> Option<usize> {
        self.scroll_active_terminal(delta);
        let mut parser = self.terms.active_session()?.parser().lock().ok()?;
        Some(select::terminal_top(parser.screen_mut()))
    }

    /// One wheel notch over the active terminal, routed like xterm does:
    /// - the child enabled mouse tracking (zidane, vim with `mouse=a`, htop):
    ///   forward it as a wheel report at the pane-relative cell, so the app
    ///   scrolls its own view;
    /// - the child is on the alternate screen without mouse tracking (less,
    ///   man): send arrow keys ("alternate scroll"), since that screen has no
    ///   scrollback of its own;
    /// - otherwise (a shell's main screen, or an exited session): scroll the
    ///   vt100 scrollback.
    fn wheel_active_terminal(&mut self, up: bool, ev: &MouseEvent, panel: Rect) {
        let Some(session) = self.terms.active_session_mut() else {
            return;
        };
        let bytes = {
            let Ok(parser) = session.parser().lock() else {
                return;
            };
            let screen = parser.screen();
            let mode = screen.mouse_protocol_mode();
            if session.exited()
                || (mode == vt100::MouseProtocolMode::None && !screen.alternate_screen())
            {
                None
            } else if mode != vt100::MouseProtocolMode::None {
                // A notch over the border still lands on an edge cell.
                let (col, row) = body_cell(Block::bordered().inner(panel), ev);
                // An unencodable position drops the notch, as xterm does.
                Some(
                    encode_wheel(up, ev.modifiers, col, row, screen.mouse_protocol_encoding())
                        .unwrap_or_default(),
                )
            } else {
                let key = KeyEvent::new(
                    if up { KeyCode::Up } else { KeyCode::Down },
                    KeyModifiers::NONE,
                );
                encode_key(key, screen.application_cursor())
                    .map(|b| b.repeat(WHEEL_LINES as usize))
            }
        };
        match bytes {
            Some(bytes) if !bytes.is_empty() => session.write_key_bytes(&bytes),
            Some(_) => {}
            None => self.scroll_active_terminal(if up { WHEEL_LINES } else { -WHEEL_LINES }),
        }
    }

    /// Scroll the active session's vt100 scrollback by `delta` lines: positive
    /// scrolls up (older output, larger offset), negative scrolls down toward the
    /// live screen (offset 0). vt100 clamps the offset to the actual scrollback,
    /// so overshoot is harmless. New output while scrolled back keeps the offset
    /// (vt100's behavior); it snaps back when the user scrolls down to 0.
    fn scroll_active_terminal(&mut self, delta: i16) {
        let Some(session) = self.terms.active_session() else {
            return;
        };
        let Ok(mut parser) = session.parser().lock() else {
            return;
        };
        let current = parser.screen().scrollback() as i32;
        let next = (current + delta as i32).max(0) as usize;
        parser.screen_mut().set_scrollback(next);
    }

    /// Resolve the current selection to a terminal target: `(title, container,
    /// is_instance)`, or an `Err(status message)` explaining why one can't open.
    /// Pure over the snapshot so it is unit-testable; [`Self::open_terminal`]
    /// does the PTY spawn around it.
    ///
    /// Instances tab: the instance under the cursor (or a process row's parent),
    /// which must be running. Services tab: the selected service's first running
    /// container.
    fn term_target(&self) -> Result<(String, String, bool), String> {
        let snapshot = self
            .snapshot
            .as_ref()
            .ok_or_else(|| "terminal: no data yet".to_string())?;
        match self.tab {
            Tab::Instances => {
                let idx = self
                    .selected_instance_index()
                    .ok_or_else(|| "terminal: select an instance".to_string())?;
                let row = snapshot
                    .instances
                    .get(idx)
                    .ok_or_else(|| "terminal: select an instance".to_string())?;
                instance_term_target(row, "terminal")
            }
            Tab::Services => {
                let row = snapshot
                    .services
                    .get(self.selected())
                    .ok_or_else(|| "terminal: select a service".to_string())?;
                let container = row
                    .containers
                    .iter()
                    .find(|(_, status)| matches!(status, ContainerStatus::Running(_)))
                    .map(|(name, _)| name.clone())
                    .ok_or_else(|| {
                        format!("terminal: no running container for `{}`", service_key(row))
                    })?;
                let title = container
                    .strip_prefix(NAME_PREFIX)
                    .unwrap_or(&container)
                    .to_string();
                // Keyed like instances: `box/…` on a machine (titles and the
                // tab dedup).
                let machine = row.machine.as_deref();
                Ok((qualify(machine, &title), qualify(machine, &container), false))
            }
            // The Ports tab has no terminal target: forwards aren't containers.
            Tab::Ports => Err("terminal: not available on the Ports tab".to_string()),
            Tab::Inbox => Err("terminal: not available on the Inbox tab".to_string()),
            Tab::Machines => Err("terminal: not available on the Machines tab".to_string()),
        }
    }

    /// Open (or focus) an integrated terminal for the current selection. `t`
    /// dedups against a live terminal for the same container; `T`
    /// (`force_new`) always spawns a fresh one.
    ///
    /// This does I/O inline — a PTY spawn — same precedent as
    /// [`Self::open_logs`] / [`Self::open_config`] doing user-triggered work
    /// without going through the event loop. Failures land in `self.status`.
    pub(super) fn open_terminal(&mut self, force_new: bool) {
        let target = self.term_target();
        self.open_terminal_to(target, force_new);
    }

    /// Open (or focus) a terminal on instance `name` (a key,
    /// `remote::instance_key`), whatever is selected: the Inbox thread pane
    /// targets a thread's child, not a table row.
    pub(super) fn open_instance_terminal(&mut self, name: &str) {
        let target = match self.snapshot.as_ref().map(|s| remote::find_instance(s, name)) {
            None => Err("terminal: no data yet".to_string()),
            Some(None) => Err(format!("terminal: `{name}` not in the snapshot")),
            Some(Some(row)) => instance_term_target(row, "terminal"),
        };
        self.open_terminal_to(target, false);
    }

    /// `a` (Instances tab, an instance row): attach a tab to one of the
    /// instance's running helper sessions. A row that isn't running or
    /// whose machine is unreachable says so; else the event loop asks the
    /// daemon for its sessions ([`Fetch::Sessions`]), answered through
    /// [`Self::sessions_listed`]. A no-op off an instance row.
    pub(super) fn attach_session(&mut self) {
        let Some(Node::Instance(i)) = self.selected_node() else { return };
        let Some(row) = self.snapshot.as_ref().and_then(|s| s.instances.get(i)) else { return };
        let key = instance_key(row);
        if let Err(msg) = instance_term_target(row, "attach") {
            self.status = Some(msg);
        } else if remote::unreachable(&self.machines, row.machine.as_deref()) {
            self.status = Some(format!("attach: `{key}`'s machine is unreachable"));
        } else {
            self.status = Some(format!("attach: listing `{key}`'s sessions…"));
            self.pending_fetch.push(Fetch::Sessions { instance: key });
        }
    }

    /// [`Fetch::Sessions`]' answer for `instance` (a key): its `session ls`
    /// lines, or the line to show. `exec --attach`'s rule
    /// (`commands::exec::attach_candidates`: the one detached, else the
    /// running ones, detached first): none is a status line, one opens its
    /// tab, several a picker ([`Confirmed::Attach`]).
    pub fn sessions_listed(&mut self, instance: &str, lines: Result<Vec<String>, String>) {
        let listing = match lines {
            Ok(lines) => lines.join("\n"),
            Err(msg) => {
                self.status = Some(msg);
                return;
            }
        };
        let found: Vec<(String, String)> = crate::commands::exec::attach_candidates(&listing)
            .into_iter()
            .map(|(s, line)| (s.id, line.to_string()))
            .collect();
        match found.as_slice() {
            [] => self.status = Some(format!("attach: no running session in `{instance}`")),
            [(id, _)] => {
                let id = id.clone();
                self.open_attach(instance, &id);
            }
            // Another modal opened while the list was on its way: don't
            // replace it.
            _ if !matches!(self.modal, Modal::None) => {
                self.status = Some(format!("attach: `{instance}` has {} running sessions (a again to pick)", found.len()));
            }
            _ => {
                self.status = None;
                let body = session_lines(&found, 0);
                let question = format!("{instance}: attach to a session");
                let action = Confirmed::Attach { instance: instance.to_string(), sessions: found, cursor: 0 };
                self.modal = Modal::Confirm(ConfirmModal::new(question, body, action));
            }
        }
    }

    /// Open a new tab attached to helper session `id` of instance `key`
    /// (never deduped: a `t` tab on the same container is another session).
    /// The row is looked up again, as it may have stopped since `a`.
    pub(super) fn open_attach(&mut self, key: &str, id: &str) {
        let target = match self.snapshot.as_ref().map(|s| remote::find_instance(s, key)) {
            None => Err("attach: no data yet".to_string()),
            Some(None) => Err(format!("attach: `{key}` not in the snapshot")),
            Some(Some(row)) => instance_term_target(row, "attach"),
        };
        match target {
            Ok((title, container, _)) => {
                let argvs = self.attach_argvs(&title, id);
                self.spawn_tab(title, container, argvs);
            }
            Err(msg) => self.status = Some(msg),
        }
    }

    /// What an attach tab runs: this host's [`ExecCli::attach_argv`], no
    /// re-dial; on a machine `remote::attach_argv`, both its first dial and
    /// its [`Redial`] (a reconnect never starts a second process).
    fn attach_argvs(&self, key: &str, id: &str) -> Result<(Vec<String>, Option<Vec<String>>), String> {
        let attach = |e: String| format!("attach: {e}");
        if let (Some(machine), name) = remote::split(key) {
            let m = self.machine_entry(machine).map_err(attach)?;
            let argv = remote::attach_argv(m, name, id, &|| self.local_exe()).map_err(attach)?;
            return Ok((argv.clone(), Some(argv)));
        }
        self.exec_cli.as_ref().map_err(|e| attach(e.clone()))?.attach_argv(key, id).map(|argv| (argv, None)).map_err(attach)
    }

    /// The shared tail of [`Self::open_terminal`] and
    /// [`Self::open_instance_terminal`]: dedup, argv, spawn, focus.
    fn open_terminal_to(&mut self, target: Result<(String, String, bool), String>, force_new: bool) {
        let (title, container, is_instance) = match target {
            Ok(t) => t,
            Err(msg) => {
                self.status = Some(msg);
                return;
            }
        };

        // Dedup: an already-open live terminal for this container just gets focus.
        if !force_new {
            if let Some(idx) = self.terms.find(&container) {
                self.terms.set_active(idx);
                self.focus = Focus::Terminal;
                self.status = None;
                return;
            }
        }

        let id = crate::commands::exec::mint_session_id(crate::state::Instance::now());
        let argvs = self.term_argv(&title, &container, is_instance, &id);
        self.spawn_tab(title, container, argvs);
    }

    /// Spawn a tab running `argvs` (its first dial, and the re-dial of a
    /// [`Redial`] tab), focused; or the status says why not.
    fn spawn_tab(&mut self, title: String, container: String, argvs: Result<(Vec<String>, Option<Vec<String>>), String>) {
        let (argv, attach) = match argvs {
            Ok(argvs) => argvs,
            Err(msg) => {
                self.status = Some(msg);
                return;
            }
        };

        // Size doesn't matter yet: the event loop's pre-draw resize corrects the
        // first frame. Reuse the active session's size when there is one, else a
        // sane 24x80 default.
        let (rows, cols) = self
            .terms
            .active_session()
            .map(|s| s.size())
            .unwrap_or((24, 80));
        match TermSession::spawn(title, container, argv, rows, cols, self.kitty) {
            Ok(mut session) => {
                session.redial = attach.map(|attach| Redial::new(attach, Instant::now()));
                self.terms.open(session);
                self.focus = Focus::Terminal;
                self.status = None;
            }
            Err(e) => self.status = Some(format!("terminal: {e:#}")),
        }
    }

    /// What a terminal tab runs. An instance: `devsandbox exec` (the CLI's
    /// login shell, [`SHELL_FALLBACK_CMD`]); its errors (no container yet,
    /// not in state) print in the tab, which stays open as `(exited)`. A
    /// service: a plain interactive runtime `exec` of the same shell, the
    /// binary named by the snapshot (`runtime_name` is the backend's `bin`
    /// for docker, podman and Apple's `container` alike).
    ///
    /// On a machine (a `box/…` key) either is this host's `devsandbox exec`
    /// on the qualified name, over the machine's link (a service through an
    /// instance using it, `remote::service_argv`;
    /// docs/architecture/daemon/machines.md, *Dashboard*). A remote
    /// instance's shell runs in helper session `id`, and the second value is
    /// the attach its tab re-dials after a lost connection ([`Redial`]);
    /// `None` for every other tab.
    fn term_argv(
        &self,
        title: &str,
        container: &str,
        is_instance: bool,
        id: &str,
    ) -> Result<(Vec<String>, Option<Vec<String>>), String> {
        let terminal = |e: String| format!("terminal: {e}");
        if is_instance {
            if let (Some(machine), name) = remote::split(title) {
                let m = self.machine_entry(machine).map_err(terminal)?;
                let exe = || self.local_exe();
                let first = remote::session_exec_argv(m, name, id, &exe).map_err(terminal)?;
                let attach = remote::attach_argv(m, name, id, &exe).map_err(terminal)?;
                return Ok((first, Some(attach)));
            }
            return self.exec_argv(title, &[]).map(|argv| (argv, None)).map_err(terminal);
        }
        let snapshot = self.snapshot.as_ref().ok_or_else(|| "terminal: no data yet".to_string())?;
        if let (Some(machine), container) = remote::split(container) {
            let row = snapshot
                .services
                .iter()
                .find(|r| r.machine.as_deref() == Some(machine) && r.containers.iter().any(|(c, _)| c == container))
                .ok_or_else(|| terminal(format!("`{machine}/{container}` not in the snapshot")))?;
            let exe = || self.local_exe();
            return remote::service_argv(self.machine_entry(machine)?, row, container, &exe).map(|argv| (argv, None)).map_err(terminal);
        }
        let mut argv = vec![snapshot.runtime_name.clone(), "exec".into(), "-i".into(), "-t".into(), container.into()];
        argv.extend(SHELL_FALLBACK_CMD.iter().map(|s| s.to_string()));
        Ok((argv, None))
    }

    /// The `devsandbox exec` of instance `key` (a terminal tab, `:exec`):
    /// this host's [`ExecCli`], or for a machine's instance this host's
    /// `devsandbox exec` on its qualified name (`remote::exec_argv`).
    pub fn exec_argv(&self, key: &str, command: &[String]) -> Result<Vec<String>, String> {
        let (machine, name) = remote::split(key);
        let Some(machine) = machine else {
            return self.exec_cli.as_ref().map_err(String::clone)?.argv(name, command);
        };
        remote::exec_argv(self.machine_entry(machine)?, name, command, &|| self.local_exe())
    }

    /// This host's devsandbox, which a machine's tabs run.
    fn local_exe(&self) -> Result<String, String> {
        self.exec_cli.as_ref().map_err(String::clone)?.exe()
    }

    /// Machine `name`'s snapshot entry (a tab's argv names it).
    fn machine_entry(&self, name: &str) -> Result<&crate::serve::snapshots::SnapshotMachine, String> {
        remote::machine(&self.machines, name).ok_or_else(|| format!("no machine named `{name}`"))
    }
}

/// The 0-based cell of the terminal `body` under `ev`, clamped onto the body
/// when the pointer is off it (the border, or past the panel mid-drag).
fn body_cell(body: Rect, ev: &MouseEvent) -> (u16, u16) {
    let col = ev.column.saturating_sub(body.x).min(body.width.saturating_sub(1));
    let row = ev.row.saturating_sub(body.y).min(body.height.saturating_sub(1));
    (col, row)
}

/// Terminal target for an instance row, which must be running: its key
/// (the title, `box/web-2` on a machine) and its container's. `what`
/// prefixes the refusal (`terminal`, `attach`).
fn instance_term_target(row: &InstanceRow, what: &str) -> Result<(String, String, bool), String> {
    let key = instance_key(row);
    if !matches!(row.status, ContainerStatus::Running(_)) {
        return Err(format!("{what}: `{key}` is not running"));
    }
    Ok((key, qualify(row.machine.as_deref(), &row.container), true))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tui::app::test_support::*;
    use crate::tui::app::*;

    #[test]
    fn terminal_clipboard_relay_follows_the_setting_and_always_drains() {
        let mut app = new_app();
        app.terms.open(term_sess("web-1", "devsandbox-web-1"));
        let copy = |app: &App, b64: &str| {
            app.terms.active_session().unwrap().feed_output(format!("\x1b]52;c;{b64}\x07").as_bytes())
        };
        copy(&app, "aGk=");
        assert_eq!(app.take_terminal_clipboard(), Some(("web-1".to_string(), b"aGk=".to_vec())), "on by default");
        app.settings.terminal_clipboard = false;
        copy(&app, "b2Zm");
        assert_eq!(app.take_terminal_clipboard(), None);
        // Drained while off: turning it on doesn't send the old copy.
        app.settings.terminal_clipboard = true;
        assert_eq!(app.take_terminal_clipboard(), None);
    }

    #[test]
    fn mouse_click_in_panel_focuses_terminal() {
        let mut app = new_app();
        app.terms.open(term_sess("web-1", "devsandbox-web-1"));
        assert_eq!(app.focus, Focus::Dashboard);
        let panel = crate::tui::ui::terminal_panel_rect(FRAME, false);
        // A click in the panel body (below the title row) focuses the terminal.
        let click = mouse_at(
            MouseEventKind::Down(MouseButton::Left),
            panel.x + 2,
            panel.y + 2,
        );
        app.on_mouse(&click, FRAME);
        assert_eq!(app.focus, Focus::Terminal);
    }

    #[test]
    fn mouse_click_outside_panel_unfocuses() {
        let mut app = new_app();
        app.terms.open(term_sess("web-1", "devsandbox-web-1"));
        app.focus = Focus::Terminal;
        // Top-left corner is outside the bottom-right panel → back to dashboard.
        let click = mouse_at(MouseEventKind::Down(MouseButton::Left), 0, 0);
        app.on_mouse(&click, FRAME);
        assert_eq!(app.focus, Focus::Dashboard);
    }

    #[test]
    fn mouse_click_on_tab_label_activates_it() {
        let mut app = new_app();
        app.terms.open(term_sess("web-1", "devsandbox-web-1"));
        app.terms.open(term_sess("api-2", "devsandbox-api-2"));
        // Two tabs open; the second is active. Click the FIRST tab's label.
        assert_eq!(app.terms.active(), 1);
        let panel = crate::tui::ui::terminal_panel_rect(FRAME, false);
        // Labels (not focused): "1:web-1" at panel.x+1, "2:api-2" after +2 sep.
        // Land on the first character of the first label.
        let click = mouse_at(
            MouseEventKind::Down(MouseButton::Left),
            panel.x + 1,
            panel.y,
        );
        app.on_mouse(&click, FRAME);
        assert_eq!(app.terms.active(), 0);
        assert_eq!(app.focus, Focus::Terminal);
        // Now focused, so the `▶ ` mark (2 cols) shifts labels right by 2.
        // Tab 2 "2:api-2" starts at x+1 + 2(mark) + 7("1:web-1") + 2(sep) = x+12.
        let click2 = mouse_at(
            MouseEventKind::Down(MouseButton::Left),
            panel.x + 1 + 2 + 7 + 2,
            panel.y,
        );
        app.on_mouse(&click2, FRAME);
        assert_eq!(app.terms.active(), 1);
    }

    #[test]
    fn mouse_click_in_gap_between_tabs_keeps_active() {
        let mut app = new_app();
        app.terms.open(term_sess("web-1", "devsandbox-web-1"));
        app.terms.open(term_sess("api-2", "devsandbox-api-2"));
        app.terms.set_active(0);
        let panel = crate::tui::ui::terminal_panel_rect(FRAME, false);
        // The two-space gap after "1:web-1" (cols x+1+7, x+1+8) hits no label,
        // so the active tab is unchanged — but the click still focuses.
        let click = mouse_at(
            MouseEventKind::Down(MouseButton::Left),
            panel.x + 1 + 7,
            panel.y,
        );
        app.on_mouse(&click, FRAME);
        assert_eq!(app.terms.active(), 0);
        assert_eq!(app.focus, Focus::Terminal);
    }

    #[test]
    fn mouse_in_panel_ignored_when_no_terminal() {
        let mut app = new_app();
        let click = mouse_at(MouseEventKind::Down(MouseButton::Left), 50, 30);
        app.on_mouse(&click, FRAME);
        assert_eq!(app.focus, Focus::Dashboard);
    }

    #[test]
    fn mouse_wheel_scrolls_active_terminal_scrollback() {
        let mut app = new_app();
        app.terms.open(term_sess("web-1", "devsandbox-web-1"));
        // Build real scrollback: push 60 lines through a 24-row screen so lines
        // scroll off the top and vt100 has somewhere to scroll back to.
        {
            let session = app.terms.active_session().unwrap();
            let mut parser = session.parser().lock().unwrap();
            for i in 0..60 {
                parser.process(format!("line {i}\r\n").as_bytes());
            }
        }
        let panel = crate::tui::ui::terminal_panel_rect(FRAME, false);
        let body = (panel.x + 2, panel.y + 2);
        fn offset(app: &App) -> usize {
            app.terms
                .active_session()
                .unwrap()
                .parser()
                .lock()
                .unwrap()
                .screen()
                .scrollback()
        }
        assert_eq!(offset(&app), 0);
        app.on_mouse(&mouse_at(MouseEventKind::ScrollUp, body.0, body.1), FRAME);
        assert_eq!(offset(&app), 3);
        app.on_mouse(&mouse_at(MouseEventKind::ScrollUp, body.0, body.1), FRAME);
        assert_eq!(offset(&app), 6);
        app.on_mouse(&mouse_at(MouseEventKind::ScrollDown, body.0, body.1), FRAME);
        assert_eq!(offset(&app), 3);
        for _ in 0..5 {
            app.on_mouse(&mouse_at(MouseEventKind::ScrollDown, body.0, body.1), FRAME);
        }
        assert_eq!(offset(&app), 0);
        app.on_mouse(&mouse_at(MouseEventKind::ScrollUp, 0, 0), FRAME);
        assert_eq!(offset(&app), 0);
    }

    #[test]
    fn wheel_is_reported_to_a_child_tracking_the_mouse() {
        let mut app = new_app();
        app.terms.open(term_sess("web-1", "devsandbox-web-1"));
        let session = app.terms.active_session().unwrap();
        session.feed_output(b"\x1b[?1049h\x1b[?1000h\x1b[?1006h");
        let panel = crate::tui::ui::terminal_panel_rect(FRAME, false);
        // Body cell (2, 1): one column/row in from the border.
        let (x, y) = (panel.x + 3, panel.y + 2);
        app.on_mouse(&mouse_at(MouseEventKind::ScrollUp, x, y), FRAME);
        app.on_mouse(&mouse_at(MouseEventKind::ScrollDown, x, y), FRAME);
        let session = app.terms.active_session().unwrap();
        assert_eq!(session.take_written(), b"\x1b[<64;3;2M\x1b[<65;3;2M");
        // A notch over the border clamps onto the first body cell.
        app.on_mouse(&mouse_at(MouseEventKind::ScrollUp, panel.x, panel.y), FRAME);
        let session = app.terms.active_session().unwrap();
        assert_eq!(session.take_written(), b"\x1b[<64;1;1M");
    }

    /// A terminal whose child enabled `modes`, and its panel.
    fn tracking_app(modes: &[u8]) -> (App, Rect) {
        let mut app = new_app();
        app.terms.open(term_sess("web-1", "devsandbox-web-1"));
        app.terms.active_session().unwrap().feed_output(modes);
        (app, crate::tui::ui::terminal_panel_rect(FRAME, false))
    }

    fn written(app: &App) -> Vec<u8> {
        app.terms.active_session().unwrap().take_written()
    }

    #[test]
    fn a_tracking_child_gets_press_drag_and_release() {
        let (mut app, panel) = tracking_app(b"\x1b[?1000h\x1b[?1002h\x1b[?1006h");
        // Body cell (2, 1): 1-based (3, 2) in the report.
        let (x, y) = (panel.x + 3, panel.y + 2);
        app.on_mouse(&mouse_at(MouseEventKind::Down(MouseButton::Left), x, y), FRAME);
        assert_eq!(written(&app), b"\x1b[<0;3;2M");
        assert_eq!(app.focus, Focus::Terminal, "the click still focuses");
        app.on_mouse(&mouse_at(MouseEventKind::Drag(MouseButton::Left), x + 4, y + 1), FRAME);
        assert_eq!(written(&app), b"\x1b[<32;7;3M");
        // Dragged off the panel: clamped onto the body's last cell.
        app.on_mouse(&mouse_at(MouseEventKind::Drag(MouseButton::Left), 200, 200), FRAME);
        let (w, h) = (panel.width - 2, panel.height - 2);
        assert_eq!(written(&app), format!("\x1b[<32;{w};{h}M").into_bytes());
        // Released outside the panel: still sent, clamped onto the body.
        app.on_mouse(&mouse_at(MouseEventKind::Up(MouseButton::Left), 0, 0), FRAME);
        assert_eq!(written(&app), b"\x1b[<0;1;1m");
        assert!(app.selection.is_none() && app.candidate.is_none());
        assert_eq!(app.term_mouse_down, None);
        // Nothing after the release: a drag without a press isn't the child's.
        app.on_mouse(&mouse_at(MouseEventKind::Drag(MouseButton::Left), x, y), FRAME);
        assert!(written(&app).is_empty());
        // The other buttons too, and modifiers.
        let mut right = mouse_at(MouseEventKind::Down(MouseButton::Right), x, y);
        right.modifiers = KeyModifiers::CONTROL;
        app.on_mouse(&right, FRAME);
        app.on_mouse(&mouse_at(MouseEventKind::Up(MouseButton::Right), x, y), FRAME);
        app.on_mouse(&mouse_at(MouseEventKind::Down(MouseButton::Middle), x, y), FRAME);
        app.on_mouse(&mouse_at(MouseEventKind::Up(MouseButton::Middle), x, y), FRAME);
        assert_eq!(written(&app), b"\x1b[<18;3;2M\x1b[<2;3;2m\x1b[<1;3;2M\x1b[<1;3;2m");
    }

    #[test]
    fn forwarding_follows_the_childs_mode_and_encoding() {
        // `?1000` alone, X10 encoding: press and release, no drags.
        let (mut app, panel) = tracking_app(b"\x1b[?1000h");
        let (x, y) = (panel.x + 1, panel.y + 1);
        app.on_mouse(&mouse_at(MouseEventKind::Down(MouseButton::Left), x, y), FRAME);
        app.on_mouse(&mouse_at(MouseEventKind::Drag(MouseButton::Left), x + 1, y), FRAME);
        app.on_mouse(&mouse_at(MouseEventKind::Up(MouseButton::Left), x + 1, y), FRAME);
        assert_eq!(written(&app), b"\x1b[M !!\x1b[M#\"!");
        // A press on the title row or border isn't the child's, nor its release.
        app.on_mouse(&mouse_at(MouseEventKind::Down(MouseButton::Left), panel.x + 5, panel.y), FRAME);
        app.on_mouse(&mouse_at(MouseEventKind::Up(MouseButton::Left), panel.x + 5, panel.y), FRAME);
        assert!(written(&app).is_empty());
        // Not tracking (or exited): nothing is forwarded.
        let (mut app, panel) = tracking_app(b"");
        app.on_mouse(&mouse_at(MouseEventKind::Down(MouseButton::Left), panel.x + 2, panel.y + 2), FRAME);
        assert!(written(&app).is_empty() && app.term_mouse_down.is_none());
        let (mut app, panel) = tracking_app(b"\x1b[?1000h");
        app.terms.active_session().unwrap().set_exited();
        app.on_mouse(&mouse_at(MouseEventKind::Down(MouseButton::Left), panel.x + 2, panel.y + 2), FRAME);
        assert!(written(&app).is_empty());
    }

    #[test]
    fn hover_goes_to_an_any_motion_child_once_per_cell() {
        let (mut app, panel) = tracking_app(b"\x1b[?1003h\x1b[?1006h");
        let moved = |x, y| mouse_at(MouseEventKind::Moved, x, y);
        // Body cell (2, 1): 1-based (3, 2) in the report.
        let (x, y) = (panel.x + 3, panel.y + 2);
        app.on_mouse(&moved(x, y), FRAME);
        assert_eq!(written(&app), b"\x1b[<35;3;2M");
        // Same cell again: suppressed. A new cell is reported.
        app.on_mouse(&moved(x, y), FRAME);
        assert!(written(&app).is_empty());
        app.on_mouse(&moved(x + 1, y), FRAME);
        assert_eq!(written(&app), b"\x1b[<35;4;2M");
        // Border, title row, outside the panel: nothing, and leaving resets
        // the dedupe so coming back to the same cell reports again.
        for (bx, by) in [(panel.x, panel.y + 2), (panel.x + 5, panel.y), (0, 0)] {
            app.on_mouse(&moved(bx, by), FRAME);
        }
        assert!(written(&app).is_empty());
        app.on_mouse(&moved(x + 1, y), FRAME);
        assert_eq!(written(&app), b"\x1b[<35;4;2M");
        // A press resets it too (the child saw the pointer at the press).
        app.on_mouse(&mouse_at(MouseEventKind::Down(MouseButton::Left), x + 1, y), FRAME);
        app.on_mouse(&mouse_at(MouseEventKind::Up(MouseButton::Left), x + 1, y), FRAME);
        assert_eq!(written(&app), b"\x1b[<0;4;2M\x1b[<0;4;2m");
        app.on_mouse(&moved(x + 1, y), FRAME);
        assert_eq!(written(&app), b"\x1b[<35;4;2M");
        assert!(app.selection.is_none() && app.candidate.is_none(), "hover never selects");
        // Modifiers ride along.
        let mut ctrl = moved(x, y);
        ctrl.modifiers = KeyModifiers::CONTROL;
        app.on_mouse(&ctrl, FRAME);
        assert_eq!(written(&app), b"\x1b[<51;3;2M");
    }

    #[test]
    fn hover_resets_when_the_active_session_changes() {
        let (mut app, panel) = tracking_app(b"\x1b[?1003h\x1b[?1006h");
        let (x, y) = (panel.x + 3, panel.y + 2);
        app.on_mouse(&mouse_at(MouseEventKind::Moved, x, y), FRAME);
        assert_eq!(written(&app), b"\x1b[<35;3;2M");
        app.terms.open(term_sess("api-2", "devsandbox-api-2"));
        app.terms.active_session().unwrap().feed_output(b"\x1b[?1003h\x1b[?1006h");
        // Same cell, other session: it hasn't seen the pointer yet.
        app.on_mouse(&mouse_at(MouseEventKind::Moved, x, y), FRAME);
        assert_eq!(written(&app), b"\x1b[<35;3;2M");
    }

    #[test]
    fn hover_is_dropped_without_any_motion() {
        for modes in [&b""[..], b"\x1b[?9h", b"\x1b[?1000h\x1b[?1006h", b"\x1b[?1002h\x1b[?1006h"] {
            let (mut app, panel) = tracking_app(modes);
            app.on_mouse(&mouse_at(MouseEventKind::Moved, panel.x + 3, panel.y + 2), FRAME);
            assert!(written(&app).is_empty(), "{modes:?}");
        }
        // An exited AnyMotion session gets nothing either.
        let (mut app, panel) = tracking_app(b"\x1b[?1003h");
        app.terms.active_session().unwrap().set_exited();
        app.on_mouse(&mouse_at(MouseEventKind::Moved, panel.x + 3, panel.y + 2), FRAME);
        assert!(written(&app).is_empty());
    }

    #[test]
    fn a_modal_hides_the_terminal_from_the_mouse() {
        let (mut app, panel) = tracking_app(b"");
        for i in 0..60 {
            app.terms.active_session().unwrap().feed_output(format!("line {i}\r\n").as_bytes());
        }
        app.on_key(key(KeyCode::Char('?')));
        assert!(matches!(app.modal, Modal::Help(_)));
        let (x, y) = (panel.x + 2, panel.y + 2);
        app.on_mouse(&mouse_at(MouseEventKind::Down(MouseButton::Left), x, y), FRAME);
        app.on_mouse(&mouse_at(MouseEventKind::ScrollUp, x, y), FRAME);
        assert_eq!(app.focus, Focus::Dashboard);
        let session = app.terms.active_session().unwrap();
        assert_eq!(session.parser().lock().unwrap().screen().scrollback(), 0);
    }

    #[test]
    fn wheel_sends_arrows_on_the_alternate_screen_without_mouse_tracking() {
        let mut app = new_app();
        app.terms.open(term_sess("web-1", "devsandbox-web-1"));
        let session = app.terms.active_session().unwrap();
        // less/man style: alternate screen plus application cursor keys.
        session.feed_output(b"\x1b[?1049h\x1b[?1h");
        let panel = crate::tui::ui::terminal_panel_rect(FRAME, false);
        let (x, y) = (panel.x + 2, panel.y + 2);
        app.on_mouse(&mouse_at(MouseEventKind::ScrollDown, x, y), FRAME);
        let session = app.terms.active_session().unwrap();
        assert_eq!(session.take_written(), b"\x1bOB\x1bOB\x1bOB");
        assert_eq!(session.parser().lock().unwrap().screen().scrollback(), 0);
    }

    #[test]
    fn wheel_on_an_exited_session_only_scrolls_back() {
        let mut app = new_app();
        app.terms.open(term_sess("web-1", "devsandbox-web-1"));
        let session = app.terms.active_session().unwrap();
        for i in 0..60 {
            session.feed_output(format!("line {i}\r\n").as_bytes());
        }
        session.feed_output(b"\x1b[?1000h");
        session.set_exited();
        let panel = crate::tui::ui::terminal_panel_rect(FRAME, false);
        app.on_mouse(&mouse_at(MouseEventKind::ScrollUp, panel.x + 2, panel.y + 2), FRAME);
        let session = app.terms.active_session().unwrap();
        assert!(session.take_written().is_empty());
        assert_eq!(session.parser().lock().unwrap().screen().scrollback(), 3);
    }

    #[test]
    fn keys_follow_the_childs_kitty_flags() {
        let mut app = new_app();
        open_test_term(&mut app, "web-1", "devsandbox-web-1");
        let ctrl_m = KeyEvent::new(KeyCode::Char('m'), KeyModifiers::CONTROL);
        let written = |app: &App| app.terms.active_session().unwrap().take_written();
        // No flags pushed: legacy, ctrl+m is the same `\r` as Enter.
        app.on_key(ctrl_m);
        assert_eq!(written(&app), b"\r");
        // The child opts in on the alternate screen, like zidane does.
        app.terms.active_session().unwrap().feed_output(b"\x1b[?1049h\x1b[>1u");
        app.on_key(ctrl_m);
        assert_eq!(written(&app), b"\x1b[109;5u");
        app.on_key(KeyEvent::new(KeyCode::Char('a'), KeyModifiers::NONE));
        assert_eq!(written(&app), b"a");
    }

    #[test]
    fn terminal_focus_swallows_dashboard_keys() {
        let mut app = new_app();
        open_test_term(&mut app, "web-1", "devsandbox-web-1");
        let before = app.tab;
        // Tab must not switch the top-level tab while a terminal is focused.
        app.on_key(key(KeyCode::Tab));
        assert_eq!(app.tab, before);
        app.on_key(key(KeyCode::Char('q')));
        assert!(!app.should_quit);
        assert_eq!(app.focus, Focus::Terminal);
    }

    #[test]
    fn ctrl_bracket_and_f12_leave_terminal() {
        let mut app = new_app();
        open_test_term(&mut app, "web-1", "devsandbox-web-1");
        app.on_key(KeyEvent::new(KeyCode::Char(']'), KeyModifiers::CONTROL));
        assert_eq!(app.focus, Focus::Dashboard);

        open_test_term(&mut app, "web-1", "devsandbox-web-1");
        app.on_key(key(KeyCode::F(12)));
        assert_eq!(app.focus, Focus::Dashboard);
    }

    #[test]
    fn enter_terminal_needs_a_terminal() {
        let mut app = new_app();
        app.on_key(KeyEvent::new(KeyCode::Char(']'), KeyModifiers::CONTROL));
        assert_eq!(app.focus, Focus::Dashboard);
        assert_eq!(app.status.as_deref(), Some("no terminal open — press t"));
        app.on_key(key(KeyCode::F(12)));
        assert_eq!(app.focus, Focus::Dashboard);
        assert_eq!(app.status.as_deref(), Some("no terminal open — press t"));

        app.terms
            .open(TermSession::test_session("web-1", "devsandbox-web-1", 24, 80));
        app.on_key(KeyEvent::new(KeyCode::Char(']'), KeyModifiers::CONTROL));
        assert_eq!(app.focus, Focus::Terminal);
    }

    #[test]
    fn dashboard_brackets_cycle_and_x_closes() {
        let mut app = new_app();
        app.terms
            .open(TermSession::test_session("a", "devsandbox-a", 24, 80));
        app.terms
            .open(TermSession::test_session("b", "devsandbox-b", 24, 80)); // active = 1
        app.on_key(key(KeyCode::Char(']')));
        assert_eq!(app.terms.active(), 0);
        app.on_key(key(KeyCode::Char('[')));
        assert_eq!(app.terms.active(), 1);
        app.on_key(key(KeyCode::Char('x')));
        assert_eq!(app.terms.sessions().len(), 1);
        assert_eq!(app.terms.active_session().unwrap().title, "a");
    }

    #[test]
    fn exited_terminal_swallows_keys_but_leaves() {
        let mut app = new_app();
        app.terms
            .open(TermSession::test_session("web-1", "devsandbox-web-1", 24, 80));
        app.terms.active_session().unwrap().set_exited();
        app.focus = Focus::Terminal;
        // Ordinary keys are swallowed without panicking; focus is unchanged.
        app.on_key(key(KeyCode::Char('a')));
        app.on_key(key(KeyCode::Enter));
        assert_eq!(app.focus, Focus::Terminal);
        app.on_key(key(KeyCode::F(12)));
        assert_eq!(app.focus, Focus::Dashboard);
    }

    #[test]
    fn x_closes_exited_terminal_and_returns_to_dashboard() {
        let mut app = new_app();
        app.terms
            .open(TermSession::test_session("web-1", "devsandbox-web-1", 24, 80));
        app.terms.active_session().unwrap().set_exited();
        app.focus = Focus::Terminal;
        // `x` closes the exited session in place; with none left, focus drops
        // back to the dashboard.
        app.on_key(key(KeyCode::Char('x')));
        assert!(app.terms.is_empty());
        assert_eq!(app.focus, Focus::Dashboard);
    }

    #[test]
    fn x_closes_exited_terminal_but_stays_focused_with_others() {
        let mut app = new_app();
        app.terms
            .open(TermSession::test_session("web-1", "devsandbox-web-1", 24, 80));
        app.terms
            .open(TermSession::test_session("web-2", "devsandbox-web-2", 24, 80));
        app.terms.active_session().unwrap().set_exited();
        app.focus = Focus::Terminal;
        app.on_key(key(KeyCode::Char('x')));
        // One session remains, so the terminal stays focused.
        assert_eq!(app.terms.sessions().len(), 1);
        assert_eq!(app.focus, Focus::Terminal);
    }

    #[test]
    fn term_target_instance_requires_running() {
        let mut app = new_app();
        app.set_snapshot(snapshot_with_status(1, ContainerStatus::Missing));
        app.on_key(key(KeyCode::Down));
        assert_eq!(
            app.term_target(),
            Err("terminal: `inst0` is not running".into())
        );
        app.set_snapshot(snapshot_with_status(1, running()));
        app.on_key(key(KeyCode::Down));
        assert_eq!(
            app.term_target(),
            Ok(("inst0".into(), "devsandbox-inst0".into(), true))
        );
    }

    #[test]
    fn term_target_service_picks_first_running() {
        let mut app = new_app();
        app.tab = Tab::Services;
        app.set_snapshot(service_snapshot(vec![(
            "devsandbox-svc-web-1".into(),
            ContainerStatus::Exited("Exited (0)".into()),
        )]));
        assert_eq!(
            app.term_target(),
            Err("terminal: no running container for `svc`".into())
        );
        // First running container wins; title strips the prefix.
        app.set_snapshot(service_snapshot(vec![
            (
                "devsandbox-svc-web-1".into(),
                ContainerStatus::Exited("Exited (0)".into()),
            ),
            ("devsandbox-svc-api-2".into(), running()),
        ]));
        assert_eq!(
            app.term_target(),
            Ok(("svc-api-2".into(), "devsandbox-svc-api-2".into(), false))
        );
    }

    /// A machine's instance or service: keyed (title and dedup) by machine,
    /// run as this host's devsandbox on the qualified name (its `exec` goes
    /// over the machine's link), whatever kind of machine it is.
    #[test]
    fn a_machines_rows_open_terminals_through_the_local_cli() {
        for kind in [crate::serve::machines::MachineKind::Ssh, crate::serve::machines::MachineKind::Inbound] {
            let mut app = machine_app();
            app.machines[0].kind = kind;
            app.selected[Tab::Instances.index()] = 5;
            let target = app.term_target();
            assert_eq!(target, Ok(("box/inst1".into(), "box/devsandbox-inst1".into(), true)));
            assert_eq!(app.term_argv("box/inst1", "box/devsandbox-inst1", true, ID), Err("terminal: the devsandbox executable isn't known yet".into()));
            app.exec_cli = Ok(cli());
            // In session ID, which the tab re-dials an attach to.
            let (argv, attach) = app.term_argv("box/inst1", "box/devsandbox-inst1", true, ID).unwrap();
            assert_eq!(argv, ["/opt/bin/devsandbox", "exec", "-i", "-t", "--reserve-255", "--session=1790000000-a1b2", "--", "box/inst1"]);
            assert_eq!(attach, Some(["/opt/bin/devsandbox", "exec", "--reserve-255", "--attach=1790000000-a1b2", "--", "box/inst1"].map(String::from).to_vec()));
            // A local instance of the same name: this host's devsandbox, no re-dial.
            let (argv, attach) = app.term_argv("inst1", "devsandbox-inst1", true, ID).unwrap();
            assert_eq!(argv[..4], ["/opt/bin/devsandbox", "-C", "/home/u/cfg", "exec"]);
            assert_eq!(attach, None);
            // `:exec` too.
            assert_eq!(app.exec_argv("box/inst1", &["uname".into()]).unwrap(), ["/opt/bin/devsandbox", "exec", "-i", "-t", "--", "box/inst1", "uname"]);
            assert_eq!(app.exec_argv("nope/x", &[]), Err("no machine named `nope`".into()));
            // Seen only through the control plane (routed): the same tab, its dial
            // routed.
            let mut seen = app.machines.clone();
            seen[0].via = Some("k".into());
            seen[0].kind = crate::serve::machines::MachineKind::Routed;
            let real = std::mem::replace(&mut app.machines, seen);
            assert_eq!(app.exec_argv("box/inst1", &[]).unwrap(), ["/opt/bin/devsandbox", "exec", "-i", "-t", "--", "box/inst1"]);
            assert_eq!(app.term_argv("box/inst1", "box/devsandbox-inst1", true, ID).unwrap().0[..5], ["/opt/bin/devsandbox", "exec", "-i", "-t", "--reserve-255"]);
            app.machines = real;

            // Dedup: box's tab doesn't stand for the local one's.
            app.terms.open(term_sess("box/inst1", "box/devsandbox-inst1"));
            assert_eq!(app.terms.find("devsandbox-inst1"), None);
            assert_eq!(app.terms.find("box/devsandbox-inst1"), Some(0));

            // A service: through an instance using it, else refused.
            app.tab = Tab::Services;
            let db = app.snapshot.as_ref().unwrap().services.iter().position(|s| s.name == "db").unwrap();
            app.selected[Tab::Services.index()] = db;
            assert_eq!(app.term_target(), Ok(("box/svc-db".into(), "box/devsandbox-svc-db".into(), false)));
            let unused = app.term_argv("box/svc-db", "box/devsandbox-svc-db", false, ID).unwrap_err();
            assert!(unused.contains("no instance on `box` uses service `db`"), "{unused}");
            app.snapshot.as_mut().unwrap().services[db].used_by = vec!["inst1".into()];
            let (argv, attach) = app.term_argv("box/svc-db", "box/devsandbox-svc-db", false, ID).unwrap();
            assert_eq!(attach, None, "a service tab doesn't re-dial");
            assert_eq!(argv, ["/opt/bin/devsandbox", "exec", "--service=db", "--", "box/inst1"]);
        }
    }

    const ID: &str = "1790000000-a1b2";

    fn attach() -> Vec<String> {
        vec!["devsandbox".into(), "attach".into()]
    }

    /// A tab's dials: lost (255 after a connected run) waits out the
    /// backoff, then re-dials the attach; the session's own code ends it.
    #[test]
    fn redial_waits_then_re_dials_until_the_session_answers() {
        use std::time::Duration;
        let t0 = Instant::now();
        let s = Duration::from_secs;
        let mut r = Redial::new(attach(), t0);
        assert_eq!(r.step(None, t0 + s(60)), None, "running");
        assert!(r.live() && !r.ended());
        // Lost after a minute: re-dial in 1 s.
        assert_eq!(r.step(Some(255), t0 + s(60)), None);
        assert_eq!(r.attempt(), Some(1));
        assert_eq!(r.step(None, t0 + s(60) + Duration::from_millis(500)), None, "still waiting");
        assert_eq!(r.step(None, t0 + s(61)), Some(&attach()[..]));
        r.dialed(t0 + s(61));
        assert!(r.live() && r.attempt().is_none());
        // The re-dial fails at once: the next wait is longer.
        assert_eq!(r.step(Some(255), t0 + s(62)), None);
        assert_eq!(r.attempt(), Some(2));
        assert_eq!(r.step(None, t0 + s(63)), None);
        assert_eq!(r.step(None, t0 + s(64)), Some(&attach()[..]));
        r.dialed(t0 + s(64));
        // The program exits: the tab ends.
        assert_eq!(r.step(Some(0), t0 + s(90)), None);
        assert!(r.ended());
        assert_eq!(r.step(Some(255), t0 + s(200)), None, "ended stays ended");

        // A first dial refused at once (the link isn't up): no re-dial.
        let mut r = Redial::new(attach(), t0);
        assert_eq!(r.step(Some(255), t0 + Duration::from_millis(300)), None);
        assert!(r.ended());
        // A session gone: ends too.
        let mut r = Redial::new(attach(), t0);
        r.step(Some(255), t0 + s(60));
        r.step(None, t0 + s(61));
        r.dialed(t0 + s(61));
        r.step(Some(250), t0 + s(62));
        assert!(r.ended());
    }

    /// In the app: a remote tab whose link dropped shows as reconnecting
    /// (still the dedup target, keys swallowed), until its wait is over;
    /// `x` closes it, which stops the loop. A tab without a `Redial` just
    /// exits.
    #[test]
    fn a_dropped_remote_tab_reconnects_in_place() {
        use std::time::Duration;
        let mut app = new_app();
        let t0 = Instant::now();
        let mut remote = TermSession::test_session("box/web", "box/devsandbox-web", 24, 80);
        remote.redial = Some(Redial::new(attach(), t0));
        app.terms.open(remote);
        app.terms.open(TermSession::test_session("web", "devsandbox-web", 24, 80));
        app.redial_terminals(t0 + Duration::from_secs(30));
        assert!(!app.terms.sessions()[0].reconnecting(), "running");

        app.terms.sessions_mut()[0].set_exited_with(255);
        app.terms.sessions_mut()[1].set_exited_with(255);
        app.redial_terminals(t0 + Duration::from_secs(30));
        let tabs = app.terms.sessions();
        assert!(tabs[0].reconnecting() && tabs[0].redial.as_ref().unwrap().attempt() == Some(1));
        assert!(!tabs[1].reconnecting(), "a local tab just exits");
        assert_eq!(app.terms.find("box/devsandbox-web"), Some(0), "`t` focuses the reconnecting tab");
        assert_eq!(app.terms.find("devsandbox-web"), None);
        assert_eq!(crate::tui::ui::terminal_tab_labels(&app), ["1:box/web (reconnecting…)", "2:web (exited)"]);
        // A second try of the same outage counts in the label.
        let mut second = Redial::new(attach(), t0);
        second.step(Some(255), t0 + Duration::from_secs(30));
        assert!(second.step(None, t0 + Duration::from_secs(31)).is_some());
        second.dialed(t0 + Duration::from_secs(31));
        second.step(Some(255), t0 + Duration::from_secs(32));
        let saved = app.terms.sessions_mut()[0].redial.replace(second);
        assert_eq!(crate::tui::ui::terminal_tab_labels(&app)[0], "1:box/web (reconnecting… 2)");
        app.terms.sessions_mut()[0].redial = saved;

        // Keys are swallowed while it waits; `x` closes it.
        app.terms.set_active(0);
        app.focus = Focus::Terminal;
        app.on_key(key(KeyCode::Char('a')));
        assert!(app.terms.sessions()[0].take_written().is_empty());
        app.on_key(key(KeyCode::Char('x')));
        assert_eq!(app.terms.sessions().len(), 1);
        assert_eq!(app.terms.sessions()[0].title, "web");
    }

    fn cli() -> ExecCli {
        ExecCli { exe: Some("/opt/bin/devsandbox".into()), root: "/home/u/cfg".into() }
    }

    #[test]
    fn exec_cli_argv_puts_the_instance_after_the_separator() {
        let base = ["/opt/bin/devsandbox", "-C", "/home/u/cfg", "exec", "-i", "-t", "--", "-web"];
        assert_eq!(cli().argv("-web", &[]).unwrap(), base);
        let cmd = ["ls".to_string(), "-la".to_string()];
        assert_eq!(cli().argv("-web", &cmd).unwrap(), [&base[..], &["ls", "-la"]].concat());
    }

    #[test]
    fn instance_terminal_runs_devsandbox_exec() {
        let mut app = new_app();
        app.set_snapshot(snapshot_with_status(1, running()));
        // No executable yet: the tab doesn't open, the status says why.
        assert_eq!(
            app.term_argv("inst0", "devsandbox-inst0", true, ID),
            Err("terminal: the devsandbox executable isn't known yet".into())
        );
        app.exec_cli = Ok(cli());
        assert_eq!(app.term_argv("inst0", "devsandbox-inst0", true, ID), Ok((cli().argv("inst0", &[]).unwrap(), None)));
    }

    #[test]
    fn service_terminal_runs_the_snapshots_runtime() {
        let mut app = new_app();
        let mut snap = service_snapshot(vec![("devsandbox-svc-api-2".into(), running())]);
        snap.runtime_name = "podman".into();
        app.set_snapshot(snap);
        let (argv, attach) = app.term_argv("svc-api-2", "devsandbox-svc-api-2", false, ID).unwrap();
        assert_eq!(attach, None);
        assert_eq!(argv[..5], ["podman", "exec", "-i", "-t", "devsandbox-svc-api-2"]);
        assert_eq!(argv[5..], SHELL_FALLBACK_CMD);
        // The exec CLI isn't needed for a service.
        assert!(app.exec_cli.is_err());
    }

    #[test]
    fn exec_cli_attach_argv_is_an_attach_only_exec() {
        use clap::Parser;
        let argv = cli().attach_argv("-web", ID).unwrap();
        assert_eq!(argv, ["/opt/bin/devsandbox", "-C", "/home/u/cfg", "exec", "--attach=1790000000-a1b2", "--", "-web"]);
        let parsed = crate::Cli::try_parse_from(std::iter::once("devsandbox").chain(argv[1..].iter().map(String::as_str))).unwrap();
        assert!(matches!(
            parsed.command.unwrap(),
            crate::Command::Exec { attach: Some(Some(ref a)), session: None, ref name, ref command, .. }
                if a == ID && name == "-web" && command.is_empty()
        ));
    }

    /// `a` on a running instance row asks for its sessions; a stopped
    /// row, an unreachable machine's, a process row or another tab don't.
    #[test]
    fn a_queues_a_sessions_fetch_for_a_running_instance_row() {
        let mut app = new_app();
        app.set_snapshot(snapshot_with_status(1, ContainerStatus::Missing));
        app.on_key(key(KeyCode::Down));
        app.on_key(key(KeyCode::Char('a')));
        assert_eq!(app.take_pending_fetch(), []);
        assert_eq!(app.status.as_deref(), Some("attach: `inst0` is not running"));

        app.set_snapshot(snapshot_with_status(1, running()));
        app.on_key(key(KeyCode::Char('a')));
        assert_eq!(app.take_pending_fetch(), [Fetch::Sessions { instance: "inst0".into() }]);

        let mut app = app_on_proc_row(&["7"]);
        app.on_key(key(KeyCode::Char('a')));
        assert_eq!(app.take_pending_fetch(), []);

        let mut app = machine_app();
        app.selected[Tab::Instances.index()] = 5;
        app.on_key(key(KeyCode::Char('a')));
        assert_eq!(app.take_pending_fetch(), [Fetch::Sessions { instance: "box/inst1".into() }]);
        app.machines[0].state = crate::serve::snapshots::LinkState::Unreachable;
        app.on_key(key(KeyCode::Char('a')));
        assert_eq!(app.take_pending_fetch(), []);
        assert_eq!(app.status.as_deref(), Some("attach: `box/inst1`'s machine is unreachable"));
        app.tab = Tab::Services;
        app.on_key(key(KeyCode::Char('a')));
        assert_eq!(app.take_pending_fetch(), []);
    }

    const RUNNING: &str = "1790000000-a1b2 running detached 2026-01-01T00:00:00Z bash -l";
    const OTHER: &str = "1790000100-c3d4 running detached 2026-01-01T00:01:40Z vim";
    const ATTACHED: &str = "1790000200-e5f6 running attached 2026-01-01T00:03:20Z zsh -l";

    /// A tab-spawning app: `/bin/true` stands in for devsandbox, so the PTY
    /// child exits at once.
    fn attach_app() -> App {
        let mut app = new_app();
        app.set_snapshot(snapshot_with_status(1, running()));
        app.exec_cli = Ok(ExecCli { exe: Some("/bin/true".into()), root: "/home/u/cfg".into() });
        app
    }

    #[test]
    fn sessions_listed_reports_an_error_or_none() {
        let mut app = attach_app();
        app.sessions_listed("inst0", Err("attach: no instance `inst0`".into()));
        assert_eq!(app.status.as_deref(), Some("attach: no instance `inst0`"));
        let lines = vec![
            "1790000100-c3d4 exited 0 - 2026-01-01T00:01:40Z vim".to_string(),
            "1790000200-e5f6 lost - 2026-01-01T00:03:20Z sh".to_string(),
        ];
        app.sessions_listed("inst0", Ok(lines));
        assert_eq!(app.status.as_deref(), Some("attach: no running session in `inst0`"));
        assert!(app.terms.is_empty() && matches!(app.modal, Modal::None));
    }

    /// One running session, attached (a client docker left behind, say):
    /// a tab on it, taking it over. One detached beside attached ones:
    /// that one, no picker.
    #[test]
    fn a_single_attached_session_opens_a_tab() {
        let mut app = attach_app();
        app.sessions_listed("inst0", Ok(vec![ATTACHED.into(), "1790000100-c3d4 exited 0 - 2026-01-01T00:01:40Z vim".into()]));
        assert_eq!(app.status, None);
        assert_eq!(app.terms.sessions().len(), 1);
        assert!(matches!(app.modal, Modal::None));

        let mut app = machine_app();
        app.exec_cli = Ok(ExecCli { exe: Some("/bin/true".into()), root: "/home/u/cfg".into() });
        app.sessions_listed("box/inst1", Ok(vec![ATTACHED.into(), OTHER.into()]));
        assert!(matches!(app.modal, Modal::None), "the one detached wins");
        assert_eq!(app.terms.sessions()[0].redial.as_ref().unwrap().attach[3], "--attach=1790000100-c3d4");
    }

    /// One detached session: a new tab on it, beside a `t` tab of the same
    /// container. A remote one re-dials the same attach.
    #[test]
    fn one_detached_session_opens_an_attach_tab() {
        let mut app = attach_app();
        app.terms.open(term_sess("inst0", "devsandbox-inst0"));
        assert_eq!(app.attach_argvs("inst0", ID), Ok((ExecCli { exe: Some("/bin/true".into()), root: "/home/u/cfg".into() }.attach_argv("inst0", ID).unwrap(), None)));
        app.sessions_listed("inst0", Ok(vec![RUNNING.into()]));
        assert_eq!(app.status, None);
        let tabs = app.terms.sessions();
        assert_eq!(tabs.len(), 2, "not deduped against the `t` tab");
        assert_eq!((tabs[1].title.as_str(), tabs[1].container.as_str()), ("inst0", "devsandbox-inst0"));
        assert!(tabs[1].redial.is_none());
        assert_eq!(app.focus, Focus::Terminal);

        let mut app = machine_app();
        app.exec_cli = Ok(ExecCli { exe: Some("/bin/true".into()), root: "/home/u/cfg".into() });
        app.sessions_listed("box/inst1", Ok(vec![RUNNING.into()]));
        let tab = &app.terms.sessions()[0];
        assert_eq!((tab.title.as_str(), tab.container.as_str()), ("box/inst1", "box/devsandbox-inst1"));
        let attach = ["/bin/true", "exec", "--reserve-255", "--attach=1790000000-a1b2", "--", "box/inst1"].map(String::from).to_vec();
        assert_eq!(tab.redial.as_ref().unwrap().attach, attach);
        assert_eq!(app.attach_argvs("box/inst1", ID), Ok((attach.clone(), Some(attach))));
    }

    /// Several: a picker over them, detached first, each line its `ls`
    /// line (attached or detached); `j`/`k` move, `enter` attaches the
    /// cursor's, `esc` closes it without a tab.
    #[test]
    fn several_sessions_open_a_picker() {
        let mut app = attach_app();
        app.sessions_listed("inst0", Ok(vec![ATTACHED.into(), RUNNING.into(), OTHER.into()]));
        let Modal::Confirm(view) = &app.modal else { panic!("no picker") };
        assert_eq!(view.question, "inst0: attach to a session");
        assert_eq!(view.body, [format!("› {RUNNING}"), format!("  {OTHER}"), format!("  {ATTACHED}")]);
        assert_eq!(view.keys_hint(), "↑↓ move · enter attach · esc cancel");
        assert_eq!(view.choices(), "[enter] attach (an attached one is taken over)  [esc] cancel");
        app.on_key(key(KeyCode::Esc));
        assert!(matches!(app.modal, Modal::None) && app.terms.is_empty());

        // No detached one: a picker over the attached ones.
        let mut app = attach_app();
        let other_attached = OTHER.replace("detached", "attached");
        app.sessions_listed("inst0", Ok(vec![ATTACHED.into(), other_attached.clone()]));
        let Modal::Confirm(view) = &app.modal else { panic!("no picker") };
        assert_eq!(view.body, [format!("› {ATTACHED}"), format!("  {other_attached}")]);
        app.on_key(key(KeyCode::Esc));
        assert!(matches!(app.modal, Modal::None) && app.terms.is_empty());

        // On a machine, so the tab's re-dial shows the id it attached.
        let mut app = machine_app();
        app.exec_cli = Ok(ExecCli { exe: Some("/bin/true".into()), root: "/home/u/cfg".into() });
        app.sessions_listed("box/inst1", Ok(vec![RUNNING.into(), OTHER.into()]));
        app.on_key(key(KeyCode::Char('j')));
        app.on_key(key(KeyCode::Char('j')));
        app.on_key(key(KeyCode::Char('k')));
        let Modal::Confirm(view) = &app.modal else { panic!("no picker") };
        assert_eq!(view.body[1], format!("› {OTHER}"));
        app.on_key(key(KeyCode::Enter));
        assert!(matches!(app.modal, Modal::None));
        let tabs = app.terms.sessions();
        assert_eq!(tabs.len(), 1);
        assert_eq!(tabs[0].redial.as_ref().unwrap().attach[3], "--attach=1790000100-c3d4");
        assert_eq!(app.focus, Focus::Terminal);
    }

    /// `a` and `enter` on a session row attach that id, an attached one too
    /// (it takes over); a machine's tab re-dials it.
    #[test]
    fn a_or_enter_on_a_session_row_attaches_it() {
        let mut app = select_session_row(attach_app(), "inst0", "1790000000-a1b2 attached bash -l");
        app.on_key(key(KeyCode::Char('a')));
        assert_eq!(app.terms.sessions().len(), 1);
        assert_eq!(app.focus, Focus::Terminal);
        app.focus = Focus::Dashboard;
        app.on_key(key(KeyCode::Enter));
        assert_eq!(app.terms.sessions().len(), 2, "never deduped");
        assert!(matches!(app.modal, Modal::None), "enter isn't the config view here");

        let mut app = machine_app();
        app.exec_cli = Ok(ExecCli { exe: Some("/bin/true".into()), root: "/home/u/cfg".into() });
        let mut app = select_session_row(app, "box/inst1", "1790000100-c3d4 detached vim");
        app.on_key(key(KeyCode::Enter));
        let tab = &app.terms.sessions()[0];
        assert_eq!(tab.title, "box/inst1");
        assert_eq!(tab.redial.as_ref().unwrap().attach[3], "--attach=1790000100-c3d4");
    }

    #[test]
    fn find_dedup_vs_force_new() {
        // TermTabs dedup: an exited tab for a container is not a target, a live
        // one is (mirrors `t` vs `T` at the app layer).
        let mut app = new_app();
        let dead = TermSession::test_session("web-1", "devsandbox-web-1", 24, 80);
        dead.set_exited();
        app.terms.open(dead);
        assert_eq!(app.terms.find("devsandbox-web-1"), None);
        app.terms
            .open(TermSession::test_session("web-1", "devsandbox-web-1", 24, 80));
        assert_eq!(app.terms.find("devsandbox-web-1"), Some(1));
    }
}