rsclaw 2026.5.20

AI Agent Engine Compatible with OpenClaw
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
//! Native desktop operator backed by `enigo` (input synthesis) and
//! `xcap` (screenshot). Cross-platform: macOS / Windows / Linux X11 +
//! Wayland (xcap handles portal under Wayland).
//!
//! Behaviour notes:
//!   - `enigo::Enigo` is not `Send` on all platforms (Windows in particular)
//!     and input synthesis is fundamentally blocking, so every action runs
//!     inside `tokio::task::spawn_blocking` with a fresh `Enigo` per call. The
//!     operator itself is a unit struct that is trivially `Send + Sync`.
//!   - Coordinates from the model are in **physical** pixels (raw screenshot
//!     space). On macOS Retina, `enigo` expects logical coordinates, so we
//!     divide by `ctx.scale_factor`. On Windows / Linux X11 the API takes
//!     physical pixels and we pass through unchanged.
//!   - `activate_app` shells out per platform to bring **all** windows of the
//!     target app to the front. The objc2-app-kit / EnumWindows / xdotool
//!     routes are listed as TODOs for a v2 that wants zero shell-out overhead.

use std::{process::Command, time::Duration};

use anyhow::{Context as _, Result, anyhow};
use enigo::{
    Axis, Button, Coordinate,
    Direction::{Click, Press, Release},
    Enigo, Key, Keyboard, Mouse, Settings,
};
use image::{ImageFormat, RgbaImage};
use tracing::{debug, warn};
use xcap::Monitor;

use crate::computer::{
    action::{Action, ActionSpec, ExecCtx, MouseButton, Screenshot, ScrollDir},
    operator::{ActionFut, ActionOutput, Operator, ScreenshotFut},
};

const ACTIVATE_DELAY_MS: u64 = 400;

/// Native desktop operator. Unit struct: holds no state because every
/// platform call needs a fresh `Enigo` on the calling OS thread anyway
/// (Windows `Enigo` is not `Send`).
pub struct NativeOperator;

impl NativeOperator {
    /// Construct a new native operator. Cheap — no state is captured.
    pub fn new() -> Self {
        Self
    }
}

impl Default for NativeOperator {
    fn default() -> Self {
        Self::new()
    }
}

impl Operator for NativeOperator {
    fn name(&self) -> &'static str {
        "native"
    }

    fn action_spaces(&self) -> Vec<ActionSpec> {
        // Action shape mirrors the UI-TARS-desktop NutJSOperator surface
        // for compatibility with existing GUI-VLM playbooks, but the
        // coordinate envelope is the portable `<box>x,y</box>` form so
        // any VLM (not just UI-TARS-trained) can emit it without
        // special-token tokenizer support.
        vec![
            ActionSpec::new("click(start_box='<box>x1,y1</box>')"),
            ActionSpec::new("left_double(start_box='<box>x1,y1</box>')"),
            ActionSpec::new("right_single(start_box='<box>x1,y1</box>')"),
            ActionSpec::new("drag(start_box='<box>x1,y1</box>', end_box='<box>x3,y3</box>')"),
            ActionSpec::with_note("hotkey(key='')", "# Lowercase, space-separated, max 4 keys"),
            ActionSpec::with_note("type(content='')", "# Add \\n at end of content to submit"),
            ActionSpec::new(
                "scroll(start_box='<box>x1,y1</box>', direction='down or up or right or left')",
            ),
            ActionSpec::with_note(
                "wait()",
                "# Default sleep 1s and re-screenshot. Pass wait(seconds=5) for slow page loads (max 60).",
            ),
            ActionSpec::with_note(
                "activate_app(app='AppName')",
                "# Bring an app forward when it's not visible. Use BEFORE clicking when the target app isn't on screen.",
            ),
            ActionSpec::new("finished(content='xxx')"),
            ActionSpec::with_note(
                "call_user()",
                "# Submit and call user when stuck or need help",
            ),
        ]
    }

    fn screenshot(&self) -> ScreenshotFut<'_> {
        Box::pin(async move {
            tokio::task::spawn_blocking(capture_primary_screen)
                .await
                .context("screenshot blocking task join failed")?
        })
    }

    fn execute<'a>(&'a self, action: &'a Action, ctx: &'a ExecCtx) -> ActionFut<'a> {
        Box::pin(async move {
            // Clone what we need into the blocking task (Action is
            // Clone, ExecCtx is Copy).
            let action = action.clone();
            let ctx = *ctx;

            // Wait + Finished + CallUser are pure tokio — no enigo,
            // no spawn_blocking. Handle them up front.
            match &action {
                Action::Wait { seconds } => {
                    let s = seconds.clamp(0.0, 60.0);
                    tokio::time::sleep(Duration::from_secs_f32(s)).await;
                    return Ok(ActionOutput::ok());
                }
                Action::Finished { content } => {
                    debug!(content = %content, "native operator: finished");
                    return Ok(ActionOutput::ok());
                }
                Action::CallUser { reason } => {
                    debug!(reason = %reason, "native operator: call_user");
                    return Ok(ActionOutput::ok());
                }
                Action::ActivateApp { app } => {
                    return activate_app(app).await;
                }
                _ => {}
            }

            tokio::task::spawn_blocking(move || execute_blocking(&action, &ctx))
                .await
                .context("execute blocking task join failed")?
        })
    }
}

