vector-core 0.13.1

Core library for Vector: the single source of truth for all Vector clients, SDKs and interfaces.
Documentation
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
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
//! Database layer — SQLite with per-account databases.
//!
//! Architecture:
//! - Read pool: multiple connections for parallel reads (WAL mode)
//! - Write pool: single Mutex-protected connection (serialized writes)
//! - RAII guards: auto-return connections to pools on drop
//!
//! All connection functions use static `DATA_DIR` — no Tauri AppHandle required.

use std::path::PathBuf;
use std::sync::{Arc, Mutex, OnceLock, LazyLock, RwLock};
use std::ops::{Deref, DerefMut};

use serde::{Deserialize, Serialize};

pub mod settings;
pub mod at_rest;
pub mod miniapps;
pub mod schema;
pub mod profiles;
pub mod id_cache;
pub mod events;
pub mod attachments;
pub mod media_store;
pub mod chats;
pub mod wrappers;
pub mod nip17_keys;
pub mod community;
pub mod v1_purge;
pub mod bots;
pub mod notify;
pub mod saved;
#[cfg(target_arch = "wasm32")]
pub mod webfs;
#[cfg(target_arch = "wasm32")]
use webfs::{clear_active_account_file_in, list_account_npubs_in, read_active_account_file_in, write_active_account_file_in};

pub use settings::{
    get_sql_setting, set_sql_setting, advance_u64_setting, get_pkey, set_pkey, get_seed, set_seed, remove_setting,
    get_signer_type, set_signer_type,
    get_bunker_url, set_bunker_url,
    get_bunker_remote_pubkey, set_bunker_remote_pubkey,
    commit_bunker_account_setup,
    get_nip55_user_pubkey, set_nip55_user_pubkey,
    get_nip55_signer_package, set_nip55_signer_package,
    commit_nip55_account_setup, commit_external_signer_setup,
};

// ============================================================================
// App Data Directory
// ============================================================================

static APP_DATA_DIR: OnceLock<PathBuf> = OnceLock::new();

pub fn set_app_data_dir(path: PathBuf) {
    let _ = APP_DATA_DIR.set(path);
}

/// The data dir every test must use — ONE per process, alive for its whole life.
///
/// `APP_DATA_DIR` is set-once, so in a test binary only the first
/// `set_app_data_dir` ever takes effect: every later helper silently kept using
/// the FIRST test's `TempDir`, which was deleted the moment that test returned,
/// leaving the rest to build account dirs under a path that no longer existed.
/// Which test drew the short straw depended on thread scheduling, so the failures
/// wandered. Tests already isolate by account subdirectory, so sharing the root is
/// safe; what they cannot share is a lifetime owned by one of them.
#[cfg(test)]
pub(crate) fn shared_test_data_dir() -> &'static std::path::Path {
    static DIR: OnceLock<tempfile::TempDir> = OnceLock::new();
    // Never dropped: process-lifetime by construction, so no test can pull it out
    // from under another. Named by process, so the next run can clear what it left.
    DIR.get_or_init(|| {
        sweep_dead_test_dirs();
        tempfile::Builder::new().prefix(&format!("vector-test-{}-", std::process::id())).tempdir().expect("test data dir")
    })
    .path()
}

/// Earlier runs' roots: every test process leaves one, and the OS is slow to reclaim them.
#[cfg(test)]
fn sweep_dead_test_dirs() {
    let Ok(entries) = std::fs::read_dir(std::env::temp_dir()) else { return };
    for entry in entries.flatten() {
        let name = entry.file_name().to_string_lossy().into_owned();
        let Some(pid) = name.strip_prefix("vector-test-").and_then(|r| r.split('-').next()).and_then(|p| p.parse::<i32>().ok()) else { continue };
        // SAFETY: signal 0 delivers nothing; it only asks whether the process exists.
        #[cfg(unix)]
        let gone = unsafe { libc::kill(pid, 0) } == -1 && std::io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH);
        #[cfg(not(unix))]
        let gone = { let _ = pid; false };
        if gone {
            let _ = std::fs::remove_dir_all(entry.path());
        }
    }
}

pub fn get_app_data_dir() -> Result<&'static PathBuf, String> {
    APP_DATA_DIR.get().ok_or_else(|| "App data directory not initialized".to_string())
}

/// Host app version, stamped into each account on open so a later downgrade can
/// name what wrote the schema. Optional: the downgrade guard keys off the
/// migration high-water mark, never this.
static APP_VERSION: OnceLock<String> = OnceLock::new();

pub fn set_app_version(version: impl Into<String>) {
    let _ = APP_VERSION.set(version.into());
}

/// Host-installed override for the download directory. Tauri sets this
/// at boot via `set_download_dir()` so platform conventions (XDG on
/// Linux, Known Folders on Windows) are honored. Headless callers
/// (vector-agent CLI, tests) fall through to the env-var path.
static DOWNLOAD_DIR_OVERRIDE: OnceLock<PathBuf> = OnceLock::new();

/// Install the host-resolved download directory. Must be called at
/// startup before any `get_download_dir()` consumer runs; callers that
/// run earlier hit the fallback.
pub fn set_download_dir(path: PathBuf) {
    let _ = DOWNLOAD_DIR_OVERRIDE.set(path);
}

/// Where the user's own copies go: Saves, and media kept unencrypted. Android's public
/// `Download/Vector`, which outlives the app; elsewhere the download directory.
static PUBLIC_DIR_OVERRIDE: OnceLock<PathBuf> = OnceLock::new();

pub fn set_public_dir(path: PathBuf) {
    let _ = PUBLIC_DIR_OVERRIDE.set(path);
}

pub fn get_public_dir() -> PathBuf {
    PUBLIC_DIR_OVERRIDE.get().cloned().unwrap_or_else(get_download_dir)
}

/// Every folder Vector writes plain files into: the download directory, then the public one.
pub fn download_roots() -> Vec<PathBuf> {
    let (download, public) = (get_download_dir(), get_public_dir());
    if public == download { vec![download] } else { vec![download, public] }
}

/// Platform-appropriate download directory for file attachments.
///
/// Prefers the host-installed override (honors `xdg-user-dirs`,
/// `FOLDERID_Downloads`, `NSDownloadsDirectory`, `NSDocumentDirectory`).
/// Falls back to `$HOME/Downloads/vector` on desktop, then
/// `<app_data>/vector_downloads` on mobile / pre-init.
pub fn get_download_dir() -> PathBuf {
    if let Some(installed) = DOWNLOAD_DIR_OVERRIDE.get() {
        return installed.clone();
    }
    #[cfg(any(target_os = "macos", target_os = "linux"))]
    {
        if let Ok(home) = std::env::var("HOME") {
            return PathBuf::from(home).join("Downloads/vector");
        }
    }
    #[cfg(target_os = "windows")]
    {
        if let Ok(profile) = std::env::var("USERPROFILE") {
            return PathBuf::from(profile).join("Downloads").join("vector");
        }
    }
    // Mobile / fallback: use data dir
    if let Ok(data_dir) = get_app_data_dir() {
        return data_dir.join("vector_downloads");
    }
    PathBuf::from("/tmp/vector_downloads")
}

// ============================================================================
// Current Account
// ============================================================================

static CURRENT_ACCOUNT: LazyLock<Arc<RwLock<Option<String>>>> = LazyLock::new(|| Arc::new(RwLock::new(None)));
// PENDING_ACCOUNT lives exclusively in src-tauri's account_manager —
// any "pending account" check must go through that crate, not here.

/// Filename for the persistent active-account marker. Plain text, just the npub.
const ACTIVE_ACCOUNT_FILE: &str = "active_account";

/// npub bech32 form: `npub1` + 58 chars from the bech32 alphabet (no `1`, `b`, `i`, `o`).
fn is_valid_npub(s: &str) -> bool {
    if s.len() != 63 || !s.starts_with("npub1") {
        return false;
    }
    s.bytes().skip(5).all(|c| matches!(c,
        b'q' | b'p' | b'z' | b'r' | b'y' | b'9' | b'x' | b'8' |
        b'g' | b'f' | b'2' | b't' | b'v' | b'd' | b'w' | b'0' |
        b's' | b'3' | b'j' | b'n' | b'5' | b'4' | b'k' | b'h' |
        b'c' | b'e' | b'6' | b'm' | b'u' | b'a' | b'7' | b'l'
    ))
}

pub fn get_current_account() -> Result<String, String> {
    CURRENT_ACCOUNT.read().unwrap()
        .as_ref().cloned()
        .ok_or_else(|| "No active account".to_string())
}

/// Set the currently-active npub for THIS process AND persist it to the
/// `<app_data>/active_account` marker so the next boot picks the same account.
///
/// Every call site asserts user intent ("this account is now active"); the
/// marker write is idempotent and gracefully no-ops when `APP_DATA_DIR` is
/// not yet configured (e.g. during in-process unit tests).
pub fn set_current_account(npub: String) -> Result<(), String> {
    *CURRENT_ACCOUNT.write().unwrap() = Some(npub.clone());
    let _ = write_active_account_file(&npub);
    Ok(())
}

/// Clear the in-memory active account WITHOUT touching the on-disk marker.
/// Used by `reset_session()` so the next-boot marker stays intact while
/// in-process state is torn down for an inline account swap.
pub fn clear_current_account_in_memory() {
    *CURRENT_ACCOUNT.write().unwrap() = None;
}

/// Read the active-account marker file. Returns the stored npub if it exists,
/// is well-formed, AND the corresponding account directory still exists.
/// Any failure path returns Ok(None) so boot falls back to single-account or picker.
pub fn read_active_account_file() -> Result<Option<String>, String> {
    let app_data = match get_app_data_dir() {
        Ok(p) => p,
        Err(_) => return Ok(None),
    };
    read_active_account_file_in(app_data)
}

/// Atomic write of the active-account marker (temp + rename).
pub fn write_active_account_file(npub: &str) -> Result<(), String> {
    let app_data = get_app_data_dir()?.clone();
    write_active_account_file_in(&app_data, npub)
}

/// Remove the active-account marker. Used after deleting the active account.
pub fn clear_active_account_file() -> Result<(), String> {
    let app_data = get_app_data_dir()?;
    clear_active_account_file_in(app_data)
}

/// Scan the app data directory for valid npub directories. Strict bech32 regex
/// rejects typos and stray subdirectories. Does NOT validate that each account
/// has a usable database — callers do that separately.
pub fn list_account_npubs() -> Result<Vec<String>, String> {
    let app_data = get_app_data_dir()?;
    Ok(list_account_npubs_in(app_data))
}

// ----- path-parameterized internals (kept private so tests can inject a temp dir) -----

/// Bound on bytes read from the active-account marker. A valid marker
/// is 63 bytes (canonical npub) plus optional trailing newline. The
/// marker lives in a user-writable dir, so accidental / malicious
/// multi-gigabyte writes are a realistic OOM vector if read unbounded.
#[cfg(not(target_arch = "wasm32"))]
const MARKER_MAX_BYTES: u64 = 256;

#[cfg(not(target_arch = "wasm32"))]
fn read_active_account_file_in(app_data: &std::path::Path) -> Result<Option<String>, String> {
    use std::io::Read;

    let path = app_data.join(ACTIVE_ACCOUNT_FILE);
    if !path.exists() {
        return Ok(None);
    }
    // Pre-check size, then belt-and-suspenders cap via `take()` to
    // cover the TOCTOU window between metadata and open. Metadata
    // failures fail-safe to "missing".
    if let Ok(meta) = std::fs::metadata(&path) {
        if meta.len() > MARKER_MAX_BYTES {
            return Ok(None);
        }
    } else {
        return Ok(None);
    }
    let mut buf = String::new();
    let file = match std::fs::File::open(&path) {
        Ok(f) => f,
        Err(_) => return Ok(None),
    };
    if file.take(MARKER_MAX_BYTES).read_to_string(&mut buf).is_err() {
        return Ok(None);
    }
    let npub = buf.trim().to_string();
    if !is_valid_npub(&npub) {
        return Ok(None);
    }
    // `symlink_metadata` instead of `is_dir()` (which follows links): a
    // crafted symlink at `<app_data>/<valid-npub-name>` pointing at
    // `~/Documents` etc. would otherwise pass, and downstream
    // `remove_dir_all` in delete_account / logout would traverse it.
    // Bech32 validation alone is insufficient — the attacker controls
    // the filename, not the npub semantic.
    match std::fs::symlink_metadata(app_data.join(&npub)) {
        Ok(meta) if meta.file_type().is_dir() && !meta.file_type().is_symlink() => {}
        _ => return Ok(None),
    }
    Ok(Some(npub))
}

