lingxia-browser 0.18.0

Browser runtime capability crate for LingXia
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
//! Browser tab state: tab id resolution and scopes, open/close/update/activate,
//! and the create-token machinery shared with WebView creation.

use crate::BUILTIN_BROWSER_APPID;
use crate::internal_pages::registered_control_page_route;
use crate::policy::{is_lingxia_startup_url, normalize_browser_target_url};
use crate::types::{BrowserAutomationError, BrowserTabInfo, TrustedControlPageNavigation};
use crate::webview::{
    browser_create_webview, browser_destroy_webview_if_matches, browser_find_webview,
    browser_load_url,
};
use lingxia_platform::traits::app_runtime::AppRuntime;
use lingxia_webview::{WebView, WebViewDataMode};
use lxapp::{LxApp, LxAppError};
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, OnceLock};

pub(crate) const INTERNAL_TAB_PATH_PREFIX: &str = "/tabs/";

// Internal browser tab model:
// 1) All tabs are hosted by the built-in browser lxapp (BUILTIN_BROWSER_APPID).
// 2) Callers may provide a stable tab key; the core resolves that key against an
//    explicit scope and maps it to a canonical runtime UUID tab id.
// 3) One canonical runtime tab id maps to one page path: /tabs/{tab_id}.
// 4) One canonical runtime tab id owns one managed WebView instance lifecycle.

#[derive(Clone)]
pub(crate) struct BrowserTabState {
    pub(crate) session_id: u64,
    /// Stable creation sequence of the tab entry. Listing APIs order by this
    /// value so `tabs()` reflects creation order regardless of id naming;
    /// unlike `create_token` it never changes when a WebView is recreated.
    pub(crate) created_order: u64,
    /// Monotonic token to identify the current create lifecycle of this tab.
    /// Used to ignore stale async callbacks when tab gets recreated quickly.
    pub(crate) create_token: u64,
    /// True while a WebView create for `create_token` is still in-flight.
    /// Cleared once the create resolves; used to detect dead tabs whose
    /// earlier create failed so they can be recreated instead of being
    /// stuck with a `pending_url` that is never replayed.
    pub(crate) create_in_flight: bool,
    /// URL queued for loading while WebView creation is in-flight.
    pub(crate) pending_url: Option<String>,
    /// Normalized first URL. Aside reuse is keyed to this value and navigation
    /// never rewrites it.
    pub(crate) initial_url: Option<String>,
    pub(crate) current_url: Option<String>,
    pub(crate) title: Option<String>,
    /// URL `title` was reported for. Titles are never cleared on navigation,
    /// so nav-finish must not attribute page A's title to page B.
    pub(crate) title_url: Option<String>,
    /// PNG-encoded favicon of the current page, as reported by the platform
    /// webview (`WebViewDelegate::on_favicon_changed`). `Arc`'d so shell
    /// layers can mirror it into layout snapshots without copying.
    pub(crate) favicon_png: Option<Arc<Vec<u8>>>,
    /// Session-history availability reported by the platform webview
    /// (`WebViewDelegate::on_history_changed`); drives smart back/forward
    /// affordances in shell chrome.
    pub(crate) can_go_back: bool,
    pub(crate) can_go_forward: bool,
    /// When true the tab's WebView has been destroyed to free memory
    /// (Chrome-style discard); the entry/metadata is kept and the WebView is
    /// recreated from `current_url` on reactivation.
    pub(crate) discarded: bool,
    /// Website-data lifetime preserved when a discarded WebView is recreated.
    pub(crate) data_mode: WebViewDataMode,
    /// URL-callback tabs reject every file navigation, including redirects
    /// initiated after the initial HTTP(S) document loads.
    pub(crate) url_callback: Arc<AtomicBool>,
    /// When true this tab is hosted outside product browser chrome (e.g. a
    /// docked aside or URL surface). New-window requests (`target=_blank`,
    /// `window.open`) load in the same WebView instead of spawning a new
    /// main-area tab, while automation can still discover the tab.
    pub(crate) standalone: bool,
    /// When true this tab belongs to the API-managed aside browser group.
    pub(crate) aside: bool,
    /// The lxapp that opened this tab (None for globally-scoped tabs). Used
    /// to attribute follow-up surfaces (e.g. a new-window request from a
    /// docked aside tab) to the right owner.
    pub(crate) owner_appid: Option<String>,
    /// Session that owned the tab. Keeping this separately from the browser
    /// lxapp's `session_id` lets shells retire tabs after their owner restarts.
    pub(crate) owner_session_id: Option<u64>,
}

fn tab_generation_matches(tab: &BrowserTabState, session_id: u64, create_token: u64) -> bool {
    tab.session_id == session_id && tab.create_token == create_token
}

pub(crate) fn browser_tab_generation_matches(
    tab_id: &str,
    session_id: u64,
    create_token: u64,
) -> bool {
    let Some(normalized) = normalize_runtime_tab_id(tab_id) else {
        return false;
    };
    lock_state()
        .tabs
        .get(&normalized)
        .is_some_and(|tab| tab_generation_matches(tab, session_id, create_token))
}

pub(crate) fn browser_internal_url_if_token_matches(
    tab_id: &str,
    session_id: u64,
    create_token: u64,
) -> Option<String> {
    let normalized = normalize_runtime_tab_id(tab_id)?;
    let url = {
        let state = lock_state();
        let tab = state.tabs.get(&normalized)?;
        tab_generation_matches(tab, session_id, create_token)
            .then(|| tab.pending_url.clone().or_else(|| tab.current_url.clone()))
            .flatten()?
    };
    (crate::policy::extract_url_scheme(&url).as_deref() == Some(crate::policy::LINGXIA_SCHEME))
        .then_some(url)
}

fn browser_find_webview_for_generation(
    tab_id: &str,
    tab_path: &str,
    session_id: u64,
    create_token: u64,
) -> Option<Arc<WebView>> {
    let current_generation = lock_state()
        .tabs
        .get(tab_id)
        .is_some_and(|tab| tab_generation_matches(tab, session_id, create_token));
    current_generation
        .then(|| browser_find_webview(tab_path, session_id).ok())
        .flatten()
}

pub(crate) struct BrowserState {
    // tab_id -> tab lifecycle state (single WebView lifecycle per tab_id)
    pub(crate) tabs: HashMap<String, BrowserTabState>,
    recently_closed: Vec<ClosedBrowserTab>,
    /// Complete browser-session user-agent override. WebView creation reads it
    /// before the first load, including for tabs created or restored later.
    pub(crate) user_agent_override: Option<String>,
}

static BROWSER_STATE: OnceLock<Mutex<BrowserState>> = OnceLock::new();
static BROWSER_TAB_COUNTER: AtomicU64 = AtomicU64::new(1);
static BROWSER_CREATE_TOKEN: AtomicU64 = AtomicU64::new(1);
static BROWSER_CREATED_ORDER: AtomicU64 = AtomicU64::new(1);
static BROWSER_LOAD_MUTEX: OnceLock<Mutex<()>> = OnceLock::new();
static BROWSER_ACTIVE_TAB_ID: OnceLock<Mutex<Option<String>>> = OnceLock::new();
static BROWSER_AUTOMATION_TAB_ID: OnceLock<Mutex<Option<String>>> = OnceLock::new();
static BROWSER_TABS_CHANGED_HANDLER: OnceLock<Mutex<Option<TabsChangedHandler>>> = OnceLock::new();
static BROWSER_TAB_PRESENT_HANDLER: OnceLock<Mutex<Option<TabPresentHandler>>> = OnceLock::new();
static BROWSER_NAVIGATION_FINISHED_HANDLER: OnceLock<Mutex<Option<NavigationFinishedHandler>>> =
    OnceLock::new();
static BROWSER_TITLE_CHANGED_HANDLER: OnceLock<Mutex<Option<TitleChangedHandler>>> =
    OnceLock::new();

/// Process-wide observer invoked when the browser tab set/metadata changes.
type TabsChangedHandler = Arc<dyn Fn() + Send + Sync>;
/// Process-wide observer invoked when a caller wants a tab brought onscreen.
type TabPresentHandler = Arc<dyn Fn(&str) + Send + Sync>;
type NavigationFinishedHandler = Arc<dyn Fn(&str, &str) + Send + Sync>;
type TitleChangedHandler = Arc<dyn Fn(&str, &str) + Send + Sync>;

pub(crate) fn set_tabs_changed_handler(handler: TabsChangedHandler) {
    let slot = BROWSER_TABS_CHANGED_HANDLER.get_or_init(|| Mutex::new(None));
    if let Ok(mut slot) = slot.lock() {
        *slot = Some(handler);
    }
}

pub(crate) fn set_tab_present_handler(handler: TabPresentHandler) {
    let slot = BROWSER_TAB_PRESENT_HANDLER.get_or_init(|| Mutex::new(None));
    if let Ok(mut slot) = slot.lock() {
        *slot = Some(handler);
    }
}

pub(crate) fn set_navigation_finished_handler(handler: NavigationFinishedHandler) {
    let slot = BROWSER_NAVIGATION_FINISHED_HANDLER.get_or_init(|| Mutex::new(None));
    if let Ok(mut slot) = slot.lock() {
        *slot = Some(handler);
    }
}

pub(crate) fn set_title_changed_handler(handler: TitleChangedHandler) {
    let slot = BROWSER_TITLE_CHANGED_HANDLER.get_or_init(|| Mutex::new(None));
    if let Ok(mut slot) = slot.lock() {
        *slot = Some(handler);
    }
}

fn records_browser_history(tab: &BrowserTabState) -> bool {
    tab.data_mode != WebViewDataMode::Ephemeral
        && !tab.url_callback.load(Ordering::Acquire)
        && !tab.standalone
}

fn validate_reused_tab_policy(
    tab: &BrowserTabState,
    data_mode: WebViewDataMode,
    standalone: bool,
) -> Result<(), LxAppError> {
    if tab.data_mode != data_mode || tab.standalone != standalone {
        return Err(LxAppError::InvalidParameter(
            "an existing browser tab cannot change data mode or standalone status".to_string(),
        ));
    }
    Ok(())
}

pub(crate) fn notify_navigation_finished(
    tab_id: &str,
    session_id: u64,
    create_token: u64,
    url: &str,
) {
    let handler = BROWSER_NAVIGATION_FINISHED_HANDLER
        .get()
        .and_then(|slot| slot.lock().ok())
        .and_then(|slot| slot.clone());
    if let Some(handler) = handler {
        // Pass the stored title only when it belongs to the finishing URL;
        // otherwise it is a stale title from the previous page.
        let title = {
            let state = lock_state();
            normalize_runtime_tab_id(tab_id)
                .and_then(|normalized| state.tabs.get(&normalized))
                .filter(|tab| tab.session_id == session_id && tab.create_token == create_token)
                .filter(|tab| records_browser_history(tab))
                .map(|tab| {
                    (tab.title_url.as_deref() == Some(url))
                        .then(|| tab.title.clone())
                        .flatten()
                        .unwrap_or_default()
                })
        };
        if let Some(title) = title {
            handler(url, &title);
        }
    }
}

fn notify_title_changed(url: &str, title: &str) {
    let handler = BROWSER_TITLE_CHANGED_HANDLER
        .get()
        .and_then(|slot| slot.lock().ok())
        .and_then(|slot| slot.clone());
    if let Some(handler) = handler {
        handler(url, title);
    }
}

/// Invokes the registered tabs-changed handler (if any). Must never be
/// called while a browser state lock is held: handlers typically read the
/// tab list back synchronously.
pub(crate) fn notify_tabs_changed() {
    let handler = BROWSER_TABS_CHANGED_HANDLER
        .get()
        .and_then(|slot| slot.lock().ok())
        .and_then(|slot| slot.clone());
    if let Some(handler) = handler {
        handler();
    }
}

fn notify_tab_present_requested(tab_id: &str) {
    let handler = BROWSER_TAB_PRESENT_HANDLER
        .get()
        .and_then(|slot| slot.lock().ok())
        .and_then(|slot| slot.clone());
    if let Some(handler) = handler {
        handler(tab_id);
    }
}

pub(crate) fn lock_state() -> MutexGuard<'static, BrowserState> {
    BROWSER_STATE
        .get_or_init(|| {
            Mutex::new(BrowserState {
                tabs: HashMap::new(),
                recently_closed: Vec::new(),
                user_agent_override: None,
            })
        })
        .lock()
        .unwrap_or_else(|e| {
            lxapp::warn!("[InternalBrowser] recovered poisoned browser state mutex");
            e.into_inner()
        })
}

fn lock_active_tab() -> MutexGuard<'static, Option<String>> {
    BROWSER_ACTIVE_TAB_ID
        .get_or_init(|| Mutex::new(None))
        .lock()
        .unwrap_or_else(|e| e.into_inner())
}

fn lock_automation_tab() -> MutexGuard<'static, Option<String>> {
    BROWSER_AUTOMATION_TAB_ID
        .get_or_init(|| Mutex::new(None))
        .lock()
        .unwrap_or_else(|e| e.into_inner())
}

/// Sets the active tab; returns whether the active tab actually changed.
fn set_active_browser_tab(tab_id: &str) -> bool {
    if is_standalone_tab(tab_id) {
        return false;
    }
    let mut active = lock_active_tab();
    if active.as_deref() == Some(tab_id) {
        return false;
    }
    *active = Some(tab_id.to_string());
    true
}

#[derive(Clone, Copy)]
pub(crate) enum BrowserTabScope<'a> {
    Global,
    OwnerSession {
        owner_appid: &'a str,
        owner_session_id: u64,
    },
}

fn generate_tab_id() -> String {
    loop {
        let candidate = format!(
            "tab-{}",
            BROWSER_TAB_COUNTER.fetch_add(1, Ordering::Relaxed)
        );
        if !lock_state().tabs.contains_key(&candidate) {
            return candidate;
        }
    }
}

fn validate_requested_tab_key(input: &str) -> Result<String, LxAppError> {
    let trimmed = input.trim();
    if trimmed.is_empty() {
        return Err(LxAppError::InvalidParameter(
            "tab_id is required".to_string(),
        ));
    }
    if !trimmed
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
    {
        return Err(LxAppError::InvalidParameter(
            "tab_id must contain only ASCII letters, digits, '-' or '_'".to_string(),
        ));
    }
    Ok(trimmed.to_ascii_lowercase())
}

pub(crate) fn normalize_runtime_tab_id(input: &str) -> Option<String> {
    validate_requested_tab_key(input).ok()
}

fn resolve_tab_scope_seed(scope: BrowserTabScope<'_>, stable_tab_key: &str) -> String {
    match scope {
        BrowserTabScope::Global => format!("global:{stable_tab_key}"),
        BrowserTabScope::OwnerSession {
            owner_appid,
            owner_session_id,
        } => format!("owner:{owner_appid}:{owner_session_id}:{stable_tab_key}"),
    }
}

fn deterministic_tab_suffix(seed: &str) -> String {
    const FNV_OFFSET_A: u64 = 0xcbf29ce484222325;
    const FNV_PRIME: u64 = 0x100000001b3;

    fn fnv1a64(bytes: &[u8], offset: u64, prime: u64) -> u64 {
        let mut hash = offset;
        for byte in bytes {
            hash ^= u64::from(*byte);
            hash = hash.wrapping_mul(prime);
        }
        hash
    }

    format!(
        "{:08x}",
        fnv1a64(seed.as_bytes(), FNV_OFFSET_A, FNV_PRIME) as u32
    )
}

fn resolve_browser_tab_id(
    requested_tab_key: Option<&str>,
    scope: BrowserTabScope<'_>,
) -> Result<String, LxAppError> {
    match requested_tab_key {
        Some(tab_key) => {
            let stable_tab_key = validate_requested_tab_key(tab_key)?;
            match scope {
                BrowserTabScope::Global => Ok(stable_tab_key),
                BrowserTabScope::OwnerSession { .. } => {
                    let seed = resolve_tab_scope_seed(scope, &stable_tab_key);
                    Ok(format!(
                        "{}-{}",
                        stable_tab_key,
                        deterministic_tab_suffix(&seed)
                    ))
                }
            }
        }
        None => Ok(generate_tab_id()),
    }
}

fn next_browser_create_token() -> u64 {
    BROWSER_CREATE_TOKEN.fetch_add(1, Ordering::Relaxed)
}

