From 9bb9e698a6990240d2c849db046e215902e7f943 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 12:43:52 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E7=9B=A3=E7=9C=8B=EF=BC=9Ashell=20?= =?UTF-8?q?=E5=8A=A0=20monitor=EF=BC=8C=E6=8C=87=E4=BB=A4=E6=AF=8F?= =?UTF-8?q?=E5=8D=B0=E5=87=BA=E6=96=B0=E7=9A=84=E4=B8=80=E8=A1=8C=E5=B0=B1?= =?UTF-8?q?=E5=8F=AB=E9=86=92=20Bot=20=E4=B8=80=E6=AC=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 指令馬上放背景;一秒內印出的併成一次,最多列 20 行,標明「這是指令的輸出,不是使用者說的話」;Bot 閒著就開一輪,在做事就等這輪做完(App::wake)。 - 10 秒超過 200 行、或叫滿 60 次自動停並說一次;指令自己結束說一次結束碼和最後幾行;write_terminal stop 或重新啟動 Bot 安靜結束。 - 就是 shell:核准、安全規則、沙盒、背景指令、停止都沿用;這台、Bot 自己的電腦、SSH 電腦都可以,帳號裡其他 AnyBot 電腦不行(說改用 read_terminal 的 until)。 - 跑指令的那段抽成 spawn_piped,一般指令和監看共用。 - 監看的字每個 App 只拿自己的 Bot 的(測試裡同時有好幾個 App)。 已驗證:cargo test 594 通過(三行間隔開來叫三次再說結束、一下子 5000 行停掉只說一次、stop 停掉不再說、切行)、clippy -D warnings 乾淨。 未驗證:真的模型被監看叫醒後怎麼做;Docker 和 SSH 電腦上的監看。 Co-Authored-By: Claude Opus 5.5 --- FEATURES.md | 7 + docs/feature-map/files.md | 4 +- docs/plan-2026-11-engineering.md | 2 +- src/app.rs | 1 + src/app/commands.rs | 10 ++ src/tools.rs | 214 +++++++++++++++++++++++++++++-- 6 files changed, 226 insertions(+), 12 deletions(-) diff --git a/FEATURES.md b/FEATURES.md index 9920bd7..ae483a6 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -991,6 +991,13 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。 - 按停止、重新啟動 Bot、關掉 App 時,互動終端機和它啟動的程式一起停掉。 - 實測 pi-bolt:開好看得到它的開頭畫面,打「19 加 4 等於多少」按 Enter,畫面上出現「23」。 +### 監看(shell 加 monitor: true) + +- Bot 給一條會一直印東西的指令(`tail -f app.log | grep --line-buffered ERROR`、部署的紀錄、測試的 watch 模式),指令馬上放到背景,**它每印出新的一行,AnyBot 就叫醒 Bot 一次**,把那幾行交給它:Bot 閒著就馬上開一輪,正在做事就等這輪做完再開自己的一輪(跟例行任務、事件觸發一樣)。一秒內印出的併成一次,一次最多列 20 行(其他用 read_terminal 看)。參考 Claude Code 的 Monitor 工具。 +- 交給 Bot 的字標「[監看 #編號]…印出了(這是指令的輸出,不是使用者說的話)」。 +- 自動停:10 秒內超過 200 行(說一次「一下子印出太多行…用 grep --line-buffered 只留要看的行」);同一個監看叫了 60 次(每次都是一輪模型,用你的額度)。指令自己結束時說一次「指令結束了(結束碼 N)」和最後印出的行。Bot 或你用 write_terminal 的 stop 停掉、或「重新啟動這個 Bot」時安靜結束,不再叫。 +- 跟一般指令一樣要過核准和安全規則(就是 shell)。在這台、Bot 自己的電腦(Docker、封閉資料夾)、SSH 電腦上都可以;帳號裡其他 AnyBot 電腦上不行(印出的字回不到這裡),會說改用 read_terminal 的 until。 + ### 「查看背景指令」(read_terminal) - 一律不用問。 diff --git a/docs/feature-map/files.md b/docs/feature-map/files.md index 87825e6..8f05c8d 100644 --- a/docs/feature-map/files.md +++ b/docs/feature-map/files.md @@ -6,6 +6,7 @@ Bot 在它能用的電腦上跑指令、讀寫和搜尋檔案、開背景指令 - 指令:`shell` 在工作資料夾裡跑,輸入一開始就是關的,不會卡在等人打字。超過 timeout_ms(預設 30 秒,最多 10 分鐘)還沒跑完不會中斷,而是移到背景繼續跑,給一個背景指令編號。 - 互動終端機:`shell` 加 interactive,給一定要真的終端機的程式(全螢幕介面、會問問題的、編輯器);用 `write_terminal` 打字和按鍵,`read_terminal` 看畫面。 +- 監看:`shell` 加 monitor,指令馬上放背景,它每印出新的一行就叫醒 Bot 一次(一秒內的併一次,最多列 20 行);閒著馬上開一輪,在做事就等這輪做完。10 秒超過 200 行或叫滿 60 次自動停;指令結束說一次;stop 停掉的不再說。 - 背景指令:`read_terminal`(id;wait_ms 最多 120 秒,等到有新東西又安靜下來;until 等某段字出現);`write_terminal` 加 stop 停掉它和它啟動的所有程式。 - 檔案:`list_dir` 看資料夾;`read_file` 讀(每行有行號,用 offset、limit 分段,檔案最大 8 MB);`search` 找字(結果是「路徑:行號:內容」,有 ripgrep 時可以用正規表示式);`edit_file` 改(old_text 必須剛好出現一次;old_text 留空就是新建或整個覆寫)。 - 工作資料夾:這台電腦是 Bot 設定的「起始資料夾」(沒填就是家目錄);Bot 自己的電腦是它自己的資料夾;SSH 電腦是設定的資料夾或對方的家目錄。 @@ -24,7 +25,7 @@ Bot 在它能用的電腦上跑指令、讀寫和搜尋檔案、開背景指令 ## 怎麼操作 - Bot:先用 `list_dir`、`search`、`read_file` 看清楚再動手,改檔案用 `edit_file`。跑很久的指令讓它進背景,再用 `read_terminal` 的 wait_ms 等,不要一直重查;指令列的 AI 工具用它們的非互動模式(例如 `claude -p "…"`)。一定要看終端機畫面時才用 interactive,用完關掉。每個工具都有 `computer`。交結果用 `send_file`,不要只說檔案在哪;要使用者馬上看到用 `open_for_person`;要公開網址用 `publish_site`(path,name 只用英文字母、數字和 -)。除了 `send_file`,這些都屬於「檔案與指令」能力。結果太長被截(只留開頭和結尾,中間寫「完整內容用 read_result 讀:id=…」)或較早的結果被收起時,用 `read_result`(id、from、chars,一次最多兩萬字)讀完整的,不要為了看完整的再做一次那一步(每個 Bot 都有,完整結果留 7 天)。 -- 驗證:請 Bot 在它自己的電腦寫一個 report.md 傳給你,聊天要出現檔案卡片,點開看得到內容;請它讀這台電腦工作資料夾外的檔案,要跳出「讀取工作資料夾以外的地方:…」;請它跑 `sleep 40; echo done`,要說已移到背景,再用 `read_terminal` 等到 done。自動測試:`cargo test tools::`、`cargo test pty::`、`cargo test agent::`、`cargo test preview::`、`cargo test app::files_ui::`、`cargo test rewind`。請 Bot 改兩個檔案,再打「/rewind」選那一句,兩個檔案要回到原本的內容、那句話回到輸入框。 +- 驗證:請 Bot 在它自己的電腦寫一個 report.md 傳給你,聊天要出現檔案卡片,點開看得到內容;請它讀這台電腦工作資料夾外的檔案,要跳出「讀取工作資料夾以外的地方:…」;請它跑 `sleep 40; echo done`,要說已移到背景,再用 `read_terminal` 等到 done。自動測試:`cargo test tools::`、`cargo test pty::`、`cargo test agent::`、`cargo test preview::`、`cargo test app::files_ui::`、`cargo test rewind`、`cargo test a_watched_command`。請 Bot 改兩個檔案,再打「/rewind」選那一句,兩個檔案要回到原本的內容、那句話回到輸入框。 ## 陷阱 @@ -37,5 +38,6 @@ Bot 在它能用的電腦上跑指令、讀寫和搜尋檔案、開背景指令 - `open_for_person` 不打開程式或指令檔(打開就會執行),改用 `send_file`;AnyBot 在伺服器上時,網址會在使用者正在用的那台電腦打開(不知道是哪台就打不開),檔案打不開,也改用 `send_file`。 - SSH 電腦上的檔案不能直接 `send_file`、`open_for_person` 或 `publish_site`;帳號裡其他電腦的檔案可以 `send_file`(最多 20 MB),但不能打開或發佈。先複製到 Bot 自己的電腦。 - `publish_site`:任何知道網址的人都看得到。每個網站名字第一次會問(工作資料夾外的每次都問);最多 500 個檔案、25 MB;點開頭的檔案、node_modules、機密檔案、指到資料夾外的連結會略過;一定要有 index.html。 +- 監看每叫一次就是一輪模型、用使用者的額度:先用 grep --line-buffered 篩到只剩要看的行。帳號裡其他 AnyBot 電腦上不能監看。 - 檢查點只記 `edit_file` 改的:用 `shell` 改的(cat >、sed -i、git、npm…)不在裡面,帳號裡其他 AnyBot 電腦上的檔案也不在;超過 2 MB 的檔案不存,退回時會說沒辦法還原。要能退回,改檔案就用 `edit_file`。 - 按停止會停掉正在跑的那一步,和這個 Bot 的互動終端機(連同它們啟動的程式);一般的背景指令(例如故意開著的伺服器)會繼續跑。「重新啟動這個 Bot」停掉這個 Bot 的全部背景指令,關掉 App 全部停掉。整個 AnyBot 同時最多 24 個背景指令在跑,滿了新的不會留在背景(會先停掉),用不到的用 stop 關掉。 diff --git a/docs/plan-2026-11-engineering.md b/docs/plan-2026-11-engineering.md index 15b47ff..f105795 100644 --- a/docs/plan-2026-11-engineering.md +++ b/docs/plan-2026-11-engineering.md @@ -105,7 +105,7 @@ - 做法:`SessionStart`、`UserPromptSubmit`、`PreToolUse`(回 allow/ask/deny,可以改參數)、`PostToolUse`(可以改 Bot 讀到的結果)、`Stop`(可以叫它繼續)、`Notification`。設定檔放在資料夾的 `hooks/`,或管理員的 policy 位置(MDM 可推);hook 是指令或 HTTP。hook 自己出錯時照常做,紀錄寫清楚。 - 做完:一個 PreToolUse hook 擋 `rm`、一個改參數、一個 Stop hook 讓它多做一輪,都有測試。 -### M3. monitor 工具 ⬜ +### M3. monitor 工具 ✅(做成 shell 的 monitor 參數:核准、安全規則、背景指令、停止都沿用;Bot 在做事時等這輪做完再叫,不插進正在做的那一輪) - 做法:Bot 給一條指令,每輸出一行就變成一則通知/訊息;自動 line-buffered;一次失敗不停;太多行自動停並說明。 - 做完:`tail -f` 一個檔案,寫三行收到三則;一秒寫一千行會自動停。 diff --git a/src/app.rs b/src/app.rs index d51b4c2..4a01efa 100644 --- a/src/app.rs +++ b/src/app.rs @@ -5980,6 +5980,7 @@ impl App { // 會議錄音 turned into text here go to their bot (a brain on a server has no window). self.meetings_poll(ctx); self.tick_routines(ctx); + self.monitor_tick(ctx); self.tick_asks(ctx); self.tick_branches(ctx); self.watchdog(); diff --git a/src/app/commands.rs b/src/app/commands.rs index f5d7ac3..4330a19 100644 --- a/src/app/commands.rs +++ b/src/app/commands.rs @@ -96,6 +96,16 @@ impl App { } } + /// 監看 (shell with monitor): what watched commands printed wakes their bots — a turn now, + /// or one of its own after the one it is in. + pub(super) fn monitor_tick(&mut self, ctx: &egui::Context) { + let c = ctx.clone(); + crate::tools::set_monitor_repaint(Arc::new(move || c.request_repaint())); + for (bot_id, text) in crate::tools::monitor_take(|b| self.state.bot(b).is_some()) { + self.wake(ctx, bot_id, Message { wake: true, ..Message::user(&text) }); + } + } + /// The points 「/rewind」 can go back to: the person's messages in this conversation, newest /// first (index in the chat, its time, its words). fn rewind_points(&self, bot_id: u64) -> Vec<(usize, i64, String)> { diff --git a/src/tools.rs b/src/tools.rs index 45ef254..9974057 100644 --- a/src/tools.rs +++ b/src/tools.rs @@ -60,7 +60,8 @@ pub fn specs() -> Vec { "parameters": {"type": "object", "properties": { "command": {"type": "string"}, "timeout_ms": {"type": "integer", "description": "How long to wait before moving it to the background (default 30000). Interactive: how long to wait for its first screen (at most 15000)."}, - "interactive": {"type": "boolean", "description": "Run in a real terminal you can see and type into (default false)."}}, "required": ["command"]}}), + "interactive": {"type": "boolean", "description": "Run in a real terminal you can see and type into (default false)."}, + "monitor": {"type": "boolean", "description": "Watch it (監看): it goes to the background at once and every new line it prints wakes you with those lines (a second's lines come together) — e.g. `tail -f app.log | grep --line-buffered ERROR`, a deploy's log, a test watcher. Filter it to the lines that matter: too many lines (over 200 in 10 s) stop it. Stop it with write_terminal stop. Not on another AnyBot of the account."}}, "required": ["command"]}}), json!({"name": "read_terminal", "description": "Look at a background command: its latest output, or a 互動終端機's screen. wait_ms waits (up to 120000) until it shows something new and goes quiet, or until the text in `until` appears, or it ends — instead of checking again and again.", "parameters": {"type": "object", "properties": {"id": {"type": "integer"}, "wait_ms": {"type": "integer"}, "until": {"type": "string", "description": "Return as soon as this text is on the screen / in the output."}}, "required": ["id"]}}), json!({"name": "write_terminal", "description": "Type into a 互動終端機 (a command started with interactive=true): text (each new line presses Enter) and/or keys, then see its screen once it settles (wait_ms, default 4000, up to 120000). close=true sends Ctrl-D. A plain command's input is closed: it can't be typed into.", @@ -1682,6 +1683,7 @@ pub fn run_on(name: &str, args: &str, target: &Target, cancel: &AtomicBool, ids: }; match &target.place { Place::Local { workdir } => run(name, args, workdir, cancel, ids), + Place::Device { .. } if name == "shell" && monitor_of(&v) => ("監看不能用在帳號裡的其他 AnyBot 電腦上(它印出的字回不到這裡叫你):改用 read_terminal 的 until 等某段字出現。".into(), false), Place::Device { host, dir } => { // The device runs the tool in the bot's work folder (its own home when unset), and // must answer before the relay gives up at 35 s: long commands move to the @@ -1720,7 +1722,7 @@ pub fn run_on(name: &str, args: &str, target: &Target, cancel: &AtomicBool, ids: } if name == "shell" { let home = dirs::home_dir().unwrap_or_else(|| PathBuf::from("/Users")); - return done(shell(&arg_str(&v, "command"), root, timeout_of(&v), interactive_of(&v), cancel, ids, Some(&home))); + return done(shell(&arg_str(&v, "command"), root, timeout_of(&v), interactive_of(&v), monitor_of(&v), cancel, ids, Some(&home))); } run(name, args, root, cancel, ids) } @@ -1797,6 +1799,9 @@ pub fn run_on(name: &str, args: &str, target: &Target, cancel: &AtomicBool, ids: let tty = name == "shell" && interactive_of(&v); let wrapper = wrapper_for(place, &remote, name == "shell", tty, &job).unwrap_or_default(); let kill = matches!(place, Place::Box { .. }).then(|| crate::cloudbox::exec_kill_argv(&job)); + if name == "shell" && monitor_of(&v) { + return done(start_monitor(build_wrapper_command(&wrapper, &ids.conversation, &ids.request), &remote, ids, kill)); + } done(shell_wrapped(&wrapper, &remote, timeout_of(&v), tty, cancel, ids, kill)) } } @@ -1932,7 +1937,7 @@ pub fn run(name: &str, args: &str, workdir: &Path, cancel: &AtomicBool, ids: &Ru v.get("limit").and_then(Value::as_u64).map(|l| l as usize).unwrap_or(READ_DEFAULT_LINES), ), "edit_file" => edit_file(&resolve(workdir, &arg_str(&v, "path")), &arg_str(&v, "old_text"), &arg_str(&v, "new_text")), - "shell" => shell(&arg_str(&v, "command"), workdir, timeout_of(&v), interactive_of(&v), cancel, ids, None), + "shell" => shell(&arg_str(&v, "command"), workdir, timeout_of(&v), interactive_of(&v), monitor_of(&v), cancel, ids, None), "read_terminal" => read_terminal(v.get("id").and_then(Value::as_u64).unwrap_or(0), v.get("wait_ms").and_then(Value::as_u64).unwrap_or(0), &arg_str(&v, "until")), "write_terminal" if v.get("stop").and_then(Value::as_bool).unwrap_or(false) => stop_terminal(v.get("id").and_then(Value::as_u64).unwrap_or(0)), "write_terminal" => write_terminal(v.get("id").and_then(Value::as_u64).unwrap_or(0), &arg_str(&v, "input"), &keys_of(&v), v.get("close").and_then(Value::as_bool).unwrap_or(false), v.get("wait_ms").and_then(Value::as_u64).unwrap_or(0)), @@ -2140,9 +2145,12 @@ fn edit_file(p: &Path, old: &str, new: &str) -> Result { } } -fn shell(cmd: &str, workdir: &Path, timeout_ms: u64, interactive: bool, cancel: &AtomicBool, ids: &RunIds, seal: Option<&Path>) -> Result { +#[allow(clippy::too_many_arguments)] +fn shell(cmd: &str, workdir: &Path, timeout_ms: u64, interactive: bool, monitor: bool, cancel: &AtomicBool, ids: &RunIds, seal: Option<&Path>) -> Result { let command = build_command_sealed(cmd, workdir, &protected_dirs(), &readable_dirs(), seal, &ids.conversation, &ids.request); - let r = if interactive { run_terminal(command, cmd, first_look_ms(timeout_ms), cancel, ids, None) } else { run_command(command, cmd, timeout_ms, cancel, ids, None) }; + let r = if monitor { + start_monitor(command, cmd, ids, None) + } else if interactive { run_terminal(command, cmd, first_look_ms(timeout_ms), cancel, ids, None) } else { run_command(command, cmd, timeout_ms, cancel, ids, None) }; // (The bot's own sealed computer keeps every command in the sandbox: no hints about outside.) let note = |out: &str| sandbox_note(cmd, out).filter(|_| seal.is_none()).map(|n| format!("{out}\n{n}")).unwrap_or_else(|| out.to_string()); match r { @@ -2167,6 +2175,10 @@ fn first_look_ms(timeout_ms: u64) -> u64 { } /// Whether a shell call asks for a 互動終端機. +fn monitor_of(v: &Value) -> bool { + v.get("monitor").and_then(Value::as_bool).unwrap_or(false) +} + fn interactive_of(v: &Value) -> bool { v.get("interactive").and_then(Value::as_bool).unwrap_or(false) } @@ -2179,11 +2191,12 @@ fn keys_of(v: &Value) -> Vec { } } -fn run_command(mut command: Command, cmd: &str, timeout_ms: u64, cancel: &AtomicBool, ids: &RunIds, kill: Option>) -> Result { +/// Start a plain command: its input closed at once (as if from /dev/null: a program that reads its +/// input to the end — `pi-bolt -p`, `cat`, a script piped to python — goes on instead of waiting +/// forever for words that never come; one that needs typing runs as a 互動終端機), its output and +/// errors gathered in one place as they come (the newest 4 MB). +fn spawn_piped(mut command: Command) -> Result<(std::process::Child, u32, Arc>), String> { let mut child = command.spawn().map_err(|e| format!("無法執行:{e}"))?; - // Its input is closed at once (as if from /dev/null): a program that reads its input to the - // end — `pi-bolt -p`, `cat`, a script piped to python — goes on instead of waiting forever - // for words that never come. One that needs typing runs as a 互動終端機 (interactive). drop(child.stdin.take()); let root = child.id(); let output = Arc::new(Mutex::new(String::new())); @@ -2204,6 +2217,11 @@ fn run_command(mut command: Command, cmd: &str, timeout_ms: u64, cancel: &Atomic } }); } + Ok((child, root, output)) +} + +fn run_command(command: Command, cmd: &str, timeout_ms: u64, cancel: &AtomicBool, ids: &RunIds, kill: Option>) -> Result { + let (mut child, root, output) = spawn_piped(command)?; let start = Instant::now(); loop { if let Ok(Some(status)) = child.try_wait() { @@ -2405,12 +2423,146 @@ fn stop_terminal(id: u64) -> Result { if exit.lock().unwrap().is_some() { return Ok(format!("背景指令 #{id} 本來就結束了。")); } + monitor_quiet(id); kill_tree(root); child.lock().unwrap().kill(); kill_far(&far); Ok(format!("已停止背景指令 #{id}(連同它啟動的程式)。")) } +// ---------- 監看 (shell with monitor, M3) ---------- +// A command watched: it goes to the background at once, and every new line it prints wakes its +// bot with those lines (the lines of one second together, at most MONITOR_BATCH_LINES shown) — +// a turn now when it is idle, a turn of its own after the one it is in (App::wake). Like Claude +// Code's Monitor tool. Too many lines (MONITOR_MAX_LINES in MONITOR_WINDOW) or wakes +// (MONITOR_MAX_WAKES) stop it, said once; its end is said once; a stop (write_terminal, the +// bot restarted) ends it quietly. + +/// Lines shown in one wake (the rest: read_terminal). +pub const MONITOR_BATCH_LINES: usize = 20; +/// More lines than this in MONITOR_WINDOW stop it. +pub const MONITOR_MAX_LINES: usize = 200; +const MONITOR_WINDOW: Duration = Duration::from_secs(10); +/// One watch wakes its bot at most this many times (each wake is a turn of the model). +pub const MONITOR_MAX_WAKES: usize = 60; +/// Lines that come within this are one wake. +const MONITOR_GATHER: Duration = Duration::from_millis(1000); + +fn monitor_out() -> &'static Mutex> { + static O: OnceLock>> = OnceLock::new(); + O.get_or_init(|| Mutex::new(vec![])) +} + +fn monitor_quiet_set() -> &'static Mutex> { + static Q: OnceLock>> = OnceLock::new(); + Q.get_or_init(|| Mutex::new(Default::default())) +} + +/// A watched command stopped on purpose: its end isn't news. +fn monitor_quiet(id: u64) { + monitor_quiet_set().lock().unwrap_or_else(|e| e.into_inner()).insert(id); +} + +static MONITOR_REPAINT: OnceLock> = OnceLock::new(); + +/// How the app is told there is something to wake a bot with (set once at start). +pub fn set_monitor_repaint(f: Arc) { + let _ = MONITOR_REPAINT.set(f); +} + +/// What watched commands said since last time to the bots `mine` takes: (bot, the words to wake +/// it with). The others' stay (a second AnyBot in one process — tests — has bots of its own). +pub fn monitor_take(mine: impl Fn(u64) -> bool) -> Vec<(u64, String)> { + let mut all = monitor_out().lock().unwrap_or_else(|e| e.into_inner()); + let (taken, left): (Vec<_>, Vec<_>) = std::mem::take(&mut *all).into_iter().partition(|(b, _)| mine(*b)); + *all = left; + taken +} + +fn monitor_say(bot: u64, text: String) { + monitor_out().lock().unwrap_or_else(|e| e.into_inner()).push((bot, text)); + if let Some(r) = MONITOR_REPAINT.get() { + r(); + } +} + +/// The new complete lines in `buf` from byte `from` (all of it once the program ended), and where +/// the next read starts. Empty lines are left out. +fn new_lines(buf: &str, from: usize, ended: bool) -> (Vec, usize) { + let rest = buf.get(from..).unwrap_or(""); + let upto = if ended { rest.len() } else { rest.rfind('\n').map(|i| i + 1).unwrap_or(0) }; + let lines = rest[..upto].lines().map(|l| l.trim_end_matches('\r').to_string()).filter(|l| !l.trim().is_empty()).collect(); + (lines, from + upto) +} + +/// Start watching `cmd` for the bot whose conversation `ids` names. +fn start_monitor(command: Command, cmd: &str, ids: &RunIds, kill: Option>) -> Result { + let bot: u64 = ids.conversation.parse().map_err(|_| "監看只能在 Bot 的對話裡用".to_string())?; + if !room_for_terminal() { + return Err(NO_ROOM.into()); + } + let (child, root, output) = spawn_piped(command)?; + let child = Arc::new(Mutex::new(Proc::Std(child))); + let (exit, ended) = (Arc::new(Mutex::new(None)), Arc::new(Mutex::new(None))); + watch_exit(&child, &exit, &ended); + let id = keep_terminal(Terminal { command: cmd.to_string(), io: Io::Pipe(output.clone()), child, exit: exit.clone(), ended, kill, root, conversation: ids.conversation.clone() }); + let shown: String = cmd.chars().take(60).collect(); + std::thread::spawn(move || watch_lines(bot, id, &shown, &output, &exit)); + Ok(format!( + "已開始監看(背景指令 #{id}):它每印出新的一行,AnyBot 就叫你一次(一秒內的一起來,一次最多列 {MONITOR_BATCH_LINES} 行),不用再用 read_terminal 等它。10 秒內超過 {MONITOR_MAX_LINES} 行、或叫了你 {MONITOR_MAX_WAKES} 次會自動停。不需要了就 write_terminal(id={id}, stop=true)。" + )) +} + +fn watch_lines(bot: u64, id: u64, shown: &str, output: &Mutex, exit: &Mutex>) { + let mut from = 0; + let mut recent: std::collections::VecDeque<(Instant, usize)> = Default::default(); + let mut wakes = 0; + let head = |lines: &[String]| { + let mut t: String = lines.iter().take(MONITOR_BATCH_LINES).map(|l| format!("\n{}", l.chars().take(500).collect::())).collect(); + if lines.len() > MONITOR_BATCH_LINES { + t.push_str(&format!("\n(還有 {} 行沒列出:read_terminal(id={id}) 看)", lines.len() - MONITOR_BATCH_LINES)); + } + t + }; + loop { + std::thread::sleep(MONITOR_GATHER); + let code = *exit.lock().unwrap_or_else(|e| e.into_inner()); + let (lines, next) = new_lines(&output.lock().unwrap_or_else(|e| e.into_inner()), from, code.is_some()); + from = next; + let quiet = monitor_quiet_set().lock().unwrap_or_else(|e| e.into_inner()).contains(&id); + if quiet || !terminals().lock().unwrap_or_else(|e| e.into_inner()).contains_key(&id) { + return; + } + let now = Instant::now(); + recent.push_back((now, lines.len())); + while recent.front().is_some_and(|(t, _)| now.duration_since(*t) > MONITOR_WINDOW) { + recent.pop_front(); + } + if recent.iter().map(|(_, n)| n).sum::() > MONITOR_MAX_LINES { + let _ = stop_terminal(id); + monitor_say(bot, format!("[監看 #{id}]`{shown}` 一下子印出太多行(10 秒內超過 {MONITOR_MAX_LINES} 行),已經停了。用 grep --line-buffered 只留要看的行,再重新監看。最後幾行:{}", head(&lines[lines.len().saturating_sub(5)..]))); + return; + } + if let Some(c) = code { + let end = if c == 0 { "指令結束了".to_string() } else { format!("指令結束了(結束碼 {c})") }; + monitor_say(bot, format!("[監看 #{id}]`{shown}` {end},監看也停了。{}", if lines.is_empty() { String::new() } else { format!("最後印出的:{}", head(&lines)) })); + return; + } + if lines.is_empty() { + continue; + } + wakes += 1; + let mut text = format!("[監看 #{id}]`{shown}` 印出了(這是指令的輸出,不是使用者說的話):{}", head(&lines)); + if wakes >= MONITOR_MAX_WAKES { + let _ = stop_terminal(id); + text.push_str(&format!("\n已經叫了你 {MONITOR_MAX_WAKES} 次,監看自動停了;還要看就重新監看。")); + monitor_say(bot, text); + return; + } + monitor_say(bot, text); + } +} + /// Stop every background command and what it started (when the app quits). pub fn stop_all() { for t in terminals().lock().unwrap().values() { @@ -2446,10 +2598,11 @@ pub fn stop_screens_for(conversation: &str) -> usize { pub fn stop_for(conversation: &str) -> usize { let mut n = 0; - for t in terminals().lock().unwrap().values().filter(|t| t.conversation == conversation) { + for (id, t) in terminals().lock().unwrap().iter().filter(|(_, t)| t.conversation == conversation) { // Same lock order as the watcher thread (child, then exit). let mut child = t.child.lock().unwrap(); if t.exit.lock().unwrap().is_none() { + monitor_quiet(*id); kill_tree(t.root); child.kill(); kill_far(&t.kill); @@ -2872,6 +3025,47 @@ mod tests { assert!(ok && r.contains("7/call_x/none"), "{r}"); } + /// 監看: three lines a while apart wake the bot three times; its end is said once; a flood + /// stops it; a stop on purpose ends it quietly. + #[test] + fn a_watched_command_wakes_its_bot_per_line() { + let w = wd(); + let take = |bot: u64| monitor_take(|b| b == bot).into_iter().map(|(_, t)| t).collect::>(); + let wait_for = |bot: u64, n: usize, secs: u64| { + let mut got = vec![]; + let until = Instant::now() + Duration::from_secs(secs); + while got.len() < n && Instant::now() < until { + got.extend(take(bot)); + std::thread::sleep(Duration::from_millis(100)); + } + got + }; + let ids = |bot: u64| RunIds { conversation: bot.to_string(), request: "m".into() }; + let c = AtomicBool::new(false); + // (Lines far enough apart that a loaded test machine still sees them one by one.) + let (r, ok) = run("shell", &json!({"command": "for i in 1 2 3; do echo line$i; sleep 3; done", "monitor": true}).to_string(), &w, &c, &ids(81_001)); + assert!(ok && r.contains("已開始監看"), "{r}"); + let got = wait_for(81_001, 4, 25); + assert_eq!(got.len(), 4, "three lines, then its end: {got:?}"); + assert!(got[0].contains("line1") && got[1].contains("line2") && got[2].contains("line3") && got[3].contains("指令結束了"), "{got:?}"); + assert!(got[0].contains("不是使用者說的話") && !got[0].contains("line2")); + // A flood: stopped, said once. + let (r, ok) = run("shell", &json!({"command": "yes hello | head -n 5000; sleep 30", "monitor": true}).to_string(), &w, &c, &ids(81_002)); + assert!(ok, "{r}"); + let got = wait_for(81_002, 1, 10); + assert!(got.len() == 1 && got[0].contains("太多行"), "{got:?}"); + std::thread::sleep(Duration::from_millis(1500)); + assert!(take(81_002).is_empty(), "nothing after it stopped"); + // Stopped on purpose: no word about its end. + let (r, _) = run("shell", &json!({"command": "sleep 30", "monitor": true}).to_string(), &w, &c, &ids(81_003)); + let id: u64 = r.split('#').nth(1).and_then(|s| s.split(')').next()).and_then(|s| s.parse().ok()).expect(&r); + run("write_terminal", &json!({"id": id, "stop": true}).to_string(), &w, &c, &ids(81_003)); + std::thread::sleep(Duration::from_millis(2500)); + assert!(take(81_003).is_empty()); + assert_eq!(new_lines("a\nb\npart", 0, false), (vec!["a".to_string(), "b".to_string()], 4)); + assert_eq!(new_lines("a\nb\npart", 4, true), (vec!["part".to_string()], 8)); + } + #[test] fn sandbox_blocks_protected_folders() { if sandbox_exec().is_none() {