#[cfg(not(target_arch = "wasm32"))]
fn write_active_account_file_in(app_data: &std::path::Path, npub: &str) -> Result<(), String> {
    if !is_valid_npub(npub) {
        return Err(format!("Invalid npub format: {}", npub));
    }
    if !app_data.exists() {
        std::fs::create_dir_all(app_data)
            .map_err(|e| format!("Failed to create app data dir: {}", e))?;
    }
    // Refuse to point the marker at a directory that doesn't exist as a
    // real subfolder. Closes the race where a concurrent `delete_account`
    // for `npub` runs between the caller's existence check and this write.
    // `symlink_metadata` (matching the read path) so a crafted
    // `<app_data>/<valid-npub-name>` symlink can't satisfy the check.
    match std::fs::symlink_metadata(app_data.join(npub)) {
        Ok(meta) if meta.file_type().is_dir() && !meta.file_type().is_symlink() => {}
        _ => return Err(format!("Account directory missing or invalid: {}", npub)),
    }
    let tmp = app_data.join(format!("{}.tmp", ACTIVE_ACCOUNT_FILE));
    let final_path = app_data.join(ACTIVE_ACCOUNT_FILE);

    // Trailing newline so `cat` doesn't mangle the shell prompt and so editors
    // that auto-strip trailing newlines don't dirty-mark the file on save.
    let mut payload = String::with_capacity(npub.len() + 1);
    payload.push_str(npub);
    payload.push('\n');

    if let Err(e) = std::fs::write(&tmp, payload.as_bytes()) {
        let _ = std::fs::remove_file(&tmp);
        return Err(format!("Failed to write active account temp file: {}", e));
    }

    // Retry the rename a few times. On Windows, transient antivirus or backup
    // scans can hold a brief sharing-violation lock on the destination file.
    let mut last_err = None;
    for attempt in 0..3 {
        match std::fs::rename(&tmp, &final_path) {
            Ok(_) => return Ok(()),
            Err(e) => {
                last_err = Some(e);
                if attempt < 2 {
                    std::thread::sleep(std::time::Duration::from_millis(50));
                }
            }
        }
    }

    // Don't leave the temp file behind if every attempt failed.
    let _ = std::fs::remove_file(&tmp);
    Err(format!(
        "Failed to rename active account file: {}",
        last_err.map(|e| e.to_string()).unwrap_or_default()
    ))
}

#[cfg(not(target_arch = "wasm32"))]
fn clear_active_account_file_in(app_data: &std::path::Path) -> Result<(), String> {
    let path = app_data.join(ACTIVE_ACCOUNT_FILE);
    if path.exists() {
        std::fs::remove_file(&path)
            .map_err(|e| format!("Failed to remove active account file: {}", e))?;
    }
    Ok(())
}

#[cfg(not(target_arch = "wasm32"))]
fn list_account_npubs_in(app_data: &std::path::Path) -> Vec<String> {
    let mut out = Vec::new();
    if let Ok(entries) = std::fs::read_dir(app_data) {
        for entry in entries.flatten() {
            if entry.file_type().is_ok_and(|ft| ft.is_dir()) {
                let name = entry.file_name().to_string_lossy().to_string();
                if is_valid_npub(&name) {
                    out.push(name);
                }
            }
        }
    }
    out
}

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

    /// Real npub from the project's own test fixtures (matches bech32 regex).
    const VALID_A: &str = "npub16ye7evyevwnl0fc9hujsxf9zym72e063awn0pvde0huvpyec5nyq4dg4wn";
    const VALID_B: &str = "npub12w73tzcqgpr2pcy4el5x60d2emeud4cyeeayynzqgg2fefzgytaqm4ktz3";

    fn touch_account_dir(base: &std::path::Path, npub: &str) {
        fs::create_dir_all(base.join(npub)).unwrap();
    }

    #[test]
    fn npub_validator_accepts_canonical_form() {
        assert!(is_valid_npub(VALID_A));
        assert!(is_valid_npub(VALID_B));
    }

    #[test]
    fn npub_validator_rejects_wrong_length() {
        assert!(!is_valid_npub("npub1abc"));
        assert!(!is_valid_npub(&format!("{}x", VALID_A)));
        assert!(!is_valid_npub(""));
    }

    #[test]
    fn npub_validator_rejects_missing_prefix() {
        let body = &VALID_A[5..];
        assert!(!is_valid_npub(&format!("nsec1{}", body)));
        assert!(!is_valid_npub(&format!("xxxx1{}", body)));
    }

    #[test]
    fn npub_validator_rejects_non_bech32_chars() {
        // Replace one char in the body with each disallowed bech32 letter.
        for bad in ['1', 'b', 'i', 'o', 'B', 'I', 'O', '!', '*', ' '] {
            let mut s = String::from(VALID_A);
            s.replace_range(10..11, &bad.to_string());
            assert!(!is_valid_npub(&s), "should reject character {:?}", bad);
        }
    }

    #[test]
    fn write_then_read_round_trips() {
        let tmp = TempDir::new().unwrap();
        touch_account_dir(tmp.path(), VALID_A);

        write_active_account_file_in(tmp.path(), VALID_A).unwrap();
        assert_eq!(
            read_active_account_file_in(tmp.path()).unwrap(),
            Some(VALID_A.to_string())
        );
    }

    #[test]
    fn write_rejects_invalid_npub() {
        let tmp = TempDir::new().unwrap();
        let err = write_active_account_file_in(tmp.path(), "npub1nope").unwrap_err();
        assert!(err.contains("Invalid"));
        // No file should have been created (neither final nor temp).
        assert!(!tmp.path().join(ACTIVE_ACCOUNT_FILE).exists());
        assert!(!tmp.path().join(format!("{}.tmp", ACTIVE_ACCOUNT_FILE)).exists());
    }

    #[test]
    fn write_rejects_missing_account_dir() {
        // A concurrent `delete_account` between the caller's existence check
        // and write_active_account_file would otherwise leave a stale marker
        // pointing at a now-deleted account.
        let tmp = TempDir::new().unwrap();
        let err = write_active_account_file_in(tmp.path(), VALID_A).unwrap_err();
        assert!(err.contains("missing or invalid"),
            "expected account-dir-missing error, got: {}", err);
        // Marker must not have been written.
        assert!(!tmp.path().join(ACTIVE_ACCOUNT_FILE).exists());
        assert!(!tmp.path().join(format!("{}.tmp", ACTIVE_ACCOUNT_FILE)).exists());
    }

    #[test]
    fn write_rejects_symlinked_account_dir() {
        // A crafted `<app_data>/<valid-npub-name>` symlink to ~/Documents
        // would otherwise pass `is_dir()` and let the marker point at an
        // attacker-controlled location, which downstream delete/logout paths
        // would then traverse.
        let tmp = TempDir::new().unwrap();
        let target = TempDir::new().unwrap();
        let link = tmp.path().join(VALID_A);
        #[cfg(unix)]
        {
            std::os::unix::fs::symlink(target.path(), &link).unwrap();
            let err = write_active_account_file_in(tmp.path(), VALID_A).unwrap_err();
            assert!(err.contains("missing or invalid"),
                "expected symlink rejection, got: {}", err);
        }
        // On Windows symlink creation may require elevated privileges; skip
        // the assertion there rather than gate the whole test on platform.
        #[cfg(not(unix))]
        let _ = (target, link);
    }

    #[test]
    fn read_returns_none_when_marker_missing() {
        let tmp = TempDir::new().unwrap();
        assert_eq!(read_active_account_file_in(tmp.path()).unwrap(), None);
    }

    #[test]
    fn read_returns_none_when_marker_is_garbage() {
        let tmp = TempDir::new().unwrap();
        fs::write(tmp.path().join(ACTIVE_ACCOUNT_FILE), b"not-an-npub\n").unwrap();
        assert_eq!(read_active_account_file_in(tmp.path()).unwrap(), None);
    }

    #[test]
    fn read_returns_none_when_account_dir_missing() {
        // Marker exists, npub is well-formed, but the account directory was
        // deleted out from under us. Boot must fall through to picker, never crash.
        let tmp = TempDir::new().unwrap();
        fs::write(tmp.path().join(ACTIVE_ACCOUNT_FILE), VALID_A).unwrap();
        assert_eq!(read_active_account_file_in(tmp.path()).unwrap(), None);
    }

    #[test]
    fn read_returns_none_when_marker_oversized() {
        // Marker lives in a user-writable directory — guard against a giant
        // file OOMing the app. Anything past MARKER_MAX_BYTES is treated as
        // corrupt.
        let tmp = TempDir::new().unwrap();
        let payload = vec![b'x'; (MARKER_MAX_BYTES + 1024) as usize];
        fs::write(tmp.path().join(ACTIVE_ACCOUNT_FILE), &payload).unwrap();
        assert_eq!(read_active_account_file_in(tmp.path()).unwrap(), None);
    }

    #[test]
    fn read_trims_whitespace() {
        let tmp = TempDir::new().unwrap();
        touch_account_dir(tmp.path(), VALID_A);
        fs::write(
            tmp.path().join(ACTIVE_ACCOUNT_FILE),
            format!("  {}\n", VALID_A),
        ).unwrap();
        assert_eq!(
            read_active_account_file_in(tmp.path()).unwrap(),
            Some(VALID_A.to_string())
        );
    }

    #[test]
    fn read_handles_crlf_line_endings() {
        let tmp = TempDir::new().unwrap();
        touch_account_dir(tmp.path(), VALID_A);
        fs::write(
            tmp.path().join(ACTIVE_ACCOUNT_FILE),
            format!("{}\r\n", VALID_A),
        ).unwrap();
        assert_eq!(
            read_active_account_file_in(tmp.path()).unwrap(),
            Some(VALID_A.to_string())
        );
    }

    #[test]
    fn npub_validator_rejects_uppercase_prefix() {
        let upper = format!("NPUB1{}", &VALID_A[5..]);
        assert!(!is_valid_npub(&upper));
    }

    #[test]
    fn write_then_read_round_trips_with_newline() {
        // Belt-and-braces check: confirms our own writer (which appends \n)
        // round-trips through our own reader (which trims) with no surprises.
        let tmp = TempDir::new().unwrap();
        touch_account_dir(tmp.path(), VALID_A);
        write_active_account_file_in(tmp.path(), VALID_A).unwrap();

        let raw = fs::read_to_string(tmp.path().join(ACTIVE_ACCOUNT_FILE)).unwrap();
        assert!(raw.ends_with('\n'));

        assert_eq!(
            read_active_account_file_in(tmp.path()).unwrap(),
            Some(VALID_A.to_string())
        );
    }

    #[test]
    fn write_overwrites_previous_marker_atomically() {
        let tmp = TempDir::new().unwrap();
        touch_account_dir(tmp.path(), VALID_A);
        touch_account_dir(tmp.path(), VALID_B);

        write_active_account_file_in(tmp.path(), VALID_A).unwrap();
        write_active_account_file_in(tmp.path(), VALID_B).unwrap();

        assert_eq!(
            read_active_account_file_in(tmp.path()).unwrap(),
            Some(VALID_B.to_string())
        );
        // The temp file used for atomic rename should not linger.
        assert!(!tmp.path().join(format!("{}.tmp", ACTIVE_ACCOUNT_FILE)).exists());
    }

    #[test]
    fn clear_removes_marker_and_is_idempotent() {
        let tmp = TempDir::new().unwrap();
        touch_account_dir(tmp.path(), VALID_A);
        write_active_account_file_in(tmp.path(), VALID_A).unwrap();
        assert!(tmp.path().join(ACTIVE_ACCOUNT_FILE).exists());

        clear_active_account_file_in(tmp.path()).unwrap();
        assert!(!tmp.path().join(ACTIVE_ACCOUNT_FILE).exists());

        // Calling clear again on an already-clean state must not error.
        clear_active_account_file_in(tmp.path()).unwrap();
    }

    #[test]
    fn list_npubs_finds_valid_dirs_only() {
        let tmp = TempDir::new().unwrap();
        touch_account_dir(tmp.path(), VALID_A);
        touch_account_dir(tmp.path(), VALID_B);
        // Decoys: stray dirs and files that must NOT be picked up.
        fs::create_dir_all(tmp.path().join("npub1tooshort")).unwrap();
        fs::create_dir_all(tmp.path().join("not-an-npub-dir")).unwrap();
        fs::create_dir_all(tmp.path().join("tor")).unwrap();
        fs::write(tmp.path().join(ACTIVE_ACCOUNT_FILE), VALID_A).unwrap();

        let mut found = list_account_npubs_in(tmp.path());
        found.sort();
        let mut expected = vec![VALID_A.to_string(), VALID_B.to_string()];
        expected.sort();
        assert_eq!(found, expected);
    }

    #[test]
    fn list_npubs_skips_dirs_containing_invalid_chars() {
        let tmp = TempDir::new().unwrap();
        // Insert a 'b', 'i', 'o', or '1' into the body — invalid bech32 chars.
        let mut bogus = String::from(VALID_A);
        bogus.replace_range(10..11, "b");
        fs::create_dir_all(tmp.path().join(&bogus)).unwrap();

        let found = list_account_npubs_in(tmp.path());
        assert!(found.is_empty(), "found unexpected entries: {:?}", found);
    }

    #[test]
    fn write_creates_app_data_dir_if_missing() {
        let tmp = TempDir::new().unwrap();
        let nested = tmp.path().join("does/not/exist/yet");
        // Parent app_data is auto-created by mkdir_all; the account dir must
        // also exist by the time we write, so the marker can't end up
        // pointing at a non-existent account.
        std::fs::create_dir_all(&nested).unwrap();
        touch_account_dir(&nested, VALID_A);
        write_active_account_file_in(&nested, VALID_A).unwrap();
        assert!(nested.join(ACTIVE_ACCOUNT_FILE).exists());
    }
}

