croft-software 0.2.182

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
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
//! `croft view` (#362): a pane asks the croft that hosts it to open a file.
//!
//! Over SSH `imgcat file.png` works because the escape sequences travel
//! through the terminal, but croft's richer previews (PDF pages, sheets,
//! SQLite) are editor tabs, and a shell prompt had no way to ask for one.
//! This module is the channel: croft listens on a per-process Unix socket,
//! exports its path into every pane it spawns, and `croft view <path>`
//! connects to it.
//!
//! # Direction, and why it is not the drop relay
//!
//! The drop relay ([`crate::app`]'s `relay_dir`) runs remote -> local: a
//! remote croft asks the user's local pump to fetch something. This runs the
//! other way and never crosses a machine: the pane's shell is a CHILD of the
//! croft it is talking to, so both ends are always the same host and the same
//! uid, whether that host is the laptop or the box behind `croft remote`.
//! That is what makes a plain `0600` socket sufficient here.
//!
//! # Why the client resolves the path
//!
//! A relative `croft view report.pdf` means "relative to the shell's cwd",
//! and the server cannot know that: the pane's cwd is the client's own, it
//! changes with every `cd`, and croft's notion of the pane cwd is a scraped
//! approximation refreshed on a timer. The client holds the truth, so it
//! resolves before sending and the server only ever sees absolute paths.

use std::io::Write;
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};

/// Env var naming the host croft's socket, exported into every pane.
pub const SOCK_ENV: &str = "CROFT_VIEW_SOCK";

/// The bound socket's path, published to every pane spawned after the bind.
///
/// A `OnceLock` rather than the process environment (#362). portable-pty
/// snapshots `std::env::vars_os()` when a pane's `CommandBuilder` is built and
/// then clears the child's environment before applying only that snapshot, so
/// a `set_var` after `App::new` constructed the first pane never reached that
/// pane's shell. Read at SPAWN time instead, there is no ordering to get
/// wrong: a pane built before the bind simply carries no socket, and every
/// pane built after carries the right one.
pub static SOCK_PATH: std::sync::OnceLock<PathBuf> = std::sync::OnceLock::new();

/// One request, one JSON line.
///
/// The path travels as raw BYTES rather than a `String` because a filename
/// on Linux is bytes, not UTF-8: `to_string_lossy` would replace an invalid
/// sequence with U+FFFD and the server would open the wrong path (or none).
/// A JSON array of integers is unlovely on the wire and exactly lossless,
/// which is the trade worth making for something the user never reads.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ViewRequest {
    pub path: Vec<u8>,
    /// Ask only whether `path` is open in a tab, opening nothing (#620):
    /// `croft edit --wait` polls with this until the user closes the tab.
    /// Omitted from the wire when false, so a request from this build reads
    /// the same to an older croft.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub probe: bool,
    /// Where to put the caret once the file is open, as a 0-based (line,
    /// column), from a `path:line[:col]` argument (#1606). Omitted from the
    /// wire when absent, so an older croft still reads the request.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub at: Option<(usize, usize)>,
}

/// The server's answer. `Err` carries a message the client prints verbatim,
/// so the reason a view failed is decided by the side that knows it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "status", rename_all = "lowercase")]
pub enum ViewReply {
    Ok,
    Err { message: String },
}

impl ViewRequest {
    pub fn new(path: &Path) -> Self {
        use std::os::unix::ffi::OsStrExt;
        Self {
            path: path.as_os_str().as_bytes().to_vec(),
            probe: false,
            at: None,
        }
    }

    /// Open `path` with the caret at `at`, a 0-based (line, column) (#1606).
    pub fn at(path: &Path, at: Option<(usize, usize)>) -> Self {
        Self {
            at,
            ..Self::new(path)
        }
    }

    /// "Is `path` still open?" (#620).
    pub fn probe(path: &Path) -> Self {
        Self {
            probe: true,
            ..Self::new(path)
        }
    }

    pub fn to_path(&self) -> PathBuf {
        use std::os::unix::ffi::OsStrExt;
        PathBuf::from(std::ffi::OsStr::from_bytes(&self.path))
    }
}

/// Where the croft with this pid listens.
///
/// Keyed by pid, not by workspace: two crofts can share a workspace, and a
/// pane must reach the one that spawned it rather than whichever bound
/// first. The name is kept short because an `AF_UNIX` path is capped near
/// 104 bytes on macOS and the cache dir already eats most of that.
pub fn socket_path(cache_dir: &Path, pid: u32) -> PathBuf {
    socket_path_with(cache_dir, pid, &nonce())
}

/// A short random tail, so a recycled pid cannot aim a stale
/// `CROFT_VIEW_SOCK` at a DIFFERENT croft.
///
/// The pid alone made the name predictable in the wrong way. A process that
/// outlives the croft that spawned it - a `nohup`, a `setsid`, a disowned
/// job - keeps the variable, and once that pid is recycled by another croft
/// the client connects successfully and the file opens in a window the user
/// was not looking at. A refusal is recoverable and says what happened; the
/// wrong window is silent.
///
/// The pid stays FIRST so the sweep can still read it, and six hex
/// characters cost little against the 104-byte `AF_UNIX` path budget.
fn nonce() -> String {
    // No rand dependency for six characters: the address of a heap
    // allocation and the clock are both unpredictable enough for a name
    // whose only job is to differ from a previous boot's.
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.subsec_nanos() as u64)
        .unwrap_or(0);
    let here = Box::into_raw(Box::new(0u8));
    let mixed = now ^ (here as u64);
    // SAFETY: the pointer came from `Box::into_raw` one line above and has
    // not been used since.
    drop(unsafe { Box::from_raw(here) });
    format!("{:06x}", mixed & 0xff_ffff)
}

pub fn socket_path_with(cache_dir: &Path, pid: u32, nonce: &str) -> PathBuf {
    cache_dir.join(format!("view-{pid}-{nonce}.sock"))
}

/// The pid a socket file name was made for, or None if the name is not one
/// croft wrote. Both spellings are read: a socket left by a croft from
/// before the nonce existed is still that croft's to spare or to clear.
pub fn pid_of_socket(name: &str) -> Option<u32> {
    let rest = name.strip_prefix("view-")?.strip_suffix(".sock")?;
    let head = rest.split_once('-').map_or(rest, |(pid, _)| pid);
    let pid = head.parse::<u32>().ok()?;
    // A number that cannot be a pid is not one. The sweep casts this to
    // `pid_t`, where 0 means the caller's process group and 4294967295 means
    // -1, "every process we may signal": both answer "alive" to signal 0, so
    // such a file would be spared forever instead of swept.
    (pid > 0 && pid <= i32::MAX as u32).then_some(pid)
}

/// Resolve the user's argument against the client's cwd.
///
/// `~` is deliberately NOT expanded: every shell croft spawns expands it
/// before `croft view` is ever exec'd, so a literal `~` reaching here means
/// the user quoted it and meant a file of that name.
pub fn resolve(cwd: &Path, arg: &Path) -> PathBuf {
    if arg.is_absolute() {
        arg.to_path_buf()
    } else {
        cwd.join(arg)
    }
}

/// The file and 0-based (line, column) a `path:line` or `path:line:col`
/// argument names, as compilers, `grep -n` and stack traces print them
/// (#1606). `None` unless `arg` names nothing as a whole while the part
/// before the `:line[:col]` suffix is a file, so a file literally named
/// `a:1` still opens as itself. The path is resolved against `cwd`; a
/// column missing or 0 is the line's start, and line 0 is the first line.
pub fn split_location(cwd: &Path, arg: &Path) -> Option<(PathBuf, (usize, usize))> {
    let number = |s: &str| {
        (!s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()))
            .then(|| s.parse::<usize>().ok())
            .flatten()
    };
    if std::fs::symlink_metadata(resolve(cwd, arg)).is_ok() {
        return None;
    }
    let text = arg.to_str()?;
    let (rest, last) = text.rsplit_once(':')?;
    let last = number(last)?;
    let file = |p: &str| {
        let path = resolve(cwd, Path::new(p));
        (!p.is_empty() && path.is_file()).then_some(path)
    };
    if let Some((head, line)) = rest.rsplit_once(':')
        && let Some(line) = number(line)
        && let Some(path) = file(head)
    {
        return Some((path, (line.saturating_sub(1), last.saturating_sub(1))));
    }
    file(rest).map(|path| (path, (last.saturating_sub(1), 0)))
}

/// Send one request and wait for the reply, both bounded by a deadline.
///
/// A croft wedged mid-frame must not hang the user's shell forever: a shell
/// that never returns is a worse failure than a view that does not open.
///
/// The socket timeouts alone did not deliver that, and the doc here used to
/// claim they did. `SO_RCVTIMEO` applies per `recv` while `read_line` loops
/// over `fill_buf`, so a croft dribbling a byte inside every window held the
/// shell indefinitely — verbatim the defect fixed on the SERVER half, left
/// standing on the client half of the same module. Exposure was low (the only
/// writer is croft itself, sending one `write_all`) but the asymmetry inside
/// one file is the point: the fix belonged to the read, not to the caller.
///
/// The WRITE half keeps that shape deliberately, and the doc above should not
/// be read as saying otherwise: `SO_SNDTIMEO` is also per-syscall while
/// `write_all` loops, so a peer dribbling reads could re-arm it the same way.
/// It stays because the exposure really is nil here rather than merely low:
/// the request is one short line to a croft that is about to read it, and a
/// bounded write would need the same deadline machinery for a case no client
/// can reach.
pub fn send(socket: &Path, req: &ViewRequest) -> std::io::Result<ViewReply> {
    let first = send_once(socket, req)?;
    // ONE retry, and only on the one refusal that says nothing about this
    // request. The server accepts on the frame loop under a 20ms budget
    // shared by every client it serves that frame, so a scheduling gap
    // between this process's `connect` and its `write_all` gets the
    // connection refused for a deadline the user's shell has no part in.
    // Nothing was opened in that case (the request was never read), so a
    // second attempt cannot double-open, and a croft that is genuinely wedged
    // fails the same way one frame later.
    // Compared EXACTLY, not by suffix. The server wraps this one refusal as
    // `unreadable request: {e}`, so the whole string is knowable here; a
    // suffix test also matches any future reply that happens to END with the
    // same words, and one of them already can, since the absolute-path
    // refusal ends with a client-supplied path. Today that is harmless
    // (the retry re-sends and is refused again, opening nothing), but the
    // retry's entire safety argument is "nothing was opened", and a reply
    // that named a path after a side effect would become double-executed
    // with no test noticing.
    if first == retryable_refusal() {
        return send_once(socket, req);
    }
    Ok(first)
}

