wsb-daemon 0.248.6265

wsb's daemon: the workbench, the GitHub mirror's schedule and peer continuity, for every workspace on the machine
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
use wsb::prelude::*;
use axum::{
    extract::{Query, State},
    http::StatusCode,
    Json,
};
use std::{
    collections::HashMap,
    fs,
    path::{Component, Path, PathBuf},
};

use super::{fleet::workspace_root_of, sessions::ErrorResponse};
use wsb::fleet::{config::GitModules, error::SuperGitError};
use wsb::git_backend::FileStatusKind;
use crate::web::handlers::fleet::RepoDetailedStatus;
use crate::web::ops::OpKind;
use crate::web::state::WebState;
use wsb::workspace_state::WorkspaceState;
use axum::extract::State as AxumState;

#[derive(Debug, Deserialize)]
pub struct WorkspacePathQuery {
    #[serde(default)]
    path: Option<String>,
}

#[derive(Debug, Deserialize)]
pub struct WorkspaceUpdateRequest {
    #[serde(default)]
    pub path: Option<String>,
}

#[derive(Debug, Serialize)]
pub struct WorkspaceUpdateResponse {
    pub path: String,
    pub version: String,
}

#[derive(Debug, Serialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum WorkspaceEntryKind {
    File,
    Directory,
}

#[derive(Debug, Serialize, Clone)]
pub struct WorkspaceSubmoduleInfo {
    pub name: String,
    pub version: Option<String>,
    pub github_repo: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
}

#[derive(Debug, Serialize)]
pub struct WorkspaceEntry {
    pub path: String,
    pub name: String,
    pub kind: WorkspaceEntryKind,
    pub hidden: bool,
    pub submodule: Option<WorkspaceSubmoduleInfo>,
    /// Git status for this entry, pre-computed by the backend.
    /// For files: the file's own status. For plain directories: the worst
    /// status among all files within. For submodule directories: null
    /// (use repo_status instead).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub git_status: Option<FileStatusKind>,
    /// Full repo status for submodule directory entries. Null for files and
    /// plain directories.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub repo_status: Option<RepoDetailedStatus>,
    /// For files inside a submodule, the workspace-relative path of the owning
    /// submodule (e.g. "libs/core"). Null for files in the superproject and for
    /// directory entries. Used by the diff view to scope git operations.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub repo_path: Option<String>,
}

/// The most listings one request may ask for.
///
/// A refresh asks for the listings the user has open, so this is far above any
/// real tree. Asking for more is refused outright rather than answered with a
/// silently truncated set, which would leave the caller believing it had
/// refreshed listings it never received.
pub const MAX_TREE_BATCH: usize = 512;

#[derive(Debug, Deserialize)]
pub struct WorkspaceTreesRequest {
    pub paths: Vec<String>,
}

/// One listing's outcome within a batch. A directory that cannot be read fails
/// on its own — the listings beside it were read and are still worth having.
#[derive(Debug, Serialize)]
#[serde(tag = "outcome", rename_all = "snake_case")]
pub enum WorkspaceTreeResult {
    Listed {
        path: String,
        entries: Vec<WorkspaceEntry>,
    },
    Failed {
        path: String,
        error: String,
    },
}

#[derive(Debug, Serialize)]
pub struct WorkspaceTreesResponse {
    pub root: String,
    pub trees: Vec<WorkspaceTreeResult>,
}

/// What a `changed` event tells the client to re-read.
///
/// Two different things can move, and they are named separately because they
/// cost differently: a listing whose own contents changed, and a repository
/// whose git status changed — which moves the status shown on every row
/// beneath it, however deep.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct WorkspaceChangedEvent {
    /// Listings to re-read outright.
    pub listings: Vec<String>,
    /// When set, every listing at or under this path belongs to the repository
    /// that changed; `""` means the whole workspace. Null when nothing about a
    /// repository's status moved.
    pub subtree: Option<String>,
}

impl WorkspaceChangedEvent {
    /// A directory's own contents changed — something was created, deleted,
    /// renamed or copied in it.
    pub fn listings(paths: Vec<String>) -> Self {
        Self {
            listings: paths,
            subtree: None,
        }
    }

    /// A repository's git status changed.
    ///
    /// Its row lives in the listing that contains it, and the git state of
    /// every row inside it moved with it — so both are named.
    pub fn repo_status(repo_path: &str) -> Self {
        if repo_path == "." {
            // The superproject owns the root listing and, transitively, every
            // path in the workspace that no submodule has claimed.
            return Self {
                listings: vec![String::new()],
                subtree: Some(String::new()),
            };
        }
        let containing_listing = match std::path::Path::new(repo_path).parent() {
            Some(parent) if !parent.as_os_str().is_empty() => wsb::platform::slash_path(parent),
            // A top-level submodule is a row in the root listing.
            _ => String::new(),
        };
        Self {
            listings: vec![containing_listing],
            subtree: Some(repo_path.to_string()),
        }
    }

    /// We fell behind the change stream and cannot know what moved. Everything
    /// the client holds is suspect, and saying so is the only honest answer.
    pub fn everything() -> Self {
        Self {
            listings: vec![String::new()],
            subtree: Some(String::new()),
        }
    }
}

#[derive(Debug, Serialize)]
pub struct WorkspaceFileResponse {
    pub root: String,
    pub path: String,
    pub content: String,
    /// Unix timestamp (seconds) of the file's mtime at the time of this read.
    pub mtime_secs: u64,
}

#[derive(Debug, Deserialize)]
pub struct WorkspaceFileSaveRequest {
    pub path: String,
    pub content: String,
    /// The mtime_secs the client last saw. If the file on disk is newer than
    /// this, the save is rejected (409 Conflict) to prevent silent overwrites.
    pub expected_mtime_secs: u64,
}

// ---------------------------------------------------------------------------
// File operation request types
// ---------------------------------------------------------------------------

#[derive(Debug, Deserialize)]
pub struct WorkspaceCreateFileRequest {
    pub path: String,
    #[serde(default)]
    pub content: Option<String>,
}

#[derive(Debug, Deserialize)]
pub struct WorkspaceCreateDirRequest {
    pub path: String,
}

#[derive(Debug, Deserialize)]
pub struct WorkspaceDeleteRequest {
    pub path: String,
    #[serde(default)]
    pub recursive: Option<bool>,
}

#[derive(Debug, Deserialize)]
pub struct WorkspaceRenameRequest {
    pub from: String,
    pub to: String,
}

#[derive(Debug, Deserialize)]
pub struct WorkspaceCopyRequest {
    pub from: String,
    pub to: String,
}

// ---------------------------------------------------------------------------
// File operation helper: parent directory path(s) to refresh
// ---------------------------------------------------------------------------

fn parent_dir_path(relative: &Path) -> String {
    match relative.parent() {
        Some(p) if !p.as_os_str().is_empty() => wsb::platform::slash_path(p),
        _ => String::new(),
    }
}

fn conflict_error(error: String) -> (StatusCode, Json<ErrorResponse>) {
    (StatusCode::CONFLICT, Json(ErrorResponse { error }))
}

// ---------------------------------------------------------------------------
// POST /workspace/create-file
// ---------------------------------------------------------------------------

pub async fn create_file(
    State(state): State<WebState>,
    Json(body): Json<WorkspaceCreateFileRequest>,
) -> Result<Json<WorkspaceFileResponse>, (StatusCode, Json<ErrorResponse>)> {
    let root = workspace_root_of(&state);
    let relative = sanitize_relative_path(&body.path)?;
    if relative.as_os_str().is_empty() {
        return Err(bad_request("file path must not be empty".to_string()));
    }
    let target = resolve_workspace_path(&root, &relative)?;
    let content = body.content.unwrap_or_default();

    if target.exists() {
        return Err(conflict_error(format!(
            "path '{}' already exists",
            display_relative_path(&relative)
        )));
    }

    // Ensure parent directory exists.
    if let Some(parent) = target.parent() {
        fs::create_dir_all(parent).map_err(internal_error)?;
    }

    fs::write(&target, content.as_bytes()).map_err(internal_error)?;

    let mtime_secs = fs::metadata(&target)
        .map(|m| {
            m.modified()
                .map(|t| {
                    t.duration_since(std::time::UNIX_EPOCH)
                        .unwrap_or_default()
                        .as_secs()
                })
                .unwrap_or(0)
        })
        .unwrap_or(0);

    // Notify watchers.
    let _ = state
        .file_changed_tx
        .send(crate::web::state::FileChangedEvent {
            path: display_relative_path(&relative),
            mtime_secs: Some(mtime_secs),
        });
    let parent_path = parent_dir_path(&relative);
    let _ = state
        .workspace_changed_tx
        .send(WorkspaceChangedEvent::listings(vec![parent_path]));

    Ok(Json(WorkspaceFileResponse {
        root: root.display().to_string(),
        path: display_relative_path(&relative),
        content,
        mtime_secs,
    }))
}

// ---------------------------------------------------------------------------
// POST /workspace/create-directory
// ---------------------------------------------------------------------------

#[derive(Debug, Serialize)]
pub struct WorkspaceCreateDirResponse {
    pub root: String,
    pub path: String,
}

pub async fn create_directory(
    State(state): State<WebState>,
    Json(body): Json<WorkspaceCreateDirRequest>,
) -> Result<Json<WorkspaceCreateDirResponse>, (StatusCode, Json<ErrorResponse>)> {
    let root = workspace_root_of(&state);
    let relative = sanitize_relative_path(&body.path)?;
    if relative.as_os_str().is_empty() {
        return Err(bad_request("directory path must not be empty".to_string()));
    }
    let target = resolve_workspace_path(&root, &relative)?;

    if target.exists() {
        return Err(conflict_error(format!(
            "path '{}' already exists",
            display_relative_path(&relative)
        )));
    }

    fs::create_dir_all(&target).map_err(internal_error)?;

    let parent_path = parent_dir_path(&relative);
    let _ = state
        .workspace_changed_tx
        .send(WorkspaceChangedEvent::listings(vec![parent_path]));

    Ok(Json(WorkspaceCreateDirResponse {
        root: root.display().to_string(),
        path: display_relative_path(&relative),
    }))
}

// ---------------------------------------------------------------------------
// POST /workspace/delete
// ---------------------------------------------------------------------------

pub async fn delete_entry(
    State(state): State<WebState>,
    Json(body): Json<WorkspaceDeleteRequest>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<ErrorResponse>)> {
    let root = workspace_root_of(&state);
    let relative = sanitize_relative_path(&body.path)?;
    if relative.as_os_str().is_empty() {
        return Err(bad_request("path must not be empty".to_string()));
    }
    let target = resolve_workspace_path(&root, &relative)?;
    let recursive = body.recursive.unwrap_or(false);
    let rel_str = display_relative_path(&relative);
    let label = format!("delete {}", rel_str);
    let parent_path = parent_dir_path(&relative);
    let rel_str_for_closure = rel_str.clone();

    let op_handle = state.ops.start_op(OpKind::FileOperation, label).await;

    let result =
        tokio::task::spawn_blocking(move || -> Result<(), (StatusCode, Json<ErrorResponse>)> {
            let rel_str = rel_str_for_closure;
            let meta = fs::metadata(&target)
                .map_err(|_| bad_request(format!("path '{}' does not exist", rel_str)))?;

            if meta.is_dir() {
                if !recursive {
                    // Check if directory is empty.
                    let is_empty = fs::read_dir(&target)
                        .map_err(internal_error)?
                        .next()
                        .is_none();
                    if !is_empty {
                        return Err(bad_request(format!(
                            "directory '{}' is not empty; set recursive=true to delete",
                            rel_str
                        )));
                    }
                    fs::remove_dir(&target).map_err(internal_error)?;
                } else {
                    fs::remove_dir_all(&target).map_err(internal_error)?;
                }
            } else {
                fs::remove_file(&target).map_err(internal_error)?;
            }

            Ok(())
        })
        .await
        .map_err(|e| internal_error(format!("delete task panicked: {e}")));

    match result {
        Ok(Ok(())) => {
            op_handle.complete().await;
            let _ = state
                .file_changed_tx
                .send(crate::web::state::FileChangedEvent {
                    path: rel_str,
                    mtime_secs: None,
                });
            let _ = state
                .workspace_changed_tx
                .send(WorkspaceChangedEvent::listings(vec![parent_path]));
            Ok(Json(serde_json::json!({ "deleted": true })))
        }
        Ok(Err(e)) => {
            op_handle.fail(e.1.error.clone()).await;
            Err(e)
        }
        Err(e) => {
            op_handle.fail(e.1.error.clone()).await;
            Err(e)
        }
    }
}

// ---------------------------------------------------------------------------
// POST /workspace/rename
// ---------------------------------------------------------------------------

pub async fn rename_entry(
    State(state): State<WebState>,
    Json(body): Json<WorkspaceRenameRequest>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<ErrorResponse>)> {
    let root = workspace_root_of(&state);
    let from_rel = sanitize_relative_path(&body.from)?;
    let to_rel = sanitize_relative_path(&body.to)?;
    if from_rel.as_os_str().is_empty() {
        return Err(bad_request("from path must not be empty".to_string()));
    }
    if to_rel.as_os_str().is_empty() {
        return Err(bad_request("to path must not be empty".to_string()));
    }

    let from_target = resolve_workspace_path(&root, &from_rel)?;
    let to_target = resolve_workspace_path(&root, &to_rel)?;

    if to_target.exists() {
        return Err(conflict_error(format!(
            "destination '{}' already exists",
            display_relative_path(&to_rel)
        )));
    }

    let from_str = display_relative_path(&from_rel);
    let to_str = display_relative_path(&to_rel);
    let label = format!("rename {} → {}", from_str, to_str);
    let from_parent = parent_dir_path(&from_rel);
    let to_parent = parent_dir_path(&to_rel);

    let op_handle = state.ops.start_op(OpKind::FileOperation, label).await;

    // Ensure destination parent exists.
    if let Some(parent) = to_target.parent() {
        if let Err(e) = fs::create_dir_all(parent) {
            let msg = e.to_string();
            op_handle.fail(msg.clone()).await;
            return Err(internal_error(msg));
        }
    }

    let result = tokio::task::spawn_blocking(move || {
        fs::rename(&from_target, &to_target).map_err(internal_error)
    })
    .await
    .map_err(|e| internal_error(format!("rename task panicked: {e}")));

    match result {
        Ok(Ok(())) => {
            op_handle.complete().await;
            let _ = state
                .file_changed_tx
                .send(crate::web::state::FileChangedEvent {
                    path: from_str,
                    mtime_secs: None,
                });
            let mut changed_dirs = vec![from_parent, to_parent];
            changed_dirs.dedup();
            let _ = state
                .workspace_changed_tx
                .send(WorkspaceChangedEvent::listings(changed_dirs));
            Ok(Json(serde_json::json!({ "renamed": true, "to": to_str })))
        }
        Ok(Err(e)) => {
            op_handle.fail(e.1.error.clone()).await;
            Err(e)
        }
        Err(e) => {
            op_handle.fail(e.1.error.clone()).await;
            Err(e)
        }
    }
}

// ---------------------------------------------------------------------------
// POST /workspace/copy
// ---------------------------------------------------------------------------