// pending-account accessors removed — see comment above the static decl.
// All callers use `src-tauri::account_manager::{get,set,clear}_pending_account`.

// ============================================================================
// Connection Pools
// ============================================================================

/// One account's database resources, held behind an `Arc`.
///
/// The connections an account uses are reachable ONLY through its own
/// `Session`, so a task that captured one keeps talking to the account it
/// started with even after a swap — it cannot be handed the next account's
/// database, because it never asks "who is current?" again.
///
/// That makes teardown structural: swapping installs a new `Session` and drops
/// the reference to the old one, whose pool closes when the last in-flight
/// guard finishes with it. Nothing to clear, nothing to remember to clear.
pub struct Session {
    /// Identity for "is this the account on screen?".
    ///
    /// Not the `Arc` address: binding a session to a database builds a new one
    /// holding the same state (see `rebound`), and a task bound to the session
    /// it grew from is still that account's. Comparing addresses would make
    /// those tasks silently stop painting after a re-initialise.
    id: u64,
    /// The database this session opens, resolved ONCE when it is built.
    /// `None` only before an account is bound, where there is nothing better
    /// than the ambient lookup to fall back to.
    db_path: Option<PathBuf>,
    read_pool: Mutex<Vec<rusqlite::Connection>>,
    /// Signalled when a reader comes home, for a read waiting on one.
    reader_free: std::sync::Condvar,
    /// Pooled readers out right now; with the idle ones, never past [`MAX_READERS`].
    readers_out: std::sync::atomic::AtomicUsize,
    write_conn: Mutex<Option<rusqlite::Connection>>,
    /// Signalled when the writer comes home, for a write waiting on it.
    writer_free: std::sync::Condvar,
    /// Writer guards out right now: none out and none home means nothing to wait for.
    writers_out: std::sync::atomic::AtomicUsize,
    /// This account's chats and profiles in memory — the DB's read-through
    /// cache, and so bound to the same account for the same reason.
    chat_state: Arc<tokio::sync::Mutex<crate::state::ChatState>>,
    /// Everything else the account owns, keyed by type. See [`Session::scoped`].
    scoped: RwLock<std::collections::HashMap<std::any::TypeId, Arc<dyn std::any::Any + Send + Sync>>>,
    /// Raised when this account stops being the one on screen.
    stopped: SessionStop,
}

/// "This account is no longer current" — a flag long work polls, and a signal
/// it can await.
#[derive(Default)]
struct SessionStop {
    flag: std::sync::atomic::AtomicBool,
    wake: tokio::sync::Notify,
}

impl Session {
    pub(crate) fn empty() -> Arc<Self> {
        let s = Arc::new(Session {
            id: next_session_id(),
            db_path: None,
            read_pool: Mutex::new(Vec::new()),
            reader_free: std::sync::Condvar::new(),
            readers_out: std::sync::atomic::AtomicUsize::new(0),
            write_conn: Mutex::new(None),
            writer_free: std::sync::Condvar::new(),
            writers_out: std::sync::atomic::AtomicUsize::new(0),
            chat_state: Arc::new(tokio::sync::Mutex::new(crate::state::ChatState::new())),
            scoped: RwLock::new(std::collections::HashMap::new()),
            stopped: SessionStop::default(),
        });
        crate::transport::prefs::attach(&s);
        crate::media::ram::attach(&s);
        crate::media::store::attach(&s);
        crate::media::pending::attach(&s);
        s
    }

    /// A session bound to one account's database file, with a fresh in-memory
    /// state — the caller loads it from that database.
    fn bound(db_path: PathBuf) -> Arc<Self> {
        let s = Arc::new(Session {
            id: next_session_id(),
            db_path: Some(db_path),
            read_pool: Mutex::new(Vec::new()),
            reader_free: std::sync::Condvar::new(),
            readers_out: std::sync::atomic::AtomicUsize::new(0),
            write_conn: Mutex::new(None),
            writer_free: std::sync::Condvar::new(),
            writers_out: std::sync::atomic::AtomicUsize::new(0),
            chat_state: Arc::new(tokio::sync::Mutex::new(crate::state::ChatState::new())),
            scoped: RwLock::new(std::collections::HashMap::new()),
            stopped: SessionStop::default(),
        });
        crate::transport::prefs::attach(&s);
        crate::media::ram::attach(&s);
        crate::media::store::attach(&s);
        crate::media::pending::attach(&s);
        s
    }

    /// The same account's session, pointed at its database, keeping everything
    /// it already holds.
    ///
    /// Two callers need this. Re-initialising an account that is already open —
    /// `init_database` is documented idempotent, and the schema check and
    /// Android's background sync both re-run it — must not empty the chat list
    /// under a running app. And a login legitimately fills a session before the
    /// account's database exists: creating an account installs its keys and
    /// client first, and only reaches `init_database` once the user has chosen
    /// a PIN. Binding the session it was filling is a promotion, not a swap.
    fn rebound(&self, db_path: PathBuf) -> Arc<Self> {
        Arc::new(Session {
            id: self.id,
            db_path: Some(db_path),
            read_pool: Mutex::new(Vec::new()),
            reader_free: std::sync::Condvar::new(),
            readers_out: std::sync::atomic::AtomicUsize::new(0),
            write_conn: Mutex::new(None),
            writer_free: std::sync::Condvar::new(),
            writers_out: std::sync::atomic::AtomicUsize::new(0),
            chat_state: self.chat_state.clone(),
            scoped: RwLock::new(self.scoped.read().unwrap_or_else(|e| e.into_inner()).clone()),
            stopped: SessionStop::default(),
        })
    }

    /// This account's instance of `T`, built on first touch.
    ///
    /// The home for anything an account owns beyond its database: caches keyed
    /// by its row ids, queues holding its work, routing tables holding its
    /// keys. Previously these were process globals with a hand-written clear in
    /// two teardown paths, which is how they drifted — one path cleared fields
    /// the other did not, and a cache added without a clear leaked into the
    /// next account. Here there is nothing to clear: the account's instances go
    /// when its session does.
    ///
    /// Keyed by a marker type the owning module declares, so the session never
    /// has to know what any of this is, and two modules storing the same SHAPE
    /// (say a `Mutex<HashMap<PublicKey, _>>`) can't collide on one slot.
    ///
    /// ```ignore
    /// struct InboxRelayCache;               // the key, private to this module
    /// fn cache() -> Arc<Mutex<HashMap<PublicKey, CachedRelays>>> {
    ///     db::current_session().scoped::<InboxRelayCache, _>()
    /// }
    /// ```
    pub fn scoped<K: 'static, T: Default + Send + Sync + 'static>(self: &Arc<Self>) -> Arc<T> {
        let key = std::any::TypeId::of::<(K, T)>();
        if let Some(existing) = self.scoped.read().unwrap_or_else(|e| e.into_inner()).get(&key) {
            return existing.clone().downcast::<T>().expect("keyed by its own TypeId");
        }
        let mut map = self.scoped.write().unwrap_or_else(|e| e.into_inner());
        // Another thread may have inserted while the read lock was released.
        map.entry(key)
            .or_insert_with(|| Arc::new(T::default()) as Arc<dyn std::any::Any + Send + Sync>)
            .clone()
            .downcast::<T>()
            .expect("keyed by its own TypeId")
    }

    /// This session's identity. Stable across a re-initialise of the same
    /// account, distinct for every other. Callers that key a cache by "which
    /// account is this" use it in place of the old generation counter.
    pub fn id(&self) -> u64 {
        self.id
    }

    /// The database this session opens, once it is bound to one.
    pub fn db_path(&self) -> Option<PathBuf> {
        self.db_path.clone()
    }

    /// Whether this account has been switched away from.
    ///
    /// Purely an efficiency signal. Work that continues past it is still
    /// CORRECT — it writes to this account's own storage and paints nothing —
    /// it is just no longer work anyone is waiting for. Long syncs poll this at
    /// their loop heads so a swap stops the relay traffic and the decryption
    /// rather than grinding on for a screen nobody is looking at.
    ///
    /// Never use it to decide whether a write is SAFE. That is structural now.
    pub fn stopped(&self) -> bool {
        self.stopped.flag.load(std::sync::atomic::Ordering::Acquire)
    }

    /// Resolves once this account is switched away from — for `select!` against
    /// a fetch, so an in-flight request is dropped instead of awaited out.
    pub async fn on_stop(&self) {
        loop {
            let waiting = self.stopped.wake.notified();
            if self.stopped() {
                return;
            }
            waiting.await;
            if self.stopped() {
                return;
            }
        }
    }

    fn stop(&self) {
        self.stopped.flag.store(true, std::sync::atomic::Ordering::Release);
        self.stopped.wake.notify_waiters();
    }

    /// Whether this session is the account currently on screen.
    ///
    /// For code holding a session it captured earlier — a drop handler, a
    /// callback fired by a relay OK — where there is no await to be bound
    /// across and the question is "is what I captured still current?".
    pub fn is_live(&self) -> bool {
        self.id == CURRENT_SESSION.read().unwrap_or_else(|e| e.into_inner()).id
    }

    /// This account's in-memory chats and profiles.
    ///
    /// Reached through the session, so a task bound to account A keeps reading
    /// and writing A's chats after a swap. Its state is then an orphan nothing
    /// displays, rather than corruption in the account now on screen.
    pub fn chat_state(&self) -> Arc<tokio::sync::Mutex<crate::state::ChatState>> {
        self.chat_state.clone()
    }

    /// Where THIS session opens connections. A bound session never consults the
    /// ambient account, so a pool miss after a swap still opens the file this
    /// session belongs to rather than the incoming account's.
    fn path(&self) -> Result<PathBuf, String> {
        match &self.db_path {
            Some(p) => Ok(p.clone()),
            None => get_current_db_path(),
        }
    }

    /// Take a READ connection from this session, opening one against this
    /// session's own database if the pool is empty.
    ///
    /// The pool grows to `MAX_READERS` and stays: a reader closed later would free its
    /// schema and caches into pages shared with long-lived data, holes the system never
    /// takes back. Past the cap a read waits for one to come home (queries take micro- to
    /// milliseconds); a nested read on this thread, or a wait past `READER_WAIT`, opens a
    /// passing connection that closes on return.
    #[track_caller]
    pub fn acquire_read(self: &Arc<Self>) -> Result<ConnectionGuard, String> {
        use std::sync::atomic::Ordering;
        let nested = READERS_HERE.with(|n| n.get() > 0) || NEVER_WAIT.with(std::cell::Cell::get);
        let deadline = web_time::Instant::now() + READER_WAIT;
        let mut pool = self.read_pool.lock().unwrap_or_else(|e| e.into_inner());
        let pooled = loop {
            // The most recently used: the rest stay cold.
            if let Some(conn) = pool.pop() {
                self.readers_out.fetch_add(1, Ordering::Relaxed);
                return Ok(ConnectionGuard::new(conn, self.clone(), true));
            }
            if self.readers_out.load(Ordering::Relaxed) < MAX_READERS {
                break true;
            }
            if nested {
                break false;
            }
            // One thread on the web: nothing else could bring a reader back.
            #[cfg(target_arch = "wasm32")]
            break false;
            #[cfg(not(target_arch = "wasm32"))]
            {
                let left = deadline.saturating_duration_since(web_time::Instant::now());
                if left.is_zero() {
                    break false;
                }
                pool = self.reader_free.wait_timeout(pool, left).unwrap_or_else(|e| e.into_inner()).0;
            }
        };
        #[cfg(target_arch = "wasm32")]
        let _ = deadline;
        // Counted before the lock goes, so the cap holds against a read arriving meanwhile.
        let path = self.path()?;
        if pooled {
            self.readers_out.fetch_add(1, Ordering::Relaxed);
        }
        drop(pool);
        match create_connection(&path) {
            Ok(conn) => Ok(ConnectionGuard::new(conn, self.clone(), pooled)),
            Err(e) => {
                if pooled {
                    let _held = self.read_pool.lock().unwrap_or_else(|e| e.into_inner());
                    self.readers_out.fetch_sub(1, Ordering::Relaxed);
                    self.reader_free.notify_all();
                }
                Err(e)
            }
        }
    }

