// AnyBot's browser, the full toolset. botbrowser.rs starts Chrome and keeps profiles; this file // drives a tab through the Chrome DevTools Protocol like a person would (a Firefox tab through // WebDriver BiDi: bidi.rs does each DevTools command the BiDi way, so the tools are the same): // - real mouse and keyboard (Input.dispatchMouseEvent / insertText / dispatchKeyEvent), so // React date pickers, dropdowns and menus that ignore scripted events still respond; // - a numbered list of everything clickable (links with their addresses, buttons, fields, // dropdowns, tabs, calendar cells — anything the page gives a pointer cursor); // - after each action only what changed (new address, new text), not the whole page again; // - tab screenshots (no screen-recording permission needed), tables as Markdown, find on page, // waiting for text, tabs, back/forward/reload, file uploads, downloads, PDF, page dialogs and // running a script on the page. use serde_json::{json, Value}; use std::io::ErrorKind; use std::net::{SocketAddr, TcpStream}; use std::time::{Duration, Instant}; use crate::botbrowser::{self, Kind}; const CALL_TIMEOUT_SECS: u64 = 30; /// Longest element list in one answer. const MAX_ELEMENTS: usize = 250; /// One connection to a tab: DevTools (Chrome-family), or a tab of a Firefox driven over BiDi. pub struct Tab { link: Link, next: u64, } enum Link { Cdp(Box>), Bidi { port: u16, context: String }, } /// The ordinary page tabs of a /json/list answer, most recently used first. pub(crate) fn pages(list: &Value) -> Vec { list.as_array().cloned().unwrap_or_default().into_iter().filter(|t| t["type"] == "page" && !t["url"].as_str().unwrap_or("").starts_with("devtools://")).collect() } /// The browser's port for a profile (starting it if needed), and which protocol it speaks. pub fn port_of(profile: Option<&str>) -> Result<(String, u16, Kind), String> { let prof = botbrowser::resolve(profile)?; let (_, port, _) = botbrowser::ensure(&prof, None)?; Ok((prof.clone(), port, botbrowser::kind_of(Some(&prof)))) } impl Tab { /// The tab this step works on: its job's latest own tab, else the latest one no other job /// has (the list has the most recently used first). pub fn current(profile: Option<&str>) -> Result { let (_, port, kind) = port_of(profile)?; let list = botbrowser::pages_of(kind, port)?; // This job's own latest tab (another bot's job may have one in front). let t = botbrowser::pick_tab(&list).ok_or("AnyBot 瀏覽器沒有開著的分頁,請先用 browser_open 打開網址。")?; botbrowser::claim(t["id"].as_str().unwrap_or("")); if kind == Kind::Firefox { let context = t["id"].as_str().unwrap_or("").to_string(); crate::bidi::touch(port, &context); return Ok(Tab { link: Link::Bidi { port, context }, next: 0 }); } Tab::connect(port, t) } fn connect(port: u16, t: &Value) -> Result { let ws_url = t["webSocketDebuggerUrl"].as_str().ok_or("這個分頁不能控制(可能已被別的工具連著)")?; let addr: SocketAddr = format!("127.0.0.1:{port}").parse().unwrap(); let stream = TcpStream::connect_timeout(&addr, Duration::from_secs(5)).map_err(|e| e.to_string())?; stream.set_read_timeout(Some(Duration::from_secs(CALL_TIMEOUT_SECS))).ok(); let (ws, _) = tungstenite::client::client(ws_url, stream).map_err(|e| format!("連不上 AnyBot 瀏覽器:{e}"))?; Ok(Tab { link: Link::Cdp(Box::new(ws)), next: 0 }) } pub fn is_firefox(&self) -> bool { matches!(self.link, Link::Bidi { .. }) } /// One DevTools command; events that arrive meanwhile are skipped. (On Firefox, done the /// WebDriver BiDi way, with an answer shaped the same.) pub fn call(&mut self, method: &str, params: Value) -> Result { let ws = match &mut self.link { Link::Bidi { port, context } => return crate::bidi::cdp(*port, context, method, ¶ms), Link::Cdp(ws) => ws, }; self.next += 1; let id = self.next; ws.send(tungstenite::Message::Text(json!({"id": id, "method": method, "params": params}).to_string().into())).map_err(|e| e.to_string())?; let start = Instant::now(); loop { if start.elapsed() > Duration::from_secs(CALL_TIMEOUT_SECS) { return Err("瀏覽器太久沒有回應(頁面可能跳出了對話框:可以用 browser_dialog 處理)".into()); } match ws.read() { Ok(tungstenite::Message::Text(t)) => { let v: Value = serde_json::from_str(t.as_str()).unwrap_or(Value::Null); if v["id"] == id { if let Some(e) = v.get("error") { return Err(e["message"].as_str().unwrap_or("瀏覽器拒絕了這個動作").to_string()); } return Ok(v["result"].clone()); } } Ok(_) => {} Err(tungstenite::Error::Io(e)) if e.kind() == ErrorKind::WouldBlock || e.kind() == ErrorKind::TimedOut => return Err("瀏覽器太久沒有回應(頁面可能跳出了對話框:可以用 browser_dialog 處理)".into()), Err(e) => return Err(e.to_string()), } } } /// Run JavaScript and get its value back. pub fn eval(&mut self, expr: &str) -> Result { let r = self.call("Runtime.evaluate", json!({"expression": expr, "returnByValue": true, "awaitPromise": true, "userGesture": true}))?; if let Some(ex) = r.get("exceptionDetails") { return Err(format!("頁面上的程式出錯:{}", ex["exception"]["description"].as_str().or(ex["text"].as_str()).unwrap_or(""))); } Ok(r["result"]["value"].clone()) } fn close(self) { if let Link::Cdp(mut ws) = self.link { let _ = ws.close(None); } } } // ---------- what the page offers ---------- /// Every element matching `sel`, the page's own and those inside open shadow roots (web /// components: Chromium's settings pages, YouTube, many app frameworks), in the order they are /// laid out: a host, then what its shadow root shows, then its own children. Plain /// querySelectorAll stops at every shadow root, so those buttons had no number at all. const DEEP_JS: &str = "const deepAll = (sel, root) => { const out = []; const walk = r => { for (const el of r.querySelectorAll('*')) { if (sel === '*' || el.matches(sel)) out.push(el); if (el.shadowRoot) walk(el.shadowRoot); } }; walk(root || document); return out; };"; /// Numbers everything clickable or fillable (data-anybot-ref) and lists it. const ELEMENTS_JS: &str = r#"(() => { %DEEP% const vis = el => { const r = el.getBoundingClientRect(); if (r.width < 2 || r.height < 2) return false; const s = getComputedStyle(el); return s.visibility !== 'hidden' && s.display !== 'none' && +s.opacity > 0.05; }; const clean = s => (s || '').replace(/\s+/g, ' ').trim(); const name = el => clean(el.getAttribute('aria-label') || el.innerText || el.value || el.getAttribute('placeholder') || el.title || el.getAttribute('alt') || (el.querySelector('img[alt]') || {}).alt || '').slice(0, 80); const label = el => { const a = el.getAttribute('aria-label'); if (a) return clean(a).slice(0, 60); if (el.labels && el.labels[0]) return clean(el.labels[0].innerText).slice(0, 60); const id = el.getAttribute('aria-labelledby'); if (id) { const home = el.getRootNode(); const l = (home.getElementById ? home : document).getElementById(id); if (l) return clean(l.innerText).slice(0, 60); } return clean(el.getAttribute('placeholder') || el.name || el.title || ''); }; const base = 'a[href],button,input:not([type=hidden]),select,textarea,summary,[contenteditable=""],[contenteditable=true],[role=button],[role=link],[role=tab],[role=menuitem],[role=menuitemcheckbox],[role=option],[role=checkbox],[role=radio],[role=combobox],[role=switch],[role=treeitem],[role=gridcell],[onclick],[tabindex]:not([tabindex="-1"])'; const all = deepAll('*'); const order = new Map(all.map((el, i) => [el, i])); const set = new Set(all.filter(el => el.matches(base))); // Anything the page shows a pointer cursor for (calendar days, cards, custom buttons…). for (const el of all) { if (set.size > 4000) break; if (!el.matches('div,span,li,td,th,p,img,svg,i,label')) continue; if (getComputedStyle(el).cursor === 'pointer' && !(el.parentElement && getComputedStyle(el.parentElement).cursor === 'pointer')) set.add(el); } // Numbers stay with their control from one read to the next (a [17] read a minute ago is still // the same reply box); new controls get the next numbers; ones not listed now lose theirs. const prev = new Map(); for (const e of all) if (e.hasAttribute('data-anybot-ref')) prev.set(e, +e.getAttribute('data-anybot-ref')); let next = Math.max(window.__anybotRefNext || 1, 1); for (const v of prev.values()) if (v + 1 > next) next = v + 1; const used = new Set(); const listed = new Set(); const inView = el => { const r = el.getBoundingClientRect(); return r.bottom > 0 && r.top < innerHeight && r.right > 0 && r.left < innerWidth; }; const ordered = [...set].filter(el => vis(el) && !el.closest('[aria-hidden=true]')).sort((a, b) => order.get(a) - order.get(b)); const out = []; const seen = new Set(); let n = 0; for (const el of ordered) { const tag = el.tagName.toLowerCase(); const role = el.getAttribute('role') || ''; let kind, text = name(el), extra = ''; if (tag === 'a') { kind = '連結'; extra = el.href ? '→ ' + el.href : ''; } else if (tag === 'select') { kind = '下拉選單'; text = label(el); extra = [...el.options].map(o => (o.selected ? '✓' : '') + clean(o.text)).slice(0, 20).join(' / '); } else if (tag === 'input' || tag === 'textarea') { const t = (el.type || 'text').toLowerCase(); if (t === 'checkbox' || t === 'radio') { kind = t === 'checkbox' ? '勾選框' : '選項'; text = label(el) || text; extra = el.checked ? '已勾' : '未勾'; } else if (t === 'submit' || t === 'button' || t === 'reset') kind = '按鈕'; else if (t === 'file') { kind = '上傳檔案'; text = label(el) || '選擇檔案'; } else { kind = '輸入框'; text = label(el); const ac = (el.autocomplete || '').toLowerCase(); const nm = [el.name, el.id, el.placeholder, text].join(' '); const digits = (el.value || '').replace(/\D/g, ''); const secret = t === 'password' || el.hasAttribute('data-anybot-vault-secret') || ac === 'cc-number' || ac === 'cc-csc' || (digits.length >= 13 && digits.length <= 19) || (/cvc|cvv|csc|security.?code|安全碼/i.test(nm) && digits.length >= 3 && digits.length <= 4); extra = secret ? (el.value ? '(已填)' : (t === 'password' ? '(密碼)' : '')) : (el.value ? '目前:' + clean(el.value).slice(0, 40) : ''); if (el.readOnly) extra += '(唯讀,點它會打開選擇器)'; } } else if (el.isContentEditable) { kind = '輸入框'; text = label(el) || clean(el.innerText).slice(0, 40); } else if (tag === 'button' || role === 'button' || tag === 'summary') kind = '按鈕'; else if (role === 'tab') { kind = '分頁標籤'; if (el.getAttribute('aria-selected') === 'true') extra = '(目前)'; } else if (role === 'menuitem' || role === 'menuitemcheckbox' || role === 'option' || role === 'treeitem') { kind = '選單項目'; if (el.getAttribute('aria-selected') === 'true' || el.getAttribute('aria-checked') === 'true') extra = '(已選)'; } else if (role === 'combobox') { kind = '下拉選單'; extra = clean(el.innerText).slice(0, 40); } else if (role === 'link') kind = '連結'; else if (role === 'checkbox' || role === 'switch' || role === 'radio') { kind = '勾選框'; extra = el.getAttribute('aria-checked') === 'true' ? '已勾' : '未勾'; } else if (role === 'gridcell' || tag === 'td') { kind = '格子'; const full = el.getAttribute('title') || el.getAttribute('aria-label') || el.getAttribute('data-date') || (el.closest('[title]') || {}).title || ''; if (full && full !== text) text = text ? text + '(' + full + ')' : full; } else { kind = '可點的項目'; const cell = el.closest('td[title],[role=gridcell][aria-label],[data-date]'); if (cell) { kind = '格子'; const full = cell.getAttribute('title') || cell.getAttribute('aria-label') || cell.getAttribute('data-date'); if (full && full !== text) text = text ? text + '(' + full + ')' : full; } } if (!text && !extra) continue; if (el.disabled || el.getAttribute('aria-disabled') === 'true') extra += '(停用)'; const key = kind + '|' + text + '|' + extra; if (seen.has(key)) continue; seen.add(key); n += 1; let num = prev.get(el); if (!num || used.has(num)) num = next++; used.add(num); listed.add(el); el.setAttribute('data-anybot-ref', String(num)); out.push('[' + num + '] ' + kind + '「' + text + '」' + (extra ? ' ' + extra : '') + (inView(el) ? '' : ' (要捲動)')); if (n >= %MAX%) break; } for (const e of prev.keys()) if (!listed.has(e)) e.removeAttribute('data-anybot-ref'); window.__anybotRefNext = next; return JSON.stringify({t: document.title, u: location.href, list: out, more: ordered.length > n}); })()"#; /// The numbered list of what can be clicked or filled. pub fn elements(tab: &mut Tab) -> Result<(String, String, Vec, bool), String> { let v = tab.eval(&ELEMENTS_JS.replace("%DEEP%", DEEP_JS).replace("%MAX%", &MAX_ELEMENTS.to_string()))?; let p: Value = v.as_str().and_then(|s| serde_json::from_str(s).ok()).unwrap_or(Value::Null); let list = p["list"].as_array().map(|a| a.iter().filter_map(|x| x.as_str().map(String::from)).collect()).unwrap_or_default(); Ok((p["t"].as_str().unwrap_or("").into(), p["u"].as_str().unwrap_or("").into(), list, p["more"].as_bool().unwrap_or(false))) } /// Draws a numbered box over every listed element that is on screen (removed after the shot). const MARKS_JS: &str = r#"(() => { %DEEP% const old = document.getElementById('__anybot_marks'); if (old) old.remove(); const box = document.createElement('div'); box.id = '__anybot_marks'; box.style.cssText = 'position:fixed;inset:0;pointer-events:none;z-index:2147483647'; const colors = ['#e11d48', '#2563eb', '#16a34a', '#d97706', '#9333ea']; for (const el of deepAll('[data-anybot-ref]')) { const r = el.getBoundingClientRect(); if (r.bottom < 0 || r.top > innerHeight || r.right < 0 || r.left > innerWidth || r.width < 2) continue; const n = el.getAttribute('data-anybot-ref'); const c = colors[n % colors.length]; const f = document.createElement('div'); f.style.cssText = `position:fixed;left:${r.left}px;top:${r.top}px;width:${r.width}px;height:${r.height}px;border:1.5px solid ${c};border-radius:3px;box-sizing:border-box`; const tag = document.createElement('div'); tag.textContent = n; tag.style.cssText = `position:fixed;left:${Math.max(0, r.left - 1)}px;top:${Math.max(0, r.top - 15)}px;background:${c};color:#fff;font:bold 11px/14px -apple-system,Arial;padding:0 3px;border-radius:3px`; box.appendChild(f); box.appendChild(tag); } for (const el of deepAll('[data-anybot-vault-secret],input[type=password],input[autocomplete="cc-number"],input[autocomplete="cc-csc"]')) { const r = el.getBoundingClientRect(); if (r.bottom < 0 || r.top > innerHeight || r.right < 0 || r.left > innerWidth || r.width < 2) continue; const m = document.createElement('div'); m.style.cssText = `position:fixed;left:${r.left}px;top:${r.top}px;width:${r.width}px;height:${r.height}px;background:#000;border-radius:3px`; box.appendChild(m); } document.documentElement.appendChild(box); return 1; })()"#; const SNAPSHOT_JS: &str = "JSON.stringify({t: document.title, u: location.href, x: document.body ? document.body.innerText : ''})"; fn snapshot(tab: &mut Tab) -> (String, String, Vec) { let v = tab.eval(SNAPSHOT_JS).unwrap_or(Value::Null); let p: Value = v.as_str().and_then(|s| serde_json::from_str(s).ok()).unwrap_or(Value::Null); let lines = p["x"].as_str().unwrap_or("").lines().map(str::trim).filter(|l| !l.is_empty()).map(String::from).collect(); (p["t"].as_str().unwrap_or("").into(), p["u"].as_str().unwrap_or("").into(), lines) } /// The most of a field's text a typing step reports back. const FIELD_SHOWN_CHARS: usize = 400; /// The focused field (through shadow roots), as `el`, for the scripts below. const FOCUSED_JS: &str = "let el = document.activeElement; while (el && el.shadowRoot && el.shadowRoot.activeElement) el = el.shadowRoot.activeElement;"; /// What the focused field holds (an editor's lines too). fn field_text(tab: &mut Tab) -> String { let js = format!("(() => {{ {FOCUSED_JS} if (!el) return ''; return (el.isContentEditable ? el.innerText : (el.value !== undefined ? el.value : '')) || ''; }})()"); tab.eval(&js).ok().and_then(|v| v.as_str().map(String::from)).unwrap_or_default() } /// Put text into the focused field in one go. Lines, or long text in Firefox (whose typing is a /// key at a time), go in like a paste (an editor such as Threads' takes a paste event whole, line /// breaks and all), else by the browser's own insertText — each checked by what the field holds /// after it (Firefox hands an editor a paste event without its text). A post used to take four /// steps for this (a file, the clipboard, a click, ctrl+v). Typed keys only when neither took. fn insert_text(tab: &mut Tab, text: &str) -> Result<(), String> { if text.contains('\n') || (tab.is_firefox() && text.chars().count() > 30) { let t = serde_json::to_string(text).unwrap_or_default(); let before = field_text(tab); let paste = format!("(() => {{ {FOCUSED_JS} if (!el) return false; try {{ const dt = new DataTransfer(); dt.setData('text/plain', {t}); const ev = new ClipboardEvent('paste', {{clipboardData: dt, bubbles: true, cancelable: true, composed: true}}); return !el.dispatchEvent(ev); }} catch (e) {{ return false; }} }})()"); if tab.eval(&paste)?.as_bool() == Some(true) { // (An editor may put the text in a moment later.) settle(150); if field_text(tab) != before { return Ok(()); } } let exec = format!("(() => {{ {FOCUSED_JS} if (!el) return false; return document.execCommand('insertText', false, {t}); }})()"); if tab.eval(&exec)?.as_bool() == Some(true) && field_text(tab) != before { return Ok(()); } } tab.call("Input.insertText", json!({"text": text})).map(|_| ()) } /// How a step that changed nothing on the page is told. const NO_CHANGE: &str = "頁面看起來沒有變化"; /// The text box the cursor is in now (its label, placeholder or first words), or "" when it isn't /// in one. fn focused_field(tab: &mut Tab) -> String { const JS: &str = "(() => { let e = document.activeElement; while (e && e.shadowRoot && e.shadowRoot.activeElement) e = e.shadowRoot.activeElement; if (!e) return ''; const t = (e.type || '').toLowerCase(); const box = e.isContentEditable || e.tagName === 'TEXTAREA' || (e.tagName === 'INPUT' && !['button','submit','checkbox','radio','file','reset','image','hidden'].includes(t)); if (!box) return ''; const c = s => (s || '').replace(/\\s+/g, ' ').trim(); return (c(e.getAttribute('aria-label')) || c(e.getAttribute('placeholder')) || c(e.getAttribute('aria-placeholder')) || c(e.innerText) || '輸入框').slice(0, 40); })()"; tab.eval(JS).ok().and_then(|v| v.as_str().map(String::from)).unwrap_or_default() } /// What an action changed: the address, and the lines of text that are new. fn changes(before: &(String, String, Vec), after: &(String, String, Vec)) -> String { let mut out = vec![]; if before.1 != after.1 { out.push(format!("網址變成:{}", after.1)); } if before.0 != after.0 { out.push(format!("標題:{}", after.0)); } let old: std::collections::HashSet<&String> = before.2.iter().collect(); let new: Vec<&String> = after.2.iter().filter(|l| !old.contains(l)).collect(); let gone = before.2.iter().filter(|l| !after.2.contains(l)).count(); if new.is_empty() && gone == 0 && before.1 == after.1 { out.push(format!("{NO_CHANGE}(可能要等一下、換一個元素,或用 browser_screenshot 看看)。")); } else if !new.is_empty() { let shown: Vec = new.iter().take(40).map(|l| l.chars().take(160).collect()).collect(); out.push(format!("新出現的文字:\n{}{}", shown.join("\n"), if new.len() > 40 { format!("\n…還有 {} 行(用 browser_read 看全部)", new.len() - 40) } else { String::new() })); } out.join("\n") } // ---------- finding an element ---------- /// The element a bot means: its number, else visible text / label / placeholder. /// The way browser_scroll goes: up, top, bottom, or (anything else) down. fn scroll_direction(asked: &str) -> &'static str { match asked.trim().to_lowercase().as_str() { "up" => "up", "top" => "top", "bottom" => "bottom", _ => "down", } } fn find_js(r#ref: &str, text: &str) -> String { let rf = serde_json::to_string(r#ref.trim().trim_matches(['[', ']'])).unwrap_or_default(); let tx = serde_json::to_string(text.trim()).unwrap_or_default(); format!( r#"(() => {{ {deep} const rf = {rf}, tx = {tx}; if (rf) {{ const e = deepAll('[data-anybot-ref="' + rf + '"]')[0]; if (e) return e; }} if (!tx) return null; const t = s => (s || '').replace(/\s+/g, ' ').trim(); const vis = e => {{ const r = e.getBoundingClientRect(); return r.width > 1 && r.height > 1; }}; const all = deepAll('a,button,[role],input,select,textarea,label,summary,li,td,th,span,div,p,img').filter(vis); const hit = e => [t(e.innerText), t(e.getAttribute('aria-label')), t(e.getAttribute('placeholder')), t(e.title), t(e.value), e.labels && e.labels[0] ? t(e.labels[0].innerText) : '']; // The control the words name, not the box around it: 「Customer name:」 is a