fn next_browser_created_order() -> u64 {
    BROWSER_CREATED_ORDER.fetch_add(1, Ordering::Relaxed)
}

// ---------------------------------------------------------------------------
// Owner resolution (used by FFI bridge layer)
// ---------------------------------------------------------------------------

fn resolve_owner_lxapp(owner_appid: &str, owner_session_id: u64) -> Result<Arc<LxApp>, LxAppError> {
    let owner_appid = owner_appid.trim();
    if owner_appid.is_empty() || owner_session_id == 0 {
        return Err(LxAppError::InvalidParameter(
            "owner_appid and owner_session_id are required".to_string(),
        ));
    }

    let owner = lxapp::try_get(owner_appid).ok_or_else(|| {
        LxAppError::ResourceNotFound(format!(
            "owner lxapp not found for browser tab operation: {}",
            owner_appid
        ))
    })?;

    if owner.session_id() != owner_session_id {
        return Err(LxAppError::InvalidParameter(format!(
            "owner session mismatch for {}: expected {}, got {}",
            owner_appid,
            owner.session_id(),
            owner_session_id
        )));
    }

    Ok(owner)
}

pub(crate) fn register_builtin_browser_host() {
    // Synthetic host: just owns tab session_id + page lifecycle. browser-shell
    // upgrades this to a real asset bundle later (see lingxia-browser-shell).
    lxapp::register_synthetic_lxapp(BUILTIN_BROWSER_APPID);
}

/// Ensure browser lxapp instance exists in manager.
pub(crate) fn ensure_browser_lxapp() -> Result<Arc<LxApp>, LxAppError> {
    let _load_guard = BROWSER_LOAD_MUTEX
        .get_or_init(|| Mutex::new(()))
        .lock()
        .unwrap_or_else(|e| e.into_inner());

    if let Some(browser) = lxapp::try_get(BUILTIN_BROWSER_APPID) {
        return Ok(browser);
    }

    lxapp::ensure_builtin_lxapp(BUILTIN_BROWSER_APPID)
}

pub(crate) fn browser_tab_path_for_runtime_id(tab_id: &str) -> String {
    format!("{INTERNAL_TAB_PATH_PREFIX}{tab_id}")
}

pub(crate) fn browser_tab_path_for_id(tab_id: &str) -> String {
    normalize_runtime_tab_id(tab_id)
        .map(|tab_id| browser_tab_path_for_runtime_id(&tab_id))
        .unwrap_or_else(|| INTERNAL_TAB_PATH_PREFIX.to_string())
}

pub(crate) fn normalize_optional_string(value: Option<&str>) -> Option<String> {
    let text = value.unwrap_or_default().trim();
    if text.is_empty() {
        None
    } else {
        Some(text.to_string())
    }
}

fn build_tab_info(tab_id: &str, state: &BrowserTabState) -> BrowserTabInfo {
    BrowserTabInfo {
        tab_id: tab_id.to_string(),
        path: browser_tab_path_for_runtime_id(tab_id),
        session_id: state.session_id,
        current_url: state.current_url.clone(),
        title: state.title.clone(),
        can_go_back: state.can_go_back,
        can_go_forward: state.can_go_forward,
    }
}

pub fn browser_tab_info(tab_id: &str) -> Option<BrowserTabInfo> {
    let normalized = normalize_runtime_tab_id(tab_id)?;
    let state = lock_state();
    state
        .tabs
        .get(&normalized)
        .map(|tab| build_tab_info(&normalized, tab))
}

/// Tabs in creation order — the listing contract for automation and shells;
/// id ordering is an accident of stable-key naming and must not leak out.
pub fn browser_tabs() -> Vec<BrowserTabInfo> {
    let state = lock_state();
    let mut tabs: Vec<(u64, BrowserTabInfo)> = state
        .tabs
        .iter()
        .map(|(tab_id, tab)| (tab.created_order, build_tab_info(tab_id, tab)))
        .collect();
    tabs.sort_by_key(|(created_order, _)| *created_order);
    tabs.into_iter().map(|(_, tab)| tab).collect()
}

pub fn browser_current_tab() -> Option<BrowserTabInfo> {
    let active_tab_id = lock_active_tab().clone();
    let state = lock_state();
    if let Some(tab_id) = active_tab_id
        && let Some(tab) = state.tabs.get(&tab_id)
        && !tab.standalone
    {
        return Some(build_tab_info(&tab_id, tab));
    }
    // Fall back to the earliest-created product tab (the stable "first" tab).
    state
        .tabs
        .iter()
        .filter(|(_, tab)| !tab.standalone)
        .min_by_key(|(_, tab)| tab.created_order)
        .map(|(tab_id, tab)| build_tab_info(tab_id, tab))
}

pub fn browser_automation_current_tab() -> Option<BrowserTabInfo> {
    if let Some(tab_id) = lock_automation_tab().clone()
        && let Some(info) = browser_tab_info(&tab_id)
    {
        return Some(info);
    }
    browser_current_tab().or_else(|| browser_tabs().into_iter().next())
}

pub fn browser_activate_tab(tab_id: &str) -> Result<BrowserTabInfo, BrowserAutomationError> {
    let normalized_tab_id = normalize_runtime_tab_id(tab_id)
        .ok_or_else(|| BrowserAutomationError::TabNotFound(tab_id.to_string()))?;
    let (info, standalone) = {
        let state = lock_state();
        let tab = state
            .tabs
            .get(&normalized_tab_id)
            .ok_or_else(|| BrowserAutomationError::TabNotFound(tab_id.to_string()))?;
        (build_tab_info(&normalized_tab_id, tab), tab.standalone)
    };
    *lock_automation_tab() = Some(normalized_tab_id.clone());
    // Automation may select a standalone tab, but that must not change product
    // browser chrome, LRU, or lifecycle ownership.
    if !standalone && set_active_browser_tab(&normalized_tab_id) {
        notify_tabs_changed();
    }
    Ok(info)
}

pub fn browser_present_tab(tab_id: &str) -> Result<BrowserTabInfo, BrowserAutomationError> {
    let info = browser_activate_tab(tab_id)?;
    notify_tab_present_requested(&info.tab_id);
    Ok(info)
}

fn browser_update_tab_info_inner(
    tab_id: &str,
    expected_generation: Option<(u64, u64)>,
    current_url: Option<&str>,
    title: Option<&str>,
) -> bool {
    let Some(normalized) = normalize_runtime_tab_id(tab_id) else {
        return false;
    };
    let (changed, changed_title) = {
        let mut state = lock_state();
        let Some(tab) = state.tabs.get_mut(&normalized) else {
            return false;
        };
        if expected_generation.is_some_and(|(session_id, create_token)| {
            tab.session_id != session_id || tab.create_token != create_token
        }) {
            return false;
        }
        let mut changed = false;
        let mut changed_title = None;
        if current_url.is_some() {
            let value = normalize_optional_string(current_url);
            if tab.current_url != value {
                tab.current_url = value;
                changed = true;
            }
        }
        if let Some(value) = normalize_optional_string(title) {
            // Only non-empty titles update the record: an empty title means "not
            // yet known" (e.g. a webview's initial KVO fire before the document
            // title is parsed) and must never clobber a title already reported.
            // Even an unchanged title re-binds title_url: the report is for the
            // page currently loaded in the tab.
            tab.title_url = tab.current_url.clone();
            if tab.title.as_deref() != Some(value.as_str()) {
                tab.title = Some(value.clone());
                if records_browser_history(tab)
                    && let Some(url) = tab.current_url.clone()
                {
                    changed_title = Some((url, value));
                }
                changed = true;
            }
        }
        (changed, changed_title)
    };
    if changed {
        notify_tabs_changed();
    }
    if let Some((url, title)) = changed_title {
        notify_title_changed(&url, &title);
    }
    true
}

pub(crate) fn browser_update_tab_info(
    tab_id: &str,
    current_url: Option<&str>,
    title: Option<&str>,
) -> bool {
    browser_update_tab_info_inner(tab_id, None, current_url, title)
}

pub(crate) fn browser_update_tab_info_if_token_matches(
    tab_id: &str,
    session_id: u64,
    create_token: u64,
    current_url: Option<&str>,
    title: Option<&str>,
) -> bool {
    browser_update_tab_info_inner(tab_id, Some((session_id, create_token)), current_url, title)
}

