croft-software 0.2.232

VSCode-style TUI written in Rust
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
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
//! SSH connect and install, the ssh-pane offer, handing off to a remote croft, Remote
//! Explorer keys, config sync, drop relay and scp uploads, port forwarding, and opening
//! URLs on the local machine.

use super::*;
use crate::widgets::confirm_frame::{ConfirmFrame, Inset, draw_confirm};

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RemotePullKind {
    /// File or directory copied from the user's local Mac into the
    /// inbox; on completion the relay file is moved into `dest_dir`.
    File,
    /// Local-Mac clipboard contents staged at `<inbox>/<id>/clipboard.txt`;
    /// on completion the bytes are pasted into the requesting terminal pane.
    Clipboard {
        /// Stable [`PtyTerminal::uid`] of the pane that requested the paste
        /// (#2967), so switching panes before the relay responds cannot paste
        /// into a different shell.
        terminal_uid: Option<u64>,
    },
    /// URL handed to the user's local Mac `open(1)`; on completion croft
    /// just surfaces a status confirmation. No payload is shipped back.
    Open,
    /// Remote loopback port forwarded home over the SSH master; the `.ok`
    /// payload carries the chosen local port, which croft records so the PORTS
    /// panel can label and open it. `remote_port` is the port being forwarded.
    Forward { remote_port: u16 },
}

pub(super) const REMOTE_PULL_TIMEOUT: Duration = Duration::from_secs(120);

/// Options for [`App::open_web_url`].
#[derive(Default)]
pub(in crate::app) struct WebOpenOpts {
    /// Human-readable label substituted for the URL in the relay
    /// `"Opening … on your local Mac"` status line (e.g. `"ssh_config(5)"`).
    pub(in crate::app) relay_label: Option<&'static str>,
    /// Override for the local `"Opened …"` status line (e.g.
    /// `"Opened ssh_config(5) docs"`).
    pub(in crate::app) local_opened_status: Option<&'static str>,
    /// When `true`, `cfg!(test)` records `"Open <url>"` instead of launching
    /// the host browser so unit tests exercising UI link commands stay inert.
    pub(in crate::app) inert_in_tests: bool,
}

/// Where this croft session is running and which host capabilities its
/// launcher exported, read once from the process environment at startup
/// (#2062).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(super) struct HostSession {
    /// True when croft was invoked over an SSH login (`SSH_CONNECTION`,
    /// `SSH_TTY` or `SSH_CLIENT`).
    pub(super) is_remote: bool,
    /// Deterministic relay id exported by `croft remote` (`CROFT_RELAY_KEY`),
    /// empty filtered out. Inert under `cfg!(test)` so tests opt in directly
    /// without being steered by another test's environment.
    pub(super) relay_key: Option<String>,
    /// True when running inside a persistent session wrapper (`session-host`
    /// or `dtach`), exported as `CROFT_SESSION_PERSISTENT`.
    pub(super) persistent: bool,
    /// True when launched by `croft remote` with remote self-update watching
    /// enabled (`CROFT_REMOTE_AUTOUPDATE`).
    pub(super) remote_autoupdate: bool,
    /// True when release-availability checks are disabled
    /// (`CROFT_NO_UPDATE_CHECK`).
    pub(super) no_update_check: bool,
}

impl HostSession {
    /// Read the session origin and capabilities from the process environment
    /// once at startup.
    pub(super) fn from_env() -> Self {
        let relay_key = if cfg!(test) {
            None
        } else {
            std::env::var("CROFT_RELAY_KEY")
                .ok()
                .filter(|s| !s.is_empty())
        };
        Self {
            is_remote: crate::remote::running_over_ssh(),
            relay_key,
            persistent: std::env::var_os("CROFT_SESSION_PERSISTENT").is_some(),
            remote_autoupdate: std::env::var_os("CROFT_REMOTE_AUTOUPDATE").is_some(),
            no_update_check: std::env::var_os("CROFT_NO_UPDATE_CHECK").is_some(),
        }
    }

    /// Whether this session uses the remote relay for clipboard copies and
    /// pastes (opted into via `relay_key`).
    pub(super) fn is_relay_session(&self) -> bool {
        self.relay_key.is_some()
    }

    /// Active relay id: the startup-resolved `relay_key`, or in tests the
    /// thread-serialized `CROFT_RELAY_KEY` used by `with_relay_home`.
    pub(super) fn effective_relay_key(&self) -> Option<std::borrow::Cow<'_, str>> {
        if let Some(id) = self.relay_key.as_deref() {
            return Some(std::borrow::Cow::Borrowed(id));
        }
        #[cfg(test)]
        {
            std::env::var("CROFT_RELAY_KEY")
                .ok()
                .filter(|s| !s.is_empty())
                .map(std::borrow::Cow::Owned)
        }
        #[cfg(not(test))]
        {
            None
        }
    }

    /// `$HOME/.cache/croft/relay-<CROFT_RELAY_KEY>/` on this remote box, or
    /// `None` when no relay is attached.
    pub(super) fn relay_dir(&self) -> Option<PathBuf> {
        let id = self.effective_relay_key()?;
        Some(croft_cache_dir().join(format!("relay-{id}")))
    }
}

impl App {
    pub(super) fn render_local_open_confirm(&self, frame: &mut ratatui::Frame) {
        let Some(url) = &self.pending_local_open else {
            return;
        };
        let frame_spec = ConfirmFrame {
            title: " OPEN ON LOCAL MAC? ",
            accent: self.theme.ui(Color::Rgb(0xff, 0xa5, 0x00)),
            title_fg: Color::Black,
            height: 8,
            inset: Inset::Wide,
        };
        draw_confirm(frame, self.theme, frame_spec, |frame, inner| {
            let green = Style::default()
                .fg(Color::Green)
                .add_modifier(Modifier::BOLD);
            let body = ratatui::text::Text::from(vec![
                ratatui::text::Line::from(ratatui::text::Span::styled(
                    "This URL will open in YOUR LOCAL MAC's browser via the croft relay.",
                    Style::default().fg(self.theme.ui(Color::White)),
                )),
                ratatui::text::Line::from(""),
                ratatui::text::Line::from(ratatui::text::Span::styled(
                    truncate_for_display(url, inner.width as usize),
                    Style::default().fg(self.theme.ui(Color::Rgb(0x4e, 0x9a, 0xff))),
                )),
                ratatui::text::Line::from(""),
                ratatui::text::Line::from(vec![
                    ratatui::text::Span::styled("[Y]", green),
                    ratatui::text::Span::raw("es once   "),
                    ratatui::text::Span::styled("[A]", green),
                    ratatui::text::Span::raw("lways for this session   "),
                    ratatui::text::Span::styled(
                        "[N]",
                        Style::default().fg(Color::Red).add_modifier(Modifier::BOLD),
                    ),
                    ratatui::text::Span::raw("o / Esc"),
                ]),
            ]);
            frame.render_widget(ratatui::widgets::Paragraph::new(body), inner);
        });
    }