/// The tail of the one reply [`send`] retries. Shared with the server rather
/// than spelled twice: a reworded refusal would otherwise turn the retry off
/// silently, which is the failure this constant exists to make impossible.
pub const FRAME_BUDGET_REFUSAL: &str = "the request did not arrive within the frame budget";

/// The one reply [`send`] retries, spelled exactly as the server sends it.
///
/// Built from the same pieces the server uses (`answer_view_client` wraps a
/// read error as `unreadable request: {e}`), so a reworded refusal fails to
/// match here and the retry turns itself off rather than firing on the wrong
/// reply.
fn retryable_refusal() -> ViewReply {
    ViewReply::Err {
        message: format!("unreadable request: {FRAME_BUDGET_REFUSAL}"),
    }
}

fn send_once(socket: &Path, req: &ViewRequest) -> std::io::Result<ViewReply> {
    let mut stream = std::os::unix::net::UnixStream::connect(socket)?;
    stream.set_read_timeout(Some(std::time::Duration::from_secs(5)))?;
    stream.set_write_timeout(Some(std::time::Duration::from_secs(5)))?;
    exchange(&mut stream, req)
}

/// Write one request on a connected stream and read croft's answer.
///
/// A write that fails because croft already hung up still reads the answer
/// (#2377). Croft gives a request one frame to arrive, then refuses it with
/// [`FRAME_BUDGET_REFUSAL`] and closes. A client descheduled between
/// `connect` and this write finds the socket closed (`EPIPE`) with that
/// refusal already in its receive buffer. Returning the write error dropped
/// the one reply [`send`] retries, so a busy shell printed "Broken pipe"
/// where croft had asked for a second attempt. Only a broken pipe is read
/// through: any other write error, and a broken pipe with no reply behind
/// it, is reported as the write error it is. A reply that did arrive is
/// croft's answer whatever it says, so one that does not parse is reported
/// as malformed, as it is when the write went through, and not as a croft
/// that is gone: that would send git's sequence editor to its fallback for
/// a croft that answered.
fn exchange(
    stream: &mut std::os::unix::net::UnixStream,
    req: &ViewRequest,
) -> std::io::Result<ViewReply> {
    let mut line = serde_json::to_string(req)
        .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
    line.push('\n');
    if let Err(e) = stream
        .write_all(line.as_bytes())
        .and_then(|()| stream.flush())
    {
        if e.kind() != std::io::ErrorKind::BrokenPipe {
            return Err(e);
        }
        // `InvalidData` is the one read error with bytes behind it (a reply
        // that is not JSON, not UTF-8, or too long); every other one says
        // nothing came back.
        return match read_reply(stream) {
            Err(read) if read.kind() != std::io::ErrorKind::InvalidData => Err(e),
            answer => answer,
        };
    }
    read_reply(stream)
}

/// Croft's one-line answer to a request, within the client's 5s.
fn read_reply(stream: &std::os::unix::net::UnixStream) -> std::io::Result<ViewReply> {
    let reply = read_line_by_deadline(
        stream,
        std::time::Instant::now() + std::time::Duration::from_secs(5),
        "croft did not reply within 5s",
    )?;
    if reply.trim().is_empty() {
        return Err(std::io::Error::new(
            std::io::ErrorKind::UnexpectedEof,
            "croft accepted the request but closed without replying",
        ));
    }
    serde_json::from_str(reply.trim())
        .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))
}

/// The most `croft view -` will take from a pipe.
///
/// Uncapped, `some_command | croft view -` with a runaway producer buffered
/// the whole stream in RAM and then wrote a 0600 copy of it into the cache
/// dir. The request is capped for exactly this reasoning; the payload was
/// not.
///
/// It is NOT the editor's `MAX_FILE_BYTES` (50 MiB), and an earlier version
/// of this doc claiming it should be was wrong in a way worth recording:
/// that constant is the TEXT branch's cap, taken after `open` has already
/// dispatched images, SVG, PDF and sheets to their own limits, and
/// `Editor::open_pdf` applies no size limit at all. A 60 MiB PDF down a pipe
/// therefore opens today; lowering this to 50 MiB would refuse it at the
/// staging step for a bound that never applied to it.
///
/// What this number bounds is the RAM the client buffers and the bytes it
/// writes to disk on a stranger's say-so, so it is deliberately above every
/// per-format cap rather than equal to any one of them.
pub const MAX_STAGED_STDIN_BYTES: u64 = 64 * 1024 * 1024;

/// The most a single request may be. A path plus JSON framing; anything past
/// this is not a `croft view` invocation, and reading it unbounded would grow
/// the UI thread's buffer on a client's say-so.
pub const MAX_REQUEST_BYTES: u64 = 64 * 1024;

/// Read one newline-framed line, re-arming the socket timeout from `deadline`
/// on every `recv`.
///
/// The re-arming is the whole mechanism. `SO_RCVTIMEO` is per `recv` and this
/// loops, so a timeout armed once outside is reset by every byte arriving
/// inside its window: a peer dribbling under the budget is answered by each
/// read and never trips it. Capping bytes does not substitute, because the
/// cost is per read rather than per byte.
///
/// A per-`recv` timeout is not fatal here — it is one window closing, and
/// whether that ends the read is the DEADLINE's decision rather than the
/// errno's. Returning it directly refused the peer promptly but reported
/// `EAGAIN`, which is also what a socket left non-blocking reports, so two
/// unrelated defects produced identical text.
pub fn read_line_by_deadline(
    stream: &std::os::unix::net::UnixStream,
    deadline: std::time::Instant,
    whose: &str,
) -> std::io::Result<String> {
    use std::io::Read;
    let mut line: Vec<u8> = Vec::new();
    let mut chunk = [0u8; 4096];
    loop {
        let left = deadline.saturating_duration_since(std::time::Instant::now());
        if left.is_zero() {
            // The wording is the CALLER's, because the two callers bound
            // different things. The server has a frame budget; a `croft view`
            // client has no frames at all, and printing "did not arrive within
            // the frame budget" at a shell prompt names a budget that process
            // does not have.
            return Err(std::io::Error::new(std::io::ErrorKind::TimedOut, whose));
        }
        stream.set_read_timeout(Some(left))?;
        match (&*stream).read(&mut chunk) {
            Ok(0) => break,
            Ok(n) => {
                line.extend_from_slice(&chunk[..n]);
                if let Some(pos) = line.iter().position(|b| *b == b'\n') {
                    // Checked BEFORE accepting the line, not after. The cap
                    // used to be tested on the next iteration, so a request
                    // that carried its newline in the very chunk that crossed
                    // the limit was accepted and deserialised: the bound held
                    // for an unterminated flood and not for a terminated one,
                    // which is the case an actual client sends.
                    // `>=`, not `>`: `pos` is an INDEX and the accumulate
                    // branch below tests a LENGTH, so the two were a byte apart
                    // on the same cap.
                    if pos as u64 >= MAX_REQUEST_BYTES {
                        return Err(std::io::Error::new(
                            std::io::ErrorKind::InvalidData,
                            "request exceeded the maximum length",
                        ));
                    }
                    line.truncate(pos);
                    break;
                }
                if line.len() as u64 > MAX_REQUEST_BYTES {
                    return Err(std::io::Error::new(
                        std::io::ErrorKind::InvalidData,
                        "request exceeded the maximum length",
                    ));
                }
            }
            // EINTR is retried like a timeout: a signal landing on this
            // thread mid-`recv` (any child exiting under a handler, a resize)
            // says nothing about the client, and the deadline above still
            // bounds the loop. Returning it refused a well-formed request
            // with "Interrupted system call", seen under the parallel suite.
            Err(e)
                if matches!(
                    e.kind(),
                    std::io::ErrorKind::WouldBlock
                        | std::io::ErrorKind::TimedOut
                        | std::io::ErrorKind::Interrupted
                ) => {}
            Err(e) => return Err(e),
        }
    }
    String::from_utf8(line).map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))
}

/// Read one request from an accepted connection, bounded by `deadline`.
///
/// The socket's read timeout does NOT bound this on its own, which is why the
/// work is delegated to [`read_line_by_deadline`] rather than done with a
/// `BufReader`: `SO_RCVTIMEO` applies per `recv` while a line read loops, so a
/// client writing one byte inside every window resets the timeout forever and
/// holds the caller. The drain runs on the frame loop, so that freezes the
/// whole editor, and same-uid is not a defence: any process in any pane (a
/// build script, a piped installer) can do it by accident.
///
/// The byte cap and the deadline are separate bounds: the cap stops one
/// enormous line, the deadline stops a slow one. Neither substitutes.
pub fn read_request(
    stream: &std::os::unix::net::UnixStream,
    deadline: std::time::Instant,
) -> std::io::Result<ViewRequest> {
    let text = read_line_by_deadline(stream, deadline, FRAME_BUDGET_REFUSAL)?;
    serde_json::from_str(text.trim())
        .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))
}

pub fn write_reply(
    stream: &mut std::os::unix::net::UnixStream,
    reply: &ViewReply,
) -> std::io::Result<()> {
    let mut line = serde_json::to_string(reply)
        .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
    line.push('\n');
    stream.write_all(line.as_bytes())?;
    stream.flush()
}