// ---------------------------------------------------------------------------
// Screenshot
// ---------------------------------------------------------------------------

/// Capture the primary monitor and encode as PNG.
fn capture_primary_screen() -> Result<Screenshot> {
    let monitors = Monitor::all().map_err(|e| anyhow!("xcap::Monitor::all failed: {e}"))?;
    if monitors.is_empty() {
        return Err(anyhow!("no monitors detected"));
    }

    // Prefer the primary; fall back to the first if `is_primary` errors
    // (xcap occasionally returns errors on fresh sessions).
    let monitor = monitors
        .iter()
        .find(|m| m.is_primary().unwrap_or(false))
        .unwrap_or(&monitors[0])
        .clone();

    let scale_factor = monitor.scale_factor().unwrap_or(1.0);
    let monitor_w = monitor.width().unwrap_or(0);
    let monitor_h = monitor.height().unwrap_or(0);

    let img: RgbaImage = monitor
        .capture_image()
        .map_err(|e| anyhow!("xcap capture_image failed: {e}"))?;

    let physical_w = img.width();
    let physical_h = img.height();

    // xcap's `width`/`height` reports the physical pixel size on macOS
    // Retina, so logical = physical / scale_factor. If the monitor
    // metadata disagrees with the captured image (rare), trust the
    // image.
    let _ = (monitor_w, monitor_h);

    let logical_w = if scale_factor > 0.0 {
        (physical_w as f32 / scale_factor).round() as u32
    } else {
        physical_w
    };
    let logical_h = if scale_factor > 0.0 {
        (physical_h as f32 / scale_factor).round() as u32
    } else {
        physical_h
    };

    // Encode RGBA -> PNG via the `image` crate.
    let mut png_bytes: Vec<u8> = Vec::with_capacity(physical_w as usize * physical_h as usize / 4);
    {
        let mut cursor = std::io::Cursor::new(&mut png_bytes);
        img.write_to(&mut cursor, ImageFormat::Png)
            .context("PNG encode failed")?;
    }

    Ok(Screenshot {
        png_bytes,
        logical_size: (logical_w, logical_h),
        physical_size: (physical_w, physical_h),
        scale_factor,
    })
}

// ---------------------------------------------------------------------------
// Action dispatch
// ---------------------------------------------------------------------------

