Files
capri-core-rust/crates/capri-computer/src/browser.rs
T

274 lines
15 KiB
Rust

//! Goal predicates and browser page verification (ported from `browser-search-state.mjs`).
//! Observations (`view`) use Capri's JSON shape: `{window:{windowId,untrustedTitle,modal,fullscreen}, targets:[...]}`.
use std::sync::LazyLock;
use regex::Regex;
use serde_json::{json, Value};
use unicode_normalization::UnicodeNormalization;
use url::Url;
macro_rules! re {
($s:expr) => {{
static R: LazyLock<Regex> = LazyLock::new(|| Regex::new($s).unwrap());
&*R
}};
}
pub fn requires_fullscreen(goal: &str) -> bool {
let cleaned = re!(r"(?i)\b(?:do not|don't|never|without)\b[^.!?\n]{0,50}\bfull[ -]?screen\b|не\s+[^.!?\n]{0,40}(?:полноэкран\p{L}*|на\s+весь\s+экран)").replace_all(goal, "");
re!(r"(?i)\bfull[ -]?screen\b|на\s+весь\s+экран|полноэкран").is_match(&cleaned)
}
pub fn requires_page_search(goal: &str) -> bool {
let v = re!(r"(?i)\b(?:do not|don't|never|not|without)\b[^.!?\n]{0,60}\baddress\s+bar\b|не\s+[^.!?\n]{0,50}адресн\p{L}*\s+строк\p{L}*").replace_all(goal, "");
re!(r"(?i)\bsearch\s+(?:bar|box|field)\b|(?:строк\p{L}*|пол\p{L}*)\s+поиска").is_match(&v) && !re!(r"(?i)\baddress\s+bar\b|адресн\p{L}*\s+строк").is_match(&v)
}
pub fn draft_only(goal: &str) -> bool {
re!(r"(?i)\b(?:do not|don't|never|without)\s+(?:press(?:ing)?\s+enter|submit(?:ting)?|navigat\w*)|не\s+(?:нажимай\w*\s+(?:enter|ввод)|отправляй\w*|переходи\w*)").is_match(goal)
}
fn mentions_site(goal: &str) -> bool {
re!(r"(?i)\b(?:on|in|at|go\s+to|visit|open)\s+(?:the\s+)?(?:netflix|youtube)\b|на\s+(?:нетфликсе|ютубе|youtube|netflix)").is_match(goal)
}
/// A search that belongs to a site's own search field (Netflix, YouTube), not Google.
pub fn site_search(goal: &str) -> bool {
let clauses: Vec<&str> = re!(r"(?i)[.!?;]|\b(?:and then|then|after that|afterwards)\b|\s+(?:затем|потом)\s+").split(goal).collect();
let strip = |c: &str| re!(r"(?i)\bgoogle chrome\b").replace_all(c, "").into_owned();
let Some(i) = clauses.iter().position(|c| re!(r"(?i)\b(?:search|find|google)\b|найди|поищи|погугли").is_match(&strip(c))) else { return mentions_site(goal) };
if re!(r"(?i)\b(?:official\s+[^.!?]{0,100}\b(?:site|website)|google)\b|официальн\p{L}*\s+сайт|погугли").is_match(&strip(clauses[i])) {
return false;
}
clauses[..=i].iter().any(|c| mentions_site(c))
}
/// Navigation intent ("go to", "visit"...) for rewriting an address draft into `open_url`.
pub fn navigation_goal(goal: &str) -> bool {
re!(r"(?i)\b(?:go to|navigate|visit|watch)\b|перейди|открой\s+сайт").is_match(goal)
}
/// "google <x>" / "search the web" (not "google chrome").
pub fn web_search_goal(goal: &str) -> bool {
goal.to_lowercase().contains("погугли")
|| re!(r"(?i)\b(google|search\s+the\s+web)\s+(\S+)").captures_iter(goal).any(|c| !(c[1].eq_ignore_ascii_case("google") && c[2].trim_end_matches(|ch: char| !ch.is_alphanumeric()).eq_ignore_ascii_case("chrome")))
}
/// Modal on screen requires the goal to ask for a dialog; fullscreen goals need fullscreen.
pub fn display_requirement_met(goal: &str, view: &Value) -> bool {
if view["window"]["modal"] == true && !re!(r"(?i)\b(?:open|show|fill|type|enter|leave)\b[^.!?]{0,120}\b(?:dialog|picker|menu)\b|(?:открой|покажи|заполни|введи|оставь)[^.!?]{0,100}(?:диалог|меню|окн)").is_match(goal) {
return false;
}
if !requires_fullscreen(goal) {
return true;
}
let page = page_state(view);
view["window"]["fullscreen"] == true && page.as_ref().is_none_or(|p| p["results"] != "images" || p["imageViewer"] == true)
}
fn address(view: &Value) -> Option<&Value> {
view["targets"].as_array()?.iter().find(|t| t["browserAddress"] == true)
}
fn parse_address(raw: &str) -> Option<Url> {
let with_scheme = if re!(r"(?i)^[a-z]+://").is_match(raw) { raw.to_string() } else { format!("https://{raw}") };
Url::parse(&with_scheme).ok()
}
fn norm(s: &str) -> String {
s.nfkc().collect::<String>().to_lowercase().split_whitespace().collect::<Vec<_>>().join(" ")
}
fn network_error(view: &Value) -> bool {
view["targets"].as_array().into_iter().flatten().any(|t| t["untrustedLabel"].as_str().is_some_and(|l| re!(r"^ERR_[A-Z_]+$").is_match(l)))
}
fn google(u: &Url) -> bool {
u.host_str().is_some_and(|h| h.eq_ignore_ascii_case("google.com") || h.eq_ignore_ascii_case("www.google.com"))
}
/// `ready | loading | challenge | network | window_changed` for a submitted search.
pub fn search_state(view: &Value, window_id: &str, text: &str) -> &'static str {
if view["window"]["windowId"].as_str() != Some(window_id) {
return "window_changed";
}
let Some(a) = address(view) else { return "loading" };
let Some(url) = parse_address(a["untrustedValue"].as_str().unwrap_or("")) else { return "loading" };
if google(&url) && url.path().starts_with("/sorry/") {
return "challenge";
}
if network_error(view) {
return "network";
}
let title = norm(view["window"]["untrustedTitle"].as_str().unwrap_or(""));
let q = url.query_pairs().find(|(k, _)| k == "q").map(|(_, v)| v.into_owned());
if google(&url) && url.path() == "/search" && q.as_deref().map(norm) == Some(norm(text)) && a["focused"] != true && !re!(r"(?i)^https?:").is_match(&title) && title.contains(&norm(text)) {
"ready"
} else {
"loading"
}
}
/// `ready | loading | challenge | network | sign_in | profile | window_changed` for an opened URL.
pub fn navigation_state(view: &Value, window_id: &str, requested: &str) -> &'static str {
if view["window"]["windowId"].as_str() != Some(window_id) {
return "window_changed";
}
let (Some(a), Ok(req)) = (address(view), Url::parse(requested)) else { return "loading" };
let Some(actual) = parse_address(a["untrustedValue"].as_str().unwrap_or("")) else { return "loading" };
if google(&actual) && actual.path().starts_with("/sorry/") {
return "challenge";
}
if network_error(view) {
return "network";
}
let host = |u: &Url| u.host_str().unwrap_or("").to_lowercase().trim_start_matches("www.").to_string();
let focused = a["focused"] == true;
let netflix = req.scheme() == "https" && host(&req) == "netflix.com" && actual.scheme() == "https" && host(&actual) == "netflix.com" && actual.port() == req.port() && !focused;
let np = re!(r"(?i)^/[a-z]{2}(?:-[a-z]{2})?/").replace(actual.path(), "/").trim_end_matches('/').to_string();
let np = if np.is_empty() { "/".to_string() } else { np };
if netflix && re!(r"(?i)^/(?:login|signup)(?:/|$)").is_match(&np) {
return "sign_in";
}
if netflix && re!(r"(?i)^/(?:profiles|ManageProfiles)(?:/|$)").is_match(&np) {
return "profile";
}
let title_id = re!(r"^/title/(\d+)$").captures(req.path()).map(|c| c[1].to_string());
let same_netflix = netflix && ((req.path() == "/" && req.query().is_none() && np == "/browse") || title_id.as_ref().is_some_and(|id| np == req.path() || (np == "/browse" && actual.query_pairs().any(|(k, v)| k == "jbv" && v == id.as_str()))));
let series = req.host_str() == Some("www.cyberpunk.net") && req.path() == "/en/edgerunners2" && re!(r"(?i)^/[a-z]{2}(?:-[a-z]{2})?/edgerunners2/?$").is_match(actual.path());
let title = view["window"]["untrustedTitle"].as_str().unwrap_or("");
let params_ok = req.query_pairs().all(|(k, v)| actual.query_pairs().any(|(k2, v2)| k2 == k && v2 == v));
if actual.scheme() == req.scheme() && actual.port() == req.port() && host(&actual) == host(&req) && (actual.path() == req.path() || same_netflix || series) && params_ok && !focused && !title.is_empty() && !re!(r"(?i)^(?:https?:|new tab\b|новая вкладка(?:\s|$))").is_match(title) {
"ready"
} else {
"loading"
}
}
/// Current results page: `{query, results: images|web, imageViewer?}`.
pub fn page_state(view: &Value) -> Option<Value> {
let raw = address(view)?["untrustedValue"].as_str()?.to_string();
let url = parse_address(&raw)?;
let q = url.query_pairs().find(|(k, _)| k == "q")?.1.into_owned();
if q.is_empty() || search_state(view, view["window"]["windowId"].as_str()?, &q) != "ready" {
return None;
}
let images = url.query_pairs().any(|(k, v)| (k == "udm" && v == "2") || (k == "tbm" && v == "isch"));
let mut v = json!({"source": "Current browser address and window title", "query": q, "results": if images { "images" } else { "web" }});
if re!(r"(?i)[?#&](?:imgrc|vhid|imgdii|vssid|sv)=").is_match(url.as_str()) {
v["imageViewer"] = json!(true);
}
Some(v)
}
/// A blocking dialog (modal, cookie consent) is actionable state, not a failed navigation.
pub fn navigation_obstacle(view: &Value) -> Option<&'static str> {
if view["window"]["modal"] == true {
return Some("modal");
}
let labels: Vec<&str> = view["targets"].as_array().into_iter().flatten().filter_map(|t| t["untrustedLabel"].as_str()).collect();
let choice = labels.iter().any(|l| re!(r"(?i)^(?:accept all|reject all|reject optional cookies|only necessary|necessary cookies only|i agree|принять все|отклонить все|только необходимые|tout accepter|tout refuser|alle akzeptieren|alle ablehnen|aceptar todo|rechazar todo|aceitar tudo|rejeitar tudo)$").is_match(l.trim()));
(choice && labels.iter().any(|l| re!(r"(?i)cookie|cookies|consent|файл\p{L}* cookie|конфиденциальност").is_match(l))).then_some("cookie_consent")
}
/// Same page ignoring `www.`, fragment, parameter order and Google query case/spacing.
pub fn same_navigation_url(a: &str, b: &str) -> bool {
let normalize = |s: &str| -> Option<String> {
let mut u = Url::parse(s).ok()?;
let host = u.host_str()?.to_lowercase();
let host = host.trim_start_matches("www.").to_string();
u.set_host(Some(&host)).ok()?;
u.set_fragment(None);
let google_search = host == "google.com" && u.path() == "/search";
let mut pairs: Vec<(String, String)> = u.query_pairs().map(|(k, v)| {
let q = google_search && k == "q";
(k.into_owned(), if q { norm(&v) } else { v.into_owned() })
}).collect();
pairs.sort();
if pairs.is_empty() {
u.set_query(None);
} else {
u.query_pairs_mut().clear().extend_pairs(pairs);
}
Some(u.to_string())
};
normalize(a).is_some_and(|x| Some(x) == normalize(b))
}
/// `evidenceKey`: NFKC, lower-case, without whitespace and quotes.
pub fn evidence_key(s: &str) -> String {
s.nfkc().collect::<String>().to_lowercase().chars().filter(|c| !c.is_whitespace() && !"\"'«»“”‘’".contains(*c)).collect()
}
/// Evidence must exist in the current observation (title, scene, any label/value).
pub fn evidence_exists(view: &Value, evidence: &str) -> bool {
if evidence.trim().chars().count() <= 1 {
return false;
}
let needle = evidence_key(&re!(r"\s*\[[^\]]{1,80}\]\s*$").replace(evidence, ""));
let mut hay: Vec<String> = vec![];
for k in ["/window/untrustedTitle", "/scene", "/application/summary", "/application/timeline/name"] {
if let Some(s) = view.pointer(k).and_then(Value::as_str) {
hay.push(s.into());
}
}
for t in view["targets"].as_array().into_iter().flatten() {
let (l, v) = (t["untrustedLabel"].as_str(), t["untrustedValue"].as_str());
hay.extend(l.map(String::from));
hay.extend(v.map(String::from));
if let Some(l) = l {
hay.push(format!("{l}: {}", v.unwrap_or("")));
}
}
hay.iter().any(|h| evidence_key(h).contains(&needle))
}
#[cfg(test)]
mod tests {
use super::*;
fn view(address: &str, title: &str, focused: bool) -> Value {
json!({"window": {"windowId": "7", "untrustedTitle": title}, "targets": [{"untrustedLabel": "Search or enter address", "untrustedValue": address, "browserAddress": true, "focused": focused}]})
}
#[test]
fn goals() {
assert!(requires_fullscreen("open an image and show it full screen") && !requires_fullscreen("do not go fullscreen"));
assert!(requires_page_search("type cats in the Google search bar") && !requires_page_search("use the address bar search field"));
assert!(draft_only("type hello but don't press enter") && !draft_only("search hello"));
assert!(site_search("open YouTube and search for lofi") && !site_search("google the official Netflix site"));
assert!(navigation_goal("go to https://example.org"));
assert!(web_search_goal("google blue roses in Chrome") && !web_search_goal("open google chrome"));
}
#[test]
fn page_states() {
let ready = view("https://www.google.com/search?q=Blue+roses", "blue roses - Google Search", false);
assert_eq!(search_state(&ready, "7", "blue roses"), "ready");
assert_eq!(search_state(&ready, "8", "blue roses"), "window_changed");
assert_eq!(search_state(&view("https://www.google.com/search?q=blue+roses", "blue roses", true), "7", "blue roses"), "loading", "address still focused");
assert_eq!(search_state(&view("https://www.google.com/sorry/index", "x", false), "7", "a"), "challenge");
assert_eq!(page_state(&view("google.com/search?q=cats&udm=2&imgrc=abc", "cats - Google Search", false)).unwrap()["imageViewer"], true);
assert_eq!(navigation_state(&view("netflix.com/fr/login", "Netflix", false), "7", "https://www.netflix.com/"), "sign_in");
assert_eq!(navigation_state(&view("www.netflix.com/browse", "Netflix", false), "7", "https://www.netflix.com/"), "ready");
assert_eq!(navigation_state(&view("https://example.org/a?x=1&y=2", "Example", false), "7", "https://example.org/a?y=2"), "ready");
assert_eq!(navigation_state(&view("https://example.org/a", "New tab", false), "7", "https://example.org/a"), "loading");
assert!(same_navigation_url("https://www.google.com/search?q=Blue%20Roses&hl=en#x", "https://google.com/search?hl=en&q=blue+roses"));
assert!(!same_navigation_url("https://a.org/x", "https://a.org/y"));
let modal = json!({"window": {"modal": true}, "targets": []});
assert_eq!(navigation_obstacle(&modal), Some("modal"));
let cookies = json!({"window": {}, "targets": [{"untrustedLabel": "Accept all"}, {"untrustedLabel": "We use cookies"}]});
assert_eq!(navigation_obstacle(&cookies), Some("cookie_consent"));
}
#[test]
fn evidence() {
let v = json!({"window": {"untrustedTitle": "Document 1 — Kate"}, "targets": [{"untrustedLabel": "Save", "untrustedValue": null}]});
assert!(evidence_exists(&v, "“Document 1 — Kate”"));
assert!(evidence_exists(&v, "Save [a1b2c3d4-ui-3]"), "decorated target ids are stripped");
assert!(!evidence_exists(&v, "Open") && !evidence_exists(&v, "S"));
assert!(!display_requirement_met("save it", &json!({"window": {"modal": true}})));
assert!(display_requirement_met("open the save dialog", &json!({"window": {"modal": true}})));
}
}