victauri-plugin 0.9.0

Tauri plugin for Victauri — embedded MCP server with full-stack introspection
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
use tauri::{Manager, Runtime};
use victauri_core::WindowState;

/// Runtime-erased interface for webview and backend access, allowing the MCP
/// server to interact with Tauri windows and the application backend without
/// generic parameters.
///
/// Victauri implements this for `tauri::AppHandle`; it is public so tests (and embedders) can
/// supply a mock. **Stability contract:** any method added to this trait in a future release
/// will have a default implementation, so implementing it does not pin you to an exact
/// version. [`WindowState`] is `#[non_exhaustive]` — build one with
/// `WindowState::new(label).with_*(..)`.
pub trait WebviewBridge: Send + Sync {
    /// Execute JavaScript in the target webview (defaults to "main" or first visible window).
    ///
    /// # Errors
    ///
    /// Returns an error string if no matching window is found or the eval fails.
    fn eval_webview(&self, label: Option<&str>, script: &str) -> Result<(), String>;
    /// Retrieve the state of one or all windows (position, size, visibility, focus, URL).
    fn get_window_states(&self, label: Option<&str>) -> Vec<WindowState>;
    /// Like [`get_window_states`](Self::get_window_states), but distinguishes "could not ask"
    /// (the UI thread did not answer in time) from "no such window". A caller that reports a
    /// window as missing, or a list as empty, must use this.
    ///
    /// # Errors
    ///
    /// Returns an error string if the window states could not be obtained.
    fn try_get_window_states(&self, label: Option<&str>) -> Result<Vec<WindowState>, String> {
        Ok(self.get_window_states(label))
    }
    /// Return the labels of all open webview windows.
    fn list_window_labels(&self) -> Vec<String>;
    /// Like [`list_window_labels`](Self::list_window_labels), but distinguishes "could not
    /// ask" (e.g. the UI thread did not answer in time) from "there are no windows". A caller
    /// deciding that a window is GONE must use this — an empty list from a wedged UI is not
    /// evidence of anything.
    ///
    /// # Errors
    ///
    /// Returns an error string if the window list could not be obtained.
    fn try_list_window_labels(&self) -> Result<Vec<String>, String> {
        Ok(self.list_window_labels())
    }
    /// Like [`eval_webview`](Self::eval_webview), but returns the label of the window the
    /// script was actually delivered to (for `None`, the resolved default window). The default
    /// implementation returns the requested label, or an EMPTY string when it cannot know which
    /// window a `None` label resolved to — callers must treat empty as "unknown".
    ///
    /// # Errors
    ///
    /// Returns an error string if no matching window is found or the eval fails.
    fn eval_webview_resolved(&self, label: Option<&str>, script: &str) -> Result<String, String> {
        self.eval_webview(label, script)?;
        Ok(label.map(str::to_string).unwrap_or_default())
    }
    /// Return the platform-native window handle for screenshot capture.
    /// Windows: `HWND`, macOS: `CGWindowID` (window number), Linux: `X11` window ID.
    ///
    /// # Errors
    ///
    /// Returns an error string if no matching window is found or the handle type is unsupported.
    fn get_native_handle(&self, label: Option<&str>) -> Result<isize, String>;
    /// Perform a window management action (minimize, maximize, close, show, hide, etc.).
    ///
    /// # Errors
    ///
    /// Returns an error string if no matching window is found or the action fails.
    fn manage_window(&self, label: Option<&str>, action: &str) -> Result<String, String>;
    /// Set the logical size of a window in device-independent pixels.
    ///
    /// # Errors
    ///
    /// Returns an error string if no matching window is found or the resize fails.
    fn resize_window(&self, label: Option<&str>, width: u32, height: u32) -> Result<(), String>;
    /// Set the logical position of a window in device-independent pixels.
    ///
    /// # Errors
    ///
    /// Returns an error string if no matching window is found or the move fails.
    fn move_window(&self, label: Option<&str>, x: i32, y: i32) -> Result<(), String>;
    /// Set the title bar text of a window.
    ///
    /// # Errors
    ///
    /// Returns an error string if no matching window is found or the title change fails.
    fn set_window_title(&self, label: Option<&str>, title: &str) -> Result<(), String>;

    // ── Native (OS-level, trusted) input ───────────────────────────────────
    //
    // These deliver real OS input events (`isTrusted: true`), unlike the JS
    // bridge's synthetic events. They are needed for app handlers that gate on
    // `event.isTrusted` and for user-activation-gated browser APIs. Default
    // implementations return an error so platforms without support degrade
    // gracefully (callers fall back to synthetic input).

    /// Type Unicode text as trusted OS keyboard input into the focused element
    /// of the target window. The element must already hold focus.
    ///
    /// # Errors
    /// Returns an error if not supported on this platform or the window is missing.
    fn native_type_text(&self, _label: Option<&str>, _text: &str) -> Result<(), String> {
        Err(
            "native (trusted) keyboard input is not implemented on this platform; \
             use synthetic input via the `input` tool without `trusted`"
                .to_string(),
        )
    }

    /// Press a single named key (e.g. `Enter`, `Tab`, `Escape`, `ArrowDown`) as
    /// trusted OS keyboard input to the focused element of the target window.
    ///
    /// # Errors
    /// Returns an error if not supported on this platform or the key is unknown.
    fn native_key(&self, _label: Option<&str>, _key: &str) -> Result<(), String> {
        Err(
            "native (trusted) key input is not implemented on this platform; \
             use synthetic input via the `input` tool without `trusted`"
                .to_string(),
        )
    }

    /// Click at logical (CSS-pixel) coordinates within the target window's
    /// content area, as a trusted OS mouse event.
    ///
    /// # Errors
    /// Returns an error if not supported on this platform or the window is missing.
    fn native_click(&self, _label: Option<&str>, _x: f64, _y: f64) -> Result<(), String> {
        Err(
            "native (trusted) mouse input is not implemented on this platform; \
             use synthetic input via the `interact` tool"
                .to_string(),
        )
    }

    // ── Backend Access ─────────────────────────────────────────────────────

    /// Return the app's per-user data directory (e.g. `~/.local/share/<app>/`).
    ///
    /// # Errors
    ///
    /// Returns an error if the path cannot be resolved.
    fn app_data_dir(&self) -> Result<std::path::PathBuf, String> {
        Err("backend access not available".to_string())
    }

    /// Return the app's per-user config directory (e.g. `~/.config/<app>/`).
    ///
    /// # Errors
    ///
    /// Returns an error if the path cannot be resolved.
    fn app_config_dir(&self) -> Result<std::path::PathBuf, String> {
        Err("backend access not available".to_string())
    }

    /// Return the app's log directory.
    ///
    /// # Errors
    ///
    /// Returns an error if the path cannot be resolved.
    fn app_log_dir(&self) -> Result<std::path::PathBuf, String> {
        Err("backend access not available".to_string())
    }

    /// Return the app's local data directory.
    ///
    /// # Errors
    ///
    /// Returns an error if the path cannot be resolved.
    fn app_local_data_dir(&self) -> Result<std::path::PathBuf, String> {
        Err("backend access not available".to_string())
    }

    /// Return the Tauri app configuration as JSON.
    #[must_use]
    fn tauri_config(&self) -> serde_json::Value {
        serde_json::Value::Null
    }
}

fn find_window<'a, R: Runtime>(
    windows: &'a std::collections::HashMap<String, tauri::WebviewWindow<R>>,
    label: Option<&str>,
) -> Result<&'a tauri::WebviewWindow<R>, String> {
    match label {
        Some(l) => windows
            .get(l)
            .ok_or_else(|| format!("window not found: {l}")),
        None => windows
            .get("main")
            // Deterministic fallbacks: `webview_windows()` is a HashMap whose iteration order
            // differs between calls, so "first visible" must be chosen by a stable key or two
            // consecutive calls can pick different windows.
            .or_else(|| {
                let mut visible: Vec<_> = windows
                    .iter()
                    .filter(|(_, w)| w.is_visible().unwrap_or(false))
                    .collect();
                visible.sort_by(|a, b| a.0.cmp(b.0));
                visible.first().map(|(_, w)| *w)
            })
            .or_else(|| windows.iter().min_by(|a, b| a.0.cmp(b.0)).map(|(_, w)| w))
            .ok_or_else(|| "no window available".to_string()),
    }
}

