rsclaw-desktop 0.1.0

Desktop crate for RsClaw — internal workspace crate, not for direct use
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
//! Native desktop session backed by `enigo` (input) + `rsclaw-platform::capture`
//! (script-based screen capture + window enumeration; replaces xcap).
//!
//! Input synthesis runs inside `tokio::task::spawn_blocking` with a fresh
//! `Enigo` per call because `Enigo` is not `Send` on Windows. Screenshots
//! are similarly blocking.

use std::process::Command;

use base64::Engine;
use enigo::{
    Axis, Button, Coordinate,
    Direction::{Click, Press, Release},
    Enigo, Key, Keyboard, Mouse, Settings,
};
use rsclaw_platform::capture;
use tracing::warn;

use super::DesktopSession;

/// Unit struct — holds no state because every enigo call needs a fresh
/// instance on the calling OS thread.
pub struct NativeDesktopSession;

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Construct a fresh `Enigo` or return an error string.
fn new_enigo() -> Result<Enigo, String> {
    Enigo::new(&Settings::default()).map_err(|e| {
        let hint = if cfg!(target_os = "macos")
            && (e.to_string().contains("permission") || e.to_string().contains("simulate input"))
        {
            " (macOS: grant Accessibility + Input Monitoring in System Settings)"
        } else {
            ""
        };
        format!("enigo init failed: {e}{hint}")
    })
}

/// Pass coordinates through to enigo (enigo on macOS uses device-independent
/// points, the same unit returned by AppleScript `position`/`size`).
fn scale_for_input(x: u32, y: u32) -> (i32, i32) {
    (x as i32, y as i32)
}

/// Capture a region of the screen (logical points). Script-based capture grabs
/// exactly the requested rect, so no monitor enumeration / scale-crop needed.
fn capture_region(x: u32, y: u32, w: u32, h: u32) -> Result<String, String> {
    let png = capture::capture_region_png(x as i32, y as i32, w, h).map_err(|e| e.to_string())?;
    Ok(capture::png_to_data_uri(&png))
}

/// Count pixels in a screen region whose RGB is within `tol` (per channel) of
/// the target colour. Returns `(matching, total)`. The script capture returns
/// exactly the requested region (at native resolution), so we scan every pixel.
#[allow(clippy::too_many_arguments)]
fn region_color_count(
    x: u32,
    y: u32,
    w: u32,
    h: u32,
    r: u32,
    g: u32,
    b: u32,
    tol: u32,
) -> Result<(u32, u32), String> {
    let img = capture::capture_region_rgba(x as i32, y as i32, w, h).map_err(|e| e.to_string())?;
    let (tr, tg, tb, tol) = (r as i32, g as i32, b as i32, tol as i32);
    let mut count: u32 = 0;
    let mut total: u32 = 0;
    for px in img.pixels() {
        let [pr, pg, pb, _pa] = px.0;
        total += 1;
        if (pr as i32 - tr).abs() <= tol
            && (pg as i32 - tg).abs() <= tol
            && (pb as i32 - tb).abs() <= tol
        {
            count += 1;
        }
    }
    Ok((count, total))
}

/// Capture the full primary monitor (fallback when window bounds unavailable).
fn capture_primary_monitor() -> Result<String, String> {
    let png = capture::capture_full_png().map_err(|e| e.to_string())?;
    Ok(capture::png_to_data_uri(&png))
}

/// Capture an app window's content directly by window backing store
/// (`CGWindowListCreateImage` under xcap). Overlap-proof — works even when
/// other windows cover it and without bringing the app frontmost — and does
/// NOT trigger any app-side screenshot UI (so it never pollutes a chat input
/// box the way WeChat's Ctrl+Cmd+A capture does).
///
/// `Window::all()` is ordered front-to-back, so the first matching window is
/// the frontmost. Capturing the frontmost window lets one call serve both the
/// main window and a transient child window (e.g. WeChat's merged-record
/// viewer): when the child is open it is frontmost and gets captured;
/// otherwise the main window does. A 200x200 minimum filters out tooltips and
/// other tiny helper windows. Returns a PNG data URI.
/// Find the frontmost on-screen window of an app (≥200×200) via the script-based
/// window list. The list is front-to-back where the OS provides ordering, so the
/// first match is frontmost — letting one call serve both the main window and a
/// transient child (e.g. WeChat's merged-record viewer).
/// Virtual-screen rect (origin + size) via GetSystemMetrics — matches the area
/// `capture_full_png` grabs (System.Windows.Forms.SystemInformation.VirtualScreen).
/// Fast (no process spawn); used so the plugin's full-screen 0-1000 coords convert
/// to correct screen pixels. SM_*VIRTUALSCREEN = 76..79.
#[cfg(target_os = "windows")]
fn virtual_screen_rect() -> (i32, i32, u32, u32) {
    unsafe extern "system" {
        fn GetDC(h: isize) -> isize;
        fn ReleaseDC(h: isize, dc: isize) -> i32;
        fn GetDeviceCaps(dc: isize, index: i32) -> i32;
    }
    // PHYSICAL screen size (DESKTOPHORZRES=118 / DESKTOPVERTRES=117) — independent
    // of this process's DPI awareness. capture_full_png also captures physical
    // pixels (SetProcessDPIAware), and enigo SendInput maps in physical space, so
    // returning physical here keeps OCR→0-1000→screen→click all in one coord space
    // on scaled displays (e.g. 2560x1440 @150%, where logical is 1707x960).
    unsafe {
        let dc = GetDC(0);
        let w = GetDeviceCaps(dc, 118).max(0) as u32;
        let h = GetDeviceCaps(dc, 117).max(0) as u32;
        ReleaseDC(0, dc);
        if w > 0 && h > 0 {
            (0, 0, w, h)
        } else {
            // Fallback to logical metrics if GetDeviceCaps fails.
            unsafe extern "system" {
                fn GetSystemMetrics(n: i32) -> i32;
            }
            (
                0,
                0,
                GetSystemMetrics(0).max(0) as u32,
                GetSystemMetrics(1).max(0) as u32,
            )
        }
    }
}

fn find_app_window(app_name: &str) -> Result<capture::WindowInfo, String> {
    let wins = capture::list_windows().map_err(|e| e.to_string())?;
    // App identity differs by platform: macOS list reports the app's display name
    // ("WeChat"/"Weixin"), Windows reports the process name ("Weixin"), and the
    // caller may pass a macOS bundle id ("com.tencent.xinWeChat"). Match the exact
    // name first, then known aliases (case-insensitive substring) so the same
    // plugin works on both OSes — esp. WeChat 4.x renamed the process to "Weixin".
    let target = app_name.to_lowercase();
    let aliases: &[&str] = if target.contains("wechat") || target.contains("weixin") {
        &["weixin", "wechat", "微信"]
    } else {
        &[]
    };
    let matches = |w: &capture::WindowInfo| {
        let a = w.app.to_lowercase();
        a == target || aliases.iter().any(|al| a.contains(al) || w.app.contains(al))
    };
    // WeChat's process owns several non-UI helper top-level windows (a tray-message
    // sink, IME hosts, a splash). They can be larger than the real chat window but
    // render BLANK, so "pick the biggest weixin window" grabs the wrong one. Skip
    // them by their (ASCII, encoding-safe) titles; the real chat window is titled
    // "微信" and is the largest of what remains.
    const HELPER_TITLES: &[&str] = &[
        "WxTrayIconMessageWindow",
        "Default IME",
        "MSCTFIME UI",
        "Weixin", // English splash/loader window, not the chat UI
        "",       // untitled helper surfaces
    ];
    let qualifies = |w: &capture::WindowInfo| {
        matches(w)
            && !w.minimized
            && w.w >= 200
            && w.h >= 200
            && !HELPER_TITLES.contains(&w.title.as_str())
    };
    // Pick the LARGEST qualifying window (the chat UI), not just the first.
    let largest = |wins: &[capture::WindowInfo]| {
        wins.iter()
            .filter(|&w| qualifies(w))
            .max_by_key(|w| (w.w as u64) * (w.h as u64))
            .cloned()
    };
    if let Some(w) = largest(&wins) {
        return Ok(w);
    }
    // Nothing on-screen: the app may have closed to the tray (WeChat 4.x destroys
    // its top-level window on close). Try to restore the hidden main window, then
    // re-enumerate once before giving up — keeps the monitor loop self-healing.
    if capture::restore_app_window(app_name).unwrap_or(false) {
        std::thread::sleep(std::time::Duration::from_millis(800));
        let wins2 = capture::list_windows().map_err(|e| e.to_string())?;
        if let Some(w) = largest(&wins2) {
            return Ok(w);
        }
    }
    Err(format!("no on-screen window for app '{app_name}'"))
}