/// Stores the webview-reported session-history availability for `tab_id`
/// and fires the tabs-changed observer when it changed. Returns `false`
/// when the tab does not exist.
pub(crate) fn browser_update_tab_nav_state(
    tab_id: &str,
    can_go_back: bool,
    can_go_forward: bool,
) -> bool {
    let Some(normalized) = normalize_runtime_tab_id(tab_id) else {
        return false;
    };
    let changed = {
        let mut state = lock_state();
        let Some(tab) = state.tabs.get_mut(&normalized) else {
            return false;
        };
        let changed = tab.can_go_back != can_go_back || tab.can_go_forward != can_go_forward;
        tab.can_go_back = can_go_back;
        tab.can_go_forward = can_go_forward;
        changed
    };
    if changed {
        notify_tabs_changed();
    }
    true
}

/// Stores the PNG favicon reported by the platform webview for `tab_id`
/// (empty bytes clear it) and fires the tabs-changed observer when it
/// actually changed. Returns `false` when the tab does not exist.
pub(crate) fn browser_update_tab_favicon(tab_id: &str, png_bytes: Vec<u8>) -> bool {
    let Some(normalized) = normalize_runtime_tab_id(tab_id) else {
        return false;
    };
    let value = if png_bytes.is_empty() {
        None
    } else {
        Some(Arc::new(png_bytes))
    };
    let cache_bytes = value.clone();
    let (changed, url) = {
        let mut state = lock_state();
        let Some(tab) = state.tabs.get_mut(&normalized) else {
            return false;
        };
        let same = match (&tab.favicon_png, &value) {
            (None, None) => true,
            (Some(old), Some(new)) => old.as_ref() == new.as_ref(),
            _ => false,
        };
        if !same {
            tab.favicon_png = value;
        }
        (
            !same,
            (tab.data_mode != WebViewDataMode::Ephemeral)
                .then(|| tab.current_url.clone())
                .flatten(),
        )
    };
    if changed {
        if let (Some(url), Some(bytes), Some(runtime)) = (url, cache_bytes, lxapp::get_platform()) {
            lingxia_service::favicon::store_for_url(&runtime.app_cache_dir(), &url, &bytes);
        }
        notify_tabs_changed();
    }
    true
}

/// PNG favicon currently stored for `tab_id`, if any.
pub(crate) fn browser_tab_favicon(tab_id: &str) -> Option<Arc<Vec<u8>>> {
    let normalized = normalize_runtime_tab_id(tab_id)?;
    lock_state()
        .tabs
        .get(&normalized)
        .and_then(|tab| tab.favicon_png.clone())
}

// ---------------------------------------------------------------------------
// Create-token machinery (shared with the WebView creation flow)
// ---------------------------------------------------------------------------

#[derive(Debug)]
pub(crate) enum TabCreateState {
    Active {
        pending_url: Option<String>,
        user_agent_override: Option<String>,
    },
    Missing,
    Stale,
}

pub(crate) fn browser_tab_create_state(
    tab_id: &str,
    session_id: u64,
    create_token: u64,
) -> TabCreateState {
    let mut state = lock_state();
    let user_agent_override = state.user_agent_override.clone();
    match state.tabs.get_mut(tab_id) {
        Some(tab) if tab.session_id == session_id && tab.create_token == create_token => {
            // This create cycle now owns a live WebView; clear the in-flight
            // marker so a missing WebView later means the tab must be recreated.
            tab.create_in_flight = false;
            TabCreateState::Active {
                pending_url: tab.pending_url.clone(),
                user_agent_override,
            }
        }
        Some(_) => TabCreateState::Stale,
        None => TabCreateState::Missing,
    }
}

pub(crate) fn browser_remove_tab_if_token_matches(
    tab_id: &str,
    session_id: u64,
    create_token: u64,
) {
    let removed = {
        let mut state = lock_state();
        let should_remove = state
            .tabs
            .get(tab_id)
            .map(|tab| tab.session_id == session_id && tab.create_token == create_token)
            .unwrap_or(false);
        if should_remove {
            state.tabs.remove(tab_id);
        }
        should_remove
    };
    if removed {
        notify_tabs_changed();
    }
}

pub(crate) fn browser_clear_pending_if_token_matches(
    tab_id: &str,
    session_id: u64,
    create_token: u64,
) {
    let mut state = lock_state();
    if let Some(tab) = state.tabs.get_mut(tab_id)
        && tab.session_id == session_id
        && tab.create_token == create_token
    {
        tab.pending_url = None;
    }
}

pub(crate) fn browser_commit_navigation_if_token_matches(
    tab_id: &str,
    session_id: u64,
    create_token: u64,
    current_url: Option<&str>,
) {
    let committed = {
        let mut state = lock_state();
        if let Some(tab) = state.tabs.get_mut(tab_id)
            && tab.session_id == session_id
            && tab.create_token == create_token
        {
            tab.pending_url = None;
            tab.current_url = normalize_optional_string(current_url);
            true
        } else {
            false
        }
    };
    if committed {
        notify_tabs_changed();
    }
}

fn browser_clear_pending_url(tab_id: &str) {
    let mut state = lock_state();
    if let Some(tab) = state.tabs.get_mut(tab_id) {
        tab.pending_url = None;
    }
}

// ---------------------------------------------------------------------------
// Open / close
// ---------------------------------------------------------------------------

fn open_internal_browser_tab_with_scope(
    url: &str,
    requested_tab_key: Option<&str>,
    scope: BrowserTabScope<'_>,
    standalone: bool,
    aside: bool,
    data_mode: WebViewDataMode,
    url_callback: bool,
) -> Result<String, LxAppError> {
    let browser = ensure_browser_lxapp()?;
    let browser_session_id = browser.session_id();

    let raw_url = url.trim();

    // `lingxia://newtab` (and bare `lingxia://`) → startup page (no URL).
    // Other `lingxia://` pages stay as-is and are served by the lingxia:// scheme handler.
    let effective_url: String = match is_lingxia_startup_url(raw_url) {
        Some(true) => String::new(),
        _ => raw_url.to_string(),
    };
    let target_url = effective_url.as_str();

    let normalized_target_url = normalize_browser_target_url(target_url);
    let has_target_url = !normalized_target_url.is_empty();
    let (owner_appid, owner_session_id) = match scope {
        BrowserTabScope::Global => (None, None),
        BrowserTabScope::OwnerSession {
            owner_appid,
            owner_session_id,
        } => (Some(owner_appid.to_string()), Some(owner_session_id)),
    };
    let tab_id = resolve_browser_tab_id(requested_tab_key, scope)?;
    let path = browser_tab_path_for_runtime_id(&tab_id);
    let session_id = browser_session_id;
    let mut create_token: Option<u64> = None;
    let mut is_new_tab = false;

    let url_callback_policy = {
        let mut state = lock_state();
        if let Some(existing) = state.tabs.get_mut(&tab_id) {
            validate_reused_tab_policy(existing, data_mode, standalone)?;
            if existing.session_id != session_id {
                // The browser lxapp restarted. Its old WebView generation
                // cannot satisfy a navigation for the new native session.
                existing.create_in_flight = false;
            }
            existing.session_id = session_id;
            existing.url_callback.store(url_callback, Ordering::Release);
            if has_target_url {
                existing.pending_url = Some(normalized_target_url.clone());
            }
            existing.url_callback.clone()
        } else {
            is_new_tab = true;
            let token = next_browser_create_token();
            create_token = Some(token);
            let url_callback_policy = Arc::new(AtomicBool::new(url_callback));
            state.tabs.insert(
                tab_id.clone(),
                BrowserTabState {
                    session_id,
                    created_order: next_browser_created_order(),
                    create_token: token,
                    create_in_flight: true,
                    pending_url: if has_target_url {
                        Some(normalized_target_url.clone())
                    } else {
                        None
                    },
                    initial_url: has_target_url.then(|| {
                        lxapp::lingxia_surface::normalize_initial_url(&normalized_target_url)
                    }),
                    current_url: None,
                    title: None,
                    title_url: None,
                    favicon_png: None,
                    can_go_back: false,
                    can_go_forward: false,
                    discarded: false,
                    data_mode,
                    url_callback: url_callback_policy.clone(),
                    standalone,
                    aside,
                    owner_appid,
                    owner_session_id,
                },
            );
            url_callback_policy
        }
    };

    if is_new_tab {
        let token = create_token.expect("create_token must exist for new tab");
        if let Err(e) = browser_create_webview(
            &path,
            session_id,
            &tab_id,
            token,
            data_mode,
            url_callback_policy.clone(),
            standalone,
        ) {
            lock_state().tabs.remove(&tab_id);
            return Err(e);
        }
        // A standalone browser is hosted outside product browser chrome, so it
        // must not drive the main coordinator's active-tab and memory policy.
        if !standalone {
            let _ = set_active_browser_tab(&tab_id);
        }
        notify_tabs_changed();
        return Ok(tab_id);
    }

    // Existing tab — load target URL if provided.
    if has_target_url {
        let create_token = lock_state()
            .tabs
            .get(&tab_id)
            .map(|tab| tab.create_token)
            .ok_or_else(|| {
                LxAppError::ResourceNotFound(format!("browser tab not found: {tab_id}"))
            })?;
        match browser_load_url(&path, session_id, create_token, &normalized_target_url) {
            Ok(()) => {
                if let Some(s) = lock_state().tabs.get_mut(&tab_id) {
                    s.pending_url = None;
                    s.current_url = Some(normalized_target_url.clone());
                }
            }
            Err(LxAppError::ResourceNotFound(_)) => {
                // WebView is missing. If a create is still in-flight, keep
                // pending_url for replay once the WebView becomes ready.
                // Otherwise the earlier create failed (or the WebView is gone),
                // so start a fresh create cycle instead of leaving the tab dead.
                let retry_token = {
                    let mut state = lock_state();
                    match state.tabs.get_mut(&tab_id) {
                        Some(tab) if !tab.create_in_flight => {
                            let token = next_browser_create_token();
                            tab.create_token = token;
                            tab.create_in_flight = true;
                            tab.discarded = false;
                            Some(token)
                        }
                        _ => None,
                    }
                };
                if let Some(token) = retry_token
                    && let Err(e) = browser_create_webview(
                        &path,
                        session_id,
                        &tab_id,
                        token,
                        data_mode,
                        url_callback_policy.clone(),
                        standalone,
                    )
                {
                    lock_state().tabs.remove(&tab_id);
                    return Err(e);
                }
            }
            Err(e) => {
                browser_clear_pending_url(&tab_id);
                return Err(e);
            }
        }
    }

    if !standalone {
        let _ = set_active_browser_tab(&tab_id);
    }
    notify_tabs_changed();
    Ok(tab_id)
}

