Skip to main content

rightkit_qa/
control.rs

1//! Drive the real Tauri app through the in-app `rightkit-control` server.
2//!
3//! The app is launched hidden or backgrounded with `RIGHTKIT_CONTROL_SERVICE` and an
4//! isolated `RIGHTKIT_SUITE_ROOT`, discovers the `rightkit-service` record
5//! (`service.json`), and talks over the current-user-only socket / named pipe as the
6//! allowlisted app `right-qa`. No TCP and no shared secrets. The harness never searches for
7//! processes by name to kill them: it records the pid it started and kills that
8//! tree only.
9use crate::process::{is_alive, kill_tree, Tracker};
10use crate::util::{err, new_id, sleep_ms, Error, Result};
11use crate::workspace::QaWorkspace;
12use rightkit_process::OwnedChild;
13#[cfg(not(target_os = "macos"))]
14use rightkit_process::OwnedCommand;
15use rightkit_service::{Client, ServiceError, Suite};
16use serde_json::{json, Value};
17use std::fs;
18use std::path::{Path, PathBuf};
19use std::process::Command;
20#[cfg(not(target_os = "macos"))]
21use std::process::Stdio;
22use std::sync::{Arc, Mutex};
23use std::time::{Duration, Instant};
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26pub enum Mode {
27    /// Window never shown (`open -g -j -n` on macOS, hidden window on Windows).
28    Hidden,
29    /// Window shown but the app is not activated and frontmost is unchanged.
30    Background,
31    Visible,
32}
33
34impl Mode {
35    pub fn parse(s: &str) -> Result<Self> {
36        match s {
37            "hidden" => Ok(Mode::Hidden),
38            "background" => Ok(Mode::Background),
39            "visible" => Ok(Mode::Visible),
40            other => err(format!(
41                "unknown ui mode '{other}' (hidden|background|visible)"
42            )),
43        }
44    }
45}
46
47#[derive(Debug, Clone)]
48pub struct LaunchSpec {
49    /// A `.app` bundle, or a plain executable (wrapped into a throwaway bundle on macOS).
50    pub binary: PathBuf,
51    pub mode: Mode,
52    pub env: Vec<(String, String)>,
53    pub startup_timeout: Duration,
54    pub label: String,
55}
56
57#[derive(Debug, Clone)]
58pub struct StopReport {
59    pub pid: u32,
60    pub endpoint_closed: bool,
61    pub process_gone: bool,
62    pub frontmost_before: Option<String>,
63    pub frontmost_after: Option<String>,
64    pub frontmost_unchanged: bool,
65    /// Every distinct foreground state sampled during the session (empty when unmeasurable).
66    pub frontmost_states: Vec<String>,
67    /// Every sampled foreground PID belonged to no app process started by this control session.
68    /// This is the background invariant; `frontmost_unchanged` remains diagnostic only.
69    pub owned_never_frontmost: bool,
70    /// Owned fixture PIDs observed in foreground, if any.
71    pub owned_frontmost_pids: Vec<u32>,
72}
73
74pub struct Control {
75    pub pid: u32,
76    /// `rightkit-service` name the app serves (`control-xxxxxxxx`).
77    pub service: String,
78    pub log_path: PathBuf,
79    raw_log: PathBuf,
80    suite: Suite,
81    endpoint: String,
82    client: Mutex<Option<Arc<Client>>>,
83    child: Option<OwnedChild>,
84    tracker: Tracker,
85    frontmost_before: Option<String>,
86    focus: Option<FocusMonitor>,
87    request_timeout: Duration,
88    stopped: bool,
89}
90
91const APP: &str = "right-qa";
92
93fn svc_err(e: ServiceError) -> Error {
94    Error(e.to_string())
95}
96
97enum CallError {
98    TimedOut,
99    Service(ServiceError),
100}
101
102/// Run `f` on a helper thread and give up after `timeout`; the thread is left to finish
103/// on its own (it ends when the app is killed or the connection is aborted).
104fn bounded<T: Send + 'static>(
105    timeout: Duration,
106    f: impl FnOnce() -> T + Send + 'static,
107) -> Option<T> {
108    let (tx, rx) = std::sync::mpsc::channel();
109    std::thread::spawn(move || {
110        let _ = tx.send(f());
111    });
112    rx.recv_timeout(timeout).ok()
113}
114
115fn call_bounded(
116    client: &Arc<Client>,
117    method: &str,
118    params: Value,
119    timeout: Duration,
120) -> std::result::Result<Value, CallError> {
121    let c = client.clone();
122    let m = method.to_string();
123    match bounded(timeout, move || c.call(&m, params)) {
124        Some(r) => r.map_err(CallError::Service),
125        None => {
126            client.abort();
127            Err(CallError::TimedOut)
128        }
129    }
130}
131
132fn connect_bounded(suite: &Suite, service: &str, timeout: Duration) -> Result<Client> {
133    let (s, sv) = (suite.clone(), service.to_string());
134    match bounded(timeout, move || Client::connect(&s, &sv, APP)) {
135        Some(r) => r.map_err(svc_err),
136        None => err(format!(
137            "connecting to {service} did not finish within {}ms",
138            timeout.as_millis()
139        )),
140    }
141}
142
143fn bounded_connect_health(suite: &Suite, service: &str, timeout: Duration) -> Option<Arc<Client>> {
144    let (s, sv) = (suite.clone(), service.to_string());
145    bounded(timeout, move || {
146        let c = Client::connect(&s, &sv, APP).ok()?;
147        c.call("health", json!({})).ok()?;
148        Some(Arc::new(c))
149    })
150    .flatten()
151}
152
153fn endpoint_open(endpoint: &str) -> bool {
154    rightkit_service::probe_endpoint(endpoint)
155}
156
157/// Foreground app as `name` (macOS) or `pid:hwnd` (Windows). `None` means the
158/// foreground could NOT be measured; it is never treated as "unchanged".
159pub fn frontmost() -> Option<String> {
160    #[cfg(target_os = "macos")]
161    {
162        rightkit_control::mac::frontmost_name()
163    }
164    #[cfg(windows)]
165    {
166        use windows::Win32::UI::WindowsAndMessaging::{
167            GetForegroundWindow, GetWindowThreadProcessId,
168        };
169        unsafe {
170            let h = GetForegroundWindow();
171            if h.0.is_null() {
172                return None;
173            }
174            let mut pid = 0u32;
175            if GetWindowThreadProcessId(h, Some(&mut pid)) == 0 || pid == 0 {
176                return None;
177            }
178            Some(format!("{pid}:{:x}", h.0 as usize))
179        }
180    }
181    #[cfg(not(any(target_os = "macos", windows)))]
182    {
183        None
184    }
185}
186
187/// Samples the foreground on its own thread for the whole life of a control session, so
188/// a transient steal (focus leaves and returns) is caught, and an unmeasurable
189/// foreground is reported as such instead of comparing equal.
190struct FocusMonitor {
191    stop: Arc<std::sync::atomic::AtomicBool>,
192    seen: Arc<Mutex<(usize, usize, Vec<String>)>>, // (measured, unavailable, distinct states in order)
193    owned: Arc<Mutex<(Vec<u32>, Option<String>)>>, // primary PID(s), exact executable prefix
194    enforce_owned: bool,
195    owned_frontmost: Arc<Mutex<Vec<u32>>>,
196    thread: Option<std::thread::JoinHandle<()>>,
197}
198
199impl FocusMonitor {
200    fn start(enforce_owned: bool) -> FocusMonitor {
201        let seen: Arc<Mutex<(usize, usize, Vec<String>)>> = Arc::new(Mutex::new((0, 0, vec![])));
202        let owned: Arc<Mutex<(Vec<u32>, Option<String>)>> = Arc::new(Mutex::new((vec![], None)));
203        let owned_frontmost = Arc::new(Mutex::new(vec![]));
204        let record = move |seen: &Mutex<(usize, usize, Vec<String>)>,
205                           _owned: &Mutex<(Vec<u32>, Option<String>)>,
206                           _owned_frontmost: &Mutex<Vec<u32>>| {
207            {
208                let mut g = seen.lock().unwrap_or_else(|e| e.into_inner());
209                match frontmost() {
210                    Some(f) => {
211                        g.0 += 1;
212                        if g.2.last() != Some(&f) {
213                            g.2.push(f);
214                        }
215                    }
216                    None => g.1 += 1,
217                }
218            }
219            #[cfg(target_os = "macos")]
220            if enforce_owned {
221                match rightkit_control::mac::frontmost_pid() {
222                    Some(pid) => {
223                        let (primary, prefix) =
224                            _owned.lock().unwrap_or_else(|e| e.into_inner()).clone();
225                        let mut candidates = primary;
226                        let mut inventory_ok = true;
227                        if let Some(prefix) = prefix {
228                            match pids_with_command_prefix(&prefix) {
229                                Ok(pids) => candidates.extend(pids),
230                                Err(_) => inventory_ok = false,
231                            }
232                        }
233                        if !inventory_ok {
234                            let mut g = seen.lock().unwrap_or_else(|e| e.into_inner());
235                            g.1 += 1;
236                        }
237                        if candidates.into_iter().any(|p| p == pid as u32) {
238                            let mut observed =
239                                _owned_frontmost.lock().unwrap_or_else(|e| e.into_inner());
240                            if !observed.contains(&(pid as u32)) {
241                                observed.push(pid as u32);
242                            }
243                        }
244                    }
245                    None => {
246                        // An unmeasurable PID makes the strict background proof fail.
247                        let mut g = seen.lock().unwrap_or_else(|e| e.into_inner());
248                        g.1 += 1;
249                    }
250                }
251            }
252        };
253        record(&seen, &owned, &owned_frontmost);
254        let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
255        let (s2, seen2, owned2, observed2) = (
256            stop.clone(),
257            seen.clone(),
258            owned.clone(),
259            owned_frontmost.clone(),
260        );
261        let thread = std::thread::spawn(move || {
262            while !s2.load(std::sync::atomic::Ordering::SeqCst) {
263                std::thread::sleep(Duration::from_millis(20));
264                record(&seen2, &owned2, &observed2);
265            }
266        });
267        FocusMonitor {
268            stop,
269            seen,
270            owned,
271            enforce_owned,
272            owned_frontmost,
273            thread: Some(thread),
274        }
275    }
276    fn track_primary(&self, pid: u32) {
277        self.owned
278            .lock()
279            .unwrap_or_else(|e| e.into_inner())
280            .0
281            .push(pid);
282    }
283    #[cfg(target_os = "macos")]
284    fn track_prefix(&self, prefix: String) {
285        self.owned.lock().unwrap_or_else(|e| e.into_inner()).1 = Some(prefix);
286    }
287    /// `(unchanged, states, owned_never_frontmost, owned_frontmost_pids)`.
288    fn finish(&mut self) -> (bool, Vec<String>, bool, Vec<u32>) {
289        self.stop.store(true, std::sync::atomic::Ordering::SeqCst);
290        if let Some(t) = self.thread.take() {
291            let _ = t.join();
292        }
293        let g = self.seen.lock().unwrap_or_else(|e| e.into_inner());
294        let unchanged = g.0 > 0 && g.1 == 0 && g.2.len() == 1;
295        let observed = self
296            .owned_frontmost
297            .lock()
298            .unwrap_or_else(|e| e.into_inner())
299            .clone();
300        #[cfg(target_os = "macos")]
301        // Unverified launch interval: if the executable identity was never registered
302        // before launch, startup samples could not be attributed, so never claim success.
303        let identity_registered = self
304            .owned
305            .lock()
306            .unwrap_or_else(|e| e.into_inner())
307            .1
308            .is_some();
309        #[cfg(target_os = "macos")]
310        let owned_never_frontmost =
311            !self.enforce_owned || (identity_registered && g.1 == 0 && observed.is_empty());
312        #[cfg(not(target_os = "macos"))]
313        // No native foreground-PID sampler exists on these targets yet; background
314        // claims fail closed instead of treating name-only sampling as proof.
315        let owned_never_frontmost = !self.enforce_owned;
316        (unchanged, g.2.clone(), owned_never_frontmost, observed)
317    }
318}
319
320/// Environment passed to the app must not put secrets in a process listing: on macOS
321/// `open --env K=V` exposes values in argv. Only `RIGHTKIT_*` keys travel that way, and
322/// no key that names a credential is accepted at all.
323fn check_env(env: &[(String, String)]) -> Result<()> {
324    for (k, _) in env {
325        let up = k.to_ascii_uppercase();
326        if [
327            "TOKEN",
328            "SECRET",
329            "PASSWORD",
330            "PASSWD",
331            "API_KEY",
332            "APIKEY",
333            "PRIVATE_KEY",
334            "CREDENTIAL",
335        ]
336        .iter()
337        .any(|w| up.contains(w))
338        {
339            return err(format!("environment key {k} names a credential; secrets are never passed to a launched app through its command line or environment"));
340        }
341        #[cfg(target_os = "macos")]
342        if !up.starts_with("RIGHTKIT_") {
343            return err(format!("environment key {k} would be exposed in `open` arguments; macOS launches carry only RIGHTKIT_* keys"));
344        }
345    }
346    Ok(())
347}
348
349/// Absolute path of the executable that `open` will actually run for `bundle`, read from
350/// `Contents/Info.plist` `CFBundleExecutable`. `None` (fail closed) when the key is absent,
351/// names a path component trick, or the file is not a regular file inside `Contents/MacOS`.
352#[cfg(target_os = "macos")]
353#[doc(hidden)]
354pub fn resolve_bundle_executable(bundle: &Path) -> Option<String> {
355    let plist = bundle.join("Contents").join("Info.plist");
356    let out = Command::new("plutil")
357        .args(["-extract", "CFBundleExecutable", "raw", "-o", "-"])
358        .arg(&plist)
359        .output()
360        .ok()?;
361    if !out.status.success() {
362        return None;
363    }
364    let name = String::from_utf8(out.stdout).ok()?;
365    let name = name.trim();
366    if name.is_empty() || name == "." || name == ".." || name.contains('/') || name.contains('\0') {
367        return None;
368    }
369    let exe = bundle.join("Contents").join("MacOS").join(name);
370    let meta = fs::metadata(&exe).ok()?;
371    if !meta.is_file() {
372        return None;
373    }
374    Some(exe.to_string_lossy().into_owned())
375}
376
377#[cfg(target_os = "macos")]
378fn make_bundle(dir: &Path, binary: &Path, id: &str, background: bool) -> Result<PathBuf> {
379    let exe = binary
380        .file_name()
381        .and_then(|n| n.to_str())
382        .ok_or_else(|| Error("binary has no file name".into()))?;
383    let app = dir.join(format!("{exe}.app"));
384    let macos = app.join("Contents").join("MacOS");
385    fs::create_dir_all(&macos)?;
386    let target = macos.join(exe);
387    let _ = fs::remove_file(&target);
388    let abs = fs::canonicalize(binary)
389        .map_err(|e| Error(format!("app binary not found: {}: {e}", binary.display())))?;
390    // The process must show the bundle path (not a resolved symlink) so the harness can
391    // find exactly the instance it started: hard link, else copy.
392    if fs::hard_link(&abs, &target).is_err() {
393        fs::copy(&abs, &target)?;
394    }
395    // Background fixtures must be non-activating before AppKit creates any window.
396    let ui_element = if background {
397        "<key>LSUIElement</key><true/>\n"
398    } else {
399        ""
400    };
401    let plist = format!(
402        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\"><dict>\n<key>CFBundleExecutable</key><string>{exe}</string>\n<key>CFBundleIdentifier</key><string>app.rightkit.qa.{id}</string>\n<key>CFBundleName</key><string>{exe}</string>\n<key>CFBundlePackageType</key><string>APPL</string>\n<key>CFBundleVersion</key><string>1</string>\n{ui_element}</dict></plist>\n"
403    );
404    fs::write(app.join("Contents").join("Info.plist"), plist)?;
405    Ok(app)
406}
407
408#[cfg(target_os = "macos")]
409/// Pids whose command line STARTS with `prefix` (so `open`, which merely carries the
410/// bundle path as an argument, is never mistaken for the app).
411fn pids_with_command_prefix(prefix: &str) -> std::result::Result<Vec<u32>, String> {
412    let out = Command::new("ps")
413        .args(["-ax", "-o", "pid=,command="])
414        .output()
415        .map_err(|e| format!("ps PID inventory failed: {e}"))?;
416    if !out.status.success() {
417        return Err(format!("ps PID inventory exited with {}", out.status));
418    }
419    let mut pids = vec![];
420    for line in String::from_utf8_lossy(&out.stdout).lines() {
421        let line = line.trim_start();
422        let Some((pid, cmd)) = line.split_once(' ') else {
423            continue;
424        };
425        if cmd.trim_start().starts_with(prefix) {
426            pids.push(
427                pid.trim()
428                    .parse::<u32>()
429                    .map_err(|e| format!("invalid PID inventory row: {e}"))?,
430            );
431        }
432    }
433    Ok(pids)
434}
435
436pub fn launch(spec: &LaunchSpec, ws: &QaWorkspace, tracker: &Tracker) -> Result<Control> {
437    if !spec.binary.exists() {
438        return err(format!(
439            "UI app binary not found: {}",
440            spec.binary.display()
441        ));
442    }
443    let id = new_id().replace('-', "");
444    let service = format!("control-{}", &id[..8]);
445    // Isolated per-run suite root: the app's service.json never collides with an installed app's.
446    let suite =
447        Suite::at(ws.home.join(format!("suite-{}", &id[..8]))).map_err(|e| Error(e.to_string()))?;
448    let log_path = ws.evidence_dir.join(format!("app-{}.log", &id[..8]));
449    // launchd-started apps cannot open log files on external volumes (`open` fails with
450    // -10810), so the live log goes to the system temp dir and is copied into the
451    // evidence dir when the app stops.
452    let raw_log = ws.home.join(format!("app-{}.log", &id[..8]));
453    // macOS launches go through `open --env`, which exposes values in argv, so only the
454    // workspace's RIGHTKIT_* keys travel; apps derive isolation from RIGHTKIT_QA_DATA_DIR
455    // there. The XDG_*/WEBVIEW2_*/<APP>_DATA_DIR keys serve direct-exec platforms.
456    // Caller-supplied `spec.env` is still checked strictly below.
457    let mut env: Vec<(String, String)> = ws
458        .env
459        .iter()
460        .filter(|(k, _)| cfg!(not(target_os = "macos")) || k.starts_with("RIGHTKIT_"))
461        .map(|(k, v)| (k.clone(), v.clone()))
462        .collect();
463    env.push(("RIGHTKIT_CONTROL_SERVICE".into(), service.clone()));
464    env.push((
465        "RIGHTKIT_SUITE_ROOT".into(),
466        suite.root().to_string_lossy().into(),
467    ));
468    env.push((
469        "RIGHTKIT_QA_HIDDEN".into(),
470        if spec.mode == Mode::Hidden { "1" } else { "0" }.into(),
471    ));
472    // Hidden runs stay hidden until a test explicitly reveals a window; any such
473    // reveal still uses the background window policy and target-pid input.
474    env.push((
475        "RIGHTKIT_QA_BACKGROUND".into(),
476        if spec.mode != Mode::Visible { "1" } else { "0" }.into(),
477    ));
478    env.extend(spec.env.iter().cloned());
479    check_env(&env)?;
480    let frontmost_before = frontmost();
481    let focus = FocusMonitor::start(spec.mode != Mode::Visible);
482    let deadline = Instant::now() + spec.startup_timeout;
483
484    // The executable identity is registered inside start_process BEFORE `open`, so
485    // startup foreground samples are attributed; the pid follows once known.
486    let (pid, child) = start_process(spec, ws, &env, &raw_log, &id, tracker, &focus, deadline)?;
487    focus.track_primary(pid);
488    tracker.register(pid, &spec.label);
489
490    let mut control = Control {
491        pid,
492        service: service.clone(),
493        log_path,
494        raw_log,
495        suite: suite.clone(),
496        endpoint: String::new(),
497        client: Mutex::new(None),
498        child,
499        tracker: tracker.clone(),
500        frontmost_before,
501        focus: Some(focus),
502        request_timeout: Duration::from_secs(20),
503        stopped: false,
504    };
505    loop {
506        // Each attempt is bounded by the startup deadline: a hung host must not defeat it.
507        let left = deadline.saturating_duration_since(Instant::now());
508        if let Some(c) = bounded_connect_health(&suite, &service, left.min(Duration::from_secs(5)))
509        {
510            control.endpoint = c.record().endpoint.clone();
511            *control.client.lock().unwrap() = Some(c);
512            break;
513        }
514        if !is_alive(pid) {
515            let tail = fs::read_to_string(&control.raw_log)
516                .map(|t| crate::util::tail(&t, 1500))
517                .unwrap_or_default();
518            return err(format!(
519                "app exited before its control server came up (pid {pid}); log tail: {tail}"
520            ));
521        }
522        if Instant::now() >= deadline {
523            let _ = control.stop();
524            return err(format!(
525                "control service did not answer within {}ms; was the app built with its control feature and launched with RIGHTKIT_CONTROL_SERVICE?",
526                spec.startup_timeout.as_millis()
527            ));
528        }
529        sleep_ms(100);
530    }
531    // The server comes up before the window exists (hidden launch): wait until the page
532    // itself answers, so the first scenario step never races window creation.
533    loop {
534        if let Ok(Value::String(state)) = control.eval("return document.readyState;") {
535            if state == "complete" || state == "interactive" {
536                break;
537            }
538        }
539        if Instant::now() >= deadline {
540            let _ = control.stop();
541            return err(format!(
542                "app window never became ready within {}ms",
543                spec.startup_timeout.as_millis()
544            ));
545        }
546        sleep_ms(100);
547    }
548    Ok(control)
549}
550
551#[allow(clippy::too_many_arguments)]
552fn start_process(
553    spec: &LaunchSpec,
554    ws: &QaWorkspace,
555    env: &[(String, String)],
556    log_path: &Path,
557    id: &str,
558    _tracker: &Tracker,
559    focus: &FocusMonitor,
560    deadline: Instant,
561) -> Result<(u32, Option<OwnedChild>)> {
562    #[cfg(target_os = "macos")]
563    {
564        let bundle = if spec.binary.extension().map(|e| e == "app").unwrap_or(false) {
565            spec.binary.clone()
566        } else {
567            make_bundle(&ws.root, &spec.binary, &id[..8], spec.mode != Mode::Visible)?
568        };
569        let needle = format!("{}/Contents/MacOS/", bundle.display());
570        // Register the REAL executable (CFBundleExecutable) before `open`. When it cannot be
571        // resolved and validated, register nothing: the launch interval stays unverified and
572        // `owned_never_frontmost` fails closed instead of matching a guessed name.
573        if let Some(executable) = resolve_bundle_executable(&bundle) {
574            focus.track_prefix(executable);
575        }
576        let mut cmd = Command::new("open");
577        match spec.mode {
578            Mode::Hidden => cmd.args(["-g", "-j", "-n"]),
579            Mode::Background => cmd.args(["-g", "-n"]),
580            Mode::Visible => cmd.args(["-n"]),
581        };
582        // `open --env NAME=VALUE` is the only form that reaches the app on current macOS
583        // (bare `--env NAME` forwarding does not). The per-run secret is therefore briefly
584        // visible in `ps`; it is minted per launch, loopback-only, and dies with the app.
585        for (k, v) in env {
586            cmd.arg("--env").arg(format!("{k}={v}"));
587        }
588        cmd.arg("--stdout")
589            .arg(log_path)
590            .arg("--stderr")
591            .arg(log_path)
592            .arg(&bundle);
593        let st = cmd.status()?;
594        if !st.success() {
595            return err(format!("open exited {st}"));
596        }
597        loop {
598            if let Some(pid) = pids_with_command_prefix(&needle)
599                .ok()
600                .and_then(|pids| pids.into_iter().next())
601            {
602                return Ok((pid, None));
603            }
604            if Instant::now() >= deadline {
605                return err("launched app pid not found");
606            }
607            sleep_ms(100);
608        }
609    }
610    #[cfg(not(target_os = "macos"))]
611    {
612        let _ = (ws, id, focus);
613        let log = fs::File::create(log_path)?;
614        let log2 = log.try_clone()?;
615        let mut cmd = Command::new(&spec.binary);
616        cmd.stdin(Stdio::null())
617            .stdout(Stdio::from(log))
618            .stderr(Stdio::from(log2));
619        for (k, v) in env {
620            cmd.env(k, v);
621        }
622        let mut owned = OwnedCommand::from_command(cmd);
623        if spec.mode != Mode::Visible {
624            owned.windows_hide();
625        }
626        let _ = deadline;
627        let child = owned
628            .spawn()
629            .map_err(|e| Error(format!("failed to start {}: {e}", spec.binary.display())))?;
630        Ok((child.id(), Some(child)))
631    }
632}
633
634impl Control {
635    pub fn set_request_timeout(&mut self, t: Duration) {
636        self.request_timeout = t;
637    }
638
639    /// One bounded request. The deadline is real: when it passes the connection is
640    /// aborted (unblocking the read) and the call fails. A request that may already have
641    /// reached the app is replayed only when the method is a pure read; effects
642    /// (click, key, type, command, eval, ...) are never silently executed twice.
643    fn rpc(&self, method: &str, params: Value) -> Result<Value> {
644        let replayable = matches!(method, "health" | "dom" | "ax" | "screenshot" | "move");
645        let mut g = self.client.lock().unwrap();
646        for attempt in 0..2 {
647            let client = match g.as_ref() {
648                Some(c) => c.clone(),
649                None => {
650                    // Not yet sent anything: reconnecting is always safe.
651                    let c = Arc::new(connect_bounded(
652                        &self.suite,
653                        &self.service,
654                        self.request_timeout,
655                    )?);
656                    *g = Some(c.clone());
657                    c
658                }
659            };
660            match call_bounded(&client, method, params.clone(), self.request_timeout) {
661                Ok(v) => return Ok(v),
662                Err(CallError::TimedOut) => {
663                    *g = None;
664                    return err(format!(
665                        "{method}: no reply within {}ms; connection aborted",
666                        self.request_timeout.as_millis()
667                    ));
668                }
669                Err(CallError::Service(e)) if e.retryable && replayable && attempt == 0 => {
670                    *g = None
671                }
672                Err(CallError::Service(e)) => {
673                    if e.retryable {
674                        *g = None;
675                    }
676                    let mut m = svc_err(e);
677                    if !replayable {
678                        m = Error(format!("{} (not replayed: {method} has effects and the first attempt may have been applied)", m.0));
679                    }
680                    return Err(m);
681                }
682            }
683        }
684        err("control rpc failed")
685    }
686
687    fn json(&self, method: &str, params: Value) -> Result<Value> {
688        let v = self.rpc(method, params)?;
689        if v.get("ok") == Some(&Value::Bool(false)) {
690            return err(format!(
691                "{method}: {}",
692                v.get("error")
693                    .and_then(Value::as_str)
694                    .unwrap_or("unknown error")
695            ));
696        }
697        Ok(v)
698    }
699
700    pub fn health(&self) -> Result<Value> {
701        self.rpc("health", json!({}))
702    }
703    /// Prove the allowlist: an app that is not on it is refused at hello. Returns the error code.
704    pub fn unlisted_app_probe(&self) -> Result<String> {
705        match Client::connect(&self.suite, &self.service, "not-allowlisted-probe") {
706            Ok(_) => err("an unlisted app was accepted by the control service"),
707            Err(e) => Ok(e.code),
708        }
709    }
710    pub fn click(&self, x: f64, y: f64, button: &str, count: u32) -> Result<()> {
711        self.json(
712            "click",
713            json!({"x": x, "y": y, "button": button, "count": count}),
714        )
715        .map(|_| ())
716    }
717    /// [`click`](Self::click) holding modifiers (`"shift"`, `"cmd"`, `"alt"`, `"ctrl"`). They
718    /// travel on the native mouse events, so the page sees `e.shiftKey` etc. as real input.
719    pub fn click_with(
720        &self,
721        x: f64,
722        y: f64,
723        button: &str,
724        count: u32,
725        modifiers: &[&str],
726    ) -> Result<()> {
727        self.json(
728            "click",
729            json!({"x": x, "y": y, "button": button, "count": count, "modifiers": modifiers}),
730        )
731        .map(|_| ())
732    }
733    pub fn move_to(&self, x: f64, y: f64) -> Result<()> {
734        self.json("move", json!({"x": x, "y": y})).map(|_| ())
735    }
736    pub fn drag(&self, from: (f64, f64), to: (f64, f64), steps: u32) -> Result<()> {
737        self.json(
738            "drag",
739            json!({"x1": from.0, "y1": from.1, "x2": to.0, "y2": to.1, "steps": steps}),
740        )
741        .map(|_| ())
742    }
743    pub fn wheel(&self, x: f64, y: f64, dx: f64, dy: f64) -> Result<()> {
744        self.json("wheel", json!({"x": x, "y": y, "dx": dx, "dy": dy}))
745            .map(|_| ())
746    }
747    pub fn key(&self, spec: &str) -> Result<()> {
748        self.json("key", json!({"key": spec})).map(|_| ())
749    }
750    pub fn type_text(&self, text: &str) -> Result<()> {
751        self.json("type", json!({"text": text})).map(|_| ())
752    }
753    /// Evaluate a JS function body (`return ...`) in the page; returns its JSON value.
754    pub fn eval(&self, js: &str) -> Result<Value> {
755        Ok(self
756            .json("eval", json!({"js": js}))?
757            .get("value")
758            .cloned()
759            .unwrap_or(Value::Null))
760    }
761    pub fn dom(&self, selector: &str) -> Result<Vec<Value>> {
762        let v = self.json("dom", json!({"selector": selector}))?;
763        Ok(v.get("elements")
764            .and_then(Value::as_array)
765            .cloned()
766            .unwrap_or_default())
767    }
768    pub fn ax(&self) -> Result<Vec<Value>> {
769        let v = self.json("ax", json!({}))?;
770        Ok(v.get("nodes")
771            .and_then(Value::as_array)
772            .cloned()
773            .unwrap_or_default())
774    }
775    pub fn screenshot_png(&self) -> Result<Vec<u8>> {
776        let v = self.json("screenshot", json!({}))?;
777        // The server masks credential elements before writing; a server that does not
778        // report `masked` predates redaction and its captures are refused.
779        if v.get("masked").and_then(Value::as_u64).is_none() {
780            return err("control server does not redact screenshots; capture refused");
781        }
782        let path = PathBuf::from(
783            v.get("path")
784                .and_then(Value::as_str)
785                .ok_or_else(|| Error("screenshot returned no path".into()))?,
786        );
787        let body = fs::read(&path)?;
788        let _ = fs::remove_file(&path);
789        if body.len() < 8 || &body[1..4] != b"PNG" {
790            return err("screenshot method did not return a PNG");
791        }
792        Ok(body)
793    }
794    pub fn screenshot_to(&self, path: &Path) -> Result<()> {
795        if let Some(p) = path.parent() {
796            fs::create_dir_all(p)?;
797        }
798        fs::write(path, self.screenshot_png()?)?;
799        Ok(())
800    }
801    /// A typed app command registered with `Control::command(name, f)`. The server
802    /// hands the command its `args` string verbatim.
803    pub fn command(&self, name: &str, args: &Value) -> Result<Value> {
804        let args = match args {
805            Value::String(s) => s.clone(),
806            Value::Null => String::new(),
807            other => other.to_string(),
808        };
809        let v = self.json("command", json!({"name": name, "args": args}))?;
810        Ok(v.get("result").cloned().unwrap_or(Value::Null))
811    }
812
813    /// Centre of the first element matching `selector`, in viewport CSS px.
814    pub fn center_of(&self, selector: &str) -> Result<(f64, f64)> {
815        let els = self.dom(selector)?;
816        let first = els
817            .first()
818            .ok_or_else(|| Error(format!("selector matched no element: {selector}")))?;
819        let r: Vec<f64> = first
820            .get("rect")
821            .and_then(Value::as_array)
822            .map(|a| a.iter().filter_map(Value::as_f64).collect())
823            .unwrap_or_default();
824        if r.len() < 4 || r[2] <= 0.0 || r[3] <= 0.0 {
825            return err(format!("{selector} has no visible box"));
826        }
827        Ok((r[0] + r[2] / 2.0, r[1] + r[3] / 2.0))
828    }
829    pub fn click_selector(&self, selector: &str) -> Result<()> {
830        let (x, y) = self.center_of(selector)?;
831        self.click(x, y, "left", 1)
832    }
833
834    /// Poll a JS function body until it returns something truthy; bounded.
835    pub fn wait_eval(&self, js: &str, timeout: Duration) -> Result<Value> {
836        let deadline = Instant::now() + timeout;
837        let mut last;
838        loop {
839            match self.eval(js) {
840                Ok(v) => {
841                    let truthy = !matches!(v, Value::Null | Value::Bool(false))
842                        && v != json!(0)
843                        && v != json!("");
844                    if truthy {
845                        return Ok(v);
846                    }
847                    last = v;
848                }
849                Err(e) => last = json!(e.0),
850            }
851            if Instant::now() >= deadline {
852                return err(format!("timeout waiting for `{js}` (last: {last})"));
853            }
854            sleep_ms(100);
855        }
856    }
857
858    /// Stop the app: kill the recorded pid tree, prove the port closed, and check
859    /// we did not change the frontmost app.
860    pub fn stop(&mut self) -> Result<StopReport> {
861        if self.stopped {
862            return err("control session already stopped");
863        }
864        self.stopped = true;
865        if let Some(mut c) = self.child.take() {
866            let _ = c.terminate_tree();
867        }
868        kill_tree(self.pid);
869        let deadline = Instant::now() + Duration::from_secs(5);
870        while Instant::now() < deadline && (is_alive(self.pid) || endpoint_open(&self.endpoint)) {
871            sleep_ms(50);
872        }
873        let _ = fs::copy(&self.raw_log, &self.log_path);
874        let _ = fs::remove_file(&self.raw_log);
875        let after = frontmost();
876        let (steady, states, owned_never_frontmost, owned_frontmost_pids) = self
877            .focus
878            .take()
879            .map(|mut f| f.finish())
880            .unwrap_or((false, vec![], false, vec![]));
881        let process_gone = !is_alive(self.pid);
882        let endpoint_closed = self.endpoint.is_empty() || !endpoint_open(&self.endpoint);
883        if process_gone {
884            self.tracker.forget(self.pid);
885        }
886        Ok(StopReport {
887            pid: self.pid,
888            endpoint_closed,
889            process_gone,
890            frontmost_unchanged: steady
891                && self.frontmost_before.is_some()
892                && self.frontmost_before == after,
893            frontmost_states: states,
894            frontmost_before: self.frontmost_before.clone(),
895            frontmost_after: after,
896            owned_never_frontmost,
897            owned_frontmost_pids,
898        })
899    }
900}
901
902impl Drop for Control {
903    fn drop(&mut self) {
904        if !self.stopped {
905            let _ = self.stop();
906        }
907    }
908}