/// The label of the window a `None` label resolves to (see `find_window`). MAIN THREAD ONLY:
/// it lists the webview windows, which clones their handles (see [`on_main`]) — for a sync
/// Tauri command such as the eval callback.
pub(crate) fn default_window_label<R: Runtime>(app: &tauri::AppHandle<R>) -> Option<String> {
    let windows = app.webview_windows();
    find_window(&windows, None)
        .ok()
        .map(|window| window.label().to_string())
}

/// Serializes Victauri's main-thread round trips.
///
/// **Correction (0.9.0): the heap corruption described below was NOT caused by concurrent round
/// trips as such.** Its real cause was the `AppHandle` clone each round trip made on the calling
/// thread (see [`on_main`]) — cloning or dropping any Tauri handle off the main thread races a
/// non-atomic `Rc` inside tao on Linux. Serializing only limited how many threads cloned at once,
/// which is why it reduced the crash without removing it. The lock stays: it bounds how much
/// Victauri can queue onto the UI thread and is measured-safe. The original 0.8.8 notes follow.
///
/// Concurrent `run_on_main_thread` round trips corrupt the process heap on Linux/WebKitGTK —
/// glibc aborts the app with `malloc(): unaligned tcache chunk detected` or `corrupted
/// double-linked list`. Measured on Ubuntu 24.04 + `WebKitGTK` 2.52, three concurrent
/// introspection loops for 8s: **5/8 runs died** unserialized, **8/8** with the tokio
/// `block_in_place` hand-off removed, and **0/28** once the whole round trip is serialized here.
///
/// The bisect that pinned it down, so a future reader does not re-do it:
/// * Not the reload. Reload-hammering with no introspection never died (0/4); introspection
///   with no reload at all died every time (4/4). The crash is unrelated to page reloads.
/// * Not the dispatch alone. Locking only around `run_on_main_thread` still died 4/8 — what
///   matters is how many round trips are in flight at once, not how the message is posted.
/// * Not load. One unthrottled loop issuing the same total number of calls never died (0/4);
///   three concurrent loops died. Concurrency is the variable, not volume.
/// * Not our HTTP/tokio layer. A tool that touches no webview (`get_memory_stats`) at the same
///   concurrency never died (0/5).
/// * Not new. The pre-rmcp-3.1.2 tree died at the same rate (6/8), so this long predates 0.8.8.
///
/// Serializing costs effectively nothing: the closures already execute one at a time on the
/// single main thread, so this only stops several round trips being in flight *around* it.
///
/// The lock is only taken OFF the main thread: a caller already on the main thread (including
/// an `on_main` closure that calls back into the bridge) runs inline without it — see `on_main`.
static MAIN_DISPATCH_LOCK: DispatchGate = DispatchGate::new();

/// The serialization state behind [`MAIN_DISPATCH_LOCK`] (a separate type so tests can use
/// their own gate instead of the process-wide one).
///
/// The lock alone is not enough: a caller whose closure STARTED but outlived its timeout + grace
/// returns "outcome unknown" and releases the lock while that closure is still executing on the
/// main thread. `in_flight` counts dispatched closures that have reached the main thread and not
/// yet finished, and the next lock holder also waits (within its own deadline) for it to reach
/// zero — so there is still never more than one round trip in flight (R4-LOCK1).
struct DispatchGate {
    lock: std::sync::Mutex<()>,
    in_flight: std::sync::atomic::AtomicUsize,
}

impl DispatchGate {
    const fn new() -> Self {
        Self {
            lock: std::sync::Mutex::new(()),
            in_flight: std::sync::atomic::AtomicUsize::new(0),
        }
    }
}

/// Decrements [`DispatchGate::in_flight`] when a dispatched closure finishes — including by
/// unwinding, so a panicking closure can never wedge every later round trip.
struct InFlightGuard(&'static DispatchGate);

impl Drop for InFlightGuard {
    fn drop(&mut self) {
        self.0
            .in_flight
            .fetch_sub(1, std::sync::atomic::Ordering::AcqRel);
    }
}

/// The Tauri main (UI) thread, recorded ON it by [`adopt_main_thread`] (from plugin `setup`).
static MAIN_THREAD: std::sync::OnceLock<std::thread::ThreadId> = std::sync::OnceLock::new();

/// Record the calling thread as the Tauri main thread. Called on the main thread by
/// [`adopt_main_thread`].
fn record_main_thread() {
    let _ = MAIN_THREAD.set(std::thread::current().id());
}

thread_local! {
    /// An app handle owned by the main thread and only ever cloned or dropped there (installed
    /// by [`install_main_app`] via [`adopt_main_thread`]). `on_main` closures take their handle from
    /// here instead of from a clone made on the calling thread — see [`on_main`] for why a
    /// Tauri handle must never be cloned or dropped off the main thread.
    static MAIN_APP: std::cell::RefCell<Option<Box<dyn std::any::Any>>> =
        const { std::cell::RefCell::new(None) };
}

/// Keep a main-thread-owned clone of `app` for `on_main` closures. Must be called ON the main
/// thread (see [`adopt_main_thread`]); a call from any other thread stores into that thread's
/// slot, which no closure ever reads.
fn install_main_app<R: Runtime>(app: &tauri::AppHandle<R>) {
    MAIN_APP.with(|slot| *slot.borrow_mut() = Some(Box::new(app.clone())));
}

/// How plugin setup adopted the Tauri main thread (see [`adopt_main_thread`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum MainThreadAdoption {
    /// Setup ran on the main thread: recorded and installed in place.
    Inline,
    /// Setup ran on another thread; recording and installation were posted to the main thread.
    Posted,
}

/// Record the Tauri main thread and give it its own app handle ([`record_main_thread`] +
/// [`install_main_app`]) — ON the main thread, wherever plugin `setup` happens to run.
///
/// Tauri normally runs plugin `setup` on the main thread, but an app may also register a plugin
/// at runtime from a background thread (`AppHandle::plugin`), and `setup` then runs THERE.
/// Recording that thread as "main" and installing the handle in its thread-local slot would
/// leave every later [`on_main`] round trip failing with "the main-thread app handle is not
/// installed" (the closures read the real main thread's slot, which stays empty).
///
/// Which thread is the main one is learned from Tauri itself: `run_on_main_thread` runs a
/// closure inline when called ON the main thread and queues it otherwise, so a tiny probe tells
/// the two apart. On the main thread the adoption happens in place (no handle is cloned
/// anywhere else). Off it, the adoption is posted to the main thread with a handle cloned here —
/// one unavoidable off-main clone, of the same kind `setup` itself already makes in that case
/// (it clones the handle for the MCP server) — and round trips made before it runs fail cleanly
/// with "not installed" instead of misbehaving.
pub(crate) fn adopt_main_thread<R: Runtime>(
    app: &tauri::AppHandle<R>,
) -> Result<MainThreadAdoption, String> {
    adopt_on_main(
        app,
        |job| app.run_on_main_thread(job).map_err(|e| e.to_string()),
        |main: &tauri::AppHandle<R>| {
            record_main_thread();
            install_main_app(main);
        },
    )
}

/// Generic core of [`adopt_main_thread`], testable with a fake main thread. `post` must run a
/// job inline when called on the main thread and queue it there otherwise (Tauri's
/// `run_on_main_thread` contract); `adopt` is always called on the main thread.
fn adopt_on_main<H: Clone + Send + 'static>(
    handle: &H,
    post: impl Fn(Box<dyn FnOnce() + Send>) -> Result<(), String>,
    adopt: impl Fn(&H) + Send + 'static,
) -> Result<MainThreadAdoption, String> {
    use std::sync::atomic::{AtomicBool, Ordering};

    let here = std::thread::current().id();
    let ran_here = std::sync::Arc::new(AtomicBool::new(false));
    let flag = std::sync::Arc::clone(&ran_here);
    // Queued (off the main thread), this runs later on the main thread and finds a different
    // thread id there, so it does nothing.
    post(Box::new(move || {
        if std::thread::current().id() == here {
            flag.store(true, Ordering::Release);
        }
    }))?;
    if ran_here.load(Ordering::Acquire) {
        adopt(handle);
        return Ok(MainThreadAdoption::Inline);
    }
    let owned = handle.clone();
    post(Box::new(move || adopt(&owned)))?;
    Ok(MainThreadAdoption::Posted)
}