    pub(super) fn handle_remote_key(&mut self, key: KeyEvent) {
        let has_mod = key
            .modifiers
            .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SUPER);
        match key.code {
            KeyCode::Up => self.remote.move_up(),
            KeyCode::Down => self.remote.move_down(),
            KeyCode::PageUp => self.remote.scroll_up(10),
            KeyCode::PageDown => self.remote.scroll_down(10),
            KeyCode::Left if !self.remote.filter.is_empty() => {
                self.remote.move_filter_caret(|t, c| {
                    crate::widgets::line_edit::caret_left(t, c, key_walks_by_word(key))
                })
            }
            KeyCode::Right if !self.remote.filter.is_empty() => {
                self.remote.move_filter_caret(|t, c| {
                    crate::widgets::line_edit::caret_right(t, c, key_walks_by_word(key))
                })
            }
            KeyCode::Home if !self.remote.filter.is_empty() => {
                self.remote.move_filter_caret(|_, _| 0)
            }
            KeyCode::End if !self.remote.filter.is_empty() => self
                .remote
                .move_filter_caret(|t, _| crate::widgets::line_edit::char_len(t)),
            KeyCode::Delete if !self.remote.filter.is_empty() => {
                self.remote.delete_filter(key_walks_by_word(key));
            }
            KeyCode::Backspace if !self.remote.filter.is_empty() => {
                self.remote.backspace_filter(key_walks_by_word(key));
            }
            KeyCode::Char(' ') if has_mod => {}
            KeyCode::Char(c) if !has_mod => {
                self.remote.push_filter_char(c);
            }
            KeyCode::Enter => {
                if let Some(target) = self.remote.selected_target().cloned() {
                    self.request_remote_launch(target.alias, None);
                }
            }
            KeyCode::Esc if !self.remote.clear_filter() => {
                self.set_sidebar_view(SidebarView::Explorer);
            }
            _ => {}
        }
    }

    /// Remote: Sync Config Now (#262): run `croft sync-config <host>` in a
    /// terminal pane, where ssh can ask for a password and the report of
    /// what was pushed, kept or left for the user to settle stays readable.
    pub(super) fn sync_config_to(&mut self, host: &str) {
        let host = host.trim();
        // Typed into a shell below: an alias is plain, so anything else is
        // refused rather than quoted.
        let plain = !host.is_empty()
            && !host.starts_with('-')
            && host
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || "._@-".contains(c));
        if !plain {
            self.status = format!("{host:?} is not an ssh host alias");
            return;
        }
        let exe = std::env::current_exe()
            .map(|p| p.display().to_string())
            .unwrap_or_else(|_| String::from("croft"));
        match crate::widgets::terminal::PtyTerminal::new(self.roots.primary()) {
            Ok(mut term) => {
                term.set_manual_name(Some(format!("config sync: {host}")));
                term.write_input(
                    format!(
                        "{} sync-config {host}\r",
                        crate::remote::shell_quote_for_e_arg(std::path::Path::new(&exe))
                    )
                    .as_bytes(),
                );
                self.insert_terminal(term);
                self.show_terminal = true;
                self.focus_pane(Pane::Terminal);
                self.status = format!("Syncing config to {host}");
            }
            Err(e) => self.status = format!("Could not open a terminal: {e}"),
        }
    }

    /// Housekeeping for the ssh-pane offer (#364), from the top of `render`
    /// like `dress_host_accents`: an offer nobody took or dismissed clears
    /// itself after [`SSH_OFFER_TTL`], and a pane that closed takes its offer
    /// and its per-pane memory along. No system calls: the sampling itself
    /// rides the label thread (see `refresh_terminal_labels`).
    pub(super) fn expire_ssh_offer(&mut self) {
        let now = std::time::Instant::now();
        if self
            .ssh_offer
            .as_ref()
            .is_some_and(|o| now.duration_since(o.since) > SSH_OFFER_TTL)
        {
            self.dismiss_ssh_offer();
        }
        let live: std::collections::BTreeSet<u64> =
            self.terminals.iter().map(|t| t.uid()).collect();
        self.ssh_offer_seen.retain(|uid, _| live.contains(uid));
        if self
            .ssh_offer
            .as_ref()
            .is_some_and(|o| !live.contains(&o.pane))
        {
            self.dismiss_ssh_offer();
        }
    }

    /// Fold the label thread's ssh samples into the offer state (#364):
    /// each `(shell pid, host)` names the pane by its shell and goes through
    /// `consider_ssh_offer` keyed on the pane's uid.
    pub(super) fn apply_ssh_samples(&mut self, samples: Vec<(i32, Option<String>)>) {
        for (shell_pid, host) in samples {
            let Some(uid) = self
                .terminals
                .iter()
                .find(|t| t.shell_pid() == Some(shell_pid))
                .map(|t| t.uid())
            else {
                continue;
            };
            self.consider_ssh_offer(uid, host);
        }
    }

    /// One pane's sampled ssh host, against what it was last seen connected
    /// to (#364). A session is offered when it STARTS: the same host on the
    /// next sample is the same session, not a new reason to prompt. `None`
    /// ends the session; an offer for that pane goes with it.
    pub(super) fn consider_ssh_offer(&mut self, pane: u64, host: Option<String>) {
        let previous = self.ssh_offer_seen.insert(pane, host.clone()).flatten();
        match host {
            None => {
                if self.ssh_offer.as_ref().is_some_and(|o| o.pane == pane) {
                    self.dismiss_ssh_offer();
                }
            }
            Some(host) => {
                if previous.as_deref() == Some(host.as_str()) {
                    return;
                }
                // The pane moved to another host: whatever it was offered
                // for is no longer where it is, offerable or not.
                if self.ssh_offer.as_ref().is_some_and(|o| o.pane == pane) {
                    self.dismiss_ssh_offer();
                }
                if !crate::remote::offer_allowed(
                    &host,
                    self.remote_offer_disabled,
                    &self.remote_offer_excluded,
                    &self.remote_offer_refused,
                    std::time::SystemTime::now(),
                ) {
                    return;
                }
                self.status =
                    format!("Connected to {host} · Open workspace here? (Cmd+K G, Esc dismisses)");
                let cwd_at_offer = self.pane_cwd_report(pane);
                self.ssh_offer = Some(SshOffer {
                    pane,
                    host,
                    since: std::time::Instant::now(),
                    cwd_at_offer,
                });
            }
        }
    }

    /// The pane's last OSC 7 report: its shell's directory and host.
    pub(super) fn pane_cwd_report(&self, pane: u64) -> Option<crate::remote::CwdReport> {
        let term = self.terminals.iter().find(|t| t.uid() == pane)?;
        Some((term.shell_cwd()?, term.shell_host()))
    }

    /// Take the open offer for launching (#364), clearing it: the host, and
    /// the remote shell's directory when the pane reported one that can be
    /// trusted to be on that host (see `remote::remote_workspace_path`).
    pub(super) fn accept_ssh_offer(&mut self) -> Option<(String, Option<String>)> {
        let offer = self.ssh_offer.take()?;
        if self.status.starts_with("Connected to ") {
            self.status.clear();
        }
        let now = self.pane_cwd_report(offer.pane);
        let path = crate::remote::remote_workspace_path(
            &offer.host,
            offer.cwd_at_offer.as_ref(),
            now.as_ref(),
        );
        Some((offer.host, path))
    }

    /// Remember that provisioning `host` failed (#364): the ssh-pane offer
    /// stops prompting for it for `REFUSED_HOST_TTL`. Recorded for any
    /// install that fails, offer-launched or not, because the fact learned
    /// is about the host; and undone by the next success (below), so a box
    /// that merely failed on a bad day is offered again once it works.
    pub(super) fn note_provisioning_failed(&mut self, host: &str, detail: &str) {
        crate::output::push(
            crate::output::CHANNEL_REMOTE,
            crate::output::OutputLevel::Error,
            &format!("Could not install croft on {host}: {detail}"),
        );
        let key = host.to_ascii_lowercase();
        let now = std::time::SystemTime::now();
        self.remote_offer_refused.insert(key.clone(), now);
        let _ = crate::remote::remember_refused_host(
            &crate::remote::refused_hosts_path(&croft_cache_dir()),
            &key,
            now,
        );
    }

    /// A provisioning of `host` succeeded (#364): any remembered refusal is
    /// stale, in memory and on disk. The disk side runs unconditionally:
    /// the file is shared by every croft on the machine, so another
    /// instance may have recorded a refusal this one never loaded, and
    /// `forget_refused_host` is a no-op when there is nothing to forget.
    pub(super) fn note_provisioning_succeeded(&mut self, host: &str) {
        crate::output::push(
            crate::output::CHANNEL_REMOTE,
            crate::output::OutputLevel::Info,
            &format!("croft is installed on {host}; launching the remote workspace"),
        );
        let key = host.to_ascii_lowercase();
        self.remote_offer_refused.remove(&key);
        let _ = crate::remote::forget_refused_host(
            &crate::remote::refused_hosts_path(&croft_cache_dir()),
            &key,
        );
    }

    /// Drop the open offer and its status line, if any (#364).
    pub(super) fn dismiss_ssh_offer(&mut self) {
        if self.ssh_offer.take().is_some() && self.status.starts_with("Connected to ") {
            self.status.clear();
        }
    }

    pub(super) fn request_remote_launch(&mut self, host: String, path: Option<String>) {
        // The launch ends this croft once the remote one is up (#862).
        self.guard_unsaved(UnsavedExit::RemoteLaunch { host, path });
    }

    pub(super) fn start_remote_launch(&mut self, host: String, path: Option<String>) {
        self.status = format!("Connecting to {host}");
        match crate::remote_connect::SshAuth::start(&host) {
            Ok(auth) => {
                self.connect_auth = Some(auth);
                self.connect_dialog = Some(crate::widgets::connect_dialog::ConnectDialog::new(
                    host.clone(),
                ));
                self.pending_remote_launch_path = path;
                self.pending_remote_launch_host = Some(host);
                self.overlays.welcome.request_clear();
            }
            Err(e) => {
                self.status = format!("Could not start ssh: {e}");
            }
        }
    }

    /// Re-root the workspace onto the host the active pane is ssh'd into
    /// (#364).
    ///
    /// Reads the pane's foreground argv rather than its scrollback: what the
    /// user typed may have scrolled away, been edited, or never been typed at
    /// all (a shell function, a `Host` alias resolved by ssh itself), while
    /// argv is what is actually running.
    ///
    /// The foreground PROCESS GROUP LEADER is what identifies the session,
    /// and it is right for the case that matters: `ssh box` typed at a
    /// prompt is its own group leader. A PIPELINE is the limit — `ssh box |
    /// tee log` makes the whole pipeline one group whose leader is not
    /// necessarily the ssh, so the command reports "not an SSH session"
    /// rather than guessing. Measured rather than assumed: on zsh the leader
    /// resolves to the LAST stage. Refusing is the right failure here, since
    /// the alternative is walking the process tree to find an ssh somewhere
    /// under the pane and offering to re-root onto a host the user piped
    /// output from rather than one they are working on.
    ///
    /// Explicit in the first slice, deliberately: the automatic status-bar
    /// offer needed a per-host opt-out, a memory of hosts that refused
    /// provisioning and a decision about how often to prompt, none of which
    /// belonged alongside the detection itself. Those exist now (the second
    /// slice: `consider_ssh_offer` and its gates), and the offer accepts
    /// through the same `request_remote_launch` this command reaches for.
    pub(super) fn open_workspace_on_ssh_host(&mut self) {
        let Some(term) = self.terminals.get(self.active_terminal) else {
            self.status = String::from("No terminal pane is open");
            return;
        };
        let Some(fg) = term.foreground_pid() else {
            self.status = String::from("This pane is not running anything");
            return;
        };
        let Some(cmd) = crate::proc::info::process_cmdline(fg) else {
            self.status = String::from("Could not read what this pane is running");
            return;
        };
        let argv: Vec<&str> = cmd.iter().map(String::as_str).collect();
        let targets = crate::remote::discover_ssh_targets();
        match crate::remote::ssh_reroot_decision(&argv, &targets) {
            Ok(host) => {
                let alias = host.alias.clone();
                // The far side's OSC 7 report opens the workspace where the
                // remote shell is. With no earlier report to tell a fresh one
                // from a stale one, it is trusted only when it names this
                // host; otherwise the login directory, as before.
                let uid = self.terminals[self.active_terminal].uid();
                let report = self.pane_cwd_report(uid);
                let path =
                    crate::remote::remote_workspace_path(&alias, report.as_ref(), report.as_ref());
                self.request_remote_launch(alias, path);
            }
            // The message distinguishes "not ssh" from "ssh to a box croft
            // has no config entry for": the second names the host, because
            // adding it to ~/.ssh/config is the action available.
            Err(why) => self.status = why,
        }
    }

    pub fn poll_connect_dialog(&mut self) -> bool {
        let Some(auth) = self.connect_auth.as_mut() else {
            return false;
        };
        let events = auth.drain_events();
        if events.is_empty() {
            return false;
        }
        let Some(dialog) = self.connect_dialog.as_mut() else {
            return false;
        };
        let mut authenticated = false;
        let mut failed: Option<String> = None;
        for ev in events {
            match ev {
                crate::remote_connect::SshAuthEvent::Log(chunk) => {
                    dialog.push_log(&chunk);
                }
                crate::remote_connect::SshAuthEvent::Prompt { kind, line } => {
                    dialog.set_prompt(kind, line);
                }
                crate::remote_connect::SshAuthEvent::Authenticated => {
                    dialog.set_installing();
                    authenticated = true;
                }
                crate::remote_connect::SshAuthEvent::Failed(detail) => {
                    failed = Some(detail);
                }
            }
        }
        if let Some(detail) = failed {
            dialog.set_failed(detail);
            self.tear_down_connect_auth();
        }
        if authenticated
            && let (Some(auth), Some(host)) = (
                self.connect_auth.take(),
                self.pending_remote_launch_host.take(),
            )
        {
            let adopted = auth.hand_off();
            let path = self.pending_remote_launch_path.take();
            let session =
                match crate::install_session::InstallSession::start(adopted, host.clone(), path) {
                    Ok(session) => session,
                    // No thread could start: the connect ends here, failed,
                    // as an install that failed at once would.
                    Err(e) => {
                        let detail = format!("croft could not start the install: {e}");
                        if let Some(dialog) = self.connect_dialog.as_mut() {
                            dialog.set_failed(detail.clone());
                        }
                        self.tear_down_connect_auth();
                        self.status = format!("Remote install failed: {detail}");
                        return true;
                    }
                };
            self.install_session = Some(session);
            crate::output::push(
                crate::output::CHANNEL_REMOTE,
                crate::output::OutputLevel::Info,
                &format!(
                    "Preparing croft on {host}: checking for an install, provisioning if missing"
                ),
            );
            self.status = format!("Preparing remote croft on {host}");
        }
        true
    }

    pub fn poll_install_session(&mut self) -> bool {
        let Some(session) = self.install_session.as_mut() else {
            return false;
        };
        let events = session.drain_events();
        let mut changed = !events.is_empty();
        let mut can_launch = false;
        let mut done = false;
        let mut failure: Option<String> = None;
        for ev in events {
            match ev {
                crate::install_session::InstallEvent::Log(line) => {
                    if let Some(dialog) = self.connect_dialog.as_mut() {
                        dialog.push_log(&line);
                    }
                }
                crate::install_session::InstallEvent::CanLaunch => can_launch = true,
                crate::install_session::InstallEvent::FallbackPrompt { reason } => {
                    if let Some(dialog) = self.connect_dialog.as_mut() {
                        // What a yes installs, shown before the answer (#950).
                        dialog.set_fallback_prompt(
                            &reason,
                            &crate::remote::REMOTE_COMPILE_SIDE_EFFECTS,
                        );
                    } else if let Some(session) = self.install_session.as_ref() {
                        // No dialog to ask through: decline so the installer
                        // errors out with the `croft setup-cross` guidance
                        // instead of blocking forever on an answer.
                        session.respond_fallback(false);
                    }
                }
                crate::install_session::InstallEvent::Done(Ok(())) => done = true,
                crate::install_session::InstallEvent::Done(Err(detail)) => {
                    failure = Some(detail);
                }
            }
        }
        // Once we've handed the terminal to the remote croft, the install
        // keeps running in a detached thread and signals completion to that
        // remote process via the install-stamp it watches; nothing here.
        if self.remote_launch.is_some() {
            return changed;
        }
        // A croft is already on the remote: drop the user into it now and
        // let the (re)install finish in the background. The running remote
        // croft re-execs into the new binary when the stamp advances.
        if can_launch {
            if let Some(session) = self.install_session.as_mut()
                && let Some(adopted) = session.take_adopted()
            {
                let launch = RemoteLaunch {
                    host: session.host.clone(),
                    path: session.path.clone(),
                    adopted: Some(adopted),
                };
                self.hand_off_to_remote(launch);
            }
            return true;
        }
        if let Some(detail) = failure {
            // Remember the host as one croft could not provision (#364), so
            // the ssh-pane offer stops prompting for it for a while. Kept
            // beside the failure it learns from, and best-effort: a write
            // that fails costs one repeated offer.
            if let Some(host) = self.install_session.as_ref().map(|s| s.host.clone()) {
                self.note_provisioning_failed(&host, &detail);
            }
            if let Some(dialog) = self.connect_dialog.as_mut() {
                dialog.set_failed(detail.clone());
            }
            // Nothing will run through the install's SSH connection now: close
            // it, as an install that could not start does, instead of leaving
            // it open until croft exits (#2610). An install that already let
            // the user into the remote croft never gets here.
            if let Some(adopted) = self
                .install_session
                .take()
                .and_then(|mut session| session.take_adopted())
            {
                crate::remote::close_master(adopted);
            }
            // An install whose thread crashed leaves the status line to the
            // crash notice, as every background job does (#2562); the dialog
            // says what happened to the connect.
            if detail != crate::install_session::CRASHED_DETAIL {
                self.status = format!("Remote install failed: {detail}");
            }
            changed = true;
        } else if done {
            if let Some(mut session) = self.install_session.take()
                && let Some(adopted) = session.take_adopted()
            {
                let launch = RemoteLaunch {
                    host: session.host.clone(),
                    path: session.path.clone(),
                    adopted: Some(adopted),
                };
                self.hand_off_to_remote(launch);
            }
            changed = true;
        }
        changed
    }

    /// The croft on the remote is ready: quit so the terminal goes to it
    /// (the main loop launches `launch` once this one has let go). The quit
    /// ends this croft, so edits made since the connect was asked for are
    /// asked about first (#862); what the user already chose to leave then
    /// goes without asking again.
    pub(super) fn hand_off_to_remote(&mut self, launch: RemoteLaunch) {
        let host = launch.host.clone();
        self.note_provisioning_succeeded(&host);
        self.remote_launch = Some(launch);
        self.status = format!("Launching croft on {host}");
        self.connect_dialog = None;
        let handoff = UnsavedExit::RemoteHandoff { host };
        let left_as_agreed = self
            .remote_handoff_ok
            .take()
            .is_some_and(|ok| Some(ok) == self.unsaved_stamp());
        if left_as_agreed {
            self.finish_unsaved_exit(handoff);
        } else {
            self.guard_unsaved(handoff);
        }
    }

    pub(super) fn tear_down_connect_auth(&mut self) {
        if let Some(mut auth) = self.connect_auth.take() {
            auth.cancel();
        }
        self.install_session = None;
        self.pending_remote_launch_host = None;
        self.pending_remote_launch_path = None;
        self.remote_handoff_ok = None;
    }

    pub fn handle_connect_dialog_key(&mut self, key: KeyEvent) {
        let Some(dialog) = self.connect_dialog.as_mut() else {
            return;
        };
        if dialog.phase.is_terminal() {
            if matches!(key.code, KeyCode::Esc | KeyCode::Enter | KeyCode::Char(' ')) {
                self.connect_dialog = None;
                self.tear_down_connect_auth();
            }
            return;
        }
        let has_mod = key
            .modifiers
            .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SUPER);
        match key.code {
            KeyCode::Esc => {
                self.connect_dialog = None;
                self.tear_down_connect_auth();
                self.status = String::from("Connect cancelled");
            }
            KeyCode::Enter => {
                if !dialog.phase.awaits_input() {
                    return;
                }
                if matches!(
                    dialog.phase,
                    crate::widgets::connect_dialog::DialogPhase::AwaitingFallbackConfirmation
                ) {
                    let payload = dialog.input_for_submit();
                    self.answer_install_fallback(&payload);
                    return;
                }
                let payload = dialog.input_for_submit();
                dialog.submitted = true;
                dialog.status_line = format!("Verifying credentials with {}", dialog.host);
                dialog.clear_input();
                if let Some(auth) = self.connect_auth.as_mut() {
                    auth.respond_to_prompt(&payload);
                }
            }
            KeyCode::Left => {
                let word = !dialog.input_is_secret() && key_walks_by_word(key);
                dialog.move_input_caret(|t, c| crate::widgets::line_edit::caret_left(t, c, word));
            }
            KeyCode::Right => {
                let word = !dialog.input_is_secret() && key_walks_by_word(key);
                dialog.move_input_caret(|t, c| crate::widgets::line_edit::caret_right(t, c, word));
            }
            KeyCode::Home => dialog.move_input_caret(|_, _| 0),
            KeyCode::End => dialog.move_input_caret(|t, _| crate::widgets::line_edit::char_len(t)),
            KeyCode::Delete => {
                let word = !dialog.input_is_secret() && key_walks_by_word(key);
                dialog.delete_input(word);
            }
            KeyCode::Backspace => {
                let word = !dialog.input_is_secret() && key_walks_by_word(key);
                dialog.backspace_input(word);
            }
            KeyCode::Char('l') | KeyCode::Char('L') if has_mod || !dialog.phase.awaits_input() => {
                dialog.toggle_logs();
            }
            KeyCode::Char(c) if !has_mod => dialog.push_input_char(c),
            _ => {}
        }
    }

    pub fn handle_connect_dialog_click(&mut self, col: u16, row: u16) -> bool {
        let Some(dialog) = self.connect_dialog.as_mut() else {
            return false;
        };
        if rect_contains(dialog.toggle_logs_btn, col, row) {
            dialog.toggle_logs();
            return true;
        }
        if rect_contains(dialog.cancel_btn, col, row) {
            self.connect_dialog = None;
            self.tear_down_connect_auth();
            self.status = String::from("Connect cancelled");
            return true;
        }
        if rect_contains(dialog.submit_btn, col, row) && dialog.phase.awaits_input() {
            if matches!(
                dialog.phase,
                crate::widgets::connect_dialog::DialogPhase::AwaitingFallbackConfirmation
            ) {
                let payload = dialog.input_for_submit();
                self.answer_install_fallback(&payload);
                return true;
            }
            let payload = dialog.input_for_submit();
            dialog.submitted = true;
            dialog.status_line = format!(
                "Sending {} chars to {}",
                payload.chars().count(),
                dialog.host
            );
            dialog.clear_input();
            if let Some(auth) = self.connect_auth.as_mut() {
                auth.respond_to_prompt(&payload);
            }
            return true;
        }
        rect_contains(dialog.last_area, col, row)
    }

    /// Resolve the connect dialog's slow-fallback question. "y"/"yes"
    /// continues with the compile-on-remote install; anything else aborts
    /// the connect so the user can run `croft setup-cross` and reconnect
    /// for the seconds-fast prebuilt-binary path.
    pub(super) fn answer_install_fallback(&mut self, payload: &str) {
        let proceed = matches!(payload.trim().to_ascii_lowercase().as_str(), "y" | "yes");
        if proceed {
            if let Some(dialog) = self.connect_dialog.as_mut() {
                // What a yes installs must have been on screen (#950): a
                // window too short to show it all keeps the question open.
                if !dialog.notes.is_empty() && !dialog.notes_shown {
                    dialog.error = Some(String::from(
                        "Make the window taller to read what a remote compile installs, then answer",
                    ));
                    // Emptied, so the y typed again once it fits is a yes,
                    // not "yy".
                    dialog.clear_input();
                    return;
                }
                dialog.set_installing();
            }
            if let Some(session) = self.install_session.as_ref() {
                session.respond_fallback(true);
            }
            return;
        }
        if let Some(session) = self.install_session.as_ref() {
            session.respond_fallback(false);
        }
        self.connect_dialog = None;
        self.tear_down_connect_auth();
        self.status = String::from(
            "Connect cancelled — run `croft setup-cross`, then reconnect for a fast install",
        );
    }

    pub(super) fn open_ssh_config_in_editor(&mut self) {
        let Some(path) = crate::remote::primary_ssh_config_path() else {
            self.status = String::from("Cannot find $HOME/.ssh/config");
            return;
        };
        if let Some(parent) = path.parent() {
            let _ = std::fs::create_dir_all(parent);
        }
        if !path.exists()
            && let Err(e) = std::fs::write(&path, "")
        {
            self.status = format!("Could not create {}: {e}", path.display());
            return;
        }
        match self.editor.open_pinned(&path) {
            Ok(()) => {
                self.focus_pane(Pane::Editor);
                self.status = format!("Opened {}", self.status_path(&path));
            }
            Err(e) => {
                self.status = format!("Open {} failed: {e}", self.status_path(&path));
            }
        }
    }

    /// Single web-URL opener for every link path in `src/app/` (terminal
    /// hyperlinks, LSP document links and `window/showDocument`, Markdown /
    /// PDF external links, and UI help links).
    ///
    /// Enforces one validation and transport rule everywhere:
    /// 1. Trim surrounding whitespace, reject control characters, and admit
    ///    only `http://` and `https://` schemes.
    /// 2. When the remote drop relay is active, forward loopback URLs home or
    ///    ask the local machine to open the URL (honouring
    ///    `trust_local_browser`).
    /// 3. On a plain-SSH remote session without a relay, refuse rather than
    ///    launching a headless browser on the remote host.
    /// 4. Locally, open via the platform launcher (or stay inert under
    ///    `cfg!(test)` when `opts.inert_in_tests` is set).
    ///
    /// Returns `true` when the URL was accepted for opening or queued for
    /// relay confirmation, and `false` on refusal or local launch error.
    pub(in crate::app) fn open_web_url(&mut self, url: &str, opts: WebOpenOpts) -> bool {
        let trimmed = url.trim();
        if trimmed.chars().any(char::is_control) {
            self.status = format!("Refused to open malformed link: {trimmed:?}");
            return false;
        }
        let lower = trimmed.to_ascii_lowercase();
        if !lower.starts_with("http://") && !lower.starts_with("https://") {
            self.status = format!("Refused to open non-web link: {trimmed}");
            return false;
        }
        // Under `cfg!(test)`, `with_relay_home` sets the process-wide
        // `CROFT_RELAY_KEY` env var (also used by non-remote tests purely to
        // isolate `croft_cache_dir`). For `inert_in_tests` callers
        // (`try_open_url_for_user`), route through the relay only when this
        // `App` itself is remote or explicitly opted into a relay, so local
        // tests are never hijacked by an ambient `CROFT_RELAY_KEY`.
        let use_relay = if opts.inert_in_tests && cfg!(test) {
            (self.session.is_remote || self.session.is_relay_session()) && self.drop_relay_active()
        } else {
            self.drop_relay_active()
        };
        if use_relay {
            if let Some(target) = crate::port_detect::loopback_url_target(trimmed) {
                self.request_remote_forward_for_url(target, trimmed);
            } else if self.trust_local_browser {
                self.request_remote_url_open(trimmed.to_string());
                let label = opts.relay_label.unwrap_or(trimmed);
                self.status = format!("Opening {label} on your local Mac");
            } else {
                self.pending_local_open = Some(trimmed.to_string());
            }
            return true;
        }
        if self.session.is_remote {
            self.status = format!("Running remotely without a browser relay: {trimmed}");
            return false;
        }
        if opts.inert_in_tests && cfg!(test) {
            // Tests never start a browser.
            self.status = format!("Open {trimmed}");
            return true;
        }
        match open_url(trimmed) {
            Ok(()) => {
                self.status = match opts.local_opened_status {
                    Some(status) => status.to_string(),
                    None => format!("Opened {trimmed}"),
                };
                true
            }
            Err(e) => {
                self.status = format!("Could not open {trimmed}: {e}");
                false
            }
        }
    }

    pub(super) fn open_ssh_learn_more(&mut self) {
        self.open_web_url(
            "https://man.openbsd.org/ssh_config",
            WebOpenOpts {
                relay_label: Some("ssh_config(5)"),
                local_opened_status: Some("Opened ssh_config(5) docs"),
                inert_in_tests: false,
            },
        );
    }

    pub(super) fn refresh_remote_if_config_changed(&mut self) -> bool {
        if self.sidebar_view != SidebarView::Remote {
            return false;
        }
        if !self.remote.refresh_if_config_changed() {
            return false;
        }
        self.status = String::from("Reloaded SSH remotes");
        true
    }

    /// Queue every dropped path for an interactive SCP upload to the
    /// currently selected SSH target. The actual scp invocation happens
    /// in `main_loop` after suspending the alt-screen, so scp inherits
    /// the host shell's stdin / stdout / stderr — that means password
    /// prompts, FIDO touch requests, and host-key confirmations all work
    /// the way the user expects, and the user sees scp's progress and
    /// errors directly. After all uploads finish (success or failure),
    /// croft prompts for Enter and resumes the TUI.
    pub(super) fn import_paths_into_remote(&mut self, paths: &[PathBuf]) {
        let Some(target) = self.remote.selected_target().cloned() else {
            self.status = String::from("Drop ignored: no Remote Explorer host selected");
            return;
        };
        if paths.is_empty() {
            return;
        }
        for src in paths {
            self.pending_scp_uploads.push(ScpUpload {
                alias: target.alias.clone(),
                src: src.clone(),
            });
        }
        self.status = format!(
            "Queued {} item(s) for scp copy to {} (you'll see scp's prompts next)",
            paths.len(),
            target.alias,
        );
    }

    pub fn take_pending_scp_uploads(&mut self) -> Vec<ScpUpload> {
        std::mem::take(&mut self.pending_scp_uploads)
    }

    /// True when this croft is a remote-launched session whose local parent is
    /// running a drop pump. Gated on `CROFT_RELAY_KEY`, set only by a `croft
    /// remote` launch command. The key is the deterministic `hash(launch arg)`
    /// shared with the local pump; because it's deterministic, dtach freezing it
    /// at first launch is harmless — every reconnect recomputes the same value,
    /// so the running croft and a fresh pump always agree on one relay dir. A
    /// session predating this var (an old long-lived dtach session) simply has
    /// no key and reports the relay unavailable rather than timing out.
    pub(super) fn drop_relay_active(&self) -> bool {
        self.session.effective_relay_key().is_some()
    }

    /// `$HOME/.cache/croft/relay-<CROFT_RELAY_KEY>/` on this remote box. The key
    /// is `hash(launch arg)` — the same id the dtach socket uses — computed by
    /// the local launcher and the local pump and carried here in env. Keying on
    /// the launch identity (not `workspace_root`) keeps the rendezvous stable
    /// across an in-session workspace change and the updater's self-re-exec,
    /// both of which move `workspace_root` away from where the pump's `pwd`
    /// lands.
    /// `None` when no `CROFT_RELAY_KEY` is set (not a relay-capable session).
    pub(super) fn relay_dir(&self) -> Option<PathBuf> {
        self.session.relay_dir()
    }

    pub(super) fn relay_log_path(&self) -> Option<PathBuf> {
        self.relay_dir().map(|d| d.join("requests.log"))
    }

    pub(super) fn relay_inbox_path(&self) -> Option<PathBuf> {
        self.relay_dir().map(|d| d.join("inbox"))
    }

    /// Ensure the relay dir + inbox exist before writing a request. On the first
    /// drop after a dtach reattach (or on a fresh box) the local pump's
    /// `tail -F` may have started against a path this croft hadn't created yet;
    /// `tail -F` retries, so a lazy mkdir here is enough. Idempotent and cheap.
    pub(super) fn ensure_relay_dir(&self) {
        if let Some(inbox) = self.relay_inbox_path() {
            let _ = std::fs::create_dir_all(inbox);
        }
    }

    pub(super) fn request_remote_pulls(&mut self, paths: &[PathBuf]) {
        let dest_dir = self.paste_target_dir();
        let Some(log_path) = self.relay_log_path() else {
            self.status = String::from("Drop relay not available on this remote session");
            return;
        };
        self.ensure_relay_dir();
        let mut lines = String::new();
        let mut staged: Vec<PendingRemotePull> = Vec::new();
        let now = std::time::Instant::now();
        for src in paths {
            let request_id = Self::relay_request_id("pull");
            let basename = src
                .file_name()
                .map(|s| s.to_string_lossy().into_owned())
                .unwrap_or_else(|| String::from("dropped"));
            lines.push_str("pull\t");
            lines.push_str(&request_id);
            lines.push('\t');
            lines.push_str(&src.to_string_lossy());
            lines.push('\n');
            staged.push(PendingRemotePull {
                request_id,
                src_display: src.to_string_lossy().into_owned(),
                basename,
                dest_dir: dest_dir.clone(),
                started_at: now,
                kind: RemotePullKind::File,
                open_after_forward: None,
                remote_ipv6: false,
            });
        }
        match append_to_relay_log(&log_path, &lines) {
            Ok(()) => {
                self.status = format!(
                    "Fetching {} item(s) from your local Mac via croft relay",
                    staged.len(),
                );
                self.pending_remote_pulls.extend(staged);
            }
            Err(e) => {
                self.status = format!("Drop relay write failed: {e}");
            }
        }
    }

    /// Check the relay inbox for completed pulls and surface them in the
    /// explorer. Returns true if any pending pull resolved (success,
    /// failure, or timeout) so the main loop knows to redraw.
    pub fn drain_remote_pulls(&mut self) -> bool {
        if self.pending_remote_pulls.is_empty() {
            return false;
        }
        let Some(inbox) = self.relay_inbox_path() else {
            self.pending_remote_pulls.clear();
            self.status = String::from("Drop relay vanished mid-pull");
            return true;
        };
        let mut still_pending: Vec<PendingRemotePull> = Vec::new();
        let mut placed: Vec<PathBuf> = Vec::new();
        let mut opened_urls: Vec<String> = Vec::new();
        let mut forwarded: Vec<(u16, bool, u16)> = Vec::new();
        let mut deferred_opens: Vec<String> = Vec::new();
        let mut errors: Vec<String> = Vec::new();
        let mut affected: BTreeSet<PathBuf> = BTreeSet::new();
        let pulls = std::mem::take(&mut self.pending_remote_pulls);
        let mut clipboard_payloads: Vec<(Option<u64>, Vec<u8>)> = Vec::new();
        for pull in pulls {
            let request_dir = inbox.join(&pull.request_id);
            let ok = request_dir.join(".ok");
            let err = request_dir.join(".err");
            if ok.exists() {
                match pull.kind {
                    RemotePullKind::File => {
                        let staged_src = request_dir.join(&pull.basename);
                        affected.insert(pull.dest_dir.clone());
                        match crate::widgets::file_tree::move_into(&pull.dest_dir, &staged_src) {
                            Ok(p) => placed.push(p),
                            Err(e) => errors.push(format!("{}: {e}", pull.src_display)),
                        }
                    }
                    RemotePullKind::Clipboard { terminal_uid } => {
                        let staged = request_dir.join("clipboard.txt");
                        match std::fs::read(&staged) {
                            Ok(bytes) => clipboard_payloads.push((terminal_uid, bytes)),
                            Err(e) => errors.push(format!("clipboard relay: {e}")),
                        }
                    }
                    RemotePullKind::Open => {
                        opened_urls.push(pull.src_display.clone());
                    }
                    RemotePullKind::Forward { remote_port } => {
                        let local_port = std::fs::read_to_string(&ok)
                            .ok()
                            .and_then(|s| s.trim().parse::<u16>().ok())
                            .unwrap_or(remote_port);
                        forwarded.push((remote_port, pull.remote_ipv6, local_port));
                        if let Some(orig_url) = pull.open_after_forward {
                            deferred_opens.push(rewrite_loopback_url(&orig_url, local_port));
                        }
                    }
                }
                let _ = std::fs::remove_dir_all(&request_dir);
            } else if err.exists() {
                let msg =
                    std::fs::read_to_string(&err).unwrap_or_else(|_| String::from("relay error"));
                errors.push(format!("{}: {}", pull.src_display, msg.trim()));
                let _ = std::fs::remove_dir_all(&request_dir);
            } else if pull.started_at.elapsed() > REMOTE_PULL_TIMEOUT {
                errors.push(format!("{}: timed out after 120s", pull.src_display));
                let _ = std::fs::remove_dir_all(&request_dir);
            } else {
                still_pending.push(pull);
            }
        }
        let resolved_any = !placed.is_empty()
            || !opened_urls.is_empty()
            || !forwarded.is_empty()
            || !errors.is_empty();
        let port_origin = self.port_origin();
        for (remote_port, remote_ipv6, local_port) in &forwarded {
            self.ports.record_forwarded(
                *remote_port,
                *remote_ipv6,
                *local_port,
                port_origin.clone(),
            );
        }
        self.pending_remote_pulls = still_pending;
        for dir in &affected {
            if let Some(idx) = self.tree.index_of_dir(dir) {
                self.tree.refresh_children(idx);
            }
        }
        if !placed.is_empty() {
            self.tree.marked.clear();
            for p in &placed {
                self.tree.marked.insert(p.clone());
            }
            if let Some(first) = placed.first()
                && let Some(idx) = self.tree.nodes.iter().position(|n| &n.path == first)
            {
                self.tree.selected = idx;
                self.tree.anchor = idx;
            }
        }
        if resolved_any {
            self.status = if errors.is_empty() {
                if !forwarded.is_empty() && placed.is_empty() && opened_urls.is_empty() {
                    let (remote, _, local) = forwarded[0];
                    if local == remote {
                        format!("Forwarded port {remote} to your machine")
                    } else {
                        format!("Forwarded remote port {remote} to local {local}")
                    }
                } else if !opened_urls.is_empty() && placed.is_empty() {
                    if opened_urls.len() == 1 {
                        format!("Opened {} in your local browser", opened_urls[0])
                    } else {
                        format!("Opened {} URL(s) in your local browser", opened_urls.len())
                    }
                } else if placed.len() == 1 {
                    format!("Pulled {} from your Mac", placed[0].display())
                } else {
                    format!("Pulled {} item(s) from your Mac", placed.len())
                }
            } else if placed.is_empty() && opened_urls.is_empty() {
                format!("Drop relay failed: {}", errors.join("; "))
            } else {
                format!(
                    "Pulled {} / opened {}; failures: {}",
                    placed.len(),
                    opened_urls.len(),
                    errors.join("; "),
                )
            };
        }
        for url in deferred_opens {
            self.request_remote_url_open(url);
        }
        let delivered_clipboard = !clipboard_payloads.is_empty();
        for (terminal_uid, bytes) in clipboard_payloads {
            if !bytes.is_empty() {
                self.paste_terminal_input_for_uid(terminal_uid, &bytes);
            }
        }
        resolved_any || delivered_clipboard
    }

    pub fn report_scp_results(
        &mut self,
        moved: usize,
        total: usize,
        errors: usize,
        affected_dirs: &[PathBuf],
    ) {
        for dir in affected_dirs {
            if let Some(idx) = self.tree.index_of_dir(dir) {
                self.tree.refresh_children(idx);
            }
        }
        self.status = if errors == 0 {
            format!("Uploaded {moved}/{total} via scp")
        } else {
            format!("Uploaded {moved}/{total} via scp; {errors} error(s)")
        };
    }

    /// Click on a port-detection toast button. Returns whether a button was hit
    /// (and the action taken); a click elsewhere returns false so it falls
    /// through to normal handling.
    pub(super) fn handle_port_toast_click(&mut self, x: u16, y: u16) -> bool {
        let Some(toast) = self.port_toast.as_ref() else {
            return false;
        };
        let Some(action) = toast
            .buttons
            .iter()
            .find(|(r, _)| rect_contains(*r, x, y))
            .map(|(_, a)| *a)
        else {
            return false;
        };
        let port = toast.port;
        self.port_toast = None;
        match action {
            PortToastAction::ForwardAndOpen => self.request_remote_forward(port, true),
            PortToastAction::ForwardOnly => self.request_remote_forward(port, false),
            PortToastAction::Open => match open_url(&format!("http://127.0.0.1:{port}/")) {
                Ok(()) => self.status = format!("Opened http://localhost:{port}/"),
                Err(e) => self.status = format!("Open failed: {e}"),
            },
            PortToastAction::Dismiss => {}
        }
        true
    }

    /// A relay request id: the kind, this process, and a per-process counter.
    /// The relay keys its remote inbox directory by this id, so two requests
    /// raised in the same instant must not share one — the first reply would
    /// satisfy both pending pulls and delete the directory out from under the
    /// second, which then times out with its tunnel already up.
    pub(super) fn relay_request_id(kind: &str) -> String {
        static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
        // A per-run nonce as well as the pid: claims outlive the process in
        // the relay dir, and a later croft reusing this pid (after a reboot,
        // in a container) would find every one of its ids already claimed.
        static NONCE: std::sync::OnceLock<u128> = std::sync::OnceLock::new();
        let nonce = NONCE.get_or_init(|| {
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map_or(0, |d| d.as_nanos())
        });
        let n = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        format!("{kind}-{}-{nonce:x}-{n}", std::process::id())
    }

    /// Ask the local launcher (via the drop relay) to forward IPv4 loopback
    /// `port` home over the live SSH master, optionally opening the local
    /// browser once it's up.
    pub(super) fn request_remote_forward(&mut self, port: u16, open: bool) {
        self.request_remote_forward_target(port, false, open);
    }

    /// Ask the local launcher (via the drop relay) to forward loopback `port`
    /// on `remote_ipv6` (`[::1]` when true, `127.0.0.1` when false) home over
    /// the live SSH master, optionally opening the local browser once it's up.
    pub(super) fn request_remote_forward_target(
        &mut self,
        port: u16,
        remote_ipv6: bool,
        open: bool,
    ) {
        // Forwarded already: reuse the tunnel. Asking again found the remote
        // port held locally by croft's own first tunnel and fell back to a
        // random one, so every click on the same link opened one more tunnel
        // and one more browser tab at a new 127.0.0.1 address (#648).
        if let Some(local) = self.ports.forwarded_local_port_for(port, remote_ipv6) {
            if open {
                self.request_remote_url_open(format!("http://127.0.0.1:{local}/"));
                self.status = format!("Opening port {port} (forwarded to {local})");
            } else {
                self.status = format!("Port {port} is already forwarded to {local}");
            }
            return;
        }
        // And one request per (port, family) at a time: a second click before
        // the first forward answered sent a duplicate.
        if self.pending_remote_pulls.iter().any(|p| {
            matches!(p.kind, RemotePullKind::Forward { remote_port } if remote_port == port)
                && p.remote_ipv6 == remote_ipv6
        }) {
            self.status = format!("Port {port} is already being forwarded");
            return;
        }
        let Some(log_path) = self.relay_log_path() else {
            self.status = String::from("Forward port: drop relay vanished");
            return;
        };
        self.ensure_relay_dir();
        let request_id = Self::relay_request_id("forward");
        let open_flag = u8::from(open);
        let line = if remote_ipv6 {
            format!("forward\t{request_id}\t{port}\t{open_flag}\t[::1]\n")
        } else {
            format!("forward\t{request_id}\t{port}\t{open_flag}\n")
        };
        match append_to_relay_log(&log_path, &line) {
            Ok(()) => {
                self.pending_remote_pulls.push(PendingRemotePull {
                    request_id,
                    src_display: format!("port {port}"),
                    basename: String::new(),
                    dest_dir: PathBuf::new(),
                    started_at: std::time::Instant::now(),
                    kind: RemotePullKind::Forward { remote_port: port },
                    open_after_forward: None,
                    remote_ipv6,
                });
                self.status = format!("Forwarding port {port}…");
            }
            Err(e) => self.status = format!("Forward port: relay write failed: {e}"),
        }
    }

    /// Forward remote loopback `target` (preserving IPv4 vs IPv6 `[::1]`) home
    /// and open `url` rewritten to the chosen local port
    /// (`127.0.0.1:<local_port>`), preserving the original scheme
    /// (`http`/`https`), path, query and fragment.
    pub(super) fn request_remote_forward_for_url(
        &mut self,
        target: crate::port_detect::LoopbackTarget,
        url: &str,
    ) {
        let port = target.port;
        if let Some(local) = self.ports.forwarded_local_port_for(port, target.ipv6) {
            let rewritten = rewrite_loopback_url(url, local);
            self.request_remote_url_open(rewritten);
            self.status = format!("Opening port {port} (forwarded to {local})");
            return;
        }
        if let Some(existing) = self.pending_remote_pulls.iter_mut().find(|p| {
            matches!(p.kind, RemotePullKind::Forward { remote_port } if remote_port == port)
                && p.remote_ipv6 == target.ipv6
        }) {
            existing.open_after_forward = Some(url.to_string());
            self.status = format!("Port {port} is already being forwarded");
            return;
        }
        let Some(log_path) = self.relay_log_path() else {
            self.status = String::from("Forward port: drop relay vanished");
            return;
        };
        self.ensure_relay_dir();
        let request_id = Self::relay_request_id("forward");
        // Establish the SSH forward without auto-opening `http://127.0.0.1:<local>/`:
        // `drain_remote_pulls` opens the full rewritten URL once the local port lands.
        let line = if target.ipv6 {
            format!("forward\t{request_id}\t{port}\t0\t[::1]\n")
        } else {
            format!("forward\t{request_id}\t{port}\t0\n")
        };
        match append_to_relay_log(&log_path, &line) {
            Ok(()) => {
                self.pending_remote_pulls.push(PendingRemotePull {
                    request_id,
                    src_display: format!("port {port}"),
                    basename: String::new(),
                    dest_dir: PathBuf::new(),
                    started_at: std::time::Instant::now(),
                    kind: RemotePullKind::Forward { remote_port: port },
                    open_after_forward: Some(url.to_string()),
                    remote_ipv6: target.ipv6,
                });
                self.status = format!("Forwarding port {port}…");
            }
            Err(e) => self.status = format!("Forward port: relay write failed: {e}"),
        }
    }

    /// Tear down a previously established forward. Fire and forget — the entry
    /// is already gone from the panel, so there's no completion to await.
    pub(super) fn request_remote_unforward(&mut self, local: u16, remote: u16, remote_ipv6: bool) {
        let Some(log_path) = self.relay_log_path() else {
            return;
        };
        self.ensure_relay_dir();
        let request_id = Self::relay_request_id("unforward");
        let line = if remote_ipv6 {
            format!("unforward\t{request_id}\t{local}\t{remote}\t[::1]\n")
        } else {
            format!("unforward\t{request_id}\t{local}\t{remote}\n")
        };
        let _ = append_to_relay_log(&log_path, &line);
    }

    pub(super) fn request_remote_url_open(&mut self, url: String) {
        let Some(log_path) = self.relay_log_path() else {
            self.status = String::from("Open link: drop relay vanished");
            return;
        };
        self.ensure_relay_dir();
        let request_id = Self::relay_request_id("open");
        let mut line = String::from("open\t");
        line.push_str(&request_id);
        line.push('\t');
        line.push_str(&url);
        line.push('\n');
        match append_to_relay_log(&log_path, &line) {
            Ok(()) => {
                self.pending_remote_pulls.push(PendingRemotePull {
                    request_id,
                    src_display: url,
                    basename: String::new(),
                    dest_dir: PathBuf::new(),
                    started_at: std::time::Instant::now(),
                    kind: RemotePullKind::Open,
                    open_after_forward: None,
                    remote_ipv6: false,
                });
            }
            Err(e) => {
                self.status = format!("Open link: relay write failed: {e}");
            }
        }
    }

    /// Handle a key while the local-browser confirmation modal is open.
    /// `Y`/`Enter` opens this URL once. `A` opens it AND remembers
    /// "always" for the rest of the session. `N`/`Esc` cancels.
    pub(super) fn handle_local_open_confirm_key(&mut self, key: KeyEvent) {
        let Some(url) = self.pending_local_open.clone() else {
            return;
        };
        match key.code {
            KeyCode::Char('y') | KeyCode::Char('Y') | KeyCode::Enter => {
                self.pending_local_open = None;
                self.request_remote_url_open(url.clone());
                self.status = format!("Opening {url} on your local Mac");
            }
            KeyCode::Char('a') | KeyCode::Char('A') => {
                self.pending_local_open = None;
                self.trust_local_browser = true;
                self.request_remote_url_open(url.clone());
                self.status = format!("Trusted local browser for this session. Opening {url}");
            }
            KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Esc => {
                self.pending_local_open = None;
                self.status = String::from("Open link cancelled");
            }
            _ => {}
        }
    }

    pub(super) fn render_connect_dialog(&mut self, frame: &mut ratatui::Frame) {
        let visible = self.cursor_visible_phase();
        let theme = self.theme;
        let Some(dialog) = self.connect_dialog.as_mut() else {
            return;
        };
        dialog.theme = theme;
        let area = frame.area();
        use ratatui::widgets::Widget as _;
        dialog.render(area, frame.buffer_mut());
        if visible && let Some((cx, cy)) = dialog.cursor_screen_pos() {
            frame.set_cursor_position((cx, cy));
        }
    }
}