/// Execute a non-async action on the calling thread with a fresh
/// `Enigo`. Any input error is reported back via `ActionOutput::err`
/// so the driver can feed it into the next turn rather than blowing
/// up the whole loop.
fn execute_blocking(action: &Action, ctx: &ExecCtx) -> Result<ActionOutput> {
    let mut enigo = match Enigo::new(&Settings::default()) {
        Ok(e) => e,
        Err(e) => {
            // The most common Enigo init failure on macOS is a missing
            // Accessibility / Input-Monitoring grant — the message
            // returned by enigo itself ("the application does not have
            // the permission to simulate input") is correct but doesn't
            // tell the user where to fix it. Surface a one-shot
            // actionable hint here so the operator-error gets surfaced
            // to the agent loop with concrete remediation steps.
            let err_str = e.to_string();
            let hint = if cfg!(target_os = "macos")
                && (err_str.contains("permission") || err_str.contains("simulate input"))
            {
                " (macOS: open System Settings -> Privacy & Security -> \
                 Accessibility AND Input Monitoring, then add the \
                 currently-running rsclaw binary at \
                 target/debug/rsclaw or target/release/rsclaw. \
                 Restart the gateway after granting.)"
            } else {
                ""
            };
            warn!(error = %e, hint, "failed to construct Enigo");
            return Ok(ActionOutput::err(format!("enigo init failed: {e}{hint}")));
        }
    };

    match action {
        Action::MouseMove { x, y } => {
            let (lx, ly) = scale_for_input(*x, *y, ctx.scale_factor);
            try_input(enigo.move_mouse(lx, ly, Coordinate::Abs), "move_mouse")
        }
        Action::Click { x, y, button } => {
            let (lx, ly) = scale_for_input(*x, *y, ctx.scale_factor);
            if let Err(msg) = ok_or_msg(enigo.move_mouse(lx, ly, Coordinate::Abs), "move_mouse") {
                return Ok(ActionOutput::err(msg));
            }
            let btn = map_button(*button);
            try_input(enigo.button(btn, Click), "button")
        }
        Action::DoubleClick { x, y } => {
            let (lx, ly) = scale_for_input(*x, *y, ctx.scale_factor);
            if let Err(msg) = ok_or_msg(enigo.move_mouse(lx, ly, Coordinate::Abs), "move_mouse") {
                return Ok(ActionOutput::err(msg));
            }
            if let Err(msg) = ok_or_msg(enigo.button(Button::Left, Click), "button") {
                return Ok(ActionOutput::err(msg));
            }
            try_input(enigo.button(Button::Left, Click), "button")
        }
        Action::Drag {
            from_x,
            from_y,
            to_x,
            to_y,
        } => {
            let (fx, fy) = scale_for_input(*from_x, *from_y, ctx.scale_factor);
            let (tx, ty) = scale_for_input(*to_x, *to_y, ctx.scale_factor);
            if let Err(msg) = ok_or_msg(enigo.move_mouse(fx, fy, Coordinate::Abs), "move_mouse") {
                return Ok(ActionOutput::err(msg));
            }
            if let Err(msg) = ok_or_msg(enigo.button(Button::Left, Press), "button press") {
                return Ok(ActionOutput::err(msg));
            }
            if let Err(msg) = ok_or_msg(enigo.move_mouse(tx, ty, Coordinate::Abs), "drag move") {
                // Best-effort release before bailing.
                let _ = enigo.button(Button::Left, Release);
                return Ok(ActionOutput::err(msg));
            }
            try_input(enigo.button(Button::Left, Release), "button release")
        }
        Action::Scroll {
            x,
            y,
            direction,
            clicks,
        } => {
            let (lx, ly) = scale_for_input(*x, *y, ctx.scale_factor);
            // Move first so the scroll lands at the requested point.
            if let Err(msg) = ok_or_msg(enigo.move_mouse(lx, ly, Coordinate::Abs), "move_mouse") {
                return Ok(ActionOutput::err(msg));
            }
            let (axis, length) = scroll_amount(*direction, *clicks);
            try_input(enigo.scroll(length, axis), "scroll")
        }
        Action::Type { text } => type_text(&mut enigo, text),
        Action::Hotkey { keys } => press_hotkey(&mut enigo, keys),
        Action::HoldKey { key, seconds } => {
            let Some(k) = parse_key(key) else {
                return Ok(ActionOutput::err(format!("unknown key: {key}")));
            };
            let s = seconds.clamp(0.0, 60.0);
            if let Err(msg) = ok_or_msg(enigo.key(k, Press), "key press") {
                return Ok(ActionOutput::err(msg));
            }
            std::thread::sleep(Duration::from_secs_f32(s));
            try_input(enigo.key(k, Release), "key release")
        }
        Action::Screenshot => {
            // Mainly a no-op gate in some retry patterns. Capture and
            // discard so call sites that rely on the side effect of a
            // fresh frame still get one.
            let _ = capture_primary_screen()?;
            Ok(ActionOutput::ok())
        }
        // The async variants are handled before we reach this function.
        Action::Wait { .. }
        | Action::Finished { .. }
        | Action::CallUser { .. }
        | Action::ActivateApp { .. } => Ok(ActionOutput::ok()),
    }
}

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