/// The main thread's own app handle (a clone made HERE, on the main thread), if installed.
fn main_app<R: Runtime>() -> Option<tauri::AppHandle<R>> {
    MAIN_APP.with(|slot| {
        slot.borrow()
            .as_ref()
            .and_then(|any| any.downcast_ref::<tauri::AppHandle<R>>())
            .cloned()
    })
}

/// Whether the current thread is the recorded Tauri main thread (false if not yet recorded).
fn is_main_thread() -> bool {
    MAIN_THREAD
        .get()
        .is_some_and(|id| *id == std::thread::current().id())
}

/// Run `f` on the Tauri **main (UI) thread** and return its result.
///
/// Every webview/window access MUST happen on the main thread. Tauri's window/webview
/// handles wrap a non-`Send` `Rc<WebView>` (and a `RefCell`-backed window store) that are
/// guarded only by an `unsafe impl Send` with a *main-thread-only* contract. The Victauri
/// MCP server runs on a background (axum/tokio) thread, so touching those handles directly —
/// e.g. `self.webview_windows()` cloning the `Rc` — races the main thread's own refcounting
/// (notably `tauri::ipc::protocol::get` while the app handles its real IPC). Two threads
/// mutating a non-atomic `Rc` count corrupts it → use-after-free, which surfaces as
/// `STATUS_*_BUFFER_OVERRUN` once Rust's debug `assert_unchecked` on `Rc::inc_strong`
/// (1.78+) starts checking it. See Tauri issue #10001 for the identical crash class.
///
/// **The same applies to the `AppHandle` itself — never clone or drop one off the main thread.**
/// On Linux every Tauri handle (`AppHandle`, `Webview`, `WebviewWindow`) carries
/// tauri-runtime-wry's `Context`, which holds the main-thread `DispatcherMainThreadContext` BY
/// VALUE, which holds tao's `EventLoopWindowTarget`, which holds `windows:
/// Rc<RefCell<HashSet<WindowId>>>`. So cloning or dropping any handle bumps a NON-ATOMIC count
/// that the main thread bumps all the time (IPC, window access). This function used to clone
/// the `AppHandle` on the calling thread for every round trip; under concurrent introspection
/// that corrupted the heap (glibc `corrupted double-linked list` / `unaligned fastbin chunk`) on
/// Linux/WebKitGTK. Proven without Victauri: a bare Tauri app whose background threads only
/// clone+drop its `AppHandle` while the page makes IPC calls aborted 3/3; 12 threads doing
/// `run_on_main_thread` with an off-thread clone aborted 5/5, and 5/5 with an EMPTY closure.
/// So the closure takes a handle cloned ON the main thread ([`install_main_app`]), and the
/// caller only borrows `app` to post it (`AppHandle::run_on_main_thread` does not clone).
///
/// `run_on_main_thread` marshals the closure onto the UI thread (and runs it inline if we are
/// already on it), so all `Rc` access stays single-threaded. The closure's value comes back
/// over a oneshot `std::sync::mpsc` channel; the bounded `recv` is a safety net against a
/// wedged event loop and never blocks the main thread (the closure runs *there*, the wait
/// happens on the calling background thread).
///
/// The closure runs ON the UI/event-loop thread, so a panic in it would unwind into tao/winit
/// and **abort the whole process** — strictly worse than the use-after-free this dispatcher
/// exists to prevent — and would skip the result send, hanging the caller the full timeout. So
/// the closure is run under `catch_unwind` and a panic is converted into an error that is always
/// sent back. (Today every closure is panic-free by construction, but the helper must not let a
/// future one take the app down.)
///
/// Round trips are additionally serialized through [`MAIN_DISPATCH_LOCK`] — see there for the
/// heap corruption that requires it and the bisect that established it.
///
/// **Blocking.** Off the main thread this call BLOCKS its thread until the closure's outcome is
/// known — up to its 10 s deadline, or about 20 s when the closure started just before it (see
/// [`serialized_round_trip`]). On a multi-threaded tokio runtime it runs under `block_in_place`,
/// so the runtime keeps serving other tasks. On a **current-thread** runtime that is impossible
/// (`block_in_place` panics there), so the whole runtime — every task on it — stalls for that
/// long while the UI is wedged. Victauri's own server runs on a multi-threaded runtime; do not
/// call bridge methods from a current-thread runtime you care about.
fn on_main<R, T, F>(app: &tauri::AppHandle<R>, what: &str, f: F) -> Result<T, String>
where
    R: Runtime,
    T: Send + 'static,
    F: FnOnce(&tauri::AppHandle<R>) -> T + Send + 'static,
{
    let timeout = std::time::Duration::from_secs(10);

    // Already ON the main thread (a sync Tauri command, a menu handler, or an `on_main` closure
    // that calls back into the bridge): run inline, WITHOUT the dispatch lock. Taking the lock
    // here could deadlock — a background holder waits for its closure, which is queued behind
    // us on this very thread — freezing the UI for the full timeout. Skipping it is safe: no
    // other closure can execute on this thread concurrently, and the heap corruption the lock
    // prevents needs several cross-thread round trips in flight, which an inline call is not.
    if is_main_thread() {
        return std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(app)))
            .map_err(|_| format!("{what} panicked on the main thread"));
    }

    let round_trip = move || -> Result<T, String> {
        // No handle is cloned here, on the calling thread (see above): the closure takes the
        // main thread's own handle, and `app` is only borrowed to post it.
        let owned_what = what.to_string();
        serialized_round_trip(
            &MAIN_DISPATCH_LOCK,
            what,
            timeout,
            |job| {
                app.run_on_main_thread(job)
                    .map_err(|e| format!("failed to dispatch {what} to the main thread: {e}"))
            },
            move || {
                main_app::<R>().map(|main| f(&main)).ok_or_else(|| {
                    format!(
                        "{owned_what}: the main-thread app handle is not installed (the plugin \
                         setup has not run)"
                    )
                })
            },
        )?
    };

    // Blocking here must not park a tokio runtime worker — under a wedged UI that could
    // otherwise starve the embedded axum/MCP server. On a multi-threaded runtime, `block_in_place`
    // tells the scheduler to run other tasks elsewhere while this thread blocks. (It panics on a
    // current-thread runtime, so guard on the flavor; with no runtime at all, just block.)
    match tokio::runtime::Handle::try_current().map(|h| h.runtime_flavor()) {
        Ok(tokio::runtime::RuntimeFlavor::MultiThread) => tokio::task::block_in_place(round_trip),
        _ => round_trip(),
    }
}

/// One serialized round trip: take `gate`'s lock (see [`MAIN_DISPATCH_LOCK`]), then hand `f` to `post`
/// and wait for it.
///
/// `timeout` is one deadline shared by everything BEFORE the closure starts — the wait for the
/// lock, for an earlier abandoned closure still running, and for this closure to be picked up —
/// so serializing cannot stack N callers into N * timeout when the UI wedges: a closure that has
/// not started by the deadline is abandoned (it never runs) and the call returns at `timeout`.
/// A closure that DID start before the deadline is waited for up to a further `timeout` (the
/// `grace` passed to [`dispatch_and_wait`]) so its real outcome is reported rather than
/// "timed out" for work that happened. So a call returns within `timeout` if its closure never
/// started, and within about 2 × `timeout` in the worst case (it started just before the
/// deadline and then ran long).
fn serialized_round_trip<T, F>(
    gate: &'static DispatchGate,
    what: &str,
    timeout: std::time::Duration,
    post: impl FnOnce(Box<dyn FnOnce() + Send>) -> Result<(), String>,
    f: F,
) -> Result<T, String>
where
    T: Send + 'static,
    F: FnOnce() -> T + Send + 'static,
{
    let deadline = std::time::Instant::now() + timeout;
    let lock_timeout = || {
        format!(
            "{what} did not complete on the main thread: timed out waiting for the main-thread \
             dispatch lock"
        )
    };
    let _serialize = loop {
        match gate.lock.try_lock() {
            Ok(guard) => break guard,
            Err(std::sync::TryLockError::Poisoned(poisoned)) => break poisoned.into_inner(),
            Err(std::sync::TryLockError::WouldBlock) => {
                let remaining = deadline.saturating_duration_since(std::time::Instant::now());
                if remaining.is_zero() {
                    return Err(lock_timeout());
                }
                std::thread::sleep(remaining.min(std::time::Duration::from_millis(2)));
            }
        }
    };
    // An earlier caller may have given up on a closure that is STILL RUNNING on the main thread
    // (it started, then outlived that caller's timeout + grace). Wait for it — bounded by this
    // caller's own deadline, so callers never stack into N * timeout — before putting a second
    // round trip in flight beside it.
    // A plain sleep. (Round 4 briefly tried a yield spin here and removed it while chasing a
    // Linux heap abort; the abort's real cause was the off-main-thread `AppHandle` clone
    // documented on `on_main`, not the wait.)
    while gate.in_flight.load(std::sync::atomic::Ordering::Acquire) != 0 {
        let remaining = deadline.saturating_duration_since(std::time::Instant::now());
        if remaining.is_zero() {
            return Err(format!(
                "{what} did not complete on the main thread: timed out waiting for an earlier \
                 main-thread call that is still running (it will not run)"
            ));
        }
        std::thread::sleep(remaining.min(std::time::Duration::from_millis(2)));
    }
    let remaining = deadline.saturating_duration_since(std::time::Instant::now());
    if remaining.is_zero() {
        return Err(lock_timeout());
    }
    // Count the closure from BEFORE it can start (the count is raised ahead of the
    // queued->running transition inside `dispatch_and_wait`'s job), so once a caller has seen
    // its job start, the next lock holder is guaranteed to see it in flight.
    let counted_post = move |job: Box<dyn FnOnce() + Send>| {
        post(Box::new(move || {
            gate.in_flight
                .fetch_add(1, std::sync::atomic::Ordering::AcqRel);
            let _done = InFlightGuard(gate);
            job();
        }))
    };
    // Returns with the lock still held until the closure has either run or been abandoned,
    // so no second round trip is ever in flight beside a closure that may still start.
    dispatch_and_wait(what, remaining, timeout, counted_post, f)
}