fn capture_app_window(app_name: &str) -> Result<String, String> {
    let win = find_app_window(app_name)?;
    // Capture the exact window by id — occlusion-proof (Apple `screencapture -l`
    // on macOS), handles hardware-accelerated / opaque windows like WeChat 4.x
    // that the old in-process xcap path hung on.
    let png = capture::capture_window_png(win.id).map_err(|e| e.to_string())?;
    if png.is_empty() {
        return Err("window capture produced an empty image (window off-screen?)".to_string());
    }
    Ok(capture::png_to_data_uri(&png))
}

/// On-device OCR of an app window via macOS Vision (through `python3` +
/// pyobjc, same shell-out pattern as `cgwindow_fallback`). Captures the
/// window by id (occlusion-proof) to a temp PNG, runs accurate text
/// recognition, and returns a JSON array of recognised lines with 0-1000
/// relative centre coords: `[{"text":"东升","x":143,"y":699}, ...]`.
/// Far more precise than VLM grounding for clicking a named row.
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
fn ocr_window(_app_name: &str) -> Result<String, String> {
    Err("ocr_window only implemented on macOS and Windows".to_string())
}

/// Maximise a window (by HWND) and force it to the foreground, even over another
/// app (e.g. a stray File Explorer) — a background gateway process can't normally
/// win SetForegroundWindow, so we AttachThreadInput to the current foreground
/// thread first to bypass Windows' foreground lock. Maximising also guarantees the
/// window is unoccluded for the CopyFromScreen region grab. CREATE_NO_WINDOW keeps
/// the helper PowerShell from flashing a console.
#[cfg(target_os = "windows")]
fn focus_window(hwnd: u64) {
    use std::os::windows::process::CommandExt;
    let script = format!(
        r#"$sig=@'
using System;
using System.Runtime.InteropServices;
public class FW {{
  [DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr h, int n);
  [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr h);
  [DllImport("user32.dll")] public static extern bool BringWindowToTop(IntPtr h);
  [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
  [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid);
  [DllImport("user32.dll")] public static extern bool AttachThreadInput(uint a, uint b, bool f);
  [DllImport("kernel32.dll")] public static extern uint GetCurrentThreadId();
  public static void Go(IntPtr h) {{
    ShowWindow(h, 5); // SW_SHOW — bring up WITHOUT resizing (SW_MAXIMIZE blanks WeChat CEF)
    IntPtr fg = GetForegroundWindow();
    uint pid; uint fgT = GetWindowThreadProcessId(fg, out pid);
    uint cur = GetCurrentThreadId();
    AttachThreadInput(cur, fgT, true);
    BringWindowToTop(h); SetForegroundWindow(h);
    AttachThreadInput(cur, fgT, false);
  }}
}}
'@
Add-Type $sig
[FW]::Go([IntPtr]{hwnd})"#,
        hwnd = hwnd
    );
    let mut cmd = Command::new("powershell");
    cmd.args(["-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", &script]);
    cmd.creation_flags(0x08000000);
    let _ = cmd.output();
}

/// Capture the WeChat window for OCR via a screen-region grab. WeChat 4.x's
/// risk-control blanks PrintWindow (per-window) captures — they come back solid
/// black — but a CopyFromScreen (GDI BitBlt) region grab of the window's on-screen
/// rect is NOT blocked. We foreground + un-minimise the window first (CopyFromScreen
/// captures whatever is displayed at those coords, so the window must be visible),
/// then grab its rect. Returns the PNG plus the refreshed window bounds, so OCR maps
/// hits to correct screen-absolute click points. macOS keeps its backing-store path.
#[cfg(target_os = "windows")]
fn wechat_region_capture(app_name: &str) -> Result<(Vec<u8>, capture::WindowInfo), String> {
    // IMPORTANT: do NOT programmatically focus / maximise / restore the window.
    // WeChat's CEF renderer paints blank gray when its window is shown or resized
    // from a background process — so any SetForegroundWindow/ShowWindow turns the
    // capture into a featureless gray rectangle. Instead capture the window's
    // current on-screen rect exactly as it sits (CopyFromScreen, which WeChat's
    // risk-control does NOT blank, unlike PrintWindow). This relies on WeChat being
    // left visible and unoccluded; if it isn't, the grab will look blank and the
    // caller falls back to WeChat's own built-in screenshot.
    let win = find_app_window(app_name)?;
    let png = capture::capture_region_png(win.x, win.y, win.w, win.h).map_err(|e| e.to_string())?;
    Ok((png, win))
}

/// Heuristic: is a capture essentially blank (solid black / uniform)? WeChat
/// risk-control blanks PrintWindow to pure black; if a region grab ever comes back
/// blank too (window occluded, or stricter anti-capture), we fall back to WeChat's
/// own screenshot. Samples sparsely and reports blank when <1% of sampled pixels
/// are non-black.
#[cfg(target_os = "windows")]
fn looks_blank(png: &[u8]) -> bool {
    match capture::png_to_rgba(png) {
        Ok(img) => {
            let mut nonblack = 0u64;
            let mut total = 0u64;
            for p in img.pixels().step_by(37) {
                total += 1;
                let [r, g, b, _] = p.0;
                if r > 16 || g > 16 || b > 16 {
                    nonblack += 1;
                }
            }
            total == 0 || (nonblack as f64 / total as f64) < 0.01
        }
        // Undecodable → don't assume blank; let OCR try.
        Err(_) => false,
    }
}

/// Read the current clipboard image as PNG bytes (WeChat's built-in screenshot
/// copies the captured region here). Requires STA.
#[cfg(target_os = "windows")]
fn clipboard_image_png() -> Result<Vec<u8>, String> {
    use std::os::windows::process::CommandExt;
    let out_png = std::env::temp_dir().join(format!("rsclaw_clip_{}.png", std::process::id()));
    let script = format!(
        r#"Add-Type -AssemblyName System.Windows.Forms,System.Drawing
$img = [System.Windows.Forms.Clipboard]::GetImage()
if ($img -eq $null) {{ Write-Output 'NOIMG'; exit 1 }}
$img.Save('{path}', [System.Drawing.Imaging.ImageFormat]::Png)
Write-Output 'OK'"#,
        path = out_png.display()
    );
    let mut cmd = Command::new("powershell");
    cmd.args([
        "-NoProfile",
        "-ExecutionPolicy",
        "Bypass",
        "-STA",
        "-Command",
        &script,
    ]);
    cmd.creation_flags(0x08000000);
    let res = cmd
        .output()
        .map_err(|e| format!("clipboard image spawn failed: {e}"))?;
    if !res.status.success() {
        return Err(format!(
            "clipboard has no image ({})",
            String::from_utf8_lossy(&res.stdout).trim()
        ));
    }
    let bytes = std::fs::read(&out_png).map_err(|e| format!("read clipboard png: {e}"))?;
    let _ = std::fs::remove_file(&out_png);
    Ok(bytes)
}

/// FALLBACK capture via WeChat's OWN built-in screenshot (PC default hotkey Alt+A
/// → drag-select the window → Enter copies to clipboard). Used only when the region
/// grab comes back blank, since WeChat's internal screenshot is never blocked by its
/// own risk-control. Intrusive (steals focus, flashes the selection overlay).
#[cfg(target_os = "windows")]
fn wechat_screenshot_png(win: &capture::WindowInfo) -> Result<Vec<u8>, String> {
    use std::{thread::sleep, time::Duration};
    focus_window(win.id);
    sleep(Duration::from_millis(450));
    let mut e = new_enigo()?;
    // Trigger WeChat's screenshot (Alt held while pressing 'a').
    e.key(Key::Alt, Press)
        .map_err(|err| format!("alt down: {err}"))?;
    e.key(Key::Unicode('a'), Click)
        .map_err(|err| format!("press a: {err}"))?;
    e.key(Key::Alt, Release)
        .map_err(|err| format!("alt up: {err}"))?;
    sleep(Duration::from_millis(700)); // selection overlay appears
    // Drag-select the whole window (real down → move → move → up).
    let pad = 2;
    let (x1, y1) = (win.x + pad, win.y + pad);
    let (x2, y2) = (win.x + win.w as i32 - pad, win.y + win.h as i32 - pad);
    e.move_mouse(x1, y1, Coordinate::Abs)
        .map_err(|err| format!("move start: {err}"))?;
    e.button(Button::Left, Press)
        .map_err(|err| format!("btn down: {err}"))?;
    e.move_mouse((x1 + x2) / 2, (y1 + y2) / 2, Coordinate::Abs)
        .map_err(|err| format!("move mid: {err}"))?;
    e.move_mouse(x2, y2, Coordinate::Abs)
        .map_err(|err| format!("move end: {err}"))?;
    e.button(Button::Left, Release)
        .map_err(|err| format!("btn up: {err}"))?;
    sleep(Duration::from_millis(350));
    // Enter = 完成/复制 → puts the capture on the clipboard, closes the overlay.
    e.key(Key::Return, Click)
        .map_err(|err| format!("enter: {err}"))?;
    sleep(Duration::from_millis(450));
    clipboard_image_png()
}

/// Windows on-device OCR via Windows.Media.Ocr (WinRT) through PowerShell. For
/// WeChat the window is captured via a screen-region grab (PrintWindow is blanked
/// by WeChat risk-control); other apps use the occlusion-proof PrintWindow path.
/// Prints the same JSON shape as macOS: `[{"text","conf","x","y","sx","sy"}]` with
/// x/y 0-1000 window-relative and sx/sy screen-absolute click points. Because the
/// captured image IS the window rect at a known origin, sx/sy land correctly.
#[cfg(target_os = "windows")]
fn ocr_window(app_name: &str) -> Result<String, String> {
    let lname = app_name.to_lowercase();
    let (png, wx, wy, ww, wh) = if lname.contains("wechat") || lname.contains("weixin") {
        // WeChat: bring its window to the FOREGROUND first (it shares the desktop with
        // the douyin browser, which steals focus), then full-screen grab. Foregrounding
        // (SetForegroundWindow, NO resize) is safe — only resize/maximise blanks the CEF
        // surface. Capture is a full-screen CopyFromScreen (risk-control-proof, unlike
        // PrintWindow). WeChat must be left maximised so its UI fills the screen.
        // ww=wh=0 tells the OCR driver the image pixels ARE screen coordinates.
        if let Ok(win) = find_app_window(app_name) {
            focus_window(win.id);
            std::thread::sleep(std::time::Duration::from_millis(350));
        }
        let png = capture::capture_full_png().map_err(|e| e.to_string())?;
        (png, 0i32, 0i32, 0u32, 0u32)
    } else {
        let win = find_app_window(app_name)?;
        let png = capture::capture_window_png(win.id).map_err(|e| e.to_string())?;
        (png, win.x, win.y, win.w, win.h)
    };
    let tmp = std::env::temp_dir().join(format!(
        "rsclaw_ocr_{}.png",
        std::process::id()
    ));
    std::fs::write(&tmp, &png).map_err(|e| format!("write OCR temp PNG: {e}"))?;
    // Write the OCR script to a temp .ps1 (avoids -Command quoting hell) and run
    // it STA (WinRT requires it). Args: <png> <wx> <wy> <ww> <wh>.
    let ps = std::env::temp_dir().join("rsclaw_ocr_win.ps1");
    let _ = std::fs::write(&ps, OCR_WIN_PS1);
    let mut ocr_cmd = Command::new("powershell");
    ocr_cmd
        .args([
            "-NoProfile",
            "-ExecutionPolicy",
            "Bypass",
            "-STA",
            "-File",
        ])
        .arg(&ps)
        .arg(&tmp)
        .arg(wx.to_string())
        .arg(wy.to_string())
        .arg(ww.to_string())
        .arg(wh.to_string());
    {
        // CREATE_NO_WINDOW: don't allocate a console window (no screen flash on
        // every monitor_tick).
        use std::os::windows::process::CommandExt;
        ocr_cmd.creation_flags(0x08000000);
    }
    let out = ocr_cmd
        .output()
        .map_err(|e| format!("powershell OCR spawn failed: {e}"))?;
    let _ = std::fs::remove_file(&tmp);
    if !out.status.success() {
        return Err(format!(
            "Windows OCR failed: {}",
            String::from_utf8_lossy(&out.stderr).trim()
        ));
    }
    Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
}

/// Windows.Media.Ocr driver (PowerShell, STA). argv: png, wx, wy, ww, wh (window
/// screen bounds in logical px). Emits `[{"text","conf","x","y","sx","sy"}]`:
/// x/y are 0-1000 window-relative line centres; sx/sy are screen-absolute click
/// points (window origin + relative * window size). conf is 100 (Windows OCR has
/// no per-line confidence). The captured PNG IS the window, so we normalise by
/// the image's own pixel size.
#[cfg(target_os = "windows")]
const OCR_WIN_PS1: &str = r#"param([string]$img,[int]$wx,[int]$wy,[int]$ww,[int]$wh)
$ErrorActionPreference='Stop'
Add-Type -AssemblyName System.Runtime.WindowsRuntime
[void][Windows.Storage.StorageFile,Windows.Storage,ContentType=WindowsRuntime]
[void][Windows.Media.Ocr.OcrEngine,Windows.Foundation,ContentType=WindowsRuntime]
[void][Windows.Graphics.Imaging.BitmapDecoder,Windows.Foundation,ContentType=WindowsRuntime]
$asTask=([System.WindowsRuntimeSystemExtensions].GetMethods()|?{$_.Name -eq 'AsTask' -and $_.GetParameters().Count -eq 1 -and $_.GetParameters()[0].ParameterType.Name -eq 'IAsyncOperation`1'})[0]
function Await($op,$t){ $m=$asTask.MakeGenericMethod($t); $tk=$m.Invoke($null,@($op)); $tk.Wait(); $tk.Result }
$file=Await ([Windows.Storage.StorageFile]::GetFileFromPathAsync($img)) ([Windows.Storage.StorageFile])
$stream=Await ($file.OpenAsync([Windows.Storage.FileAccessMode]::Read)) ([Windows.Storage.Streams.IRandomAccessStream])
$dec=Await ([Windows.Graphics.Imaging.BitmapDecoder]::CreateAsync($stream)) ([Windows.Graphics.Imaging.BitmapDecoder])
$sb=Await ($dec.GetSoftwareBitmapAsync()) ([Windows.Graphics.Imaging.SoftwareBitmap])
$iw=[double]$dec.PixelWidth; $ih=[double]$dec.PixelHeight
$eng=[Windows.Media.Ocr.OcrEngine]::TryCreateFromUserProfileLanguages()
if(-not $eng){ $eng=[Windows.Media.Ocr.OcrEngine]::TryCreateFromLanguage(([Windows.Media.Ocr.OcrEngine]::AvailableRecognizerLanguages)[0]) }
$res=Await ($eng.RecognizeAsync($sb)) ([Windows.Media.Ocr.OcrResult])
$out=@()
foreach($l in $res.Lines){
  $minx=1e9;$miny=1e9;$maxx=0;$maxy=0
  foreach($w in $l.Words){ $r=$w.BoundingRect; if($r.X -lt $minx){$minx=$r.X}; if($r.Y -lt $miny){$miny=$r.Y}; if(($r.X+$r.Width) -gt $maxx){$maxx=$r.X+$r.Width}; if(($r.Y+$r.Height) -gt $maxy){$maxy=$r.Y+$r.Height} }
  if($maxx -le 0){continue}
  $cx=($minx+$maxx)/2.0; $cy=($miny+$maxy)/2.0
  $rx=[int][math]::Round($cx/$iw*1000.0); $ry=[int][math]::Round($cy/$ih*1000.0)
  # ww<=0 => full-screen capture: the image pixels ARE screen coordinates.
  if($ww -le 0){ $sx=[int]$cx; $sy=[int]$cy } else { $sx=[int]($wx + $cx/$iw*$ww); $sy=[int]($wy + $cy/$ih*$wh) }
  $out += [pscustomobject]@{ text=$l.Text; conf=100; x=$rx; y=$ry; sx=$sx; sy=$sy }
}
$out | ConvertTo-Json -Compress -Depth 3
"#;

#[cfg(target_os = "macos")]
fn ocr_window(app_name: &str) -> Result<String, String> {
    let win = find_app_window(app_name)?;
    // Bounds of the EXACT window we OCR (frontmost match — may be a CEF popover
    // that AppleScript/get_main_window can't see). Passing them to the OCR driver
    // lets it emit screen-absolute click points, so callers never have to re-resolve
    // the window (and never mis-scale a popover's coords by the main window).
    let (wx, wy, ww, wh) = (win.x, win.y, win.w, win.h);
    // Capture the exact window by id (occlusion-proof) to a temp PNG for python.
    let png = capture::capture_window_png(win.id).map_err(|e| e.to_string())?;
    let tmp = std::env::temp_dir().join(format!(
        "rsclaw_ocr_{}_{}.png",
        std::process::id(),
        win.id
    ));
    std::fs::write(&tmp, &png).map_err(|e| format!("write OCR temp PNG: {e}"))?;
    let out = Command::new("python3")
        .arg("-c")
        .arg(OCR_VISION_PY)
        .arg(&tmp)
        .arg(wx.to_string())
        .arg(wy.to_string())
        .arg(ww.to_string())
        .arg(wh.to_string())
        .output()
        .map_err(|e| format!("python3 OCR spawn failed (need pyobjc Vision): {e}"))?;
    let _ = std::fs::remove_file(&tmp);
    if !out.status.success() {
        return Err(format!(
            "Vision OCR failed: {}",
            String::from_utf8_lossy(&out.stderr).trim()
        ));
    }
    Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
}

/// macOS Vision text-recognition driver (run via `python3 -c`). Reads an image
/// path from argv[1] and the OCR'd window's screen bounds from argv[2..6]
/// (x,y,w,h in logical points). Prints `[{"text","conf","x","y","sx","sy"}]`:
/// `x`/`y` are 0-1000 top-left window-relative; `sx`/`sy` are screen-absolute
/// click points (window origin + relative offset) so callers click without
/// re-resolving the window. RecognitionLevel 0 = accurate (1 misses small CJK).
#[cfg(target_os = "macos")]
const OCR_VISION_PY: &str = r#"import sys, json, Vision, Quartz
from Foundation import NSURL
url = NSURL.fileURLWithPath_(sys.argv[1])
wx, wy, ww, wh = (int(sys.argv[2]), int(sys.argv[3]), int(sys.argv[4]), int(sys.argv[5])) if len(sys.argv) >= 6 else (0, 0, 0, 0)
src = Quartz.CGImageSourceCreateWithURL(url, None)
cg = Quartz.CGImageSourceCreateImageAtIndex(src, 0, None)
req = Vision.VNRecognizeTextRequest.alloc().init()
req.setRecognitionLevel_(0)
req.setRecognitionLanguages_(['zh-Hans', 'zh-Hant', 'en'])
h = Vision.VNImageRequestHandler.alloc().initWithCGImage_options_(cg, {})
h.performRequests_error_([req], None)
out = []
for o in (req.results() or []):
    c = o.topCandidates_(1)
    if not c:
        continue
    b = o.boundingBox()
    fx = b.origin.x + b.size.width / 2.0            # 0-1 left-origin
    fy = 1.0 - (b.origin.y + b.size.height / 2.0)   # 0-1 top-origin (Vision is bottom-left)
    # `conf` is Vision's per-line confidence scaled to 0-100. Clean CJK reads
    # score ~100; partial / edge-clipped glyphs (the source of garbled text when
    # scrolling) score ~30. Callers can drop low-confidence lines.
    out.append({'text': c[0].string(),
                'conf': int(c[0].confidence() * 100),
                'x': int(fx * 1000),
                'y': int(fy * 1000),
                'sx': int(wx + fx * ww),
                'sy': int(wy + fy * wh)})
print(json.dumps(out, ensure_ascii=False))
"#;

/// Convert a macOS bundle-id to the process name used by System Events.
/// E.g. "com.tencent.xinWeChat" -> "WeChat", "com.apple.Safari" -> "Safari".
fn bundle_to_app_name(bundle_id: &str) -> String {
    // Common overrides for apps whose process name differs from bundle-id tail.
    match bundle_id {
        "com.tencent.xinWeChat" => "WeChat".to_string(),
        "com.tencent.xinWeChat.desktop" => "WeChat".to_string(),
        _ => {
            // Take the last path component and strip common suffixes.
            let tail = bundle_id.rsplit('.').next().unwrap_or(bundle_id);
            tail.to_string()
        }
    }
}

/// Run an AppleScript via osascript and return stdout as String.
fn run_osascript(script: &str) -> Result<String, String> {
    match Command::new("osascript").arg("-e").arg(script).output() {
        Ok(out) if out.status.success() => {
            Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
        }
        Ok(out) => Err(format!(
            "osascript failed: {}",
            String::from_utf8_lossy(&out.stderr)
        )),
        Err(e) => Err(format!("osascript spawn failed: {e}")),
    }
}

/// Convert a key name to an AppleScript key code (macOS).
fn key_to_applescript_code(name: &str) -> Result<u16, String> {
    let code = match name.trim().to_lowercase().as_str() {
        // Letters
        "a" => 0,
        "b" => 11,
        "c" => 8,
        "d" => 2,
        "e" => 14,
        "f" => 3,
        "g" => 5,
        "h" => 4,
        "i" => 34,
        "j" => 38,
        "k" => 40,
        "l" => 37,
        "m" => 46,
        "n" => 45,
        "o" => 31,
        "p" => 35,
        "q" => 12,
        "r" => 15,
        "s" => 1,
        "t" => 17,
        "u" => 32,
        "v" => 9,
        "w" => 13,
        "x" => 7,
        "y" => 16,
        "z" => 6,
        // Numbers
        "0" => 29,
        "1" => 18,
        "2" => 19,
        "3" => 20,
        "4" => 21,
        "5" => 23,
        "6" => 22,
        "7" => 26,
        "8" => 28,
        "9" => 25,
        // Special keys
        "return" | "enter" => 36,
        "delete" | "del" => 51,
        "escape" | "esc" => 53,
        "space" | "spacebar" => 49,
        "tab" => 48,
        "up" | "arrowup" | "uparrow" => 126,
        "down" | "arrowdown" | "downarrow" => 125,
        "left" | "arrowleft" | "leftarrow" => 123,
        "right" | "arrowright" | "rightarrow" => 124,
        "pageup" | "pgup" => 116,
        "pagedown" | "pgdn" => 121,
        "home" => 115,
        "end" => 119,
        "f1" => 122,
        "f2" => 120,
        "f3" => 99,
        "f4" => 118,
        "f5" => 96,
        "f6" => 97,
        "f7" => 98,
        "f8" => 100,
        "f9" => 101,
        "f10" => 109,
        "f11" => 103,
        "f12" => 111,
        _ => return Err(format!("unknown key for AppleScript: {name}")),
    };
    Ok(code)
}

/// Convert modifier names to AppleScript modifier string.
fn modifiers_to_applescript(modifiers: &[String]) -> String {
    let mut parts = Vec::new();
    for m in modifiers {
        match m.trim().to_lowercase().as_str() {
            "command" | "cmd" | "meta" | "super" => parts.push("command down"),
            "control" | "ctrl" => parts.push("control down"),
            "shift" => parts.push("shift down"),
            "option" | "alt" => parts.push("option down"),
            _ => {}
        }
    }
    if parts.is_empty() {
        String::new()
    } else {
        format!("using {{{}}}", parts.join(", "))
    }
}

/// Parse a key name to enigo::Key.
fn parse_key(name: &str) -> Option<Key> {
    let k = match name.trim().to_lowercase().as_str() {
        "return" | "enter" => Key::Return,
        "ctrl" | "control" => Key::Control,
        "shift" => Key::Shift,
        "alt" | "option" => Key::Alt,
        "cmd" | "command" | "meta" | "win" | "super" => Key::Meta,
        "tab" => Key::Tab,
        "escape" | "esc" => Key::Escape,
        "space" | "spacebar" => Key::Space,
        "backspace" => Key::Backspace,
        "delete" | "del" => Key::Delete,
        "up" | "arrowup" | "uparrow" => Key::UpArrow,
        "down" | "arrowdown" | "downarrow" => Key::DownArrow,
        "left" | "arrowleft" | "leftarrow" => Key::LeftArrow,
        "right" | "arrowright" | "rightarrow" => Key::RightArrow,
        "pageup" | "pgup" => Key::PageUp,
        "pagedown" | "pgdn" => Key::PageDown,
        "home" => Key::Home,
        "end" => Key::End,
        "capslock" => Key::CapsLock,
        "f1" => Key::F1,
        "f2" => Key::F2,
        "f3" => Key::F3,
        "f4" => Key::F4,
        "f5" => Key::F5,
        "f6" => Key::F6,
        "f7" => Key::F7,
        "f8" => Key::F8,
        "f9" => Key::F9,
        "f10" => Key::F10,
        "f11" => Key::F11,
        "f12" => Key::F12,
        s if s.chars().count() == 1 => Key::Unicode(s.chars().next()?),
        _ => return None,
    };
    Some(k)
}

/// Fallback to Core Graphics window list when AppleScript/System Events
/// can't enumerate windows (common with sandboxed apps like WeChat).
/// Only works on macOS; returns an error on other platforms.
fn cgwindow_fallback(owner_name: &str) -> Result<String, String> {
    let owner_escaped = owner_name.replace('"', r#"\""#).replace('\'', "'\"'\"'");
    let py = format!(
        r#"import Quartz, json
wl = Quartz.CGWindowListCopyWindowInfo(Quartz.kCGWindowListOptionAll, Quartz.kCGNullWindowID)
best = None
best_area = 0
for w in wl:
    if w.get('kCGWindowOwnerName','') != '{}':
        continue
    b = w.get('kCGWindowBounds',{{}})
    x, y, wi, h = int(b.get('X',0)), int(b.get('Y',0)), int(b.get('Width',0)), int(b.get('Height',0))
    if wi < 200 or h < 200:
        continue
    area = wi * h
    if area > best_area:
        best_area = area
        best = (x, y, wi, h)
if best:
    print(json.dumps({{'x':best[0],'y':best[1],'w':best[2],'h':best[3]}}))
else:
    print('')
"#,
        owner_escaped
    );
    match Command::new("python3").args(["-c", &py]).output() {
        Ok(out) if out.status.success() => {
            let text = String::from_utf8_lossy(&out.stdout).trim().to_string();
            if text.is_empty() {
                Err(format!(
                    "cgwindow_fallback: no {owner_name} window found via CGWindowList"
                ))
            } else {
                Ok(text)
            }
        }
        Ok(out) => Err(format!(
            "cgwindow_fallback: python3 failed: {}",
            String::from_utf8_lossy(&out.stderr)
        )),
        Err(e) => Err(format!("cgwindow_fallback: python3 spawn failed: {e}")),
    }
}

// ---------------------------------------------------------------------------
// DesktopSession impl
// ---------------------------------------------------------------------------

#[async_trait::async_trait]
impl DesktopSession for NativeDesktopSession {
    async fn activate_app(&self, bundle_id: &str) -> Result<String, String> {
        let bundle_id = bundle_id.to_owned();
        tokio::task::spawn_blocking(move || {
            if cfg!(target_os = "macos") {
                // Frontmost check (System Events) — used both as a fast-path
                // (skip the whole activation dance when already frontmost, the
                // common case in a monitor loop) and as the verify poll.
                let check_script = format!(
                    r#"tell application "System Events"
    return frontmost of (first process whose bundle identifier is "{}")
end tell"#,
                    bundle_id.replace('"', r#"\""#)
                );
                let is_frontmost = || {
                    matches!(
                        Command::new("osascript").args(["-e", &check_script]).output(),
                        Ok(out) if out.status.success()
                            && String::from_utf8_lossy(&out.stdout).trim().eq_ignore_ascii_case("true")
                    )
                };

                // FAST PATH: already frontmost → return immediately (~30ms).
                // Previously every call paid 500ms + 300ms + up to 5×300ms of
                // fixed sleeps (~2-5s) even when the app was already active —
                // the dominant cost in the monitor loop.
                if is_frontmost() {
                    return Ok("ok".to_string());
                }

                // Three-layer fallback (matches wechat_agent.py):
                // 1. open -b (system-level launchctl, most reliable)
                // 2. activate via AppleScript
                // 3. set frontmost via System Events
                let _ = Command::new("open").args(["-b", &bundle_id]).output();
                std::thread::sleep(std::time::Duration::from_millis(250));

                let script_activate = format!(
                    r#"tell application id "{}" to activate"#,
                    bundle_id.replace('"', r#"\""#)
                );
                let _ = Command::new("osascript")
                    .args(["-e", &script_activate])
                    .output();

                let script_frontmost = format!(
                    r#"tell application "System Events"
    set frontmost of (first process whose bundle identifier is "{}") to true
end tell"#,
                    bundle_id.replace('"', r#"\""#)
                );
                let _ = Command::new("osascript")
                    .args(["-e", &script_frontmost])
                    .output();

                // Verify frontmost up to 4 times (100ms apart), exit as soon as
                // confirmed.
                for _ in 0..4 {
                    std::thread::sleep(std::time::Duration::from_millis(100));
                    if is_frontmost() {
                        return Ok("ok".to_string());
                    }
                    let _ = Command::new("open").args(["-b", &bundle_id]).output();
                }
                Ok("ok".to_string()) // Return ok even if frontmost check fails
            } else if cfg!(target_os = "windows") {
                let escaped = bundle_id
                    .replace('`', "``")
                    .replace('*', "`*")
                    .replace('?', "`?")
                    .replace('[', "`[")
                    .replace(']', "`]")
                    .replace('\'', "''");
                let ps = format!(
                    r#"Add-Type -Name W -Namespace N -MemberDefinition '[DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr hWnd);'; Get-Process | Where-Object {{$_.ProcessName -like '*{}*'}} | ForEach-Object {{ if ($_.MainWindowHandle -ne 0) {{ [N.W]::SetForegroundWindow($_.MainWindowHandle) }} }}"#,
                    escaped
                );
                #[allow(unused_mut)]
                let mut ps_cmd = Command::new("powershell");
                ps_cmd.args(["-NoProfile", "-Command", &ps]);
                #[cfg(windows)]
                {
                    use std::os::windows::process::CommandExt;
                    ps_cmd.creation_flags(0x08000000);
                }
                match ps_cmd.output() {
                    Ok(out) if out.status.success() => Ok("ok".to_string()),
                    Ok(out) => Err(format!("powershell failed: {}", String::from_utf8_lossy(&out.stderr))),
                    Err(e) => Err(format!("powershell spawn failed: {e}")),
                }
            } else if cfg!(target_os = "linux") {
                let wmctrl = Command::new("wmctrl").args(["-a", &bundle_id]).status();
                if matches!(&wmctrl, Ok(s) if s.success()) {
                    return Ok("ok".to_string());
                }
                match Command::new("xdotool")
                    .args(["search", "--class", &bundle_id, "windowactivate"])
                    .status()
                {
                    Ok(s) if s.success() => Ok("ok".to_string()),
                    Ok(s) => Err(format!("xdotool exit status: {s}")),
                    Err(e) => Err(format!("neither wmctrl nor xdotool worked: {e}")),
                }
            } else {
                Err("activate_app: unsupported platform".to_string())
            }
        })
        .await
        .map_err(|e| format!("activate_app join failed: {e}"))?
    }

    async fn list_windows(&self, bundle_id: &str) -> Result<String, String> {
        let bundle_id = bundle_id.to_owned();
        tokio::task::spawn_blocking(move || {
            if cfg!(target_os = "macos") {
                let app_name = bundle_to_app_name(&bundle_id);
                let script = format!(
                    r#"tell application "System Events" to tell process "{}" to set winList to {{}}
repeat with i from 1 to (count windows)
    set w to window i
    set wName to name of w
    set wPos to position of w
    set wSize to size of w
    set wInfo to "{{\"idx\":" & i & ",\"title\":\"" & wName & "\",\"x\":" & (item 1 of wPos) & ",\"y\":" & (item 2 of wPos) & ",\"w\":" & (item 1 of wSize) & ",\"h\":" & (item 2 of wSize) & "}}"
    set end of winList to wInfo
end repeat
set AppleScript's text item delimiters to ","
return "[" & (winList as string) & "]"
"#,
                    app_name.replace('"', r#"\""#)
                );
                match run_osascript(&script) {
                    Ok(json) => Ok(json),
                    Err(e) => Err(format!("list_windows failed: {e}")),
                }
            } else {
                Err("list_windows: not yet implemented on this platform".to_string())
            }
        })
        .await
        .map_err(|e| format!("list_windows join failed: {e}"))?
    }

    async fn close_window(&self, bundle_id: &str, window_idx: u32) -> Result<String, String> {
        let bundle_id = bundle_id.to_owned();
        tokio::task::spawn_blocking(move || {
            if cfg!(target_os = "macos") {
                let app_name = bundle_to_app_name(&bundle_id);
                let script = format!(
                    r#"tell application "System Events" to tell process "{}" to click button 1 of window {}"#,
                    app_name.replace('"', r#"\""#),
                    window_idx
                );
                match run_osascript(&script) {
                    Ok(_) => Ok("ok".to_string()),
                    Err(e) => Err(format!("close_window failed: {e}")),
                }
            } else {
                Err("close_window: not yet implemented on this platform".to_string())
            }
        })
        .await
        .map_err(|e| format!("close_window join failed: {e}"))?
    }

    async fn get_main_window(&self, bundle_id: &str) -> Result<String, String> {
        let bundle_id = bundle_id.to_owned();
        tokio::task::spawn_blocking(move || {
            if cfg!(target_os = "macos") {
                let app_name = bundle_to_app_name(&bundle_id);
                // Try AppleScript first (most accurate when Accessibility works).
                let script = format!(
                    r#"tell application "System Events" to tell process "{}"
    set winCount to count of windows
    if winCount = 0 then return "0,0,0,0"
    set targetWin to missing value
    repeat with w in windows
        if name of w contains "Weixin" or name of w contains "WeChat" then
            set targetWin to w
            exit repeat
        end if
    end repeat
    if targetWin is missing value then set targetWin to window 1
    set p to position of targetWin
    set s to size of targetWin
    return (item 1 of p as text) & "," & (item 2 of p as text) & "," & (item 1 of s as text) & "," & (item 2 of s as text)
end tell"#,
                    app_name.replace('"', r#"\""#)
                );
                match run_osascript(&script) {
                    Ok(output) => {
                        let trimmed = output.trim();
                        if trimmed == "0,0,0,0" {
                            // AppleScript sees 0 windows — fall back to Core Graphics.
                            return cgwindow_fallback("WeChat");
                        }
                        let parts: Vec<&str> = trimmed.split(',').collect();
                        if parts.len() == 4 {
                            Ok(format!(
                                "{{\"x\":{},\"y\":{},\"w\":{},\"h\":{}}}",
                                parts[0], parts[1], parts[2], parts[3]
                            ))
                        } else {
                            Err(format!("get_main_window: unexpected output: {output}"))
                        }
                    }
                    Err(_) => cgwindow_fallback("WeChat"),
                }
            } else {
                #[cfg(target_os = "windows")]
                {
                    // Full-screen-capture model: WeChat's OCR is a full-screen grab and
                    // the plugin's 0-1000 coords are relative to the whole screen, so the
                    // "main window" bounds the plugin should use ARE the full virtual
                    // screen. Return its rect (origin + size) so relative→screen maps 1:1.
                    let (vx, vy, vw, vh) = virtual_screen_rect();
                    return Ok(format!(
                        "{{\"x\":{vx},\"y\":{vy},\"w\":{vw},\"h\":{vh}}}"
                    ));
                }
                #[cfg(not(target_os = "windows"))]
                {
                    return Err("get_main_window: not yet implemented on this platform".to_string());
                }
            }
        })
        .await
        .map_err(|e| format!("get_main_window join failed: {e}"))?
    }

    async fn screenshot_window(&self, bundle_id: &str) -> Result<String, String> {
        // Primary path: direct window-backing-store capture (overlap-proof,
        // no app-side screenshot UI, so it never pollutes a chat input box).
        let app_name = bundle_to_app_name(bundle_id);
        match tokio::task::spawn_blocking(move || capture_app_window(&app_name))
            .await
            .map_err(|e| format!("screenshot_window join failed: {e}"))?
        {
            Ok(image) => return Ok(image),
            Err(e) => warn!("capture_app_window failed ({e}); falling back to region capture"),
        }
        // Fallback: main window bounds + region crop, then primary monitor.
        // (region crop captures whatever is on top of the rect, so it is less
        // reliable when other windows overlap — used only if direct fails.)
        match self.get_main_window(bundle_id).await {
            Ok(bounds) => {
                let parsed: serde_json::Value = serde_json::from_str(&bounds)
                    .map_err(|e| format!("screenshot_window: failed to parse bounds: {e}"))?;
                let x = parsed["x"].as_u64().unwrap_or(0) as u32;
                let y = parsed["y"].as_u64().unwrap_or(0) as u32;
                let w = parsed["w"].as_u64().unwrap_or(0) as u32;
                let h = parsed["h"].as_u64().unwrap_or(0) as u32;
                self.screenshot_region(x, y, w, h).await
            }
            Err(_) => {
                // Fallback: capture primary monitor.
                tokio::task::spawn_blocking(move || capture_primary_monitor())
                    .await
                    .map_err(|e| format!("screenshot_window fallback join failed: {e}"))?
            }
        }
    }

    async fn screenshot_region(&self, x: u32, y: u32, w: u32, h: u32) -> Result<String, String> {
        tokio::task::spawn_blocking(move || capture_region(x, y, w, h))
            .await
            .map_err(|e| format!("screenshot_region join failed: {e}"))?
    }

    async fn region_has_color(
        &self,
        x: u32,
        y: u32,
        w: u32,
        h: u32,
        r: u32,
        g: u32,
        b: u32,
        tolerance: u32,
        min_count: u32,
    ) -> Result<String, String> {
        let (count, total) =
            tokio::task::spawn_blocking(move || region_color_count(x, y, w, h, r, g, b, tolerance))
                .await
                .map_err(|e| format!("region_has_color join failed: {e}"))??;
        let ratio = if total > 0 {
            count as f64 / total as f64
        } else {
            0.0
        };
        let hit = count >= min_count;
        Ok(format!(
            "{{\"hit\":{hit},\"count\":{count},\"total\":{total},\"ratio\":{ratio:.4}}}"
        ))
    }

    async fn ocr_window(&self, bundle_id: &str) -> Result<String, String> {
        let app_name = bundle_to_app_name(bundle_id);
        tokio::task::spawn_blocking(move || ocr_window(&app_name))
            .await
            .map_err(|e| format!("ocr_window join failed: {e}"))?
    }

    async fn mouse_move(&self, x: u32, y: u32) -> Result<String, String> {
        tokio::task::spawn_blocking(move || {
            let mut enigo = new_enigo()?;
            let (lx, ly) = scale_for_input(x, y);
            enigo
                .move_mouse(lx, ly, Coordinate::Abs)
                .map_err(|e| format!("move_mouse: {e}"))?;
            Ok("ok".to_string())
        })
        .await
        .map_err(|e| format!("mouse_move join failed: {e}"))?
    }

    async fn mouse_click(&self, x: u32, y: u32) -> Result<String, String> {
        tokio::task::spawn_blocking(move || {
            let mut enigo = new_enigo()?;
            let (lx, ly) = scale_for_input(x, y);
            enigo
                .move_mouse(lx, ly, Coordinate::Abs)
                .map_err(|e| format!("move_mouse: {e}"))?;
            enigo
                .button(Button::Left, Click)
                .map_err(|e| format!("button click: {e}"))?;
            Ok("ok".to_string())
        })
        .await
        .map_err(|e| format!("mouse_click join failed: {e}"))?
    }

    async fn mouse_double_click(&self, x: u32, y: u32) -> Result<String, String> {
        tokio::task::spawn_blocking(move || {
            let mut enigo = new_enigo()?;
            let (lx, ly) = scale_for_input(x, y);
            enigo
                .move_mouse(lx, ly, Coordinate::Abs)
                .map_err(|e| format!("move_mouse: {e}"))?;
            enigo
                .button(Button::Left, Click)
                .map_err(|e| format!("button click 1: {e}"))?;
            std::thread::sleep(std::time::Duration::from_millis(80));
            enigo
                .button(Button::Left, Click)
                .map_err(|e| format!("button click 2: {e}"))?;
            Ok("ok".to_string())
        })
        .await
        .map_err(|e| format!("mouse_double_click join failed: {e}"))?
    }

    async fn mouse_drag(&self, x1: u32, y1: u32, x2: u32, y2: u32) -> Result<String, String> {
        tokio::task::spawn_blocking(move || {
            if cfg!(target_os = "macos") {
                // macOS: use Python+Quartz for reliable multi-step dragging.
                // enigo's move_mouse does not produce the exact CGEvent sequence
                // that WeChat's screenshot overlay requires.
                let py = format!(
                    r#"import time, Quartz
steps = 20
x1, y1, x2, y2 = {}, {}, {}, {}

# mouseDown @ start
Quartz.CGEventPost(Quartz.kCGHIDEventTap,
    Quartz.CGEventCreateMouseEvent(None, Quartz.kCGEventLeftMouseDown,
        Quartz.CGPoint(x1, y1), Quartz.kCGMouseButtonLeft))
time.sleep(0.1)

# mouseDragged 20 times
for i in range(1, steps + 1):
    t = i / steps
    cx = x1 + (x2 - x1) * t
    cy = y1 + (y2 - y1) * t
    Quartz.CGEventPost(Quartz.kCGHIDEventTap,
        Quartz.CGEventCreateMouseEvent(None, Quartz.kCGEventLeftMouseDragged,
            Quartz.CGPoint(cx, cy), Quartz.kCGMouseButtonLeft))
    time.sleep(0.025)

# mouseUp @ end
time.sleep(0.1)
Quartz.CGEventPost(Quartz.kCGHIDEventTap,
    Quartz.CGEventCreateMouseEvent(None, Quartz.kCGEventLeftMouseUp,
        Quartz.CGPoint(x2, y2), Quartz.kCGMouseButtonLeft))
print('ok')
"#,
                    x1, y1, x2, y2
                );
                match Command::new("python3").args(["-c", &py]).output() {
                    Ok(out) if out.status.success() => Ok("ok".to_string()),
                    Ok(out) => Err(format!(
                        "mouse_drag: python3 failed: {}",
                        String::from_utf8_lossy(&out.stderr)
                    )),
                    Err(e) => Err(format!("mouse_drag: python3 spawn failed: {e}")),
                }
            } else {
                let mut enigo = new_enigo()?;
                let (fx, fy) = scale_for_input(x1, y1);
                let (tx, ty) = scale_for_input(x2, y2);
                enigo
                    .move_mouse(fx, fy, Coordinate::Abs)
                    .map_err(|e| format!("move_mouse start: {e}"))?;
                enigo
                    .button(Button::Left, Press)
                    .map_err(|e| format!("button press: {e}"))?;
                enigo
                    .move_mouse(tx, ty, Coordinate::Abs)
                    .map_err(|e| format!("move_mouse end: {e}"))?;
                enigo
                    .button(Button::Left, Release)
                    .map_err(|e| format!("button release: {e}"))?;
                Ok("ok".to_string())
            }
        })
        .await
        .map_err(|e| format!("mouse_drag join failed: {e}"))?
    }

    async fn mouse_scroll(&self, clicks: i32) -> Result<String, String> {
        tokio::task::spawn_blocking(move || {
            // macOS: WeChat 4.x's CEF/radium view IGNORES enigo's scroll event
            // (decorated with an event source + flags) — the message list never
            // moves (verified: screenshot hash identical before/after). A RAW
            // CGScrollWheelEvent does move it. Match enigo's vertical sign
            // convention (wheel1 = -clicks) so callers are unaffected: a
            // negative `clicks` scrolls UP toward older content.
            #[cfg(target_os = "macos")]
            {
                use core_graphics::event::{CGEvent, CGEventTapLocation, ScrollEventUnit};
                use core_graphics::event_source::{CGEventSource, CGEventSourceStateID};
                let source = CGEventSource::new(CGEventSourceStateID::HIDSystemState)
                    .map_err(|()| "scroll: CGEventSource::new failed".to_string())?;
                let event =
                    CGEvent::new_scroll_event(source, ScrollEventUnit::LINE, 1, -clicks, 0, 0)
                        .map_err(|()| "scroll: new_scroll_event failed".to_string())?;
                event.post(CGEventTapLocation::HID);
                return Ok("ok".to_string());
            }
            #[cfg(not(target_os = "macos"))]
            {
                let mut enigo = new_enigo()?;
                let axis = Axis::Vertical;
                enigo
                    .scroll(clicks, axis)
                    .map_err(|e| format!("scroll: {e}"))?;
                Ok("ok".to_string())
            }
        })
        .await
        .map_err(|e| format!("mouse_scroll join failed: {e}"))?
    }

    async fn key_press(&self, key: &str, modifiers: &[String]) -> Result<String, String> {
        let key = key.to_owned();
        let modifiers: Vec<String> = modifiers.to_vec();
        tokio::task::spawn_blocking(move || {
            if cfg!(target_os = "macos") {
                // macOS: use AppleScript/System Events for reliable shortcut delivery
                // (enigo sends global CGEvents which some sandboxed apps ignore).
                let target_code = key_to_applescript_code(&key)?;
                let mod_script = modifiers_to_applescript(&modifiers);
                let script = format!(
                    r#"tell application "System Events" to key code {} {}"#,
                    target_code, mod_script
                );
                run_osascript(&script)
            } else {
                let mut enigo = new_enigo()?;
                let target = parse_key(&key).ok_or_else(|| format!("unknown key: {key}"))?;
                let mut mod_keys = Vec::new();
                for m in &modifiers {
                    // The (mac-authored) callers pass "command" for shortcuts that on
                    // Windows/Linux are Ctrl (Cmd+V→Ctrl+V, Cmd+A→Ctrl+A). enigo's
                    // Meta = the Win key here, which would fire Win+V (clipboard
                    // history) etc. Remap command/meta/super → Control off macOS.
                    let ml = m.trim().to_lowercase();
                    let m_eff = match ml.as_str() {
                        "command" | "cmd" | "meta" | "super" | "win" => "control",
                        other => other,
                    };
                    let mk = parse_key(m_eff).ok_or_else(|| format!("unknown modifier: {m}"))?;
                    mod_keys.push(mk);
                }
                for mk in &mod_keys {
                    enigo
                        .key(*mk, Press)
                        .map_err(|e| format!("modifier press: {e}"))?;
                }
                enigo
                    .key(target, Click)
                    .map_err(|e| format!("key press: {e}"))?;
                for mk in mod_keys.iter().rev() {
                    if let Err(e) = enigo.key(*mk, Release) {
                        warn!(error = %e, "modifier release error (best-effort)");
                    }
                }
                Ok("ok".to_string())
            }
        })
        .await
        .map_err(|e| format!("key_press join failed: {e}"))?
    }

    async fn clipboard_set(&self, text: &str) -> Result<String, String> {
        let text = text.to_owned();
        tokio::task::spawn_blocking(move || {
            if cfg!(target_os = "macos") {
                match Command::new("pbcopy")
                    .stdin(std::process::Stdio::piped())
                    .spawn()
                {
                    Ok(mut child) => {
                        use std::io::Write;
                        if let Some(mut stdin) = child.stdin.take() {
                            let _ = stdin.write_all(text.as_bytes());
                        }
                        match child.wait() {
                            Ok(s) if s.success() => Ok("ok".to_string()),
                            Ok(s) => Err(format!("pbcopy exit status: {s}")),
                            Err(e) => Err(format!("pbcopy wait failed: {e}")),
                        }
                    }
                    Err(e) => Err(format!("pbcopy spawn failed: {e}")),
                }
            } else if cfg!(target_os = "linux") {
                let mut cmd = Command::new("xclip")
                    .args(["-selection", "clipboard"])
                    .stdin(std::process::Stdio::piped())
                    .spawn();
                if cmd.is_err() {
                    cmd = Command::new("xsel")
                        .args(["--clipboard", "--input"])
                        .stdin(std::process::Stdio::piped())
                        .spawn();
                }
                match cmd {
                    Ok(mut child) => {
                        use std::io::Write;
                        if let Some(mut stdin) = child.stdin.take() {
                            let _ = stdin.write_all(text.as_bytes());
                        }
                        match child.wait() {
                            Ok(s) if s.success() => Ok("ok".to_string()),
                            Ok(s) => Err(format!("xclip/xsel exit status: {s}")),
                            Err(e) => Err(format!("xclip/xsel wait failed: {e}")),
                        }
                    }
                    Err(e) => Err(format!("no clipboard tool available: {e}")),
                }
            } else if cfg!(target_os = "windows") {
                // Write the text as UTF-8 to a temp file and have PowerShell read it
                // back — passing Chinese through a -Command arg mangles it to '?'
                // (and then Set-Clipboard fails). Run STA (clipboard needs it).
                let tmp = std::env::temp_dir()
                    .join(format!("rsclaw_clipset_{}.txt", std::process::id()));
                std::fs::write(&tmp, text.as_bytes())
                    .map_err(|e| format!("clipboard_set temp write: {e}"))?;
                // Retry Set-Clipboard a few times: when a RustDesk/remote viewer is
                // connected its clipboard sync intermittently holds the clipboard,
                // making Set-Clipboard throw "failed to open clipboard".
                let ps = format!(
                    "$t=[System.IO.File]::ReadAllText('{}',[System.Text.Encoding]::UTF8); \
                     $ok=$false; \
                     for($i=0;$i -lt 10;$i++){{ try{{ Set-Clipboard -Value $t -ErrorAction Stop; $ok=$true; break }} \
                     catch{{ Start-Sleep -Milliseconds 250 }} }} \
                     if(-not $ok){{ Write-Error 'clipboard busy after retries'; exit 1 }}",
                    tmp.display()
                );
                #[allow(unused_mut)]
                let mut ps_cmd = Command::new("powershell");
                ps_cmd.args(["-NoProfile", "-STA", "-Command", &ps]);
                #[cfg(windows)]
                {
                    use std::os::windows::process::CommandExt;
                    ps_cmd.creation_flags(0x08000000);
                }
                let r = ps_cmd.output();
                let _ = std::fs::remove_file(&tmp);
                match r {
                    Ok(out) if out.status.success() => Ok("ok".to_string()),
                    Ok(out) => Err(format!(
                        "Set-Clipboard failed: {}",
                        String::from_utf8_lossy(&out.stderr)
                    )),
                    Err(e) => Err(format!("powershell spawn failed: {e}")),
                }
            } else {
                Err("clipboard_set: unsupported platform".to_string())
            }
        })
        .await
        .map_err(|e| format!("clipboard_set join failed: {e}"))?
    }

    async fn clipboard_get(&self) -> Result<String, String> {
        tokio::task::spawn_blocking(move || {
            if cfg!(target_os = "macos") {
                match Command::new("pbpaste").output() {
                    Ok(out) if out.status.success() => {
                        Ok(String::from_utf8_lossy(&out.stdout).into_owned())
                    }
                    Ok(out) => Err(format!(
                        "pbpaste failed: {}",
                        String::from_utf8_lossy(&out.stderr)
                    )),
                    Err(e) => Err(format!("pbpaste spawn failed: {e}")),
                }
            } else if cfg!(target_os = "linux") {
                let out = Command::new("xclip")
                    .args(["-selection", "clipboard", "-o"])
                    .output();
                let out = if out.is_err() {
                    Command::new("xsel")
                        .args(["--clipboard", "--output"])
                        .output()
                } else {
                    out
                };
                match out {
                    Ok(out) if out.status.success() => {
                        Ok(String::from_utf8_lossy(&out.stdout).into_owned())
                    }
                    Ok(out) => Err(format!(
                        "xclip/xsel failed: {}",
                        String::from_utf8_lossy(&out.stderr)
                    )),
                    Err(e) => Err(format!("no clipboard tool available: {e}")),
                }
            } else if cfg!(target_os = "windows") {
                #[allow(unused_mut)]
                let mut ps_cmd = Command::new("powershell");
                ps_cmd.args(["-NoProfile", "-Command", "Get-Clipboard"]);
                #[cfg(windows)]
                {
                    use std::os::windows::process::CommandExt;
                    ps_cmd.creation_flags(0x08000000);
                }
                match ps_cmd.output()
                {
                    Ok(out) if out.status.success() => {
                        Ok(String::from_utf8_lossy(&out.stdout).trim().to_owned())
                    }
                    Ok(out) => Err(format!(
                        "Get-Clipboard failed: {}",
                        String::from_utf8_lossy(&out.stderr)
                    )),
                    Err(e) => Err(format!("powershell spawn failed: {e}")),
                }
            } else {
                Err("clipboard_get: unsupported platform".to_string())
            }
        })
        .await
        .map_err(|e| format!("clipboard_get join failed: {e}"))?
    }

    async fn clipboard_set_file(&self, file_path: &str) -> Result<String, String> {
        let file_path = file_path.to_owned();
        tokio::task::spawn_blocking(move || {
            if cfg!(target_os = "macos") {
                let script = format!(
                    "set the clipboard to (POSIX file \"{}\")",
                    file_path.replace('"', "\\\"").replace('\\', "\\\\")
                );
                match Command::new("osascript").args(["-e", &script]).output() {
                    Ok(out) if out.status.success() => Ok("ok".to_string()),
                    Ok(out) => Err(format!(
                        "osascript failed: {}",
                        String::from_utf8_lossy(&out.stderr)
                    )),
                    Err(e) => Err(format!("osascript spawn failed: {e}")),
                }
            } else if cfg!(target_os = "linux") {
                // xclip with target uri-list for file references
                let uri = format!("file://{file_path}\n");
                match Command::new("xclip")
                    .args(["-selection", "clipboard", "-t", "text/uri-list"])
                    .stdin(std::process::Stdio::piped())
                    .spawn()
                {
                    Ok(mut child) => {
                        use std::io::Write;
                        if let Some(mut stdin) = child.stdin.take() {
                            let _ = stdin.write_all(uri.as_bytes());
                        }
                        match child.wait() {
                            Ok(s) if s.success() => Ok("ok".to_string()),
                            Ok(s) => Err(format!("xclip exit status: {s}")),
                            Err(e) => Err(format!("xclip wait failed: {e}")),
                        }
                    }
                    Err(e) => Err(format!("xclip spawn failed: {e}")),
                }
            } else if cfg!(target_os = "windows") {
                let ps = format!("Set-Clipboard -Path '{}'", file_path.replace('\'', "''"));
                #[allow(unused_mut)]
                let mut ps_cmd = Command::new("powershell");
                ps_cmd.args(["-NoProfile", "-Command", &ps]);
                #[cfg(windows)]
                {
                    use std::os::windows::process::CommandExt;
                    ps_cmd.creation_flags(0x08000000);
                }
                match ps_cmd.output()
                {
                    Ok(out) if out.status.success() => Ok("ok".to_string()),
                    Ok(out) => Err(format!(
                        "Set-Clipboard failed: {}",
                        String::from_utf8_lossy(&out.stderr)
                    )),
                    Err(e) => Err(format!("powershell spawn failed: {e}")),
                }
            } else {
                Err("clipboard_set_file: unsupported platform".to_string())
            }
        })
        .await
        .map_err(|e| format!("clipboard_set_file join failed: {e}"))?
    }
    async fn clipboard_get_image(&self) -> Result<String, String> {
        tokio::task::spawn_blocking(move || {
            if cfg!(target_os = "macos") {
                let tmp = format!("/tmp/rsclaw_cb_{}.png", std::process::id());
                let py = format!(
                    r#"from AppKit import NSPasteboard, NSBitmapImageRep, NSPasteboardTypeTIFF, NSPNGFileType
import sys
pb = NSPasteboard.generalPasteboard()
data = pb.dataForType_(NSPasteboardTypeTIFF)
if data is None:
    print('CLIPBOARD_EMPTY', file=sys.stderr)
    sys.exit(1)
rep = NSBitmapImageRep.imageRepWithData_(data)
if rep is None:
    print('REP_NONE', file=sys.stderr)
    sys.exit(1)
png = rep.representationUsingType_properties_(NSPNGFileType, None)
if png is None:
    print('PNG_NONE', file=sys.stderr)
    sys.exit(1)
with open('{}', 'wb') as f:
    f.write(bytes(png))
print('ok')
"#,
                    tmp
                );
                match Command::new("python3").args(["-c", &py]).output() {
                    Ok(out) if out.status.success() => {
                        match std::fs::read(&tmp) {
                            Ok(bytes) => {
                                let _ = std::fs::remove_file(&tmp);
                                if bytes.is_empty() {
                                    return Err("clipboard_get_image: empty image".to_string());
                                }
                                let b64 = base64::engine::general_purpose::STANDARD.encode(&bytes);
                                Ok(format!("data:image/png;base64,{b64}"))
                            }
                            Err(e) => Err(format!("clipboard_get_image: read temp file: {e}")),
                        }
                    }
                    Ok(out) => {
                        let stderr = String::from_utf8_lossy(&out.stderr);
                        if stderr.contains("CLIPBOARD_EMPTY") {
                            return Err("clipboard_get_image: clipboard has no image (screenshot likely failed)".to_string());
                        }
                        Err(format!(
                            "clipboard_get_image: python3 failed: {}",
                            stderr
                        ))
                    }
                    Err(e) => Err(format!("clipboard_get_image: python3 spawn failed: {e}")),
                }
            } else {
                Err("clipboard_get_image: not yet implemented on this platform".to_string())
            }
        })
        .await
        .map_err(|e| format!("clipboard_get_image join failed: {e}"))?
    }

    async fn mouse_right_click(&self, x: u32, y: u32) -> Result<String, String> {
        tokio::task::spawn_blocking(move || {
            let mut enigo = new_enigo()?;
            let (lx, ly) = scale_for_input(x, y);
            enigo
                .move_mouse(lx, ly, Coordinate::Abs)
                .map_err(|e| format!("move_mouse: {e}"))?;
            enigo
                .button(Button::Right, Click)
                .map_err(|e| format!("right button click: {e}"))?;
            Ok("ok".to_string())
        })
        .await
        .map_err(|e| format!("mouse_right_click join failed: {e}"))?
    }

    async fn file_dialog_open(&self, title: &str, _filters: &[String]) -> Result<String, String> {
        let title = title.to_owned();
        tokio::task::spawn_blocking(move || {
            if cfg!(target_os = "macos") {
                let script = format!(
                    r#"choose file with prompt "{}""#,
                    title.replace('"', "\\\"")
                );
                match Command::new("osascript").args(["-e", &script]).output() {
                    Ok(out) if out.status.success() => {
                        let path = String::from_utf8_lossy(&out.stdout).trim().to_string();
                        // AppleScript returns alias like "alias Macintosh HD:Users:..."
                        // Convert to POSIX path
                        if path.starts_with("alias ") {
                            let alias_path = path.strip_prefix("alias ").unwrap_or(&path);
                            match Command::new("osascript")
                                .args([
                                    "-e",
                                    &format!("POSIX path of {} \"{}\"", "alias", alias_path),
                                ])
                                .output()
                            {
                                Ok(out2) if out2.status.success() => {
                                    Ok(String::from_utf8_lossy(&out2.stdout).trim().to_string())
                                }
                                _ => Ok(path),
                            }
                        } else {
                            Ok(path)
                        }
                    }
                    Ok(out) => Err(format!(
                        "osascript failed: {}",
                        String::from_utf8_lossy(&out.stderr)
                    )),
                    Err(e) => Err(format!("osascript spawn failed: {e}")),
                }
            } else {
                Err("file_dialog_open: only macOS supported".to_string())
            }
        })
        .await
        .map_err(|e| format!("file_dialog_open join failed: {e}"))?
    }
}