fix: Linux 操作恢復順暢——保險箱空的不給填入工具、同一個錯誤不再鬼打牆;Wayland 可一律允許、長網頁有編號、Enter 只看游標那格;做完就關掉瀏覽器
一台 Linux(Ubuntu 26.04、X11)上一輪 Threads 海巡 40 分鐘只送出 1 則:小模型一直誤叫保險箱填入(171 次),而 4b53ad4 之後回的是「沒有開著的分頁,請先 browser_open」,Bot 照做又再誤叫。
- 保險箱:只給有東西可填的種類(空的就沒有 vault 工具、browser 也沒有 fill);填入先查 id 在不在,錯誤講對、指向 type;規劃與填入都在這個任務自己的分頁上(本機、box、遠端手腳)
- 同一個工具連續 3 次回一樣的錯誤(換參數也一樣):這一回合不再執行
- Wayland(GNOME/KDE,wlroots 的座標點擊)認不出 App 時,改給「操作這台電腦的螢幕」一律允許(一律允許清單裡可移除)
- 元素樹走訪上限 4000 → 20000:長網頁捲下去,看得到的部分也有編號
- 敏感動作關卡:Enter/送出只看游標所在(或正在打字)的欄位;座標點擊只看點到的最內層控制項;英文整字比對(PayPal 不是 pay);步驟在別台電腦時不查大腦本機的編號
- 打字先點欄位再檢查最前面是不是 AnyBot;批次從 AnyBot 切到要操作的 App 不再中斷,切到第三個 App 或回到 AnyBot 才停
- 估算對話長度只算真的會送出的最新 3 張截圖
- 做完就關掉瀏覽器(設定 › 電腦 › AnyBot 瀏覽器設定檔,預設開):一輪結束關掉用過的 Firefox/Chrome,別的 Bot 還在用就只關自己的分頁;box 的 Chromium 不變
Mac 444、Linux 448 個測試通過;Firefox 收尾實機測試(Mac、Linux Snap 版)通過;已在那台 Linux 上部署驗證。
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
674d3878d6
commit
69080f9117
190
src/agent.rs
190
src/agent.rs
|
|
@ -51,6 +51,8 @@ pub struct Job {
|
||||||
pub roles: tools::Roles,
|
pub roles: tools::Roles,
|
||||||
/// 在這台電腦上執行 is on.
|
/// 在這台電腦上執行 is on.
|
||||||
pub local_execution: bool,
|
pub local_execution: bool,
|
||||||
|
/// 做完就關掉瀏覽器: the browsers this turn used are closed when it ends (see browser::tidy).
|
||||||
|
pub close_browsers: bool,
|
||||||
/// This bot's computer tools are on (when off, using them asks the person first).
|
/// This bot's computer tools are on (when off, using them asks the person first).
|
||||||
pub tools_enabled: bool,
|
pub tools_enabled: bool,
|
||||||
/// 直接操作 mode; the window can switch it on mid-turn ("全部允許").
|
/// 直接操作 mode; the window can switch it on mid-turn ("全部允許").
|
||||||
|
|
@ -342,6 +344,8 @@ enum BotBrowser {
|
||||||
struct UsedBrowsers {
|
struct UsedBrowsers {
|
||||||
list: Vec<BotBrowser>,
|
list: Vec<BotBrowser>,
|
||||||
via_name: String,
|
via_name: String,
|
||||||
|
/// Close each browser when done (not only the tabs).
|
||||||
|
close: bool,
|
||||||
/// This job's name in the browsers (its tabs are kept apart by it).
|
/// This job's name in the browsers (its tabs are kept apart by it).
|
||||||
job: String,
|
job: String,
|
||||||
}
|
}
|
||||||
|
|
@ -360,9 +364,9 @@ fn with_job(args: &str, job: &str) -> String {
|
||||||
}
|
}
|
||||||
|
|
||||||
impl UsedBrowsers {
|
impl UsedBrowsers {
|
||||||
fn new(via_name: &str, bot_id: u64) -> Self {
|
fn new(via_name: &str, bot_id: u64, close: bool) -> Self {
|
||||||
let n = JOB_SEQ.fetch_add(1, Ordering::Relaxed);
|
let n = JOB_SEQ.fetch_add(1, Ordering::Relaxed);
|
||||||
UsedBrowsers { list: vec![], via_name: via_name.to_string(), job: format!("{bot_id}-{}-{n}", crate::model::now_ms()) }
|
UsedBrowsers { list: vec![], via_name: via_name.to_string(), close, job: format!("{bot_id}-{}-{n}", crate::model::now_ms()) }
|
||||||
}
|
}
|
||||||
|
|
||||||
fn add(&mut self, b: BotBrowser) {
|
fn add(&mut self, b: BotBrowser) {
|
||||||
|
|
@ -373,7 +377,14 @@ impl UsedBrowsers {
|
||||||
|
|
||||||
fn close_tabs(&mut self) {
|
fn close_tabs(&mut self) {
|
||||||
for b in std::mem::take(&mut self.list) {
|
for b in std::mem::take(&mut self.list) {
|
||||||
let args = |p: &str| with_job(&if p.is_empty() { r#"{"action":"tidy"}"#.to_string() } else { serde_json::json!({"action": "tidy", "profile": p}).to_string() }, &self.job);
|
let close = self.close;
|
||||||
|
let args = |p: &str| {
|
||||||
|
let mut a = serde_json::json!({"action": "tidy", "close": close});
|
||||||
|
if !p.is_empty() {
|
||||||
|
a["profile"] = serde_json::json!(p);
|
||||||
|
}
|
||||||
|
with_job(&a.to_string(), &self.job)
|
||||||
|
};
|
||||||
let never = AtomicBool::new(false);
|
let never = AtomicBool::new(false);
|
||||||
match &b {
|
match &b {
|
||||||
BotBrowser::Here(p) => {
|
BotBrowser::Here(p) => {
|
||||||
|
|
@ -665,6 +676,42 @@ fn refresh_own(job: &mut Job, bot_id: u64) -> Option<String> {
|
||||||
/// How many times in a row this very call (same tool, same arguments) already came back with the
|
/// How many times in a row this very call (same tool, same arguments) already came back with the
|
||||||
/// very same answer among the latest steps. Waiting tools are left out: there the same answer is
|
/// very same answer among the latest steps. Waiting tools are left out: there the same answer is
|
||||||
/// the point. So is what the person answers: the same question may well get the same answer.
|
/// the point. So is what the person answers: the same question may well get the same answer.
|
||||||
|
/// 「一律允許」 for this computer's whole screen: what is offered when the desktop can't say
|
||||||
|
/// which app a step lands in (GNOME / KDE on Wayland never can; wlroots can't for a point).
|
||||||
|
const SCREEN_CONTROL_GRANT: &str = "computer:control";
|
||||||
|
|
||||||
|
/// What a screen step on this computer asks: (the grant 「一律允許」 keeps, the question). Per app
|
||||||
|
/// when the desktop names it; for the screen as a whole when it can't — the question then says
|
||||||
|
/// so. (An empty grant there used to make every click, key and scroll ask with no 「一律允許」.)
|
||||||
|
fn screen_control_ask(app: Option<&str>, via: &str, what: &str) -> (String, String) {
|
||||||
|
match app.map(str::trim).filter(|a| !a.is_empty()) {
|
||||||
|
Some(a) => (format!("app:{a}"), format!("讓 {via} 看到「{a}」,並在其中點擊和輸入:{what}")),
|
||||||
|
None => (SCREEN_CONTROL_GRANT.to_string(), format!("讓 {via} 在這台電腦的螢幕上點擊和輸入:{what}\n(這個桌面看不出是哪個 App;一律允許後,這台電腦的螢幕操作不再逐步詢問,付款、刪除、送出這類動作仍會問。)")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Failures in a row of one tool, all saying the same, after which it isn't run this turn.
|
||||||
|
const SAME_FAILURES_STOP: usize = 3;
|
||||||
|
|
||||||
|
/// How many of `name`'s latest results this turn are failures with the same words, in a row
|
||||||
|
/// (its other arguments aside; a success or other words end the count).
|
||||||
|
fn same_failures(runs: &[(String, bool, String)], name: &str) -> usize {
|
||||||
|
if matches!(name, "read_terminal" | "write_terminal" | "browser_wait") {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
let mine = runs.iter().rev().filter(|r| r.0 == name);
|
||||||
|
let mut first: Option<&str> = None;
|
||||||
|
let mut n = 0;
|
||||||
|
for (_, failed, text) in mine {
|
||||||
|
if !*failed || first.is_some_and(|f| f != text) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
first = Some(text);
|
||||||
|
n += 1;
|
||||||
|
}
|
||||||
|
n
|
||||||
|
}
|
||||||
|
|
||||||
fn same_answers(history: &[Message], name: &str, args: &str) -> usize {
|
fn same_answers(history: &[Message], name: &str, args: &str) -> usize {
|
||||||
if matches!(name, "read_terminal" | "browser_wait" | "write_terminal") || name == crate::ask::TOOL || name == tools::HANDOFF_TOOL {
|
if matches!(name, "read_terminal" | "browser_wait" | "write_terminal") || name == crate::ask::TOOL || name == tools::HANDOFF_TOOL {
|
||||||
return 0;
|
return 0;
|
||||||
|
|
@ -791,7 +838,17 @@ pub fn estimate_tokens(s: &str) -> u64 {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn history_tokens(system: &str, h: &[Message]) -> u64 {
|
fn history_tokens(system: &str, h: &[Message]) -> u64 {
|
||||||
estimate_tokens(system) + h.iter().map(|m| estimate_tokens(&m.text) + m.tool_calls.iter().map(|c| estimate_tokens(&c.args)).sum::<u64>() + m.images.iter().map(|p| image_tokens(p)).sum::<u64>() + 4).sum::<u64>()
|
// Pictures as they are sent: a step's screenshot only while it is one of the newest
|
||||||
|
// KEEP_SCREENSHOTS (older ones go as a note, see providers::kept_images); counting every one
|
||||||
|
// of a fifty-step task made compaction come early and shrink results the bot still needed.
|
||||||
|
let kept = providers::kept_images(h);
|
||||||
|
let pictures = |i: usize, m: &Message| -> u64 {
|
||||||
|
if m.role == Role::Tool && !kept.contains(&i) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
m.images.iter().map(|p| image_tokens(p)).sum()
|
||||||
|
};
|
||||||
|
estimate_tokens(system) + h.iter().enumerate().map(|(i, m)| estimate_tokens(&m.text) + m.tool_calls.iter().map(|c| estimate_tokens(&c.args)).sum::<u64>() + pictures(i, m) + 4).sum::<u64>()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// What a picture costs the model that receives it. Vision providers price by pixels (a
|
/// What a picture costs the model that receives it. Vision providers price by pixels (a
|
||||||
|
|
@ -1144,6 +1201,9 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc<
|
||||||
let mut tools_on = job.tools_enabled;
|
let mut tools_on = job.tools_enabled;
|
||||||
// The screen and browser steps of this turn (to stop the same step being tried over and over).
|
// The screen and browser steps of this turn (to stop the same step being tried over and over).
|
||||||
let mut tried: Vec<String> = Vec::new();
|
let mut tried: Vec<String> = Vec::new();
|
||||||
|
// Every step's (tool, failed, what it said) this turn: a tool that keeps failing the same
|
||||||
|
// way, whatever it is given, is stopped (see same_failures).
|
||||||
|
let runs: std::cell::RefCell<Vec<(String, bool, String)>> = Default::default();
|
||||||
let mut local_on = job.local_execution;
|
let mut local_on = job.local_execution;
|
||||||
// 「允許一次」at a computer's own gates (電腦工具、在這台電腦上) holds for the rest of
|
// 「允許一次」at a computer's own gates (電腦工具、在這台電腦上) holds for the rest of
|
||||||
// this turn: a task that takes eight steps on the person's computer asks once, not eight
|
// this turn: a task that takes eight steps on the person's computer asks once, not eight
|
||||||
|
|
@ -1151,7 +1211,7 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc<
|
||||||
// (send, delete, pay) still ask every time.
|
// (send, delete, pay) still ask every time.
|
||||||
let mut tools_once = false;
|
let mut tools_once = false;
|
||||||
let mut local_once = false;
|
let mut local_once = false;
|
||||||
let mut browsers = UsedBrowsers::new(&job.via_name, bot_id);
|
let mut browsers = UsedBrowsers::new(&job.via_name, bot_id, job.close_browsers);
|
||||||
// 電腦現況: what someone at each computer already knows (system, sudo, network, apps…).
|
// 電腦現況: what someone at each computer already knows (system, sudo, network, apps…).
|
||||||
// Added ONCE here, before the step loop: the turn's system prefix (instructions + facts)
|
// Added ONCE here, before the step loop: the turn's system prefix (instructions + facts)
|
||||||
// and its tool list (and the deterministic `quick_tools` map of it) never change between
|
// and its tool list (and the deterministic `quick_tools` map of it) never change between
|
||||||
|
|
@ -1400,6 +1460,19 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc<
|
||||||
repeat_note = "⚠️ 同一步你已經做了 2 次,結果都一模一樣。如果這次還一樣,就換一個做法。\n".into();
|
repeat_note = "⚠️ 同一步你已經做了 2 次,結果都一模一樣。如果這次還一樣,就換一個做法。\n".into();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// 換參數也一樣: the same tool failing with the same words however it is called (171
|
||||||
|
// vault fills with made-up ids, each told "open a tab first"): after three, not run.
|
||||||
|
let fails = same_failures(&runs.borrow(), &call.name);
|
||||||
|
if fails >= SAME_FAILURES_STOP {
|
||||||
|
let last = runs.borrow().iter().rev().find(|r| r.0 == call.name).map(|r| r.2.clone()).unwrap_or_default();
|
||||||
|
let text = format!("沒有執行:{} 已經連續 {fails} 次回一樣的錯誤(換參數也一樣),再叫它也不會成功。這一回合不要再用它:換一個工具做,或告訴使用者卡在哪裡。它上一次說:{last}", call.name);
|
||||||
|
trouble.set(true);
|
||||||
|
send(StreamEvent::ToolStatus(call.id.clone(), ToolStatus::Failed));
|
||||||
|
let result = Message::tool_result(&call.id, &call.name, &text);
|
||||||
|
send(StreamEvent::ToolResult(result.clone()));
|
||||||
|
history.push(result);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
// 拒絕後停下: refused once already, and the person hasn't written since.
|
// 拒絕後停下: refused once already, and the person hasn't written since.
|
||||||
let refused_key = format!("{}\n{}", call.name, canonical_args(&call.args));
|
let refused_key = format!("{}\n{}", call.name, canonical_args(&call.args));
|
||||||
said_no.set(false);
|
said_no.set(false);
|
||||||
|
|
@ -1421,6 +1494,7 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc<
|
||||||
if matches!(status, ToolStatus::Failed | ToolStatus::Denied) || !repeat_note.is_empty() || output.contains(crate::computer::NOOP_TAG) {
|
if matches!(status, ToolStatus::Failed | ToolStatus::Denied) || !repeat_note.is_empty() || output.contains(crate::computer::NOOP_TAG) {
|
||||||
trouble.set(true);
|
trouble.set(true);
|
||||||
}
|
}
|
||||||
|
runs.borrow_mut().push((call.name.clone(), status == ToolStatus::Failed, output.chars().take(400).collect()));
|
||||||
job.note(crate::oplog::Record::ToolFinished { op: job.op.clone(), call_id: call.id.clone(), status: format!("{status:?}").to_lowercase(), at: crate::model::now_ms() });
|
job.note(crate::oplog::Record::ToolFinished { op: job.op.clone(), call_id: call.id.clone(), status: format!("{status:?}").to_lowercase(), at: crate::model::now_ms() });
|
||||||
send(StreamEvent::ToolStatus(call.id.clone(), status));
|
send(StreamEvent::ToolStatus(call.id.clone(), status));
|
||||||
let body = noted(&moved, &call.id, output);
|
let body = noted(&moved, &call.id, output);
|
||||||
|
|
@ -2072,6 +2146,12 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc<
|
||||||
Card((String, crate::vault_store::Item)),
|
Card((String, crate::vault_store::Item)),
|
||||||
Contact((String, crate::vault_store::Item)),
|
Contact((String, crate::vault_store::Item)),
|
||||||
}
|
}
|
||||||
|
// An item the vault doesn't have: said before any browser is touched (the
|
||||||
|
// answer used to be "no open tab, browser_open first", and the bot went round).
|
||||||
|
if let Err(e) = crate::vault::check_ids(&call.name, &call.args) {
|
||||||
|
finish(&mut history, &e, ToolStatus::Failed, None);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
// The fill lands in the same browser browser_* uses: the chosen computer's,
|
// The fill lands in the same browser browser_* uses: the chosen computer's,
|
||||||
// the cloud box's, or this one's. The vault store and the person's approval
|
// the cloud box's, or this one's. The vault store and the person's approval
|
||||||
// stay on this computer; a chosen computer spends one entry's secret per call.
|
// stay on this computer; a chosen computer spends one entry's secret per call.
|
||||||
|
|
@ -2084,6 +2164,7 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc<
|
||||||
};
|
};
|
||||||
let v0 = tools::args_of(&call.args);
|
let v0 = tools::args_of(&call.args);
|
||||||
let profile = v0["profile"].as_str().unwrap_or("").to_string();
|
let profile = v0["profile"].as_str().unwrap_or("").to_string();
|
||||||
|
let tag = browsers.job.clone();
|
||||||
let plan_here = || -> Result<(Plan, String, String), String> {
|
let plan_here = || -> Result<(Plan, String, String), String> {
|
||||||
if call.name == crate::vault::TOOL {
|
if call.name == crate::vault::TOOL {
|
||||||
crate::vault::plan_login(&call.args).map(|pl| {
|
crate::vault::plan_login(&call.args).map(|pl| {
|
||||||
|
|
@ -2107,7 +2188,7 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc<
|
||||||
// On a chosen computer the page lives over the relay: read its url there,
|
// On a chosen computer the page lives over the relay: read its url there,
|
||||||
// plan with this computer's vault, fill there only after the person allows.
|
// plan with this computer's vault, fill there only after the person allows.
|
||||||
let planned: Result<(Plan, String, String), String> = match &place {
|
let planned: Result<(Plan, String, String), String> = match &place {
|
||||||
BrowserAt::Device(h) => match crate::remote::run_on_device(h, crate::vault::REMOTE_TOOL, &serde_json::json!({"kind": "host", "profile": profile}).to_string(), &job.via_name)
|
BrowserAt::Device(h) => match crate::remote::run_on_device(h, crate::vault::REMOTE_TOOL, &with_job(&serde_json::json!({"kind": "host", "profile": profile}).to_string(), &tag), &job.via_name)
|
||||||
.and_then(|r| if r["ok"].as_bool().unwrap_or(false) { Ok(r) } else { Err(r["text"].as_str().unwrap_or("那台電腦的瀏覽器無法使用").to_string()) })
|
.and_then(|r| if r["ok"].as_bool().unwrap_or(false) { Ok(r) } else { Err(r["text"].as_str().unwrap_or("那台電腦的瀏覽器無法使用").to_string()) })
|
||||||
{
|
{
|
||||||
Ok(t) => {
|
Ok(t) => {
|
||||||
|
|
@ -2134,8 +2215,10 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc<
|
||||||
}
|
}
|
||||||
Err(e) => Err(e),
|
Err(e) => Err(e),
|
||||||
}
|
}
|
||||||
BrowserAt::Box => crate::botbrowser::in_box(plan_here),
|
// (On this job's own tab, like its other browser steps: planned outside
|
||||||
BrowserAt::Here => plan_here(),
|
// it, every tab looked like another job's — "no open tab".)
|
||||||
|
BrowserAt::Box => crate::botbrowser::as_job(&tag, || crate::botbrowser::in_box(plan_here)),
|
||||||
|
BrowserAt::Here => crate::botbrowser::as_job(&tag, plan_here),
|
||||||
};
|
};
|
||||||
let (output, status) = match planned {
|
let (output, status) = match planned {
|
||||||
Err(e) => (e, ToolStatus::Failed),
|
Err(e) => (e, ToolStatus::Failed),
|
||||||
|
|
@ -2161,19 +2244,23 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc<
|
||||||
} else {
|
} else {
|
||||||
started();
|
started();
|
||||||
let submit = tools::args_of(&call.args)["submit"].as_bool().unwrap_or(false);
|
let submit = tools::args_of(&call.args)["submit"].as_bool().unwrap_or(false);
|
||||||
|
let fill_here = || match &plan {
|
||||||
|
Plan::Login(pl) => crate::vault::fill_login_with(pl, submit, remember_site),
|
||||||
|
Plan::Card((host, _)) => crate::vault::fill_card_on(&call.args, Some(host)),
|
||||||
|
Plan::Contact((host, _)) => crate::vault::fill_contact_on(&call.args, Some(host)),
|
||||||
|
};
|
||||||
let r = match (&plan, &place) {
|
let r = match (&plan, &place) {
|
||||||
(Plan::Login(pl), BrowserAt::Device(h)) => remote_vault_login(h, &job, pl, submit, remember_site),
|
(Plan::Login(pl), BrowserAt::Device(h)) => remote_vault_login(h, &job, &tag, pl, submit, remember_site),
|
||||||
(Plan::Login(pl), _) => crate::vault::fill_login_with(pl, submit, remember_site),
|
|
||||||
(Plan::Card((host, c)), BrowserAt::Device(h)) => {
|
(Plan::Card((host, c)), BrowserAt::Device(h)) => {
|
||||||
let a = serde_json::json!({"kind": "form", "values": crate::vault::card_values(c), "site": host, "profile": profile, "https": true}).to_string();
|
let a = serde_json::json!({"kind": "form", "values": crate::vault::card_values(c), "site": host, "profile": profile, "https": true}).to_string();
|
||||||
remote_vault_page(h, &job, &a).and_then(|page| crate::vault::card_fill_text(c, &page))
|
remote_vault_page(h, &job, &with_job(&a, &tag)).and_then(|page| crate::vault::card_fill_text(c, &page))
|
||||||
}
|
}
|
||||||
(Plan::Card((host, _)), _) => crate::vault::fill_card_on(&call.args, Some(host)),
|
|
||||||
(Plan::Contact((host, c)), BrowserAt::Device(h)) => {
|
(Plan::Contact((host, c)), BrowserAt::Device(h)) => {
|
||||||
let a = serde_json::json!({"kind": "form", "values": crate::vault::contact_values(c), "site": host, "profile": profile}).to_string();
|
let a = serde_json::json!({"kind": "form", "values": crate::vault::contact_values(c), "site": host, "profile": profile}).to_string();
|
||||||
remote_vault_page(h, &job, &a).and_then(|page| crate::vault::contact_fill_text(c, &page))
|
remote_vault_page(h, &job, &with_job(&a, &tag)).and_then(|page| crate::vault::contact_fill_text(c, &page))
|
||||||
}
|
}
|
||||||
(Plan::Contact((host, _)), _) => crate::vault::fill_contact_on(&call.args, Some(host)),
|
(_, BrowserAt::Box) => crate::botbrowser::as_job(&tag, || crate::botbrowser::in_box(fill_here)),
|
||||||
|
(_, BrowserAt::Here) => crate::botbrowser::as_job(&tag, fill_here),
|
||||||
};
|
};
|
||||||
match r {
|
match r {
|
||||||
Ok(t) => (t, ToolStatus::Done),
|
Ok(t) => (t, ToolStatus::Done),
|
||||||
|
|
@ -2373,16 +2460,11 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc<
|
||||||
if detected.as_deref().is_some_and(|a| computer::is_self_app(a, None)) {
|
if detected.as_deref().is_some_and(|a| computer::is_self_app(a, None)) {
|
||||||
Decision::Deny("Bot 不能點擊或操作 AnyBot 自己的視窗或核准按鈕。".into())
|
Decision::Deny("Bot 不能點擊或操作 AnyBot 自己的視窗或核准按鈕。".into())
|
||||||
} else {
|
} else {
|
||||||
let app = detected.clone().unwrap_or_else(|| "目前的 App".into());
|
let (grant, reason) = screen_control_ask(detected.as_deref(), &job.via_name, &what);
|
||||||
// Never offer a permanent `app:目前的 App` grant when the window system (e.g. Wayland Portal) can't identify the app.
|
if grants.iter().any(|g| g == SCREEN_CONTROL_GRANT || *g == grant) {
|
||||||
let grant = match detected {
|
|
||||||
Some(a) => format!("app:{a}"),
|
|
||||||
None => String::new(),
|
|
||||||
};
|
|
||||||
if grants.iter().any(|g| g == "computer:control" || (!grant.is_empty() && *g == grant)) {
|
|
||||||
Decision::Allow
|
Decision::Allow
|
||||||
} else {
|
} else {
|
||||||
Decision::Ask { reason: format!("讓 {} 看到「{app}」,並在其中點擊和輸入:{what}", job.via_name), grant }
|
Decision::Ask { reason, grant }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -2455,8 +2537,13 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc<
|
||||||
// time, on every computer (local, remote device, or box), in direct mode too.
|
// time, on every computer (local, remote device, or box), in direct mode too.
|
||||||
// Harness policy: the model (and anything it read on a page) cannot grant its way past this one.
|
// Harness policy: the model (and anything it read on a page) cannot grant its way past this one.
|
||||||
let parsed_args = tools::args_of(&call.args);
|
let parsed_args = tools::args_of(&call.args);
|
||||||
|
// (This computer's latest look is only about steps on this computer: for the box or
|
||||||
|
// another computer its numbers name other controls — the chat's latest look does.)
|
||||||
|
let here = !on_box && on_device.is_none();
|
||||||
let sensitive_click = matches!(call.name.as_str(), "computer_use_click" | "computer_use_batch" | "computer_use_menu_click" | "computer_use_typing" | "computer_use_press_key")
|
let sensitive_click = matches!(call.name.as_str(), "computer_use_click" | "computer_use_batch" | "computer_use_menu_click" | "computer_use_typing" | "computer_use_press_key")
|
||||||
&& computer::sensitive_target(&call.name, &parsed_args)
|
&& here
|
||||||
|
.then(|| computer::sensitive_target(&call.name, &parsed_args))
|
||||||
|
.flatten()
|
||||||
.or_else(|| sensitive_in_history(&call.name, &parsed_args, &history))
|
.or_else(|| sensitive_in_history(&call.name, &parsed_args, &history))
|
||||||
.is_some_and(|l| computer::sensitive_words(&l));
|
.is_some_and(|l| computer::sensitive_words(&l));
|
||||||
let decision = if sensitive_click && gate.is_ok() && target.is_ok() && !matches!(decision, Decision::Deny(_)) {
|
let decision = if sensitive_click && gate.is_ok() && target.is_ok() && !matches!(decision, Decision::Deny(_)) {
|
||||||
|
|
@ -2615,9 +2702,9 @@ fn remote_vault_page(host: &str, job: &Job, args: &str) -> Result<serde_json::Va
|
||||||
|
|
||||||
/// A vault login on the computer that has the browser: the secret from this computer's vault,
|
/// A vault login on the computer that has the browser: the secret from this computer's vault,
|
||||||
/// the fill there, the wording here (the vault store and the new-site memory stay here).
|
/// the fill there, the wording here (the vault store and the new-site memory stay here).
|
||||||
fn remote_vault_login(host: &str, job: &Job, pl: &crate::vault::LoginPlan, submit: bool, remember_site: bool) -> Result<String, String> {
|
fn remote_vault_login(host: &str, job: &Job, tag: &str, pl: &crate::vault::LoginPlan, submit: bool, remember_site: bool) -> Result<String, String> {
|
||||||
let (u, p, source) = crate::vault::login_secret_of(pl)?;
|
let (u, p, source) = crate::vault::login_secret_of(pl)?;
|
||||||
let args = serde_json::json!({"kind": "login", "username": u, "password": p, "site": pl.host, "profile": pl.profile, "submit": submit}).to_string();
|
let args = with_job(&serde_json::json!({"kind": "login", "username": u, "password": p, "site": pl.host, "profile": pl.profile, "submit": submit}).to_string(), tag);
|
||||||
remote_vault_page(host, job, &args).and_then(|page| crate::vault::login_fill_text(pl, &u, &source, submit, &page, remember_site))
|
remote_vault_page(host, job, &args).and_then(|page| crate::vault::login_fill_text(pl, &u, &source, submit, &page, remember_site))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -2705,6 +2792,7 @@ mod tests {
|
||||||
default_computer: String::new(),
|
default_computer: String::new(),
|
||||||
roles: tools::Roles::default(),
|
roles: tools::Roles::default(),
|
||||||
local_execution: false,
|
local_execution: false,
|
||||||
|
close_browsers: true,
|
||||||
grants: vec![],
|
grants: vec![],
|
||||||
context_tokens: DEFAULT_CONTEXT_TOKENS,
|
context_tokens: DEFAULT_CONTEXT_TOKENS,
|
||||||
via: String::new(),
|
via: String::new(),
|
||||||
|
|
@ -3803,7 +3891,7 @@ echo '<meta charset=utf-8><title>done</title>送出了' > done.html; (setsid pyt
|
||||||
assert_eq!((v["_job"].as_str(), v["url"].as_str(), v["profile"].as_str()), (Some("6-1-1"), Some("https://example.com"), Some("工作")));
|
assert_eq!((v["_job"].as_str(), v["url"].as_str(), v["profile"].as_str()), (Some("6-1-1"), Some("https://example.com"), Some("工作")));
|
||||||
assert_eq!(serde_json::from_str::<serde_json::Value>(&with_job("", "j")).unwrap()["_job"], "j");
|
assert_eq!(serde_json::from_str::<serde_json::Value>(&with_job("", "j")).unwrap()["_job"], "j");
|
||||||
// Two jobs never share a name.
|
// Two jobs never share a name.
|
||||||
assert_ne!(UsedBrowsers::new("b", 6).job, UsedBrowsers::new("b", 6).job);
|
assert_ne!(UsedBrowsers::new("b", 6, true).job, UsedBrowsers::new("b", 6, true).job);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|
@ -3936,6 +4024,52 @@ echo '<meta charset=utf-8><title>done</title>送出了' > done.html; (setsid pyt
|
||||||
assert!(image_tokens(&pic) <= 3200 && image_tokens("QUJD") >= 800);
|
assert!(image_tokens(&pic) <= 3200 && image_tokens("QUJD") >= 800);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Old screenshots of a long screen task are not sent (only the newest few are), so they
|
||||||
|
/// don't take room either; the newest ones and the person's pictures do.
|
||||||
|
#[test]
|
||||||
|
fn only_the_screenshots_that_are_sent_take_room() {
|
||||||
|
let pic = "A".repeat(1_500_000);
|
||||||
|
let shot = |i: usize| Message { images: vec![pic.clone()], ..Message::tool_result(&format!("c{i}"), "computer_use_screenshot", "螢幕截圖") };
|
||||||
|
let few: Vec<Message> = (0..crate::computer::KEEP_SCREENSHOTS).map(shot).collect();
|
||||||
|
let many: Vec<Message> = (0..40).map(shot).collect();
|
||||||
|
let text_only = |h: &[Message]| history_tokens("", &h.iter().map(|m| Message { images: vec![], ..m.clone() }).collect::<Vec<_>>());
|
||||||
|
// Forty screenshots cost what the newest three do, plus their words.
|
||||||
|
assert_eq!(history_tokens("", &many) - text_only(&many), history_tokens("", &few) - text_only(&few));
|
||||||
|
// A picture the person attached always counts.
|
||||||
|
let mut h = many.clone();
|
||||||
|
h.insert(0, Message { images: vec![pic.clone()], ..Message::user("看這個") });
|
||||||
|
assert!(history_tokens("", &h) - history_tokens("", &many) > 800);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_tool_that_keeps_failing_the_same_way_is_stopped() {
|
||||||
|
let run = |n: &str, failed: bool, t: &str| (n.to_string(), failed, t.to_string());
|
||||||
|
// Made-up ids, the same answer each time: counted whatever the arguments were.
|
||||||
|
let runs = vec![run("browser_open", false, "已打開"), run("browser_fill_contact", true, "沒有存任何聯絡資訊"), run("browser_fill_contact", true, "沒有存任何聯絡資訊"), run("browser_fill_contact", true, "沒有存任何聯絡資訊")];
|
||||||
|
assert_eq!(same_failures(&runs, "browser_fill_contact"), SAME_FAILURES_STOP);
|
||||||
|
assert_eq!(same_failures(&runs, "browser_open"), 0);
|
||||||
|
// Other words, or a success in between, start the count again.
|
||||||
|
let runs = vec![run("browser_click", true, "找不到 A"), run("browser_click", true, "找不到 B"), run("browser_click", true, "找不到 B")];
|
||||||
|
assert_eq!(same_failures(&runs, "browser_click"), 2);
|
||||||
|
let runs = vec![run("shell", true, "x"), run("shell", false, "ok"), run("shell", true, "x")];
|
||||||
|
assert_eq!(same_failures(&runs, "shell"), 1);
|
||||||
|
// Waiting is not failing.
|
||||||
|
assert_eq!(same_failures(&[run("browser_wait", true, "x"), run("browser_wait", true, "x"), run("browser_wait", true, "x")], "browser_wait"), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_desktop_that_cannot_name_the_app_still_offers_always() {
|
||||||
|
// GNOME / KDE on Wayland: no app name, so the grant is the screen's (it used to be none,
|
||||||
|
// and every click asked with no 「一律允許」).
|
||||||
|
let (grant, q) = screen_control_ask(None, "小幫手", "點一下 (400, 300)");
|
||||||
|
assert_eq!(grant, SCREEN_CONTROL_GRANT);
|
||||||
|
assert!(q.contains("看不出是哪個 App") && q.contains("付款"), "{q}");
|
||||||
|
let (grant, q) = screen_control_ask(Some("firefox"), "小幫手", "點一下");
|
||||||
|
assert_eq!(grant, "app:firefox");
|
||||||
|
assert!(q.contains("「firefox」"));
|
||||||
|
assert_eq!(screen_control_ask(Some(" "), "小幫手", "x").0, SCREEN_CONTROL_GRANT);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn tokens_count_chinese_heavier() {
|
fn tokens_count_chinese_heavier() {
|
||||||
assert_eq!(estimate_tokens("abcdefgh"), 2);
|
assert_eq!(estimate_tokens("abcdefgh"), 2);
|
||||||
|
|
@ -3987,6 +4121,7 @@ echo '<meta charset=utf-8><title>done</title>送出了' > done.html; (setsid pyt
|
||||||
default_computer: crate::model::THIS_COMPUTER_NAME.into(),
|
default_computer: crate::model::THIS_COMPUTER_NAME.into(),
|
||||||
roles: tools::Roles { own: crate::model::BOT_COMPUTER_NAME.into(), person: Some(crate::model::THIS_COMPUTER_NAME.into()), server: false },
|
roles: tools::Roles { own: crate::model::BOT_COMPUTER_NAME.into(), person: Some(crate::model::THIS_COMPUTER_NAME.into()), server: false },
|
||||||
local_execution: true,
|
local_execution: true,
|
||||||
|
close_browsers: true,
|
||||||
grants: vec![],
|
grants: vec![],
|
||||||
context_tokens: DEFAULT_CONTEXT_TOKENS,
|
context_tokens: DEFAULT_CONTEXT_TOKENS,
|
||||||
via: "test".into(),
|
via: "test".into(),
|
||||||
|
|
@ -4069,6 +4204,7 @@ echo '<meta charset=utf-8><title>done</title>送出了' > done.html; (setsid pyt
|
||||||
default_computer: crate::model::BOT_COMPUTER_NAME.into(),
|
default_computer: crate::model::BOT_COMPUTER_NAME.into(),
|
||||||
roles: tools::Roles { own: crate::model::BOT_COMPUTER_NAME.into(), person: Some(crate::model::THIS_COMPUTER_NAME.into()), server: false },
|
roles: tools::Roles { own: crate::model::BOT_COMPUTER_NAME.into(), person: Some(crate::model::THIS_COMPUTER_NAME.into()), server: false },
|
||||||
local_execution: false,
|
local_execution: false,
|
||||||
|
close_browsers: true,
|
||||||
grants: vec![],
|
grants: vec![],
|
||||||
context_tokens: DEFAULT_CONTEXT_TOKENS,
|
context_tokens: DEFAULT_CONTEXT_TOKENS,
|
||||||
via: "test".into(),
|
via: "test".into(),
|
||||||
|
|
@ -4154,6 +4290,7 @@ echo '<meta charset=utf-8><title>done</title>送出了' > done.html; (setsid pyt
|
||||||
default_computer: crate::model::THIS_COMPUTER_NAME.into(),
|
default_computer: crate::model::THIS_COMPUTER_NAME.into(),
|
||||||
roles: tools::Roles { own: crate::model::BOT_COMPUTER_NAME.into(), person: Some(crate::model::THIS_COMPUTER_NAME.into()), server: false },
|
roles: tools::Roles { own: crate::model::BOT_COMPUTER_NAME.into(), person: Some(crate::model::THIS_COMPUTER_NAME.into()), server: false },
|
||||||
local_execution: false,
|
local_execution: false,
|
||||||
|
close_browsers: true,
|
||||||
tools_enabled: false,
|
tools_enabled: false,
|
||||||
direct: Arc::new(AtomicBool::new(false)),
|
direct: Arc::new(AtomicBool::new(false)),
|
||||||
local_locked: false,
|
local_locked: false,
|
||||||
|
|
@ -4375,6 +4512,7 @@ echo '<meta charset=utf-8><title>done</title>送出了' > done.html; (setsid pyt
|
||||||
default_computer: crate::model::THIS_COMPUTER_NAME.into(),
|
default_computer: crate::model::THIS_COMPUTER_NAME.into(),
|
||||||
roles: tools::Roles { own: crate::model::BOT_COMPUTER_NAME.into(), person: Some(crate::model::THIS_COMPUTER_NAME.into()), server: false },
|
roles: tools::Roles { own: crate::model::BOT_COMPUTER_NAME.into(), person: Some(crate::model::THIS_COMPUTER_NAME.into()), server: false },
|
||||||
local_execution: false,
|
local_execution: false,
|
||||||
|
close_browsers: true,
|
||||||
tools_enabled: false,
|
tools_enabled: false,
|
||||||
direct: Arc::new(AtomicBool::new(true)),
|
direct: Arc::new(AtomicBool::new(true)),
|
||||||
local_locked: false,
|
local_locked: false,
|
||||||
|
|
|
||||||
14
src/app.rs
14
src/app.rs
|
|
@ -1495,10 +1495,11 @@ impl App {
|
||||||
tool_specs.push(serde_json::json!({"name": "publish_site", "description": "Publish a web page or a folder with index.html that you made as a public website on the person's AnyBot account server. Publishing again with the same name replaces it. Give the person the address you get back.",
|
tool_specs.push(serde_json::json!({"name": "publish_site", "description": "Publish a web page or a folder with index.html that you made as a public website on the person's AnyBot account server. Publishing again with the same name replaces it. Give the person the address you get back.",
|
||||||
"parameters": {"type": "object", "properties": {"path": {"type": "string", "description": "Folder with index.html, or one .html file"}, "name": {"type": "string", "description": "Short site name: letters, digits and -"}, "computer": {"type": "string", "enum": names.clone()}}, "required": ["path", "name"]}}));
|
"parameters": {"type": "object", "properties": {"path": {"type": "string", "description": "Folder with index.html, or one .html file"}, "name": {"type": "string", "description": "Short site name: letters, digits and -"}, "computer": {"type": "string", "enum": names.clone()}}, "required": ["path", "name"]}}));
|
||||||
}
|
}
|
||||||
if crate::botbrowser::available() {
|
|
||||||
tool_specs.extend(crate::vault::specs());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
// 保險庫: only what there is to fill (an empty vault offers no fill at all — see Offer).
|
||||||
|
let vault = if !untrusted && crate::botbrowser::available() { crate::vault::offer() } else { crate::vault::Offer::default() };
|
||||||
|
tool_specs.extend(crate::vault::specs_for(&vault));
|
||||||
|
crate::browser::limit_fill(&mut tool_specs, &vault.kinds());
|
||||||
if b.demos.iter().any(|d| d.shots.iter().any(|s| !s.is_empty())) {
|
if b.demos.iter().any(|d| d.shots.iter().any(|s| !s.is_empty())) {
|
||||||
tool_specs.push(crate::teach::view_step_spec());
|
tool_specs.push(crate::teach::view_step_spec());
|
||||||
}
|
}
|
||||||
|
|
@ -1593,6 +1594,7 @@ impl App {
|
||||||
default_computer,
|
default_computer,
|
||||||
roles,
|
roles,
|
||||||
local_execution: !untrusted && self.local_on(),
|
local_execution: !untrusted && self.local_on(),
|
||||||
|
close_browsers: self.state.close_browsers_when_done,
|
||||||
local_locked: !self.managed.local.allows() || self.state.local_never,
|
local_locked: !self.managed.local.allows() || self.state.local_never,
|
||||||
tools_enabled: !untrusted && b.tools_enabled,
|
tools_enabled: !untrusted && b.tools_enabled,
|
||||||
direct,
|
direct,
|
||||||
|
|
@ -3968,6 +3970,11 @@ impl App {
|
||||||
ui.label(RichText::new(t("需要 Chrome、Brave、Edge、Chromium 或 Firefox 才能用 AnyBot 自己的瀏覽器。")).size(11.5).color(p.text3));
|
ui.label(RichText::new(t("需要 Chrome、Brave、Edge、Chromium 或 Firefox 才能用 AnyBot 自己的瀏覽器。")).size(11.5).color(p.text3));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
setting_row(ui, p, "做完就關掉瀏覽器", "Bot 做完一件事,就把它用過的瀏覽器視窗整個關掉(登入都還在,下次會再打開);別的 Bot 還在用的不關", |ui| {
|
||||||
|
if ui.add(egui::Checkbox::without_text(&mut self.state.close_browsers_when_done)).changed() {
|
||||||
|
self.dirty = true;
|
||||||
|
}
|
||||||
|
});
|
||||||
let current = crate::botbrowser::current();
|
let current = crate::botbrowser::current();
|
||||||
for name in crate::botbrowser::choices() {
|
for name in crate::botbrowser::choices() {
|
||||||
ui.horizontal(|ui| {
|
ui.horizontal(|ui| {
|
||||||
|
|
@ -5746,6 +5753,7 @@ fn grant_label(g: &str) -> String {
|
||||||
"browser:read" => "「讀取瀏覽器分頁」".into(),
|
"browser:read" => "「讀取瀏覽器分頁」".into(),
|
||||||
"read:anywhere" => "「讀取工作資料夾以外」".into(),
|
"read:anywhere" => "「讀取工作資料夾以外」".into(),
|
||||||
"computer:see" => "「看你的螢幕」".into(),
|
"computer:see" => "「看你的螢幕」".into(),
|
||||||
|
"computer:control" => "「操作這台電腦的螢幕」".into(),
|
||||||
g if g.starts_with("app:") => format!("操作「{}」", &g[4..]),
|
g if g.starts_with("app:") => format!("操作「{}」", &g[4..]),
|
||||||
g if g.starts_with("mcp:") => format!("使用連接器「{}」", &g[4..]),
|
g if g.starts_with("mcp:") => format!("使用連接器「{}」", &g[4..]),
|
||||||
g if g.starts_with("login:") => format!("登入 {}", &g[6..]),
|
g if g.starts_with("login:") => format!("登入 {}", &g[6..]),
|
||||||
|
|
|
||||||
|
|
@ -9,6 +9,8 @@ use crate::cloudbox::{self, Rebuild, Run};
|
||||||
|
|
||||||
/// The floating bar stays this long after the bot's last mouse/keyboard action on this Mac.
|
/// The floating bar stays this long after the bot's last mouse/keyboard action on this Mac.
|
||||||
const LOCAL_BAR_SECS: u64 = 8;
|
const LOCAL_BAR_SECS: u64 = 8;
|
||||||
|
/// The row for 「一律允許」 on the whole screen (a desktop that can't name apps).
|
||||||
|
const SCREEN_ROW: &str = "整個螢幕(看不出是哪個 App 時)";
|
||||||
|
|
||||||
/// Another AnyBot of the account: (id, name, online).
|
/// Another AnyBot of the account: (id, name, online).
|
||||||
pub type Peer = (String, String, bool);
|
pub type Peer = (String, String, bool);
|
||||||
|
|
@ -843,7 +845,8 @@ impl App {
|
||||||
.state
|
.state
|
||||||
.bots
|
.bots
|
||||||
.iter()
|
.iter()
|
||||||
.flat_map(|b| b.allow_rules.iter().filter_map(|g| g.strip_prefix("app:")).map(|a| (b.id, b.name.clone(), a.to_string())).collect::<Vec<_>>())
|
// (The whole screen, when the desktop couldn't name the app: listed and removable too.)
|
||||||
|
.flat_map(|b| b.allow_rules.iter().filter_map(|g| if g == "computer:control" { Some(SCREEN_ROW) } else { g.strip_prefix("app:") }).map(|a| (b.id, b.name.clone(), a.to_string())).collect::<Vec<_>>())
|
||||||
.collect();
|
.collect();
|
||||||
if apps.is_empty() {
|
if apps.is_empty() {
|
||||||
return;
|
return;
|
||||||
|
|
@ -862,7 +865,7 @@ impl App {
|
||||||
for (id, bot, app) in &apps {
|
for (id, bot, app) in &apps {
|
||||||
sec_row_s(ui, p, app, &format!("{bot} 可以使用"), "", |ui| {
|
sec_row_s(ui, p, app, &format!("{bot} 可以使用"), "", |ui| {
|
||||||
if crate::icons::button(ui, crate::icons::Icon::Trash, 14.0, p.text3, p.hover).on_hover_text(format!("{} {app}", t("移除"))).clicked() {
|
if crate::icons::button(ui, crate::icons::Icon::Trash, 14.0, p.text3, p.hover).on_hover_text(format!("{} {app}", t("移除"))).clicked() {
|
||||||
remove = Some((*id, format!("app:{app}")));
|
remove = Some((*id, if app == SCREEN_ROW { "computer:control".to_string() } else { format!("app:{app}") }));
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
|
||||||
15
src/bidi.rs
15
src/bidi.rs
|
|
@ -209,6 +209,21 @@ pub fn close(port: u16, id: &str) -> Result<(), String> {
|
||||||
command(port, "browsingContext.close", json!({"context": id})).map(|_| ())
|
command(port, "browsingContext.close", json!({"context": id})).map(|_| ())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Ask this Firefox to quit (every window of its profile). Its answer may not come — it closes
|
||||||
|
/// the connection as it goes — so the caller checks that it is gone. The connection is dropped.
|
||||||
|
pub fn close_browser(port: u16) {
|
||||||
|
let conn = conns().lock().unwrap_or_else(|e| e.into_inner()).remove(&port);
|
||||||
|
let conn = match conn {
|
||||||
|
Some(c) => c,
|
||||||
|
None => match Conn::open(port) {
|
||||||
|
Ok(c) => Arc::new(Mutex::new(c)),
|
||||||
|
Err(_) => return,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
let _ = conn.lock().unwrap_or_else(|e| e.into_inner()).call("browser.close", json!({}), 5);
|
||||||
|
recent().lock().unwrap_or_else(|e| e.into_inner()).remove(&port);
|
||||||
|
}
|
||||||
|
|
||||||
// ---------- DevTools commands, done the BiDi way ----------
|
// ---------- DevTools commands, done the BiDi way ----------
|
||||||
|
|
||||||
/// WebDriver's code for a key DevTools names (Enter, ArrowDown…); a letter is itself.
|
/// WebDriver's code for a key DevTools names (Enter, ArrowDown…); a letter is itself.
|
||||||
|
|
|
||||||
|
|
@ -724,6 +724,77 @@ fn ensure_firefox(profile: &str, dir: &std::path::Path, first_url: Option<&str>)
|
||||||
Err(format!("Firefox 沒有及時打開(設定檔「{profile}」)。請再試一次。"))
|
Err(format!("Firefox 沒有及時打開(設定檔「{profile}」)。請再試一次。"))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// How long a browser gets to quit when asked before it is told to stop.
|
||||||
|
const QUIT_WAIT: Duration = Duration::from_secs(8);
|
||||||
|
|
||||||
|
/// Close this profile's whole browser (every window). Its logins stay in the profile; the next
|
||||||
|
/// step that needs it opens it again. Not the box's Chromium, nor the person's own browser.
|
||||||
|
pub fn quit(profile: Option<&str>) -> Result<(), String> {
|
||||||
|
if using_box() {
|
||||||
|
return Err("Bot 的電腦裡的瀏覽器不在這裡關。".into());
|
||||||
|
}
|
||||||
|
let prof = resolve(profile)?;
|
||||||
|
if prof == PERSON_PROFILE {
|
||||||
|
return Err("「你的瀏覽器」是你自己的視窗,AnyBot 不會關。".into());
|
||||||
|
}
|
||||||
|
let Some(port) = live_port(&prof) else { return Ok(()) };
|
||||||
|
let gone = |still: &dyn Fn() -> bool| {
|
||||||
|
let start = Instant::now();
|
||||||
|
while start.elapsed() < QUIT_WAIT {
|
||||||
|
if !still() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
std::thread::sleep(Duration::from_millis(250));
|
||||||
|
}
|
||||||
|
false
|
||||||
|
};
|
||||||
|
match place(&prof) {
|
||||||
|
Some((Kind::Firefox, dir)) => {
|
||||||
|
crate::bidi::close_browser(port);
|
||||||
|
if gone(&|| firefox_in_use(&dir)) {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
// It didn't take the request: stop its program (the way a window's close does).
|
||||||
|
let pid = firefox_pid(&dir).ok_or("Firefox 沒有關掉,也找不到它的程式")?;
|
||||||
|
let _ = Command::new("kill").arg("-TERM").arg(pid.to_string()).status();
|
||||||
|
if gone(&|| firefox_in_use(&dir)) { Ok(()) } else { Err(format!("Firefox(設定檔「{prof}」)沒有關掉")) }
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
close_chrome(port)?;
|
||||||
|
if gone(&|| alive(port)) { Ok(()) } else { Err(format!("瀏覽器(設定檔「{prof}」)沒有關掉")) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The program holding this Firefox profile open.
|
||||||
|
fn firefox_pid(dir: &std::path::Path) -> Option<u32> {
|
||||||
|
#[cfg(target_os = "linux")]
|
||||||
|
{
|
||||||
|
std::fs::read_link(dir.join("lock")).ok().and_then(|t| t.to_string_lossy().rsplit('+').next().and_then(|p| p.parse::<u32>().ok()))
|
||||||
|
}
|
||||||
|
#[cfg(target_os = "macos")]
|
||||||
|
{
|
||||||
|
Command::new("lsof").arg("-t").arg(dir.join(".parentlock")).output().ok().and_then(|o| String::from_utf8_lossy(&o.stdout).lines().next().and_then(|l| l.trim().parse().ok()))
|
||||||
|
}
|
||||||
|
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
|
||||||
|
{
|
||||||
|
let _ = dir;
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Chrome's own quit (DevTools Browser.close on the browser's connection).
|
||||||
|
fn close_chrome(port: u16) -> Result<(), String> {
|
||||||
|
let mut r = local().get(&endpoint(port, "/json/version")).call().map_err(|e| e.to_string())?;
|
||||||
|
let v: Value = serde_json::from_str(&r.body_mut().read_to_string().unwrap_or_default()).unwrap_or_default();
|
||||||
|
let ws_url = v["webSocketDebuggerUrl"].as_str().ok_or("瀏覽器沒有給控制它的位址")?;
|
||||||
|
let addr = std::net::SocketAddr::from(([127, 0, 0, 1], port));
|
||||||
|
let stream = std::net::TcpStream::connect_timeout(&addr, Duration::from_secs(5)).map_err(|e| e.to_string())?;
|
||||||
|
let (mut ws, _) = tungstenite::client::client(ws_url, stream).map_err(|e| e.to_string())?;
|
||||||
|
ws.send(tungstenite::Message::Text(serde_json::json!({"id": 1, "method": "Browser.close"}).to_string().into())).map_err(|e| e.to_string())?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
/// Open a link in a new tab of the bot's browser (in the named profile, which becomes current).
|
/// Open a link in a new tab of the bot's browser (in the named profile, which becomes current).
|
||||||
pub fn open(url: &str, profile: Option<&str>) -> Result<String, String> {
|
pub fn open(url: &str, profile: Option<&str>) -> Result<String, String> {
|
||||||
if crate::web::is_forbidden_browser_url(url) {
|
if crate::web::is_forbidden_browser_url(url) {
|
||||||
|
|
@ -1024,6 +1095,63 @@ mod tests {
|
||||||
r.unwrap();
|
r.unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 做完就關掉瀏覽器, live: a job's end closes its Firefox — unless another job is on it.
|
||||||
|
/// Firefox opens headless in a scratch profile:
|
||||||
|
/// HOME=$T ANYBOT_DATA_DIR=$T/data ANYBOT_FIREFOX_HEADLESS=1 <test binary> --ignored a_finished_job_quits_its_firefox
|
||||||
|
#[test]
|
||||||
|
#[ignore]
|
||||||
|
fn a_finished_job_quits_its_firefox() {
|
||||||
|
use std::io::{Read, Write};
|
||||||
|
let root = firefox_roots()[0].clone();
|
||||||
|
assert!(root.starts_with(std::env::var("HOME").unwrap()) && !root.exists(), "run with HOME set to an empty scratch folder");
|
||||||
|
let dir = root.join("x2.收尾");
|
||||||
|
std::fs::create_dir_all(&dir).unwrap();
|
||||||
|
std::fs::write(root.join("profiles.ini"), "[Profile0]\nName=收尾\nIsRelative=1\nPath=x2.收尾\n").unwrap();
|
||||||
|
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 = "<html><head><title>頁面</title></head><body>hi</body></html>";
|
||||||
|
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 tidy = |job: &str| as_job(job, || crate::browser::run("browser_tabs", &serde_json::json!({"action": "tidy", "close": true, "profile": "收尾"})).map(|r| r.0));
|
||||||
|
let open_as = |job: &str| as_job(job, || open(&url, Some("收尾")));
|
||||||
|
let quit_within = |secs: u64| {
|
||||||
|
let t = Instant::now();
|
||||||
|
while firefox_in_use(&dir) && t.elapsed() < Duration::from_secs(secs) {
|
||||||
|
std::thread::sleep(Duration::from_millis(200));
|
||||||
|
}
|
||||||
|
!firefox_in_use(&dir)
|
||||||
|
};
|
||||||
|
let r = (|| -> Result<(), String> {
|
||||||
|
// Two jobs on the same browser: the first one's end leaves it open, closing its tabs.
|
||||||
|
open_as("j1")?;
|
||||||
|
open_as("j2")?;
|
||||||
|
let said = tidy("j1")?;
|
||||||
|
assert!(said.contains("分頁") && firefox_in_use(&dir), "{said}");
|
||||||
|
// The last one's end closes the whole browser.
|
||||||
|
let said = tidy("j2")?;
|
||||||
|
assert!(said.contains("關掉"), "{said}");
|
||||||
|
assert!(quit_within(10), "Firefox is still running");
|
||||||
|
// And the next step opens it again.
|
||||||
|
open_as("j3")?;
|
||||||
|
assert!(firefox_in_use(&dir));
|
||||||
|
tidy("j3")?;
|
||||||
|
assert!(quit_within(10));
|
||||||
|
Ok(())
|
||||||
|
})();
|
||||||
|
if firefox_in_use(&dir) {
|
||||||
|
if let Some(pid) = firefox_pid(&dir) {
|
||||||
|
let _ = Command::new("kill").arg(pid.to_string()).status();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
r.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_firefox_profile_answers_to_its_own_name() {
|
fn a_firefox_profile_answers_to_its_own_name() {
|
||||||
let list = vec![DEFAULT_PROFILE.to_string(), "工作".to_string(), format!("阿金{FIREFOX_MARK}"), format!("Sunny{FIREFOX_MARK}")];
|
let list = vec![DEFAULT_PROFILE.to_string(), "工作".to_string(), format!("阿金{FIREFOX_MARK}"), format!("Sunny{FIREFOX_MARK}")];
|
||||||
|
|
|
||||||
108
src/browser.rs
108
src/browser.rs
|
|
@ -597,6 +597,31 @@ actions:
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 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::<Vec<_>>().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,
|
/// 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
|
/// so every guard downstream (approvals incl. the vault's, oplog, replay, the remote link, the
|
||||||
/// work log) keeps its stable per-action name.
|
/// work log) keeps its stable per-action name.
|
||||||
|
|
@ -1011,27 +1036,54 @@ fn shrink(b64: &str) -> Option<String> {
|
||||||
/// A job is done with this browser: keep the page it ended on, close the rest (the list is
|
/// A job is done with this browser: keep the page it ended on, close the rest (the list is
|
||||||
/// latest-used first). A browser that isn't open stays closed. Not offered to the model; the
|
/// latest-used first). A browser that isn't open stays closed. Not offered to the model; the
|
||||||
/// loop calls it (browser_tabs action "tidy") when a job ends.
|
/// loop calls it (browser_tabs action "tidy") when a job ends.
|
||||||
fn tidy(profile: Option<&str>) -> Result<String, String> {
|
fn tidy(profile: Option<&str>, close_window: bool) -> Result<String, String> {
|
||||||
let job = botbrowser::job();
|
let job = botbrowser::job();
|
||||||
// (Its tabs are nobody's from here on, whatever happens below.)
|
// (Its tabs are nobody's from here on, whatever happens below.)
|
||||||
let mine = if job.is_empty() { vec![] } else { botbrowser::release(&job) };
|
let mine = if job.is_empty() { vec![] } else { botbrowser::release(&job) };
|
||||||
let Some(port) = botbrowser::running_port(profile) else { return Ok("瀏覽器沒有開著。".into()) };
|
let Some(port) = botbrowser::running_port(profile) else { return Ok("瀏覽器沒有開著。".into()) };
|
||||||
let kind = botbrowser::kind_of(profile);
|
let kind = botbrowser::kind_of(profile);
|
||||||
let list = botbrowser::pages_of(kind, port)?;
|
let list = botbrowser::pages_of(kind, port)?;
|
||||||
let close: Vec<&Value> = if job.is_empty() {
|
match tidy_plan(&job, close_window && !botbrowser::using_box(), &list, &mine, botbrowser::others_tab) {
|
||||||
// (An older brain that doesn't say which job: the old way, all but the front page.)
|
Tidy::Quit => {
|
||||||
list.iter().skip(1).collect()
|
botbrowser::quit(profile)?;
|
||||||
} else {
|
Ok("用完了,瀏覽器視窗已關掉(登入都還在)。".into())
|
||||||
// The job's own tabs but its latest; other jobs' and the person's are left alone.
|
}
|
||||||
list.iter().filter(|t| mine.iter().any(|m| t["id"].as_str() == Some(m.as_str()))).skip(1).collect()
|
Tidy::Tabs(ids) => {
|
||||||
};
|
let closed = ids.iter().filter(|id| botbrowser::close_tab(kind, port, id).is_ok()).count();
|
||||||
let closed = close.iter().filter(|t| botbrowser::close_tab(kind, port, t["id"].as_str().unwrap_or("")).is_ok()).count();
|
|
||||||
Ok(format!("關了 {closed} 個用完的分頁。"))
|
Ok(format!("關了 {closed} 個用完的分頁。"))
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, PartialEq)]
|
||||||
|
enum Tidy {
|
||||||
|
/// Close the whole browser.
|
||||||
|
Quit,
|
||||||
|
/// Close these tabs.
|
||||||
|
Tabs(Vec<String>),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What a job's end closes in a browser (`list`: its tabs, latest-used first; `mine`: the job's).
|
||||||
|
/// With `close_window`, the whole browser when no other running job has a tab there — its
|
||||||
|
/// windows used to stay open after every job, five Firefox profiles at once on a small machine —
|
||||||
|
/// else all the job's tabs. Without it, the job's tabs but its latest (the page it ended on).
|
||||||
|
fn tidy_plan(job: &str, close_window: bool, list: &[Value], mine: &[String], others: impl Fn(&str) -> bool) -> Tidy {
|
||||||
|
let id = |t: &Value| t["id"].as_str().unwrap_or("").to_string();
|
||||||
|
if job.is_empty() {
|
||||||
|
// (An older brain that doesn't say which job: the old way, all but the front page.)
|
||||||
|
return Tidy::Tabs(list.iter().skip(1).map(id).collect());
|
||||||
|
}
|
||||||
|
if close_window && !list.iter().any(|t| others(&id(t))) {
|
||||||
|
return Tidy::Quit;
|
||||||
|
}
|
||||||
|
let own: Vec<String> = list.iter().map(id).filter(|i| mine.contains(i)).collect();
|
||||||
|
// Other jobs' tabs and the person's are left alone.
|
||||||
|
Tidy::Tabs(own.into_iter().skip(if close_window { 0 } else { 1 }).collect())
|
||||||
|
}
|
||||||
|
|
||||||
fn tabs(args: &Value, profile: Option<&str>) -> Result<String, String> {
|
fn tabs(args: &Value, profile: Option<&str>) -> Result<String, String> {
|
||||||
if s(args, "action") == "tidy" {
|
if s(args, "action") == "tidy" {
|
||||||
return tidy(profile);
|
return tidy(profile, args["close"] == true);
|
||||||
}
|
}
|
||||||
let (_, port, kind) = port_of(profile)?;
|
let (_, port, kind) = port_of(profile)?;
|
||||||
// Another job's tabs aren't listed, switched to or closed.
|
// Another job's tabs aren't listed, switched to or closed.
|
||||||
|
|
@ -1178,6 +1230,42 @@ mod tests {
|
||||||
assert!(mapped.contains(&n), "internal tool {n} is unreachable from browser");
|
assert!(mapped.contains(&n), "internal tool {n} is unreachable from browser");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[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::<Vec<Value>>();
|
||||||
|
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::*;
|
use super::*;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|
|
||||||
195
src/computer.rs
195
src/computer.rs
|
|
@ -1004,6 +1004,66 @@ fn fill_form_tool(v: &Value) -> Result<String, String> {
|
||||||
")))
|
")))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The apps a batch was approved for: the one in front when it starts — unless that is AnyBot,
|
||||||
|
/// where the person just typed the request — and the one its first click lands in. Its first
|
||||||
|
/// click bringing that app forward is the plan, not a switch (it used to stop every
|
||||||
|
/// 「點網址列 → 打字 → Enter」 started from the chat after one step).
|
||||||
|
struct BatchApps {
|
||||||
|
names: Vec<String>,
|
||||||
|
pids: Vec<i32>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl BatchApps {
|
||||||
|
fn add(&mut self, name: &str, pid: Option<i32>) {
|
||||||
|
if name.trim().is_empty() || is_self_app(name, pid) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
self.names.push(name.trim().to_lowercase());
|
||||||
|
self.pids.extend(pid.filter(|p| *p > 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The front app (`name`, `pid`) before a later step: Err says why the batch stops.
|
||||||
|
fn still_on(&mut self, name: &str, pid: i32) -> Result<(), String> {
|
||||||
|
if is_self_app(name, Some(pid)) {
|
||||||
|
return Err("最前面變成了 AnyBot 自己的視窗".into());
|
||||||
|
}
|
||||||
|
if self.names.is_empty() && self.pids.is_empty() {
|
||||||
|
// Started on AnyBot with no point to go by: the app the first step brought forward.
|
||||||
|
self.add(name, Some(pid));
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
if (pid > 0 && self.pids.contains(&pid)) || self.names.contains(&name.trim().to_lowercase()) {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
Err(format!("最前面的 App 已切換為「{name}」"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn batch_apps(acts: &[Value], scale: (f64, f64)) -> BatchApps {
|
||||||
|
let mut m = BatchApps { names: vec![], pids: vec![] };
|
||||||
|
if let Some((app, pid)) = mac::front_app() {
|
||||||
|
m.add(&app, Some(pid));
|
||||||
|
}
|
||||||
|
// The first step that names a place: a number is in the app of the latest look, a point in
|
||||||
|
// the window under it.
|
||||||
|
for a in acts {
|
||||||
|
if !a["ref"].is_null() {
|
||||||
|
if let Some((app, _)) = SPOTS.lock().unwrap_or_else(|e| e.into_inner()).as_ref() {
|
||||||
|
m.add(app, None);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if let (Some(x), Some(y)) = (a["x"].as_f64(), a["y"].as_f64()) {
|
||||||
|
let (sx, sy) = to_screen(x, y, scale);
|
||||||
|
if let Some((app, pid)) = mac::window_at(sx, sy) {
|
||||||
|
m.add(&app, Some(pid));
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
m
|
||||||
|
}
|
||||||
|
|
||||||
pub fn batch(v: &Value, scale: (f64, f64)) -> Result<String, String> {
|
pub fn batch(v: &Value, scale: (f64, f64)) -> Result<String, String> {
|
||||||
let acts = v["actions"].as_array().ok_or("computer_use_batch 要給 actions:動作陣列,每個有 action(click、typing、press_key、scroll、mouse_move、drag)和它的參數")?;
|
let acts = v["actions"].as_array().ok_or("computer_use_batch 要給 actions:動作陣列,每個有 action(click、typing、press_key、scroll、mouse_move、drag)和它的參數")?;
|
||||||
if acts.is_empty() {
|
if acts.is_empty() {
|
||||||
|
|
@ -1012,14 +1072,14 @@ pub fn batch(v: &Value, scale: (f64, f64)) -> Result<String, String> {
|
||||||
if acts.len() > MAX_BATCH {
|
if acts.len() > MAX_BATCH {
|
||||||
return Err(format!("一次最多 {MAX_BATCH} 個動作({} 個太多了)", acts.len()));
|
return Err(format!("一次最多 {MAX_BATCH} 個動作({} 個太多了)", acts.len()));
|
||||||
}
|
}
|
||||||
let start_pid = mac::front_app().map(|(_, p)| p);
|
let mut meant = batch_apps(acts, scale);
|
||||||
let mut notes = Vec::new();
|
let mut notes = Vec::new();
|
||||||
for (i, a) in acts.iter().enumerate() {
|
for (i, a) in acts.iter().enumerate() {
|
||||||
let name = action_tool(a["action"].as_str().unwrap_or(""))?;
|
let name = action_tool(a["action"].as_str().unwrap_or(""))?;
|
||||||
if i > 0 {
|
if i > 0 {
|
||||||
if let (Some(was), Some((now_name, now))) = (start_pid, mac::front_app()) {
|
if let Some((now_name, now)) = mac::front_app() {
|
||||||
if was != now {
|
if let Err(why) = meant.still_on(&now_name, now) {
|
||||||
notes.push(format!("(第 {} 步前最前面的 App 已切換為「{now_name}」,停止後續 {} 步以便先確認權限)", i + 1, acts.len() - i));
|
notes.push(format!("(第 {} 步前{why},停止後續 {} 步以便先確認權限)", i + 1, acts.len() - i));
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -1136,7 +1196,11 @@ pub fn act(name: &str, v: &Value, scale: (f64, f64)) -> Result<String, String> {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn act_inner(name: &str, v: &Value, scale: (f64, f64), allow_self: bool) -> Result<String, String> {
|
fn act_inner(name: &str, v: &Value, scale: (f64, f64), allow_self: bool) -> Result<String, String> {
|
||||||
if !allow_self && (name == "computer_use_press_key" || name == "computer_use_typing") {
|
// Keys go to the front window: never AnyBot's own. Typing into a numbered field clicks it
|
||||||
|
// first, which brings its window forward — checked after that click, below (checked before
|
||||||
|
// it, a bot couldn't type anywhere while the person's last click was in AnyBot's chat).
|
||||||
|
let typing_by_ref = name == "computer_use_typing" && !v["ref"].is_null();
|
||||||
|
if !allow_self && (name == "computer_use_press_key" || (name == "computer_use_typing" && !typing_by_ref)) {
|
||||||
refuse_self_front()?;
|
refuse_self_front()?;
|
||||||
}
|
}
|
||||||
keys_go_where_looked(name, v)?;
|
keys_go_where_looked(name, v)?;
|
||||||
|
|
@ -1220,10 +1284,12 @@ fn act_inner(name: &str, v: &Value, scale: (f64, f64), allow_self: bool) -> Resu
|
||||||
if let Some((x, y, what)) = &at {
|
if let Some((x, y, what)) = &at {
|
||||||
if !allow_self {
|
if !allow_self {
|
||||||
refuse_self_point(*x, *y)?;
|
refuse_self_point(*x, *y)?;
|
||||||
refuse_self_front()?;
|
|
||||||
}
|
}
|
||||||
mac::click(*x, *y, "left", 1, 0);
|
mac::click(*x, *y, "left", 1, 0);
|
||||||
std::thread::sleep(std::time::Duration::from_millis(150));
|
std::thread::sleep(std::time::Duration::from_millis(150));
|
||||||
|
if !allow_self {
|
||||||
|
refuse_self_front()?;
|
||||||
|
}
|
||||||
if crate::cloudbox::replaces_field(what, v) {
|
if crate::cloudbox::replaces_field(what, v) {
|
||||||
press_keys("cmd+a", KEY_HOLD_SECS)?;
|
press_keys("cmd+a", KEY_HOLD_SECS)?;
|
||||||
std::thread::sleep(std::time::Duration::from_millis(50));
|
std::thread::sleep(std::time::Duration::from_millis(50));
|
||||||
|
|
@ -1575,33 +1641,41 @@ fn high_risk_submit_words(label: &str) -> bool {
|
||||||
"pay", "purchase", "buy now", "checkout", "check out", "place order", "confirm order", "transfer", "delete", "erase",
|
"pay", "purchase", "buy now", "checkout", "check out", "place order", "confirm order", "transfer", "delete", "erase",
|
||||||
];
|
];
|
||||||
let low = label.to_lowercase();
|
let low = label.to_lowercase();
|
||||||
HIGH.iter().any(|w| if w.is_ascii() { low.contains(w) } else { label.contains(w) })
|
// English as whole words: 「PayPal」, 「Payments」, 「display」 aren't 「pay」.
|
||||||
|
HIGH.iter().any(|w| if w.is_ascii() { has_word(&low, w) } else { label.contains(w) })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `w` in `text` with no letter or digit right before or after it.
|
||||||
|
fn has_word(text: &str, w: &str) -> bool {
|
||||||
|
text.match_indices(w).any(|(i, _)| {
|
||||||
|
let before = text[..i].chars().next_back();
|
||||||
|
let after = text[i + w.len()..].chars().next();
|
||||||
|
!before.is_some_and(char::is_alphanumeric) && !after.is_some_and(char::is_alphanumeric)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The words of what a step clicks or submits (by ref, name, raw `x, y` coordinates, or keyboard
|
/// The words of what a step clicks or submits (by ref, name, raw `x, y` coordinates, or keyboard
|
||||||
/// Enter/Delete submit); a batch answers with the first sensitive action it carries.
|
/// Enter/Delete submit); a batch answers with the first sensitive action it carries. Read from
|
||||||
|
/// this computer's latest look — only for steps on this computer (see agent.rs).
|
||||||
pub fn sensitive_target(name: &str, args: &Value) -> Option<String> {
|
pub fn sensitive_target(name: &str, args: &Value) -> Option<String> {
|
||||||
|
let spots = SPOTS.lock().unwrap_or_else(|e| e.into_inner()).clone().map(|(_, s)| s);
|
||||||
|
sensitive_target_in(name, args, spots.as_ref(), scale_here())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sensitive_target_in(name: &str, args: &Value, spots: Option<&crate::marks::Spots>, scale: (f64, f64)) -> Option<String> {
|
||||||
if name == "computer_use_menu_click" {
|
if name == "computer_use_menu_click" {
|
||||||
let items: Vec<&str> = args["menu"].as_array()?.iter().filter_map(|x| x.as_str()).collect();
|
let items: Vec<&str> = args["menu"].as_array()?.iter().filter_map(|x| x.as_str()).collect();
|
||||||
return items.iter().rev().find(|s| sensitive_words(s)).map(|s| (*s).to_string());
|
return items.iter().rev().find(|s| sensitive_words(s)).map(|s| (*s).to_string());
|
||||||
}
|
}
|
||||||
let spots = SPOTS.lock().unwrap_or_else(|e| e.into_inner()).clone().map(|(_, s)| s);
|
let ref_of = |a: &Value| -> Option<String> { a["ref"].as_str().map(str::trim).filter(|r| !r.is_empty()).map(String::from).or_else(|| a["ref"].as_u64().map(|n| n.to_string())) };
|
||||||
let label_of_click = |a: &Value| -> Option<String> {
|
let label_of_click = |a: &Value| -> Option<String> {
|
||||||
let r = a["ref"]
|
if let (Some(r), Some(s)) = (ref_of(a), spots) {
|
||||||
.as_str()
|
|
||||||
.map(str::trim)
|
|
||||||
.filter(|r| !r.is_empty())
|
|
||||||
.map(String::from)
|
|
||||||
.or_else(|| a["ref"].as_u64().map(|n| n.to_string()));
|
|
||||||
if let Some(r) = r {
|
|
||||||
if let Some(ref s) = spots {
|
|
||||||
if let Ok((_, l)) = s.get(&r) {
|
if let Ok((_, l)) = s.get(&r) {
|
||||||
return Some(l);
|
return Some(l);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
if let Some(named) = ["name", "text"].iter().find_map(|k| a[*k].as_str().map(str::trim).filter(|t| !t.is_empty())) {
|
if let Some(named) = ["name", "text"].iter().find_map(|k| a[*k].as_str().map(str::trim).filter(|t| !t.is_empty())) {
|
||||||
if let Some(ref s) = spots {
|
if let Some(s) = spots {
|
||||||
if let Ok(n) = s.named(named) {
|
if let Ok(n) = s.named(named) {
|
||||||
if let Some((_, l)) = s.by_number.get(&n) {
|
if let Some((_, l)) = s.by_number.get(&n) {
|
||||||
return Some(l.clone());
|
return Some(l.clone());
|
||||||
|
|
@ -1610,12 +1684,14 @@ pub fn sensitive_target(name: &str, args: &Value) -> Option<String> {
|
||||||
}
|
}
|
||||||
return Some(named.to_string());
|
return Some(named.to_string());
|
||||||
}
|
}
|
||||||
// Raw (x, y) coordinate click: check if the point lands on any numbered control in `SPOTS`.
|
// Raw (x, y): the control the point is on — the innermost one (a row or a list around a
|
||||||
if let (Some(x), Some(y), Some(ref s)) = (a["x"].as_f64(), a["y"].as_f64(), &spots) {
|
// button carries all its words; any box within reach used to count, so a click in a
|
||||||
let (sx, sy) = to_screen(x, y, scale_here());
|
// list with 「傳送」 somewhere in it asked).
|
||||||
if let Some((_, _, _, _, l)) = s.rects.iter().find(|(rx, ry, rw, rh, l)| sx >= *rx - 6.0 && sx <= *rx + *rw + 6.0 && sy >= *ry - 6.0 && sy <= *ry + *rh + 6.0 && sensitive_words(l)) {
|
if let (Some(x), Some(y), Some(s)) = (a["x"].as_f64(), a["y"].as_f64(), spots) {
|
||||||
return Some(l.clone());
|
let (sx, sy) = to_screen(x, y, scale);
|
||||||
}
|
let within = |m: f64| s.rects.iter().filter(move |(rx, ry, rw, rh, _)| sx >= *rx - m && sx <= *rx + *rw + m && sy >= *ry - m && sy <= *ry + *rh + m);
|
||||||
|
let smallest = |m: f64| within(m).min_by(|a, b| (a.2 * a.3).total_cmp(&(b.2 * b.3)));
|
||||||
|
return smallest(0.0).or_else(|| smallest(6.0)).map(|r| r.4.clone());
|
||||||
}
|
}
|
||||||
None
|
None
|
||||||
};
|
};
|
||||||
|
|
@ -1631,14 +1707,19 @@ pub fn sensitive_target(name: &str, args: &Value) -> Option<String> {
|
||||||
}
|
}
|
||||||
_ => false,
|
_ => false,
|
||||||
};
|
};
|
||||||
if submits {
|
if !submits {
|
||||||
if let Some(ref s) = spots {
|
return None;
|
||||||
if let Some((_, l)) = s.by_number.values().find(|(_, l)| high_risk_submit_words(l)) {
|
|
||||||
return Some(l.clone());
|
|
||||||
}
|
}
|
||||||
|
let s = spots?;
|
||||||
|
// What Enter goes into: the field typed into (by ref), else the one with the cursor —
|
||||||
|
// not every control on the screen (a search box on a page with a 「Delete」 link
|
||||||
|
// anywhere used to ask on every Enter).
|
||||||
|
let field = ref_of(a).and_then(|r| s.get(&r).ok().map(|(_, l)| l)).or_else(|| s.by_number.values().map(|(_, l)| l).find(|l| l.contains("游標在這)")).cloned());
|
||||||
|
match field {
|
||||||
|
Some(l) => high_risk_submit_words(&l).then_some(l),
|
||||||
|
// No field has the cursor (a button has the focus): a button Enter would press.
|
||||||
|
None => s.by_number.values().map(|(_, l)| l).find(|l| l.starts_with("按鈕") && high_risk_submit_words(l)).cloned(),
|
||||||
}
|
}
|
||||||
}
|
|
||||||
None
|
|
||||||
};
|
};
|
||||||
match name {
|
match name {
|
||||||
"computer_use_click" => label_of_click(args),
|
"computer_use_click" => label_of_click(args),
|
||||||
|
|
@ -2366,6 +2447,58 @@ mod tests {
|
||||||
let hit = sensitive_target("computer_use_menu_click", &serde_json::json!({"menu": ["郵件", "傳送"]}));
|
let hit = sensitive_target("computer_use_menu_click", &serde_json::json!({"menu": ["郵件", "傳送"]}));
|
||||||
assert!(hit.is_some_and(|l| sensitive_words(&l)));
|
assert!(hit.is_some_and(|l| sensitive_words(&l)));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn enter_asks_only_about_the_field_it_goes_into() {
|
||||||
|
let gate = |spots: &crate::marks::Spots, name: &str, args: serde_json::Value| sensitive_target_in(name, &args, Some(spots), (1.0, 1.0)).filter(|l| sensitive_words(l));
|
||||||
|
let mut page = crate::marks::Spots::default();
|
||||||
|
page.by_number.insert(3, ((50.0, 20.0), "輸入框「搜尋」(游標在這)".into()));
|
||||||
|
page.by_number.insert(9, ((300.0, 400.0), "連結「Delete account」".into()));
|
||||||
|
page.by_number.insert(10, ((300.0, 450.0), "連結「PayPal」".into()));
|
||||||
|
// Enter in the search box of a page with 「Delete」 somewhere: not asked any more.
|
||||||
|
assert_eq!(gate(&page, "computer_use_press_key", serde_json::json!({"key": "Return"})), None);
|
||||||
|
assert_eq!(gate(&page, "computer_use_typing", serde_json::json!({"text": "貓抓板", "submit": true})), None);
|
||||||
|
assert_eq!(gate(&page, "computer_use_typing", serde_json::json!({"ref": 3, "text": "貓抓板", "submit": true})), None);
|
||||||
|
// Enter into a field that is about deleting / paying: asked.
|
||||||
|
let mut confirm = crate::marks::Spots::default();
|
||||||
|
confirm.by_number.insert(4, ((50.0, 20.0), "輸入框「輸入 DELETE 以確認刪除」(游標在這)".into()));
|
||||||
|
assert!(gate(&confirm, "computer_use_press_key", serde_json::json!({"key": "enter"})).is_some());
|
||||||
|
// No field has the cursor and a 「付款」 button is there: Enter may press it, asked.
|
||||||
|
let mut checkout = crate::marks::Spots::default();
|
||||||
|
checkout.by_number.insert(5, ((50.0, 20.0), "按鈕「確認付款」".into()));
|
||||||
|
assert!(gate(&checkout, "computer_use_press_key", serde_json::json!({"key": "Return"})).is_some());
|
||||||
|
// English words whole: 「PayPal」 isn't 「pay」, 「Pay now」 is.
|
||||||
|
assert!(!high_risk_submit_words("PayPal") && !high_risk_submit_words("Payments") && high_risk_submit_words("Pay now"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_batch_started_from_the_chat_goes_on_in_the_app_it_clicked() {
|
||||||
|
// Started with AnyBot in front, the first click on Firefox: Firefox is the plan.
|
||||||
|
let mut m = BatchApps { names: vec![], pids: vec![] };
|
||||||
|
m.add("anybot", Some(1));
|
||||||
|
m.add("firefox", Some(42));
|
||||||
|
assert!(m.still_on("firefox", 42).is_ok());
|
||||||
|
assert!(m.still_on("Firefox", 43).is_ok(), "another window of the same app");
|
||||||
|
assert!(m.still_on("gnome-terminal", 7).is_err(), "a third app stops it");
|
||||||
|
assert!(m.still_on("anybot", 1).is_err(), "AnyBot itself stops it");
|
||||||
|
// Nothing to go by at the start: the app the first step brought forward.
|
||||||
|
let mut m = BatchApps { names: vec![], pids: vec![] };
|
||||||
|
assert!(m.still_on("firefox", 42).is_ok());
|
||||||
|
assert!(m.still_on("mousepad", 9).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_click_by_point_is_about_the_control_under_it() {
|
||||||
|
let gate = |spots: &crate::marks::Spots, x: f64, y: f64| sensitive_target_in("computer_use_click", &serde_json::json!({"x": x, "y": y}), Some(spots), (1.0, 1.0)).filter(|l| sensitive_words(l));
|
||||||
|
let mut s = crate::marks::Spots::default();
|
||||||
|
// A list whose words include 「傳送」, with a reply box inside it and a 「傳送」 button.
|
||||||
|
s.rects.push((0.0, 0.0, 800.0, 600.0, "清單「留言 傳送 讚」".into()));
|
||||||
|
s.rects.push((100.0, 100.0, 300.0, 40.0, "輸入框「回覆」".into()));
|
||||||
|
s.rects.push((420.0, 100.0, 60.0, 40.0, "按鈕「傳送」".into()));
|
||||||
|
assert_eq!(gate(&s, 200.0, 120.0), None, "in the reply box");
|
||||||
|
assert!(gate(&s, 450.0, 120.0).is_some(), "on the send button");
|
||||||
|
assert!(gate(&s, 483.0, 120.0).is_some(), "a few points off the button still counts");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
|
|
||||||
|
|
@ -138,9 +138,15 @@ fn named_inside(n: &Value) -> bool {
|
||||||
|
|
||||||
/// The controls and text of a snapshot, with where each is on the screen (nodes the app gave
|
/// The controls and text of a snapshot, with where each is on the screen (nodes the app gave
|
||||||
/// no place are left out: they can't be shown or clicked).
|
/// no place are left out: they can't be shown or clicked).
|
||||||
|
/// The most nodes of one snapshot looked at (numbering still stops at 600 controls).
|
||||||
|
const MAX_WALKED_NODES: usize = 20_000;
|
||||||
|
|
||||||
pub fn elements_of(tree: &Value, app: &str) -> Vec<crate::marks::Element> {
|
pub fn elements_of(tree: &Value, app: &str) -> Vec<crate::marks::Element> {
|
||||||
fn walk(n: &Value, out: &mut Vec<crate::marks::Element>, app: &str, seen: &mut usize) {
|
fn walk(n: &Value, out: &mut Vec<crate::marks::Element>, app: &str, seen: &mut usize) {
|
||||||
if *seen >= 4000 {
|
// A bound for a runaway tree only. Nodes out of sight count here too, so 4000 ran out on
|
||||||
|
// a long web page scrolled down before the part on the screen was reached: what was
|
||||||
|
// visible got no numbers. (agent-desktop gives at most 10 000.)
|
||||||
|
if *seen >= MAX_WALKED_NODES {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
*seen += 1;
|
*seen += 1;
|
||||||
|
|
@ -215,6 +221,17 @@ pub fn launch(app: &str) -> Result<(), String> {
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_long_page_scrolled_down_still_numbers_what_is_on_screen() {
|
||||||
|
// A browser page scrolled far down: thousands of nodes above, out of sight, come first.
|
||||||
|
let above: Vec<serde_json::Value> = (0..5000).map(|i| serde_json::json!({"role": "link", "name": format!("舊貼文 {i}"), "ref_id": format!("o{i}"), "states": ["offscreen"], "bounds": {"x": 20.0, "y": -9000.0, "width": 80.0, "height": 20.0}})).collect();
|
||||||
|
let mut kids = above;
|
||||||
|
kids.push(serde_json::json!({"role": "button", "name": "回覆", "ref_id": "reply", "bounds": {"x": 400.0, "y": 300.0, "width": 60.0, "height": 30.0}}));
|
||||||
|
let tree = serde_json::json!({"role": "document web", "name": "Threads", "children": kids});
|
||||||
|
let els = elements_of(&tree, "firefox");
|
||||||
|
assert!(els.iter().any(|e| e.name == "回覆" && e.active), "the visible button got no number");
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn hidden_and_offscreen_controls_get_no_number() {
|
fn hidden_and_offscreen_controls_get_no_number() {
|
||||||
let tree = serde_json::json!({"role": "window", "children": [
|
let tree = serde_json::json!({"role": "window", "children": [
|
||||||
|
|
|
||||||
|
|
@ -669,6 +669,10 @@ pub struct State {
|
||||||
/// 「在你離開時自動更新用戶端」(4vprnG); on by default like the original.
|
/// 「在你離開時自動更新用戶端」(4vprnG); on by default like the original.
|
||||||
#[serde(default = "yes")]
|
#[serde(default = "yes")]
|
||||||
pub auto_update_when_away: bool,
|
pub auto_update_when_away: bool,
|
||||||
|
/// 做完就關掉瀏覽器: when a bot's turn ends, the AnyBot browsers it used are closed (unless
|
||||||
|
/// another bot is working in one). On by default; off keeps the page it ended on.
|
||||||
|
#[serde(default = "yes")]
|
||||||
|
pub close_browsers_when_done: bool,
|
||||||
/// 訊息管道: Slack / Discord / Telegram channels a bot answers.
|
/// 訊息管道: Slack / Discord / Telegram channels a bot answers.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub channels: Vec<crate::channels::Channel>,
|
pub channels: Vec<crate::channels::Channel>,
|
||||||
|
|
@ -1145,6 +1149,7 @@ impl State {
|
||||||
alert_sound: true,
|
alert_sound: true,
|
||||||
direct_mode: false,
|
direct_mode: false,
|
||||||
auto_update_when_away: true,
|
auto_update_when_away: true,
|
||||||
|
close_browsers_when_done: true,
|
||||||
channels: vec![],
|
channels: vec![],
|
||||||
next_channel_id: 1,
|
next_channel_id: 1,
|
||||||
mcp_servers: vec![],
|
mcp_servers: vec![],
|
||||||
|
|
|
||||||
|
|
@ -678,7 +678,7 @@ fn system_with_summaries(req: &ChatRequest) -> String {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Which messages still show their screenshots: the newest `KEEP_SCREENSHOTS`.
|
/// Which messages still show their screenshots: the newest `KEEP_SCREENSHOTS`.
|
||||||
fn kept_images(history: &[Message]) -> Vec<usize> {
|
pub(crate) fn kept_images(history: &[Message]) -> Vec<usize> {
|
||||||
let mut idx: Vec<usize> = history.iter().enumerate().filter(|(_, m)| !m.images.is_empty() && !m.summary && m.role == Role::Tool).map(|(i, _)| i).collect();
|
let mut idx: Vec<usize> = history.iter().enumerate().filter(|(_, m)| !m.images.is_empty() && !m.summary && m.role == Role::Tool).map(|(i, _)| i).collect();
|
||||||
let drop = idx.len().saturating_sub(crate::computer::KEEP_SCREENSHOTS);
|
let drop = idx.len().saturating_sub(crate::computer::KEEP_SCREENSHOTS);
|
||||||
idx.drain(..drop);
|
idx.drain(..drop);
|
||||||
|
|
|
||||||
|
|
@ -1259,7 +1259,9 @@ fn device_run(v: &Value, s: &Settings, via_relay: bool, from: &str) -> Resp {
|
||||||
// 保險庫填入 on this computer's browser: the brain planned it, the person approved it; this
|
// 保險庫填入 on this computer's browser: the brain planned it, the person approved it; this
|
||||||
// one command carries that entry's secret (vault::REMOTE_TOOL); the page's host guard holds.
|
// one command carries that entry's secret (vault::REMOTE_TOOL); the page's host guard holds.
|
||||||
if tool == crate::vault::REMOTE_TOOL {
|
if tool == crate::vault::REMOTE_TOOL {
|
||||||
return Resp::json(&crate::vault::run_remote(args));
|
// (On the job's own tab, like the brain's other browser steps here.)
|
||||||
|
let job = crate::tools::args_of(args)["_job"].as_str().unwrap_or("").to_string();
|
||||||
|
return Resp::json(&crate::botbrowser::as_job(&job, || crate::vault::run_remote(args)));
|
||||||
}
|
}
|
||||||
if crate::macapps::is_mac_tool(tool) && cfg!(target_os = "macos") {
|
if crate::macapps::is_mac_tool(tool) && cfg!(target_os = "macos") {
|
||||||
let (text, ok) = crate::macapps::run(tool, args);
|
let (text, ok) = crate::macapps::run(tool, args);
|
||||||
|
|
|
||||||
138
src/vault.rs
138
src/vault.rs
|
|
@ -44,18 +44,99 @@ pub fn run_remote(args: &str) -> Value {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The vault tools the bot gets (with AnyBot's browser).
|
/// What the vault can fill right now (on the brain, where the vault lives). A kind with nothing
|
||||||
pub fn specs() -> Vec<Value> {
|
/// behind it isn't offered: a bot that patrols Threads with an empty vault was handed three fill
|
||||||
vec![
|
/// tools anyway, and a small model kept "accidentally" calling them — 171 failed fills in one
|
||||||
serde_json::json!({"name": LIST_TOOL, "description": "List what the person saved in AnyBot's 保險庫 (vault): logins (site, username, notes — never the password), payment cards (nickname, brand, last 4 digits, expiry — never the number or security code) and contact info (name, address, phones, emails). Notes say when to use an item. Use the ids with browser_fill_login / browser_fill_card / browser_fill_contact.",
|
/// turn, each answered with "open a tab first", which sent it round again.
|
||||||
"parameters": {"type": "object", "properties": {"kind": {"type": "string", "enum": ["all", "login", "card", "contact"]}, "query": {"type": "string", "description": "Words to search for"}}}}),
|
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||||
serde_json::json!({"name": TOOL, "description": "Sign in on the current tab of AnyBot's browser with a login from the person's vault (or the macOS Keychain / 1Password). You never see the password; the person approves each use. Open the login page with browser_open first; after filling, press the page's sign-in button (computer_use or ask the person) and check with browser_read.",
|
pub struct Offer {
|
||||||
"parameters": {"type": "object", "properties": {"login_id": {"type": "string", "description": "From vault_list (default: the saved login for the current site)"}, "site": {"type": "string", "description": "Domain to use (default: the current tab's)"}, "submit": {"type": "boolean", "description": "Also submit the form"}}}}),
|
pub login: bool,
|
||||||
serde_json::json!({"name": CARD_TOOL, "description": "Fill a saved payment card into the checkout form on the current tab of AnyBot's browser (card number, expiry, security code, name). You never see the number or security code; the person approves every use. Card fields inside a payment provider's frame may need the person's help. Never submit a payment without the person saying so.",
|
pub card: bool,
|
||||||
"parameters": {"type": "object", "properties": {"card_id": {"type": "string", "description": "From vault_list"}}, "required": ["card_id"]}}),
|
pub contact: bool,
|
||||||
serde_json::json!({"name": CONTACT_TOOL, "description": "Fill saved contact info (name, address, phone, email) into the form on the current tab of AnyBot's browser, e.g. a shipping or billing address.",
|
}
|
||||||
"parameters": {"type": "object", "properties": {"contact_id": {"type": "string", "description": "From vault_list"}}, "required": ["contact_id"]}}),
|
|
||||||
]
|
impl Offer {
|
||||||
|
/// From the kinds saved in the vault, and whether logins can also come from elsewhere
|
||||||
|
/// (the macOS Keychain, the 1Password CLI).
|
||||||
|
pub fn from_kinds(kinds: &[crate::vault_store::Kind], logins_elsewhere: bool) -> Offer {
|
||||||
|
use crate::vault_store::Kind;
|
||||||
|
Offer { login: logins_elsewhere || kinds.contains(&Kind::Login), card: kinds.contains(&Kind::Card), contact: kinds.contains(&Kind::Contact) }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn any(&self) -> bool {
|
||||||
|
self.login || self.card || self.contact
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The kinds the browser tool's `fill` action may name.
|
||||||
|
pub fn kinds(&self) -> Vec<&'static str> {
|
||||||
|
[("login", self.login), ("card", self.card), ("contact", self.contact)].into_iter().filter(|k| k.1).map(|k| k.0).collect()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What this computer's vault (and keychain / 1Password) can fill now.
|
||||||
|
pub fn offer() -> Offer {
|
||||||
|
let kinds: Vec<crate::vault_store::Kind> = crate::vault_store::list().map(|l| l.into_iter().map(|i| i.kind).collect()).unwrap_or_default();
|
||||||
|
Offer::from_kinds(&kinds, cfg!(target_os = "macos") || op_installed())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The 1Password CLI is on the tools' PATH.
|
||||||
|
fn op_installed() -> bool {
|
||||||
|
let exe = if cfg!(windows) { "op.exe" } else { "op" };
|
||||||
|
crate::cloudbox::tool_path().split(if cfg!(windows) { ';' } else { ':' }).filter(|d| !d.is_empty()).any(|d| std::path::Path::new(d).join(exe).is_file())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The vault tools the bot gets (with AnyBot's browser): only for what there is to fill.
|
||||||
|
pub fn specs_for(offer: &Offer) -> Vec<Value> {
|
||||||
|
if !offer.any() {
|
||||||
|
return vec![];
|
||||||
|
}
|
||||||
|
let mut v = vec![serde_json::json!({"name": LIST_TOOL, "description": "List what the person saved in AnyBot's 保險庫 (vault): logins (site, username, notes — never the password), payment cards (nickname, brand, last 4 digits, expiry — never the number or security code) and contact info (name, address, phones, emails). Notes say when to use an item. Use the ids with the browser tool's fill action. Only for signing in, paying or filling an address — never for typing into a page (that is the browser tool's type).",
|
||||||
|
"parameters": {"type": "object", "properties": {"kind": {"type": "string", "enum": ["all", "login", "card", "contact"]}, "query": {"type": "string", "description": "Words to search for"}}}})];
|
||||||
|
if offer.login {
|
||||||
|
v.push(serde_json::json!({"name": TOOL, "description": "Sign in on the current tab of AnyBot's browser with a login from the person's vault (or the macOS Keychain / 1Password). You never see the password; the person approves each use. Open the login page with browser_open first; after filling, press the page's sign-in button (computer_use or ask the person) and check with browser_read.",
|
||||||
|
"parameters": {"type": "object", "properties": {"login_id": {"type": "string", "description": "From vault_list (default: the saved login for the current site)"}, "site": {"type": "string", "description": "Domain to use (default: the current tab's)"}, "submit": {"type": "boolean", "description": "Also submit the form"}}}}));
|
||||||
|
}
|
||||||
|
if offer.card {
|
||||||
|
v.push(serde_json::json!({"name": CARD_TOOL, "description": "Fill a saved payment card into the checkout form on the current tab of AnyBot's browser (card number, expiry, security code, name). You never see the number or security code; the person approves every use. Card fields inside a payment provider's frame may need the person's help. Never submit a payment without the person saying so.",
|
||||||
|
"parameters": {"type": "object", "properties": {"card_id": {"type": "string", "description": "From vault_list"}}, "required": ["card_id"]}}));
|
||||||
|
}
|
||||||
|
if offer.contact {
|
||||||
|
v.push(serde_json::json!({"name": CONTACT_TOOL, "description": "Fill saved contact info (name, address, phone, email) into the form on the current tab of AnyBot's browser, e.g. a shipping or billing address.",
|
||||||
|
"parameters": {"type": "object", "properties": {"contact_id": {"type": "string", "description": "From vault_list"}}, "required": ["contact_id"]}}));
|
||||||
|
}
|
||||||
|
v
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A fill that names an item the vault doesn't have is answered at once — before the browser is
|
||||||
|
/// touched, so the answer is about the item and not about tabs — in words that send the bot to
|
||||||
|
/// the tool it meant (it usually wanted to type into the page).
|
||||||
|
pub fn check_ids(tool: &str, args: &str) -> Result<(), String> {
|
||||||
|
let items = crate::vault_store::list().unwrap_or_default();
|
||||||
|
check_ids_in(tool, args, &items.iter().map(|i| (i.id.as_str(), i.kind)).collect::<Vec<_>>())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn check_ids_in(tool: &str, args: &str, items: &[(&str, crate::vault_store::Kind)]) -> Result<(), String> {
|
||||||
|
use crate::vault_store::Kind;
|
||||||
|
let v = crate::tools::args_of(args);
|
||||||
|
let (field, kind, what) = match tool {
|
||||||
|
CARD_TOOL => ("card_id", Kind::Card, "付款卡"),
|
||||||
|
CONTACT_TOOL => ("contact_id", Kind::Contact, "聯絡資訊"),
|
||||||
|
_ => ("login_id", Kind::Login, "登入資訊"),
|
||||||
|
};
|
||||||
|
let id = v[field].as_str().unwrap_or("").trim();
|
||||||
|
// A login without an id is looked up by the page's site (and the keychain / 1Password).
|
||||||
|
if tool == TOOL && id.is_empty() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
if items.iter().any(|(i, k)| *i == id && *k == kind) {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let not_this = "這個工具只把使用者存在保險庫的帳密、卡號或地址填進表單,不是用來在網頁上打字。要在輸入框打字請用 browser 的 action=type(value 是要打的字),要開網址用 action=open。";
|
||||||
|
Err(if items.iter().any(|(_, k)| *k == kind) {
|
||||||
|
format!("沒有執行:保險庫裡沒有 id 為「{id}」的{what}(先用 vault_list 看 id)。{not_this}")
|
||||||
|
} else {
|
||||||
|
format!("沒有執行:保險庫裡沒有存任何{what},這一步用不上。{not_this}")
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// vault_list: what the bot may know (no passwords, card numbers or security codes).
|
/// vault_list: what the bot may know (no passwords, card numbers or security codes).
|
||||||
|
|
@ -699,6 +780,39 @@ pub(crate) fn contact_fill_text(c: &crate::vault_store::Item, got: &Value) -> Re
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_empty_vault_offers_no_fill_tools() {
|
||||||
|
use crate::vault_store::Kind;
|
||||||
|
let names = |o: &Offer| specs_for(o).iter().map(|t| t["name"].as_str().unwrap().to_string()).collect::<Vec<_>>();
|
||||||
|
// Linux with nothing saved and no 1Password: nothing to fill, nothing offered.
|
||||||
|
let none = Offer::from_kinds(&[], false);
|
||||||
|
assert!(!none.any() && specs_for(&none).is_empty());
|
||||||
|
// Only what is there.
|
||||||
|
let contacts = Offer::from_kinds(&[Kind::Contact], false);
|
||||||
|
assert_eq!(names(&contacts), [LIST_TOOL, CONTACT_TOOL]);
|
||||||
|
assert_eq!(contacts.kinds(), ["contact"]);
|
||||||
|
// Logins can come from the keychain / 1Password with nothing saved.
|
||||||
|
assert_eq!(names(&Offer::from_kinds(&[], true)), [LIST_TOOL, TOOL]);
|
||||||
|
assert_eq!(names(&Offer::from_kinds(&[Kind::Card, Kind::Login], false)), [LIST_TOOL, TOOL, CARD_TOOL]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_fill_of_an_item_that_is_not_there_says_so_first() {
|
||||||
|
use crate::vault_store::Kind;
|
||||||
|
// 「contact_id: x」 with no contacts saved: about the vault, not about tabs, and pointing
|
||||||
|
// at what the bot meant to do.
|
||||||
|
let e = check_ids_in(CONTACT_TOOL, r#"{"contact_id":"x"}"#, &[]).unwrap_err();
|
||||||
|
assert!(e.contains("沒有存任何聯絡資訊") && e.contains("action=type") && !e.contains("分頁"), "{e}");
|
||||||
|
let e = check_ids_in(CARD_TOOL, r#"{"card_id":"y"}"#, &[("c1", Kind::Card)]).unwrap_err();
|
||||||
|
assert!(e.contains("「y」") && e.contains("vault_list"), "{e}");
|
||||||
|
// An id of another kind is no id of this one.
|
||||||
|
assert!(check_ids_in(CONTACT_TOOL, r#"{"contact_id":"c1"}"#, &[("c1", Kind::Card)]).is_err());
|
||||||
|
assert!(check_ids_in(CONTACT_TOOL, r#"{"contact_id":"k1"}"#, &[("k1", Kind::Contact)]).is_ok());
|
||||||
|
// A login by site (no id) is looked up later; one by id must exist.
|
||||||
|
assert!(check_ids_in(TOOL, r#"{"site":"threads.com"}"#, &[]).is_ok());
|
||||||
|
assert!(check_ids_in(TOOL, r#"{"login_id":"zz"}"#, &[]).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn hosts_and_candidates() {
|
fn hosts_and_candidates() {
|
||||||
assert_eq!(host_of("https://accounts.Google.com/signin?x=1"), "accounts.google.com");
|
assert_eq!(host_of("https://accounts.Google.com/signin?x=1"), "accounts.google.com");
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue