Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Browser: cited reads (browser_cite, quote → checked text-fragment link)
Lin (kwant bot)0dddb25e3ce8
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d540f59b..6f6a9e36 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -57,6 +57,11 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).the notification toggles. This is step 4 of Automation Discovery.### Changed+- **Bots cite what they read on the web, with links that open the page at the quote.** A bot passes+ the exact words (or a block id from its read) and kwant checks they are on the page once, word for+ word, and returns the quote, its address and a link that opens the page with it highlighted. A+ quote that isn't on the page, or is on it more than once, is refused with the reason, so a bot+ can't make one up. Bots are told to back web facts with these links. No model calls.- **Bots don't re-read a page that hasn't changed, and find controls on crowded pages.** When a botreads its browser page again and nothing changed since its last look, it gets a one-line"unchanged" instead of the whole page. On a page with more than 40 controls, the bot can say whatdiff --git a/docs/bot-browser.md b/docs/bot-browser.mdindex 91e17e72..e3d2a1b1 100644--- a/docs/bot-browser.md+++ b/docs/bot-browser.md@@ -66,8 +66,46 @@ come first, ties in page order. Ref numbers are the page's own, so a control pasclicks by its ref. `controls_note` says what was left out. Step answers (`/act`, `browser_act`)list the first 40 in page order.+## Citing what a bot read++A bot backs facts it read on the web with links that open the page at the words it quotes+(`#:~:text=` text fragments). It never writes the link itself: it passes the words, and kwant checks+them against the page open now (`sandbox::cite`, plain text matching, no model call).+- MCP: `browser_cite` with `text` (the exact words) or `block` (an id from a read with blocks). It+ only reads, so it is free in always-ask turns (`READ_ONLY_SELF_TOOLS`) and is a core tool.+- HTTP: `POST /api/sandbox/:id/cite` with `{"text": …}` or `{"block": …}`.++The answer is `{quote, url, link}`; `quote` is the page's own text and `url` the address it is on.+The words must be on the page word for word: runs of spaces and line breaks count as one space,+capitals count. They must be there exactly once, in whole words, in the page's rendered text+(`innerText`, up to 200,000 characters) or in a same-origin frame's, which is then the `url`.+Otherwise the call is refused with the reason (HTTP 422, a tool error): not on the page (with the+page's spelling when only the capitals differ), on it N times (quote more), starts or ends inside a+word. Nothing is quoted from the bot's own text.++The link: `text=start` for a quote of up to 300 characters on one line, else `text=start,end` with+its first and last five words. Every part is percent-encoded except letters, digits and `._~`, so+`-`, `,`, `&`, `%` and spaces in the words can't break the fragment. Browsers highlight the first+match, without case; `cite::resolve` mirrors that (more leniently: no word or block boundaries), and+when its first match isn't the quote, up to three words before and after it on the same line are+added as `prefix-,` and `,-suffix`. If that still doesn't single it out, the call is refused rather+than returning a link that highlights something else. An address with its own fragment+(`#/route`) keeps it: `#/route:~:text=…`.++Blocks: `browser_page` with `blocks: true` (HTTP `/page?blocks=1`) sends the page's lines as+`[b3-9f2a] text` (first 150, each cut at 300 characters) instead of `text`. The id is the line's+number and a hash of its text, so an id from an older read never cites a different block: if lines+moved it finds the block by its hash, and if it's gone the call is refused ("read it again"). A+read with blocks has its own `hash`, so "unchanged" (`since`, per-turn reads) only answers for the+same kind of read.++Limits: frames from other sites can't be read from the page, so their text can't be cited; a+browser's own matching follows the page's blocks, which `innerText` lines only approximate, so a+link can occasionally highlight nothing (it then opens at the top); pages that change text on load+or per visit can make a link miss later.+## Tests-`tests/browser_refs_test.rs`, `tests/browser_progress_test.rs` and `tests/browser_reads_test.rs` (real Chrome, skipped without one;-the `saucedemo_*` tests are ignored and need the network), `ref_tests` in `src/sandbox/browser.rs`-and the tests in `src/sandbox/progress.rs` and `src/sandbox/reads.rs`.+`tests/browser_refs_test.rs`, `tests/browser_progress_test.rs` and `tests/browser_reads_test.rs` and `tests/browser_cite_test.rs` (real Chrome, skipped without one;+the `saucedemo_*` and `a_public_page_*` tests are ignored and need the network), `ref_tests` in `src/sandbox/browser.rs`+and the tests in `src/sandbox/progress.rs`, `src/sandbox/reads.rs` and `src/sandbox/cite.rs`.diff --git a/src/drivers/activity.rs b/src/drivers/activity.rsindex 12ba7b80..5cff16a3 100644--- a/src/drivers/activity.rs+++ b/src/drivers/activity.rs@@ -473,6 +473,7 @@ pub fn summarize(name: &str, args: &Value) -> (String, Option<String>) {},"browser_page" | "browser_snapshot" | "browser_read" => ("Reading the browser page".into(), None),"browser_screenshot" => ("Looking at the browser page".into(), None),+ "browser_cite" => ("Checking a quote on the browser page".into(), None),"browser_act" | "browser_click" | "browser_type" => ("Using the browser".into(), None),"ask_user" => ("Asking you a question".into(), None),"request_human_step" => ("Asking you to do a step in the browser".into(), arg(args, &["reason"]).map(str::to_string)),diff --git a/src/drivers/api.rs b/src/drivers/api.rsindex b225fb38..ef2efd1a 100644--- a/src/drivers/api.rs+++ b/src/drivers/api.rs@@ -418,7 +418,7 @@ const DEFER_TOOLS_ABOVE_CHARS: usize = 12_000;const UPFRONT_TOOLS_CHARS: usize = 8_000;/// kwnt's own tools a turn always gets in full: talking to the person, memory, teammates, the/// browser and files. The rest (routines, bots, spaces, settings, …) are a lookup away.-const CORE_SELF_TOOLS: [&str; 12] = [+const CORE_SELF_TOOLS: [&str; 13] = ["ask_user","search_history","memory_add",@@ -428,6 +428,7 @@ const CORE_SELF_TOOLS: [&str; 12] = ["browser_open","browser_page","browser_act",+ "browser_cite","list_attachments","read_attachment","share_file",diff --git a/src/drivers/mod.rs b/src/drivers/mod.rsindex 83a724e0..1bd39b9b 100644--- a/src/drivers/mod.rs+++ b/src/drivers/mod.rs@@ -439,6 +439,7 @@ impl TurnInput {- `browser_page` (optional find): read the page (url, title, text, clickable controls numbered like [3] button \"Add to cart\"). It says \"unchanged\" if nothing changed since you last saw it; on a page with many controls, find (words for what you look for) lists the matching ones first.\n\- `browser_act` (action click + ref, type + text (+ ref), key + key, scroll + delta_y): click a control by its number from the clickable list, type into that field (or the focused one), press a key, scroll. If a ref is gone or covered, nothing is clicked and you get a fresh list.\n\- `browser_screenshot` (optional width, e.g. 390 phone / 1280 desktop): see the page as a picture, for layout, colours and spacing.\n\+ - `browser_cite` (text: the exact words from the page, or block: an id from `browser_page` with blocks): checks the quote is on the page word for word and once, and returns {{quote, url, link}}; the link opens the page with the quote highlighted. When you answer facts you read on the web, back each with its cite link. If a quote is refused, quote the page exactly or quote more; never quote from memory.\n\Every call returns the updated page and what changed, so you rarely need a separate read. If it says nothing changed or tells you to stop, don't repeat the action: try something else. \The current page state and its clickable list are usually already in the request; act on them directly.\n\{control_rules}",@@ -455,6 +456,7 @@ impl TurnInput {- Type into a field by its number (leave out ref for the focused field): curl -sS -X POST '{api}/act' -H 'Content-Type: application/json' -d '{{\"action\":\"type\",\"ref\":5,\"text\":\"<text>\"}}'\n\- Press a key: curl -sS -X POST '{api}/act' -H 'Content-Type: application/json' -d '{{\"action\":\"key\",\"key\":\"Enter\"}}'\n\- Scroll: curl -sS -X POST '{api}/act' -H 'Content-Type: application/json' -d '{{\"action\":\"scroll\",\"delta_y\":600}}'\n\+ - Cite what you read: curl -sS -X POST '{api}/cite' -H 'Content-Type: application/json' -d '{{\"text\":\"<the exact words from the page>\"}}' (or {{\"block\":\"b3-9f2a\"}}, an id from '{api}/page?blocks=1'). It checks the quote is on the page word for word and once, and returns quote, url and a link that opens the page with it highlighted; when you answer facts you read on the web, back each with its link. If it refuses, quote the page exactly or quote more; never quote from memory.\n\Every /act call returns the updated page (url, title, text, clickable) and what changed, so you rarely need a separate read. If it says nothing changed or tells you to stop, don't repeat the action: try something else. \The current page state and its clickable list are usually already in the request; act on them directly.\n\{control_rules}",diff --git a/src/sandbox/browser.rs b/src/sandbox/browser.rsindex 7288ce9c..7b7b7591 100644--- a/src/sandbox/browser.rs+++ b/src/sandbox/browser.rs@@ -1308,6 +1308,46 @@ impl BrowserController {Some(snap)}+ /// The page's rendered text and its same-origin frames', each with its own address (the page+ /// first), for citing what a bot read ([`super::cite`]). Frames from other sites can't be read+ /// from the page, so they are left out.+ pub async fn frame_texts(&self) -> Option<Vec<super::cite::FrameText>> {+ let expression = r#"+ (function() {+ var out = [];+ function walk(win, depth) {+ var doc;+ try { doc = win.document; if (!doc) return; } catch (e) { return; }+ // A frame without an address of its own (about:blank, srcdoc) can't be linked to+ var href = String(win.location.href);+ if (depth === 0 || !/^about:/.test(href)) {+ out.push([href, doc.body ? doc.body.innerText.substring(0, 200000) : '']);+ }+ if (depth > 3 || out.length > 20) return;+ for (var i = 0; i < win.frames.length; i++) {+ try { walk(win.frames[i], depth + 1); } catch (e) {}+ }+ }+ walk(window, 0);+ return out;+ })()+ "#;+ let res = self+ .send_cdp_command("Runtime.evaluate", json!({ "expression": expression, "returnByValue": true }))+ .await+ .ok()?;+ let frames: Vec<super::cite::FrameText> = res["result"]["value"]+ .as_array()?+ .iter()+ .filter_map(|f| {+ let url = f.get(0)?.as_str()?.to_string();+ let text = f.get(1)?.as_str()?.to_string();+ Some(super::cite::FrameText { url, text })+ })+ .collect();+ (!frames.is_empty() && !frames[0].url.is_empty()).then_some(frames)+ }+pub async fn extract_content(&self) -> Result<String, BrowserError> {let expression = r#"(function() {diff --git a/src/sandbox/cite.rs b/src/sandbox/cite.rsnew file mode 100644index 00000000..151b6a1e--- /dev/null+++ b/src/sandbox/cite.rs@@ -0,0 +1,458 @@+//! Cited reads: a bot quotes what it read, and kwant checks the words are really on the page and+//! gives back a link that opens the page with them highlighted (a `#:~:text=` text fragment).+//! Pure, so the rules are tested as tables; `routes::cite_sandbox` reads the page's text (and its+//! same-origin frames') and calls [`cite_text`] or [`cite_block`]. Nothing here is made up: a+//! quote that isn't on the page word for word, or is on it more than once, is refused.++/// One document's rendered text: the page itself, or a frame inside it with its own address.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct FrameText {+ pub url: String,+ pub text: String,+}++/// A checked quote: the page's own words, the address they are on, and a link that opens it+/// with them highlighted.+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]+pub struct Citation {+ pub quote: String,+ pub url: String,+ pub link: String,+}++/// The longest quote cited in one text fragment; a longer one (or one over several lines) is cited+/// by its first and last words.+const EXACT_MAX_CHARS: usize = 300;+/// Words at each end of a long quote's link, and the most words of context around it.+const EDGE_WORDS: usize = 5;+const CONTEXT_WORDS: usize = 3;+/// Characters of a block shown in a page read; citing it copies the whole block.+pub const BLOCK_SHOWN_CHARS: usize = 300;++/// A page's text as lines, each with its runs of whitespace made one space; empty lines dropped.+/// A line is roughly one block of the page (a paragraph, a heading, a list item, a cell).+pub fn page_lines(text: &str) -> Vec<String> {+ text.lines().map(|l| l.split_whitespace().collect::<Vec<_>>().join(" ")).filter(|l| !l.is_empty()).collect()+}++fn normalize(quote: &str) -> String {+ quote.split_whitespace().collect::<Vec<_>>().join(" ")+}++fn lower(c: char) -> char {+ c.to_lowercase().next().unwrap_or(c)+}++fn is_space(c: char) -> bool {+ c == ' ' || c == '\n'+}++/// Where `pat` matches `hay` at `at` (a space in `pat` matches a space or a line break), and+/// where the match ends.+fn match_at(hay: &[char], at: usize, pat: &[char], fold: bool) -> Option<usize> {+ if pat.is_empty() || at + pat.len() > hay.len() {+ return None;+ }+ for (i, &p) in pat.iter().enumerate() {+ let h = hay[at + i];+ let same = if p == ' ' { is_space(h) } else if fold { lower(h) == p } else { h == p };+ if !same {+ return None;+ }+ }+ Some(at + pat.len())+}++fn skip_space(hay: &[char], mut at: usize) -> usize {+ while at < hay.len() && is_space(hay[at]) {+ at += 1;+ }+ at+}++/// A text fragment: `text=[prefix-,]start[,end][,-suffix]`.+#[derive(Debug, Clone, PartialEq, Eq)]+struct Fragment {+ prefix: Option<String>,+ start: String,+ end: Option<String>,+ suffix: Option<String>,+}++fn folded(s: &str) -> Vec<char> {+ s.chars().map(lower).collect()+}++/// What a browser highlights for `f` on a page whose text is `hay`: the first match, compared+/// without case. It is more lenient than a browser (no word-boundary or block rules), so it finds+/// every match a browser would and maybe more; a link is only given when the first is the quote.+fn resolve(hay: &[char], f: &Fragment) -> Option<(usize, usize)> {+ let start = folded(&f.start);+ let prefix = f.prefix.as_deref().map(folded);+ let end = f.end.as_deref().map(folded);+ let suffix = f.suffix.as_deref().map(folded);+ let suffix_ok = |at: usize| match &suffix {+ Some(sfx) => match_at(hay, skip_space(hay, at), sfx, true).is_some(),+ None => true,+ };+ for p in 0..hay.len() {+ let s = match &prefix {+ Some(pre) => match match_at(hay, p, pre, true) {+ Some(pe) => skip_space(hay, pe),+ None => continue,+ },+ None => p,+ };+ let Some(se) = match_at(hay, s, &start, true) else { continue };+ match &end {+ None if suffix_ok(se) => return Some((s, se)),+ None => {}+ Some(end) => {+ for q in se..hay.len() {+ if let Some(qe) = match_at(hay, q, end, true) {+ if suffix_ok(qe) {+ return Some((s, qe));+ }+ }+ }+ }+ }+ }+ None+}++/// Percent-encodes a fragment part: everything but ASCII letters, digits and `._~`, so the+/// `-`, `,` and `&` that structure a text fragment are never taken literally.+fn encode(part: &str) -> String {+ let mut out = String::new();+ for b in part.bytes() {+ if b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'~') {+ out.push(b as char);+ } else {+ out.push_str(&format!("%{b:02X}"));+ }+ }+ out+}++fn fragment_param(f: &Fragment) -> String {+ let mut t = String::from("text=");+ if let Some(p) = &f.prefix {+ t.push_str(&format!("{}-,", encode(p)));+ }+ t.push_str(&encode(&f.start));+ if let Some(e) = &f.end {+ t.push_str(&format!(",{}", encode(e)));+ }+ if let Some(s) = &f.suffix {+ t.push_str(&format!(",-{}", encode(s)));+ }+ t+}++/// `url` with the text fragment added (after any fragment the address already has, as in+/// `#/route:~:text=…`; an older text fragment is replaced).+fn link_for(url: &str, f: &Fragment) -> String {+ let base = match url.find(":~:") {+ Some(i) => &url[..i],+ None => url,+ };+ let sep = if base.contains('#') { ":~:" } else { "#:~:" };+ format!("{base}{sep}{}", fragment_param(f))+}++/// Word spans (start, end) in `hay[from..to]`.+fn words(hay: &[char], from: usize, to: usize) -> Vec<(usize, usize)> {+ let mut out = Vec::new();+ let mut i = from;+ while i < to {+ if is_space(hay[i]) {+ i += 1;+ continue;+ }+ let s = i;+ while i < to && !is_space(hay[i]) {+ i += 1;+ }+ out.push((s, i));+ }+ out+}++fn text_of(hay: &[char], s: usize, e: usize) -> String {+ hay[s..e].iter().map(|&c| if c == '\n' { ' ' } else { c }).collect()+}++/// The line `at` is on: (first char, end).+fn line_around(hay: &[char], at: usize) -> (usize, usize) {+ let s = hay[..at].iter().rposition(|&c| c == '\n').map_or(0, |i| i + 1);+ let e = hay[at..].iter().position(|&c| c == '\n').map_or(hay.len(), |i| at + i);+ (s, e)+}++/// A text fragment whose first match is exactly `hay[s..e]`, adding words before and after it on+/// the same line until it is; `None` when no fragment does.+fn fragment_for(hay: &[char], s: usize, e: usize) -> Option<Fragment> {+ let span_words = words(hay, s, e);+ let multi_line = hay[s..e].contains(&'\n');+ let mut shapes: Vec<(String, Option<String>)> = Vec::new();+ if !multi_line && e - s <= EXACT_MAX_CHARS {+ shapes.push((text_of(hay, s, e), None));+ }+ // First and last words, each kept within its own line+ let (first_line_end, last_line_start) = (line_around(hay, s).1, line_around(hay, e.saturating_sub(1)).0);+ let head: Vec<_> = span_words.iter().filter(|w| w.1 <= first_line_end).take(EDGE_WORDS).collect();+ let tail: Vec<_> = span_words.iter().filter(|w| w.0 >= last_line_start).collect();+ let tail = &tail[tail.len().saturating_sub(EDGE_WORDS)..];+ if let (Some(h0), Some(h1), Some(t0), Some(t1)) = (head.first(), head.last(), tail.first(), tail.last()) {+ if h1.1 <= t0.0 {+ shapes.push((text_of(hay, h0.0, h1.1), Some(text_of(hay, t0.0, t1.1))));+ }+ }+ let (line_s, _) = line_around(hay, s);+ let (_, line_e) = line_around(hay, e.saturating_sub(1));+ let before = words(hay, line_s, s);+ let after = words(hay, e, line_e);+ let prefix = |k: usize| {+ let w = &before[before.len().saturating_sub(k)..];+ (k > 0 && !w.is_empty()).then(|| text_of(hay, w[0].0, w[w.len() - 1].1))+ };+ let suffix = |k: usize| {+ let w = &after[..k.min(after.len())];+ (k > 0 && !w.is_empty()).then(|| text_of(hay, w[0].0, w[w.len() - 1].1))+ };+ for (start, end) in shapes {+ // Fewest words first: none, then words before, after, both+ let mut tries = vec![(None, None)];+ for k in 1..=CONTEXT_WORDS {+ tries.extend([(prefix(k), None), (None, suffix(k)), (prefix(k), suffix(k))]);+ }+ for (prefix, suffix) in tries {+ let f = Fragment { prefix, start: start.clone(), end: end.clone(), suffix };+ if resolve(hay, &f) == Some((s, e)) {+ return Some(f);+ }+ }+ }+ None+}++fn cite_at(url: &str, hay: &[char], s: usize, e: usize) -> Result<Citation, String> {+ let quote = text_of(hay, s, e);+ let f = fragment_for(hay, s, e).ok_or_else(|| {+ "Couldn't make a link that points only at this passage (the page repeats it in the same words); \+ quote a longer or different passage."+ .to_string()+ })?;+ Ok(Citation { quote, url: url.to_string(), link: link_for(url, &f) })+}++fn joined(text: &str) -> Vec<char> {+ page_lines(text).join("\n").chars().collect()+}++/// Every place `pat` is in `hay`, as start positions.+fn all_matches(hay: &[char], pat: &[char], fold: bool) -> Vec<usize> {+ (0..hay.len()).filter(|&p| match_at(hay, p, pat, fold).is_some()).collect()+}++fn mid_word(hay: &[char], at: usize) -> bool {+ at > 0 && at < hay.len() && hay[at - 1].is_alphanumeric() && hay[at].is_alphanumeric()+}++/// Cites `quote` from the page: it must be on it word for word (runs of whitespace and line+/// breaks count as one space), once, in whole words, in the page or one of its frames+/// (`frames[0]` is the page). The answer's quote is the page's own text.+pub fn cite_text(frames: &[FrameText], quote: &str) -> Result<Citation, String> {+ let q = normalize(quote);+ if q.is_empty() {+ return Err("Give the exact words to cite in text, or a block id in block.".into());+ }+ let pat: Vec<char> = q.chars().collect();+ let pages: Vec<(&str, Vec<char>)> = frames.iter().map(|f| (f.url.as_str(), joined(&f.text))).collect();+ let mut found: Vec<(usize, usize)> = Vec::new();+ for (i, (_, hay)) in pages.iter().enumerate() {+ found.extend(all_matches(hay, &pat, false).into_iter().map(|p| (i, p)));+ }+ match found.as_slice() {+ [] => {+ let fold: Vec<char> = pat.iter().map(|&c| lower(c)).collect();+ let near = pages.iter().find_map(|(_, hay)| all_matches(hay, &fold, true).first().map(|&p| text_of(hay, p, p + pat.len())));+ Err(match near {+ Some(near) => format!("Not cited: the page has these words with other capitals (\"{near}\"). Quote them exactly as the page has them."),+ None => "Not cited: these words aren't on the page as given. Quote the page word for word (copy them from \+ your read), or cite a block by its id; never quote from memory."+ .into(),+ })+ }+ [(i, p)] => {+ let (url, hay) = &pages[*i];+ let e = p + pat.len();+ if mid_word(hay, *p) || mid_word(hay, e) {+ return Err("Not cited: the quote starts or ends in the middle of a word. Quote whole words.".into());+ }+ cite_at(url, hay, *p, e)+ }+ many => Err(format!(+ "Not cited: these words are on the page {} times. Quote a longer passage, so it is only there once.",+ many.len()+ )),+ }+}++/// FNV-1a of a block's text, 4 hex digits: part of its id, so an id from an older read never+/// cites a different block.+fn tag(line: &str) -> String {+ let mut h: u32 = 0x811c_9dc5;+ for b in line.bytes() {+ h ^= u32::from(b);+ h = h.wrapping_mul(0x0100_0193);+ }+ format!("{:04x}", h & 0xffff)+}++/// The page's blocks (its lines) with their ids, `b<number>-<tag>`.+pub fn blocks(text: &str) -> Vec<(String, String)> {+ page_lines(text).into_iter().enumerate().map(|(i, l)| (format!("b{}-{}", i + 1, tag(&l)), l)).collect()+}++/// A block as a page read shows it: `[b3-9f2a] text`, long ones cut short.+pub fn block_line(id: &str, text: &str) -> String {+ let mut shown: String = text.chars().take(BLOCK_SHOWN_CHARS).collect();+ if text.chars().count() > BLOCK_SHOWN_CHARS {+ shown.push('…');+ }+ format!("[{id}] {shown}")+}++/// Cites a whole block of the page by the id a read showed (`b3-9f2a`, with or without the+/// brackets). If the page moved, the same block is found by its text; if it is gone, refused.+pub fn cite_block(page: &FrameText, id: &str) -> Result<Citation, String> {+ let id = id.trim().trim_start_matches('[').trim_end_matches(']');+ let parsed = id.strip_prefix('b').and_then(|r| r.split_once('-')).and_then(|(n, t)| Some((n.parse::<usize>().ok()?, t)));+ let Some((n, t)) = parsed else {+ return Err(format!("\"{id}\" isn't a block id; they look like b3-9f2a, from a page read with blocks."));+ };+ let lines = page_lines(&page.text);+ let index = match lines.get(n.wrapping_sub(1)) {+ Some(l) if tag(l) == t => Some(n - 1),+ _ => {+ let same: Vec<usize> = (0..lines.len()).filter(|&i| tag(&lines[i]) == t).collect();+ (same.len() == 1).then(|| same[0])+ }+ };+ let Some(index) = index else {+ return Err(format!("Not cited: block {id} isn't on the page any more (it changed). Read the page again with blocks."));+ };+ let hay: Vec<char> = lines.join("\n").chars().collect();+ let s: usize = lines[..index].iter().map(|l| l.chars().count() + 1).sum();+ cite_at(&page.url, &hay, s, s + lines[index].chars().count())+}++#[cfg(test)]+mod tests {+ use super::*;++ fn page(text: &str) -> Vec<FrameText> {+ vec![FrameText { url: "https://example.org/a".into(), text: text.into() }]+ }++ #[test]+ fn a_quote_on_the_page_gets_a_link_that_highlights_it() {+ let c = cite_text(&page("Intro\nThe quick brown\tfox jumps.\nEnd"), "quick brown fox").unwrap();+ assert_eq!(c.quote, "quick brown fox");+ assert_eq!(c.url, "https://example.org/a");+ assert_eq!(c.link, "https://example.org/a#:~:text=quick%20brown%20fox");+ }++ #[test]+ fn the_link_text_is_encoded() {+ let c = cite_text(&page("Price: 5-10 apples, & pears #1 (ok) über"), "5-10 apples, & pears #1 (ok) über").unwrap();+ assert_eq!(c.link, "https://example.org/a#:~:text=5%2D10%20apples%2C%20%26%20pears%20%231%20%28ok%29%20%C3%BCber");+ }++ #[test]+ fn an_address_with_a_fragment_keeps_it() {+ let f = Fragment { prefix: None, start: "x".into(), end: None, suffix: None };+ assert_eq!(link_for("https://s.test/#/route", &f), "https://s.test/#/route:~:text=x");+ assert_eq!(link_for("https://s.test/p#:~:text=old", &f), "https://s.test/p#:~:text=x");+ }++ #[test]+ fn what_isnt_on_the_page_once_and_in_whole_words_is_refused() {+ let p = page("Cats sleep a lot.\nDogs bark.\nCats sleep a lot.");+ assert!(cite_text(&p, "Cats fly").unwrap_err().contains("aren't on the page"));+ assert!(cite_text(&p, "cats SLEEP").unwrap_err().contains("other capitals (\"Cats sleep\")"));+ assert!(cite_text(&p, "Cats sleep a lot").unwrap_err().contains("2 times"));+ assert!(cite_text(&p, "ogs bark").unwrap_err().contains("middle of a word"));+ assert!(cite_text(&p, " ").is_err());+ // The quote is the page's text, not the bot's+ assert_eq!(cite_text(&p, "Dogs\n bark.").unwrap().quote, "Dogs bark.");+ }++ #[test]+ fn words_found_earlier_in_other_case_or_inside_a_word_get_context() {+ // The browser matches without case, so the earlier "The report" would be highlighted+ let c = cite_text(&page("The report below is late.\nSee the report below."), "the report below").unwrap();+ assert!(c.link.ends_with("#:~:text=See-,the%20report%20below"), "{}", c.link);+ let c = cite_text(&page("Categories\nA cat sat"), "cat sat").unwrap();+ assert!(c.link.ends_with("#:~:text=A-,cat%20sat") || c.link.ends_with("#:~:text=cat%20sat"), "{}", c.link);+ // Whatever the shape, the browser's first match is the quote+ let hay: Vec<char> = "Categories\nA cat sat".chars().collect();+ assert_eq!(resolve(&hay, &fragment_for(&hay, 13, 20).unwrap()), Some((13, 20)));+ }++ #[test]+ fn a_quote_over_several_lines_or_a_long_one_is_cited_by_its_ends() {+ let c = cite_text(&page("Title\nFirst para ends here.\nSecond para starts here and goes on."), "ends here. Second para starts").unwrap();+ assert_eq!(c.quote, "ends here. Second para starts");+ assert!(c.link.ends_with("#:~:text=ends%20here.,Second%20para%20starts"), "{}", c.link);+ let long: Vec<String> = (1..=80).map(|i| format!("word{i}")).collect();+ let c = cite_text(&page(&long.join(" ")), &long[2..70].join(" ")).unwrap();+ assert!(c.link.ends_with("#:~:text=word3%20word4%20word5%20word6%20word7,word66%20word67%20word68%20word69%20word70"), "{}", c.link);+ }++ #[test]+ fn a_quote_in_a_frame_links_to_the_frame() {+ let frames = vec![+ FrameText { url: "https://shop.test/".into(), text: "Shop".into() },+ FrameText { url: "https://shop.test/reviews".into(), text: "Great light, very bright.".into() },+ ];+ let c = cite_text(&frames, "very bright").unwrap();+ assert_eq!(c.url, "https://shop.test/reviews");+ assert_eq!(c.link, "https://shop.test/reviews#:~:text=very%20bright");+ let frames = vec![frames[1].clone(), FrameText { url: "https://x.test/".into(), text: "very bright".into() }];+ assert!(cite_text(&frames, "very bright").unwrap_err().contains("2 times"), "counted across frames");+ }++ #[test]+ fn a_block_is_cited_by_its_id_even_after_the_page_moved() {+ let p = FrameText { url: "https://example.org/a".into(), text: "Heading\n\nBody text here.\nFooter".into() };+ let b = blocks(&p.text);+ assert_eq!(b.len(), 3);+ assert!(b[1].0.starts_with("b2-") && b[1].1 == "Body text here.");+ let c = cite_block(&p, &format!("[{}]", b[1].0)).unwrap();+ assert_eq!(c.quote, "Body text here.");+ assert_eq!(c.link, "https://example.org/a#:~:text=Body%20text%20here.");+ // A new line above: the same id still finds it+ let moved = FrameText { text: format!("Banner\n{}", p.text), ..p.clone() };+ assert_eq!(cite_block(&moved, &b[1].0).unwrap().quote, "Body text here.");+ // Gone, or not an id+ let gone = FrameText { text: "Heading\nOther".into(), ..p.clone() };+ assert!(cite_block(&gone, &b[1].0).unwrap_err().contains("isn't on the page any more"));+ assert!(cite_block(&p, "3").unwrap_err().contains("isn't a block id"));+ // A block whose words come earlier on the page (in any case) can't be linked on its own+ let rep = FrameText { url: "https://e.test/".into(), text: "YES\nAre you sure\nYes".into() };+ let id = &blocks(&rep.text)[2].0;+ assert!(cite_block(&rep, id).unwrap_err().contains("Couldn't make a link"));+ assert!(block_line("b1-0000", &"x".repeat(400)).ends_with("x…"));+ }++ #[test]+ fn a_passage_that_cant_be_singled_out_is_refused() {+ // Two identical lines: the second can't be told apart by its own line's words+ let rep = FrameText { url: "u".into(), text: "Same line\nSame line".into() };+ let id = &blocks(&rep.text)[1].0;+ assert!(cite_block(&rep, id).unwrap_err().contains("Couldn't make a link"));+ }+}diff --git a/src/sandbox/mod.rs b/src/sandbox/mod.rsindex a0d7218b..f96cbe20 100644--- a/src/sandbox/mod.rs+++ b/src/sandbox/mod.rs@@ -3,6 +3,7 @@ pub mod browser;pub mod computer;pub mod credentials;pub mod manager;+pub mod cite;pub mod progress;pub mod reads;pub mod service;diff --git a/src/server/continuity.rs b/src/server/continuity.rsindex d5e9abe9..f5e96b81 100644--- a/src/server/continuity.rs+++ b/src/server/continuity.rs@@ -359,6 +359,7 @@ pub(crate) const READ_ONLY_SELF_TOOLS: &[&str] = &["mcp_search",super::page_source::TOOL,"skill_get",+ BROWSER_CITE,"task_list","tier_status",];@@ -525,6 +526,18 @@ fn browser_tools() -> Vec<Value> {"properties": {"find": {"type": "string", "description": "Words for what you look for, e.g. \"bike light add to cart\": controls naming them are listed first."},"full": {"type": "boolean", "description": "true: send the whole page even if it didn't change since your last look."},+ "blocks": {"type": "boolean", "description": "true: the text as blocks with ids ([b3-9f2a] …), so you can cite a whole block with browser_cite by its id."},+ },+ },+ }),+ json!({+ "name": BROWSER_CITE,+ "description": "Cite what you read on the page your browser shows now. Give the exact words (copied from your read) or a block id from browser_page with blocks. The words are checked against the page: they must be on it word for word and only once (spaces and line breaks don't matter, capitals do). You get {quote, url, link}: the link opens the page with the quote highlighted. A quote that isn't on the page, or is on it more than once, is refused with the reason: quote it exactly or quote more, never from memory. When you answer facts you read on the web, back each one with its cite link.",+ "inputSchema": {+ "type": "object",+ "properties": {+ "text": {"type": "string", "description": "The exact words to quote, as the page has them; whole words, a sentence or two is best."},+ "block": {"type": "string", "description": "Or a block id from browser_page with blocks, e.g. b3-9f2a, to quote that whole block."},},},}),@@ -565,6 +578,7 @@ pub const BROWSER_OPEN: &str = "browser_open";pub const BROWSER_PAGE: &str = "browser_page";pub const BROWSER_ACT: &str = "browser_act";pub const BROWSER_SCREENSHOT: &str = "browser_screenshot";+pub const BROWSER_CITE: &str = "browser_cite";/// `browser_screenshot`: MCP content blocks (a text line and the JPEG), and whether it is an error./// Same holds as the other browser tools: the person's sign-in/CAPTCHA step or their control.@@ -652,7 +666,10 @@ async fn call_browser_tool(state: &AppState, scope: &SelfScope, target: &str, na/// `reader` names who reads (empty: nobody known), for `browser_page` to answer "unchanged" when/// that reader's last page (from any browser tool) still reads the same.async fn run_browser_tool(state: &AppState, target: &str, reader: &str, name: &str, args: &Value) -> (String, bool) {- use super::routes::{act_sandbox_allowed, get_sandbox_page, navigate_sandbox, unchanged_read, InteractPayload, NavigatePayload, PageQuery};+ use super::routes::{+ act_sandbox_allowed, cite_sandbox, get_sandbox_page, navigate_sandbox, unchanged_read, CitePayload, InteractPayload, NavigatePayload,+ PageQuery,+ };let ctrl = match reader {"" => None,_ => super::routes::get_or_create_browser_controller(state, target).await,@@ -668,7 +685,12 @@ async fn run_browser_tool(state: &AppState, target: &str, reader: &str, name: &s}BROWSER_PAGE => {let find = args["find"].as_str().map(str::to_string);- get_sandbox_page(state, target, Query(PageQuery { find, since: None })).await+ let blocks = (args["blocks"].as_bool() == Some(true)).then(|| "1".to_string());+ get_sandbox_page(state, target, Query(PageQuery { find, since: None, blocks })).await+ }+ BROWSER_CITE => {+ let payload = CitePayload { text: args["text"].as_str().map(str::to_string), block: args["block"].as_str().map(str::to_string) };+ cite_sandbox(state, target, Json(payload)).await}_ => {let Some(action) = args["action"].as_str() else {@@ -1036,7 +1058,7 @@ async fn call_tool(}}}- BROWSER_OPEN | BROWSER_PAGE | BROWSER_ACT => match &scope.sandbox_target {+ BROWSER_OPEN | BROWSER_PAGE | BROWSER_ACT | BROWSER_CITE => match &scope.sandbox_target {Some(target) => call_browser_tool(state, scope, target, name, args).await,None => (format!("Unknown tool {name}."), true),},diff --git a/src/server/mod.rs b/src/server/mod.rsindex 9917e759..8b965ebc 100644--- a/src/server/mod.rs+++ b/src/server/mod.rs@@ -253,6 +253,7 @@ pub fn create_router(state: AppState) -> Router {.route("/api/sandbox/:team_id/stream", get(browser_stream::upgrade)).route("/api/sandbox/:team_id/page", get(routes::get_sandbox_page)).route("/api/sandbox/:team_id/act", post(routes::act_sandbox))+ .route("/api/sandbox/:team_id/cite", post(routes::cite_sandbox)).route("/api/sandbox/:team_id/passwords", get(passwords::list).post(passwords::save)).route("/api/sandbox/:team_id/passwords/pending", post(passwords::save_pending).delete(passwords::discard_pending)).route("/api/sandbox/:team_id/passwords/:id", delete(passwords::remove))diff --git a/src/server/routes.rs b/src/server/routes.rsindex aabf1305..691b279f 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -4402,13 +4402,58 @@ async fn broadcast_sandbox_screenshot(state: &AppState, team_id: &str, ctrl: &cr/// `GET /api/sandbox/:id/page` options. `find`: words for what the bot looks for (matching/// controls listed first). `since`: the `hash` of the bot's last read; when the page still reads-/// the same, the answer is a short `unchanged` note instead of the page.+/// the same, the answer is a short `unchanged` note instead of the page. `blocks` (`1`): the+/// page's text as blocks with ids, to cite one by its id (`POST /api/sandbox/:id/cite`).#[derive(Debug, Default, Deserialize)]pub struct PageQuery {#[serde(default)]pub find: Option<String>,#[serde(default)]pub since: Option<String>,+ #[serde(default)]+ pub blocks: Option<String>,+}++impl PageQuery {+ fn wants_blocks(&self) -> bool {+ matches!(self.blocks.as_deref().map(str::trim), Some("1" | "true" | "yes"))+ }+}++/// Most blocks one read shows; the rest are left for the bot to find with `find` or by scrolling.+const SHOWN_BLOCKS: usize = 150;++/// A read with blocks: the page's text as `[b3-9f2a] text` lines, each citable by its id, in+/// place of the plain text. Its `hash` differs from a plain read's, so an "unchanged" answer is+/// only given for the same kind of read.+async fn add_blocks(ctrl: &crate::sandbox::BrowserController, page: &mut serde_json::Value) {+ use crate::sandbox::{cite, reads};+ let Some(frames) = ctrl.frame_texts().await else { return };+ let all = cite::blocks(&frames[0].text);+ let shown: Vec<String> = all.iter().take(SHOWN_BLOCKS).map(|(id, text)| cite::block_line(id, text)).collect();+ let old = page["hash"].as_str().unwrap_or_default().to_string();+ let hash = reads::page_hash(+ page["url"].as_str().unwrap_or_default(),+ page["title"].as_str().unwrap_or_default(),+ &shown.join("\n"),+ &[],+ &format!("blocks {old}"),+ );+ if let Some(obj) = page.as_object_mut() {+ obj.remove("text");+ }+ page["blocks"] = json!(shown);+ page["hash"] = json!(hash);+ if all.len() > SHOWN_BLOCKS {+ page["blocks_note"] = json!(format!(+ "Showing the first {SHOWN_BLOCKS} of {} blocks. To cite a passage further down, scroll or quote its exact words.",+ all.len()+ ));+ }+ if frames.len() > 1 {+ page["frames_note"] =+ json!("Text inside frames isn't listed as blocks; cite it by quoting its exact words.");+ }}pub async fn get_sandbox_page(@@ -4420,13 +4465,53 @@ pub async fn get_sandbox_page(.await.ok_or_else(|| browser_unavailable(&state))?;let snap = ctrl.snapshot().await;- let page = page_state_from(&ctrl, snap, query.find.as_deref().unwrap_or_default()).await;+ let mut page = page_state_from(&ctrl, snap, query.find.as_deref().unwrap_or_default()).await;+ if query.wants_blocks() {+ add_blocks(&ctrl, &mut page).await;+ }if query.since.as_deref().is_some_and(|since| !since.is_empty() && page["hash"] == json!(since)) {return Ok(Json(unchanged_read(&page)));}Ok(Json(page))}+/// `POST /api/sandbox/:id/cite`: `text` (the exact words to quote) or `block` (an id from a read+/// with blocks).+#[derive(Debug, Default, Deserialize)]+pub struct CitePayload {+ #[serde(default)]+ pub text: Option<String>,+ #[serde(default)]+ pub block: Option<String>,+}++/// Cites what a bot read on the page open now: checks the words are on it (or in one of its+/// same-origin frames) word for word and only once, and answers `{quote, url, link}`, the link+/// opening the page with the quote highlighted. A quote that isn't there, or is there more than+/// once, is refused with the reason (422). No model is asked; nothing on the page changes.+pub async fn cite_sandbox(+ State(state): State<AppState>,+ Path(team_id): Path<String>,+ Json(payload): Json<CitePayload>,+) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {+ use crate::sandbox::cite;+ let refuse = |msg: String| (StatusCode::UNPROCESSABLE_ENTITY, Json(json!({ "error": msg })));+ let ctrl = get_or_create_browser_controller(&state, &team_id)+ .await+ .ok_or_else(|| browser_unavailable(&state))?;+ let Some(frames) = ctrl.frame_texts().await else {+ return Err(refuse("Couldn't read the page to check the quote. Open a page first.".into()));+ };+ let text = payload.text.as_deref().map(str::trim).filter(|t| !t.is_empty());+ let block = payload.block.as_deref().map(str::trim).filter(|b| !b.is_empty());+ let cited = match (text, block) {+ (Some(text), _) => cite::cite_text(&frames, text),+ (None, Some(block)) => cite::cite_block(&frames[0], block),+ (None, None) => Err("Give the exact words to cite in text, or a block id in block.".into()),+ };+ cited.map(|c| Json(json!(c))).map_err(refuse)+}+/// What a read of a page that still reads the same returns instead of it.pub fn unchanged_read(page: &serde_json::Value) -> serde_json::Value {json!({diff --git a/tests/browser_cite_test.rs b/tests/browser_cite_test.rsnew file mode 100644index 00000000..57a34f2d--- /dev/null+++ b/tests/browser_cite_test.rs@@ -0,0 +1,283 @@+//! Cited reads in kwnt's own browser, through a real Chrome: a bot quotes what it read and gets+//! back `{quote, url, link}` only when the words are on the page once (in the page or a+//! same-origin frame); the link, opened, scrolls the browser to the quote (Chrome highlights it).+//! A quote that isn't there, or is there twice, is refused. Blocks: a read with ids, cited by id.+//! Skipped when no Chrome is installed.+#[path = "support/chrome_guard.rs"]+mod chrome_guard;+use axum::{+ body::{to_bytes, Body},+ http::{Request, StatusCode},+ Router,+};+use chrome_guard::ChromeGuard;+use kwnt::{+ broker::PermissionBroker,+ config::Config,+ db::{models::Kwant, spaces::SpaceId, Database},+ router::LayaRouter,+ sandbox::{computer, BrowserController},+ server::{continuity::SelfScope, create_router, mcp_runtime, routes::get_or_create_browser_controller, AppState},+ tools::ToolRunner,+};+use serde_json::{json, Value};+use std::time::Duration;+use tempfile::{tempdir, TempDir};+use tokio::io::{AsyncReadExt, AsyncWriteExt};+use tower::ServiceExt;++/// A long page: the quote's words in other capitals near the top (Chrome would highlight those+/// for a bare fragment), a repeated line, the quote far down, and a same-origin frame.+fn long_page() -> String {+ let mut page = String::from("<!doctype html><title>report</title><h1>Quarterly notes</h1><p id=decoy>The Report Below is late.</p>");+ for i in 1..=60 {+ page.push_str(&format!("<p style=\"height:40px\">Filler paragraph {i}.</p><p>Same words here.</p>"));+ }+ page.push_str("<p id=target>See the report below.</p><p>Revenue grew 12% to €4.2m in Q3, up from 3.7m.</p>");+ page.push_str("<iframe src=\"/frame\" height=80></iframe>");+ page+}++async fn serve() -> String {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let port = listener.local_addr().unwrap().port();+ tokio::spawn(async move {+ while let Ok((mut stream, _)) = listener.accept().await {+ tokio::spawn(async move {+ let mut buf = [0u8; 4096];+ let n = stream.read(&mut buf).await.unwrap_or(0);+ let head = String::from_utf8_lossy(&buf[..n]);+ let page = if head.starts_with("GET /frame") {+ "<!doctype html><p>Reviews: the light is very bright.</p>".to_string()+ } else {+ long_page()+ };+ let reply = format!(+ "HTTP/1.1 200 OK\r\ncontent-type: text/html; charset=utf-8\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{page}",+ page.len()+ );+ let _ = stream.write_all(reply.as_bytes()).await;+ });+ }+ });+ format!("http://127.0.0.1:{port}/long")+}++struct Env {+ app: Router,+ state: AppState,+ bot: Kwant,+ tmp: TempDir,+}++/// kwnt in Local mode, so the bot's browser is a real Chrome on this machine.+async fn setup() -> Env {+ let tmp = tempdir().unwrap();+ let db = Database::init(tmp.path()).await.unwrap();+ db.set_setting(computer::SETTING_KEY, "local").await.unwrap();+ let config = Config { data_dir: tmp.path().to_path_buf(), ..Config::default() };+ let state = AppState::new(+ config.clone(),+ db,+ ToolRunner::new(tmp.path().join("workspace")),+ PermissionBroker::new(),+ LayaRouter::new(config.laya_url.clone()),+ );+ let bot = state.db.list_kwants(&SpaceId::default_space()).await.unwrap()[0].clone();+ Env { app: create_router(state.clone()), state, bot, tmp }+}++async fn send(app: &Router, method: &str, uri: &str, auth: Option<&str>, body: Value) -> Value {+ let (status, v) = send_any(app, method, uri, auth, body).await;+ assert_eq!(status, StatusCode::OK, "{v}");+ v+}++async fn send_any(app: &Router, method: &str, uri: &str, auth: Option<&str>, body: Value) -> (StatusCode, Value) {+ let mut req = Request::builder().method(method).uri(uri).header("content-type", "application/json");+ if let Some(token) = auth {+ req = req.header("authorization", format!("Bearer {token}"));+ }+ let body = if method == "GET" { Body::empty() } else { Body::from(body.to_string()) };+ let resp = app.clone().oneshot(req.body(body).unwrap()).await.unwrap();+ let status = resp.status();+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();+ (status, serde_json::from_slice(&bytes).unwrap_or(Value::Null))+}++async fn page(e: &Env, query: &str) -> Value {+ send(&e.app, "GET", &format!("/api/sandbox/{}/page{query}", e.bot.id), None, Value::Null).await+}++async fn cite(e: &Env, body: Value) -> (StatusCode, Value) {+ send_any(&e.app, "POST", &format!("/api/sandbox/{}/cite", e.bot.id), None, body).await+}++async fn eval(ctrl: &BrowserController, js: &str) -> Value {+ let res = ctrl.send_cdp_command("Runtime.evaluate", json!({"expression": js, "returnByValue": true})).await.unwrap();+ res["result"]["value"].clone()+}++/// Whether the first text on the page that starts with `words` is on screen.+async fn in_view(ctrl: &BrowserController, words: &str) -> bool {+ let js = format!(+ r#"(function() {{+ var w = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT), n;+ while ((n = w.nextNode())) {{+ var i = n.data.indexOf({words});+ if (i < 0) continue;+ var r = document.createRange(); r.setStart(n, i); r.setEnd(n, i + {words}.length);+ var b = r.getBoundingClientRect();+ return b.height > 0 && b.top >= 0 && b.bottom <= innerHeight;+ }}+ return false;+ }})()"#,+ words = json!(words)+ );+ eval(ctrl, &js).await == json!(true)+}++/// Opens `link` as a new page load (a fragment-only change in the same document doesn't run a+/// text fragment) and waits for Chrome to scroll to the quote; the scroll offset it ended at.+async fn open_link(ctrl: &BrowserController, link: &str) -> f64 {+ ctrl.navigate("about:blank").await.unwrap();+ ctrl.navigate(link).await.unwrap();+ let mut y = 0.0;+ for _ in 0..40 {+ tokio::time::sleep(Duration::from_millis(100)).await;+ y = eval(ctrl, "scrollY").await.as_f64().unwrap_or(0.0);+ if y > 0.0 {+ tokio::time::sleep(Duration::from_millis(300)).await;+ return eval(ctrl, "scrollY").await.as_f64().unwrap_or(y);+ }+ }+ y+}++#[tokio::test]+async fn a_quote_on_the_page_gets_a_link_that_opens_at_it_and_a_made_up_one_is_refused() {+ if computer::local_chrome_path().is_none() {+ eprintln!("skipped: no Chrome or Chromium installed");+ return;+ }+ let e = setup().await;+ let _chrome = ChromeGuard(e.tmp.path().join("local-chrome"));+ let url = serve().await;+ let ctrl = get_or_create_browser_controller(&e.state, &e.bot.id).await.expect("local Chrome session");+ ctrl.navigate(&url).await.unwrap();+ for _ in 0..30 {+ if eval(&ctrl, "document.querySelector('iframe') && document.querySelector('iframe').contentDocument && document.querySelector('iframe').contentDocument.body.innerText.length > 0").await == json!(true) {+ break;+ }+ tokio::time::sleep(Duration::from_millis(100)).await;+ }++ // On the page once: the page's own words, its address, and a link with context, since a+ // bare "the report below" would match the decoy at the top first+ let (status, c) = cite(&e, json!({"text": "the report\nbelow"})).await;+ assert_eq!(status, StatusCode::OK, "{c}");+ assert_eq!(c["quote"], "the report below");+ assert_eq!(c["url"], url.as_str());+ assert_eq!(c["link"], format!("{url}#:~:text=See-,the%20report%20below"));+ let y = open_link(&ctrl, c["link"].as_str().unwrap()).await;+ assert!(y > 1000.0, "Chrome scrolled to the quote: {y}");+ assert!(in_view(&ctrl, "See the report below.").await, "the quote is on screen");+ assert!(!in_view(&ctrl, "The Report Below").await, "not the decoy");++ // Encoded: %, €, commas; still opens at it+ let (_, c) = cite(&e, json!({"text": "Revenue grew 12% to €4.2m in Q3,"})).await;+ assert_eq!(c["link"], format!("{url}#:~:text=Revenue%20grew%2012%25%20to%20%E2%82%AC4.2m%20in%20Q3%2C"), "{c}");+ ctrl.navigate(&url).await.unwrap();+ assert!(open_link(&ctrl, c["link"].as_str().unwrap()).await > 1000.0);+ assert!(in_view(&ctrl, "Revenue grew").await);++ // Refused, with the reason: not there, twice, other capitals, half a word, nothing given+ ctrl.navigate(&url).await.unwrap();+ let refused = |v: &Value| v["error"].as_str().unwrap_or_default().to_string();+ let (status, v) = cite(&e, json!({"text": "Revenue fell 12%"})).await;+ assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY);+ assert!(refused(&v).contains("aren't on the page"), "{v}");+ assert!(refused(&cite(&e, json!({"text": "Same words here."})).await.1).contains("60 times"));+ assert!(refused(&cite(&e, json!({"text": "see the report below"})).await.1).contains("other capitals"));+ assert!(refused(&cite(&e, json!({"text": "evenue grew"})).await.1).contains("middle of a word"));+ assert!(refused(&cite(&e, json!({})).await.1).contains("Give the exact words"));++ // In the frame: linked to the frame's own address+ let (_, c) = cite(&e, json!({"text": "the light is very bright"})).await;+ assert_eq!(c["url"], url.replace("/long", "/frame"), "{c}");++ // A read with blocks: ids instead of the plain text, and its own hash for "unchanged"+ let plain = page(&e, "").await;+ let read = page(&e, "?blocks=1").await;+ assert!(read.get("text").is_none(), "{read}");+ let lines: Vec<&str> = read["blocks"].as_array().unwrap().iter().filter_map(Value::as_str).collect();+ assert!(lines[0].starts_with("[b1-") && lines[0].ends_with("] Quarterly notes"), "{lines:?}");+ assert!(read["frames_note"].is_string(), "{read}");+ assert_ne!(read["hash"], plain["hash"]);+ let again = page(&e, &format!("?blocks=1&since={}", read["hash"].as_str().unwrap())).await;+ assert_eq!(again["unchanged"], true, "{again}");+ let line = lines.iter().find(|l| l.ends_with("See the report below.")).unwrap();+ let id = &line[1..line.find(']').unwrap()];+ let (_, c) = cite(&e, json!({"block": id})).await;+ assert_eq!(c["quote"], "See the report below.", "{c}");+ assert_eq!(c["link"], format!("{url}#:~:text=See%20the%20report%20below."));+ let (_, v) = cite(&e, json!({"block": "b2-0000"})).await;+ assert!(refused(&v).contains("isn't on the page any more"), "{v}");++ // browser_cite in a turn: the same, as a tool; a refusal is a tool error, never a quote+ let scope = SelfScope {+ kwant_id: e.bot.id.clone(),+ kwant_name: e.bot.name.clone(),+ sandbox_target: Some(e.bot.id.clone()),+ turn_id: Some("t1".into()),+ ..Default::default()+ };+ let (_ctx, token) = mcp_runtime::prepare_turn_with_self(&e.state, &e.bot, None, None, Some(scope)).await.unwrap();+ let call = |args: Value| {+ let rpc = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "browser_cite", "arguments": args}});+ send(&e.app, "POST", "/api/mcp/self", Some(&token), rpc)+ };+ let ok = call(json!({"text": "See the report below."})).await;+ assert_ne!(ok["result"]["isError"], true, "{ok}");+ let c: Value = serde_json::from_str(ok["result"]["content"][0]["text"].as_str().unwrap()).unwrap();+ assert_eq!(c["link"], format!("{url}#:~:text=See%20the%20report%20below."));+ let bad = call(json!({"text": "The report above"})).await;+ assert_eq!(bad["result"]["isError"], true, "{bad}");+ assert!(bad["result"]["content"][0]["text"].as_str().unwrap().contains("aren't on the page"), "{bad}");+ mcp_runtime::finish_turn(&e.state, &token).await;+}++/// The same on a public page (network): a block far down GNU's "What is Free Software?" essay+/// (long, static, no cookie banner) is cited, and its link opens the essay scrolled to it.+#[tokio::test]+#[ignore = "needs the network"]+async fn a_public_page_quote_opens_at_it() {+ if computer::local_chrome_path().is_none() {+ eprintln!("skipped: no Chrome or Chromium installed");+ return;+ }+ let e = setup().await;+ let _chrome = ChromeGuard(e.tmp.path().join("local-chrome"));+ let ctrl = get_or_create_browser_controller(&e.state, &e.bot.id).await.expect("local Chrome session");+ ctrl.navigate("https://www.gnu.org/philosophy/free-sw.en.html").await.unwrap();+ let read = page(&e, "?blocks=1").await;+ let lines: Vec<&str> = read["blocks"].as_array().unwrap().iter().filter_map(Value::as_str).collect();+ // A sentence-long block well down the article+ let line = lines[lines.len() / 2..]+ .iter()+ .find(|l| l.len() > 80 && l.len() < 300 && !l.ends_with('…'))+ .unwrap_or_else(|| panic!("{lines:?}"));+ let id = &line[1..line.find(']').unwrap()];+ let (status, c) = cite(&e, json!({"block": id})).await;+ assert_eq!(status, StatusCode::OK, "{c}");+ eprintln!("cited: {c}");+ let quote = c["quote"].as_str().unwrap();+ let y = open_link(&ctrl, c["link"].as_str().unwrap()).await;+ let start: String = quote.chars().take(25).collect();+ assert!(y > 300.0, "scrolled: {y}");+ assert!(in_view(&ctrl, &start).await, "the quote is on screen: {start}");++ // A made-up quote is refused+ let (status, v) = cite(&e, json!({"text": "Free software was invented on the Moon in 1802."})).await;+ assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY, "{v}");+}diff --git a/tests/browser_tools_test.rs b/tests/browser_tools_test.rsindex fa38f17f..90aded8f 100644--- a/tests/browser_tools_test.rs+++ b/tests/browser_tools_test.rs@@ -131,7 +131,7 @@ async fn claude_turn_gets_browser_tools_that_drive_its_own_panel() {.await.unwrap();let names = tool_names(&app, &token).await;- for tool in ["browser_open", "browser_page", "browser_act", "browser_screenshot", "memory_add"] {+ for tool in ["browser_open", "browser_page", "browser_act", "browser_screenshot", "browser_cite", "memory_add"] {assert!(names.iter().any(|n| n == tool), "{tool} missing from {names:?}");}// Without a sandbox (e.g. a turn that shows no panel) they aren't offered or callable@@ -145,6 +145,7 @@ async fn claude_turn_gets_browser_tools_that_drive_its_own_panel() {assert_eq!(claude_asks(&app, &token, &format!("mcp__{SELF_SERVER_NAME}__browser_open")).await, "allow");assert_eq!(claude_asks(&app, &token, &format!("mcp__{SELF_SERVER_NAME}__browser_act")).await, "allow");assert_eq!(claude_asks(&app, &token, &format!("mcp__{SELF_SERVER_NAME}__browser_screenshot")).await, "allow");+ assert_eq!(claude_asks(&app, &token, &format!("mcp__{SELF_SERVER_NAME}__browser_cite")).await, "allow");assert!(state.broker.pending_ids().await.is_empty(), "no approval card for the bot's own browser");// The prompt tells a tools turn to use them, not curl through a shell it doesn't have