    /// Take THE write connection from this session, opening one against this
    /// session's own database if the slot is empty.
    ///
    /// SQLite takes one writer at a time, so a second connection gains nothing: it parses
    /// the schema, then sleeps in SQLite's busy poll. Waiting here wakes the moment the
    /// writer returns. A nested write on this thread, or a holder past `WRITER_WAIT`,
    /// opens its own.
    #[track_caller]
    pub fn acquire_write(self: &Arc<Self>) -> Result<WriteConnectionGuard, String> {
        use std::sync::atomic::Ordering;
        let nested = WRITERS_HERE.with(|n| n.get() > 0) || NEVER_WAIT.with(std::cell::Cell::get);
        let deadline = web_time::Instant::now() + WRITER_WAIT;
        let mut slot = self.write_conn.lock().unwrap_or_else(|e| e.into_inner());
        loop {
            if let Some(conn) = slot.take() {
                self.writers_out.fetch_add(1, Ordering::Relaxed);
                return Ok(WriteConnectionGuard::new(conn, self.clone()));
            }
            if nested || self.writers_out.load(Ordering::Relaxed) == 0 {
                break;
            }
            // One thread on the web: nothing else could bring the writer back.
            #[cfg(target_arch = "wasm32")]
            break;
            #[cfg(not(target_arch = "wasm32"))]
            {
                let left = deadline.saturating_duration_since(web_time::Instant::now());
                if left.is_zero() {
                    break;
                }
                slot = self.writer_free.wait_timeout(slot, left).unwrap_or_else(|e| e.into_inner()).0;
            }
        }
        #[cfg(target_arch = "wasm32")]
        let _ = deadline;
        // Counted before the lock goes, so a write arriving meanwhile waits for this one.
        let path = self.path()?;
        self.writers_out.fetch_add(1, Ordering::Relaxed);
        drop(slot);
        match create_connection(&path) {
            Ok(conn) => Ok(WriteConnectionGuard::new(conn, self.clone())),
            Err(e) => {
                let _held = self.write_conn.lock().unwrap_or_else(|e| e.into_inner());
                self.writers_out.fetch_sub(1, Ordering::Relaxed);
                self.writer_free.notify_all();
                Err(e)
            }
        }
    }
}

/// The account whose resources new work binds to. Read once at the START of a
/// unit of work; hold the `Arc` for its duration.
static CURRENT_SESSION: LazyLock<RwLock<Arc<Session>>> = LazyLock::new(|| RwLock::new(Session::empty()));

tokio::task_local! {
    /// The session this task is bound to, installed by [`spawn_bound`].
    ///
    /// Readable from any code running on the task, including the synchronous
    /// `db::` helpers an async body calls — which is what lets every existing
    /// call site become account-correct without growing a parameter.
    static TASK_SESSION: Arc<Session>;
}

/// The session THIS work belongs to.
///
/// A task bound by [`spawn_bound`] gets the account it started under, for its
/// whole life, however many awaits it spans and whoever logs in meanwhile. That
/// is the property the std::sync::Arc<crate::db::Session> checks were approximating by hand.
///
/// Unbound callers (startup, the UI command that performs the swap itself) get
/// the live account, which for them is the correct and only meaningful answer.
pub fn current_session() -> Arc<Session> {
    TASK_SESSION
        .try_with(Arc::clone)
        .unwrap_or_else(|_| CURRENT_SESSION.read().unwrap_or_else(|e| e.into_inner()).clone())
}

/// Run `fut` pinned to the CURRENT account, without spawning.
///
/// The counterpart to [`spawn_bound`] for work that is NOT a task we started:
/// a Tauri command, an SDK call, a JNI entry point. Nothing installs a session
/// for those, so every `db::` call inside them re-resolves the live account and
/// a swap mid-operation silently moves the rest of their writes. Wrapping the
/// body fixes the account for its whole duration — a swap then leaves the
/// operation completing against the account that asked for it, which is both
/// the correct outcome and the one the user intended.
///
/// This is what makes the hand-written "did the account change?" checks
/// unnecessary rather than merely redundant.
/// NOT an `async fn`, and that is load-bearing. An `async fn` stores its
/// parameters in the state machine it returns, so `scoped` would be sized to
/// hold the body it binds — and nesting would multiply, exactly as passing the
/// future to `scope` unboxed does. A plain fn returning `impl Future` hands
/// back a wrapper around a `Pin<Box<_>>`: a pointer, whatever the body.
///
/// This is not hypothetical. Boot crashed with a stack overflow on BOTH Android
/// and macOS, several layers into the community sync, on stacks every test here
/// runs on happily. `binding_a_future_does_not_embed_it` is the guard.
pub fn scoped<F: std::future::Future>(fut: F) -> impl std::future::Future<Output = F::Output> {
    TASK_SESSION.scope(current_session(), Box::pin(fut))
}

/// [`scoped`], but the RESULT is refused if the account changed while it ran.
///
/// For an operation whose value goes back to the UI. The work itself completed
/// correctly against its own account; what must not happen is that value being
/// painted into, or acted on by, the account now on screen. One wrapper in
/// place of a check before every write.
pub fn scoped_result<T, E, F>(fut: F) -> impl std::future::Future<Output = Result<T, E>>
where
    F: std::future::Future<Output = Result<T, E>>,
    E: From<String>,
{
    let session = current_session();
    let id = session.id;
    // Bind first, so the async block below holds only the (pointer-sized)
    // bound future rather than the body. See `scoped`.
    let bound = TASK_SESSION.scope(session, Box::pin(fut));
    async move {
        let out = bound.await;
        if id != CURRENT_SESSION.read().unwrap_or_else(|e| e.into_inner()).id {
            return Err(E::from("account changed during the operation".to_string()));
        }
        out
    }
}

/// Run `fut` pinned to a session you already hold.
///
/// For code that captured a session earlier and wants to finish that account's
/// work through it — and for tests, which need to read an account's storage
/// after the live session has moved on.
pub fn with_session<F: std::future::Future>(
    session: Arc<Session>,
    fut: F,
) -> impl std::future::Future<Output = F::Output> {
    TASK_SESSION.scope(session, Box::pin(fut))
}

/// Run blocking `f` on the blocking pool as the CURRENT account's work: a pool thread carries
/// no task binding of its own.
#[cfg(not(target_arch = "wasm32"))]
pub async fn blocking_bound<T, F>(f: F) -> Result<T, String>
where
    F: FnOnce() -> T + Send + 'static,
    T: Send + 'static,
{
    let session = current_session();
    tokio::task::spawn_blocking(move || TASK_SESSION.sync_scope(session, f)).await.map_err(|e| e.to_string())
}

/// Spawn a task pinned to the CURRENT account.
///
/// Everything it does through `db::` resolves to that account for as long as it
/// runs, so an account switch mid-flight can no longer redirect its writes. Use
/// this for any task that touches per-account state; a bare `tokio::spawn`
/// leaves the task reading whoever is live at the moment it asks.
pub fn spawn_bound<F>(fut: F) -> crate::rt::JoinHandle<F::Output>
where
    F: std::future::Future + crate::rt::MaybeSend + 'static,
    F::Output: crate::rt::MaybeSend + 'static,
{
    let session = current_session();
    // spawn-detached: this IS the binding — it installs the session it just read.
    crate::rt::spawn(TASK_SESSION.scope(session, fut))
}

impl std::fmt::Debug for Session {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Session").field("id", &self.id).field("db", &self.db_path).finish()
    }
}

/// Has the account this work belongs to been switched away from?
///
/// Check it at the head of a long loop — a sync page, a relay in a fan-out, a
/// channel in a sweep — and stop. Continuing is safe, just wasteful.
pub fn session_stopped() -> bool {
    current_session().stopped()
}

/// The live account's session id — for caches keyed by "which account is this".
pub fn current_session_id() -> u64 {
    current_session().id
}

/// The session on screen, ignoring the task binding: what unbound network code acts for.
pub fn live_session() -> Arc<Session> {
    CURRENT_SESSION.read().unwrap_or_else(|e| e.into_inner()).clone()
}

/// [`live_session`]'s id.
pub fn live_session_id() -> u64 {
    CURRENT_SESSION.read().unwrap_or_else(|e| e.into_inner()).id
}

/// Whether the work running here belongs to the account currently on screen.
///
/// There is exactly one UI, showing one account. A task bound to a previous
/// account keeps working correctly — its database, its chats, its client — but
/// what it produces must not be painted into the account the user is now
/// looking at. Every emission asks this, which is why almost none of them has
/// to ask it by hand.
pub fn session_is_live() -> bool {
    current_session().id == CURRENT_SESSION.read().unwrap_or_else(|e| e.into_inner()).id
}

/// Whether THIS work writes to the account on screen. The at-rest vault and the encryption flag
/// describe that account only, so sealing for any other is refused. A rebind of the same account
/// keeps its database, so it still counts.
pub fn writes_to_live_account() -> bool {
    let mine = current_session();
    let live = CURRENT_SESSION.read().unwrap_or_else(|e| e.into_inner());
    mine.id == live.id || (mine.db_path.is_some() && mine.db_path == live.db_path)
}

fn next_session_id() -> u64 {
    static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
    NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
}

/// Install a fresh session, dropping the reference to the previous one. Any
/// guard still outstanding against the old session returns its connection
/// there, and that pool closes with it.
fn replace_session() {
    install(Session::empty());
}

/// Install `next` and tell the outgoing account's work to stop.
fn install(next: Arc<Session>) {
    let (prev, next_id) = {
        // Sealed writes check the live account under a ticket; waiting them out here means none
        // straddles the switch.
        let _switch = crate::crypto::gate::switching();
        crate::crypto::forget_previous_key();
        let mut current = CURRENT_SESSION.write().unwrap_or_else(|e| e.into_inner());
        if current.id != next.id {
            current.stop();
            crate::media::ram::clear_for(&current);
        }
        let prev = current.id;
        let next_id = next.id;
        *current = next;
        (prev, next_id)
    };
    // After the write lock: the epoch bump reads the live id.
    crate::transport::on_session_installed(prev, next_id);
    crate::profile::sync::wake_processor();
}

/// RAII guard for READ connections — auto-returns to its OWN session's pool.
///
/// Holding the `Arc` is what makes the return safe: the connection goes back
/// where it came from, so a guard outstanding across an account swap can never
/// hand account A's connection to account B. When that older session has no
/// references left, its pool closes with it.
/// Not `Send`, like the writer's: a reader stays on its thread, so a nested read on that
/// thread is always seen as one.
pub struct ConnectionGuard {
    conn: Option<rusqlite::Connection>,
    session: Arc<Session>,
    /// A pool member, rather than a passing connection that closes on return.
    pooled: bool,
    _not_send: std::marker::PhantomData<*const ()>,
    /// When and where it was taken, to name a holder that keeps other reads waiting.
    #[cfg(debug_assertions)]
    taken: (web_time::Instant, &'static std::panic::Location<'static>),
}

impl ConnectionGuard {
    #[track_caller]
    fn new(conn: rusqlite::Connection, session: Arc<Session>, pooled: bool) -> Self {
        READERS_HERE.with(|n| n.set(n.get() + 1));
        Self {
            conn: Some(conn),
            session,
            pooled,
            _not_send: std::marker::PhantomData,
            #[cfg(debug_assertions)]
            taken: (web_time::Instant::now(), std::panic::Location::caller()),
        }
    }
}

impl Deref for ConnectionGuard {
    type Target = rusqlite::Connection;
    fn deref(&self) -> &Self::Target { self.conn.as_ref().expect("Connection already taken") }
}

impl DerefMut for ConnectionGuard {
    fn deref_mut(&mut self) -> &mut Self::Target { self.conn.as_mut().expect("Connection already taken") }
}

/// Readers a session pools. The boot burst asks for more at once; they wait their turn.
const MAX_READERS: usize = 8;
/// How long a read waits for a pooled reader before opening a passing one.
const READER_WAIT: std::time::Duration = std::time::Duration::from_millis(50);
/// How long a write waits for the writer before opening a connection of its own.
const WRITER_WAIT: std::time::Duration = std::time::Duration::from_millis(250);

thread_local! {
    /// Writer guards this thread holds: a nested write must not wait on itself.
    static WRITERS_HERE: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
    /// Reader guards this thread holds: a nested read must not wait on its own pool.
    static READERS_HERE: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
    /// A thread that must never block on the pools (the UI's): it opens a passing
    /// connection rather than wait.
    static NEVER_WAIT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}

/// Marks the calling thread as one that never waits on a pool. A host calls it from its UI
/// thread, where synchronous commands run: a wait there freezes the window.
pub fn never_wait_on_this_thread() {
    NEVER_WAIT.with(|f| f.set(true));
}

/// Homes a session's writer. A write may already be waiting on it (the session goes live
/// before its writer does), and one already returned is kept.
fn install_writer(session: &Session, conn: rusqlite::Connection) {
    let mut slot = session.write_conn.lock().unwrap_or_else(|e| e.into_inner());
    if slot.is_none() {
        *slot = Some(conn);
        session.writer_free.notify_all();
    }
}

/// Page cache a connection keeps once it goes idle. A burst (an archival sync, a re-encryption
/// sweep) has the full `cache_size` while it runs; what it leaves behind goes on return. The
/// bundled build's page cache is one pool per process, so a trim hands back every idle page.
const IDLE_CACHE_BYTES: i32 = 2 << 20;

