From 4be6d3e4d0b590918c77947cf6172b8186c4b155 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=80=A7=E9=A9=8A?= Date: Wed, 18 Nov 2026 17:33:43 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E3=80=8C=E6=95=99=E6=88=91=E5=81=9A?= =?UTF-8?q?=E3=80=8D=E8=AE=80=2030=20=E5=A4=A9=E7=9A=84=E7=A8=BD=E6=A0=B8?= =?UTF-8?q?=E7=B4=80=E9=8C=84=EF=BC=8C=E5=81=9A=E5=AE=8C=E7=9A=84=E5=9B=9E?= =?UTF-8?q?=E5=90=88=E4=B9=9F=E5=AD=B8=E5=BE=97=E5=88=B0=EF=BC=9B=E6=95=B4?= =?UTF-8?q?=E7=90=86=E5=81=9A=E6=B3=95=E5=9B=9E=E5=A0=B1=E7=9A=84=E5=95=8F?= =?UTF-8?q?=E9=A1=8C=E9=80=B2=E5=BE=97=E4=BA=86=E5=BE=85=E6=94=B9=E9=80=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 教我做(skillify)只讀那個 Bot 的工作紀錄(oplog),但一回合結束時工作紀錄就縮到只剩還在等的訊息 (通常整份刪掉)——長按的是自己早就做完的那則訊息,所以每次都回「那一回合沒有可重播的步驟」。 工作紀錄是給當掉後收尾用的,本來就只留進行中的那一回合;每一步的參數和結果另外照抄進 30 天的 稽核紀錄(oplog/audit.db,手機的稽核時間軸已經改讀它)。教我做要的正是「過去某一回合的步驟」, 所以改讀稽核紀錄,不是把工作紀錄留著。 整理做法(learn)在回答送出、這一回合 Done 之後才在背景跑(不讓使用者等),它回報的 AnyBot 自己的 問題(StreamEvent::Issues)卻排在「舊回合的零星事件一律丟掉」的檢查後面——紀錄寫了「Bot 回報了 2 個 AnyBot 自己的問題」,待改進還是空的。改成跟 Learned 一樣在那個檢查前面處理(事件的順序本來 就是 Done 在前,不能為了它讓使用者等整理做法)。 - store:records(bot) 把稽核紀錄裡 30 天內的回合和步驟還原成工作紀錄的格式(回合開頭帶使用者的話、 每一步的參數和結果、回合結束排在步驟後面);KEEP_DAYS 公開給錯誤訊息用。 - appctl skillify:讀 store::records,稽核紀錄打不開才退回工作紀錄;把手機送的訊息時間 at 交下去。 - memory::skillify: - 學的是按的那則訊息開始的那一回合:同一句話可能做過好幾次(30 天內很常見),有 at 就取那個時間 之後第一個開始的回合,沒有 at(或時鐘對不上)才取最近的。 - 比對時兩邊都照手機 plain() 的規則整理(拿掉 * _ ` # >、連結只留字、換行併成空白)——手機送的是 plain(m.text),原本訊息裡有 >、_ 或換行就對不上。技能的名字、說明、做法改用那一回合原本的字 (併成一行),不用手機去過標記的字(teach_log.txt 不會變成 teachlog.txt)。 - 回傳 Result,分開「找不到以「…」開始的那一回合(只找得到 30 天內、由一則訊息開始的回合;做事中途 插的話不算)」和「沒有可重播的步驟」;「这件事」→「這件事」(整份 memory.rs 用 ICU Hans-Hant 掃過, 只有這一個簡體字)。 - app drain_events:Issues 跟 Learned 一樣在回合結束後也收;記在主 Bot 名下(支線的算主 Bot 的)。 - 手機:教我做帶上訊息的 at;成功後呼叫的 again() 在那裡不是函式(全域的 again 是 loadChat 的旗標), 按了會丟 TypeError,拿掉。 - verify-anybot:phone 多一個 long-press [--text](觸控按住 0.8 秒),走得到長按的選單; SKILL.md、ctl 的用法一起寫。 - 功能地圖:replay.md 的「教我做」改走真的選單(長按 › 教我做),拿掉「走不到」那一步;陷阱補上學的是 哪一回合、只找 30 天內、找不到時說什麼;garden.md、replay.md 的自動測試列上新測試。 已驗證: 完整 cargo test(金鑰清空、DOCKER_HOST 指到不存在、ANYBOT_HF_BASE 連不到)全綠(672 過、46 ignored 沒跑);cargo clippy --bin anybot --all-targets -- -D warnings 沒有警告;sh deploy/ci/lint-sh.sh 過。新測試 appctl::a_turn_that_has_ended_can_still_be_taught、memory::the_phones_plain_words_find_the_turn、 memory::the_message_pressed_is_the_turn_learned、app::anybots_own_problems_found_after_the_turn_reach_the_list, store 的 the_trail_keeps_the_story… 加了 records、a_finished_turn_can_become_a_skill 加了「這件事」——把修正 拿掉再跑都失敗(找不到那一回合、待改進是空的、簡體字、學到後來那一回合、說明變成去過標記的字), 放回去都過。另外請一個乾淨脈絡的 Agent 照 replay.md、garden.md 審過 diff,它提的三點(同一句話學錯回合、 技能的字被手機去掉標記、插話也說「30 天內」)都改了。verify-anybot 冷開照地圖寫的跑:replay.md 三步 (做五步學會、重播填空格、教我做——長按 › 選單 › 「已存成技能」,那一回合已經做完、工作紀錄不在,技能 steps 1、參數和說明都照原樣 echo 教 >> teach.txt;長按插話跳「找不到以「…」開始的那一回合…」)都過,修改前 第三步是 HTTP 400;garden.md 沒事不報、/doctor 遮金鑰、待改進合併計次(browser_fill_contact 一條 count 2、 bots 驗證小幫手,重開後還在)、版本都過,修改前第三步待改進是空的。 未驗證: garden.md 的「電腦版 設定 › 更新」要開桌面視窗(desktop-shot),沒跑;「有事的報告、當掉」和 replay.md 的「網站地圖」照地圖寫的走不到(要明天 8:44、真的當掉、真的模型);garden.md 是在審查後那幾處 修改之前的建置上跑的(那幾處只動 skillify 和手機的教我做,沒動待改進);真的手機的長按沒有測(用無頭 Chrome 的觸控事件代替);超過 30 天的回合、別台裝置時鐘不準時的 at 只靠單元測試。 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Uirha5sXAsDLzxz6UZJgoC --- .claude/skills/verify-anybot/SKILL.md | 1 + .claude/skills/verify-anybot/scripts/ctl | 4 +- .../skills/verify-anybot/scripts/phone.mjs | 10 ++ docs/feature-map/garden.md | 2 +- docs/feature-map/replay.md | 6 +- mobile/index.html | 2 +- src/app.rs | 39 ++++-- src/appctl.rs | 39 +++++- src/memory.rs | 116 ++++++++++++++---- src/store.rs | 67 +++++++++- 10 files changed, 238 insertions(+), 48 deletions(-) diff --git a/.claude/skills/verify-anybot/SKILL.md b/.claude/skills/verify-anybot/SKILL.md index 8766bef..f465212 100644 --- a/.claude/skills/verify-anybot/SKILL.md +++ b/.claude/skills/verify-anybot/SKILL.md @@ -74,6 +74,7 @@ $CTL phone login # 手機密碼從 scratch 的檔案打進去(不 | `wait [秒]`、`wait-gone [秒]` | 等元素出現(看得見)/消失 | | `wait-text <字> [--in ] [秒]` | 等畫面(或某一塊)出現這些字 | | `click [--text <字>]` | 在元素正中間按一下;`--text` 選含這些字的那一個 | +| `long-press [--text <字>]` | 在元素正中間用手指(觸控)按住 0.8 秒再放開:手機的長按,例如自己訊息的選單 `long-press '.m.user .bub' --text 某句話` | | `send <字>` | 在聊天的輸入框 `#input` 打字、按送出 `#b-send` | | `type <字>` | 點進輸入框、清空、像鍵盤一樣打字 | | `press Enter`(`Escape`、`Tab`、`Backspace`) | 按鍵 | diff --git a/.claude/skills/verify-anybot/scripts/ctl b/.claude/skills/verify-anybot/scripts/ctl index 1e01e5a..2f995bf 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、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 73357b0..f82c0da 100755 --- a/.claude/skills/verify-anybot/scripts/phone.mjs +++ b/.claude/skills/verify-anybot/scripts/phone.mjs @@ -9,6 +9,7 @@ // wait-gone [秒] 等元素消失或看不見 // wait-text <字> [--in ] [秒] 等畫面上出現這些字 // click [--text <字>] 在元素正中間按一下(有 --text:符合 css 而且含這些字的那一個) +// long-press [--text <字>] 在元素正中間用手指按住 0.8 秒再放開(手機的長按,例如訊息的選單) // type <字> | --file <檔> 點進輸入框、清空、像鍵盤一樣打進去(--file:字從檔案讀,密碼不進指令列) // press <鍵> Enter、Escape、Tab、Backspace // text [css] 印出看得到的字 @@ -234,6 +235,15 @@ async function main() { await mouseClick(c, x, y); break; } + case "long-press": { + // 手指按住(觸控,不是滑鼠):頁面看 touchstart 之後有沒有放開,按滿 0.8 秒才放。 + const { x, y } = await center(c, rest[0] || die("long-press 要 css"), TEXT); + await c.send("Emulation.setTouchEmulationEnabled", { enabled: true, maxTouchPoints: 1 }); + await c.send("Input.dispatchTouchEvent", { type: "touchStart", touchPoints: [{ x, y }] }); + await sleep(800); + await c.send("Input.dispatchTouchEvent", { type: "touchEnd", touchPoints: [] }); + 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 0996c19..adfc52c 100644 --- a/docs/feature-map/replay.md +++ b/docs/feature-map/replay.md @@ -25,10 +25,9 @@ - **做五步、學會**(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 shot replay-run && $CTL botfile log.txt && $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 沒有長按或右鍵。看到:最接近的真路是上一步(同一個請求)。 +- **教我做**(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 long-press '.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-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`)、`cargo test a_turn_that_has_ended_can_still_be_taught`、`cargo test a_skill_is_replayed_without_the_model_in_between`、`cargo test skills::`、`cargo test agent::`。 ## 陷阱 @@ -36,5 +35,6 @@ - `replay_skill` 屬於「看螢幕與操作」能力:沒有這個能力的 Bot、別人(訊息管道、團隊成員)傳來的那一輪都沒有它。技能沒存步驟就只能讀了自己做。 - 重播會停下來:空格沒給齊(會說要填哪幾格);畫面上找不到同一種、同名的東西時先自動截一次圖再找,還是沒有就停在第幾步交還給 Bot;任何一步失敗、被拒或重複,後面都不做。有風險的步驟照樣問使用者。 - 某一步點的東西說不出名字(只有編號),整份就不存步驟;「教我做」也會丟掉只看畫面的步驟和照編號點的步驟。 +- 「教我做」學的是那則訊息開始的那一回合(同一句話之後又做過也一樣),只找得到 30 天內的;更早的、或做事中途插的話,會說「找不到以「…」開始的那一回合」;只有看畫面或都失敗的會說「那一回合沒有可重播的步驟」。 - `save_skill` 存同名的技能會把原本存的可重播步驟一起換掉([skills](skills.md))。 - (驗證)插話太慢,那一輪會先結束、五步被拆成兩輪就不會學:每一步送出後立刻等下一個步驟出現再送。 diff --git a/mobile/index.html b/mobile/index.html index 0409585..899215a 100644 --- a/mobile/index.html +++ b/mobile/index.html @@ -1555,7 +1555,7 @@ function msgMenu(i) { if (m.text) items.push({icon: "copy", label: "複製", on: () => copyText(m.text)}); 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 9cc99f9..dec7a37 100644 --- a/src/app.rs +++ b/src/app.rs @@ -2957,6 +2957,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); @@ -3128,14 +3139,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; @@ -8260,6 +8263,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 54cf65d..e2950c8 100644 --- a/src/appctl.rs +++ b/src/appctl.rs @@ -766,16 +766,22 @@ 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. A + // trail that can't be opened leaves the log. + let mut recs = crate::store::records(bot_id); + if recs.is_empty() { + recs = crate::oplog::OpLog::for_bot(bot_id).read(); + } + match crate::memory::skillify(&prompt, v["at"].as_i64(), &recs) { + Ok(sk) => { let n = sk.steps.len(); let name = sk.name.clone(); crate::memory::upsert_skill(&mut state.skills, sk); let who = learned(state, bot_id, &name); ok(format!("已把「{prompt}」那一回合存成技能「{name}」({n} 步可重播),{who}")) } - None => err("那一回合沒有可重播的步驟(只有看畫面的動作,或都失敗了)".into()), + Err(why) => err(why), } } "create_bot" => { @@ -1030,6 +1036,31 @@ 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); + } + #[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/memory.rs b/src/memory.rs index 783e9db..32d6f25 100644 --- a/src/memory.rs +++ b/src/memory.rs @@ -196,29 +196,40 @@ 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(" ") +} + +/// C8: 示範即教學 — turn the turn that `prompt` started into a skill, keeping the steps that +/// worked and threw nothing away. `at`: when that message was sent — the same words may have +/// started other turns since (an earlier try, a later one that went wrong), so it is the first +/// turn starting from then; without it (or with a clock that disagrees), the latest. 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. Err: why nothing was saved. +pub fn skillify(prompt: &str, at: Option, recs: &[crate::oplog::Record]) -> Result { + let key: String = plain_words(prompt).chars().take(40).collect(); + // (op, when the turn started, the words that started it), oldest first. + let turns: Vec<(&str, i64, &str)> = recs + .iter() + .filter_map(|r| match r { + crate::oplog::Record::OperationStarted { op, at, prompt: Some(p), .. } if plain_words(&p.text).chars().take(40).collect::() == key => Some((op.as_str(), *at, p.text.as_str())), + _ => None, + }) + .collect(); + let Some(&(op, _, said)) = at.and_then(|t| turns.iter().find(|(_, started, _)| *started >= t)).or(turns.last()) else { + return Err(format!("找不到以「{prompt}」開始的那一回合(只找得到 {} 天內、由一則訊息開始的回合;做事中途插的話不算)", crate::store::KEEP_DAYS)); + }; 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 { op: o, call_id, name, args, .. } if o == op => { let a: serde_json::Value = serde_json::from_str(args).unwrap_or_default(); let looks = matches!( name.as_str(), @@ -230,7 +241,7 @@ pub fn skillify(prompt: &str, recs: &[crate::oplog::Record]) -> Option { done.push((call_id.clone(), true)); } } - crate::oplog::Record::ToolFinished { op: o, call_id, status, .. } if o == &op && status != "done" => { + crate::oplog::Record::ToolFinished { op: o, call_id, status, .. } if o == op && status != "done" => { if let Some(e) = done.iter_mut().find(|(c, _)| c == call_id) { e.1 = false; } @@ -246,13 +257,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() @@ -1421,12 +1435,60 @@ mod tests { Record::ToolStarted { op: "o1".into(), call_id: "c4".into(), name: "computer".into(), args: "{\"action\":\"click\",\"ref\":3}".into(), replay: Replay::Safe, at: 8 }, Record::ToolFinished { op: "o1".into(), call_id: "c4".into(), status: "done".into(), at: 9 }, ]; - let sk = skillify("每天記一下日期", &recs).unwrap(); + let sk = skillify("每天記一下日期", None, &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"); assert!(sk.steps[0].args.contains("date")); - assert!(skillify("沒這回合", &recs).is_none()); + assert!(skillify("沒這回合", None, &recs).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 k = skillify(phone, None, &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"); + assert_eq!(skillify(said, None, &recs).map(|k| k.steps.len()), Ok(1), "the words as typed find it too"); + // 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("看一下", None, &looked).unwrap_err(), "那一回合沒有可重播的步驟(只有看畫面的動作,或都失敗了)"); + } + + /// The same words, said on two days: the message pressed is the turn learned — Monday's run + /// that worked, not Tuesday's that went wrong after it. + #[test] + fn the_message_pressed_is_the_turn_learned() { + use crate::oplog::{Prompt, Record, Replay}; + let turn = |op: &str, at: i64, cmd: &str, status: &str| { + vec![ + Record::OperationStarted { op: op.into(), at: at + 5, source_leaf: 0, prompt: Some(Prompt { at, text: "幫我簽到".into() }) }, + Record::ToolStarted { op: op.into(), call_id: "c1".into(), name: "shell".into(), args: format!("{{\"command\":\"{cmd}\"}}"), replay: Replay::Never, at: at + 6 }, + Record::ToolFinished { op: op.into(), call_id: "c1".into(), status: status.into(), at: at + 7 }, + ] + }; + let recs: Vec = [turn("mon", 1_000, "sign-in --ok", "done"), turn("tue", 2_000, "sign-in --other", "done")].concat(); + let steps = |at| skillify("幫我簽到", at, &recs).map(|k| k.steps[0].args.clone()); + assert_eq!(steps(Some(1_000)), Ok("{\"command\":\"sign-in --ok\"}".into()), "Monday's message: Monday's turn"); + assert_eq!(steps(Some(2_000)), Ok("{\"command\":\"sign-in --other\"}".into())); + assert_eq!(steps(None), Ok("{\"command\":\"sign-in --other\"}".into()), "no time: the latest"); + // A message the clock puts after every turn (another device's clock): still the latest. + assert_eq!(steps(Some(9_000)), Ok("{\"command\":\"sign-in --other\"}".into())); } #[test] fn remember_tells_the_same_thing_from_another_fact() { diff --git a/src/store.rs b/src/store.rs index b6393c7..2d5d648 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, @@ -368,6 +368,60 @@ pub fn record(bot: u64, r: &Record) { } } +/// The trail's turns as work-log lines again, oldest first, KEEP_DAYS back: each turn's start +/// (with the person's words), its steps (the arguments they ran with, how each ended) and its +/// end. What 教我做 reads — 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 (read as Never). +pub fn records(bot: u64) -> Vec { + let bot = bot as i64; + let Some(s) = store() else { return vec![] }; + let Ok(c) = s.conn.lock() else { return vec![] }; + let cutoff = crate::model::now_ms() - KEEP_DAYS * 86_400_000; + let Ok(mut st) = c.prepare("SELECT op,at,end_at,kind,name,detail,status,call_id FROM audit WHERE bot=?1 AND at>?2 AND kind IN ('turn','tool') ORDER BY id ASC") else { + return vec![]; + }; + let rows = st + .query_map(params![bot, cutoff], |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)?, + )) + }) + .map(|it| it.filter_map(Result::ok).collect::>()) + .unwrap_or_default(); + let mut out = Vec::new(); + // A turn's end goes after all of its steps (its row is the turn's first). + let mut ends = Vec::new(); + for (op, at, end_at, kind, name, detail, status, call_id) in rows { + if kind == "turn" { + out.push(Record::OperationStarted { op: op.clone(), at, source_leaf: 0, prompt: detail.map(|text| crate::oplog::Prompt { at, 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 +} + /// 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 +824,15 @@ 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): turns and steps, each turn's end + // after its steps. + let recs = records(bot); + 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_started", "tool_started", "operation_finished"]); + assert!(matches!(&recs[0], Record::OperationStarted { prompt: Some(p), .. } if p.text == "幫我叫車")); + 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[5], Record::OperationFinished { op, outcome: Outcome::Completed } if op == "op1")); } #[test]