pub async fn copy_entry(
    State(state): State<WebState>,
    Json(body): Json<WorkspaceCopyRequest>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<ErrorResponse>)> {
    let root = workspace_root_of(&state);
    let from_rel = sanitize_relative_path(&body.from)?;
    let to_rel = sanitize_relative_path(&body.to)?;
    if from_rel.as_os_str().is_empty() {
        return Err(bad_request("from path must not be empty".to_string()));
    }
    if to_rel.as_os_str().is_empty() {
        return Err(bad_request("to path must not be empty".to_string()));
    }

    let from_target = resolve_workspace_path(&root, &from_rel)?;
    let to_target = resolve_workspace_path(&root, &to_rel)?;

    if to_target.exists() {
        return Err(conflict_error(format!(
            "destination '{}' already exists",
            display_relative_path(&to_rel)
        )));
    }

    let from_str = display_relative_path(&from_rel);
    let to_str = display_relative_path(&to_rel);
    let label = format!("copy {} → {}", from_str, to_str);
    let to_parent = parent_dir_path(&to_rel);
    let to_str_clone = to_str.clone();

    let op_handle = state.ops.start_op(OpKind::FileOperation, label).await;

    let result =
        tokio::task::spawn_blocking(move || -> Result<(), (StatusCode, Json<ErrorResponse>)> {
            let meta = fs::metadata(&from_target)
                .map_err(|_| bad_request(format!("source '{}' does not exist", from_str)))?;

            // Ensure destination parent exists.
            if let Some(parent) = to_target.parent() {
                fs::create_dir_all(parent).map_err(internal_error)?;
            }

            if meta.is_dir() {
                copy_dir_recursive(&from_target, &to_target).map_err(internal_error)?;
            } else {
                fs::copy(&from_target, &to_target).map_err(internal_error)?;
            }

            Ok(())
        })
        .await
        .map_err(|e| internal_error(format!("copy task panicked: {e}")));

    match result {
        Ok(Ok(())) => {
            op_handle.complete().await;
            let _ = state
                .workspace_changed_tx
                .send(WorkspaceChangedEvent::listings(vec![to_parent]));
            Ok(Json(
                serde_json::json!({ "copied": true, "to": to_str_clone }),
            ))
        }
        Ok(Err(e)) => {
            op_handle.fail(e.1.error.clone()).await;
            Err(e)
        }
        Err(e) => {
            op_handle.fail(e.1.error.clone()).await;
            Err(e)
        }
    }
}

/// Recursively copy a directory from `src` to `dst`.
fn copy_dir_recursive(src: &Path, dst: &Path) -> std::io::Result<()> {
    fs::create_dir_all(dst)?;
    for entry in fs::read_dir(src)? {
        let entry = entry?;
        let file_type = entry.file_type()?;
        let dest_path = dst.join(entry.file_name());
        if file_type.is_dir() {
            copy_dir_recursive(&entry.path(), &dest_path)?;
        } else {
            fs::copy(entry.path(), &dest_path)?;
        }
    }
    Ok(())
}

/// POST /api/v1/workspace/trees — read several listings in one request.
///
/// The explorer refreshes every listing a change can be seen in, and that is
/// routinely more than one: a repository's status moves the git state of every
/// row inside it. One request for all of them costs one round trip and one
/// snapshot of the git state, so every listing in the answer describes the
/// same moment — listings fetched one by one could not promise that.
pub async fn list_trees(
    State(state): State<WebState>,
    Json(body): Json<WorkspaceTreesRequest>,
) -> Result<Json<WorkspaceTreesResponse>, (StatusCode, Json<ErrorResponse>)> {
    let root = workspace_root_of(&state);
    let requested = plan_tree_batch(&body.paths)?;

    // Snapshot the git status once, outside the blocking task, so every listing
    // in this response is annotated from the same state.
    let git_snapshot: HashMap<String, RepoDetailedStatus> =
        state.git_status_snapshot.read().await.clone();

    let listing_root = root.clone();
    let trees =
        tokio::task::spawn_blocking(move || read_listings(&listing_root, requested, &git_snapshot))
            .await
            .map_err(|e| internal_error(format!("list_trees task panicked: {e}")))?;

    Ok(Json(WorkspaceTreesResponse {
        root: root.display().to_string(),
        trees,
    }))
}

/// Turn the paths a batch asked for into the listings it will read.
///
/// Everything that makes the *request* wrong is decided here and refuses the
/// whole batch: no paths, more paths than may be asked for, or a path that
/// escapes the workspace. What can only be wrong about a single directory —
/// that it is gone, or is not a directory — is left to the read, which reports
/// it against that path alone.
fn plan_tree_batch(
    paths: &[String],
) -> Result<Vec<(String, PathBuf)>, (StatusCode, Json<ErrorResponse>)> {
    if paths.is_empty() {
        return Err(bad_request(
            "a tree request must name at least one path".to_string(),
        ));
    }
    if paths.len() > MAX_TREE_BATCH {
        return Err(bad_request(format!(
            "a tree request may name at most {MAX_TREE_BATCH} paths, got {}",
            paths.len()
        )));
    }

    // The same path twice is one listing; the answer is keyed by path, so a
    // duplicate could only be an identical second copy of one entry.
    let mut requested: Vec<(String, PathBuf)> = Vec::with_capacity(paths.len());
    let mut seen = std::collections::HashSet::new();
    for raw in paths {
        let relative = sanitize_relative_path(raw)?;
        let display = display_relative_path(&relative);
        if seen.insert(display.clone()) {
            requested.push((display, relative));
        }
    }

    Ok(requested)
}

/// Read every planned listing, reporting each one's outcome on its own.
///
/// One unreadable directory does not cost the caller the listings beside it:
/// it is answered with the reason it failed, in the place its rows would have
/// been. Blocking; call it from a blocking task.
fn read_listings(
    root: &Path,
    requested: Vec<(String, PathBuf)>,
    git_snapshot: &HashMap<String, RepoDetailedStatus>,
) -> Vec<WorkspaceTreeResult> {
    let mut trees = Vec::with_capacity(requested.len());
    for (path, relative) in requested {
        let target = match resolve_workspace_path(root, &relative) {
            Ok(target) => target,
            Err((_, Json(error))) => {
                trees.push(WorkspaceTreeResult::Failed {
                    path,
                    error: error.error,
                });
                continue;
            }
        };
        if !target.exists() {
            trees.push(WorkspaceTreeResult::Failed {
                path,
                error: format!("workspace path '{}' no longer exists", relative.display()),
            });
            continue;
        }
        match read_listing(&target, &relative, git_snapshot) {
            Ok(entries) => trees.push(WorkspaceTreeResult::Listed { path, entries }),
            Err((_, Json(error))) => trees.push(WorkspaceTreeResult::Failed {
                path,
                error: error.error,
            }),
        }
    }
    trees
}