/// Map physical-pixel coordinates from the screenshot into the
/// coordinate space `enigo` expects on this platform.
///
/// On macOS Retina, `enigo` takes logical pixels (physical / scale).
/// On Windows and Linux X11 the input APIs are physical. We branch at
/// runtime via `cfg!` so a single source file covers all platforms.
fn scale_for_input(x: i32, y: i32, scale_factor: f32) -> (i32, i32) {
    if cfg!(target_os = "macos") && scale_factor > 0.0 && (scale_factor - 1.0).abs() > f32::EPSILON
    {
        let lx = (x as f32 / scale_factor).round() as i32;
        let ly = (y as f32 / scale_factor).round() as i32;
        (lx, ly)
    } else {
        (x, y)
    }
}

/// Map our `MouseButton` to enigo's `Button`.
fn map_button(b: MouseButton) -> Button {
    match b {
        MouseButton::Left => Button::Left,
        MouseButton::Right => Button::Right,
        MouseButton::Middle => Button::Middle,
    }
}

/// Translate a scroll direction + click count into enigo's `(length, axis)`.
fn scroll_amount(dir: ScrollDir, clicks: i32) -> (Axis, i32) {
    match dir {
        ScrollDir::Up => (Axis::Vertical, -clicks),
        ScrollDir::Down => (Axis::Vertical, clicks),
        ScrollDir::Left => (Axis::Horizontal, -clicks),
        ScrollDir::Right => (Axis::Horizontal, clicks),
    }
}

/// Decode the common JSON / Python-string escape sequences a VLM is likely
/// to emit inside a `type(content='…')` call. The VLM action parser
/// (`computer/parser.rs:303`) intentionally preserves backslash escapes
/// verbatim — the "operator decides what to do with the literal \n" —
/// which means without this pass `type(content='hi\n')` lands as the
/// six chars `h i \ n` typed into whatever app is focused (e.g. WeChat
/// shows literal `hi\n` instead of sending "hi" + Enter).
///
/// Recognised escapes: `\n` `\t` `\r` `\\` `\'` `\"` `\0`, plus
/// `\xHH` (two hex digits) and `\uXXXX` (four hex digits, Unicode
/// code point). Unknown or malformed escapes (e.g. `\q`, `\u12`)
/// are preserved verbatim so a content string containing a real
/// backslash doesn't get silently mangled.
fn decode_string_escapes(s: &str) -> String {
    let cv: Vec<char> = s.chars().collect();
    let mut out = String::with_capacity(s.len());
    let mut i = 0;
    while i < cv.len() {
        let c = cv[i];
        if c != '\\' || i + 1 >= cv.len() {
            out.push(c);
            i += 1;
            continue;
        }
        let next = cv[i + 1];
        match next {
            'n' => {
                out.push('\n');
                i += 2;
            }
            't' => {
                out.push('\t');
                i += 2;
            }
            'r' => {
                out.push('\r');
                i += 2;
            }
            '\\' => {
                out.push('\\');
                i += 2;
            }
            '\'' => {
                out.push('\'');
                i += 2;
            }
            '"' => {
                out.push('"');
                i += 2;
            }
            '0' => {
                out.push('\0');
                i += 2;
            }
            'x' if i + 3 < cv.len()
                && cv[i + 2].is_ascii_hexdigit()
                && cv[i + 3].is_ascii_hexdigit() =>
            {
                // `\xHH` — two hex digits, 0x00..=0xFF.
                let v = (cv[i + 2].to_digit(16).unwrap() << 4) | cv[i + 3].to_digit(16).unwrap();
                if let Some(ch) = char::from_u32(v) {
                    out.push(ch);
                    i += 4;
                } else {
                    out.push('\\');
                    out.push('x');
                    i += 2;
                }
            }
            'u' if i + 5 < cv.len()
                && cv[i + 2..=i + 5].iter().all(char::is_ascii_hexdigit) =>
            {
                // `\uXXXX` — four hex digits. The VLM occasionally
                // emits Unicode escapes for CJK input.
                let v = (cv[i + 2].to_digit(16).unwrap() << 12)
                    | (cv[i + 3].to_digit(16).unwrap() << 8)
                    | (cv[i + 4].to_digit(16).unwrap() << 4)
                    | cv[i + 5].to_digit(16).unwrap();
                if let Some(ch) = char::from_u32(v) {
                    out.push(ch);
                    i += 6;
                } else {
                    out.push('\\');
                    out.push('u');
                    i += 2;
                }
            }
            other => {
                out.push('\\');
                out.push(other);
                i += 2;
            }
        }
    }
    out
}

