Skip to content

The design language that makes your AI harness better at design.

JavaScript

Fix the flaky rust-windows browser tests at their causes (#957)

Paul Bakausf06461550ac7
diff --git a/crates/browser/src/cdp.rs b/crates/browser/src/cdp.rs
index e67601693..6dd9c8712 100644
--- a/crates/browser/src/cdp.rs
+++ b/crates/browser/src/cdp.rs
@@ -244,7 +244,7 @@ impl Browser {
)));
}
};
- let conn = match Connection::connect(&ws_url) {
+ let mut conn = match Connection::connect(&ws_url) {
Ok(c) => c,
Err(e) => {
let _ = child.kill();
@@ -253,6 +253,14 @@ impl Browser {
return Err(e);
}
};
+ // A fresh profile loads its cookie store on the first request that
+ // needs it, and every page request waits for that load. On Windows the
+ // load (an encrypted SQLite store) takes 1 to 5 s and has taken over
+ // 15 s with several browsers starting at once, which the first
+ // navigation then spent out of its own timeout. Asking for the cookies
+ // here makes the launch wait for the load instead, under the protocol
+ // timeout, so a navigation deadline measures only the navigation.
+ let _ = conn.send(None, "Storage.getCookies", json!({}), PROTOCOL_TIMEOUT);
Ok(Browser {
child,
user_data_dir,
diff --git a/crates/browser/src/html_snapshot.rs b/crates/browser/src/html_snapshot.rs
index 5099d1671..bc37cb149 100644
--- a/crates/browser/src/html_snapshot.rs
+++ b/crates/browser/src/html_snapshot.rs
@@ -10,10 +10,10 @@ use std::{
collections::{BTreeMap, BTreeSet},
fs::{self, File},
io::{Read, Write},
- net::{TcpListener, TcpStream},
+ net::{Shutdown, TcpListener, TcpStream},
path::{Component, Path, PathBuf},
sync::{
- Arc,
+ Arc, Mutex,
atomic::{AtomicBool, Ordering},
},
thread::{self, JoinHandle},
@@ -192,11 +192,16 @@ impl HtmlSnapshot {
let worker_stop = stop.clone();
let snapshot = self.clone();
let worker_host = host.clone();
+ let connections = Connections::default();
+ let worker_connections = connections.clone();
let worker = thread::spawn(move || {
while !worker_stop.load(Ordering::Acquire) {
match listener.accept() {
- Ok((mut stream, _)) => {
- let _ = respond(&mut stream, &worker_host, &snapshot, scripts);
+ Ok((stream, _)) => {
+ let (host, snapshot) = (worker_host.clone(), snapshot.clone());
+ worker_connections.spawn(stream, move |stream| {
+ let _ = respond(stream, &host, &snapshot, scripts);
+ });
}
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
thread::sleep(Duration::from_millis(5))
@@ -210,6 +215,7 @@ impl HtmlSnapshot {
entry: self.entry.clone(),
stop,
worker: Some(worker),
+ connections,
})
}
}
@@ -317,11 +323,44 @@ fn encode_path(path: &str) -> String {
})
.collect()
}
+/// A snapshot server's open connections, each answered on its own thread.
+/// Chrome opens sockets it may leave idle (backup connect jobs, preconnects),
+/// and one of those must not hold the page's requests behind its read
+/// timeout. A finished connection leaves the set; dropping the server closes
+/// the rest at once instead of leaving them to their read timeout.
+#[derive(Clone, Default)]
+pub struct Connections(Arc<Mutex<(u64, BTreeMap<u64, TcpStream>)>>);
+impl Connections {
+ pub fn spawn(&self, mut stream: TcpStream, answer: impl FnOnce(&mut TcpStream) + Send + 'static) {
+ let id = {
+ let mut open = self.0.lock().unwrap_or_else(|e| e.into_inner());
+ open.0 += 1;
+ let id = open.0;
+ if let Ok(handle) = stream.try_clone() {
+ open.1.insert(id, handle);
+ }
+ id
+ };
+ let open = self.clone();
+ thread::spawn(move || {
+ answer(&mut stream);
+ let _ = stream.shutdown(Shutdown::Write);
+ open.0.lock().unwrap_or_else(|e| e.into_inner()).1.remove(&id);
+ });
+ }
+ pub fn close_all(&self) {
+ let open = std::mem::take(&mut self.0.lock().unwrap_or_else(|e| e.into_inner()).1);
+ for stream in open.into_values() {
+ let _ = stream.shutdown(Shutdown::Both);
+ }
+ }
+}
pub struct SnapshotServer {
host: String,
entry: String,
stop: Arc<AtomicBool>,
worker: Option<JoinHandle<()>>,
+ connections: Connections,
}
impl SnapshotServer {
pub fn entry_url(&self) -> String {
@@ -334,8 +373,10 @@ impl Drop for SnapshotServer {
if let Some(worker) = self.worker.take() {
let _ = worker.join();
}
+ self.connections.close_all();
}
}
+const CONNECTION_TIMEOUT: Duration = Duration::from_secs(60);
fn respond(
stream: &mut TcpStream,
host: &str,
@@ -346,8 +387,15 @@ fn respond(
// switch accepted streams back before write_all; otherwise large bodies
// stop at EWOULDBLOCK and appear as valid-header/truncated-image responses.
stream.set_nonblocking(false)?;
- stream.set_read_timeout(Some(Duration::from_secs(2)))?;
- stream.set_write_timeout(Some(Duration::from_secs(2)))?;
+ // Chrome can connect and then write its request seconds later: on Windows
+ // a fresh browser's first request takes 1.5 to 3 s to go out, sometimes
+ // over 5 s, and the socket is often open well before. Closing it early
+ // made Chrome stall the navigation for about 13 s before retrying, past
+ // the capture's navigation timeout. Wait longer than any navigation
+ // timeout instead; the connection has its own thread, so waiting blocks no
+ // other request.
+ stream.set_read_timeout(Some(CONNECTION_TIMEOUT))?;
+ stream.set_write_timeout(Some(CONNECTION_TIMEOUT))?;
let mut bytes = Vec::new();
let mut buf = [0u8; 1024];
while bytes.len() <= 8192 && !bytes.windows(4).any(|x| x == b"\r\n\r\n") {
@@ -390,3 +438,23 @@ fn respond(
)?;
stream.write_all(body)
}
+#[cfg(test)]
+mod connection_tests {
+ use super::*;
+ #[test]
+ fn finished_connections_leave_the_open_set() {
+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();
+ let addr = listener.local_addr().unwrap();
+ let open = Connections::default();
+ let _client = TcpStream::connect(addr).unwrap();
+ let (stream, _) = listener.accept().unwrap();
+ let (tx, rx) = std::sync::mpsc::channel();
+ open.spawn(stream, move |_| tx.send(()).unwrap());
+ rx.recv().unwrap();
+ let deadline = std::time::Instant::now() + Duration::from_secs(5);
+ while !open.0.lock().unwrap().1.is_empty() && std::time::Instant::now() < deadline {
+ thread::sleep(Duration::from_millis(10));
+ }
+ assert!(open.0.lock().unwrap().1.is_empty(), "a finished connection kept its socket handle");
+ }
+}
diff --git a/crates/browser/src/response_capture.rs b/crates/browser/src/response_capture.rs
index c48956382..6bd973b53 100644
--- a/crates/browser/src/response_capture.rs
+++ b/crates/browser/src/response_capture.rs
@@ -1,7 +1,7 @@
//! Opt-in, bounded CDP response evidence. This proves observed bytes, not paint.
use base64::Engine;
use serde_json::Value;
-use std::collections::HashMap;
+use std::collections::{HashMap, HashSet};
pub(crate) const MAX_BODY: usize = 16 * 1024 * 1024;
pub(crate) const MAX_TOTAL: usize = 64 * 1024 * 1024;
@@ -43,6 +43,8 @@ pub struct ResponseEvidence {
pub(crate) struct ResponseCapture {
records: Vec<ResponseRecord>,
active: HashMap<String, usize>,
+ /// Requests the browser made for itself (the tab icon), never the page.
+ browser_initiated: HashSet<String>,
pub revision: u64,
truncated: bool,
body_bytes: usize,
@@ -80,6 +82,18 @@ fn string(v: &Value, key: &str) -> String {
v.get(key).and_then(Value::as_str).unwrap_or("").to_owned()
}
+/// The browser's own fetch for the tab icon: no parser, script or preload
+/// initiated it and it is not a navigation, so CDP reports it as type `Other`
+/// with an `other` initiator. Every request the document makes carries its own
+/// type or initiator (a `<link rel=prefetch>` is `Other` from the `parser`).
+/// Chrome sends it after the load event, on its own schedule, and it paints
+/// nothing, so it is neither a page dependency nor a change to the page.
+fn browser_initiated(p: &Value) -> bool {
+ string(p, "type") == "Other"
+ && p.pointer("/initiator/type").and_then(Value::as_str) == Some("other")
+ && string(p, "requestId") != string(p, "loaderId")
+}
+
impl ResponseCapture {
pub fn event(&mut self, method: &str, p: &Value) {
if !matches!(
@@ -91,8 +105,18 @@ impl ResponseCapture {
) {
return;
}
- self.revision += 1;
let id = string(p, "requestId");
+ if self.browser_initiated.contains(&id) {
+ return;
+ }
+ if method == "Network.requestWillBeSent" && !id.is_empty() && browser_initiated(p) {
+ if self.browser_initiated.len() < MAX_RECORDS {
+ self.browser_initiated.insert(id);
+ return;
+ }
+ self.truncated = true;
+ }
+ self.revision += 1;
if id.is_empty() {
self.truncated = true;
return;
@@ -297,6 +321,23 @@ mod tests {
assert_eq!(e.responses[1].body, Some(vec![0, 255]));
}
#[test]
+ fn browser_icon_fetch_is_neither_a_dependency_nor_a_change() {
+ let mut t = ResponseCapture::default();
+ let sent = |id: &str, url: &str, kind: &str, initiator: &str| json!({"requestId":id,"loaderId":"current","request":{"url":url},"frameId":"main","type":kind,"initiator":{"type":initiator}});
+ t.event("Network.requestWillBeSent", &sent("current", "http://x/", "Document", "other"));
+ let before = t.revision;
+ // Chrome's tab-icon fetch, after load, on the main frame's loader.
+ t.event("Network.requestWillBeSent", &sent("9.2", "http://x/favicon.ico", "Other", "other"));
+ t.event("Network.responseReceived", &json!({"requestId":"9.2","response":{"url":"http://x/favicon.ico","status":404,"mimeType":"text/plain"}}));
+ t.event("Network.loadingFinished", &json!({"requestId":"9.2"}));
+ assert_eq!(t.revision, before, "the icon fetch must not read as the page changing");
+ assert_eq!(t.urls("main", "current"), vec!["http://x/"]);
+ // The document's own requests keep counting, even an `Other` one.
+ t.event("Network.requestWillBeSent", &sent("9.3", "http://x/next.js", "Other", "parser"));
+ assert_eq!(t.revision, before + 1);
+ assert_eq!(t.urls("main", "current"), vec!["http://x/", "http://x/next.js"]);
+ }
+ #[test]
fn incomplete_failed_and_wrong_document_are_explicit() {
let mut t = ResponseCapture::default();
request(&mut t, "1", "inflight");
diff --git a/crates/browser/tests/html_snapshot.rs b/crates/browser/tests/html_snapshot.rs
index 59628aa90..486514564 100644
--- a/crates/browser/tests/html_snapshot.rs
+++ b/crates/browser/tests/html_snapshot.rs
@@ -222,3 +222,45 @@ fn snapshot_server_delivers_large_binary_response_completely() {
);
assert_eq!(&response[body..], payload);
}
+
+/// Chrome opens sockets it leaves idle and writes some requests seconds after
+/// connecting. Neither may hold up another request or lose its own, and
+/// dropping the server ends every connection it still holds.
+#[test]
+fn snapshot_server_serves_around_idle_and_late_connections_and_closes_them_on_drop() {
+ use std::{
+ io::{Read, Write},
+ net::TcpStream,
+ sync::Arc,
+ time::{Duration, Instant},
+ };
+ let f = Fixture::new();
+ let snapshot = Arc::new(HtmlSnapshot::freeze(f.selection()).unwrap());
+ let server = snapshot.serve().unwrap();
+ let url = server.entry_url();
+ let host = url.strip_prefix("http://").unwrap().split('/').next().unwrap().to_string();
+ let get = |stream: &mut TcpStream| {
+ stream.set_read_timeout(Some(Duration::from_secs(10))).unwrap();
+ write!(stream, "GET /index.html HTTP/1.1\r\nHost: {host}\r\n\r\n").unwrap();
+ let mut response = Vec::new();
+ stream.read_to_end(&mut response).unwrap();
+ String::from_utf8_lossy(&response).into_owned()
+ };
+ // Accepted first and never written to: a serial server would answer the
+ // next connection only after giving up on this one.
+ let mut idle = TcpStream::connect(&host).unwrap();
+ std::thread::sleep(Duration::from_millis(50));
+ let started = Instant::now();
+ assert!(get(&mut TcpStream::connect(&host).unwrap()).starts_with("HTTP/1.1 200 OK"));
+ assert!(started.elapsed() < Duration::from_millis(1500), "an idle connection held up a request");
+ // Connected now, written later than the old 2 s idle limit.
+ let mut late = TcpStream::connect(&host).unwrap();
+ std::thread::sleep(Duration::from_millis(2500));
+ assert!(get(&mut late).starts_with("HTTP/1.1 200 OK"), "a late request lost its connection");
+ drop(server);
+ idle.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
+ let closed = Instant::now();
+ let mut buf = [0u8; 16];
+ assert!(matches!(idle.read(&mut buf), Ok(0) | Err(_)));
+ assert!(closed.elapsed() < Duration::from_secs(4), "dropping the server left a connection open");
+}
diff --git a/crates/browser/tests/response_capture.rs b/crates/browser/tests/response_capture.rs
index 6655d1d10..d67034cb2 100644
--- a/crates/browser/tests/response_capture.rs
+++ b/crates/browser/tests/response_capture.rs
@@ -1,13 +1,13 @@
//! Native transport evidence: read the response that was rendered, never refetch.
use impeccable_browser::{cdp::Browser, discovery};
use std::collections::HashMap;
-use std::io::{Read, Write};
-use std::net::TcpListener;
use std::sync::{
Arc,
atomic::{AtomicUsize, Ordering},
};
-use std::time::Duration;
+use std::time::{Duration, Instant};
+#[path = "support/http.rs"]
+mod http;
fn launch(exe: &std::path::Path) -> Option<Browser> {
Browser::launch(exe, &[], false)
@@ -22,38 +22,22 @@ fn response_capture_reads_original_bytes_and_preserves_repeated_url_ambiguity()
eprintln!("skip: no browser");
return;
};
- let listener = TcpListener::bind("127.0.0.1:0").unwrap();
- let origin = format!("http://127.0.0.1:{}", listener.local_addr().unwrap().port());
let hits = Arc::new(AtomicUsize::new(0));
- let count = hits.clone();
- std::thread::spawn(move || {
- for mut stream in listener.incoming().flatten() {
- let mut request = [0u8; 4096];
- let n = stream.read(&mut request).unwrap_or(0);
- let request = String::from_utf8_lossy(&request[..n]);
- let (kind, body) = if request.starts_with("GET /asset.bin ") {
- let number = count.fetch_add(1, Ordering::SeqCst);
- (
- "application/octet-stream",
- if number == 0 {
- vec![0, 255, 13, 128, 42]
- } else {
- vec![99, 4, 0, 128]
- },
- )
- } else {
- (
- "text/html",
- b"<!doctype html><title>capture</title><body>fixture</body>".to_vec(),
- )
- };
- let header = format!(
- "HTTP/1.1 200 OK\r\nContent-Type: {kind}\r\nContent-Length: {}\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n",
- body.len()
- );
- let _ = stream.write_all(header.as_bytes());
- let _ = stream.write_all(&body);
+ let icon_requests = Arc::new(AtomicUsize::new(0));
+ let (count, icons) = (hits.clone(), icon_requests.clone());
+ let origin = http::serve(move |path| match path {
+ "/asset.bin" => {
+ let number = count.fetch_add(1, Ordering::SeqCst);
+ Some((
+ "application/octet-stream",
+ if number == 0 { vec![0, 255, 13, 128, 42] } else { vec![99, 4, 0, 128] },
+ ))
+ }
+ "/icon.png" | "/favicon.ico" => {
+ icons.fetch_add(1, Ordering::SeqCst);
+ None
}
+ _ => Some(("text/html", b"<!doctype html><title>capture</title><link rel=icon href=/icon.png><body>fixture</body>".to_vec())),
});
let Some(mut browser) = launch(&exe) else { return; };
let mut page = browser.new_page().unwrap();
@@ -63,6 +47,19 @@ fn response_capture_reads_original_bytes_and_preserves_repeated_url_ambiguity()
);
page.begin_response_capture().unwrap();
page.goto(&origin, "load", Duration::from_secs(15)).unwrap();
+ // Chrome fetches the declared tab icon after load, on its own schedule.
+ // Wait for it so everything below covers it: it is the browser's request,
+ // not the page's, and must not read as a page dependency or a change.
+ let waited = Instant::now();
+ while icon_requests.load(Ordering::SeqCst) == 0 && waited.elapsed() < Duration::from_secs(10) {
+ std::thread::sleep(Duration::from_millis(20));
+ }
+ assert!(icon_requests.load(Ordering::SeqCst) > 0, "the browser never fetched the declared icon");
+ page.evaluate_value("true").unwrap();
+ assert!(
+ page.observed_response_urls().unwrap().iter().all(|u| !u.ends_with("/icon.png") && !u.ends_with("/favicon.ico")),
+ "the browser's icon fetch is not a page dependency"
+ );
page.evaluate_value("fetch('/asset.bin').then(r=>r.arrayBuffer()).then(()=>true)")
.unwrap();
// Pump a browser round-trip after the fetch's completion event.
@@ -118,18 +115,15 @@ fn large_utf8_document_retains_exact_bytes_without_refetch() {
// inspector buffer must accommodate it even though the UTF-8 body is <16MiB.
let body = format!("<!doctype html><meta charset=utf-8><title>€</title><!--{}-->", "a".repeat(9 * 1024 * 1024)).into_bytes();
let served = body.clone();
- let listener = TcpListener::bind("127.0.0.1:0").unwrap();
- let url = format!("http://127.0.0.1:{}/index.html", listener.local_addr().unwrap().port());
let hits = Arc::new(AtomicUsize::new(0));
let count = hits.clone();
- let server = std::thread::spawn(move || {
- let (mut stream, _) = listener.accept().unwrap();
- let mut request = [0; 4096];
- stream.read(&mut request).unwrap();
- count.fetch_add(1, Ordering::SeqCst);
- write!(stream, "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", served.len()).unwrap();
- stream.write_all(&served).unwrap();
+ let origin = http::serve(move |path| {
+ (path == "/index.html").then(|| {
+ count.fetch_add(1, Ordering::SeqCst);
+ ("text/html; charset=utf-8", served.clone())
+ })
});
+ let url = format!("{origin}/index.html");
let Some(mut browser) = launch(&exe) else { return; };
let mut page = browser.new_page().unwrap();
page.begin_response_capture().unwrap();
@@ -141,7 +135,6 @@ fn large_utf8_document_retains_exact_bytes_without_refetch() {
assert_eq!(hits.load(Ordering::SeqCst), 1);
page.close();
browser.close();
- server.join().unwrap();
}
#[test]
@@ -151,17 +144,11 @@ fn decoded_text_bodies_match_only_their_served_bytes() {
// Blink reports these as text: the BOM dropped, the Latin-1 byte as U+FFFD.
let html = b"\xEF\xBB\xBF<!doctype html><link rel=stylesheet href=a.css><p>x</p>".to_vec();
let css = b"/* caf\xE9 */\r\np{color:red}".to_vec();
- let listener = TcpListener::bind("127.0.0.1:0").unwrap();
- let origin = format!("http://127.0.0.1:{}", listener.local_addr().unwrap().port());
let (served_html, served_css) = (html.clone(), css.clone());
- std::thread::spawn(move || {
- for mut stream in listener.incoming().flatten() {
- let mut request = [0u8; 4096];
- let n = stream.read(&mut request).unwrap_or(0);
- let (kind, body) = if request[..n].starts_with(b"GET /a.css ") { ("text/css", &served_css) } else { ("text/html", &served_html) };
- let _ = write!(stream, "HTTP/1.1 200 OK\r\nContent-Type: {kind}; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len());
- let _ = stream.write_all(body);
- }
+ let origin = http::serve(move |path| match path {
+ "/a.css" => Some(("text/css; charset=utf-8", served_css.clone())),
+ "/" => Some(("text/html; charset=utf-8", served_html.clone())),
+ _ => None,
});
let Some(mut browser) = launch(&exe) else { return; };
let mut page = browser.new_page().unwrap();
diff --git a/crates/browser/tests/support/http.rs b/crates/browser/tests/support/http.rs
new file mode 100644
index 000000000..3b961b132
--- /dev/null
+++ b/crates/browser/tests/support/http.rs
@@ -0,0 +1,67 @@
+//! A local HTTP/1.1 server for browser tests.
+//!
+//! Chrome does not open exactly one connection per request. A backup connect
+//! job, a preconnect, or the tab-icon fetch can each open a socket the test did
+//! not plan for, and on a loaded machine (the Windows runner) they arrive in
+//! any order. A server that accepts once, or answers connections one at a time,
+//! then serves an idle socket while the real request waits, and the browser
+//! reports an aborted or refused connection. This one answers every
+//! connection on its own thread, ignores sockets that close without a request,
+//! and returns 404 for paths the handler does not know.
+use std::io::{Read, Write};
+use std::net::{TcpListener, TcpStream};
+use std::sync::Arc;
+use std::time::Duration;
+
+/// What a handler returns for a path: a content type and the body bytes.
+pub type Response = (&'static str, Vec<u8>);
+
+/// Serve `handler` on 127.0.0.1 for the rest of the test process and return the
+/// origin (`http://127.0.0.1:<port>`). `handler` receives the request path.
+pub fn serve<F>(handler: F) -> String
+where
+ F: Fn(&str) -> Option<Response> + Send + Sync + 'static,
+{
+ let listener = TcpListener::bind("127.0.0.1:0").expect("bind test server");
+ let origin = format!("http://127.0.0.1:{}", listener.local_addr().unwrap().port());
+ let handler = Arc::new(handler);
+ std::thread::spawn(move || {
+ for stream in listener.incoming().flatten() {
+ let handler = handler.clone();
+ std::thread::spawn(move || {
+ let _ = respond(stream, &*handler);
+ });
+ }
+ });
+ origin
+}
+
+fn respond(mut stream: TcpStream, handler: &dyn Fn(&str) -> Option<Response>) -> std::io::Result<()> {
+ stream.set_read_timeout(Some(Duration::from_secs(60)))?;
+ let mut request = Vec::new();
+ let mut buf = [0u8; 4096];
+ while !request.windows(4).any(|w| w == b"\r\n\r\n") {
+ let n = stream.read(&mut buf)?;
+ if n == 0 {
+ // A speculative socket the browser closed unused.
+ return Ok(());
+ }
+ request.extend_from_slice(&buf[..n]);
+ if request.len() > 64 * 1024 {
+ return Ok(());
+ }
+ }
+ let line = String::from_utf8_lossy(&request);
+ let path = line.split_whitespace().nth(1).unwrap_or("/").to_string();
+ let (status, kind, body) = match handler(&path) {
+ Some((kind, body)) => ("200 OK", kind, body),
+ None => ("404 Not Found", "text/plain", b"not found".to_vec()),
+ };
+ write!(
+ stream,
+ "HTTP/1.1 {status}\r\nContent-Type: {kind}\r\nContent-Length: {}\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n",
+ body.len()
+ )?;
+ stream.write_all(&body)?;
+ stream.flush()
+}
diff --git a/crates/cli/src/capture_snapshot.rs b/crates/cli/src/capture_snapshot.rs
index c596479e3..4a1815361 100644
--- a/crates/cli/src/capture_snapshot.rs
+++ b/crates/cli/src/capture_snapshot.rs
@@ -1,5 +1,6 @@
//! Immutable, explicit static-HTML inputs for native capture. Not a framework server.
//! The native caller owns the selection; private bound inputs are never HTTP routes.
+use impeccable_browser::html_snapshot::Connections;
use impeccable_comp_verbs::asset_capture::capture_sha256 as hash;
use serde_json::{Value, json};
/// Most raster regions one native capture measures in a frame. The browser
@@ -295,11 +296,16 @@ impl HtmlSnapshot {
let worker_stop = stop.clone();
let snapshot = self.clone();
let worker_host = host.clone();
+ let connections = Connections::default();
+ let worker_connections = connections.clone();
let worker = thread::spawn(move || {
while !worker_stop.load(Ordering::Acquire) {
match listener.accept() {
- Ok((mut stream, _)) => {
- let _ = respond(&mut stream, &worker_host, &snapshot);
+ Ok((stream, _)) => {
+ let (host, snapshot) = (worker_host.clone(), snapshot.clone());
+ worker_connections.spawn(stream, move |stream| {
+ let _ = respond(stream, &host, &snapshot);
+ });
}
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
thread::sleep(Duration::from_millis(5))
@@ -313,6 +319,7 @@ impl HtmlSnapshot {
entry: self.entry.clone(),
stop,
worker: Some(worker),
+ connections,
})
}
}
@@ -425,6 +432,7 @@ pub struct SnapshotServer {
entry: String,
stop: Arc<AtomicBool>,
worker: Option<JoinHandle<()>>,
+ connections: Connections,
}
impl SnapshotServer {
pub fn entry_url(&self) -> String {
@@ -437,6 +445,7 @@ impl Drop for SnapshotServer {
if let Some(worker) = self.worker.take() {
let _ = worker.join();
}
+ self.connections.close_all();
}
}
fn respond(
@@ -448,8 +457,12 @@ fn respond(
// switch accepted streams back before write_all; otherwise large bodies
// stop at EWOULDBLOCK and appear as valid-header/truncated-image responses.
stream.set_nonblocking(false)?;
- stream.set_read_timeout(Some(Duration::from_secs(2)))?;
- stream.set_write_timeout(Some(Duration::from_secs(2)))?;
+ // Chrome can connect and then write its request seconds later (see
+ // impeccable_browser::html_snapshot); closing the socket early stalls the
+ // navigation past its timeout. The connection has its own thread, so
+ // waiting longer than any navigation timeout blocks no other request.
+ stream.set_read_timeout(Some(Duration::from_secs(60)))?;
+ stream.set_write_timeout(Some(Duration::from_secs(60)))?;
let mut bytes = Vec::new();
let mut buf = [0u8; 1024];
while bytes.len() <= 8192 && !bytes.windows(4).any(|x| x == b"\r\n\r\n") {
diff --git a/crates/cli/src/component_capture.rs b/crates/cli/src/component_capture.rs
index c58d39eff..cba9135d8 100644
--- a/crates/cli/src/component_capture.rs
+++ b/crates/cli/src/component_capture.rs
@@ -112,12 +112,6 @@ pub(crate) fn render_page(
if record.url.starts_with("data:image/") {
continue;
}
- if record.url == format!("{origin}/favicon.ico")
- && record.status == Some(404.)
- && snapshot.bytes("favicon.ico").is_none()
- {
- continue;
- }
let Some(target) = record.url.strip_prefix(&origin) else {
dependency_errors.insert(format!("external dependency: {}", record.url));
continue;
diff --git a/crates/cli/tests/asset_capture.rs b/crates/cli/tests/asset_capture.rs
index 4aff4164f..4bccd2436 100644
--- a/crates/cli/tests/asset_capture.rs
+++ b/crates/cli/tests/asset_capture.rs
@@ -22,114 +22,119 @@ fn native_capture_distinguishes_paint_from_file_presence() {
let origin = format!("http://127.0.0.1:{}", listener.local_addr().unwrap().port());
let asset = image.clone();
std::thread::spawn(move || {
+ // One thread per connection, so a socket Chrome opens and leaves idle
+ // never holds the page's requests behind its read timeout.
for mut stream in listener.incoming().flatten() {
- stream
- .set_read_timeout(Some(Duration::from_secs(2)))
- .unwrap();
- let mut bytes = [0u8; 4096];
- let n = stream.read(&mut bytes).unwrap_or(0);
- let line = String::from_utf8_lossy(&bytes[..n]);
- let path = line.split_whitespace().nth(1).unwrap_or("/");
- let (mime, body) = if path == "/transparent.png" {
- ("image/png", transparent_response.clone())
- } else if path == "/art.png" || path == "/lazy.png" {
- ("image/png", asset.clone())
- } else if path == "/collision/art.png" {
- ("image/png", wrong.clone())
- } else {
- let mode = path.trim_start_matches('/');
- let parent = match mode {
- "hidden" => "visibility:hidden",
- "opacity" | "pseudo-hidden" => "opacity:0",
- "clip" => "clip-path:inset(100%)",
- _ => "",
- };
- let position = match mode {
- "shift" => "left:70px",
- "footer" => "top:500px",
- _ => "",
- };
- let img = if mode == "pseudo-url-only" {
- "<div id=art style='position:relative;width:80px;height:80px'></div><style>#art::before{content:'';position:absolute;inset:0;background:url(/art.png) center/cover}</style>"
- } else if mode.starts_with("pseudo-") && mode != "pseudo-neighbor" {
- "<div id=art style='position:relative;width:80px;height:80px'></div><style>#art::before{content:'';position:absolute;inset:0;background-image:linear-gradient(transparent,transparent),url(/art.png);background-size:cover}</style>"
- } else if mode == "layered-duplicate" {
- "<div id=art style='width:80px;height:80px;background-image:url(/art.png),url(/art.png);background-size:cover'></div>"
- } else if mode == "decoration" {
- "<img id='art' width='80' height='80' src='/transparent.png' style='background:red;box-shadow:0 0 4px blue'>"
- } else if mode == "background" {
- "<div id='art' style='width:80px;height:80px;background:url(/art.png) center/cover'></div>"
- } else if mode == "wrong" || mode == "footer-trap" {
- "<img id='art' width='80' height='80' src='/collision/art.png'>"
+ let (transparent_response, asset, wrong) = (transparent_response.clone(), asset.clone(), wrong.clone());
+ std::thread::spawn(move || {
+ stream
+ .set_read_timeout(Some(Duration::from_secs(60)))
+ .unwrap();
+ let mut bytes = [0u8; 4096];
+ let n = stream.read(&mut bytes).unwrap_or(0);
+ let line = String::from_utf8_lossy(&bytes[..n]);
+ let path = line.split_whitespace().nth(1).unwrap_or("/");
+ let (mime, body) = if path == "/transparent.png" {
+ ("image/png", transparent_response.clone())
+ } else if path == "/art.png" || path == "/lazy.png" {
+ ("image/png", asset.clone())
+ } else if path == "/collision/art.png" {
+ ("image/png", wrong.clone())
} else {
- "<img id='art' width='80' height='80' src='/art.png'>"
- };
- let cover = if mode == "duplicate" {
- "<img src=/art.png style='position:absolute;inset:0;width:80px;height:80px'>"
- } else if mode == "covered" || mode == "pseudo-covered" {
- "<div style='position:absolute;inset:0;background:white'></div>"
- } else {
- ""
- };
- let extra = match mode {
- "many-text-pseudos" => "<div id=text-only style='position:absolute;top:500px'></div><style>.marker::before,.marker::after{content:'x'}</style><script>for(let i=0;i<300;i++){const el=document.createElement('span');el.className='marker';document.querySelector('#text-only').append(el)}</script>",
- "pseudo-specificity" => "<style>#art#art#art::before{background-image:url(/art.png)!important}</style>",
- "pseudo-mutating" => "<script>setInterval(()=>{if(getComputedStyle(document.querySelector('#art'),'::before').backgroundImage.includes('none'))document.body.dataset.touched='yes'},0)</script>",
- "pseudo-neighbor" => {
- "<style>#art::before{content:''}</style><div style='position:absolute;left:20px;top:20px;width:80px;height:20px' class='ribbon'></div><style>.ribbon::before{content:'';position:absolute;inset:0;background-image:linear-gradient(white,white)}</style>"
- }
- "canvas-cover" => {
- "<canvas id='cover' width='80' height='80' style='position:absolute;left:20px;top:20px;width:80px;height:80px'></canvas><script>const c=document.querySelector('#cover').getContext('2d');c.fillStyle='blue';c.fillRect(0,0,80,80)</script>"
- }
- "canvas-only" => {
- "<canvas id='cover' width='80' height='80' style='position:absolute;left:20px;top:20px;width:80px;height:80px'></canvas><script>document.querySelector('#art').remove();const i=new Image();i.onload=()=>document.querySelector('#cover').getContext('2d').drawImage(i,0,0,80,80);i.src='/art.png'</script>"
- }
- "tiny-token" => "<style>#art{width:1px!important;height:1px!important}</style>",
- "many" => {
- "<script>for(let i=0;i<17;i++){const el=document.querySelector('#art').cloneNode(true);el.style.cssText='position:absolute;left:20px;top:20px';document.body.append(el);}</script>"
- }
- "closed-shadow" => {
- "<div id=shadow style='position:absolute;left:20px;top:20px;width:80px;height:80px'></div><script>document.querySelector('#shadow').attachShadow({mode:'closed'}).innerHTML='<span>hidden tree</span>';</script>"
- }
- "poison" => {
- "<script>const real=Element.prototype.getBoundingClientRect;Element.prototype.getBoundingClientRect=function(){const r=real.call(this);return this.id==='art'?new DOMRect(r.x+100,r.y,r.width,r.height):r;};</script>"
- }
- "state-probe" => {
- "<style>body[data-inspector] #art{display:none}</style><script>setInterval(()=>{if(Object.getOwnPropertyNames(window).some(k=>k.startsWith('__impeccable_capture_')))document.body.dataset.inspector='found';},0);</script>"
- }
- "lazy" => {
- "<img loading=lazy src=/lazy.png style='position:absolute;top:10000px;width:80px;height:80px'>"
- }
- "canvas" => {
- "<canvas style='position:absolute;left:20px;top:20px;width:80px;height:80px'></canvas>"
- }
- "footer-trap" => {
- "<img src='/art.png' style='position:absolute;top:500px;left:20px;width:80px;height:80px'>"
- }
- "mutating" => {
- "<script>new MutationObserver(()=>document.body.dataset.touched='yes').observe(document.querySelector('#art'),{attributes:true});</script>"
- }
- "ambiguous" => {
- "<script>fetch('/art.png',{cache:'no-store'}).then(r=>r.arrayBuffer()).then(()=>document.body.dataset.fetched='yes');</script>"
- }
- "rotated-overlap" => "<style>#art{transform:rotate(-2.3deg);box-shadow:0 1px 4px #0005;border-radius:3.7px}#wrap::before{content:'';position:absolute;inset:-10.3px;background:url(/art.png) center/cover;opacity:.3}</style>",
- "transition" => "<style>#art{transition:object-position 100ms linear}</style>",
- "animated" => {
- "<style>@keyframes slide{to{transform:translateX(20px)}}#wrap{animation:slide 2s infinite alternate}</style>"
- }
- _ => "",
+ let mode = path.trim_start_matches('/');
+ let parent = match mode {
+ "hidden" => "visibility:hidden",
+ "opacity" | "pseudo-hidden" => "opacity:0",
+ "clip" => "clip-path:inset(100%)",
+ _ => "",
+ };
+ let position = match mode {
+ "shift" => "left:70px",
+ "footer" => "top:500px",
+ _ => "",
+ };
+ let img = if mode == "pseudo-url-only" {
+ "<div id=art style='position:relative;width:80px;height:80px'></div><style>#art::before{content:'';position:absolute;inset:0;background:url(/art.png) center/cover}</style>"
+ } else if mode.starts_with("pseudo-") && mode != "pseudo-neighbor" {
+ "<div id=art style='position:relative;width:80px;height:80px'></div><style>#art::before{content:'';position:absolute;inset:0;background-image:linear-gradient(transparent,transparent),url(/art.png);background-size:cover}</style>"
+ } else if mode == "layered-duplicate" {
+ "<div id=art style='width:80px;height:80px;background-image:url(/art.png),url(/art.png);background-size:cover'></div>"
+ } else if mode == "decoration" {
+ "<img id='art' width='80' height='80' src='/transparent.png' style='background:red;box-shadow:0 0 4px blue'>"
+ } else if mode == "background" {
+ "<div id='art' style='width:80px;height:80px;background:url(/art.png) center/cover'></div>"
+ } else if mode == "wrong" || mode == "footer-trap" {
+ "<img id='art' width='80' height='80' src='/collision/art.png'>"
+ } else {
+ "<img id='art' width='80' height='80' src='/art.png'>"
+ };
+ let cover = if mode == "duplicate" {
+ "<img src=/art.png style='position:absolute;inset:0;width:80px;height:80px'>"
+ } else if mode == "covered" || mode == "pseudo-covered" {
+ "<div style='position:absolute;inset:0;background:white'></div>"
+ } else {
+ ""
+ };
+ let extra = match mode {
+ "many-text-pseudos" => "<div id=text-only style='position:absolute;top:500px'></div><style>.marker::before,.marker::after{content:'x'}</style><script>for(let i=0;i<300;i++){const el=document.createElement('span');el.className='marker';document.querySelector('#text-only').append(el)}</script>",
+ "pseudo-specificity" => "<style>#art#art#art::before{background-image:url(/art.png)!important}</style>",
+ "pseudo-mutating" => "<script>setInterval(()=>{if(getComputedStyle(document.querySelector('#art'),'::before').backgroundImage.includes('none'))document.body.dataset.touched='yes'},0)</script>",
+ "pseudo-neighbor" => {
+ "<style>#art::before{content:''}</style><div style='position:absolute;left:20px;top:20px;width:80px;height:20px' class='ribbon'></div><style>.ribbon::before{content:'';position:absolute;inset:0;background-image:linear-gradient(white,white)}</style>"
+ }
+ "canvas-cover" => {
+ "<canvas id='cover' width='80' height='80' style='position:absolute;left:20px;top:20px;width:80px;height:80px'></canvas><script>const c=document.querySelector('#cover').getContext('2d');c.fillStyle='blue';c.fillRect(0,0,80,80)</script>"
+ }
+ "canvas-only" => {
+ "<canvas id='cover' width='80' height='80' style='position:absolute;left:20px;top:20px;width:80px;height:80px'></canvas><script>document.querySelector('#art').remove();const i=new Image();i.onload=()=>document.querySelector('#cover').getContext('2d').drawImage(i,0,0,80,80);i.src='/art.png'</script>"
+ }
+ "tiny-token" => "<style>#art{width:1px!important;height:1px!important}</style>",
+ "many" => {
+ "<script>for(let i=0;i<17;i++){const el=document.querySelector('#art').cloneNode(true);el.style.cssText='position:absolute;left:20px;top:20px';document.body.append(el);}</script>"
+ }
+ "closed-shadow" => {
+ "<div id=shadow style='position:absolute;left:20px;top:20px;width:80px;height:80px'></div><script>document.querySelector('#shadow').attachShadow({mode:'closed'}).innerHTML='<span>hidden tree</span>';</script>"
+ }
+ "poison" => {
+ "<script>const real=Element.prototype.getBoundingClientRect;Element.prototype.getBoundingClientRect=function(){const r=real.call(this);return this.id==='art'?new DOMRect(r.x+100,r.y,r.width,r.height):r;};</script>"
+ }
+ "state-probe" => {
+ "<style>body[data-inspector] #art{display:none}</style><script>setInterval(()=>{if(Object.getOwnPropertyNames(window).some(k=>k.startsWith('__impeccable_capture_')))document.body.dataset.inspector='found';},0);</script>"
+ }
+ "lazy" => {
+ "<img loading=lazy src=/lazy.png style='position:absolute;top:10000px;width:80px;height:80px'>"
+ }
+ "canvas" => {
+ "<canvas style='position:absolute;left:20px;top:20px;width:80px;height:80px'></canvas>"
+ }
+ "footer-trap" => {
+ "<img src='/art.png' style='position:absolute;top:500px;left:20px;width:80px;height:80px'>"
+ }
+ "mutating" => {
+ "<script>new MutationObserver(()=>document.body.dataset.touched='yes').observe(document.querySelector('#art'),{attributes:true});</script>"
+ }
+ "ambiguous" => {
+ "<script>fetch('/art.png',{cache:'no-store'}).then(r=>r.arrayBuffer()).then(()=>document.body.dataset.fetched='yes');</script>"
+ }
+ "rotated-overlap" => "<style>#art{transform:rotate(-2.3deg);box-shadow:0 1px 4px #0005;border-radius:3.7px}#wrap::before{content:'';position:absolute;inset:-10.3px;background:url(/art.png) center/cover;opacity:.3}</style>",
+ "transition" => "<style>#art{transition:object-position 100ms linear}</style>",
+ "animated" => {
+ "<style>@keyframes slide{to{transform:translateX(20px)}}#wrap{animation:slide 2s infinite alternate}</style>"
+ }
+ _ => "",
+ };
+ let html = format!(
+ "<!doctype html><style>body{{margin:0;background:white}}#wrap{{position:absolute;left:20px;top:20px;width:80px;height:80px}}</style><div id='wrap' style='{parent};{position}'>{img}{cover}</div>{extra}"
+ );
+ ("text/html", html.into_bytes())
};
- let html = format!(
- "<!doctype html><style>body{{margin:0;background:white}}#wrap{{position:absolute;left:20px;top:20px;width:80px;height:80px}}</style><div id='wrap' style='{parent};{position}'>{img}{cover}</div>{extra}"
+ let _ = write!(
+ stream,
+ "HTTP/1.1 200 OK\r\nContent-Type: {mime}\r\nContent-Length: {}\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n",
+ body.len()
);
- ("text/html", html.into_bytes())
- };
- let _ = write!(
- stream,
- "HTTP/1.1 200 OK\r\nContent-Type: {mime}\r\nContent-Length: {}\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n",
- body.len()
- );
- let _ = stream.write_all(&body);
+ let _ = stream.write_all(&body);
+ });
}
});
let mut renderer = CdpAssetRenderer::from_process_env();
diff --git a/crates/cli/tests/capture_snapshot.rs b/crates/cli/tests/capture_snapshot.rs
index ba4e57e21..8d7d1dea8 100644
--- a/crates/cli/tests/capture_snapshot.rs
+++ b/crates/cli/tests/capture_snapshot.rs
@@ -475,3 +475,45 @@ fn viewport_capture_does_not_switch_responsive_picture_sources() {
);
}
}
+
+/// Chrome opens sockets it leaves idle and writes some requests seconds after
+/// connecting. Neither may hold up another request or lose its own, and
+/// dropping the server ends every connection it still holds.
+#[test]
+fn snapshot_server_serves_around_idle_and_late_connections_and_closes_them_on_drop() {
+ use std::{
+ io::{Read, Write},
+ net::TcpStream,
+ sync::Arc,
+ time::{Duration, Instant},
+ };
+ let f = Fixture::new();
+ let snapshot = Arc::new(HtmlSnapshot::freeze(f.selection()).unwrap());
+ let server = snapshot.serve().unwrap();
+ let url = server.entry_url();
+ let host = url.strip_prefix("http://").unwrap().split('/').next().unwrap().to_string();
+ let get = |stream: &mut TcpStream| {
+ stream.set_read_timeout(Some(Duration::from_secs(10))).unwrap();
+ write!(stream, "GET /index.html HTTP/1.1\r\nHost: {host}\r\n\r\n").unwrap();
+ let mut response = Vec::new();
+ stream.read_to_end(&mut response).unwrap();
+ String::from_utf8_lossy(&response).into_owned()
+ };
+ // Accepted first and never written to: a serial server would answer the
+ // next connection only after giving up on this one.
+ let mut idle = TcpStream::connect(&host).unwrap();
+ std::thread::sleep(Duration::from_millis(50));
+ let started = Instant::now();
+ assert!(get(&mut TcpStream::connect(&host).unwrap()).starts_with("HTTP/1.1 200 OK"));
+ assert!(started.elapsed() < Duration::from_millis(1500), "an idle connection held up a request");
+ // Connected now, written later than the old 2 s idle limit.
+ let mut late = TcpStream::connect(&host).unwrap();
+ std::thread::sleep(Duration::from_millis(2500));
+ assert!(get(&mut late).starts_with("HTTP/1.1 200 OK"), "a late request lost its connection");
+ drop(server);
+ idle.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
+ let closed = Instant::now();
+ let mut buf = [0u8; 16];
+ assert!(matches!(idle.read(&mut buf), Ok(0) | Err(_)));
+ assert!(closed.elapsed() < Duration::from_secs(4), "dropping the server left a connection open");
+}
diff --git a/crates/context/src/component_review/tests.rs b/crates/context/src/component_review/tests.rs
index 151c0b8bf..a2e946f77 100644
--- a/crates/context/src/component_review/tests.rs
+++ b/crates/context/src/component_review/tests.rs
@@ -903,7 +903,12 @@ fn serve_exits_after_submission_or_idle_and_removes_its_service_record() {
assert!(!dir.join("service.json").exists());
let state = store::read(&dir.join("current.json")).unwrap();
let rx = serve_in_thread(&dir, 60_000);
- std::thread::sleep(std::time::Duration::from_millis(200));
+ // Wait for the record rather than a fixed delay: a loaded runner can take
+ // longer than any fixed sleep to bind and write it.
+ let started = std::time::Instant::now();
+ while !dir.join("service.json").exists() && started.elapsed() < std::time::Duration::from_secs(10) {
+ std::thread::sleep(std::time::Duration::from_millis(20));
+ }
assert!(dir.join("service.json").exists());
store::submit(&dir, &approve(&state)).unwrap();
assert_eq!(rx.recv_timeout(std::time::Duration::from_secs(5)).unwrap(), Ok(0));
diff --git a/crates/skills/tests/hook_manifest_tests.rs b/crates/skills/tests/hook_manifest_tests.rs
index dc3c5b0ec..d9ac1b6c5 100644
--- a/crates/skills/tests/hook_manifest_tests.rs
+++ b/crates/skills/tests/hook_manifest_tests.rs
@@ -273,8 +273,10 @@ fn windows_form_runs_the_shim_in_each_harness_shell() {
Err(e) => panic!("{at}: {e}"),
};
let _ = child.stdin.take().unwrap().write_all(b"{\"probe\":1}\n");
- // A shell that kept stdin from the shim would leave it reading forever.
- let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
+ // A shell that kept stdin from the shim would leave it reading
+ // forever. The bound only has to tell that from a slow start:
+ // Windows PowerShell has taken over 30 s to start on a cold runner.
+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(120);
let code = loop {
if let Some(status) = child.try_wait().unwrap() {
break status.code();
diff --git a/docs/CLI-CONTRACT.md b/docs/CLI-CONTRACT.md
index 23795f548..cd13a708d 100644
--- a/docs/CLI-CONTRACT.md
+++ b/docs/CLI-CONTRACT.md
@@ -1984,7 +1984,7 @@ Assembly acceptance closes component and assembly reviews for this journey. The
The hero gate uses the same evidence. When the native hero capture carries an approved first-viewport review, `build-phase` compares the approved screenshot with the current hero frame; a `text`, `control` or `chrome` region that still matches it (verdict match or drift, structure at least 75%) has its contradicted verdict, control drift and ink-box readings, its type readings and a `missing` verdict against the comp turned into advisories marked `accepted in the first-viewport review` (a missing one reads `region <id> is missing (...): the comp shows material the build does not; the first viewport the user accepted lacks it too, so the acceptance covers it`). The user judged that first viewport by eye without the region, so its absence is settled; a region the approved screenshot shows and the current capture lacks does not render as accepted and still blocks as missing, so a region removed after the acceptance blocks. When the approved screenshot and the current hero frame agree as a whole (overall at least 95%, no region missing or contradicted), the user has accepted this first viewport: every non-material reason (the overall bar, the palette check, every numeric reading) becomes an advisory marked `first viewport accepted`, led by an advisory that says the user accepted it. Only material vetoes still block: missing or unreferenced plates, inline SVG illustrations, organic clips, clipped plates, invented ink, a wrong capture size, and the native rendered-presence checks. A missing plate (or image or texture) region that the approved screenshot lacks too cannot be cleared by restoring what the user accepted, so its reason adds the question for the user: place the plate at its box (the page then no longer matches the accepted screenshot and the readings apply again), or keep the first viewport without it, which downgrades the comp and is recorded only by quoting their words in `advance --force --reason` (the reason gives an example `force` accepts). Force closes the whole gate, so the force route is offered only when nothing but such plates blocks; while any other reason blocks, the reason says to clear the others first and ask once the plate is all that blocks. Only `plate`, `image` and `texture` regions get this question; a missing `band` keeps the plain missing reason. The hero report records `humanHeroReview` with the proof, that comparison, `acceptedRegions` and `viewportAccepted`. The responsive gate (and so the finish recheck) applies the same rule to its desktop comparison: with the accepted viewport still rendered at desktop width, the desktop score and contradicted regions are advisories and missing or displaced regions block, except a `text`, `control` or `chrome` region that renders as accepted in the comparison below: the accepted first viewport lacks it too, so its missing or displaced reason becomes an advisory marked `accepted in the first-viewport review` ending `the first viewport the user accepted lacks it too, so the acceptance covers it`, and its id is listed in `humanTextReview.acceptedRegions`. There the approved screenshot (captured at the comp's size) is resampled once, by the engine's area resize, to the desktop frame's own size and compared with the desktop capture at that size, so the capture under test is never resampled; the comparison is recorded as `humanTextReview.comparison` with `compSize` (the frame size) and `referenceSize` (the screenshot's own). The 95% bar holds at that scale, measured on a real accepted page (a proportional layout with one 16px type floor, its clock pinned): rendered at 1440 it scores 98.5% against its approved 1536 screenshot, at 1600 97.1%; at 1280, where the floor reflows the menu, 89.9%; the capture that stalled a run after a menu change and a clock change, 83.3%. Comparing the other way (the capture upscaled to the comp's width) scored the same faithful 1440 render 97.0% and a pure resample of the approved screenshot 96.4%, about one point of margin, which is why the frame-size comparison is used. A contradicted `text` or `control` region that still renders as accepted in that comparison (match or drift, structure at least 75%; the carry set covers `text`, `control` and `chrome` regions as at the hero, but a contradicted `chrome` region never blocks at desktop width, so only text and control acceptances show here) is an advisory marked `accepted in the first-viewport review`, and its id is listed in `humanTextReview.acceptedRegions`. When the current capture no longer matches the approved screenshot, the acceptance lapses: the gate says the hero (or desktop) capture no longer matches the first viewport the user accepted, names the regions that changed since the acceptance (those that no longer render as accepted, at most six and a count of the rest; when none does, the three furthest from it), and asks to restore what the user accepted, saying the readings apply until then. Under the overall bar this reason replaces the raw overall-bar reason; above it (and at the hero, whatever the other reasons are), it leads the other blocking reasons, or, when nothing else blocks, opens the advisories as `(advisory) the ... capture no longer matches ...`, so a lapsed acceptance is always said. It does not offer a new first-viewport review: once one is accepted the review store returns that session, so a new round cannot open. The raw score is kept as a `(measured)` advisory. After three consecutive failed hero attempts the refusal leads with an instruction to present the first-viewport review instead of iterating further; when a first viewport is already accepted (locally, or in a session the host names) it instead says the review is closed and asks to restore what the user accepted, naming what stays advisory while the capture matches (including a text, control or chrome region the accepted screenshot also lacks) and that a plate the accepted screenshot itself lacks is a question for the user, spelled out in its reason.
-Native entry capture covers first viewports with no raster region. When the bound spec names no `raster` region (a code-led Operate screen, for example), the renderer has no artwork to intervene on, so it captures each frame (`hero`, or `desktop` and `mobile`) the way the assembled-page review captures the page it shows the user: pinned local scripts, verified network dependencies, the primary-font check, and two identical viewport screenshots. The page's inputs come from the same frozen snapshot that bound the spec and comp; nothing is read twice. What the page is served follows the review: when `.impeccable/review/hero.json` is a `hero` manifest with one page component whose preview is this entry, the page gets exactly that entry plus the component's declared `dependencies` (a declared path outside the static inventory is refused), so a file the review would not serve fails here as an undeclared dependency too. Before any review manifest names the entry, the page gets the static inventory (every static browser file outside hidden directories and `node_modules`). In both cases the bound spec and comp are never served. The capture is refused when the page requests the comp, or when a file the page loads is a byte copy of the comp or of the approved review screenshot, or is an HTML, CSS, JS or SVG file that inlines either as a base64 data URI (whitespace inside the URI is ignored). These checks run on the files the page actually loads under both policies, so a served file the page never loads (an unused backup of the comp, or one listed in the manifest's `dependencies`) does not block the capture. Byte checks cannot see a re-encoded copy, so the spec itself is the backstop: it declares every raster in the first viewport as a raster region, and this spec declares none. Each frame therefore measures the area images paint, as a union on a 4px grid (`img`, `video`, `input type=image`, SVG `image`, and any element or `::before`/`::after` painting a `url()` background, border, mask, list marker or generated content). Gradients and same-document fragment references (`url(#id)`, an SVG mask, pattern, gradient, clip path, filter, marker or symbol) are code and do not count, unless the definition they name holds raster content: an `image`, `feImage`, `img`, `video` or `input type=image` anywhere inside it, an `href` or `url()` that leaves the document, or a fragment reference to another definition that holds raster content. An `image` inside a definition has no rendered box, so the element that references such a definition counts instead: through `mask`/`mask-image`, `clip-path`, `fill` or `use` at its box (a `use` also through the `fill` and `stroke` it passes to its clones), through `stroke` at its box widened by half the stroke width on screen (the transform's largest scale, or the stroke's own width for `vector-effect: non-scaling-stroke`), through `filter` at the filter region (the whole viewport when a region length uses a unit other than plain numbers, `px` in user space or percentages in bounding-box units, and the outermost `svg` box for an element inside an `svg`), and through a marker at the outermost `svg` box. A `::before` or `::after` with such a filter also counts its filter region. A no-repeat background with an explicit pixel size counts at that size, any other at its box; `object-fit: contain` or `scale-down` counts the letterboxed picture, not the element box. Each box is clipped by the ancestors on its containing-block chain that clip (non-visible overflow, or `contain: paint`), so an absolutely positioned or fixed image is not clipped by a wrapper it escapes; an element that is hidden, or under an ancestor with opacity 0, paints nothing. The result is clipped to the viewport, and the capture is refused when images paint 15% or more of it. The refusal names the largest images and says the spec declares no raster region, so a large image contradicts it: declare it as a raster region or remove it and draw that area in code. 15% sits well above logos, avatars and icons (a 200x60 logo is about 1% of a 1440x900 viewport, twelve 40px avatars under 2%) and well below any image that could carry the comparison; the measurement is recorded per frame as `rasterCoverage` in `frameProofs`. The manifest's bytes are bound to the capture like its other inputs. The frames carry no region receipts, so no rendered-presence or placement check runs; the hero and responsive gates read the frames with the same comparison and region readings as any other capture. `inputs.json` (and `nativeCapture.inputs` in the report) records `"captureMethod": "assembled-page-viewport"`, `dependencyPolicy` (`hero-review-manifest` or `static-inventory`), `servedToPage`, the browser version, a `frameProofs` entry per frame and, with a manifest, `reviewManifestSha256`; the report's `nativeCapture.integrityScope` reads `assembled-page viewport from frozen inputs; the comp and approved screenshots are never served to the page; no raster presence or placement check (no raster region); existing visual scores unchanged` (the capture's own `inputs.integrityScope` adds that images cover under 15% of each frame), with no `framePolicy`. The review's other limits apply: a page with a `canvas`, `iframe`, `object` or `embed`, a running animation, an external dependency, or a missing primary font is refused with that reason. Because the gate's frame and the reviewed screenshot come from one capture method, an accepted first-viewport review of a code-only page binds to the current capture like any other and ends the numeric fight as described above. Specs with at least one raster region keep the raster capture unchanged.
+Native entry capture covers first viewports with no raster region. When the bound spec names no `raster` region (a code-led Operate screen, for example), the renderer has no artwork to intervene on, so it captures each frame (`hero`, or `desktop` and `mobile`) the way the assembled-page review captures the page it shows the user: pinned local scripts, verified network dependencies, the primary-font check, and two identical viewport screenshots. The page's inputs come from the same frozen snapshot that bound the spec and comp; nothing is read twice. What the page is served follows the review: when `.impeccable/review/hero.json` is a `hero` manifest with one page component whose preview is this entry, the page gets exactly that entry plus the component's declared `dependencies` (a declared path outside the static inventory is refused), so a file the review would not serve fails here as an undeclared dependency too. Before any review manifest names the entry, the page gets the static inventory (every static browser file outside hidden directories and `node_modules`). In both cases the bound spec and comp are never served. The capture is refused when the page requests the comp, or when a file the page loads is a byte copy of the comp or of the approved review screenshot, or is an HTML, CSS, JS or SVG file that inlines either as a base64 data URI (whitespace inside the URI is ignored). These checks run on the files the page actually loads under both policies, so a served file the page never loads (an unused backup of the comp, or one listed in the manifest's `dependencies`) does not block the capture. The browser's own tab-icon request (Chrome fetches `/favicon.ico`, or a `<link rel=icon>` target, after the load event) is not a page load: it paints nothing in the viewport, so it is neither checked as a dependency nor counted as the page changing during capture. Byte checks cannot see a re-encoded copy, so the spec itself is the backstop: it declares every raster in the first viewport as a raster region, and this spec declares none. Each frame therefore measures the area images paint, as a union on a 4px grid (`img`, `video`, `input type=image`, SVG `image`, and any element or `::before`/`::after` painting a `url()` background, border, mask, list marker or generated content). Gradients and same-document fragment references (`url(#id)`, an SVG mask, pattern, gradient, clip path, filter, marker or symbol) are code and do not count, unless the definition they name holds raster content: an `image`, `feImage`, `img`, `video` or `input type=image` anywhere inside it, an `href` or `url()` that leaves the document, or a fragment reference to another definition that holds raster content. An `image` inside a definition has no rendered box, so the element that references such a definition counts instead: through `mask`/`mask-image`, `clip-path`, `fill` or `use` at its box (a `use` also through the `fill` and `stroke` it passes to its clones), through `stroke` at its box widened by half the stroke width on screen (the transform's largest scale, or the stroke's own width for `vector-effect: non-scaling-stroke`), through `filter` at the filter region (the whole viewport when a region length uses a unit other than plain numbers, `px` in user space or percentages in bounding-box units, and the outermost `svg` box for an element inside an `svg`), and through a marker at the outermost `svg` box. A `::before` or `::after` with such a filter also counts its filter region. A no-repeat background with an explicit pixel size counts at that size, any other at its box; `object-fit: contain` or `scale-down` counts the letterboxed picture, not the element box. Each box is clipped by the ancestors on its containing-block chain that clip (non-visible overflow, or `contain: paint`), so an absolutely positioned or fixed image is not clipped by a wrapper it escapes; an element that is hidden, or under an ancestor with opacity 0, paints nothing. The result is clipped to the viewport, and the capture is refused when images paint 15% or more of it. The refusal names the largest images and says the spec declares no raster region, so a large image contradicts it: declare it as a raster region or remove it and draw that area in code. 15% sits well above logos, avatars and icons (a 200x60 logo is about 1% of a 1440x900 viewport, twelve 40px avatars under 2%) and well below any image that could carry the comparison; the measurement is recorded per frame as `rasterCoverage` in `frameProofs`. The manifest's bytes are bound to the capture like its other inputs. The frames carry no region receipts, so no rendered-presence or placement check runs; the hero and responsive gates read the frames with the same comparison and region readings as any other capture. `inputs.json` (and `nativeCapture.inputs` in the report) records `"captureMethod": "assembled-page-viewport"`, `dependencyPolicy` (`hero-review-manifest` or `static-inventory`), `servedToPage`, the browser version, a `frameProofs` entry per frame and, with a manifest, `reviewManifestSha256`; the report's `nativeCapture.integrityScope` reads `assembled-page viewport from frozen inputs; the comp and approved screenshots are never served to the page; no raster presence or placement check (no raster region); existing visual scores unchanged` (the capture's own `inputs.integrityScope` adds that images cover under 15% of each frame), with no `framePolicy`. The review's other limits apply: a page with a `canvas`, `iframe`, `object` or `embed`, a running animation, an external dependency, or a missing primary font is refused with that reason. Because the gate's frame and the reviewed screenshot come from one capture method, an accepted first-viewport review of a code-only page binds to the current capture like any other and ends the numeric fight as described above. Specs with at least one raster region keep the raster capture unchanged.
Every native capture pins the page's clock. Before navigation the browser installs a script on every new document that starts `new Date()`, `Date()`, `Date.now()` and an argument-less `Intl.DateTimeFormat` `format` / `formatToParts` at a pinned instant and lets them advance in real time (`Date.prototype.constructor` is the shim, so `new Date().constructor === Date` holds), so code that measures elapsed time still sees time pass. A component-review round pins one instant for all its views and records it in each view's proof as `clock: {pinnedEpochMs, policy}`. An entry capture pins every frame to one instant, recorded in `inputs.json` as `clock: {pinnedEpochMs, source, policy}`: when the verified approved review carries a pinned instant, the capture uses it (`source: "approved-review"`, and the approval proof carries `pinnedClockMs`), so a page that prints the time or the day renders the state the user accepted; otherwise the capture's start (`source: "capture-start"`). Approvals recorded before pinning carry no instant and are compared as before.