/// Read one directory into the rows the explorer draws.
///
/// The single-path and batch endpoints share this: there is exactly one
/// definition of what a listing contains — its entries, their git status, the
/// repositories among them — and both roads lead to it. Blocking; call it from
/// a blocking task.
fn read_listing(
    target: &Path,
    relative: &Path,
    git_snapshot: &HashMap<String, RepoDetailedStatus>,
) -> Result<Vec<WorkspaceEntry>, (StatusCode, Json<ErrorResponse>)> {
    let metadata = fs::metadata(target).map_err(internal_error)?;
    if !metadata.is_dir() {
        return Err(bad_request(format!(
            "workspace path '{}' is not a directory",
            display_relative_path(relative)
        )));
    }

    let mut raw_entries = fs::read_dir(target)
        .map_err(internal_error)?
        .collect::<Result<Vec<_>, _>>()
        .map_err(internal_error)?;

    raw_entries.sort_by(|left, right| {
        let left_kind = left.file_type().map(|ft| ft.is_dir()).unwrap_or(false);
        let right_kind = right.file_type().map(|ft| ft.is_dir()).unwrap_or(false);
        match right_kind.cmp(&left_kind) {
            std::cmp::Ordering::Equal => left.file_name().cmp(&right.file_name()),
            ordering => ordering,
        }
    });

    let visible_directory_paths = raw_entries
        .iter()
        .filter_map(|entry| {
            let file_type = entry.file_type().ok()?;
            if !file_type.is_dir() {
                return None;
            }
            let name = entry.file_name().to_string_lossy().into_owned();
            Some(join_relative_path(relative, &name))
        })
        .collect::<Vec<_>>();
    // Submodules nest: a submodule declares its own in its own .gitmodules.
    // Parse whichever repository's working tree this directory is — the
    // superproject at the root, a submodule at any depth below it — so a
    // nested submodule is presented as the project it is rather than as a
    // plain directory. A directory that is not a repository root declares
    // nothing.
    let dir_relative = display_relative_path(relative);
    let listing_repo_root = is_repository_root(target);
    let submodules = if listing_repo_root {
        load_workspace_submodules(target, &dir_relative, &visible_directory_paths)?
    } else {
        HashMap::new()
    };
    let uninitialized_submodules = if listing_repo_root {
        load_uninitialized_submodules(target, &dir_relative, &visible_directory_paths)?
    } else {
        vec![]
    };

    // Determine which repo owns the directory being listed:
    // - The superproject contains every path in the workspace.
    // - A submodule contains its own path and everything under it.
    // Several repositories therefore contain this directory once submodules
    // nest, and the one that owns it — whose index its files appear in — is
    // the deepest of them.
    let relative_str = dir_relative.clone();
    let owning_repo: Option<&RepoDetailedStatus> = git_snapshot
        .values()
        .filter(|r| {
            if r.is_superproject {
                true
            } else {
                relative_str == r.path || relative_str.starts_with(&format!("{}/", r.path))
            }
        })
        .max_by_key(|r| r.depth);

    // Build file→status map for files in this directory's owning repo.
    // Keys are repo-relative paths; we need workspace-relative paths for lookup.
    let (file_status_map, repo_path_prefix): (HashMap<String, FileStatusKind>, &str) =
        if let Some(repo) = owning_repo {
            let prefix = if repo.is_superproject { "" } else { &repo.path };
            let map = repo
                .files
                .iter()
                .map(|f| {
                    let ws_path = if prefix.is_empty() {
                        f.path.clone()
                    } else {
                        format!("{prefix}/{}", f.path)
                    };
                    (ws_path, f.status)
                })
                .collect();
            (map, prefix)
        } else {
            (HashMap::new(), "")
        };

    let mut entries = raw_entries
        .into_iter()
        .map(|entry| {
            let file_type = entry.file_type().map_err(internal_error)?;
            let file_name = entry.file_name().to_string_lossy().into_owned();
            let entry_relative = join_relative_path(relative, &file_name);
            let submodule = if file_type.is_dir() {
                submodules.get(&entry_relative).cloned()
            } else {
                None
            };

            let (git_status, repo_status, repo_path) = if file_type.is_dir() {
                if submodule.is_some() {
                    // Submodule directory: attach full repo status, no dir aggregation
                    let rs = git_snapshot.get(&entry_relative).cloned();
                    (None, rs, None)
                } else {
                    // Plain directory: aggregate worst file status under this prefix
                    let dir_status = aggregate_dir_status(&entry_relative, &file_status_map);
                    (dir_status, None, None)
                }
            } else {
                // File: direct status lookup and owning repo path
                let fs = file_status_map.get(&entry_relative).copied();
                let rp = if repo_path_prefix.is_empty() {
                    None
                } else {
                    Some(repo_path_prefix.to_string())
                };
                (fs, None, rp)
            };

            Ok(WorkspaceEntry {
                path: entry_relative.clone(),
                name: submodule
                    .as_ref()
                    .map(|s| s.name.clone())
                    .unwrap_or(file_name),
                kind: if file_type.is_dir() {
                    WorkspaceEntryKind::Directory
                } else {
                    WorkspaceEntryKind::File
                },
                hidden: is_hidden_name(&entry_relative),
                submodule,
                git_status,
                repo_status,
                repo_path,
            })
        })
        .collect::<Result<Vec<_>, _>>()?;

    for sub in &uninitialized_submodules {
        let rs = git_snapshot.get(&sub.path).cloned();
        entries.push(WorkspaceEntry {
            path: sub.path.clone(),
            name: sub.name.clone(),
            kind: WorkspaceEntryKind::Directory,
            hidden: is_hidden_name(&sub.path),
            submodule: Some(WorkspaceSubmoduleInfo {
                name: sub.name.clone(),
                version: None,
                github_repo: sub.github_repo.clone(),
                error: Some("submodule not initialized".to_string()),
            }),
            git_status: None,
            repo_status: rs,
            repo_path: None,
        });
    }

    entries.sort_by(compare_workspace_entries);

    Ok(entries)
}

/// Aggregate the worst git status for all files under `dir_path/` prefix.
/// Ignored files do not contribute — a directory containing only ignored
/// files returns None so it appears uncoloured.
fn aggregate_dir_status(
    dir_path: &str,
    file_status_map: &HashMap<String, FileStatusKind>,
) -> Option<FileStatusKind> {
    let prefix = format!("{dir_path}/");
    let mut worst: Option<FileStatusKind> = None;
    for (path, &status) in file_status_map {
        if !path.starts_with(&prefix) {
            continue;
        }
        if status == FileStatusKind::Ignored {
            continue;
        }
        worst = Some(match worst {
            None => status,
            Some(current) => higher_priority_status(current, status),
        });
        if worst == Some(FileStatusKind::Conflict) {
            return worst;
        }
    }
    worst
}

fn higher_priority_status(a: FileStatusKind, b: FileStatusKind) -> FileStatusKind {
    if status_priority(b) > status_priority(a) {
        b
    } else {
        a
    }
}

fn status_priority(s: FileStatusKind) -> u8 {
    match s {
        FileStatusKind::Conflict => 6,
        FileStatusKind::Deleted => 5,
        FileStatusKind::Modified => 4,
        FileStatusKind::Staged => 3,
        FileStatusKind::Renamed => 2,
        FileStatusKind::Untracked => 1,
        FileStatusKind::Ignored => 0,
    }
}

/// Submodules declared by the repository whose working tree is `repo_dir`,
/// keyed by workspace-relative path. `dir_relative` is that repository's own
/// workspace-relative path ("" for the superproject), so a submodule declared
/// inside a submodule comes back under its full path ("capdag/capdag-rs").
fn load_workspace_submodules(
    repo_dir: &Path,
    dir_relative: &str,
    visible_directory_paths: &[String],
) -> Result<HashMap<String, WorkspaceSubmoduleInfo>, (StatusCode, Json<ErrorResponse>)> {
    let gitmodules = match GitModules::parse(repo_dir) {
        Ok(gm) => gm,
        // No .gitmodules is a repository with no submodules, which is ordinary.
        Err(SuperGitError::NoSubmodules) => return Ok(HashMap::new()),
        // A .gitmodules that cannot be read is not: the projects it declares
        // would silently disappear from the tree, each one drawn as a plain
        // folder with no version, no status and no repository actions. The
        // listing fails instead, naming the file that has to be fixed.
        Err(e) => {
            return Err(internal_error(format!(
                "failed to read the submodules declared in '{}': {e}",
                repo_dir.join(".gitmodules").display()
            )))
        }
    };

    let visible_directory_paths = visible_directory_paths
        .iter()
        .cloned()
        .collect::<std::collections::HashSet<_>>();

    let mut submodules = HashMap::with_capacity(gitmodules.submodules.len());
    for submodule in gitmodules.submodules {
        let relative_path = workspace_relative_submodule_path(dir_relative, &submodule.path);
        if !visible_directory_paths.contains(&relative_path) {
            continue;
        }
        let submodule_root = repo_dir.join(&submodule.path);
        let version = wsb::state::read_version_from_path(&submodule_root)
            .map(|version| version.full_version)
            .ok();
        let github_repo =
            wsb_github::parse_github_url(&submodule.url).map(|(owner, repo)| format!("{owner}/{repo}"));
        let (name, error) = match read_submodule_project_name(&submodule_root) {
            Some(name) => (name, None),
            None => (submodule.name, None),
        };
        submodules.insert(
            relative_path,
            WorkspaceSubmoduleInfo {
                name,
                version,
                github_repo,
                error,
            },
        );
    }

    Ok(submodules)
}