/// Type literal text. If the text ends with `\n` (real or escaped), strip
/// the newline and submit via `Return` to mirror NutJSOperator semantics.
/// Decodes common backslash escapes first so `type(content='hi\n')` from
/// the VLM doesn't land as a literal `hi\n` in the focused window.
fn type_text(enigo: &mut Enigo, text: &str) -> Result<ActionOutput> {
    let decoded = decode_string_escapes(text);
    let submit = decoded.ends_with('\n');
    let body: &str = if submit {
        decoded.strip_suffix('\n').unwrap_or(&decoded)
    } else {
        &decoded
    };

    if !body.is_empty() {
        if let Err(msg) = ok_or_msg(enigo.text(body), "type text") {
            return Ok(ActionOutput::err(msg));
        }
    }

    if submit {
        return try_input(enigo.key(Key::Return, Click), "submit return");
    }
    Ok(ActionOutput::ok())
}

/// Parse and execute a hotkey combination.
///
/// Tokens are separated by whitespace or `+`, lowercased before
/// lookup. The combo is press-all-then-release-in-reverse so chord
/// semantics work (e.g. `cmd shift t` re-opens the last tab).
/// Capped at 4 keys to keep the LLM honest — anything longer is
/// almost certainly a parse error or hallucination.
fn press_hotkey(enigo: &mut Enigo, keys: &str) -> Result<ActionOutput> {
    let tokens: Vec<&str> = keys
        .split(|c: char| c.is_whitespace() || c == '+')
        .filter(|s| !s.is_empty())
        .collect();

    if tokens.is_empty() {
        return Ok(ActionOutput::err("empty hotkey"));
    }
    if tokens.len() > 4 {
        return Ok(ActionOutput::err(format!(
            "hotkey too long ({} keys, max 4)",
            tokens.len()
        )));
    }

    let mut parsed: Vec<Key> = Vec::with_capacity(tokens.len());
    for tok in &tokens {
        match parse_key(tok) {
            Some(k) => parsed.push(k),
            None => return Ok(ActionOutput::err(format!("unknown key: {tok}"))),
        }
    }

    // Press in order.
    let mut pressed: Vec<Key> = Vec::with_capacity(parsed.len());
    for k in &parsed {
        if let Err(msg) = ok_or_msg(enigo.key(*k, Press), "hotkey press") {
            // Release whatever we managed to press.
            for held in pressed.iter().rev() {
                let _ = enigo.key(*held, Release);
            }
            return Ok(ActionOutput::err(msg));
        }
        pressed.push(*k);
    }

    // Release in reverse.
    let mut last_err: Option<String> = None;
    for k in parsed.iter().rev() {
        if let Err(msg) = ok_or_msg(enigo.key(*k, Release), "hotkey release") {
            last_err = Some(msg);
        }
    }
    match last_err {
        Some(msg) => Ok(ActionOutput::err(msg)),
        None => Ok(ActionOutput::ok()),
    }
}