pub(crate) fn open_internal_browser_tab(
    url: &str,
    tab_id: Option<&str>,
) -> Result<String, LxAppError> {
    open_internal_browser_tab_with_scope(
        url,
        tab_id,
        BrowserTabScope::Global,
        false,
        false,
        WebViewDataMode::ProfileDefault,
        false,
    )
}

/// Start a new trusted top-level load for a registered browser control page.
/// Stable-tab reuse never degrades to focus-only: a live tab reloads through
/// `browser_load_internal_document`, while a missing/discarded generation is
/// recreated with this URL pending.
pub(crate) fn navigate_trusted_control_page(
    url: &str,
) -> Result<TrustedControlPageNavigation, LxAppError> {
    let route = registered_control_page_route(url).ok_or_else(|| {
        LxAppError::InvalidParameter(format!(
            "trusted browser control route is not registered: {url}"
        ))
    })?;
    let tab_id = open_internal_browser_tab_with_scope(
        url,
        Some(&route),
        BrowserTabScope::Global,
        false,
        false,
        WebViewDataMode::ProfileDefault,
        false,
    )?;
    let identity = browser_tab_info(&tab_id).ok_or_else(|| {
        LxAppError::ResourceNotFound(format!("trusted browser control tab disappeared: {tab_id}"))
    })?;
    Ok(TrustedControlPageNavigation {
        tab_id,
        browser_session_id: identity.session_id,
    })
}

pub(crate) fn open_internal_browser_tab_for_owner(
    owner_appid: &str,
    owner_session_id: u64,
    url: &str,
    tab_id: Option<&str>,
    standalone: bool,
    aside: bool,
    data_mode: WebViewDataMode,
    url_callback: bool,
) -> Result<String, LxAppError> {
    let _owner = resolve_owner_lxapp(owner_appid, owner_session_id)?;
    if aside && tab_id.is_none() {
        let normalized_target = normalize_browser_target_url(url);
        let initial_url = lxapp::lingxia_surface::normalize_initial_url(&normalized_target);
        let reusable = {
            let state = lock_state();
            state.tabs.iter().find_map(|(tab_id, tab)| {
                (tab.aside
                    && tab.owner_appid.as_deref() == Some(owner_appid)
                    && tab.owner_session_id == Some(owner_session_id)
                    && tab.initial_url.as_deref() == Some(initial_url.as_str()))
                .then(|| tab_id.clone())
            })
        };
        if let Some(tab_id) = reusable {
            let _ = set_active_browser_tab(&tab_id);
            notify_tabs_changed();
            return Ok(tab_id);
        }
    }
    open_internal_browser_tab_with_scope(
        url,
        tab_id,
        BrowserTabScope::OwnerSession {
            owner_appid,
            owner_session_id,
        },
        standalone,
        aside,
        data_mode,
        url_callback,
    )
}

/// The lxapp that opened `tab_id`, when it was owner-scoped.
pub(crate) fn tab_owner_appid(tab_id: &str) -> Option<String> {
    let normalized = normalize_runtime_tab_id(tab_id)?;
    lock_state()
        .tabs
        .get(&normalized)
        .and_then(|tab| tab.owner_appid.clone())
}

/// Whether `tab_id` belongs to the API-managed aside browser group.
pub(crate) fn is_aside_tab(tab_id: &str) -> bool {
    let Some(normalized) = normalize_runtime_tab_id(tab_id) else {
        return false;
    };
    lock_state()
        .tabs
        .get(&normalized)
        .map(|tab| tab.aside)
        .unwrap_or(false)
}

/// Whether `tab_id` is hosted outside product browser chrome. New-window
/// requests from a URL-callback (login) tab go to the OS browser; other
/// standalone tabs spawn a sibling aside rather than a main-area tab.
pub(crate) fn is_standalone_tab(tab_id: &str) -> bool {
    let Some(normalized) = normalize_runtime_tab_id(tab_id) else {
        return false;
    };
    lock_state()
        .tabs
        .get(&normalized)
        .map(|tab| tab.standalone)
        .unwrap_or(false)
}

pub fn browser_tab_exists(tab_id: &str) -> bool {
    let Some(normalized) = normalize_runtime_tab_id(tab_id) else {
        return false;
    };
    lock_state().tabs.contains_key(&normalized)
}

pub(crate) fn close_browser_tab(tab_id: &str) -> Result<(), LxAppError> {
    close_browser_tab_inner(tab_id, true)
}