/// A `.gitmodules` path is relative to the repository that declares it; the
/// explorer addresses everything from the workspace root.
fn workspace_relative_submodule_path(dir_relative: &str, submodule_path: &Path) -> String {
    // Joined exactly like the entry paths this is matched against
    // (`join_relative_path`), so the two always agree.
    if dir_relative.is_empty() {
        wsb::platform::slash_path(submodule_path)
    } else {
        wsb::platform::slash_path(&Path::new(dir_relative).join(submodule_path))
    }
}

/// Whether this directory is the working tree of a git repository — the only
/// place a `.gitmodules` file declares anything. A checked-out submodule has a
/// `.git` *file* pointing into the parent's gitdir, so both kinds count.
fn is_repository_root(dir: &Path) -> bool {
    dir.join(".git").exists()
}

struct UninitializedSubmodule {
    path: String,
    name: String,
    github_repo: Option<String>,
}

fn load_uninitialized_submodules(
    repo_dir: &Path,
    dir_relative: &str,
    existing_directory_paths: &[String],
) -> Result<Vec<UninitializedSubmodule>, (StatusCode, Json<ErrorResponse>)> {
    let gitmodules = match GitModules::parse(repo_dir) {
        Ok(gm) => gm,
        Err(SuperGitError::NoSubmodules) => return Ok(Vec::new()),
        Err(e) => {
            return Err(internal_error(format!(
                "failed to read the submodules declared in '{}': {e}",
                repo_dir.join(".gitmodules").display()
            )))
        }
    };

    let existing: std::collections::HashSet<_> = existing_directory_paths.iter().collect();

    let mut result = Vec::new();
    for submodule in gitmodules.submodules {
        let relative_path = workspace_relative_submodule_path(dir_relative, &submodule.path);
        if existing.contains(&relative_path) {
            continue;
        }
        let github_repo =
            wsb_github::parse_github_url(&submodule.url).map(|(owner, repo)| format!("{owner}/{repo}"));
        result.push(UninitializedSubmodule {
            path: relative_path,
            name: submodule.name,
            github_repo,
        });
    }
    Ok(result)
}

fn read_submodule_project_name(submodule_root: &Path) -> Option<String> {
    if !submodule_root.join(".wsb").join("state.json").exists() {
        return None;
    }
    let state = WorkspaceState::load(submodule_root).ok()?;
    state.project_name.and_then(|name| {
        let trimmed = name.trim();
        if trimmed.is_empty() {
            None
        } else {
            Some(trimmed.to_string())
        }
    })
}

pub async fn read_file(
    State(state): State<WebState>,
    Query(query): Query<WorkspacePathQuery>,
) -> Result<Json<WorkspaceFileResponse>, (StatusCode, Json<ErrorResponse>)> {
    let root = workspace_root_of(&state);
    let requested = query.path.as_deref().unwrap_or("").trim();
    if requested.is_empty() {
        return Err(bad_request("workspace file path is required".to_string()));
    }

    let relative = sanitize_relative_path(requested)?;
    let target = resolve_workspace_path(&root, &relative)?;

    let (root, relative, content, mtime_secs) = tokio::task::spawn_blocking(move || {
        let metadata = fs::metadata(&target).map_err(internal_error)?;
        if !metadata.is_file() {
            return Err(bad_request(format!(
                "workspace path '{}' is not a file",
                display_relative_path(&relative)
            )));
        }

        let mtime_secs = metadata
            .modified()
            .map(|t| {
                t.duration_since(std::time::UNIX_EPOCH)
                    .unwrap_or_default()
                    .as_secs()
            })
            .unwrap_or(0);

        let bytes = fs::read(&target).map_err(internal_error)?;
        let content = String::from_utf8(bytes).map_err(|_| {
            bad_request(format!(
                "workspace file '{}' is not valid UTF-8 text",
                display_relative_path(&relative)
            ))
        })?;

        Ok((root, relative, content, mtime_secs))
    })
    .await
    .map_err(|e| internal_error(format!("read_file task panicked: {e}")))??;

    Ok(Json(WorkspaceFileResponse {
        root: root.display().to_string(),
        path: display_relative_path(&relative),
        content,
        mtime_secs,
    }))
}

/// POST /api/v1/workspace/file — write content to a workspace file.
///
/// Requires `expected_mtime_secs` matching the file's current mtime to
/// prevent silent overwrites when the file changed on disk since it was loaded.
/// Returns 409 Conflict if the on-disk mtime is newer than `expected_mtime_secs`.
pub async fn save_file(
    State(state): State<WebState>,
    Json(body): Json<WorkspaceFileSaveRequest>,
) -> Result<Json<WorkspaceFileResponse>, (StatusCode, Json<ErrorResponse>)> {
    let root = workspace_root_of(&state);
    let relative = sanitize_relative_path(&body.path)?;
    let target = resolve_workspace_path(&root, &relative)?;
    let content = body.content.clone();
    let expected_mtime = body.expected_mtime_secs;

    let (root, relative, new_mtime_secs) = tokio::task::spawn_blocking(move || {
        let metadata = fs::metadata(&target).map_err(internal_error)?;
        if !metadata.is_file() {
            return Err(bad_request(format!(
                "workspace path '{}' is not a file",
                display_relative_path(&relative)
            )));
        }

        let disk_mtime = metadata
            .modified()
            .map(|t| {
                t.duration_since(std::time::UNIX_EPOCH)
                    .unwrap_or_default()
                    .as_secs()
            })
            .unwrap_or(0);

        if disk_mtime > expected_mtime {
            return Err((
                StatusCode::CONFLICT,
                Json(ErrorResponse {
                    error: format!(
                        "file '{}' was modified on disk (disk mtime {}, client mtime {}); \
                         reload before saving",
                        display_relative_path(&relative),
                        disk_mtime,
                        expected_mtime
                    ),
                }),
            ));
        }

        fs::write(&target, content.as_bytes()).map_err(internal_error)?;

        let new_mtime = fs::metadata(&target)
            .map(|m| {
                m.modified()
                    .map(|t| {
                        t.duration_since(std::time::UNIX_EPOCH)
                            .unwrap_or_default()
                            .as_secs()
                    })
                    .unwrap_or(0)
            })
            .unwrap_or(0);

        Ok((root, relative, new_mtime))
    })
    .await
    .map_err(|e| internal_error(format!("save_file task panicked: {e}")))??;

    // Notify SSE subscribers that this file changed so other clients refresh.
    let event = crate::web::state::FileChangedEvent {
        path: display_relative_path(&relative),
        mtime_secs: Some(new_mtime_secs),
    };
    let _ = state.file_changed_tx.send(event);

    Ok(Json(WorkspaceFileResponse {
        root: root.display().to_string(),
        path: display_relative_path(&relative),
        content: body.content,
        mtime_secs: new_mtime_secs,
    }))
}

pub async fn run_update(
    AxumState(state): AxumState<WebState>,
    Json(body): Json<WorkspaceUpdateRequest>,
) -> Result<Json<WorkspaceUpdateResponse>, (StatusCode, Json<ErrorResponse>)> {
    let root = workspace_root_of(&state);
    let relative = sanitize_relative_path(body.path.as_deref().unwrap_or(""))?;
    validate_update_target(&root, &relative)?;
    let target = resolve_workspace_path(&root, &relative)?;

    let metadata = fs::metadata(&target).map_err(internal_error)?;
    if !metadata.is_dir() {
        return Err(bad_request(format!(
            "workspace path '{}' is not a directory",
            display_relative_path(&relative)
        )));
    }

    let display_path = display_relative_path(&relative);
    let version = wsb::workspace_update::run_workspace_update_async(&target)
        .await
        .map_err(internal_error)?
        .version;

    Ok(Json(WorkspaceUpdateResponse {
        path: display_path,
        version,
    }))
}

