lingxia-browser 0.11.0

Browser runtime capability crate for LingXia
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
//! 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::policy::{is_lingxia_startup_url, normalize_browser_target_url};
use crate::types::{BrowserAutomationError, BrowserTabInfo};
use crate::webview::{
    browser_create_webview, browser_destroy_webview, browser_find_webview, browser_load_url,
};
use lingxia_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,
    /// 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>,
}

pub(crate) struct BrowserState {
    // tab_id -> tab lifecycle state (single WebView lifecycle per tab_id)
    pub(crate) tabs: HashMap<String, BrowserTabState>,
}

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_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);
    }
}

/// Whether the tab's current document is a browser-internal `lingxia://`
/// page. Uses the pending URL while a load is in flight, else the committed
/// URL. External documents (http/https/about:blank/…) must never drive an
/// lxapp `PageInstance` lifecycle or receive its bridge.
pub(crate) fn browser_tab_document_is_internal(tab_id: &str) -> bool {
    let document_url = {
        let state = lock_state();
        normalize_runtime_tab_id(tab_id)
            .and_then(|normalized| state.tabs.get(&normalized))
            .and_then(|tab| tab.pending_url.clone().or_else(|| tab.current_url.clone()))
    };
    document_url
        .as_deref()
        .and_then(crate::policy::extract_url_scheme)
        .as_deref()
        == Some(crate::policy::LINGXIA_SCHEME)
}

pub(crate) fn notify_navigation_finished(tab_id: &str, 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.title_url.as_deref() == Some(url))
                .and_then(|tab| tab.title.clone())
                .unwrap_or_default()
        };
        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(),
            })
        })
        .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)
}

// ---------------------------------------------------------------------------
// 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))
}

pub fn browser_tabs() -> Vec<BrowserTabInfo> {
    let state = lock_state();
    let mut tabs: Vec<BrowserTabInfo> = state
        .tabs
        .iter()
        .map(|(tab_id, tab)| build_tab_info(tab_id, tab))
        .collect();
    tabs.sort_by(|a, b| a.tab_id.cmp(&b.tab_id));
    tabs
}

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));
    }
    let mut product_tabs = state
        .tabs
        .iter()
        .filter(|(_, tab)| !tab.standalone)
        .map(|(tab_id, tab)| build_tab_info(tab_id, tab))
        .collect::<Vec<_>>();
    product_tabs.sort_by(|a, b| a.tab_id.cmp(&b.tab_id));
    product_tabs.into_iter().next()
}

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)
}

pub(crate) fn browser_update_tab_info(
    tab_id: &str,
    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;
        };
        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 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
}

/// 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 changed = {
        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
    };
    if changed {
        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> },
    Missing,
    Stale,
}

pub(crate) fn browser_tab_create_state(
    tab_id: &str,
    session_id: u64,
    create_token: u64,
) -> TabCreateState {
    let mut state = lock_state();
    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(),
            }
        }
        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) {
            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,
                    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(),
        ) {
            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 {
        match browser_load_url(&path, session_id, &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;
                            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(),
                    )
                {
                    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,
    )
}

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. Its new-window
/// requests load inline rather than spawning 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> {
    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 removed = {
        let mut state = lock_state();
        state.tabs.remove(&normalized)
    };
    let removed_any = removed.is_some();
    if let Some(tab) = removed {
        let tab_path = browser_tab_path_for_runtime_id(&normalized);
        // 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 = browser_find_webview(&tab_path, tab.session_id).ok();
                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();
            }
            browser.remove_pages(std::slice::from_ref(&tab_path));
        }
        browser_destroy_webview(&tab_path, tab.session_id);
    }
    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(tab_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);

    // 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 = browser_find_webview(&tab_path, tab.session_id).ok();
            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();
        }
        browser.remove_pages(std::slice::from_ref(&tab_path));
    }
    browser_destroy_webview(&tab_path, tab.session_id);

    // 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(),
            ))
        } else {
            None
        }
    };

    if let Some((session_id, token, data_mode, url_callback)) = 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,
        ) {
            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(())
}

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

    #[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_finish_drops_title_from_previous_page() {
        // 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,
                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 captured: Arc<Mutex<Vec<(String, String)>>> = Arc::new(Mutex::new(Vec::new()));
        let sink = captured.clone();
        set_navigation_finished_handler(Arc::new(move |url, 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, "https://b.test/");
        notify_navigation_finished(tab_id, "https://a.test/");
        assert_eq!(
            *captured.lock().unwrap(),
            vec![
                ("https://b.test/".to_string(), String::new()),
                ("https://a.test/".to_string(), "Page A".to_string()),
            ]
        );
        lock_state().tabs.remove(tab_id);
    }

    #[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,
                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,
            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();
    }
}