use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream};
use std::path::Path;
use std::process::{Command, Output};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::thread::JoinHandle;
use std::time::{Duration, Instant};
use serde_json::Value;
use sha2::{Digest, Sha256};
use tempfile::{TempDir, tempdir};
const DEFAULT_CHROME: &str = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";
/// The Chrome this contract drives. Branded Google Chrome 153 quits headless
/// mode on its own about thirty seconds after launch, which ends the session
/// mid-contract; a Chrome for Testing build does not. Set APOC_TEST_CHROME to
/// its executable to run the whole contract.
fn chrome() -> Option<String> {
match std::env::var("APOC_TEST_CHROME") {
// An explicitly named Chrome that is missing is a broken setup, not a
// reason to skip: skipping would read as a pass.
Ok(path) => {
assert!(
Path::new(&path).is_file(),
"APOC_TEST_CHROME does not exist: {path}"
);
Some(path)
}
Err(_) => Path::new(DEFAULT_CHROME)
.is_file()
.then(|| DEFAULT_CHROME.to_string()),
}
}
struct HttpFixture {
address: std::net::SocketAddr,
stop: Arc<AtomicBool>,
thread: Option<JoinHandle<()>>,
}
impl HttpFixture {
fn start() -> Self {
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
listener.set_nonblocking(true).unwrap();
let address = listener.local_addr().unwrap();
let stop = Arc::new(AtomicBool::new(false));
let broken = Arc::new(AtomicBool::new(false));
let worker_stop = Arc::clone(&stop);
let worker_broken = Arc::clone(&broken);
let thread = std::thread::spawn(move || {
while !worker_stop.load(Ordering::Relaxed) {
match listener.accept() {
Ok((stream, _)) => {
let broken = Arc::clone(&worker_broken);
std::thread::spawn(move || serve(stream, broken));
}
Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
std::thread::sleep(Duration::from_millis(10));
}
Err(error) => panic!("browser fixture accept failed: {error}"),
}
}
});
Self {
address,
stop,
thread: Some(thread),
}
}
fn url(&self, path: &str) -> String {
format!("http://{}{}", self.address, path)
}
}
impl Drop for HttpFixture {
fn drop(&mut self) {
self.stop.store(true, Ordering::Relaxed);
let _ = TcpStream::connect(self.address);
if let Some(thread) = self.thread.take() {
thread.join().unwrap();
}
}
}
fn serve(mut stream: TcpStream, broken: Arc<AtomicBool>) {
stream.set_nonblocking(false).unwrap();
stream
.set_read_timeout(Some(Duration::from_millis(100)))
.unwrap();
let deadline = Instant::now() + Duration::from_secs(5);
let mut request = Vec::new();
let mut buffer = [0_u8; 4096];
loop {
match stream.read(&mut buffer) {
Ok(0) => return,
Ok(size) => {
request.extend_from_slice(&buffer[..size]);
if request.windows(4).any(|window| window == b"\r\n\r\n") {
break;
}
}
Err(error)
if matches!(
error.kind(),
std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
) && Instant::now() < deadline => {}
Err(_) => return,
}
if Instant::now() >= deadline {
return;
}
}
let request = String::from_utf8_lossy(&request);
let path = request
.lines()
.next()
.and_then(|line| line.split_whitespace().nth(1))
.unwrap_or("/")
.split('?')
.next()
.unwrap_or("/");
let (status, media_type, headers, body) = match path {
"/break" => {
broken.store(true, Ordering::Relaxed);
("200 OK", "text/plain", Vec::new(), "broken")
}
"/" if broken.load(Ordering::Relaxed) => (
"200 OK",
"text/html; charset=utf-8",
Vec::new(),
"<!doctype html><title>Broken</title><body><div id=\"broken\">action removed</div></body>",
),
"/" => (
"200 OK",
"text/html; charset=utf-8",
vec![("Set-Cookie", "fixture-cookie=present; Path=/")],
r#"<!doctype html>
<html>
<head>
<style>
#box { color: rgb(18, 52, 86); width: 120px; height: 40px; }
#box:hover { color: rgb(200, 10, 20); }
</style>
</head>
<body>
<button id="action" onclick="this.dataset.clicked='yes'; fetch('/api/data').then(r => r.json()).then(v => this.dataset.answer=v.answer)">Run</button>
<input id="name" aria-label="Name">
<select id="choice" onchange="this.dataset.selected=this.value">
<option value="one">One</option>
<option value="two">Two</option>
</select>
<div id="box" class="fixture">Browser fixture</div>
<script>
localStorage.setItem('local-key', 'local-value');
sessionStorage.setItem('session-key', 'session-value');
function covered(value) { return value * 2; }
window.coveredValue = covered(21);
</script>
<script src="/fixture.js"></script>
</body>
</html>"#,
),
"/fixture.js" => (
"200 OK",
"application/javascript; charset=utf-8",
Vec::new(),
"window.browserTick = 0;\nfunction browserPulse() {\n window.browserTick += 1;\n return window.browserTick;\n}\nsetInterval(browserPulse, 50);\n",
),
"/api/data" => (
"200 OK",
"application/json",
Vec::new(),
r#"{"answer":"network-ok"}"#,
),
"/mocked" => (
"200 OK",
"text/plain; charset=utf-8",
Vec::new(),
"real response",
),
"/next" => (
"200 OK",
"text/html; charset=utf-8",
Vec::new(),
"<!doctype html><title>Next</title><body>next page</body>",
),
_ => ("404 Not Found", "text/plain", Vec::new(), "not found"),
};
let mut response = format!(
"HTTP/1.1 {status}\r\nContent-Type: {media_type}\r\nContent-Length: {}\r\nConnection: close\r\n",
body.len()
);
for (name, value) in headers {
response.push_str(&format!("{name}: {value}\r\n"));
}
response.push_str("\r\n");
response.push_str(body);
let _ = stream.write_all(response.as_bytes());
}
struct Fixture {
binary: String,
home: TempDir,
runtime: TempDir,
chrome_data: TempDir,
execution_ids: Mutex<Vec<String>>,
}
impl Fixture {
fn new() -> Self {
Self {
binary: env!("CARGO_BIN_EXE_apoc").to_string(),
home: tempdir().unwrap(),
runtime: tempdir().unwrap(),
chrome_data: tempdir().unwrap(),
execution_ids: Mutex::new(Vec::new()),
}
}
fn run(&self, args: &[&str]) -> Output {
let mut arguments = args.to_vec();
let options_end = arguments
.iter()
.position(|argument| *argument == "--")
.unwrap_or(arguments.len());
arguments.splice(
options_end..options_end,
[
"--purpose",
"Running the durable browser debugger contract fixture.",
],
);
Command::new(&self.binary)
.args(arguments)
.env("APOC_HOME", self.home.path())
.env("APOC_RUNTIME_DIR", self.runtime.path())
.env("XDG_DATA_HOME", self.home.path().join("xdg"))
.env("APOC_MCP_ROOT", self.home.path())
.output()
.unwrap()
}
fn json(&self, args: &[&str]) -> Value {
let output = self.run(args);
let daemon_log = std::fs::read_to_string(self.home.path().join("daemon.log"))
.unwrap_or_else(|_| "<no daemon log>".to_string());
if !output.status.success() {
for id in self.execution_ids.lock().unwrap().iter() {
for command in [
vec![
"execution",
"get",
id.as_str(),
"--verbosity",
"info",
"--format",
"json",
],
vec![
"execution",
"logs",
id.as_str(),
"--tail-bytes",
"8000",
"--format",
"json",
],
] {
let diagnostic = self.run(&command);
eprintln!(
"browser execution diagnostic: {}\n{}",
String::from_utf8_lossy(&diagnostic.stdout),
String::from_utf8_lossy(&diagnostic.stderr),
);
}
}
}
assert!(
output.status.success(),
"command failed: {args:?}\nstdout: {}\nstderr: {}\ndaemon log:\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr),
daemon_log
);
serde_json::from_slice(&output.stdout).unwrap()
}
#[track_caller]
fn wait_json(&self, timeout: Duration, mut call: impl FnMut() -> Option<Value>) -> Value {
let deadline = Instant::now() + timeout;
while Instant::now() < deadline {
if let Some(value) = call() {
return value;
}
std::thread::sleep(Duration::from_millis(25));
}
let daemon_log = std::fs::read_to_string(self.home.path().join("daemon.log"))
.unwrap_or_else(|_| "<no daemon log>".to_string());
panic!("timed out waiting for browser debugger state\ndaemon log:\n{daemon_log}")
}
fn track(&self, id: String) {
self.execution_ids.lock().unwrap().push(id);
}
fn forget(&self, id: &str) {
self.execution_ids
.lock()
.unwrap()
.retain(|candidate| candidate != id);
}
}
impl Drop for Fixture {
fn drop(&mut self) {
for id in self.execution_ids.lock().unwrap().drain(..) {
let _ = self.run(&[
"execution",
"cancel",
&id,
"--idempotency-key",
&format!("debugger/browser-drop-cancel/{id}"),
"--timeout-ms",
"5000",
"--format",
"json",
]);
}
let _ = self.run(&[
"daemon",
"stop",
"--idempotency-key",
"browser-debugger-fixture-stop",
"--format",
"json",
]);
}
}
#[test]
fn browser_debugger_controls_live_chrome_and_recovers_durable_state() {
let Some(chrome) = chrome() else {
eprintln!("skipping live browser debugger contract because Chrome is unavailable");
return;
};
let server = HttpFixture::start();
let apoc = Fixture::new();
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
let port = listener.local_addr().unwrap().port();
drop(listener);
let port_text = port.to_string();
let data_dir = apoc.chrome_data.path().to_string_lossy().to_string();
let remote_port = format!("--remote-debugging-port={port}");
let user_data = format!("--user-data-dir={data_dir}");
let started = apoc.json(&[
"execution",
"start",
&chrome,
"--idempotency-key",
"debugger/browser-chrome-execution-v1",
"--verbosity",
"trace",
"--format",
"json",
"--",
"--headless=new",
"--disable-gpu",
"--no-first-run",
"--no-default-browser-check",
"--remote-debugging-address=127.0.0.1",
&remote_port,
&user_data,
"about:blank",
]);
let execution_id = started["execution"]["id"].as_str().unwrap().to_string();
apoc.track(execution_id.clone());
let targets = apoc.wait_json(Duration::from_secs(20), || {
let output = apoc.run(&["debugger", "targets", &port_text, "--format", "json"]);
if !output.status.success() {
return None;
}
let targets: Value = serde_json::from_slice(&output.stdout).ok()?;
targets
.as_array()?
.iter()
.any(|target| target["kind"] == "page")
.then_some(targets)
});
let target_id = targets
.as_array()
.unwrap()
.iter()
.find(|target| target["kind"] == "page")
.unwrap()["id"]
.as_str()
.unwrap()
.to_string();
let opened = apoc.json(&[
"debugger",
"open",
&port_text,
"--id",
"browser-main",
"--target-id",
&target_id,
"--execution-id",
&execution_id,
"--idempotency-key",
"debugger/browser-open-v1",
"--format",
"json",
]);
assert_eq!(opened["adapter"], "browser_cdp");
assert_eq!(opened["target_id"], target_id);
assert_eq!(opened["execution_id"], execution_id);
let root_url = server.url("/");
let navigation = apoc.json(&[
"debugger",
"browser",
"navigate",
"browser-main",
"url",
"--target",
&root_url,
"--idempotency-key",
"debugger/browser-navigate-root-v1",
"--format",
"json",
]);
assert_eq!(navigation["ready_state"], "complete");
assert_eq!(navigation["url"], root_url);
let node = apoc.json(&[
"debugger",
"browser",
"dom",
"browser-main",
"#box",
"--format",
"json",
]);
assert_eq!(node[0]["tag"], "div");
assert_eq!(node[0]["text"], "Browser fixture");
let styles = apoc.json(&[
"debugger",
"browser",
"styles",
"browser-main",
"#box",
"--format",
"json",
]);
assert!(
styles
.as_array()
.unwrap()
.iter()
.any(|style| style["name"] == "color" && style["value"] == "rgb(18, 52, 86)")
);
let cookies = apoc.json(&[
"debugger",
"browser",
"cookies",
"browser-main",
"--format",
"json",
]);
assert!(
cookies
.as_array()
.unwrap()
.iter()
.any(|cookie| cookie["name"] == "fixture-cookie" && cookie["value"] == "present")
);
for (kind, key, value) in [
("local", "local-key", "local-value"),
("session", "session-key", "session-value"),
] {
let storage = apoc.json(&[
"debugger",
"browser",
"storage",
"browser-main",
kind,
"--format",
"json",
]);
assert!(
storage
.as_array()
.unwrap()
.iter()
.any(|entry| entry["key"] == key && entry["value"] == value)
);
}
let metrics = apoc.json(&[
"debugger",
"browser",
"performance",
"browser-main",
"--format",
"json",
]);
assert!(!metrics.as_array().unwrap().is_empty());
let browser_tap = apoc.json(&[
"debugger",
"tap",
"add",
"browser-main",
"fixture.js",
"3",
"window.browserTick",
"--idempotency-key",
"debugger/browser-tap-v1",
"--format",
"json",
]);
let browser_tap_id = browser_tap["id"].as_str().unwrap().to_string();
assert_eq!(browser_tap["resolved"], true, "{browser_tap:#}");
let browser_tap_hits = apoc.wait_json(Duration::from_secs(10), || {
let hits = apoc.json(&[
"debugger",
"tap",
"hits",
"browser-main",
&browser_tap_id,
"--limit",
"20",
"--format",
"json",
]);
(!hits.as_array().unwrap().is_empty()).then_some(hits)
});
assert!(browser_tap_hits[0]["value"].as_str().is_some());
let running_after_tap = apoc.json(&["debugger", "status", "browser-main", "--format", "json"]);
assert_eq!(running_after_tap["state"]["phase"], "running");
let removed_browser_tap = apoc.json(&[
"debugger",
"tap",
"remove",
"browser-main",
&browser_tap_id,
"--idempotency-key",
"debugger/browser-tap-remove-v1",
"--format",
"json",
]);
assert_eq!(removed_browser_tap["enabled"], false);
let recording_start = apoc.json(&[
"debugger",
"recording",
"start",
"browser-main",
"--max-frames",
"4",
"--max-bytes",
"10000000",
"--idempotency-key",
"debugger/recording-start-v1",
"--format",
"json",
]);
let recording_id = recording_start["recording"]["id"]
.as_str()
.unwrap()
.to_string();
let initial_capture_id = recording_start["initial_capture"]["id"]
.as_str()
.unwrap()
.to_string();
assert_eq!(recording_start["recording"]["phase"], "running");
let edit_correlation = apoc.json(&[
"debugger",
"recording",
"correlate",
"browser-main",
"edit",
"browser fixture change",
"--path",
"tests/browser_debugger_contract.rs",
"--idempotency-key",
"debugger/recording-correlate-edit-v1",
"--format",
"json",
]);
assert_eq!(edit_correlation["kind"], "debugger.recording.edit");
assert!(
edit_correlation["details"]["path"]
.as_str()
.is_some_and(|path| path.ends_with("tests/browser_debugger_contract.rs"))
);
let commit_correlation = apoc.json(&[
"debugger",
"recording",
"correlate",
"browser-main",
"commit",
"0123456789abcdef0123456789abcdef01234567",
"--idempotency-key",
"debugger/recording-correlate-commit-v1",
"--format",
"json",
]);
assert_eq!(commit_correlation["kind"], "debugger.recording.commit");
apoc.json(&[
"debugger",
"recording",
"capture",
"browser-main",
"--reason",
"manual-checkpoint",
"--idempotency-key",
"debugger/recording-capture-v1",
"--format",
"json",
]);
let mark = apoc.json(&[
"debugger",
"recording",
"mark",
"browser-main",
"baseline",
"--idempotency-key",
"debugger/recording-mark-v1",
"--format",
"json",
]);
assert_eq!(mark["name"], "baseline");
apoc.json(&[
"debugger",
"browser",
"coverage",
"browser-main",
"start",
"--idempotency-key",
"debugger/browser-coverage-start-v1",
"--format",
"json",
]);
let next_url = server.url("/next");
let next = apoc.json(&[
"debugger",
"browser",
"navigate",
"browser-main",
"url",
"--target",
&next_url,
"--idempotency-key",
"debugger/browser-navigate-next-v1",
"--format",
"json",
]);
assert_eq!(next["url"], next_url);
let back = apoc.json(&[
"debugger",
"browser",
"navigate",
"browser-main",
"back",
"--idempotency-key",
"debugger/browser-back-v1",
"--format",
"json",
]);
assert_eq!(back["url"], root_url);
let forward = apoc.json(&[
"debugger",
"browser",
"navigate",
"browser-main",
"forward",
"--idempotency-key",
"debugger/browser-forward-v1",
"--format",
"json",
]);
assert_eq!(forward["url"], next_url);
let back = apoc.json(&[
"debugger",
"browser",
"navigate",
"browser-main",
"back",
"--idempotency-key",
"debugger/browser-back-root-v1",
"--format",
"json",
]);
assert_eq!(back["url"], root_url);
let reload = apoc.json(&[
"debugger",
"browser",
"navigate",
"browser-main",
"reload",
"--idempotency-key",
"debugger/browser-reload-v1",
"--format",
"json",
]);
assert_eq!(reload["url"], root_url);
apoc.json(&[
"debugger",
"browser",
"click",
"browser-main",
"#action",
"--idempotency-key",
"debugger/browser-click-v1",
"--format",
"json",
]);
apoc.json(&[
"debugger",
"browser",
"type",
"browser-main",
"#name",
"Doug",
"--idempotency-key",
"debugger/browser-type-v1",
"--format",
"json",
]);
apoc.json(&[
"debugger",
"browser",
"select",
"browser-main",
"#choice",
"two",
"--idempotency-key",
"debugger/browser-select-v1",
"--format",
"json",
]);
let interaction = apoc.json(&[
"debugger",
"evaluate",
"browser-main",
"JSON.stringify({clicked:document.querySelector('#action').dataset.clicked,name:document.querySelector('#name').value,choice:document.querySelector('#choice').value})",
"--idempotency-key",
"debugger/browser-evaluate-interactions-v1",
"--format",
"json",
]);
assert_eq!(
interaction["value"],
r#"{"clicked":"yes","name":"Doug","choice":"two"}"#
);
let action_button = apoc.json(&[
"debugger",
"evaluate",
"browser-main",
"document.querySelector('#action')",
"--idempotency-key",
"debugger/browser-evaluate-action-button-v1",
"--format",
"json",
]);
let action_button_id = action_button["object_id"].as_str().unwrap();
assert_eq!(action_button["kind"], "object", "{action_button:#}");
assert_eq!(action_button["subtype"], "node", "{action_button:#}");
let listeners = apoc.json(&[
"debugger",
"listeners",
"--format",
"json",
"--",
"browser-main",
action_button_id,
]);
assert!(
listeners
.as_array()
.is_some_and(|items| items.iter().any(|listener| listener["kind"] == "click")),
"{listeners:#}"
);
let requests = apoc.wait_json(Duration::from_secs(10), || {
let requests = apoc.json(&[
"debugger",
"browser",
"network",
"browser-main",
"--format",
"json",
]);
requests
.as_array()?
.iter()
.any(|request| {
request["url"]
.as_str()
.is_some_and(|url| url.ends_with("/api/data"))
&& request["completed_at"].is_number()
})
.then_some(requests)
});
let request_id = requests
.as_array()
.unwrap()
.iter()
.find(|request| request["url"].as_str().unwrap().ends_with("/api/data"))
.unwrap()["id"]
.as_str()
.unwrap();
let body = apoc.json(&[
"debugger",
"browser",
"network-body",
"browser-main",
request_id,
"--format",
"json",
]);
assert_eq!(
body["body"], r#"{"answer":"network-ok"}"#,
"requests: {requests:#}\nbody: {body:#}"
);
let coverage = apoc.json(&[
"debugger",
"browser",
"coverage",
"browser-main",
"stop",
"--idempotency-key",
"debugger/browser-coverage-stop-v1",
"--format",
"json",
]);
assert!(coverage["entries"].as_array().unwrap().iter().any(|entry| {
entry["url"].as_str().is_some_and(|url| url == root_url)
&& entry["used_bytes"].as_u64().unwrap_or(0) > 0
}));
let screenshot = apoc.json(&[
"debugger",
"browser",
"screenshot",
"browser-main",
"--selector",
"#box",
"--state",
"hover",
"--width",
"800",
"--height",
"600",
"--idempotency-key",
"debugger/browser-screenshot-v1",
"--format",
"json",
]);
assert!(screenshot["width"].as_u64().unwrap() > 0);
assert!(screenshot["height"].as_u64().unwrap() > 0);
assert!(screenshot["png_base64"].is_null());
let artifact_path = screenshot["artifact"]["path"].as_str().unwrap();
assert!(Path::new(artifact_path).starts_with(apoc.home.path().join("artifacts/sha256")));
let png = std::fs::read(artifact_path).unwrap();
assert_eq!(&png[..8], b"\x89PNG\r\n\x1a\n");
assert_eq!(
screenshot["artifact"]["id"],
format!("sha256:{:x}", Sha256::digest(&png))
);
let full_page = apoc.json(&[
"debugger",
"browser",
"screenshot",
"browser-main",
"--full-page",
"--inline",
"--idempotency-key",
"debugger/browser-screenshot-full-page-v1",
"--format",
"json",
]);
assert_eq!(full_page["full_page"], true);
assert!(full_page["png_base64"].as_str().unwrap().len() > 100);
assert_eq!(
apoc.json(&[
"debugger",
"browser",
"emulate",
"browser-main",
"iphone-se",
"--idempotency-key",
"debugger/browser-emulate-v1",
"--format",
"json",
]),
"iphone-se"
);
assert_eq!(
apoc.json(&[
"debugger",
"browser",
"throttle",
"browser-main",
"3g",
"--idempotency-key",
"debugger/browser-throttle-v1",
"--format",
"json",
]),
"3g"
);
apoc.json(&[
"debugger",
"browser",
"navigate",
"browser-main",
"url",
"--target",
&next_url,
"--idempotency-key",
"debugger/browser-navigate-emulated-v1",
"--format",
"json",
]);
let emulated_state = apoc.json(&[
"debugger",
"browser",
"state",
"browser-main",
"--format",
"json",
]);
assert_eq!(emulated_state["device"], "iphone-se");
assert_eq!(emulated_state["throttle"], "3g");
apoc.json(&[
"debugger",
"browser",
"navigate",
"browser-main",
"back",
"--idempotency-key",
"debugger/browser-back-emulated-v1",
"--format",
"json",
]);
apoc.json(&[
"debugger",
"browser",
"throttle",
"browser-main",
"off",
"--idempotency-key",
"debugger/browser-throttle-off-v1",
"--format",
"json",
]);
apoc.json(&[
"debugger",
"browser",
"emulate",
"browser-main",
"reset",
"--idempotency-key",
"debugger/browser-emulate-reset-v1",
"--format",
"json",
]);
let mock = apoc.json(&[
"debugger",
"browser",
"mock",
"browser-main",
"/mocked",
"mock response",
"--header",
"Content-Type=text/plain",
"--idempotency-key",
"debugger/browser-mock-v1",
"--format",
"json",
]);
assert_eq!(mock["pattern"], "/mocked");
let mocked_url = server.url("/mocked");
apoc.json(&[
"debugger",
"browser",
"navigate",
"browser-main",
"url",
"--target",
&mocked_url,
"--idempotency-key",
"debugger/browser-navigate-mocked-v1",
"--format",
"json",
]);
let mocked = apoc.json(&[
"debugger",
"browser",
"dom",
"browser-main",
"body",
"--format",
"json",
]);
assert_eq!(mocked[0]["text"], "mock response");
let captures_before_restart = apoc.json(&[
"debugger",
"recording",
"captures",
&recording_id,
"--format",
"json",
]);
let sequence_before_restart =
captures_before_restart.as_array().unwrap().last().unwrap()["sequence"]
.as_u64()
.unwrap();
apoc.json(&[
"daemon",
"stop",
"--idempotency-key",
"browser-debugger-recording-stop",
"--format",
"json",
]);
let recovered =
apoc.wait_json(Duration::from_secs(10), || {
let output = apoc.run(&["debugger", "status", "browser-main", "--format", "json"]);
output.status.success().then(|| serde_json::from_slice::<Value>(&output.stdout).ok())??
["state"]["connected"]
.as_bool()
.unwrap_or(false)
.then(|| serde_json::from_slice(&output.stdout).unwrap())
});
assert_eq!(recovered["adapter"], "browser_cdp");
let recording_status = apoc.json(&[
"debugger",
"recording",
"status",
"browser-main",
"--format",
"json",
]);
assert_eq!(recording_status["id"], recording_id);
assert_eq!(recording_status["phase"], "running");
let state = apoc.json(&[
"debugger",
"browser",
"state",
"browser-main",
"--format",
"json",
]);
assert_eq!(state["mocks"].as_array().unwrap().len(), 1);
apoc.json(&[
"debugger",
"browser",
"navigate",
"browser-main",
"url",
"--target",
&mocked_url,
"--idempotency-key",
"debugger/browser-navigate-mocked-after-restart-v1",
"--format",
"json",
]);
let retained_mock = apoc.json(&[
"debugger",
"browser",
"dom",
"browser-main",
"body",
"--format",
"json",
]);
assert_eq!(retained_mock[0]["text"], "mock response");
let recovered_captures = apoc.wait_json(Duration::from_secs(10), || {
let captures = apoc.json(&[
"debugger",
"recording",
"captures",
&recording_id,
"--format",
"json",
]);
captures.as_array()?.last()?["sequence"]
.as_u64()
.is_some_and(|sequence| sequence > sequence_before_restart)
.then_some(captures)
});
let retained_payloads = recovered_captures
.as_array()
.unwrap()
.iter()
.filter(|capture| capture["screenshot"]["bytes"].as_u64().unwrap_or(0) > 0)
.count();
assert!(retained_payloads <= 4);
let remaining = apoc.json(&[
"debugger",
"browser",
"unmock",
"browser-main",
"--pattern",
"/mocked",
"--idempotency-key",
"debugger/browser-unmock-v1",
"--format",
"json",
]);
assert_eq!(remaining, serde_json::json!([]));
apoc.json(&[
"debugger",
"browser",
"navigate",
"browser-main",
"url",
"--target",
&mocked_url,
"--idempotency-key",
"debugger/browser-navigate-real-v1",
"--format",
"json",
]);
let real = apoc.json(&[
"debugger",
"browser",
"dom",
"browser-main",
"body",
"--format",
"json",
]);
assert_eq!(real[0]["text"], "real response");
apoc.json(&[
"debugger",
"recording",
"shoot",
"browser-main",
"--idempotency-key",
"debugger/recording-shoot-v1",
"--format",
"json",
]);
let marks = apoc.json(&[
"debugger",
"recording",
"marks",
&recording_id,
"--format",
"json",
]);
assert_eq!(marks.as_array().unwrap().len(), 1);
assert_eq!(marks[0]["name"], "baseline");
let replay = apoc.json(&[
"debugger",
"recording",
"replay",
"browser-main",
&initial_capture_id,
"--idempotency-key",
"debugger/recording-replay-v1",
"--format",
"json",
]);
assert_eq!(replay["capture_id"], initial_capture_id);
assert_eq!(replay["url"], root_url);
let after_anchor = apoc.json(&[
"debugger",
"recording",
"shoot",
"browser-main",
"--reason",
"after-baseline",
"--idempotency-key",
"debugger/recording-after-baseline-v1",
"--format",
"json",
]);
let after_anchor_id = after_anchor["id"].as_str().unwrap().to_string();
let mutation = apoc.json(&[
"debugger",
"evaluate",
"browser-main",
"(async()=>{const box=document.querySelector('#box');box.textContent='Changed by after';box.style.backgroundColor='rgb(250, 200, 10)';box.style.color='rgb(5, 6, 7)';localStorage.setItem('after-key','changed');const image=document.createElement('img');image.id='after-image';image.src='data:image/gif;base64,R0lGODlhAQABAAAAACw=';document.body.appendChild(image);console.error('after console failure');setTimeout(()=>{throw new Error('after runtime exception')},0);await fetch('/missing');await new Promise(resolve=>setTimeout(resolve,25));return true})()",
"--idempotency-key",
"debugger/recording-after-mutation-v1",
"--format",
"json",
]);
assert_eq!(mutation["value"], true);
let after_anchor_selector = format!("capture:{after_anchor_id}");
let after = apoc.json(&[
"debugger",
"recording",
"after",
"browser-main",
"--at",
&after_anchor_selector,
"--idempotency-key",
"debugger/recording-after-v1",
"--format",
"json",
]);
assert_eq!(after["before_capture_id"], after_anchor_id);
assert!(after["diff_pixels"].as_u64().unwrap() > 0);
assert!(after["diff_percent"].as_f64().unwrap() > 0.0);
assert!(after["region"].is_object());
assert!(after["console"].as_array().unwrap().iter().any(|entry| {
entry["text"]
.as_str()
.unwrap_or_default()
.contains("after console failure")
}));
assert!(after["exceptions"].as_array().unwrap().iter().any(|entry| {
entry["text"]
.as_str()
.unwrap_or_default()
.contains("after runtime exception")
}));
assert!(!after["network_failures"].as_array().unwrap().is_empty());
assert!(
after["storage"]
.as_array()
.unwrap()
.iter()
.any(|change| change["key"] == "after-key" && change["after"] == "changed")
);
assert!(
after["styles"]
.as_array()
.unwrap()
.iter()
.any(|change| change["selector"] == "#box")
);
assert!(
after["accessibility"]
.as_array()
.unwrap()
.iter()
.any(|issue| issue["rule"] == "image-alt" && issue["selector"] == "#after-image")
);
assert!(
after["performance"]
.as_array()
.is_some_and(|metrics| !metrics.is_empty()),
"{after:#}"
);
assert_eq!(after["report"]["media_type"], "text/html");
assert!(
after["report"]["id"]
.as_str()
.is_some_and(|id| id.starts_with("sha256:"))
);
let after_report_path = Path::new(after["report"]["path"].as_str().unwrap());
assert!(after_report_path.is_file());
assert!(after_report_path.starts_with(apoc.home.path().join("artifacts/sha256")));
let after_id = after["id"].as_str().unwrap().to_string();
let after_capture_id = after["after_capture_id"].as_str().unwrap();
let captures = apoc.json(&[
"debugger",
"recording",
"captures",
&recording_id,
"--format",
"json",
]);
let after_capture = captures
.as_array()
.unwrap()
.iter()
.find(|capture| capture["id"] == after_capture_id)
.unwrap();
assert!(
after_capture["screenshot"]["artifact"]["id"]
.as_str()
.is_some_and(|id| id.starts_with("sha256:")),
"{after_capture:#}"
);
assert!(
Path::new(
after_capture["screenshot"]["artifact"]["path"]
.as_str()
.unwrap()
)
.starts_with(apoc.home.path().join("artifacts/sha256")),
"{after_capture:#}"
);
let after_get = apoc.json(&[
"debugger",
"recording",
"after-get",
&after_id,
"--format",
"json",
]);
assert_eq!(after_get["id"], after_id);
let afters = apoc.json(&[
"debugger",
"recording",
"afters",
&recording_id,
"--format",
"json",
]);
assert!(
afters
.as_array()
.unwrap()
.iter()
.any(|item| item["id"] == after_id)
);
let timeline = apoc.json(&[
"debugger",
"recording",
"timeline",
"browser-main",
"--limit",
"100",
"--idempotency-key",
"debugger/recording-timeline-v1",
"--format",
"json",
]);
assert_eq!(timeline["recording_id"], recording_id);
assert_eq!(timeline["report"]["media_type"], "text/html");
assert!(
timeline["report"]["id"]
.as_str()
.is_some_and(|id| id.starts_with("sha256:"))
);
let timeline_report_path = Path::new(timeline["report"]["path"].as_str().unwrap());
assert!(timeline_report_path.is_file());
assert!(timeline_report_path.starts_with(apoc.home.path().join("artifacts/sha256")));
let timeline_kinds = timeline["items"]
.as_array()
.unwrap()
.iter()
.filter_map(|item| item["kind"].as_str())
.collect::<std::collections::BTreeSet<_>>();
for kind in [
"capture",
"mark",
"error",
"network_failure",
"diff",
"prompt",
"execution",
"edit",
"commit",
"causal",
"debugger_event",
] {
assert!(timeline_kinds.contains(kind), "timeline omitted {kind}");
}
let timeline_html =
std::fs::read_to_string(timeline["report"]["path"].as_str().unwrap()).unwrap();
assert!(timeline_html.contains("data:image/png;base64,"));
assert!(timeline_html.contains("after console failure"));
let why = apoc.json(&[
"debugger",
"recording",
"why",
"browser-main",
"after console failure",
"--window-ms",
"300000",
"--format",
"json",
]);
assert_eq!(why["target"]["kind"], "error");
assert!(
why["target"]["label"]
.as_str()
.unwrap()
.contains("after console failure")
);
assert!(!why["causes"].as_array().unwrap().is_empty());
assert_eq!(
why["context"]["commit"]["ref_id"],
"0123456789abcdef0123456789abcdef01234567"
);
assert_eq!(why["context"]["edit"]["kind"], "edit");
assert!(
why["context"]["edit"]["details"]["path"]
.as_str()
.is_some_and(|path| path.ends_with("tests/browser_debugger_contract.rs"))
);
assert!(
why["answer"]
.as_str()
.unwrap()
.contains("after console failure")
);
let flow = apoc.json(&[
"debugger",
"flow",
"record",
"browser-main",
"fixture-flow",
"--idempotency-key",
"debugger/flow-record-v1",
"--format",
"json",
]);
assert_eq!(flow["phase"], "recording");
apoc.json(&[
"daemon",
"stop",
"--idempotency-key",
"browser-debugger-flow-stop",
"--format",
"json",
]);
apoc.wait_json(Duration::from_secs(10), || {
let output = apoc.run(&["debugger", "status", "browser-main", "--format", "json"]);
output
.status
.success()
.then(|| serde_json::from_slice::<Value>(&output.stdout).ok())??["state"]["connected"]
.as_bool()
.unwrap_or(false)
.then(|| serde_json::from_slice(&output.stdout).unwrap())
});
let recovered_flow = apoc.json(&[
"debugger",
"flow",
"show",
"browser-main",
"fixture-flow",
"--format",
"json",
]);
assert_eq!(recovered_flow["flow"]["phase"], "recording");
apoc.json(&[
"debugger",
"browser",
"click",
"browser-main",
"#action",
"--idempotency-key",
"debugger/flow-click-v1",
"--format",
"json",
]);
apoc.json(&[
"debugger", "evaluate", "browser-main",
"(()=>{const input=document.querySelector('#name');input.value='Flow value';input.dispatchEvent(new Event('change',{bubbles:true}));return input.value})()",
"--idempotency-key", "debugger/flow-input-v1", "--format", "json",
]);
let stopped_flow = apoc.json(&[
"debugger",
"flow",
"stop",
"browser-main",
"--idempotency-key",
"debugger/flow-stop-v1",
"--format",
"json",
]);
assert_eq!(stopped_flow["phase"], "stopped");
let shown_flow = apoc.json(&[
"debugger",
"flow",
"show",
"browser-main",
"fixture-flow",
"--format",
"json",
]);
assert_eq!(shown_flow["steps"].as_array().unwrap().len(), 2);
assert_eq!(shown_flow["steps"][0]["kind"], "click");
assert_eq!(shown_flow["steps"][0]["selector"], "#action");
assert_eq!(shown_flow["steps"][1]["kind"], "input");
assert_eq!(shown_flow["steps"][1]["selector"], "#name");
assert_eq!(shown_flow["steps"][1]["value"], "Flow value");
let flow_run_one = apoc.json(&[
"debugger",
"flow",
"run",
"browser-main",
"fixture-flow",
"--step-timeout-ms",
"1500",
"--idempotency-key",
"debugger/flow-run-v1",
"--format",
"json",
]);
assert_eq!(
flow_run_one["status"], "passed",
"flow run failed after daemon recovery: {flow_run_one:#}"
);
assert_eq!(flow_run_one["steps_passed"], 2);
assert!(
flow_run_one["steps"]
.as_array()
.unwrap()
.iter()
.all(|step| step["capture"].is_object())
);
let flow_run_two = apoc.json(&[
"debugger",
"flow",
"run",
"browser-main",
"fixture-flow",
"--step-timeout-ms",
"1500",
"--idempotency-key",
"debugger/flow-run-v2",
"--format",
"json",
]);
assert_eq!(flow_run_two["status"], "passed");
assert!(
flow_run_two["steps"]
.as_array()
.unwrap()
.iter()
.all(|step| step["diff_percent"].is_number())
);
apoc.json(&[
"debugger",
"evaluate",
"browser-main",
"fetch('/break').then(response=>response.text())",
"--idempotency-key",
"debugger/flow-break-v1",
"--format",
"json",
]);
let failed_flow_run = apoc.json(&[
"debugger",
"flow",
"run",
"browser-main",
"fixture-flow",
"--step-timeout-ms",
"500",
"--idempotency-key",
"debugger/flow-run-failed-v1",
"--format",
"json",
]);
assert_eq!(failed_flow_run["status"], "failed");
assert_eq!(failed_flow_run["steps"][0]["status"], "failed");
assert!(
failed_flow_run["steps"][0]["error"]
.as_str()
.unwrap()
.contains("Readiness timeout")
);
assert!(failed_flow_run["steps"][0]["capture"].is_object());
assert_eq!(failed_flow_run["steps"][1]["status"], "skipped");
let flows = apoc.json(&["debugger", "flow", "list", "--format", "json"]);
assert!(
flows
.as_array()
.unwrap()
.iter()
.any(|item| item["name"] == "fixture-flow")
);
let stopped_recording = apoc.json(&[
"debugger",
"recording",
"stop",
"browser-main",
"--idempotency-key",
"debugger/recording-stop-v1",
"--format",
"json",
]);
assert_eq!(stopped_recording["phase"], "stopped");
assert!(
stopped_recording["retained_frames"].as_u64().unwrap() <= 4
|| stopped_recording["retention_overflow"] == true
);
assert!(
apoc.json(&[
"debugger",
"browser",
"page-events",
"browser-main",
"--format",
"json",
])
.as_array()
.unwrap()
.iter()
.any(|event| event["name"] == "frameNavigated")
);
assert!(
apoc.json(&[
"debugger",
"browser",
"websockets",
"browser-main",
"--format",
"json",
])
.is_array()
);
apoc.json(&[
"debugger",
"close",
"browser-main",
"--idempotency-key",
"debugger/browser-close-v1",
"--format",
"json",
]);
apoc.json(&[
"execution",
"cancel",
&execution_id,
"--idempotency-key",
"debugger/browser-final-cancel",
"--timeout-ms",
"5000",
"--format",
"json",
]);
apoc.forget(&execution_id);
}