/// A dispatched closure that has not started yet.
const JOB_QUEUED: u8 = 0;
/// A dispatched closure that has started (its effects will happen).
const JOB_RUNNING: u8 = 1;
/// A dispatched closure its caller gave up on before it started: it must never run.
const JOB_ABANDONED: u8 = 2;

/// Hand `f` to `post` (which queues it on the main thread) and wait up to `remaining` for it.
///
/// The closure and a caller that times out race through ONE compare-and-swap: the closure only
/// runs if it moves Queued -> Running first, and the caller only reports a timeout if it moves
/// Queued -> Abandoned first. So a timeout error always means the work never happened and never
/// will — a state-mutating op (a resize, move, close, title change or eval) cannot apply after
/// the caller already saw the error and moved on. A closure that started just before the
/// deadline is waited for (up to `grace`) and its real outcome returned, instead of "timed out"
/// for work that ran.
fn dispatch_and_wait<T, F>(
    what: &str,
    remaining: std::time::Duration,
    grace: std::time::Duration,
    post: impl FnOnce(Box<dyn FnOnce() + Send>) -> Result<(), String>,
    f: F,
) -> Result<T, String>
where
    T: Send + 'static,
    F: FnOnce() -> T + Send + 'static,
{
    use std::sync::atomic::{AtomicU8, Ordering};
    use std::sync::mpsc::RecvTimeoutError;

    let (tx, rx) = std::sync::mpsc::channel();
    let state = std::sync::Arc::new(AtomicU8::new(JOB_QUEUED));
    let job_state = std::sync::Arc::clone(&state);
    post(Box::new(move || {
        if job_state
            .compare_exchange(JOB_QUEUED, JOB_RUNNING, Ordering::AcqRel, Ordering::Acquire)
            .is_err()
        {
            return;
        }
        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f));
        // Send only fails if the caller already gave up and dropped the receiver — ignore.
        let _ = tx.send(result);
    }))?;

    let outcome = match rx.recv_timeout(remaining) {
        Ok(outcome) => outcome,
        Err(RecvTimeoutError::Disconnected) => {
            return Err(format!(
                "{what} did not complete on the main thread: the event loop dropped it"
            ));
        }
        Err(RecvTimeoutError::Timeout) => {
            if state
                .compare_exchange(
                    JOB_QUEUED,
                    JOB_ABANDONED,
                    Ordering::AcqRel,
                    Ordering::Acquire,
                )
                .is_ok()
            {
                return Err(format!(
                    "{what} did not complete on the main thread: timed out before it started \
                     (it will not run)"
                ));
            }
            // It started before we gave up: its effects will happen, so report its outcome.
            rx.recv_timeout(grace).map_err(|_| {
                format!(
                    "{what} started on the main thread but did not finish in time; its outcome \
                     is unknown"
                )
            })?
        }
    };
    outcome.map_err(|_panic| format!("{what} panicked on the main thread"))
}

impl<R: Runtime> WebviewBridge for tauri::AppHandle<R> {
    fn eval_webview(&self, label: Option<&str>, script: &str) -> Result<(), String> {
        let label = label.map(str::to_string);
        let script = script.to_string();
        on_main(self, "eval_webview", move |app| {
            let windows = app.webview_windows();
            let webview = find_window(&windows, label.as_deref())?;
            webview.eval(&script).map_err(|e| e.to_string())
        })?
    }

    fn get_window_states(&self, label: Option<&str>) -> Vec<WindowState> {
        // An empty Vec here means the main-thread dispatch failed/timed out (a wedged UI), not
        // "no windows" — log it so that case is diagnosable rather than silently indistinguishable.
        self.try_get_window_states(label).unwrap_or_else(|e| {
            tracing::warn!("get_window_states: {e}");
            Vec::new()
        })
    }

    fn try_get_window_states(&self, label: Option<&str>) -> Result<Vec<WindowState>, String> {
        let label = label.map(str::to_string);
        on_main(self, "get_window_states", move |app| {
            let windows = app.webview_windows();
            let mut states = Vec::new();

            for (win_label, window) in &windows {
                if let Some(filter) = label.as_deref()
                    && win_label != filter
                {
                    continue;
                }

                let pos = window.outer_position().unwrap_or_default();
                let size = window.inner_size().unwrap_or_default();

                states.push(
                    WindowState::new(win_label.clone())
                        .with_title(window.title().unwrap_or_default())
                        .with_url(window.url().map(|u| u.to_string()).unwrap_or_default())
                        .with_visible(window.is_visible().unwrap_or(false))
                        .with_focused(window.is_focused().unwrap_or(false))
                        .with_maximized(window.is_maximized().unwrap_or(false))
                        .with_minimized(window.is_minimized().unwrap_or(false))
                        .with_fullscreen(window.is_fullscreen().unwrap_or(false))
                        .with_position(pos.x, pos.y)
                        .with_size(size.width, size.height),
                );
            }

            states
        })
    }

    fn list_window_labels(&self) -> Vec<String> {
        self.try_list_window_labels().unwrap_or_else(|e| {
            tracing::warn!("list_window_labels: {e}");
            Vec::new()
        })
    }

    fn try_list_window_labels(&self) -> Result<Vec<String>, String> {
        on_main(self, "list_window_labels", |app| {
            app.webview_windows().keys().cloned().collect()
        })
    }

    fn eval_webview_resolved(&self, label: Option<&str>, script: &str) -> Result<String, String> {
        let label = label.map(str::to_string);
        let script = script.to_string();
        on_main(self, "eval_webview", move |app| {
            let windows = app.webview_windows();
            let webview = find_window(&windows, label.as_deref())?;
            webview.eval(&script).map_err(|e| e.to_string())?;
            Ok(webview.label().to_string())
        })?
    }

    fn get_native_handle(&self, label: Option<&str>) -> Result<isize, String> {
        let label = label.map(str::to_string);
        on_main(self, "get_native_handle", move |app| {
            use raw_window_handle::{HasWindowHandle, RawWindowHandle};

            let windows = app.webview_windows();
            let _webview = find_window(&windows, label.as_deref())?;
            let handle = _webview.window_handle().map_err(|e| e.to_string())?;
            match handle.as_raw() {
                #[cfg(windows)]
                RawWindowHandle::Win32(h) => Ok(h.hwnd.get()),
                #[cfg(target_os = "macos")]
                RawWindowHandle::AppKit(h) => {
                    // CGWindowListCreateImage needs CGWindowID (the window number),
                    // not the NSView pointer. Extract via Objective-C runtime.
                    macos_window_number(h.ns_view.as_ptr())
                }
                #[cfg(target_os = "linux")]
                RawWindowHandle::Xlib(h) => Ok(h.window as isize),
                #[cfg(target_os = "linux")]
                RawWindowHandle::Xcb(h) => Ok(h.window.get() as isize),
                _ => Err("unsupported window handle type on this platform".to_string()),
            }
        })?
    }