holding a // label and its input, 「Submit order」 a

holding the button (its middle is empty page). const ctl = 'a,button,input,select,textarea,summary,[role=button],[role=link],[role=checkbox],[role=radio],[role=switch],[role=tab],[role=menuitem],[role=option],[role=textbox],[role=combobox],[contenteditable=""],[contenteditable=true]'; const isCtl = e => e.matches(ctl); const inner = e => {{ if (isCtl(e)) return e; if (e.tagName === 'LABEL' && e.control && vis(e.control)) return e.control; const c = deepAll(ctl, e).filter(vis); return c.length === 1 ? c[0] : e; }}; const shortest = l => l.slice().sort((a, b) => t(a.innerText).length - t(b.innerText).length)[0]; const pick = l => l.find(isCtl) || l.map(inner).find(isCtl) || shortest(l) || null; const exact = all.filter(e => hit(e).includes(tx)); return exact.length ? pick(exact) : pick(all.filter(e => hit(e).some(h => h.includes(tx)))); }})()"#, deep = DEEP_JS ) } /// Post addresses (a Threads or Instagram post, an X status, a comment's own link): what a reply /// answers, and what a reply is once it is up. const PERMA_JS: &str = r#"const PERMA = /\/(post|posts|status|statuses|p|reel|reels|comments)\/[A-Za-z0-9_.-]+/; const perma = h => { try { const u = new URL(h, location.href); return PERMA.test(u.pathname) ? u.origin + u.pathname.replace(/\/+$/, '') : ''; } catch (e) { return ''; } }; const permasIn = r => [...r.querySelectorAll('a[href]')].map(a => perma(a.getAttribute('href'))).filter(Boolean);"#; /// The page before a step that may send (publish.rs): the box the words go out from (the /// focused one; for a click, the one in the clicked control's dialog or form), what kind of box, /// its words, the post it answers (the page's own, or the one in the reply dialog or article /// around the box) and the words around it, and the post addresses on the page now. const SEND_INFO_JS: &str = r#"(() => { __PERMA__ const MODE = __MODE__; const REF = __EL__; const c = s => (s || '').replace(/\s+/g, ' ').trim(); const active = () => { let e = document.activeElement; while (e && e.shadowRoot && e.shadowRoot.activeElement) e = e.shadowRoot.activeElement; return e; }; const isBox = e => !!e && (e.isContentEditable || e.tagName === 'TEXTAREA' || (e.tagName === 'INPUT' && !['button','submit','checkbox','radio','file','reset','image','hidden','password'].includes((e.type || '').toLowerCase()))); const words = e => !e ? '' : ((e.isContentEditable ? e.innerText : (e.value !== undefined ? String(e.value) : '')) || ''); const around = e => e && e.closest('[role="dialog"],dialog,[aria-modal="true"],form'); let field = null; if (MODE === 'click') { const scope = around(REF); const a = active(); if (isBox(a) && (!scope || scope.contains(a))) field = a; if (!field && scope) field = [...scope.querySelectorAll('textarea,input,[contenteditable]')].find(e => isBox(e) && c(words(e))) || null; if (!field && isBox(a)) field = a; } else { field = REF || active(); if (field && !isBox(field) && field.querySelector) { const inner = field.querySelector('textarea,input,[contenteditable="true"],[contenteditable=""]'); if (isBox(inner)) field = inner; } } if (!isBox(field)) field = null; const hint = field ? (field.getAttribute('placeholder') || '') + ' ' + (field.getAttribute('aria-label') || '') : ''; const kind = !field ? 'none' : (field.isContentEditable || field.tagName === 'TEXTAREA') ? 'editor' : ((field.type || '').toLowerCase() === 'search' || field.getAttribute('role') === 'searchbox' || field.closest('[role="search"]') || /search|搜尋|搜索|查詢/i.test(hint)) ? 'search' : 'input'; let target = perma(location.href), quoted = ''; const box = field && (field.closest('[role="dialog"],dialog,[aria-modal="true"]') || field.closest('article,[role="article"]')); if (box) { const t = permasIn(box)[0]; if (t) target = t; quoted = c(box.innerText).replace(c(words(field)), ' '); } if (!quoted) quoted = c(document.title); return JSON.stringify({url: location.href, kind, text: words(field).slice(0, 4000), target, quoted: c(quoted).slice(0, 400), links: [...new Set(permasIn(document))].slice(0, 400)}); })()"#; /// The page after a send: the words still in a box (it didn't go), the words in the page (the /// deepest element holding them, outside any box), and the reply's own address — a post address /// near the words that wasn't on the page before, else the only one that newly appeared (a /// 「已發佈 · 查看」 notice). const SENT_CHECK_JS: &str = r#"(() => { __PERMA__ const EX = __EX__; const BEFORE = new Set(__LINKS__); const TARGET = __TARGET__; const n = s => (s || '').replace(/\s+/g, ' ').trim(); const boxSel = 'textarea,input,[contenteditable="true"],[contenteditable=""]'; const left = !!EX && [...document.querySelectorAll(boxSel)].some(b => n(b.isContentEditable ? b.innerText : b.value).includes(EX)); const hits = []; if (EX) for (const el of document.body.querySelectorAll('*')) { if (['SCRIPT','STYLE','NOSCRIPT','TEMPLATE'].includes(el.tagName) || el.closest(boxSel)) continue; const t = el.textContent; if (t && t.length < 20000 && n(t).includes(EX)) hits.push(el); } const deep = hits.filter(e => !hits.some(o => o !== e && e.contains(o))); const fresh = h => h && h !== TARGET && !BEFORE.has(h); let link = ''; for (const e of deep) { let p = e; for (let i = 0; i < 12 && p && !link; i++, p = p.parentElement) { const a = permasIn(p).find(fresh); if (a) link = a; } if (link) break; } if (!link) { const all = [...new Set(permasIn(document).filter(fresh))]; if (all.length === 1) link = all[0]; } return JSON.stringify({left, seen: deep.length > 0, link}); })()"#; /// How long the page is watched after a send for the words to leave the box and show (a post /// can sit at 「發佈中…」 with its words still in the box for a few seconds; estimated). const SENT_CHECK_SECS: f64 = 8.0; fn send_info(tab: &mut Tab, mode: &str, r#ref: &str, text: &str) -> Result { let el = if r#ref.trim().is_empty() && text.trim().is_empty() { "null".to_string() } else { find_js(r#ref, text) }; let js = SEND_INFO_JS.replace("__PERMA__", PERMA_JS).replace("__MODE__", &serde_json::to_string(mode).unwrap_or_default()).replace("__EL__", &el); let v = tab.eval(&js)?; v.as_str().and_then(|x| serde_json::from_str(x).ok()).ok_or_else(|| "讀不到這一頁的輸入框".to_string()) } fn sent_check(tab: &mut Tab, excerpt: &str, links: &Value, target: &str) -> Value { let js = SENT_CHECK_JS .replace("__PERMA__", PERMA_JS) .replace("__EX__", &serde_json::to_string(excerpt.split_whitespace().collect::>().join(" ").as_str()).unwrap_or_default()) .replace("__LINKS__", &if links.is_array() { links.to_string() } else { "[]".into() }) .replace("__TARGET__", &serde_json::to_string(target).unwrap_or_default()); let start = Instant::now(); let mut last = json!({"left": false, "seen": false, "link": ""}); loop { if let Some(v) = tab.eval(&js).ok().and_then(|v| v.as_str().and_then(|x| serde_json::from_str::(x).ok())) { last = v; } let gone = last["left"] == false; let shown = last["seen"] == true || last["link"].as_str().is_some_and(|l| !l.is_empty()); let secs = start.elapsed().as_secs_f64(); // Gone from the box and up on the page; gone and, half the time on, still not shown (a // page that doesn't show its own replies — waiting longer finds nothing); or time's up. if (gone && shown) || (gone && secs > SENT_CHECK_SECS / 2.0) || secs > SENT_CHECK_SECS { return last; } settle(500); } } /// Bring the element into view and get its centre (CSS pixels in the viewport). fn locate(tab: &mut Tab, r#ref: &str, text: &str) -> Result<(f64, f64, String), String> { let js = format!( "(() => {{ const el = {}; if (!el) return null; el.scrollIntoView({{block: 'center', inline: 'center'}}); const r = el.getBoundingClientRect(); return JSON.stringify({{x: r.left + r.width / 2, y: r.top + r.height / 2, tag: el.tagName, type: el.type || '', ro: !!el.readOnly}}); }})()", find_js(r#ref, text) ); let v = tab.eval(&js)?; let what = if !r#ref.trim().is_empty() { format!("[{}]", r#ref.trim().trim_matches(['[', ']'])) } else { format!("「{}」", text.trim()) }; let p: Value = v.as_str().and_then(|s| serde_json::from_str(s).ok()).ok_or_else(|| format!("這一頁找不到 {what}(可能已經不在頁面上,或換了一頁)。用 browser_read 或 browser_elements 看最新的清單。"))?; Ok((p["x"].as_f64().unwrap_or(0.0), p["y"].as_f64().unwrap_or(0.0), format!("{what}{}", if p["tag"] == "INPUT" && p["ro"] == true { "(唯讀欄位)" } else { "" }))) } fn mouse(tab: &mut Tab, kind: &str, x: f64, y: f64, button: &str, count: i64) -> Result<(), String> { tab.call("Input.dispatchMouseEvent", json!({"type": kind, "x": x, "y": y, "button": button, "buttons": if kind == "mousePressed" { 1 } else { 0 }, "clickCount": count})).map(|_| ()) } /// A real click (the page can't tell it from a person's). fn click_at(tab: &mut Tab, x: f64, y: f64, button: &str, count: i64) -> Result<(), String> { mouse(tab, "mouseMoved", x, y, "none", 0)?; for n in 1..=count { mouse(tab, "mousePressed", x, y, button, n)?; mouse(tab, "mouseReleased", x, y, button, n)?; } Ok(()) } /// Key names the bot may use → (key, code, keyCode, text). fn key_info(k: &str) -> Option<(&'static str, &'static str, i64, &'static str)> { Some(match k.to_lowercase().as_str() { "enter" | "return" => ("Enter", "Enter", 13, "\r"), "tab" => ("Tab", "Tab", 9, ""), "escape" | "esc" => ("Escape", "Escape", 27, ""), "backspace" => ("Backspace", "Backspace", 8, ""), "delete" => ("Delete", "Delete", 46, ""), "space" => (" ", "Space", 32, " "), "arrowdown" | "down" => ("ArrowDown", "ArrowDown", 40, ""), "arrowup" | "up" => ("ArrowUp", "ArrowUp", 38, ""), "arrowleft" | "left" => ("ArrowLeft", "ArrowLeft", 37, ""), "arrowright" | "right" => ("ArrowRight", "ArrowRight", 39, ""), "pagedown" => ("PageDown", "PageDown", 34, ""), "pageup" => ("PageUp", "PageUp", 33, ""), "home" => ("Home", "Home", 36, ""), "end" => ("End", "End", 35, ""), "a" => ("a", "KeyA", 65, "a"), "c" => ("c", "KeyC", 67, "c"), "v" => ("v", "KeyV", 86, "v"), "x" => ("x", "KeyX", 88, "x"), "f" => ("f", "KeyF", 70, "f"), _ => return None, }) } /// Press a key or combination ("Enter", "ctrl+a", "shift+tab"). fn press(tab: &mut Tab, combo: &str) -> Result<(), String> { let parts: Vec<&str> = combo.split('+').map(str::trim).filter(|s| !s.is_empty()).collect(); let (key, mods) = parts.split_last().ok_or("請給按鍵,例如 Enter")?; let mut m = 0; for x in mods { m |= match x.to_lowercase().as_str() { "alt" | "option" => 1, "ctrl" | "control" => 2, "cmd" | "meta" | "command" => 4, "shift" => 8, other => return Err(format!("不認得的按鍵「{other}」")), }; } let (k, code, kc, text) = key_info(key).ok_or_else(|| format!("不認得的按鍵「{key}」,可以用 Enter、Tab、Escape、Backspace、方向鍵、PageDown、Home、End,或 ctrl+a 這類組合"))?; let text = if m & (1 | 2 | 4) != 0 { "" } else { text }; tab.call("Input.dispatchKeyEvent", json!({"type": if text.is_empty() { "rawKeyDown" } else { "keyDown" }, "key": k, "code": code, "windowsVirtualKeyCode": kc, "modifiers": m, "text": text}))?; tab.call("Input.dispatchKeyEvent", json!({"type": "keyUp", "key": k, "code": code, "windowsVirtualKeyCode": kc, "modifiers": m}))?; Ok(()) } fn settle(ms: u64) { std::thread::sleep(Duration::from_millis(ms)); } /// What the page shows, cheaply: load state, address and how much text. const SIG_JS: &str = "document.readyState+'|'+location.href+'|'+(document.body?document.body.innerText.length:0)"; fn page_sig(tab: &mut Tab) -> String { tab.eval(SIG_JS).ok().and_then(|v| v.as_str().map(String::from)).unwrap_or_default() } /// Wait for an action's effect, not a fixed time: back as soon as the page has changed and holds /// still (loaded, same address and text twice in a row), or when nothing has started to change /// within `quiet_ms`; never longer than `max_ms`. (Fixed sleeps read slow pages too early and /// kept the bot waiting on fast ones.) pub fn settle_after(tab: &mut Tab, before: &str, quiet_ms: u64, max_ms: u64) { let start = Instant::now(); let mut last = String::new(); let mut changed = false; loop { settle(150); let now = page_sig(tab); changed |= now != before; let elapsed = start.elapsed().as_millis() as u64; let still = now.starts_with("complete|") && now == last; if (still && (changed || elapsed >= quiet_ms)) || elapsed >= max_ms { return; } last = now; } } /// Wait until the tab in front has loaded a real page (not the blank tab it starts as) and holds /// still, at most `max_ms`. Says whether it did. Connects afresh each look: a navigation can swap /// the page behind the tab. pub fn wait_loaded(profile: Option<&str>, max_ms: u64) -> bool { let start = Instant::now(); let mut last = String::new(); while (start.elapsed().as_millis() as u64) < max_ms { let now = Tab::current(profile).map(|mut t| { let sig = page_sig(&mut t); t.close(); sig }); let now = now.unwrap_or_default(); if now.starts_with("complete|") && !now.contains("|about:blank|") && now == last { return true; } last = now; settle(200); } false } // ---------- the tools ---------- /// The option a select names: `option`, or what models trained on Playwright give instead /// (`value`, `values`). It used to read only `option`, and with `value` it chose the empty /// 「請選擇」 and said 「已選「」」: the form went out without its city. fn select_option(args: &Value) -> String { let o = s(args, "option"); if !o.is_empty() { return o; } let v = s(args, "value"); if !v.is_empty() { return v; } args["values"].as_array().and_then(|a| a.first()).map(|v| v.as_str().map(String::from).unwrap_or_else(|| v.to_string())).unwrap_or_default().trim().to_string() } fn s(args: &Value, k: &str) -> String { args.get(k).map(|v| v.as_str().map(String::from).unwrap_or_else(|| if v.is_null() { String::new() } else { v.to_string() })).unwrap_or_default().trim().to_string() } pub const NAMES: [&str; 21] = [ "browser_elements", "browser_click", "browser_hover", "browser_type", "browser_press", "browser_select", "browser_scroll", "browser_wait", "browser_find", "browser_table", "browser_screenshot", "browser_tabs", "browser_back", "browser_upload", "browser_download", "browser_pdf", "browser_dialog", "browser_eval", // 發布關卡 (publish.rs): the system's own looks before and after a send, never offered to // the model (action_tool has no action for them). SEND_INFO, SENT_CHECK, SENT_LOG, ]; /// What each account already sent (the brain's own book, publish.rs; action `sent`). pub const SENT_LOG: &str = "browser_sent_log"; /// The page just before a step that may send: the box and its words, what it answers. pub const SEND_INFO: &str = "browser_send_info"; /// The page just after: the words still in the box, seen on the page, the reply's address. pub const SENT_CHECK: &str = "browser_sent_check"; pub fn is_tool(name: &str) -> bool { NAMES.contains(&name) } pub fn label(name: &str) -> &'static str { match name { "browser_elements" => "列出網頁上的按鈕", "browser_click" => "在瀏覽器點擊", "browser_hover" => "在瀏覽器停在上面", "browser_type" => "在瀏覽器輸入", "browser_press" => "在瀏覽器按鍵", "browser_select" => "在瀏覽器選擇", "browser_scroll" => "捲動瀏覽器", "browser_wait" => "等網頁載入", "browser_find" => "在網頁上找字", "browser_table" => "讀網頁表格", "browser_screenshot" => "瀏覽器截圖", "browser_tabs" => "瀏覽器分頁", "browser_back" => "瀏覽器上一頁", "browser_upload" => "上傳檔案到網頁", "browser_download" => "從網頁下載", "browser_pdf" => "把網頁存成 PDF", "browser_dialog" => "處理網頁對話框", "browser_eval" => "在網頁執行程式", SENT_LOG => "查已送出的紀錄", _ => "瀏覽器", } } pub fn describe(name: &str, args: &str) -> String { let v: Value = serde_json::from_str(args).unwrap_or(Value::Null); let target = if !s(&v, "ref").is_empty() { format!("[{}]", s(&v, "ref")) } else { s(&v, "text") }; match name { "browser_type" => format!("{target} ← {}", s(&v, "value").chars().take(40).collect::()), "browser_select" => format!("{target} → {}", select_option(&v)), "browser_press" => s(&v, "key"), "browser_scroll" => if target.is_empty() { s(&v, "direction") } else { target }, "browser_wait" => if s(&v, "text").is_empty() { format!("{} 秒", s(&v, "seconds")) } else { format!("等「{}」", s(&v, "text")) }, "browser_find" => format!("「{}」", s(&v, "text")), "browser_tabs" => format!("{} {}", s(&v, "action"), s(&v, "index")), "browser_back" => s(&v, "direction"), "browser_upload" => s(&v, "path"), "browser_eval" => s(&v, "script").chars().take(60).collect(), _ => target, } } /// The one browser tool's name (H2: every browser action rides on it, like `computer`). pub const TOOL: &str = "browser"; /// action -> the internal per-action tool it runs as. The internal names stay everywhere /// downstream (approvals, oplog, the work log, remote limbs): the model only ever sees `browser`. pub fn action_tool(action: &str) -> Option<&'static str> { Some(match action { "open" => "browser_open", "read" => "browser_read", "profiles" => "browser_profiles", "elements" => "browser_elements", "find" => "browser_find", "table" => "browser_table", "screenshot" => "browser_screenshot", "click" => "browser_click", "hover" => "browser_hover", "type" => "browser_type", "press" => "browser_press", "select" => "browser_select", "scroll" => "browser_scroll", "wait" => "browser_wait", "tabs" => "browser_tabs", "back" => "browser_back", "upload" => "browser_upload", "download" => "browser_download", "pdf" => "browser_pdf", "dialog" => "browser_dialog", "eval" => "browser_eval", "fill" => "browser_fill_login", // the kind picks login/card/contact; see expand_call "sent" => SENT_LOG, _ => return None, }) } /// The one browser tool. One schema, trained-prior shapes (open/read/click/type…); the old /// eighteen schemas' guidance lives in the action list below. pub fn tool(profile: &Value) -> Value { json!({ "name": TOOL, "description": "Drive AnyBot's browser: one tool, picked by action. For anything on a web page use this, never screen coordinates. Start with open (it answers like read) or read, then act by the numbers (ref) or visible text the last result showed. Never act on a page from memory — use the numbers the latest result showed. actions: - open {url}: open a link in a new tab and report the page (title, address, text, numbered controls) - read {max_chars}: read the current tab the same way (numbers for click/type/select) - elements: just the numbered clickable/fillable controls (cheaper than read) - find {text}: like Cmd-F: every place the text appears with words around it - table {index, all, max_rows}: read the page's tables as Markdown (reports, product lists) - screenshot {full, marks}: the page as a picture with numbered boxes on every control; needs no screen permission - click {ref|text, double, button}: real mouse click (menus, date pickers, dropdowns, calendar days); buying/paying/sending/deleting needs the person's OK first - hover {ref|text}: move over a control (opens hover menus) and report what appeared - type {ref|text, value, append, submit}: puts the text into a field (clears first unless append); line breaks in value go in whole, like a paste — no clipboard or ctrl+v needed. The result says what the field holds now: check it before sending. Never type passwords here: use fill - press {key}: Enter, Tab, Escape, ctrl+a, … (optionally on ref/text first) - select {ref|text, option}: choose a dropdown option (custom dropdowns included) - scroll {direction: down|up|top|bottom} (on ref/text brings it into view; loads endless lists) - wait {text | seconds, after_send}: until text appears (≤20 s) or a few seconds; with after_send: true, until `seconds` (up to 900) have passed since you last sent something — to space posts, open and type the next one first, then wait, then send - tabs {action: list|switch|new|close, index, url}: the tab strip - back {direction: back|forward|reload} - upload {ref|text, path}: put a file from this computer into a file chooser - download {ref|text}: click a download/export button, save to Downloads/AnyBot, return the path - pdf: save the page as a PDF in Downloads/AnyBot - dialog {accept, text}: answer a pop-up dialog the page opened - eval {script}: short read-only JavaScript for data the other actions can't reach; it can't send requests, navigate or submit (site APIs get accounts flagged) - sent {profile, days}: what an account already sent through this browser — AnyBot's own record (which posts, which accounts it answered, kept 60 days); much cheaper than reading a site's own replies page to the end. Sending to a post the same account already answered is refused anyway - fill {kind: login|card|contact, id, site, submit}: sign in / pay card / address from the person's 保險庫 (not for ordinary fields: those are type/select) — you never see the secret; the person approves every use (login_id/card_id/contact_id come from vault_list; default login: the current site's)", "parameters": {"type": "object", "properties": { "action": {"type": "string", "enum": ["open","read","elements","find","table","screenshot","click","hover","type","press","select","scroll","wait","tabs","back","upload","download","pdf","dialog","eval","sent","profiles","fill"]}, "url": {"type": "string"}, "max_chars": {"type": "integer", "description": "read: longest text to return (default 20000)"}, "text": {"type": "string", "description": "find/wait: the text; click/type/…: the control's visible text"}, "ref": {"type": "string", "description": "The element's number from the latest read/elements/screenshot result"}, "index": {"type": "integer", "description": "table: which table; tabs: which tab"}, "all": {"type": "boolean", "description": "table: every table"}, "max_rows": {"type": "integer"}, "full": {"type": "boolean", "description": "screenshot: the whole page"}, "marks": {"type": "boolean", "description": "screenshot: false for no number boxes"}, "double": {"type": "boolean", "description": "click: double-click"}, "button": {"type": "string", "enum": ["left", "right", "middle"]}, "value": {"type": "string", "description": "type: the text"}, "append": {"type": "boolean", "description": "type: keep what's in the field"}, "submit": {"type": "boolean", "description": "type/fill: press Enter / sign in afterwards"}, "key": {"type": "string", "description": "press: Enter, Tab, Escape, ctrl+a…"}, "option": {"type": "string", "description": "select: the option's visible text (value works too)"}, "direction": {"type": "string", "enum": ["down", "up", "top", "bottom", "back", "forward", "reload"], "description": "scroll: down/up/top/bottom; back: back/forward/reload"}, "seconds": {"type": "number"}, "days": {"type": "integer", "description": "sent: how far back (default 30, up to 60)"}, "after_send": {"type": "boolean", "description": "wait: count `seconds` from the last thing you sent (spacing posts)"}, "path": {"type": "string", "description": "upload: a file on this computer"}, "accept": {"type": "boolean", "description": "dialog"}, "script": {"type": "string", "description": "eval: read-only JavaScript"}, "kind": {"type": "string", "enum": ["login", "card", "contact"], "description": "fill: what to fill"}, "id": {"type": "string", "description": "fill: the vault item's id from vault_list"}, "site": {"type": "string", "description": "fill login: domain (default: the current tab's)"}, "name": {"type": "string", "description": "profiles: name for add/use"}, "profile": profile }, "required": ["action"]} }) } /// The `fill` action names only the kinds the vault can fill (`kinds`); with none, the browser /// tool has no `fill` at all — no action, no line in its description, no fill-only fields. pub fn limit_fill(specs: &mut [Value], kinds: &[&str]) { for t in specs.iter_mut().filter(|t| t["name"] == TOOL) { if kinds.is_empty() { let d = t["description"].as_str().unwrap_or("").lines().filter(|l| !l.starts_with("- fill ")).collect::>().join("\n"); t["description"] = json!(d); let p = &mut t["parameters"]["properties"]; if let Some(a) = p["action"]["enum"].as_array_mut() { a.retain(|x| x != "fill"); } if let Some(o) = p.as_object_mut() { for k in ["kind", "id", "site"] { o.remove(k); } } if let Some(s) = p["submit"]["description"].as_str().map(|s| s.replace("type/fill", "type")) { p["submit"]["description"] = json!(s); } } else { t["parameters"]["properties"]["kind"]["enum"] = json!(kinds); } } } /// Expand one `browser` call into the internal per-action tool at the model-output boundary, /// so every guard downstream (approvals incl. the vault's, oplog, replay, the remote link, the /// work log) keeps its stable per-action name. pub fn expand_call(c: &mut crate::model::ToolCall) { if c.name != TOOL { return; } let mut v = crate::tools::args_of(&c.args); let Some(action) = v["action"].as_str().and_then(action_tool) else { return }; let mut name = action.to_string(); if let Some(o) = v.as_object_mut() { o.remove("action"); // 「fill」 with a control on the page and the words for it is Playwright's fill (type // into a field), what models trained on it mean more often than the 保險庫: it went to // the vault, was refused, and the bot tried again and again (the form never went out). let on_page = (o.contains_key("ref") || o.contains_key("text")) && !["kind", "id", "site"].iter().any(|k| o.contains_key(*k)); if name == "browser_fill_login" && on_page { name = if o.contains_key("option") || o.contains_key("values") { "browser_select" } else { "browser_type" }.to_string(); } if name == "browser_fill_login" { // fill {kind, id} names the exact vault tool and its id field. let kind = o.remove("kind").and_then(|k| k.as_str().map(|s| s.to_string())).unwrap_or_else(|| "login".into()); let id = o.remove("id"); name = match kind.as_str() { "card" => { if let Some(id) = id { o.insert("card_id".to_string(), id); } "browser_fill_card" } "contact" => { if let Some(id) = id { o.insert("contact_id".to_string(), id); } "browser_fill_contact" } _ => { if let Some(id) = id { o.insert("login_id".to_string(), id); } "browser_fill_login" } } .to_string(); } } c.name = name; c.args = v.to_string(); } fn downloads_dir() -> std::path::PathBuf { let d = dirs::download_dir().unwrap_or_else(std::env::temp_dir).join("AnyBot"); let _ = std::fs::create_dir_all(&d); d } /// Run one browser tool. Returns (text for the bot, a JPEG as base64 when it took a picture). pub fn run(name: &str, args: &Value) -> Result<(String, Option), String> { let profile = Some(s(args, "profile")).filter(|p| !p.is_empty()); let profile = profile.as_deref(); let (rf, text) = (s(args, "ref"), s(args, "text")); match name { "browser_tabs" => return tabs(args, profile).map(|t| (t, None)), "browser_wait" if s(args, "text").is_empty() => { let secs = args["seconds"].as_f64().unwrap_or(2.0).clamp(0.2, 30.0); settle((secs * 1000.0) as u64); return Ok((format!("已等 {secs} 秒。"), None)); } _ => {} } let mut tab = Tab::current(profile)?; let r = (|| -> Result<(String, Option), String> { // Typing into a dropdown (a "#; let _ = write!(c, "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()); } }); let url = format!("http://127.0.0.1:{port}/"); let r = { botbrowser::as_job("lines", || -> Result<(), String> { botbrowser::open(&url, None)?; let refs = || -> Result { run("browser_elements", &json!({})).map(|r| r.0) }; let num = |list: &str, name: &str| -> String { list.lines().find(|l| l.contains(name)).and_then(|l| l.split(']').next()).map(|s| s.trim_start_matches('[').to_string()).unwrap_or_default() }; let first = refs()?; let ed = num(&first, "「回覆」"); assert!(!ed.is_empty(), "{first}"); let (clicked, _) = run("browser_click", &json!({"ref": ed}))?; assert!(clicked.contains("游標已在「回覆」裡"), "{clicked}"); let (typed, _) = run("browser_type", &json!({"ref": ed, "value": "第一行\n第二行\nhttps://s.shopee.tw/x"}))?; assert!(typed.contains("第一行 ⏎ 第二行 ⏎ https://s.shopee.tw/x"), "{typed}"); // The page grows: the box keeps its number. run("browser_click", &json!({"text": "加一個"}))?; let second = refs()?; assert_eq!(num(&second, "「回覆」"), ed, "{first}\n---\n{second}"); let ta = num(&second, "「備註」"); let (typed, _) = run("browser_type", &json!({"ref": ta, "value": "甲\n乙"}))?; assert!(typed.contains("甲 ⏎ 乙"), "{typed}"); Ok(()) }) }; let _ = botbrowser::quit(None); r.unwrap(); } /// 發布關卡, live, on a page shaped like Threads: the reply dialog says which post it answers; /// after ctrl+Enter the words are on the page with their own new address; Enter in the search /// box is a search; words left in the box were not sent. Run like the one above (… --ignored /// a_send_is_seen). #[test] #[ignore] fn a_send_is_seen_with_the_post_it_answers_and_its_own_address() { use std::io::{Read, Write}; let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); let port = l.local_addr().unwrap().port(); std::thread::spawn(move || { for mut c in l.incoming().flatten() { let mut buf = [0u8; 2048]; let _ = c.read(&mut buf); let body = r#"Threads 測試

"#; let _ = write!(c, "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()); } }); let url = format!("http://127.0.0.1:{port}/"); let r = { botbrowser::as_job("send", || -> Result<(), String> { botbrowser::open(&url, None)?; let info = |mode: &str, rf: &str, value: &str| -> Result { run(SEND_INFO, &json!({"mode": mode, "ref": rf, "value": value})).map(|r| serde_json::from_str(&r.0).unwrap()) }; let check = |before: &Value, text: &str| -> Result { run(SENT_CHECK, &json!({"excerpt": crate::publish::excerpt(text), "links": before["links"], "target": before["target"]})).map(|r| serde_json::from_str(&r.0).unwrap()) }; // Reply to the second post: the dialog names it (its address without the query). let list = run("browser_elements", &json!({}))?.0; let second = list.lines().find(|l| l.contains("「回覆 b」")).and_then(|l| l.split(']').next()).map(|s| s.trim_start_matches('[').to_string()).ok_or(list.clone())?; run("browser_click", &json!({"ref": second}))?; let words = "推薦這款,我家用兩年了\nhttps://s.shopee.tw/x"; run("browser_type", &json!({"text": "回覆", "value": words}))?; let before = info("key", "", "")?; assert_eq!(before["kind"], "editor", "{before}"); assert_eq!(before["target"], format!("http://127.0.0.1:{port}/@b/post/X2"), "{before}"); assert!(before["text"].as_str().unwrap().contains("推薦這款"), "{before}"); assert!(before["quoted"].as_str().unwrap().contains("推薦貓抓板嗎"), "{before}"); run("browser_press", &json!({"key": "ctrl+Return"}))?; let after = check(&before, words)?; assert_eq!(after["left"], false, "{after}"); assert_eq!(after["seen"], true, "{after}"); assert_eq!(after["link"], format!("http://127.0.0.1:{port}/@me/post/Y1"), "{after}"); // Words typed but not sent: still in the box. run("browser_click", &json!({"text": "回覆 b"}))?; run("browser_type", &json!({"text": "回覆", "value": "還沒想好要說什麼"}))?; let before = info("key", "", "")?; run("browser_press", &json!({"key": "Tab"}))?; let after = check(&before, "還沒想好要說什麼")?; assert_eq!((after["left"].clone(), after["link"].clone()), (json!(true), json!("")), "{after}"); // The search box: a search, not a post. let list = run("browser_elements", &json!({}))?.0; let q = list.lines().find(|l| l.contains("搜尋")).and_then(|l| l.split(']').next()).map(|s| s.trim_start_matches('[').to_string()).ok_or(list.clone())?; let s = info("type", &q, "貓抓板")?; assert_eq!((s["kind"].clone(), s["text"].clone()), (json!("search"), json!("貓抓板")), "{s}"); Ok(()) }) }; let _ = botbrowser::quit(None); r.unwrap(); } #[test] fn a_finished_job_closes_its_browser_unless_another_job_is_on_it() { let tabs = |ids: &[&str]| ids.iter().map(|i| json!({"id": i})).collect::>(); let mine = vec!["a".to_string(), "b".to_string()]; let nobody = |_: &str| false; // Its own tabs and the person's / leftovers: the whole browser goes. assert_eq!(tidy_plan("job1", true, &tabs(&["a", "b", "x"]), &mine, nobody), Tidy::Quit); // Another bot is working in it: only this job's tabs, every one of them. let busy = |id: &str| id == "z"; assert_eq!(tidy_plan("job1", true, &tabs(&["z", "a", "b"]), &mine, busy), Tidy::Tabs(vec!["a".into(), "b".into()])); // Switched off: as before, the job's tabs but the page it ended on. assert_eq!(tidy_plan("job1", false, &tabs(&["a", "b", "x"]), &mine, nobody), Tidy::Tabs(vec!["b".into()])); // An older brain that doesn't name the job: all but the front page. assert_eq!(tidy_plan("", true, &tabs(&["a", "b", "x"]), &[], nobody), Tidy::Tabs(vec!["b".into(), "x".into()])); } #[test] fn nothing_to_fill_means_no_fill_action() { let fills = |t: &Value| t["parameters"]["properties"]["action"]["enum"].as_array().unwrap().iter().any(|a| a == "fill"); // An empty vault: the action, its line and its fields are gone; the rest stays. let mut specs = vec![tool(&json!({"type": "string"})), json!({"name": "web_fetch"})]; limit_fill(&mut specs, &[]); let t = &specs[0]; assert!(!fills(t)); let d = t["description"].as_str().unwrap(); assert!(!d.contains("- fill ") && d.contains("- type {ref|text, value"), "{d}"); assert!(t["parameters"]["properties"]["kind"].is_null() && t["parameters"]["properties"]["id"].is_null()); assert!(!t["parameters"]["properties"]["submit"]["description"].as_str().unwrap().contains("fill")); assert_eq!(specs[1], json!({"name": "web_fetch"})); // Contacts only: fill stays, naming that kind alone. let mut specs = vec![tool(&json!({"type": "string"}))]; limit_fill(&mut specs, &["contact"]); assert!(fills(&specs[0])); assert_eq!(specs[0]["parameters"]["properties"]["kind"]["enum"], json!(["contact"])); } use super::*; #[test] fn keys_and_changes() { assert_eq!(key_info("Enter").unwrap().0, "Enter"); assert!(key_info("F13").is_none()); let a = ("t".to_string(), "u1".to_string(), vec!["a".to_string(), "b".to_string()]); let b = ("t".to_string(), "u2".to_string(), vec!["a".to_string(), "c".to_string()]); let c = changes(&a, &b); assert!(c.contains("網址變成:u2") && c.contains("新出現的文字:\nc")); assert!(changes(&a, &a).contains("沒有變化")); } #[test] fn the_front_page_tab_is_used() { let list = json!([ {"type": "service_worker", "url": "https://x", "webSocketDebuggerUrl": "ws://a"}, {"type": "page", "url": "devtools://devtools", "webSocketDebuggerUrl": "ws://b"}, {"type": "page", "url": "https://www.threads.net/", "title": "Threads", "webSocketDebuggerUrl": "ws://c"}, {"type": "page", "url": "https://example.com/", "webSocketDebuggerUrl": "ws://d"} ]); let p = pages(&list); assert_eq!(p.len(), 2); assert_eq!(p[0]["webSocketDebuggerUrl"], "ws://c"); } /// Controls inside web components (open shadow roots, two levels deep) get numbers and can be /// clicked and typed into, like Chromium's settings pages and many app frameworks. Headless: /// `ANYBOT_DATA_DIR= ANYBOT_BROWSER_ENGINE=firefox ANYBOT_FIREFOX_HEADLESS=1 cargo test /// numbers_controls_inside_web_components -- --ignored --nocapture` (or Chrome, with a window). #[test] #[ignore] fn numbers_controls_inside_web_components() { use std::io::{Read, Write}; let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); let port = l.local_addr().unwrap().port(); std::thread::spawn(move || { for mut c in l.incoming().flatten() { let mut buf = [0u8; 4096]; let _ = c.read(&mut buf); let body = r#"元件

設定

還沒按

"#; let _ = write!(c, "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len()); let _ = c.write_all(body.as_bytes()); } }); crate::botbrowser::add("shadow-test").unwrap(); let p = |v: Value| { let mut v = v; v["profile"] = json!("shadow-test"); v }; let go = || -> Result<(), String> { crate::botbrowser::open(&format!("http://127.0.0.1:{port}/"), Some("shadow-test"))?; let (els, _) = run("browser_elements", &p(json!({})))?; println!("{els}"); for want in ["「名稱」", "「開始」", "「自動更新」"] { assert!(els.contains(want), "{want} missing: {els}"); } let n = els.lines().find(|l| l.contains("「開始」")).and_then(|l| l.trim_start().strip_prefix('[')).and_then(|r| r.split(']').next()).unwrap().to_string(); run("browser_type", &p(json!({"text": "名稱", "value": "小明"})))?; let (r, _) = run("browser_click", &p(json!({"ref": n})))?; assert!(r.contains("按了開始:小明"), "{r}"); let (r, _) = run("browser_click", &p(json!({"text": "自動更新"})))?; assert!(r.contains("自動更新:開"), "{r}"); Ok(()) }; let r = go(); let _ = crate::botbrowser::remove("shadow-test"); r.unwrap(); } /// A dashboard like Shopee's affiliate pages: a React-style date picker that only reacts to /// real clicks, a custom dropdown, a table, a hover menu, an export. Run with ANYBOT_DATA_DIR /// set to a scratch folder; opens a browser window for a moment. #[test] #[ignore] fn drives_a_dashboard() { use std::io::{Read, Write}; let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); let port = l.local_addr().unwrap().port(); std::thread::spawn(move || { for mut c in l.incoming().flatten() { let mut buf = [0u8; 4096]; let n = c.read(&mut buf).unwrap_or(0); let req = String::from_utf8_lossy(&buf[..n]).to_string(); let (ctype, body): (&str, Vec) = if req.starts_with("GET /export") { ("text/csv\r\nContent-Disposition: attachment; filename=\"report.csv\"", "商品,佣金\nA,10\n".as_bytes().to_vec()) } else { ("text/html; charset=utf-8", r#"成效
2026-11-03
預設
商品分潤率
手機殼8%
乳液12%