/// Map sniffed content to the extension the editor's routing keys on.
///
/// The editor picks a viewer by EXTENSION (`crate::sheet::extension_is_sheet`,
/// `Editor::open`'s arms), so staging stdin under a bare name would land
/// every piped byte in the text fallback however recognisable it was. This
/// hands the staged file a name the existing routing already understands,
/// rather than teaching the editor a second way to decide.
pub fn extension_for(magic: crate::magic::Magic) -> &'static str {
    use crate::magic::Magic;
    match magic {
        Magic::Png => "png",
        Magic::Jpeg => "jpg",
        Magic::Gif => "gif",
        Magic::WebP => "webp",
        Magic::Bmp => "bmp",
        Magic::Ico => "ico",
        Magic::Tiff => "tiff",
        Magic::Pdf => "pdf",
        // A zip is most often an xlsx/docx here; the sheet and docx openers
        // both fail soft to the archive view, so this is the useful guess.
        Magic::Zip => "zip",
        Magic::Gzip => "gz",
        // `txz`, not `xz`: `archive::kind_from_ext` claims it, so a stream
        // past the text-size guard still reaches the tar.xz browser rather
        // than hex. A plain xz that is not a tar falls through to hex anyway.
        // Likewise for bzip2 and zstd.
        Magic::Xz => "txz",
        Magic::Bzip2 => "tbz2",
        Magic::Zstd => "tzst",
        Magic::Tar => "tar",
        Magic::Sqlite => "sqlite",
    }
}

/// Accept only a plain lowercase alphanumeric extension from `--as`.
///
/// The value becomes part of a filename croft then opens, so anything
/// carrying a separator, a dot or a NUL is refused rather than sanitised:
/// silently rewriting a user's input to something that "works" is how a
/// staged file ends up somewhere the user did not name.
pub fn sanitize_extension(raw: &str) -> Option<String> {
    let e = raw.trim().trim_start_matches('.').to_ascii_lowercase();
    if e.is_empty() || e.len() > 16 {
        return None;
    }
    e.chars().all(|c| c.is_ascii_alphanumeric()).then_some(e)
}

/// Does this look like delimiter-separated data rather than prose?
///
/// Needed because CSV has no magic bytes: `cat data.csv | croft view -` is
/// in the issue's acceptance criteria, and by content a CSV is just text.
/// The test is deliberately strict (every one of the first lines must
/// carry the SAME non-zero count of the delimiter) because the cost of a
/// false positive (prose opening in a grid) is worse than the cost of a
/// false negative (a `--as csv` away). Fields are counted per record with
/// CSV's quoting rules, so a quoted comma (`"Doe, John"`, `"1,200"`) or a
/// quoted line break is part of its field, not a column (#1217); TSV has no
/// quoting, so its tabs are counted as written.
pub fn looks_delimited(bytes: &[u8]) -> Option<&'static str> {
    if bytes.contains(&0) {
        return None;
    }
    std::str::from_utf8(bytes).ok()?;
    for (delim, quoting, ext) in [(b',', true, "csv"), (b'\t', false, "tsv")] {
        let mut reader = csv::ReaderBuilder::new()
            .has_headers(false)
            .flexible(true)
            .delimiter(delim)
            .quoting(quoting)
            .from_reader(bytes);
        let widths: Vec<usize> = reader
            .records()
            .map_while(Result::ok)
            .filter(|r| !(r.len() == 1 && r[0].trim().is_empty()))
            .take(8)
            .map(|r| r.len())
            .collect();
        // One record is a sentence, not a table: a header alone tells us
        // nothing.
        if widths.len() >= 2 && widths[0] > 1 && widths.iter().all(|&w| w == widths[0]) {
            return Some(ext);
        }
    }
    None
}

/// The extension to stage piped bytes under, if any.
///
/// `None` means "no extension": the file opens as text, which is the
/// issue's stated fallback and the right answer for a log or a diff.
pub fn stdin_extension(bytes: &[u8], hint: Option<&str>) -> anyhow::Result<Option<String>> {
    if let Some(h) = hint {
        // An unusable `--as` is refused rather than ignored. Falling back to
        // the sniff would stage the bytes under a name the user did not ask
        // for and report success, so the only signal that the flag was
        // rejected would be the file opening in the wrong viewer.
        let ext = sanitize_extension(h).ok_or_else(|| {
            anyhow::anyhow!(
                "croft view --as {h:?}: an extension must be a short run of letters and digits"
            )
        })?;
        return Ok(Some(ext));
    }
    if let Some(m) = crate::magic::sniff(bytes) {
        return Ok(Some(extension_for(m).to_string()));
    }
    Ok(looks_delimited(bytes).map(str::to_string))
}

/// Stage piped bytes as a file the editor can route on.
///
/// Kept in croft's cache dir rather than `/tmp` so the file survives a
/// tmpreaper mid-session and sits with the rest of croft's scratch state;
/// named by pid and a counter so two pipes in the same pane cannot collide.
pub fn stage_stdin(cache_dir: &Path, bytes: &[u8], hint: Option<&str>) -> anyhow::Result<PathBuf> {
    use std::sync::atomic::{AtomicU64, Ordering};
    static SEQ: AtomicU64 = AtomicU64::new(0);
    // Owner-only, both of them. Whatever came down the pipe was chosen by
    // the user, not by croft, and `vault read … | croft view -` or a piped
    // `.env` is exactly the case this command invites; the default mode
    // would leave it world-readable in a predictable path under the cache
    // dir. Possession of the account is already the trust boundary for
    // every other croft socket and staging path, and this joins them.
    use std::os::unix::fs::DirBuilderExt;
    // Validate the hint BEFORE creating anything. `croft view - --as ../x` is
    // a refusal, and a refusal must not leave a `view-stdin/` behind in the
    // user's real cache dir on its way out: the integration test for that
    // rejection runs against `~/.cache/croft`, so it was doing exactly this.
    let ext = stdin_extension(bytes, hint)?;
    let dir = cache_dir.join("view-stdin");
    std::fs::DirBuilder::new()
        .recursive(true)
        .mode(0o700)
        .create(&dir)?;
    // `DirBuilder`'s mode applies only when it CREATES, so a staging
    // directory left by an older croft (or by anything else) keeps whatever
    // mode it had. The contents are 0600 either way, so what a loose mode
    // leaks is the names, and `vault read … | croft view -` puts a
    // recognisable name in there.
    let _ = std::fs::set_permissions(&dir, std::os::unix::fs::PermissionsExt::from_mode(0o700));
    let n = SEQ.fetch_add(1, Ordering::Relaxed);
    let stem = format!("stdin-{}-{n}", std::process::id());
    let name = match ext {
        Some(ext) => format!("{stem}.{ext}"),
        None => stem,
    };
    stage_at(&dir, &name, bytes)
}

/// The prefix a staged file takes once a croft has opened it (#362).
pub const HELD_PREFIX: &str = "held-";

/// Hand a staged stdin file to the croft that is about to show it.
///
/// The staging sweep cannot judge liveness from a staged name, because
/// `stage_stdin` runs inside the short-lived `croft view` CLIENT and the pid
/// baked into the name is dead by construction. Age alone was the fallback,
/// and age alone deletes a file a croft still has open once the session
/// outlives the retention window: `sqlite_view::table_page` re-opens by path
/// on every page turn, so the tab breaks, and piped input cannot be produced
/// again by re-running anything.
///
/// So the SERVER stamps its own pid into the name at the moment it opens the
/// file, which is the one point where a live holder is known. The sweep then
/// has the same liveness signal it already uses for sockets.
///
/// Returns `None`, leaving the path alone, for anything that is not an
/// unclaimed file in a `view-stdin` directory: an ordinary file the user
/// named, and a file another croft has already claimed. The second case keeps
/// the first holder's pid rather than stacking prefixes; two crofts showing
/// one staged file is not a case worth a second mechanism, and the file
/// survives while EITHER of them is alive, which errs the safe way.
pub fn claim_staged(path: &Path, holder: u32) -> Option<PathBuf> {
    let name = path.file_name()?.to_str()?;
    if !name.starts_with("stdin-") {
        return None;
    }
    // Only inside the staging directory, so a user file that happens to be
    // called `stdin-something` is never renamed under them.
    let dir = path.parent()?;
    if dir.file_name()?.to_str()? != "view-stdin" {
        return None;
    }
    let held = dir.join(format!("{HELD_PREFIX}{holder}-{name}"));
    std::fs::rename(path, &held).ok()?;
    Some(held)
}

/// The pid holding a staged file, read back out of its name.
///
/// Rejects 0 and anything past `i32::MAX` for the reason `pid_of_socket`
/// does: the sweep casts this to `pid_t`, where 0 means the caller's process
/// group and -1 means every process it may signal, and both answer "alive" to
/// signal 0, so such a file would be spared forever instead of swept.
pub fn holder_of_staged(name: &str) -> Option<u32> {
    let (pid, _) = name.strip_prefix(HELD_PREFIX)?.split_once('-')?;
    let pid = pid.parse::<u32>().ok()?;
    (pid > 0 && pid <= i32::MAX as u32).then_some(pid)
}

/// Write `bytes` to `dir/name`, stepping past a name already taken.
///
/// Split out so the collision can be CONSTRUCTED in a test rather than
/// predicted: `stage_stdin`'s name carries a process-wide counter that every
/// other test in the binary bumps, so a fixture that guesses the next name
/// tests nothing. Two earlier attempts at that fixture were vacuous - one
/// guessed the counter, the next wrote its decoy a directory above the one
/// this writes to.
///
/// `create_new` rather than `write`, so this never truncates a file it did
/// not make. The name carries this process's pid and a counter that restarts
/// at 0, and the staging directory outlives the process, so once a croft drew
/// a recycled pid it met a months-old file and `croft view -` failed with
/// "File exists" forever. The collision is with the dead rather than with a
/// live competitor, so the answer is to step past it, not to refuse.
pub(crate) fn stage_at(dir: &Path, name: &str, bytes: &[u8]) -> anyhow::Result<PathBuf> {
    use std::os::unix::fs::OpenOptionsExt as _;
    let mut attempt = 0;
    loop {
        let suffixed = if attempt == 0 {
            name.to_string()
        } else {
            match name.rsplit_once('.') {
                Some((stem, ext)) => format!("{stem}-{attempt}.{ext}"),
                None => format!("{name}-{attempt}"),
            }
        };
        let path = dir.join(&suffixed);
        match std::fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .mode(0o600)
            .open(&path)
        {
            Ok(mut f) => {
                std::io::Write::write_all(&mut f, bytes)?;
                // Absolute for the same reason the socket path is: `-` is the
                // one branch that never calls `resolve`, so a relative name
                // here reaches the server, which resolves it against CROFT's
                // cwd rather than the client's and opens a different file or
                // none. `croft_cache_dir` is relative whenever `HOME` is.
                return Ok(std::path::absolute(&path).unwrap_or(path));
            }
            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists && attempt < 64 => {
                attempt += 1;
            }
            Err(e) => return Err(e.into()),
        }
    }
}