    #[cfg(windows)]
    fn native_type_text(&self, label: Option<&str>, text: &str) -> Result<(), String> {
        let hwnd = self.get_native_handle(label)?;
        win_focus(hwnd)?;
        win_send_text(text)
    }

    #[cfg(windows)]
    fn native_key(&self, label: Option<&str>, key: &str) -> Result<(), String> {
        let hwnd = self.get_native_handle(label)?;
        win_focus(hwnd)?;
        win_send_key(key)
    }

    #[cfg(windows)]
    fn native_click(&self, label: Option<&str>, x: f64, y: f64) -> Result<(), String> {
        let hwnd = self.get_native_handle(label)?;
        win_focus(hwnd)?;
        win_click(hwnd, x, y)
    }

    fn manage_window(&self, label: Option<&str>, action: &str) -> Result<String, String> {
        let label = label.map(str::to_string);
        let action = action.to_string();
        on_main(self, "manage_window", move |app| {
            let windows = app.webview_windows();
            let window = find_window(&windows, label.as_deref())?;

            match action.as_str() {
                "minimize" => window.minimize().map_err(|e| e.to_string())?,
                "unminimize" => window.unminimize().map_err(|e| e.to_string())?,
                "maximize" => window.maximize().map_err(|e| e.to_string())?,
                "unmaximize" => window.unmaximize().map_err(|e| e.to_string())?,
                "close" => window.close().map_err(|e| e.to_string())?,
                "focus" => window.set_focus().map_err(|e| e.to_string())?,
                "show" => window.show().map_err(|e| e.to_string())?,
                "hide" => window.hide().map_err(|e| e.to_string())?,
                "fullscreen" => window.set_fullscreen(true).map_err(|e| e.to_string())?,
                "unfullscreen" => window.set_fullscreen(false).map_err(|e| e.to_string())?,
                "always_on_top" => window.set_always_on_top(true).map_err(|e| e.to_string())?,
                "not_always_on_top" => {
                    window.set_always_on_top(false).map_err(|e| e.to_string())?;
                }
                _ => return Err(format!("unknown action: {action}")),
            }

            Ok(format!("{action} executed"))
        })?
    }

    fn resize_window(&self, label: Option<&str>, width: u32, height: u32) -> Result<(), String> {
        let label = label.map(str::to_string);
        on_main(self, "resize_window", move |app| {
            let windows = app.webview_windows();
            let window = find_window(&windows, label.as_deref())?;

            window
                .set_size(tauri::LogicalSize::new(width, height))
                .map_err(|e| e.to_string())
        })?
    }

    fn move_window(&self, label: Option<&str>, x: i32, y: i32) -> Result<(), String> {
        let label = label.map(str::to_string);
        on_main(self, "move_window", move |app| {
            let windows = app.webview_windows();
            let window = find_window(&windows, label.as_deref())?;

            window
                .set_position(tauri::LogicalPosition::new(x, y))
                .map_err(|e| e.to_string())
        })?
    }

    fn set_window_title(&self, label: Option<&str>, title: &str) -> Result<(), String> {
        let label = label.map(str::to_string);
        let title = title.to_string();
        on_main(self, "set_window_title", move |app| {
            let windows = app.webview_windows();
            let window = find_window(&windows, label.as_deref())?;

            window.set_title(&title).map_err(|e| e.to_string())
        })?
    }

    fn app_data_dir(&self) -> Result<std::path::PathBuf, String> {
        self.path().app_data_dir().map_err(|e| e.to_string())
    }

    fn app_config_dir(&self) -> Result<std::path::PathBuf, String> {
        self.path().app_config_dir().map_err(|e| e.to_string())
    }

    fn app_log_dir(&self) -> Result<std::path::PathBuf, String> {
        self.path().app_log_dir().map_err(|e| e.to_string())
    }

    fn app_local_data_dir(&self) -> Result<std::path::PathBuf, String> {
        self.path().app_local_data_dir().map_err(|e| e.to_string())
    }

    fn tauri_config(&self) -> serde_json::Value {
        let config = self.config();

        let windows: Vec<serde_json::Value> = config
            .app
            .windows
            .iter()
            .map(|w| {
                serde_json::json!({
                    "label": w.label,
                    "title": w.title,
                    "url": format!("{}", w.url),
                    "width": w.width,
                    "height": w.height,
                    "visible": w.visible,
                    "resizable": w.resizable,
                    "fullscreen": w.fullscreen,
                    "decorations": w.decorations,
                    "transparent": w.transparent,
                    "always_on_top": w.always_on_top,
                })
            })
            .collect();

        let plugins: Vec<String> = config.plugins.0.keys().cloned().collect();

        let security = serde_json::json!({
            "csp": config.app.security.csp.as_ref().map(|c| format!("{c}")),
            "freeze_prototype": config.app.security.freeze_prototype,
            "capabilities": config.app.security.capabilities.iter().map(|c| {
                match c {
                    tauri::utils::config::CapabilityEntry::Inlined(cap) => {
                        serde_json::json!({
                            "identifier": cap.identifier,
                            "description": cap.description,
                            "windows": cap.windows,
                            "webviews": cap.webviews,
                            "permissions": cap.permissions.iter().map(|p| format!("{p:?}")).collect::<Vec<_>>(),
                            "platforms": cap.platforms,
                        })
                    }
                    tauri::utils::config::CapabilityEntry::Reference(path) => {
                        serde_json::json!({ "reference": path })
                    }
                }
            }).collect::<Vec<_>>(),
        });

        serde_json::json!({
            "identifier": config.identifier,
            "product_name": config.product_name,
            "version": config.version,
            "windows": windows,
            "plugins": plugins,
            "security": security,
        })
    }
}

#[cfg(target_os = "macos")]
#[allow(unsafe_code)]
fn macos_window_number(ns_view: *mut std::ffi::c_void) -> Result<isize, String> {
    unsafe extern "C" {
        fn objc_msgSend(obj: *mut std::ffi::c_void, sel: *mut std::ffi::c_void) -> isize;
        fn sel_registerName(name: *const std::ffi::c_char) -> *mut std::ffi::c_void;
    }

    if ns_view.is_null() {
        return Err("null NSView handle".to_string());
    }

    // SAFETY: `ns_view` is a valid NSView pointer obtained from Tauri's
    // `with_webview` callback; null was checked above. `objc_msgSend` and
    // `sel_registerName` are stable Objective-C runtime ABI.
    unsafe {
        let sel_window = sel_registerName(c"window".as_ptr());
        let ns_window = objc_msgSend(ns_view, sel_window);
        if ns_window == 0 {
            return Err("NSView has no parent NSWindow".to_string());
        }
        let sel_window_number = sel_registerName(c"windowNumber".as_ptr());
        let ns_window_ptr = ns_window as *mut std::ffi::c_void;
        let window_number = objc_msgSend(ns_window_ptr, sel_window_number);
        if window_number <= 0 {
            return Err(format!("invalid CGWindowID: {window_number}"));
        }
        Ok(window_number)
    }
}

// ── Windows native (trusted) input helpers ─────────────────────────────────
//
// These deliver real OS input via SendInput, producing events with
// `isTrusted: true` (unlike the JS bridge's synthetic events).

#[cfg(windows)]
fn win_hwnd(hwnd: isize) -> windows::Win32::Foundation::HWND {
    windows::Win32::Foundation::HWND(hwnd as *mut core::ffi::c_void)
}

/// `SendInput` goes to whatever window has the foreground, not to a window we name: trusted
/// input may only be sent once the target's top-level window IS the foreground window.
#[cfg(any(windows, test))]
fn foreground_verdict(target_root: isize, foreground_root: isize) -> Result<(), String> {
    if target_root != 0 && target_root == foreground_root {
        Ok(())
    } else {
        Err(
            "refusing trusted input: the app window could not be brought to the foreground \
             (Windows' foreground lock keeps focus with the app the user is working in, e.g. a \
             terminal), so the keystrokes or click would go to that app instead. Bring the app \
             window to the front and retry, or omit `trusted` to use synthetic input."
                .to_string(),
        )
    }
}