/// One compiled per-host accent rule: hostname glob, accent color, badge.
pub(super) type HostAccent = (globset::GlobMatcher, (u8, u8, u8), Option<String>);

/// Compile the prefs' host-accent rules: glob matcher + color (danger red
/// when unset) + badge. A rule with an invalid glob is skipped.
pub(super) fn compile_host_accents(rules: &[crate::prefs::HostAccentRule]) -> Vec<HostAccent> {
    rules
        .iter()
        .filter_map(|r| {
            let m = globset::Glob::new(&r.pattern).ok()?.compile_matcher();
            let color = r
                .accent
                .as_deref()
                .and_then(crate::prefs::parse_hex)
                .unwrap_or((0xf1, 0x4c, 0x4c));
            Some((m, color, r.badge.clone()))
        })
        .collect()
}

pub(super) fn append_to_relay_log(log_path: &Path, payload: &str) -> std::io::Result<()> {
    use std::io::Write;
    let mut f = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(log_path)?;
    f.write_all(payload.as_bytes())?;
    f.sync_data().ok();
    Ok(())
}

/// Rewrite a loopback URL's host and port to `127.0.0.1:{local_port}`,
/// preserving its scheme (`http`/`https`), path, query and fragment.
pub(super) fn rewrite_loopback_url(url: &str, local_port: u16) -> String {
    if let Ok(mut parsed) = url::Url::parse(url)
        && parsed.set_host(Some("127.0.0.1")).is_ok()
        && parsed.set_port(Some(local_port)).is_ok()
    {
        return parsed.into();
    }
    format!("http://127.0.0.1:{local_port}/")
}