/// Read at most `cap` bytes, refusing anything longer rather than truncating.
///
/// An uncapped `read_to_end` let a runaway producer buffer the whole stream in
/// RAM and then write a 0600 copy of it into the cache dir.
///
/// `take(cap + 1)` rather than `take(cap)`, and `>` rather than `>=`, so a
/// payload of EXACTLY `cap` is accepted: `take(N)` stops at N, so a read of
/// exactly N cannot tell a legal N-byte payload from a truncated larger one,
/// and reading one byte more can. Split out of `run` because that argument is
/// an off-by-one nobody could test through stdin.
fn read_capped<R: std::io::Read>(reader: R, cap: u64) -> anyhow::Result<Vec<u8>> {
    use std::io::Read as _;
    let mut buf = Vec::new();
    let read = reader.take(cap + 1).read_to_end(&mut buf)? as u64;
    if read > cap {
        anyhow::bail!(
            "more than {cap} bytes arrived on stdin; write it to a file and view that instead"
        );
    }
    Ok(buf)
}

/// The reply to a probe whose file is no longer open in any tab (#620).
pub const PROBE_CLOSED: &str = "closed";

/// The reply to a probe whose file is still open. Not `Ok`: a croft from
/// before probes ignores the flag, re-opens the file and answers `Ok`, and
/// `edit --wait` must tell that apart from "still open" or it waits forever.
pub const PROBE_OPEN: &str = "open";

/// How often `croft edit --wait` asks whether its tab is still open.
const WAIT_POLL: std::time::Duration = std::time::Duration::from_millis(250);

/// `croft edit [--wait] <path>` (#620): open `path` in the hosting croft
/// like `croft view`, and with `wait` return only once its tab is closed,
/// which is what `$GIT_SEQUENCE_EDITOR` and `$EDITOR` callers expect. A
/// croft that goes away counts as closed: git then carries on with the file
/// as it was last saved, rather than hanging forever. A path that does not
/// exist yet is created empty first, as any `$EDITOR` would start it (#848).
pub fn edit(target: &std::ffi::OsStr, wait: bool, cache_dir: &Path) -> anyhow::Result<()> {
    run(Verb::Edit, target, None, cache_dir)?;
    if !wait {
        return Ok(());
    }
    let Some(socket) = std::env::var_os(SOCK_ENV).filter(|s| !s.is_empty()) else {
        return Ok(());
    };
    let cwd = std::env::current_dir()?;
    let path = match split_location(&cwd, Path::new(target)) {
        Some((path, _)) => path,
        None => resolve(&cwd, Path::new(target)),
    };
    let probe = ViewRequest::probe(&path);
    loop {
        std::thread::sleep(WAIT_POLL);
        match wait_step(send(Path::new(&socket), &probe)) {
            WaitStep::Poll => continue,
            WaitStep::Closed => return Ok(()),
            WaitStep::CannotWait => anyhow::bail!(
                "the croft hosting this pane is older than `croft edit --wait`; restart it (Ctrl+Shift+F9, Cmd+Shift+F9 on macOS) and try again"
            ),
        }
    }
}

#[derive(Debug, PartialEq, Eq)]
enum WaitStep {
    Poll,
    Closed,
    CannotWait,
}

/// What one probe reply means to `edit --wait`. Only a definite answer ends
/// the wait: the tab closed, or croft is gone. A busy frame, a slow reply or
/// any other refusal is asked again, because returning early lets git run
/// the plan the user is still editing.
fn wait_step(reply: std::io::Result<ViewReply>) -> WaitStep {
    use std::io::ErrorKind as K;
    match reply {
        Ok(ViewReply::Err { message }) if message == PROBE_CLOSED => WaitStep::Closed,
        Ok(ViewReply::Ok) => WaitStep::CannotWait,
        Ok(ViewReply::Err { .. }) => WaitStep::Poll,
        Err(e) => match e.kind() {
            K::NotFound
            | K::ConnectionRefused
            | K::ConnectionReset
            | K::BrokenPipe
            | K::UnexpectedEof => WaitStep::Closed,
            _ => WaitStep::Poll,
        },
    }
}

/// Which command the user typed (#848). It names every message [`run`]
/// prints, so a failed `croft edit` no longer reports itself as `croft
/// view`, and it decides what a path that does not exist yet means.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Verb {
    /// `croft view`: a missing file is refused, as there is nothing to show.
    View,
    /// `croft edit`: a missing file is a new one, created empty.
    Edit,
}

impl Verb {
    /// The subcommand's name, as typed after `croft`.
    pub fn name(self) -> &'static str {
        match self {
            Verb::View => "view",
            Verb::Edit => "edit",
        }
    }
}

/// Which file a `croft edit` call created: its device and inode. A call
/// that cannot open the file takes back only this one, never a file
/// something else has put at the same path since.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Created {
    dev: u64,
    ino: u64,
}

/// The absolute path `target` names, resolved against `cwd` and checked
/// before any croft is asked to open it, and the file this call created
/// there, if it created one.
/// Checked here rather than at the server so the message names the path the
/// USER typed, resolved against the cwd they typed it in.
///
/// A missing file is refused for `view`. For `edit` it is created empty when
/// its directory exists, as `vim new.py` or `code --wait new.py` start one,
/// so `EDITOR="croft edit --wait"` works for tools that name a file they
/// have not written yet (#848). A missing directory is still an error: an
/// editor creates a file, not the folders above it.
fn resolve_target(
    verb: Verb,
    cwd: &Path,
    target: &Path,
) -> anyhow::Result<(PathBuf, Option<Created>)> {
    use std::os::unix::fs::MetadataExt;
    let v = verb.name();
    let path = resolve(cwd, target);
    if path.exists() {
        return Ok((path, None));
    }
    if verb == Verb::View {
        anyhow::bail!("croft {v}: no such file: {}", path.display());
    }
    let dir = path.parent().unwrap_or(cwd);
    if !dir.is_dir() {
        anyhow::bail!(
            "croft {v}: cannot create {}: no such directory {}",
            path.display(),
            dir.display()
        );
    }
    match std::fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(&path)
    {
        // Read from the handle, so it names the file this call made. Without
        // it nothing can be shown to be ours, and nothing is taken back.
        Ok(file) => {
            let created = file.metadata().ok().map(|m| Created {
                dev: m.dev(),
                ino: m.ino(),
            });
            Ok((path, created))
        }
        // Something else created it since the check: open what is there
        // rather than truncate it.
        Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Ok((path, None)),
        Err(e) => anyhow::bail!("croft {v}: cannot create {}: {e}", path.display()),
    }
}

/// A resolved target, what made it, and the 0-based (line, column) its
/// `:line[:col]` suffix named, if any (#1606).
type Located = (PathBuf, Option<Created>, Option<(usize, usize)>);

/// [`resolve_target`] for an argument that may end in `:line[:col]`, with
/// the 0-based (line, column) that suffix names (#1606). The file before
/// the suffix is opened rather than `edit` creating an empty file named
/// `file:line`.
fn resolve_located(verb: Verb, cwd: &Path, target: &Path) -> anyhow::Result<Located> {
    if let Some((path, at)) = split_location(cwd, target) {
        return Ok((path, None, Some(at)));
    }
    let (path, created) = resolve_target(verb, cwd, target)?;
    Ok((path, created, None))
}

/// `croft view <path>` / `croft view -`, and the opening half of `croft
/// edit`, with `verb` saying which of the two the user typed.
pub fn run(
    verb: Verb,
    target: &std::ffi::OsStr,
    as_hint: Option<&str>,
    cache_dir: &Path,
) -> anyhow::Result<()> {
    let v = verb.name();
    let socket = match std::env::var_os(SOCK_ENV).filter(|s| !s.is_empty()) {
        Some(s) => PathBuf::from(s),
        None => {
            return Err(NoCroft(format!(
                "croft {v} needs a croft to {v} in: run it from a pane inside croft ({SOCK_ENV} is unset)"
            ))
            .into());
        }
    };

    // Refused rather than ignored, for the same reason an unusable `--as`
    // value is refused rather than sniffed past (see `stdin_extension`): the
    // only signal that the flag did nothing would be the file opening in the
    // viewer the user was trying to override. `--as` stages piped bytes under
    // a chosen extension, and a named file already has one.
    if target != "-" && as_hint.is_some() {
        anyhow::bail!(
            "croft {v} --as applies only to piped input (`croft {v} - --as csv`); \
             a named file is routed by its own extension"
        );
    }

    let (path, created, at) = if target == "-" {
        let buf = read_capped(std::io::stdin(), MAX_STAGED_STDIN_BYTES)?;
        if buf.is_empty() {
            anyhow::bail!("croft {v} -: nothing arrived on stdin");
        }
        (stage_stdin(cache_dir, &buf, as_hint)?, None, None)
    } else {
        // After the socket check, so `croft edit` run outside croft leaves
        // no empty file behind.
        resolve_located(verb, &std::env::current_dir()?, Path::new(target))?
    };

    let opened = open_in_croft(v, &socket, &path, at);
    // Nor does one whose croft cannot open it: a stale socket (the croft
    // that set it has exited) or a refusal takes back the empty file created
    // just above, and never a file that was already there (#848).
    if opened.is_err()
        && let Some(created) = created
    {
        take_back(&path, created);
    }
    opened
}

/// No croft to open the file in: `CROFT_VIEW_SOCK` is unset, or the croft
/// that set it is gone. Told apart from a croft that refused the file, so
/// git's sequence editor can fall back to git's own editor (#1452).
#[derive(Debug)]
pub struct NoCroft(String);