/// A trusted click lands on whatever window is topmost at the point: it must be the target.
#[cfg(any(windows, test))]
fn click_target_verdict(target_root: isize, point_root: isize) -> Result<(), String> {
    if target_root != 0 && target_root == point_root {
        Ok(())
    } else {
        Err(
            "refusing trusted click: the point is covered by another window (or lies outside \
             this one), so the click would land there. Make the element visible on screen and \
             retry, or omit `trusted` to use a synthetic click."
                .to_string(),
        )
    }
}

/// A trusted click must land inside the target window's CLIENT area (physical pixels, client
/// coordinates). Checking only that the point's top-level window is ours accepted the title
/// bar, the caption buttons (close!) and the resize border, all of which belong to the same
/// top-level window (R4-IN2). Non-finite coordinates are refused before any `as i32` cast,
/// which would turn `NaN` into 0 and saturate huge values.
#[cfg(any(windows, test))]
fn client_point_verdict(x: f64, y: f64, client_w: i32, client_h: i32) -> Result<(), String> {
    let inside = x.is_finite()
        && y.is_finite()
        && x >= 0.0
        && y >= 0.0
        && x < f64::from(client_w)
        && y < f64::from(client_h);
    if inside {
        Ok(())
    } else {
        Err(format!(
            "refusing trusted click: ({x}, {y}) lies outside the window's content area \
             ({client_w}x{client_h} physical px), so it would land on the title bar, a caption \
             button or the border. Scroll the element into view and retry, or omit `trusted` to \
             use a synthetic click."
        ))
    }
}

/// The top-level window `hwnd` belongs to (0 for none).
#[allow(unsafe_code)]
#[cfg(windows)]
fn win_root(hwnd: windows::Win32::Foundation::HWND) -> isize {
    use windows::Win32::UI::WindowsAndMessaging::{GA_ROOT, GetAncestor};
    // SAFETY: GetAncestor accepts any HWND (including null) and returns null when there is none.
    unsafe { GetAncestor(hwnd, GA_ROOT) }.0 as isize
}

/// Bring the target window to the foreground so input is routed to it, and verify it got
/// there. `SetForegroundWindow` is refused while the user is active in another app (Windows'
/// foreground lock); ignoring that sent the agent's keystrokes — Enter included — into the
/// developer's terminal.
#[allow(unsafe_code)]
#[cfg(windows)]
fn win_focus(hwnd: isize) -> Result<(), String> {
    use windows::Win32::UI::WindowsAndMessaging::{GetForegroundWindow, SetForegroundWindow};
    let target = win_hwnd(hwnd);
    let target_root = win_root(target);
    // SAFETY: hwnd comes from Tauri's window handle; SetForegroundWindow is safe
    // to call with any HWND (returns false if it fails).
    unsafe {
        let _ = SetForegroundWindow(target);
    }
    // Give the OS a brief moment to apply focus, then poll briefly for it to take.
    std::thread::sleep(std::time::Duration::from_millis(40));
    let mut verdict = Ok(());
    for _ in 0..8 {
        // SAFETY: GetForegroundWindow takes no arguments and may return null.
        verdict = foreground_verdict(target_root, win_root(unsafe { GetForegroundWindow() }));
        if verdict.is_ok() {
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(20));
    }
    verdict
}

#[cfg(windows)]
fn win_keyboard_input(
    vk: u16,
    scan: u16,
    key_up: bool,
    unicode: bool,
) -> windows::Win32::UI::Input::KeyboardAndMouse::INPUT {
    use windows::Win32::UI::Input::KeyboardAndMouse::{
        INPUT, INPUT_0, INPUT_KEYBOARD, KEYBD_EVENT_FLAGS, KEYBDINPUT, KEYEVENTF_KEYUP,
        KEYEVENTF_UNICODE, VIRTUAL_KEY,
    };
    let mut flags = KEYBD_EVENT_FLAGS(0);
    if unicode {
        flags |= KEYEVENTF_UNICODE;
    }
    if key_up {
        flags |= KEYEVENTF_KEYUP;
    }
    INPUT {
        r#type: INPUT_KEYBOARD,
        Anonymous: INPUT_0 {
            ki: KEYBDINPUT {
                wVk: VIRTUAL_KEY(vk),
                wScan: scan,
                dwFlags: flags,
                time: 0,
                dwExtraInfo: 0,
            },
        },
    }
}

/// Type Unicode text via `SendInput` (`KEYEVENTF_UNICODE` per UTF-16 code unit).
#[allow(unsafe_code)]
#[cfg(windows)]
fn win_send_text(text: &str) -> Result<(), String> {
    use windows::Win32::UI::Input::KeyboardAndMouse::{INPUT, SendInput};
    let mut inputs: Vec<INPUT> = Vec::new();
    for unit in text.encode_utf16() {
        inputs.push(win_keyboard_input(0, unit, false, true));
        inputs.push(win_keyboard_input(0, unit, true, true));
    }
    if inputs.is_empty() {
        return Ok(());
    }
    let cb = i32::try_from(std::mem::size_of::<INPUT>()).unwrap_or(0);
    // SAFETY: `inputs` is a valid slice of properly-initialized INPUT structs.
    let sent = unsafe { SendInput(&inputs, cb) } as usize;
    if sent == inputs.len() {
        Ok(())
    } else {
        Err(format!(
            "SendInput delivered {sent}/{} key events",
            inputs.len()
        ))
    }
}

/// Map a named key (Playwright-style) to a Win32 virtual-key code.
#[cfg(windows)]
fn win_vk_for_key(key: &str) -> Option<u16> {
    use windows::Win32::UI::Input::KeyboardAndMouse as k;
    let vk = match key {
        "Enter" | "Return" => k::VK_RETURN,
        "Tab" => k::VK_TAB,
        "Escape" | "Esc" => k::VK_ESCAPE,
        "Backspace" => k::VK_BACK,
        "Delete" | "Del" => k::VK_DELETE,
        "ArrowUp" | "Up" => k::VK_UP,
        "ArrowDown" | "Down" => k::VK_DOWN,
        "ArrowLeft" | "Left" => k::VK_LEFT,
        "ArrowRight" | "Right" => k::VK_RIGHT,
        "Home" => k::VK_HOME,
        "End" => k::VK_END,
        "PageUp" => k::VK_PRIOR,
        "PageDown" => k::VK_NEXT,
        "Space" | " " => k::VK_SPACE,
        "F1" => k::VK_F1,
        "F2" => k::VK_F2,
        "F3" => k::VK_F3,
        "F4" => k::VK_F4,
        "F5" => k::VK_F5,
        "F6" => k::VK_F6,
        "F7" => k::VK_F7,
        "F8" => k::VK_F8,
        "F9" => k::VK_F9,
        "F10" => k::VK_F10,
        "F11" => k::VK_F11,
        "F12" => k::VK_F12,
        _ => return None,
    };
    Some(vk.0)
}

/// Press and release a named key, or a single printable character, via `SendInput`.
#[allow(unsafe_code)]
#[cfg(windows)]
fn win_send_key(key: &str) -> Result<(), String> {
    use windows::Win32::UI::Input::KeyboardAndMouse::{INPUT, SendInput};
    let inputs: Vec<INPUT> = if let Some(vk) = win_vk_for_key(key) {
        vec![
            win_keyboard_input(vk, 0, false, false),
            win_keyboard_input(vk, 0, true, false),
        ]
    } else {
        // Single printable character → send as Unicode.
        let mut chars = key.chars();
        let (Some(c), None) = (chars.next(), chars.next()) else {
            return Err(format!(
                "unknown key '{key}' (use a named key or a single character)"
            ));
        };
        let mut buf = [0u16; 2];
        let mut v = Vec::new();
        for unit in c.encode_utf16(&mut buf) {
            v.push(win_keyboard_input(0, *unit, false, true));
            v.push(win_keyboard_input(0, *unit, true, true));
        }
        v
    };
    let cb = i32::try_from(std::mem::size_of::<INPUT>()).unwrap_or(0);
    // SAFETY: valid slice of initialized INPUT structs.
    let sent = unsafe { SendInput(&inputs, cb) } as usize;
    if sent == inputs.len() {
        Ok(())
    } else {
        Err(format!(
            "SendInput delivered {sent}/{} key events",
            inputs.len()
        ))
    }
}