/// Status-line advisory for a remote croft session that will not survive an
/// SSH transport drop. `croft remote` launches the remote croft under dtach
/// and exports `CROFT_SESSION_PERSISTENT=1`; when that marker is absent on a
/// remote (SSH) session the host has no dtach, so croft tells the user how to
/// turn persistence on. Local sessions never see it. Returned as a status
/// string only (the bottom line is info-only; no input).
pub(super) fn remote_persistence_status(is_remote: bool, persistent: bool) -> Option<&'static str> {
    if is_remote && !persistent {
        Some("Persistence off: install dtach")
    } else {
        None
    }
}

/// How long an ssh-pane offer stays up untouched (#364) before it clears
/// itself: long enough to read and act on, short enough not to be stale
/// when the user next looks at the status bar.
pub(super) const SSH_OFFER_TTL: std::time::Duration = std::time::Duration::from_secs(90);

/// Suspend the alt-screen, run every queued scp upload with the host
/// shell's stdin / stdout / stderr inherited (so the user sees scp's
/// progress and can answer any prompt it raises), then prompt for Enter
/// and restore the alt-screen. The local source is removed only on a
/// successful upload — if scp fails, the local copy stays put so the
/// user can retry without losing data.
pub(super) fn run_pending_scp_uploads(app: &mut App, terminal: &mut CroftTerminal) -> Result<()> {
    use std::io::Write;
    let uploads = app.take_pending_scp_uploads();
    if uploads.is_empty() {
        return Ok(());
    }
    // Tear down the TUI surface so scp can use the real terminal.
    disable_raw_mode().ok();
    execute!(
        terminal.backend_mut(),
        LeaveAlternateScreen,
        DisableMouseCapture,
        DisableBracketedPaste,
        DisableFocusChange,
        crossterm::cursor::SetCursorStyle::DefaultUserShape,
    )
    .ok();
    terminal.show_cursor().ok();

    let total = uploads.len();
    let mut moved = 0usize;
    let mut error_count = 0usize;
    let mut affected_dirs: Vec<PathBuf> = Vec::new();
    {
        let mut out = stdout();
        let _ = writeln!(out);
        let _ = writeln!(out, "── croft: uploading {total} item(s) via scp ──");
        let _ = writeln!(
            out,
            "(scp prompts for password / passphrase / host-key will appear below)"
        );
        let _ = writeln!(out);
        let _ = out.flush();
    }
    for (i, upload) in uploads.iter().enumerate() {
        if let Some(parent) = upload.src.parent() {
            affected_dirs.push(parent.to_path_buf());
        }
        {
            let mut out = stdout();
            let _ = writeln!(
                out,
                "[{}/{}] scp -r {} {}:",
                i + 1,
                total,
                upload.src.display(),
                upload.alias,
            );
            let _ = out.flush();
        }
        if !upload.src.exists() {
            eprintln!("  ! source no longer exists, skipping");
            error_count += 1;
            continue;
        }
        let dest = format!("{}:", upload.alias);
        let status = crate::proc::command("scp")
            .arg("-r")
            .arg(&upload.src)
            .arg(&dest)
            .status();
        match status {
            Ok(s) if s.success() => {
                moved += 1;
            }
            Ok(s) => {
                eprintln!("  ! scp exited with {s}; local source preserved");
                error_count += 1;
            }
            Err(e) => {
                eprintln!("  ! could not spawn scp: {e}");
                error_count += 1;
            }
        }
    }
    {
        let mut out = stdout();
        let _ = writeln!(out);
        let _ = writeln!(
            out,
            "── done: {moved}/{total} uploaded, {error_count} error(s) ──"
        );
        let _ = write!(out, "Press Enter to return to croft ");
        let _ = out.flush();
    }
    let mut line = String::new();
    let _ = std::io::stdin().read_line(&mut line);

    // Restore the TUI via the shared takeover block (same modes as startup
    // and the dtach-reattach re-assert).
    enable_raw_mode().ok();
    {
        use std::io::Write;
        let out = terminal.backend_mut();
        let _ = out.write_all(&takeover_mode_seq());
        let _ = out.flush();
    }
    // The takeover block set the steady bar; the next draw puts the
    // overwrite block back if it is wanted.
    app.caret_block_sent = false;
    terminal.clear().ok();
    app.overlays.activity.mark_dirty();
    app.overlays.welcome.mark_dirty();
    app.report_scp_results(moved, total, error_count, &affected_dirs);
    Ok(())
}