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)> =
454 ws.env.iter().map(|(k, v)| (k.clone(), v.clone())).collect();
455 env.push(("RIGHTKIT_CONTROL_SERVICE".into(), service.clone()));
456 env.push((
457 "RIGHTKIT_SUITE_ROOT".into(),
458 suite.root().to_string_lossy().into(),
459 ));
460 env.push((
461 "RIGHTKIT_QA_HIDDEN".into(),
462 if spec.mode == Mode::Hidden { "1" } else { "0" }.into(),
463 ));
464 env.push((
467 "RIGHTKIT_QA_BACKGROUND".into(),
468 if spec.mode != Mode::Visible { "1" } else { "0" }.into(),
469 ));
470 env.extend(spec.env.iter().cloned());
471 check_env(&env)?;
472 let frontmost_before = frontmost();
473 let focus = FocusMonitor::start(spec.mode != Mode::Visible);
474 let deadline = Instant::now() + spec.startup_timeout;
475
476 let (pid, child) = start_process(spec, ws, &env, &raw_log, &id, tracker, &focus, deadline)?;
479 focus.track_primary(pid);
480 tracker.register(pid, &spec.label);
481
482 let mut control = Control {
483 pid,
484 service: service.clone(),
485 log_path,
486 raw_log,
487 suite: suite.clone(),
488 endpoint: String::new(),
489 client: Mutex::new(None),
490 child,
491 tracker: tracker.clone(),
492 frontmost_before,
493 focus: Some(focus),
494 request_timeout: Duration::from_secs(20),
495 stopped: false,
496 };
497 loop {
498 let left = deadline.saturating_duration_since(Instant::now());
500 if let Some(c) = bounded_connect_health(&suite, &service, left.min(Duration::from_secs(5)))
501 {
502 control.endpoint = c.record().endpoint.clone();
503 *control.client.lock().unwrap() = Some(c);
504 break;
505 }
506 if !is_alive(pid) {
507 let tail = fs::read_to_string(&control.raw_log)
508 .map(|t| crate::util::tail(&t, 1500))
509 .unwrap_or_default();
510 return err(format!(
511 "app exited before its control server came up (pid {pid}); log tail: {tail}"
512 ));
513 }
514 if Instant::now() >= deadline {
515 let _ = control.stop();
516 return err(format!(
517 "control service did not answer within {}ms; was the app built with its control feature and launched with RIGHTKIT_CONTROL_SERVICE?",
518 spec.startup_timeout.as_millis()
519 ));
520 }
521 sleep_ms(100);
522 }
523 loop {
526 if let Ok(Value::String(state)) = control.eval("return document.readyState;") {
527 if state == "complete" || state == "interactive" {
528 break;
529 }
530 }
531 if Instant::now() >= deadline {
532 let _ = control.stop();
533 return err(format!(
534 "app window never became ready within {}ms",
535 spec.startup_timeout.as_millis()
536 ));
537 }
538 sleep_ms(100);
539 }
540 Ok(control)
541}
542
543#[allow(clippy::too_many_arguments)]
544fn start_process(
545 spec: &LaunchSpec,
546 ws: &QaWorkspace,
547 env: &[(String, String)],
548 log_path: &Path,
549 id: &str,
550 _tracker: &Tracker,
551 focus: &FocusMonitor,
552 deadline: Instant,
553) -> Result<(u32, Option<OwnedChild>)> {
554 #[cfg(target_os = "macos")]
555 {
556 let bundle = if spec.binary.extension().map(|e| e == "app").unwrap_or(false) {
557 spec.binary.clone()
558 } else {
559 make_bundle(&ws.root, &spec.binary, &id[..8], spec.mode != Mode::Visible)?
560 };
561 let needle = format!("{}/Contents/MacOS/", bundle.display());
562 if let Some(executable) = resolve_bundle_executable(&bundle) {
566 focus.track_prefix(executable);
567 }
568 let mut cmd = Command::new("open");
569 match spec.mode {
570 Mode::Hidden => cmd.args(["-g", "-j", "-n"]),
571 Mode::Background => cmd.args(["-g", "-n"]),
572 Mode::Visible => cmd.args(["-n"]),
573 };
574 for (k, v) in env {
578 cmd.arg("--env").arg(format!("{k}={v}"));
579 }
580 cmd.arg("--stdout")
581 .arg(log_path)
582 .arg("--stderr")
583 .arg(log_path)
584 .arg(&bundle);
585 let st = cmd.status()?;
586 if !st.success() {
587 return err(format!("open exited {st}"));
588 }
589 loop {
590 if let Some(pid) = pids_with_command_prefix(&needle)
591 .ok()
592 .and_then(|pids| pids.into_iter().next())
593 {
594 return Ok((pid, None));
595 }
596 if Instant::now() >= deadline {
597 return err("launched app pid not found");
598 }
599 sleep_ms(100);
600 }
601 }
602 #[cfg(not(target_os = "macos"))]
603 {
604 let _ = (ws, id, focus);
605 let log = fs::File::create(log_path)?;
606 let log2 = log.try_clone()?;
607 let mut cmd = Command::new(&spec.binary);
608 cmd.stdin(Stdio::null())
609 .stdout(Stdio::from(log))
610 .stderr(Stdio::from(log2));
611 for (k, v) in env {
612 cmd.env(k, v);
613 }
614 let mut owned = OwnedCommand::from_command(cmd);
615 if spec.mode != Mode::Visible {
616 owned.windows_hide();
617 }
618 let _ = deadline;
619 let child = owned
620 .spawn()
621 .map_err(|e| Error(format!("failed to start {}: {e}", spec.binary.display())))?;
622 Ok((child.id(), Some(child)))
623 }
624}
625
626impl Control {
627 pub fn set_request_timeout(&mut self, t: Duration) {
628 self.request_timeout = t;
629 }
630
631 fn rpc(&self, method: &str, params: Value) -> Result<Value> {
636 let replayable = matches!(method, "health" | "dom" | "ax" | "screenshot" | "move");
637 let mut g = self.client.lock().unwrap();
638 for attempt in 0..2 {
639 let client = match g.as_ref() {
640 Some(c) => c.clone(),
641 None => {
642 let c = Arc::new(connect_bounded(
644 &self.suite,
645 &self.service,
646 self.request_timeout,
647 )?);
648 *g = Some(c.clone());
649 c
650 }
651 };
652 match call_bounded(&client, method, params.clone(), self.request_timeout) {
653 Ok(v) => return Ok(v),
654 Err(CallError::TimedOut) => {
655 *g = None;
656 return err(format!(
657 "{method}: no reply within {}ms; connection aborted",
658 self.request_timeout.as_millis()
659 ));
660 }
661 Err(CallError::Service(e)) if e.retryable && replayable && attempt == 0 => {
662 *g = None
663 }
664 Err(CallError::Service(e)) => {
665 if e.retryable {
666 *g = None;
667 }
668 let mut m = svc_err(e);
669 if !replayable {
670 m = Error(format!("{} (not replayed: {method} has effects and the first attempt may have been applied)", m.0));
671 }
672 return Err(m);
673 }
674 }
675 }
676 err("control rpc failed")
677 }
678
679 fn json(&self, method: &str, params: Value) -> Result<Value> {
680 let v = self.rpc(method, params)?;
681 if v.get("ok") == Some(&Value::Bool(false)) {
682 return err(format!(
683 "{method}: {}",
684 v.get("error")
685 .and_then(Value::as_str)
686 .unwrap_or("unknown error")
687 ));
688 }
689 Ok(v)
690 }
691
692 pub fn health(&self) -> Result<Value> {
693 self.rpc("health", json!({}))
694 }
695 pub fn unlisted_app_probe(&self) -> Result<String> {
697 match Client::connect(&self.suite, &self.service, "not-allowlisted-probe") {
698 Ok(_) => err("an unlisted app was accepted by the control service"),
699 Err(e) => Ok(e.code),
700 }
701 }
702 pub fn click(&self, x: f64, y: f64, button: &str, count: u32) -> Result<()> {
703 self.json(
704 "click",
705 json!({"x": x, "y": y, "button": button, "count": count}),
706 )
707 .map(|_| ())
708 }
709 pub fn move_to(&self, x: f64, y: f64) -> Result<()> {
710 self.json("move", json!({"x": x, "y": y})).map(|_| ())
711 }
712 pub fn drag(&self, from: (f64, f64), to: (f64, f64), steps: u32) -> Result<()> {
713 self.json(
714 "drag",
715 json!({"x1": from.0, "y1": from.1, "x2": to.0, "y2": to.1, "steps": steps}),
716 )
717 .map(|_| ())
718 }
719 pub fn wheel(&self, x: f64, y: f64, dx: f64, dy: f64) -> Result<()> {
720 self.json("wheel", json!({"x": x, "y": y, "dx": dx, "dy": dy}))
721 .map(|_| ())
722 }
723 pub fn key(&self, spec: &str) -> Result<()> {
724 self.json("key", json!({"key": spec})).map(|_| ())
725 }
726 pub fn type_text(&self, text: &str) -> Result<()> {
727 self.json("type", json!({"text": text})).map(|_| ())
728 }
729 pub fn eval(&self, js: &str) -> Result<Value> {
731 Ok(self
732 .json("eval", json!({"js": js}))?
733 .get("value")
734 .cloned()
735 .unwrap_or(Value::Null))
736 }
737 pub fn dom(&self, selector: &str) -> Result<Vec<Value>> {
738 let v = self.json("dom", json!({"selector": selector}))?;
739 Ok(v.get("elements")
740 .and_then(Value::as_array)
741 .cloned()
742 .unwrap_or_default())
743 }
744 pub fn ax(&self) -> Result<Vec<Value>> {
745 let v = self.json("ax", json!({}))?;
746 Ok(v.get("nodes")
747 .and_then(Value::as_array)
748 .cloned()
749 .unwrap_or_default())
750 }
751 pub fn screenshot_png(&self) -> Result<Vec<u8>> {
752 let v = self.json("screenshot", json!({}))?;
753 if v.get("masked").and_then(Value::as_u64).is_none() {
756 return err("control server does not redact screenshots; capture refused");
757 }
758 let path = PathBuf::from(
759 v.get("path")
760 .and_then(Value::as_str)
761 .ok_or_else(|| Error("screenshot returned no path".into()))?,
762 );
763 let body = fs::read(&path)?;
764 let _ = fs::remove_file(&path);
765 if body.len() < 8 || &body[1..4] != b"PNG" {
766 return err("screenshot method did not return a PNG");
767 }
768 Ok(body)
769 }
770 pub fn screenshot_to(&self, path: &Path) -> Result<()> {
771 if let Some(p) = path.parent() {
772 fs::create_dir_all(p)?;
773 }
774 fs::write(path, self.screenshot_png()?)?;
775 Ok(())
776 }
777 pub fn command(&self, name: &str, args: &Value) -> Result<Value> {
780 let args = match args {
781 Value::String(s) => s.clone(),
782 Value::Null => String::new(),
783 other => other.to_string(),
784 };
785 let v = self.json("command", json!({"name": name, "args": args}))?;
786 Ok(v.get("result").cloned().unwrap_or(Value::Null))
787 }
788
789 pub fn center_of(&self, selector: &str) -> Result<(f64, f64)> {
791 let els = self.dom(selector)?;
792 let first = els
793 .first()
794 .ok_or_else(|| Error(format!("selector matched no element: {selector}")))?;
795 let r: Vec<f64> = first
796 .get("rect")
797 .and_then(Value::as_array)
798 .map(|a| a.iter().filter_map(Value::as_f64).collect())
799 .unwrap_or_default();
800 if r.len() < 4 || r[2] <= 0.0 || r[3] <= 0.0 {
801 return err(format!("{selector} has no visible box"));
802 }
803 Ok((r[0] + r[2] / 2.0, r[1] + r[3] / 2.0))
804 }
805 pub fn click_selector(&self, selector: &str) -> Result<()> {
806 let (x, y) = self.center_of(selector)?;
807 self.click(x, y, "left", 1)
808 }
809
810 pub fn wait_eval(&self, js: &str, timeout: Duration) -> Result<Value> {
812 let deadline = Instant::now() + timeout;
813 let mut last;
814 loop {
815 match self.eval(js) {
816 Ok(v) => {
817 let truthy = !matches!(v, Value::Null | Value::Bool(false))
818 && v != json!(0)
819 && v != json!("");
820 if truthy {
821 return Ok(v);
822 }
823 last = v;
824 }
825 Err(e) => last = json!(e.0),
826 }
827 if Instant::now() >= deadline {
828 return err(format!("timeout waiting for `{js}` (last: {last})"));
829 }
830 sleep_ms(100);
831 }
832 }
833
834 pub fn stop(&mut self) -> Result<StopReport> {
837 if self.stopped {
838 return err("control session already stopped");
839 }
840 self.stopped = true;
841 if let Some(mut c) = self.child.take() {
842 let _ = c.terminate_tree();
843 }
844 kill_tree(self.pid);
845 let deadline = Instant::now() + Duration::from_secs(5);
846 while Instant::now() < deadline && (is_alive(self.pid) || endpoint_open(&self.endpoint)) {
847 sleep_ms(50);
848 }
849 let _ = fs::copy(&self.raw_log, &self.log_path);
850 let _ = fs::remove_file(&self.raw_log);
851 let after = frontmost();
852 let (steady, states, owned_never_frontmost, owned_frontmost_pids) = self
853 .focus
854 .take()
855 .map(|mut f| f.finish())
856 .unwrap_or((false, vec![], false, vec![]));
857 let process_gone = !is_alive(self.pid);
858 let endpoint_closed = self.endpoint.is_empty() || !endpoint_open(&self.endpoint);
859 if process_gone {
860 self.tracker.forget(self.pid);
861 }
862 Ok(StopReport {
863 pid: self.pid,
864 endpoint_closed,
865 process_gone,
866 frontmost_unchanged: steady
867 && self.frontmost_before.is_some()
868 && self.frontmost_before == after,
869 frontmost_states: states,
870 frontmost_before: self.frontmost_before.clone(),
871 frontmost_after: after,
872 owned_never_frontmost,
873 owned_frontmost_pids,
874 })
875 }
876}
877
878impl Drop for Control {
879 fn drop(&mut self) {
880 if !self.stopped {
881 let _ = self.stop();
882 }
883 }
884}