impl std::fmt::Display for NoCroft {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

impl std::error::Error for NoCroft {}

/// Remove the file `created` names from `path`: only while that same file
/// is still there and still empty. Compared by device and inode, not by
/// path, and without following a link put in its place.
fn take_back(path: &Path, created: Created) {
    use std::os::unix::fs::MetadataExt;
    let ours = std::fs::symlink_metadata(path)
        .is_ok_and(|m| m.dev() == created.dev && m.ino() == created.ino && m.len() == 0);
    if ours {
        let _ = std::fs::remove_file(path);
    }
}

/// Ask the croft listening on `socket` to open `path`, naming the command
/// `v` in every refusal.
fn open_in_croft(
    v: &str,
    socket: &Path,
    path: &Path,
    at: Option<(usize, usize)>,
) -> anyhow::Result<()> {
    match send(socket, &ViewRequest::at(path, at)) {
        Ok(ViewReply::Ok) => Ok(()),
        Ok(ViewReply::Err { message }) => anyhow::bail!("croft {v}: {message}"),
        Err(e)
            if matches!(
                e.kind(),
                std::io::ErrorKind::ConnectionRefused
                    | std::io::ErrorKind::NotFound
                    | std::io::ErrorKind::BrokenPipe
            ) =>
        {
            // The env var outlives the croft that set it: a dtach session
            // reattached to a new croft, or a pane that survived its parent.
            // Nothing read the request, so nothing was opened.
            Err(NoCroft(format!(
                "croft {v}: the croft that opened this pane is gone (socket {})",
                socket.display()
            ))
            .into())
        }
        // A croft took the request and then closed without a reply: it may
        // have opened the file, so this is not NoCroft, and git's sequence
        // editor must not open the same plan in a second editor.
        Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => anyhow::bail!(
            "croft {v}: the croft that opened this pane is gone (socket {})",
            socket.display()
        ),
        Err(e) => anyhow::bail!("croft {v}: {e}"),
    }
}

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

    #[test]
    fn only_a_closed_tab_or_a_gone_croft_ends_edit_wait() {
        use std::io::{Error, ErrorKind};
        let err = |m: &str| {
            Ok(ViewReply::Err {
                message: m.to_string(),
            })
        };
        assert_eq!(wait_step(err(PROBE_CLOSED)), WaitStep::Closed);
        assert_eq!(wait_step(err(PROBE_OPEN)), WaitStep::Poll);
        assert_eq!(
            wait_step(err(&format!("unreadable request: {FRAME_BUDGET_REFUSAL}"))),
            WaitStep::Poll
        );
        assert_eq!(
            wait_step(Err(Error::from(ErrorKind::TimedOut))),
            WaitStep::Poll
        );
        assert_eq!(
            wait_step(Err(Error::from(ErrorKind::WouldBlock))),
            WaitStep::Poll
        );
        assert_eq!(
            wait_step(Err(Error::from(ErrorKind::ConnectionRefused))),
            WaitStep::Closed
        );
        assert_eq!(wait_step(Ok(ViewReply::Ok)), WaitStep::CannotWait);
    }

    #[test]
    fn a_relative_argument_resolves_against_the_clients_cwd_not_the_servers() {
        // The whole reason the client resolves: croft's idea of a pane's cwd
        // is a scraped approximation, and `cd` moves the truth every time.
        assert_eq!(
            resolve(Path::new("/home/u/proj"), Path::new("report.pdf")),
            PathBuf::from("/home/u/proj/report.pdf")
        );
        assert_eq!(
            resolve(Path::new("/home/u/proj"), Path::new("../out/a.png")),
            PathBuf::from("/home/u/proj/../out/a.png")
        );
    }

    #[test]
    fn an_absolute_argument_is_left_exactly_alone() {
        assert_eq!(
            resolve(Path::new("/home/u"), Path::new("/etc/hosts")),
            PathBuf::from("/etc/hosts")
        );
    }

    /// A 300-line `big.txt` in a fresh dir, as in #1606's repro.
    fn big_txt() -> tempfile::TempDir {
        let dir = tempfile::tempdir().unwrap();
        let text: String = (1..=300).map(|n| format!("line {n}\n")).collect();
        std::fs::write(dir.path().join("big.txt"), text).unwrap();
        dir
    }

    /// #1606: `file:line` and `file:line:col` name the file and a 0-based
    /// caret position, relative or absolute.
    #[test]
    fn a_file_line_argument_names_the_file_and_the_line() {
        let dir = big_txt();
        let big = dir.path().join("big.txt");
        assert_eq!(
            split_location(dir.path(), Path::new("big.txt:150")),
            Some((big.clone(), (149, 0)))
        );
        assert_eq!(
            split_location(dir.path(), Path::new("big.txt:150:3")),
            Some((big.clone(), (149, 2)))
        );
        let absolute = format!("{}:7", big.display());
        assert_eq!(
            split_location(Path::new("/"), Path::new(&absolute)),
            Some((big, (6, 0)))
        );
    }

    /// #1606: `croft edit big.txt:150` opens big.txt at line 150 and creates
    /// nothing; `croft view` takes the same argument.
    #[test]
    fn edit_and_view_of_file_line_open_the_file_and_create_nothing() {
        let dir = big_txt();
        for verb in [Verb::Edit, Verb::View] {
            let (path, created, at) =
                resolve_located(verb, dir.path(), Path::new("big.txt:150:3")).unwrap();
            assert_eq!(path, dir.path().join("big.txt"));
            assert_eq!(created, None);
            assert_eq!(at, Some((149, 2)));
        }
        let names: Vec<_> = std::fs::read_dir(dir.path())
            .unwrap()
            .map(|e| e.unwrap().file_name())
            .collect();
        assert_eq!(names, ["big.txt"], "no file named big.txt:150 appeared");
    }