點擊 0

匯出報表 "#.as_bytes().to_vec()) }; let _ = write!(c, "HTTP/1.1 200 OK\r\nContent-Type: {ctype}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len()); let _ = c.write_all(&body); } }); crate::botbrowser::add("drive-test").unwrap(); let p = |v: Value| { let mut v = v; v["profile"] = json!("drive-test"); v }; let go = || -> Result<(), String> { crate::botbrowser::open(&format!("http://127.0.0.1:{port}/"), Some("drive-test"))?; let (els, _) = run("browser_elements", &p(json!({})))?; assert!(els.contains("「數據周期」"), "{els}"); run("browser_hover", &p(json!({"text": "商品分析"})))?; let (shown, _) = run("browser_eval", &p(json!({"script": "getComputedStyle(document.getElementById('sub')).display"})))?; assert_eq!(shown.trim(), "block"); // Real click opens the picker; a calendar day (only a pointer cursor) is listed and clickable. let (r, _) = run("browser_click", &p(json!({"text": "數據周期"})))?; assert!(r.contains("近30天"), "{r}"); let (r, _) = run("browser_click", &p(json!({"text": "近30天"})))?; assert!(r.contains("點擊 60,訂單 3"), "{r}"); let (r, _) = run("browser_select", &p(json!({"text": "排序", "option": "佣金由高到低"})))?; assert!(r.contains("佣金由高到低"), "{r}"); // A plain