/// Click at logical (CSS-pixel) coordinates within the window's content area
/// via an absolute-positioned `SendInput` mouse sequence (move + down + up).
#[allow(unsafe_code)]
#[cfg(windows)]
fn win_click(hwnd: isize, x: f64, y: f64) -> Result<(), String> {
    use windows::Win32::Foundation::POINT;
    use windows::Win32::Foundation::RECT;
    use windows::Win32::Graphics::Gdi::ClientToScreen;
    use windows::Win32::UI::HiDpi::GetDpiForWindow;
    use windows::Win32::UI::Input::KeyboardAndMouse::{
        INPUT, INPUT_0, INPUT_MOUSE, MOUSE_EVENT_FLAGS, MOUSEEVENTF_ABSOLUTE, MOUSEEVENTF_LEFTDOWN,
        MOUSEEVENTF_LEFTUP, MOUSEEVENTF_MOVE, MOUSEEVENTF_VIRTUALDESK, MOUSEINPUT, SendInput,
    };
    use windows::Win32::UI::WindowsAndMessaging::{
        GetClientRect, GetSystemMetrics, SM_CXVIRTUALSCREEN, SM_CYVIRTUALSCREEN, SM_XVIRTUALSCREEN,
        SM_YVIRTUALSCREEN, WindowFromPoint,
    };
    let h = win_hwnd(hwnd);
    // SAFETY: GetDpiForWindow/GetClientRect/GetSystemMetrics/ClientToScreen are safe to call
    // with a valid HWND; GetClientRect and ClientToScreen write into our stack RECT/POINT.
    let (nx, ny) = unsafe {
        let dpi = GetDpiForWindow(h);
        let scale = if dpi == 0 { 1.0 } else { f64::from(dpi) / 96.0 };
        let (px, py) = (x * scale, y * scale);
        // Client coordinates: the client rect's origin is always (0, 0).
        let mut client = RECT::default();
        GetClientRect(h, &mut client)
            .map_err(|e| format!("refusing trusted click: cannot read the client area: {e}"))?;
        client_point_verdict(px, py, client.right, client.bottom)?;
        let mut pt = POINT {
            x: px as i32,
            y: py as i32,
        };
        let _ = ClientToScreen(h, &mut pt);
        // The click goes to the topmost window at the point, whichever app that is.
        click_target_verdict(win_root(h), win_root(WindowFromPoint(pt)))?;
        let vx = GetSystemMetrics(SM_XVIRTUALSCREEN);
        let vy = GetSystemMetrics(SM_YVIRTUALSCREEN);
        let vw = GetSystemMetrics(SM_CXVIRTUALSCREEN);
        let vh = GetSystemMetrics(SM_CYVIRTUALSCREEN);
        if vw <= 1 || vh <= 1 {
            return Err("virtual screen metrics unavailable".to_string());
        }
        let nx = ((f64::from(pt.x - vx)) * 65535.0 / f64::from(vw - 1)) as i32;
        let ny = ((f64::from(pt.y - vy)) * 65535.0 / f64::from(vh - 1)) as i32;
        (nx, ny)
    };
    let make = |flags: MOUSE_EVENT_FLAGS| INPUT {
        r#type: INPUT_MOUSE,
        Anonymous: INPUT_0 {
            mi: MOUSEINPUT {
                dx: nx,
                dy: ny,
                mouseData: 0,
                dwFlags: flags,
                time: 0,
                dwExtraInfo: 0,
            },
        },
    };
    let base = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_VIRTUALDESK;
    let inputs = [
        make(base | MOUSEEVENTF_MOVE),
        make(base | MOUSEEVENTF_LEFTDOWN),
        make(base | MOUSEEVENTF_LEFTUP),
    ];
    let cb = i32::try_from(std::mem::size_of::<INPUT>()).unwrap_or(0);
    // SAFETY: valid slice of initialized INPUT structs.
    let sent = unsafe { SendInput(&inputs, cb) } as usize;
    if sent == inputs.len() {
        Ok(())
    } else {
        Err(format!(
            "SendInput delivered {sent}/{} mouse events",
            inputs.len()
        ))
    }
}

#[cfg(test)]
mod tests {
    use super::{dispatch_and_wait, is_main_thread, record_main_thread};
    use std::sync::Arc;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::time::Duration;

    /// A stand-in main thread that starts each posted job after `delay`.
    fn post_after(delay: Duration) -> impl FnOnce(Box<dyn FnOnce() + Send>) -> Result<(), String> {
        move |job| {
            std::thread::spawn(move || {
                std::thread::sleep(delay);
                job();
            });
            Ok(())
        }
    }

    /// A stand-in main thread that is guaranteed to have STARTED the posted job before `post`
    /// returns (and so before the caller's deadline starts counting): it waits for the job to
    /// signal `started`. A plain spawned thread can be scheduled late on a loaded machine, and
    /// the caller then (correctly) abandons a job that never started — which turned tests
    /// about a job that outlives its caller into flakes.
    fn post_started(
        started: std::sync::mpsc::Receiver<()>,
    ) -> impl FnOnce(Box<dyn FnOnce() + Send>) -> Result<(), String> {
        move |job| {
            std::thread::spawn(job);
            started
                .recv_timeout(Duration::from_secs(60))
                .map_err(|_| "the stand-in main thread never started the job".to_string())
        }
    }

    #[test]
    fn a_job_still_queued_at_the_deadline_never_runs() {
        let ran = Arc::new(AtomicUsize::new(0));
        let r = Arc::clone(&ran);
        let out = dispatch_and_wait(
            "resize_window",
            Duration::from_millis(50),
            Duration::from_secs(5),
            post_after(Duration::from_millis(300)),
            move || r.fetch_add(1, Ordering::SeqCst),
        );
        assert!(out.unwrap_err().contains("will not run"));
        std::thread::sleep(Duration::from_millis(500));
        assert_eq!(ran.load(Ordering::SeqCst), 0, "an abandoned job ran anyway");
    }

    #[test]
    fn a_job_running_at_the_deadline_reports_its_real_outcome() {
        // It started before the caller gave up, so its effects happen: reporting "timed out"
        // would tell the caller a window change / eval did not happen when it did.
        let (started_tx, started_rx) = std::sync::mpsc::channel();
        let out = dispatch_and_wait(
            "eval_webview",
            Duration::from_millis(50),
            Duration::from_secs(5),
            post_started(started_rx),
            move || {
                let _ = started_tx.send(());
                std::thread::sleep(Duration::from_millis(300));
                7
            },
        );
        assert_eq!(out, Ok(7));
    }

    #[test]
    fn trusted_input_is_refused_unless_the_target_is_in_front() {
        use super::{click_target_verdict, foreground_verdict};
        assert!(foreground_verdict(0x42, 0x42).is_ok());
        let other = foreground_verdict(0x42, 0x99).unwrap_err();
        assert!(other.contains("foreground"), "{other}");
        assert!(foreground_verdict(0x42, 0).is_err(), "no foreground window");
        assert!(foreground_verdict(0, 0).is_err(), "unknown target window");
        assert!(click_target_verdict(0x42, 0x42).is_ok());
        assert!(
            click_target_verdict(0x42, 0x99)
                .unwrap_err()
                .contains("covered")
        );
        assert!(click_target_verdict(0, 0).is_err());
    }