fn sanitize_relative_path(raw: &str) -> Result<PathBuf, (StatusCode, Json<ErrorResponse>)> {
    let path = Path::new(raw);
    if path.is_absolute() {
        return Err(bad_request(format!(
            "workspace path '{}' must be relative to the workspace root",
            raw
        )));
    }

    let mut relative = PathBuf::new();
    for component in path.components() {
        match component {
            Component::CurDir => {}
            Component::Normal(part) => relative.push(part),
            Component::ParentDir => {
                return Err(bad_request(format!(
                    "workspace path '{}' must not traverse outside the workspace root",
                    raw
                )))
            }
            Component::RootDir | Component::Prefix(_) => {
                return Err(bad_request(format!(
                    "workspace path '{}' must be relative to the workspace root",
                    raw
                )))
            }
        }
    }

    Ok(relative)
}

fn validate_update_target(
    root: &Path,
    relative: &Path,
) -> Result<(), (StatusCode, Json<ErrorResponse>)> {
    if relative.as_os_str().is_empty() {
        return Ok(());
    }

    // A submodule at any depth is a valid target: the explorer offers the
    // update on every submodule row it draws, and it draws the nested ones too.
    let tree = match wsb::fleet::git::tree::SubmoduleTree::discover_allow_empty(root) {
        Ok(tree) => tree,
        Err(error) => return Err(internal_error(error)),
    };

    let relative_str = relative.to_string_lossy();
    if tree.find(&relative_str).is_some() {
        return Ok(());
    }

    Err(bad_request(format!(
        "workspace path '{}' is not a submodule root",
        relative_str
    )))
}

fn resolve_workspace_path(
    root: &Path,
    relative: &Path,
) -> Result<PathBuf, (StatusCode, Json<ErrorResponse>)> {
    let target = root.join(relative);
    if !target.starts_with(root) {
        return Err(bad_request(format!(
            "workspace path '{}' resolved outside the workspace root",
            display_relative_path(relative)
        )));
    }
    Ok(target)
}

// Every path the explorer is given is workspace-relative and written with `/`
// on every platform. On Windows a path's own spelling is `src\main.rs`, and a
// nested submodule came out `libs/core\vendor/dep`, half of each: the page,
// which addresses rows by these strings, matched neither.
fn join_relative_path(base: &Path, name: &str) -> String {
    if base.as_os_str().is_empty() {
        name.to_string()
    } else {
        wsb::platform::slash_path(&base.join(name))
    }
}

fn display_relative_path(path: &Path) -> String {
    wsb::platform::slash_path(path)
}

fn compare_workspace_entries(left: &WorkspaceEntry, right: &WorkspaceEntry) -> std::cmp::Ordering {
    let left_is_directory = left.kind == WorkspaceEntryKind::Directory;
    let right_is_directory = right.kind == WorkspaceEntryKind::Directory;
    match right_is_directory.cmp(&left_is_directory) {
        std::cmp::Ordering::Equal => {
            let left_is_submodule = left.submodule.is_some();
            let right_is_submodule = right.submodule.is_some();
            match right_is_submodule.cmp(&left_is_submodule) {
                std::cmp::Ordering::Equal => left.name.cmp(&right.name),
                ordering => ordering,
            }
        }
        ordering => ordering,
    }
}

fn is_hidden_name(path: &str) -> bool {
    Path::new(path)
        .file_name()
        .and_then(|name| name.to_str())
        .is_some_and(|name| name.starts_with('.'))
}

fn bad_request(error: String) -> (StatusCode, Json<ErrorResponse>) {
    (StatusCode::BAD_REQUEST, Json(ErrorResponse { error }))
}