fn close_browser_tab_inner(tab_id: &str, remember: bool) -> Result<(), LxAppError> {
    let normalized = normalize_runtime_tab_id(tab_id).ok_or_else(|| {
        LxAppError::InvalidParameter("tab_id must be a valid runtime browser tab id".to_string())
    })?;

    let tab_path = browser_tab_path_for_runtime_id(&normalized);
    let generation = {
        let state = lock_state();
        state
            .tabs
            .get(&normalized)
            .map(|tab| (tab.session_id, tab.create_token))
    };
    // Resolve the concrete instance while this close still names the current
    // tab generation. A delayed close must never tear down a successor that
    // reused the same logical tab path.
    let closing_webview = generation.and_then(|(session_id, create_token)| {
        browser_find_webview_for_generation(&normalized, &tab_path, session_id, create_token)
    });
    let removed = {
        let mut state = lock_state();
        let removed = state.tabs.remove(&normalized);
        if remember
            && let Some(tab) = removed.as_ref()
            && let Some(entry) = ClosedBrowserTab::from_tab(tab)
        {
            state.recently_closed.push(entry);
            if state.recently_closed.len() > 25 {
                state.recently_closed.remove(0);
            }
        }
        removed
    };
    let removed_any = removed.is_some();
    if let Some(tab) = removed {
        // Detach only when this tab currently backs the startup page bridge.
        // Closing a background tab must not break the active tab bridge.
        if let Ok(browser) = ensure_browser_lxapp() {
            let startup_path = browser.initial_route();
            if let Some(page) = browser.get_page(&startup_path) {
                let startup_webview = page.webview();
                let closing_tab_webview = closing_webview.clone();
                if let (Some(startup_webview), Some(closing_tab_webview)) =
                    (startup_webview, closing_tab_webview)
                    && Arc::ptr_eq(&startup_webview, &closing_tab_webview)
                {
                    page.detach_webview();
                }
            }
            if let Some(page) = browser.get_page(&tab_path) {
                page.detach_webview();
            }
            // remove_pages takes instance ids; resolve the tab page's live instance.
            if let Some(page) = browser.get_page(&tab_path) {
                browser.remove_pages(std::slice::from_ref(&page.instance_id_string()));
            }
        }
        if let Some(webview) = closing_webview {
            browser_destroy_webview_if_matches(&tab_path, tab.session_id, &webview);
        }
    }
    let active_matches_closed = lock_active_tab().as_deref() == Some(normalized.as_str());
    if active_matches_closed {
        let next = browser_current_tab().map(|tab| tab.tab_id);
        *lock_active_tab() = next;
    }
    if lock_automation_tab().as_deref() == Some(normalized.as_str()) {
        lock_automation_tab().take();
    }
    if removed_any || active_matches_closed {
        notify_tabs_changed();
    }
    Ok(())
}

/// Remove tabs owned by earlier incarnations of an lxapp. Pinned shortcuts
/// remain in the bookmark store and can reopen a fresh tab in the new session.
pub(crate) fn prune_stale_owner_tabs(owner_appid: &str, current_session_id: u64) -> usize {
    let stale_ids = {
        let state = lock_state();
        state
            .tabs
            .iter()
            .filter(|(_, tab)| {
                tab.owner_appid.as_deref() == Some(owner_appid)
                    && tab.owner_session_id != Some(current_session_id)
            })
            .map(|(tab_id, _)| tab_id.clone())
            .collect::<Vec<_>>()
    };
    for tab_id in &stale_ids {
        let _ = close_browser_tab_inner(tab_id, false);
    }
    lock_state().recently_closed.retain(|entry| {
        entry.owner_appid.as_deref() != Some(owner_appid)
            || entry.owner_session_id == Some(current_session_id)
    });
    stale_ids.len()
}

/// Chrome-style tab discard: destroy the tab's WebView to free its native
/// memory while keeping the tab entry (`current_url` / `title`) so the sidebar
/// still shows it. Reactivation recreates the WebView and reloads the URL.
/// Refuses to discard the active tab.
pub(crate) fn discard_browser_tab(tab_id: &str) -> Result<(), LxAppError> {
    let normalized = normalize_runtime_tab_id(tab_id).ok_or_else(|| {
        LxAppError::InvalidParameter("tab_id must be a valid runtime browser tab id".to_string())
    })?;
    if lock_active_tab().as_deref() == Some(normalized.as_str()) {
        return Err(LxAppError::InvalidParameter(
            "cannot discard the active browser tab".to_string(),
        ));
    }
    let tab = match lock_state().tabs.get(&normalized).cloned() {
        // Unknown or already discarded — nothing to free.
        Some(tab) if !tab.discarded => tab,
        _ => return Ok(()),
    };
    let tab_path = browser_tab_path_for_runtime_id(&normalized);

    let webview = browser_find_webview_for_generation(
        &normalized,
        &tab_path,
        tab.session_id,
        tab.create_token,
    );

    // Bump the create token BEFORE destroying the WebView. If the WebView is
    // still being created, its in-flight `browser_on_webview_ready` holds the
    // old token; once `wait_ready()` errors after the destroy below, its
    // `browser_remove_tab_if_token_matches(old)` no longer matches and the
    // kept entry survives (otherwise reactivate would hit ResourceNotFound).
    if let Some(state) = lock_state().tabs.get_mut(&normalized) {
        state.create_token = next_browser_create_token();
    }

    // Detach from the shared startup bridge if this tab backs it, and drop any
    // per-tab internal page — same dance as close_browser_tab.
    if let Ok(browser) = ensure_browser_lxapp() {
        let startup_path = browser.initial_route();
        if let Some(page) = browser.get_page(&startup_path) {
            let startup_webview = page.webview();
            let tab_webview = webview.clone();
            if let (Some(startup_webview), Some(tab_webview)) = (startup_webview, tab_webview)
                && Arc::ptr_eq(&startup_webview, &tab_webview)
            {
                page.detach_webview();
            }
        }
        if let Some(page) = browser.get_page(&tab_path) {
            page.detach_webview();
        }
        // remove_pages takes instance ids; resolve the tab page's live instance.
        if let Some(page) = browser.get_page(&tab_path) {
            browser.remove_pages(std::slice::from_ref(&page.instance_id_string()));
        }
    }
    if let Some(webview) = webview {
        browser_destroy_webview_if_matches(&tab_path, tab.session_id, &webview);
    }

    // Keep the entry; remember where to reload from on reactivation. Preserve
    // an in-flight `pending_url` (WebView not yet loaded / mid-navigation);
    // only fall back to `current_url` when there is no pending target.
    if let Some(state) = lock_state().tabs.get_mut(&normalized) {
        state.discarded = true;
        state.create_in_flight = false;
        if state.pending_url.is_none() {
            state.pending_url = state.current_url.clone();
        }
    }
    Ok(())
}

/// Mark a tab as the active one without touching its WebView. Lets the SDK keep
/// the Rust-side active tab in sync when switching to an already-live tab, so
/// the discard policy doesn't mistake a backgrounded tab for the active one.
pub(crate) fn mark_browser_tab_active(tab_id: &str) {
    let Some(normalized) = normalize_runtime_tab_id(tab_id) else {
        return;
    };
    let exists = lock_state().tabs.contains_key(&normalized);
    if exists && set_active_browser_tab(&normalized) {
        notify_tabs_changed();
    }
}

/// Clear browser active state when the platform leaves browser UI entirely.
/// With no active browser tab, every tab is eligible for background memory
/// reclamation according to the host policy.
pub(crate) fn clear_active_browser_tab() {
    let changed = lock_active_tab().take().is_some();
    if changed {
        notify_tabs_changed();
    }
}

/// Recreate a discarded tab's WebView and reload its saved URL, then make it
/// the active tab. No-op if the tab is already live.
pub(crate) fn reactivate_browser_tab(tab_id: &str) -> Result<(), LxAppError> {
    let normalized = normalize_runtime_tab_id(tab_id).ok_or_else(|| {
        LxAppError::InvalidParameter("tab_id must be a valid runtime browser tab id".to_string())
    })?;
    // Returns the create params when the tab needs its WebView rebuilt, or
    // `None` when it is already live (just needs (re)activating below).
    let recreate = {
        let mut state = lock_state();
        let Some(tab) = state.tabs.get_mut(&normalized) else {
            return Err(LxAppError::ResourceNotFound(
                "browser tab not found".to_string(),
            ));
        };
        if tab.discarded {
            let token = next_browser_create_token();
            tab.create_token = token;
            tab.discarded = false;
            tab.create_in_flight = true;
            // `pending_url` already holds the saved `current_url` from discard.
            Some((
                tab.session_id,
                token,
                tab.data_mode,
                tab.url_callback.clone(),
                tab.standalone,
            ))
        } else {
            None
        }
    };

    if let Some((session_id, token, data_mode, url_callback, standalone)) = recreate {
        let path = browser_tab_path_for_runtime_id(&normalized);
        if let Err(error) = browser_create_webview(
            &path,
            session_id,
            &normalized,
            token,
            data_mode,
            url_callback,
            standalone,
        ) {
            if let Some(tab) = lock_state().tabs.get_mut(&normalized) {
                tab.discarded = true;
                tab.create_in_flight = false;
            }
            return Err(error);
        }
    }

    if set_active_browser_tab(&normalized) {
        notify_tabs_changed();
    }
    Ok(())
}

/// Session-only restore metadata. Private/aside tabs never enter this stack.
#[derive(Clone, Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ClosedBrowserTab {
    pub id: String,
    pub url: String,
    pub title: String,
    #[serde(skip)]
    owner_appid: Option<String>,
    #[serde(skip)]
    owner_session_id: Option<u64>,
}

