From e039368d6b20c53a04e97c9759e00af17169d167 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 11:09:13 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E7=B4=80=E9=8C=84=E6=AA=94=E3=80=81?= =?UTF-8?q?=E7=95=B6=E6=8E=89=E5=A0=B1=E5=91=8A=E3=80=81=E7=A7=98=E5=AF=86?= =?UTF-8?q?=E9=81=AE=E7=BD=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 參考 xai-org/grok-build(每個 session 的 debug log、xai-crash-handler、xai-grok-secrets 的 sanitizer)。工程基礎計畫的 E2–E4。 - 紀錄檔(logfile.rs):AnyBot 自己說的話寫到資料夾的 logs/anybot-YYYY-MM-DD.log(時間、等級、來源;一天一個、留 7 天、一天上限 20 MB),終端機照舊印,伺服器的 docker logs 不變。ANYBOT_LOG 設等級(預設 info),其他套件只收 warn 以上。36 個執行中的 eprintln! 改成 log::info!/warn!/error!;終端機給人看的(用法、setup 的 ✗、更新進度、截圖、測試)照舊。cargo test 不開紀錄檔。 - 當掉報告:panic hook 寫 logs/crash-時間.txt(版本、執行緒、位置、訊息、backtrace);下次打開在主要 Bot 的聊天留一行並記進待改進,每份只說一次(改名 .seen.txt);螢幕電腦跳提示。 - 秘密遮罩(secrets.rs):glpat-、ghp_/github_pat_、sk-、xai-、AKIA/ASIA、xox、AIza、私鑰區塊、Bearer/Basic、JWT,名字像 TOKEN/SECRET/PASSWORD/API_KEY 的變數值 → ••••(留前綴)。用在紀錄檔、當掉報告、手機上的步驟細節和結果。工作紀錄(oplog)不遮:當掉後要照原本的參數重做;Bot 看到的不遮。 - regex、log 改成直接相依(本來就在建置裡,沒有新的下載)。 已驗證:cargo test 557 全過;新測試 secrets:: 3 個(每種格式、變數名留著、一般文字不動)、logfile:: 4 個(等級和來源、一行的格式和遮罩、每天換檔/上限只說一次/七天前的刪掉、當掉報告遮過且只說一次)。隔離的 --serve(沒有金鑰、DOCKER_HOST 指向不存在、自己的 HOME 和資料夾)跑 10 秒:logs/anybot-2026-11-17.log 有啟動版本、手機密碼提醒、記憶整理、收到停止訊號四行,終端機一樣。 未驗證:真的 panic 寫出報告後重開看到那一行(測試直接呼叫寫報告和讀報告的函式,沒有讓程式真的當掉)。 Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 2 + Cargo.toml | 3 + FEATURES.md | 6 + docs/feature-map/garden.md | 4 + docs/plan-2026-11-engineering.md | 8 +- src/agent.rs | 16 +-- src/app.rs | 65 ++++++--- src/app/goal_ui.rs | 4 +- src/app/remote_ui.rs | 3 +- src/embed.rs | 6 +- src/lock.rs | 4 +- src/logfile.rs | 236 +++++++++++++++++++++++++++++++ src/main.rs | 6 +- src/model.rs | 2 +- src/oplog.rs | 2 +- src/preview.rs | 2 +- src/remote.rs | 4 +- src/secrets.rs | 109 ++++++++++++++ 18 files changed, 439 insertions(+), 43 deletions(-) create mode 100644 src/logfile.rs create mode 100644 src/secrets.rs diff --git a/Cargo.lock b/Cargo.lock index 53d6dfb..5d409a4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -365,6 +365,7 @@ dependencies = [ "image", "jieba-rs", "libc", + "log", "memmap2", "mermaid-rs-renderer", "objc2 0.6.5", @@ -373,6 +374,7 @@ dependencies = [ "portable-pty", "pulldown-cmark", "rcgen", + "regex", "resvg", "ring", "rodio", diff --git a/Cargo.toml b/Cargo.toml index d06c34c..7a1c16f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -70,6 +70,9 @@ pulldown-cmark = { version = "0.13", default-features = false } # vercel-labs/agent-desktop, Apache-2.0, pinned to a release. agent-desktop-core = { git = "https://github.com/vercel-labs/agent-desktop", tag = "v1.1.0" } argon2 = "0.5" +# 秘密遮罩 (secrets.rs) and the log file (logfile.rs): both were already in the build through other crates. +regex = "1" +log = "0.4" [profile.release] opt-level = 2 diff --git a/FEATURES.md b/FEATURES.md index 26508c0..f4ebcaa 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -1491,6 +1491,12 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - 工具回傳的文字、圖片都會交給 Bot;一次最多等 120 秒(估計值)。 - **在聊天裡請 Bot 加**(設定畫面能做的,聊天也能做):有「管理 App」能力的 Bot 用 `manage_connectors` 列出、新增、修改(含開關)、重新連線、移除連接器。改的就是大腦上「設定 › 整合 › 連接器」那一份(Bot 的這一輪本來就在大腦上跑),所以每台螢幕電腦和手機都看得到,不會寫到手腳電腦(例如 nobledesktop 上的 ~/.local/share/AnyBot)那邊的檔案。新增、修改、移除先跳「允許…管理連接器嗎?」卡片,列出要執行的指令或網址、環境變數和標頭;名字像金鑰的(TOKEN、KEY、SECRET、PASS、AUTH…)和密碼顯示成「••••(已填)」。加好後等它連上(最多 90 秒)再回報「已連上,N 個工具」或連不上的原因;連上的工具同一輪的下一步就能用(例如「加上 GitLab,然後列出我的 MR」一次做完)。名稱重複、command 和 url 都給、網址不是 http(s)、還有「{…}」沒填、要改卻沒東西可改,都在問你之前就回給 Bot 說原因。 +### 紀錄檔、當掉報告、秘密遮罩 + +- **紀錄檔**:AnyBot 自己說的話(連線、記憶整理、模型換用、讀不到檔…)寫進資料夾的 `logs/anybot-YYYY-MM-DD.log`,每行有時間、等級、從哪裡來;一天一個檔、留 7 天、一天最多 20 MB(超過寫一行說明就不再寫,終端機照常)。終端機(伺服器的 docker logs)照舊印。ANYBOT_LOG 設等級(預設 info);其他套件只收 warn 以上。以前從 Finder 打開的 AnyBot 說的話沒有地方看。 +- **當掉報告**:任何一條執行緒 panic 時寫 `logs/crash-時間.txt`(版本、執行緒、檔案和行號、訊息、完整 backtrace)。下次打開在主要 Bot 的聊天留一行(幾次、哪裡、報告在哪),記進「待改進」;每份只說一次(看過的改名成 .seen.txt)。螢幕電腦是跳一則提示(它的聊天是大腦的)。 +- **秘密遮罩**:GitLab glpat-、GitHub ghp_/github_pat_、OpenAI/Anthropic sk-、xAI xai-、AWS AKIA、Slack xox、Google AIza、私鑰區塊、Bearer/Basic 標頭、JWT,以及名字像 TOKEN、SECRET、PASSWORD、API_KEY 的變數值,在紀錄檔、當掉報告、手機上的步驟細節和結果都換成 ••••(保留前綴,看得出是哪一種)。工作紀錄不遮(當掉後重做那一步要原本的參數),Bot 自己看到的也不遮(它可能正要用那個 Token 設定連接器)。 + ### 記憶、技能、範本 - **記憶**:每個 Bot 有三種記憶。完整設計(存在哪、分數怎麼算、送給模型的內容、每晚整理、API)見 [docs/memory.md](docs/memory.md)。 diff --git a/docs/feature-map/garden.md b/docs/feature-map/garden.md index 574a20f..a029ee0 100644 --- a/docs/feature-map/garden.md +++ b/docs/feature-map/garden.md @@ -5,6 +5,8 @@ AnyBot 自己照顧自己:Bot 做事遇到 AnyBot 本身的問題會記成「 ## 子功能 - 待改進:一輪做完、自動整理做法時,AnyBot 本身的問題(工具回錯的結果、明明開著卻說找不到、一用就出錯、要繞路才做得到、Bot 一直誤用某個工具)另外記下來,不寫進技能。同一個工具的問題合併計次,最多留 50 條;出現 2 次以上的會標出來。 +- 紀錄檔:AnyBot 自己的訊息寫在資料夾的 `logs/anybot-日期.log`(一天一個、留 7 天、一天最多 20 MB),同時照舊印在終端機(伺服器的 `make server-logs` 看得到)。等級用環境變數 ANYBOT_LOG(error、warn、info 預設、debug)。寫進去前先遮掉金鑰、Token、密碼(glpat-、ghp_、sk-、xai-、AKIA、Bearer、JWT、私鑰、名字像 TOKEN/SECRET/PASSWORD 的變數值 → ••••);手機上的步驟細節也一樣遮。 +- 當掉報告:程式內部出錯(任何一條執行緒)時寫 `logs/crash-時間.txt`(版本、執行緒、位置、訊息、backtrace,一樣遮過);下次打開在主要 Bot 的聊天留一行「AnyBot 上次執行時內部出錯…」(連到大腦的螢幕電腦是跳一則提示),並記一條待改進。每份報告只說一次。 - 園丁每日報告(平日 8:44 起):過去一天失敗或被打斷的執行、走冤枉路的執行(10 步以上且 3 成以上沒成功)、被自動暫停的例行任務、重複出現的待改進。 - 園丁每週報告(週一 8:49 起):一週內失敗 2 成以上,或平均每次 60 步、30 分鐘以上的例行任務,列出跑幾次、幾次沒成功、共幾步幾分鐘。 - 沒事不報;報告寫在主要 Bot 的聊天裡。時間照使用者的時區。 @@ -23,6 +25,8 @@ AnyBot 自己照顧自己:Bot 做事遇到 AnyBot 本身的問題會記成「 ## 陷阱 +- 工作紀錄(oplog)不遮金鑰:當掉後要照原本的參數重做那一步,遮了會壞;手機、紀錄檔、當掉報告才遮。 + - 報告一天只做一次:時間到了之後、AnyBot 開著的時候才做;那天 AnyBot 一直沒開,就不會補做。 - 每週報告只看有執行紀錄的例行任務;加紀錄功能之前跑的不算。 - 待改進是給改 AnyBot 的人看的,Bot 不會自己修;清單滿 50 條,最舊的會被擠掉。 diff --git a/docs/plan-2026-11-engineering.md b/docs/plan-2026-11-engineering.md index 81a72ff..2850b89 100644 --- a/docs/plan-2026-11-engineering.md +++ b/docs/plan-2026-11-engineering.md @@ -16,17 +16,17 @@ - 做法:`cfg(test)` 下 `cloudbox` 不啟動 VM、不跑 `docker`(除非 `ANYBOT_TEST_REAL_BOX=1`,只給標 ignored 的實機測試用),呼叫時直接回「測試裡沒有 Bot 的電腦」。 - 做完:一個測試故意叫 Bot 的電腦跑指令,要立刻失敗而不是去開 VM。 -### E2. 紀錄檔 ⬜ +### E2. 紀錄檔 ✅ - 現況:72 個 `eprintln!`,App 從 Finder 打開時看不到;伺服器靠 docker logs。 - 做法:`log.rs`:寫到資料夾的 `logs/anybot.log`(每天一個檔、留 7 天、單檔上限),同時照舊印到 stderr;等級用 `ANYBOT_LOG`(error/warn/info/debug)。`eprintln!` 全換成 `log::info!`/`warn!` 等巨集。寫進去前先過 E4 的遮罩。 - 做完:打開 App 做一輪,`logs/` 有當天的檔;`make server-logs` 照樣看得到。 -### E3. 當掉報告 ⬜ +### E3. 當掉報告 ✅ - 做法:panic hook 把版本、執行緒、訊息、位置、backtrace 寫到 `logs/crash-<時間>.txt`(先遮罩);下次啟動在主要 Bot 的聊天留一行「AnyBot 上次在 … 當掉了(…),報告在 …」,並記一條「待改進」。 - 做完:測試觸發 panic hook 會寫出報告;下次啟動讀到報告會留言、只留一次。 -### E4. 秘密遮罩 ⬜ -- 做法:`secrets.rs`:GitLab `glpat-`、GitHub `ghp_/gho_/github_pat_`、OpenAI/Anthropic/xAI `sk-`/`xai-`、AWS `AKIA…`、Slack `xox…`、Google `AIza…`、PEM 私鑰、`Bearer …`、JWT、`TOKEN=…/KEY=…/SECRET=…/PASSWORD=…` 的值 → `••••`。用在:紀錄檔、當掉報告、工作紀錄(oplog)、給手機和螢幕電腦的聊天副本裡的步驟結果。 +### E4. 秘密遮罩 ✅ +- 做法:`secrets.rs`:GitLab `glpat-`、GitHub `ghp_/gho_/github_pat_`、OpenAI/Anthropic/xAI `sk-`/`xai-`、AWS `AKIA…`、Slack `xox…`、Google `AIza…`、PEM 私鑰、`Bearer …`、JWT、`TOKEN=…/KEY=…/SECRET=…/PASSWORD=…` 的值 → `••••`。用在:紀錄檔、當掉報告、手機上的步驟細節和結果。工作紀錄(oplog)不遮:當掉後重做那一步要原本的參數。 - 做完:每一種格式都有測試;手機看到的步驟結果不含 Token。 ### E5. 一個 HTTP 用戶端、子行程成群管理、lint 規則 ⬜ diff --git a/src/agent.rs b/src/agent.rs index 80337ef..9a52fc4 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -329,22 +329,22 @@ fn learn(job: &Job, history: &[Message], cancel: &AtomicBool, send: &dyn Fn(Stre let out = match providers::run_step(&req, cancel, &|_| {}) { Ok(o) => o, Err(e) => { - eprintln!("AnyBot:整理做法時模型沒有回應:{e}"); + log::warn!("AnyBot:整理做法時模型沒有回應:{e}"); return; } }; let issues = crate::memory::learned_issues(&out.text); if !issues.is_empty() { - eprintln!("AnyBot:Bot 回報了 {} 個 AnyBot 自己的問題", issues.len()); + log::info!("AnyBot:Bot 回報了 {} 個 AnyBot 自己的問題", issues.len()); send(StreamEvent::Issues(issues)); } match (crate::memory::learned_skill(&out.text), turn.last()) { (Some(mut k), Some(reply)) => { k.steps = crate::memory::replay_steps(turn, &crate::memory::learned_replay(&out.text), &crate::memory::learned_blanks(&out.text)); - eprintln!("AnyBot:學到做法「{}」", k.name); + log::info!("AnyBot:學到做法「{}」", k.name); send(StreamEvent::Learned(k, reply.at)); } - _ => eprintln!("AnyBot:這次的做法沒有存:{}", out.text.split_whitespace().collect::>().join(" ").chars().take(200).collect::()), + _ => log::info!("AnyBot:這次的做法沒有存:{}", out.text.split_whitespace().collect::>().join(" ").chars().take(200).collect::()), } } @@ -1052,7 +1052,7 @@ fn maybe_compact(job: &Job, history: &mut Vec, percent: u64, cancel: &A let set_aside = fold_results(history); if !set_aside.is_empty() { let now = history_tokens(&job.req.system, history) + tools; - eprintln!("AnyBot:對話很長,先收起 {} 個較早的步驟結果(約 {used} → {now} token)", set_aside.len()); + log::info!("AnyBot:對話很長,先收起 {} 個較早的步驟結果(約 {used} → {now} token)", set_aside.len()); send(StreamEvent::Folded(set_aside)); if percent > 0 && now * 100 < job.context_tokens * percent { return None; @@ -1163,7 +1163,7 @@ fn make_room(job: &Job, history: &mut Vec, room: &mut Room, cancel: &At RoomWay::Pictures => { let n = drop_pictures(history); if n > 0 { - eprintln!("AnyBot:對話太長,先拿掉 {n} 張圖片再試"); + log::info!("AnyBot:對話太長,先拿掉 {n} 張圖片再試"); send(StreamEvent::Retrying(format!("對話太長了,先拿掉 {n} 張截圖再試一次…"))); send(StreamEvent::PicturesDropped); } @@ -1408,7 +1408,7 @@ impl StepPlan { self.main_next = true; self.troubles += 1; if self.troubles >= QUICK_TROUBLE_MAX && self.quick.take().is_some() { - eprintln!("AnyBot:這一回合出了 {} 次問題,剩下的步驟改用 Bot 自己的模型", self.troubles); + log::info!("AnyBot:這一回合出了 {} 次問題,剩下的步驟改用 Bot 自己的模型", self.troubles); } } } @@ -1793,7 +1793,7 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc< // Too long is the chat's problem, not the quick model's: folded below. Err(e) if providers::is_context_overflow(&e) => Err(e), Err(e) => { - eprintln!("AnyBot:快速模型 {q} 不能用({e}),這一回合改用 {}", job.req.model); + log::warn!("AnyBot:快速模型 {q} 不能用({e}),這一回合改用 {}", job.req.model); plan.quick_failed(); providers::run_step(&main_req, &cancel, &send) } diff --git a/src/app.rs b/src/app.rs index 35ed638..3896ab7 100644 --- a/src/app.rs +++ b/src/app.rs @@ -2289,7 +2289,7 @@ impl App { /// when the person presses it (resume_turn). This only notes them in the log. fn resume_interrupted(&mut self, _ctx: &egui::Context) { for t in std::mem::take(&mut self.interrupted) { - eprintln!( + log::info!( "AnyBot:Bot {} 的回合 {} 在 AnyBot 關掉時被中斷了({};可能已執行的步驟 {} 個;放回聊天的訊息 {} 則)", t.bot_id, t.op, @@ -2358,6 +2358,33 @@ impl App { } } + /// 當掉報告 (logfile.rs): what panicked since the last start, told once — in the main bot's + /// chat and in 待改進 (on a screen of a brain, whose chats are the brain's: a notice). + fn tell_crashes(&mut self) { + static TOLD: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + if TOLD.swap(true, Ordering::SeqCst) { + return; + } + let reports = crate::logfile::take_crash_reports(); + if reports.is_empty() { + return; + } + let now = crate::routines::now(); + let mut lines = vec![]; + for (when, at, what, path) in &reports { + crate::garden::note_issue(&mut self.state.improvements, &format!("AnyBot 內部出錯:{what}({at})"), "AnyBot", now); + lines.push(format!("{when} 在 {at}:{what}(報告:{})", path.display())); + } + let text = format!("AnyBot 上次執行時內部出錯 {} 次,已記進 設定 › 更新 ›「待改進」:\n{}", reports.len(), lines.join("\n")); + if self.mir.on || !self.state.remote.brain_id.is_empty() { + self.notice = Some(text); + } else { + let id = self.state.primary_bot; + self.goal_note(id, &text); + } + self.dirty = true; + } + /// Run due routines (a routine firing is a "wake" turn). fn tick_routines(&mut self, ctx: &egui::Context) { if self.demo || self.last_tick.elapsed() < std::time::Duration::from_secs(1) { @@ -5911,6 +5938,10 @@ impl App { // document folders; hands never. let hands = !self.state.remote.hands_for.is_empty(); crate::embed::set_wanted(!self.demo && !hands && (!self.mir.on || !self.state.doc_folders.is_empty())); + // 當掉報告: a panic last time is told once (logfile.rs). + if !self.demo { + self.tell_crashes(); + } // A screen of another AnyBot's brain: its bots work there, not here. if self.mir.on { self.remote_tick(ctx); @@ -5967,7 +5998,7 @@ impl App { if sweep_files { let n = crate::attach::sweep(&kept, &pages); if n > 0 { - eprintln!("AnyBot:清掉 {n} 個聊天已經不用的檔案"); + log::info!("AnyBot:清掉 {n} 個聊天已經不用的檔案"); } } let r = crate::memstore::tidy(None, &tz, crate::model::now_ms()); @@ -5977,7 +6008,7 @@ impl App { crate::cloudbox::sweep_temp(); let copy = crate::store::backup_memory(7); crate::memstore::meta_set("last_tidy", &today); - eprintln!("AnyBot:記憶整理好了({} 條做過的事壓成每週一行,{} 行每週的壓成每月一行,清掉 {} 條最近刪除;備份 {})", r.events, r.weeks, r.purged, copy.map(|p| p.display().to_string()).unwrap_or_else(|| "沒有成功".into())); + log::info!("AnyBot:記憶整理好了({} 條做過的事壓成每週一行,{} 行每週的壓成每月一行,清掉 {} 條最近刪除;備份 {})", r.events, r.weeks, r.purged, copy.map(|p| p.display().to_string()).unwrap_or_else(|| "沒有成功".into())); RUNNING.store(false, Ordering::SeqCst); }); } @@ -6013,7 +6044,7 @@ impl App { if r.is_err() && std::env::var("ANYBOT_ACCOUNT_CREATE").map(|v| v == "1").unwrap_or(false) { let invite = std::env::var("ANYBOT_RELAY_INVITE").unwrap_or_default(); if let Ok(s) = crate::remote::relay_join(&self.state.remote, url, user, &pw, true, &invite, &code) { - eprintln!("AnyBot:已建立帳號 {user}"); + log::info!("AnyBot:已建立帳號 {user}"); r = Ok(s); } } @@ -6021,10 +6052,10 @@ impl App { Ok(s) => { self.state.remote = s; self.dirty = true; - eprintln!("AnyBot:已加入帳號 {user}({url})"); + log::info!("AnyBot:已加入帳號 {user}({url})"); } Err(e) => { - eprintln!("AnyBot:登入帳號失敗(30 秒後再試):{e}"); + log::warn!("AnyBot:登入帳號失敗(30 秒後再試):{e}"); return; } } @@ -6033,12 +6064,12 @@ impl App { match crate::remote::restore(url, user, &pw, &code).and_then(|b| serde_json::from_slice::(&b).map_err(|e| e.to_string())) { Ok(mut st) => { st.remote = self.state.remote.clone(); - eprintln!("AnyBot:已從帳號備份接手 {} 個 Bot", st.bots.len()); + log::info!("AnyBot:已從帳號備份接手 {} 個 Bot", st.bots.len()); self.state = st; self.dirty = true; let _ = std::fs::write(&marker, chrono::Utc::now().to_rfc3339()); } - Err(e) => eprintln!("AnyBot:沒有接手備份:{e}"), + Err(e) => log::warn!("AnyBot:沒有接手備份:{e}"), } } } @@ -6056,7 +6087,7 @@ impl App { // 連接器: the window connects them as it draws (there is no drawing here), so a question // asked here had none of them. Connected before it starts. for (name, why) in crate::mcp::sync(&app.state.mcp_servers) { - eprintln!("連接器「{name}」連不上:{why}"); + log::warn!("連接器「{name}」連不上:{why}"); } let id = app.state.primary_bot; let start = app.state.bot(id).map(|b| b.messages.len()).unwrap_or(0); @@ -6151,15 +6182,15 @@ impl App { if let Some(url) = std::env::var("ANYBOT_VOICE_URL").ok().map(|u| u.trim().to_string()).filter(|u| !u.is_empty()) { let var = |k: &str| std::env::var(k).unwrap_or_default(); if crate::speech::own_server(&mut app.state.voice, &url, &var("ANYBOT_VOICE_LISTEN_MODEL"), &var("ANYBOT_VOICE_SPEAK_MODEL"), &var("ANYBOT_VOICE_VOICE")) { - eprintln!("AnyBot:語音用這台伺服器的語音服務({url})"); + log::info!("AnyBot:語音用這台伺服器的語音服務({url})"); app.dirty = true; } // Its model is downloaded when asked (once; then each start finds it at once). let model = var("ANYBOT_VOICE_LISTEN_MODEL"); if !model.is_empty() { std::thread::spawn(move || match crate::speech::fetch_model(&url, &model) { - Ok(()) => eprintln!("AnyBot:語音服務的模型就緒({model})"), - Err(e) => eprintln!("AnyBot:{e}"), + Ok(()) => log::info!("AnyBot:語音服務的模型就緒({model})"), + Err(e) => log::warn!("AnyBot:{e}"), }); } } @@ -6167,14 +6198,14 @@ impl App { app.background(ctx); if let Some(port) = crate::remote::lan_port() { for a in crate::remote::addresses(port) { - eprintln!("AnyBot:手機可以打開 {a}"); + log::info!("AnyBot:手機可以打開 {a}"); } } if !app.state.remote.relay_url.is_empty() { - eprintln!("AnyBot:透過帳號 {} 連線({})", app.state.remote.relay_user, app.state.remote.relay_url); + log::info!("AnyBot:透過帳號 {} 連線({})", app.state.remote.relay_user, app.state.remote.relay_url); } if app.state.remote.password.is_empty() && app.state.remote.host_token.is_empty() && std::env::var("ANYBOT_ACCOUNT").is_err() { - eprintln!("AnyBot:還沒有設定手機密碼或帳號。用 ANYBOT_PHONE_PASSWORD=… 或 ANYBOT_ACCOUNT=網址|帳號 + ANYBOT_ACCOUNT_PASSWORD=… 啟動。"); + log::warn!("AnyBot:還沒有設定手機密碼或帳號。用 ANYBOT_PHONE_PASSWORD=… 或 ANYBOT_ACCOUNT=網址|帳號 + ANYBOT_ACCOUNT_PASSWORD=… 啟動。"); } let mut last_try = Instant::now(); let mut last_brain = Instant::now() - std::time::Duration::from_secs(60); @@ -6189,7 +6220,7 @@ impl App { if !want.trim().is_empty() && !app.state.remote.host_token.is_empty() && app.state.remote.brain_name != want && last_brain.elapsed().as_secs() >= 20 { last_brain = Instant::now(); if let Some((id, name, _)) = crate::remote::devices_online(&app.state.remote).into_iter().find(|(_, n, _)| n == want.trim()) { - eprintln!("AnyBot:用「{name}」當大腦,這台當手腳"); + log::info!("AnyBot:用「{name}」當大腦,這台當手腳"); app.mir.want = Some((id, name)); app.state.remote.device_link = true; } @@ -6200,7 +6231,7 @@ impl App { // Told to stop (docker stop, systemd, Ctrl-C): what the bots started stops, the // connectors close, the chats are saved — nothing is left running behind. if STOPPING.load(Ordering::SeqCst) { - eprintln!("AnyBot:收到停止訊號,正在收尾…"); + log::info!("AnyBot:收到停止訊號,正在收尾…"); eframe::App::on_exit(&mut app); std::process::exit(0); } diff --git a/src/app/goal_ui.rs b/src/app/goal_ui.rs index e38e976..4edacf7 100644 --- a/src/app/goal_ui.rs +++ b/src/app/goal_ui.rs @@ -201,12 +201,12 @@ impl App { break; } Err(e) => { - eprintln!("AnyBot:用 {} 檢查目標沒有回應:{e}", req.model); + log::warn!("AnyBot:用 {} 檢查目標沒有回應:{e}", req.model); judged = Judged::Failed(e); } } } - eprintln!("AnyBot:Bot {bot_id} 的目標檢查:{judged:?}"); + log::info!("AnyBot:Bot {bot_id} 的目標檢查:{judged:?}"); let _ = tx.send((bot_id, 0, StreamEvent::Goal(g.since, judged))); ctx.request_repaint(); }); diff --git a/src/app/remote_ui.rs b/src/app/remote_ui.rs index 2008a8c..0be16f0 100644 --- a/src/app/remote_ui.rs +++ b/src/app/remote_ui.rs @@ -450,7 +450,8 @@ impl App { if t.get("label").is_some() { t["name"] = json!(c.name); if let Some(r) = results.get(c.id.as_str()) { - t["result"] = json!(clip(r.trim(), 600)); + // (秘密遮罩: what a step printed may hold a key; the phone shows it masked.) + t["result"] = json!(clip(&crate::secrets::mask(r.trim()), 600)); } } } diff --git a/src/embed.rs b/src/embed.rs index 8ca62f9..f2feb86 100644 --- a/src/embed.rs +++ b/src/embed.rs @@ -187,7 +187,7 @@ fn local() -> Option> { } Err(e) => { // A broken copy (a disk filled up halfway): fetch it again. - eprintln!("AnyBot:本機語意模型讀不了({e}),重新下載"); + log::warn!("AnyBot:本機語意模型讀不了({e}),重新下載"); let _ = std::fs::remove_file(dir.join("dims.json")); None } @@ -261,10 +261,10 @@ fn ensure_local() { match &r { Ok(()) => { *FETCH_ERR.lock().unwrap() = None; - eprintln!("AnyBot:本機語意模型就緒({})", model_dir().display()); + log::info!("AnyBot:本機語意模型就緒({})", model_dir().display()); } Err(e) => { - eprintln!("AnyBot:本機語意模型下載失敗:{e}"); + log::warn!("AnyBot:本機語意模型下載失敗:{e}"); *FETCH_ERR.lock().unwrap() = Some((e.clone(), Instant::now())); } } diff --git a/src/lock.rs b/src/lock.rs index 2ceaa65..9153921 100644 --- a/src/lock.rs +++ b/src/lock.rs @@ -41,7 +41,7 @@ fn take_at(p: &Path, wait: Duration) -> Result { Err(e) => { // A folder the lock can't be made in can't hold the chats either; say so, but don't // refuse to start over the lock alone. - eprintln!("AnyBot:沒辦法建立 {}({e}),這次不檢查是否有別的 AnyBot 在用同一個資料夾。", p.display()); + log::warn!("AnyBot:沒辦法建立 {}({e}),這次不檢查是否有別的 AnyBot 在用同一個資料夾。", p.display()); return Ok(DataLock { _file: None }); } }; @@ -59,7 +59,7 @@ fn take_at(p: &Path, wait: Duration) -> Result { Err(std::fs::TryLockError::WouldBlock) => return Err(busy_message(p, &mut f)), Err(std::fs::TryLockError::Error(e)) => { // A file system without locks (some network shares): go on unchecked. - eprintln!("AnyBot:{} 不能上鎖({e}),這次不檢查是否有別的 AnyBot 在用同一個資料夾。", p.display()); + log::warn!("AnyBot:{} 不能上鎖({e}),這次不檢查是否有別的 AnyBot 在用同一個資料夾。", p.display()); return Ok(DataLock { _file: None }); } } diff --git a/src/logfile.rs b/src/logfile.rs new file mode 100644 index 0000000..bf6ac45 --- /dev/null +++ b/src/logfile.rs @@ -0,0 +1,236 @@ +//! 紀錄檔與當掉報告: what AnyBot says about itself goes to `logs/anybot-YYYY-MM-DD.log` in its data +//! folder (one file a day, the last LOG_DAYS days kept, at most LOG_MAX_BYTES a day) as well as to +//! stderr, as before — an AnyBot opened from Finder had nowhere to say anything, and a server's +//! only record was `docker logs`. The level is ANYBOT_LOG (error, warn, info — the default —, +//! debug). Other crates' lines come in at warn and above only. Every line goes through the +//! secret mask (secrets.rs) first. +//! +//! A panic anywhere (the window, a bot's turn, a background thread) leaves +//! `logs/crash-