fn internal_error(error: impl ToString) -> (StatusCode, Json<ErrorResponse>) {
    (
        StatusCode::INTERNAL_SERVER_ERROR,
        Json(ErrorResponse {
            error: error.to_string(),
        }),
    )
}

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

    #[test]
    fn sanitize_relative_path_rejects_parent_traversal() {
        let error = sanitize_relative_path("../secret.txt").unwrap_err();
        assert_eq!(error.0, StatusCode::BAD_REQUEST);
        assert!(error.1.error.contains("must not traverse outside"));
    }

    #[test]
    fn list_tree_sorts_directories_before_files() {
        let temp = TempDir::new().unwrap();
        fs::create_dir(temp.path().join("src")).unwrap();
        fs::write(temp.path().join("Cargo.toml"), "wsb").unwrap();
        fs::write(temp.path().join("README.md"), "docs").unwrap();

        let mut entries = fs::read_dir(temp.path())
            .unwrap()
            .collect::<Result<Vec<_>, _>>()
            .unwrap();
        entries.sort_by(|left, right| {
            let left_kind = left.file_type().map(|ft| ft.is_dir()).unwrap_or(false);
            let right_kind = right.file_type().map(|ft| ft.is_dir()).unwrap_or(false);
            match right_kind.cmp(&left_kind) {
                std::cmp::Ordering::Equal => left.file_name().cmp(&right.file_name()),
                ordering => ordering,
            }
        });

        let names = entries
            .into_iter()
            .map(|entry| entry.file_name().to_string_lossy().into_owned())
            .collect::<Vec<_>>();
        assert_eq!(names, vec!["src", "Cargo.toml", "README.md"]);
    }

    #[test]
    fn resolve_workspace_path_stays_under_root() {
        let temp = TempDir::new().unwrap();
        let relative = match sanitize_relative_path("src/lib.rs") {
            Ok(value) => value,
            Err(_) => panic!("expected relative path to sanitize"),
        };
        let resolved = match resolve_workspace_path(temp.path(), &relative) {
            Ok(value) => value,
            Err(_) => panic!("expected workspace path to resolve under root"),
        };
        assert!(resolved.starts_with(temp.path()));
        assert!(resolved.ends_with("src/lib.rs"));
    }

    #[test]
    fn hidden_entries_are_detected_from_leaf_name() {
        assert!(is_hidden_name(".git"));
        assert!(is_hidden_name("dir/.env"));
        assert!(!is_hidden_name("src/lib.rs"));
    }

    #[test]
    fn load_workspace_submodules_reads_versions_from_version_txt() {
        let temp = TempDir::new().unwrap();
        fs::write(
            temp.path().join(".gitmodules"),
            r#"[submodule "core"]
	path = libs/core
	url = https://github.com/example/core.git
"#,
        )
        .unwrap();
        fs::create_dir_all(temp.path().join("libs/core")).unwrap();
        fs::write(temp.path().join("libs/core/version.txt"), "0.414.56214\n").unwrap();

        let submodules =
            load_workspace_submodules(temp.path(), "", &[String::from("libs/core")]).unwrap();

        assert_eq!(submodules.len(), 1);
        assert_eq!(submodules["libs/core"].name, "core");
        assert_eq!(
            submodules["libs/core"].version.as_deref(),
            Some("0.414.56214")
        );
    }

    #[test]
    fn load_workspace_submodules_omits_version_when_unavailable() {
        let temp = TempDir::new().unwrap();
        fs::write(
            temp.path().join(".gitmodules"),
            r#"[submodule "thesis"]
	path = thesis
	url = https://github.com/example/thesis.git
"#,
        )
        .unwrap();
        fs::create_dir_all(temp.path().join("thesis")).unwrap();

        let submodules =
            load_workspace_submodules(temp.path(), "", &[String::from("thesis")]).unwrap();

        assert_eq!(submodules.len(), 1);
        assert_eq!(submodules["thesis"].name, "thesis");
        assert_eq!(submodules["thesis"].version, None);
    }

    #[test]
    fn read_submodule_project_name_uses_workspace_state_when_present() {
        let temp = TempDir::new().unwrap();
        fs::create_dir_all(temp.path().join(".wsb")).unwrap();
        fs::write(
            temp.path().join(".wsb/state.json"),
            r#"{
  "version": 1,
  "project_name": "Capdag Core",
  "tools": {},
  "wstemplate_entries": [],
  "completion_hint_shown": false
}"#,
        )
        .unwrap();

        assert_eq!(
            read_submodule_project_name(temp.path()).as_deref(),
            Some("Capdag Core")
        );
    }

    #[test]
    fn compare_workspace_entries_places_submodules_before_other_nodes() {
        let mut entries = vec![
            WorkspaceEntry {
                path: "README.md".to_string(),
                name: "README.md".to_string(),
                kind: WorkspaceEntryKind::File,
                hidden: false,
                submodule: None,
                git_status: None,
                repo_status: None,
                repo_path: None,
            },
            WorkspaceEntry {
                path: "src".to_string(),
                name: "src".to_string(),
                kind: WorkspaceEntryKind::Directory,
                hidden: false,
                submodule: None,
                git_status: None,
                repo_status: None,
                repo_path: None,
            },
            WorkspaceEntry {
                path: "capdag".to_string(),
                name: "capdag".to_string(),
                kind: WorkspaceEntryKind::Directory,
                hidden: false,
                submodule: Some(WorkspaceSubmoduleInfo {
                    name: "capdag".to_string(),
                    version: Some("0.414.56214".to_string()),
                    github_repo: None,
                    error: None,
                }),
                git_status: None,
                repo_status: None,
                repo_path: None,
            },
        ];

        entries.sort_by(compare_workspace_entries);

        assert_eq!(
            entries
                .iter()
                .map(|entry| entry.name.as_str())
                .collect::<Vec<_>>(),
            vec!["capdag", "src", "README.md"]
        );
    }

    /// TEST9605: a directory is described by the `.gitmodules` of the
    /// repository it belongs to, and by no other. Listing a submodule reads
    /// that submodule's own declarations — the superproject's, whose paths are
    /// relative to a different root, must never bleed in (that once rendered
    /// the same subtree inside itself forever).
    #[test]
    fn test9605_a_listing_reads_only_its_own_repositorys_declarations() {
        let temp = TempDir::new().unwrap();
        fs::write(
            temp.path().join(".gitmodules"),
            r#"[submodule "child"]
	path = child
	url = https://github.com/example/child.git
"#,
        )
        .unwrap();
        fs::create_dir_all(temp.path().join("child/foo")).unwrap();
        fs::create_dir_all(temp.path().join("child/src")).unwrap();

        // Listing "child": it declares nothing of its own, so nothing is
        // reported — least of all the superproject's "child" entry.
        let visible = vec!["child/foo".to_string(), "child/src".to_string()];
        let result =
            load_workspace_submodules(&temp.path().join("child"), "child", &visible).unwrap();
        assert!(
            result.is_empty(),
            "a repository's declarations belong to it alone, got: {result:?}"
        );
    }

    /// TEST9606: a submodule declared inside a submodule is reported as the
    /// project it is, addressed from the workspace root. The explorer used to
    /// read only the root `.gitmodules`, so everything below the first level
    /// was drawn as a plain directory.
    #[test]
    fn test9606_nested_submodules_are_reported_under_their_full_path() {
        let temp = TempDir::new().unwrap();
        fs::create_dir_all(temp.path().join("libs/core/vendor/dep")).unwrap();
        fs::write(
            temp.path().join("libs/core/.gitmodules"),
            r#"[submodule "dep"]
	path = vendor/dep
	url = https://github.com/example/dep.git
"#,
        )
        .unwrap();
        fs::write(
            temp.path().join("libs/core/vendor/dep/version.txt"),
            "1.2.3\n",
        )
        .unwrap();

        let visible = vec!["libs/core/vendor/dep".to_string()];
        let result =
            load_workspace_submodules(&temp.path().join("libs/core"), "libs/core", &visible)
                .unwrap();

        assert_eq!(result.len(), 1);
        let nested = result
            .get("libs/core/vendor/dep")
            .expect("the nested submodule is keyed by its workspace-relative path");
        assert_eq!(nested.name, "dep");
        assert_eq!(nested.version.as_deref(), Some("1.2.3"));
    }

    /// TEST9607: only a repository's working tree declares submodules. A
    /// `.gitmodules` sitting in a plain directory — a fixture, a template, a
    /// copy — describes nothing about this workspace and must not be read as
    /// if it did.
    #[test]
    fn test9607_a_plain_directory_declares_no_submodules() {
        let temp = TempDir::new().unwrap();
        fs::create_dir_all(temp.path().join("fixtures/sub")).unwrap();
        fs::write(
            temp.path().join("fixtures/.gitmodules"),
            r#"[submodule "sub"]
	path = sub
	url = https://github.com/example/sub.git
"#,
        )
        .unwrap();

        assert!(!is_repository_root(&temp.path().join("fixtures")));

        fs::create_dir_all(temp.path().join("repo/.git")).unwrap();
        assert!(is_repository_root(&temp.path().join("repo")));

        // A checked-out submodule carries a .git *file*, not a directory.
        fs::create_dir_all(temp.path().join("sub")).unwrap();
        fs::write(
            temp.path().join("sub/.git"),
            "gitdir: ../.git/modules/sub\n",
        )
        .unwrap();
        assert!(is_repository_root(&temp.path().join("sub")));
    }

    #[test]
    fn load_uninitialized_submodules_only_reports_missing_root_children() {
        // "sub" is in .gitmodules but not on disk — it is uninitialized.
        // "initialized" is on disk and in .gitmodules — it is initialized.
        // The function returns only the missing ones when given the on-disk set.
        let temp = TempDir::new().unwrap();
        fs::write(
            temp.path().join(".gitmodules"),
            r#"[submodule "sub"]
	path = sub
	url = https://github.com/example/sub.git
[submodule "initialized"]
	path = initialized
	url = https://github.com/example/initialized.git
"#,
        )
        .unwrap();
        fs::create_dir_all(temp.path().join("initialized")).unwrap();

        // Root listing — visible dirs are direct children (single segment).
        let root_visible_dirs = vec!["initialized".to_string()];
        let result = load_uninitialized_submodules(temp.path(), "", &root_visible_dirs).unwrap();
        assert_eq!(result.len(), 1, "only 'sub' is uninitialized");
        assert_eq!(result[0].path, "sub");
    }

    /// TEST9647: a `.gitmodules` that cannot be read fails the listing it
    /// belongs to. It used to be swallowed with a log line, so every project
    /// the file declares vanished from the tree — drawn as plain folders with
    /// no version, no status and no repository actions, and nothing on screen
    /// to say why.
    #[test]
    fn test9647_an_unreadable_gitmodules_fails_the_listing_that_declares_it() {
        let temp = TempDir::new().unwrap();
        fs::create_dir_all(temp.path().join(".git")).unwrap();
        fs::create_dir_all(temp.path().join("libs")).unwrap();
        // A key outside any [section] header — the shape a hand-edit produces.
        fs::write(temp.path().join(".gitmodules"), "path = libs\n").unwrap();

        let planned = plan_tree_batch(&[String::new()]).unwrap();
        let trees = read_listings(temp.path(), planned, &HashMap::new());

        match &trees[0] {
            WorkspaceTreeResult::Failed { path, error } => {
                assert_eq!(path, "");
                assert!(error.contains(".gitmodules"), "got: {error}");
            }
            other => panic!("an unreadable .gitmodules must fail the listing, got {other:?}"),
        }
    }

    /// TEST9638: what makes a batch request wrong refuses the batch; what makes
    /// one directory unreadable is answered against that directory. A caller
    /// that asked for something impossible must be told so, not handed a
    /// shorter list it might mistake for an answer.
    #[test]
    fn test9638_a_batch_refuses_bad_requests_and_isolates_bad_paths() {
        let empty = plan_tree_batch(&[]).unwrap_err();
        assert_eq!(empty.0, StatusCode::BAD_REQUEST);
        assert!(empty.1.error.contains("at least one path"));

        let too_many: Vec<String> = (0..=MAX_TREE_BATCH).map(|i| format!("dir{i}")).collect();
        let refused = plan_tree_batch(&too_many).unwrap_err();
        assert_eq!(refused.0, StatusCode::BAD_REQUEST);
        assert!(refused.1.error.contains(&MAX_TREE_BATCH.to_string()));

        let escaping = plan_tree_batch(&["../outside".to_string()]).unwrap_err();
        assert_eq!(escaping.0, StatusCode::BAD_REQUEST);

        // The same listing asked for twice is one listing.
        let planned =
            plan_tree_batch(&["src".to_string(), "./src".to_string(), "docs".to_string()]).unwrap();
        assert_eq!(
            planned
                .iter()
                .map(|(path, _)| path.as_str())
                .collect::<Vec<_>>(),
            vec!["src", "docs"]
        );
    }

    /// TEST9639: every listing in a batch is read, and one that cannot be read
    /// fails alone. A directory deleted between the change event and the
    /// refresh must not cost the caller the listings it asked for beside it.
    #[test]
    fn test9639_one_unreadable_listing_does_not_lose_the_others() {
        let temp = TempDir::new().unwrap();
        fs::create_dir_all(temp.path().join("src")).unwrap();
        fs::write(temp.path().join("src/main.rs"), "fn main() {}\n").unwrap();
        fs::write(temp.path().join("README.md"), "docs\n").unwrap();

        let planned = plan_tree_batch(&[
            String::new(),
            "src".to_string(),
            "gone".to_string(),
            "README.md".to_string(),
        ])
        .unwrap();
        let trees = read_listings(temp.path(), planned, &HashMap::new());

        assert_eq!(trees.len(), 4);
        match &trees[0] {
            WorkspaceTreeResult::Listed { path, entries } => {
                assert_eq!(path, "");
                assert!(entries.iter().any(|e| e.path == "src"));
                assert!(entries.iter().any(|e| e.path == "README.md"));
            }
            other => panic!("the root listing should have been read, got {other:?}"),
        }
        match &trees[1] {
            WorkspaceTreeResult::Listed { path, entries } => {
                assert_eq!(path, "src");
                assert_eq!(
                    entries.iter().map(|e| e.path.as_str()).collect::<Vec<_>>(),
                    vec!["src/main.rs"]
                );
            }
            other => panic!("src should have been read, got {other:?}"),
        }
        match &trees[2] {
            WorkspaceTreeResult::Failed { path, error } => {
                assert_eq!(path, "gone");
                assert!(error.contains("no longer exists"), "got: {error}");
            }
            other => panic!("a missing directory should fail, got {other:?}"),
        }
        match &trees[3] {
            WorkspaceTreeResult::Failed { path, error } => {
                assert_eq!(path, "README.md");
                assert!(error.contains("not a directory"), "got: {error}");
            }
            other => panic!("a file is not a listing, got {other:?}"),
        }
    }

    /// TEST9632: a repository's status change names the one listing that draws
    /// its row, and the subtree whose rows carry its git state. The root used
    /// to be named for every repository in the fleet — for a nested repository,
    /// a listing that does not contain its row at all — while the rows inside
    /// the repository, the ones whose colour actually moved, were named by
    /// nothing and stayed stale until something else re-read them.
    #[test]
    fn test9632_a_repo_status_names_its_listing_and_its_subtree() {
        let superproject = WorkspaceChangedEvent::repo_status(".");
        assert_eq!(superproject.listings, vec![String::new()]);
        assert_eq!(superproject.subtree.as_deref(), Some(""));

        let top_level = WorkspaceChangedEvent::repo_status("capdag");
        assert_eq!(top_level.listings, vec![String::new()]);
        assert_eq!(top_level.subtree.as_deref(), Some("capdag"));

        let nested = WorkspaceChangedEvent::repo_status("capdag/capdag-rs");
        assert_eq!(nested.listings, vec!["capdag".to_string()]);
        assert_eq!(nested.subtree.as_deref(), Some("capdag/capdag-rs"));

        let deep = WorkspaceChangedEvent::repo_status("libs/core/vendor/dep");
        assert_eq!(deep.listings, vec!["libs/core/vendor".to_string()]);
        assert_eq!(deep.subtree.as_deref(), Some("libs/core/vendor/dep"));
    }

    /// TEST9637: a directory's own contents changing is not a repository's
    /// status changing. A created or deleted file re-reads the one directory it
    /// happened in — naming a subtree there would re-read every listing under
    /// it for a change that cannot be seen in any of them.
    #[test]
    fn test9637_a_content_change_names_no_subtree() {
        let created = WorkspaceChangedEvent::listings(vec!["src/web".to_string()]);
        assert_eq!(created.listings, vec!["src/web".to_string()]);
        assert_eq!(created.subtree, None);

        // Falling behind the stream is the one case where nothing is known, and
        // it says so rather than guessing at a smaller answer.
        let lost = WorkspaceChangedEvent::everything();
        assert_eq!(lost.listings, vec![String::new()]);
        assert_eq!(lost.subtree.as_deref(), Some(""));
    }

    /// TEST9615: "Workspace Update" is offered on every submodule row the
    /// explorer draws, so it must accept a submodule at any depth — and still
    /// refuse a directory that is not a submodule root at all.
    #[test]
    fn test9615_update_targets_are_submodules_at_any_depth() {
        let temp = TempDir::new().unwrap();
        fs::write(
            temp.path().join(".gitmodules"),
            "[submodule \"core\"]\n\tpath = libs/core\n\turl = https://github.com/example/core.git\n",
        )
        .unwrap();
        fs::create_dir_all(temp.path().join("libs/core/.git")).unwrap();
        fs::write(
            temp.path().join("libs/core/.gitmodules"),
            "[submodule \"dep\"]\n\tpath = vendor/dep\n\turl = https://github.com/example/dep.git\n",
        )
        .unwrap();
        fs::create_dir_all(temp.path().join("libs/core/vendor/dep")).unwrap();
        fs::create_dir_all(temp.path().join("libs/core/src")).unwrap();

        assert!(validate_update_target(temp.path(), Path::new("libs/core")).is_ok());
        assert!(validate_update_target(temp.path(), Path::new("libs/core/vendor/dep")).is_ok());
        assert!(validate_update_target(temp.path(), Path::new("")).is_ok());

        let error = validate_update_target(temp.path(), Path::new("libs/core/src")).unwrap_err();
        assert_eq!(error.0, StatusCode::BAD_REQUEST);
        assert!(error.1.error.contains("is not a submodule root"));
    }

    /// TEST9608: an uninitialized submodule of a submodule is still shown, at
    /// its own place in the tree, so a checkout that was never run is visible
    /// where the missing directory would be rather than silently absent.
    #[test]
    fn test9608_uninitialized_nested_submodules_keep_their_full_path() {
        let temp = TempDir::new().unwrap();
        fs::create_dir_all(temp.path().join("libs/core")).unwrap();
        fs::write(
            temp.path().join("libs/core/.gitmodules"),
            r#"[submodule "dep"]
	path = vendor/dep
	url = https://github.com/example/dep.git
"#,
        )
        .unwrap();

        let result =
            load_uninitialized_submodules(&temp.path().join("libs/core"), "libs/core", &[])
                .unwrap();

        assert_eq!(result.len(), 1);
        assert_eq!(result[0].path, "libs/core/vendor/dep");
        assert_eq!(result[0].name, "dep");
    }
}