/// Map a single key token (already lowercased after split) to an
/// `enigo::Key`. Returns `None` for unrecognised tokens so the caller
/// can surface a useful error instead of silently dropping the input.
fn parse_key(raw: &str) -> Option<Key> {
    let key = raw.trim().to_lowercase();
    let k = match key.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,
        // Single-char fallback (a-z, 0-9, punctuation).
        s if s.chars().count() == 1 => Key::Unicode(s.chars().next()?),
        _ => return None,
    };
    Some(k)
}

/// Wrap an enigo `InputResult` into a simple `Result<(), String>`.
fn ok_or_msg<E: std::fmt::Display>(
    res: std::result::Result<(), E>,
    op: &'static str,
) -> std::result::Result<(), String> {
    res.map_err(|e| format!("{op}: {e}"))
}

/// Bridge `enigo` errors into `ActionOutput` so the driver can keep
/// going on a single failed action.
fn try_input<E: std::fmt::Display>(
    res: std::result::Result<(), E>,
    op: &'static str,
) -> Result<ActionOutput> {
    match res {
        Ok(()) => Ok(ActionOutput::ok()),
        Err(e) => {
            warn!(operation = op, error = %e, "enigo input error");
            Ok(ActionOutput::err(format!("{op}: {e}")))
        }
    }
}

// ---------------------------------------------------------------------------
// activate_app — platform-specific shell-out
// ---------------------------------------------------------------------------

/// Bring **all** windows of the named application to the front.
///
/// macOS uses `osascript`. Windows uses PowerShell (EnumWindows-via-
/// process). Linux uses `wmctrl` first, then `xdotool` as a fallback.
/// On unsupported platforms returns `ActionOutput::err` instead of
/// panicking.
async fn activate_app(app: &str) -> Result<ActionOutput> {
    let app = app.to_owned();
    let res = tokio::task::spawn_blocking(move || activate_app_blocking(&app))
        .await
        .context("activate_app join failed")?;
    Ok(res)
}

fn activate_app_blocking(app: &str) -> ActionOutput {
    #[cfg(target_os = "macos")]
    {
        let mut errors = Vec::new();
        for candidate in macos_app_candidates(app) {
            match activate_macos_app(&candidate) {
                Ok(()) => return ActionOutput::ok(),
                Err(e) => errors.push(format!("{candidate}: {e}")),
            }
        }
        return ActionOutput::err(format!("activate_app failed: {}", errors.join("; ")));
    }
    #[cfg(not(target_os = "macos"))]
    activate_app_blocking_non_macos(app)
}

#[cfg(not(target_os = "macos"))]
fn activate_app_blocking_non_macos(app: &str) -> ActionOutput {
    if cfg!(target_os = "windows") {
        // PowerShell pipeline: enumerate every process whose name
        // matches and hand its main window to SetForegroundWindow.
        // TODO(v2): replace with `windows` crate EnumWindows + per-PID
        // SetForegroundWindow to bring secondary windows too.
        // Two layers of escaping inside one literal:
        //   - PowerShell single-quoted strings: `'` is doubled.
        //   - `-like` glob pattern: `*` and `?` are wildcards; escape with PowerShell's
        //     backtick so an app name literally containing them matches only that
        //     character. Without this, an app named `Microsoft Edge*` (or VLM
        //     hallucinating a trailing `*`) would match every process — bringing a
        //     random app forward instead of the requested one. R3 review I5.
        let escaped = app
            .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() => ActionOutput::ok(),
            Ok(out) => {
                let stderr = String::from_utf8_lossy(&out.stderr).into_owned();
                ActionOutput::err(format!("powershell failed: {stderr}"))
            }
            Err(e) => ActionOutput::err(format!("powershell spawn failed: {e}")),
        }
    } else if cfg!(target_os = "linux") {
        // Try wmctrl first (matches by visible window title), then
        // xdotool by class. Either being absent is a soft error.
        let wmctrl = Command::new("wmctrl").args(["-a", &app]).status();
        if matches!(&wmctrl, Ok(s) if s.success()) {
            return ActionOutput::ok();
        }
        let xdotool = Command::new("xdotool")
            .args(["search", "--class", &app, "windowactivate"])
            .status();
        match xdotool {
            Ok(s) if s.success() => ActionOutput::ok(),
            Ok(s) => ActionOutput::err(format!("xdotool exit status: {s}")),
            Err(e) => ActionOutput::err(format!("neither wmctrl nor xdotool worked: {e}")),
        }
    } else {
        ActionOutput::err("activate_app: unsupported platform")
    }
}

