From 571d07596e269ef052f8b8de963d897e6a7f46c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=80=A7=E9=A9=8A?= Date: Tue, 17 Nov 2026 14:21:09 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E7=8D=A8=E7=AB=8B=E5=AF=A9=E6=9F=A5?= =?UTF-8?q?=E6=89=BE=E5=88=B0=E7=9A=84=E5=95=8F=E9=A1=8C=EF=BC=88=E4=B8=80?= =?UTF-8?q?=EF=BC=89=EF=BC=9A=E6=89=8B=E6=A9=9F=E9=80=9A=E7=9F=A5=E7=9A=84?= =?UTF-8?q?=E5=85=81=E8=A8=B1=E3=80=81hooks=E3=80=81Linux=20=E6=B2=99?= =?UTF-8?q?=E7=9B=92?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 手機通知: - 一個帶 #answer=once 的連結就能放行正在等的請求:沒帶鑰匙的連結不回答任何事。 - 舊通知可能答到新請求(同一步連問三次編號相同、有些模型每輪從 0 編):每個請求一把隨機鑰匙;通知也不能回答「需要處理」和問題卡;整個請求放不進通知(多行的指令)就不給按鈕。 - 停在登入畫面時按通知,回答會不見;兩指放大被當成鍵盤;換對話時舊訊息一起滑進來。 Hooks: - hook 的 ask 只有在電腦上的步驟有用,連接器、App 操作、傳檔案…直接做了:現在都會問。 - hook 留一個背景程式就把一輪卡住;逾時只殺 shell、它啟動的還在跑。 - hook 改 AnyBot 欄位名(path)會被舊的 file_path 蓋回去。 - 打開一律放行、--approve once 會替人答應新增 hook。 - 管理員的 hook 改成最後跑:看得到個人 hook 改過的參數,它的拒絕算數。 Linux 沙盒:私密資料夾寫成相對路徑時,在沙盒裡對到別的資料夾,等於沒擋。 已驗證:cargo test 613 通過、clippy -D warnings 乾淨。未驗證:手機網頁那幾項沒有自動測試,要實機看。 Co-Authored-By: Claude Fable 5.2 --- mobile/index.html | 23 +++++++++++----- src/agent.rs | 16 ++++++++++- src/app.rs | 19 ++++++++++--- src/app/remote_ui.rs | 14 ++++++++-- src/hooks.rs | 65 ++++++++++++++++++++++++++++++++++---------- src/landlock.rs | 3 ++ 6 files changed, 112 insertions(+), 28 deletions(-) diff --git a/mobile/index.html b/mobile/index.html index 7655f95..578a3f3 100644 --- a/mobile/index.html +++ b/mobile/index.html @@ -842,7 +842,7 @@ try { matchMedia("(prefers-color-scheme: dark)").addEventListener("change", () = const S = { sending: [], voice: {}, relay: false, token: localStorage.getItem("anybot.token") || "", host: localStorage.getItem("anybot.host") || "", version: 0, bots: [], approvals: [], pages: [], models: [], hostName: "", mac: false, box: "", boxOn: false, role: "owner", - prevShown: 0, answer: null, sc: "", + prevShown: 0, prevFirst: "", answer: null, sc: "", open: 0, msgs: [], pending: [], quote: null, unfold: {}, openSteps: {}, detail: {}, audit: {}, settings: null, polling: false, chatSig: "", file: null, search: "", size: [0, 0], right: false, @@ -1289,7 +1289,7 @@ function chatHead() { } $("island").onclick = () => go("details", {bot: S.open}); function openChat(id) { - if (S.open !== id) { S.msgs = []; S.pending = []; S.quote = null; S.unfold = {}; S.openSteps = {}; S.chatSig = ""; S.prevShown = 0; $("msgs").innerHTML = ""; } + if (S.open !== id) { S.msgs = []; S.pending = []; S.quote = null; S.unfold = {}; S.openSteps = {}; S.chatSig = ""; S.prevShown = 0; S.prevFirst = ""; $("msgs").innerHTML = ""; } S.open = id; // Your bubbles as 聊天的顏色 on the computer says (ob.bubble): "quiet" a light grey with the // page's ink (the default), "bot" the bot's colour, "black". (An older AnyBot sends no field: its colour.) @@ -1419,7 +1419,10 @@ function renderMsgs() { let h = ""; // A message that arrived since the last draw slides up into place; the whole history on // opening a chat draws plain (no animation on every old message). - const freshFrom = S.prevShown > 0 && S.msgs.length > S.prevShown ? S.prevShown : S.msgs.length; + // (Another conversation of the same bot — its first message differs — draws plain too.) + const first = S.msgs.length ? String(S.msgs[0].at || "") + (S.msgs[0].text || "").slice(0, 40) : ""; + const same = first === S.prevFirst; S.prevFirst = first; + const freshFrom = same && S.prevShown > 0 && S.msgs.length > S.prevShown ? S.prevShown : S.msgs.length; S.prevShown = S.msgs.length; const fr = (i) => (i >= freshFrom ? " fresh" : ""); S.msgs.forEach((m, i) => { @@ -3406,7 +3409,8 @@ function openFromHash() { // Tapping 允許/拒絕 on a notification: answer it once the token is in place. const ans = h.get("answer"); // (With the request it was about: one that changed since is not answered by an old banner.) - if (ans && b && (ans === "once" || ans === "reject")) S.answer = {bot: b, answer: ans, call: h.get("call") || ""}; + // (A link with no key answers nothing: only a banner's own buttons carry one.) + if (ans && b && h.get("call") && (ans === "once" || ans === "reject")) S.answer = {bot: b, answer: ans, call: h.get("call")}; const sc = new URLSearchParams(location.search).get("sc"); if (sc) S.sc = sc; if (location.hash || location.search) history.replaceState(null, "", location.pathname); @@ -3415,13 +3419,18 @@ openFromHash(); if ("serviceWorker" in navigator) navigator.serviceWorker.addEventListener("message", (e) => { const d = e.data && e.data.open; if (!d) return; if (d.host && d.host !== S.host && S.relay) { S.host = d.host; localStorage.setItem("anybot.host", S.host); S.version = 0; } - if (d.answer && S.token && d.bot) api(base() + `api/bots/${d.bot}/answer`, {json: {answer: d.answer, call: d.ask || ""}}).then(() => toast("已從通知回覆")).catch((e) => toast(e.message)); - if (d.bot) go("chat", {bot: +d.bot}); + if (d.answer && d.ask && d.bot) { + // (Not signed in yet: kept, and sent once the phone is — apply.) + if (S.token) api(base() + `api/bots/${d.bot}/answer`, {json: {answer: d.answer, call: d.ask}}).then(() => toast("已從通知回覆")).catch((e) => toast(e.message)); + else S.answer = {bot: +d.bot, answer: d.answer, call: d.ask}; + } + if (d.bot && S.token) go("chat", {bot: +d.bot}); else if (d.bot) S.open = +d.bot; }); // iOS: the keyboard floats over the page instead of shrinking it; measure it and lift the composer. if (window.visualViewport) { const kb = () => { - const k = Math.max(0, Math.round(innerHeight - visualViewport.height - visualViewport.offsetTop)); + // (Zoomed in with two fingers the visible part is smaller too: that isn't a keyboard.) + const k = visualViewport.scale > 1.01 ? 0 : Math.max(0, Math.round(innerHeight - visualViewport.height - visualViewport.offsetTop)); document.documentElement.style.setProperty("--kb", k + "px"); }; visualViewport.addEventListener("resize", kb); diff --git a/src/agent.rs b/src/agent.rs index b8e9ce1..e0e5178 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -1756,7 +1756,7 @@ fn run_call(t: CallTurn<'_>, asked: ToolCall) -> Flow { hooks.fire("PreToolUse", Some(&call.name), input) }; let call = match &hook_word.input { - Some(v) => ToolCall { args: crate::hooks::args_back(v), ..call }, + Some(v) => ToolCall { args: crate::hooks::args_back(v, &call.args), ..call }, None => call, }; let hook_no = hook_word.block.clone().or_else(|| hook_word.permission.clone().filter(|(p, _)| p == "deny").map(|(_, r)| r)).or_else(|| hook_word.stop.clone()); @@ -1874,6 +1874,20 @@ fn run_call(t: CallTurn<'_>, asked: ToolCall) -> Flow { browser: Default::default(), }; let tool = steps::tool_for(&s); + // A hook's 「ask」: OnComputer puts it with its own question; every other tool asks here + // (a connector already allowed, an app action, a file sent out… would have gone ahead). + if tool.name() != "OnComputer" { + if let Some(why) = s.hook_word.permission.clone().filter(|(p, _)| p == "ask").map(|(_, w)| w) { + let answer = s.ask_person(ApprovalKind::Action, format!("{}(你的 hook 要先問:{})", s.what(), if why.is_empty() { "沒有說原因" } else { why.as_str() }), String::new()); + if s.cancel.load(Ordering::Relaxed) { + return Flow::End; + } + if answer == ApprovalAnswer::Reject { + s.finish("使用者拒絕了這個操作。在他傳下一則訊息之前不要再試同樣的操作,也不要換個寫法做同一件事;告訴他你停在哪裡,問他想怎麼做。", ToolStatus::Denied, None); + return Flow::Next; + } + } + } log::debug!("{} 由 {} 處理", s.call.name, tool.name()); tool.run(&mut s) } diff --git a/src/app.rs b/src/app.rs index 6c587b0..988c72b 100644 --- a/src/app.rs +++ b/src/app.rs @@ -215,6 +215,10 @@ pub struct App { doctor_out: Arc>>, /// Lines for a bot's chat that work on another thread finished (/rewind's files…). later_notes: Arc>>, + /// The key a phone banner's 允許/拒絕 must carry to answer a bot's waiting request: made + /// new for every request (the tool call's id repeats — one step may ask three times, and + /// some models number their calls from 0 every turn), and not guessable from a link. + pub(crate) ask_keys: HashMap, /// 「/compact」 summaries finished on their thread: (bot, (messages replaced, summary, first kept message's time)). #[allow(clippy::type_complexity)] compact_out: Arc)>>>, @@ -498,6 +502,7 @@ impl App { strangers: Default::default(), doctor_out: Default::default(), later_notes: Default::default(), + ask_keys: Default::default(), compact_out: Default::default(), managed: if demo { policy::Managed::default() } else { policy::read() }, settings_was_open: false, @@ -2627,7 +2632,7 @@ impl App { self.enable_direct_mode(); self.state.always_approve = true; // What the person's own turns are waiting on now goes ahead. - let waiting: Vec = self.approvals.iter().filter(|(id, a)| !self.strangers.contains(id) && crate::always::answer_for(a.kind).is_some()).map(|(id, _)| *id).collect(); + let waiting: Vec = self.approvals.iter().filter(|(id, a)| !self.strangers.contains(id) && a.tool != crate::hooks::MANAGE_TOOL && crate::always::answer_for(a.kind).is_some()).map(|(id, _)| *id).collect(); for id in waiting { self.answer(ctx, id, ApprovalAnswer::Once); } @@ -4169,6 +4174,8 @@ impl App { /// attention (the Dock icon bounces when AnyBot isn't in front, and the 提示音 rings). fn on_new_approval(&mut self, ctx: &egui::Context, bot_id: u64) { self.popup_hidden.remove(&bot_id); + let key = crate::httpd::random_hex(16); + self.ask_keys.insert(bot_id, key.clone()); // (A brain on a server has nobody to hear it.) let chime = !self.demo && !self.headless && self.state.alert_sound; if chime { @@ -4180,6 +4187,9 @@ impl App { if self.state.notify && self.away() { if let (Some(b), Some(a)) = (self.state.bot(bot_id), self.approvals.get(&bot_id)) { let mut what = a.reason.split('\n').next().unwrap_or("").to_string(); + // 允許 on a banner must be about all of it: a request that doesn't fit there + // whole (a command of several lines) is answered in the chat. + let whole = a.reason.lines().filter(|l| !l.starts_with("(在 ")).count() <= 1 && what.chars().count() <= 170; // 「{callee} 需要你」 for a step only the person can do. let mut title = if a.kind == ApprovalKind::Handoff { format!("{}:需要你", b.name) } else { format!("{} 需要你允許", b.name) }; if a.kind == ApprovalKind::Question { @@ -4192,8 +4202,8 @@ impl App { } // 允許/拒絕 on the banner only for a request to allow (a question, or a step // only the person can do, opens the chat). - if matches!(a.kind, ApprovalKind::Action | ApprovalKind::EnableTools | ApprovalKind::EnableThisComputer) { - crate::remote::notify_approval(&title, &what, bot_id, &a.call_id); + if whole && a.tool != crate::hooks::MANAGE_TOOL && matches!(a.kind, ApprovalKind::Action | ApprovalKind::EnableTools | ApprovalKind::EnableThisComputer) { + crate::remote::notify_approval(&title, &what, bot_id, &key); } else { crate::remote::notify(crate::remote::Notice::Need, &title, &what, bot_id); } @@ -6175,7 +6185,8 @@ impl App { // an app action waiting on its card is answered too — it used to wait to the limit.) if let Some(a) = app.approvals.get(&id) { let (kind, tool, reason) = (a.kind, a.tool.clone(), a.reason.clone()); - let yes = opts.approve && crate::always::answer_for(kind).is_some(); + // (A hook change is the person's to allow: it would run outside the sandbox from then on.) + let yes = opts.approve && tool != crate::hooks::MANAGE_TOOL && crate::always::answer_for(kind).is_some(); if json { line(serde_json::json!({"type": "approval", "tool": tool, "reason": reason, "answer": if yes { "once" } else { "reject" }})); } else { diff --git a/src/app/remote_ui.rs b/src/app/remote_ui.rs index 936f182..7df3b38 100644 --- a/src/app/remote_ui.rs +++ b/src/app/remote_ui.rs @@ -613,7 +613,9 @@ impl App { Cmd::Answer { bot, answer, text, call } => { // From a notification banner: only the request it showed (it may have been // answered since, and another one be waiting). - if !call.is_empty() && self.approvals.get(&bot).map(|a| a.call_id.as_str()) != Some(call.as_str()) { + // (And only a request to allow: 「允許」 on a hand-off would mean 「我完成了」.) + let allowable = self.approvals.get(&bot).is_some_and(|a| matches!(a.kind, ApprovalKind::Action | ApprovalKind::EnableTools | ApprovalKind::EnableThisComputer)); + if !call.is_empty() && !(allowable && self.ask_keys.get(&bot) == Some(&call)) { self.goal_note(bot, "通知上的「允許/拒絕」沒有用上:那個請求已經不在等了(回答過,或換成了別的)。打開聊天看現在在等什麼。"); return; } @@ -1853,7 +1855,9 @@ mod phone_act_tests { let bot = app.state.bots[0].id; let wait = |app: &mut App, call: &str| { let (tx, rx) = std::sync::mpsc::channel(); - app.approvals.insert(bot, crate::providers::Approval { call_id: call.into(), tool: "shell".into(), reason: "刪除 build".into(), grant: String::new(), reply: tx, kind: ApprovalKind::Action }); + // (The same tool call asking again, as one step does: a new key each time.) + app.approvals.insert(bot, crate::providers::Approval { call_id: "c0".into(), tool: "shell".into(), reason: "刪除 build".into(), grant: String::new(), reply: tx, kind: ApprovalKind::Action }); + app.ask_keys.insert(bot, call.into()); rx }; let rx = wait(&mut app, "call-2"); @@ -1863,6 +1867,12 @@ mod phone_act_tests { assert!(app.state.bot(bot).unwrap().messages.iter().any(|m| m.note && m.text.contains("沒有用上"))); app.remote_cmd(&ctx, Cmd::Answer { bot, answer: "once".into(), text: String::new(), call: "call-2".into() }); assert!(matches!(rx.try_recv(), Ok(ApprovalAnswer::Once))); + // A hand-off isn't answered from a banner, even with its key. + let (tx, rx2) = std::sync::mpsc::channel(); + app.approvals.insert(bot, crate::providers::Approval { call_id: "c0".into(), tool: "x".into(), reason: "登入".into(), grant: String::new(), reply: tx, kind: ApprovalKind::Handoff }); + app.ask_keys.insert(bot, "k".into()); + app.remote_cmd(&ctx, Cmd::Answer { bot, answer: "once".into(), text: String::new(), call: "k".into() }); + assert!(rx2.try_recv().is_err()); // From the app itself (no request id): as before. let rx = wait(&mut app, "call-3"); app.remote_cmd(&ctx, Cmd::Answer { bot, answer: "reject".into(), text: String::new(), call: String::new() }); diff --git a/src/hooks.rs b/src/hooks.rs index 116240a..ac5e099 100644 --- a/src/hooks.rs +++ b/src/hooks.rs @@ -97,7 +97,8 @@ pub fn read_config(p: &std::path::Path) -> Result { } } -/// Both files' hooks, the admin's first. +/// Both files' hooks. The person's run first and the admin's last: the admin's see the +/// arguments as a personal hook left them, and the strictest word (deny over ask over allow) stands. #[derive(Clone, Debug, Default)] pub struct Hooks { pub admin: Config, @@ -135,7 +136,7 @@ impl Hooks { /// The hooks for this event (and tool), in order. fn matching(&self, event: &str, tool: Option<&str>) -> Vec { let mut out = vec![]; - for c in [&self.admin, &self.mine] { + for c in [&self.mine, &self.admin] { for g in c.hooks.get(event).into_iter().flatten() { if tool.is_none_or(|t| matches(&g.matcher, t)) { out.extend(g.hooks.iter().cloned()); @@ -214,6 +215,11 @@ fn run_one(h: &Hook, input: &Value) -> Result { c.current_dir(h); } c.stdin(std::process::Stdio::piped()).stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::piped()); + #[cfg(unix)] + { + use std::os::unix::process::CommandExt; + c.process_group(0); + } let mut child = c.spawn().map_err(|e| format!("無法執行:{e}"))?; // (On a thread: a hook that never reads its input mustn't hold the turn past its timeout.) if let Some(mut si) = child.stdin.take() { @@ -222,14 +228,33 @@ fn run_one(h: &Hook, input: &Value) -> Result { let _ = si.write_all(text.as_bytes()); }); } + // What it printed, gathered as it comes: a program the hook left running keeps the pipe + // open, and the hook's own end must not wait for it. let read = |s: Option>| { - std::thread::spawn(move || { - let mut b = String::new(); - if let Some(mut s) = s { - let _ = s.read_to_string(&mut b); + let got = std::sync::Arc::new(std::sync::Mutex::new(Vec::::new())); + let g = got.clone(); + let t = std::thread::spawn(move || { + let Some(mut s) = s else { return }; + let mut chunk = [0u8; 8192]; + while let Ok(n) = s.read(&mut chunk) { + if n == 0 { + break; + } + let mut g = g.lock().unwrap_or_else(|e| e.into_inner()); + if g.len() < 1024 * 1024 { + g.extend_from_slice(&chunk[..n]); + } } - b - }) + }); + (got, t) + }; + let text = |(got, t): (std::sync::Arc>>, std::thread::JoinHandle<()>)| { + let t0 = Instant::now(); + while !t.is_finished() && t0.elapsed() < Duration::from_millis(300) { + std::thread::sleep(Duration::from_millis(10)); + } + let b = got.lock().unwrap_or_else(|e| e.into_inner()).clone(); + String::from_utf8_lossy(&b).into_owned() }; let out = read(child.stdout.take().map(|s| Box::new(s) as Box)); let err = read(child.stderr.take().map(|s| Box::new(s) as Box)); @@ -239,13 +264,14 @@ fn run_one(h: &Hook, input: &Value) -> Result { break st.code(); } if t0.elapsed() > Duration::from_secs(secs) { + crate::tools::kill_tree(child.id()); let _ = child.kill(); let _ = child.wait(); return Err(format!("超過 {secs} 秒沒有結束,停掉了")); } std::thread::sleep(Duration::from_millis(20)); }; - Ok(Ran { code, out: out.join().unwrap_or_default(), err: err.join().unwrap_or_default() }) + Ok(Ran { code, out: text(out), err: text(err) }) } /// What the hooks of one event said, put together. @@ -261,7 +287,7 @@ pub struct Said { pub context: String, /// PostToolUse: the result the bot reads instead. pub output: Option, - /// "continue": false — the whole turn stops, and why. + /// "continue": false, and why: PreToolUse — this step isn't run; UserPromptSubmit — this turn isn't. pub stop: Option, } @@ -391,13 +417,17 @@ pub fn tool_input(args: &str) -> Value { v } -/// The arguments a PreToolUse hook gave, back in AnyBot's names. -pub fn args_back(v: &Value) -> String { +/// The arguments a PreToolUse hook gave, back in AnyBot's names. A field has two names for the +/// hook (tool_input): whichever of them it changed from `before` (the arguments it was given) counts. +pub fn args_back(v: &Value, before: &str) -> String { + let was = crate::tools::args_of(before); let mut v = v.clone(); if let Some(o) = v.as_object_mut() { for (ours, theirs) in [("path", "file_path"), ("old_text", "old_string"), ("new_text", "new_string")] { if let Some(x) = o.remove(theirs) { - o.insert(ours.into(), x); + if !o.contains_key(ours) || x != was[ours] { + o.insert(ours.into(), x); + } } } } @@ -574,7 +604,10 @@ mod tests { assert_eq!(said.permission.as_ref().map(|p| p.0.as_str()), Some("allow")); let asks = cmd("PreToolUse", "Edit|Write", r#"echo '{"hookSpecificOutput":{"permissionDecision":"ask","permissionDecisionReason":"改檔前問我"}}'"#); assert_eq!(pre(&asks, "edit_file", json!({"path": "a", "new_text": "x"})).permission, Some(("ask".into(), "改檔前問我".into()))); - assert_eq!(args_back(&json!({"file_path": "b.txt", "new_string": "y"})), json!({"path": "b.txt", "new_text": "y"}).to_string()); + assert_eq!(args_back(&json!({"file_path": "b.txt", "new_string": "y"}), "{}"), json!({"path": "b.txt", "new_text": "y"}).to_string()); + // The hook changed AnyBot's name and left Claude Code's as it was: its change counts. + assert_eq!(args_back(&json!({"path": "/safe/x", "file_path": "/etc/x"}), r#"{"path":"/etc/x"}"#), json!({"path": "/safe/x"}).to_string()); + assert_eq!(args_back(&json!({"path": "/etc/x", "file_path": "/safe/y"}), r#"{"path":"/etc/x"}"#), json!({"path": "/safe/y"}).to_string()); } /// A hook's own trouble (a crash, a timeout, nonsense) changes nothing. @@ -587,6 +620,10 @@ mod tests { let t0 = Instant::now(); assert_eq!(pre(&slow, "shell", json!({"command": "ls"})), Said::default()); assert!(t0.elapsed() < Duration::from_secs(4)); + // A program the hook leaves running doesn't hold the turn. + let t0 = Instant::now(); + assert_eq!(pre(&cmd("PreToolUse", "", "sleep 20 & echo '{}'"), "shell", json!({"command": "ls"})), Said::default()); + assert!(t0.elapsed() < Duration::from_secs(5)); assert!(!matches("[", "shell") && matches("", "x") && matches("mcp__.*", "mcp__gitlab__get")); // A big event to a hook that never reads it: its timeout still ends it. let t0 = Instant::now(); diff --git a/src/landlock.rs b/src/landlock.rs index e68f792..6849e23 100644 --- a/src/landlock.rs +++ b/src/landlock.rs @@ -208,6 +208,9 @@ pub fn wrap(cmd: &str, spec: &Spec) -> Option { if !active() || spec.hidden.is_empty() { return None; } + // (Whole paths: the sandbox starts in the command's work folder, not where AnyBot is.) + let whole = |v: &[PathBuf]| v.iter().map(|p| std::path::absolute(p).unwrap_or_else(|_| p.clone())).collect::>(); + let spec = Spec { hidden: whole(&spec.hidden), readable: whole(&spec.readable), no_write: whole(&spec.no_write), work: std::path::absolute(&spec.work).unwrap_or_else(|_| spec.work.clone()) }; let mut c = std::process::Command::new(helper()?); c.arg(ARG).args(spec.to_args()).args(["--", "/bin/sh", "-c", cmd]); Some(c)