Skip to main content

strata/
mcp_bridge.rs

1//! Model Context Protocol (MCP) Dev Bridge and In-Process IPC Dispatcher.
2//!
3//! Provides the bidirectional communication pipeline connecting external AI agents
4//! to active Strata runtime windows, emulating mouse movements with authentic Yaru
5//! cursor overlays, taking high-resolution screenshots, and safely batching UI actions.
6
7use serde_json::{json, Value};
8use std::io::{BufRead, BufReader, Read, Write};
9#[cfg(not(unix))]
10use std::net::TcpListener;
11#[cfg(unix)]
12use std::os::unix::net::{UnixListener, UnixStream};
13use std::path::PathBuf;
14use std::sync::mpsc::{channel, Sender};
15use std::sync::Mutex;
16use std::time::Duration;
17
18use crate::runtime::AppRuntime;
19use strata_platform::{KeyCode, Modifiers, MouseButton, PlatformEvent};
20
21type PendingItem = (String, Sender<String>);
22
23fn get_pending_queue() -> &'static Mutex<Vec<PendingItem>> {
24    static QUEUE: std::sync::OnceLock<Mutex<Vec<PendingItem>>> = std::sync::OnceLock::new();
25    QUEUE.get_or_init(|| Mutex::new(Vec::new()))
26}
27
28#[cfg(unix)]
29fn get_current_uid() -> u32 {
30    extern "C" {
31        fn getuid() -> u32;
32    }
33    unsafe { getuid() }
34}
35
36#[cfg(target_os = "linux")]
37fn verify_peer_credentials(stream: &UnixStream) -> Result<(), std::io::Error> {
38    use std::os::unix::io::AsRawFd;
39
40    #[repr(C)]
41    struct UCred {
42        pid: i32,
43        uid: u32,
44        gid: u32,
45    }
46
47    extern "C" {
48        fn getsockopt(
49            sockfd: std::os::raw::c_int,
50            level: std::os::raw::c_int,
51            optname: std::os::raw::c_int,
52            optval: *mut std::os::raw::c_void,
53            optlen: *mut u32,
54        ) -> std::os::raw::c_int;
55    }
56
57    let fd = stream.as_raw_fd();
58    let mut ucred = UCred {
59        pid: 0,
60        uid: u32::MAX,
61        gid: u32::MAX,
62    };
63    let mut len = std::mem::size_of::<UCred>() as u32;
64
65    const SOL_SOCKET: std::os::raw::c_int = 1;
66    const SO_PEERCRED: std::os::raw::c_int = 17;
67
68    let res = unsafe {
69        getsockopt(
70            fd,
71            SOL_SOCKET,
72            SO_PEERCRED,
73            &mut ucred as *mut _ as *mut std::os::raw::c_void,
74            &mut len as *mut u32,
75        )
76    };
77
78    if res != 0 {
79        return Err(std::io::Error::last_os_error());
80    }
81
82    let my_uid = get_current_uid();
83    if ucred.uid != my_uid {
84        return Err(std::io::Error::new(
85            std::io::ErrorKind::PermissionDenied,
86            format!(
87                "Peer UID {} does not match process UID {}",
88                ucred.uid, my_uid
89            ),
90        ));
91    }
92
93    Ok(())
94}
95
96#[cfg(any(target_os = "macos", target_os = "ios"))]
97fn verify_peer_credentials(stream: &UnixStream) -> Result<(), std::io::Error> {
98    use std::os::unix::io::AsRawFd;
99
100    extern "C" {
101        fn getpeereid(
102            s: std::os::raw::c_int,
103            euid: *mut u32,
104            egid: *mut u32,
105        ) -> std::os::raw::c_int;
106    }
107
108    let fd = stream.as_raw_fd();
109    let mut euid = u32::MAX;
110    let mut egid = u32::MAX;
111    let res = unsafe { getpeereid(fd, &mut euid, &mut egid) };
112    if res != 0 {
113        return Err(std::io::Error::last_os_error());
114    }
115
116    let my_uid = get_current_uid();
117    if euid != my_uid {
118        return Err(std::io::Error::new(
119            std::io::ErrorKind::PermissionDenied,
120            format!("Peer UID {} does not match process UID {}", euid, my_uid),
121        ));
122    }
123
124    Ok(())
125}
126
127#[cfg(all(unix, not(any(target_os = "linux", target_os = "macos", target_os = "ios"))))]
128fn verify_peer_credentials(_stream: &UnixStream) -> Result<(), std::io::Error> {
129    Ok(())
130}
131
132/// Spawns a background thread listening for MCP connections over Unix domain sockets (Unix)
133/// or localhost TCP (Windows, advertising `127.0.0.1:<port>` in `socket_path`).
134pub fn start_mcp_dev_listener(socket_path: Option<PathBuf>) -> Result<(), std::io::Error> {
135    let path = socket_path.unwrap_or_else(default_dev_socket_path);
136
137    // Clean up stale socket/descriptor file if present
138    if path.exists() {
139        let _ = std::fs::remove_file(&path);
140    }
141
142    if let Some(parent) = path.parent() {
143        #[cfg(unix)]
144        {
145            use std::os::unix::fs::DirBuilderExt;
146            let mut builder = std::fs::DirBuilder::new();
147            builder.recursive(true);
148            builder.mode(0o700);
149            let _ = builder.create(parent);
150            use std::os::unix::fs::PermissionsExt;
151            let _ = std::fs::set_permissions(parent, std::fs::Permissions::from_mode(0o700));
152        }
153        #[cfg(not(unix))]
154        {
155            let _ = std::fs::create_dir_all(parent);
156        }
157    }
158
159    #[cfg(unix)]
160    {
161        let listener = UnixListener::bind(&path)?;
162        use std::os::unix::fs::PermissionsExt;
163        let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600));
164
165        std::thread::Builder::new()
166            .name("strata-mcp-ipc-listener".to_string())
167            .spawn(move || {
168                for stream in listener.incoming().flatten() {
169                    if verify_peer_credentials(&stream).is_ok() {
170                        let _ = stream.set_read_timeout(Some(Duration::from_secs(30)));
171                        let _ = stream.set_write_timeout(Some(Duration::from_secs(30)));
172                        if let Ok(reader_stream) = stream.try_clone() {
173                            handle_client_connection(BufReader::new(reader_stream), stream);
174                        }
175                    }
176                }
177            })?;
178    }
179
180    #[cfg(not(unix))]
181    {
182        let listener = TcpListener::bind("127.0.0.1:0")?;
183        let local_addr = listener.local_addr()?.to_string();
184        std::fs::write(&path, &local_addr)?;
185
186        std::thread::Builder::new()
187            .name("strata-mcp-ipc-listener".to_string())
188            .spawn(move || {
189                for stream in listener.incoming().flatten() {
190                    let _ = stream.set_read_timeout(Some(Duration::from_secs(30)));
191                    let _ = stream.set_write_timeout(Some(Duration::from_secs(30)));
192                    if let Ok(reader_stream) = stream.try_clone() {
193                        handle_client_connection(BufReader::new(reader_stream), stream);
194                    }
195                }
196            })?;
197    }
198
199    Ok(())
200}
201
202fn dispatch_to_ui_thread(req_json: String) -> String {
203    let (tx, rx) = channel();
204    if let Ok(mut q) = get_pending_queue().lock() {
205        q.push((req_json, tx));
206    }
207
208    // Signal GTK main event loop to wake up and process the queue
209    #[cfg(target_os = "linux")]
210    strata_platform::post_platform_event(strata_platform::PlatformEvent::RedrawRequested);
211
212    match rx.recv_timeout(Duration::from_secs(5)) {
213        Ok(res) => res,
214        Err(_) => json!({
215            "jsonrpc": "2.0",
216            "error": { "code": -32000, "message": "Request timed out waiting for UI thread" }
217        })
218        .to_string(),
219    }
220}
221
222/// Splits an `execute_actions` request on `"wait"` steps so every delay sleeps on the background
223/// IPC thread instead of blocking the UI main thread or polluting `input_dispatch_us`.
224fn execute_actions_nonblocking_on_ipc_thread(id: Value, actions: &[Value]) -> String {
225    let mut total_executed: u64 = 0;
226    let mut pending_batch: Vec<Value> = Vec::new();
227
228    for act in actions {
229        if act.get("action").and_then(|v| v.as_str()) == Some("wait") {
230            if !pending_batch.is_empty() {
231                let batch = std::mem::take(&mut pending_batch);
232                let sub_req = json!({
233                    "jsonrpc": "2.0",
234                    "id": id,
235                    "method": "execute_actions",
236                    "params": { "actions": batch },
237                });
238                let resp_str = dispatch_to_ui_thread(sub_req.to_string());
239                if let Ok(parsed) = serde_json::from_str::<Value>(&resp_str) {
240                    if parsed.get("error").is_some() {
241                        return resp_str;
242                    }
243                    total_executed += parsed
244                        .get("result")
245                        .and_then(|r| r.get("executed_actions"))
246                        .and_then(|v| v.as_u64())
247                        .unwrap_or(0);
248                } else {
249                    return resp_str;
250                }
251            }
252            let ms = act
253                .get("ms")
254                .and_then(|m| m.as_u64())
255                .unwrap_or(50)
256                .min(5000);
257            if ms > 0 {
258                std::thread::sleep(Duration::from_millis(ms));
259            }
260            total_executed += 1;
261        } else {
262            pending_batch.push(act.clone());
263        }
264    }
265
266    if !pending_batch.is_empty() {
267        let sub_req = json!({
268            "jsonrpc": "2.0",
269            "id": id,
270            "method": "execute_actions",
271            "params": { "actions": pending_batch },
272        });
273        let resp_str = dispatch_to_ui_thread(sub_req.to_string());
274        if let Ok(parsed) = serde_json::from_str::<Value>(&resp_str) {
275            if parsed.get("error").is_some() {
276                return resp_str;
277            }
278            total_executed += parsed
279                .get("result")
280                .and_then(|r| r.get("executed_actions"))
281                .and_then(|v| v.as_u64())
282                .unwrap_or(0);
283        } else {
284            return resp_str;
285        }
286    }
287
288    json!({
289        "jsonrpc": "2.0",
290        "id": id,
291        "result": { "executed_actions": total_executed },
292    })
293    .to_string()
294}
295
296fn handle_client_connection<R: Read, W: Write>(mut reader: BufReader<R>, mut stream: W) {
297    let mut line = String::new();
298    while let Ok(n) = reader.read_line(&mut line) {
299        if n == 0 {
300            break;
301        }
302        let trimmed = line.trim();
303        if trimmed.is_empty() {
304            line.clear();
305            continue;
306        }
307
308        // Handle `execute_actions` batches containing `"wait"` on this background IPC thread so
309        // waiting never freezes the UI main thread or spikes `input_dispatch_us`.
310        let response = if let Ok(parsed) = serde_json::from_str::<Value>(trimmed) {
311            let is_exec_with_wait = parsed.get("method").and_then(|m| m.as_str())
312                == Some("execute_actions")
313                && parsed
314                    .get("params")
315                    .and_then(|p| p.get("actions"))
316                    .and_then(|a| a.as_array())
317                    .is_some_and(|arr| {
318                        arr.iter()
319                            .any(|a| a.get("action").and_then(|v| v.as_str()) == Some("wait"))
320                    });
321            if is_exec_with_wait {
322                let id = parsed.get("id").cloned().unwrap_or(Value::Null);
323                let actions = parsed
324                    .get("params")
325                    .and_then(|p| p.get("actions"))
326                    .and_then(|a| a.as_array())
327                    .cloned()
328                    .unwrap_or_default();
329                execute_actions_nonblocking_on_ipc_thread(id, &actions)
330            } else {
331                dispatch_to_ui_thread(trimmed.to_string())
332            }
333        } else {
334            dispatch_to_ui_thread(trimmed.to_string())
335        };
336
337        let mut out_bytes = response.into_bytes();
338        out_bytes.push(b'\n');
339        if stream.write_all(&out_bytes).is_err() {
340            break;
341        }
342        let _ = stream.flush();
343
344        line.clear();
345    }
346}
347
348/// Structured outcome returned when draining or executing MCP commands, separating full view
349/// rebuilds from paint-only redraws (e.g. fast-path hover restyling or cursor-only moves).
350#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
351pub struct McpDrainOutcome {
352    pub needs_rebuild: bool,
353    pub needs_redraw: bool,
354}
355
356impl McpDrainOutcome {
357    pub fn merge(&mut self, other: Self) {
358        self.needs_rebuild |= other.needs_rebuild;
359        self.needs_redraw |= other.needs_redraw;
360    }
361
362    pub fn any_dirty(self) -> bool {
363        self.needs_rebuild || self.needs_redraw
364    }
365}
366
367/// Dispatches a synthetic MCP [`PlatformEvent`] through DevTools (when enabled) and the host
368/// application's event hook (`launch_with_events` / `launch_with_frame`), returning
369/// `(intercepted_by_devtools, needs_rebuild, needs_redraw)`.
370fn dispatch_synthetic_event_to_hook<F>(
371    runtime: &mut AppRuntime,
372    event: &PlatformEvent,
373    user_event_hook: &mut F,
374) -> (bool, bool, bool)
375where
376    F: FnMut(&PlatformEvent, &mut AppRuntime) -> bool,
377{
378    #[cfg(feature = "devtools")]
379    if let Some(ref mut dt) = runtime.devtools {
380        if strata_devtools::DevToolsEventInterceptor::intercept(&mut dt.hud, event) {
381            runtime.mark_paint_dirty();
382            return (true, true, true);
383        }
384    }
385    let hook_signals_before = strata_dom::reactive::has_dirty_signals();
386    if user_event_hook(event, runtime)
387        || (!hook_signals_before && strata_dom::reactive::has_dirty_signals())
388    {
389        runtime.mark_paint_dirty();
390        (false, true, true)
391    } else {
392        (false, false, false)
393    }
394}
395
396fn current_mcp_pointer_pos(runtime: &AppRuntime) -> (f32, f32) {
397    runtime
398        .mcp_cursor
399        .as_ref()
400        .map(|c| (c.current_x, c.current_y))
401        .unwrap_or(runtime.last_mouse_pos)
402}
403
404fn exec_mcp_move<F>(
405    runtime: &mut AppRuntime,
406    x: f32,
407    y: f32,
408    smooth: bool,
409    user_event_hook: &mut F,
410) -> McpDrainOutcome
411where
412    F: FnMut(&PlatformEvent, &mut AppRuntime) -> bool,
413{
414    runtime.last_mouse_pos = (x, y);
415    let ev = PlatformEvent::MouseMove { x, y };
416    let (intercepted, h_rb, h_rd) = dispatch_synthetic_event_to_hook(runtime, &ev, user_event_hook);
417    if intercepted {
418        return McpDrainOutcome {
419            needs_rebuild: h_rb,
420            needs_redraw: h_rd,
421        };
422    }
423    let (rb, rd) = runtime.mcp_move_pointer_outcome(x, y, smooth);
424    McpDrainOutcome {
425        needs_rebuild: h_rb || rb,
426        needs_redraw: h_rd || rd,
427    }
428}
429
430fn exec_mcp_down<F>(
431    runtime: &mut AppRuntime,
432    button: MouseButton,
433    x: Option<f32>,
434    y: Option<f32>,
435    user_event_hook: &mut F,
436) -> McpDrainOutcome
437where
438    F: FnMut(&PlatformEvent, &mut AppRuntime) -> bool,
439{
440    let mut out = McpDrainOutcome::default();
441    let (px, py) = match (x, y) {
442        (Some(px), Some(py)) => {
443            out.merge(exec_mcp_move(runtime, px, py, false, user_event_hook));
444            (px, py)
445        }
446        _ => current_mcp_pointer_pos(runtime),
447    };
448    let ev = PlatformEvent::MouseDown {
449        button,
450        x: px,
451        y: py,
452    };
453    let (intercepted, h_rb, h_rd) = dispatch_synthetic_event_to_hook(runtime, &ev, user_event_hook);
454    out.merge(McpDrainOutcome {
455        needs_rebuild: h_rb,
456        needs_redraw: h_rd,
457    });
458    if !intercepted {
459        let (rb, rd) = runtime.mcp_mouse_down_outcome(button, None, None);
460        out.merge(McpDrainOutcome {
461            needs_rebuild: rb,
462            needs_redraw: rd,
463        });
464    }
465    out
466}
467
468fn exec_mcp_up<F>(
469    runtime: &mut AppRuntime,
470    button: MouseButton,
471    x: Option<f32>,
472    y: Option<f32>,
473    user_event_hook: &mut F,
474) -> McpDrainOutcome
475where
476    F: FnMut(&PlatformEvent, &mut AppRuntime) -> bool,
477{
478    let mut out = McpDrainOutcome::default();
479    let (px, py) = match (x, y) {
480        (Some(px), Some(py)) => {
481            out.merge(exec_mcp_move(runtime, px, py, false, user_event_hook));
482            (px, py)
483        }
484        _ => current_mcp_pointer_pos(runtime),
485    };
486    let ev = PlatformEvent::MouseUp {
487        button,
488        x: px,
489        y: py,
490    };
491    let (intercepted, h_rb, h_rd) = dispatch_synthetic_event_to_hook(runtime, &ev, user_event_hook);
492    out.merge(McpDrainOutcome {
493        needs_rebuild: h_rb,
494        needs_redraw: h_rd,
495    });
496    if !intercepted {
497        let (rb, rd) = runtime.mcp_mouse_up_outcome(button, None, None);
498        out.merge(McpDrainOutcome {
499            needs_rebuild: rb,
500            needs_redraw: rd,
501        });
502    }
503    out
504}
505
506fn exec_mcp_click<F>(
507    runtime: &mut AppRuntime,
508    button: MouseButton,
509    x: Option<f32>,
510    y: Option<f32>,
511    count: usize,
512    user_event_hook: &mut F,
513) -> McpDrainOutcome
514where
515    F: FnMut(&PlatformEvent, &mut AppRuntime) -> bool,
516{
517    let mut out = McpDrainOutcome::default();
518    if let (Some(px), Some(py)) = (x, y) {
519        out.merge(exec_mcp_move(runtime, px, py, false, user_event_hook));
520    }
521    for _ in 0..count.max(1) {
522        out.merge(exec_mcp_down(runtime, button, None, None, user_event_hook));
523        out.merge(exec_mcp_up(runtime, button, None, None, user_event_hook));
524    }
525    out
526}
527
528fn exec_mcp_scroll<F>(
529    runtime: &mut AppRuntime,
530    delta_x: f32,
531    delta_y: f32,
532    x: Option<f32>,
533    y: Option<f32>,
534    user_event_hook: &mut F,
535) -> McpDrainOutcome
536where
537    F: FnMut(&PlatformEvent, &mut AppRuntime) -> bool,
538{
539    let mut out = McpDrainOutcome::default();
540    if let (Some(px), Some(py)) = (x, y) {
541        out.merge(exec_mcp_move(runtime, px, py, false, user_event_hook));
542    }
543    let ev = PlatformEvent::Scroll {
544        delta_x,
545        delta_y,
546        is_momentum: false,
547    };
548    let (intercepted, h_rb, h_rd) = dispatch_synthetic_event_to_hook(runtime, &ev, user_event_hook);
549    out.merge(McpDrainOutcome {
550        needs_rebuild: h_rb,
551        needs_redraw: h_rd,
552    });
553    if !intercepted {
554        let (rb, rd) = runtime.mcp_mouse_scroll_outcome(delta_x, delta_y, None, None);
555        out.merge(McpDrainOutcome {
556            needs_rebuild: rb,
557            needs_redraw: rd,
558        });
559    }
560    out
561}
562
563fn exec_mcp_type<F>(
564    runtime: &mut AppRuntime,
565    text: &str,
566    user_event_hook: &mut F,
567) -> McpDrainOutcome
568where
569    F: FnMut(&PlatformEvent, &mut AppRuntime) -> bool,
570{
571    let mut out = McpDrainOutcome::default();
572    let mut char_buf = [0u8; 4];
573    for ch in text.chars() {
574        let ev = PlatformEvent::ReceivedCharacter(ch);
575        let (intercepted, h_rb, h_rd) =
576            dispatch_synthetic_event_to_hook(runtime, &ev, user_event_hook);
577        out.merge(McpDrainOutcome {
578            needs_rebuild: h_rb,
579            needs_redraw: h_rd,
580        });
581        if !intercepted {
582            let s = ch.encode_utf8(&mut char_buf);
583            let (rb, rd) = runtime.mcp_keyboard_type_outcome(s);
584            out.merge(McpDrainOutcome {
585                needs_rebuild: rb,
586                needs_redraw: rd,
587            });
588        }
589    }
590    out
591}
592
593fn exec_mcp_key<F>(
594    runtime: &mut AppRuntime,
595    key: KeyCode,
596    modifiers: Modifiers,
597    user_event_hook: &mut F,
598) -> McpDrainOutcome
599where
600    F: FnMut(&PlatformEvent, &mut AppRuntime) -> bool,
601{
602    let mut out = McpDrainOutcome::default();
603    if let Some(ref mut c) = runtime.mcp_cursor {
604        c.touch_activity();
605    }
606    let ev_down = PlatformEvent::KeyDown { key, modifiers };
607    let (intercepted_down, h_rb_down, h_rd_down) =
608        dispatch_synthetic_event_to_hook(runtime, &ev_down, user_event_hook);
609    out.merge(McpDrainOutcome {
610        needs_rebuild: h_rb_down,
611        needs_redraw: h_rd_down,
612    });
613    if !intercepted_down {
614        let res_down = runtime.dispatch_key_event(&ev_down);
615        out.merge(McpDrainOutcome {
616            needs_rebuild: res_down.needs_rebuild(),
617            needs_redraw: res_down.needs_redraw(),
618        });
619    }
620
621    let ev_up = PlatformEvent::KeyUp { key, modifiers };
622    let (intercepted_up, h_rb_up, h_rd_up) =
623        dispatch_synthetic_event_to_hook(runtime, &ev_up, user_event_hook);
624    out.merge(McpDrainOutcome {
625        needs_rebuild: h_rb_up,
626        needs_redraw: h_rd_up,
627    });
628    if !intercepted_up {
629        let res_up = runtime.dispatch_key_event(&ev_up);
630        out.merge(McpDrainOutcome {
631            needs_rebuild: res_up.needs_rebuild(),
632            needs_redraw: res_up.needs_redraw(),
633        });
634    }
635    if out.needs_redraw {
636        runtime.mark_paint_dirty();
637    }
638    out
639}
640
641/// Drains and processes all pending MCP requests on the active main UI thread, forwarding all
642/// synthetic input events (`KeyDown`/`KeyUp`/`ReceivedCharacter`/`Scroll`/`MouseMove`/`MouseDown`/`MouseUp`)
643/// through `user_event_hook` just like native OS events.
644///
645/// For `take_screenshot`, captures the pixel buffer on the UI thread (~1–2 ms) and offloads
646/// PNG compression + base64 encoding onto a background worker thread so rendering never stalls.
647pub fn drain_and_execute_mcp_requests_with_hook<F>(
648    runtime: &mut AppRuntime,
649    mut user_event_hook: F,
650) -> McpDrainOutcome
651where
652    F: FnMut(&PlatformEvent, &mut AppRuntime) -> bool,
653{
654    let mut items = Vec::new();
655    {
656        if let Ok(mut lock) = get_pending_queue().lock() {
657            if lock.is_empty() {
658                return McpDrainOutcome::default();
659            }
660            items = std::mem::take(&mut *lock);
661        }
662    }
663
664    let mut total = McpDrainOutcome::default();
665    for (req_str, tx) in items {
666        let parsed: Value = match serde_json::from_str(&req_str) {
667            Ok(v) => v,
668            Err(e) => {
669                let err = json!({
670                    "jsonrpc": "2.0",
671                    "error": { "code": -32700, "message": format!("Parse error: {}", e) }
672                });
673                let _ = tx.send(err.to_string());
674                continue;
675            }
676        };
677
678        let id = parsed.get("id").cloned();
679        let method = parsed.get("method").and_then(|m| m.as_str()).unwrap_or("");
680        let params = parsed.get("params").cloned().unwrap_or(json!({}));
681
682        if method == "take_screenshot" {
683            match runtime.mcp_capture_screenshot_buffer() {
684                Ok(buf) => {
685                    let width = buf.width;
686                    let height = buf.height;
687                    let tx_worker = tx.clone();
688                    let id_worker = id.clone();
689                    let spawn_res = std::thread::Builder::new()
690                        .name("strata-mcp-png-encode".to_string())
691                        .spawn(move || {
692                            let resp = match buf.encode_png_bytes() {
693                                Ok(bytes) => json!({
694                                    "jsonrpc": "2.0",
695                                    "id": id_worker,
696                                    "result": {
697                                        "png_base64": base64_encode(&bytes),
698                                        "width": width,
699                                        "height": height,
700                                    }
701                                }),
702                                Err(err_msg) => json!({
703                                    "jsonrpc": "2.0",
704                                    "id": id_worker,
705                                    "error": { "code": -32603, "message": err_msg }
706                                }),
707                            };
708                            let _ = tx_worker.send(resp.to_string());
709                        });
710                    if let Err(e) = spawn_res {
711                        let resp = json!({
712                            "jsonrpc": "2.0",
713                            "id": id,
714                            "error": { "code": -32603, "message": format!("Failed to spawn PNG encoder thread: {e}") }
715                        });
716                        let _ = tx.send(resp.to_string());
717                    }
718                }
719                Err(err_msg) => {
720                    let resp = json!({
721                        "jsonrpc": "2.0",
722                        "id": id,
723                        "error": { "code": -32603, "message": err_msg }
724                    });
725                    let _ = tx.send(resp.to_string());
726                }
727            }
728            continue;
729        }
730
731        let (result, outcome) =
732            execute_mcp_command_with_hook(runtime, method, params, &mut user_event_hook);
733        total.merge(outcome);
734
735        let resp = match result {
736            Ok(val) => json!({
737                "jsonrpc": "2.0",
738                "id": id,
739                "result": val,
740            }),
741            Err(err_msg) => json!({
742                "jsonrpc": "2.0",
743                "id": id,
744                "error": { "code": -32603, "message": err_msg }
745            }),
746        };
747        let _ = tx.send(resp.to_string());
748    }
749
750    total
751}
752
753/// Drains and processes all pending MCP requests on the active main UI thread, returning
754/// separate `needs_rebuild` and `needs_redraw` flags.
755pub fn drain_and_execute_mcp_requests_with_outcome(runtime: &mut AppRuntime) -> McpDrainOutcome {
756    drain_and_execute_mcp_requests_with_hook(runtime, |_, _| false)
757}
758
759/// Drains and processes all pending MCP requests on the active main UI thread.
760///
761/// Returns true if any executed command requires a view rebuild or display list redraw.
762pub fn drain_and_execute_mcp_requests(runtime: &mut AppRuntime) -> bool {
763    drain_and_execute_mcp_requests_with_outcome(runtime).any_dirty()
764}
765
766/// Core execution routine for MCP commands directly modifying `AppRuntime` (returning a combined dirty bool).
767pub fn execute_mcp_command_core(
768    runtime: &mut AppRuntime,
769    method: &str,
770    params: Value,
771) -> (Result<Value, String>, bool) {
772    let (res, outcome) = execute_mcp_command_with_outcome(runtime, method, params);
773    (res, outcome.any_dirty())
774}
775
776/// Core execution routine for MCP commands returning structured `(needs_rebuild, needs_redraw)`.
777pub fn execute_mcp_command_with_outcome(
778    runtime: &mut AppRuntime,
779    method: &str,
780    params: Value,
781) -> (Result<Value, String>, McpDrainOutcome) {
782    execute_mcp_command_with_hook(runtime, method, params, &mut |_, _| false)
783}
784
785/// Core execution routine for MCP commands that also forwards synthetic input events through the
786/// host application's event hook (`launch_with_events` / `launch_with_frame`).
787pub fn execute_mcp_command_with_hook<F>(
788    runtime: &mut AppRuntime,
789    method: &str,
790    params: Value,
791    user_event_hook: &mut F,
792) -> (Result<Value, String>, McpDrainOutcome)
793where
794    F: FnMut(&PlatformEvent, &mut AppRuntime) -> bool,
795{
796    let clean = McpDrainOutcome::default();
797    match method {
798        "session_info" => {
799            let cursor_info = runtime.mcp_cursor.as_ref().map(|c| {
800                json!({
801                    "x": c.current_x,
802                    "y": c.current_y,
803                    "target_x": c.target_x,
804                    "target_y": c.target_y,
805                    "is_moving": c.is_moving,
806                    "fade_opacity": c.fade_opacity,
807                    "cursor_icon": format!("{:?}", c.cursor_icon),
808                    "is_down": c.is_down,
809                })
810            });
811
812            let focus_info = runtime.active_focus.as_ref().map(|a| {
813                let text = if runtime.active_input_is_password(a) {
814                    AppRuntime::mask_password_text(&a.state.text.get())
815                } else {
816                    a.state.text.get()
817                };
818                json!({
819                    "input_index": a.input_index,
820                    "input_id": a.input_id,
821                    "text": text,
822                    "cursor": a.state.cursor_index.get(),
823                })
824            });
825
826            let info = json!({
827                "viewport_width": runtime.viewport_width,
828                "viewport_height": runtime.viewport_height,
829                "dpr": runtime.dpr,
830                "frame_count": runtime.frame_count,
831                "cursor": cursor_info,
832                "active_focus": focus_info,
833                "cursor_theme": runtime.cursor_theme().name,
834            });
835
836            (Ok(info), clean)
837        }
838        "get_perf_profile" => {
839            let summary = runtime.perf_profile_summary();
840            match serde_json::to_value(&summary) {
841                Ok(val) => (Ok(val), clean),
842                Err(e) => (Err(format!("Failed to serialize perf profile: {e}")), clean),
843            }
844        }
845        "mouse_move" => {
846            let x = params.get("x").and_then(|v| v.as_f64()).unwrap_or(0.0) as f32;
847            let y = params.get("y").and_then(|v| v.as_f64()).unwrap_or(0.0) as f32;
848            let smooth = params
849                .get("smooth")
850                .and_then(|v| v.as_bool())
851                .unwrap_or(true);
852
853            let out = exec_mcp_move(runtime, x, y, smooth, user_event_hook);
854            let cur_icon = runtime
855                .mcp_cursor
856                .as_ref()
857                .map(|c| format!("{:?}", c.cursor_icon))
858                .unwrap_or_else(|| "Default".to_string());
859
860            (
861                Ok(json!({
862                    "x": x,
863                    "y": y,
864                    "smooth": smooth,
865                    "cursor_icon": cur_icon,
866                    "needs_rebuild": out.needs_rebuild,
867                    "needs_redraw": out.needs_redraw,
868                    "hover_fast_path_used": runtime.last_hover_fast_path_used(),
869                })),
870                out,
871            )
872        }
873        "mouse_click" => {
874            let x = params.get("x").and_then(|v| v.as_f64()).map(|f| f as f32);
875            let y = params.get("y").and_then(|v| v.as_f64()).map(|f| f as f32);
876            let btn_str = params
877                .get("button")
878                .and_then(|b| b.as_str())
879                .unwrap_or("left");
880            let count = params.get("count").and_then(|c| c.as_u64()).unwrap_or(1) as usize;
881            let button = parse_mouse_button(btn_str);
882
883            let out = exec_mcp_click(runtime, button, x, y, count, user_event_hook);
884            (
885                Ok(json!({
886                    "clicked": true,
887                    "needs_rebuild": out.needs_rebuild,
888                    "needs_redraw": out.needs_redraw,
889                })),
890                out,
891            )
892        }
893        "mouse_down" => {
894            let x = params.get("x").and_then(|v| v.as_f64()).map(|f| f as f32);
895            let y = params.get("y").and_then(|v| v.as_f64()).map(|f| f as f32);
896            let btn_str = params
897                .get("button")
898                .and_then(|b| b.as_str())
899                .unwrap_or("left");
900            let button = parse_mouse_button(btn_str);
901
902            let out = exec_mcp_down(runtime, button, x, y, user_event_hook);
903            (Ok(json!({ "down": true })), out)
904        }
905        "mouse_up" => {
906            let x = params.get("x").and_then(|v| v.as_f64()).map(|f| f as f32);
907            let y = params.get("y").and_then(|v| v.as_f64()).map(|f| f as f32);
908            let btn_str = params
909                .get("button")
910                .and_then(|b| b.as_str())
911                .unwrap_or("left");
912            let button = parse_mouse_button(btn_str);
913
914            let out = exec_mcp_up(runtime, button, x, y, user_event_hook);
915            (Ok(json!({ "up": true })), out)
916        }
917        "mouse_scroll" | "mouse_wheel" => {
918            let delta_x = params
919                .get("delta_x")
920                .and_then(|v| v.as_f64())
921                .unwrap_or(0.0) as f32;
922            let delta_y = params
923                .get("delta_y")
924                .and_then(|v| v.as_f64())
925                .unwrap_or(0.0) as f32;
926            let x = params.get("x").and_then(|v| v.as_f64()).map(|f| f as f32);
927            let y = params.get("y").and_then(|v| v.as_f64()).map(|f| f as f32);
928
929            let out = exec_mcp_scroll(runtime, delta_x, delta_y, x, y, user_event_hook);
930            (
931                Ok(json!({
932                    "scrolled": true,
933                    "delta_x": delta_x,
934                    "delta_y": delta_y,
935                    "needs_rebuild": out.needs_rebuild,
936                    "needs_redraw": out.needs_redraw,
937                })),
938                out,
939            )
940        }
941        "keyboard_type" => {
942            let text = params.get("text").and_then(|t| t.as_str()).unwrap_or("");
943            let out = exec_mcp_type(runtime, text, user_event_hook);
944            (Ok(json!({ "typed_chars": text.chars().count() })), out)
945        }
946        "keyboard_key" | "key_press" => {
947            let key_str = params.get("key").and_then(|k| k.as_str()).unwrap_or("");
948            let key = parse_key_code(key_str);
949            let modifiers = parse_modifiers(params.get("modifiers"));
950
951            let out = exec_mcp_key(runtime, key, modifiers, user_event_hook);
952            (
953                Ok(json!({
954                    "key_sent": key_str,
955                    "resolved_key": format!("{:?}", key),
956                    "needs_rebuild": out.needs_rebuild,
957                    "needs_redraw": out.needs_redraw,
958                })),
959                out,
960            )
961        }
962        "take_screenshot" => match runtime.mcp_capture_screenshot_buffer() {
963            Ok(buf) => {
964                let width = buf.width;
965                let height = buf.height;
966                match buf.encode_png_bytes() {
967                    Ok(bytes) => {
968                        let base64_str = base64_encode(&bytes);
969                        (
970                            Ok(json!({
971                                "png_base64": base64_str,
972                                "width": width,
973                                "height": height,
974                            })),
975                            clean,
976                        )
977                    }
978                    Err(e) => (Err(e), clean),
979                }
980            }
981            Err(e) => (Err(e), clean),
982        },
983        "inspect_element" => {
984            let x = params.get("x").and_then(|v| v.as_f64()).unwrap_or(0.0) as f32;
985            let y = params.get("y").and_then(|v| v.as_f64()).unwrap_or(0.0) as f32;
986            let (tag, classes, bounds, text, cursor_icon) = runtime.mcp_inspect_element(x, y);
987
988            (
989                Ok(json!({
990                    "tag": tag,
991                    "classes": classes,
992                    "bounds": {
993                        "x": bounds.x,
994                        "y": bounds.y,
995                        "width": bounds.width,
996                        "height": bounds.height,
997                    },
998                    "text": text,
999                    "cursor_icon": format!("{:?}", cursor_icon),
1000                })),
1001                clean,
1002            )
1003        }
1004        "execute_actions" => {
1005            let actions_val = params.get("actions").cloned().unwrap_or(json!([]));
1006            let actions: Vec<Value> = actions_val.as_array().cloned().unwrap_or_default();
1007            let mut executed = 0;
1008            let mut batch_outcome = McpDrainOutcome::default();
1009
1010            for act in actions {
1011                let act_type = act.get("action").and_then(|a| a.as_str()).unwrap_or("");
1012                match act_type {
1013                    "move" => {
1014                        let x = act.get("x").and_then(|v| v.as_f64()).unwrap_or(0.0) as f32;
1015                        let y = act.get("y").and_then(|v| v.as_f64()).unwrap_or(0.0) as f32;
1016                        let smooth = act.get("smooth").and_then(|v| v.as_bool()).unwrap_or(true);
1017                        batch_outcome.merge(exec_mcp_move(
1018                            runtime,
1019                            x,
1020                            y,
1021                            smooth,
1022                            user_event_hook,
1023                        ));
1024                        executed += 1;
1025                    }
1026                    "down" => {
1027                        let btn = parse_mouse_button(
1028                            act.get("button").and_then(|b| b.as_str()).unwrap_or("left"),
1029                        );
1030                        let x = act.get("x").and_then(|v| v.as_f64()).map(|f| f as f32);
1031                        let y = act.get("y").and_then(|v| v.as_f64()).map(|f| f as f32);
1032                        batch_outcome.merge(exec_mcp_down(runtime, btn, x, y, user_event_hook));
1033                        executed += 1;
1034                    }
1035                    "up" => {
1036                        let btn = parse_mouse_button(
1037                            act.get("button").and_then(|b| b.as_str()).unwrap_or("left"),
1038                        );
1039                        let x = act.get("x").and_then(|v| v.as_f64()).map(|f| f as f32);
1040                        let y = act.get("y").and_then(|v| v.as_f64()).map(|f| f as f32);
1041                        batch_outcome.merge(exec_mcp_up(runtime, btn, x, y, user_event_hook));
1042                        executed += 1;
1043                    }
1044                    "click" => {
1045                        let x = act.get("x").and_then(|v| v.as_f64()).map(|f| f as f32);
1046                        let y = act.get("y").and_then(|v| v.as_f64()).map(|f| f as f32);
1047                        let btn = parse_mouse_button(
1048                            act.get("button").and_then(|b| b.as_str()).unwrap_or("left"),
1049                        );
1050                        let count = act.get("count").and_then(|c| c.as_u64()).unwrap_or(1) as usize;
1051                        batch_outcome.merge(exec_mcp_click(
1052                            runtime,
1053                            btn,
1054                            x,
1055                            y,
1056                            count,
1057                            user_event_hook,
1058                        ));
1059                        executed += 1;
1060                    }
1061                    "type" => {
1062                        let text = act.get("text").and_then(|t| t.as_str()).unwrap_or("");
1063                        batch_outcome.merge(exec_mcp_type(runtime, text, user_event_hook));
1064                        executed += 1;
1065                    }
1066                    "key" | "key_press" => {
1067                        let key =
1068                            parse_key_code(act.get("key").and_then(|k| k.as_str()).unwrap_or(""));
1069                        let mods = parse_modifiers(act.get("modifiers"));
1070                        batch_outcome.merge(exec_mcp_key(runtime, key, mods, user_event_hook));
1071                        executed += 1;
1072                    }
1073                    "scroll" | "wheel" => {
1074                        let dx = act.get("delta_x").and_then(|v| v.as_f64()).unwrap_or(0.0) as f32;
1075                        let dy = act.get("delta_y").and_then(|v| v.as_f64()).unwrap_or(0.0) as f32;
1076                        let x = act.get("x").and_then(|v| v.as_f64()).map(|f| f as f32);
1077                        let y = act.get("y").and_then(|v| v.as_f64()).map(|f| f as f32);
1078                        batch_outcome.merge(exec_mcp_scroll(
1079                            runtime,
1080                            dx,
1081                            dy,
1082                            x,
1083                            y,
1084                            user_event_hook,
1085                        ));
1086                        executed += 1;
1087                    }
1088                    "wait" => {
1089                        // Waits are scheduled off the UI main thread by the MCP server and the
1090                        // background IPC listener (`execute_actions_nonblocking_on_ipc_thread`).
1091                        // Never block the UI thread via `std::thread::sleep`.
1092                        executed += 1;
1093                    }
1094                    _ => {}
1095                }
1096            }
1097
1098            (
1099                Ok(json!({ "executed_actions": executed })),
1100                batch_outcome,
1101            )
1102        }
1103        unknown => (Err(format!("Unknown MCP method: {}", unknown)), clean),
1104    }
1105}
1106
1107fn parse_mouse_button(s: &str) -> MouseButton {
1108    match s.to_ascii_lowercase().as_str() {
1109        "middle" | "wheel" => MouseButton::Middle,
1110        "right" => MouseButton::Right,
1111        _ => MouseButton::Left,
1112    }
1113}
1114
1115fn parse_key_code(s: &str) -> KeyCode {
1116    match s.trim().to_ascii_lowercase().as_str() {
1117        "enter" | "return" => KeyCode::Enter,
1118        "escape" | "esc" => KeyCode::Escape,
1119        "backspace" => KeyCode::Backspace,
1120        "delete" | "del" => KeyCode::Delete,
1121        "tab" => KeyCode::Tab,
1122        "space" | " " => KeyCode::Space,
1123        "arrowleft" | "left" => KeyCode::ArrowLeft,
1124        "arrowright" | "right" => KeyCode::ArrowRight,
1125        "arrowup" | "up" => KeyCode::ArrowUp,
1126        "arrowdown" | "down" => KeyCode::ArrowDown,
1127        "home" => KeyCode::Home,
1128        "end" => KeyCode::End,
1129        "pageup" => KeyCode::PageUp,
1130        "pagedown" => KeyCode::PageDown,
1131        "a" | "keya" => KeyCode::KeyA,
1132        "b" | "keyb" => KeyCode::KeyB,
1133        "c" | "keyc" => KeyCode::KeyC,
1134        "d" | "keyd" => KeyCode::KeyD,
1135        "e" | "keye" => KeyCode::KeyE,
1136        "f" | "keyf" => KeyCode::KeyF,
1137        "g" | "keyg" => KeyCode::KeyG,
1138        "h" | "keyh" => KeyCode::KeyH,
1139        "i" | "keyi" => KeyCode::KeyI,
1140        "j" | "keyj" => KeyCode::KeyJ,
1141        "k" | "keyk" => KeyCode::KeyK,
1142        "l" | "keyl" => KeyCode::KeyL,
1143        "m" | "keym" => KeyCode::KeyM,
1144        "n" | "keyn" => KeyCode::KeyN,
1145        "o" | "keyo" => KeyCode::KeyO,
1146        "p" | "keyp" => KeyCode::KeyP,
1147        "q" | "keyq" => KeyCode::KeyQ,
1148        "r" | "keyr" => KeyCode::KeyR,
1149        "s" | "keys" => KeyCode::KeyS,
1150        "t" | "keyt" => KeyCode::KeyT,
1151        "u" | "keyu" => KeyCode::KeyU,
1152        "v" | "keyv" => KeyCode::KeyV,
1153        "w" | "keyw" => KeyCode::KeyW,
1154        "x" | "keyx" => KeyCode::KeyX,
1155        "y" | "keyy" => KeyCode::KeyY,
1156        "z" | "keyz" => KeyCode::KeyZ,
1157        "0" | "digit0" => KeyCode::Digit0,
1158        "1" | "digit1" => KeyCode::Digit1,
1159        "2" | "digit2" => KeyCode::Digit2,
1160        "3" | "digit3" => KeyCode::Digit3,
1161        "4" | "digit4" => KeyCode::Digit4,
1162        "5" | "digit5" => KeyCode::Digit5,
1163        "6" | "digit6" => KeyCode::Digit6,
1164        "7" | "digit7" => KeyCode::Digit7,
1165        "8" | "digit8" => KeyCode::Digit8,
1166        "9" | "digit9" => KeyCode::Digit9,
1167        "f1" => KeyCode::F1,
1168        "f2" => KeyCode::F2,
1169        "f3" => KeyCode::F3,
1170        "f4" => KeyCode::F4,
1171        "f5" => KeyCode::F5,
1172        "f6" => KeyCode::F6,
1173        "f7" => KeyCode::F7,
1174        "f8" => KeyCode::F8,
1175        "f9" => KeyCode::F9,
1176        "f10" => KeyCode::F10,
1177        "f11" => KeyCode::F11,
1178        "f12" => KeyCode::F12,
1179        "/" | "slash" => KeyCode::Slash,
1180        "," | "comma" => KeyCode::Comma,
1181        "." | "period" => KeyCode::Period,
1182        "-" | "minus" => KeyCode::Minus,
1183        "=" | "+" | "equal" | "equals" | "plus" => KeyCode::Equals,
1184        "[" | "bracketleft" => KeyCode::BracketLeft,
1185        "]" | "bracketright" => KeyCode::BracketRight,
1186        ";" | "semicolon" => KeyCode::Semicolon,
1187        "'" | "\"" | "quote" | "apostrophe" => KeyCode::Quote,
1188        "\\" | "|" | "backslash" => KeyCode::Backslash,
1189        "`" | "backquote" | "grave" => KeyCode::Backquote,
1190        _ => KeyCode::Space,
1191    }
1192}
1193
1194fn parse_modifiers(val: Option<&Value>) -> Modifiers {
1195    let mut mods = Modifiers::default();
1196    if let Some(v) = val {
1197        mods.shift = v.get("shift").and_then(|b| b.as_bool()).unwrap_or(false);
1198        mods.ctrl = v.get("ctrl").and_then(|b| b.as_bool()).unwrap_or(false);
1199        mods.alt = v.get("alt").and_then(|b| b.as_bool()).unwrap_or(false);
1200        mods.meta = v.get("meta").and_then(|b| b.as_bool()).unwrap_or(false);
1201    }
1202    mods
1203}
1204
1205pub fn default_dev_socket_path() -> PathBuf {
1206    if let Ok(path) = std::env::var("STRATA_DEV_SOCKET") {
1207        PathBuf::from(path)
1208    } else if let Ok(runtime_dir) = std::env::var("XDG_RUNTIME_DIR") {
1209        PathBuf::from(runtime_dir).join("strata-dev.sock")
1210    } else {
1211        #[cfg(unix)]
1212        {
1213            let uid = get_current_uid();
1214            let runtime_dir = PathBuf::from(format!("/tmp/strata-runtime-{}", uid));
1215            runtime_dir.join("strata-dev.sock")
1216        }
1217        #[cfg(not(unix))]
1218        {
1219            std::env::temp_dir().join("strata-dev.sock")
1220        }
1221    }
1222}
1223
1224fn base64_encode(data: &[u8]) -> String {
1225    const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1226    let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
1227    for chunk in data.chunks(3) {
1228        let b0 = chunk[0];
1229        let b1 = if chunk.len() > 1 { chunk[1] } else { 0 };
1230        let b2 = if chunk.len() > 2 { chunk[2] } else { 0 };
1231
1232        let n = ((b0 as u32) << 16) | ((b1 as u32) << 8) | (b2 as u32);
1233
1234        out.push(TABLE[((n >> 18) & 63) as usize] as char);
1235        out.push(TABLE[((n >> 12) & 63) as usize] as char);
1236        if chunk.len() > 1 {
1237            out.push(TABLE[((n >> 6) & 63) as usize] as char);
1238        } else {
1239            out.push('=');
1240        }
1241        if chunk.len() > 2 {
1242            out.push(TABLE[(n & 63) as usize] as char);
1243        } else {
1244            out.push('=');
1245        }
1246    }
1247    out
1248}