#[cfg(target_os = "macos")]
fn macos_app_candidates(app: &str) -> Vec<String> {
    let trimmed = app.trim();
    let mut candidates = Vec::new();
    if !trimmed.is_empty() {
        candidates.push(trimmed.to_owned());
    }
    match trimmed.to_ascii_lowercase().as_str() {
        "wechat" => {
            candidates.push("WeChat".to_owned());
            candidates.push("微信".to_owned());
        }
        "weixin" => {
            candidates.push("WeChat".to_owned());
            candidates.push("微信".to_owned());
        }
        "douyin" | "tiktok" => candidates.push("抖音".to_owned()),
        _ => {}
    }
    candidates.dedup();
    candidates
}

#[cfg(target_os = "macos")]
fn activate_macos_app(app: &str) -> std::result::Result<(), String> {
    let escaped = app.replace('\\', "\\\\").replace('"', "\\\"");
    let script = format!(
        r#"tell application "{escaped}" to activate
delay 0.4
tell application "System Events"
  if exists process "{escaped}" then
    tell process "{escaped}"
      set frontmost to true
      if (count of windows) > 0 then
        try
          perform action "AXRaise" of window 1
        end try
      end if
    end tell
  end if
end tell"#
    );
    match Command::new("osascript").arg("-e").arg(&script).output() {
        Ok(out) if out.status.success() => Ok(()),
        Ok(out) => {
            let stderr = String::from_utf8_lossy(&out.stderr).trim().to_owned();
            let open = Command::new("open").args(["-a", app]).output();
            match open {
                Ok(open_out) if open_out.status.success() => {
                    std::thread::sleep(Duration::from_millis(ACTIVATE_DELAY_MS));
                    Ok(())
                }
                Ok(open_out) => {
                    let open_stderr = String::from_utf8_lossy(&open_out.stderr).trim().to_owned();
                    Err(format!(
                        "osascript failed: {stderr}; open -a failed: {open_stderr}"
                    ))
                }
                Err(e) => Err(format!(
                    "osascript failed: {stderr}; open -a spawn failed: {e}"
                )),
            }
        }
        Err(e) => Err(format!("osascript spawn failed: {e}")),
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    #[test]
    fn default_constructs() {
        // Calls Default explicitly through the trait so the test
        // catches accidental removal of `impl Default for
        // NativeOperator`. `<T as Default>::default()` keeps the trait
        // dispatch path visible without tripping
        // clippy::default_constructed_unit_structs (the lint targets
        // the field-syntax `T::default()` shorthand on unit structs).
        let _op: NativeOperator = <NativeOperator as Default>::default();
        let _op2 = NativeOperator::new();
    }

    #[test]
    fn name_is_native() {
        let op = NativeOperator::new();
        assert_eq!(op.name(), "native");
    }

    #[test]
    fn action_spaces_advertise_core_capabilities() {
        let op = NativeOperator::new();
        let specs = op.action_spaces();
        assert!(
            specs.len() >= 9,
            "expected at least 9 action specs, got {}",
            specs.len()
        );
        let sigs: Vec<&str> = specs.iter().map(|s| s.signature).collect();
        for needle in ["click", "type", "hotkey", "scroll", "wait", "finished"] {
            assert!(
                sigs.iter().any(|s| s.contains(needle)),
                "action_spaces missing `{needle}`: {:?}",
                sigs
            );
        }
    }

    #[test]
    fn parse_key_handles_modifiers_and_chars() {
        assert!(matches!(parse_key("cmd"), Some(Key::Meta)));
        assert!(matches!(parse_key("CTRL"), Some(Key::Control)));
        assert!(matches!(parse_key("return"), Some(Key::Return)));
        assert!(matches!(parse_key("a"), Some(Key::Unicode('a'))));
        assert!(parse_key("not-a-real-key").is_none());
    }

    #[test]
    fn scroll_amount_signs() {
        assert_eq!(scroll_amount(ScrollDir::Up, 3), (Axis::Vertical, -3));
        assert_eq!(scroll_amount(ScrollDir::Down, 3), (Axis::Vertical, 3));
        assert_eq!(scroll_amount(ScrollDir::Left, 2), (Axis::Horizontal, -2));
        assert_eq!(scroll_amount(ScrollDir::Right, 2), (Axis::Horizontal, 2));
    }

    #[test]
    fn decode_string_escapes_handles_common_sequences() {
        // The VLM parser preserves \n etc. verbatim — type_text must decode
        // before driving enigo, else WeChat etc. shows literal `hi\n`.
        assert_eq!(decode_string_escapes(r"hi\n"), "hi\n");
        assert_eq!(decode_string_escapes(r"tab\there"), "tab\there");
        assert_eq!(decode_string_escapes(r"crlf\r\n"), "crlf\r\n");
        assert_eq!(decode_string_escapes(r"quote\'mark"), "quote'mark");
        assert_eq!(decode_string_escapes(r#"dquote\""#), "dquote\"");
        assert_eq!(decode_string_escapes(r"slash\\path"), r"slash\path");
        // Unknown escape preserved verbatim (don't silently mangle a
        // legitimate backslash followed by an unrecognised char).
        assert_eq!(decode_string_escapes(r"unknown\x"), r"unknown\x");
        // Trailing lone backslash also preserved.
        assert_eq!(decode_string_escapes(r"trail\"), r"trail\");
        // Plain text unchanged.
        assert_eq!(
            decode_string_escapes("正式版即将上线,敬请期待。"),
            "正式版即将上线,敬请期待。"
        );
    }

    #[test]
    fn decode_string_escapes_handles_hex_and_unicode() {
        // `\xHH` — two hex digits → byte cast to char (0..=0xFF).
        assert_eq!(decode_string_escapes(r"a\x41b"), "aAb");
        assert_eq!(decode_string_escapes(r"\x00end"), "\0end");
        // `\uXXXX` — four hex digits → Unicode code point. VLMs sometimes
        // emit Unicode escapes for CJK content. Build the input string
        // programmatically so the source file doesn't need to spell out
        // the raw `\u...` escape syntax inline (which gets confused
        // through editors that auto-process the sequence).
        let cjk_input = format!("hi {}u4e2d!", '\\');
        assert_eq!(
            decode_string_escapes(&cjk_input),
            format!("hi {}!", '\u{4e2d}')
        );
        let acc_input = format!("{}u00e9clair", '\\');
        assert_eq!(
            decode_string_escapes(&acc_input),
            format!("{}clair", '\u{00e9}')
        );
        // Truncated / malformed forms preserve verbatim.
        assert_eq!(decode_string_escapes(r"\xZZ"), r"\xZZ");
        assert_eq!(decode_string_escapes(r"\u12"), r"\u12");
        // Surrogate code points (0xD800..=0xDFFF) are invalid Unicode
        // scalars and must NOT panic — fall through verbatim.
        assert_eq!(decode_string_escapes(r"\ud800"), r"\ud800");
    }
}