    /// The request carries the location to croft, and a request without one
    /// reads as before.
    #[test]
    fn the_location_travels_in_the_request_only_when_there_is_one() {
        let path = Path::new("/w/big.txt");
        let line = serde_json::to_string(&ViewRequest::at(path, Some((149, 2)))).unwrap();
        let back: ViewRequest = serde_json::from_str(&line).unwrap();
        assert_eq!(back.at, Some((149, 2)));
        let plain = serde_json::to_string(&ViewRequest::new(path)).unwrap();
        assert!(!plain.contains("\"at\""), "{plain}");
        let old: ViewRequest = serde_json::from_str(r#"{"path":[47]}"#).unwrap();
        assert_eq!(old.at, None);
    }

    /// Negative (#1606): a file literally named `a:1` is itself, and a suffix
    /// whose prefix is no file, or is not a number, is no location.
    #[test]
    fn a_name_that_exists_or_has_no_file_before_the_suffix_is_not_split() {
        let dir = big_txt();
        std::fs::write(dir.path().join("a:1"), "x").unwrap();
        std::fs::create_dir(dir.path().join("sub")).unwrap();
        for arg in [
            "a:1",
            "big.txt",
            "nope.txt:3",
            "big.txt:abc",
            "big.txt:",
            "big.txt:-3",
            "big.txt:3:x",
            "sub:3",
            ":3",
        ] {
            assert_eq!(split_location(dir.path(), Path::new(arg)), None, "{arg}");
        }
        // `croft edit` of a new name ending in a number still creates it.
        let (path, created, at) =
            resolve_located(Verb::Edit, dir.path(), Path::new("notes:2")).unwrap();
        assert_eq!(path, dir.path().join("notes:2"));
        assert!(created.is_some() && at.is_none());
        let (path, created, at) =
            resolve_located(Verb::Edit, dir.path(), Path::new("a:1")).unwrap();
        assert_eq!((path, created, at), (dir.path().join("a:1"), None, None));
    }

    /// #848: `croft edit TODO.md` on a file not yet on disk was refused, so
    /// `EDITOR="croft edit --wait"` broke for any tool that names a file it
    /// has not written, where `vim` or `code --wait` start one.
    #[test]
    fn edit_creates_a_missing_file_in_an_existing_directory() {
        let dir = tempfile::tempdir().unwrap();
        let (path, created) = resolve_target(Verb::Edit, dir.path(), Path::new("TODO.md")).unwrap();
        assert_eq!(path, dir.path().join("TODO.md"));
        assert!(created.is_some(), "this call made it");
        assert_eq!(
            std::fs::read(&path).unwrap(),
            b"",
            "the new file is created empty"
        );

        // An existing file is opened as it is, never truncated.
        std::fs::write(&path, "keep me").unwrap();
        let (_, created) = resolve_target(Verb::Edit, dir.path(), Path::new("TODO.md")).unwrap();
        assert_eq!(
            created, None,
            "an existing file is not this call's to take back"
        );
        assert_eq!(std::fs::read_to_string(&path).unwrap(), "keep me");
    }

    /// #848 review: a `croft edit` whose croft cannot open the file takes
    /// back the empty file it created. Only that one: an empty file another
    /// process has put at the same path since is left alone.
    #[test]
    fn only_the_file_this_call_created_is_taken_back() {
        let dir = tempfile::tempdir().unwrap();
        let (path, created) = resolve_target(Verb::Edit, dir.path(), Path::new("TODO.md")).unwrap();
        let created = created.expect("this call made it");
        // Made while the first exists, so it cannot reuse its inode.
        let other = dir.path().join("other.md");
        std::fs::write(&other, b"").unwrap();
        std::fs::rename(&other, &path).unwrap();
        take_back(&path, created);
        assert!(
            path.exists(),
            "an empty file this call did not create stays"
        );
    }

    /// #848 guard: the empty file this call created, still in place, is
    /// taken back; one it created but that has since been written to, or a
    /// file that was already there, is not.
    #[test]
    fn the_created_file_is_taken_back_while_it_is_still_empty() {
        let dir = tempfile::tempdir().unwrap();
        let (path, created) = resolve_target(Verb::Edit, dir.path(), Path::new("new.md")).unwrap();
        take_back(&path, created.unwrap());
        assert!(!path.exists(), "the empty file this call made is gone");

        let (path, created) = resolve_target(Verb::Edit, dir.path(), Path::new("kept.md")).unwrap();
        std::fs::write(&path, "written since").unwrap();
        take_back(&path, created.unwrap());
        assert_eq!(std::fs::read_to_string(&path).unwrap(), "written since");
    }

    /// #848: an editor creates a file, not the folders above it, and the
    /// refusal names `croft edit`, the command the user typed.
    #[test]
    fn edit_refuses_a_missing_directory_and_says_croft_edit() {
        let dir = tempfile::tempdir().unwrap();
        let err = resolve_target(Verb::Edit, dir.path(), Path::new("no/such/TODO.md"))
            .unwrap_err()
            .to_string();
        assert!(
            err.starts_with("croft edit: ") && err.contains("no such directory"),
            "names the command and the reason: {err}"
        );
        assert!(err.contains("TODO.md"), "names the path: {err}");
        assert!(!dir.path().join("no").exists(), "no folders were created");
    }

    /// `croft view` keeps refusing a missing file, as there is nothing to
    /// preview, and creates nothing on the way out (#848).
    #[test]
    fn view_still_refuses_a_missing_file_and_creates_nothing() {
        let dir = tempfile::tempdir().unwrap();
        let err = resolve_target(Verb::View, dir.path(), Path::new("nope.pdf"))
            .unwrap_err()
            .to_string();
        assert!(
            err.starts_with("croft view: no such file") && err.contains("nope.pdf"),
            "{err}"
        );
        assert!(!dir.path().join("nope.pdf").exists());

        std::fs::write(dir.path().join("here.pdf"), "x").unwrap();
        assert_eq!(
            resolve_target(Verb::View, dir.path(), Path::new("here.pdf")).unwrap(),
            (dir.path().join("here.pdf"), None)
        );
    }

    /// #848 guard: `croft edit newdir/` names a folder, not a file. The
    /// trailing slash must not be read as a new file called `newdir`.
    #[test]
    fn edit_never_turns_a_path_ending_in_a_slash_into_a_file() {
        let dir = tempfile::tempdir().unwrap();
        let err = resolve_target(Verb::Edit, dir.path(), Path::new("newdir/"));
        assert!(err.is_err(), "{err:?}");
        assert!(
            !dir.path().join("newdir").exists(),
            "neither a file nor a folder was created"
        );
    }

    /// #848 guard: only `edit` creates. The refusal wording stays `view`'s
    /// own, and a missing folder is refused as a missing file, not created.
    #[test]
    fn view_never_creates_even_where_edit_would() {
        let dir = tempfile::tempdir().unwrap();
        for target in ["new.md", "no/such/new.md"] {
            let err = resolve_target(Verb::View, dir.path(), Path::new(target))
                .unwrap_err()
                .to_string();
            assert!(err.starts_with("croft view: no such file"), "{err}");
            assert!(!err.contains("edit"), "{err}");
        }
        assert_eq!(
            std::fs::read_dir(dir.path()).unwrap().count(),
            0,
            "nothing was created"
        );
    }

    #[test]
    fn a_tilde_is_a_filename_here_because_the_shell_already_had_its_turn() {
        // Every shell croft spawns expands `~` before exec, so one arriving
        // here was quoted and means a file of that name.
        assert_eq!(
            resolve(Path::new("/w"), Path::new("~")),
            PathBuf::from("/w/~")
        );
    }

    #[test]
    fn a_path_that_is_not_utf8_survives_the_round_trip() {
        // The reason `path` is bytes. A lossy String would turn this into
        // U+FFFD and the server would open a different file, or none.
        use std::os::unix::ffi::OsStrExt;
        let raw = std::ffi::OsStr::from_bytes(b"/tmp/\xff\xfe-broken.png");
        let original = PathBuf::from(raw);
        assert!(
            original.to_str().is_none(),
            "fixture must be invalid UTF-8, or this test proves nothing"
        );
        let wire = serde_json::to_string(&ViewRequest::new(&original)).unwrap();
        let back: ViewRequest = serde_json::from_str(&wire).unwrap();
        assert_eq!(back.to_path(), original);
    }

    #[test]
    fn a_path_with_a_newline_survives_because_the_encoding_is_not_the_delimiter() {
        // The wire is line-delimited, so a raw path containing `\n` would
        // truncate the request if it were written unencoded. JSON escapes it.
        let original = PathBuf::from("/tmp/two\nlines.pdf");
        let wire = serde_json::to_string(&ViewRequest::new(&original)).unwrap();
        assert!(!wire.contains('\n'), "the encoded form must be one line");
        let back: ViewRequest = serde_json::from_str(&wire).unwrap();
        assert_eq!(back.to_path(), original);
    }

    #[test]
    fn the_socket_is_keyed_by_pid_so_two_crofts_do_not_contend() {
        // The name is `view-<pid>-<nonce>.sock` now, so this pins the two
        // properties rather than the spelling: different crofts never share a
        // path, and the pid stays readable, which is what the sweep needs to
        // tell a dead croft's socket from a live one's.
        let dir = Path::new("/c");
        // NOT `assert_ne!(socket_path(dir, 10), socket_path(dir, 11))`: the
        // nonce alone makes any two calls differ, so that assertion holds
        // even if the pid were dropped from the name entirely. It reads as
        // evidence for a property it cannot see. Both pids being READABLE
        // back out is the property the sweep actually depends on, and it
        // implies the paths differ.
        let ten = socket_path(dir, 10);
        let eleven = socket_path(dir, 11);
        let name = ten.file_name().unwrap().to_str().unwrap();
        assert_eq!(pid_of_socket(name), Some(10));
        assert_eq!(
            pid_of_socket(eleven.file_name().unwrap().to_str().unwrap()),
            Some(11)
        );
        assert!(
            ten.starts_with("/c"),
            "and it stays in the cache dir: {ten:?}"
        );
    }

    /// Serve connections from a NON-blocking listener until told to stop,
    /// answering each with the reply `answer` picks for its index, and hand
    /// back how many arrived.
    ///
    /// Non-blocking so the thread can be told to stop without a connection
    /// arriving to unblock it: a test that must prove NO third connection
    /// happened cannot wait on a blocking `accept` for one.
    fn serve_counting(
        listener: std::os::unix::net::UnixListener,
        stop: std::sync::Arc<std::sync::atomic::AtomicBool>,
        answer: impl Fn(usize) -> ViewReply + Send + 'static,
    ) -> std::thread::JoinHandle<usize> {
        listener.set_nonblocking(true).unwrap();
        std::thread::spawn(move || {
            let mut seen = 0usize;
            while !stop.load(std::sync::atomic::Ordering::Relaxed) {
                match listener.accept() {
                    Ok((mut stream, _)) => {
                        // Production clears this on every accepted stream, and
                        // for the same reason: macOS inherits the listener's
                        // flags across accept, so the read below would return
                        // before the client has written.
                        stream.set_nonblocking(false).unwrap();
                        let deadline =
                            std::time::Instant::now() + std::time::Duration::from_secs(5);
                        if read_line_by_deadline(&stream, deadline, "no request").is_err() {
                            continue;
                        }
                        let reply = answer(seen);
                        seen += 1;
                        let _ = write_reply(&mut stream, &reply);
                    }
                    Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
                        std::thread::sleep(std::time::Duration::from_millis(2));
                    }
                    Err(_) => break,
                }
            }
            seen
        })
    }

    /// The one refusal `send` retries is retried, and the retry is what
    /// produces the success (#362).
    ///
    /// The connection COUNT is the assertion that matters. Asserting only the
    /// reply would pass if the server had answered `Ok` first time, which is
    /// the same green a deleted retry produces.
    #[test]
    fn a_frame_budget_refusal_is_retried_once_and_then_succeeds() {
        let tmp = tempfile::tempdir().unwrap();
        let sock = tmp.path().join("v.sock");
        let listener = std::os::unix::net::UnixListener::bind(&sock).unwrap();
        let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
        let server = serve_counting(listener, std::sync::Arc::clone(&stop), |i| {
            if i == 0 {
                retryable_refusal()
            } else {
                ViewReply::Ok
            }
        });

        let reply = send(&sock, &ViewRequest::new(Path::new("/tmp/x"))).unwrap();
        stop.store(true, std::sync::atomic::Ordering::Relaxed);
        let seen = server.join().unwrap();

        assert_eq!(
            reply,
            ViewReply::Ok,
            "the refusal names croft's own frame budget, which the client had \
             no part in, so a second attempt is owed"
        );
        assert_eq!(
            seen, 2,
            "and the success must come from a SECOND connection: delete the \
             retry and this is 1 with the refusal returned"
        );
    }

    /// A refusal croft sent before the request was written is still read
    /// (#2377).
    ///
    /// Croft refuses a request that misses its frame and closes; a client
    /// descheduled between `connect` and the write then finds the socket
    /// closed. The pair below is that moment made exact: croft's end has
    /// written the refusal and gone before the client writes a byte. Without
    /// the read-through the client returns the `EPIPE` and `send` never sees
    /// the one reply it retries, which is what printed "Broken pipe" at a busy
    /// shell (and failed `a_view_request_from_a_pane_opens_the_file_in_the_editor`
    /// on a loaded CI runner).
    #[test]
    fn a_refusal_sent_before_the_request_is_written_is_still_read() {
        use std::os::unix::net::UnixStream;
        let (mut gone, closed) = UnixStream::pair().unwrap();
        drop(closed);
        assert_eq!(
            gone.write_all(b"{}\n").unwrap_err().kind(),
            std::io::ErrorKind::BrokenPipe,
            "the write this test is about must fail the way a closed croft makes it fail"
        );

        let (mut client, mut croft) = UnixStream::pair().unwrap();
        write_reply(&mut croft, &retryable_refusal()).unwrap();
        drop(croft);

        assert_eq!(
            exchange(&mut client, &ViewRequest::new(Path::new("/tmp/x"))).unwrap(),
            retryable_refusal(),
            "the refusal is croft's answer and `send` retries it, so the broken \
             write must not hide it"
        );
    }

