interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core-mv / crates / aien-cli / src / browser_mirror.rs

1494 lines · 56849 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Headless-Chrome Cockpit mirror over the Chrome DevTools Protocol (CDP).
17//!
18//! This is the Rust replacement for the removed Python script
19//! `basecamp/scripts/browser_mirror_test.py` (sovereign-core #180/#181). It
20//! carries no new dependencies: the websocket client, the tiny HTTP fetch and
21//! the base64 decoder are written here against `std::net`.
22//!
23//! Modes (also exposed by the `aien-browser-mirror` binary and `aien --browser`):
24//!
25//! * `test` Cockpit self-test: hydration, chat stream, navigation, three screenshots.
26//! * `mentor` Send one prompt to the Cockpit chat, wait for the reply, screenshot it.
27//! * `screenshot` Open any URL, capture a PNG, record the document title.
28//! * `eval` Open any URL and evaluate a JavaScript expression (value returned as JSON).
29//!
30//! Every mode spawns its own Chrome with a private profile directory. Linux
31//! cleanup requires pidfd support to stop tagged detached helpers without a
32//! recycled-PID race. Detached-helper cleanup on other Unix is not qualified.
33
34use serde_json::{json, Value};
35use std::fs;
36use std::io::{Read, Write};
37use std::net::TcpStream;
38use std::os::unix::fs::DirBuilderExt;
39#[cfg(not(target_os = "linux"))]
40use std::os::unix::process::CommandExt;
41use std::path::{Path, PathBuf};
42use std::process::{Child, Command, Stdio};
43use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
44
45/// Default Cockpit address (spark-cockpit-rs).
46pub const DEFAULT_URL: &str = "http://127.0.0.1:18095";
47
48/// How long to wait for Chrome to publish its debugging port.
49const CHROME_BOOT_TIMEOUT: Duration = Duration::from_secs(20);
50/// Per-command CDP reply timeout.
51const CDP_REPLY_TIMEOUT: Duration = Duration::from_secs(30);
52/// Largest websocket message we accept (screenshots are a few MB).
53const MAX_WS_MESSAGE: usize = 64 * 1024 * 1024;
54/// How long dropping a browser may take to see every one of its processes gone.
55const REAP_TIMEOUT: Duration = Duration::from_secs(5);
56/// Environment variable carrying a per-browser tag. Chrome's crash reporters detach into
57/// their own session, so they escape the process group; the inherited tag still finds them.
58const TAG_VAR: &str = "AIEN_BROWSER_MIRROR_TAG";
59
60/// Where screenshots and reports land when no `--out-dir` is given.
61pub fn default_out_dir() -> PathBuf {
62 let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
63 Path::new(&home).join("basecamp").join("ui-tests")
64}
65
66/// Candidate Chrome binaries, first match wins. `AIEN_CHROME` overrides.
67pub fn chrome_candidates() -> Vec<String> {
68 let mut v = Vec::new();
69 if let Ok(p) = std::env::var("AIEN_CHROME") {
70 if !p.is_empty() {
71 v.push(p);
72 }
73 }
74 for name in [
75 "google-chrome",
76 "google-chrome-stable",
77 "chromium",
78 "chromium-browser",
79 "chrome",
80 ] {
81 v.push(name.to_string());
82 }
83 v
84}
85
86/// Returns the first Chrome binary that answers `--version`, if any.
87pub fn find_chrome() -> Option<String> {
88 chrome_candidates().into_iter().find(|c| {
89 Command::new(c)
90 .arg("--version")
91 .stdout(Stdio::null())
92 .stderr(Stdio::null())
93 .status()
94 .map(|s| s.success())
95 .unwrap_or(false)
96 })
97}
98
99fn now_secs() -> u64 {
100 SystemTime::now()
101 .duration_since(UNIX_EPOCH)
102 .map(|d| d.as_secs())
103 .unwrap_or(0)
104}
105
106fn now_nanos() -> u128 {
107 SystemTime::now()
108 .duration_since(UNIX_EPOCH)
109 .map(|d| d.as_nanos())
110 .unwrap_or(0)
111}
112
113// ---------------------------------------------------------------------------
114// base64 (standard alphabet, padding tolerated)
115// ---------------------------------------------------------------------------
116
117const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
118
119fn base64_encode(data: &[u8]) -> String {
120 let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
121 for chunk in data.chunks(3) {
122 let b = [
123 chunk[0],
124 chunk.get(1).copied().unwrap_or(0),
125 chunk.get(2).copied().unwrap_or(0),
126 ];
127 let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]);
128 out.push(B64[(n >> 18) as usize & 63] as char);
129 out.push(B64[(n >> 12) as usize & 63] as char);
130 out.push(if chunk.len() > 1 {
131 B64[(n >> 6) as usize & 63] as char
132 } else {
133 '='
134 });
135 out.push(if chunk.len() > 2 {
136 B64[n as usize & 63] as char
137 } else {
138 '='
139 });
140 }
141 out
142}
143
144/// Decodes standard base64. Whitespace is skipped; anything else is an error.
145pub fn base64_decode(text: &str) -> Result<Vec<u8>, String> {
146 fn val(c: u8) -> Option<u32> {
147 match c {
148 b'A'..=b'Z' => Some(u32::from(c - b'A')),
149 b'a'..=b'z' => Some(u32::from(c - b'a') + 26),
150 b'0'..=b'9' => Some(u32::from(c - b'0') + 52),
151 b'+' => Some(62),
152 b'/' => Some(63),
153 _ => None,
154 }
155 }
156 let mut out = Vec::with_capacity(text.len() / 4 * 3);
157 let mut acc: u32 = 0;
158 let mut bits = 0u32;
159 for &c in text.as_bytes() {
160 if c.is_ascii_whitespace() || c == b'=' {
161 continue;
162 }
163 let v = val(c).ok_or_else(|| format!("base64: invalid byte 0x{:02x}", c))?;
164 acc = (acc << 6) | v;
165 bits += 6;
166 if bits >= 8 {
167 bits -= 8;
168 out.push((acc >> bits) as u8);
169 acc &= (1 << bits) - 1;
170 }
171 }
172 Ok(out)
173}
174
175// ---------------------------------------------------------------------------
176// Minimal HTTP GET (used for /json on the DevTools port)
177// ---------------------------------------------------------------------------
178
179fn http_get(host: &str, port: u16, path: &str, timeout: Duration) -> Result<String, String> {
180 let mut s = TcpStream::connect((host, port)).map_err(|e| format!("connect: {}", e))?;
181 s.set_read_timeout(Some(timeout))
182 .map_err(|e| format!("timeout: {}", e))?;
183 let req = format!(
184 "GET {} HTTP/1.1\r\nHost: {}:{}\r\nConnection: close\r\n\r\n",
185 path, host, port
186 );
187 s.write_all(req.as_bytes())
188 .map_err(|e| format!("write: {}", e))?;
189 // Chrome honours Content-Length but keeps the connection open, so read the
190 // headers first and then exactly the announced body.
191 let mut head = Vec::new();
192 let mut one = [0u8; 1];
193 while !head.ends_with(b"\r\n\r\n") {
194 let n = s.read(&mut one).map_err(|e| format!("read: {}", e))?;
195 if n == 0 {
196 return Err("http: connection closed in headers".to_string());
197 }
198 head.push(one[0]);
199 if head.len() > 64 * 1024 {
200 return Err("http: header too long".to_string());
201 }
202 }
203 let head = String::from_utf8_lossy(&head).to_string();
204 let status = head.lines().next().unwrap_or("");
205 if !status.contains(" 200 ") {
206 return Err(format!("http: {}", status));
207 }
208 let len = head.lines().find_map(|l| {
209 let (k, v) = l.split_once(':')?;
210 if k.trim().eq_ignore_ascii_case("content-length") {
211 v.trim().parse::<usize>().ok()
212 } else {
213 None
214 }
215 });
216 let mut body = Vec::new();
217 match len {
218 Some(n) => {
219 body.resize(n, 0);
220 s.read_exact(&mut body)
221 .map_err(|e| format!("read body: {}", e))?;
222 }
223 None => {
224 s.read_to_end(&mut body)
225 .map_err(|e| format!("read: {}", e))?;
226 }
227 }
228 Ok(String::from_utf8_lossy(&body).to_string())
229}
230
231// ---------------------------------------------------------------------------
232// Websocket client (RFC 6455, client side, text frames)
233// ---------------------------------------------------------------------------
234
235struct WebSocket {
236 stream: TcpStream,
237 rng: u64,
238}
239
240impl WebSocket {
241 /// Connects to `ws://host:port/path` and completes the HTTP upgrade.
242 fn connect(url: &str) -> Result<Self, String> {
243 let rest = url
244 .strip_prefix("ws://")
245 .ok_or_else(|| format!("websocket: unsupported url {}", url))?;
246 let (hostport, path) = match rest.find('/') {
247 Some(i) => (&rest[..i], &rest[i..]),
248 None => (rest, "/"),
249 };
250 let (host, port) = match hostport.rsplit_once(':') {
251 Some((h, p)) => (h, p.parse::<u16>().map_err(|e| format!("port: {}", e))?),
252 None => (hostport, 80),
253 };
254 let stream = TcpStream::connect((host, port)).map_err(|e| format!("connect: {}", e))?;
255 stream
256 .set_read_timeout(Some(CDP_REPLY_TIMEOUT))
257 .map_err(|e| format!("timeout: {}", e))?;
258 stream.set_nodelay(true).ok();
259 let mut ws = WebSocket {
260 stream,
261 rng: now_nanos() as u64 ^ 0x9E37_79B9_7F4A_7C15,
262 };
263 let mut key = [0u8; 16];
264 for b in key.iter_mut() {
265 *b = ws.next_byte();
266 }
267 let req = format!(
268 "GET {} HTTP/1.1\r\nHost: {}:{}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\
269 Sec-WebSocket-Key: {}\r\nSec-WebSocket-Version: 13\r\n\r\n",
270 path,
271 host,
272 port,
273 base64_encode(&key)
274 );
275 ws.stream
276 .write_all(req.as_bytes())
277 .map_err(|e| format!("handshake write: {}", e))?;
278 // Read the response headers byte by byte up to the blank line.
279 let mut head = Vec::new();
280 let mut one = [0u8; 1];
281 while !head.ends_with(b"\r\n\r\n") {
282 let n = ws
283 .stream
284 .read(&mut one)
285 .map_err(|e| format!("handshake read: {}", e))?;
286 if n == 0 {
287 return Err("handshake: connection closed".to_string());
288 }
289 head.push(one[0]);
290 if head.len() > 16 * 1024 {
291 return Err("handshake: header too long".to_string());
292 }
293 }
294 let text = String::from_utf8_lossy(&head);
295 let status = text.lines().next().unwrap_or("");
296 if !status.contains(" 101 ") {
297 return Err(format!("handshake refused: {}", status));
298 }
299 Ok(ws)
300 }
301
302 fn next_byte(&mut self) -> u8 {
303 // xorshift64*: only used for mask keys and the handshake nonce.
304 let mut x = self.rng;
305 x ^= x >> 12;
306 x ^= x << 25;
307 x ^= x >> 27;
308 self.rng = x;
309 (x.wrapping_mul(0x2545_F491_4F6C_DD1D) >> 56) as u8
310 }
311
312 fn send_frame(&mut self, opcode: u8, payload: &[u8]) -> Result<(), String> {
313 let mut frame = Vec::with_capacity(payload.len() + 14);
314 frame.push(0x80 | opcode);
315 let len = payload.len();
316 if len < 126 {
317 frame.push(0x80 | len as u8);
318 } else if len <= 0xFFFF {
319 frame.push(0x80 | 126);
320 frame.extend_from_slice(&(len as u16).to_be_bytes());
321 } else {
322 frame.push(0x80 | 127);
323 frame.extend_from_slice(&(len as u64).to_be_bytes());
324 }
325 let mask = [
326 self.next_byte(),
327 self.next_byte(),
328 self.next_byte(),
329 self.next_byte(),
330 ];
331 frame.extend_from_slice(&mask);
332 frame.extend(payload.iter().enumerate().map(|(i, b)| b ^ mask[i % 4]));
333 self.stream
334 .write_all(&frame)
335 .map_err(|e| format!("websocket write: {}", e))
336 }
337
338 fn send_text(&mut self, text: &str) -> Result<(), String> {
339 self.send_frame(0x1, text.as_bytes())
340 }
341
342 fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), String> {
343 self.stream
344 .read_exact(buf)
345 .map_err(|e| format!("websocket read: {}", e))
346 }
347
348 /// Reads one complete text message, answering pings and honouring close.
349 fn recv_text(&mut self) -> Result<String, String> {
350 let mut message: Vec<u8> = Vec::new();
351 loop {
352 let mut hdr = [0u8; 2];
353 self.read_exact(&mut hdr)?;
354 let fin = hdr[0] & 0x80 != 0;
355 let opcode = hdr[0] & 0x0F;
356 let masked = hdr[1] & 0x80 != 0;
357 let mut len = u64::from(hdr[1] & 0x7F);
358 if len == 126 {
359 let mut b = [0u8; 2];
360 self.read_exact(&mut b)?;
361 len = u64::from(u16::from_be_bytes(b));
362 } else if len == 127 {
363 let mut b = [0u8; 8];
364 self.read_exact(&mut b)?;
365 len = u64::from_be_bytes(b);
366 }
367 if len as usize > MAX_WS_MESSAGE || message.len() + len as usize > MAX_WS_MESSAGE {
368 return Err("websocket: message too large".to_string());
369 }
370 let mut mask = [0u8; 4];
371 if masked {
372 self.read_exact(&mut mask)?;
373 }
374 let mut payload = vec![0u8; len as usize];
375 self.read_exact(&mut payload)?;
376 if masked {
377 for (i, b) in payload.iter_mut().enumerate() {
378 *b ^= mask[i % 4];
379 }
380 }
381 match opcode {
382 0x0..=0x2 => {
383 message.extend_from_slice(&payload);
384 if fin {
385 return String::from_utf8(message)
386 .map_err(|e| format!("websocket: bad utf-8: {}", e));
387 }
388 }
389 0x8 => {
390 self.send_frame(0x8, &payload).ok();
391 return Err("websocket: closed by peer".to_string());
392 }
393 0x9 => self.send_frame(0xA, &payload)?,
394 0xA => {}
395 other => return Err(format!("websocket: unknown opcode {}", other)),
396 }
397 }
398 }
399
400 fn close(&mut self) {
401 self.send_frame(0x8, &1000u16.to_be_bytes()).ok();
402 }
403}
404
405// ---------------------------------------------------------------------------
406// Chrome process + CDP session
407// ---------------------------------------------------------------------------
408
409struct ChromeProcess {
410 child: Child,
411 profile_dir: PathBuf,
412 port: u16,
413 /// Value of `TAG_VAR` in every process this browser started (unique per spawn).
414 tag: String,
415 /// Once reaped, its numeric PID/PGID is no longer an ownership handle.
416 main_reaped: bool,
417}
418
419impl ChromeProcess {
420 fn spawn(binary: &str, url: &str) -> Result<Self, String> {
421 #[cfg(target_os = "linux")]
422 if !TaggedProcess::available() {
423 return Err("safe Chrome cleanup requires Linux pidfd signaling".to_string());
424 }
425 let tag = format!("aien-browser-mirror-{}-{}", std::process::id(), now_nanos());
426 let profile_dir = std::env::temp_dir().join(&tag);
427 fs::DirBuilder::new()
428 .mode(0o700)
429 .create(&profile_dir)
430 .map_err(|e| format!("profile dir: {}", e))?;
431 let mut command = Command::new(binary);
432 command.env(TAG_VAR, &tag);
433 // Chrome's crashpad handler keeps its database under XDG_CONFIG_HOME (default ~/.config).
434 // With a read-only HOME (the aien-local-ci sandbox) the handler exits with "--database is
435 // required" and Chrome dies with SIGTRAP before it opens the debugging port. Keep the
436 // config and cache dirs inside this run's throwaway profile so a read-only HOME is enough.
437 command.env("XDG_CONFIG_HOME", &profile_dir);
438 command.env("XDG_CACHE_HOME", &profile_dir);
439 // Linux teardown signals only pidfds, never numeric PID/PGID targets, so
440 // Chrome stays in the caller's process group: a Ctrl-C or a harness
441 // group kill that ends the caller before Drop runs also reaches Chrome.
442 // Other Unix teardown signals the group, so Chrome leads its own there.
443 #[cfg(not(target_os = "linux"))]
444 command.process_group(0);
445 // --use-gl=disabled --disable-software-rasterizer: with --disable-gpu alone, Chrome 153
446 // headless on aarch64 (DGX Spark, no display) falls back to a SwiftShader GPU process and
447 // Page.captureScreenshot then gets no reply at all (sovereign-core #661; main 92df274c).
448 let spawned = command
449 .arg("--headless=new")
450 .arg("--remote-debugging-port=0")
451 .arg(format!("--user-data-dir={}", profile_dir.display()))
452 .arg("--remote-allow-origins=*")
453 .arg("--no-first-run")
454 .arg("--no-default-browser-check")
455 .arg("--disable-dev-shm-usage")
456 .arg("--disable-gpu")
457 .arg("--use-gl=disabled")
458 .arg("--disable-software-rasterizer")
459 .arg("--no-sandbox")
460 .arg("--window-size=1280,900")
461 .arg(url)
462 .stdin(Stdio::null())
463 .stdout(Stdio::null())
464 .stderr(Stdio::null())
465 .spawn();
466 let child = match spawned {
467 Ok(c) => c,
468 Err(e) => {
469 fs::remove_dir_all(&profile_dir).ok();
470 return Err(format!("spawn {}: {}", binary, e));
471 }
472 };
473 let mut me = ChromeProcess {
474 child,
475 profile_dir,
476 port: 0,
477 tag,
478 main_reaped: false,
479 };
480 // Chrome writes "<port>\n<browser ws path>" once the debugger listens.
481 let deadline = Instant::now() + CHROME_BOOT_TIMEOUT;
482 let marker = me.profile_dir.join("DevToolsActivePort");
483 loop {
484 if let Ok(text) = fs::read_to_string(&marker) {
485 if let Some(p) = text
486 .lines()
487 .next()
488 .and_then(|l| l.trim().parse::<u16>().ok())
489 {
490 me.port = p;
491 break;
492 }
493 }
494 if let Ok(Some(status)) = me.child.try_wait() {
495 me.main_reaped = true;
496 return Err(format!("chrome exited early: {}", status));
497 }
498 if Instant::now() >= deadline {
499 return Err("chrome did not publish DevToolsActivePort in time".to_string());
500 }
501 std::thread::sleep(Duration::from_millis(100));
502 }
503 Ok(me)
504 }
505
506 /// Finds the websocket URL of the first page target.
507 fn page_ws_url(&self) -> Result<String, String> {
508 let deadline = Instant::now() + CHROME_BOOT_TIMEOUT;
509 loop {
510 if let Ok(body) = http_get("127.0.0.1", self.port, "/json", Duration::from_secs(5)) {
511 if let Ok(Value::Array(targets)) = serde_json::from_str::<Value>(&body) {
512 for t in &targets {
513 if t.get("type").and_then(Value::as_str) == Some("page") {
514 if let Some(ws) = t.get("webSocketDebuggerUrl").and_then(Value::as_str)
515 {
516 return Ok(ws.to_string());
517 }
518 }
519 }
520 }
521 }
522 if Instant::now() >= deadline {
523 return Err("chrome exposed no page target".to_string());
524 }
525 std::thread::sleep(Duration::from_millis(150));
526 }
527 }
528}
529
530/// Candidate PIDs whose environment holds the exact tag. Numeric PIDs are
531/// only discovery hints: pin identity and revalidate before signaling.
532#[cfg(test)]
533fn tagged_pids(tag: &str) -> Vec<u32> {
534 owned_pids(tag, None)
535}
536
537fn has_browser_identity(pid: u32, tag: &str, profile: Option<&Path>) -> bool {
538 let needle = format!("{}={}", TAG_VAR, tag);
539 let tagged = fs::read(format!("/proc/{}/environ", pid))
540 .map(|env| env.split(|b| *b == 0).any(|kv| kv == needle.as_bytes()))
541 .unwrap_or(false);
542 if tagged {
543 return true;
544 }
545 // Chrome scrubs the tag on some tasks, but retains the exact private
546 // profile argument. Never accept a substring or a prefix match.
547 profile.is_some_and(|path| {
548 let arg = format!("--user-data-dir={}", path.display());
549 fs::read(format!("/proc/{}/cmdline", pid))
550 .map(|cmd| {
551 if cmd.split(|b| *b == 0).any(|v| v == arg.as_bytes()) {
552 return true;
553 }
554 // Chrome replaces argv with a single space-joined process
555 // title and clears the original environment. Accept that
556 // representation only for a Chrome image, with its exact
557 // executable prefix and a complete profile flag token.
558 use std::os::unix::ffi::OsStrExt;
559 let Ok(exe) = fs::read_link(format!("/proc/{}/exe", pid)) else {
560 return false;
561 };
562 let chrome = matches!(
563 exe.file_name().and_then(|v| v.to_str()),
564 Some("chrome" | "chromium" | "chromium-browser")
565 );
566 let parts: Vec<_> = cmd.split(|b| *b == 0).filter(|v| !v.is_empty()).collect();
567 if !chrome || parts.len() != 1 {
568 return false;
569 }
570 let title = parts[0];
571 let prefix = [exe.as_os_str().as_bytes(), b" "].concat();
572 let needle = [b" ", arg.as_bytes()].concat();
573 title.starts_with(&prefix)
574 && title.windows(needle.len()).enumerate().any(|(i, w)| {
575 w == needle
576 && (i + needle.len() == title.len() || title[i + needle.len()] == b' ')
577 })
578 })
579 .unwrap_or(false)
580 })
581}
582
583fn owned_pids(tag: &str, profile: Option<&Path>) -> Vec<u32> {
584 let Ok(entries) = fs::read_dir("/proc") else {
585 return Vec::new();
586 };
587 entries
588 .filter_map(|e| e.ok()?.file_name().to_str()?.parse::<u32>().ok())
589 .filter(|pid| has_browser_identity(*pid, tag, profile))
590 .collect()
591}
592
593/// A Linux process identity, not a numeric PID that can be recycled.
594#[cfg(target_os = "linux")]
595struct TaggedProcess(std::os::fd::OwnedFd);
596
597#[cfg(target_os = "linux")]
598impl TaggedProcess {
599 fn pin(pid: u32) -> Option<Self> {
600 use std::os::fd::FromRawFd;
601 let raw = unsafe { libc::syscall(libc::SYS_pidfd_open, pid, 0u32) };
602 if raw < 0 {
603 return None;
604 }
605 Some(Self(unsafe {
606 std::os::fd::OwnedFd::from_raw_fd(raw as i32)
607 }))
608 }
609
610 fn available() -> bool {
611 Self::pin(std::process::id()).is_some_and(|p| p.signal(0))
612 }
613
614 #[cfg(test)]
615 fn open(pid: u32, tag: &str) -> Option<Self> {
616 Self::open_owned(pid, tag, None)
617 }
618
619 fn open_owned(pid: u32, tag: &str, profile: Option<&Path>) -> Option<Self> {
620 // Pin before checking the environment. If the task exits and the
621 // number is recycled, this descriptor still names only the old task.
622 let process = Self::pin(pid)?;
623 if !has_browser_identity(pid, tag, profile) {
624 return None;
625 }
626 Some(process)
627 }
628
629 fn kill(&self) -> bool {
630 self.signal(libc::SIGKILL)
631 }
632
633 fn signal(&self, signal: i32) -> bool {
634 use std::os::fd::AsRawFd;
635 unsafe {
636 libc::syscall(
637 libc::SYS_pidfd_send_signal,
638 self.0.as_raw_fd(),
639 signal,
640 std::ptr::null::<libc::siginfo_t>(),
641 0u32,
642 ) == 0
643 }
644 }
645}
646
647#[cfg(test)]
648fn kill_tagged_pid(pid: u32, tag: &str) -> bool {
649 #[cfg(target_os = "linux")]
650 {
651 TaggedProcess::open(pid, tag).is_some_and(|p| p.kill())
652 }
653 #[cfg(not(target_os = "linux"))]
654 {
655 let _ = (pid, tag);
656 false
657 }
658}
659
660impl ChromeProcess {
661 /// Linux teardown pins tasks and revalidates their exact tag or private
662 /// profile identity before fd signaling. Rewritten Chrome titles require
663 /// a Chrome image, its exact executable prefix and a complete profile flag.
664 /// Returns true only after the child is reaped and no owned task remains.
665 /// A timeout returns false without a final unbounded child wait.
666 fn reap(&mut self) -> bool {
667 let deadline = Instant::now() + REAP_TIMEOUT;
668 // Linux uses only pinned identities; numeric groups are never a
669 // signal target, even if another reaper already collected the child.
670 #[cfg(not(target_os = "linux"))]
671 if !self.main_reaped {
672 unsafe { libc::kill(-(self.child.id() as libc::pid_t), libc::SIGKILL) };
673 self.child.kill().ok();
674 }
675 loop {
676 let tagged = owned_pids(&self.tag, Some(&self.profile_dir));
677 for &pid in &tagged {
678 #[cfg(target_os = "linux")]
679 if let Some(task) =
680 TaggedProcess::open_owned(pid, &self.tag, Some(&self.profile_dir))
681 {
682 task.kill();
683 }
684 }
685 match self.child.try_wait() {
686 Ok(Some(_)) => self.main_reaped = true,
687 Err(e) if e.raw_os_error() == Some(libc::ECHILD) => self.main_reaped = true,
688 _ => {}
689 }
690 if self.main_reaped && tagged.is_empty() {
691 return true;
692 }
693 if Instant::now() >= deadline {
694 return false;
695 }
696 std::thread::sleep(Duration::from_millis(20));
697 }
698 }
699}
700
701impl Drop for ChromeProcess {
702 fn drop(&mut self) {
703 if self.reap() {
704 fs::remove_dir_all(&self.profile_dir).ok();
705 } else {
706 eprintln!(
707 "browser cleanup timed out; retained private profile {}",
708 self.profile_dir.display()
709 );
710 }
711 }
712}
713
714/// One CDP page session.
715pub struct CdpClient {
716 ws: WebSocket,
717 next_id: u64,
718}
719
720impl CdpClient {
721 fn connect(ws_url: &str) -> Result<Self, String> {
722 Ok(CdpClient {
723 ws: WebSocket::connect(ws_url)?,
724 next_id: 1,
725 })
726 }
727
728 /// Sends a CDP command and returns its `result` object.
729 pub fn send(&mut self, method: &str, params: Value) -> Result<Value, String> {
730 let id = self.next_id;
731 self.next_id += 1;
732 let msg = json!({"id": id, "method": method, "params": params});
733 self.ws.send_text(&msg.to_string())?;
734 let deadline = Instant::now() + CDP_REPLY_TIMEOUT;
735 loop {
736 if Instant::now() >= deadline {
737 return Err(format!("cdp: {} timed out", method));
738 }
739 let text = self.ws.recv_text()?;
740 let v: Value = serde_json::from_str(&text).map_err(|e| format!("cdp json: {}", e))?;
741 if v.get("id").and_then(Value::as_u64) != Some(id) {
742 continue; // an event or a stale reply
743 }
744 if let Some(err) = v.get("error") {
745 return Err(format!("cdp {}: {}", method, err));
746 }
747 return Ok(v.get("result").cloned().unwrap_or(Value::Null));
748 }
749 }
750
751 /// Evaluates JavaScript and returns the value (`returnByValue`).
752 pub fn eval(&mut self, expr: &str, await_promise: bool) -> Result<Value, String> {
753 let r = self.send(
754 "Runtime.evaluate",
755 json!({"expression": expr, "returnByValue": true, "awaitPromise": await_promise}),
756 )?;
757 if let Some(ex) = r.get("exceptionDetails") {
758 let text = ex
759 .get("exception")
760 .and_then(|e| e.get("description"))
761 .and_then(Value::as_str)
762 .or_else(|| ex.get("text").and_then(Value::as_str))
763 .unwrap_or("javascript exception");
764 return Err(format!("eval: {}", text));
765 }
766 Ok(r.get("result")
767 .and_then(|x| x.get("value"))
768 .cloned()
769 .unwrap_or(Value::Null))
770 }
771
772 /// Captures a PNG screenshot into `out_dir/filename`; returns the path.
773 pub fn screenshot(&mut self, out_dir: &Path, filename: &str) -> Result<PathBuf, String> {
774 let r = self.send("Page.captureScreenshot", json!({"format": "png"}))?;
775 let data = r
776 .get("data")
777 .and_then(Value::as_str)
778 .ok_or_else(|| "screenshot: no data".to_string())?;
779 let bytes = base64_decode(data)?;
780 fs::create_dir_all(out_dir).map_err(|e| format!("out dir: {}", e))?;
781 let path = out_dir.join(filename);
782 fs::write(&path, bytes).map_err(|e| format!("write {}: {}", path.display(), e))?;
783 Ok(path)
784 }
785
786 /// Waits until the page's `document.readyState` is complete (or the deadline passes).
787 /// Chrome's first document is `about:blank`, already complete, so unless that is the
788 /// target the page must also have left it.
789 fn wait_loaded(&mut self, url: &str, timeout: Duration) {
790 let blank_ok = url == "about:blank";
791 let deadline = Instant::now() + timeout;
792 while Instant::now() < deadline {
793 let state = self
794 .eval("[document.readyState, location.href]", false)
795 .unwrap_or(Value::Null);
796 if state[0] == "complete" && (blank_ok || state[1] != "about:blank") {
797 return;
798 }
799 std::thread::sleep(Duration::from_millis(200));
800 }
801 }
802}
803
804/// A live browser: Chrome process plus the page session. Dropping it kills Chrome.
805pub struct Mirror {
806 _chrome: ChromeProcess,
807 pub cdp: CdpClient,
808}
809
810impl Mirror {
811 /// Spawns Chrome on `url` and attaches to its page.
812 pub fn open(url: &str) -> Result<Self, String> {
813 let binary = find_chrome().ok_or_else(|| {
814 "no Chrome found (set AIEN_CHROME or install google-chrome/chromium)".to_string()
815 })?;
816 let chrome = ChromeProcess::spawn(&binary, url)?;
817 let ws_url = chrome.page_ws_url()?;
818 let mut cdp = CdpClient::connect(&ws_url)?;
819 cdp.send("Page.enable", json!({}))?;
820 cdp.send("Runtime.enable", json!({}))?;
821 cdp.wait_loaded(url, Duration::from_secs(15));
822 Ok(Mirror {
823 _chrome: chrome,
824 cdp,
825 })
826 }
827}
828
829impl Drop for Mirror {
830 fn drop(&mut self) {
831 self.cdp.ws.close();
832 }
833}
834
835// ---------------------------------------------------------------------------
836// Modes
837// ---------------------------------------------------------------------------
838
839fn write_report(out_dir: &Path, name: &str, report: &Value) -> Result<PathBuf, String> {
840 fs::create_dir_all(out_dir).map_err(|e| format!("out dir: {}", e))?;
841 let path = out_dir.join(name);
842 let text = serde_json::to_string_pretty(report).map_err(|e| e.to_string())?;
843 fs::write(&path, text).map_err(|e| format!("write {}: {}", path.display(), e))?;
844 Ok(path)
845}
846
847fn agent_messages_js() -> &'static str {
848 // Current Cockpit (spark-cockpit-rs/static): agent replies are rows with
849 // class "message-row agent-row". The old ".chat-msg.assistant" selector is
850 // kept as a fallback for older builds.
851 "Array.from(document.querySelectorAll('.message-row.agent-row, .chat-msg.assistant'))\
852 .map(el => el.textContent.trim())"
853}
854
855fn send_chat_js(prompt: &str) -> String {
856 format!(
857 "(() => {{ const inp = document.getElementById('chat-input'); if (!inp) return 'no-input';\
858 inp.value = {p}; inp.dispatchEvent(new Event('input', {{bubbles: true}}));\
859 const btn = document.getElementById('btn-send');\
860 if (btn) {{ btn.click(); return 'clicked'; }}\
861 if (typeof sendMessage === 'function') {{ sendMessage(); return 'called'; }}\
862 return 'no-send'; }})()",
863 p = Value::String(prompt.to_string())
864 )
865}
866
867/// Polls agent rows until a reply appears and stops growing (or `timeout` passes).
868fn wait_for_reply(cdp: &mut CdpClient, before: usize, timeout: Duration) -> (String, bool) {
869 let deadline = Instant::now() + timeout;
870 let mut last = String::new();
871 let mut stable = 0u32;
872 while Instant::now() < deadline {
873 std::thread::sleep(Duration::from_millis(500));
874 let msgs = cdp.eval(agent_messages_js(), false).unwrap_or(Value::Null);
875 let texts: Vec<String> = msgs
876 .as_array()
877 .map(|a| {
878 a.iter()
879 .filter_map(Value::as_str)
880 .map(str::to_string)
881 .collect()
882 })
883 .unwrap_or_default();
884 if texts.len() > before {
885 let current = texts.last().cloned().unwrap_or_default();
886 if !current.is_empty() && current == last {
887 stable += 1;
888 if stable >= 4 {
889 return (current, true);
890 }
891 } else {
892 stable = 0;
893 }
894 last = current;
895 }
896 }
897 (last, false)
898}
899
900/// Cockpit self-test: hydration, chat stream, navigation, three screenshots.
901pub fn run_test(url: &str, out_dir: &Path) -> Value {
902 let mut report = json!({
903 "mode": "test",
904 "timestamp": now_secs(),
905 "target_url": url,
906 "assertions": {},
907 "screenshots": [],
908 "status": "in_progress"
909 });
910 let push_shot = |report: &mut Value, p: PathBuf| {
911 if let Some(a) = report["screenshots"].as_array_mut() {
912 a.push(json!(p.display().to_string()));
913 }
914 };
915 let mut mirror = match Mirror::open(url) {
916 Ok(m) => m,
917 Err(e) => {
918 report["status"] = json!("FAILED");
919 report["error"] = json!(e);
920 if let Ok(p) = write_report(out_dir, "report.json", &report) {
921 report["report_path"] = json!(p.display().to_string());
922 }
923 return report;
924 }
925 };
926 let cdp = &mut mirror.cdp;
927
928 // 1. Hydration: title, chat input and navigation present.
929 let title = cdp
930 .eval("document.title", false)
931 .ok()
932 .and_then(|v| v.as_str().map(str::to_string))
933 .unwrap_or_default();
934 let has_input = cdp
935 .eval("!!document.getElementById('chat-input')", false)
936 .ok()
937 .and_then(|v| v.as_bool())
938 .unwrap_or(false);
939 let has_nav = cdp
940 .eval(
941 "!!(document.querySelector('[data-view]') || document.querySelector('[data-tab]'))",
942 false,
943 )
944 .ok()
945 .and_then(|v| v.as_bool())
946 .unwrap_or(false);
947 let hydrated = !title.is_empty() && has_input && has_nav;
948 report["assertions"]["initial_page_hydration"] = json!({
949 "pass": hydrated, "title": title, "chat_input": has_input, "navigation": has_nav
950 });
951 if let Ok(p) = cdp.screenshot(out_dir, "cockpit_init.png") {
952 push_shot(&mut report, p);
953 }
954
955 // 2. Chat stream: send a prompt and wait for a stable agent reply.
956 let before = cdp
957 .eval(&format!("{}.length", agent_messages_js()), false)
958 .ok()
959 .and_then(|v| v.as_u64())
960 .unwrap_or(0) as usize;
961 let sent = cdp
962 .eval(
963 &send_chat_js("Hello AIEN, please report current sovereign status."),
964 false,
965 )
966 .unwrap_or(Value::Null);
967 let (reply, stable) = if sent.as_str() == Some("clicked") || sent.as_str() == Some("called") {
968 wait_for_reply(cdp, before, Duration::from_secs(45))
969 } else {
970 (String::new(), false)
971 };
972 let chat_pass = !reply.is_empty() && stable;
973 report["assertions"]["chat_live_stream"] = json!({
974 "pass": chat_pass, "send": sent, "reply_chars": reply.chars().count(), "stable": stable
975 });
976 if let Ok(p) = cdp.screenshot(out_dir, "cockpit_chat_stream.png") {
977 push_shot(&mut report, p);
978 }
979
980 // 3. Navigation: click every nav control, confirm a visible view switches.
981 let nav = cdp
982 .eval(
983 "(() => { const btns = Array.from(document.querySelectorAll('[data-view], [data-tab]'));\
984 const seen = []; for (const b of btns) { b.click();\
985 const v = b.dataset.view || b.dataset.tab;\
986 const el = document.getElementById('view-' + v) || document.getElementById('pane-' + v)\
987 || document.getElementById(v);\
988 seen.push({view: v, present: !!el, visible: !!el && el.offsetParent !== null}); }\
989 return seen; })()",
990 false,
991 )
992 .unwrap_or(Value::Null);
993 let nav_items = nav.as_array().cloned().unwrap_or_default();
994 let nav_pass = !nav_items.is_empty()
995 && nav_items
996 .iter()
997 .all(|i| i.get("present").and_then(Value::as_bool).unwrap_or(false));
998 report["assertions"]["tab_navigation_and_actions"] = json!({"pass": nav_pass, "views": nav});
999 // Back to chat for the final frame.
1000 cdp.eval(
1001 "document.querySelector('[data-view=\"chat\"], [data-tab=\"chat\"]')?.click()",
1002 false,
1003 )
1004 .ok();
1005 if let Ok(p) = cdp.screenshot(out_dir, "cockpit_actions.png") {
1006 push_shot(&mut report, p);
1007 }
1008
1009 let all = hydrated && chat_pass && nav_pass;
1010 report["status"] = json!(if all { "PASSED" } else { "FAILED" });
1011 if let Ok(p) = write_report(out_dir, "report.json", &report) {
1012 report["report_path"] = json!(p.display().to_string());
1013 }
1014 report
1015}
1016
1017/// Mentor session: one prompt into the Cockpit chat, wait for the reply, screenshot.
1018pub fn run_mentor(url: &str, prompt: &str, out_dir: &Path) -> Value {
1019 let mut report = json!({
1020 "mode": "mentor",
1021 "timestamp": now_secs(),
1022 "target_url": url,
1023 "prompt": prompt,
1024 "response": "",
1025 "screenshot": "",
1026 "status": "in_progress"
1027 });
1028 let mut mirror = match Mirror::open(url) {
1029 Ok(m) => m,
1030 Err(e) => {
1031 report["status"] = json!("FAILED");
1032 report["error"] = json!(e);
1033 if let Ok(p) = write_report(out_dir, "mentor_response.json", &report) {
1034 report["report_path"] = json!(p.display().to_string());
1035 }
1036 return report;
1037 }
1038 };
1039 let cdp = &mut mirror.cdp;
1040 cdp.eval(
1041 "document.querySelector('[data-view=\"chat\"], [data-tab=\"chat\"]')?.click()",
1042 false,
1043 )
1044 .ok();
1045 let before = cdp
1046 .eval(&format!("{}.length", agent_messages_js()), false)
1047 .ok()
1048 .and_then(|v| v.as_u64())
1049 .unwrap_or(0) as usize;
1050 let sent = cdp
1051 .eval(&send_chat_js(prompt), false)
1052 .unwrap_or(Value::Null);
1053 report["send"] = sent;
1054 let (reply, stable) = wait_for_reply(cdp, before, Duration::from_secs(120));
1055 report["response"] = json!(reply);
1056 report["stable"] = json!(stable);
1057 if let Ok(p) = cdp.screenshot(out_dir, "cockpit_mentor_response.png") {
1058 report["screenshot"] = json!(p.display().to_string());
1059 }
1060 report["status"] = json!(if reply.chars().count() > 50 {
1061 "COMPLETED"
1062 } else {
1063 "FAILED"
1064 });
1065 if let Ok(p) = write_report(out_dir, "mentor_response.json", &report) {
1066 report["report_path"] = json!(p.display().to_string());
1067 }
1068 report
1069}
1070
1071/// Opens `url`, records the title and saves `filename` (PNG) under `out_dir`.
1072pub fn run_screenshot(url: &str, out_dir: &Path, filename: &str) -> Value {
1073 let mut mirror = match Mirror::open(url) {
1074 Ok(m) => m,
1075 Err(e) => return json!({"mode": "screenshot", "status": "error", "error": e}),
1076 };
1077 let title = mirror
1078 .cdp
1079 .eval("document.title", false)
1080 .unwrap_or(Value::Null);
1081 match mirror.cdp.screenshot(out_dir, filename) {
1082 Ok(p) => json!({
1083 "mode": "screenshot", "status": "ok", "target_url": url,
1084 "title": title, "screenshot": p.display().to_string()
1085 }),
1086 Err(e) => json!({"mode": "screenshot", "status": "error", "error": e, "title": title}),
1087 }
1088}
1089
1090/// Opens `url` and evaluates `expr`, returning its value.
1091pub fn run_eval(url: &str, expr: &str) -> Value {
1092 let mut mirror = match Mirror::open(url) {
1093 Ok(m) => m,
1094 Err(e) => return json!({"mode": "eval", "status": "error", "error": e}),
1095 };
1096 match mirror.cdp.eval(expr, true) {
1097 Ok(v) => json!({"mode": "eval", "status": "ok", "target_url": url, "value": v}),
1098 Err(e) => json!({"mode": "eval", "status": "error", "error": e}),
1099 }
1100}
1101
1102/// Entry point shared by the `browser` tool and the binary.
1103///
1104/// `action` is one of `test`, `mentor`, `screenshot`, `eval`. `arg` is the
1105/// mentor prompt or the eval expression. Unknown actions report an error.
1106pub fn dispatch(action: &str, arg: Option<&str>, url: &str, out_dir: &Path) -> Value {
1107 match action {
1108 "test" => run_test(url, out_dir),
1109 "mentor" => run_mentor(
1110 url,
1111 arg.unwrap_or("AIEN, report self-improvement status."),
1112 out_dir,
1113 ),
1114 "screenshot" => run_screenshot(url, out_dir, arg.unwrap_or("screenshot.png")),
1115 "eval" => run_eval(url, arg.unwrap_or("document.title")),
1116 other => json!({
1117 "status": "error",
1118 "error": format!("unknown browser action '{}' (use test, mentor, screenshot or eval)", other)
1119 }),
1120 }
1121}
1122
1123#[cfg(test)]
1124mod tests {
1125 use super::*;
1126
1127 #[test]
1128 fn base64_roundtrip() {
1129 for s in ["", "f", "fo", "foo", "foob", "fooba", "foobar"] {
1130 let enc = base64_encode(s.as_bytes());
1131 assert_eq!(base64_decode(&enc).unwrap(), s.as_bytes());
1132 }
1133 assert_eq!(base64_encode(b"foobar"), "Zm9vYmFy");
1134 assert_eq!(base64_decode("Zm9v\nYmFy").unwrap(), b"foobar");
1135 assert!(base64_decode("Zm9v*").is_err());
1136 }
1137
1138 #[test]
1139 fn unknown_action_is_an_error() {
1140 let v = dispatch("fly", None, DEFAULT_URL, Path::new("/nonexistent"));
1141 assert_eq!(v["status"], "error");
1142 assert!(v["error"].as_str().unwrap().contains("fly"));
1143 }
1144
1145 /// Spawns a real headless Chrome on a local stub page, screenshots it and
1146 /// evaluates the title. Skipped (with a note) when no Chrome is installed,
1147 /// so CI without a browser still passes.
1148 #[test]
1149 fn stub_page_screenshot_and_eval() {
1150 if find_chrome().is_none() {
1151 eprintln!("skipping stub_page_screenshot_and_eval: no Chrome binary found");
1152 return;
1153 }
1154 let dir = tempfile::tempdir().expect("tempdir");
1155 let page = dir.path().join("stub.html");
1156 fs::write(
1157 &page,
1158 "<!doctype html><html><head><title>AIEN Stub</title></head>\
1159 <body><h1 id=\"h\">mirror</h1><textarea id=\"chat-input\"></textarea></body></html>",
1160 )
1161 .unwrap();
1162 let url = format!("file://{}", page.display());
1163 let out = dir.path().join("shots");
1164
1165 let shot = run_screenshot(&url, &out, "stub.png");
1166 assert_eq!(shot["status"], "ok", "{}", shot);
1167 assert_eq!(shot["title"], "AIEN Stub");
1168 let bytes = fs::read(out.join("stub.png")).unwrap();
1169 assert!(bytes.len() > 100, "png too small: {} bytes", bytes.len());
1170 assert_eq!(&bytes[..8], b"\x89PNG\r\n\x1a\n");
1171
1172 let ev = run_eval(
1173 &url,
1174 "document.getElementById('h').textContent + ':' + 2 * 21",
1175 );
1176 assert_eq!(ev["status"], "ok", "{}", ev);
1177 assert_eq!(ev["value"], "mirror:42");
1178 }
1179
1180 /// `(state, ppid, starttime)` from `/proc/<pid>/stat`, or `None` once the pid is gone.
1181 fn proc_stat(pid: u32) -> Option<(char, u32, u64)> {
1182 let stat = fs::read_to_string(format!("/proc/{}/stat", pid)).ok()?;
1183 // Fields after "(comm)": state ppid pgrp session tty tpgid flags ... starttime is the 20th.
1184 let rest: Vec<&str> = stat.rsplit_once(')')?.1.split_whitespace().collect();
1185 Some((
1186 rest.first()?.chars().next()?,
1187 rest.get(1)?.parse().ok()?,
1188 rest.get(19)?.parse().ok()?,
1189 ))
1190 }
1191
1192 /// Every process the browser started, as `(pid, starttime)`: the descendants of `root`
1193 /// plus the crash reporters they name with `--crashpad-handler-pid`, which detach into
1194 /// their own session and so are nobody's child.
1195 fn chrome_family(root: u32) -> Vec<(u32, u64)> {
1196 let all: Vec<u32> = fs::read_dir("/proc")
1197 .unwrap()
1198 .filter_map(|e| e.ok()?.file_name().to_str()?.parse().ok())
1199 .collect();
1200 let mut family: Vec<u32> = vec![root];
1201 let mut grew = true;
1202 while grew {
1203 grew = false;
1204 for &p in &all {
1205 if !family.contains(&p)
1206 && proc_stat(p).is_some_and(|(_, ppid, _)| family.contains(&ppid))
1207 {
1208 family.push(p);
1209 grew = true;
1210 }
1211 }
1212 }
1213 let mut named: Vec<u32> = Vec::new();
1214 for &p in &family {
1215 let cmd = fs::read(format!("/proc/{}/cmdline", p)).unwrap_or_default();
1216 for arg in cmd.split(|b| *b == 0) {
1217 if let Some(n) = arg.strip_prefix(b"--crashpad-handler-pid=") {
1218 if let Some(n) = std::str::from_utf8(n).ok().and_then(|s| s.parse().ok()) {
1219 named.push(n);
1220 }
1221 }
1222 }
1223 }
1224 family.extend(named);
1225 family.sort_unstable();
1226 family.dedup();
1227 family
1228 .into_iter()
1229 .filter_map(|p| proc_stat(p).map(|(_, _, start)| (p, start)))
1230 .collect()
1231 }
1232
1233 /// True while `pid` is the same process (same start time) and not a zombie.
1234 fn still_running(pid: u32, start: u64) -> bool {
1235 proc_stat(pid).is_some_and(|(state, _, s)| s == start && state != 'Z' && state != 'X')
1236 }
1237
1238 /// Dropping the Chrome handle must leave none of its processes behind: not the GPU
1239 /// process, not the renderers, not the crash reporters that detach from the group.
1240 #[test]
1241 fn dropping_chrome_reaps_every_helper() {
1242 let Some(binary) = find_chrome() else {
1243 eprintln!("skipping dropping_chrome_reaps_every_helper: no Chrome binary found");
1244 return;
1245 };
1246 let dir = tempfile::tempdir().expect("tempdir");
1247 let page = dir.path().join("stub.html");
1248 fs::write(&page, "<!doctype html><title>reap</title><h1>reap</h1>").unwrap();
1249 let chrome = ChromeProcess::spawn(&binary, &format!("file://{}", page.display()))
1250 .expect("spawn chrome");
1251 chrome.page_ws_url().expect("page target");
1252 // The tag reaches the processes that leave the group (crash reporters).
1253 let tag = chrome.tag.clone();
1254 let tagged = tagged_pids(&tag);
1255 assert!(!tagged.is_empty(), "no process carries the tag");
1256 let mut family = chrome_family(chrome.child.id());
1257 family.extend(
1258 tagged
1259 .iter()
1260 .filter_map(|&p| proc_stat(p).map(|(_, _, s)| (p, s))),
1261 );
1262 family.sort_unstable();
1263 family.dedup();
1264 // Short-lived helpers may exit on their own between listing and checking.
1265 let family: Vec<(u32, u64)> = family
1266 .into_iter()
1267 .filter(|&(p, s)| still_running(p, s))
1268 .collect();
1269
1270 // Negative control: the detector sees the live helpers, so "none left" below is a
1271 // real observation and not a detector that cannot see anything.
1272 assert!(
1273 family.len() >= 3,
1274 "detector found too few chrome processes: {:?}",
1275 family
1276 );
1277
1278 drop(chrome);
1279 // Orphaned zombies are reaped by init; give that a moment, never the processes.
1280 let deadline = Instant::now() + Duration::from_secs(2);
1281 let mut left: Vec<(u32, u64)> = family.clone();
1282 while !left.is_empty() && Instant::now() < deadline {
1283 std::thread::sleep(Duration::from_millis(100));
1284 left.retain(|&(p, s)| still_running(p, s));
1285 }
1286 let names: Vec<String> = left
1287 .iter()
1288 .map(|(p, _)| {
1289 let comm = fs::read_to_string(format!("/proc/{}/cmdline", p)).unwrap_or_default();
1290 format!(
1291 "{} {}",
1292 p,
1293 comm.replace('\0', " ").chars().take(80).collect::<String>()
1294 )
1295 })
1296 .collect();
1297 assert!(
1298 left.is_empty(),
1299 "chrome processes left running: {:#?}",
1300 names
1301 );
1302 assert_eq!(
1303 tagged_pids(&tag),
1304 Vec::<u32>::new(),
1305 "tagged processes left"
1306 );
1307 }
1308
1309 /// The tag sweep finds exactly the processes spawned with its tag. Negative control:
1310 /// a process with a different tag, and one with none, are never matched (so drop can
1311 /// never kill a stranger).
1312 #[test]
1313 fn tag_sweep_matches_only_its_own_tag() {
1314 let tag = format!("sweep-test-{}-{}", std::process::id(), now_nanos());
1315 let spawn = |value: Option<&str>| {
1316 let mut c = Command::new("sleep");
1317 c.arg("30").stdin(Stdio::null()).stdout(Stdio::null());
1318 if let Some(v) = value {
1319 c.env(TAG_VAR, v);
1320 }
1321 c.spawn().expect("spawn sleep")
1322 };
1323 let mut mine = spawn(Some(&tag));
1324 let mut prefix = spawn(Some(&tag[..tag.len() - 1]));
1325 let mut other = spawn(Some("sweep-test-someone-else"));
1326 let mut none = spawn(None);
1327 // A freshly forked child may still hold the parent's environment until exec.
1328 let deadline = Instant::now() + Duration::from_secs(5);
1329 let mut found = tagged_pids(&tag);
1330 while found.is_empty() && Instant::now() < deadline {
1331 std::thread::sleep(Duration::from_millis(20));
1332 found = tagged_pids(&tag);
1333 }
1334 let ids = [mine.id(), prefix.id(), other.id(), none.id()];
1335 for c in [&mut mine, &mut prefix, &mut other, &mut none] {
1336 c.kill().ok();
1337 c.wait().ok();
1338 }
1339 assert_eq!(found, vec![ids[0]], "sweep must match only {:?}", ids);
1340 assert!(tagged_pids(&tag).is_empty());
1341 }
1342
1343 #[cfg(target_os = "linux")]
1344 #[test]
1345 fn stale_candidates_and_exited_pidfds_cannot_signal_a_stranger() {
1346 let tag = format!("pidfd-test-{}-{}", std::process::id(), now_nanos());
1347 let spawn = |value: &str| {
1348 Command::new("sleep")
1349 .arg("30")
1350 .env(TAG_VAR, value)
1351 .spawn()
1352 .expect("spawn owned fixture")
1353 };
1354 let mut mine = spawn(&tag);
1355 let mut prefix = spawn(&tag[..tag.len() - 1]);
1356 let mut other = spawn("pidfd-test-other");
1357 let deadline = Instant::now() + Duration::from_secs(5);
1358 let pinned = loop {
1359 if let Some(p) = TaggedProcess::open(mine.id(), &tag) {
1360 break Some(p);
1361 }
1362 if Instant::now() >= deadline {
1363 break None;
1364 }
1365 std::thread::sleep(Duration::from_millis(10));
1366 };
1367 // Simulate a stale discovery list that now names a foreign task:
1368 // validation must happen after opening the identity handle.
1369 let refused_prefix = !kill_tagged_pid(prefix.id(), &tag);
1370 let refused_other = !kill_tagged_pid(other.id(), &tag);
1371 let owned_signaled = pinned.as_ref().is_some_and(|p| p.kill());
1372 if !owned_signaled {
1373 mine.kill().ok();
1374 }
1375 mine.wait().ok();
1376 let dead_handle_refused = pinned.as_ref().is_some_and(|p| !p.kill());
1377 let neighbors_alive =
1378 matches!(prefix.try_wait(), Ok(None)) && matches!(other.try_wait(), Ok(None));
1379 for c in [&mut prefix, &mut other] {
1380 c.kill().ok();
1381 c.wait().ok();
1382 }
1383 assert!(
1384 pinned.is_some(),
1385 "kernel pidfd support and exact-tag pin required"
1386 );
1387 assert!(
1388 owned_signaled
1389 && refused_prefix
1390 && refused_other
1391 && dead_handle_refused
1392 && neighbors_alive
1393 );
1394 }
1395
1396 #[cfg(target_os = "linux")]
1397 #[test]
1398 fn undetected_child_does_not_extend_drop_past_cleanup_deadline() {
1399 let dir = tempfile::tempdir().unwrap();
1400 let profile = dir.path().join("private-profile");
1401 fs::create_dir(&profile).unwrap();
1402 let child = Command::new("sleep")
1403 .arg("8")
1404 .env_remove(TAG_VAR)
1405 .spawn()
1406 .unwrap();
1407 let pid = child.id();
1408 // Keep an owner-controlled pinned handle even when the production
1409 // detector intentionally cannot recognize this synthetic child.
1410 let control = TaggedProcess::pin(pid).unwrap();
1411 let chrome = ChromeProcess {
1412 child,
1413 profile_dir: profile.clone(),
1414 port: 0,
1415 tag: format!("undetected-{}-{}", std::process::id(), now_nanos()),
1416 main_reaped: false,
1417 };
1418 let start = Instant::now();
1419 drop(chrome);
1420 let elapsed = start.elapsed();
1421 let retained = profile.exists();
1422 control.kill();
1423 unsafe {
1424 libc::waitpid(pid as libc::pid_t, std::ptr::null_mut(), 0);
1425 }
1426 assert!(
1427 elapsed < REAP_TIMEOUT + Duration::from_secs(2),
1428 "drop exceeded deadline: {elapsed:?}"
1429 );
1430 assert!(
1431 retained,
1432 "uncertain teardown must retain its private profile"
1433 );
1434 }
1435
1436 #[cfg(target_os = "linux")]
1437 #[test]
1438 #[ignore = "explicit isolated inherited-SIGCHLD qualification"]
1439 fn cleanup_with_inherited_ignored_sigchld() {
1440 // Run via exec under SIGCHLD=SIG_IGN, not through chrome_binary():
1441 // its --version probe cannot wait for auto-reaped children.
1442 let mut action = std::mem::MaybeUninit::<libc::sigaction>::uninit();
1443 assert_eq!(
1444 unsafe { libc::sigaction(libc::SIGCHLD, std::ptr::null(), action.as_mut_ptr()) },
1445 0
1446 );
1447 assert_eq!(unsafe { action.assume_init() }.sa_sigaction, libc::SIG_IGN);
1448 let binary = std::env::var("AIEN_CHROME").expect("explicit Chrome path required");
1449 let chrome = ChromeProcess::spawn(&binary, "data:text/html,owned-sigchld-fixture").unwrap();
1450 let tag = chrome.tag.clone();
1451 let profile = chrome.profile_dir.clone();
1452 drop(chrome);
1453 assert!(owned_pids(&tag, Some(&profile)).is_empty());
1454 assert!(!profile.exists());
1455 }
1456
1457 #[cfg(target_os = "linux")]
1458 #[test]
1459 fn exact_private_profile_identifies_a_task_without_its_tag() {
1460 let dir = tempfile::tempdir().unwrap();
1461 let profile = dir.path().join("private-profile");
1462 let tag = format!("profile-fixture-{}-{}", std::process::id(), now_nanos());
1463 let spawn = |path: &Path| {
1464 Command::new("sh")
1465 .args(["-c", "kill -STOP $$", "profile-fixture"])
1466 .arg(format!("--user-data-dir={}", path.display()))
1467 .env_remove(TAG_VAR)
1468 .spawn()
1469 .unwrap()
1470 };
1471 let mut mine = spawn(&profile);
1472 let mut neighbor = spawn(&profile.with_extension("other"));
1473 let deadline = Instant::now() + Duration::from_secs(5);
1474 let pinned = loop {
1475 if let Some(p) = TaggedProcess::open_owned(mine.id(), &tag, Some(&profile)) {
1476 break Some(p);
1477 }
1478 if Instant::now() >= deadline {
1479 break None;
1480 }
1481 std::thread::sleep(Duration::from_millis(10));
1482 };
1483 let rejected = TaggedProcess::open_owned(neighbor.id(), &tag, Some(&profile)).is_none();
1484 let signaled = pinned.as_ref().is_some_and(|p| p.kill());
1485 if !signaled {
1486 mine.kill().ok();
1487 }
1488 mine.wait().ok();
1489 let neighbor_alive = matches!(neighbor.try_wait(), Ok(None));
1490 neighbor.kill().ok();
1491 neighbor.wait().ok();
1492 assert!(pinned.is_some() && signaled && rejected && neighbor_alive);
1493 }
1494}