impl ClosedBrowserTab {
    fn from_tab(tab: &BrowserTabState) -> Option<Self> {
        if tab.standalone || tab.aside || tab.data_mode == WebViewDataMode::Ephemeral {
            return None;
        }
        let url = tab
            .current_url
            .clone()
            .or_else(|| tab.pending_url.clone())?;
        // Restore website tabs only; internal pages require a fresh native trusted load.
        if !matches!(
            crate::policy::extract_url_scheme(&url).as_deref(),
            Some("http" | "https")
        ) {
            return None;
        }
        Some(Self {
            id: uuid::Uuid::new_v4().to_string(),
            url,
            title: tab.title.clone().unwrap_or_default(),
            owner_appid: tab.owner_appid.clone(),
            owner_session_id: tab.owner_session_id,
        })
    }
}

pub fn recently_closed() -> Vec<ClosedBrowserTab> {
    lock_state().recently_closed.iter().rev().cloned().collect()
}

pub fn reopen_closed(id: Option<&str>) -> Result<String, LxAppError> {
    let entry = {
        let mut state = lock_state();
        let index = state
            .recently_closed
            .iter()
            .rposition(|entry| id.is_none_or(|id| entry.id == id))
            .ok_or_else(|| LxAppError::ResourceNotFound("no recently closed tab".to_string()))?;
        state.recently_closed.remove(index)
    };
    let result = match (&entry.owner_appid, entry.owner_session_id) {
        (Some(appid), Some(session_id)) => crate::open_for_app(appid, session_id, &entry.url, None),
        _ => crate::open(&entry.url, None),
    };
    match result {
        Ok(tab_id) => {
            browser_update_tab_info(&tab_id, None, Some(&entry.title));
            let _ = crate::present(&tab_id);
            Ok(tab_id)
        }
        Err(error) => {
            let mut state = lock_state();
            state.recently_closed.push(entry);
            if state.recently_closed.len() > 25 {
                state.recently_closed.remove(0);
            }
            Err(error)
        }
    }
}

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

    #[test]
    fn recently_closed_only_records_normal_website_tabs_with_owner() {
        let mut tab = BrowserTabState {
            session_id: 1,
            created_order: 1,
            create_token: 1,
            create_in_flight: false,
            pending_url: None,
            initial_url: None,
            current_url: Some("https://example.test/".into()),
            title: Some("Example".into()),
            title_url: None,
            favicon_png: None,
            can_go_back: false,
            can_go_forward: false,
            discarded: false,
            data_mode: WebViewDataMode::ProfileDefault,
            url_callback: Arc::new(AtomicBool::new(false)),
            standalone: false,
            aside: false,
            owner_appid: Some("owner".into()),
            owner_session_id: Some(42),
        };
        let entry = ClosedBrowserTab::from_tab(&tab).unwrap();
        assert_eq!(entry.url, "https://example.test/");
        assert_eq!(entry.owner_session_id, Some(42));
        assert_eq!(entry.title, "Example");
        tab.data_mode = WebViewDataMode::Ephemeral;
        assert!(ClosedBrowserTab::from_tab(&tab).is_none());
        tab.data_mode = WebViewDataMode::ProfileDefault;
        tab.aside = true;
        assert!(ClosedBrowserTab::from_tab(&tab).is_none());
        tab.aside = false;
        tab.standalone = true;
        assert!(ClosedBrowserTab::from_tab(&tab).is_none());
        tab.standalone = false;
        tab.current_url = Some("lingxia://settings".into());
        assert!(ClosedBrowserTab::from_tab(&tab).is_none());
    }

    #[test]
    fn webview_creation_receives_the_browser_user_agent_override() {
        let tab_id = generate_tab_id();
        let previous_user_agent = {
            let mut state = lock_state();
            let previous = state
                .user_agent_override
                .replace("TestAgent/1.0".to_string());
            state.tabs.insert(
                tab_id.clone(),
                BrowserTabState {
                    session_id: 42,
                    created_order: next_browser_created_order(),
                    create_token: 7,
                    create_in_flight: true,
                    pending_url: Some("https://example.test/".to_string()),
                    initial_url: Some("https://example.test/".to_string()),
                    current_url: None,
                    title: None,
                    title_url: None,
                    favicon_png: None,
                    can_go_back: false,
                    can_go_forward: false,
                    discarded: false,
                    data_mode: WebViewDataMode::ProfileDefault,
                    url_callback: Arc::new(AtomicBool::new(false)),
                    standalone: false,
                    aside: false,
                    owner_appid: None,
                    owner_session_id: None,
                },
            );
            previous
        };

        let state = browser_tab_create_state(&tab_id, 42, 7);
        assert!(matches!(
            state,
            TabCreateState::Active {
                pending_url: Some(url),
                user_agent_override: Some(user_agent),
            } if url == "https://example.test/" && user_agent == "TestAgent/1.0"
        ));
        assert!(!lock_state().tabs[&tab_id].create_in_flight);
        let mut state = lock_state();
        state.tabs.remove(&tab_id);
        state.user_agent_override = previous_user_agent;
    }

    #[test]
    fn tab_generation_match_rejects_a_recreated_tab() {
        let tab = BrowserTabState {
            session_id: 42,
            created_order: 1,
            create_token: 8,
            create_in_flight: false,
            pending_url: None,
            initial_url: None,
            current_url: None,
            title: None,
            title_url: None,
            favicon_png: None,
            can_go_back: false,
            can_go_forward: false,
            discarded: false,
            data_mode: WebViewDataMode::ProfileDefault,
            url_callback: Arc::new(AtomicBool::new(false)),
            standalone: false,
            aside: false,
            owner_appid: None,
            owner_session_id: None,
        };

        assert!(tab_generation_matches(&tab, 42, 8));
        assert!(!tab_generation_matches(&tab, 42, 7));
        assert!(!tab_generation_matches(&tab, 41, 8));
    }

    #[test]
    fn discarded_or_recreated_tab_rejects_stale_internal_reload() {
        let tab_id = generate_tab_id();
        lock_state().tabs.insert(
            tab_id.clone(),
            BrowserTabState {
                session_id: 42,
                created_order: next_browser_created_order(),
                create_token: 8,
                create_in_flight: false,
                pending_url: None,
                initial_url: Some("lingxia://settings".to_string()),
                current_url: Some("lingxia://settings".to_string()),
                title: None,
                title_url: None,
                favicon_png: None,
                can_go_back: false,
                can_go_forward: false,
                discarded: false,
                data_mode: WebViewDataMode::ProfileDefault,
                url_callback: Arc::new(AtomicBool::new(false)),
                standalone: false,
                aside: false,
                owner_appid: None,
                owner_session_id: None,
            },
        );

        assert_eq!(
            browser_internal_url_if_token_matches(&tab_id, 42, 8).as_deref(),
            Some("lingxia://settings")
        );
        lock_state().tabs.get_mut(&tab_id).unwrap().create_token = 9;
        assert_eq!(browser_internal_url_if_token_matches(&tab_id, 42, 8), None);
        lock_state().tabs.remove(&tab_id);
    }

    #[test]
    fn stable_browser_tab_ids_are_deterministic_per_scope() {
        let global_a = resolve_browser_tab_id(Some("settings"), BrowserTabScope::Global).unwrap();
        let global_b = resolve_browser_tab_id(Some("settings"), BrowserTabScope::Global).unwrap();
        let owner_a = resolve_browser_tab_id(
            Some("settings"),
            BrowserTabScope::OwnerSession {
                owner_appid: "app.demo",
                owner_session_id: 1,
            },
        )
        .unwrap();
        let owner_b = resolve_browser_tab_id(
            Some("settings"),
            BrowserTabScope::OwnerSession {
                owner_appid: "app.demo",
                owner_session_id: 2,
            },
        )
        .unwrap();

        assert_eq!(global_a, global_b);
        assert_ne!(global_a, owner_a);
        assert_ne!(owner_a, owner_b);
    }

    #[test]
    fn stable_browser_tab_ids_reject_invalid_keys() {
        let result = resolve_browser_tab_id(Some("settings/main"), BrowserTabScope::Global);
        assert!(matches!(result, Err(LxAppError::InvalidParameter(_))));
    }

    #[test]
    fn navigation_history_respects_title_privacy_and_generation() {
        // Metadata bookkeeping needs no WebView; seed the tab entry directly.
        let tab_id = "navfinishtitletest";
        lock_state().tabs.insert(
            tab_id.to_string(),
            BrowserTabState {
                session_id: 1,
                created_order: next_browser_created_order(),
                create_token: 1,
                create_in_flight: false,
                pending_url: None,
                initial_url: None,
                current_url: None,
                title: None,
                title_url: None,
                favicon_png: None,
                can_go_back: false,
                can_go_forward: false,
                discarded: false,
                data_mode: WebViewDataMode::ProfileDefault,
                url_callback: Arc::new(AtomicBool::new(false)),
                standalone: false,
                aside: false,
                owner_appid: None,
                owner_session_id: None,
            },
        );
        assert!(browser_update_tab_info(
            tab_id,
            Some("https://a.test/"),
            Some("Page A")
        ));

        let visits: Arc<Mutex<Vec<(String, String)>>> = Arc::new(Mutex::new(Vec::new()));
        let visit_sink = visits.clone();
        set_navigation_finished_handler(Arc::new(move |url, title| {
            visit_sink
                .lock()
                .unwrap()
                .push((url.to_string(), title.to_string()));
        }));
        let titles: Arc<Mutex<Vec<(String, String)>>> = Arc::new(Mutex::new(Vec::new()));
        let title_sink = titles.clone();
        set_title_changed_handler(Arc::new(move |url, title| {
            title_sink
                .lock()
                .unwrap()
                .push((url.to_string(), title.to_string()));
        }));

        // Page B finishes before its title is reported: A's title must not leak.
        notify_navigation_finished(tab_id, 1, 1, "https://b.test/");
        notify_navigation_finished(tab_id, 1, 1, "https://a.test/");
        assert_eq!(
            *visits.lock().unwrap(),
            vec![
                ("https://b.test/".to_string(), String::new()),
                ("https://a.test/".to_string(), "Page A".to_string()),
            ]
        );

        assert!(browser_update_tab_info_if_token_matches(
            tab_id,
            1,
            1,
            Some("https://normal.test/"),
            Some("Normal")
        ));
        assert_eq!(
            *titles.lock().unwrap(),
            vec![("https://normal.test/".to_string(), "Normal".to_string())]
        );

        let assert_private_policy =
            |data_mode: WebViewDataMode, url_callback: bool, standalone: bool, suffix: &str| {
                {
                    let mut state = lock_state();
                    let tab = state.tabs.get_mut(tab_id).unwrap();
                    tab.data_mode = data_mode;
                    tab.url_callback.store(url_callback, Ordering::Release);
                    tab.standalone = standalone;
                }
                let url = format!("https://auth.test/callback?code={suffix}");
                notify_navigation_finished(tab_id, 1, 1, &url);
                assert!(browser_update_tab_info_if_token_matches(
                    tab_id,
                    1,
                    1,
                    Some(&url),
                    Some(&format!("Secret {suffix}"))
                ));
                assert_eq!(visits.lock().unwrap().len(), 2);
                assert_eq!(titles.lock().unwrap().len(), 1);
            };

        assert_private_policy(WebViewDataMode::Ephemeral, false, false, "ephemeral");
        assert_private_policy(WebViewDataMode::ProfileDefault, true, false, "callback");
        assert_private_policy(WebViewDataMode::ProfileDefault, false, true, "standalone");

        {
            let mut state = lock_state();
            let tab = state.tabs.get_mut(tab_id).unwrap();
            tab.data_mode = WebViewDataMode::ProfileDefault;
            tab.standalone = false;
            tab.create_token = 2;
        }
        assert!(!browser_update_tab_info_if_token_matches(
            tab_id,
            1,
            1,
            Some("https://auth.test/callback?code=stale"),
            Some("Stale secret")
        ));
        notify_navigation_finished(tab_id, 1, 1, "https://auth.test/callback?code=stale");
        assert_eq!(visits.lock().unwrap().len(), 2);
        assert_eq!(titles.lock().unwrap().len(), 1);
        lock_state().tabs.remove(tab_id);
    }

    #[test]
    fn stable_tab_reuse_rejects_privacy_policy_changes() {
        let tab = BrowserTabState {
            session_id: 1,
            created_order: next_browser_created_order(),
            create_token: 1,
            create_in_flight: false,
            pending_url: None,
            initial_url: None,
            current_url: None,
            title: None,
            title_url: None,
            favicon_png: None,
            can_go_back: false,
            can_go_forward: false,
            discarded: false,
            data_mode: WebViewDataMode::ProfileDefault,
            url_callback: Arc::new(AtomicBool::new(false)),
            standalone: false,
            aside: false,
            owner_appid: None,
            owner_session_id: None,
        };

        assert!(validate_reused_tab_policy(&tab, WebViewDataMode::ProfileDefault, false).is_ok());
        assert!(validate_reused_tab_policy(&tab, WebViewDataMode::Ephemeral, false).is_err());
        assert!(validate_reused_tab_policy(&tab, WebViewDataMode::ProfileDefault, true).is_err());
    }

    #[test]
    fn runtime_tab_id_lookup_normalizes_stable_keys() {
        assert_eq!(
            normalize_runtime_tab_id("settings"),
            Some("settings".to_string())
        );
        assert_eq!(
            normalize_runtime_tab_id("SeTtings"),
            Some("settings".to_string())
        );
        assert!(normalize_runtime_tab_id("settings/main").is_none());
    }

    #[test]
    fn standalone_surface_tabs_remain_in_automation_inventory() {
        let tab_id = generate_tab_id();
        lock_state().tabs.insert(
            tab_id.clone(),
            BrowserTabState {
                session_id: 7,
                created_order: next_browser_created_order(),
                create_token: 1,
                create_in_flight: false,
                pending_url: None,
                initial_url: Some("https://auth.example.test/".to_string()),
                current_url: Some("https://auth.example.test/".to_string()),
                title: None,
                title_url: None,
                favicon_png: None,
                can_go_back: false,
                can_go_forward: false,
                discarded: false,
                data_mode: WebViewDataMode::Ephemeral,
                url_callback: Arc::new(AtomicBool::new(true)),
                standalone: true,
                aside: false,
                owner_appid: Some("app.demo".to_string()),
                owner_session_id: Some(3),
            },
        );

        let info = browser_tabs()
            .into_iter()
            .find(|tab| tab.tab_id == tab_id)
            .expect("standalone URL surface should be visible to devtools");
        assert_eq!(
            info.current_url.as_deref(),
            Some("https://auth.example.test/")
        );
        lock_state().tabs.remove(&tab_id);
    }

    #[test]
    fn activating_standalone_tab_does_not_replace_product_active_tab() {
        let product_tab_id = generate_tab_id();
        let standalone_tab_id = generate_tab_id();
        let make_tab = |standalone| BrowserTabState {
            session_id: 7,
            created_order: next_browser_created_order(),
            create_token: 1,
            create_in_flight: false,
            pending_url: None,
            initial_url: None,
            current_url: None,
            title: None,
            title_url: None,
            favicon_png: None,
            can_go_back: false,
            can_go_forward: false,
            discarded: false,
            data_mode: WebViewDataMode::ProfileDefault,
            url_callback: Arc::new(AtomicBool::new(false)),
            standalone,
            aside: false,
            owner_appid: None,
            owner_session_id: None,
        };
        lock_state()
            .tabs
            .insert(product_tab_id.clone(), make_tab(false));
        lock_state()
            .tabs
            .insert(standalone_tab_id.clone(), make_tab(true));
        assert!(set_active_browser_tab(&product_tab_id));

        let activated = browser_activate_tab(&standalone_tab_id).unwrap();

        assert_eq!(activated.tab_id, standalone_tab_id);
        assert_eq!(
            browser_current_tab().map(|tab| tab.tab_id),
            Some(product_tab_id.clone())
        );
        assert_eq!(
            browser_automation_current_tab().map(|tab| tab.tab_id),
            Some(standalone_tab_id.clone())
        );
        lock_state().tabs.remove(&standalone_tab_id);
        lock_state().tabs.remove(&product_tab_id);
        lock_active_tab().take();
        lock_automation_tab().take();
    }
}