    /// A broken pipe with nothing behind it is still the write error (#2377).
    ///
    /// The read-through is for an answer croft gave; a croft that closed
    /// without one must not turn into "closed without replying", which
    /// describes a request croft read.
    #[test]
    fn a_broken_pipe_with_no_reply_is_reported_as_the_write_error() {
        let (mut client, croft) = std::os::unix::net::UnixStream::pair().unwrap();
        drop(croft);

        let err = exchange(&mut client, &ViewRequest::new(Path::new("/tmp/x"))).unwrap_err();
        assert_eq!(err.kind(), std::io::ErrorKind::BrokenPipe, "{err}");
    }

    /// A malformed reply behind a broken pipe is reported as malformed.
    ///
    /// Something answered, so this is not a croft that is gone: reported as
    /// the write error, it became `NoCroft` and sent git's sequence editor to
    /// its fallback editor, while the same reply after a write that went
    /// through is reported as the bad reply it is.
    #[test]
    fn a_malformed_reply_behind_a_broken_pipe_is_reported_as_malformed() {
        use std::os::unix::net::UnixStream;
        let (mut client, mut croft) = UnixStream::pair().unwrap();
        croft.write_all(b"not a reply\n").unwrap();
        drop(croft);

        let err = exchange(&mut client, &ViewRequest::new(Path::new("/tmp/x"))).unwrap_err();
        assert_eq!(err.kind(), std::io::ErrorKind::InvalidData, "{err}");
    }

    /// One retry, not a loop (#362).
    ///
    /// Nothing else in the suite would catch the `if` becoming a `while`, and
    /// a croft wedged for a whole frame would then hold the user's shell for
    /// as long as it stayed wedged.
    #[test]
    fn the_frame_budget_retry_is_one_attempt_not_a_loop() {
        let tmp = tempfile::tempdir().unwrap();
        let sock = tmp.path().join("v.sock");
        let listener = std::os::unix::net::UnixListener::bind(&sock).unwrap();
        let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
        let server = serve_counting(listener, std::sync::Arc::clone(&stop), |_| {
            retryable_refusal()
        });

        let reply = send(&sock, &ViewRequest::new(Path::new("/tmp/x"))).unwrap();
        // Long enough that a looping client would have made more attempts by
        // now, so the count below is a real bound rather than a race.
        std::thread::sleep(std::time::Duration::from_millis(50));
        stop.store(true, std::sync::atomic::Ordering::Relaxed);
        let seen = server.join().unwrap();

        assert_eq!(
            reply,
            retryable_refusal(),
            "a croft refusing twice is reported, not retried forever"
        );
        assert_eq!(seen, 2, "exactly two attempts, not {seen}");
    }

    /// The cap accepts EXACTLY `cap` bytes and refuses one more.
    ///
    /// `read_capped`'s `take(cap + 1)` and `>` carry a deliberate off-by-one
    /// argument that nothing could check while it was inline in `run`: a
    /// `take(cap)` cannot tell a legal cap-byte payload from a truncated
    /// larger one, and a `>=` would refuse the legal one. Both mutations are
    /// invisible in a suite that never drives the boundary.
    #[test]
    fn the_stdin_cap_accepts_exactly_the_cap_and_refuses_one_more() {
        assert_eq!(
            read_capped(&b"1234567"[..], 8).unwrap(),
            b"1234567",
            "under the cap"
        );
        assert_eq!(
            read_capped(&b"12345678"[..], 8).unwrap(),
            b"12345678",
            "EXACTLY the cap must be accepted: `take(cap)` plus `==` refuses \
             this, which is the mutation the `+ 1` exists to reject"
        );
        let over = read_capped(&b"123456789"[..], 8);
        assert!(
            over.is_err(),
            "one byte past the cap must be refused rather than truncated: \
             a truncated payload stages a corrupt file and reports success"
        );
        assert!(
            over.unwrap_err().to_string().contains("more than 8 bytes"),
            "and the message must name the cap the user hit: `contains(\"8\")` \
             passed on any stray 8 in any wording"
        );
    }

    /// The sniff reads a WINDOW of lines, and the window is load-bearing.
    ///
    /// `looks_delimited` takes the first 8 non-empty lines. Nothing
    /// distinguished that from "all lines", so widening or narrowing the
    /// window, or dropping the `take` entirely, was invisible: a fixture
    /// whose rows all agree passes either way.
    #[test]
    fn the_delimiter_sniff_judges_the_first_eight_lines_only() {
        let mut agreeing = String::new();
        for i in 0..8 {
            agreeing.push_str(&format!("a{i},b{i}\n"));
        }
        let mut disagreeing = agreeing.clone();
        disagreeing.push_str("this row has no delimiter at all\n");
        assert_eq!(
            looks_delimited(agreeing.as_bytes()),
            Some("csv"),
            "eight agreeing rows are a table"
        );
        assert_eq!(
            looks_delimited(disagreeing.as_bytes()),
            Some("csv"),
            "and a NINTH row that disagrees is outside the window: drop the \
             `take(8)` and this reads None, which is the change the window \
             exists to make and nothing else here would notice"
        );
        let early = format!("a,b\nno delimiter here\n{agreeing}");
        assert_eq!(
            looks_delimited(early.as_bytes()),
            None,
            "a row that disagrees INSIDE the window rejects the whole sniff"
        );
        // The FLOOR, which the three fixtures above do not reach: every one of
        // them stays green for any `take(n)` from 2 through 7, because the
        // first needs only two agreeing rows and the others disagree at rows 9
        // and 2. Seven agreeing rows and a disagreeing EIGHTH is red for every
        // window narrower than 8 and green at 8, so the number is now bounded
        // from both sides rather than only from above.
        let mut seven = String::new();
        for i in 0..7 {
            seven.push_str(&format!("a{i},b{i}\n"));
        }
        seven.push_str("the eighth row has no delimiter\n");
        assert_eq!(
            looks_delimited(seven.as_bytes()),
            None,
            "the eighth row is INSIDE the window, so it must reject the sniff"
        );
    }

    /// A quoted field holding a comma is one field, so piped CSV with names
    /// or thousands separators still opens in the grid (#1217).
    #[test]
    fn a_quoted_comma_is_part_of_its_field_in_the_sniff() {
        assert_eq!(looks_delimited(b"\"Doe, John\",42\nRoe,7\n"), Some("csv"));
        let data = b"name,qty,price\nwidget,3,9.99\ngadget,10,1.50\n\"comma, inc\",1,100\n";
        assert_eq!(looks_delimited(data), Some("csv"));
        // A quoted line break stays inside its record too.
        assert_eq!(
            looks_delimited(b"note,id\n\"two\nlines\",1\nok,2\n"),
            Some("csv")
        );
    }

    /// Negative: prose with commas is still not a table, a quoted comma
    /// doesn't paper over a row that really has a column too many, and a
    /// tab inside quotes still counts for TSV, which has no quoting.
    #[test]
    fn prose_and_ragged_rows_are_still_not_a_table() {
        assert_eq!(
            looks_delimited(b"Hello, world.\nThis is prose, really, honestly.\n"),
            None
        );
        assert_eq!(looks_delimited(b"a,b\n\"x, y\",1,2\n"), None);
        assert_eq!(looks_delimited(b"a\tb\n\"x\ty\"\t1\n"), None);
        assert_eq!(looks_delimited(b"a\tb\nx\t1\n"), Some("tsv"));
    }

    #[test]
    fn an_extension_hint_that_could_escape_the_staging_dir_is_refused() {
        // Refused, not sanitised: rewriting the user's input to something
        // that "works" is how a staged file lands where nobody named it.
        for bad in ["../x", "a/b", "a.b", "", "  ", "ext with space", "é"] {
            assert_eq!(sanitize_extension(bad), None, "{bad:?} must be refused");
        }
        assert_eq!(sanitize_extension("CSV").as_deref(), Some("csv"));
        assert_eq!(sanitize_extension(".png").as_deref(), Some("png"));
    }

    #[test]
    fn delimited_data_is_recognised_only_when_every_row_agrees() {
        assert_eq!(looks_delimited(b"a,b,c\n1,2,3\n4,5,6\n"), Some("csv"));
        assert_eq!(looks_delimited(b"a\tb\n1\t2\n"), Some("tsv"));
    }

    #[test]
    fn prose_with_commas_is_not_mistaken_for_a_table() {
        // The strictness is the point: a false positive opens an essay in a
        // spreadsheet grid, and the false negative costs one `--as csv`.
        assert_eq!(
            looks_delimited(
                b"Hello, world, and welcome.\nThis line, however, differs.\nOne more.\n"
            ),
            None
        );
    }

    #[test]
    fn a_single_line_is_a_sentence_rather_than_a_table() {
        // A lone header row is indistinguishable from a comma'd sentence.
        assert_eq!(looks_delimited(b"name,age,city\n"), None);
    }

    #[test]
    fn binary_content_never_reaches_the_delimiter_test() {
        assert_eq!(looks_delimited(b"a,b\n\x00\x01,\x02\n"), None);
    }

    #[test]
    fn the_hint_beats_the_sniff_which_beats_the_delimiter_guess() {
        let png = b"\x89PNG\r\n\x1a\n\x00\x00\x00\x0dIHDR";
        // Sniff wins over nothing.
        assert_eq!(stdin_extension(png, None).unwrap().as_deref(), Some("png"));
        // An explicit hint wins over the sniff: the user knows more than we do.
        assert_eq!(
            stdin_extension(png, Some("bin")).unwrap().as_deref(),
            Some("bin")
        );
        // Delimited text is the last resort.
        assert_eq!(
            stdin_extension(b"a,b\n1,2\n", None).unwrap().as_deref(),
            Some("csv")
        );
        // And plain text gets no extension, so it opens as text.
        assert_eq!(
            stdin_extension(b"just a log line\nand another\n", None).unwrap(),
            None
        );
    }

    #[test]
    fn an_unusable_as_flag_is_an_error_rather_than_a_silent_fallback() {
        // Falling back to the sniff would stage the bytes under a name the
        // user did not ask for and report success, so the only sign the flag
        // was rejected would be the file opening in the wrong viewer.
        let err = stdin_extension(b"a,b\n1,2\n", Some("../x")).unwrap_err();
        assert!(
            err.to_string().contains("--as"),
            "the message must name the flag, got {err}"
        );
        // And the good case still resolves.
        assert_eq!(
            stdin_extension(b"anything", Some("json"))
                .unwrap()
                .as_deref(),
            Some("json")
        );
    }

