diff --git a/.claude/skills/verify-anybot/SKILL.md b/.claude/skills/verify-anybot/SKILL.md index f465212..59b6eec 100644 --- a/.claude/skills/verify-anybot/SKILL.md +++ b/.claude/skills/verify-anybot/SKILL.md @@ -76,6 +76,7 @@ $CTL phone login # 手機密碼從 scratch 的檔案打進去(不 | `click [--text <字>]` | 在元素正中間按一下;`--text` 選含這些字的那一個 | | `long-press [--text <字>]` | 在元素正中間用手指(觸控)按住 0.8 秒再放開:手機的長按,例如自己訊息的選單 `long-press '.m.user .bub' --text 某句話` | | `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 2f995bf..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、long-press、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 f82c0da..e2eb9fe 100755 --- a/.claude/skills/verify-anybot/scripts/phone.mjs +++ b/.claude/skills/verify-anybot/scripts/phone.mjs @@ -11,6 +11,7 @@ // click [--text <字>] 在元素正中間按一下(有 --text:符合 css 而且含這些字的那一個) // long-press [--text <字>] 在元素正中間用手指按住 0.8 秒再放開(手機的長按,例如訊息的選單) // type <字> | --file <檔> 點進輸入框、清空、像鍵盤一樣打進去(--file:字從檔案讀,密碼不進指令列) +// upload <檔> 在檔案選擇欄(input type=file,可以是隱藏的)選這個檔案,等於系統的檔案選擇器選好按「打開」 // press <鍵> Enter、Escape、Tab、Backspace // text [css] 印出看得到的字 // shot <名稱> 證據:/NN-名稱.png(截圖)、.ax.txt(無障礙樹)、.txt(看得到的字) @@ -244,6 +245,16 @@ async function main() { await c.send("Input.dispatchTouchEvent", { type: "touchEnd", touchPoints: [] }); 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/replay.md b/docs/feature-map/replay.md index 231177c..92c8596 100644 --- a/docs/feature-map/replay.md +++ b/docs/feature-map/replay.md @@ -28,7 +28,7 @@ - **教我做**(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-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 long-press '.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`、`the_phones_plain_words_find_the_turn`、`the_message_pressed_is_the_turn_learned`)、`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::`。 +- 自動測試:`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::`。 ## 陷阱 @@ -36,6 +36,6 @@ - `replay_skill` 屬於「看螢幕與操作」能力:沒有這個能力的 Bot、別人(訊息管道、團隊成員)傳來的那一輪都沒有它。技能沒存步驟就只能讀了自己做。 - 重播會停下來:空格沒給齊(會說要填哪幾格);畫面上找不到同一種、同名的東西時先自動截一次圖再找,還是沒有就停在第幾步交還給 Bot;任何一步失敗、被拒或重複,後面都不做。有風險的步驟照樣問使用者。 - 某一步點的東西說不出名字(只有編號),整份就不存步驟;「教我做」也會丟掉只看畫面、讀說明或技能、重播的步驟和照編號點的步驟。 -- 「教我做」學的是那則訊息開始的那一回合(同一句話別次做的不算);按過重新產生、重新傳送或重試,學的是聊天裡留著的最後那一次。只找得到 30 天內的;更早的、做事中途插的話,會說「找不到以「…」開始的那一回合」;只有看畫面或都失敗的會說「那一回合沒有可重播的步驟」。舊版手機頁面不帶訊息的時間,就學最近一次以同樣的話開始的回合(插的話跟某一回合開頭一樣,會學到那一回合)。 +- 「教我做」學的是那則訊息開始的那一回合(同一句話別次做的不算);按過重新產生、重新傳送或重試,學的是聊天裡留著的最後那一次。只找得到 30 天內的;更早的、做事中途插的話,會說「找不到以「…」開始的那一回合」;只有看畫面或都失敗的會說「那一回合沒有可重播的步驟」。舊版手機頁面不帶訊息的時間、或那一回合是這一版以前做的(沒記時間),就學最近一次以同樣的話開始的回合(插的話跟某一回合開頭一樣,會學到那一回合)。 - `save_skill` 存同名的技能會把原本存的可重播步驟一起換掉([skills](skills.md))。 - (驗證)插話太慢,那一輪會先結束、五步被拆成兩輪就不會學:每一步送出後立刻等下一個步驟出現再送。 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 6a22199..cd0056b 100644 --- a/src/memory.rs +++ b/src/memory.rs @@ -207,20 +207,25 @@ fn plain_words(t: &str) -> String { /// 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 — none (a 插話 -/// starts no turn of its own): not found. Without `at` (an older phone page) it is the latest -/// turn started by the same words. `starts`: the turns' first lines (store::turn_starts). -/// Ok: (that turn, the words that started it). +/// 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> { let key: String = plain_words(prompt).chars().take(40).collect(); - starts - .iter() - .rev() - .find_map(|r| match r { - crate::oplog::Record::OperationStarted { op, prompt: Some(p), .. } if at.is_none_or(|t| p.at == t) && plain_words(&p.text).chars().take(40).collect::() == key => Some((op.clone(), p.text.clone())), + 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, }) - .ok_or_else(|| format!("找不到以「{prompt}」開始的那一回合(只找得到 {} 天內、由一則訊息開始的回合;做事中途插的話不算)", crate::store::KEEP_DAYS)) + }; + 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, @@ -1497,6 +1502,24 @@ mod tests { 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"); + } #[test] fn remember_tells_the_same_thing_from_another_fact() { let bot = 4261; diff --git a/src/store.rs b/src/store.rs index 83299a8..32abf45 100644 --- a/src/store.rs +++ b/src/store.rs @@ -326,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,prompt_at) VALUES(?1,?2,?3,'turn',?4,?5)", - params![bot, op, at, prompt.as_ref().map(|p| p.text.clone()), prompt.as_ref().map(|p| p.at)], - ); - } + 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]); } @@ -397,7 +392,13 @@ pub fn turn_records(bot: u64, op: &str) -> Vec { 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![] }; - let Ok(mut st) = c.prepare(&format!("SELECT op,at,end_at,kind,name,detail,status,call_id,prompt_at FROM audit WHERE {filter} ORDER BY id ASC")) else { + 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 @@ -436,6 +437,15 @@ fn rebuilt(filter: &str, args: impl rusqlite::Params) -> Vec { 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 { @@ -851,6 +861,34 @@ mod tests { 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)