fn page_cache_bytes(conn: &rusqlite::Connection) -> i32 {
    let (mut used, mut peak) = (0, 0);
    // SAFETY: the handle lives as long as the borrow, and CACHE_USED only reads pager stats.
    unsafe {
        rusqlite::ffi::sqlite3_db_status(
            conn.handle(),
            rusqlite::ffi::SQLITE_DBSTATUS_CACHE_USED,
            &mut used,
            &mut peak,
            0,
        );
    }
    used
}

fn trim_for_idle(conn: &rusqlite::Connection) {
    if page_cache_bytes(conn) > IDLE_CACHE_BYTES {
        let _ = conn.release_memory();
    }
}

impl Drop for ConnectionGuard {
    fn drop(&mut self) {
        READERS_HERE.with(|n| n.set(n.get().saturating_sub(1)));
        #[cfg(debug_assertions)]
        {
            let held = self.taken.0.elapsed();
            if held >= READER_WAIT {
                crate::log_warn!("[DB] reader held {} ms from {}", held.as_millis(), self.taken.1);
            }
        }
        let Some(conn) = self.conn.take() else { return };
        if !self.pooled {
            return;
        }
        trim_for_idle(&conn);
        let mut pool = self.session.read_pool.lock().unwrap_or_else(|e| e.into_inner());
        // fetch_update: its rename, try_update, is newer than the toolchains Vector builds with.
        #[allow(deprecated)]
        let _ = self.session.readers_out.fetch_update(
            std::sync::atomic::Ordering::Relaxed,
            std::sync::atomic::Ordering::Relaxed,
            |n| n.checked_sub(1),
        );
        pool.push(conn);
        self.session.reader_free.notify_one();
    }
}

/// RAII guard for the WRITE connection — auto-returns on drop.
/// Not `Send`: a writer stays on its thread, so it is never held across an `.await` and a
/// nested write on that thread is always seen as one.
pub struct WriteConnectionGuard {
    conn: Option<rusqlite::Connection>,
    session: Arc<Session>,
    _not_send: std::marker::PhantomData<*const ()>,
    /// When and where it was taken, to name a holder that makes other writes wait.
    #[cfg(debug_assertions)]
    taken: (web_time::Instant, &'static std::panic::Location<'static>),
}

impl WriteConnectionGuard {
    #[track_caller]
    fn new(conn: rusqlite::Connection, session: Arc<Session>) -> Self {
        WRITERS_HERE.with(|n| n.set(n.get() + 1));
        Self {
            conn: Some(conn),
            session,
            _not_send: std::marker::PhantomData,
            #[cfg(debug_assertions)]
            taken: (web_time::Instant::now(), std::panic::Location::caller()),
        }
    }
}

impl Deref for WriteConnectionGuard {
    type Target = rusqlite::Connection;
    fn deref(&self) -> &Self::Target { self.conn.as_ref().expect("Write connection already taken") }
}

impl DerefMut for WriteConnectionGuard {
    fn deref_mut(&mut self) -> &mut Self::Target { self.conn.as_mut().expect("Write connection already taken") }
}

impl Drop for WriteConnectionGuard {
    fn drop(&mut self) {
        WRITERS_HERE.with(|n| n.set(n.get().saturating_sub(1)));
        #[cfg(debug_assertions)]
        {
            let held = self.taken.0.elapsed();
            if held >= WRITER_WAIT {
                crate::log_warn!("[DB] writer held {} ms from {}", held.as_millis(), self.taken.1);
            }
        }
        if let Some(conn) = self.conn.take() {
            trim_for_idle(&conn);
            let mut spare = None;
            {
                let mut slot = self.session.write_conn.lock().unwrap_or_else(|e| e.into_inner());
                #[allow(deprecated)]
                let _ = self.session.writers_out.fetch_update(
                    std::sync::atomic::Ordering::Relaxed,
                    std::sync::atomic::Ordering::Relaxed,
                    |n| n.checked_sub(1),
                );
                // The slot may already hold a connection installed meanwhile.
                if slot.is_none() {
                    *slot = Some(conn);
                    self.session.writer_free.notify_one();
                } else {
                    spare = Some(conn);
                }
            }
            // Closed outside the lock.
            drop(spare);
        }
    }
}

// ============================================================================
// Connection Factory
// ============================================================================

/// Single source of truth for per-account directories. Every per-account
/// subsystem (DB, Tor state) resolves its path through this;
/// compose further subpaths with `.join(...)` — never insert layers
/// between `<app_data>` and `<npub>`.
///
/// Validates npub format before joining as defence-in-depth against
/// path traversal: a crafted IPC input like `"../../etc"` would
/// otherwise yield `<app_data>/../../etc` and downstream
/// `remove_dir_all` (delete_account, logout) would walk arbitrary dirs.
pub fn account_dir(npub: &str) -> Result<PathBuf, String> {
    if !is_valid_npub(npub) {
        return Err(format!("Invalid npub format: {}", npub));
    }
    Ok(get_app_data_dir()?.join(npub))
}

/// Make every commit so far durable: the write-ahead log synced to disk. Commits are only
/// written, not synced, until a checkpoint; this is for a step that can't be undone after them.
#[cfg(not(target_arch = "wasm32"))]
pub fn sync_wal() -> Result<(), String> {
    let db = current_account_dir()?.join("vector.db");
    for path in [db.with_file_name("vector.db-wal"), db] {
        // Windows flushes only a handle opened for writing.
        match std::fs::OpenOptions::new().read(true).write(true).open(&path) {
            Ok(file) => file.sync_all().map_err(|e| format!("sync {}: {e}", path.display()))?,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
            Err(e) => return Err(format!("sync {}: {e}", path.display())),
        }
    }
    Ok(())
}

/// The directory of the account this task belongs to, for files that are that
/// account's alone. Resolved through the session, never the account on screen.
pub fn current_account_dir() -> Result<PathBuf, String> {
    let db = current_session().path()?;
    db.parent().map(PathBuf::from).ok_or_else(|| "account directory unknown".to_string())
}

fn get_current_db_path() -> Result<PathBuf, String> {
    let npub = get_current_account()?;
    Ok(account_dir(&npub)?.join("vector.db"))
}

/// Open a connection, riding out a TRANSIENT lock on the file.
///
/// `busy_timeout` governs waits inside a connection that already exists; it
/// cannot help the open itself, and `journal_mode=WAL` needs the lock briefly.
/// A task started under the previous account can still be holding this file for
/// a moment — it resolves the CURRENT account when it takes a connection, so a
/// swap points it here — and failing outright turns that into a failed login or
/// a failed account switch. Bounded: a genuinely stuck holder still surfaces.
fn create_connection(path: &PathBuf) -> Result<rusqlite::Connection, String> {
    const OPEN_RETRIES: u32 = 4;
    let mut last_err = String::new();
    for attempt in 0..OPEN_RETRIES {
        match open_connection(path) {
            Ok(conn) => return Ok(conn),
            Err(e) if e.contains("locked") || e.contains("busy") => {
                last_err = e;
                // One thread on the web: nothing else can release the lock while we wait.
                #[cfg(not(target_arch = "wasm32"))]
                std::thread::sleep(std::time::Duration::from_millis(50 * u64::from(attempt + 1)));
                #[cfg(target_arch = "wasm32")]
                let _ = attempt;
            }
            Err(e) => return Err(e),
        }
    }
    Err(last_err)
}

/// A fresh connection to `path`, for reads that must not go through a session's pool.
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
pub(crate) fn connect_at(path: &std::path::Path) -> Result<rusqlite::Connection, String> {
    create_connection(&path.to_path_buf())
}

/// Set by a web build whose storage never syncs to disk itself (IndexedDB
/// mirroring, memory): SQLite must not ask it to, which IndexedDB refuses, and
/// with no shared memory there is no WAL, only a journal best kept in memory.
#[cfg(target_arch = "wasm32")]
static RELAXED_DURABILITY: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

#[cfg(target_arch = "wasm32")]
pub fn set_relaxed_durability(on: bool) {
    RELAXED_DURABILITY.store(on, std::sync::atomic::Ordering::Relaxed);
}

fn durability_pragmas() -> &'static str {
    #[cfg(target_arch = "wasm32")]
    if RELAXED_DURABILITY.load(std::sync::atomic::Ordering::Relaxed) {
        return "PRAGMA journal_mode=MEMORY; PRAGMA synchronous=OFF;";
    }
    "PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;"
}

fn open_connection(path: &PathBuf) -> Result<rusqlite::Connection, String> {
    let conn = rusqlite::Connection::open(path)
        .map_err(|e| format!("Failed to open database: {}", e))?;

    // busy_timeout FIRST, alone: `journal_mode=WAL` takes a brief exclusive lock,
    // and until the timeout is set it is still 0 — so a connection opened while
    // another is active failed outright ("database is locked") instead of waiting
    // the moment or two the other needed. Every pragma below now waits too.
    conn.execute_batch("PRAGMA busy_timeout=5000;")
        .map_err(|e| format!("Failed to set busy_timeout: {}", e))?;

    // WAL for concurrent reads. cache_size negative = KiB: 16 MiB is a burst's ceiling, so a
    // big transaction never spills mid-write (an idle connection is trimmed, see
    // IDLE_CACHE_BYTES); temp_store=MEMORY keeps GROUP BY / sort scratch off disk.
    conn.execute_batch(&format!(
        "{} PRAGMA foreign_keys=ON; PRAGMA cache_size=-16000; PRAGMA temp_store=MEMORY;",
        durability_pragmas()
    ))
        .map_err(|e| format!("Failed to set pragmas: {}", e))?;
    // Room for every hot statement: page loads, unread counts and the persist path together
    // outgrow rusqlite's default of 16, and an evicted statement re-prepares on its next use.
    conn.set_prepared_statement_cache_capacity(64);

    // Memory-mapped reads skip a copy and a syscall per page. 64-bit only: each pooled connection
    // maps the file separately, which a 32-bit address space can't spare.
    #[cfg(target_pointer_width = "64")]
    let _ = conn.execute_batch("PRAGMA mmap_size=268435456;");

    Ok(conn)
}

/// Get a READ connection (headless-safe — no AppHandle).
#[track_caller]
pub fn get_db_connection_guard_static() -> Result<ConnectionGuard, String> {
    current_session().acquire_read()
}

/// Process-wide serialization lock for tests that install into the global DB pool.
/// Any test calling `init_database` must hold this for its whole body — otherwise
/// concurrent inits race on the shared account/data-dir state and clobber each other.
/// One shared guard across every module (community, ...) so cross-module test
/// parallelism can't collide.
#[cfg(test)]
pub(crate) static DB_TEST_GUARD: std::sync::Mutex<()> = std::sync::Mutex::new(());

/// Get the WRITE connection (headless-safe — no AppHandle).
#[track_caller]
pub fn get_write_connection_guard_static() -> Result<WriteConnectionGuard, String> {
    current_session().acquire_write()
}

// ============================================================================
// Downgrade guard
// ============================================================================

/// Where each build stamps its version after successfully opening an account.
const LAST_APP_VERSION_KEY: &str = "last_app_version";

/// A newer Vector already opened this account's database.
///
/// Vector has no downgrade path: older builds neither recognise nor preserve
/// newer schema, and the corruption that follows is silent until the user opens
/// the wrong chat.
#[derive(Debug, Clone, serde::Serialize)]
pub struct DowngradeBlock {
    /// Migration high-water mark found in the account's DB.
    pub db_schema: u32,
    /// Highest migration this build can apply.
    pub supported_schema: u32,
    /// App version that last opened it, when one was stamped.
    pub last_app_version: Option<String>,
}

impl std::fmt::Display for DowngradeBlock {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "This account was last opened by a newer version of Vector")?;
        if let Some(version) = &self.last_app_version {
            write!(f, " ({version})")?;
        }
        write!(
            f,
            ". Its database is at schema {} and this build only understands {}. \
             Opening it would corrupt your messages, so Vector has stopped. \
             Reinstall the newer version to continue.",
            self.db_schema, self.supported_schema
        )
    }
}

/// The check itself, against an already-open connection.
fn downgrade_block(conn: &rusqlite::Connection) -> Option<DowngradeBlock> {
    let db_schema = schema::applied_migration_high_water(conn);
    if db_schema <= schema::HIGHEST_MIGRATION_ID {
        return None;
    }
    Some(DowngradeBlock {
        db_schema,
        supported_schema: schema::HIGHEST_MIGRATION_ID,
        last_app_version: conn
            .query_row(
                "SELECT value FROM settings WHERE key = ?1",
                rusqlite::params![LAST_APP_VERSION_KEY],
                |row| row.get::<_, String>(0),
            )
            .ok(),
    })
}

/// Whether this account's DB was written by a newer Vector.
///
/// Read-only and side-effect free, so a host can call it before
/// [`init_database`] and put a real dialog in front of the user rather than
/// surfacing a failed boot.
pub fn inspect_downgrade(npub: &str) -> Result<Option<DowngradeBlock>, String> {
    let db_path = account_dir(npub)?.join("vector.db");
    // Never create the file just to inspect it.
    #[cfg(target_arch = "wasm32")]
    let exists = webfs::db_exists(&db_path);
    #[cfg(not(target_arch = "wasm32"))]
    let exists = db_path.exists();
    if !exists {
        return Ok(None);
    }
    let conn = create_connection(&db_path)?;
    Ok(downgrade_block(&conn))
}