    fn leaked_gate() -> &'static super::DispatchGate {
        Box::leak(Box::new(super::DispatchGate::new()))
    }

    /// R4-LOCK1: a round trip whose closure STARTED but outlived timeout + grace returned
    /// "outcome unknown" and released the dispatch lock while the closure was still running on
    /// the main thread — so the next caller put a second round trip in flight beside it, the
    /// exact condition `MAIN_DISPATCH_LOCK` exists to prevent (`WebKitGTK` heap corruption).
    #[test]
    fn a_job_outliving_its_caller_blocks_the_next_round_trip_until_it_finishes() {
        use super::serialized_round_trip;
        use std::time::Instant;
        let gate = leaked_gate();
        let first_end = Arc::new(std::sync::Mutex::new(None::<Instant>));
        let fe = Arc::clone(&first_end);
        // The first job is known to have started before its caller's deadline, and it runs
        // until released — no sleep decides either (both used to race a loaded scheduler).
        let (started_tx, started_rx) = std::sync::mpsc::channel();
        let (release_tx, release_rx) = std::sync::mpsc::channel::<()>();
        let first = serialized_round_trip(
            gate,
            "first",
            Duration::from_millis(50),
            post_started(started_rx),
            move || {
                let _ = started_tx.send(());
                let _ = release_rx.recv();
                *fe.lock().unwrap() = Some(Instant::now());
            },
        );
        assert!(
            first.unwrap_err().contains("outcome is unknown"),
            "precondition: the first caller gave up while its job was running"
        );
        // Release the first job only once the second caller holds the dispatch lock — it is
        // then provably waiting on the still-running job, not merely about to start.
        let releaser = std::thread::spawn(move || {
            while gate.lock.try_lock().is_ok() {
                std::thread::sleep(Duration::from_millis(1));
            }
            std::thread::sleep(Duration::from_millis(20));
            release_tx.send(()).unwrap();
        });
        let second_start = serialized_round_trip(
            gate,
            "second",
            Duration::from_secs(5),
            post_after(Duration::ZERO),
            Instant::now,
        )
        .expect("the second round trip runs once the first job is done");
        releaser.join().unwrap();
        let first_end = first_end
            .lock()
            .unwrap()
            .expect("the first job finished before the second started");
        assert!(
            second_start >= first_end,
            "second round trip started {:?} before the abandoned first job finished",
            first_end - second_start
        );
    }

    /// The wait for an earlier caller's still-running job is bounded by the caller's OWN
    /// deadline (no N * timeout stacking), and a caller that gives up never runs its job.
    #[test]
    fn waiting_for_an_abandoned_job_is_bounded_by_the_callers_deadline() {
        use super::serialized_round_trip;
        let gate = leaked_gate();
        let (started_tx, started_rx) = std::sync::mpsc::channel();
        let first = serialized_round_trip(
            gate,
            "first",
            Duration::from_millis(30),
            post_started(started_rx),
            move || {
                let _ = started_tx.send(());
                std::thread::sleep(Duration::from_millis(1500));
            },
        );
        assert!(first.unwrap_err().contains("outcome is unknown"));
        let ran = Arc::new(AtomicUsize::new(0));
        let r = Arc::clone(&ran);
        let started = std::time::Instant::now();
        let second = serialized_round_trip(
            gate,
            "second",
            Duration::from_millis(200),
            post_after(Duration::ZERO),
            move || r.fetch_add(1, Ordering::SeqCst),
        );
        let waited = started.elapsed();
        let err = second.unwrap_err();
        assert!(err.contains("still running"), "{err}");
        assert!(waited < Duration::from_millis(1000), "waited {waited:?}");
        std::thread::sleep(Duration::from_millis(1600));
        assert_eq!(
            ran.load(Ordering::SeqCst),
            0,
            "a caller that gave up ran its job"
        );
    }

    /// R4-IN2: a trusted click was only checked for landing on OUR top-level window — which
    /// includes its title bar and close button. It must land inside the client area.
    #[test]
    fn trusted_click_must_land_inside_the_client_area() {
        use super::client_point_verdict;
        assert!(client_point_verdict(0.0, 0.0, 800, 600).is_ok());
        assert!(client_point_verdict(799.9, 599.9, 800, 600).is_ok());
        for (x, y) in [
            (-1.0, 10.0),  // left of the client area (window border)
            (10.0, -30.0), // above it: the title bar / caption buttons
            (800.0, 10.0), // right edge is exclusive
            (10.0, 600.0),
            (f64::NAN, 10.0), // `NaN as i32` is 0: would silently click the corner
            (10.0, f64::INFINITY),
            (1e12, 10.0), // `as i32` saturates to i32::MAX
        ] {
            let err = client_point_verdict(x, y, 800, 600).unwrap_err();
            assert!(err.contains("outside"), "({x}, {y}): {err}");
        }
        assert!(
            client_point_verdict(0.0, 0.0, 0, 0).is_err(),
            "empty client area"
        );
    }

    #[test]
    fn a_panicking_job_is_an_error_not_a_hang() {
        let out: Result<(), String> = dispatch_and_wait(
            "get_native_handle",
            Duration::from_secs(5),
            Duration::from_secs(5),
            post_after(Duration::ZERO),
            || panic!("boom"),
        );
        assert!(out.unwrap_err().contains("panicked"));
    }

    /// A stand-in Tauri main thread: runs posted jobs in order, inline when posted from itself
    /// (exactly what tauri-runtime-wry's `send_user_message` does).
    struct FakeMainThread {
        jobs: std::sync::mpsc::Sender<Box<dyn FnOnce() + Send>>,
        id: std::thread::ThreadId,
    }

    impl FakeMainThread {
        fn start() -> Self {
            let (jobs, rx) = std::sync::mpsc::channel::<Box<dyn FnOnce() + Send>>();
            let (id_tx, id_rx) = std::sync::mpsc::channel();
            std::thread::spawn(move || {
                id_tx.send(std::thread::current().id()).unwrap();
                while let Ok(job) = rx.recv() {
                    job();
                }
            });
            Self {
                jobs,
                id: id_rx.recv().unwrap(),
            }
        }

        fn post(&self) -> impl Fn(Box<dyn FnOnce() + Send>) -> Result<(), String> + '_ {
            move |job| {
                if std::thread::current().id() == self.id {
                    job();
                    Ok(())
                } else {
                    self.jobs.send(job).map_err(|e| e.to_string())
                }
            }
        }

        /// Run `f` on the fake main thread and wait for it.
        fn run<T: Send + 'static>(&self, f: impl FnOnce() -> T + Send + 'static) -> T {
            let (tx, rx) = std::sync::mpsc::channel();
            self.jobs
                .send(Box::new(move || tx.send(f()).unwrap()))
                .unwrap();
            rx.recv().unwrap()
        }
    }

    type Adopted = Arc<std::sync::Mutex<Vec<(std::thread::ThreadId, String)>>>;

    fn recording_adopt(log: &Adopted) -> impl Fn(&String) + Send + 'static {
        let log = Arc::clone(log);
        move |h: &String| {
            log.lock()
                .unwrap()
                .push((std::thread::current().id(), h.clone()));
        }
    }

    /// R5B-MAIN1: Tauri lets an app register a plugin later from a background thread
    /// (`AppHandle::plugin`), and then the plugin's `setup` runs THERE. Recording that thread as
    /// "main" and installing the handle in its thread-local left every later `on_main` round
    /// trip failing with "the main-thread app handle is not installed". Adoption must happen on
    /// the real main thread.
    #[test]
    fn setup_off_the_main_thread_adopts_the_real_main_thread() {
        let main = FakeMainThread::start();
        let log: Adopted = Arc::default();
        let handle = "app".to_string();
        let outcome = super::adopt_on_main(&handle, main.post(), recording_adopt(&log));
        assert_eq!(outcome, Ok(super::MainThreadAdoption::Posted));
        // The posted adoption runs before anything posted after it.
        main.run(|| ());
        let adopted = log.lock().unwrap().clone();
        assert_eq!(adopted, vec![(main.id, "app".to_string())]);
    }

    /// The normal case — setup on the main thread — adopts in place, before returning.
    #[test]
    fn setup_on_the_main_thread_adopts_inline() {
        let main = Arc::new(FakeMainThread::start());
        let log: Adopted = Arc::default();
        let (m, l) = (Arc::clone(&main), Arc::clone(&log));
        let outcome = main.run(move || {
            let outcome = super::adopt_on_main(&"app".to_string(), m.post(), recording_adopt(&l));
            // Adopted before `adopt_on_main` returned, not merely queued.
            let adopted_now = l.lock().unwrap().len();
            (outcome, adopted_now)
        });
        assert_eq!(outcome, (Ok(super::MainThreadAdoption::Inline), 1));
        assert_eq!(log.lock().unwrap()[0].0, main.id);
    }

    #[test]
    fn main_thread_is_recorded_once_and_only_that_thread_matches() {
        // Record from a dedicated thread (standing in for Tauri's setup thread): only that
        // thread is "main"; every other thread — including this test's — is not.
        std::thread::spawn(|| {
            record_main_thread();
            assert!(is_main_thread(), "the recording thread is the main thread");
        })
        .join()
        .unwrap();
        assert!(
            !is_main_thread(),
            "a different thread must not be treated as main"
        );
        std::thread::spawn(|| assert!(!is_main_thread()))
            .join()
            .unwrap();
        // A second record from another thread must not move it (set-once).
        std::thread::spawn(record_main_thread).join().unwrap();
        assert!(!is_main_thread());
    }
}