diff --git a/.claude/skills/verify-anybot/SKILL.md b/.claude/skills/verify-anybot/SKILL.md index 063d644..516f9b1 100644 --- a/.claude/skills/verify-anybot/SKILL.md +++ b/.claude/skills/verify-anybot/SKILL.md @@ -74,12 +74,13 @@ $CTL phone login # 手機密碼從 scratch 的檔案打進去(不 | `wait [秒]`、`wait-gone [秒]` | 等元素出現(看得見)/消失 | | `wait-text <字> [--in ] [秒]` | 等畫面(或某一塊)出現這些字 | | `click [--text <字>]` | 在元素正中間按一下;`--text` 選含這些字的那一個 | -| `longpress [--text <字>] [毫秒]`、`longpress --selected` | 手指按住(觸控)元素正中間或選取的字,預設 800 毫秒再放開;印出 contextmenu「頁面攔下」(頁面自己的選單)、「頁面沒攔」(瀏覽器自己的,不畫出來)或「沒有 contextmenu」 | +| `longpress [--text <字>] [毫秒]`、`longpress --selected` | 手指按住(觸控)元素正中間或選取的字,預設 800 毫秒再放開;印出 contextmenu「頁面攔下」(頁面自己的選單)、「頁面沒攔」(瀏覽器自己的,不畫出來)或「沒有 contextmenu」。`long-press` 是同一個動作 | | `rightclick [--text <字>]`、`rightclick --selected` | 滑鼠右鍵,一樣印出 contextmenu 給了誰 | | `drag-select <字>` | 用滑鼠從這段字的頭拖到尾(像人選取一段),印出選到的字 | | `selection [字]` | 印出選取的字;給了字就要剛好是它(`''`:什麼都沒選) | | `copy`、`clipboard [字]` | 像按 ⌘C 複製選取的字;印出剪貼簿(給了字就要剛好是它)。都是無頭 Chrome 自己的剪貼簿,不碰這台 Mac 的 | | `send <字>` | 在聊天的輸入框 `#input` 打字、按送出 `#b-send` | +| `upload <檔>` | 在檔案選擇欄(`input type=file`,隱藏的也可以)選這個檔案,代替系統的檔案選擇器;聊天的附件是 `upload '#file' <檔>`,送出前 `wait-text <檔名> --in '#chips'` | | `type <字>` | 點進輸入框、清空、像鍵盤一樣打字 | | `press Enter`(`Escape`、`Tab`、`Backspace`) | 按鍵 | | `text [css]` | 印出看得到的字 | diff --git a/.claude/skills/verify-anybot/scripts/ctl b/.claude/skills/verify-anybot/scripts/ctl index 1e01e5a..90d704c 100755 --- a/.claude/skills/verify-anybot/scripts/ctl +++ b/.claude/skills/verify-anybot/scripts/ctl @@ -16,7 +16,7 @@ # ctl model-reply <比對的字> <回答> | --clear 之後 system 或最後一則使用者訊息含這段字的請求,假模型回這個答案 # ctl model [jq 篩選] 假模型收到的請求(model-requests.jsonl,一行一個) # ctl procs [--none] <字> 這次 scratch 開的程式(環境帶著 scratch 的 HOME)裡,指令列含這段字的;--none:要一個都沒有 -# ctl phone <動作> … 用無頭 Chrome 操作手機頁面(start、open [--listed]、login [--wrong]、send <字>、click、type、wait…、shot、stop) +# ctl phone <動作> … 用無頭 Chrome 操作手機頁面(start、open [--listed]、login [--wrong]、send <字>、click、long-press、upload、type、wait…、shot、stop) # ctl fingerprint 比對連上時拿到的憑證和資料夾裡的 lan-cert.der # ctl desktop-shot <名稱> [ANYBOT_SHOT_*=值 …] 把桌面視窗畫成圖(會在螢幕上開一下視窗:要 ABV_ALLOW_WINDOW=1) # ctl down 關掉這次開的一切、把最後狀態抄進證據、刪 scratch;證據留著 @@ -419,7 +419,7 @@ cmd_phone() { node "$PHONE" --state "$st" type '#input' "$1" node "$PHONE" --state "$st" click '#b-send' ;; stop) node "$PHONE" --state "$st" stop; setv CHROME_PID "" ;; - "") die "ctl phone …" ;; + "") die "ctl phone …" ;; *) node "$PHONE" --state "$st" --out "$RUN/phone" "$sub" "$@" ;; esac } diff --git a/.claude/skills/verify-anybot/scripts/phone.mjs b/.claude/skills/verify-anybot/scripts/phone.mjs index 2cf62bf..7d4f49b 100755 --- a/.claude/skills/verify-anybot/scripts/phone.mjs +++ b/.claude/skills/verify-anybot/scripts/phone.mjs @@ -9,13 +9,14 @@ // wait-gone [秒] 等元素消失或看不見 // wait-text <字> [--in ] [秒] 等畫面上出現這些字 // click [--text <字>] 在元素正中間按一下(有 --text:符合 css 而且含這些字的那一個) -// longpress |--selected [--text <字>] [毫秒] 手指按住元素正中間(或選取的字)再放開(預設 800 毫秒) +// longpress |--selected [--text <字>] [毫秒] 手指按住元素正中間(或選取的字)再放開(預設 800 毫秒);long-press 是同一個動作 // rightclick |--selected [--text <字>] 滑鼠右鍵;兩個都印出 contextmenu 給了頁面還是瀏覽器 // drag-select <字> 用滑鼠從這段字的頭拖到尾(像人選取一段),印出選到的字 // selection [字] 印出現在選取的字;給了字就要剛好是它('' 是什麼都沒選) // copy 像按 ⌘C:瀏覽器自己複製選取的字(進無頭 Chrome 自己的剪貼簿,不碰這台 Mac 的) // clipboard [字] 印出無頭 Chrome 剪貼簿裡的字;給了字就要剛好是它 // type <字> | --file <檔> 點進輸入框、清空、像鍵盤一樣打進去(--file:字從檔案讀,密碼不進指令列) +// upload <檔> 在檔案選擇欄(input type=file,可以是隱藏的)選這個檔案,等於系統的檔案選擇器選好按「打開」 // press <鍵> Enter、Escape、Tab、Backspace // text [css] 印出看得到的字 // shot <名稱> 證據:/NN-名稱.png(截圖)、.ax.txt(無障礙樹)、.txt(看得到的字) @@ -275,7 +276,7 @@ async function main() { await mouseClick(c, x, y); break; } - case "longpress": case "rightclick": { + case "longpress": case "long-press": case "rightclick": { const { x, y } = rest[0] === "--selected" ? await selectedMiddle(c) : await center(c, rest[0] || die(`${cmd} 要 css 或 --selected`), TEXT); await c.evaluate(MENU_WATCH); if (cmd === "rightclick") { @@ -324,6 +325,16 @@ async function main() { if (rest[0] !== undefined && t !== rest[0]) die(`剪貼簿裡是「${t}」,不是「${rest[0]}」`); break; } + case "upload": { + // 系統的檔案選擇器開不了(無頭):直接把檔案放進那個 input,頁面照樣收到 change。 + const file = rest[1] || die("upload 要 css 和檔案"); + if (!fs.existsSync(file)) die(`沒有這個檔案:${file}`); + const { root } = await c.send("DOM.getDocument", { depth: 0 }); + const { nodeId } = await c.send("DOM.querySelector", { nodeId: root.nodeId, selector: rest[0] }); + if (!nodeId) die(`找不到 ${rest[0]}`); + await c.send("DOM.setFileInputFiles", { nodeId, files: [path.resolve(file)] }); + break; + } case "type": { const css = rest[0]; const text = FILE ? fs.readFileSync(FILE, "utf8").trim() : rest[1]; diff --git a/docs/feature-map/garden.md b/docs/feature-map/garden.md index 7fa6131..f4dba3f 100644 --- a/docs/feature-map/garden.md +++ b/docs/feature-map/garden.md @@ -34,7 +34,7 @@ AnyBot 自己照顧自己:Bot 做事遇到 AnyBot 本身的問題會記成「 - **版本**(covers `garden-update`):帳戶選單 › 設定 › 更新。指令:`$CTL phone open --listed && $CTL phone click '#b-me' && $CTL phone click '#sheet-in .opt' --text 設定 && $CTL phone click '[data-go="updates"]' && $CTL phone wait-text 已是最新版 --in '#list' && $CTL api GET /api/settings --jq '{version, newer}'`。看到:版本(這個 checkout 的 HEAD)和建置時間、「已是最新版」。 - **電腦版 設定 › 更新**(covers `garden-issues`、`garden-update`、`garden-daily`):指令:要開視窗——`$CTL stop && ABV_ALLOW_WINDOW=1 $CTL desktop-shot garden-updates ANYBOT_SHOT_TAB=updates`(示範資料:真資料的截圖打不開 更新;有新版:加 `ANYBOT_SHOT_NEWER=0`)。看到:「自動更新」「園丁報告」開關、「重新啟動」;示範資料沒有待改進,「待改進」那一條的 ×2 和「全部清除」靠上面那一步的 state 和 `cargo test garden::`。 - **有事的報告、當掉**(covers `garden-daily`、`garden-weekly`、`garden-crash`):指令:走不到——scratch 一開就把今天那份看過(沒事不報),下一份要明天平日 8:44、每週要週一;「園丁報告」開關只在電腦版;當掉要程式真的出錯。看到:最接近的真路是自動測試(有失敗才報、一天一次、每週只列花太多的、當掉報告只說一次又遮過);關掉「園丁報告」兩種都不出現要在電腦版看。 -- 自動測試:`cargo test garden::`、`cargo test memory::`(`anybots_own_problems_are_reported_apart_from_the_skill`)、`cargo test logfile::`、`cargo test doctor::`。 +- 自動測試:`cargo test garden::`、`cargo test anybots_own_problems`(整理做法時另外記;一輪做完之後才回報的也記進清單)、`cargo test logfile::`、`cargo test doctor::`。 ## 陷阱 diff --git a/docs/feature-map/replay.md b/docs/feature-map/replay.md index aa98fd1..b8217f2 100644 --- a/docs/feature-map/replay.md +++ b/docs/feature-map/replay.md @@ -25,16 +25,17 @@ - **做五步、學會**(covers `replay-learn`、`replay-steps`):指令:`$CTL model-reply 整理經驗 '{"save":true,"name":"記一筆","description":"在 log.txt 記一筆","instructions":"用 shell 在 log.txt 加一行。注意:一次一行。","replay":[9],"blanks":{"第五筆":"內容"},"tool_issues":[]}' && $CTL phone send '記五筆 [[call shell {"command":"sleep 4; echo 1"}]]' && $CTL wait-api /api/bots/1 '[.messages[].tools[]?] | length == 1' && $CTL phone send '[[call shell {"command":"sleep 4; echo 2"}]]' && $CTL wait-api /api/bots/1 '[.messages[].tools[]?] | length == 2' && $CTL phone send '[[call shell {"command":"sleep 4; echo 3"}]]' && $CTL wait-api /api/bots/1 '[.messages[].tools[]?] | length == 3' && $CTL phone send '[[call shell {"command":"sleep 4; echo 4"}]]' && $CTL wait-api /api/bots/1 '[.messages[].tools[]?] | length == 4' && $CTL phone send '[[call shell {"command":"echo 第五筆 >> log.txt"}]]' && $CTL phone wait-text '學會了新做法「記一筆」' --in '#msgs' 60 && $CTL phone shot replay-learned && $CTL model 'select(.rule) | .user_full | split(":\n- ")[0]' && $CTL state '.skills[] | select(.name == "記一筆") | .steps'`。看到:一輪五個「執行指令」,回覆下面「(學會了新做法「記一筆」,下次做這件事會照著做。)」;回頭看的請求列了每一步(插話也各佔一號,第五步是 9)和「已經有的技能」;技能只留那一步,「第五筆」變成 `{{內容}}`。 - **重播、填空格**(covers `replay-steps`):先不給空格,再給;再看設定 › 整合 的清單。指令:`$CTL phone send '[[call replay_skill {"name":"記一筆"}]]' && $CTL phone wait-text '「記一筆」每次要填:內容' --in '#msgs' && $CTL phone send '[[call replay_skill {"name":"記一筆","values":{"內容":"重播的一筆"}}]]' && $CTL phone wait-text '重播「記一筆」做完了' --in '#msgs' && $CTL phone wait-text '重播技能' --in '#msgs' && $CTL phone shot replay-run && $CTL botfile log.txt && $CTL api GET /api/bots/1 --jq '[.messages[].tools[]? | select(.label == "重播技能") | .detail]' && $CTL api GET /api/bots/1 --jq '[.messages[] | select(.via | test("重播")) | .tools[].detail]' && $CTL phone open --listed && $CTL phone click '#b-me' && $CTL phone click '#sheet-in .opt' --text 設定 && $CTL phone click '[data-go="integrations"]' && $CTL phone wait-text '可重播 1 步' --in '#list'`。看到:第一次「「記一筆」每次要填:內容。用 values…」;第二次(電腦版「正在照技能重做:記一筆」)「執行指令 echo 重播的一筆 >> log.txt」沒經過模型(那一則標「fake-model(重播)」),回覆帶「(重播「記一筆」做完了,共 1 步。…)」;兩次叫重播的那一步都寫「重播技能 「記一筆」」;log.txt 多一行「重播的一筆」;清單裡記一筆標「可重播 1 步」。 -- **教我做(大腦那邊)**(covers `replay-teach`):做一回合,再送「教我做」選單送的同一個請求。指令:`$CTL phone open --listed && $CTL phone click '.row[data-bot="1"]' && $CTL phone send '寫教學 [[call shell {"command":"echo 教 >> teach.txt"}]]' && $CTL wait-api /api/bots/1 '[.messages[].tools[]? | select(.detail | test("teach"))] | length == 1' && $CTL api POST /api/act/app '{"name":"skillify","args":{"prompt":"寫教學 [[call shell {\"command\":\"echo 教 >> teach.txt\"}]]"}}'`。看到:「已把「…」那一回合存成技能「…」(1 步可重播),…」。 -- **教我做的選單**(covers `replay-teach`):按住自己那則「寫教學」,看選單。指令:`$CTL phone longpress '.m.user .bub' --text 寫教學 && $CTL phone wait-text 教我做 --in '#sheet-in' && $CTL phone shot replay-teach`。看到:自己訊息的選單有「複製」「選取文字」「引用回覆」「教我做(學這一回合)」;「教我做」送的就是上一步那個請求(存成技能看上一步)。 +- **教我做**(covers `replay-teach`):做一回合、等它做完,按住自己那則訊息 ›「教我做(學這一回合)」。指令:`$CTL phone open --listed && $CTL phone click '.row[data-bot="1"]' && $CTL phone send '寫教學 [[call shell {"command":"echo 教 >> teach.txt"}]]' && $CTL wait-api /api/bots/1 '[.messages[].tools[]? | select(.detail | test("teach"))] | length == 1' && $CTL wait-api '/api/state?since=0' '.bots[0].busy == false' && $CTL phone longpress '.m.user .bub' --text 寫教學 && $CTL phone wait-text 教我做 --in '#sheet-in' && $CTL phone shot replay-teach-menu && $CTL phone click '#sheet-in .opt' --text 教我做 && $CTL phone wait-text 已存成技能 --in '#toast' && $CTL phone shot replay-teach-saved && $CTL api GET /api/settings --jq '[.skills[] | select(.description | startswith("示範學會:寫教學")) | {name, description, steps}]'`。看到:選單有表情、「複製」「選取文字」「引用回覆」「教我做(學這一回合)」;按了跳「已存成技能,下次說名字就會照做」;多一個技能「寫教學 [[call shell {"comma」,steps 1,說明照那一回合原本的字「示範學會:寫教學 …echo 教 >> teach.txt…」——那一回合已經做完,照樣找得到。 +- **重新產生之後教我做**(covers `replay-teach`):送一句、做完,指定重做時換一個指令,按回答下面的「重新產生」,再按住那則訊息 ›「教我做」。指令:`$CTL phone send '簽到 [[call shell {"command":"echo wrong >> sign.txt"}]]' && $CTL wait-api /api/bots/1 '[.messages[].tools[]? | select(.detail | test("wrong"))] | length == 1' && $CTL wait-api '/api/state?since=0' '.bots[0].busy == false' && $CTL model-reply '簽到 [[call' '[[call shell {"command":"echo right >> sign.txt"}]]' && $CTL phone click '[data-regen]' && $CTL wait-api /api/bots/1 '[.messages[].tools[]? | select(.detail | test("right"))] | length == 1' && $CTL wait-api '/api/state?since=0' '.bots[0].busy == false' && $CTL phone longpress '.m.user .bub' --text 簽到 && $CTL phone click '#sheet-in .opt' --text 教我做 && $CTL phone wait-text 已存成技能 --in '#toast' && $CTL phone shot replay-teach-regenerated && $CTL state '[.skills[] | select(.description | startswith("示範學會:簽到")) | .steps[].args]'`。看到:聊天裡留下的是重做的那次(「執行指令 echo right >> sign.txt」);存的技能只有一步,是 `echo right >> sign.txt`——學的是聊天裡留著的那一次,不是被換掉的第一次(說明照那則訊息的字,所以還寫著 wrong)。 - **網站地圖**(covers `replay-map`):指令:走不到——地圖的內容是真的模型照回頭看的提示寫的(假模型照劇本回)。看到:最接近的真路是第一步:回頭看的請求帶著「已經有的技能」,同名就合併;寫法靠自動測試。 -- 自動測試:`cargo test memory::`(`a_long_enough_job_is_looked_back_on`、`what_differs_each_time_becomes_a_blank_filled_at_replay`)、`cargo test a_skill_is_replayed_without_the_model_in_between`、`cargo test skills::`、`cargo test agent::`。 +- 自動測試:`cargo test memory::`(`a_long_enough_job_is_looked_back_on`、`what_differs_each_time_becomes_a_blank_filled_at_replay`、`the_phones_plain_words_find_the_turn`、`the_message_pressed_is_the_turn_learned`、`a_message_with_a_file_and_an_older_turn_can_be_taught`)、`cargo test appctl::`(`a_turn_that_has_ended_can_still_be_taught`、`after_regenerating_the_attempt_shown_is_learned`、`a_skill_learned_in_a_branch_is_the_main_bots`)、`cargo test store::`、`cargo test a_skill_is_replayed_without_the_model_in_between`、`cargo test skills::`、`cargo test agent::`。 ## 陷阱 - 自動學到的、「教我做」存的技能,都自動算進那個 Bot 自己的技能清單(支線學的算主 Bot 的)。 - `replay_skill` 屬於「看螢幕與操作」能力:沒有這個能力的 Bot、別人(訊息管道、團隊成員)傳來的那一輪都沒有它。技能沒存步驟就只能讀了自己做。 - 重播會停下來:空格沒給齊(會說要填哪幾格);畫面上找不到同一種、同名的東西時先自動截一次圖再找,還是沒有就停在第幾步交還給 Bot;任何一步失敗、被拒或重複,後面都不做。有風險的步驟照樣問使用者。 -- 某一步點的東西說不出名字(只有編號),整份就不存步驟;「教我做」也會丟掉只看畫面的步驟和照編號點的步驟。 +- 某一步點的東西說不出名字(只有編號),整份就不存步驟;「教我做」也會丟掉只看畫面、讀說明或技能、重播的步驟和照編號點的步驟。 +- 「教我做」學的是那則訊息開始的那一回合(同一句話別次做的不算);按過重新產生、重新傳送或重試,學的是聊天裡留著的最後那一次。只找得到 30 天內的;更早的、做事中途插的話,會說「找不到以「…」開始的那一回合」;只有看畫面或都失敗的會說「那一回合沒有可重播的步驟」。舊版手機頁面不帶訊息的時間、或那一回合是這一版以前做的(沒記時間),就學最近一次以同樣的話開始的回合(插的話跟某一回合開頭一樣,會學到那一回合)。 - `save_skill` 存同名的技能會把原本存的可重播步驟一起換掉([skills](skills.md))。 - (驗證)插話太慢,那一輪會先結束、五步被拆成兩輪就不會學:每一步送出後立刻等下一個步驟出現再送。 diff --git a/mobile/index.html b/mobile/index.html index 450bedc..96cade8 100644 --- a/mobile/index.html +++ b/mobile/index.html @@ -1608,7 +1608,7 @@ function msgMenu(i) { if (m.text) items.push({icon: "text-cursor", label: "選取文字", on: () => selectSheet(i, m)}); if (m.text && m.role !== "user" && S.voice.speak) items.push({icon: "audio-lines", label: "唸出來", on: () => speakText(m.text)}); if (m.text && owner()) items.push({icon: "reply", label: "引用回覆", on: () => { S.quote = {text: plain(m.text).slice(0, 300), raw: m.text}; renderQuote(); $("input").focus(); }}); - if (m.text && owner() && m.role === "user") items.push({icon: "sparkles", label: "教我做(學這一回合)", on: async () => { if (await app("skillify", {prompt: plain(m.text).slice(0, 200)}, 0, "已存成技能,下次說名字就會照做")) again(); }}); + if (m.text && owner() && m.role === "user") items.push({icon: "sparkles", label: "教我做(學這一回合)", on: () => app("skillify", {prompt: plain(m.text).slice(0, 200), at: m.at}, 0, "已存成技能,下次說名字就會照做")}); const lastBot = [...S.msgs].reverse().find((x) => x.role !== "user" && x.text); if (m === lastBot && owner()) items.push({icon: "refresh", label: "重新產生這個回答", on: regen}); // 重新產生 kept what it replaced (on the brain): put it back. diff --git a/src/app.rs b/src/app.rs index bf458ff..917fa49 100644 --- a/src/app.rs +++ b/src/app.rs @@ -2961,6 +2961,17 @@ impl App { self.dirty = true; continue; } + // 待改進: AnyBot's own problems the same look back found, queued for whoever fixes + // AnyBot — after the turn too. (A branch's are its main bot's, as its skills are.) + if let StreamEvent::Issues(list) = ev { + let name = self.state.bot(self.state.home_of(id)).map(|b| b.name.clone()).unwrap_or_default(); + let now = crate::routines::now(); + for i in &list { + crate::garden::note_issue(&mut self.state.improvements, i, &name, now); + } + self.dirty = true; + continue; + } // 目標: the check after a turn has spoken. if let StreamEvent::Goal(since, judged) = ev { self.goal_verdict(ctx, id, since, judged); @@ -3138,14 +3149,6 @@ impl App { m.images.clear(); } } - // 待改進: AnyBot's own problems this bot ran into, queued for whoever fixes AnyBot. - StreamEvent::Issues(list) => { - let name = b.name.clone(); - let now = crate::routines::now(); - for i in &list { - crate::garden::note_issue(&mut self.state.improvements, i, &name, now); - } - } // The model said how much it reads: this bot summarizes in time from now on. StreamEvent::ContextLimit(n) => { b.context_tokens = n; @@ -8296,6 +8299,26 @@ mod tests { } } + /// 待改進: the look back that finds AnyBot's own problems runs after the turn has ended + /// (agent::learn, after Done) — what it reports is queued then, like the skill it learns, + /// not dropped with a finished turn's leftovers. + #[test] + fn anybots_own_problems_found_after_the_turn_reach_the_list() { + let ctx = egui::Context::default(); + let mut app = super::App::new(&ctx, Some(std::env::temp_dir().join("anybot-issues-after-turn.png"))); + let id = app.state.bots[0].id; + let name = app.state.bots[0].name.clone(); + app.state.improvements.clear(); + app.streams.insert(id, Live { cancel: Arc::new(AtomicBool::new(false)), started: Instant::now(), last: Instant::now(), produced: true, status: None, paused: false, paused_at: None, unattended: false, steer: Arc::new(Mutex::new(vec![])), direct: Arc::new(AtomicBool::new(false)), turn_id: "t".into(), turn: 1 }); + // As agent.rs sends them: the turn is done, then the look back reports. + app.tx.send((id, 1, StreamEvent::Done)).unwrap(); + app.tx.send((id, 1, StreamEvent::Issues(vec!["browser_fill_contact 填不進電話欄".into(), "browser_fill_contact 又填錯欄".into()]))).unwrap(); + app.drain_events(&ctx); + assert!(!app.streams.contains_key(&id), "the turn is over"); + let got: Vec<(String, u32, Vec)> = app.state.improvements.iter().map(|i| (i.text.clone(), i.count, i.bots.clone())).collect(); + assert_eq!(got, vec![("browser_fill_contact 填不進電話欄".to_string(), 2, vec![name])], "one item for the one tool, counted twice"); + } + /// A question that takes another's place with the same call id (call_0 every round) and as /// many questions — the last one answered on the phone, or while this chat wasn't open — /// starts fresh: it doesn't take the last one's step and picks, so 送出 can't send answers diff --git a/src/appctl.rs b/src/appctl.rs index 8457063..475cfbf 100644 --- a/src/appctl.rs +++ b/src/appctl.rs @@ -411,6 +411,8 @@ pub fn routine_report(r: &Routine) -> String { /// A skill this bot just learned is one of its own; the others learn it when the person ticks /// it for them (Bot 設定 › 技能). Says who can use it now. fn learned(state: &mut State, bot_id: u64, name: &str) -> String { + // (A branch's is its main bot's.) + let bot_id = state.home_of(bot_id); give_skill(state, bot_id, name); if state.bots.iter().any(|b| b.id != bot_id && b.skills.is_some()) { "你會用了;其他 Bot 要在 Bot 設定 › 技能勾選才會。".into() @@ -804,9 +806,13 @@ pub fn apply(state: &mut State, bot_id: u64, name: &str, args: &str) -> Outcome if prompt.is_empty() { return err("要學的是哪件事?".into()); } - let recs = crate::oplog::OpLog::for_bot(bot_id).read(); - match crate::memory::skillify(&prompt, &recs) { - Some(sk) => { + // That turn has usually ended (the person presses it under their own message): the + // work log keeps only the open turn; the audit trail keeps each one KEEP_DAYS. Which + // turn from the turns' first lines (`at`: when the message was sent), then that one's steps. + let taught = crate::memory::taught_turn(&prompt, v["at"].as_i64(), &crate::store::turn_starts(bot_id)) + .and_then(|(op, said)| crate::memory::skillify(&said, &crate::store::turn_records(bot_id, &op))); + match taught { + Ok(sk) => { let n = sk.steps.len(); let name = sk.name.clone(); if let Some(why) = branch_replaces_skill(state, asker, &name) { @@ -816,7 +822,7 @@ pub fn apply(state: &mut State, bot_id: u64, name: &str, args: &str) -> Outcome let who = learned(state, bot_id, &name); ok(format!("已把「{prompt}」那一回合存成技能「{name}」({n} 步可重播),{who}")) } - None => err("那一回合沒有可重播的步驟(只有看畫面的動作,或都失敗了)".into()), + Err(why) => err(why), } } "create_bot" => { @@ -1071,6 +1077,72 @@ mod tests { assert!(st.bot(other).unwrap().skills.is_none()); } + /// 教我做 is pressed under a message whose turn is over — and a turn's work log is gone the + /// moment it ends. The audit trail still has its steps. + #[test] + fn a_turn_that_has_ended_can_still_be_taught() { + use crate::oplog::{OpLog, Outcome, Prompt, Record, Replay}; + let mut st = State::samples(); + // (Its own id: this process's tests share one trail.) + let bot = 7341; + st.bots[0].id = bot; + let log = OpLog::for_bot(bot); + let now = crate::model::now_ms(); + let said = "寫教學 [[call shell {\"command\":\"echo 教 >> teach.txt\"}]]"; + log.append(&Record::OperationStarted { op: "teach-1".into(), at: now, source_leaf: 0, prompt: Some(Prompt { at: now, text: said.into() }) }); + log.append(&Record::ToolStarted { op: "teach-1".into(), call_id: "c1".into(), name: "shell".into(), args: "{\"command\":\"echo 教 >> teach.txt\"}".into(), replay: Replay::Never, at: now + 1 }); + log.append(&Record::ToolFinished { op: "teach-1".into(), call_id: "c1".into(), status: "done".into(), at: now + 2 }); + log.finish("teach-1", Outcome::Completed); + assert!(log.read().is_empty(), "the turn's work log is gone once it ends"); + let out = apply(&mut st, bot, "skillify", &json!({"prompt": said}).to_string()); + assert!(out.ok && out.text.contains("(1 步可重播)"), "{}", out.text); + let k = st.skills.iter().find(|k| k.description == format!("示範學會:{said}")).expect("saved"); + assert_eq!((k.steps.len(), k.steps[0].tool.as_str(), k.steps[0].args.as_str()), (1, "shell", "{\"command\":\"echo 教 >> teach.txt\"}")); + let none = apply(&mut st, bot, "skillify", r#"{"prompt":"沒做過的事"}"#); + assert!(!none.ok && none.text.contains("找不到以「沒做過的事」開始的那一回合"), "{}", none.text); + } + + /// 重新產生 starts the same message again: 教我做 under it learns the attempt the chat shows + /// (the last), not the one it replaced — the trail keeps when each turn's message was sent. + #[test] + fn after_regenerating_the_attempt_shown_is_learned() { + use crate::oplog::{OpLog, Outcome, Prompt, Record, Replay}; + let mut st = State::samples(); + let bot = 7342; + st.bots[0].id = bot; + let log = OpLog::for_bot(bot); + let sent = crate::model::now_ms() - 10_000; + let said = "簽到 [[call shell {\"command\":\"echo wrong >> sign.txt\"}]]"; + for (op, started, cmd) in [("try-1", sent + 5, "echo wrong >> sign.txt"), ("try-2", sent + 5_000, "echo right >> sign.txt")] { + log.append(&Record::OperationStarted { op: op.into(), at: started, source_leaf: sent, prompt: Some(Prompt { at: sent, text: said.into() }) }); + log.append(&Record::ToolStarted { op: op.into(), call_id: "c1".into(), name: "shell".into(), args: json!({"command": cmd}).to_string(), replay: Replay::Never, at: started + 1 }); + log.append(&Record::ToolFinished { op: op.into(), call_id: "c1".into(), status: "done".into(), at: started + 2 }); + log.finish(op, Outcome::Completed); + } + let out = apply(&mut st, bot, "skillify", &json!({"prompt": said, "at": sent}).to_string()); + assert!(out.ok, "{}", out.text); + let k = st.skills.iter().find(|k| k.description == format!("示範學會:{said}")).expect("saved"); + assert_eq!(k.steps[0].args, json!({"command": "echo right >> sign.txt"}).to_string()); + // A message sent at another time (a 插話 with the same words) started neither. + let other = apply(&mut st, bot, "skillify", &json!({"prompt": said, "at": sent + 1_000}).to_string()); + assert!(!other.ok && other.text.contains("找不到"), "{}", other.text); + } + + /// A branch's skill is its main bot's (as everything it keeps). + #[test] + fn a_skill_learned_in_a_branch_is_the_main_bots() { + let mut st = State::samples(); + let main = st.bots[0].id; + st.bot_mut(main).unwrap().skills = Some(vec![]); + let mut b = st.bots[0].clone(); + b.id = 778; + b.branch_of = main; + st.branch_bots.push(b); + learned(&mut st, 778, "支線學的"); + assert_eq!(st.bot(main).unwrap().skills.clone().unwrap(), vec!["支線學的".to_string()]); + assert!(!st.bot(778).unwrap().skills.clone().unwrap_or_default().contains(&"支線學的".to_string())); + } + #[test] fn a_routine_can_say_how_many_it_is_to_send_and_the_run_is_told() { let mut st = State::samples(); diff --git a/src/attach.rs b/src/attach.rs index 3d4398e..865b2bc 100644 --- a/src/attach.rs +++ b/src/attach.rs @@ -256,10 +256,25 @@ pub fn for_model(atts: &[Attachment]) -> (String, Vec) { (text, images) } +/// The words a person wrote, without what for_model put after them (a turn's first line in the +/// work log is the model's copy of the message). +pub fn typed_part(text: &str) -> &str { + text.find("\n\n[附件").map_or(text, |i| &text[..i]) +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn the_words_typed_come_back_from_the_models_copy() { + let a = |name: &str| Attachment { name: name.into(), path: format!("/nowhere/{name}"), image: name.ends_with(".png"), bytes: 3, on_box: String::new() }; + let (extra, _) = for_model(&[a("貓.png"), a("帳.bin")]); + assert!(extra.contains("[附件圖片「貓.png」") && extra.contains("[附件「帳.bin」"), "{extra}"); + assert_eq!(typed_part(&format!("看這張\n第二行{extra}")), "看這張\n第二行"); + assert_eq!(typed_part("沒有附件"), "沒有附件"); + } + #[test] fn text_and_images_reach_the_model() { let dir = std::env::temp_dir().join(format!("anybot-attach-test-{}", std::process::id())); diff --git a/src/memory.rs b/src/memory.rs index 783e9db..54cab7e 100644 --- a/src/memory.rs +++ b/src/memory.rs @@ -196,41 +196,64 @@ pub fn merge_skill_files(skills: &mut Vec) -> usize { n } -/// C8: 示範即教學 — turn the most recent finished turn that answered `prompt` into a skill, -/// keeping the steps that worked and threw nothing away. Looking steps (screenshots, reads) are -/// dropped: a replay looks for itself. Steps that point at a number on the screen (ref) are -/// dropped too — numbers only live as long as the look that made them. -pub fn skillify(prompt: &str, recs: &[crate::oplog::Record]) -> Option { - let key: String = prompt.chars().take(40).collect(); - let mut op = String::new(); - for r in recs.iter().rev() { - if let crate::oplog::Record::OperationStarted { op: o, prompt: Some(p), .. } = r { - if p.text.chars().take(40).collect::() == key { - op = o.clone(); - break; - } - } - } - if op.is_empty() { - return None; - } +/// A message's words as the phone's 教我做 sends them (its `plain()`): link targets, markdown +/// marks and line breaks gone. A turn is found by these, whichever way its words arrive. +fn plain_words(t: &str) -> String { + static LINK: std::sync::OnceLock = std::sync::OnceLock::new(); + let link = LINK.get_or_init(|| regex::Regex::new(r"\[([^\]]+)\]\([^)]+\)").expect("link pattern")); + let t: String = link.replace_all(t, "$1").chars().filter(|c| !"*_`#>".contains(*c)).collect(); + t.split_whitespace().collect::>().join(" ") +} + +/// Which turn 教我做 means: the one the pressed message started. `at` is when that message was +/// sent; one message can start several turns (重新產生、重新傳送、重試 start it again) and the +/// chat shows the last, so it is the latest turn started by that very message (by its time +/// alone: the model's copy of the words carries its attachments' text too) — none (a 插話 starts +/// no turn of its own): not found. Without `at` (an older phone page), or for a turn kept before +/// the trail had the time (0), it is the latest turn started by the same words. `starts`: the +/// turns' first lines (store::turn_starts). Ok: (that turn, the words the person typed). +pub fn taught_turn(prompt: &str, at: Option, starts: &[crate::oplog::Record]) -> Result<(String, String), String> { + // A message from before times were kept says `at: 0`: that names no turn — go by its words. + let at = at.filter(|t| *t > 0); + let key: String = plain_words(prompt).chars().take(40).collect(); + let same_words = |p: &crate::oplog::Prompt| plain_words(crate::attach::typed_part(&p.text)).chars().take(40).collect::() == key; + let latest = |ok: &dyn Fn(&crate::oplog::Prompt) -> bool| { + starts.iter().rev().find_map(|r| match r { + crate::oplog::Record::OperationStarted { op, prompt: Some(p), .. } if ok(p) => Some((op.clone(), crate::attach::typed_part(&p.text).to_string())), + _ => None, + }) + }; + let found = match at { + Some(t) => latest(&|p| p.at == t).or_else(|| latest(&|p| p.at == 0 && same_words(p))), + None => latest(&same_words), + }; + found.ok_or_else(|| format!("找不到以「{prompt}」開始的那一回合(只找得到 {} 天內、由一則訊息開始的回合;做事中途插的話不算)", crate::store::KEEP_DAYS)) +} + +/// Steps a replay never repeats: looking (a replay looks for itself), reading a guide or a skill, +/// replaying one. The learner (replay_steps) and 教我做 (skillify) drop the same ones. +fn never_replayed(name: &str) -> bool { + matches!(name, "computer_use_screenshot" | "computer_use_zoom" | "computer_use_show" | "browser_read" | "browser_screenshot" | "browser_elements" | "browser_sent_log" | "anybot_guide" | "use_skill" | "replay_skill") +} + +/// C8: 示範即教學 — a turn's steps that worked and threw nothing away, as a skill named in the +/// words that started it (`said`; `recs`: that turn's lines, store::turn_records). Steps a replay +/// never repeats are dropped, and so are steps that point at a number on the screen (ref) — +/// numbers only live as long as the look that made them. Err: why nothing was saved. +pub fn skillify(said: &str, recs: &[crate::oplog::Record]) -> Result { let mut done: Vec<(String, bool)> = vec![]; // index-parallel with steps: (call_id, finished ok) let mut steps: Vec<(String, String)> = vec![]; for r in recs { match r { - crate::oplog::Record::ToolStarted { op: o, call_id, name, args, .. } if o == &op => { + crate::oplog::Record::ToolStarted { call_id, name, args, .. } => { let a: serde_json::Value = serde_json::from_str(args).unwrap_or_default(); - let looks = matches!( - name.as_str(), - "computer_use_screenshot" | "computer_use_zoom" | "computer_use_look" | "browser_screenshot" | "browser_read" | "browser_elements" - ) || (name == "computer" && matches!(a["action"].as_str().unwrap_or(""), "screenshot" | "zoom" | "look" | "scroll" | "move")); let numbered = a["ref"].is_number() || !a["actions"].is_null(); - if !looks && !numbered { + if !never_replayed(name) && !numbered { steps.push((name.clone(), args.clone())); done.push((call_id.clone(), true)); } } - crate::oplog::Record::ToolFinished { op: o, call_id, status, .. } if o == &op && status != "done" => { + crate::oplog::Record::ToolFinished { call_id, status, .. } if status != "done" => { if let Some(e) = done.iter_mut().find(|(c, _)| c == call_id) { e.1 = false; } @@ -246,13 +269,16 @@ pub fn skillify(prompt: &str, recs: &[crate::oplog::Record]) -> Option { .take(24) .collect(); if kept.is_empty() { - return None; + return Err("那一回合沒有可重播的步驟(只有看畫面的動作,或都失敗了)".into()); } - let name: String = prompt.chars().take(24).collect(); - Some(Skill { + // Named and described in that turn's own words (what the phone sends has lost its marks: + // teach_log.txt came as teachlog.txt), on one line. + let said = said.split_whitespace().collect::>().join(" "); + let name: String = said.chars().take(24).collect(); + Ok(Skill { name, - description: format!("示範學會:{prompt}"), - instructions: format!("照著做過一次的那條路做完这件事:{prompt}"), + description: format!("示範學會:{said}"), + instructions: format!("照著做過一次的那條路做完這件事:{said}"), steps: kept, source: "learned".into(), ..Default::default() @@ -537,7 +563,7 @@ pub fn replay_steps(turn: &[crate::model::Message], picks: &[usize], blanks: &[( let mut out = vec![]; for &k in picks { let Some((_, Some(c))) = k.checked_sub(1).and_then(|i| steps.get(i)) else { continue }; - if c.status == crate::model::ToolStatus::Failed || matches!(c.name.as_str(), "computer_use_screenshot" | "computer_use_zoom" | "browser_read" | "browser_screenshot" | "browser_elements" | "browser_sent_log" | "anybot_guide" | "use_skill" | "replay_skill") { + if c.status == crate::model::ToolStatus::Failed || never_replayed(&c.name) { continue; } let v: serde_json::Value = serde_json::from_str(&c.args).unwrap_or_default(); @@ -1412,21 +1438,93 @@ mod tests { use crate::oplog::{Prompt, Record, Replay}; let recs = vec![ Record::OperationStarted { op: "o1".into(), at: 1, source_leaf: 0, prompt: Some(Prompt { at: 1, text: "每天記一下日期".into() }) }, - Record::ToolStarted { op: "o1".into(), call_id: "c1".into(), name: "computer".into(), args: "{\"action\":\"screenshot\"}".into(), replay: Replay::Safe, at: 2 }, + Record::ToolStarted { op: "o1".into(), call_id: "c1".into(), name: "computer_use_screenshot".into(), args: "{}".into(), replay: Replay::Safe, at: 2 }, Record::ToolFinished { op: "o1".into(), call_id: "c1".into(), status: "done".into(), at: 3 }, Record::ToolStarted { op: "o1".into(), call_id: "c2".into(), name: "shell".into(), args: "{\"cmd\":\"date\"}".into(), replay: Replay::Safe, at: 4 }, Record::ToolFinished { op: "o1".into(), call_id: "c2".into(), status: "done".into(), at: 5 }, Record::ToolStarted { op: "o1".into(), call_id: "c3".into(), name: "shell".into(), args: "{\"cmd\":\"rm\"}".into(), replay: Replay::Safe, at: 6 }, Record::ToolFinished { op: "o1".into(), call_id: "c3".into(), status: "failed".into(), at: 7 }, - Record::ToolStarted { op: "o1".into(), call_id: "c4".into(), name: "computer".into(), args: "{\"action\":\"click\",\"ref\":3}".into(), replay: Replay::Safe, at: 8 }, + Record::ToolStarted { op: "o1".into(), call_id: "c4".into(), name: "computer_use_click".into(), args: "{\"ref\":3}".into(), replay: Replay::Safe, at: 8 }, Record::ToolFinished { op: "o1".into(), call_id: "c4".into(), status: "done".into(), at: 9 }, + // Reading the guide or a skill, replaying one: never a step of its own (as the learner). + Record::ToolStarted { op: "o1".into(), call_id: "c5".into(), name: "anybot_guide".into(), args: "{\"topic\":\"replay\"}".into(), replay: Replay::Safe, at: 10 }, + Record::ToolStarted { op: "o1".into(), call_id: "c6".into(), name: "use_skill".into(), args: "{\"name\":\"記日期\"}".into(), replay: Replay::Safe, at: 11 }, + Record::ToolStarted { op: "o1".into(), call_id: "c7".into(), name: "replay_skill".into(), args: "{\"name\":\"記日期\"}".into(), replay: Replay::Never, at: 12 }, ]; - let sk = skillify("每天記一下日期", &recs).unwrap(); - // only the shell date step survives: looks and numbered clicks are dropped, failures too - assert_eq!(sk.steps.len(), 1); - assert_eq!(sk.steps[0].tool, "shell"); + let (op, said) = taught_turn("每天記一下日期", None, &recs[..1]).unwrap(); + assert_eq!((op.as_str(), said.as_str()), ("o1", "每天記一下日期")); + let sk = skillify(&said, &recs).unwrap(); + // only the shell date step survives: looks, guides, skills and numbered clicks are dropped, failures too + assert_eq!(sk.steps.iter().map(|s| s.tool.as_str()).collect::>(), ["shell"]); assert!(sk.steps[0].args.contains("date")); - assert!(skillify("沒這回合", &recs).is_none()); + assert!(taught_turn("沒這回合", None, &recs[..1]).unwrap_err().starts_with("找不到以「沒這回合」開始的那一回合")); + assert!(sk.instructions.starts_with("照著做過一次的那條路做完這件事"), "{}", sk.instructions); + } + + /// The phone's 教我做 sends the message as it shows it (plain(): no marks, no line breaks, + /// a link's words only): that still finds the turn the message started. + #[test] + fn the_phones_plain_words_find_the_turn() { + use crate::oplog::{Prompt, Record, Replay}; + let said = "寫教學\n**記一筆** 到 [紀錄](https://example.com) >> teach_log.txt"; + let recs = vec![ + Record::OperationStarted { op: "o1".into(), at: 1, source_leaf: 0, prompt: Some(Prompt { at: 1, text: said.into() }) }, + Record::ToolStarted { op: "o1".into(), call_id: "c1".into(), name: "shell".into(), args: "{\"command\":\"echo 教 >> teach_log.txt\"}".into(), replay: Replay::Never, at: 2 }, + Record::ToolFinished { op: "o1".into(), call_id: "c1".into(), status: "done".into(), at: 3 }, + ]; + // (mobile/index.html: plain(m.text).slice(0, 200)) + let phone = "寫教學 記一筆 到 紀錄 teachlog.txt"; + let (op, words) = taught_turn(phone, Some(1), &recs[..1]).unwrap(); + assert_eq!((op.as_str(), words.as_str()), ("o1", said)); + assert_eq!(taught_turn(said, None, &recs[..1]).map(|t| t.0), Ok("o1".into()), "the words as typed find it too"); + let k = skillify(&words, &recs).unwrap(); + assert_eq!(k.steps.len(), 1); + // Named and described in the turn's own words, on one line. + assert_eq!(k.description, "示範學會:寫教學 **記一筆** 到 [紀錄](https://example.com) >> teach_log.txt"); + // Only looking: the turn is there, nothing to replay. + let looked = vec![ + Record::OperationStarted { op: "o2".into(), at: 1, source_leaf: 0, prompt: Some(Prompt { at: 1, text: "看一下".into() }) }, + Record::ToolStarted { op: "o2".into(), call_id: "c1".into(), name: "browser_screenshot".into(), args: "{}".into(), replay: Replay::Safe, at: 2 }, + ]; + assert_eq!(skillify("看一下", &looked).unwrap_err(), "那一回合沒有可重播的步驟(只有看畫面的動作,或都失敗了)"); + } + + /// The message pressed is the turn learned: Monday's 「幫我簽到」 is Monday's run, not + /// Tuesday's; Tuesday's, started again with 重新產生, is the attempt the chat shows (the last), + /// not the one thrown away; a 插話 with the same words started no turn: not found. + #[test] + fn the_message_pressed_is_the_turn_learned() { + use crate::oplog::{Prompt, Record}; + // (op, when the turn started, when its message was sent) + let start = |op: &str, started: i64, sent: i64| Record::OperationStarted { op: op.into(), at: started, source_leaf: sent, prompt: Some(Prompt { at: sent, text: "幫我簽到".into() }) }; + let starts = [start("mon", 1_005, 1_000), start("tue", 2_005, 2_000), start("tue-again", 2_500, 2_000)]; + let op = |at| taught_turn("幫我簽到", at, &starts).map(|t| t.0); + assert_eq!(op(Some(1_000)), Ok("mon".into()), "Monday's message: Monday's turn"); + assert_eq!(op(Some(2_000)), Ok("tue-again".into()), "regenerated: the attempt shown, not the one replaced"); + assert!(op(Some(2_200)).unwrap_err().starts_with("找不到以「幫我簽到」開始的那一回合"), "a 插話 typed at 2_200 started no turn"); + assert_eq!(op(None), Ok("tue-again".into()), "no time (an older phone page): the latest by its words"); + } + + /// A message sent with a file: the turn's words carry the file's text after the person's + /// (the model's copy) — found by the message's time, named in the words typed. A turn kept + /// before the trail had the time (0) is found by its words. + #[test] + fn a_message_with_a_file_and_an_older_turn_can_be_taught() { + use crate::oplog::{Prompt, Record}; + let file = crate::attach::Attachment { name: "貓.png".into(), path: "/nowhere/貓.png".into(), image: true, bytes: 3, on_box: String::new() }; + let modelled = format!("看這張{}", crate::attach::for_model(&[file]).0); + let starts = [ + Record::OperationStarted { op: "old".into(), at: 500, source_leaf: 0, prompt: Some(Prompt { at: 0, text: "以前的簽到".into() }) }, + Record::OperationStarted { op: "with-file".into(), at: 3_005, source_leaf: 3_000, prompt: Some(Prompt { at: 3_000, text: modelled }) }, + ]; + assert_eq!(taught_turn("看這張", Some(3_000), &starts), Ok(("with-file".into(), "看這張".into()))); + assert_eq!(taught_turn("看這張", None, &starts).map(|t| t.0), Ok("with-file".into()), "by its words too"); + assert_eq!(taught_turn("以前的簽到", Some(400), &starts).map(|t| t.0), Ok("old".into()), "a turn from before the time was kept"); + assert!(taught_turn("以前的", Some(400), &starts).is_err(), "…by all its words, not a part"); + // A message from before times were kept comes with `at: 0`: found by its words, never as + // whichever untimed turn is newest. + assert_eq!(taught_turn("以前的簽到", Some(0), &starts).map(|t| t.0), Ok("old".into())); + assert!(taught_turn("完全不同的一句話", Some(0), &starts).is_err(), "at 0 names no turn"); } #[test] fn remember_tells_the_same_thing_from_another_fact() { diff --git a/src/store.rs b/src/store.rs index b6393c7..32abf45 100644 --- a/src/store.rs +++ b/src/store.rs @@ -21,8 +21,8 @@ use rusqlite::{params, Connection}; use std::path::PathBuf; use std::sync::{Mutex, OnceLock}; -/// How far back the timeline answers. Rows older than this are deleted on open. -const KEEP_DAYS: i64 = 30; +/// How far back the timeline (and 教我做) answers. Rows older than this are deleted on open. +pub const KEEP_DAYS: i64 = 30; pub struct Store { conn: Mutex, @@ -82,12 +82,21 @@ fn audit_schema(c: &Connection) -> Option<()> { name TEXT, detail TEXT, status TEXT, - call_id TEXT + call_id TEXT, + prompt_at INTEGER ); CREATE INDEX IF NOT EXISTS audit_bot_at ON audit(bot, at DESC); CREATE INDEX IF NOT EXISTS audit_call ON audit(bot, op, call_id);", ) - .ok() + .ok()?; + // A turn's row keeps when the person's message was sent (教我做 finds the turns a message + // started by it). A trail from before has no such column: add it (its old rows stay NULL). + let has = c.query_row("SELECT COUNT(*) FROM pragma_table_info('audit') WHERE name='prompt_at'", [], |r| r.get::<_, i64>(0)).ok()? > 0; + if !has { + // (Another AnyBot on the same folder may have just added it: then this one fails, harmlessly.) + let _ = c.execute_batch("ALTER TABLE audit ADD COLUMN prompt_at INTEGER;"); + } + Some(()) } fn memory_schema(c: &Connection) -> Option<()> { @@ -317,12 +326,7 @@ pub fn record(bot: u64, r: &Record) { let Ok(c) = s.conn.lock() else { return }; let now = crate::model::now_ms(); match r { - Record::OperationStarted { op, at, prompt, .. } => { - let _ = c.execute( - "INSERT INTO audit(bot,op,at,kind,detail) VALUES(?1,?2,?3,'turn',?4)", - params![bot, op, at, prompt.as_ref().map(|p| p.text.clone())], - ); - } + Record::OperationStarted { op, at, prompt, .. } => insert_turn(&c, bot, op, *at, prompt.as_ref()), Record::StepAttempt { op, step, .. } => { let _ = c.execute("INSERT INTO audit(bot,op,at,kind,name) VALUES(?1,?2,?3,'model',?4)", params![bot, op, now, step]); } @@ -368,6 +372,80 @@ pub fn record(bot: u64, r: &Record) { } } +/// The turns of the last KEEP_DAYS, oldest first, as each one's first work-log line: what the +/// person said and when that message was sent (0: a turn kept before the trail had it). What +/// 教我做 picks a turn from — then turn_records reads just that one. +pub fn turn_starts(bot: u64) -> Vec { + let cutoff = crate::model::now_ms() - KEEP_DAYS * 86_400_000; + rebuilt("bot=?1 AND at>?2 AND kind='turn'", params![bot as i64, cutoff]).into_iter().filter(|r| matches!(r, Record::OperationStarted { .. })).collect() +} + +/// One turn of the trail as work-log lines again: its start, its steps (the arguments they ran +/// with, how each ended) and its end — the JSONL log drops a turn the moment it ends. Model +/// attempts, typed messages and stops aren't rebuilt; a step's replay class isn't kept (Never). +pub fn turn_records(bot: u64, op: &str) -> Vec { + rebuilt("bot=?1 AND op=?2 AND kind IN ('turn','tool')", params![bot as i64, op]) +} + +/// The trail's turn and step rows that `filter` picks, in order, as work-log lines (each turn's +/// end after its steps). +fn rebuilt(filter: &str, args: impl rusqlite::Params) -> Vec { + let Some(s) = store() else { return vec![] }; + let Ok(c) = s.conn.lock() else { return vec![] }; + rebuilt_on(&c, filter, args) +} + +fn rebuilt_on(c: &Connection, filter: &str, args: impl rusqlite::Params) -> Vec { + // (A trail that never got prompt_at reads every message's time as unknown.) + let sql = |sent: &str| format!("SELECT op,at,end_at,kind,name,detail,status,call_id,{sent} FROM audit WHERE {filter} ORDER BY id ASC"); + let Ok(mut st) = c.prepare(&sql("prompt_at")).or_else(|_| c.prepare(&sql("NULL"))) else { + return vec![]; + }; + let rows = st + .query_map(args, |r| { + Ok(( + (r.get::<_, String>(0)?, r.get::<_, i64>(1)?, r.get::<_, Option>(2)?, r.get::<_, String>(3)?), + (r.get::<_, Option>(4)?, r.get::<_, Option>(5)?, r.get::<_, Option>(6)?, r.get::<_, Option>(7)?, r.get::<_, Option>(8)?), + )) + }) + .map(|it| it.filter_map(Result::ok).collect::>()) + .unwrap_or_default(); + let mut out = Vec::new(); + let mut ends = Vec::new(); + for ((op, at, end_at, kind), (name, detail, status, call_id, prompt_at)) in rows { + if kind == "turn" { + let sent = prompt_at.unwrap_or(0); + out.push(Record::OperationStarted { op: op.clone(), at, source_leaf: sent, prompt: detail.map(|text| crate::oplog::Prompt { at: sent, text }) }); + let outcome = match status.as_deref() { + Some("completed") => Some(Outcome::Completed), + Some("aborted") => Some(Outcome::Aborted), + Some("failed") => Some(Outcome::Failed), + _ => None, + }; + if let Some(outcome) = outcome { + ends.push(Record::OperationFinished { op, outcome }); + } + continue; + } + let call_id = call_id.unwrap_or_default(); + out.push(Record::ToolStarted { op: op.clone(), call_id: call_id.clone(), name: name.unwrap_or_default(), args: detail.unwrap_or_default(), replay: crate::oplog::Replay::Never, at }); + if let Some(status) = status.filter(|s| s != "running") { + out.push(Record::ToolFinished { op, call_id, status, at: end_at.unwrap_or(at) }); + } + } + out.extend(ends); + out +} + +/// A turn's row, with when its message was sent — or without, on a trail that never got that +/// column (the ALTER failed): the timeline keeps going either way. +fn insert_turn(c: &Connection, bot: i64, op: &str, at: i64, prompt: Option<&crate::oplog::Prompt>) { + let text = prompt.map(|p| p.text.as_str()); + if c.execute("INSERT INTO audit(bot,op,at,kind,detail,prompt_at) VALUES(?1,?2,?3,'turn',?4,?5)", params![bot, op, at, text, prompt.map(|p| p.at)]).is_err() { + let _ = c.execute("INSERT INTO audit(bot,op,at,kind,detail) VALUES(?1,?2,?3,'turn',?4)", params![bot, op, at, text]); + } +} + /// 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. pub fn turns(bot: u64) -> serde_json::Value { @@ -770,6 +848,79 @@ mod tests { assert_eq!(ts[1]["steps"][1]["name"], "computer"); assert_eq!(ts[1]["steps"][1]["status"], "done", "the finished tool answers with its end status"); assert_eq!(ts[1]["steps"][2]["state"], "consumed"); + // …and as work-log lines again (what 教我做 reads): the turns' starts, with when the + // message was sent; then one turn's start, steps and end. + let starts = turns_started(bot); + assert_eq!(starts, [("op1".to_string(), Some(("幫我叫車".to_string(), at(0)))), ("op2".to_string(), None)]); + let recs = turn_records(bot, "op1"); + let kinds: Vec = recs.iter().map(|r| serde_json::to_value(r).unwrap()["type"].as_str().unwrap().to_string()).collect(); + assert_eq!(kinds, ["operation_started", "tool_started", "tool_finished", "operation_finished"]); + assert!(matches!(&recs[1], Record::ToolStarted { call_id, args, .. } if call_id == "c1" && args == "{\"action\":\"click\"}")); + assert!(matches!(&recs[2], Record::ToolFinished { status, at, .. } if status == "done" && *at == t0 + 20)); + assert!(matches!(&recs[3], Record::OperationFinished { op, outcome: Outcome::Completed } if op == "op1")); + assert!(!turn_records(bot, "op2").iter().any(|r| matches!(r, Record::OperationFinished { .. })), "the open turn has no end"); + } + + /// Another AnyBot holds the trail's write lock when this one opens it: the new column can't + /// be added — the trail still opens, and turns are still written (their time unknown). + #[test] + fn the_trail_keeps_writing_when_the_new_column_cannot_be_added() { + let dir = std::env::temp_dir().join(format!("anybot-audit-noalter-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let p = dir.join("audit.db"); + let other = connect(&p).unwrap(); + other + .execute_batch( + "CREATE TABLE audit(id INTEGER PRIMARY KEY, bot INTEGER NOT NULL, op TEXT NOT NULL, at INTEGER NOT NULL, end_at INTEGER, kind TEXT NOT NULL, name TEXT, detail TEXT, status TEXT, call_id TEXT); + CREATE INDEX audit_bot_at ON audit(bot, at DESC); CREATE INDEX audit_call ON audit(bot, op, call_id); + BEGIN IMMEDIATE;", + ) + .unwrap(); + let c = connect(&p).unwrap(); + c.busy_timeout(std::time::Duration::ZERO).unwrap(); + assert!(audit_schema(&c).is_some(), "the trail still opens"); + other.execute_batch("COMMIT;").unwrap(); + let has: i64 = c.query_row("SELECT COUNT(*) FROM pragma_table_info('audit') WHERE name='prompt_at'", [], |r| r.get(0)).unwrap(); + assert_eq!(has, 0, "the column couldn't be added"); + insert_turn(&c, 5, "op1", 100, Some(&Prompt { at: 90, text: "照樣記下".into() })); + let recs = rebuilt_on(&c, "bot=?1", params![5]); + assert!(matches!(recs.as_slice(), [Record::OperationStarted { op, prompt: Some(p), .. }] if op == "op1" && p.text == "照樣記下" && p.at == 0), "{recs:?}"); + let _ = std::fs::remove_dir_all(&dir); + } + + /// (op, (words, when sent)) of each turn turn_starts gives. + fn turns_started(bot: u64) -> Vec<(String, Option<(String, i64)>)> { + turn_starts(bot) + .into_iter() + .filter_map(|r| match r { + Record::OperationStarted { op, prompt, .. } => Some((op, prompt.map(|p| (p.text, p.at)))), + _ => None, + }) + .collect() + } + + /// A trail from before turns kept when their message was sent: it gains the column, keeps + /// its rows (read as sent at 0), and new turns keep the time. + #[test] + fn an_older_trail_learns_when_messages_were_sent() { + let dir = std::env::temp_dir().join(format!("anybot-audit-migrate-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let c = connect(&dir.join("audit.db")).unwrap(); + c.execute_batch( + "CREATE TABLE audit(id INTEGER PRIMARY KEY, bot INTEGER NOT NULL, op TEXT NOT NULL, at INTEGER NOT NULL, end_at INTEGER, kind TEXT NOT NULL, name TEXT, detail TEXT, status TEXT, call_id TEXT); + INSERT INTO audit(bot,op,at,kind,detail,status) VALUES (5,'old',100,'turn','以前的事','completed');", + ) + .unwrap(); + audit_schema(&c).unwrap(); + audit_schema(&c).unwrap(); + let old: (String, Option) = c.query_row("SELECT detail, prompt_at FROM audit WHERE op='old'", [], |r| Ok((r.get(0)?, r.get(1)?))).unwrap(); + assert_eq!(old, ("以前的事".to_string(), None)); + c.execute("INSERT INTO audit(bot,op,at,kind,detail,prompt_at) VALUES (5,'new',200,'turn','新的事',190)", []).unwrap(); + let new: Option = c.query_row("SELECT prompt_at FROM audit WHERE op='new'", [], |r| r.get(0)).unwrap(); + assert_eq!(new, Some(190)); + let _ = std::fs::remove_dir_all(&dir); } #[test]