// ============================================================================
// Database Initialization
// ============================================================================

/// Initialize the database for a given account (creates tables if needed).
pub fn init_database(npub: &str) -> Result<(), String> {
    let profile_dir = account_dir(npub)?;

    #[cfg(not(target_arch = "wasm32"))]
    if !profile_dir.exists() {
        std::fs::create_dir_all(&profile_dir)
            .map_err(|e| format!("Failed to create profile directory: {}", e))?;
    }
    #[cfg(target_arch = "wasm32")]
    webfs::register_account(get_app_data_dir()?, npub)?;

    let db_path = profile_dir.join("vector.db");
    let mut conn = create_connection(&db_path)?;

    // Migrations are boot-time, one-shot work: if another connection holds the
    // write lock (a straggling task from the previous session, a slow host),
    // waiting longer is strictly better than failing account init. The 5s
    // default is tuned for steady-state queries, not this.
    conn.execute_batch("PRAGMA busy_timeout=30000;")
        .map_err(|e| format!("Failed to set migration busy_timeout: {}", e))?;

    // Before ANY write. SQL_SCHEMA is all CREATE TABLE IF NOT EXISTS, so an
    // older build would resurrect tables newer migrations dropped and then
    // start writing rows against a schema it cannot see.
    if let Some(block) = downgrade_block(&conn) {
        return Err(block.to_string());
    }

    // No tables yet is a new account. One from before Keep Media was a choice kept every
    // download, so it goes on keeping media and its old downloads move in.
    let fresh = conn
        .query_row("SELECT 1 FROM sqlite_master WHERE type='table' AND name='settings'", [], |_| Ok(()))
        .is_err();

    conn.execute_batch(schema::SQL_SCHEMA)
        .map_err(|e| format!("Failed to create schema: {}", e))?;

    // Run migrations
    schema::run_migrations(&mut conn)?;

    let _ = conn.execute(
        "INSERT OR IGNORE INTO settings (key, value) VALUES ('keep_media', ?1)",
        [if fresh { "false" } else { "true" }],
    );

    // Stamped after migrations, so it names the build whose schema is now on
    // disk. A blocked build never reaches here, so this only ever records a
    // version that could actually read what it wrote.
    if let Some(version) = APP_VERSION.get() {
        let _ = conn.execute(
            "INSERT OR REPLACE INTO settings (key, value) VALUES (?1, ?2)",
            rusqlite::params![LAST_APP_VERSION_KEY, version],
        );
    }

    // SQLite's prescribed open-time step for long-lived connections: analyze every table that needs
    // it (missing stats, or grown/shrunk 10x), bounded by a temporary analysis_limit so it stays
    // fast. The 0x10000 bit forces checking all tables since a fresh connection has no query history;
    // this also satisfies the "run optimize after CREATE INDEX" guidance for the migrations above.
    let _ = conn.execute_batch("PRAGMA optimize=0x10002;");

    // Seed the in-session delete-tombstone set from this account's durable rows,
    // so ingest keeps refusing deleted messages across restarts (the swap's
    // session bump cleared the set; a fresh boot starts empty).
    {
        let mut stmt = conn.prepare("SELECT event_id FROM deleted_messages")
            .map_err(|e| format!("tombstone seed prepare: {}", e))?;
        let ids = stmt.query_map([], |row| row.get::<_, String>(0))
            .map_err(|e| format!("tombstone seed query: {}", e))?
            .filter_map(|r| r.ok());
        crate::state::seed_message_tombstones(ids);
    }

    // MLS is fully removed. Migration 41 drops the relational tables, but the OpenMLS/MDK
    // crypto store lived in a SEPARATE per-account file (`<account>/mls/`) that no migration
    // can reach. Purge it here: it's dead weight (can run to hundreds of MB) and, worse,
    // stale MLS private key material lingering for a feature that no longer exists. Best-effort
    // and idempotent — a cleanup failure must never block account init.
    let mls_dir = profile_dir.join("mls");
    if mls_dir.exists() {
        match std::fs::remove_dir_all(&mls_dir) {
            Ok(()) => crate::log_info!("[db] purged orphaned MLS store for account"),
            Err(e) => crate::log_warn!("[db] could not purge orphaned MLS store: {}", e),
        }
    }

    // Install a NEW session before opening anything: guards still outstanding
    // against the previous one return their connections there, and that pool
    // closes with it. Nothing from the old account can reach the new pool.
    //
    // A session already pointed at this database, or not yet pointed at one at
    // all, is THIS account's — bind it and keep what it holds (see `rebound`).
    // Only a session belonging to a different account starts over.
    let session = {
        let next = {
            let current = CURRENT_SESSION.read().unwrap_or_else(|e| e.into_inner());
            match current.db_path.as_deref() {
                Some(p) if p != db_path => Session::bound(db_path.clone()),
                _ => current.rebound(db_path.clone()),
            }
        };
        install(next.clone());
        next
    };

    // Pre-warm readers, opened outside the pool's lock and only up to its cap: the session
    // is live already, and a read may have opened one meanwhile.
    let warm: Vec<_> = (0..4).filter_map(|_| create_connection(&db_path).ok()).collect();
    {
        let mut pool = session.read_pool.lock().unwrap_or_else(|e| e.into_inner());
        for c in warm {
            if pool.len() + session.readers_out.load(std::sync::atomic::Ordering::Relaxed) < MAX_READERS {
                pool.push(c);
            }
        }
        session.reader_free.notify_all();
    }

    // Set write connection
    install_writer(&session, create_connection(&db_path)?);

    // Straight from `db_path` into `session`: switch_account opens the database before it
    // marks the account current, and the task may be bound to the previous session.
    crate::transport::prefs::hydrate(&session, &db_path);
    if let Ok(conn) = create_connection(&db_path) {
        crate::media::store::load_index(&session, &conn);
    }

    // Read the notification preferences now: every badge recount resolves every
    // chat against them, so a lazy first read would land a SQLite round trip on
    // that path with the chat state lock held.
    crate::notify::warm();

    crate::profile::sync::wake_processor();
    Ok(())
}

/// Drop this account's database resources.
///
/// Installing a fresh session IS the teardown: the previous one is released,
/// and its connections close once the last outstanding guard returns. A guard
/// still in flight keeps serving the account it began under.
pub fn close_database() {
    replace_session();
}

/// Run plain `PRAGMA optimize` on the live write connection — the periodic top-up SQLite recommends
/// for long-lived connections (the heavy lifting is the `optimize=0x10002` at connection open).
/// Best-effort and cheap: re-analyzes only tables whose stats the planner used and that changed
/// materially since the last run.
pub fn optimize_database() {
    let session = current_session();
    let guard = session.write_conn.lock().unwrap_or_else(|e| e.into_inner());
    if let Some(conn) = guard.as_ref() {
        let _ = conn.execute_batch("PRAGMA optimize;");
    }
}

/// Get all available accounts (npub directories in app data).
pub fn get_accounts() -> Result<Vec<String>, String> {
    let app_data = get_app_data_dir()?;
    #[cfg(target_arch = "wasm32")]
    return Ok(list_account_npubs_in(app_data)
        .into_iter()
        .filter(|npub| webfs::db_exists(&app_data.join(npub).join("vector.db")))
        .collect());
    #[cfg(not(target_arch = "wasm32"))]
    {
        let mut accounts = Vec::new();

        if let Ok(entries) = std::fs::read_dir(app_data) {
            for entry in entries.flatten() {
                if entry.file_type().is_ok_and(|ft| ft.is_dir()) {
                    let name = entry.file_name().to_string_lossy().to_string();
                    if name.starts_with("npub1") {
                        // Check if vector.db exists
                        if entry.path().join("vector.db").exists() {
                            accounts.push(name);
                        }
                    }
                }
            }
        }

        Ok(accounts)
    }
}

/// Get the profile directory path for a given npub.
pub fn get_profile_directory(npub: &str) -> Result<PathBuf, String> {
    if !npub.starts_with("npub1") {
        return Err(format!("Invalid npub format: {}", npub));
    }
    let dir = account_dir(npub)?;
    #[cfg(not(target_arch = "wasm32"))]
    if !dir.exists() {
        std::fs::create_dir_all(&dir)
            .map_err(|e| format!("Failed to create profile directory: {}", e))?;
    }
    Ok(dir)
}

/// Get database path for a given npub.
pub fn get_database_path(npub: &str) -> Result<PathBuf, String> {
    Ok(get_profile_directory(npub)?.join("vector.db"))
}

// ============================================================================
// ID Caches
// ============================================================================

/// Clear every id cache on account switch. Row ids are PER-ACCOUNT (each account
/// has its own DB + id sequence), so a stale entry after a swap points into the
/// wrong DB: writes FK-fail silently and reads hit the wrong row. The caches live
/// in `id_cache`; this is the public entry the swap path + callers already use.
pub fn clear_id_caches() {
    id_cache::clear_id_caches();
    community::clear_banlist_cache();
    community::clear_channel_community_cache();
}

// ============================================================================
// System Event Types
// ============================================================================

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[repr(u8)]
pub enum SystemEventType {
    MemberLeft = 0,
    MemberJoined = 1,
    MemberRemoved = 2,
    WallpaperChanged = 3,
}

impl SystemEventType {
    pub fn display_message(&self, display_name: &str) -> String {
        match self {
            SystemEventType::MemberLeft => format!("{} has left", display_name),
            SystemEventType::MemberJoined => format!("{} has joined", display_name),
            SystemEventType::MemberRemoved => format!("{} was removed", display_name),
            SystemEventType::WallpaperChanged => format!("{} changed the wallpaper", display_name),
        }
    }