    #[test]
    fn staged_stdin_carries_the_content_and_the_routing_extension() {
        let tmp = tempfile::tempdir().unwrap();
        let p = stage_stdin(tmp.path(), b"a,b\n1,2\n", None).unwrap();
        assert_eq!(
            p.extension().and_then(|e| e.to_str()),
            Some("csv"),
            "the editor routes on extension, so staging without one lands in text"
        );
        assert_eq!(std::fs::read(&p).unwrap(), b"a,b\n1,2\n");
    }

    /// #1645: piped xz is staged under a name `archive::kind_from_ext`
    /// claims. `Editor::open` runs that extension route before its 50 MiB
    /// text-size guard and content sniffing only after it, so a bare `.xz`
    /// name sent a 50 to 100 MiB tar.xz stream to hex instead of the browser.
    #[test]
    fn staged_xz_stdin_routes_to_the_tar_xz_browser_by_extension() {
        let tmp = tempfile::tempdir().unwrap();
        let mut t = tar::Builder::new(Vec::new());
        let mut hdr = tar::Header::new_ustar();
        hdr.set_size(3);
        hdr.set_mode(0o644);
        hdr.set_cksum();
        t.append_data(&mut hdr, "a.txt", &b"hi\n"[..]).unwrap();
        let mut xz = Vec::new();
        lzma_rs::xz_compress(&mut std::io::Cursor::new(t.into_inner().unwrap()), &mut xz).unwrap();
        let p = stage_stdin(tmp.path(), &xz, None).unwrap();
        assert_eq!(
            crate::archive::kind_from_ext(&p),
            Some(crate::archive::ArchiveKind::TarXz),
            "{}",
            p.display()
        );
        let mut e = crate::widgets::editor::Editor::new();
        e.open(&p).unwrap();
        assert_eq!(e.archive.as_ref().expect("browsed").kind.label(), "TAR.XZ");
    }

    /// #1645: piped bzip2 and zstd are staged under names `kind_from_ext`
    /// claims too, for the same reason as xz above.
    #[test]
    fn staged_bzip2_and_zstd_stdin_route_to_their_tar_browsers_by_extension() {
        use crate::archive::{ArchiveKind, kind_from_ext};
        use crate::magic::Magic;
        for (magic, kind) in [
            (Magic::Bzip2, ArchiveKind::TarBz2),
            (Magic::Zstd, ArchiveKind::TarZst),
        ] {
            let name = format!("stdin.{}", extension_for(magic));
            assert_eq!(kind_from_ext(Path::new(&name)), Some(kind), "{name}");
        }
        // `pzstd` output piped in opens with a skippable frame, not the zstd
        // magic, and is still staged as a zstd tarball (#1645 review).
        let pzstd = b"\x50\x2a\x4d\x18\x04\x00\x00\x00skip\x28\xb5\x2f\xfd\x04\x00";
        assert_eq!(
            stdin_extension(pzstd, None).unwrap().as_deref(),
            Some("tzst")
        );
    }

    #[test]
    fn staged_stdin_is_readable_only_by_its_owner() {
        // Piped content is chosen by the user, and `vault read … | croft view -`
        // is exactly what this command invites. A default-mode file would sit
        // world-readable at a predictable path under the cache dir.
        use std::os::unix::fs::PermissionsExt;
        let tmp = tempfile::tempdir().unwrap();
        let p = stage_stdin(tmp.path(), b"hunter2", Some("txt")).unwrap();
        let mode = std::fs::metadata(&p).unwrap().permissions().mode() & 0o777;
        assert_eq!(mode, 0o600, "staged stdin was mode {mode:o}");
        let dir_mode = std::fs::metadata(p.parent().unwrap())
            .unwrap()
            .permissions()
            .mode()
            & 0o777;
        assert_eq!(dir_mode, 0o700, "the staging dir was mode {dir_mode:o}");
    }

    #[test]
    fn two_pipes_in_one_process_do_not_collide() {
        let tmp = tempfile::tempdir().unwrap();
        let a = stage_stdin(tmp.path(), b"first", Some("txt")).unwrap();
        let b = stage_stdin(tmp.path(), b"second", Some("txt")).unwrap();
        assert_ne!(a, b);
        assert_eq!(std::fs::read(&a).unwrap(), b"first");
        assert_eq!(std::fs::read(&b).unwrap(), b"second");
    }

    #[test]
    fn a_socket_name_carries_the_pid_first_and_a_tail_that_differs() {
        // The pid stays readable by the sweep, and the tail is what stops a
        // recycled pid from aiming a stale `CROFT_VIEW_SOCK` at a different
        // croft: two sockets for the SAME pid must not be the same file.
        let dir = PathBuf::from("/tmp/croft-test");
        let a = socket_path(&dir, 4242);
        let b = socket_path(&dir, 4242);
        let name_a = a.file_name().unwrap().to_str().unwrap();
        assert_eq!(
            pid_of_socket(name_a),
            Some(4242),
            "the sweep must read the pid"
        );
        assert_ne!(a, b, "two binds by one pid must not collide on one name");
        assert!(
            name_a.len() < 104,
            "the whole name has to fit an AF_UNIX path with room for the dir"
        );
    }

    #[test]
    fn a_socket_name_from_before_the_nonce_is_still_read() {
        // A croft that started before this change owns `view-<pid>.sock`, and
        // the sweep must still spare or clear it by pid rather than skip it
        // as unrecognised and leave it forever.
        assert_eq!(pid_of_socket("view-77.sock"), Some(77));
        assert_eq!(pid_of_socket("view-77-a1b2c3.sock"), Some(77));
        assert_eq!(pid_of_socket("not-a-view-socket"), None);
        assert_eq!(pid_of_socket("view-notapid.sock"), None);
    }

    #[test]
    fn a_staged_name_already_on_disk_is_stepped_past_not_overwritten() {
        // CONSTRUCTED, not predicted. Two earlier versions of this test were
        // vacuous: the first guessed `SEQ`'s next value, which every other
        // test in this binary bumps, and the second wrote its decoy one
        // directory ABOVE the `view-stdin` subdirectory `stage_stdin` writes
        // to, so the name under test was free either way and the retry arm
        // was never reached. Going through `stage_at` removes the guess: the
        // collision is a file this test put exactly where the next write
        // will land.
        //
        // The file it meets is somebody else's data - a croft that drew this
        // pid months ago - so stepping past is the whole point. `create_new`
        // is what stops the write landing on it, and the retry is what stops
        // the command failing forever.
        let tmp = tempfile::tempdir().unwrap();
        let taken = tmp.path().join("x.txt");
        std::fs::write(&taken, b"an older croft's bytes").unwrap();

        let path = stage_at(tmp.path(), "x.txt", b"mine").unwrap();

        assert_eq!(
            path.file_name().unwrap().to_str().unwrap(),
            "x-1.txt",
            "the taken name must be stepped past, not reused: {path:?}"
        );
        assert_eq!(
            std::fs::read(&taken).unwrap(),
            b"an older croft's bytes",
            "and the file that held it must be untouched"
        );
        assert_eq!(std::fs::read(&path).unwrap(), b"mine");
    }

    #[test]
    fn a_request_and_its_reply_cross_a_real_socket() {
        // The halves are written against each other, so a test that only
        // exercised the codecs would agree with itself. This runs the actual
        // connect / write / read / reply path.
        let tmp = tempfile::tempdir().unwrap();
        let sock = tmp.path().join("v.sock");
        let listener = crate::session::bind_socket_0600(&sock).unwrap();
        let sent = PathBuf::from("/tmp/some\u{fffd}where/a.pdf");
        let server = {
            let sent = sent.clone();
            std::thread::spawn(move || {
                let (mut stream, _) = listener.accept().unwrap();
                let req = read_request(
                    &stream,
                    std::time::Instant::now() + std::time::Duration::from_secs(5),
                )
                .unwrap();
                assert_eq!(req.to_path(), sent);
                write_reply(&mut stream, &ViewReply::Ok).unwrap();
            })
        };
        assert_eq!(
            send(&sock, &ViewRequest::new(&sent)).unwrap(),
            ViewReply::Ok
        );
        server.join().unwrap();
    }

    #[test]
    fn the_servers_error_text_reaches_the_client_verbatim() {
        // The side that knows why decides the message; the client prints it.
        let tmp = tempfile::tempdir().unwrap();
        let sock = tmp.path().join("v.sock");
        let listener = crate::session::bind_socket_0600(&sock).unwrap();
        let server = std::thread::spawn(move || {
            let (mut stream, _) = listener.accept().unwrap();
            let _ = read_request(
                &stream,
                std::time::Instant::now() + std::time::Duration::from_secs(5),
            );
            write_reply(
                &mut stream,
                &ViewReply::Err {
                    message: String::from("/x is a directory"),
                },
            )
            .unwrap();
        });
        let got = send(&sock, &ViewRequest::new(Path::new("/x"))).unwrap();
        assert_eq!(
            got,
            ViewReply::Err {
                message: String::from("/x is a directory")
            }
        );
        server.join().unwrap();
    }

    #[test]
    fn a_server_that_hangs_up_without_replying_is_an_error_not_a_success() {
        // Silence must not read as consent: the client would otherwise exit 0
        // having opened nothing.
        let tmp = tempfile::tempdir().unwrap();
        let sock = tmp.path().join("v.sock");
        let listener = crate::session::bind_socket_0600(&sock).unwrap();
        let server = std::thread::spawn(move || {
            let (stream, _) = listener.accept().unwrap();
            // Read the request BEFORE hanging up. Dropping straight after
            // accept makes the kind depend on whether the client's write
            // landed first: EPIPE if not, EOF if so. Reading first pins the
            // case this test is about: croft took the request and died.
            let _ = read_request(
                &stream,
                std::time::Instant::now() + std::time::Duration::from_secs(5),
            );
            drop(stream);
        });
        let err = send(&sock, &ViewRequest::new(Path::new("/x"))).unwrap_err();
        assert_eq!(err.kind(), std::io::ErrorKind::UnexpectedEof);
        server.join().unwrap();
    }
}