1use 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 Hidden,
29 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 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 pub frontmost_states: Vec<String>,
67 pub owned_never_frontmost: bool,
70 pub owned_frontmost_pids: Vec<u32>,
72}
73
74pub struct Control {
75 pub pid: u32,
76 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
102fn 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
157pub 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
187struct FocusMonitor {
191 stop: Arc<std::sync::atomic::AtomicBool>,
192 seen: Arc<Mutex<(usize, usize, Vec<String>)>>, owned: Arc<Mutex<(Vec<u32>, Option<String>)>>, 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 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 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 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 let owned_never_frontmost = !self.enforce_owned;
316 (unchanged, g.2.clone(), owned_never_frontmost, observed)
317 }
318}
319
320fn 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#[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 if fs::hard_link(&abs, &target).is_err() {
393 fs::copy(&abs, &target)?;
394 }
395 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")]
409fn 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 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 let raw_log = ws.home.join(format!("app-{}.log", &id[..8]));
453 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 pub fn wait_for_text(
861 &self,
862 selector: Option<&str>,
863 text: &str,
864 timeout: Duration,
865 ) -> Result<()> {
866 let sel = serde_json::to_string(selector.unwrap_or("body")).unwrap_or_default();
867 let needle = serde_json::to_string(text).unwrap_or_default();
868 let js = format!(
869 "return ((document.querySelector({sel}) || {{}}).innerText || '').includes({needle});"
870 );
871 self.wait_eval(&js, timeout).map(|_| ())
872 }
873
874 pub fn stop(&mut self) -> Result<StopReport> {
877 if self.stopped {
878 return err("control session already stopped");
879 }
880 self.stopped = true;
881 if let Some(mut c) = self.child.take() {
882 let _ = c.terminate_tree();
883 }
884 kill_tree(self.pid);
885 let deadline = Instant::now() + Duration::from_secs(5);
886 while Instant::now() < deadline && (is_alive(self.pid) || endpoint_open(&self.endpoint)) {
887 sleep_ms(50);
888 }
889 let _ = fs::copy(&self.raw_log, &self.log_path);
890 let _ = fs::remove_file(&self.raw_log);
891 let after = frontmost();
892 let (steady, states, owned_never_frontmost, owned_frontmost_pids) = self
893 .focus
894 .take()
895 .map(|mut f| f.finish())
896 .unwrap_or((false, vec![], false, vec![]));
897 let process_gone = !is_alive(self.pid);
898 let endpoint_closed = self.endpoint.is_empty() || !endpoint_open(&self.endpoint);
899 if process_gone {
900 self.tracker.forget(self.pid);
901 }
902 Ok(StopReport {
903 pid: self.pid,
904 endpoint_closed,
905 process_gone,
906 frontmost_unchanged: steady
907 && self.frontmost_before.is_some()
908 && self.frontmost_before == after,
909 frontmost_states: states,
910 frontmost_before: self.frontmost_before.clone(),
911 frontmost_after: after,
912 owned_never_frontmost,
913 owned_frontmost_pids,
914 })
915 }
916}
917
918impl Drop for Control {
919 fn drop(&mut self) {
920 if !self.stopped {
921 let _ = self.stop();
922 }
923 }
924}