From 6e6ab2b1aa590d1c2caba6a3001181a34c976fae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=80=A7=E9=A9=8A?= Date: Sat, 21 Nov 2026 14:01:41 +0800 Subject: [PATCH] =?UTF-8?q?=E6=93=8D=E4=BD=9C=E7=B4=80=E9=8C=84=EF=BC=88?= =?UTF-8?q?=E8=A8=88=E7=95=AB=20D5=20=E7=AC=AC=E4=B8=80=E6=AD=A5=EF=BC=89?= =?UTF-8?q?=EF=BC=9A=E7=9C=8B=E5=BE=97=E5=88=B0=20Bot=20=E6=AF=8F=E4=B8=80?= =?UTF-8?q?=E8=BC=AA=E5=81=9A=E4=BA=86=E4=BB=80=E9=BA=BC=E3=80=82=E5=A4=A7?= =?UTF-8?q?=E8=85=A6=E5=BE=9E=E7=A8=BD=E6=A0=B8=E7=B4=80=E9=8C=84=EF=BC=88?= =?UTF-8?q?30=20=E5=A4=A9=EF=BC=89=E6=95=B4=E7=90=86=E6=AF=8F=E4=B8=80?= =?UTF-8?q?=E8=BC=AA=EF=BC=88store::who=5Fstarted=E3=80=81evidence?= =?UTF-8?q?=EF=BC=89=EF=BC=9A=E8=AA=B0=E7=99=BC=E8=B5=B7=EF=BC=88=E4=BD=A0?= =?UTF-8?q?=EF=BC=8F=E4=BE=8B=E8=A1=8C=E4=BB=BB=E5=8B=99=E5=90=AB=20?= =?UTF-8?q?=E2=8F=B0=20=E6=8F=90=E9=86=92=EF=BC=8F=E5=88=A5=E7=9A=84=20Bot?= =?UTF-8?q?=EF=BC=89=E3=80=81=E6=80=8E=E9=BA=BC=E7=B5=90=E6=9D=9F=E3=80=81?= =?UTF-8?q?=E7=9C=8B=E4=BA=86=EF=BC=88=E7=B6=B2=E5=9D=80=E3=80=81=E6=AA=94?= =?UTF-8?q?=E6=A1=88=E3=80=81=E8=B3=87=E6=96=99=E5=A4=BE=E3=80=81=E6=90=9C?= =?UTF-8?q?=E5=B0=8B=E3=80=81=E6=89=BE=E6=96=87=E4=BB=B6=E6=88=96=E8=A8=98?= =?UTF-8?q?=E6=86=B6=E3=80=81=E9=A0=81=E9=9D=A2=EF=BC=89=E3=80=81=E5=AF=AB?= =?UTF-8?q?=E4=BA=86=EF=BC=88=E6=94=B9=E7=9A=84=E6=AA=94=E6=A1=88=E3=80=81?= =?UTF-8?q?=E9=A0=81=E9=9D=A2=E3=80=81=E4=B8=8B=E8=BC=89=E3=80=81PDF?= =?UTF-8?q?=EF=BC=89=E3=80=81=E5=9F=B7=E8=A1=8C=E4=BA=86=EF=BC=88=E6=8C=87?= =?UTF-8?q?=E4=BB=A4=E3=80=81=E7=B6=B2=E9=A0=81=E8=85=B3=E6=9C=AC=EF=BC=89?= =?UTF-8?q?=E3=80=81=E6=AF=8F=E5=80=8B=E5=B7=A5=E5=85=B7=E5=B9=BE=E6=AC=A1?= =?UTF-8?q?=E3=80=81=E5=B9=BE=E6=AD=A5=E8=A2=AB=E6=8B=92=E7=B5=95=E6=88=96?= =?UTF-8?q?=E5=A4=B1=E6=95=97=E3=80=81=E8=8A=B1=E5=A4=9A=E4=B9=85=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 電腦版:右側面板「動態」最上面「操作紀錄」(activity_ui),最近 8 輪一輪一張,點開看清單和工具次數;「只看沒人看著時做的」。面板開著每 5 秒在背景重讀;螢幕電腦向大腦要(新路 api/sync/audit/)。手機「對話詳細資訊 › 稽核」每一輪最上面多一列「你發起 · 多久 · 失敗 N 步」和看了/寫了/執行了。功能地圖新的一區 activity.md(README 有列)、FEATURES.md、計畫 D5 狀態。 已驗證: cargo test 全綠(833),新測試 a_turn_says_who_started_it_and_what_it_did(三種發起者、看了不重複、寫了檔案和頁面、執行、失敗和拒絕、時長、空資料夾寫工作資料夾)、activity_ui 的時長說法;featuremap 過(新區的四段、Bot 那行、索引);clippy 錯誤數跟之前一樣(12);verify-anybot:scratch 跑看資料夾和寫檔兩輪,api/bots/1/audit 兩輪 who person、completed,寫檔那輪 wrote hello.txt、tools edit_file 1,看資料夾那輪 looked 工作資料夾;手機稽核頁兩輪最上面「你發起 · 0 秒」「看了:工作資料夾」「寫了:hello.txt」;桌面截圖(真資料)右側「操作紀錄」兩張卡、點開那張「寫了 · hello.txt」「工具:edit_file ×1」。 未驗證: 例行任務和別的 Bot 叫的那幾輪(要等排程或第二個 Bot);螢幕電腦向大腦要(要兩台)。 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Uirha2uBHmbnuWBhNzjbJm --- FEATURES.md | 7 ++ docs/feature-map/README.md | 1 + docs/feature-map/activity.md | 33 +++++++ docs/plan-2026-11-openbot.md | 2 +- mobile/index.html | 9 +- src/app.rs | 3 + src/app/activity_ui.rs | 170 +++++++++++++++++++++++++++++++++++ src/app/panel_ui.rs | 2 + src/featuremap.rs | 1 + src/remote.rs | 2 + src/store.rs | 92 ++++++++++++++++++- 11 files changed, 319 insertions(+), 3 deletions(-) create mode 100644 docs/feature-map/activity.md create mode 100644 src/app/activity_ui.rs diff --git a/FEATURES.md b/FEATURES.md index f25d0bb..d8006a0 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -1565,6 +1565,13 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - 指令輸出、連接器的回答太長時,給模型的只留開頭和結尾各 6000 字,中間寫「…(中間省略 N 個字;完整內容用 read_result 讀:id=r…)…」;完整的存在資料夾的 `outputs/`(一份最多 20 MB、留 7 天,同樣的內容同一個 id)。較早的結果為了騰出空間被收起時也一樣寫 id。 - 每個 Bot 都有 `read_result`(id、從第幾個字、一次最多兩萬字),只是看,計畫模式也能用。以前叫 Bot「再做一次這一步」看完整的:會改東西的步驟重做很危險,答案也可能不一樣,長紀錄的中間就這樣不見了。 +### 操作紀錄(右側「動態」、手機「稽核」) + +- 每一輪做了什麼,照系統自己記下的步驟整理(稽核紀錄,30 天):**誰發起**(你/例行任務(含 ⏰ 提醒)/別的 Bot)、怎麼結束、**看了**(網址、讀的檔案、資料夾、搜尋、找文件或記憶、頁面)、**寫了**(改的檔案、頁面、下載、存成 PDF)、**執行了**(指令、網頁腳本)、每個工具幾次、幾步被拒絕或失敗、花多久。各自不重複、最多 12 項。 +- 電腦版:右側面板「動態」最上面「操作紀錄」,最近 8 輪,一輪一張(時間 · 誰 · 結果、開頭那句話、「N 步 · 看了 · 寫了 · 執行 · 失敗 · 多久」,有失敗那行是紅字),點一下展開清單和工具次數;「只看沒人看著時做的」只留例行任務和別的 Bot 叫的。面板開著每 5 秒重讀,在背景讀;螢幕電腦向大腦要(`api/sync/audit/`)。 +- 手機「對話詳細資訊 › 稽核」:每一輪最上面多一列「你發起 · 2 分 13 秒 · 失敗 1 步」和「看了:…、寫了:…、執行了:…」。 +- 從參數整理:用指令改的檔只算「執行了」;網頁裡打字、送出算在工具次數。功能地圖新的一區 activity.md。 + ### 個人資料與用量(設定 › 個人資料) - 設定多一頁「個人資料」(一般的下一頁;左下角選單也有「個人資料與用量…」)。最上面名字和「過去一年有 N 個活躍日」。 diff --git a/docs/feature-map/README.md b/docs/feature-map/README.md index ad2b518..17b2a1a 100644 --- a/docs/feature-map/README.md +++ b/docs/feature-map/README.md @@ -90,6 +90,7 @@ Bot 讀得到的是開頭、子功能、使用者怎麼到、Bot 那一行和沒 - [routines](routines.md):排程與事件觸發、執行紀錄、完成條件、自動暫停。 - [goal](goal.md):/goal:沒達成就繼續做、評審只看證據。 - [plan](plan.md):/plan:先查清楚、交計畫給你核准,核准後才動手、照步驟打勾。 +- [activity](activity.md):操作紀錄:每一輪誰發起、看了/寫了/執行了什麼、工具次數、失敗、花多久;電腦版右側「動態」、手機「稽核」。 - [tasks](tasks.md):任務:每件交代的事一張卡,狀態由系統算(等你、追進度、驗收、已交付、你已確認…)、證據等級、清掉聊天也留著。 ### 在電腦上做事 diff --git a/docs/feature-map/activity.md b/docs/feature-map/activity.md new file mode 100644 index 0000000..5a73820 --- /dev/null +++ b/docs/feature-map/activity.md @@ -0,0 +1,33 @@ +# 操作紀錄 + +每個 Bot 每一輪做了什麼,照系統自己記下的步驟(稽核紀錄,留 30 天)整理:誰叫它做的、怎麼結束、看了什麼、寫了什麼、執行了什麼、用了哪些工具幾次、幾步失敗、花多久。聊天裡不多任何東西;電腦版在右側面板的「動態」,手機在「對話詳細資訊 › 稽核」。 + +## 子功能 + +- `activity-who` 誰發起:「你」、「例行任務」(例行任務和 ⏰ 提醒叫醒的那一輪)、「別的 Bot」(「[來自 Bot]」開頭的那一輪)。 +- `activity-evidence` 做了什麼:看了(打開的網址、web_fetch、讀的檔案、看的資料夾(空的寫「工作資料夾」)、搜尋、找文件或記憶、讀的頁面)、寫了(改的檔案、寫的頁面、下載的檔案、存成的 PDF)、執行了(指令、網頁腳本,太長的截短),各自不重複、最多 12 項;工具各幾次;被拒絕或失敗的步數;從開始到最後一步結束花多久。 +- `activity-panel` 電腦版:右側面板「動態」最上面「操作紀錄」,最近 8 輪,每輪一張:時間 · 誰 · 結果(完成/停止/失敗/進行中),開頭那句話,「N 步 · 看了 a · 寫了 b · 執行 c · 失敗 d · 花多久」(有失敗的那行字是紅的);點一下展開看了、寫了、執行了的清單和每個工具的次數。「只看沒人看著時做的」只留例行任務和別的 Bot 叫的。面板開著時每 5 秒重讀;螢幕電腦向大腦要(`api/sync/audit/`)。 +- `activity-phone` 手機「稽核」:每一輪最上面一列「你發起 · 2 分 13 秒 · 失敗 1 步」,下面「看了:…、寫了:…、執行了:…」(各前 4 項,多的寫「等 N 項」),再來是原本每一步的清單。 + +## 使用者怎麼到 + +- 電腦版:點聊天頂端 Bot 的名字打開右側面板,「動態」分頁最上面。 +- 手機:聊天頂端 Bot 名字 › 對話詳細資訊 › 「稽核」分頁(擁有者和管理員)。 + +## 怎麼操作(verify-anybot) + +- Bot:沒有專門的工具;使用者問「你剛剛做了什麼」照聊天裡的步驟回答,問「例行任務昨天做了什麼」請他打開這裡(手機:對話詳細資訊 › 稽核)。 + +前提: + +- 基本前提和「手機已登入」(README)。 + +- **兩輪工具的紀錄**(covers `activity-who`、`activity-evidence`、`activity-phone`):請 Bot 看資料夾、再建一個檔案,看稽核。指令:`$CTL api POST /api/bots/1/send '{"text":"看資料夾 [[call list_dir {}]]"}' && $CTL wait-api /api/bots/1 '[.messages[]?.text] | any(test("FAKE-MODEL 收到工具結果"))' 90 && $CTL api POST /api/bots/1/send '{"text":"寫檔 [[call edit_file {\"path\":\"hello.txt\",\"old\":\"\",\"new\":\"你好\"}]]"}' && $CTL wait-api /api/bots/1 '[.messages[]?.text] | map(select(test("FAKE-MODEL 收到工具結果"))) | length >= 2' 60 && $CTL api GET /api/bots/1/audit --jq '[.turns[] | {who, outcome, evidence}]' && $CTL phone click '.row[data-bot="1"]' && $CTL phone click '#b-chatmore' && $CTL phone click '#sheet-in .opt' --text '對話詳細資訊' && $CTL phone click '[data-tab="audit"]' && $CTL phone wait-text '你發起' && $CTL phone shot activity-phone`。看到:兩輪都是 who「person」、outcome「completed」;寫檔那輪 wrote「hello.txt」、tools edit_file 1;看資料夾那輪 looked「工作資料夾」;手機每一輪最上面「你發起 · 0 秒」和「看了:工作資料夾」「寫了:hello.txt」。 +- **電腦版的操作紀錄**(covers `activity-panel`):指令:要開視窗——`$CTL stop && ABV_ALLOW_WINDOW=1 $CTL desktop-shot activity ANYBOT_SHOT_REAL=1 ANYBOT_SHOT_VIEW=panel ANYBOT_SHOT_FRAMES=500 'ANYBOT_SHOT_CLICK=960,356@420'`。看到:右側「動態」最上面「操作紀錄」、「只看沒人看著時做的」,兩張卡「11/21 13:57 · 你 · 完成」,點開的那張有「寫了 · hello.txt」「工具:edit_file ×1」。例行任務、別的 Bot 叫的那幾輪:走不到(要等排程或第二個 Bot),靠自動測試。 +- 自動測試:`cargo test a_turn_says_who_started_it_and_what_it_did`、`cargo test app::activity_ui::`、`cargo test layout_audit::`。 + +## 陷阱 + +- 「看了」「寫了」是從步驟的參數整理的:Bot 用指令(shell)改檔,只出現在「執行了」,不在「寫了」;網頁裡打字、送出算在工具次數(browser_type、browser_press),不在「寫了」。 +- 稽核紀錄留 30 天;更早的不在這裡(聊天裡的步驟還在)。 +- 時間是那一輪第一步到最後一步結束;還在跑的那一輪算到目前為止。 diff --git a/docs/plan-2026-11-openbot.md b/docs/plan-2026-11-openbot.md index a5201fb..768eb3a 100644 --- a/docs/plan-2026-11-openbot.md +++ b/docs/plan-2026-11-openbot.md @@ -183,7 +183,7 @@ 例行任務、目標、計畫都改用這個結構。 - 做完:一個例行任務在任務頁看得到每一步;改流程後舊的執行紀錄照舊。 -**D5. 操作紀錄/證據** +**D5. 操作紀錄/證據**——11/21 做了第一步:每一輪誰發起、看了/寫了/執行了、工具次數、失敗、多久,電腦版右側「動態」和手機「稽核」都看得到,可以只看沒人看著時做的。寫的檔案的大小和雜湊、有沒有通過驗收、花的 token、從回答點到它的紀錄還沒做。 - 現況:聊天裡的步驟、`oplog`(開始、嘗試、工具開始/結束)、`audit.db`(30 天)、完成宣稱檢查(`claims.rs`)、任務的證據等級都有了。缺:讀了/寫了哪些檔沒有結構化記錄(只在參數裡)、稽核沒記結果和誰允許的、電腦版沒有稽核時間線(手機的 對話詳細資訊 › 稽核 才有)。 - 做什麼:每一輪一份紀錄:做了哪些步驟、用了哪個工具、看了什麼(網址、檔案)、寫了什麼(路徑、大小、雜湊)、結果放在哪、 有沒有通過驗收、誰發起的(你、例行任務、別的 Bot)、花了多少 token。放在獨立的「活動」頁,聊天裡不加雜訊(記憶:北極星的顯示原則)。 diff --git a/mobile/index.html b/mobile/index.html index dbfac33..bad7d5b 100644 --- a/mobile/index.html +++ b/mobile/index.html @@ -2714,7 +2714,14 @@ function tabBody(b, d) { if (x.type === "queue") return item({icon: "message", k: "你插進來的話", v: x.text, r: x.state === "waiting" ? "排隊中" : x.state === "consumed" ? "已送達" : "已取消"}); return item({icon: "stop", k: "你按了停止"}); }).join(""); - h += group(`${plain(t.prompt || "(無訊息的回合)").slice(0, 24)} · ${ago(t.at)} · ${OUT[t.outcome] || "進行中…"}`, steps); // (group() escapes the title itself) + // 操作紀錄 (plan D5): who started it, how long, what failed, and what it looked at, wrote and ran. + const e = t.evidence; + const WHO = {routine: "例行任務", bot: "別的 Bot", person: "你"}; + const secs = Math.round(((e && e.duration_ms) || 0) / 1000); + const dur = secs < 60 ? `${secs} 秒` : secs < 3600 ? `${Math.floor(secs / 60)} 分 ${secs % 60} 秒` : `${Math.floor(secs / 3600)} 小時 ${Math.floor(secs % 3600 / 60)} 分`; + const parts = e ? [["looked", "看了"], ["wrote", "寫了"], ["ran", "執行了"]].filter(([k]) => (e[k] || []).length).map(([k, w]) => `${w}:${e[k].slice(0, 4).join("、")}${e[k].length > 4 ? ` 等 ${e[k].length} 項` : ""}`) : []; + const sum = e ? item({icon: "activity", k: `${WHO[t.who] || "你"}發起 · ${dur}${e.failed ? ` · 失敗 ${e.failed} 步` : ""}`, v: parts.join("\n")}) : ""; + h += group(`${plain(t.prompt || "(無訊息的回合)").slice(0, 24)} · ${ago(t.at)} · ${OUT[t.outcome] || "進行中…"}`, sum + steps); // (group() escapes the title itself) } return h; } diff --git a/src/app.rs b/src/app.rs index 8fcdd0d..18c3e78 100644 --- a/src/app.rs +++ b/src/app.rs @@ -43,6 +43,7 @@ mod voice_ui; mod drops_ui; mod tasks_ui; mod me_ui; +mod activity_ui; mod memory_ui; mod goal_ui; mod context_ui; @@ -338,6 +339,7 @@ pub struct App { /// 任務: the list the brain works out, and its dialog. tk: tasks_ui::TasksUi, me: me_ui::MeUi, + act: activity_ui::ActivityUi, drop_last: String, nightly_checked: Option, /// Files and pictures waiting to go with the next message. @@ -604,6 +606,7 @@ impl App { drop_page: None, tk: Default::default(), me: Default::default(), + act: Default::default(), drop_last: String::new(), nightly_checked: None, att: Default::default(), diff --git a/src/app/activity_ui.rs b/src/app/activity_ui.rs new file mode 100644 index 0000000..53c09a3 --- /dev/null +++ b/src/app/activity_ui.rs @@ -0,0 +1,170 @@ +// 操作紀錄 (plan D5) in the side panel's 動態: the bot's latest turns — who started each (you, a +// routine, another bot), how it ended, and what it did: what it looked at, wrote and ran, which +// tools how often, what failed, how long — each opened for the lists. 「只看沒人看著時做的」 +// keeps the routines' and other bots' turns. From the audit trail (store::turns, 30 days), read +// on a thread every few seconds while the panel shows it; on a screen, asked of the brain. + +use super::panel_ui::{panel_card, panel_title}; +use super::*; +use std::sync::mpsc::{channel, Receiver}; + +#[derive(Default)] +pub(super) struct ActivityUi { + /// Each bot's turns as last read, and when. + turns: HashMap, + rx: Option<(u64, Receiver>)>, + /// The turns opened to their lists (by op id). + open: std::collections::HashSet, + /// Only the turns nobody watched (routines, other bots). + unattended: bool, +} + +const EVERY_SECS: u64 = 5; +const SHOWN: usize = 8; + +impl App { + fn activity_refresh(&mut self, ctx: &egui::Context, bot: u64) { + if let Some((b, rx)) = &self.act.rx { + if let Ok(v) = rx.try_recv() { + if let Some(v) = v { + self.act.turns.insert(*b, (Instant::now(), v)); + } else if let Some(x) = self.act.turns.get_mut(b) { + x.0 = Instant::now(); + } + self.act.rx = None; + } else { + return; + } + } + if self.act.turns.get(&bot).is_some_and(|(at, _)| at.elapsed().as_secs() < EVERY_SECS) { + return; + } + let (tx, rx) = channel(); + let repaint = ctx.clone(); + if self.mir.on { + let s = self.state.remote.clone(); + std::thread::spawn(move || { + let _ = tx.send(crate::remote::to_brain(&s, "GET", &format!("/audit/{bot}"), &[], &[], 20).ok()); + repaint.request_repaint(); + }); + } else { + std::thread::spawn(move || { + let _ = tx.send(Some(crate::store::turns(bot))); + repaint.request_repaint(); + }); + } + self.act.rx = Some((bot, rx)); + } + + /// The 操作紀錄 section of 動態. + pub(super) fn panel_record(&mut self, ui: &mut egui::Ui, ctx: &egui::Context, bot: &Bot) { + let p = self.pal; + self.activity_refresh(ctx, bot.id); + panel_title(ui, "操作紀錄", p); + ui.horizontal(|ui| { + ui.add_space(12.0); + ui.checkbox(&mut self.act.unattended, RichText::new(t("只看沒人看著時做的")).size(FONT_XS).color(p.text2)).on_hover_text(t("例行任務和別的 Bot 叫它做的那幾輪")); + }); + ui.add_space(6.0); + let Some((_, v)) = self.act.turns.get(&bot.id) else { + hint(ui, "正在讀紀錄…", p); + ui.add_space(16.0); + return; + }; + let turns: Vec = v["turns"].as_array().cloned().unwrap_or_default().into_iter().filter(|x| !self.act.unattended || x["who"] != "person").take(SHOWN).collect(); + if turns.is_empty() { + hint(ui, if self.act.unattended { "最近 30 天沒有沒人看著時做的事" } else { "最近 30 天還沒有紀錄" }, p); + ui.add_space(16.0); + return; + } + let tz = crate::routines::tz_of(&self.state.timezone); + let mut toggle: Option = None; + panel_card(ui, p, |ui| { + for (i, x) in turns.iter().enumerate() { + if i > 0 { + ui.separator(); + } + let op = x["op"].as_str().unwrap_or("").to_string(); + let e = &x["evidence"]; + let who = match x["who"].as_str() { + Some("routine") => t("例行任務"), + Some("bot") => t("別的 Bot"), + _ => t("你"), + }; + let outcome = match x["outcome"].as_str() { + Some("completed") => t("完成"), + Some("aborted") => t("停止"), + Some("failed") => t("失敗"), + _ => t("進行中"), + }; + let when = { + use chrono::TimeZone; + tz.timestamp_millis_opt(x["at"].as_i64().unwrap_or(0)).single().map(|d| d.format("%m/%d %H:%M").to_string()).unwrap_or_default() + }; + let n = |k: &str| e[k].as_array().map(Vec::len).unwrap_or(0); + let steps: u64 = e["tools"].as_object().map(|o| o.values().filter_map(|v| v.as_u64()).sum()).unwrap_or(0); + let mut sum = format!("{steps} 步"); + for (k, w) in [("looked", "看了"), ("wrote", "寫了"), ("ran", "執行")] { + if n(k) > 0 { + sum.push_str(&format!(" · {w} {}", n(k))); + } + } + let failed = e["failed"].as_u64().unwrap_or(0); + if failed > 0 { + sum.push_str(&format!(" · 失敗 {failed}")); + } + sum.push_str(&format!(" · {}", duration_words(e["duration_ms"].as_i64().unwrap_or(0)))); + let prompt = x["prompt"].as_str().unwrap_or("").lines().next().unwrap_or("").to_string(); + let head = format!("{when} · {who} · {outcome}"); + let r = ui.add(egui::Label::new(RichText::new(&head).size(FONT_XS).color(if failed > 0 || outcome == t("失敗") { p.danger } else { p.text3 })).sense(egui::Sense::click())); + let r2 = ui.add(egui::Label::new(RichText::new(if prompt.is_empty() { t("(沒有文字)") } else { prompt }).size(FONT_SM).color(p.text)).truncate().sense(egui::Sense::click())); + let r3 = ui.add(egui::Label::new(RichText::new(&sum).size(FONT_XS).color(p.text2)).truncate().sense(egui::Sense::click())); + if r.clicked() || r2.clicked() || r3.clicked() { + toggle = Some(op.clone()); + } + if self.act.open.contains(&op) { + for (k, w) in [("looked", "看了"), ("wrote", "寫了"), ("ran", "執行了")] { + let items = e[k].as_array().cloned().unwrap_or_default(); + if items.is_empty() { + continue; + } + ui.label(RichText::new(t(w)).size(FONT_XS).strong().color(p.text2)); + for it in items { + let s = it.as_str().unwrap_or("").to_string(); + ui.add(egui::Label::new(RichText::new(format!("· {s}")).size(FONT_XS).color(p.text2)).truncate()).on_hover_text(s); + } + } + if let Some(o) = e["tools"].as_object() { + let mut v: Vec<(&String, u64)> = o.iter().map(|(k, n)| (k, n.as_u64().unwrap_or(0))).collect(); + v.sort_by_key(|(k, n)| (std::cmp::Reverse(*n), (*k).clone())); + let line = v.iter().map(|(k, n)| format!("{k} ×{n}")).collect::>().join("、"); + ui.add(egui::Label::new(RichText::new(format!("{}:{line}", t("工具"))).size(FONT_XS).color(p.text3)).wrap()); + } + } + } + }); + if let Some(op) = toggle { + if !self.act.open.remove(&op) { + self.act.open.insert(op); + } + } + } +} + +/// 2 分 13 秒; 45 秒; 1 小時 5 分. +fn duration_words(ms: i64) -> String { + let s = (ms / 1000).max(0); + match s { + 0..=59 => format!("{s} 秒"), + 60..=3599 => format!("{} 分 {} 秒", s / 60, s % 60), + _ => format!("{} 小時 {} 分", s / 3600, s % 3600 / 60), + } +} + +#[cfg(test)] +mod tests { + #[test] + fn how_long_is_said_in_words() { + assert_eq!((super::duration_words(45_400), super::duration_words(133_000), super::duration_words(3_900_000)), ("45 秒".into(), "2 分 13 秒".into(), "1 小時 5 分".into())); + } +} diff --git a/src/app/panel_ui.rs b/src/app/panel_ui.rs index c618cd7..19085ee 100644 --- a/src/app/panel_ui.rs +++ b/src/app/panel_ui.rs @@ -120,6 +120,8 @@ impl App { } } } + // 操作紀錄: what it did, turn by turn (activity_ui). + self.panel_record(ui, ctx, bot); // 建議 panel_title(ui, "建議", p); let mut open_channels = false; diff --git a/src/featuremap.rs b/src/featuremap.rs index 0df2f9f..88b71c8 100644 --- a/src/featuremap.rs +++ b/src/featuremap.rs @@ -69,6 +69,7 @@ pub const AREAS: &[Area] = &[ area!("settings", "設定總覽"), area!("appearance", "外觀與語音"), area!("garden", "園丁、待改進與更新"), + area!("activity", "操作紀錄"), ]; /// The tool a bot reads the map with. diff --git a/src/remote.rs b/src/remote.rs index 0d82d43..1c8af81 100644 --- a/src/remote.rs +++ b/src/remote.rs @@ -825,6 +825,8 @@ pub fn handle(req: Req, via_relay: bool) -> Resp { ("GET", ["api", "bots", id, "detail"]) => phone_act("detail", json!({"bot": id.parse::().unwrap_or(0)}), &role), // The audit timeline of this bot's work log (owner/admin; the phone's 稽核時間軸), // read from the 30-day SQLite audit trail (since the JSONL log shrinks at turn end). + // 操作紀錄 on a screen: the brain's audit trail (the screens' road). + ("GET", ["api", "sync", "audit", id]) => Resp::json(&crate::store::turns(id.parse().unwrap_or(0))), ("GET", ["api", "bots", id, "audit"]) => { let bid = id.parse().unwrap_or(0); let trail = crate::store::turns(bid); diff --git a/src/store.rs b/src/store.rs index 32abf45..b5ae5ef 100644 --- a/src/store.rs +++ b/src/store.rs @@ -448,6 +448,69 @@ fn insert_turn(c: &Connection, bot: i64, op: &str, at: i64, prompt: Option<&crat /// The phone's 稽核時間軸: finished turns stay here, so the page answers for /// KEEP_DAYS, not just for the turn running now. Newest turn first; the last 20 turns. +/// Who started a turn, from how its first words were written: a routine (「[例行任務]…」 or a +/// reminder 「⏰ …」), another bot (「[來自 Bot]…」), or the person. +pub fn who_started(prompt: &str) -> &'static str { + let p = prompt.trim_start(); + if p.starts_with("[例行任務]") || p.starts_with("⏰ ") { + "routine" + } else if p.starts_with("[來自 Bot]") { + "bot" + } else { + "person" + } +} + +/// What a turn did, from its steps (操作紀錄, plan D5): what it looked at (pages, files, searches), +/// what it wrote (files, pages, downloads), what it ran (commands, scripts), how many times each +/// tool, how many steps failed, and how long it took. +pub fn evidence(steps: &[serde_json::Value], started: i64) -> serde_json::Value { + use serde_json::json; + const MAX: usize = 12; + let mut looked: Vec = vec![]; + let mut wrote: Vec = vec![]; + let mut ran: Vec = vec![]; + let mut tools: std::collections::BTreeMap = Default::default(); + let (mut failed, mut last) = (0u64, started); + let add = |list: &mut Vec, s: String| { + let s = s.trim().to_string(); + if !s.is_empty() && !list.contains(&s) && list.len() < MAX { + list.push(s); + } + }; + for st in steps.iter().filter(|s| s["type"] == "tool") { + let name = st["name"].as_str().unwrap_or(""); + *tools.entry(name.to_string()).or_default() += 1; + if matches!(st["status"].as_str(), Some("failed" | "denied")) { + failed += 1; + } + last = last.max(st["end_at"].as_i64().or(st["at"].as_i64()).unwrap_or(0)); + let a: serde_json::Value = serde_json::from_str(st["args"].as_str().unwrap_or("")).unwrap_or_default(); + let g = |k: &str| a[k].as_str().unwrap_or("").to_string(); + let short = |s: String, n: usize| if s.chars().count() > n { format!("{}…", s.chars().take(n).collect::()) } else { s }; + match name { + "browser_open" | "web_fetch" => add(&mut looked, g("url")), + "read_file" => add(&mut looked, g("path")), + "list_dir" => add(&mut looked, if g("path").trim().is_empty() { "工作資料夾".to_string() } else { g("path") }), + "search" => add(&mut looked, format!("搜尋「{}」{}", g("pattern"), g("path")).trim().to_string()), + "search_documents" | "search_memory" => add(&mut looked, format!("找「{}」", g("query"))), + "read_page" => add(&mut looked, format!("頁面 {}", a["id"].as_u64().map(|i| i.to_string()).unwrap_or_else(|| g("title")))), + "edit_file" => add(&mut wrote, g("path")), + "write_page" => add(&mut wrote, format!("頁面「{}」", g("title"))), + "browser_download" => add(&mut wrote, "下載的檔案(Downloads/AnyBot)".to_string()), + "browser_pdf" => add(&mut wrote, "網頁存成 PDF(Downloads/AnyBot)".to_string()), + "shell" => add(&mut ran, short(g("command"), 100)), + "browser_eval" => add(&mut ran, format!("網頁腳本:{}", short(g("script"), 60))), + _ => {} + } + } + json!({ + "looked": looked, "wrote": wrote, "ran": ran, + "tools": tools, "failed": failed, + "duration_ms": (last - started).max(0), + }) +} + pub fn turns(bot: u64) -> serde_json::Value { let bot = bot as i64; let Some(s) = store() else { return serde_json::json!({"turns": []}) }; @@ -533,7 +596,7 @@ pub fn turns(bot: u64) -> serde_json::Value { let out: Vec = turns[turns.len() - keep..] .iter() .rev() - .map(|t| serde_json::json!({"op": t.op, "at": t.at, "prompt": t.prompt, "outcome": t.outcome, "steps": t.steps})) + .map(|t| serde_json::json!({"op": t.op, "at": t.at, "prompt": t.prompt, "outcome": t.outcome, "who": who_started(&t.prompt), "evidence": evidence(&t.steps, t.at), "steps": t.steps})) .collect(); serde_json::json!({"turns": out}) } @@ -794,6 +857,33 @@ mod tests { use super::*; use crate::oplog::{Prompt, Replay}; + /// 操作紀錄: who started a turn, and what it looked at, wrote and ran, from its steps. + #[test] + fn a_turn_says_who_started_it_and_what_it_did() { + assert_eq!(who_started("[例行任務]「Hanna Threads 海巡」時間到了:…"), "routine"); + assert_eq!(who_started("⏰ 提醒:繳電費"), "routine"); + assert_eq!(who_started("[來自 Bot]「Wang」問你:…"), "bot"); + assert_eq!(who_started("ghost太少篇了 你再多試幾個關鍵字"), "person"); + let step = |name: &str, args: serde_json::Value, status: &str, at: i64| serde_json::json!({"type": "tool", "name": name, "args": args.to_string(), "status": status, "at": at, "end_at": at + 500}); + let steps = vec![ + serde_json::json!({"type": "model", "step": "assistant", "attempts": 1}), + step("browser_open", serde_json::json!({"url": "https://www.threads.com/@hanna"}), "done", 1_000), + step("browser_open", serde_json::json!({"url": "https://www.threads.com/@hanna"}), "done", 2_000), + step("read_file", serde_json::json!({"path": "notes.md"}), "done", 3_000), + step("edit_file", serde_json::json!({"path": "report.md"}), "done", 4_000), + step("write_page", serde_json::json!({"title": "Hanna 推廣紀錄"}), "done", 5_000), + step("shell", serde_json::json!({"command": "ls -la ~/Downloads"}), "failed", 6_000), + step("browser_press", serde_json::json!({"key": "ctrl+Return"}), "denied", 7_000), + ]; + let e = evidence(&steps, 0); + assert_eq!(e["looked"], serde_json::json!(["https://www.threads.com/@hanna", "notes.md"]), "once each"); + assert_eq!(e["wrote"], serde_json::json!(["report.md", "頁面「Hanna 推廣紀錄」"])); + assert_eq!(e["ran"], serde_json::json!(["ls -la ~/Downloads"])); + assert_eq!((e["tools"]["browser_open"].as_u64(), e["failed"].as_u64(), e["duration_ms"].as_i64()), (Some(2), Some(2), Some(7_500))); + assert_eq!(evidence(&[], 9)["duration_ms"], 0); + assert_eq!(evidence(&[step("list_dir", serde_json::json!({}), "done", 1)], 0)["looked"], serde_json::json!(["工作資料夾"])); + } + #[test] fn the_memory_index_answers_in_chinese() { // (One database per test process, one bot id: 4243 is ours here.)