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
Bot browser downloads land in its folder; browser_upload answers the page's picker (#593)
Oleksandr Ivanchenko7bdefb8c0f6d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 45053ff7..c8291390 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).## Unreleased+### Added+- Bots can open menus that show only on hover, like a video tile's ⋮ menu: the tile and its hidden buttons now appear in the bot's list of controls, clicking one moves the mouse over the tile first, and a new hover action shows what appears. The payment check is unchanged.+- Bots can download and upload files in their browser: a download is saved in the bot's own folder under downloads/ and never replaces a file already there, and a new browser_upload tool gives a page's file picker a file from the bot's folder or a chat attachment. Under Ask, each upload asks you first.+## [Mac 0.9.12] - 2026-11-14kwant 0.9.12: Dev mode that says when it finds your code and lighter long jobs on API engines.diff --git a/frontend/src/components/ModernApprovalCard.tsx b/frontend/src/components/ModernApprovalCard.tsxindex 42ede829..afeb001e 100644--- a/frontend/src/components/ModernApprovalCard.tsx+++ b/frontend/src/components/ModernApprovalCard.tsx@@ -48,11 +48,12 @@ const mcpView = (approval: PendingApproval) => {};/** Arguments worth a line of their own on the card, in this order (0.6.13 spec C1). */-const KEY_FACTS = ['title', 'name', 'path', 'url', 'repo', 'command'];+const KEY_FACTS = ['title', 'name', 'path', 'files', 'url', 'repo', 'command'];/*** Up to two short "key: value" lines from a tool's arguments, so the card says what the call is- * about without opening the details. Only text and numbers; everything else stays in the details.+ * about without opening the details. Text, numbers, and an array of strings (joined); everything+ * else stays in the details.*/export function keyFacts(args: unknown, max = 2): Array<[string, string]> {if (!args || typeof args !== 'object' || Array.isArray(args)) return [];@@ -60,7 +61,10 @@ export function keyFacts(args: unknown, max = 2): Array<[string, string]> {const out: Array<[string, string]> = [];for (const k of KEY_FACTS) {const v = a[k];- const text = typeof v === 'string' ? v.trim() : typeof v === 'number' ? String(v) : '';+ const text = typeof v === 'string' ? v.trim()+ : typeof v === 'number' ? String(v)+ : Array.isArray(v) ? v.filter((x) => typeof x === 'string').join(', ')+ : '';if (text) out.push([k, text]);if (out.length >= max) break;}diff --git a/frontend/src/toolLabel.ts b/frontend/src/toolLabel.tsindex 7c32d686..c44087ef 100644--- a/frontend/src/toolLabel.ts+++ b/frontend/src/toolLabel.ts@@ -39,6 +39,7 @@ const VERBS: Record<string, Verb> = {browser_click: ['using the browser', 'use the browser'],browser_type: ['using the browser', 'use the browser'],browser_act: ['using the browser', 'use the browser'],+ browser_upload: ['uploading a file to a website', 'upload a file to a website'],browser_snapshot: ['reading the browser page', 'read the browser page'],browser_screenshot: ['looking at the browser page', 'look at the browser page'],ask_user: ['asking you a question', 'ask you a question'],diff --git a/frontend/tests/mobileCards.test.mjs b/frontend/tests/mobileCards.test.mjsindex 18c37b60..9f431b06 100644--- a/frontend/tests/mobileCards.test.mjs+++ b/frontend/tests/mobileCards.test.mjs@@ -85,6 +85,9 @@ test('approval card on a phone: header, one sentence, two key facts, details clo// title comes before repo in the spec's order; body/head/base stay in the details.assert.deepEqual(m.keyFacts(pr().details.arguments), [['title', 'Behind the seat: timed checkout'], ['repo', 'acme/site']]);assert.match(html, /data-approval-facts/);+ // #593: an array of strings (browser_upload's `files`) joins into one line instead of hiding.+ assert.deepEqual(m.keyFacts({ files: ['downloads/Self-checkout.mp4'] }), [['files', 'downloads/Self-checkout.mp4']]);+ assert.deepEqual(m.keyFacts({ files: ['a.txt', 'b.txt'] }), [['files', 'a.txt, b.txt']]);// Details start closed: the JSON is not in the markup, the toggle says so.assert.doesNotMatch(html, /data-approval-details=""/);assert.doesNotMatch(html, /"head"/);diff --git a/src/drivers/mod.rs b/src/drivers/mod.rsindex 202587a0..a708ebc6 100644--- a/src/drivers/mod.rs+++ b/src/drivers/mod.rs@@ -651,10 +651,12 @@ impl TurnInput {Your browser session is displayed live in the user's right panel; the user can browse in it too.\n\Never open a host desktop browser (no `open <url>`, `xdg-open`, etc.) and don't use the shell or curl for it. Use ONLY your `{tools}` tools:\n\- `browser_open` (url): open a page.\n\- - `browser_page` (optional find): read the page (url, title, text, clickable controls numbered like [3] button \"Add to cart\"; *[12] marks one that just appeared, e.g. an opened menu's options). 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_page` (optional find): read the page (url, title, text, clickable controls numbered like [3] button \"Add to cart\"; *[12] marks one that just appeared, e.g. an opened menu's options). 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. A file you downloaded shows as \"Download started: X (40%)\" then \"Downloaded X (size) to downloads/X in your folder.\"; a page's own file picker shows as a note starting \"A file picker opened\".\n\+ - `browser_act` (action click + ref, hover + 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. A control marked (on hover) shows only when the mouse is over its card (a tile's ⋮ button): click it as usual and the card is hovered first; action hover + ref or text only hovers and says what appeared.\n\- `browser_screenshot` (optional width, e.g. 390 phone / 1280 desktop; share: true also posts it in the chat as you): see the page as a picture, for layout, colours and spacing. When the person asks to see something (a mockup, a page, a change), share the picture: describing it isn't enough.\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\+ - `browser_upload` (files: one or more, each a path in your own folder, e.g. downloads/clip.mp4, or a chat attachment's id): answer a file picker the page has open. Refused if no picker is open. After you click the page's upload button, its result (or your next `browser_page`) has a note starting \"A file picker opened\"; then call browser_upload.\n\+ A download goes only into your own folder, under downloads/, never into the person's Downloads folder. Use the file only after the page state says \"Downloaded …\". \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}",@@ -666,12 +668,15 @@ impl TurnInput {Browser API: {api}\n\Never open a host desktop browser (no `open <url>`, `xdg-open`, etc.). Use ONLY these commands (the full API, do not search for more):\n\- Open a page: curl -sS -X POST '{api}/navigate' -H 'Content-Type: application/json' -d '{{\"url\":\"<url>\"}}'\n\- - Read the page (url, title, text, clickable controls numbered like [3] button \"Add to cart\"; *[12] marks one that just appeared, and a hash): curl -sS '{api}/page'. Add ?since=<hash of your last read> to get only \"unchanged\" when nothing changed, and &find=<words> on a page with many controls to list the matching ones first.\n\+ - Read the page (url, title, text, clickable controls numbered like [3] button \"Add to cart\"; *[12] marks one that just appeared, and a hash): curl -sS '{api}/page'. Add ?since=<hash of your last read> to get only \"unchanged\" when nothing changed, and &find=<words> on a page with many controls to list the matching ones first. A file you downloaded shows as \"Download started: X (40%)\" then \"Downloaded X (size) to downloads/X in your folder.\"; a page's own file picker shows as a note starting \"A file picker opened\".\n\- Click a control by its number from the clickable list: curl -sS -X POST '{api}/act' -H 'Content-Type: application/json' -d '{{\"action\":\"click\",\"ref\":3}}' (if it is gone or covered, nothing is clicked and you get a fresh list)\n\+ - A control marked (on hover), like [7] button \"More\" (on hover) · Clip 1, shows only when the mouse is over its card: click it by its number as usual and the card is hovered first. To only hover and see what appears: curl -sS -X POST '{api}/act' -H 'Content-Type: application/json' -d '{{\"action\":\"hover\",\"ref\":7}}'\n\- 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-9f2a41c0\"}}, 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\+ - Answer a file picker the page has open: curl -sS -X POST '{api}/act' -H 'Content-Type: application/json' -d '{{\"action\":\"upload\",\"files\":[\"downloads/clip.mp4\"]}}' (each a path in your own folder or a chat attachment's id). Refused if no picker is open.\n\+ A download goes only into your own folder, under downloads/, never into the person's Downloads folder. Use the file only after the page state says \"Downloaded …\". \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/mcp/payment_floor.rs b/src/mcp/payment_floor.rsindex 48ee369f..bb647974 100644--- a/src/mcp/payment_floor.rs+++ b/src/mcp/payment_floor.rs@@ -1091,6 +1091,8 @@ mod tests {assert!(act(json!({"action": "key", "key": "Tab"}), Some("https://shop.example.com/checkout")).is_none());assert!(act(json!({"action": "key", "key": "Enter"}), Some("https://example.com/search")).is_none());assert!(act(json!({"action": "scroll"}), Some("https://shop.example.com/checkout")).is_none());+ // A hover only moves the mouse: it never pays, even over "Pay now" on a checkout page+ assert!(act(json!({"action": "hover", "text": "Pay now"}), Some("https://shop.example.com/checkout")).is_none());// Typing a card number anywhereassert!(act(json!({"action": "type", "text": "4111-1111-1111-1111"}), None).is_some());assert!(act(json!({"action": "type", "text": "4111 1111 1111 1112"}), None).is_none(), "fails Luhn");diff --git a/src/sandbox/browser.rs b/src/sandbox/browser.rsindex 2e51a735..caf95fb2 100644--- a/src/sandbox/browser.rs+++ b/src/sandbox/browser.rs@@ -145,15 +145,51 @@ async fn await_reply(ws: &mut WsStream, id: u64) -> Result<Result<Value, BrowserErr(BrowserError::Protocol("Connection closed before response".into()))}-/// `function(needle)` evaluated in the page. Collects visible interactive elements (incl. open-/// shadow roots and same-origin iframes), topmost first. With a needle, picks the best label match-/// and either returns its viewport center (when nothing covers it) or clicks it directly. With-/// `probe`, returns the matched item itself (with its element) and touches nothing.+/// `function(needle, probe)` evaluated in the page. Collects visible interactive elements (incl.+/// open shadow roots and same-origin iframes), topmost first. After them it lists, at most 40 of+/// each, controls that show only on hover (opacity 0 or visibility hidden inside a shown card: a+/// tile's ⋮ button), with the card to hover, and then clickable cards (the outermost element with+/// a pointer cursor whose parent has none: a tile with a JS click listener), so tiles never push+/// ordinary controls out of a capped list. An icon-only control+/// is named by its aria-label or title, else by its icon word (`more_vert` reads "More").+/// With a needle, picks the best label match (controls listed before cards and hover controls+/// existed first) and either returns its viewport center (when nothing covers it), clicks it+/// directly, or, for a control shown on hover, keeps it for `REF_JS('hovered')` and says+/// `hover: true`. With `probe`, returns the matched item itself (with its element and the label+/// the payment floor judged before icon words were read) and touches nothing; with no needle+/// either, returns all items (with their elements).const CLICKABLES_JS: &str = r#"function (needle, probe) {var SEL = 'button,a[href],[role=button],[role=link],[role=menuitem],[role=tab],[role=checkbox],[role=option],input,textarea,select,summary,label,[onclick]';- var items = [];+ // Clickable cards (a div with a JS click listener) and controls shown only on hover are listed+ // at most this many each, after the ordinary controls, so a busy page doesn't flood the list+ var CARD_CAP = 40, HOVER_CAP = 40;+ // The word a person reads for an icon-only control's icon-font word (Material icons and symbols)+ var ICONS = { more_vert: 'More', more_horiz: 'More', download: 'Download', file_download: 'Download',+ close: 'Close', delete: 'Delete', delete_outline: 'Delete', edit: 'Edit', share: 'Share', ios_share: 'Share',+ content_copy: 'Copy', play_arrow: 'Play', pause: 'Pause', search: 'Search', menu: 'Menu', settings: 'Settings',+ upload: 'Upload', file_upload: 'Upload', add: 'Add', arrow_back: 'Back', favorite: 'Like', favorite_border: 'Like' };+ var ICON_SEL = 'i,mat-icon,[class*=icon],[class*=Icon],[class*=symbol],[class*=Symbol]';+ var items = [], cards = [], hovers = [], seq = 0;+ var styles = new Map(), fades = new Map();function clean(s) { return (s || '').replace(/\s+/g, ' ').trim().slice(0, 80); }- // A control's role for the ref list: what it is, in one word+ function style(el) { var s = styles.get(el); if (!s) { s = getComputedStyle(el); styles.set(el, s); } return s; }+ // The parent element, also out of a shadow root (to its host); null at a document's top+ function up(el) { return el.parentElement || (el.parentNode && el.parentNode.host) || null; }+ // Whether el or an element around it is fully see-through (opacity 0)+ function faded(el) {+ if (!el || el.nodeType !== 1) return false;+ if (fades.has(el)) return fades.get(el);+ var f = Number(style(el).opacity) === 0 || faded(up(el));+ fades.set(el, f);+ return f;+ }+ // innerText leaves out the text of a visibility:hidden element; a control shown on hover still has a name+ function textOf(el) {+ var t = el.innerText;+ if (!clean(t) && style(el).visibility !== 'visible') t = el.textContent;+ return t || '';+ }+ // A control a role for the ref list: what it is, in one wordfunction roleOf(el) {var role = (el.getAttribute('role') || '').toLowerCase();if (role) return role;@@ -165,7 +201,17 @@ const CLICKABLES_JS: &str = r#"function (needle, probe) {if (tag === 'TEXTAREA' || (tag === 'INPUT' && ['submit', 'button', 'image', 'reset'].indexOf(t) < 0)) return 'field';return 'button';}- function nameOf(el) {+ // The icon-font word an icon-only control shows (its whole text, in an icon element), or ''+ function iconWord(el, text) {+ if (!/^[a-z][a-z0-9]*(_[a-z0-9]+)*$/.test(text)) return '';+ var icons = [el].concat(Array.prototype.slice.call(el.querySelectorAll(ICON_SEL)));+ for (var i = 0; i < icons.length; i++) {+ if ((i > 0 || el.matches(ICON_SEL)) && clean(icons[i].textContent) === text) return text;+ }+ return '';+ }+ // With old, the name as it was before icon words were read (the payment floor judges that one)+ function nameOf(el, old) {var tag = el.tagName;if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') {var t = (el.type || '').toLowerCase();@@ -173,13 +219,34 @@ const CLICKABLES_JS: &str = r#"function (needle, probe) {if (t === 'hidden') return '';return clean(el.getAttribute('aria-label') || el.placeholder || el.name || el.id);}- return clean(el.innerText || el.getAttribute('aria-label') || el.title || el.value);+ if (old) return clean(el.innerText || el.getAttribute('aria-label') || el.title || el.value);+ var text = textOf(el), word = iconWord(el, clean(text));+ if (word) return clean(el.getAttribute('aria-label') || el.title) || (ICONS.hasOwnProperty(word) ? ICONS[word] : word);+ return clean(text || el.getAttribute('aria-label') || el.title || el.value);}- function labelOf(el) {- var name = nameOf(el), tag = el.tagName, t = (el.type || '').toLowerCase();+ function labelOf(el, old) {+ var name = nameOf(el, old), tag = el.tagName, t = (el.type || '').toLowerCase();if (!name || !(tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') || t === 'submit' || t === 'button') return name;return name + ' (' + (t === 'checkbox' || t === 'radio' ? t : 'field') + ')';}+ // A card's name: its aria-label or title, else its first line of text that isn't one of its own+ // controls or icons (a tile's ⋮ button reads more_vert), else an image's alt text+ function cardLabel(el) {+ var named = clean(el.getAttribute('aria-label') || el.title);+ if (named) return named.slice(0, 60);+ var own = new Set(), inner = el.querySelectorAll(SEL + ',' + ICON_SEL);+ for (var i = 0; i < inner.length; i++) {+ var ls = (inner[i].innerText || inner[i].textContent || '').split('\n');+ for (var k = 0; k < ls.length; k++) own.add(clean(ls[k]));+ }+ var lines = (el.innerText || '').split('\n');+ for (var j = 0; j < lines.length; j++) {+ var line = clean(lines[j]);+ if (line && !own.has(line)) return line.slice(0, 60);+ }+ var img = el.querySelector('img[alt]:not([alt=""])');+ return img ? clean(img.alt).slice(0, 60) : '';+ }// The text that tells a repeated control apart (the product a repeated "Add to cart" belongs// to): the first line of the largest block around it that holds no other control of that namefunction contextOf(el, name, twins) {@@ -197,6 +264,46 @@ const CLICKABLES_JS: &str = r#"function (needle, probe) {}return '';}+ // The visible element to hover so that el shows: the nearest one around it that is shown and+ // larger than el (the tile, not a wrapper of the button's own size)+ function cardFor(el, r0) {+ for (var a = up(el), d = 0; a && d < 12; a = up(a), d++) {+ if (a.tagName === 'BODY' || a.tagName === 'HTML') return null;+ var r = a.getBoundingClientRect();+ if (r.width < r0.width + 8 && r.height < r0.height + 8) continue;+ var cs = style(a);+ if (cs.display === 'none' || cs.visibility !== 'visible' || faded(a)) continue;+ return a;+ }+ return null;+ }+ // A card: the outermost element with a pointer cursor that isn't (in) a listed control+ function isCard(el) {+ if (el.tagName === 'BODY' || el.tagName === 'HTML' || style(el).cursor !== 'pointer') return false;+ var p = up(el);+ if (p && style(p).cursor === 'pointer') return false;+ return !el.closest(SEL);+ }+ // One control covers (nearly) all of it: that control is listed itself+ function filled(el, r) {+ var inner = el.querySelectorAll(SEL);+ for (var i = 0; i < inner.length; i++) {+ var q = inner[i].getBoundingClientRect();+ if (q.width * q.height >= 0.8 * r.width * r.height) return true;+ }+ return false;+ }+ function place(el, r, root, ox, oy) {+ var lx = r.left + r.width / 2, ly = r.top + r.height / 2;+ var x = ox + lx, y = oy + ly;+ var inView = x >= 0 && y >= 0 && x <= innerWidth && y <= innerHeight;+ var onTop = false;+ if (inView) {+ var hit = root.elementFromPoint ? root.elementFromPoint(lx, ly) : null;+ onTop = !hit || hit === el || el.contains(hit) || hit.contains(el);+ }+ return { x: Math.round(x), y: Math.round(y), inView: inView, onTop: onTop };+ }function walk(root, ox, oy) {var all;try { all = root.querySelectorAll('*'); } catch (e) { return; }@@ -207,38 +314,72 @@ const CLICKABLES_JS: &str = r#"function (needle, probe) {try { var d = el.contentDocument; if (d) { var fr = el.getBoundingClientRect(); walk(d, ox + fr.left, oy + fr.top); } } catch (e) {}continue;}- if (!el.matches(SEL)) continue;- var r = el.getBoundingClientRect();+ var r, cs, p;+ if (!el.matches(SEL)) {+ if (!isCard(el)) continue;+ r = el.getBoundingClientRect();+ var win = el.ownerDocument.defaultView || window;+ if (r.width < 16 || r.height < 16 || (r.width >= win.innerWidth * 0.95 && r.height >= win.innerHeight * 0.95)) continue;+ cs = style(el);+ if (cs.visibility !== 'visible' || cs.display === 'none' || faded(el) || filled(el, r)) continue;+ var name = cardLabel(el);+ if (!name) continue;+ p = place(el, r, root, ox, oy);+ cards.push({ seq: seq++, label: name, old: name, name: name, role: 'card', kind: 'card', x: p.x, y: p.y, inView: p.inView, onTop: p.onTop, el: el, tier: 1 });+ continue;+ }+ r = el.getBoundingClientRect();if (r.width < 2 || r.height < 2) continue;- var cs = getComputedStyle(el);- if (cs.visibility === 'hidden' || cs.display === 'none' || Number(cs.opacity) === 0) continue;- var label = labelOf(el);+ cs = style(el);+ if (cs.display === 'none') continue;+ // Hidden only until the mouse is over something around it: a ⋮ button at opacity 0 on a tile+ var hidden = cs.visibility === 'hidden' || Number(cs.opacity) === 0;+ var role = roleOf(el), card = null;+ if (hidden || faded(up(el))) card = role === 'field' || role === 'checkbox' || role === 'radio' || role === 'select' ? null : cardFor(el, r);+ if (hidden && !card) continue;+ var label = labelOf(el, false);if (!label) continue;- var lx = r.left + r.width / 2, ly = r.top + r.height / 2;- var x = ox + lx, y = oy + ly;- var inView = x >= 0 && y >= 0 && x <= innerWidth && y <= innerHeight;- var onTop = false;- if (inView) {- var hit = root.elementFromPoint ? root.elementFromPoint(lx, ly) : null;- onTop = !hit || hit === el || el.contains(hit) || hit.contains(el);- }- items.push({ label: label, name: nameOf(el), role: roleOf(el), x: Math.round(x), y: Math.round(y), inView: inView, onTop: onTop, el: el });+ p = place(el, r, root, ox, oy);+ var item = { seq: seq++, label: label, old: labelOf(el, true), name: nameOf(el, false), role: role, kind: 'control',+ x: p.x, y: p.y, inView: p.inView, onTop: p.onTop, el: el, tier: hidden ? 1 : 0,+ card: card, cardLabel: card ? cardLabel(card) : '' };+ (hidden ? hovers : items).push(item);}}walk(document, 0, 0);- items.sort(function (a, b) { return (b.onTop - a.onTop) || (b.inView - a.inView); });+ // Each kind topmost first, then in page order. Ordinary controls come first, then the ones shown+ // on hover, then cards, so a page of many tiles never pushes its buttons out of a capped list+ function order(a, b) { return (b.onTop - a.onTop) || (b.inView - a.inView) || (a.seq - b.seq); }+ items = items.sort(order).concat(hovers.sort(order).slice(0, HOVER_CAP), cards.sort(order).slice(0, CARD_CAP));+ function registry() {+ var reg = window[Symbol.for('kwnt.refs')];+ if (!reg) {+ reg = { gen: 0 };+ try { Object.defineProperty(window, Symbol.for('kwnt.refs'), { value: reg }); } catch (e) {}+ }+ return reg;+ }var match = null;if (needle) {+ // The controls listed before cards and hover-only controls existed first, so a label that+ // matched one of those still picks the same element (the payment floor judges that one)var n = clean(needle).toLowerCase(), best = 0;- for (var j = 0; j < items.length; j++) {- var l = items[j].label.toLowerCase();- var s = l === n ? 3 : l.indexOf(n) === 0 ? 2 : l.indexOf(n) >= 0 ? 1 : 0;- if (s > best) { best = s; match = items[j]; }+ for (var tier = 0; tier < 2 && !best; tier++) {+ for (var j = 0; j < items.length; j++) {+ if (items[j].tier !== tier) continue;+ var l = items[j].label.toLowerCase();+ var s = l === n ? 3 : l.indexOf(n) === 0 ? 2 : l.indexOf(n) >= 0 ? 1 : 0;+ if (s > best) { best = s; match = items[j]; }+ }}- if (probe) return match;+ if (probe) return match ? { el: match.el, label: match.old || match.label, item: match } : null;if (match) {var m = match.el;- if (!match.onTop) {+ if (match.card) {+ // Shown on hover: the click hovers its card first (see REF_JS 'hovered')+ registry().hovered = { el: m, label: match.label, old: match.old, kind: match.kind, card: match.card, cardLabel: match.cardLabel };+ match = { label: match.label, hover: true, clicked: false };+ } else if (!match.onTop) {m.scrollIntoView({ block: 'center' });if (typeof m.focus === 'function') m.focus();m.click();@@ -248,16 +389,21 @@ const CLICKABLES_JS: &str = r#"function (needle, probe) {}}}+ if (!needle) {+ // Listed, a control inside a see-through wrapper (shown on hover too, but matched with the+ // ordinary controls, as before cards existed) joins the other hover controls+ var plain = [], onHover = [], tiles = [];+ items.forEach(function (i) { (i.kind === 'card' ? tiles : i.card ? onHover : plain).push(i); });+ items = plain.concat(onHover.sort(order), tiles);+ }+ // A peek (no needle, probe): the items with their elements, without numbering them+ if (!needle && probe) return items;if (!needle) {// A listing numbers the controls (ref = position + 1) and keeps their elements in the page,// so the next `act` by ref hits exactly this element or says it is gonevar twins = {};for (var k = 0; k < items.length; k++) (twins[items[k].name] = twins[items[k].name] || []).push(items[k].el);- var reg = window[Symbol.for('kwnt.refs')];- if (!reg) {- reg = { gen: 0 };- try { Object.defineProperty(window, Symbol.for('kwnt.refs'), { value: reg }); } catch (e) {}- }+ var reg = registry();// A control is new when its element wasn't in this page's previous list (a dropdown's// options, a dialog's buttons). The first list of a page, and one after the address changed// (other than its #fragment), marks nothing@@ -265,69 +411,143 @@ const CLICKABLES_JS: &str = r#"function (needle, probe) {var before = reg.items && reg.href === here ? new Set(reg.items.map(function (i) { return i.el; })) : null;reg.gen += 1;reg.href = here;- reg.items = items.map(function (i) { return { el: i.el, label: i.label }; });+ reg.items = items.map(function (i) { return { el: i.el, label: i.label, old: i.old, kind: i.kind, card: i.card, cardLabel: i.cardLabel }; });reg.labelOf = labelOf;+ reg.cardLabel = cardLabel;return { gen: reg.gen, items: items.map(function (i, k) {- return { ref: k + 1, label: i.label, name: i.name, role: i.role, onTop: i.onTop,+ return { ref: k + 1, label: i.label, name: i.name, role: i.role, onTop: i.onTop, hover: !!i.card,new: !!before && !before.has(i.el),- context: twins[i.name].length > 1 ? contextOf(i.el, i.name, twins[i.name]) : '' };+ context: i.card ? i.cardLabel : twins[i.name].length > 1 ? contextOf(i.el, i.name, twins[i.name]) : '' };}) };}return { items: items.map(function (i) { return { label: i.label, onTop: i.onTop }; }), match: match };}"#;-/// Finds control `ref` from the last listing (see [`CLICKABLES_JS`]). With `probe`, returns-/// `{el, label}` (or null) and touches nothing. Otherwise checks it can still be clicked: still-/// in the page, shown, the same label, and on top at its center after scrolling it into view-/// (so a cookie banner or modal over it is reported, not clicked through). Returns-/// `{ok: true, x, y, label}` in top-page pixels, or `{ok: false, why}`.+/// Finds control `ref` from the last listing (see [`CLICKABLES_JS`]), or with `"hovered"` the+/// hover-only control a click by label picked. With `probe` true, returns `{el, label}` (or+/// null) and touches nothing. Otherwise checks it can still be clicked: still in the page, shown,+/// the same label, and on top at its center after scrolling it into view (so a cookie banner or+/// modal over it is reported, not clicked through). Returns `{ok: true, x, y, label, hovered}` in+/// top-page pixels, or `{ok: false, why}`. A control that shows on hover and isn't shown yet+/// returns `{ok: false, hover: {x, y, card}}`: where to put the mouse first; with `probe` 'spot'+/// that place comes back as `{ok: true, x, y, label, card}`.const REF_JS: &str = r#"function (ref, probe) {function clean(s) { return (s || '').replace(/\s+/g, ' ').trim().slice(0, 80); }var reg = window[Symbol.for('kwnt.refs')];- var item = reg && reg.items && reg.items[ref - 1];- if (probe) return item ? { el: item.el, label: item.label } : null;+ // 'hovered': the control a click by label picked that shows only on hover+ var item = ref === 'hovered' ? reg && reg.hovered : reg && reg.items && reg.items[ref - 1];+ if (probe === true) return item ? { el: item.el, label: item.old || item.label } : null;if (!item) return { ok: false, why: reg ? 'there is no ref ' + ref + ' in the last list' : 'this page has no list of refs yet (it changed or reloaded)' };var el = item.el;if (!el.isConnected) return { ok: false, why: 'it is no longer on the page' };- var label = reg.labelOf ? reg.labelOf(el) : item.label;+ var label = item.kind === 'card' ? (reg.cardLabel ? reg.cardLabel(el) : item.label) : reg.labelOf ? reg.labelOf(el) : item.label;if (label !== item.label) return { ok: false, why: 'it now reads "' + label + '", not "' + item.label + '"' };- function shown() {- var r = el.getBoundingClientRect();+ // A control shown on hover counts as shown only when nothing around it is see-through either+ function seeThrough(node) {+ for (var a = node; a && a.nodeType === 1; a = a.parentElement || (a.parentNode && a.parentNode.host)) {+ if (Number(getComputedStyle(a).opacity) === 0) return true;+ }+ return false;+ }+ function shown(node, whole) {+ var r = node.getBoundingClientRect();if (r.width < 2 || r.height < 2) return null;- var cs = getComputedStyle(el);+ var cs = getComputedStyle(node);if (cs.visibility === 'hidden' || cs.display === 'none' || Number(cs.opacity) === 0) return null;+ if (whole && (cs.visibility !== 'visible' || seeThrough(node))) return null;return r;}- var r = shown();- if (!r) return { ok: false, why: 'it is hidden now' };- var win = el.ownerDocument.defaultView;- if (r.top < 0 || r.left < 0 || r.bottom > win.innerHeight || r.right > win.innerWidth) {- el.scrollIntoView({ block: 'center', inline: 'center' });- r = shown();- if (!r) return { ok: false, why: 'it is hidden now' };- }- var lx = r.left + r.width / 2, ly = r.top + r.height / 2;- // The top-page point: add the offsets of the (same-origin) frames it sits in- var x = lx, y = ly, frames = [];- for (var w = win; w !== w.top && w.frameElement; w = w.parent) {- var fr = w.frameElement.getBoundingClientRect();- x += fr.left; y += fr.top;- frames.push(w.frameElement);- }- if (x < 0 || y < 0 || x > innerWidth || y > innerHeight) return { ok: false, why: 'it is outside the window' };function covers(hit, target) { return !hit || hit === target || target.contains(hit) || hit.contains(target); }function what(hit) {var t = clean(hit.innerText || hit.getAttribute('aria-label') || '').slice(0, 40);return hit.tagName.toLowerCase() + (t ? ' "' + t + '"' : '');}- var root = el.getRootNode();- var hit = root.elementFromPoint ? root.elementFromPoint(lx, ly) : null;- if (!covers(hit, el)) return { ok: false, why: 'it is covered by ' + what(hit) };- if (frames.length) {- var top = document.elementFromPoint(x, y), outer = frames[frames.length - 1];- if (!covers(top, outer)) return { ok: false, why: 'it is covered by ' + what(top) };+ // Where to put the mouse on node, in top-page pixels: its center, scrolled into view, and+ // nothing over it (so a cookie banner or modal over it is reported, not clicked through)+ function spot(node, whole) {+ var r = shown(node, whole);+ if (!r) return { ok: false, why: 'it is hidden now' };+ var win = node.ownerDocument.defaultView;+ if (r.top < 0 || r.left < 0 || r.bottom > win.innerHeight || r.right > win.innerWidth) {+ node.scrollIntoView({ block: 'center', inline: 'center' });+ r = shown(node, whole);+ if (!r) return { ok: false, why: 'it is hidden now' };+ }+ var lx = r.left + r.width / 2, ly = r.top + r.height / 2;+ // The top-page point: add the offsets of the (same-origin) frames it sits in+ var x = lx, y = ly, frames = [];+ for (var w = win; w !== w.top && w.frameElement; w = w.parent) {+ var fr = w.frameElement.getBoundingClientRect();+ x += fr.left; y += fr.top;+ frames.push(w.frameElement);+ }+ if (x < 0 || y < 0 || x > innerWidth || y > innerHeight) return { ok: false, why: 'it is outside the window' };+ var root = node.getRootNode();+ var hit = root.elementFromPoint ? root.elementFromPoint(lx, ly) : null;+ if (!covers(hit, node)) return { ok: false, why: 'it is covered by ' + what(hit) };+ if (frames.length) {+ var top = document.elementFromPoint(x, y), outer = frames[frames.length - 1];+ if (!covers(top, outer)) return { ok: false, why: 'it is covered by ' + what(top) };+ }+ return { ok: true, x: Math.round(x), y: Math.round(y) };+ }+ var card = item.card;+ if (card && !shown(el, true)) {+ // Shown only on hover: say where to hover (its card), or why that can't be done+ if (!card.isConnected) return { ok: false, why: 'it is hidden now' };+ var c = spot(card, true);+ if (!c.ok) return { ok: false, why: 'it shows on hover, and its card "' + item.cardLabel + '" ' + c.why.replace(/^it /, '') };+ if (probe === 'spot') return { ok: true, x: c.x, y: c.y, label: item.label, card: item.cardLabel };+ return { ok: false, hover: { x: c.x, y: c.y, card: item.cardLabel }, label: item.label };+ }+ var s = spot(el, !!card);+ if (!s.ok) return s;+ return { ok: true, x: s.x, y: s.y, label: item.label, hovered: !!card };+}"#;++/// `function(target)`: a label or a ref to hover. Finds it (as a click would), keeps what is+/// shown now (for [`APPEARED_JS`]) and returns where to put the mouse: the card of a control that+/// shows on hover, else the control itself, as `{ok, x, y, label, card}` or `{ok: false, why}`.+const HOVER_JS: &str = r#"function (target) {+ var CLICK = __CLICKABLES__;+ var REF = __REF__;+ var key = target;+ if (typeof target === 'string') {+ var m = CLICK(target, true);+ if (!m) return { ok: false, why: 'nothing on the page matches "' + target + '"' };+ var reg = window[Symbol.for('kwnt.refs')];+ if (!reg) {+ reg = { gen: 0 };+ try { Object.defineProperty(window, Symbol.for('kwnt.refs'), { value: reg }); } catch (e) {}+ }+ var i = m.item;+ reg.hovered = { el: i.el, label: i.label, old: i.old, kind: i.kind, card: i.card, cardLabel: i.cardLabel };+ key = 'hovered';+ }+ var spot = REF(key, 'spot');+ if (spot.ok) {+ // What is shown now, to tell what the hover brings up+ var shown = new Set();+ var now = CLICK(null, true);+ for (var k = 0; k < now.length; k++) if (!now[k].card) shown.add(now[k].el);+ window[Symbol.for('kwnt.refs')].shownBefore = shown;+ }+ return spot;+}"#;++/// `function()` after a hover: the controls shown now that weren't before it (at most 12), as+/// `Label (role)`.+const APPEARED_JS: &str = r#"function () {+ var CLICK = __CLICKABLES__;+ var reg = window[Symbol.for('kwnt.refs')];+ var before = reg && reg.shownBefore;+ if (!before) return [];+ reg.shownBefore = null;+ var now = CLICK(null, true), out = [];+ for (var k = 0; k < now.length && out.length < 12; k++) {+ if (!now[k].card && !before.has(now[k].el)) out.push(now[k].label + ' (' + now[k].role + ')');}- return { ok: true, x: Math.round(x), y: Math.round(y), label: item.label };+ return out;}"#;/// What the payment floor needs from the page before a `browser_act` (see@@ -580,7 +800,8 @@ impl ClickTarget {}/// One line of the control list: `[3] button "Add to cart" · Sauce Labs Backpack`. The context-/// (nearby text) is only there when several controls share a name. A control that wasn't in the+/// (nearby text) is only there when several controls share a name, or, for a control that shows+/// on hover (marked [`HOVER_MARK`]), it is the card to hover. A control that wasn't in the/// page's previous list starts with [`NEW_MARK`]: `*[12] option "Large"`.pub fn ref_line(item: &Value) -> Option<String> {let r = item["ref"].as_u64()?;@@ -588,6 +809,9 @@ pub fn ref_line(item: &Value) -> Option<String> {let role = item["role"].as_str().filter(|r| !r.is_empty()).unwrap_or("button");let mark = if item["new"].as_bool() == Some(true) { NEW_MARK } else { "" };let mut line = format!("{mark}[{r}] {role} \"{name}\"");+ if item["hover"].as_bool() == Some(true) {+ line.push_str(HOVER_MARK);+ }if let Some(ctx) = item["context"].as_str().filter(|c| !c.is_empty()) {line.push_str(" · ");line.push_str(ctx);@@ -595,6 +819,22 @@ pub fn ref_line(item: &Value) -> Option<String> {Some(line)}+/// Marks a control that shows only when the mouse is over its card (the card follows as the+/// context): `[7] button "More" (on hover) · Clip 1`. A click on it hovers the card first.+pub const HOVER_MARK: &str = " (on hover)";++/// How long a page gets to show what it shows on hover (a CSS transition, a JS mouseenter).+const HOVER_SETTLE: Duration = Duration::from_millis(200);++/// What a hover brought up, for the bot: `Hovered over "Clip 1". Appeared: More (button)`.+pub fn hover_summary(over: &str, appeared: &[String]) -> String {+ if appeared.is_empty() {+ format!("Hovered over \"{over}\". Nothing new appeared.")+ } else {+ format!("Hovered over \"{over}\". Appeared: {}", appeared.join(", "))+ }+}+/// Marks a control line as new since the page's previous list (see [`ref_line`]).pub const NEW_MARK: &str = "*";@@ -1258,6 +1498,9 @@ pub struct BrowserController {needs_wake: Arc<AtomicBool>,/// How many live views show this page now: a watched page is never frozen.watchers: Arc<AtomicUsize>,+ /// The bot session's own download/chooser connection (see [`super::browser_downloads`]),+ /// started once this controller has a working folder to land downloads in.+ downloads: Arc<std::sync::Mutex<Option<super::browser_downloads::DownloadCenter>>>,}/// Stops media in a page that is put to rest, so a feed or video doesn't keep decoding. Media it@@ -1346,6 +1589,7 @@ impl BrowserController {ws_generation: Arc::default(),needs_wake: Arc::default(),watchers: Arc::default(),+ downloads: Arc::default(),}}@@ -1450,6 +1694,56 @@ impl BrowserController {ctrl}+ /// Starts this session's own download/chooser connection, landing downloads under+ /// `workspace/downloads/` and reporting (but not auto-answering) file pickers it opens.+ /// Idempotent: a session already running its own connection keeps it. `local`, `context_id`+ /// and `staging_root` are passed straight to [`super::browser_downloads::DownloadCenter::start`].+ pub async fn configure_downloads(+ &self,+ workspace: std::path::PathBuf,+ local: bool,+ context_id: Option<String>,+ staging_root: std::path::PathBuf,+ ) {+ if self.downloads.lock().unwrap_or_else(|e| e.into_inner()).is_some() {+ return;+ }+ let center = super::browser_downloads::DownloadCenter::start(self.clone(), workspace, local, context_id, staging_root).await;+ let mut guard = self.downloads.lock().unwrap_or_else(|e| e.into_inner());+ if guard.is_none() {+ *guard = Some(center);+ }+ }++ /// One line worth telling the bot about its most recent download, if the session has its own+ /// connection running and there's something new to say.+ pub fn latest_download_report(&self) -> Option<serde_json::Value> {+ self.downloads.lock().unwrap_or_else(|e| e.into_inner()).as_ref()?.report()+ }++ /// The current download's status, like `latest_download_report`, but without consuming a+ /// terminal state: for a page read that's a side effect of something else, so the bot's own+ /// dedicated "did it finish" check still gets to see the terminal state once.+ pub fn peek_download_report(&self) -> Option<serde_json::Value> {+ self.downloads.lock().unwrap_or_else(|e| e.into_inner()).as_ref()?.peek()+ }++ /// The currently open file picker on this session, if any.+ pub fn open_chooser_report(&self) -> Option<serde_json::Value> {+ self.downloads.lock().unwrap_or_else(|e| e.into_inner()).as_ref()?.open_chooser()+ }++ /// Answers the currently open chooser on this session with `files`. Refuses with a plain+ /// message if no download/chooser connection is running (the session was never configured)+ /// or no picker is open.+ pub async fn answer_upload(&self, local: bool, files: Vec<super::browser_downloads::UploadFile>) -> Result<Vec<String>, String> {+ let center = self.downloads.lock().unwrap_or_else(|e| e.into_inner()).clone();+ let Some(center) = center else {+ return Err("This session isn't set up to answer file pickers yet.".into());+ };+ center.answer_chooser(local, files).await+ }+/// The person's control for one live view. Refused with [`BrowserError::HeldByPerson`] while/// another live view has it, and with [`BrowserError::HumanControl`] while a bot is mid-step.pub async fn take_control(&self) -> Result<PersonLease, BrowserError> {@@ -2341,27 +2635,55 @@ impl BrowserController {}/// Clicks control `r` from the last list with a real mouse click at its center, after- /// checking it is still in the page, shown, unchanged and not covered (see [`REF_JS`]).+ /// checking it is still in the page, shown, unchanged and not covered (see [`REF_JS`]). A+ /// control that shows only on hover (a tile's ⋮ button) gets the mouse over its card first./// Otherwise clicks nothing and says why ([`BrowserError::StaleRef`]); the page state the/// caller returns next re-lists the controls.pub async fn click_ref(&self, r: u32) -> Result<String, BrowserError> {+ self.click_checked(json!(r), &format!("ref {r}")).await+ }++ /// One [`REF_JS`] check of `key` (a ref, or `"hovered"`).+ async fn ref_check(&self, key: &Value) -> Result<Value, BrowserError> {let res = self.send_cdp_command("Runtime.evaluate",- json!({ "expression": format!("({REF_JS})({r}, false)"), "returnByValue": true }),+ json!({ "expression": format!("({REF_JS})({key}, false)"), "returnByValue": true }),).await?;if let Some(err) = res.get("exceptionDetails") {return Err(BrowserError::Protocol(format!("ref check failed: {}", err["text"])));}- let v = &res["result"]["value"];+ Ok(res["result"]["value"].clone())+ }++ /// Clicks `key` (see [`Self::ref_check`]) after checking it. A control shown only on hover+ /// gets the mouse over its card, a moment to show, and the check again: still hidden means+ /// nothing is clicked. `what` names it in the error ("ref 3", "\"More\"").+ async fn click_checked(&self, key: Value, what: &str) -> Result<String, BrowserError> {+ let mut v = self.ref_check(&key).await?;+ if let Some(h) = v.get("hover").filter(|h| h.is_object()).cloned() {+ self.mouse_move(h["x"].as_i64().unwrap_or(0), h["y"].as_i64().unwrap_or(0)).await?;+ tokio::time::sleep(HOVER_SETTLE).await;+ v = self.ref_check(&key).await?;+ if v.get("hover").is_some_and(Value::is_object) {+ let card = h["card"].as_str().unwrap_or_default();+ return Err(BrowserError::StaleRef(format!(+ "Didn't click {what}: it stayed hidden after hovering over \"{card}\". The clickable list was read again just now; pick from the new list."+ )));+ }+ }if v["ok"].as_bool() != Some(true) {let why = v["why"].as_str().unwrap_or("it can't be found");return Err(BrowserError::StaleRef(format!(- "Didn't click ref {r}: {why}. The clickable list was read again just now; pick from the new list."+ "Didn't click {what}: {why}. The clickable list was read again just now; pick from the new list.")));}let (x, y) = (v["x"].as_i64().unwrap_or(0), v["y"].as_i64().unwrap_or(0));+ if v["hovered"].as_bool() == Some(true) {+ // From the card onto the control, so the hover that shows it holds through the click+ self.mouse_move(x, y).await?;+ }self.interact_click(x, y).await?;tokio::time::sleep(Duration::from_millis(250)).await;let _ = self.sync_location().await;@@ -2369,6 +2691,58 @@ impl BrowserController {Ok(v["label"].as_str().unwrap_or_default().to_string())}+ /// Moves the mouse to `x`, `y` (top-page pixels): what makes a page show what it shows on hover.+ pub async fn mouse_move(&self, x: i64, y: i64) -> Result<(), BrowserError> {+ self.send_cdp_command("Input.dispatchMouseEvent", json!({ "type": "mouseMoved", "x": x, "y": y })).await?;+ Ok(())+ }++ /// Hovers `target` (a ref or a label, matched as a click would be; a control that shows on+ /// hover is hovered through its card) and says what appeared: `Hovered over "Clip 1".+ /// Appeared: More (button), Download (menuitem)`. Clicks nothing.+ pub async fn hover_target(&self, target: &ClickTarget) -> Result<String, BrowserError> {+ let arg = match target {+ ClickTarget::Ref(r) => json!(r),+ ClickTarget::Text(t) => json!(t),+ };+ let script = HOVER_JS.replace("__CLICKABLES__", CLICKABLES_JS).replace("__REF__", REF_JS);+ let res = self+ .send_cdp_command(+ "Runtime.evaluate",+ json!({ "expression": format!("({script})({arg})"), "returnByValue": true }),+ )+ .await?;+ if let Some(err) = res.get("exceptionDetails") {+ return Err(BrowserError::Protocol(format!("hover check failed: {}", err["text"])));+ }+ let v = &res["result"]["value"];+ let what = match target {+ ClickTarget::Ref(r) => format!("ref {r}"),+ ClickTarget::Text(t) => format!("\"{t}\""),+ };+ if v["ok"].as_bool() != Some(true) {+ let why = v["why"].as_str().unwrap_or("it can't be found");+ return Err(BrowserError::StaleRef(format!(+ "Didn't hover over {what}: {why}. The clickable list was read again just now; pick from the new list."+ )));+ }+ self.mouse_move(v["x"].as_i64().unwrap_or(0), v["y"].as_i64().unwrap_or(0)).await?;+ tokio::time::sleep(HOVER_SETTLE + Duration::from_millis(50)).await;+ let res = self+ .send_cdp_command(+ "Runtime.evaluate",+ json!({ "expression": format!("({})()", APPEARED_JS.replace("__CLICKABLES__", CLICKABLES_JS)), "returnByValue": true }),+ )+ .await?;+ let appeared: Vec<String> = res["result"]["value"]+ .as_array()+ .map(|a| a.iter().filter_map(|s| s.as_str().map(str::to_string)).collect())+ .unwrap_or_default();+ let _ = self.capture_screenshot().await;+ let over = v["card"].as_str().or(v["label"].as_str()).unwrap_or_default();+ Ok(hover_summary(over, &appeared))+ }+/// Clicks `target`: a ref with [`Self::click_ref`], a label with [`Self::click_text`].pub async fn click_target(&self, target: &ClickTarget) -> Result<String, BrowserError> {match target {@@ -2400,6 +2774,10 @@ impl BrowserController {options.join(" | "))));};+ if value["match"]["hover"].as_bool() == Some(true) {+ // Shown only on hover: CLICKABLES_JS kept it as 'hovered' for the checked click+ return self.click_checked(json!("hovered"), &format!("\"{label}\"")).await;+ }if value["match"]["clicked"].as_bool() == Some(true) {tokio::time::sleep(Duration::from_millis(300)).await;let _ = self.sync_location().await;@@ -2603,7 +2981,7 @@ mod agent_shot_tests {#[cfg(test)]mod ref_tests {- use super::{ref_line, ClickTarget};+ use super::{hover_summary, ref_line, ClickTarget, CLICKABLES_JS, PAYMENT_SIGNALS_JS, REF_JS};use serde_json::json;#[test]@@ -2634,6 +3012,49 @@ mod ref_tests {assert_eq!(line(json!({"ref": 12, "role": "option", "name": "Large", "new": true})).as_deref(), Some("*[12] option \"Large\""));assert_eq!(line(json!({"ref": 12, "role": "option", "name": "Large", "new": false})).as_deref(), Some("[12] option \"Large\""));}++ /// A control that shows only on hover says so, with its card as the context; a copied line+ /// of it is still that ref.+ #[test]+ fn a_hover_control_line_names_its_card() {+ let l = ref_line(&json!({"ref": 7, "role": "button", "name": "More", "hover": true, "context": "Self-checkout"})).unwrap();+ assert_eq!(l, "[7] button \"More\" (on hover) · Self-checkout");+ assert_eq!(ClickTarget::from_args(&json!({"text": l})), Some(ClickTarget::Ref(7)));+ let card = ref_line(&json!({"ref": 6, "role": "card", "name": "Self-checkout", "hover": false})).unwrap();+ assert_eq!(card, "[6] card \"Self-checkout\"");+ assert_eq!(ref_line(&json!({"ref": 6, "role": "card", "name": "Self-checkout", "hover": true, "new": true})).unwrap(),+ "*[6] card \"Self-checkout\" (on hover)");+ }++ #[test]+ fn a_hover_says_what_appeared() {+ assert_eq!(hover_summary("Clip 1", &["More (button)".into(), "Download (menuitem)".into()]),+ "Hovered over \"Clip 1\". Appeared: More (button), Download (menuitem)");+ assert_eq!(hover_summary("More", &[]), "Hovered over \"More\". Nothing new appeared.");+ }++ /// The words icon-only controls get, and the caps on cards and hover controls, are the ones+ /// the brief names (the real-Chrome test in tests/browser_hover_test.rs checks them on a page).+ #[test]+ fn icon_words_and_caps_are_the_named_ones() {+ for pair in ["more_vert: 'More'", "more_horiz: 'More'", "download: 'Download'", "close: 'Close'",+ "delete: 'Delete'", "edit: 'Edit'", "share: 'Share'"] {+ assert!(CLICKABLES_JS.contains(pair), "{pair}");+ }+ assert!(CLICKABLES_JS.contains("var CARD_CAP = 40, HOVER_CAP = 40;"));+ // display:none is never a hover control: it is dropped before the hover check+ let none = CLICKABLES_JS.find("if (cs.display === 'none') continue;").unwrap();+ assert!(none < CLICKABLES_JS.find("var hidden = cs.visibility === 'hidden'").unwrap());+ }++ /// The payment floor's script still embeds the click matcher and the ref check, and both still+ /// hand it the label it judged before icon words were read (`old`).+ #[test]+ fn the_payment_check_judges_the_old_label() {+ assert!(PAYMENT_SIGNALS_JS.contains("__CLICKABLES__") && PAYMENT_SIGNALS_JS.contains("__REF__"));+ assert!(CLICKABLES_JS.contains("label: match.old || match.label, item: match"));+ assert!(REF_JS.contains("if (probe === true) return item ? { el: item.el, label: item.old || item.label } : null;"));+ }}#[cfg(test)]diff --git a/src/sandbox/browser_downloads.rs b/src/sandbox/browser_downloads.rsnew file mode 100644index 00000000..7f4c6cbe--- /dev/null+++ b/src/sandbox/browser_downloads.rs@@ -0,0 +1,814 @@+//! Downloads a bot's own page triggers, and file choosers it opens, have nobody to show a card+//! to and no Hand back/Try again button: `browser_stream.rs`'s chooser and download handling is+//! built for the person's own live view. This module gives every bot session its own, dedicated+//! DevTools connection (never the one `send_cdp_command` uses for ordinary actions) that stays+//! connected in the background, lands finished downloads in the bot's own `downloads/` folder,+//! and answers a bot's own file picker from a file in that folder or a chat attachment.+//!+//! Known, accepted gaps (see `autonomy/bot-browser-files/impl-files.md`): whether+//! `Browser.setDownloadBehavior` / `Page.setInterceptFileChooserDialog` are scoped to this one+//! DevTools connection or to the whole target was not verified against real Chrome (the earlier+//! harness run was stopped rather than risk the shared server's memory); this follows the+//! `Browser.*` methods' own CDP domain (browser-level, not page-level) and is documented as an+//! assumption. Because of that assumption, every session sets `Browser.setDownloadBehavior` to+//! the *same* shared staging folder (outside every bot's workspace) and claims a finished+//! download only once its `downloadWillBegin.frameId` shows up in this page's own frame tree —+//! regardless of whether the setting turns out to be per-connection or browser-wide, only the+//! center whose page the download actually started on ever moves the file into its own+//! `downloads/`. Reconnecting to follow a popup polls `get_ws_url()` every few seconds rather than+//! reacting the instant a popup opens, so capture on a brand new popup can lag by that long.+//!+//! Remote Chrome (`KWNT_BROWSER_CDP_URL`) has no filesystem in common with this server, so a+//! staging path means nothing there: `local` sessions get `allowAndName` at the shared staging+//! path; every other session gets `deny` with `eventsEnabled: true`, and a download attempt is+//! reported back as failed rather than tracked.++use super::browser::{connect_cdp, BrowserController, BrowserError, WsStream};+use super::safe_fs;+use futures::{SinkExt, StreamExt};+use serde_json::{json, Value};+use std::collections::HashSet;+use std::ffi::OsStr;+use std::path::{Path, PathBuf};+use std::sync::atomic::{AtomicU64, Ordering};+use std::sync::{Arc, Mutex as StdMutex};+use std::time::Duration;+use tokio::sync::{mpsc, oneshot};+use tokio_tungstenite::tungstenite::Message;++/// A download is cancelled once it passes this: nobody asked for anything this large, and the+/// bot's folder isn't a place to quietly fill a disk.+const MAX_DOWNLOAD_BYTES: u64 = 1_000_000_000;+/// This browser has no filesystem in common with kwnt: the most this connection will chunk in+/// for one upload, mirroring `browser_stream.rs`'s own remote-chooser cap.+const REMOTE_UPLOAD_CAP_BYTES: u64 = 100 * 1024 * 1024;+const UPLOAD_CHUNK_BYTES: usize = 1024 * 1024;+const FOLLOW_EVERY: Duration = Duration::from_secs(2);+const RETRY_WAIT: Duration = Duration::from_secs(3);+const JOB_WAIT: Duration = Duration::from_secs(20);+/// A staged download left in the shared incoming folder this long without being landed (no+/// center's frame tree ever claimed it, or a crash interrupted the move) is swept as an orphan.+const INCOMING_ORPHAN_AGE: Duration = Duration::from_secs(3600);+/// Remote Chrome has no filesystem in common with this server, so a download can't be kept.+const REMOTE_DOWNLOAD_REFUSAL: &str = "Downloads need the browser on this computer for now.";++#[derive(Clone)]+enum DlStatus {+ InProgress,+ Done(String),+ Cancelled,+ Failed(String),+}++#[derive(Clone)]+struct DownloadEntry {+ guid: String,+ name: String,+ total: Option<u64>,+ received: u64,+ status: DlStatus,+ reported_terminal: bool,+}++#[derive(Clone)]+struct ChooserInfo {+ backend_node_id: i64,+ frame_id: String,+ accept: String,+ multiple: bool,+}++#[derive(Default)]+struct Shared {+ download: Option<DownloadEntry>,+ chooser: Option<ChooserInfo>,+ /// Frame ids belonging to this page, seeded from `Page.getFrameTree` at setup and kept+ /// current from `Page.frameAttached`/`Page.frameNavigated`: the set a `downloadWillBegin`+ /// event's `frameId` is checked against before this center claims the download as its own.+ frames: HashSet<String>,+}++struct Job {+ method: String,+ params: Value,+ reply: oneshot::Sender<Result<Value, BrowserError>>,+}++/// A file ready to hand to a chooser: already resolved and validated by the caller (a workspace+/// path opened through [`safe_fs`], or a chat attachment) before it reaches this module, which+/// only ever deals in CDP mechanics.+pub struct UploadFile {+ pub name: String,+ pub mime: String,+ pub last_modified_ms: i64,+ pub source: UploadSource,+}++pub enum UploadSource {+ /// A path this Chrome can open directly (same host), already placed under its correct+ /// display name by the caller.+ Path(PathBuf),+ /// This browser has no filesystem in common with kwnt: the bytes, sent in over CDP.+ Bytes(Vec<u8>),+}++impl UploadFile {+ fn len(&self) -> u64 {+ match &self.source {+ UploadSource::Path(p) => std::fs::metadata(p).map(|m| m.len()).unwrap_or(0),+ UploadSource::Bytes(b) => b.len() as u64,+ }+ }+}++/// One dedicated connection per bot session, running in the background for as long as the+/// session's [`BrowserController`] lives.+#[derive(Clone)]+pub struct DownloadCenter {+ shared: Arc<StdMutex<Shared>>,+ jobs: mpsc::Sender<Job>,+}++impl DownloadCenter {+ /// `local`: whether this Chrome shares a filesystem with this server (see the module doc).+ /// `browser_context_id`: the session's own context, for a non-default context (VM / job+ /// pages); `None` for a local page, which shares the kwant profile's default context.+ /// `staging_root`: one folder shared by every session, outside any bot's workspace.+ ///+ /// Waits briefly for the first connect-and-setup round trip (`Page.enable`,+ /// `Browser.setDownloadBehavior`, ...) to land before returning, so that round trip is always+ /// part of whatever request just opened this session, never something a later, unrelated+ /// request races against and appears to have caused. A browser slow or unreachable past that+ /// wait just keeps retrying in the background, same as before this wait existed.+ pub async fn start(ctrl: BrowserController, workspace: PathBuf, local: bool, browser_context_id: Option<String>, staging_root: PathBuf) -> Self {+ let shared = Arc::new(StdMutex::new(Shared::default()));+ let (tx, rx) = mpsc::channel(8);+ let (ready_tx, ready_rx) = oneshot::channel();+ let center = Self { shared: shared.clone(), jobs: tx };+ let session = Session { workspace, local, browser_context_id, staging_root };+ tokio::spawn(run(ctrl, session, shared, rx, ready_tx));+ let _ = tokio::time::timeout(Duration::from_secs(2), ready_rx).await;+ center+ }++ /// `entry`'s current status as the JSON a bot sees, without touching `reported_terminal`.+ fn entry_value(entry: &DownloadEntry) -> Value {+ let pct = entry+ .total+ .filter(|t| *t > 0)+ .map(|t| (entry.received.saturating_mul(100) / t).min(100));+ match &entry.status {+ DlStatus::InProgress => json!({+ "status": "in_progress",+ "name": entry.name,+ "note": match pct {+ Some(p) => format!("Download started: {} ({p}%)", entry.name),+ None => format!("Download started: {}", entry.name),+ },+ }),+ DlStatus::Done(rel) => {+ let note = format!(+ "Downloaded {} ({}) to {} in your folder.",+ entry.name,+ human_size(entry.received),+ rel+ );+ json!({"status": "done", "name": entry.name, "path": rel, "note": note})+ }+ DlStatus::Cancelled => {+ let note = format!("The download of {} was stopped: it passed 1 GB.", entry.name);+ json!({"status": "cancelled", "name": entry.name, "note": note})+ }+ DlStatus::Failed(why) => {+ let note = format!("The download of {} failed: {why}", entry.name);+ json!({"status": "failed", "name": entry.name, "note": note})+ }+ }+ }++ /// Current download info, if any, without marking a terminal state consumed: safe to call+ /// any number of times, unlike `report` below. For a page read that's a side effect of+ /// something else (an action's own before/after snapshot, a navigation's result) rather than+ /// the bot's dedicated "did it finish" check, which must still see the terminal state once+ /// itself.+ pub fn peek(&self) -> Option<Value> {+ let shared = self.shared.lock().unwrap_or_else(|e| e.into_inner());+ Some(Self::entry_value(shared.download.as_ref()?))+ }++ /// One line worth telling the bot about its most recent download, if anything changed: once+ /// it's reported as finished, cancelled or failed, it won't be reported again.+ pub fn report(&self) -> Option<Value> {+ let mut shared = self.shared.lock().unwrap_or_else(|e| e.into_inner());+ let entry = shared.download.as_mut()?;+ if entry.reported_terminal {+ return None;+ }+ let value = Self::entry_value(entry);+ if !matches!(entry.status, DlStatus::InProgress) {+ entry.reported_terminal = true;+ }+ Some(value)+ }++ /// The currently open file picker on this session, if any, worth telling the bot about.+ pub fn open_chooser(&self) -> Option<Value> {+ let shared = self.shared.lock().unwrap_or_else(|e| e.into_inner());+ let c = shared.chooser.as_ref()?;+ let accept = if c.accept.is_empty() { "any file".to_string() } else { c.accept.clone() };+ Some(json!({+ "accept": c.accept,+ "multiple": c.multiple,+ "note": format!(+ "A file picker opened (accepts {accept}). Use browser_upload with a file from your folder or a chat attachment."+ ),+ }))+ }++ async fn call(&self, method: &str, params: Value) -> Result<Value, BrowserError> {+ let (tx, rx) = oneshot::channel();+ self.jobs+ .send(Job { method: method.to_string(), params, reply: tx })+ .await+ .map_err(|_| BrowserError::Protocol("download/chooser connection isn't running".into()))?;+ rx.await+ .map_err(|_| BrowserError::Protocol("download/chooser connection dropped the request".into()))?+ }++ /// Answers the currently open chooser with `files`, exactly as the person's own chooser+ /// answer does in `browser_stream.rs`: `DOM.setFileInputFiles` when Chrome shares kwnt's+ /// filesystem, a chunked in-page injection otherwise. Refuses if no chooser is open.+ pub async fn answer_chooser(&self, local: bool, files: Vec<UploadFile>) -> Result<Vec<String>, String> {+ if files.is_empty() {+ return Err("No file was given to answer the picker with.".into());+ }+ let chooser = { self.shared.lock().unwrap_or_else(|e| e.into_inner()).chooser.clone() };+ let Some(chooser) = chooser else {+ return Err("No file picker is open on the page right now.".into());+ };+ let files: Vec<UploadFile> = if chooser.multiple { files } else { files.into_iter().take(1).collect() };+ if !local {+ let total: u64 = files.iter().map(UploadFile::len).sum();+ if total > REMOTE_UPLOAD_CAP_BYTES {+ return Err(+ "That's more than this browser can take over a remote connection: 100 MB in all. Pick a smaller file.".into(),+ );+ }+ }+ let names: Vec<String> = files.iter().map(|f| f.name.clone()).collect();+ let result = if local {+ self.set_files_local(&chooser, &files).await+ } else {+ self.inject_files_remote(&chooser, &files).await+ };+ result.map_err(|_| "The page moved on before the file could be set.".to_string())?;+ self.shared.lock().unwrap_or_else(|e| e.into_inner()).chooser = None;+ Ok(names)+ }++ async fn set_files_local(&self, chooser: &ChooserInfo, files: &[UploadFile]) -> Result<(), BrowserError> {+ let mut paths = Vec::with_capacity(files.len());+ for f in files {+ match &f.source {+ UploadSource::Path(p) => paths.push(p.to_string_lossy().to_string()),+ UploadSource::Bytes(_) => {+ return Err(BrowserError::Protocol("local upload needs a path, not bytes".into()))+ }+ }+ }+ self.call("DOM.setFileInputFiles", json!({"files": paths, "backendNodeId": chooser.backend_node_id}))+ .await+ .map(|_| ())+ }++ async fn inject_files_remote(&self, chooser: &ChooserInfo, files: &[UploadFile]) -> Result<(), BrowserError> {+ use base64::Engine;+ let world = self+ .call("Page.createIsolatedWorld", json!({"frameId": chooser.frame_id, "worldName": "kwnt_bot_upload"}))+ .await?;+ let context = world["executionContextId"]+ .as_i64()+ .ok_or_else(|| BrowserError::Protocol("no execution context for the upload".into()))?;+ let resolved = self+ .call("DOM.resolveNode", json!({"backendNodeId": chooser.backend_node_id, "executionContextId": context}))+ .await?;+ let object = resolved["object"]["objectId"]+ .as_str()+ .map(str::to_string)+ .ok_or_else(|| BrowserError::Protocol("couldn't resolve the file input".into()))?;+ let outcome: Result<(), BrowserError> = async {+ for f in files {+ let bytes = match &f.source {+ UploadSource::Bytes(b) => b,+ UploadSource::Path(_) => {+ return Err(BrowserError::Protocol("remote upload needs bytes, not a path".into()))+ }+ };+ let began = self+ .call(+ "Runtime.callFunctionOn",+ json!({+ "objectId": object,+ "functionDeclaration": crate::server::browser_input::UPLOAD_BEGIN_FN,+ "arguments": [{"value": {"name": f.name, "mime": f.mime, "lastModified": f.last_modified_ms}}],+ "returnByValue": true,+ }),+ )+ .await?;+ if began["result"]["value"] != Value::Bool(true) {+ return Err(BrowserError::Protocol("the page refused the upload".into()));+ }+ for chunk in bytes.chunks(UPLOAD_CHUNK_BYTES) {+ let b64 = base64::engine::general_purpose::STANDARD.encode(chunk);+ let r = self+ .call(+ "Runtime.callFunctionOn",+ json!({+ "objectId": object,+ "functionDeclaration": crate::server::browser_input::UPLOAD_CHUNK_FN,+ "arguments": [{"value": b64}],+ "returnByValue": true,+ }),+ )+ .await?;+ if r["result"]["value"] != Value::Bool(true) {+ return Err(BrowserError::Protocol("the page refused an upload chunk".into()));+ }+ }+ let finished = self+ .call(+ "Runtime.callFunctionOn",+ json!({+ "objectId": object,+ "functionDeclaration": crate::server::browser_input::UPLOAD_FINISH_FN,+ "returnByValue": true,+ }),+ )+ .await?;+ if finished["result"]["value"] != Value::Bool(true) {+ return Err(BrowserError::Protocol("the page refused to finish the upload".into()));+ }+ }+ Ok(())+ }+ .await;+ let _ = self.call("Runtime.releaseObject", json!({"objectId": object})).await;+ outcome+ }+}++/// A session's own, unchanging settings for [`run`], grouped so the function stays under+/// clippy's argument-count lint.+struct Session {+ workspace: PathBuf,+ local: bool,+ browser_context_id: Option<String>,+ staging_root: PathBuf,+}++async fn run(+ ctrl: BrowserController,+ session: Session,+ shared: Arc<StdMutex<Shared>>,+ mut jobs: mpsc::Receiver<Job>,+ ready: oneshot::Sender<()>,+) {+ let Session { workspace, local, browser_context_id, staging_root } = session;+ let mut ready = Some(ready);+ let _ = tokio::fs::create_dir_all(&staging_root).await;+ loop {+ sweep_incoming(&staging_root).await;+ let ws_url = match ctrl.get_ws_url().await {+ Ok(u) => u,+ Err(_) => {+ tokio::time::sleep(RETRY_WAIT).await;+ continue;+ }+ };+ let mut ws = match connect_cdp(&ws_url).await {+ Ok(w) => w,+ Err(_) => {+ tokio::time::sleep(RETRY_WAIT).await;+ continue;+ }+ };+ let msg_id = AtomicU64::new(1);+ if setup(&mut ws, &msg_id, &shared, &staging_root, local, browser_context_id.as_deref()).await.is_err() {+ tokio::time::sleep(RETRY_WAIT).await;+ continue;+ }+ if let Some(tx) = ready.take() {+ let _ = tx.send(());+ }+ let mut follow = tokio::time::interval(FOLLOW_EVERY);+ follow.tick().await;+ loop {+ tokio::select! {+ biased;+ job = jobs.recv() => {+ let Some(job) = job else { return };+ let result = job_call(&mut ws, &msg_id, &shared, &workspace, local, &job.method, job.params).await;+ let failed = result.is_err();+ let _ = job.reply.send(result);+ if failed { break; }+ }+ msg = ws.next() => {+ if on_message(msg, &mut ws, &msg_id, &shared, &workspace, local).await.is_err() { break; }+ }+ _ = follow.tick() => {+ if let Ok(fresh) = ctrl.get_ws_url().await {+ if fresh != ws_url { break; }+ }+ }+ }+ }+ }+}++/// `incoming`: the shared staging folder (outside any workspace) every session points+/// `Browser.setDownloadBehavior` at, so the global setting can't single out one bot's folder.+/// `local`: allow downloads there; otherwise deny them but keep hearing about attempts. Also+/// seeds `shared.frames` from this page's own frame tree, for `handle_event` to claim a download+/// only once it sees a `frameId` that's actually this page's.+async fn setup(+ ws: &mut WsStream,+ msg_id: &AtomicU64,+ shared: &Arc<StdMutex<Shared>>,+ incoming: &Path,+ local: bool,+ browser_context_id: Option<&str>,+) -> Result<(), BrowserError> {+ call_raw(ws, msg_id, "Page.enable", json!({})).await?;+ let behavior = download_behavior_params(local, incoming, browser_context_id);+ call_raw(ws, msg_id, "Browser.setDownloadBehavior", behavior).await?;+ call_raw(ws, msg_id, "Page.setInterceptFileChooserDialog", json!({"enabled": true})).await?;+ if let Ok(tree) = call_raw(ws, msg_id, "Page.getFrameTree", json!({})).await {+ let mut frames = HashSet::new();+ collect_frame_ids(&tree["frameTree"], &mut frames);+ shared.lock().unwrap_or_else(|e| e.into_inner()).frames = frames;+ }+ Ok(())+}++/// Builds `Browser.setDownloadBehavior`'s params for the Fix #4 mode switch: a `local` session+/// (one with a filesystem in common with this server) gets `allowAndName` at the shared staging+/// path; every other session (remote Chrome, with none) gets `deny`, kept to `eventsEnabled` so a+/// download attempt is still reported rather than silently vanishing.+fn download_behavior_params(local: bool, incoming: &Path, browser_context_id: Option<&str>) -> Value {+ let mut behavior = json!({+ "behavior": if local { "allowAndName" } else { "deny" },+ "eventsEnabled": true,+ });+ if local {+ behavior["downloadPath"] = json!(incoming.to_string_lossy());+ }+ if let Some(ctx) = browser_context_id {+ behavior["browserContextId"] = json!(ctx);+ }+ behavior+}++/// Recurses through a `Page.getFrameTree` result (`{frame: {id}, childFrames: [...]}`), collecting+/// every frame id belonging to this page.+fn collect_frame_ids(node: &Value, out: &mut HashSet<String>) {+ if let Some(id) = node["frame"]["id"].as_str() {+ out.insert(id.to_string());+ }+ for child in node["childFrames"].as_array().into_iter().flatten() {+ collect_frame_ids(child, out);+ }+}++/// Sends one request and waits only for its own reply, dropping anything else read in the+/// meantime: used for the short setup/follow-up calls this module issues on its own, never for a+/// job a caller is waiting on (see [`job_call`], which dispatches as it goes instead).+async fn call_raw(ws: &mut WsStream, msg_id: &AtomicU64, method: &str, params: Value) -> Result<Value, BrowserError> {+ let id = msg_id.fetch_add(1, Ordering::SeqCst);+ let request = json!({"id": id, "method": method, "params": params});+ ws.send(Message::Text(request.to_string())).await.map_err(|e| BrowserError::Ws(e.to_string()))?;+ tokio::time::timeout(JOB_WAIT, async {+ loop {+ match ws.next().await {+ Some(Ok(Message::Text(txt))) => {+ let Ok(parsed) = serde_json::from_str::<Value>(&txt) else { continue };+ if parsed.get("id").and_then(Value::as_u64) != Some(id) {+ continue;+ }+ if let Some(err) = parsed.get("error") {+ return Err(BrowserError::Protocol(err.to_string()));+ }+ return Ok(parsed.get("result").cloned().unwrap_or(Value::Null));+ }+ Some(Ok(Message::Close(_))) | None => {+ return Err(BrowserError::Protocol("connection closed before a reply".into()))+ }+ Some(Err(e)) => return Err(BrowserError::Ws(e.to_string())),+ _ => continue,+ }+ }+ })+ .await+ .map_err(|_| BrowserError::Timeout)?+}++/// Sends one request on behalf of a caller awaiting its own result, meanwhile dispatching any+/// unsolicited events (downloads, choosers) that arrive while waiting, instead of dropping them.+async fn job_call(+ ws: &mut WsStream,+ msg_id: &AtomicU64,+ shared: &Arc<StdMutex<Shared>>,+ workspace: &Path,+ local: bool,+ method: &str,+ params: Value,+) -> Result<Value, BrowserError> {+ let id = msg_id.fetch_add(1, Ordering::SeqCst);+ let request = json!({"id": id, "method": method, "params": params});+ ws.send(Message::Text(request.to_string())).await.map_err(|e| BrowserError::Ws(e.to_string()))?;+ loop {+ let msg = tokio::time::timeout(JOB_WAIT, ws.next()).await.map_err(|_| BrowserError::Timeout)?;+ if let Some(Ok(Message::Text(txt))) = &msg {+ if let Ok(v) = serde_json::from_str::<Value>(txt) {+ if v.get("id").and_then(Value::as_u64) == Some(id) {+ if let Some(err) = v.get("error") {+ return Err(BrowserError::Protocol(err.to_string()));+ }+ return Ok(v.get("result").cloned().unwrap_or(Value::Null));+ }+ }+ }+ on_message(msg, ws, msg_id, shared, workspace, local).await?;+ }+}++async fn on_message(+ msg: Option<Result<Message, tokio_tungstenite::tungstenite::Error>>,+ ws: &mut WsStream,+ msg_id: &AtomicU64,+ shared: &Arc<StdMutex<Shared>>,+ workspace: &Path,+ local: bool,+) -> Result<(), BrowserError> {+ match msg {+ Some(Ok(Message::Text(txt))) => {+ let Ok(v) = serde_json::from_str::<Value>(&txt) else { return Ok(()) };+ if let Some(method) = v.get("method").and_then(Value::as_str) {+ let params = v.get("params").cloned().unwrap_or(Value::Null);+ handle_event(ws, msg_id, method, params, shared, workspace, local).await;+ }+ Ok(())+ }+ Some(Ok(Message::Close(_))) | None => Err(BrowserError::Protocol("connection closed".into())),+ Some(Err(e)) => Err(BrowserError::Ws(e.to_string())),+ _ => Ok(()),+ }+}++async fn handle_event(+ ws: &mut WsStream,+ msg_id: &AtomicU64,+ method: &str,+ params: Value,+ shared: &Arc<StdMutex<Shared>>,+ workspace: &Path,+ local: bool,+) {+ match method {+ "Browser.downloadWillBegin" => {+ let Some(guid) = params["guid"].as_str().map(str::to_string) else { return };+ let frame_id = params["frameId"].as_str().unwrap_or_default();+ let name = sanitize_name(params["suggestedFilename"].as_str().unwrap_or("download"));+ let mut s = shared.lock().unwrap_or_else(|e| e.into_inner());+ // Another bot's session may see this event too (see the module doc's accepted gap):+ // only claim it when the frame it started on is actually this page's own.+ if !s.frames.contains(frame_id) {+ return;+ }+ s.download = Some(DownloadEntry {+ guid,+ name,+ total: None,+ received: 0,+ status: if local {+ DlStatus::InProgress+ } else {+ DlStatus::Failed(REMOTE_DOWNLOAD_REFUSAL.into())+ },+ reported_terminal: false,+ });+ }+ "Browser.downloadProgress" => {+ // Remote mode already answered `downloadWillBegin` as failed and never allowed the+ // download to start: nothing here is this center's to track.+ if !local {+ return;+ }+ let Some(guid) = params["guid"].as_str().map(str::to_string) else { return };+ let state = params["state"].as_str().unwrap_or_default().to_string();+ let received = params["receivedBytes"].as_u64().unwrap_or(0);+ let total = params["totalBytes"].as_u64().filter(|t| *t > 0);+ let file_path = params["filePath"].as_str().map(str::to_string);+ let mut finish = None;+ let mut over_cap = false;+ {+ let mut s = shared.lock().unwrap_or_else(|e| e.into_inner());+ // `downloadProgress` carries no `frameId`, so unlike `downloadWillBegin` there's+ // nothing here to check frame ownership against. Rather than adopt an unrecognized+ // guid outright (which would hand another bot's progress to this center whenever+ // the setting turns out to be browser-wide), only ever update a guid this center+ // already claimed via a frame-checked `downloadWillBegin`; anything else is ignored.+ let Some(entry) = s.download.as_mut().filter(|e| e.guid == guid) else { return };+ if let Some(t) = total {+ entry.total = Some(t);+ }+ entry.received = received;+ match state.as_str() {+ "completed" => match file_path {+ Some(path) => finish = Some((entry.name.clone(), path)),+ None => entry.status = DlStatus::Failed("Chrome didn't say where the file landed.".into()),+ },+ "canceled" => entry.status = DlStatus::Cancelled,+ _ if received > MAX_DOWNLOAD_BYTES => over_cap = true,+ _ => {}+ }+ }+ if over_cap {+ let _ = call_raw(ws, msg_id, "Browser.cancelDownload", json!({"guid": guid})).await;+ }+ if let Some((name, path)) = finish {+ tokio::spawn(land_download(workspace.to_path_buf(), shared.clone(), guid, name, path));+ }+ }+ "Page.fileChooserOpened" => {+ let backend_node_id = params["backendNodeId"].as_i64().unwrap_or_default();+ let frame_id = params["frameId"].as_str().unwrap_or_default().to_string();+ let multiple = params["mode"].as_str() == Some("selectMultiple");+ let accept = describe_accept(ws, msg_id, backend_node_id).await;+ let mut s = shared.lock().unwrap_or_else(|e| e.into_inner());+ s.chooser = Some(ChooserInfo { backend_node_id, frame_id, accept, multiple });+ }+ "Page.frameAttached" => {+ if let Some(id) = params["frameId"].as_str() {+ shared.lock().unwrap_or_else(|e| e.into_inner()).frames.insert(id.to_string());+ }+ }+ "Page.frameNavigated" => {+ let Some(id) = params["frame"]["id"].as_str() else { return };+ let mut s = shared.lock().unwrap_or_else(|e| e.into_inner());+ if params["frame"]["parentId"].is_null() {+ s.chooser = None;+ // A top-level navigation leaves any earlier subframes behind; keep the set from+ // growing forever and start it over with just the new main frame.+ s.frames.clear();+ }+ s.frames.insert(id.to_string());+ }+ _ => {}+ }+}++async fn describe_accept(ws: &mut WsStream, msg_id: &AtomicU64, backend_node_id: i64) -> String {+ let Ok(described) = call_raw(ws, msg_id, "DOM.describeNode", json!({"backendNodeId": backend_node_id})).await+ else {+ return String::new();+ };+ described["node"]["attributes"]+ .as_array()+ .map(Vec::as_slice)+ .unwrap_or_default()+ .chunks(2)+ .find(|pair| pair.first().and_then(Value::as_str) == Some("accept"))+ .and_then(|pair| pair.get(1))+ .and_then(Value::as_str)+ .unwrap_or_default()+ .to_string()+}++/// Moves a finished download out of staging and into the bot's own `downloads/` folder, picking+/// a collision-free name there (Chrome already made the staged name collision-free on its own+/// side via `allowAndName`, so this is the one place a name actually has to be chosen).+async fn land_download(workspace: PathBuf, shared: Arc<StdMutex<Shared>>, guid: String, name: String, staged_path: String) {+ let landing_guid = guid.clone();+ let result = tokio::task::spawn_blocking(move || -> std::io::Result<String> {+ std::fs::create_dir_all(&workspace)?;+ let root = safe_fs::Dir::open_strict(&workspace)?;+ let dir = root.make_dirs(Path::new("downloads"))?;+ let mut src = std::fs::File::open(&staged_path)?;+ let existing: HashSet<String> = dir+ .list()?+ .into_iter()+ .filter(|e| matches!(e.kind, safe_fs::Kind::File))+ .map(|e| e.name.to_string_lossy().to_string())+ .collect();+ let final_name = collision_safe_name(&existing, &name);+ dir.replace_file(OsStr::new(&final_name), &format!(".landing-{landing_guid}"), &mut src, 0o600)?;+ drop(src);+ let _ = std::fs::remove_file(&staged_path);+ Ok(final_name)+ })+ .await;+ let mut s = shared.lock().unwrap_or_else(|e| e.into_inner());+ if let Some(entry) = &mut s.download {+ if entry.guid == guid {+ entry.status = match result {+ Ok(Ok(final_name)) => DlStatus::Done(format!("downloads/{final_name}")),+ Ok(Err(e)) => DlStatus::Failed(e.to_string()),+ Err(_) => DlStatus::Failed("something went wrong landing the download".into()),+ };+ }+ }+}++/// Deletes any file left in the shared incoming folder older than `INCOMING_ORPHAN_AGE`: a+/// backstop for a staged download no center's frame tree ever claimed, or one `land_download`+/// never got to finish moving before a restart.+async fn sweep_incoming(incoming: &Path) {+ let Ok(mut entries) = tokio::fs::read_dir(incoming).await else { return };+ let cutoff = std::time::SystemTime::now() - INCOMING_ORPHAN_AGE;+ while let Ok(Some(entry)) = entries.next_entry().await {+ if entry.metadata().await.ok().and_then(|m| m.modified().ok()).is_some_and(|m| m < cutoff) {+ let _ = tokio::fs::remove_file(entry.path()).await;+ }+ }+}++fn collision_safe_name(existing: &HashSet<String>, name: &str) -> String {+ if !existing.contains(name) {+ return name.to_string();+ }+ let (stem, ext) = match name.rsplit_once('.') {+ Some((s, e)) if !s.is_empty() => (s.to_string(), Some(e.to_string())),+ _ => (name.to_string(), None),+ };+ for n in 2..10_000u32 {+ let candidate = match &ext {+ Some(e) => format!("{stem} ({n}).{e}"),+ None => format!("{stem} ({n})"),+ };+ if !existing.contains(&candidate) {+ return candidate;+ }+ }+ format!("{name}.{}", uuid::Uuid::new_v4())+}++fn sanitize_name(raw: &str) -> String {+ let base = Path::new(raw).file_name().and_then(|n| n.to_str()).unwrap_or("download");+ let cleaned: String = base.chars().map(|c| if c.is_control() { '_' } else { c }).collect();+ let cleaned = cleaned.trim();+ if cleaned.is_empty() || cleaned == "." || cleaned == ".." {+ "download".to_string()+ } else {+ cleaned.chars().take(200).collect()+ }+}++fn human_size(bytes: u64) -> String {+ const UNITS: [&str; 5] = ["B", "KB", "MB", "GB", "TB"];+ if bytes < 1024 {+ return format!("{bytes} B");+ }+ let mut size = bytes as f64;+ let mut unit = 0;+ while size >= 1024.0 && unit < UNITS.len() - 1 {+ size /= 1024.0;+ unit += 1;+ }+ format!("{size:.1} {}", UNITS[unit])+}++#[cfg(test)]+mod tests {+ use super::*;++ // Fix #4: local sessions (a filesystem in common with this server) get downloads kept at the+ // shared staging path; every other session (remote Chrome) gets them refused up front, since+ // there's nowhere in common to land the bytes.+ #[test]+ fn local_sessions_allow_and_name_at_the_staging_path() {+ let incoming = Path::new("/tmp/kwnt-download-tmp");+ let params = download_behavior_params(true, incoming, None);+ assert_eq!(params["behavior"], "allowAndName");+ assert_eq!(params["eventsEnabled"], true);+ assert_eq!(params["downloadPath"], "/tmp/kwnt-download-tmp");+ assert!(params.get("browserContextId").is_none());+ }++ #[test]+ fn remote_sessions_deny_but_keep_hearing_about_attempts() {+ let incoming = Path::new("/tmp/kwnt-download-tmp");+ let params = download_behavior_params(false, incoming, None);+ assert_eq!(params["behavior"], "deny");+ assert_eq!(params["eventsEnabled"], true);+ assert!(params.get("downloadPath").is_none(), "a remote session has no filesystem in common with this server");+ }++ #[test]+ fn a_non_default_browser_context_is_passed_through_either_way() {+ let incoming = Path::new("/tmp/kwnt-download-tmp");+ let local = download_behavior_params(true, incoming, Some("ctx-123"));+ assert_eq!(local["browserContextId"], "ctx-123");+ let remote = download_behavior_params(false, incoming, Some("ctx-123"));+ assert_eq!(remote["browserContextId"], "ctx-123");+ }+}diff --git a/src/sandbox/mod.rs b/src/sandbox/mod.rsindex 8a97b3cd..e09a3fd5 100644--- a/src/sandbox/mod.rs+++ b/src/sandbox/mod.rs@@ -2,6 +2,7 @@ pub mod agent_vm;pub mod app_links;pub mod bitwarden;pub mod browser;+pub mod browser_downloads;pub mod browser_history;pub mod chrome_download;pub mod computer;diff --git a/src/sandbox/service.rs b/src/sandbox/service.rsindex 0c649f6b..0f56e7e8 100644--- a/src/sandbox/service.rs+++ b/src/sandbox/service.rs@@ -105,6 +105,12 @@ struct ServiceState {browser: BrowserController,endpoint: String,sessions: HashMap<String, SessionTarget>,+ /// The configured controller behind each live session, reused across calls so its+ /// `downloads` connection (see `browser_downloads.rs`) stays the one background task the+ /// whole session's downloads and file choosers are tracked on, instead of a blank one per+ /// call. Not persisted: a reconnect starts empty and each session gets a fresh controller the+ /// next time it's used, same as before this cache existed.+ controllers: HashMap<String, BrowserController>,}impl BrowserService {@@ -442,7 +448,7 @@ impl BrowserService {browser.keep_identity().await;let sessions = tokio::fs::read(self.sessions_file()).await.ok().and_then(|bytes| serde_json::from_slice(&bytes).ok()).unwrap_or_default();- Ok(ServiceState { browser, endpoint, sessions })+ Ok(ServiceState { browser, endpoint, sessions, controllers: HashMap::new() })}/// What to tell the person when the browser could not be reached. In local mode that is the@@ -567,7 +573,7 @@ impl BrowserService {self.rested.lock().unwrap_or_else(|e| e.into_inner()).get(key).copied()}- async fn open_session(&self, id: &str, _workspace: &Path) -> Result<BrowserController, BrowserError> {+ async fn open_session(&self, id: &str, workspace: &Path) -> Result<BrowserController, BrowserError> {let mut lock = self.state.lock().await;if lock.is_none() { *lock = Some(self.connect().await?); }let mut targets = lock.as_ref().unwrap().browser.send_cdp_command("Target.getTargets", json!({})).await;@@ -586,6 +592,7 @@ impl BrowserService {};let existing = state.sessions.get(id).filter(|session| targets["targetInfos"].as_array().is_some_and(|targets| targets.iter().any(|target| target["targetId"] == session.target)));+ let reused = existing.is_some();let local = self.mode() == ComputerMode::Local;let alive = |target: &str| targets["targetInfos"].as_array().is_some_and(|targets| targets.iter().any(|t| t["targetId"] == target));@@ -623,7 +630,20 @@ impl BrowserService {};state.sessions.insert(id.to_string(), session.clone());self.save_sessions(&state.sessions).await?;- let ctrl = BrowserController::at_endpoint(&state.endpoint, Some(session.target), false);+ // Reuse the same session's controller, not a fresh one, so its `downloads` connection (a+ // dedicated background task; see `configure_downloads` below) stays the one the whole+ // session's downloads and file choosers are tracked on. A fresh controller here would+ // get a fresh, empty `downloads`, so every call would start its own blank-state download+ // center and never see what an earlier call's center already observed.+ let cached = reused.then(|| state.controllers.get(id).cloned()).flatten();+ let ctrl = match cached {+ Some(ctrl) => ctrl,+ None => {+ let ctrl = BrowserController::at_endpoint(&state.endpoint, Some(session.target.clone()), false);+ state.controllers.insert(id.to_string(), ctrl.clone());+ ctrl+ }+ };if !local {// The VM browser's profile is on tmpfs, so its contexts' cookies go when the// container restarts: keep them per team in the data folder (local mode's on-disk@@ -642,6 +662,11 @@ impl BrowserService {ctrl.set_viewport(1280, 800).await?;}ctrl.refresh_location().await?;+ // Next to #578's attachments root/chooser-tmp: one folder shared by every session's+ // download staging, outside any bot's workspace (see `browser_downloads.rs`'s doc).+ let download_staging = self.root.join("attachments").join("download-tmp");+ let context_id = (!session.context.is_empty()).then_some(session.context.clone());+ ctrl.configure_downloads(workspace.to_path_buf(), local, context_id, download_staging).await;Ok(ctrl)}diff --git a/src/sandbox/site_guard.rs b/src/sandbox/site_guard.rsindex def56237..9c50486e 100644--- a/src/sandbox/site_guard.rs+++ b/src/sandbox/site_guard.rs@@ -185,13 +185,13 @@ fn system_resolve(name: &str, port: u16) -> Option<Vec<IpAddr>> {pub const NAVIGATION_WAIT: std::time::Duration = std::time::Duration::from_millis(300);/// Whether a bot action (`act`'s `action`, and `key` for a key press) can load a page: a click,-/// and Enter or Space (which follow a focused link or press a focused button). A scroll, plain-/// typing and other keys can't, so they skip [`NAVIGATION_WAIT`]. A page script that navigates on+/// and Enter or Space (which follow a focused link or press a focused button). A scroll, a hover,+/// plain typing and other keys can't, so they skip [`NAVIGATION_WAIT`]. A page script that navigates on/// some other key is still refused by the guard; the bot hears of it on the same reply if the/// refusal arrives in time, else on its next action.pub fn may_navigate(action: &str, key: Option<&str>) -> bool {match action {- "scroll" | "type" => false,+ "scroll" | "type" | "hover" => false,"key" => matches!(key.unwrap_or("Enter"), "Enter" | " " | "Space" | "Spacebar"),_ => true,}@@ -503,7 +503,7 @@ mod tests {for (action, key) in [("click", None), ("click_text", None), ("key", None), ("key", Some("Enter")), ("key", Some(" ")), ("key", Some("Space"))] {assert!(may_navigate(action, key), "{action} {key:?}");}- for (action, key) in [("scroll", None), ("type", None), ("key", Some("Tab")), ("key", Some("Escape")), ("key", Some("ArrowDown"))] {+ for (action, key) in [("scroll", None), ("type", None), ("hover", None), ("key", Some("Tab")), ("key", Some("Escape")), ("key", Some("ArrowDown"))] {assert!(!may_navigate(action, key), "{action} {key:?}");}}diff --git a/src/server/attachments.rs b/src/server/attachments.rsindex fb648fc9..f16ddf31 100644--- a/src/server/attachments.rs+++ b/src/server/attachments.rs@@ -423,7 +423,7 @@ pub fn view(a: &Attachment) -> Value {v}-async fn load(state: &AppState, id: &str) -> Option<Attachment> {+pub async fn load(state: &AppState, id: &str) -> Option<Attachment> {uuid::Uuid::parse_str(id).ok()?;state.db.get_attachment(id).await.ok().flatten()}@@ -794,7 +794,7 @@ async fn task_origin(state: &AppState, scope: &SelfScope) -> Option<String> {/// The turn may see files of its own chat, of the chat its delegated task came from, and files/// this agent shared anywhere.-async fn visible(state: &AppState, scope: &SelfScope, id: &str) -> Option<Attachment> {+pub(crate) async fn visible(state: &AppState, scope: &SelfScope, id: &str) -> Option<Attachment> {let a = load(state, id).await?;let own_chat = a.context_id.is_some() && a.context_id == context_of(scope);let own_file = a.source == "agent" && a.kwant_id.as_deref() == Some(scope.kwant_id.as_str());@@ -805,6 +805,16 @@ async fn visible(state: &AppState, scope: &SelfScope, id: &str) -> Option<Attach(origin.is_some() && a.context_id == origin).then_some(a)}+/// As [`visible`], for a caller that has a chat id and an owning bot but no full turn to check+/// against: the browser API's curl path, keyed only on the page (and so the chat and bot) it was+/// called on. Same rule, minus the "chat a delegated task came from" leg, which needs a turn.+pub(crate) async fn visible_to(state: &AppState, chat: Option<&str>, owner_kwant: Option<&str>, id: &str) -> Option<Attachment> {+ let a = load(state, id).await?;+ let own_chat = chat.is_some() && a.context_id.as_deref() == chat;+ let own_file = owner_kwant.is_some() && a.source == "agent" && a.kwant_id.as_deref() == owner_kwant;+ (own_chat || own_file).then_some(a)+}+pub async fn tool_list(state: &AppState, scope: &SelfScope) -> (String, bool) {let Some(ctx) = context_of(scope) else {return ("This turn has no chat.".into(), true);diff --git a/src/server/continuity.rs b/src/server/continuity.rsindex 7da136cd..254edc10 100644--- a/src/server/continuity.rs+++ b/src/server/continuity.rs@@ -717,19 +717,34 @@ fn browser_tools() -> Vec<Value> {}),json!({"name": BROWSER_ACT,- "description": "Do one thing on the current page and get the page back. click clicks a control by its ref, the number in the page's clickable list ([3] button \"Add to cart\"), or by its visible label in text; a line starting with * (*[12] option \"Large\") is a control that appeared since your last look, e.g. the options a click opened; if the ref is gone, hidden or covered nothing is clicked and you get a fresh list. type types into the field with that ref, or the focused field; key presses a key (Enter, Tab, Escape, ArrowDown…); scroll scrolls by delta_y pixels (negative is up).",+ "description": "Do one thing on the current page and get the page back. click clicks a control by its ref, the number in the page's clickable list ([3] button \"Add to cart\"), or by its visible label in text; a line starting with * (*[12] option \"Large\") is a control that appeared since your last look, e.g. the options a click opened; if the ref is gone, hidden or covered nothing is clicked and you get a fresh list. A control marked (on hover) ([7] button \"More\" (on hover) · Clip 1) shows only when the mouse is over its card; click it as usual and the card is hovered first. hover puts the mouse over a ref or label and says what appeared, without clicking. type types into the field with that ref, or the focused field; key presses a key (Enter, Tab, Escape, ArrowDown…); scroll scrolls by delta_y pixels (negative is up).","inputSchema": {"type": "object","properties": {- "action": {"type": "string", "enum": ["click", "click_text", "type", "key", "scroll"]},- "ref": {"type": "integer", "description": "click or type: the control's number from the clickable list"},- "text": {"type": "string", "description": "click: a visible label, when there's no ref; type: the text to type"},+ "action": {"type": "string", "enum": ["click", "click_text", "hover", "type", "key", "scroll"]},+ "ref": {"type": "integer", "description": "click, hover or type: the control's number from the clickable list"},+ "text": {"type": "string", "description": "click or hover: a visible label, when there's no ref; type: the text to type"},"key": {"type": "string", "description": "key: the key to press"},"delta_y": {"type": "number", "description": "scroll: pixels to scroll, default 600"},},"required": ["action"],},}),+ json!({+ "name": BROWSER_UPLOAD,+ "description": "Answer a file picker your browser has open (browser_page says so with a note starting \"A file picker opened\"). Give one or more files, each either a path in your own folder (for instance a file you downloaded earlier, downloads/clip.mp4) or a chat attachment's id. Refused if no picker is open.",+ "inputSchema": {+ "type": "object",+ "properties": {+ "files": {+ "type": "array",+ "items": {"type": "string"},+ "description": "Each a path under your folder, or a chat attachment id.",+ },+ },+ "required": ["files"],+ },+ }),]}@@ -738,6 +753,7 @@ 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";+pub const BROWSER_UPLOAD: &str = "browser_upload";/// `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.@@ -857,7 +873,7 @@ async fn call_browser_tool(state: &AppState, scope: &SelfScope, target: &str, na}Err(super::routes::PageRefusal::Unavailable) => {}}- let (text, is_error, busy) = run_browser_tool_coded(state, target, &reader, name, args).await;+ let (text, is_error, busy) = run_browser_tool_coded(state, target, &reader, name, args, Some(scope)).await;super::busy_retry::note(&reader, name, args, busy);// A CAPTCHA wall: ask the person to solve it, then show the agent the page they left. Also// when the call itself failed: a click that stalled, was covered or timed out because a@@ -904,16 +920,29 @@ fn page_refusal_text(state: &AppState, refusal: super::routes::PageRefusal) -> S/// `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) {- let (text, is_error, _) = run_browser_tool_coded(state, target, reader, name, args).await;+ let (text, is_error, _) = run_browser_tool_coded(state, target, reader, name, args, None).await;(text, is_error)}/// [`run_browser_tool`], plus whether the handler answered that the browser is busy (matched on-/// the answer's `code`, see [`super::busy_retry::is_busy`]).-async fn run_browser_tool_coded(state: &AppState, target: &str, reader: &str, name: &str, args: &Value) -> (String, bool, bool) {+/// the answer's `code`, see [`super::busy_retry::is_busy`]). `scope`: the calling turn, when one+/// is driving this call (always `browser_upload`'s caller, since it alone touches attachments);+/// `None` for the scope-less re-reads this module does on its own (see [`run_browser_tool`]).+async fn run_browser_tool_coded(+ state: &AppState,+ target: &str,+ reader: &str,+ name: &str,+ args: &Value,+ scope: Option<&SelfScope>,+) -> (String, bool, bool) {use super::routes::{act_sandbox_allowed, cite_sandbox, get_sandbox_page, navigate_sandbox, unchanged_read, CitePayload, InteractPayload, NavigatePayload,- PageQuery,+ PageQuery, UploadCaller,+ };+ let caller = match scope {+ Some(s) => UploadCaller::Turn(s),+ None => UploadCaller::None,};let ctrl = match reader {"" => None,@@ -937,6 +966,25 @@ async fn run_browser_tool_coded(state: &AppState, target: &str, reader: &str, nalet 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}+ BROWSER_UPLOAD => {+ let files: Vec<String> = args["files"].as_array().into_iter().flatten().filter_map(|f| f.as_str().map(str::to_string)).collect();+ if files.is_empty() {+ return ("files is required: a path in your folder or a chat attachment id, one or more".into(), true, false);+ }+ let payload = InteractPayload {+ action: "upload".to_string(),+ x: None,+ y: None,+ text: None,+ key: None,+ code: None,+ delta_x: None,+ delta_y: None,+ ref_: None,+ files: Some(files),+ };+ act_sandbox_allowed(state, target, Json(payload), caller).await+ }_ => {let Some(action) = args["action"].as_str() else {return ("action is required: click, type, key or scroll".into(), true, false);@@ -951,9 +999,10 @@ async fn run_browser_tool_coded(state: &AppState, target: &str, reader: &str, nadelta_x: None,delta_y: args["delta_y"].as_f64(),ref_: Some(args["ref"].clone()).filter(|r| !r.is_null()),+ files: None,};// SelfToolsApprover already gave a payment its card (browser_act_payment)- act_sandbox_allowed(state, target, Json(payload)).await+ act_sandbox_allowed(state, target, Json(payload), caller).await}};match result {@@ -1346,7 +1395,7 @@ async fn call_tool(}// on the turn's own page (its job page in a chat), so a page held for another job's// sign-in doesn't stop this one- BROWSER_OPEN | BROWSER_PAGE | BROWSER_ACT | BROWSER_CITE => match super::browser_pages::scope_page(scope) {+ BROWSER_OPEN | BROWSER_PAGE | BROWSER_ACT | BROWSER_CITE | BROWSER_UPLOAD => match super::browser_pages::scope_page(scope) {Some(target) => call_browser_tool(state, scope, &target, name, args).await,None => (format!("Unknown tool {name}."), true),},diff --git a/src/server/routes.rs b/src/server/routes.rsindex c56a5c4a..63bfae94 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -6337,6 +6337,10 @@ pub struct InteractPayload {/// click (or type): a numbered ref from the page's clickable list instead of a label#[serde(default, rename = "ref")]pub ref_: Option<serde_json::Value>,+ /// upload: each a workspace-relative path under `downloads/` (or elsewhere in the bot's+ /// folder) or a chat attachment id, answering the currently open file picker.+ #[serde(default)]+ pub files: Option<Vec<String>>,}pub async fn interact_sandbox(@@ -6403,17 +6407,23 @@ pub async fn interact_sandbox(/// Compact, text-only page state for agents (no base64 image to wade through).async fn sandbox_page_state(ctrl: &crate::sandbox::BrowserController) -> serde_json::Value {let snap = ctrl.snapshot().await;- page_state_from(ctrl, snap, "").await+ page_state_from(ctrl, snap, "", false).await}/// [`sandbox_page_state`] from a snapshot already read (`None`: the page couldn't be read)./// `find`: the bot's words for what it looks for, to list the matching controls first on a page/// with more than [`reads::SHOWN_CONTROLS`](crate::sandbox::reads::SHOWN_CONTROLS). `hash` says-/// what the read shows, for [`get_sandbox_page`]'s `since`.+/// what the read shows, for [`get_sandbox_page`]'s `since`. `consume`: whether a download's+/// terminal status, once reported here, should stop being reported again. Only the one dedicated+/// `browser_page` read a bot polls to learn a download finished should pass `true`; every other+/// read that happens to build a page state as a side effect of something else (an action's own+/// before/after snapshot, a navigation's result) must pass `false`, or it can win the race and+/// swallow the terminal report before the bot's own poll ever sees it.async fn page_state_from(ctrl: &crate::sandbox::BrowserController,snap: Option<crate::sandbox::progress::Snapshot>,find: &str,+ consume: bool,) -> serde_json::Value {use crate::sandbox::reads;let (url, title, text) = match snap {@@ -6450,6 +6460,13 @@ async fn page_state_from(if let Some(captcha) = captcha {page["captcha"] = json!(captcha);}+ let download = if consume { ctrl.latest_download_report() } else { ctrl.peek_download_report() };+ if let Some(download) = download {+ page["download"] = download;+ }+ if let Some(chooser) = ctrl.open_chooser_report() {+ page["file_chooser"] = chooser;+ }page}@@ -6526,6 +6543,22 @@ impl BotCall {}}+/// Who a `browser_upload` call may answer a chat attachment id for. Not every path that reaches+/// [`act_sandbox_allowed`] has a full turn to check an id against: a turn (the MCP path, which+/// also honors the chat a delegated task came from — see [`super::attachments::visible`]), the+/// bot (and chat, when the route names one) a curl call came in as, or neither, when no id can+/// match and only a workspace path is accepted.+#[derive(Clone, Copy, Default)]+pub enum UploadCaller<'a> {+ #[default]+ None,+ Turn(&'a super::continuity::SelfScope),+ Bot {+ kwant: &'a str,+ chat: Option<&'a str>,+ },+}+/// `POST /api/sandbox/:id/bot/:kwant_id/navigate`: the browser API a bot's prompt gave it before/// the address named its chat. Still served: a bot copying it out of history is asked in its/// newest turn on the browser.@@ -6638,7 +6671,11 @@ async fn act_as() -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {let page = by.as_ref().map_or_else(|| team_id.clone(), BotCall::page_in(&team_id));refuse_while_held(&state, &page, by.is_some()).await?;- let result = act_sandbox(State(state.clone()), Path(page.clone()), payload).await;+ let caller = match &by {+ Some(b) => UploadCaller::Bot { kwant: &b.kwant, chat: b.chat.as_deref() },+ None => UploadCaller::None,+ };+ let result = act_sandbox(State(state.clone()), Path(page.clone()), payload, caller).await;ask_on_wall(&state, &team_id, &page, by.as_ref().map(BotCall::caller), result).await}@@ -6771,7 +6808,7 @@ pub async fn get_sandbox_page() -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {let ctrl = page_controller(&state, &team_id).await?;let snap = ctrl.snapshot().await;- let mut 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(), true).await;if query.wants_blocks() {add_blocks(&ctrl, &mut page).await;}@@ -6819,14 +6856,23 @@ pub async fn cite_sandbox(/// 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!({+ let mut out = json!({"url": page["url"],"title": page["title"],"hash": page["hash"],"blocked": page["blocked"],"unchanged": true,"note": crate::sandbox::reads::UNCHANGED_NOTE,- })+ });+ // A download or an open chooser is news on its own, never folded into the page's hash: say so+ // even on an otherwise unchanged read, so it's never missed between two look-the-same reads.+ if page.get("download").is_some() {+ out["download"] = page["download"].clone();+ }+ if page.get("file_chooser").is_some() {+ out["file_chooser"] = page["file_chooser"].clone();+ }+ out}/// Agent-facing action endpoint (`POST /api/sandbox/:id/act`, the shell bots' browser API):@@ -6838,6 +6884,7 @@ pub async fn act_sandbox(State(state): State<AppState>,Path(team_id): Path<String>,Json(payload): Json<InteractPayload>,+ caller: UploadCaller<'_>,) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {let ctrl = page_controller(&state, &team_id).await?;let args = json!({"action": payload.action, "text": payload.text, "key": payload.key, "ref": payload.ref_});@@ -6850,7 +6897,134 @@ pub async fn act_sandbox());return Ok(Json(page));}- act_sandbox_allowed(State(state), Path(team_id), Json(payload)).await+ act_sandbox_allowed(State(state), Path(team_id), Json(payload), caller).await+}++/// Turns `browser_upload`'s file list into what [`crate::sandbox::browser_downloads`] needs to+/// answer a chooser: each entry is a chat attachment id visible to `caller` (same rule as+/// `read_attachment`/`share_file`: the turn's own chat, the chat a delegated task came from, and+/// files this bot shared — see [`super::attachments::visible`]; an id outside that falls through+/// to the plain "isn't a file in your folder" refusal below, same as an id that doesn't exist, so+/// a call never learns that an id exists in another chat) or, failing that, a path under the+/// bot's own folder (opened through [`safe_fs`](crate::sandbox::safe_fs), so `..` and a symlink+/// out of the folder are refused). Remote delivery (no filesystem in common with this Chrome)+/// reads every file's bytes, capped at 100 MB in all; local delivery stages a copy made from the+/// handle already opened and checked above (see [`stage_upload_copy`]) and passes that copy's+/// path, rather than the original attachment blob or workspace path — Chrome may not actually+/// read the file until well after this call returns, and by then a path handed back by name alone+/// could point at something else.+async fn resolve_upload_files(+ state: &AppState,+ workspace: &std::path::Path,+ local: bool,+ files: &[String],+ caller: UploadCaller<'_>,+) -> Result<Vec<crate::sandbox::browser_downloads::UploadFile>, String> {+ use crate::sandbox::browser_downloads::{UploadFile, UploadSource};+ use crate::sandbox::safe_fs;+ const REMOTE_CAP: u64 = 100 * 1024 * 1024;+ const TOO_BIG: &str = "That's more than this browser can take over a remote connection: 100 MB in all. Pick a smaller file.";+ let mut remaining = REMOTE_CAP;+ let mut out = Vec::with_capacity(files.len());+ for raw in files {+ let found = match caller {+ UploadCaller::Turn(scope) => super::attachments::visible(state, scope, raw).await,+ UploadCaller::Bot { kwant, chat } => super::attachments::visible_to(state, chat, Some(kwant), raw).await,+ UploadCaller::None => None,+ };+ if let Some(a) = found {+ if a.context_id.as_deref().is_some_and(|c| c.starts_with("document:")) {+ return Err(format!("{} can't be used this way.", a.name));+ }+ let root = super::attachments::root(state);+ let blob = super::attachments::blob_path(&root, &a.sha256)+ .ok_or_else(|| format!("{} is missing.", a.name))?;+ let last_modified_ms = a.created_at.timestamp_millis();+ if local {+ let src = std::fs::File::open(&blob).map_err(|_| format!("{} is missing.", a.name))?;+ let path = stage_upload_copy(state, &a.name, src).await.map_err(|_| format!("Couldn't read {}.", a.name))?;+ out.push(UploadFile { name: a.name, mime: a.mime, last_modified_ms, source: UploadSource::Path(path) });+ } else {+ let size = a.size.max(0) as u64;+ if size > remaining {+ return Err(TOO_BIG.to_string());+ }+ let bytes = tokio::fs::read(&blob).await.map_err(|_| format!("Couldn't read {}.", a.name))?;+ remaining -= size;+ out.push(UploadFile { name: a.name, mime: a.mime, last_modified_ms, source: UploadSource::Bytes(bytes) });+ }+ continue;+ }+ let rel = std::path::Path::new(raw.trim_start_matches('/'));+ let dir = safe_fs::Dir::open_strict(workspace).map_err(|_| "Your folder couldn't be opened.".to_string())?;+ // An id-shaped `raw` that fell through here might be an attachment id in a chat `caller`+ // can't see: echoing it back would tell the call it exists, so this refusal drops it+ // (same wording as a path that isn't found); a path keeps its name, since that's never+ // someone else's id.+ let mut file = dir.open_file(rel).map_err(|_| match uuid::Uuid::parse_str(raw) {+ Ok(_) => "That isn't a file in your folder or an attachment in this chat.".to_string(),+ Err(_) => format!("{raw} isn't a file in your folder."),+ })?;+ let name = rel.file_name().and_then(|n| n.to_str()).unwrap_or("file").to_string();+ let last_modified_ms = chrono::Utc::now().timestamp_millis();+ if local {+ let path = stage_upload_copy(state, &name, file).await.map_err(|_| format!("Couldn't read {raw}."))?;+ out.push(UploadFile { name, mime: String::new(), last_modified_ms, source: UploadSource::Path(path) });+ } else {+ let bytes = safe_fs::read_capped(&mut file, remaining).map_err(|_| TOO_BIG.to_string())?;+ remaining -= bytes.len() as u64;+ let mime = mime_guess::from_path(rel).first_or_octet_stream().to_string();+ out.push(UploadFile { name, mime, last_modified_ms, source: UploadSource::Bytes(bytes) });+ }+ }+ Ok(out)+}++const UPLOAD_TMP_TTL: std::time::Duration = std::time::Duration::from_secs(120);+const UPLOAD_TMP_ORPHAN_AGE: std::time::Duration = std::time::Duration::from_secs(600);++/// A copy of `src` (an attachment blob, or a workspace file — in both cases a handle+/// [`resolve_upload_files`] already opened and checked, read from directly rather than by+/// re-opening its path afterward) under a short-lived folder of kwnt's own, outside every bot's+/// workspace: same pattern as `browser_stream.rs`'s `chooser-tmp` for the live-view sheet.+/// `DOM.setFileInputFiles` names the file from its path's own basename, so the copy is named+/// after the real name, sanitized through [`super::attachments::clean_name`]. Staging outside the+/// workspace, from the handle rather than the path, closes the window between the check already+/// done on `src` and whenever Chrome actually reads the staged copy (the page may only do that+/// once the person acts on it, e.g. only once a form is submitted, so the copy can't be removed+/// right after this call returns either — it's swept up after `UPLOAD_TMP_TTL`, with+/// `sweep_upload_tmp` as a backstop for an orphan left behind by a restart).+async fn stage_upload_copy(state: &AppState, name: &str, mut src: std::fs::File) -> std::io::Result<PathBuf> {+ let tmp_root = super::attachments::root(state).join("upload-tmp");+ sweep_upload_tmp(&tmp_root).await;+ let dir = tmp_root.join(uuid::Uuid::new_v4().to_string());+ tokio::fs::create_dir_all(&dir).await?;+ let dest = dir.join(super::attachments::clean_name(name));+ let dest_for_copy = dest.clone();+ tokio::task::spawn_blocking(move || -> std::io::Result<()> {+ let mut out = std::fs::File::create(&dest_for_copy)?;+ std::io::copy(&mut src, &mut out)?;+ Ok(())+ })+ .await+ .map_err(std::io::Error::other)??;+ tokio::spawn(async move {+ tokio::time::sleep(UPLOAD_TMP_TTL).await;+ let _ = tokio::fs::remove_dir_all(&dir).await;+ });+ Ok(dest)+}++/// Deletes any `upload-tmp` directory older than `UPLOAD_TMP_ORPHAN_AGE`, a backstop for the+/// scheduled cleanup in [`stage_upload_copy`] if the process restarted before it ran.+async fn sweep_upload_tmp(tmp_root: &std::path::Path) {+ let Ok(mut entries) = tokio::fs::read_dir(tmp_root).await else { return };+ let cutoff = std::time::SystemTime::now() - UPLOAD_TMP_ORPHAN_AGE;+ while let Ok(Some(entry)) = entries.next_entry().await {+ if entry.metadata().await.ok().and_then(|m| m.modified().ok()).is_some_and(|m| m < cutoff) {+ let _ = tokio::fs::remove_dir_all(entry.path()).await;+ }+ }}/// [`act_sandbox`] without the payment check: for `browser_act`, whose approver already asked.@@ -6858,6 +7032,7 @@ pub async fn act_sandbox_allowed(State(state): State<AppState>,Path(team_id): Path<String>,Json(payload): Json<InteractPayload>,+ caller: UploadCaller<'_>,) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {let ctrl = page_controller(&state, &team_id).await?;let _permit = ctrl.control.try_read().map_err(|_| browser_request_failed(crate::sandbox::BrowserError::HumanControl))?;@@ -6876,7 +7051,7 @@ pub async fn act_sandbox_allowed(let here = before.as_ref().map(|b| b.url.clone()).unwrap_or_default();let repeat = ctrl.progress.lock().unwrap_or_else(|e| e.into_inner()).before(&here, key.as_deref());if let Some(stop) = repeat {- let mut page = page_state_from(&ctrl, before, "").await;+ let mut page = page_state_from(&ctrl, before, "", false).await;page["stalled"] = json!(true);page["error"] = json!(stop);return Ok(Json(page));@@ -6917,9 +7092,49 @@ pub async fn act_sandbox_allowed(.await.map(|_| "scrolled".to_string()).map_err(|e| e.to_string()),+ ("upload", _) => {+ let files = payload.files.clone().unwrap_or_default();+ if files.is_empty() {+ Err("files is required: a path in your folder or a chat attachment id.".to_string())+ } else {+ // `team_id` here is the page key: a job page (bot+chat) key for the common case,+ // not a team/channel/kwant id by itself, so it's resolved the same way+ // `controller_for` resolves this very controller's own workspace (open_page ->+ // controller_for both strip the page key down to its team/bot id first).+ match resolve_sandbox_target_info(&state, super::browser_pages::page_team(&team_id)).await {+ Some((_, workspace)) => {+ let local = state.browser_service.mode() == crate::sandbox::computer::ComputerMode::Local;+ match resolve_upload_files(&state, &workspace, local, &files, caller).await {+ Ok(resolved) => {+ let requested = resolved.len();+ ctrl.answer_upload(local, resolved).await.map(|names| {+ let mut message = format!(+ "Gave the page {}. Check the page shows it before you go on.",+ names.join(", ")+ );+ if names.len() < requested {+ if let Some(first) = names.first() {+ message.push_str(&format!(+ " This picker takes one file, so only {first} was used."+ ));+ }+ }+ message+ })+ }+ Err(e) => Err(e),+ }+ }+ None => Err("Couldn't find your folder.".to_string()),+ }+ }+ }+ // Shows what a page shows on hover (a tile's ⋮ menu) and says what appeared; clicks nothing+ ("hover", Some(target)) => ctrl.hover_target(&target).await.map_err(|e| e.to_string()),("click_text" | "click", None) => Err("click needs ref (a number from the clickable list) or text (a label).".to_string()),+ ("hover", None) => Err("hover needs ref (a number from the clickable list) or text (a label).".to_string()),(other, _) => Err(format!(- "Unknown action \"{}\". Use click (with ref or text), type (with text), key (with key) or scroll (with delta_y).",+ "Unknown action \"{}\". Use click (with ref or text), hover (with ref or text), type (with text), key (with key), scroll (with delta_y) or upload (with files).",other)),};@@ -6940,6 +7155,11 @@ pub async fn act_sandbox_allowed(};let mut after = ctrl.snapshot().await;let mut changed = diff(&after);+ // A hover mostly shows what was already in the page's text (an opacity-0 button): what it+ // brought up is the change+ if payload.action == "hover" && changed.is_none() {+ changed = result.as_ref().ok().and_then(|r| r.split_once("Appeared: ")).map(|(_, a)| format!("Appeared: {a}"));+ }if changed.is_none() {tokio::time::sleep(std::time::Duration::from_millis(400)).await;after = ctrl.snapshot().await;@@ -6954,7 +7174,7 @@ pub async fn act_sandbox_allowed(}}let stall = ctrl.progress.lock().unwrap_or_else(|e| e.into_inner()).after(changed.is_some());- let mut page = page_state_from(&ctrl, after, "").await;+ let mut page = page_state_from(&ctrl, after, "", false).await;page["changed"] = json!(changed.as_deref().unwrap_or("Nothing on the page changed."));match result {Ok(done) => page["result"] = json!(done),diff --git a/tests/browser_download_upload_test.rs b/tests/browser_download_upload_test.rsnew file mode 100644index 00000000..f61f4d8f--- /dev/null+++ b/tests/browser_download_upload_test.rs@@ -0,0 +1,469 @@+//! A bot's own browser saving a download straight into its folder, and a new `browser_upload`+//! tool answering a page's own file picker with a file from that folder or a chat attachment.+//! Runs a real windowless Chrome in Local mode and is skipped when none is installed.++#[path = "support/chrome_guard.rs"]+mod chrome_guard;+use chrome_guard::ChromeGuard;+use axum::{+ body::{to_bytes, Body},+ http::{Request, StatusCode},+ Router,+};+use kwnt::{+ broker::PermissionBroker,+ config::Config,+ db::{spaces::SpaceId, Database},+ router::LayaRouter,+ sandbox::computer,+ server::{+ continuity::{SelfScope, TurnOrigin},+ create_router, mcp_runtime,+ routes::resolve_sandbox_target_info,+ 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 button that navigates to `/note`, which replies with `Content-Disposition: attachment`+/// so Chrome treats it as a download rather than showing it.+const DOWNLOAD_PAGE: &str = "<!doctype html><title>dl</title><body>\+<button onclick=\"location.href='/note'\">Get the file</button>";+/// A hidden file input behind a button, same shape as `browser_file_chooser_test.rs`.+const UPLOAD_PAGE: &str = "<!doctype html><html><head><title>pick</title></head><body style=margin:0>\+<input type=file id=f style=display:none>\+<button onclick=f.click() style='position:fixed;inset:0'>Pick a file</button>\+<script>f.onchange=function(){document.title='picked:'+Array.from(f.files).map(function(x){return x.name}).join(',')}</script>\+</body></html>";+/// Same shape as `UPLOAD_PAGE`, but the input takes more than one file at once (non-blocking item 2).+const MULTI_UPLOAD_PAGE: &str = "<!doctype html><html><head><title>pick</title></head><body style=margin:0>\+<input type=file id=f multiple style=display:none>\+<button onclick=f.click() style='position:fixed;inset:0'>Pick files</button>\+<script>f.onchange=function(){document.title='picked:'+Array.from(f.files).map(function(x){return x.name}).join(',')}</script>\+</body></html>";+const NOTE_BYTES: &[u8] = b"hello from the download test, not a real document";++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 req = String::from_utf8_lossy(&buf[..n]).to_string();+ let path = req.split_whitespace().nth(1).unwrap_or("/");+ let reply = match path {+ "/note" => format!(+ "HTTP/1.1 200 OK\r\ncontent-type: application/octet-stream\r\n\+ content-disposition: attachment; filename=\"note.txt\"\r\n\+ content-length: {}\r\nconnection: close\r\n\r\n",+ NOTE_BYTES.len()+ )+ .into_bytes()+ .into_iter()+ .chain(NOTE_BYTES.iter().copied())+ .collect::<Vec<u8>>(),+ "/upload" => {+ let reply = format!(+ "HTTP/1.1 200 OK\r\ncontent-type: text/html\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{UPLOAD_PAGE}",+ UPLOAD_PAGE.len()+ );+ reply.into_bytes()+ }+ "/multi-upload" => {+ let reply = format!(+ "HTTP/1.1 200 OK\r\ncontent-type: text/html\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{MULTI_UPLOAD_PAGE}",+ MULTI_UPLOAD_PAGE.len()+ );+ reply.into_bytes()+ }+ _ => {+ let reply = format!(+ "HTTP/1.1 200 OK\r\ncontent-type: text/html\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{DOWNLOAD_PAGE}",+ DOWNLOAD_PAGE.len()+ );+ reply.into_bytes()+ }+ };+ let _ = stream.write_all(&reply).await;+ });+ }+ });+ format!("http://127.0.0.1:{port}")+}++struct Env {+ app: Router,+ state: AppState,+ _tmp: TempDir,+}++async fn setup() -> Env {+ std::env::remove_var("DISPLAY");+ std::env::remove_var("WAYLAND_DISPLAY");+ std::env::set_var("KWNT_COMPUTER_MODE", "local");+ let tmp = tempdir().unwrap();+ let db = Database::init(tmp.path()).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()));+ Env { app: create_router(state.clone()), state, _tmp: tmp }+}++fn rpc(method: &str, params: Value) -> Value {+ json!({"jsonrpc": "2.0", "id": 1, "method": method, "params": params})+}++async fn post(app: &Router, uri: &str, token: &str, body: Value) -> Value {+ let req = Request::builder()+ .method("POST")+ .uri(uri)+ .header("content-type", "application/json")+ .header("authorization", format!("Bearer {token}"))+ .body(Body::from(body.to_string()))+ .unwrap();+ let resp = app.clone().oneshot(req).await.unwrap();+ assert_eq!(resp.status(), StatusCode::OK);+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();+ serde_json::from_slice(&bytes).unwrap_or(Value::Null)+}++/// Calls one self tool; returns its parsed `page` JSON and whether it errored.+async fn self_tool(app: &Router, token: &str, name: &str, args: Value) -> (Value, bool) {+ let v = post(app, "/api/mcp/self", token, rpc("tools/call", json!({"name": name, "arguments": args}))).await;+ let is_error = v["result"]["isError"].as_bool().unwrap_or(false);+ let text = v["result"]["content"][0]["text"].as_str().unwrap_or("");+ (serde_json::from_str(text).unwrap_or(Value::Null), is_error)+}++/// Uploads a small file through the real `/api/attachments` route, returning its id.+async fn upload_attachment(state: &AppState, name: &str, bytes: &'static [u8]) -> String {+ let app = create_router(state.clone());+ let req = Request::builder()+ .method("POST")+ .uri(format!("/api/attachments?name={name}"))+ .header("content-type", "application/octet-stream")+ .body(Body::from(bytes))+ .unwrap();+ let resp = app.oneshot(req).await.unwrap();+ assert_eq!(resp.status(), StatusCode::CREATED);+ let body = to_bytes(resp.into_body(), usize::MAX).await.unwrap();+ let v: Value = serde_json::from_slice(&body).unwrap();+ v["id"].as_str().expect("attachment id").to_string()+}++/// Polls `browser_page` until a file picker is reported open, or panics.+async fn wait_for_chooser(app: &Router, token: &str) -> Value {+ for _ in 0..50 {+ let (page, is_error) = self_tool(app, token, "browser_page", json!({})).await;+ assert!(!is_error, "{page}");+ if page["file_chooser"].is_object() {+ return page["file_chooser"].clone();+ }+ tokio::time::sleep(Duration::from_millis(100)).await;+ }+ panic!("no file picker was ever reported open");+}++/// Polls `browser_page` until `download.status` is terminal (done/cancelled/failed), or panics.+async fn wait_for_download(app: &Router, token: &str) -> Value {+ for _ in 0..100 {+ let (page, is_error) = self_tool(app, token, "browser_page", json!({})).await;+ assert!(!is_error, "{page}");+ if let Some(status) = page["download"]["status"].as_str() {+ if status != "in_progress" {+ return page["download"].clone();+ }+ }+ tokio::time::sleep(Duration::from_millis(150)).await;+ }+ panic!("download never reached a terminal state");+}++#[tokio::test]+async fn a_download_lands_in_the_bots_own_folder() {+ if computer::local_chrome_path().is_none() {+ eprintln!("skipped: no Chrome or Chromium installed");+ return;+ }+ let e = setup().await;+ let _chrome = ChromeGuard(e.state.config.data_dir.join("local-chrome"));+ let kwants = e.state.db.list_kwants(&SpaceId::default_space()).await.unwrap();+ let bot = &kwants[0];+ let scope = SelfScope { kwant_id: bot.id.clone(), kwant_name: bot.name.clone(), sandbox_target: Some(bot.id.clone()), ..Default::default() };+ let (_ctx, token) = mcp_runtime::prepare_turn_with_self(&e.state, bot, None, None, Some(scope)).await.unwrap();++ let base = serve().await;+ let (page, is_error) = self_tool(&e.app, &token, "browser_open", json!({"url": base})).await;+ assert!(!is_error, "{page}");++ let (page, is_error) = self_tool(&e.app, &token, "browser_act", json!({"action": "click_text", "text": "Get the file"})).await;+ assert!(!is_error, "{page}");++ let report = wait_for_download(&e.app, &token).await;+ assert_eq!(report["status"], "done", "{report}");+ assert_eq!(report["name"], "note.txt");+ assert_eq!(report["path"], "downloads/note.txt");+ assert!(report["note"].as_str().unwrap().contains("Downloaded note.txt"), "{report}");++ let (_, workspace) = resolve_sandbox_target_info(&e.state, &bot.id).await.expect("bot workspace");+ let landed = std::fs::read(workspace.join("downloads/note.txt")).expect("file landed on disk");+ assert_eq!(landed, NOTE_BYTES);++ mcp_runtime::finish_turn(&e.state, &token).await;+}++#[tokio::test]+async fn a_second_download_with_the_same_name_never_overwrites_the_first() {+ if computer::local_chrome_path().is_none() {+ eprintln!("skipped: no Chrome or Chromium installed");+ return;+ }+ let e = setup().await;+ let _chrome = ChromeGuard(e.state.config.data_dir.join("local-chrome"));+ let kwants = e.state.db.list_kwants(&SpaceId::default_space()).await.unwrap();+ let bot = &kwants[0];+ let scope = SelfScope { kwant_id: bot.id.clone(), kwant_name: bot.name.clone(), sandbox_target: Some(bot.id.clone()), ..Default::default() };+ let (_ctx, token) = mcp_runtime::prepare_turn_with_self(&e.state, bot, None, None, Some(scope)).await.unwrap();++ let base = serve().await;+ for _ in 0..2 {+ let (page, is_error) = self_tool(&e.app, &token, "browser_open", json!({"url": base})).await;+ assert!(!is_error, "{page}");+ let (page, is_error) = self_tool(&e.app, &token, "browser_act", json!({"action": "click_text", "text": "Get the file"})).await;+ assert!(!is_error, "{page}");+ wait_for_download(&e.app, &token).await;+ }++ let (_, workspace) = resolve_sandbox_target_info(&e.state, &bot.id).await.expect("bot workspace");+ assert!(workspace.join("downloads/note.txt").exists());+ assert!(workspace.join("downloads/note (2).txt").exists(), "the second download got a collision-safe name instead of overwriting");++ mcp_runtime::finish_turn(&e.state, &token).await;+}++#[tokio::test]+async fn a_download_in_one_bots_session_never_reaches_another() {+ if computer::local_chrome_path().is_none() {+ eprintln!("skipped: no Chrome or Chromium installed");+ return;+ }+ let e = setup().await;+ let _chrome = ChromeGuard(e.state.config.data_dir.join("local-chrome"));+ let kwants = e.state.db.list_kwants(&SpaceId::default_space()).await.unwrap();+ let (bot_a, bot_b) = (&kwants[0], &kwants[1]);+ let scope_a = SelfScope { kwant_id: bot_a.id.clone(), kwant_name: bot_a.name.clone(), sandbox_target: Some(bot_a.id.clone()), ..Default::default() };+ let scope_b = SelfScope { kwant_id: bot_b.id.clone(), kwant_name: bot_b.name.clone(), sandbox_target: Some(bot_b.id.clone()), ..Default::default() };+ let (_ctx_a, token_a) = mcp_runtime::prepare_turn_with_self(&e.state, bot_a, None, None, Some(scope_a)).await.unwrap();+ let (_ctx_b, token_b) = mcp_runtime::prepare_turn_with_self(&e.state, bot_b, None, None, Some(scope_b)).await.unwrap();++ let base = serve().await;+ // Both sessions share the one local Chrome: open B's page first, so its own dedicated+ // DevTools connection and frame tree are already up before A's download ever begins.+ let (page, is_error) = self_tool(&e.app, &token_b, "browser_open", json!({"url": base})).await;+ assert!(!is_error, "{page}");+ let (page, is_error) = self_tool(&e.app, &token_a, "browser_open", json!({"url": base})).await;+ assert!(!is_error, "{page}");++ let (page, is_error) = self_tool(&e.app, &token_a, "browser_act", json!({"action": "click_text", "text": "Get the file"})).await;+ assert!(!is_error, "{page}");+ let report = wait_for_download(&e.app, &token_a).await;+ assert_eq!(report["status"], "done", "{report}");++ let (_, workspace_a) = resolve_sandbox_target_info(&e.state, &bot_a.id).await.expect("bot a workspace");+ assert!(workspace_a.join("downloads/note.txt").exists(), "the download should land in A's own folder");++ let (_, workspace_b) = resolve_sandbox_target_info(&e.state, &bot_b.id).await.expect("bot b workspace");+ assert!(!workspace_b.join("downloads").exists() || std::fs::read_dir(workspace_b.join("downloads")).unwrap().next().is_none(), "nothing should have landed in B's folder");++ let (page_b, is_error) = self_tool(&e.app, &token_b, "browser_page", json!({})).await;+ assert!(!is_error, "{page_b}");+ assert!(page_b["download"].is_null(), "B's own page never started a download, so it should report none: {page_b}");++ mcp_runtime::finish_turn(&e.state, &token_a).await;+ mcp_runtime::finish_turn(&e.state, &token_b).await;+}++#[tokio::test]+async fn browser_upload_answers_the_pages_own_picker_with_a_workspace_file() {+ if computer::local_chrome_path().is_none() {+ eprintln!("skipped: no Chrome or Chromium installed");+ return;+ }+ let e = setup().await;+ let _chrome = ChromeGuard(e.state.config.data_dir.join("local-chrome"));+ let kwants = e.state.db.list_kwants(&SpaceId::default_space()).await.unwrap();+ let bot = &kwants[0];+ let scope = SelfScope { kwant_id: bot.id.clone(), kwant_name: bot.name.clone(), sandbox_target: Some(bot.id.clone()), ..Default::default() };+ let (_ctx, token) = mcp_runtime::prepare_turn_with_self(&e.state, bot, None, None, Some(scope)).await.unwrap();++ let (_, workspace) = resolve_sandbox_target_info(&e.state, &bot.id).await.expect("bot workspace");+ std::fs::create_dir_all(workspace.join("downloads")).unwrap();+ std::fs::write(workspace.join("downloads/clip.mp4"), b"not really a video, just test bytes").unwrap();++ let base = serve().await;+ let (page, is_error) = self_tool(&e.app, &token, "browser_open", json!({"url": format!("{base}/upload")})).await;+ assert!(!is_error, "{page}");++ let (page, is_error) = self_tool(&e.app, &token, "browser_act", json!({"action": "click_text", "text": "Pick a file"})).await;+ assert!(!is_error, "{page}");+ let chooser = wait_for_chooser(&e.app, &token).await;+ assert!(chooser["note"].as_str().unwrap_or("").contains("A file picker opened"), "{chooser}");++ let (page, is_error) = self_tool(&e.app, &token, "browser_upload", json!({"files": ["downloads/clip.mp4"]})).await;+ assert!(!is_error, "{page}");+ assert!(page["result"].as_str().unwrap_or("").contains("clip.mp4"), "{page}");+ assert!(page["title"].as_str().unwrap_or("").contains("picked:clip.mp4"), "the page's own change handler should have seen the file: {page}");++ mcp_runtime::finish_turn(&e.state, &token).await;+}++#[tokio::test]+async fn browser_upload_answers_the_pages_own_picker_with_a_chat_attachment() {+ if computer::local_chrome_path().is_none() {+ eprintln!("skipped: no Chrome or Chromium installed");+ return;+ }+ let e = setup().await;+ let _chrome = ChromeGuard(e.state.config.data_dir.join("local-chrome"));+ let kwants = e.state.db.list_kwants(&SpaceId::default_space()).await.unwrap();+ let bot = &kwants[0];+ let scope = SelfScope {+ kwant_id: bot.id.clone(),+ kwant_name: bot.name.clone(),+ sandbox_target: Some(bot.id.clone()),+ origin: Some(TurnOrigin { channel_id: Some("chat-a".into()), ..Default::default() }),+ ..Default::default()+ };+ let (_ctx, token) = mcp_runtime::prepare_turn_with_self(&e.state, bot, None, None, Some(scope)).await.unwrap();++ // A real chat attachment only gets its context_id once it's actually sent with a message+ // (see `attachments::attach_to_message`); link it to this turn's own chat the same way.+ let attachment_id = upload_attachment(&e.state, "post.mov", b"\x00\x00\x00\x14ftypqt attachment bytes, also not a real video").await;+ e.state.db.link_attachments(std::slice::from_ref(&attachment_id), "msg-a", "chat-a", Some("chat-a"), None, None).await.unwrap();++ let base = serve().await;+ let (page, is_error) = self_tool(&e.app, &token, "browser_open", json!({"url": format!("{base}/upload")})).await;+ assert!(!is_error, "{page}");+ let (page, is_error) = self_tool(&e.app, &token, "browser_act", json!({"action": "click_text", "text": "Pick a file"})).await;+ assert!(!is_error, "{page}");+ wait_for_chooser(&e.app, &token).await;++ let (page, is_error) = self_tool(&e.app, &token, "browser_upload", json!({"files": [attachment_id]})).await;+ assert!(!is_error, "{page}");+ assert!(page["title"].as_str().unwrap_or("").contains("picked:post.mov"), "{page}");++ mcp_runtime::finish_turn(&e.state, &token).await;+}++#[tokio::test]+async fn browser_upload_refuses_an_attachment_from_another_chat() {+ if computer::local_chrome_path().is_none() {+ eprintln!("skipped: no Chrome or Chromium installed");+ return;+ }+ let e = setup().await;+ let _chrome = ChromeGuard(e.state.config.data_dir.join("local-chrome"));+ let kwants = e.state.db.list_kwants(&SpaceId::default_space()).await.unwrap();+ let bot = &kwants[0];+ let scope = SelfScope {+ kwant_id: bot.id.clone(),+ kwant_name: bot.name.clone(),+ sandbox_target: Some(bot.id.clone()),+ origin: Some(TurnOrigin { channel_id: Some("chat-a".into()), ..Default::default() }),+ ..Default::default()+ };+ let (_ctx, token) = mcp_runtime::prepare_turn_with_self(&e.state, bot, None, None, Some(scope)).await.unwrap();++ let (_, workspace) = resolve_sandbox_target_info(&e.state, &bot.id).await.expect("bot workspace");+ std::fs::create_dir_all(&workspace).unwrap();++ // Linked to a different chat than the one this turn runs in.+ let attachment_id = upload_attachment(&e.state, "secret.mov", b"\x00\x00\x00\x14ftypqt someone else's chat's file").await;+ e.state.db.link_attachments(std::slice::from_ref(&attachment_id), "msg-b", "chat-b", Some("chat-b"), None, None).await.unwrap();++ let base = serve().await;+ let (page, is_error) = self_tool(&e.app, &token, "browser_open", json!({"url": format!("{base}/upload")})).await;+ assert!(!is_error, "{page}");+ let (page, is_error) = self_tool(&e.app, &token, "browser_act", json!({"action": "click_text", "text": "Pick a file"})).await;+ assert!(!is_error, "{page}");+ wait_for_chooser(&e.app, &token).await;++ let (page, is_error) = self_tool(&e.app, &token, "browser_upload", json!({"files": [attachment_id]})).await;+ assert!(is_error, "{page}");+ let error = page["error"].as_str().unwrap_or("");+ assert!(error.contains("isn't a file in your folder"), "{page}");+ assert!(!error.contains(&attachment_id), "the refusal must not reveal that the id exists: {page}");++ let (page, is_error) = self_tool(&e.app, &token, "browser_page", json!({})).await;+ assert!(!is_error, "{page}");+ assert!(page["file_chooser"].is_object(), "nothing should have reached the page: the picker should still be open");++ mcp_runtime::finish_turn(&e.state, &token).await;+}++#[tokio::test]+async fn browser_upload_fills_a_multiple_file_input_in_one_call() {+ if computer::local_chrome_path().is_none() {+ eprintln!("skipped: no Chrome or Chromium installed");+ return;+ }+ let e = setup().await;+ let _chrome = ChromeGuard(e.state.config.data_dir.join("local-chrome"));+ let kwants = e.state.db.list_kwants(&SpaceId::default_space()).await.unwrap();+ let bot = &kwants[0];+ let scope = SelfScope { kwant_id: bot.id.clone(), kwant_name: bot.name.clone(), sandbox_target: Some(bot.id.clone()), ..Default::default() };+ let (_ctx, token) = mcp_runtime::prepare_turn_with_self(&e.state, bot, None, None, Some(scope)).await.unwrap();++ let (_, workspace) = resolve_sandbox_target_info(&e.state, &bot.id).await.expect("bot workspace");+ std::fs::create_dir_all(workspace.join("downloads")).unwrap();+ std::fs::write(workspace.join("downloads/one.txt"), b"first file").unwrap();+ std::fs::write(workspace.join("downloads/two.txt"), b"second file").unwrap();++ let base = serve().await;+ let (page, is_error) = self_tool(&e.app, &token, "browser_open", json!({"url": format!("{base}/multi-upload")})).await;+ assert!(!is_error, "{page}");+ let (page, is_error) = self_tool(&e.app, &token, "browser_act", json!({"action": "click_text", "text": "Pick files"})).await;+ assert!(!is_error, "{page}");+ wait_for_chooser(&e.app, &token).await;++ let (page, is_error) =+ self_tool(&e.app, &token, "browser_upload", json!({"files": ["downloads/one.txt", "downloads/two.txt"]})).await;+ assert!(!is_error, "{page}");+ let title = page["title"].as_str().unwrap_or("");+ assert!(title.contains("picked:one.txt,two.txt"), "the page's own change handler should have seen both files: {page}");++ mcp_runtime::finish_turn(&e.state, &token).await;+}++#[tokio::test]+async fn browser_upload_is_refused_with_no_picker_open() {+ if computer::local_chrome_path().is_none() {+ eprintln!("skipped: no Chrome or Chromium installed");+ return;+ }+ let e = setup().await;+ let _chrome = ChromeGuard(e.state.config.data_dir.join("local-chrome"));+ let kwants = e.state.db.list_kwants(&SpaceId::default_space()).await.unwrap();+ let bot = &kwants[0];+ let scope = SelfScope { kwant_id: bot.id.clone(), kwant_name: bot.name.clone(), sandbox_target: Some(bot.id.clone()), ..Default::default() };+ let (_ctx, token) = mcp_runtime::prepare_turn_with_self(&e.state, bot, None, None, Some(scope)).await.unwrap();++ let base = serve().await;+ let (page, is_error) = self_tool(&e.app, &token, "browser_open", json!({"url": format!("{base}/upload")})).await;+ assert!(!is_error, "{page}");++ let (_, workspace) = resolve_sandbox_target_info(&e.state, &bot.id).await.expect("bot workspace");+ std::fs::create_dir_all(&workspace).unwrap();+ std::fs::write(workspace.join("stray.txt"), b"nothing should want this").unwrap();+ let (page, is_error) = self_tool(&e.app, &token, "browser_upload", json!({"files": ["stray.txt"]})).await;+ assert!(is_error, "{page}");+ assert!(page["error"].as_str().unwrap_or("").contains("No file picker is open"), "{page}");++ mcp_runtime::finish_turn(&e.state, &token).await;+}diff --git a/tests/browser_hover_test.rs b/tests/browser_hover_test.rsnew file mode 100644index 00000000..4bbcf2c0--- /dev/null+++ b/tests/browser_hover_test.rs@@ -0,0 +1,365 @@+//! Hover-only controls and clickable cards in kwnt's own browser, through a real Chrome: a tile+//! grid where each tile is a div with a JS click listener and its ⋮ button is opacity 0 until the+//! mouse is over the tile (Google Flow's clip grid). The list names the tiles as cards and the ⋮+//! buttons as "More" (on hover) with their tile; a click on one, by label or by ref, hovers the+//! tile first and then opens its menu, whose Download item is clicked next. The hover action says+//! what appeared. Ordinary controls are listed before hover controls and cards, which are capped+//! at 40 each, icon-only buttons are named by their icon word, and the payment check still judges+//! the same element and label. 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,+ reads::{pick_controls, SHOWN_CONTROLS},+ BrowserError,+ },+ server::{continuity::browser_act_payment, create_router, routes::get_or_create_browser_controller, AppState},+ tools::ToolRunner,+};+use serde_json::{json, Value};+use tempfile::{tempdir, TempDir};+use tokio::io::{AsyncReadExt, AsyncWriteExt};+use tower::ServiceExt;++/// Tiles as Google Flow draws them: a div with a click listener (no button, no link, no role),+/// a ⋮ icon button at opacity 0 that `.tile:hover` shows, and a menu it opens in a portal.+const TILES_PAGE: &str = r##"<!doctype html><title>flow</title>+<style>+body{font:14px sans-serif;margin:20px}+.grid{display:grid;grid-template-columns:repeat(4,200px);gap:12px}+.tile{position:relative;height:140px;background:#333;color:#fff;cursor:pointer}+.tile .more{position:absolute;top:6px;right:6px;opacity:0}+.tile:hover .more{opacity:1}+.tile .share{position:absolute;top:6px;left:6px;visibility:hidden}+.tile:hover .share{visibility:visible}+.menu{position:fixed;background:#fff;border:1px solid #000;color:#000}+.menu [role=menuitem]{padding:6px 12px;cursor:pointer}+</style>+<div class=grid>+ <div class=tile data-name="Clip 1"><div>Clip 1</div><button class=more><i class="google-symbols">more_vert</i></button></div>+ <div class=tile data-name="Clip 2"><div>Clip 2</div><button class=more><i class="google-symbols">more_vert</i></button></div>+ <div class=tile data-name="Clip 3"><div>Clip 3</div><button class=share><span class="material-symbols-outlined">share</span></button></div>+ <div class=tile id=js data-name="Clip 4"><div>Clip 4</div><button id=edit style="position:absolute;bottom:6px;left:6px;opacity:0"><i class="material-icons">edit</i></button></div>+ <div class=tile data-name="Clip 5"><div>Clip 5</div><button id=never style="position:absolute;bottom:6px;right:6px;opacity:0" aria-label="Never shown"></button><button style="display:none">Gone for good</button></div>+</div>+<div id=portal></div>+<script>+document.querySelectorAll('.tile').forEach(function (t) {+ t.addEventListener('click', function (e) { if (e.target.closest('button')) return; document.title = 'opened ' + t.dataset.name; });+ var more = t.querySelector('.more');+ if (more) more.addEventListener('click', function (e) {+ e.stopPropagation();+ var r = this.getBoundingClientRect(), p = document.getElementById('portal');+ p.innerHTML = '<div class=menu role=menu style="left:' + r.left + 'px;top:' + (r.bottom + 4) + 'px"><div role=menuitem>Download</div><div role=menuitem>Delete</div></div>';+ p.querySelector('[role=menuitem]').addEventListener('click', function () { document.title = 'download ' + t.dataset.name; p.innerHTML = ''; });+ });+ var share = t.querySelector('.share');+ if (share) share.addEventListener('click', function (e) { e.stopPropagation(); document.title = 'share ' + t.dataset.name; });+});+// Shown by a script on mouseenter, not by CSS+var js = document.getElementById('js'), edit = document.getElementById('edit');+js.addEventListener('mouseenter', function () { edit.style.opacity = 1; });+js.addEventListener('mouseleave', function () { edit.style.opacity = 0; });+edit.addEventListener('click', function (e) { e.stopPropagation(); document.title = 'edit Clip 4'; });+</script>"##;++/// Icon-only buttons and cards named every way the list knows.+const LABELS_PAGE: &str = r##"<!doctype html><title>labels</title>+<button><i class="material-icons">more_vert</i></button>+<button><span class="material-symbols-outlined">more_horiz</span></button>+<button aria-label="Close dialog"><i class="material-icons">close</i></button>+<button title="Remove clip"><i class="material-icons">delete</i></button>+<button class="material-icons">download</button>+<a href="#s"><i class="google-symbols">share</i></a>+<button><i class="material-icons">photo_camera</i></button>+<button>close</button>+<div style="cursor:pointer;width:200px;height:60px" aria-label="Open project">x</div>+<div style="cursor:pointer;width:200px;height:60px"><img alt="Sunset clip" width=50 height=50></div>+<div style="cursor:pointer;width:200px;height:60px"><button style="width:200px;height:60px">Big</button></div>+<div style="cursor:pointer;position:fixed;inset:0;z-index:-1">Backdrop</div>"##;++const CARD_PAGE: &str = "<!doctype html><title>card</title><form onsubmit=\"return false\">\+<input autocomplete=cc-number placeholder='Card number'><button type=submit>Continue</button></form>";++/// 60 clickable cards, of which the list shows 40, and after them in the page 10 buttons, which+/// the list puts before the cards.+fn many_page() -> String {+ let cards: String = (0..60)+ .map(|i| format!("<div style='cursor:pointer;display:inline-block;width:120px;height:40px;margin:2px'>Card {i}</div>"))+ .collect();+ let buttons: String = (0..10).map(|i| format!("<button>Button {i}</button>")).collect();+ format!("<!doctype html><title>many</title>{cards}{buttons}")+}++/// A small HTTP server for the pages above on 127.0.0.1, so the test needs no network.+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 req = String::from_utf8_lossy(&buf[..n]).to_string();+ let path = req.split_whitespace().nth(1).unwrap_or("/").to_string();+ let page = match path.as_str() {+ "/tiles" => TILES_PAGE.to_string(),+ "/labels" => LABELS_PAGE.to_string(),+ "/card" => CARD_PAGE.to_string(),+ _ => many_page(),+ };+ let reply = format!(+ "HTTP/1.1 200 OK\r\ncontent-type: text/html\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}")+}++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 open(e: &Env, url: &str) -> kwnt::sandbox::BrowserController {+ let ctrl = get_or_create_browser_controller(&e.state, &e.bot.id).await.expect("local Chrome session");+ ctrl.navigate(url).await.unwrap();+ ctrl+}+++async fn pay(e: &Env, args: Value) -> Option<String> {+ browser_act_payment(&e.state, &e.bot.id, &args).await+}+async fn post_act(app: &Router, bot: &str, body: Value) -> (StatusCode, Value) {+ let req = Request::builder()+ .method("POST")+ .uri(format!("/api/sandbox/{bot}/act"))+ .header("content-type", "application/json")+ .body(Body::from(body.to_string()))+ .unwrap();+ let resp = app.clone().oneshot(req).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 get_page(app: &Router, bot: &str) -> Value {+ let req = Request::builder().uri(format!("/api/sandbox/{bot}/page")).body(Body::empty()).unwrap();+ let resp = app.clone().oneshot(req).await.unwrap();+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();+ serde_json::from_slice(&bytes).unwrap()+}++/// The ref of the first listed control whose line contains `needle`.+fn ref_of(page: &Value, needle: &str) -> u64 {+ let lines = page["clickable"].as_array().expect("a clickable list");+ let line = lines.iter().filter_map(Value::as_str).find(|l| l.contains(needle)).unwrap_or_else(|| panic!("{needle} in {page}"));+ let line = line.trim_start_matches('*');+ line[1..line.find(']').unwrap()].parse().unwrap()+}+++fn lines(page: &Value) -> Vec<String> {+ page["clickable"].as_array().expect("a clickable list").iter().filter_map(Value::as_str).map(|l| l.trim_start_matches('*').to_string()).collect()+}++#[tokio::test]+async fn a_hover_only_menu_on_a_tile_opens_and_downloads_by_text_and_by_ref() {+ 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 base = serve().await;+ let ctrl = open(&e, &format!("{base}/tiles")).await;++ // The tiles are cards; each ⋮ button is "More", shown on hover, with its tile+ let page = get_page(&e.app, &e.bot.id).await;+ let list = lines(&page);+ for want in [+ r#"card "Clip 1""#,+ r#"button "More" (on hover) · Clip 1"#,+ r#"button "More" (on hover) · Clip 2"#,+ r#"button "Share" (on hover) · Clip 3"#,+ r#"button "Edit" (on hover) · Clip 4"#,+ ] {+ assert!(list.iter().any(|l| l.ends_with(want)), "{want} in {list:#?}");+ }+ assert!(!list.iter().any(|l| l.contains("Gone for good")), "display:none is never listed: {list:#?}");+ assert!(!list.iter().any(|l| l.contains("more_vert")), "the icon word is read as More: {list:#?}");++ // By text: More hovers Clip 1 first, then opens its menu; Download is in it+ let (status, page) = post_act(&e.app, &e.bot.id, json!({"action": "click_text", "text": "More"})).await;+ assert_eq!(status, StatusCode::OK);+ assert!(page["error"].is_null(), "{page}");+ assert_eq!(page["result"], "clicked \"More\"", "{page}");+ assert!(lines(&page).iter().any(|l| l.ends_with(r#"menuitem "Download""#)), "{page}");+ let (_, page) = post_act(&e.app, &e.bot.id, json!({"action": "click_text", "text": "Download"})).await;+ assert_eq!(page["title"], "download Clip 1", "{page}");++ // By ref: Clip 2's More, then the Download the menu brought up+ open(&e, &format!("{base}/tiles")).await;+ let page = get_page(&e.app, &e.bot.id).await;+ let (_, page) = post_act(&e.app, &e.bot.id, json!({"action": "click", "ref": ref_of(&page, "(on hover) · Clip 2")})).await;+ assert!(page["error"].is_null(), "{page}");+ let download = page["clickable"].as_array().unwrap().iter().filter_map(Value::as_str).find(|l| l.ends_with(r#"menuitem "Download""#)).unwrap().to_string();+ assert!(download.starts_with('*'), "the menu's items are new: {download}");+ let (_, page) = post_act(&e.app, &e.bot.id, json!({"action": "click", "ref": ref_of(&page, r#"menuitem "Download""#)})).await;+ assert_eq!(page["title"], "download Clip 2", "{page}");++ // Shown by visibility (CSS) and by a mouseenter script: both click+ open(&e, &format!("{base}/tiles")).await;+ let page = get_page(&e.app, &e.bot.id).await;+ let (_, page) = post_act(&e.app, &e.bot.id, json!({"action": "click", "ref": ref_of(&page, "(on hover) · Clip 3")})).await;+ assert_eq!(page["title"], "share Clip 3", "{page}");+ let (_, page) = post_act(&e.app, &e.bot.id, json!({"action": "click_text", "text": "Edit"})).await;+ assert_eq!(page["title"], "edit Clip 4", "{page}");++ // The tile itself, a div with a click listener, by its name+ let (_, page) = post_act(&e.app, &e.bot.id, json!({"action": "click_text", "text": "Clip 2"})).await;+ assert_eq!(page["title"], "opened Clip 2", "{page}");++ // A button that never shows: hovered, still hidden, so nothing is clicked+ open(&e, &format!("{base}/tiles")).await;+ let page = get_page(&e.app, &e.bot.id).await;+ let never = ref_of(&page, "Never shown") as u32;+ let err = ctrl.click_ref(never).await.unwrap_err();+ assert!(matches!(err, BrowserError::StaleRef(_)), "{err}");+ assert!(err.to_string().contains("stayed hidden after hovering over \"Clip 5\""), "{err}");+ let err = ctrl.click_target(&kwnt::sandbox::ClickTarget::Text("Never shown".into())).await.unwrap_err();+ assert!(err.to_string().contains("Didn't click \"Never shown\": it stayed hidden"), "{err}");+ assert_eq!(ctrl.sync_location().await.unwrap().1, "flow");+}++#[tokio::test]+async fn a_hover_says_what_appeared_and_clicks_nothing() {+ 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 base = serve().await;+ open(&e, &format!("{base}/tiles")).await;++ let (status, page) = post_act(&e.app, &e.bot.id, json!({"action": "hover", "text": "Clip 1"})).await;+ assert_eq!(status, StatusCode::OK);+ assert_eq!(page["result"], "Hovered over \"Clip 1\". Appeared: More (button)", "{page}");+ assert_eq!(page["changed"], "Appeared: More (button)", "{page}");+ assert_eq!(page["title"], "flow", "a hover clicks nothing: {page}");++ // By ref, a hover-only control: its card is hovered+ let page = get_page(&e.app, &e.bot.id).await;+ let (_, page) = post_act(&e.app, &e.bot.id, json!({"action": "hover", "ref": ref_of(&page, "(on hover) · Clip 2")})).await;+ assert!(page["result"].as_str().unwrap().starts_with("Hovered over \"Clip 2\". Appeared: More (button)"), "{page}");++ // Nothing to hover, and no target at all+ let (_, page) = post_act(&e.app, &e.bot.id, json!({"action": "hover", "text": "No such thing"})).await;+ assert!(page["error"].as_str().unwrap().contains("Didn't hover over \"No such thing\""), "{page}");+ let (_, page) = post_act(&e.app, &e.bot.id, json!({"action": "hover"})).await;+ assert!(page["error"].as_str().unwrap().contains("hover needs ref"), "{page}");++ // A hover never pays+ assert_eq!(pay(&e, json!({"action": "hover", "text": "More"})).await, None);+}++#[tokio::test]+async fn cards_are_capped_and_icon_buttons_are_named() {+ 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 base = serve().await;++ let ctrl = open(&e, &format!("{base}/many")).await;+ let all = ctrl.list_clickables(400).await;+ assert_eq!(all.iter().filter(|l| l.contains("] card \"Card ")).count(), 40, "{all:#?}");+ // 60 cards and 10 buttons: the 40 lines a bot is shown hold all 10 buttons, first+ let (shown, _) = pick_controls(&all, "", SHOWN_CONTROLS);+ let buttons: Vec<&String> = shown.iter().filter(|l| l.contains("] button \"Button ")).collect();+ assert_eq!(buttons.len(), 10, "{shown:#?}");+ assert!(shown[..10].iter().all(|l| l.contains("] button \"Button ")), "{shown:#?}");++ open(&e, &format!("{base}/labels")).await;+ let all: Vec<String> = ctrl.list_clickables(400).await;+ let names: Vec<&str> = all.iter().map(|l| l.split_once("] ").unwrap().1).collect();+ assert_eq!(+ names,+ [+ r#"button "More""#,+ r#"button "More""#,+ r#"button "Close dialog""#,+ r#"button "Remove clip""#,+ r#"button "Download""#,+ r#"link "Share""#,+ r#"button "photo_camera""#,+ r#"button "close""#,+ r#"button "Big""#,+ r#"card "Open project""#,+ r#"card "Sunset clip""#,+ ],+ "{all:#?}"+ );+}++#[tokio::test]+async fn the_payment_check_still_judges_the_same_control() {+ 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 base = serve().await;++ open(&e, &format!("{base}/card")).await;+ let page = get_page(&e.app, &e.bot.id).await;+ let why = pay(&e, json!({"action": "click_text", "text": "Continue"})).await.expect("Continue on a card form");+ assert!(why.contains("card fields"), "{why}");+ let why = pay(&e, json!({"action": "click", "ref": ref_of(&page, "Continue")})).await.expect("by ref too");+ assert!(why.contains("card fields"), "{why}");++ // On the tile page nothing is a payment: More, a hover-only control, and a card+ open(&e, &format!("{base}/tiles")).await;+ let page = get_page(&e.app, &e.bot.id).await;+ assert_eq!(pay(&e, json!({"action": "click_text", "text": "More"})).await, None);+ assert_eq!(pay(&e, json!({"action": "click", "ref": ref_of(&page, "(on hover) · Clip 1")})).await, None);+ assert_eq!(pay(&e, json!({"action": "click_text", "text": "Clip 1"})).await, None);+}