    pub fn as_u8(&self) -> u8 { *self as u8 }
}

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

    /// Build a minimal in-memory SQLite connection — just enough to drop
    /// a connection through the guard machinery. We don't run schema or
    /// migrations because we only care about the guard's Drop pathway.
    fn fake_conn() -> rusqlite::Connection {
        rusqlite::Connection::open_in_memory().unwrap()
    }

    #[test]
    fn a_new_session_wakes_the_idle_profile_processor() {
        let _guard = DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        let wakes = || crate::profile::sync::SESSION_WAKES.load(std::sync::atomic::Ordering::SeqCst);
        let before = wakes();
        close_database();
        assert!(
            wakes() > before,
            "a session going live must wake the processor, or queued profiles wait for its next timer"
        );
    }

    #[test]
    fn close_database_installs_a_fresh_session() {
        // The guard is the POINT here, not boilerplate: `close_database`
        // replaces the process-global session, so running unguarded yanks the
        // database out from under whichever test is mid-query.
        let _guard = DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        let before = current_session();
        close_database();
        let after = current_session();
        assert!(
            !Arc::ptr_eq(&before, &after),
            "close_database must install a NEW session — the old one is what in-flight guards return to"
        );
    }

    #[test]
    fn a_guard_returns_its_connection_to_its_own_session() {
        let session = Session::empty();
        drop(ConnectionGuard::new(fake_conn(), session.clone(), true));
        assert_eq!(session.read_pool.lock().unwrap().len(), 1, "the connection goes home");
    }

    #[test]
    fn the_burst_reuses_the_reader_it_just_returned() {
        let session = Session::empty();
        let a = ConnectionGuard::new(fake_conn(), session.clone(), true);
        let b = ConnectionGuard::new(fake_conn(), session.clone(), true);
        // SAFETY: only compared, never dereferenced.
        let b_handle = unsafe { b.handle() } as usize;
        drop(a);
        drop(b);
        let next = session.acquire_read().unwrap();
        assert_eq!(unsafe { next.handle() } as usize, b_handle, "most recently used first, so the oldest can age out");
    }

    fn writer_session(dir: &tempfile::TempDir) -> Arc<Session> {
        let path = dir.path().join("vector.db");
        drop(open_connection(&path).unwrap());
        Session::bound(path)
    }

    fn handle_of(w: &WriteConnectionGuard) -> usize {
        // SAFETY: only compared, never dereferenced.
        unsafe { w.handle() as usize }
    }

    #[test]
    fn a_write_waits_for_the_writer_instead_of_opening_another() {
        let dir = tempfile::tempdir().unwrap();
        let session = writer_session(&dir);
        let first = session.acquire_write().unwrap();
        let held = handle_of(&first);
        let s2 = session.clone();
        let waiter = std::thread::spawn(move || {
            let t = web_time::Instant::now();
            let w = s2.acquire_write().unwrap();
            (handle_of(&w), t.elapsed())
        });
        std::thread::sleep(std::time::Duration::from_millis(60));
        drop(first);
        let (got, waited) = waiter.join().unwrap();
        assert_eq!(got, held, "the same writer, handed over");
        assert!(waited < WRITER_WAIT, "woken by the return, not the timeout: {waited:?}");
    }

    #[test]
    fn a_first_write_with_nothing_out_opens_at_once() {
        let dir = tempfile::tempdir().unwrap();
        let t = web_time::Instant::now();
        let _w = writer_session(&dir).acquire_write().unwrap();
        assert!(t.elapsed() < WRITER_WAIT / 2, "{:?}", t.elapsed());
    }

    #[test]
    fn a_write_waiting_at_login_wakes_when_the_writer_is_installed() {
        let dir = tempfile::tempdir().unwrap();
        let session = writer_session(&dir);
        let early = session.acquire_write().unwrap();
        let s2 = session.clone();
        let waiter = std::thread::spawn(move || {
            let t = web_time::Instant::now();
            let w = s2.acquire_write().unwrap();
            (handle_of(&w), t.elapsed())
        });
        std::thread::sleep(std::time::Duration::from_millis(40));
        let installed = open_connection(&dir.path().join("vector.db")).unwrap();
        // SAFETY: only compared, never dereferenced.
        let installed_handle = unsafe { installed.handle() } as usize;
        install_writer(&session, installed);
        let (got, waited) = waiter.join().unwrap();
        assert_eq!(got, installed_handle);
        assert!(waited < WRITER_WAIT, "woken by the install: {waited:?}");
        drop(early);
    }

    #[test]
    fn the_pool_stops_at_its_cap_and_a_read_waits_for_one_back() {
        let dir = tempfile::tempdir().unwrap();
        let session = writer_session(&dir);
        let s2 = session.clone();
        let (tx, rx) = std::sync::mpsc::channel();
        let (go, wait) = std::sync::mpsc::channel::<()>();
        let holder = std::thread::spawn(move || {
            let held: Vec<_> = (0..MAX_READERS).map(|_| s2.acquire_read().unwrap()).collect();
            // SAFETY: only compared, never dereferenced.
            tx.send(held.iter().map(|g| unsafe { g.handle() } as usize).collect::<Vec<_>>()).unwrap();
            wait.recv().unwrap();
            drop(held);
        });
        let held = rx.recv().unwrap();
        let s3 = session.clone();
        let reader = std::thread::spawn(move || {
            let t = web_time::Instant::now();
            let r = s3.acquire_read().unwrap();
            (unsafe { r.handle() } as usize, t.elapsed())
        });
        std::thread::sleep(std::time::Duration::from_millis(5));
        go.send(()).unwrap();
        holder.join().unwrap();
        let (got, waited) = reader.join().unwrap();
        assert!(held.contains(&got), "one of the pool's own, not a new connection");
        assert!(waited < READER_WAIT, "woken by the return: {waited:?}");
        assert_eq!(session.read_pool.lock().unwrap().len(), MAX_READERS, "the pool never grew past its cap");
        assert_eq!(session.readers_out.load(std::sync::atomic::Ordering::Relaxed), 0, "every reader counted home");
    }

    #[test]
    fn a_nested_read_never_waits_and_its_passing_connection_closes() {
        let dir = tempfile::tempdir().unwrap();
        let session = writer_session(&dir);
        let held: Vec<_> = (0..MAX_READERS).map(|_| session.acquire_read().unwrap()).collect();
        let t = web_time::Instant::now();
        let passing = session.acquire_read().unwrap();
        assert!(t.elapsed() < READER_WAIT / 2, "{:?}", t.elapsed());
        drop(passing);
        drop(held);
        assert_eq!(session.read_pool.lock().unwrap().len(), MAX_READERS, "the passing one closed instead of joining");
        assert_eq!(session.readers_out.load(std::sync::atomic::Ordering::Relaxed), 0, "every reader counted home");
    }

    #[test]
    fn a_read_kept_waiting_past_the_bound_opens_a_passing_connection() {
        let dir = tempfile::tempdir().unwrap();
        let session = writer_session(&dir);
        let s2 = session.clone();
        let (tx, rx) = std::sync::mpsc::channel();
        let (go, wait) = std::sync::mpsc::channel::<()>();
        let holder = std::thread::spawn(move || {
            let held: Vec<_> = (0..MAX_READERS).map(|_| s2.acquire_read().unwrap()).collect();
            tx.send(()).unwrap();
            wait.recv().unwrap();
            drop(held);
        });
        rx.recv().unwrap();
        let t = web_time::Instant::now();
        let r = session.acquire_read().unwrap();
        assert!(t.elapsed() >= READER_WAIT, "{:?}", t.elapsed());
        drop(r);
        go.send(()).unwrap();
        holder.join().unwrap();
        assert_eq!(session.read_pool.lock().unwrap().len(), MAX_READERS);
    }

    #[test]
    fn the_ui_thread_never_waits_on_a_full_pool() {
        let dir = tempfile::tempdir().unwrap();
        let session = writer_session(&dir);
        let s2 = session.clone();
        let (tx, rx) = std::sync::mpsc::channel();
        let (go, wait) = std::sync::mpsc::channel::<()>();
        let holder = std::thread::spawn(move || {
            let r: Vec<_> = (0..MAX_READERS).map(|_| s2.acquire_read().unwrap()).collect();
            let w = s2.acquire_write().unwrap();
            tx.send(()).unwrap();
            wait.recv().unwrap();
            drop((r, w));
        });
        rx.recv().unwrap();
        let ui = std::thread::spawn(move || {
            never_wait_on_this_thread();
            let t = web_time::Instant::now();
            let r = session.acquire_read().unwrap();
            let w = session.acquire_write().unwrap();
            drop((r, w));
            t.elapsed()
        });
        let took = ui.join().unwrap();
        go.send(()).unwrap();
        holder.join().unwrap();
        assert!(took < READER_WAIT / 2, "{took:?}");
    }

    #[test]
    fn a_failed_open_gives_its_place_back() {
        let dir = tempfile::tempdir().unwrap();
        let session = Session::bound(dir.path().join("missing").join("vector.db"));
        assert!(session.acquire_read().is_err());
        assert!(session.acquire_write().is_err());
        assert_eq!(session.readers_out.load(std::sync::atomic::Ordering::Relaxed), 0);
        assert_eq!(session.writers_out.load(std::sync::atomic::Ordering::Relaxed), 0);
    }

    #[test]
    fn a_nested_write_never_waits_on_itself() {
        let dir = tempfile::tempdir().unwrap();
        let session = writer_session(&dir);
        let outer = session.acquire_write().unwrap();
        let t = web_time::Instant::now();
        let inner = session.acquire_write().unwrap();
        assert!(t.elapsed() < WRITER_WAIT / 2, "{:?}", t.elapsed());
        assert_ne!(handle_of(&inner), handle_of(&outer));
    }

    #[test]
    fn a_writer_held_past_the_wait_lets_another_write_open_its_own() {
        let dir = tempfile::tempdir().unwrap();
        let session = writer_session(&dir);
        let first = session.acquire_write().unwrap();
        let held = handle_of(&first);
        let s2 = session.clone();
        let waiter = std::thread::spawn(move || {
            let t = web_time::Instant::now();
            let w = s2.acquire_write().unwrap();
            (handle_of(&w), t.elapsed())
        });
        let (got, waited) = waiter.join().unwrap();
        assert_ne!(got, held);
        assert!(waited >= WRITER_WAIT, "{waited:?}");
        drop(first);
    }

    /// A real file database: an in-memory one's pages ARE its storage and never trim.
    fn file_conn(dir: &tempfile::TempDir) -> rusqlite::Connection {
        let conn = open_connection(&dir.path().join("vector.db")).unwrap();
        conn.execute_batch("CREATE TABLE IF NOT EXISTS t(k BLOB PRIMARY KEY, v BLOB);").unwrap();
        conn
    }

    /// One transaction of ~6 MiB: past the idle cap, inside `cache_size`.
    const BURST: &str = "BEGIN; WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 2000) \
                         INSERT INTO t SELECT randomblob(16), randomblob(3000) FROM n; COMMIT;";

    #[test]
    fn the_writer_keeps_a_small_cache_warm_and_hands_back_a_burst() {
        // One page cache per process: a parallel trim or close would empty this test's.
        let _guard = DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        let dir = tempfile::tempdir().unwrap();
        let session = Session::empty();
        let parked = |s: &Arc<Session>| s.write_conn.lock().unwrap().as_ref().map(page_cache_bytes).unwrap();

        let w = WriteConnectionGuard::new(file_conn(&dir), session.clone());
        w.execute("INSERT INTO t VALUES (randomblob(16), randomblob(100))", []).unwrap();
        let small = page_cache_bytes(&w);
        assert!(small > 0);
        drop(w);
        assert_eq!(parked(&session), small, "everyday use stays warm");

        let w = WriteConnectionGuard::new(session.write_conn.lock().unwrap().take().unwrap(), session.clone());
        w.execute_batch(BURST).unwrap();
        assert!(page_cache_bytes(&w) > IDLE_CACHE_BYTES, "the burst had its headroom");
        drop(w);
        assert!(parked(&session) < IDLE_CACHE_BYTES);
    }

    #[test]
    fn a_reader_hands_back_a_burst_when_it_goes_idle() {
        let _guard = DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        let dir = tempfile::tempdir().unwrap();
        let session = Session::empty();
        file_conn(&dir).execute_batch(BURST).unwrap();

        let r = ConnectionGuard::new(file_conn(&dir), session.clone(), true);
        // Unmapped, so every page it scans lands in its own cache.
        r.execute_batch("PRAGMA mmap_size=0;").unwrap();
        let _: i64 = r.query_row("SELECT sum(length(v)) FROM t", [], |row| row.get(0)).unwrap();
        assert!(page_cache_bytes(&r) > IDLE_CACHE_BYTES);
        drop(r);
        assert!(page_cache_bytes(&session.read_pool.lock().unwrap()[0]) < IDLE_CACHE_BYTES);
    }

    #[test]
    fn a_guard_outstanding_across_a_swap_returns_to_the_session_it_came_from() {
        // The property that replaced the generation counter, and a stronger
        // one: the old design could only assert a stale connection did NOT
        // pollute the new pool. Holding the Arc says where it actually went,
        // so account A's connection is unreachable from account B by
        // construction rather than by a comparison someone has to remember.
        let old = Session::empty();
        let new_session = Session::empty();

        let guard = ConnectionGuard::new(fake_conn(), old.clone(), true);
        // ...the account switches while the guard is still in flight...
        drop(guard);

        assert_eq!(old.read_pool.lock().unwrap().len(), 1, "returned to the session it was taken from");
        assert_eq!(new_session.read_pool.lock().unwrap().len(), 0, "never reachable from the new account");
    }

    #[test]
    fn a_pool_miss_after_a_swap_opens_the_sessions_own_database() {
        // The other half of the guarantee. Returning a connection was already
        // safe; ACQUIRING one was not, because a miss resolved the ambient
        // account and could open the incoming account's file into the outgoing
        // account's pool. A bound session never asks what is current.
        let dir = tempfile::tempdir().unwrap();
        let path_a = dir.path().join("a.db");
        let path_b = dir.path().join("b.db");

        let session_a = Session::bound(path_a.clone());
        let _unrelated = Session::bound(path_b.clone());

        // A task still holding A misses A's (empty) pool and opens a connection.
        let guard = session_a.acquire_read().expect("acquire against the held session");
        // Compare by filename: macOS reports the /private-resolved path.
        let opened = guard.path().expect("a file-backed connection").to_string();
        assert!(
            opened.ends_with("a.db") && !opened.ends_with("b.db"),
            "a miss opens the session's OWN database, never the incoming account's (opened {opened})"
        );
        assert!(!Arc::ptr_eq(&session_a, &current_session()), "the live session really did move on");
    }

    /// Run `fut` bound to `session`, exactly as `spawn_bound` would.
    ///
    /// These tests never install their throwaway sessions globally. They used
    /// to, and every other test in the binary reads chats, caches and keys
    /// through the live session — so one of these swapping it mid-run pulled
    /// them out from under whatever was executing in parallel. Binding proves
    /// the same property without a global write.
    async fn bound_to<F: std::future::Future>(session: Arc<Session>, fut: F) -> F::Output {
        TASK_SESSION.scope(session, fut).await
    }

    /// Every task that touches per-account state must be bound to an account.
    ///
    /// The worklist is empty: every spawn in this crate either binds or says on
    /// the line why it owns no account state. See [`crate::spawn_audit`].
    #[test]
    fn per_account_tasks_are_spawned_bound_to_their_account() {
        crate::spawn_audit::assert_all_spawns_bound(std::path::Path::new(env!("CARGO_MANIFEST_DIR")), &[]);
    }

    #[tokio::test]
    async fn a_bound_task_keeps_its_account_across_a_swap() {
        // What the std::sync::Arc<crate::db::Session> checks were approximating by hand: the task
        // began under account A, so its work resolves to A however many awaits
        // it spans and whoever logs in meanwhile. No check, nothing to forget.
        // The live session stands in for whoever logged in next.
        let dir = tempfile::tempdir().unwrap();
        let a = Session::bound(dir.path().join("a.db"));

        let seen = bound_to(a.clone(), async {
            crate::rt::yield_now().await;
            current_session()
        })
        .await;

        assert!(Arc::ptr_eq(&seen, &a), "the task still sees the account it started under");
        assert!(!Arc::ptr_eq(&seen, &current_session()), "the live account is not reachable from it");
    }

    #[tokio::test]
    async fn a_bound_tasks_chat_writes_cannot_reach_the_new_account() {
        // The bug this closes, in the form it actually took: a task holding a
        // chat id from account A finishes after the swap and inserts it into
        // whatever STATE it finds. The group chats that appeared in a freshly
        // created account arrived exactly this way.
        use crate::chat::{Chat, ChatType};
        let dir = tempfile::tempdir().unwrap();
        let a = Session::bound(dir.path().join("a.db"));
        let live_before = current_session().chat_state().lock().await.chats.len();

        bound_to(a.clone(), async {
            crate::rt::yield_now().await;
            crate::state::STATE.lock().await.chats.push(Chat::new("a-chat".into(), ChatType::DirectMessage, Vec::new()));
        })
        .await;

        assert_eq!(
            a.chat_state().lock().await.chats.len(),
            1,
            "it landed in the state of the account the task began under"
        );
        assert_eq!(
            current_session().chat_state().lock().await.chats.len(),
            live_before,
            "and nothing reached the account on screen"
        );
    }

    #[tokio::test]
    async fn a_bound_task_cannot_publish_through_the_new_accounts_client() {
        // The client carries the signer, so reaching the wrong one means
        // publishing account A's payload under account B's identity. A bound
        // task reaches the client it started with, which the swap has already
        // shut down — its send fails instead of succeeding as the wrong person.
        use nostr_sdk::prelude::*;
        let dir = tempfile::tempdir().unwrap();
        let a = Session::bound(dir.path().join("a.db"));
        let a_identity = Keys::generate().public_key();

        let seen = bound_to(a.clone(), async move {
            crate::state::set_my_public_key(a_identity);
            crate::rt::yield_now().await;
            crate::state::my_public_key()
        })
        .await;

        assert_eq!(seen, Some(a_identity), "the task signs as the account it began under");
        assert_ne!(crate::state::my_public_key(), Some(a_identity), "and the live account is someone else");
    }

    #[test]
    fn binding_an_unbound_session_to_a_database_keeps_what_it_holds() {
        // Creating an account installs its keys and client BEFORE its database
        // exists — `init_database` only runs once the user has chosen a PIN.
        // Replacing the session there would discard the login in progress.
        let dir = tempfile::tempdir().unwrap();
        let staging = Session::empty();
        let held = staging.scoped::<Session, Mutex<u8>>();
        *held.lock().unwrap() = 7;

        let promoted = staging.rebound(dir.path().join("a.db"));
        assert_eq!(*promoted.scoped::<Session, Mutex<u8>>().lock().unwrap(), 7, "the login survives being bound");
        assert!(promoted.db_path.is_some(), "and it now has a database");
        assert_eq!(promoted.id, staging.id, "and it is still the same account, so its tasks keep painting");
    }

    #[tokio::test]
    async fn a_bound_task_paints_nothing_into_the_account_on_screen() {
        // Binding fixes where work LANDS; it cannot fix what the user SEES,
        // because there is one UI showing one account. So emission asks once,
        // centrally, and a task belonging to a previous account goes quiet.
        let dir = tempfile::tempdir().unwrap();
        let previous = Session::bound(dir.path().join("previous.db"));
        assert!(session_is_live(), "work for the account on screen paints");

        let painted = bound_to(previous, async {
            crate::rt::yield_now().await;
            session_is_live()
        })
        .await;

        assert!(!painted, "a task bound to another account paints nothing");
        assert!(session_is_live(), "and the account now on screen still does");
    }

    #[tokio::test]
    async fn switching_accounts_tells_the_previous_one_to_stop() {
        // Purely an efficiency signal — the work would still be correct — but a
        // boot sync is minutes of relay traffic and decryption, and after a swap
        // nobody is waiting for any of it.
        let _serialized = DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        let previous = current_session();
        assert!(!previous.stopped(), "running work is not told to stop");

        // `on_stop` must be pending until the switch, then resolve.
        let waiter = { let p = previous.clone(); crate::rt::spawn(async move { p.on_stop().await }) };
        crate::rt::yield_now().await;
        assert!(!waiter.is_finished(), "nothing to report while the account is current");

        close_database();

        assert!(previous.stopped(), "the outgoing account is told to stop");
        assert!(!current_session().stopped(), "the incoming one is not");
        crate::rt::time::timeout(std::time::Duration::from_secs(5), waiter)
            .await
            .expect("on_stop resolves on the switch")
            .expect("without panicking");
    }

    #[test]
    fn re_initialising_the_same_account_does_not_tell_it_to_stop() {
        // `init_database` runs more than once per account — the schema check at
        // boot, Android's background sync. Reading that as a swap would abort a
        // sync that is still perfectly wanted.
        let dir = tempfile::tempdir().unwrap();
        let staging = Session::empty();
        let promoted = staging.rebound(dir.path().join("a.db"));
        assert!(!staging.stopped(), "binding a session is not switching away from it");
        assert_eq!(promoted.id, staging.id);
    }

    /// Binding must not grow with what it binds.
    ///
    /// `scope` takes the future BY VALUE, so an unboxed `scoped` embeds the
    /// whole inner state machine in its caller's. Nesting then multiplies, and
    /// a deep chain of bound calls overflows a worker stack — which is exactly
    /// what happened: boot crashed on BOTH Android and macOS, several layers
    /// into the community sync, on stacks every one of these tests runs on
    /// happily. Sizes are what the compiler gives us; the invariant is that the
    /// wrapper adds a bounded amount regardless of the body.
    #[test]
    fn binding_a_future_does_not_embed_it() {
        // A deliberately fat body: 8KB of state the future must carry.
        let fat = async {
            let block = [0u8; 8192];
            crate::rt::yield_now().await;
            block[0]
        };
        let fat_size = std::mem::size_of_val(&fat);
        assert!(fat_size >= 8192, "the body really is large ({fat_size})");

        let bound = scoped(fat);
        let bound_size = std::mem::size_of_val(&bound);
        assert!(
            bound_size < 1024,
            "binding must cost a pointer, not a copy of the body \
             (body {fat_size} bytes, bound {bound_size})"
        );
    }

    #[test]
    fn a_dropped_session_closes_its_pool() {
        // Teardown IS the drop: no clearing step to forget.
        let session = Session::empty();
        drop(ConnectionGuard::new(fake_conn(), session.clone(), true));
        assert_eq!(Arc::strong_count(&session), 1, "the guard released its reference");
        drop(session); // pool + connections close here
    }

    #[test]
    fn a_stale_write_guard_cannot_clobber_the_new_accounts_connection() {
        // Under the old design the stale guard and the fresh connection shared
        // one global slot, so the guard's Drop had to be talked out of
        // overwriting it. They are now in different sessions and cannot meet.
        let old = Session::empty();
        let new_session = Session::empty();

        let stale_guard = WriteConnectionGuard::new(fake_conn(), old.clone());
        // init_database installs the new account's write connection.
        *new_session.write_conn.lock().unwrap() = Some(fake_conn());

        drop(stale_guard);

        assert!(
            new_session.write_conn.lock().unwrap().is_some(),
            "the new account's write connection is untouched"
        );
        assert!(
            old.write_conn.lock().unwrap().is_some(),
            "the stale guard returned to its own session's slot"
        );
    }

    #[test]
    fn a_new_accounts_empty_write_slot_stays_empty() {
        // The old worry: a stale guard filling the fresh account's empty slot
        // with a connection pointing at a different database. It has no way to
        // reach that slot now — it only knows its own session.
        let old = Session::empty();
        let new_session = Session::empty();

        let stale_guard = WriteConnectionGuard::new(fake_conn(), old.clone());
        drop(stale_guard);

        assert!(
            new_session.write_conn.lock().unwrap().is_none(),
            "the new account's slot is untouched by the previous account's guard"
        );
    }
}

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

    fn test_account() -> (tempfile::TempDir, std::sync::MutexGuard<'static, ()>, String) {
        let guard = DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        close_database();
        clear_id_caches();
        let tmp = tempfile::tempdir().unwrap();
        // Bases must not collide across test modules: APP_DATA_DIR is a
        // OnceLock shared by the whole binary, and this generator collapses
        // after ~4 chars, so nearby seeds yield near-identical npubs.
        // Taken: 0, 900, 5_000, 50_000, 70_000, 71_000, 81_000, 90_000.
        static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(61_000);
        let n = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        const B: &[u8] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
        let mut acct = String::from("npub1");
        let mut v = n as usize;
        for _ in 0..58 {
            acct.push(B[v % 32] as char);
            v = v / 32 + 7;
        }
        set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
        set_current_account(acct.clone()).unwrap();
        (tmp, guard, acct)
    }

    #[tokio::test]
    async fn re_initialising_the_same_account_keeps_its_loaded_state() {
        // init_database is documented idempotent, and callers lean on that —
        // the schema check and Android's background sync both re-run it against
        // an account already loaded. Dropping its chats there would empty the
        // list under a running app.
        use crate::chat::{Chat, ChatType};
        let (_dir, _lock, acct) = test_account();
        init_database(&acct).unwrap();
        crate::state::STATE.lock().await.chats.push(Chat::new("kept".into(), ChatType::DirectMessage, Vec::new()));

        init_database(&acct).unwrap();
        assert_eq!(crate::state::STATE.lock().await.chats.len(), 1, "same account, same in-memory state");
    }

    /// A DB this build fully understands must open, or the guard is useless.
    #[test]
    fn an_equal_schema_opens_normally() {
        let (_tmp, _guard, acct) = test_account();
        init_database(&acct).unwrap();
        assert!(inspect_downgrade(&acct).unwrap().is_none());
        // Re-opening is still fine: the stamp write must not trip the guard.
        init_database(&acct).unwrap();
        assert!(inspect_downgrade(&acct).unwrap().is_none());
    }

    /// Absent DB is not a downgrade; it must not be created just to look.
    #[test]
    fn a_missing_database_is_not_a_downgrade() {
        let (_tmp, _guard, acct) = test_account();
        assert!(inspect_downgrade(&acct).unwrap().is_none());
        assert!(!account_dir(&acct).unwrap().join("vector.db").exists());
    }

    #[test]
    fn a_newer_schema_blocks_the_open_and_names_the_build() {
        let (_tmp, _guard, acct) = test_account();
        init_database(&acct).unwrap();

        // Stand in for a newer Vector having run one migration past this build.
        let db_path = account_dir(&acct).unwrap().join("vector.db");
        {
            let conn = create_connection(&db_path).unwrap();
            conn.execute(
                "INSERT OR REPLACE INTO schema_migrations (id, applied_at) VALUES (?1, 0)",
                rusqlite::params![schema::HIGHEST_MIGRATION_ID + 1],
            )
            .unwrap();
            conn.execute(
                "INSERT OR REPLACE INTO settings (key, value) VALUES (?1, ?2)",
                rusqlite::params![LAST_APP_VERSION_KEY, "9.9.9"],
            )
            .unwrap();
        }
        close_database();

        let block = inspect_downgrade(&acct)
            .unwrap()
            .expect("a higher migration id must read as a downgrade");
        assert_eq!(block.db_schema, schema::HIGHEST_MIGRATION_ID + 1);
        assert_eq!(block.supported_schema, schema::HIGHEST_MIGRATION_ID);
        assert_eq!(block.last_app_version.as_deref(), Some("9.9.9"));

        let err = init_database(&acct).unwrap_err();
        assert!(err.contains("9.9.9"), "must name the newer build: {err}");
    }

    /// The guard has to fire before SQL_SCHEMA runs: its CREATE TABLE IF NOT
    /// EXISTS statements would otherwise resurrect tables newer migrations drop.
    #[test]
    fn a_blocked_open_writes_nothing() {
        let (_tmp, _guard, acct) = test_account();
        init_database(&acct).unwrap();
        let db_path = account_dir(&acct).unwrap().join("vector.db");
        {
            let conn = create_connection(&db_path).unwrap();
            conn.execute(
                "INSERT OR REPLACE INTO schema_migrations (id, applied_at) VALUES (?1, 0)",
                rusqlite::params![schema::HIGHEST_MIGRATION_ID + 5],
            )
            .unwrap();
            conn.execute("DROP TABLE IF EXISTS settings", []).unwrap();
        }
        close_database();

        assert!(init_database(&acct).is_err());

        // SQL_SCHEMA would have recreated `settings`; it must still be gone.
        let conn = create_connection(&db_path).unwrap();
        let exists: bool = conn
            .query_row(
                "SELECT 1 FROM sqlite_master WHERE type='table' AND name='settings'",
                [],
                |_| Ok(true),
            )
            .unwrap_or(false);
        assert!(!exists, "a blocked open must not write to the database");
    }
}