Merge branch 'fix-approval-key': 遠端的回答只交給它畫出來的那張卡(F1)

手機頁面、手機通知、螢幕電腦的回答都帶著那張卡的 key,大腦只交給 key 對得上、正在等的那張;
沒帶 key 的不收。通知上的按鈕只答 notice_answers 的允許請求(一次/拒絕)。沒用上的回答照來源
說怎麼辦;螢幕電腦不再推卡片通知(只有大腦推),自己的 Notification hook 照跑;問題卡照卡的
key 認。verify-approval-routing 跟著改,F1 成為回歸測試。

四輪,每輪都有乾淨脈絡的獨立審查,最後兩輪沒有 P0/P1。
已驗證: 全部 cargo test、clippy、lint-sh、run.sh --replay(10 個重走)、verify-anybot 手機流程;
  與 serve-bind 試合併後全部 cargo test 三次全綠
未驗證: 真的手機推播、真的第二台螢幕電腦、帳號伺服器那份頁面(要 make update-server);
  --ignored 沒有涵蓋審批卡的遠端回答
人類簽名: 使用者在對話中同意合併(2026-11-18)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
王性驊 2026-11-18 13:58:14 +08:00
commit 03aef031dd
19 changed files with 733 additions and 324 deletions

View File

@ -1,19 +1,23 @@
--- ---
name: verify-approval-routing name: verify-approval-routing
description: 改到「等你允許的卡片」從哪裡、被誰回答時用——大腦的 approvals/ask_keys、app.rs 的 answer()/on_new_approval、remote_ui.rs 的 Cmd::Answer、手機頁面 renderDock、手機通知 sw.js、螢幕電腦的回答、Bot 的 wait_answer。跑 TLA+ 模型檢查「允許只會落在按的人看到的那張卡上」,並告訴你模型還對不對得上現在的程式碼。 description: 改到「等你允許的卡片」從哪裡、被誰回答時用——大腦的 approvals/ask_keys、app.rs 的 answer()/on_new_approval/notice_answers、remote_ui.rs 的 Cmd::Answer 和 approval_json、手機頁面 renderDock/renderQuestion、手機通知 sw.js、螢幕電腦的回答和同步、Bot 的 wait_answer。跑 TLA+ 模型檢查「允許只會落在按的人看到的那張卡上」,並告訴你模型還對不對得上現在的程式碼。
--- ---
# 驗證:等你允許的卡片,回答落在哪一張 # 驗證:等你允許的卡片,回答落在哪一張
Bot 要做會動到你電腦的事時,大腦放一張「允許/一律允許/拒絕」的卡等你。能回答這張卡的地方有四個:大腦自己的視窗、手機頁面上的卡、手機通知上的「允許/拒絕」、螢幕電腦(鏡像大腦的另一台)。除了大腦自己的視窗,其他三個看到的都是某個時候抄過去的卡,按下去的回答要經過網路才到大腦。這個技能用 TLA+ 把「卡出現、卡不見、畫面同步、按下、回答到達」所有先後順序都走一遍,檢查兩條規則。 Bot 要做會動到你電腦的事時,大腦放一張卡等你:「允許/一律允許/拒絕」,或「需要處理」的「我完成了/跳過」,或問題卡。能回答這張卡的地方有四個:大腦自己的視窗、手機頁面上的卡、手機通知上的「允許/拒絕」、螢幕電腦(鏡像大腦的另一台)。除了大腦自己的視窗,其他三個看到的都是某個時候抄過去的卡,按下去的回答要經過網路才到大腦。每張卡有自己的 key(`on_new_approval` 發的),遠端的回答都帶著它,大腦只交給那張卡。這個技能用 TLA+ 把「卡出現、卡不見、畫面同步、按下、回答到達」所有先後順序都走一遍,檢查三條規則,再確認修法沒有把路堵死。
## 規則和傷害 ## 規則和傷害
- **AllowOnlyWhatWasSeen**:使用者按「允許」或「一律允許」,只會讓他按下時看到的那張卡通過。 - **AllowOnlyWhatWasSeen**:使用者按「允許」「一律允許」(需要處理的卡上是「我完成了」),只會讓他按下時看到的那張卡通過。
傷害:不然 Bot 會拿使用者對另一件事說的「好」,去做一件他從沒看過的事(刪檔、送出、付款都可能)。 傷害:不然 Bot 會拿使用者對另一件事說的「好」,去做一件他從沒看過的事(刪檔、送出、付款都可能)。
- **RuleOnlyWhatWasSeen**:「一律允許」記到 Bot 身上的類別,一定是按下時那張卡上寫的。 - **RuleOnlyWhatWasSeen**:「一律允許」記到 Bot 身上的類別,一定是按下時那張卡上寫的。
傷害:不然一個使用者沒看過的類別會被永久放行,之後同類的事都不再問。 傷害:不然一個使用者沒看過的類別會被永久放行,之後同類的事都不再問。
(在這個模型裡它壞的時候前一條一定也壞;分開寫是因為傷害不同:一次 vs 永久。) (在這個模型裡它壞的時候前一條一定也壞;分開寫是因為傷害不同:一次 vs 永久。)
- **NoticeNeverFinishesHandoff**:手機通知上的「允許/拒絕」只回答「要你允許的事」,絕不會變成「需要處理」的「我完成了/跳過」。
傷害:不然 Bot 以為你已經登入、通過驗證(其實沒有),接著在那個狀態下做事。
- **路沒堵死**(`CanAnswer.cfg`,要「違反」`SomePlaceCannotAnswer`):有一種走法,手機頁面、手機通知、螢幕電腦的回答都各自真的交給了一張卡。
傷害:修法要是讓某個地方再也答不了(例如手機不送 key),使用者在那裡按什麼都沒用。
## 什麼時候用 ## 什麼時候用
@ -24,58 +28,60 @@ Bot 要做會動到你電腦的事時,大腦放一張「允許/一律允許
## 怎麼跑(一個指令,約 10 秒) ## 怎麼跑(一個指令,約 10 秒)
```sh ```sh
.claude/skills/verify-approval-routing/run.sh # 程式碼有沒有改過+三個 cfg .claude/skills/verify-approval-routing/run.sh # 程式碼有沒有改過+兩個 cfg
.claude/skills/verify-approval-routing/run.sh --replay # 再加上在真的程式上重走反例(cargo test,要編譯) .claude/skills/verify-approval-routing/run.sh --replay # 再加上在真的程式上重走(cargo test,要編譯)
``` ```
- 需要 Java 11 以上(`$JAVA`、PATH 上的 `java`,或 Homebrew 的 openjdk@17)、python3、curl。第一次把 tla2tools 1.7.4 下載到 `~/.local/share/anybot-formal/tla2tools-1.7.4.jar`,每次都核對 SHA-256 `936a262061c914694dfd669a543be24573c45d5aa0ff20a8b96b23d01e050e88`。不放進 repo。 - 需要 Java 11 以上(`$JAVA`、PATH 上的 `java`,或 Homebrew 的 openjdk@17)、python3、curl。第一次把 tla2tools 1.7.4 下載到 `~/.local/share/anybot-formal/tla2tools-1.7.4.jar`,每次都核對 SHA-256 `936a262061c914694dfd669a543be24573c45d5aa0ff20a8b96b23d01e050e88`。不放進 repo。
- 結束碼:0 跟基準一樣;1 跟基準不一樣(新的破口,或已知發現 F1 不見了);2 工具出錯;3 跟基準一樣,但對照的程式碼改過了——結果還不能信,照「程式碼改了之後」做。 - 結束碼:0 跟基準一樣;1 跟基準不一樣(新的破口,或某個地方再也答不了卡);2 工具出錯;3 跟基準一樣,但對照的程式碼改過了——結果還不能信,照「程式碼改了之後」做。
- 基準(同步 commit 時的輸出): - 基準(同步 commit 時的輸出):
``` ```
== 程式碼有沒有改過(對照 coverage.tsv,同步 commit 見 SKILL.md) == 程式碼有沒有改過(對照 coverage.tsv,同步 commit 見 SKILL.md)
沒有改:模型描述的還是現在這份程式碼。 沒有改:模型描述的還是現在這份程式碼。
== Guarded:通過(界限內 1155 個狀態都看過) == AllSurfaces:通過(界限內 421324 個狀態都看過)
== AllSurfacesKeyed:通過(界限內 716889 個狀態都看過) == CanAnswer:違反 SomePlaceCannotAnswer ——預期中:找得到一種走法,手機頁面、通知、螢幕電腦的回答都交得出去
== AllSurfaces:違反 AllowOnlyWhatWasSeen ——預期中的已知發現 F1(…) TLC 的步驟(…)
== 在真的程式上重走(--replay 才有)
10 個都通過:真的程式也是(跟 AllSurfaces 一致)
== 全部跟預期一樣。 == 全部跟預期一樣。
``` ```
| cfg(`model/`) | 誰能回答 | 程式事實 | 預期 | | cfg(`model/`) | 檢查什麼 | 預期 |
| --- | --- | --- | --- | | --- | --- | --- |
| `Guarded.cfg` | 大腦視窗、手機通知 | 照現在的程式 | 通過 | | `AllSurfaces.cfg` | 四個地方都能回答,照現在的程式;三條規則 | 通過 |
| `AllSurfacesKeyed.cfg` | 四個都能 | 假設手機頁面、螢幕電腦也帶那張卡的 key(F1 的修法,程式裡還沒有) | 通過:除了 F1 沒有別的破口 | | `CanAnswer.cfg` | 同一份模型,找「三個遠端都真的答到卡」的走法 | 違反 `SomePlaceCannotAnswer`(找到了) |
| `AllSurfaces.cfg` | 四個都能 | 照現在的程式 | 違反:已知發現 F1 |
預期寫在 `run.sh` 的 `EXPECT`。 預期寫在 `run.sh` 的 `EXPECT`;`--replay` 跑的測試寫在 `REPLAY`。
## 讀結果 ## 讀結果
- **每一個結果都用 `/pstack:statechart` 讀。** 把 `model/ApprovalRouting.tla`、那個 cfg 和 `model/statechart-view.ts`(寫好的白話標籤)複製到 repo 外面的暫存資料夾,照 `/pstack:statechart` 自己的說明跑;它要 TLC 或 Java 時,給它 `run.sh` 下載的那個 jar 和你的 Java。違反時它把最短的反例寫成白話步驟;通過時它畫狀態圖——圖只畫得出 500 個狀態以內的模型,要看通過的圖就把 cfg 的 `N` 改成 2、只留兩個回答的地方(例如 Guarded 在 N = 2 是 168 個狀態)。`run.sh` 自己只印 TLC 的動作名稱。 - **每一個結果都用 `/pstack:statechart` 讀。** 把 `model/ApprovalRouting.tla`、那個 cfg 和 `model/statechart-view.ts`(寫好的白話標籤)複製到 repo 外面的暫存資料夾,照 `/pstack:statechart` 自己的說明跑;它要 TLC 或 Java 時,給它 `run.sh` 下載的那個 jar 和你的 Java。違反時它把最短的反例寫成白話步驟;通過時它畫狀態圖——圖只畫得出 500 個狀態以內的模型,要看通過的圖就把 cfg 的 `N` 改成 2、`Surfaces` 只留兩個(例如 `{"desk", "banner"}`)。`run.sh` 自己只印 TLC 的動作名稱。
- **分辨真的 bug 和模型錯:** - **分辨真的 bug 和模型錯:**
1. 把反例每一步照「對照表」對到程式碼,問兩件事:程式真的能這樣走嗎?這一步在程式裡是不是一口氣做完、中間不會插進別的事? 1. 把反例每一步照「對照表」對到程式碼,問兩件事:程式真的能這樣走嗎?這一步在程式裡是不是一口氣做完、中間不會插進別的事?
2. 在真的程式上重走:`run.sh --replay`,或照 `src/app/remote_ui.rs` 最後的 `approval_routing_replay` 模組寫一個測試,每一步對應模型的一個動作(它示範了怎麼送 `NeedApproval`、怎麼呼叫 `answer()` 和 `remote_cmd(Cmd::Answer…)`)。 2. 在真的程式上重走:`run.sh --replay`,或照 `src/app/remote_ui.rs` 最後的 `approval_routing_replay` 模組(和 `src/app/mirror_ui.rs` 的 `a_screen_answers_only_the_card_it_shows`、`a_screen_keeps_its_cards_key_in_step_with_the_brains`)寫一個測試,每一步對應模型的一個動作。它們示範了怎麼送 `NeedApproval`、怎麼呼叫 `answer()`、`remote_cmd(Cmd::Answer…)`、`phone_cards`、`brain_pull`、`mirror_apply`(螢幕電腦要設 `ctx_handle`,新卡的 key 才會換進它自己的 `ask_keys`)。
3. 真的程式走不出來 → 先當成模型錯,改模型直到你說得出差在哪;不要改規則。走得出來 → 是 bug:照下面 F1 的寫法記下來(反例用程式碼的話講),不要放寬規則讓它通過,也不要沒問過人就改產品程式。 3. 真的程式走不出來 → 先當成模型錯,改模型直到你說得出差在哪;不要改規則。走得出來 → 是 bug:照下面 F1 的寫法記下來(反例用程式碼的話講),不要放寬規則讓它通過,也不要沒問過人就改產品程式。
- 手機頁面(JavaScript)不在 `cargo test` 裡:改了 `renderDock`、`renderQuestion` 送出的東西,用 `verify-anybot` 技能在真的手機頁面上按一次(允許、拒絕會用;舊卡、沒帶 key 的回答不算)。
## 已知發現 F1:手機頁面和螢幕電腦的「允許」會落在後來的卡上 ## F1(已修好):手機頁面和螢幕電腦的「允許」曾經落在後來的卡上
TLC 在 `AllSurfaces.cfg` 找到的最短反例,用程式碼的話講: 這個技能第一次跑(commit 8c4315a)找到的。當時 TLC 在 `AllSurfaces.cfg` 的最短反例,用程式碼的話講:
1. Bot 要在你的電腦上做 A:`Step::ask_person` 送出 `NeedApproval`,大腦的 `drain_events` 把卡 A 放進 `approvals`,`on_new_approval` 發 key k1。 1. 卡 A 放上來:`NeedApproval` → `approvals.insert`,`on_new_approval` 發 key k1。
2. 手機的長輪詢拿到 `api/state`,`renderDock` 畫出卡 A。 2. 手機的長輪詢拿到 `api/state`,`renderDock` 畫出卡 A(`approval_json` 沒給 key)。
3. 卡 A 在手機上沒被回答就不見了:你在電腦上回答了它(`answer()`),或按了停止、沒人在旁邊等超過 15 分鐘(`stop`、`watchdog`)。 3. 卡 A 在手機上沒被回答就不見了:電腦上回答了(`answer()`),或按了停止、15 分鐘逾時。
4. Bot 問下一件 B(同一輪的下一個工具呼叫,或你再傳訊息後的新一輪),`NeedApproval` 在路上。 4. Bot 問下一件 B,卡 B 放上來,key 換成 k2。
5. 手機上還是卡 A;你(或另一個能允許的人,例如管理員用他的手機)按「允許」或「一律允許」:`renderDock` POST `{answer: "always"}`,沒有 `call`。 5. 手機上還是卡 A;有人按「一律允許」:`renderDock` POST `{answer: "always"}`,沒有 `call`。
6. 大腦放上卡 B,key 換成 k2。(POST 比卡 B 早送出、晚到也行,網路就是這樣。) 6. 大腦的 `Cmd::Answer`:`call` 是空的就跳過 key 的檢查,`grant` 讀卡 B 的,`answer()` 讓 B 通過、把 B 的 grant 推進 `allow_rules`。
7. 大腦的 `Cmd::Answer`:`call` 是空的,跳過 key 的檢查;`grant` 讀現在這張卡(B)的;`answer()` 把 `Always(B 的 grant)` 交給卡 B,也把 B 的 grant 推進 `allow_rules`。
結果:B 被允許,而且 B 那一類以後都不再問;按的人只看過 A。螢幕電腦(`answer()` 的 `mir.on` 分支送 `{"bot", "action": "answer", "answer", "text"}` 到 `api/sync/act`)一樣不帶 `call`,走同一條路。手機通知上的按鈕帶 `call = d.ask`(那張卡的 key),大腦會擋,所以 `Guarded.cfg` 通過。 螢幕電腦(`answer()` 的 `mir.on` 分支)也不帶 `call`,走同一條路。當時的真程式重現:`rm -rf` 那張收到 `Always("rm")`、`allow_rules` 記下 `rm`。
真的程式上重現:`cargo test --bin anybot approval_routing_replay -- --include-ignored` 裡 `a_phone_card_tapped_after_it_changed_answers_nothing_else` 失敗,訊息是「手機上看到的是 npm install;rm -rf 那張收到 Ok(Always("rm")),一律允許記下 ["rm"]」。這個測試標了 `#[ignore]`,平常的 `cargo test` 不跑。 修法(這一版的程式):
- `approval_json` 把卡的 key 給手機(支線的卡用支線自己的 key),`renderDock` 的三個按鈕、「全部允許,之後直接操作」、問題卡的送出和略過都送 `call: a.key`;問題卡的表單也用 key 分辨是哪一張(call id 會重複)。
會遇到的時候:兩個人都能允許(擁有者和管理員各拿一支手機)、你同時開著電腦和手機、或卡 A 被允許後 Bot 很快就問下一件。窗口是手機輪詢的延遲。 - 大腦給螢幕電腦的 `approvals` 帶 `key`;螢幕電腦把它記在 `mir.keys`、拿它當自己這張卡的 key(`new_approval_keyed`),回答時送 `call`;新卡用 key 分辨,不再只看 call id。舊版大腦沒給 key 時照舊(不送 call)。
- `Cmd::Answer`:key 不是現在在等的那張卡的、或根本沒帶 key(開了很久的舊頁面、舊版螢幕電腦)→ 不收。通知送來的(`from: "notice"`)另外要過 `notice_answers`——放通知按鈕和收通知回答用同一條規則——而且只收 once/reject。
修法方向(沒有改,等人決定):`approval_json` 把這張卡的 ask key 給手機、`renderDock` 送成 `call`;螢幕電腦同步時拿到大腦的 key、回答時帶上(它自己的 `ask_keys` 是本機亂數,不能用)。`Cmd::Answer` 現有的檢查就會擋掉舊的回答——`AllSurfacesKeyed.cfg` 就是這個修法,模型裡通過。 - 不收的時候(有卡在等才說):照它從哪條路來寫該怎麼辦——`api/bots/…/answer`(手機)沒帶 key 是「這個頁面太舊…重新整理再回答;還是不行(帳號伺服器還沒更新),就在電腦上回答」;`api/sync/act`(螢幕電腦,`Cmd::Answer` 的 `screen`)沒帶 key 是「那台電腦的 AnyBot 比這台舊…設定 › 更新」;帶了舊 key 是「那張卡已經不在等了」。支線的卡寫在主線的聊天(`home_of`:支線自己的訊息哪裡都不顯示)。直接操作打開時放行的「可以用電腦嗎」卡(`settled_by_direct`),手機「全部允許,之後直接操作」接著送來的那個回答不寫。
- 回歸測試:`a_phone_card_tapped_after_it_changed_answers_nothing_else`(舊程式會失敗)、`a_phone_answer_without_its_cards_key_answers_nothing`、`a_banner_answers_only_its_own_request`、`a_branch_card_on_the_phone_carries_its_own_key_and_target`、`the_answer_after_direct_mode_let_its_card_through_says_nothing`、`a_screen_answers_only_the_card_it_shows`、`a_screen_keeps_its_cards_key_in_step_with_the_brains`、`a_question_in_anothers_place_starts_with_nothing_picked`(大腦視窗和螢幕電腦的問題卡表單照 key 認)、`a_card_in_anothers_place_is_published_again`(同一個 call_0 的新卡、支線的新卡都會重新送到手機和螢幕電腦)。
## 對照表:模型的每個動作 ↔ 程式碼 ## 對照表:模型的每個動作 ↔ 程式碼
@ -84,68 +90,68 @@ TLC 在 `AllSurfaces.cfg` 找到的最短反例,用程式碼的話講:
| 模型的動作 | 程式碼(id) | 模型假設這段做的事 | | 模型的動作 | 程式碼(id) | 模型假設這段做的事 |
| --- | --- | --- | | --- | --- | --- |
| `BotAsks` | `bot.ask_person`(src/agent/steps.rs `Step::ask_person`) | 送 `ToolStatus(Waiting)` 和 `NeedApproval`,帶這張卡自己的 reply channel,然後 `wait_answer`。同一個 Bot 一次只等一張:一步裡的工具呼叫一個一個跑(agent.rs 的 `for asked in calls`)。 | | `BotAsks` | `bot.ask_person`(src/agent/steps.rs `Step::ask_person`) | 送 `ToolStatus(Waiting)` 和 `NeedApproval`,帶這張卡自己的 reply channel,然後 `wait_answer`。同一個 Bot 一次只等一張:一步裡的工具呼叫一個一個跑(agent.rs 的 `for asked in calls`)。 |
| (Bot 收到回答) | `bot.wait_answer`(src/agent.rs `wait_answer`) | 收到哪個回答就是哪個;channel 斷了或按停止=拒絕。回答只會從這張卡自己的 reply 來。 | | (Bot 收到回答) | `bot.wait_answer`(src/agent.rs) | 收到哪個回答就是哪個;channel 斷了或按停止=拒絕。回答只會從這張卡自己的 reply 來。 |
| `CardShows` | `brain.need_approval`、`brain.on_new_approval`(src/app.rs) | UI 執行緒一次做完:`approvals.insert`(同一個 Bot 只有一格)、`ask_keys` 換成新的亂數 key、不在 App 前面時推一則手機通知(帶這把 key)。 | | `CardShows` | `brain.need_approval`、`brain.on_new_approval`、`brain.new_approval_keyed`、`brain.notice_answers`(src/app.rs) | UI 執行緒一次做完:`approvals.insert`(同一個 Bot 只有一格)、`ask_keys` 換成新的亂數 key、不在 App 前面時推手機通知——`notice_answers` 的卡才帶 key 和「允許/拒絕」;螢幕電腦(`mir.on`)不推。 |
| `TurnStops` | `brain.stop`、`brain.watchdog`(src/app.rs) | `approvals.remove`,reply 被丟掉 → Bot 拿到拒絕;舊一輪還在路上的事件 `drain_events` 不收。之後 Bot 可以再問下一件。 | | `TurnStops` | `brain.stop`、`brain.watchdog`(src/app.rs) | `approvals.remove`,reply 被丟掉 → Bot 拿到拒絕;舊一輪還在路上的事件 `drain_events` 不收。之後 Bot 可以再問下一件。 |
| `YouAnswerOnDesk` | `desk.approval_dock`、`desk.approval_body`、`brain.answer`(src/app.rs) | 同一個畫面格裡畫出現在的卡、讀按鈕或 Enter/Esc、呼叫 `answer()`:看到的就是現在的卡。 | | `YouAnswerOnDesk` | `desk.approval_dock`、`desk.approval_body`、`desk.question_card`、`brain.answer`(src/app.rs) | 同一個畫面格裡畫出現在的卡、讀按鈕或 Enter/Esc、呼叫 `answer()`:看到的就是現在的卡。問題卡的表單(步驟、勾選、打的字)照卡的 key 認,換了一張(就算同一個 call_0、題數一樣)就從頭開始。 |
| `PageRefreshes` | `page.approval_json`(src/app/remote_ui.rs)、`page.render_dock`(mobile/index.html) | 手機拿到的是大腦某一刻的 `approvals`,可以一直不更新;`approval_json` 給的卡沒有 key。 | | `PageRefreshes` | `page.approval_json`、`page.phone_cards`(src/app/remote_ui.rs)、`page.render_dock`、`page.question`(mobile/index.html) | 手機拿到的是大腦某一刻的 `approvals`,每張卡帶自己的 `key`(支線的卡放在主線的聊天、`target` 是支線、帶支線的 key);可以一直不更新。 |
| `YouTapOnPage` | `page.render_dock`、`remote.answer_routes`(src/remote.rs) | 按下就清掉手機上的卡,POST `{answer}`;沒有 `call`,remote.rs 把沒有的 `call` 當成 `""`。三個按鈕:允許(一次)、一律允許、拒絕。 | | `YouTapOnPage` | `page.render_dock`、`page.question`、`remote.answer_routes`(src/remote.rs) | 按下就清掉手機上的卡,POST `{answer, call: a.key}`(問題卡 `{answer: "answered"\|"reject", text, call}`);更新前就開著的舊頁面不帶 `call`。 |
| `YouTapBanner` | `banner.notificationclick`(mobile/sw.js)、`page.banner_answer`(mobile/index.html) | 只有 allow → `once`、deny → `reject`;帶 `call = d.ask`(推通知時那張卡的 key)。同一個 Bot 新的通知蓋掉舊的。 | | `YouTapBanner` | `banner.notificationclick`(mobile/sw.js)、`page.banner_answer`、`page.open_from_hash`、`page.banner_message`(mobile/index.html) | 只有 allow → `once`、deny → `reject`;帶 `call = d.ask`(推通知時那張卡的 key)和 `from: "notice"`。同一個 Bot 新的通知蓋掉舊的。 |
| `ScreenRefreshes` | `screen.sync`(src/app/mirror_ui.rs) | 螢幕電腦把大腦的 `approvals` 整份換進來,可以一直不更新。 | | `ScreenRefreshes` | `screen.view`、`screen.sync`(src/app/mirror_ui.rs) | 大腦給的每張卡帶 `key`;螢幕電腦把 `approvals` 整份換進來,key 記在 `mir.keys`,key 變了才算新卡,新卡用 `new_approval_keyed` 把同一把 key 放進自己的 `ask_keys`;可以一直不更新。 |
| `YouAnswerOnScreen` | `brain.answer` 的 `mir.on` 分支、`remote.answer_routes` | 螢幕電腦先拿掉自己的卡,送 `{"bot", "action": "answer", "answer", "text"}`,沒有 `call`。 | | `YouAnswerOnScreen` | `brain.answer` 的 `mir.on` 分支、`remote.answer_routes` | 螢幕電腦先拿掉自己的卡,送 `{"bot", "action": "answer", "answer", "text", "call": mir.keys 裡那把}`;舊版螢幕電腦不帶 `call`。 |
| `BrainTakesAnswer` | `brain.cmd_answer`(src/app/remote_ui.rs `Cmd::Answer`)、`brain.answer` | UI 執行緒一次做完:帶了 `call` 卻不是現在這張的 key(或卡不在)→ 寫「沒有用上」、不動;否則 `answer()` 交給現在的卡;「一律允許」的 grant 讀現在這張卡的。 | | `BrainTakesAnswer` | `brain.cmd_answer`(src/app/remote_ui.rs `Cmd::Answer`)、`brain.notice_answers`、`brain.answer` | UI 執行緒一次做完:有卡在等、帶了 key、key 是現在 `ask_keys` 那把(`ThisCard`),而且不是通知、或是 `notice_answers` 的卡加上 once/reject(`Fits`),才交給 `answer()`;不然不動(有卡在等時在主線的聊天寫「沒有用上」,寫什麼看它從哪條路來;模型不管寫不寫、寫什麼)。「一律允許」的 grant 讀現在這張卡的。 |
| `Settle`(上面幾個共用) | `brain.answer` | `approvals.remove` → `Always` 就把 grant 推進 `allow_rules` → `reply.send`。 | | `Settle`(上面幾個共用) | `brain.answer` | `approvals.remove` → `Always` 而且是 Action 就把 grant 推進 `allow_rules` → `reply.send`。 |
## 程式事實(cfg 的常數) ## 程式事實(cfg 的常數)
每一條對應程式裡的一行。程式改了讓某一條不再成立,三個 cfg 都要改它:`AllSurfacesKeyed.cfg` 也是「現在的程式」,只有 `PageSendsKey`、`ScreenSendsKey` 兩條是假設 F1 修好。 每一條對應程式裡的一行。程式改了讓某一條不再成立,兩個 cfg 都要改它。
| 常數 | 現在 | 程式碼 | | 常數 | 現在 | 程式碼 |
| --- | --- | --- | | --- | --- | --- |
| `FreshKeyPerCard` | TRUE | `brain.on_new_approval`:`let key = crate::httpd::random_hex(16);` `self.ask_keys.insert(bot_id, key.clone());` | | `FreshKeyPerCard` | TRUE | `brain.on_new_approval`:`let key = crate::httpd::random_hex(16);`,`brain.new_approval_keyed`:`self.ask_keys.insert(bot_id, key.clone());` |
| `BannerKeyChecked` | TRUE | `brain.cmd_answer`:`if !call.is_empty() && !(allowable && self.ask_keys.get(&bot) == Some(&call)) {` … `return;` | | `KeyChecked` | TRUE | `brain.cmd_answer`:`self.ask_keys.get(&bot) == Some(&call)` |
| `PageSendsKey` | FALSE | `page.render_dock`:``api(base() + `api/bots/${(a && a.target) \|\| S.open}/answer`, {json: {answer: x.dataset.a}})`` | | `KeylessRefused` | TRUE | `brain.cmd_answer`:`let this_card = waiting.is_some() && !call.is_empty() && …` |
| `ScreenSendsKey` | FALSE | `brain.answer`:`self.mirror_act(serde_json::json!({"bot": bot_id, "action": "answer", "answer": a, "text": text}));` | | `NoticeFitsChecked` | TRUE | `brain.cmd_answer`:`let fits = !notice \|\| (waiting.is_some_and(super::notice_answers) && matches!(answer.as_str(), "once" \| "reject"));` |
| `PageSendsKey` | TRUE | `page.render_dock`:`{json: {answer: x.dataset.a, call: a.key \|\| ""}}`;`page.question`:`Object.assign({call: a.key \|\| ""}, body)` |
| `ScreenSendsKey` | TRUE | `brain.answer`:`"call": call`(`self.mir.keys.get(&bot_id)`) |
## 範圍:證明了什麼、沒有證明什麼 ## 範圍:證明了什麼、沒有證明什麼
- 證明的:在下面的界限裡,卡出現、卡不見、畫面同步、按下、回答到達的每一種先後順序(網路延遲任意、手機和螢幕電腦的畫面任意舊、回答可以任意晚到),兩條規則在 `Guarded`、`AllSurfacesKeyed` 都成立,在 `AllSurfaces` 不成立(F1)。 - 證明的:在下面的界限裡,卡出現、卡不見、畫面同步、按下、回答到達的每一種先後順序(網路延遲任意、手機和螢幕電腦的畫面任意舊、回答可以任意晚到、手機頁面和螢幕電腦可能是更新前的舊版而不帶 key),三條規則都成立;而且手機頁面、通知、螢幕電腦的回答都還交得到卡上。
- 界限:一個 Bot;一段時間問 `N = 3` 件事;每個地方同時最多一個回答在路上(cfg 的 `CONSTRAINT OneAnswerOnTheWayPerSurface`,程式沒有這個限制);手機頁面一支(兩個人兩支手機是同一類順序);每張卡都是一般的「允許這個操作」(Action),而且都有「一律允許」的類別。 - 界限:一個 Bot;一段時間問 `N = 3` 件事,前兩件是允許請求、第三件是「需要處理」;每個地方同時最多一個回答在路上(cfg 的 `CONSTRAINT OneAnswerOnTheWayPerSurface`,程式沒有這個限制);手機頁面一支(兩個人兩支手機是同一類順序)。
- 假設:大腦視窗上「看到就回答」在同一個畫面格裡做完。 - 假設:大腦視窗上「看到就回答」在同一個畫面格裡做完;`notice_answers` 在模型裡等於「是允許請求」(它另外擋掉太長的指令和 hooks 的改動,這兩種也只會讓通知「不答」)。
- 沒有放進模型(這些地方改了,這個檢查不會發現): - 沒有放進模型(這些地方改了,這個檢查不會發現):
- 大腦視窗上按住「允許」不放、放開前卡被換成另一張:egui 的按鈕放開時才算按下,兩張卡的按鈕 id 一樣,可能也會落到新卡上。**沒驗證,建議當下一個目標。** - 大腦視窗上按住「允許」不放、放開前卡被換成另一張:egui 的按鈕放開時才算按下,兩張卡的按鈕 id 一樣,可能也會落到新卡上。沒驗證。
- 問題卡(Question)和「需要處理」(Handoff):手機頁面上的「送出」「我完成了」也不帶 `call`,舊的「允許」落到 Handoff 上就是「我完成了」。沒驗證。
- 一律放行(/always-approve)、直接操作、自動審核、hooks 替你回答的;打開直接操作時一起放行的「可以用電腦嗎」。 - 一律放行(/always-approve)、直接操作、自動審核、hooks 替你回答的;打開直接操作時一起放行的「可以用電腦嗎」。
- 支線(`a.target`)、群組聊天、同一個 Bot 兩輪同時在跑、`app_pending`(App 操作工具的卡)。 - 群組聊天、同一個 Bot 兩輪同時在跑、`app_pending`(App 操作工具的卡;它也走 `on_new_approval`,所以一樣有 key)。
- `call_id` 本身(模型用 ask key 分辨卡);`ToolStatus` 用 `call_id` 清卡;Enter/Esc 的 0.6 秒等待和對話框、游標的規則(那些有 `app::tests` 的測試)。 - 問題卡的內容(模型把問題卡當成一般的卡:送出/略過都是一個帶 key 的回答)。
- Enter/Esc 的 0.6 秒等待和對話框、游標的規則(那些有 `app::tests` 的測試)。
- 手機通知什麼時候被別的通知蓋掉(模型讓舊通知一直留著,比真的寬)。 - 手機通知什麼時候被別的通知蓋掉(模型讓舊通知一直留著,比真的寬)。
- 帳號伺服器(`relay/`)自己編進去一份手機頁面:伺服器沒更新前,用帳號登入的手機送不出 key,回答全都不收(安全,但答不了)。這是部署的事,不在模型裡。
- 舊的帳號伺服器頁面上按通知:舊頁面送 `call = d.ask` 但沒有 `from: "notice"`,大腦把它當手機自己的卡(不過 `Fits`)。今天還是安全的,因為兩件事:通知的 key 只發給 `notice_answers` 的卡(`on_new_approval`),而舊的 sw.js 也只送 once/reject。哪天通知帶 key 的範圍變了,或 sw.js 能送別的回答,這條路要放進模型。
- 螢幕電腦不推通知:`new_approval_keyed` 在 `mir.on` 時只響、只跳 macOS 的通知、只跑這台自己的 Notification hook(`hooks::notification`;hooks 是每台電腦自己的),不推到手機(`remote::notify_approval`/`notify` 都不叫)。以前會推:帳號伺服器在那則通知蓋上螢幕電腦的 host(`relay/src/main.rs` 的 `relay/host/notify`),手機按了就切到螢幕電腦、把回答送過去,而螢幕電腦不替手機做任何事(`remote_tick` 丟掉 `mir.on` 時的手機指令)、也不給手機畫面,「允許」就不見了。同一張卡由大腦推(同一個「通知」設定,大腦不在前面或閒置 90 秒時;大腦在伺服器上就一定推);大腦那台正在用時,大腦和螢幕電腦都不推。模型的 `YouTapBanner` 只畫大腦推的通知,這一條是照程式讀的,沒有測試(推播只在非示範模式、而且要連帳號伺服器)。
- 「沒有用上」寫在哪個聊天、寫什麼字、直接操作放行過的卡不寫(`settled_by_direct`):只影響要不要說一句,不影響哪張卡收到回答;`remote_ui.rs`、`mirror_ui.rs` 的測試管。
## 覆蓋紀錄和同步 commit ## 覆蓋紀錄和同步 commit
- **同步 commit:`4939838`**——在這個 commit 對過:`coverage.tsv` 每一段程式碼都照「對照表」描述的那樣做,`run.sh` 輸出就是上面的基準。 - **同步 commit:最後一次改 `coverage.tsv` 的那個 commit**——`git log -1 --format=%h -- .claude/skills/verify-approval-routing/coverage.tsv`。在那個 commit 對過:`coverage.tsv` 每一段程式碼都照「對照表」描述的那樣做,`run.sh --replay` 的輸出就是上面的基準。(寫成這樣,是因為確認和 rehash 跟著程式碼一起進同一個 commit,那個 commit 的編號事先不知道。)
- `coverage.tsv` 記每一段在同步 commit 時的 sha256;`run.sh` 第一步重算、比對。 - `coverage.tsv` 記每一段在同步 commit 時的 sha256;`run.sh` 第一步重算、比對。
- 看同步 commit 之後誰動過這些檔: - 看同步 commit 之後誰動過這些檔:
`git log --oneline 4939838..HEAD -- src/app.rs src/app/remote_ui.rs src/app/mirror_ui.rs src/remote.rs src/agent.rs src/agent/steps.rs mobile/index.html mobile/sw.js` `git log --oneline "$(git log -1 --format=%h -- .claude/skills/verify-approval-routing/coverage.tsv)"..HEAD -- src/app.rs src/app/remote_ui.rs src/app/mirror_ui.rs src/remote.rs src/agent.rs src/agent/steps.rs mobile/index.html mobile/sw.js`
## 程式碼改了之後(`run.sh` 結束碼 3) ## 程式碼改了之後(`run.sh` 結束碼 3)
1. 對每個「改過了」的段落跑 `drift.py … --show <id>`,跟「對照表」那一列、「程式事實」那一列比:模型假設的事還成立嗎?還是一口氣做完嗎? 1. 對每個「改過了」的段落跑 `drift.py … --show <id>`,跟「對照表」那一列、「程式事實」那一列比:模型假設的事還成立嗎?還是一口氣做完嗎?
2. 不成立 → 改模型:程式事實就改三個 cfg 的那個常數,別的就改 `ApprovalRouting.tla` 裡那個動作。是刻意的行為改變,連 `run.sh` 的 `EXPECT` 和這份檔一起改。不要改規則。 2. 不成立 → 改模型:程式事實就改兩個 cfg 的那個常數,別的就改 `ApprovalRouting.tla` 裡那個動作。是刻意的行為改變,連 `run.sh` 的 `EXPECT` 和這份檔一起改。不要改規則。
例:`on_new_approval` 改成 `self.ask_keys.entry(bot_id).or_insert(key)`(只在第一次發 key)→ `FreshKeyPerCard = FALSE` → `Guarded` 違反 `AllowOnlyWhatWasSeen`:舊通知上的「允許」讓後來的卡通過,`--replay` 的 `an_old_banner_does_not_allow_the_next_card` 也失敗。現有的 `a_banner_answers_only_its_own_request` 是自己塞 key 的,抓不到這個。 例:`Cmd::Answer` 改成沒帶 key 也收(`(call.is_empty() || …)`)→ `KeylessRefused = FALSE` → `AllSurfaces` 違反 `AllowOnlyWhatWasSeen`:舊頁面上的「允許」讓後來的卡通過;`--replay` 的 `a_phone_card_tapped_after_it_changed_answers_nothing_else` 也失敗。手機頁面不送 key → `PageSendsKey = FALSE` → `AllSurfaces` 照樣通過,但 `CanAnswer` 也「通過」了(手機頁面再也答不到卡),`run.sh` 說不預期。
3. 跑 `run.sh`;不預期的違反照「讀結果」分辨,用 `/pstack:statechart` 讀。 3. 跑 `run.sh --replay`;不預期的結果照「讀結果」分辨,用 `/pstack:statechart` 讀。
4. 確認模型描述現在的程式之後才跑 `drift.py … --rehash`,再把上面的同步 commit 改成你確認時的 commit。沒確認就不要動同步 commit,也不要 rehash。 4. 確認模型描述現在的程式之後才跑 `drift.py … --rehash`,跟程式碼放進同一個 commit——那個 commit 就是新的同步 commit。沒確認就不要 rehash。
5. 段落搬家或改名(「找不到」)→ 改 `coverage.tsv` 那一行的「開始」「結束」,再走 1–4。新增了能回答卡片的地方 → 在模型加一個動作、在 `coverage.tsv` 加它的段落、在對照表加一列。 5. 段落搬家或改名(「找不到」)→ 改 `coverage.tsv` 那一行的「開始」「結束」,再走 1–4。新增了能回答卡片的地方 → 在模型加一個動作、在 `coverage.tsv` 加它的段落、在對照表加一列、在 `REPLAY` 加它的測試。
## F1 修好之後
- `AllSurfaces.cfg` 的 `PageSendsKey`、`ScreenSendsKey` 改成 TRUE(照修好的程式碼對過),`run.sh` 的 `EXPECT` 改成 `AllSurfaces:pass`;`AllSurfacesKeyed.cfg` 跟它一樣了,可以刪掉(連 `EXPECT` 裡那一項)。
- 拿掉 `approval_routing_replay` 裡 `#[ignore]`,`run.sh --replay` 那段改成兩個測試都要 ok。
- 這份檔的 F1 改成「已修好(commit …)」,照「程式碼改了之後」移動同步 commit。
## 檔案 ## 檔案
- `model/ApprovalRouting.tla`:模型(每個動作的註解寫了對應的程式碼)。 - `model/ApprovalRouting.tla`:模型(每個動作的註解寫了對應的程式碼)。
- `model/Guarded.cfg`、`model/AllSurfaces.cfg`、`model/AllSurfacesKeyed.cfg`:三種情況。 - `model/AllSurfaces.cfg`、`model/CanAnswer.cfg`:三條規則;路沒堵死。
- `model/statechart-view.ts`:給 `/pstack:statechart` 的白話標籤。 - `model/statechart-view.ts`:給 `/pstack:statechart` 的白話標籤。
- `run.sh`:唯一要跑的指令。`drift.py`、`coverage.tsv`:程式碼有沒有改過。 - `run.sh`:唯一要跑的指令。`drift.py`、`coverage.tsv`:程式碼有沒有改過。
- `src/app/remote_ui.rs` 最後的 `approval_routing_replay`:在真的程式上重走(只有測試,不改行為)。 - 測試(只有測試,不改行為):`src/app/remote_ui.rs` 的 `approval_routing_replay`、`phone_act_tests::a_banner_answers_only_its_own_request`、`phone_act_tests::a_phone_answer_without_its_cards_key_answers_nothing`、`phone_act_tests::a_branch_card_on_the_phone_carries_its_own_key_and_target`、`phone_act_tests::the_answer_after_direct_mode_let_its_card_through_says_nothing`;`src/app/mirror_ui.rs` 的 `tests::a_screen_answers_only_the_card_it_shows`、`tests::a_screen_keeps_its_cards_key_in_step_with_the_brains`;`src/app.rs` 的 `tests::a_question_in_anothers_place_starts_with_nothing_picked`;`src/app/remote_ui.rs` 的 `phone_act_tests::a_card_in_anothers_place_is_published_again`。

View File

@ -3,16 +3,24 @@
desk.approval_body src/app.rs block ^ fn approval_body\( } fd8c84806d8b8867c011f463c3753f1960824a5df46535031ba1c0aaa5263d07 desk.approval_body src/app.rs block ^ fn approval_body\( } fd8c84806d8b8867c011f463c3753f1960824a5df46535031ba1c0aaa5263d07
desk.approval_dock src/app.rs block ^ fn approval_dock\( } cda918bb255c4533d2d116736aaeb10aa2b9477b6c2858f1698b81b6dcef8794 desk.approval_dock src/app.rs block ^ fn approval_dock\( } cda918bb255c4533d2d116736aaeb10aa2b9477b6c2858f1698b81b6dcef8794
brain.need_approval src/app.rs block ^ if let StreamEvent::NeedApproval\(a\) = ev \{ } 5d62c439986d0e2ee6d0f28b3cbaf28fca8688c0c60395d86e77a77a35bd55ec brain.need_approval src/app.rs block ^ if let StreamEvent::NeedApproval\(a\) = ev \{ } 5d62c439986d0e2ee6d0f28b3cbaf28fca8688c0c60395d86e77a77a35bd55ec
brain.on_new_approval src/app.rs block ^ fn on_new_approval\( } 64c8f015a02fc27d83d391928cd173e5440ab7c84b942af2969a41834dc35b5c brain.on_new_approval src/app.rs block ^ fn on_new_approval\( } c110c0341ae1b8cbcc59d0b4dc1dba7a2b8006885837e515ea6c0ef23a195205
brain.answer src/app.rs block ^ fn answer\(&mut self, ctx: &egui::Context, bot_id: u64, answer: ApprovalAnswer\) } 920ddafb3d2e905a08c2780f0bab8322b95ee8e292fc186007635d373c9bb48b brain.new_approval_keyed src/app.rs block ^ fn new_approval_keyed\( } cfba6b7d4b08bc0a2d46363f5ff27205cf0c49c3a80f0cf4673c9546ab99f34d
brain.notice_answers src/app.rs block ^fn notice_answers\( } a846a5e243978060ff4810ced82a064820da0966634bb9e730a14e6a5b303400
brain.answer src/app.rs block ^ fn answer\(&mut self, ctx: &egui::Context, bot_id: u64, answer: ApprovalAnswer\) } 192102f8e18c5859f58b3fb89acf5faffcd5339603f7e7ec3ab47aaf94c52cfd
brain.stop src/app.rs block ^ fn stop\(&mut self, bot_id: u64\) } c7b8144a99b5cd03d37dd34ca1745dca693d4f2f0197a51d29dfb71b3e770f4f brain.stop src/app.rs block ^ fn stop\(&mut self, bot_id: u64\) } c7b8144a99b5cd03d37dd34ca1745dca693d4f2f0197a51d29dfb71b3e770f4f
brain.watchdog src/app.rs block ^ fn watchdog\(&mut self\) } 50af66bd5a7f254e4400edb2f0fedc550465a43ac0d9fce155e5353c8d4ae336 brain.watchdog src/app.rs block ^ fn watchdog\(&mut self\) } 50af66bd5a7f254e4400edb2f0fedc550465a43ac0d9fce155e5353c8d4ae336
brain.cmd_answer src/app/remote_ui.rs block ^ Cmd::Answer \{ bot, answer, text, call \} => \{ } 01d9f1eb4e306f0e07a5edc22f474372e18fcd645e99ea572d4e5c916b86a7d9 brain.cmd_answer src/app/remote_ui.rs block ^ Cmd::Answer \{ bot, answer, text, call, notice, screen \} => \{ } 8100f28ea03fedbd4cd58f988c5d32be2761151349110b134dcfb54d61a4e482
page.approval_json src/app/remote_ui.rs block ^fn approval_json\( } 344450dd2ab853a7ff6422c9b2385fda22d7c50f4ff94d5fafff43b947975eac page.approval_json src/app/remote_ui.rs block ^fn approval_json\( } a5170e3eb427a05a10941d43ca7f43355955c4225cb361843d2435051c8a29c1
page.render_dock mobile/index.html block ^function renderDock\(\) \{ } dcd232baf47e82373b818f71b9a9525545d0b1ee70797631612d5434378cf331 page.phone_cards src/app/remote_ui.rs block ^ fn phone_cards\( } 9a76fc7d54e92000598bd6800c232c5b61a4494cd60d33c2313542ce6893058c
page.banner_answer mobile/index.html block ^ if \(S\.answer && S\.token\) \{ } 77366a55d5aaf8443edbac2825c4455d2462e18a2cb9d1ab23484ce748fbe07b page.render_dock mobile/index.html block ^function renderDock\(\) \{ } bfc86600b3b561ba0c32355b5a8b3372bc0f1afbb8482eaa6ccddf92b5ba1e94
page.question mobile/index.html block ^function renderQuestion\(a, force\) \{ } 829ae3088ec69585ecd9cff0d12cf5fd538ccc86869c4e46a6e9d8c4110d3a40
page.banner_answer mobile/index.html block ^ if \(S\.answer && S\.token\) \{ } 04f38fec448257ad65387689db94759688822087e9d4b1635d37f431b9e0ff0a
page.open_from_hash mobile/index.html block ^function openFromHash\(\) \{ } 5306ec26de8b8e458d92129b94dfa576b10df210ae5266c725567324e3a43a9c
page.banner_message mobile/index.html block ^if \("serviceWorker" in navigator\) navigator\.serviceWorker\.addEventListener\("message" }); 69c873dddd0316fe2dda023bf32d815dbc1238f5a7f810011d678272cd19b70d
banner.notificationclick mobile/sw.js block ^self\.addEventListener\("notificationclick" }); e6d98794998fa048ef0179a4893291d4c1bb67a34a7d25b7cbdff3f022ce4bc3 banner.notificationclick mobile/sw.js block ^self\.addEventListener\("notificationclick" }); e6d98794998fa048ef0179a4893291d4c1bb67a34a7d25b7cbdff3f022ce4bc3
remote.answer_routes src/remote.rs grep => Cmd::Answer \{ - c3bfd841a0a304186b2a19701b56114d021956bd3b27e79310a26f40be6a59ca remote.answer_routes src/remote.rs grep => Cmd::Answer \{ - 02c54c27a1e19ef9e185dba4ee11f3881ec24c9408f24696a8422ab46d5881a1
screen.sync src/app/mirror_ui.rs until ^ let mut waiting = HashMap::new\(\); self\.approvals\.retain\(\|id, _\| keep\.contains\(id\)\); b40f54c3e33188e3b5b1a02d11c177641f1b358eb7e4b192f799d2381f49fa55 screen.view src/app/mirror_ui.rs until ^ out\["approvals"\] = self \.collect\(\); 5ff7997d09ce6b9b30ea393be31d5af104762c1dcb2a176e68e178ea062cb4e7
screen.sync src/app/mirror_ui.rs until ^ let mut waiting = HashMap::new\(\); self\.mir\.keys\.retain\( 96ab946e8136f472eed78462dfe2c77dcf3ca4fb5105d40abd2cb6e476cf317d
bot.wait_answer src/agent.rs block ^fn wait_answer\( } bea92a9095394ff0ccab0b7e120a19e2cfec4921655d1709018354c7eadc9eaa bot.wait_answer src/agent.rs block ^fn wait_answer\( } bea92a9095394ff0ccab0b7e120a19e2cfec4921655d1709018354c7eadc9eaa
bot.ask_person src/agent/steps.rs block ^ pub fn ask_person\( } 564d1660a7a3655a7ad995b8a3b578235fc3ea21a40ad7e45e454e352e2af7c5 bot.ask_person src/agent/steps.rs block ^ pub fn ask_person\( } 564d1660a7a3655a7ad995b8a3b578235fc3ea21a40ad7e45e454e352e2af7c5
desk.question_card src/app.rs block ^ fn question_card\( } c69b3056f46a67d6debd11f82a6ec246da2d78098ca31dbd241c4d0e974a3c14

Can't render this file because it has a wrong number of fields in line 2.

View File

@ -1,16 +1,19 @@
\* 四個地方都能回答,照現在的程式碼。已知發現 F1:手機頁面和螢幕電腦的回答不帶 call, \* 四個地方都能回答,照現在的程式碼(F1 修好之後):每個回答都帶那張卡的 key,大腦只交給那張卡;
\* 會落在後來的卡上。修好之前這個 cfg 會違反規則;run.sh 只確認違反的是 F1 那一種。 \* 更新前就開著的舊手機頁面、舊版螢幕電腦不帶 key,大腦不收。要通過。
SPECIFICATION Spec SPECIFICATION Spec
CONSTANTS CONSTANTS
N = 3 N = 3
Surfaces = {"desk", "page", "banner", "screen"} Surfaces = {"desk", "page", "banner", "screen"}
FreshKeyPerCard = TRUE FreshKeyPerCard = TRUE
BannerKeyChecked = TRUE KeyChecked = TRUE
PageSendsKey = FALSE KeylessRefused = TRUE
ScreenSendsKey = FALSE NoticeFitsChecked = TRUE
PageSendsKey = TRUE
ScreenSendsKey = TRUE
INVARIANTS INVARIANTS
TypeOK TypeOK
AllowOnlyWhatWasSeen AllowOnlyWhatWasSeen
RuleOnlyWhatWasSeen RuleOnlyWhatWasSeen
NoticeNeverFinishesHandoff
CONSTRAINT CONSTRAINT
OneAnswerOnTheWayPerSurface OneAnswerOnTheWayPerSurface

View File

@ -1,16 +0,0 @@
\* 四個地方都能回答,假設手機頁面和螢幕電腦也帶上那張卡的 key(F1 的修法,程式裡還沒有)。
\* 要通過:除了 F1,其他地方沒有別的破口。
SPECIFICATION Spec
CONSTANTS
N = 3
Surfaces = {"desk", "page", "banner", "screen"}
FreshKeyPerCard = TRUE
BannerKeyChecked = TRUE
PageSendsKey = TRUE
ScreenSendsKey = TRUE
INVARIANTS
TypeOK
AllowOnlyWhatWasSeen
RuleOnlyWhatWasSeen
CONSTRAINT
OneAnswerOnTheWayPerSurface

View File

@ -7,18 +7,24 @@
(* 大腦(app.rs 的 App)把卡放在 approvals[bot],每張新卡在 on_new_approval *) (* 大腦(app.rs 的 App)把卡放在 approvals[bot],每張新卡在 on_new_approval *)
(* 發一把 ask_keys[bot]。能回答的地方有四個: *) (* 發一把 ask_keys[bot]。能回答的地方有四個: *)
(* desk 大腦自己的視窗(approval_dock/approval_body → answer()) *) (* desk 大腦自己的視窗(approval_dock/approval_body → answer()) *)
(* page 手機頁面上的卡(mobile/index.html renderDock) *) (* page 手機頁面上的卡(mobile/index.html renderDock、renderQuestion) *)
(* banner 手機通知上的「允許/拒絕」(mobile/sw.js,帶 d.ask = key) *) (* banner 手機通知上的「允許/拒絕」(mobile/sw.js,帶 d.ask = key) *)
(* screen 螢幕電腦(mirror:answer() 的 mir.on 分支) *) (* screen 螢幕電腦(mirror:answer() 的 mir.on 分支) *)
(* desk 在同一個畫面格裡看到卡、處理按鍵、呼叫 answer();另外三個看到的是 *) (* desk 在同一個畫面格裡看到卡、處理按鍵、呼叫 answer();另外三個看到的是 *)
(* 某個時候抄過去的卡,回答要經過網路,到大腦時才由 remote_ui.rs 的 *) (* 某個時候抄過去的卡(和它的 key),回答要經過網路,到大腦時由 *)
(* Cmd::Answer 交給「那時候」在等的卡。 *) (* remote_ui.rs 的 Cmd::Answer 決定收不收。手機頁面可能是更新前就開著的舊 *)
(* 頁面、螢幕電腦可能是舊版:它們的回答不帶 key。 *)
(* *)
(* 卡有兩種:「允許這個操作」(allow:Action、要開電腦工具…)和「需要處理」*)
(* (handoff:按鈕是「我完成了/跳過」,送出去也是 once/reject)。 *)
(* *) (* *)
(* 規則(cfg 的 INVARIANT): *) (* 規則(cfg 的 INVARIANT): *)
(* AllowOnlyWhatWasSeen 「允許」「一律允許」只會讓按的人當時看到的那張 *) (* AllowOnlyWhatWasSeen 「允許」「一律允許」(在需要處理的卡上是「我完成 *)
(* 卡通過。 *) (* 了」)只會讓按的人當時看到的那張卡通過。 *)
(* RuleOnlyWhatWasSeen 「一律允許」記到 Bot 身上的類別,一定是按的人當 *) (* RuleOnlyWhatWasSeen 「一律允許」記到 Bot 身上的類別,一定是按的人當 *)
(* 時看到的那張卡上寫的。 *) (* 時看到的那張卡上寫的。 *)
(* NoticeNeverFinishesHandoff 手機通知上的按鈕只回答「允許這個操作」的 *)
(* 卡,絕不會變成「我完成了」。 *)
(* *) (* *)
(* 每個動作對應哪段程式碼:.claude/skills/verify-approval-routing/SKILL.md *) (* 每個動作對應哪段程式碼:.claude/skills/verify-approval-routing/SKILL.md *)
(* 的「對照表」。程式碼一改,先照那張表重新對過,再相信這裡的結果。 *) (* 的「對照表」。程式碼一改,先照那張表重新對過,再相信這裡的結果。 *)
@ -26,22 +32,29 @@
EXTENDS Naturals, FiniteSets EXTENDS Naturals, FiniteSets
CONSTANTS CONSTANTS
N, \* 這段時間 Bot 會問幾次(請求 1..N,一個問完才問下一個) N, \* 這段時間 Bot 會問幾次(請求 1..N,一個問完才問下一個)
Surfaces, \* 有哪些地方能回答:{"desk", "page", "banner", "screen"} 的子集 Surfaces, \* 有哪些地方能回答:{"desk", "page", "banner", "screen"} 的子集
\* 程式事實:每一條都對應程式裡的一行,見 SKILL.md「程式事實」。 \* 程式事實:每一條都對應程式裡的一行,見 SKILL.md「程式事實」。
FreshKeyPerCard, \* on_new_approval:每張新卡一把新的 ask_keys(random_hex) FreshKeyPerCard, \* on_new_approval:每張新卡一把新的 ask_keys(random_hex)
BannerKeyChecked, \* Cmd::Answer:帶 call 的回答,call 要等於現在的 ask_keys 才算 KeyChecked, \* Cmd::Answer:帶 key 的回答,key 要是現在在等的那張卡的才算
PageSendsKey, \* renderDock 的按鈕:POST 的 JSON 裡有 call KeylessRefused, \* Cmd::Answer:沒帶 key 的回答(舊頁面、舊版螢幕電腦)不算
ScreenSendsKey \* answer() 的 mir.on 分支:mirror_act 的 JSON 裡有 call NoticeFitsChecked, \* Cmd::Answer:通知上的回答只收 notice_answers 的卡、只收 once/reject
PageSendsKey, \* 手機頁面(renderDock、renderQuestion)送出 call = 那張卡的 key
ScreenSendsKey \* 螢幕電腦 answer()(mir.on)送出 call = 大腦給那張卡的 key
None == 0 \* 沒有卡/沒有 key None == 0 \* 沒有卡/沒有 key
NoView == <<None, None>> \* 畫面上沒有卡;有卡時是 <<請求, 那張卡的 key>> NoView == <<None, None>> \* 畫面上沒有卡;有卡時是 <<請求, 那張卡的 key>>
Grant(r) == r \* 每個請求的「一律允許」類別都不一樣(npm install、修改檔案…) Grant(r) == r \* 每個請求的「一律允許」類別都不一樣(npm install、修改檔案…)
Allow == {"once", "always"} \* 「允許」和「一律允許」;"reject" 是「拒絕」 Kind(r) == IF r = N THEN "handoff" ELSE "allow" \* 最後一件是「需要處理」,其他是允許請求
Allow == {"once", "always"} \* 「允許」「一律允許」(需要處理的卡上 once 是「我完成了」)
DeskButtons == {"once", "always", "reject"} \* approval_body:允許/一律允許/拒絕 \* 卡上的按鈕(大腦視窗 approval_body/handoff_card、手機 renderDock、螢幕電腦一樣):
PageButtons == {"once", "always", "reject"} \* renderDock:允許一次/一律允許/拒絕 Buttons(r) == IF Kind(r) = "handoff" THEN {"once", "reject"} ELSE {"once", "always", "reject"}
BannerButtons == {"once", "reject"} \* sw.js:allow → once、deny → reject BannerButtons == {"once", "reject"} \* sw.js:allow → once、deny → reject
\* 手機頁面送出的 key:現在的頁面送那張卡的;更新前就開著的舊頁面什麼都不送。
PageKeys(v) == IF PageSendsKey THEN {v[2], None} ELSE {None}
\* 螢幕電腦送出的 key:現在的版本送大腦給的;舊版什麼都不送。
ScreenKeys(v) == IF ScreenSendsKey THEN {v[2], None} ELSE {None}
VARIABLES VARIABLES
bot, \* Bot 那一邊:"thinking" 下一步還沒問、"sent" NeedApproval 在路上、 bot, \* Bot 那一邊:"thinking" 下一步還沒問、"sent" NeedApproval 在路上、
@ -50,17 +63,21 @@ VARIABLES
card, \* 大腦的 approvals[bot]:正在等的請求,None 表示沒有 card, \* 大腦的 approvals[bot]:正在等的請求,None 表示沒有
askKey, \* 大腦的 ask_keys[bot](卡被回答後不清掉) askKey, \* 大腦的 ask_keys[bot](卡被回答後不清掉)
keys, \* 發過幾把 key(新 key 就是下一個號碼) keys, \* 發過幾把 key(新 key 就是下一個號碼)
page, \* 手機頁面上畫的卡(S.approvals) page, \* 手機頁面上畫的卡(S.approvals,含 key)
screen, \* 螢幕電腦上畫的卡(它自己的 approvals,從大腦同步來) screen, \* 螢幕電腦上畫的卡(它的 approvals 和 mir.keys,從大腦同步來)
banner, \* 手機通知上的卡(同一個 Bot 新的通知蓋掉舊的:tag "bot-<id>") banner, \* 手機通知上的卡(同一個 Bot 新的通知蓋掉舊的:tag "bot-<id>")
inflight, \* 已經送出、大腦還沒處理的回答 inflight, \* 已經送出、大腦還沒處理的回答
allowed, \* 記錄:<<讓哪個請求通過, 按的人看到的請求>> \* 記錄(程式裡沒有這些值,只拿來檢查規則;規則成立時一直是 FALSE,不讓狀態變多):
rules \* 記錄:<<一律允許記下的類別, 按的人看到的請求>> wrongAllow, \* 有沒有一個「允許」「一律允許」「我完成了」交給了按的人沒看到的卡
wrongRule, \* 有沒有一個「一律允許」記下了按的人沒看到的那一類
noticeOnHandoff, \* 有沒有手機通知上的按鈕回答了「需要處理」的卡
landedFrom \* 哪些地方(page/banner/screen)的回答真的交給過一張卡
vars == <<bot, asked, card, askKey, keys, page, screen, banner, inflight, allowed, rules>> vars == <<bot, asked, card, askKey, keys, page, screen, banner, inflight, wrongAllow, wrongRule, noticeOnHandoff, landedFrom>>
Views == (0..N) \X (0..N) Views == (0..N) \X (0..N)
Msg == [from: {"page", "banner", "screen"}, ans: PageButtons, key: 0..N, seen: 1..N] Answers == {"once", "always", "reject"}
Msg == [from: {"page", "banner", "screen"}, ans: Answers, key: 0..N, seen: 1..N, notice: BOOLEAN]
TypeOK == TypeOK ==
/\ bot \in {"thinking", "sent", "waiting", "done"} /\ bot \in {"thinking", "sent", "waiting", "done"}
@ -70,8 +87,8 @@ TypeOK ==
/\ keys \in 0..N /\ keys \in 0..N
/\ page \in Views /\ screen \in Views /\ banner \in Views /\ page \in Views /\ screen \in Views /\ banner \in Views
/\ inflight \subseteq Msg /\ inflight \subseteq Msg
/\ allowed \subseteq (1..N) \X (1..N) /\ wrongAllow \in BOOLEAN /\ wrongRule \in BOOLEAN /\ noticeOnHandoff \in BOOLEAN
/\ rules \subseteq (1..N) \X (1..N) /\ landedFrom \subseteq {"page", "banner", "screen"}
Init == Init ==
/\ bot = "thinking" /\ bot = "thinking"
@ -83,16 +100,20 @@ Init ==
/\ screen = NoView /\ screen = NoView
/\ banner = NoView /\ banner = NoView
/\ inflight = {} /\ inflight = {}
/\ allowed = {} /\ wrongAllow = FALSE
/\ rules = {} /\ wrongRule = FALSE
/\ noticeOnHandoff = FALSE
/\ landedFrom = {}
(* 大腦把回答交給「現在在等的那張卡」:app.rs answer() — *) (* 大腦把回答交給「現在在等的那張卡」:app.rs answer() — *)
(* approvals.remove(&bot_id);Always 就把 g 推進 b.allow_rules; *) (* approvals.remove(&bot_id);Always 而且是 Action 就把 g 推進 *)
(* a.reply.send(answer)。Bot 的 wait_answer 收到後往下做。 *) (* b.allow_rules;a.reply.send(answer)。Bot 的 wait_answer 收到後往下做。 *)
(* `seen` 是按的人當時看到的請求:只拿來寫記錄,程式裡沒有這個值。 *) (* `seen`(按的人看到的請求)、`from`("desk" 是大腦自己的視窗)只拿來寫記錄。*)
Settle(ans, seen) == Settle(ans, seen, from) ==
/\ allowed' = IF ans \in Allow THEN allowed \cup {<<card, seen>>} ELSE allowed /\ wrongAllow' = (wrongAllow \/ (ans \in Allow /\ card # seen))
/\ rules' = IF ans = "always" THEN rules \cup {<<Grant(card), seen>>} ELSE rules /\ wrongRule' = (wrongRule \/ (ans = "always" /\ Kind(card) = "allow" /\ Grant(card) # Grant(seen)))
/\ noticeOnHandoff' = (noticeOnHandoff \/ (from = "banner" /\ Kind(card) = "handoff"))
/\ landedFrom' = IF from = "desk" THEN landedFrom ELSE landedFrom \cup {from}
/\ card' = None /\ card' = None
/\ bot' = IF asked = N THEN "done" ELSE "thinking" /\ bot' = IF asked = N THEN "done" ELSE "thinking"
@ -103,11 +124,12 @@ BotAsks ==
/\ asked < N /\ asked < N
/\ asked' = asked + 1 /\ asked' = asked + 1
/\ bot' = "sent" /\ bot' = "sent"
/\ UNCHANGED <<card, askKey, keys, page, screen, banner, inflight, allowed, rules>> /\ UNCHANGED <<card, askKey, keys, page, screen, banner, inflight, wrongAllow, wrongRule, noticeOnHandoff, landedFrom>>
(* 大腦的 drain_events 拿到 NeedApproval:approvals.insert(id, a),接著 *) (* 大腦的 drain_events 拿到 NeedApproval:approvals.insert(id, a),接著 *)
(* on_new_approval:ask_keys.insert(bot_id, 新 key);不在 App 前面時推一則 *) (* on_new_approval → new_approval_keyed:ask_keys.insert(bot_id, 新 key); *)
(* 手機通知(remote::notify_approval,帶這把 key)。 *) (* 不在 App 前面時推一則手機通知——notice_answers 的卡(允許請求)才帶 *)
(* 這把 key 和「允許/拒絕」,其他的只是「打開聊天」。 *)
CardShows == CardShows ==
/\ bot = "sent" /\ bot = "sent"
/\ bot' = "waiting" /\ bot' = "waiting"
@ -116,8 +138,8 @@ CardShows ==
THEN /\ keys' = keys + 1 THEN /\ keys' = keys + 1
/\ askKey' = keys + 1 /\ askKey' = keys + 1
ELSE UNCHANGED <<keys, askKey>> ELSE UNCHANGED <<keys, askKey>>
/\ banner' \in IF "banner" \in Surfaces THEN {banner, <<asked, askKey'>>} ELSE {banner} /\ banner' \in IF "banner" \in Surfaces /\ Kind(asked) = "allow" THEN {banner, <<asked, askKey'>>} ELSE {banner}
/\ UNCHANGED <<asked, page, screen, inflight, allowed, rules>> /\ UNCHANGED <<asked, page, screen, inflight, wrongAllow, wrongRule, noticeOnHandoff, landedFrom>>
(* 卡沒被回答就不見了:按停止、重新啟動 Bot、沒人在旁邊等超過 15 分鐘 *) (* 卡沒被回答就不見了:按停止、重新啟動 Bot、沒人在旁邊等超過 15 分鐘 *)
(* (watchdog)。approvals.remove 丟掉 reply,wait_answer 拿到 Err → Reject;*) (* (watchdog)。approvals.remove 丟掉 reply,wait_answer 拿到 Err → Reject;*)
@ -127,75 +149,77 @@ TurnStops ==
/\ bot \in {"sent", "waiting"} /\ bot \in {"sent", "waiting"}
/\ card' = None /\ card' = None
/\ bot' = IF asked = N THEN "done" ELSE "thinking" /\ bot' = IF asked = N THEN "done" ELSE "thinking"
/\ UNCHANGED <<asked, askKey, keys, page, screen, banner, inflight, allowed, rules>> /\ UNCHANGED <<asked, askKey, keys, page, screen, banner, inflight, wrongAllow, wrongRule, noticeOnHandoff, landedFrom>>
(* 大腦自己的視窗:approval_dock 畫出這張卡(approval_body),同一格裡的 *) (* 大腦自己的視窗:approval_dock 畫出這張卡(approval_body,需要處理的是 *)
(* 按鈕或 Enter/Esc 直接呼叫 answer()。看到的就是現在的卡。 *) (* handoff_card),同一格裡的按鈕或 Enter/Esc 直接呼叫 answer()。看到的就是 *)
(* 現在的卡。 *)
YouAnswerOnDesk == YouAnswerOnDesk ==
/\ "desk" \in Surfaces /\ "desk" \in Surfaces
/\ card # None /\ card # None
/\ \E ans \in DeskButtons : Settle(ans, card) /\ \E ans \in Buttons(card) : Settle(ans, card, "desk")
/\ UNCHANGED <<asked, askKey, keys, page, screen, banner, inflight>> /\ UNCHANGED <<asked, askKey, keys, page, screen, banner, inflight>>
(* 手機頁面的長輪詢 api/state 帶回 approvals(approval_json),apply() *) (* 手機頁面的長輪詢 api/state 帶回 approvals(approval_json,含這張卡的 *)
(* → renderDock 重畫。 *) (* key),apply() → renderDock 重畫。 *)
PageRefreshes == PageRefreshes ==
/\ "page" \in Surfaces /\ "page" \in Surfaces
/\ page' = IF card = None THEN NoView ELSE <<card, askKey>> /\ page' = IF card = None THEN NoView ELSE <<card, askKey>>
/\ UNCHANGED <<bot, asked, card, askKey, keys, screen, banner, inflight, allowed, rules>> /\ UNCHANGED <<bot, asked, card, askKey, keys, screen, banner, inflight, wrongAllow, wrongRule, noticeOnHandoff, landedFrom>>
(* 手機頁面上按卡片的按鈕:$("ask").innerHTML = ""; *) (* 手機頁面上按卡片的按鈕(允許/一律允許/拒絕、我完成了/跳過、問題卡的 *)
(* POST api/bots/{id}/answer {answer}(remote.rs 把沒有的 call 當成 "")。 *) (* 送出/略過、「全部允許,之後直接操作」):清掉手機上的卡,POST *)
(* api/bots/{id}/answer {answer, call: a.key};舊頁面不帶 call。 *)
YouTapOnPage == YouTapOnPage ==
/\ "page" \in Surfaces /\ "page" \in Surfaces
/\ page # NoView /\ page # NoView
/\ \E ans \in PageButtons : /\ \E ans \in Buttons(page[1]), k \in PageKeys(page) :
inflight' = inflight \cup {[from |-> "page", ans |-> ans, inflight' = inflight \cup {[from |-> "page", ans |-> ans, key |-> k, seen |-> page[1], notice |-> FALSE]}
key |-> IF PageSendsKey THEN page[2] ELSE None,
seen |-> page[1]]}
/\ page' = NoView /\ page' = NoView
/\ UNCHANGED <<bot, asked, card, askKey, keys, screen, banner, allowed, rules>> /\ UNCHANGED <<bot, asked, card, askKey, keys, screen, banner, wrongAllow, wrongRule, noticeOnHandoff, landedFrom>>
(* 手機通知上按「允許」或「拒絕」:sw.js notificationclick 關掉通知, *) (* 手機通知上按「允許」或「拒絕」:sw.js notificationclick 關掉通知, *)
(* 打開頁面帶 answer 和 call = d.ask,apply() POST 出去。 *) (* 頁面 POST {answer, call: d.ask, from: "notice"}。 *)
YouTapBanner == YouTapBanner ==
/\ banner # NoView /\ banner # NoView
/\ \E ans \in BannerButtons : /\ \E ans \in BannerButtons :
inflight' = inflight \cup {[from |-> "banner", ans |-> ans, key |-> banner[2], seen |-> banner[1]]} inflight' = inflight \cup {[from |-> "banner", ans |-> ans, key |-> banner[2], seen |-> banner[1], notice |-> TRUE]}
/\ banner' = NoView /\ banner' = NoView
/\ UNCHANGED <<bot, asked, card, askKey, keys, page, screen, allowed, rules>> /\ UNCHANGED <<bot, asked, card, askKey, keys, page, screen, wrongAllow, wrongRule, noticeOnHandoff, landedFrom>>
(* 螢幕電腦從大腦同步:mirror_ui.rs 把大腦的 approvals 換進來。 *) (* 螢幕電腦從大腦同步:mirror_ui.rs 把大腦的 approvals 換進來, *)
(* 每張卡的 key 記在 mir.keys。 *)
ScreenRefreshes == ScreenRefreshes ==
/\ "screen" \in Surfaces /\ "screen" \in Surfaces
/\ screen' = IF card = None THEN NoView ELSE <<card, askKey>> /\ screen' = IF card = None THEN NoView ELSE <<card, askKey>>
/\ UNCHANGED <<bot, asked, card, askKey, keys, page, banner, inflight, allowed, rules>> /\ UNCHANGED <<bot, asked, card, askKey, keys, page, banner, inflight, wrongAllow, wrongRule, noticeOnHandoff, landedFrom>>
(* 螢幕電腦上回答:answer() 的 mir.on 分支 approvals.remove, *) (* 螢幕電腦上回答:answer() 的 mir.on 分支 approvals.remove, *)
(* mirror_act {"bot", "action": "answer", "answer", "text"} 送到大腦的 *) (* mirror_act {"bot", "action": "answer", "answer", "text", "call"} 送到 *)
(* api/sync/act。 *) (* 大腦的 api/sync/act;舊版螢幕電腦不帶 call。 *)
YouAnswerOnScreen == YouAnswerOnScreen ==
/\ "screen" \in Surfaces /\ "screen" \in Surfaces
/\ screen # NoView /\ screen # NoView
/\ \E ans \in DeskButtons : /\ \E ans \in Buttons(screen[1]), k \in ScreenKeys(screen) :
inflight' = inflight \cup {[from |-> "screen", ans |-> ans, inflight' = inflight \cup {[from |-> "screen", ans |-> ans, key |-> k, seen |-> screen[1], notice |-> FALSE]}
key |-> IF ScreenSendsKey THEN screen[2] ELSE None,
seen |-> screen[1]]}
/\ screen' = NoView /\ screen' = NoView
/\ UNCHANGED <<bot, asked, card, askKey, keys, page, banner, allowed, rules>> /\ UNCHANGED <<bot, asked, card, askKey, keys, page, banner, wrongAllow, wrongRule, noticeOnHandoff, landedFrom>>
(* 大腦處理一個遠端回答:remote_ui.rs Cmd::Answer。 *)
(* this_card:有卡在等、帶了 key、key 是現在 ask_keys 的那把。 *)
(* fits:不是通知,或是 notice_answers 的卡而且是 once/reject。 *)
(* 兩個都成立才交給 answer();不然什麼都不做(有卡在等時寫「沒有用上」)。 *)
ThisCard(m) ==
/\ card # None
/\ IF m.key = None THEN ~KeylessRefused ELSE (~KeyChecked \/ askKey = m.key)
Fits(m) == ~m.notice \/ ~NoticeFitsChecked \/ (Kind(card) = "allow" /\ m.ans \in BannerButtons)
(* 大腦處理一個遠端回答:remote_ui.rs Cmd::Answer。帶了 call 卻不是現在 *)
(* 這張卡的 key(或卡已經不在)→ 寫「沒有用上」、什麼都不做; *)
(* 沒帶 call → 照舊交給 answer(),answer() 找現在的卡; *)
(* 「一律允許」的 grant 也是讀現在這張卡的。 *)
BrainTakesAnswer == BrainTakesAnswer ==
/\ \E m \in inflight : /\ \E m \in inflight :
/\ inflight' = inflight \ {m} /\ inflight' = inflight \ {m}
/\ IF m.key # None /\ BannerKeyChecked /\ ~(card # None /\ askKey = m.key) /\ IF ThisCard(m) /\ Fits(m)
THEN UNCHANGED <<bot, card, allowed, rules>> THEN Settle(m.ans, m.seen, m.from)
ELSE IF card = None ELSE UNCHANGED <<bot, card, wrongAllow, wrongRule, noticeOnHandoff, landedFrom>>
THEN UNCHANGED <<bot, card, allowed, rules>>
ELSE Settle(m.ans, m.seen)
/\ UNCHANGED <<asked, askKey, keys, page, screen, banner>> /\ UNCHANGED <<asked, askKey, keys, page, screen, banner>>
(* 不再問了,什麼都不變(讓 TLC 不把結束當成卡死)。 *) (* 不再問了,什麼都不變(讓 TLC 不把結束當成卡死)。 *)
@ -223,10 +247,18 @@ Spec == Init /\ [][Next]_vars
OneAnswerOnTheWayPerSurface == OneAnswerOnTheWayPerSurface ==
\A s \in {"page", "banner", "screen"} : Cardinality({m \in inflight : m.from = s}) <= 1 \A s \in {"page", "banner", "screen"} : Cardinality({m \in inflight : m.from = s}) <= 1
(* 「允許」「一律允許」只會讓按的人當時看到的那張卡通過。 *) (* 「允許」「一律允許」(「我完成了」)只會讓按的人當時看到的那張卡通過。 *)
AllowOnlyWhatWasSeen == \A p \in allowed : p[1] = p[2] AllowOnlyWhatWasSeen == ~wrongAllow
(* 「一律允許」記下的類別,一定是按的人當時看到的那張卡上寫的。 *) (* 「一律允許」記下的類別,一定是按的人當時看到的那張卡上寫的。 *)
RuleOnlyWhatWasSeen == \A p \in rules : p[1] = Grant(p[2]) RuleOnlyWhatWasSeen == ~wrongRule
(* 手機通知上的按鈕只回答允許請求,絕不會變成需要處理的「我完成了/跳過」。*)
NoticeNeverFinishesHandoff == ~noticeOnHandoff
(* 檢查修法沒有把路堵死(CanAnswer.cfg,要「違反」):有一種走法,手機頁面、 *)
(* 手機通知、螢幕電腦的回答都各自真的交給了一張卡。哪天某個地方再也答不了 *)
(* (例如手機不送 key),這一條會「通過」,run.sh 會說不預期。 *)
SomePlaceCannotAnswer == ~({"page", "banner", "screen"} \subseteq landedFrom)
============================================================================= =============================================================================

View File

@ -0,0 +1,16 @@
\* 檢查修法沒有把路堵死:要「違反」SomePlaceCannotAnswer——TLC 找得到一種走法,手機頁面、
\* 手機通知、螢幕電腦的回答都各自真的交給了一張卡。照現在的程式碼。
SPECIFICATION Spec
CONSTANTS
N = 3
Surfaces = {"desk", "page", "banner", "screen"}
FreshKeyPerCard = TRUE
KeyChecked = TRUE
KeylessRefused = TRUE
NoticeFitsChecked = TRUE
PageSendsKey = TRUE
ScreenSendsKey = TRUE
INVARIANTS
SomePlaceCannotAnswer
CONSTRAINT
OneAnswerOnTheWayPerSurface

View File

@ -1,15 +0,0 @@
\* 大腦自己的視窗+手機通知:今天會分辨「是哪一張卡」的兩條路。照現在的程式碼,要通過。
SPECIFICATION Spec
CONSTANTS
N = 3
Surfaces = {"desk", "banner"}
FreshKeyPerCard = TRUE
BannerKeyChecked = TRUE
PageSendsKey = FALSE
ScreenSendsKey = FALSE
INVARIANTS
TypeOK
AllowOnlyWhatWasSeen
RuleOnlyWhatWasSeen
CONSTRAINT
OneAnswerOnTheWayPerSurface

View File

@ -1,14 +1,14 @@
// /pstack:statechart 讀 ApprovalRouting 的結果時用的白話標籤(照 pstack 0.15.43 的 view 格式寫; // /pstack:statechart 讀 ApprovalRouting 的結果時用的白話標籤(照 pstack 0.15.43 的 view 格式寫;
// /pstack:statechart 現在的說明不一樣時,照它的說明改這個檔)。 // /pstack:statechart 現在的說明不一樣時,照它的說明改這個檔)。
type Pair = { 1: number; 2: number }; type Pair = { 1: number; 2: number };
type Msg = { from: string; ans: string; key: number; seen: number }; type Msg = { from: string; ans: string; key: number; seen: number; notice: boolean };
type V = { bot: string; card: number; page: Pair; screen: Pair; banner: Pair; inflight: Msg[]; allowed: Pair[]; rules: Pair[] }; type V = { bot: string; card: number; page: Pair; screen: Pair; banner: Pair; inflight: Msg[]; wrongAllow: boolean; wrongRule: boolean; noticeOnHandoff: boolean };
export const title = "等你允許的卡片:回答落在哪一張"; export const title = "等你允許的卡片:回答落在哪一張";
export const state = (v: V) => { export const state = (v: V) => {
const wrong = v.allowed.some((p) => p[1] !== p[2]); const wrong = v.wrongAllow || v.wrongRule ? "讓沒看到的卡通過了" : v.noticeOnHandoff ? "通知的按鈕回答了需要處理的卡" : "";
const brain = wrong ? "讓沒看到的卡通過了" : v.card !== 0 ? "有一張卡在等" : v.bot === "sent" ? "新的請求在路上" : "沒有卡在等"; const brain = wrong || (v.card !== 0 ? "有一張卡在等" : v.bot === "sent" ? "新的請求在路上" : "沒有卡在等");
const drawn = [v.page, v.banner, v.screen].filter((p) => p[1] !== 0); const drawn = [v.page, v.banner, v.screen].filter((p) => p[1] !== 0);
const away = drawn.length === 0 ? "沒有卡" : drawn.some((p) => p[1] !== v.card) ? "有舊的卡" : "是現在這張"; const away = drawn.length === 0 ? "沒有卡" : drawn.some((p) => p[1] !== v.card) ? "有舊的卡" : "是現在這張";
const sent = v.inflight.length === 0 ? "沒有" : v.inflight.some((m) => m.seen !== v.card) ? "給舊卡的回答" : "給現在這張的回答"; const sent = v.inflight.length === 0 ? "沒有" : v.inflight.some((m) => m.seen !== v.card) ? "給舊卡的回答" : "給現在這張的回答";

View File

@ -1,8 +1,8 @@
#!/bin/sh #!/bin/sh
# 驗證「等你允許的卡片」的回答路由(TLA+ 模型+程式碼有沒有改過)。 # 驗證「等你允許的卡片」的回答路由(TLA+ 模型+程式碼有沒有改過)。
# 用法:.claude/skills/verify-approval-routing/run.sh [--replay] # 用法:.claude/skills/verify-approval-routing/run.sh [--replay]
# --replay 另外在真的程式上重走模型的反例(cargo test,第一次要編譯)。 # --replay 另外在真的程式上重走模型的步驟(cargo test,第一次要編譯)。
# 結束碼:0 跟預期一樣;1 結果跟預期不一樣(新的破口,或已知發現不見了); # 結束碼:0 跟預期一樣;1 結果跟預期不一樣(新的破口,或某個地方再也答不了卡);
# 2 工具出錯;3 結果跟預期一樣,但模型對照的程式碼改過了(結果還不能信)。 # 2 工具出錯;3 結果跟預期一樣,但模型對照的程式碼改過了(結果還不能信)。
set -u set -u
here=$(cd "$(dirname "$0")" && pwd) here=$(cd "$(dirname "$0")" && pwd)
@ -15,10 +15,13 @@ TLA_URL="https://github.com/tlaplus/tlaplus/releases/download/v$TLA_VERSION/tla2
tools="${XDG_DATA_HOME:-$HOME/.local/share}/anybot-formal" tools="${XDG_DATA_HOME:-$HOME/.local/share}/anybot-formal"
jar="$tools/tla2tools-$TLA_VERSION.jar" jar="$tools/tla2tools-$TLA_VERSION.jar"
# 每個 cfg 預期的結果:pass 通過;fail 違反規則(AllSurfaces:已知發現 F1,手機頁面、 # 每個 cfg 預期的結果:AllSurfaces 三條規則都要通過;CanAnswer 要「違反」它唯一的那條
# 螢幕電腦的回答不帶 call)。AllSurfacesKeyed 排在 AllSurfaces 前面:它通過,才能說 # (SomePlaceCannotAnswer)——那是 TLC 找到一種走法,手機頁面、手機通知、螢幕電腦的回答
# AllSurfaces 的違反只是 F1。 # 都各自交給了一張卡,證明修法沒有把路堵死。
EXPECT="Guarded:pass AllSurfacesKeyed:pass AllSurfaces:fail" EXPECT="AllSurfaces:pass CanAnswer:fail"
# --replay 跑的測試(每一個都要通過;對照 SKILL.md「讀結果」)。
REPLAY="approval_routing_replay a_banner_answers_only_its_own_request a_phone_answer_without_its_cards_key_answers_nothing a_screen_answers_only_the_card_it_shows a_screen_keeps_its_cards_key_in_step_with_the_brains a_branch_card_on_the_phone_carries_its_own_key_and_target a_card_in_anothers_place_is_published_again a_question_in_anothers_place_starts_with_nothing_picked the_answer_after_direct_mode_let_its_card_through_says_nothing"
say() { printf '%s\n' "$*"; } say() { printf '%s\n' "$*"; }
@ -53,7 +56,7 @@ drift=$?
[ $drift -eq 0 ] && say " 沒有改:模型描述的還是現在這份程式碼。" [ $drift -eq 0 ] && say " 沒有改:模型描述的還是現在這份程式碼。"
unexpected=0 unexpected=0
keyed_ok=0; guarded=; everywhere= everywhere=
for pair in $EXPECT; do for pair in $EXPECT; do
cfg=${pair%%:*}; want=${pair#*:} cfg=${pair%%:*}; want=${pair#*:}
log="$out/$cfg.out" log="$out/$cfg.out"
@ -66,51 +69,36 @@ for pair in $EXPECT; do
else else
say "== ${cfg}:TLC 出錯,看 ${log}"; tail -20 "$log"; exit 2 say "== ${cfg}:TLC 出錯,看 ${log}"; tail -20 "$log"; exit 2
fi fi
[ "$cfg" = AllSurfacesKeyed ] && [ "$result" = pass ] && keyed_ok=1
[ "$cfg" = Guarded ] && guarded=$result
[ "$cfg" = AllSurfaces ] && everywhere=$result [ "$cfg" = AllSurfaces ] && everywhere=$result
if [ "$result" = "$want" ] && { [ "$want" = pass ] || [ $keyed_ok -eq 1 ]; }; then case "$cfg/$result/$want" in
[ "$want" = fail ] && line="${line} ——預期中的已知發現 F1(AllSurfacesKeyed 通過,所以只差在手機頁面、螢幕電腦不帶 call)" CanAnswer/fail/fail) say "== ${cfg}:${line} ——預期中:找得到一種走法,手機頁面、通知、螢幕電腦的回答都交得出去" ;;
say "== ${cfg}:${line}" CanAnswer/pass/fail) unexpected=1; say "== ${cfg}:${line} ——不預期!有個地方(手機頁面、通知或螢幕電腦)的回答再也交不到卡上。照 SKILL.md「讀結果」。" ;;
else */pass/pass) say "== ${cfg}:${line}" ;;
unexpected=1 *) unexpected=1; say "== ${cfg}:${line} ——不預期!這是新的破口,或模型錯了。照 SKILL.md「讀結果」分辨。" ;;
if [ "$want" = pass ]; then esac
say "== ${cfg}:${line} ——不預期!這是新的破口,或模型錯了。照 SKILL.md「讀結果」分辨。"
elif [ "$result" = pass ]; then
say "== ${cfg}:${line} ——不預期:已知發現 F1 不見了。程式修好了就照 SKILL.md「F1 修好之後」更新;不然是模型被改壞了。"
else
say "== ${cfg}:${line} ——AllSurfacesKeyed 沒通過,這個違反不一定只是 F1:先處理 AllSurfacesKeyed。"
fi
fi
if [ "$result" = fail ]; then if [ "$result" = fail ]; then
say " 反例(TLC 的步驟;用 /pstack:statechart 讀成白話):" say " TLC 的步驟(用 /pstack:statechart 讀成白話):"
sed -n 's/^State \([0-9]*\): <\([A-Za-z]*\).*/ \1. \2/p' "$log" sed -n 's/^State \([0-9]*\): <\([A-Za-z]*\).*/ \1. \2/p' "$log"
say " 完整輸出:${log}" say " 完整輸出:${log}"
fi fi
done done
if [ "${1:-}" = "--replay" ]; then if [ "${1:-}" = "--replay" ]; then
say "== 在真的程式上重走(cargo test approval_routing_replay)" say "== 在真的程式上重走(cargo test:${REPLAY})"
(cd "$root" && cargo test --bin anybot approval_routing_replay -- --include-ignored >"$out/replay.out" 2>&1) # shellcheck disable=SC2086
if grep -q "an_old_banner_does_not_allow_the_next_card ... ok" "$out/replay.out"; then banner=pass (cd "$root" && cargo test --bin anybot -- $REPLAY >"$out/replay.out" 2>&1)
elif grep -q "an_old_banner_does_not_allow_the_next_card ... FAILED" "$out/replay.out"; then banner=fail if ! grep -q "^test result:" "$out/replay.out"; then say " cargo test 沒跑出結果,看 ${out}/replay.out"; exit 2; fi
else say " cargo test 沒跑出結果,看 ${out}/replay.out"; exit 2; fi passed=$(grep -c " \.\.\. ok$" "$out/replay.out")
if grep -q "a_phone_card_tapped_after_it_changed_answers_nothing_else ... ok" "$out/replay.out"; then page=pass failed=$(grep " \.\.\. FAILED$" "$out/replay.out" | sed 's/^test //; s/ \.\.\. FAILED$//')
elif grep -q "a_phone_card_tapped_after_it_changed_answers_nothing_else ... FAILED" "$out/replay.out"; then page=fail # 真的程式跟模型要說同一件事:AllSurfaces 通過 ↔ 測試都過;違反 ↔ 有測試沒過。
else say " cargo test 沒跑出結果,看 ${out}/replay.out"; exit 2; fi if [ -z "$failed" ] && [ "$passed" -ge 10 ]; then real=pass; else real=fail; fi
# 真的程式跟模型要說同一件事:通過對通過、違反對失敗。 case "$real/$everywhere" in
case "$banner/$guarded" in pass/pass) say " ${passed} 個都通過:真的程式也是(跟 AllSurfaces 一致)" ;;
pass/pass) say " 舊通知不會讓下一張卡通過:真的程式也是(跟 Guarded 一致)" ;; fail/fail) unexpected=1; say " 真的程式也走得出 AllSurfaces 的反例——是真的 bug。沒過的有:"; printf '%s\n' "$failed" | sed 's/^/ /' ;;
fail/fail) say " 真的程式也走得出 Guarded 的反例:$(grep -m1 '第一張卡的通知讓第二件事通過了' "$out/replay.out" | sed 's/^ *//')——是真的 bug" ;; fail/pass) unexpected=1; say " 真的程式沒過、模型卻說 AllSurfaces 通過:模型漏了東西,或測試壞了。沒過的有:"; printf '%s\n' "$failed" | sed 's/^/ /' ;;
pass/fail) unexpected=1; say " 真的程式走不出 Guarded 的反例:先當成模型錯(照 SKILL.md「讀結果」)" ;; pass/fail) unexpected=1; say " 真的程式走不出 AllSurfaces 的反例:先當成模型錯(照 SKILL.md「讀結果」),或這幾個測試沒走到那條路。" ;;
fail/pass) unexpected=1; say " 真的程式讓舊通知通過了,模型卻說 Guarded 通過:模型漏了東西,看 ${out}/replay.out" ;;
esac
case "$page/$everywhere" in
fail/fail) say " F1 在真的程式上重現:$(grep -m1 '手機上看到的是' "$out/replay.out" | sed 's/^ *//')" ;;
pass/pass) say " 手機頁面舊卡的回答不會落到新卡:真的程式也是(F1 修好了?照 SKILL.md「F1 修好之後」)" ;;
pass/fail) unexpected=1; say " F1 在真的程式上沒有重現,模型卻說 AllSurfaces 違反:先當成模型錯,或 F1 已經修好" ;;
fail/pass) unexpected=1; say " 真的程式讓手機舊卡的回答落到新卡,模型卻說 AllSurfaces 通過:模型漏了東西,看 ${out}/replay.out" ;;
esac esac
[ "$real" = pass ] || say " 看 ${out}/replay.out"
fi fi
if [ $unexpected -ne 0 ]; then exit 1; fi if [ $unexpected -ne 0 ]; then exit 1; fi

View File

@ -2142,6 +2142,7 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開)
- 思考過程和工具步驟可以展開,看得到每步的結果;一輪做完會收起來; - 思考過程和工具步驟可以展開,看得到每步的結果;一輪做完會收起來;
- 訊息下方:複製、重新產生;長按:複製、引用回覆、重新產生、重新送出、表情回應; - 訊息下方:複製、重新產生;長按:複製、引用回覆、重新產生、重新送出、表情回應;
- 允許請求卡片:允許一次、一律允許、拒絕,以及「全部允許,之後直接操作」;Bot 需要你接手時有電腦畫面縮圖; - 允許請求卡片:允許一次、一律允許、拒絕,以及「全部允許,之後直接操作」;Bot 需要你接手時有電腦畫面縮圖;
- 卡片(允許、需要處理、問題卡)只答它畫出來的那一張:回答帶著那張卡的編號,大腦只交給那張卡。那張已經被回答(電腦上、另一支手機上)、被停止、或換成了下一張時,按了不算,聊天裡留一行「手機上的回答沒有用上:那張卡已經不在等了…」;開了很久沒重新整理的舊頁面送不出編號,也不算(「這個頁面太舊…重新整理再回答;還是不行(帳號伺服器還沒更新),就在電腦上回答」)。螢幕電腦上的卡也一樣;比大腦舊的螢幕電腦送不出編號,在它上面按什麼都不算,大腦寫「螢幕電腦上的回答沒有用上:那台電腦的 AnyBot 比這台舊…」,要在那台 設定 › 更新 換新版。支線的卡沒用上時,這一行寫在主線的聊天(支線的卡就顯示在那裡)。「全部允許,之後直接操作」先打開直接操作、直接操作已經放行了那張「可以用電腦嗎」,手機接著送來的回答就不算舊回答、不寫。以前沒帶編號,舊卡上的「允許」「一律允許」會落到後來的那張;
- 輸入:工作中再傳是插話(顯示排隊)、空白時送出鍵變停止、附加照片/檔案(最大 30 MB)、拍照、語音輸入、建議問題; - 輸入:工作中再傳是插話(顯示排隊)、空白時送出鍵變停止、附加照片/檔案(最大 30 MB)、拍照、語音輸入、建議問題;
- 記憶小卡片(擁有者):打字停 300 ms 後出現在輸入框上方,排成一行可以左右滑,和電腦版一樣預先勾好、點一下加入或拿掉; - 記憶小卡片(擁有者):打字停 300 ms 後出現在輸入框上方,排成一行可以左右滑,和電腦版一樣預先勾好、點一下加入或拿掉;
- 你的訊息下面有「帶了 N 條記憶」,點開看是哪幾條; - 你的訊息下面有「帶了 N 條記憶」,點開看是哪幾條;
@ -2310,9 +2311,9 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開)
「不在」的意思是:沒開視窗、視窗不在最前面,或 90 秒沒動作。用 `anybot --serve` 時一律推播。 「不在」的意思是:沒開視窗、視窗不在最前面,或 90 秒沒動作。用 `anybot --serve` 時一律推播。
推播內容只有手機解得開(Web Push 加密),點通知會直接打開那個 Bot 的聊天。 推播內容只有手機解得開(Web Push 加密),點通知會直接打開那個 Bot 的聊天。等你的卡(允許、問你、需要處理)只由大腦推:螢幕電腦推的通知會把手機帶到螢幕電腦,那台不替手機做事也不給手機畫面,按「允許」等於沒按,所以螢幕電腦不推;大腦不在前面時照樣推同一張卡。
- **在通知上直接允許/拒絕**(Android 會顯示按鈕;iPhone 點了打開聊天):只有「要你允許的事」才有按鈕(某個操作、讓 Bot 用電腦工具、在這台電腦上執行);問題卡和「需要處理」沒有,要打開來回答。按「允許」是允許一次。通知帶著那個請求的編號,大腦會確認它還是正在等的那一個:已經回答過、或換成別的請求時,不會被舊通知答到,聊天裡留一行「通知上的「允許/拒絕」沒有用上…」。 - **在通知上直接允許/拒絕**(Android 會顯示按鈕;iPhone 點了打開聊天):只有「要你允許的事」才有按鈕(某個操作、讓 Bot 用電腦工具、在這台電腦上執行);問題卡和「需要處理」沒有,要打開來回答。按「允許」是允許一次。通知帶著那個請求的編號,大腦會確認它還是正在等的那一個:已經回答過、或換成別的請求時,不會被舊通知答到,聊天裡留一行「通知上的「允許/拒絕」沒有用上…」。大腦也記得這是通知送來的:通知上的按鈕只回答「要你允許的事」、只有允許一次或拒絕,不會變成「需要處理」的「我完成了」、問題卡的「略過」或一律允許(放按鈕和收回答用同一條規則)。
- 手機網頁:新訊息從下面滑進來(打開聊天時舊訊息不動;系統設定減少動態時不動);iPhone 鍵盤蓋住畫面時輸入框跟著抬高;送出和按允許時輕震一下(支援的手機)。 - 手機網頁:新訊息從下面滑進來(打開聊天時舊訊息不動;系統設定減少動態時不動);iPhone 鍵盤蓋住畫面時輸入框跟著抬高;送出和按允許時輕震一下(支援的手機)。
- 主畫面圖示長按有兩個捷徑:「主要 Bot 對話」「未讀對話」(第一個未讀的 Bot)。 - 主畫面圖示長按有兩個捷徑:「主要 Bot 對話」「未讀對話」(第一個未讀的 Bot)。

View File

@ -14,7 +14,7 @@
- 附件:「附加檔案」、拖進視窗、⌘V 貼圖。每個檔最多 50 MB,一個文字檔最多讀 20,000 字給模型。 - 附件:「附加檔案」、拖進視窗、⌘V 貼圖。每個檔最多 50 MB,一個文字檔最多讀 20,000 字給模型。
- 長對話:用到「模型可讀長度」的 7 成,先收起舊步驟的長結果,不夠才把舊對話寫成摘要,聊天裡出現「較早的對話已整理成摘要」(「展開摘要」)。 - 長對話:用到「模型可讀長度」的 7 成,先收起舊步驟的長結果,不夠才把舊對話寫成摘要,聊天裡出現「較早的對話已整理成摘要」(「展開摘要」)。
- 卡住偵測:120 秒還沒開始回應,顯示「模型未能及時開始回應。請重試。」;開始後安靜 35 秒,顯示「回應中斷:模型超過 35 秒沒有送出任何內容。」。等你允許、工具在跑時不算。 - 卡住偵測:120 秒還沒開始回應,顯示「模型未能及時開始回應。請重試。」;開始後安靜 35 秒,顯示「回應中斷:模型超過 35 秒沒有送出任何內容。」。等你允許、工具在跑時不算。
- 問題卡:Bot 用 `ask_person` 在聊天最下面(最新一則訊息之後)放一張卡,跟聊天一起上下捲,不會蓋住聊天;卡片出現和換下一題時聊天會自己捲到它,往上捲看完內容再捲回來回答(輸入框上方的臉旁邊寫「等你回答」,按「↓」回到最下面)。一次最多 6 題、每題最多 8 個選項:單選、複選(「可以選好幾個」)或填寫(「輸入回答」)。每題都有「自己回答」的框;按鈕有「下一題」/「送出」「上一題」「略過」。 - 問題卡:Bot 用 `ask_person` 在聊天最下面(最新一則訊息之後)放一張卡,跟聊天一起上下捲,不會蓋住聊天;卡片出現和換下一題時聊天會自己捲到它,往上捲看完內容再捲回來回答(輸入框上方的臉旁邊寫「等你回答」,按「↓」回到最下面)。一次最多 6 題、每題最多 8 個選項:單選、複選(「可以選好幾個」)或填寫(「輸入回答」)。每題都有「自己回答」的框;按鈕有「下一題」/「送出」「上一題」「略過」。換成另一張問題卡(就算編號一樣)就從第一題、什麼都沒選重新開始。
- 生活卡片(`show_card`):航班、地點、天氣、商品、活動,最多顯示 12 列,有網址時多一個「查看來源 ↗」。 - 生活卡片(`show_card`):航班、地點、天氣、商品、活動,最多顯示 12 列,有網址時多一個「查看來源 ↗」。
- 表情:你可以對 Bot 的回答按表情(6 個常用加「更多表情符號」),Bot 下一輪看得到;Bot 用 `react` 在你的訊息上按表情。 - 表情:你可以對 Bot 的回答按表情(6 個常用加「更多表情符號」),Bot 下一輪看得到;Bot 用 `react` 在你的訊息上按表情。
- 重新看圖(`look_image`):較早的圖片在模型那邊只剩一段摘要時,Bot 請看得懂圖的模型,針對一個問題重看其中一張。 - 重新看圖(`look_image`):較早的圖片在模型那邊只剩一段摘要時,Bot 請看得懂圖的模型,針對一個問題重看其中一張。

View File

@ -41,5 +41,6 @@
- 從帳號看畫面的票會出現在網址裡,所以網頁一打開就換掉連結裡那張(舊的當場作廢),每次斷線重連再換一張;票只在發出後十分鐘內能開新連線,已連上的畫面在要票的手機還登入時一直開著。斷線超過十分鐘:手機網頁用自己的登入重新要票;電腦開的網頁顯示「這個畫面連結已過期」並停止重試,回 AnyBot 再開一次。驗證:開著畫面、關掉 Wi-Fi 一分鐘再打開要自己接回;把連結複製到另一個瀏覽器(原本的已經開著)要連不上。 - 從帳號看畫面的票會出現在網址裡,所以網頁一打開就換掉連結裡那張(舊的當場作廢),每次斷線重連再換一張;票只在發出後十分鐘內能開新連線,已連上的畫面在要票的手機還登入時一直開著。斷線超過十分鐘:手機網頁用自己的登入重新要票;電腦開的網頁顯示「這個畫面連結已過期」並停止重試,回 AnyBot 再開一次。驗證:開著畫面、關掉 Wi-Fi 一分鐘再打開要自己接回;把連結複製到另一個瀏覽器(原本的已經開著)要連不上。
- 「在這台電腦上執行」設成永不允許(或被管理員鎖住)時,這台的檔案也不能傳出去、打開或發佈。 - 「在這台電腦上執行」設成永不允許(或被管理員鎖住)時,這台的檔案也不能傳出去、打開或發佈。
- SSH 電腦上的檔案不能直接傳到聊天、打開給使用者看或發佈網站,要先複製到 Bot 自己的電腦。 - SSH 電腦上的檔案不能直接傳到聊天、打開給使用者看或發佈網站,要先複製到 Bot 自己的電腦。
- 螢幕電腦的 AnyBot 比大腦舊時,在它上面按允許卡片都不算(舊版說不出是哪一張卡),大腦的聊天寫「螢幕電腦上的回答沒有用上…」:在那台 設定 › 更新 換新版,或在大腦、手機上答。
- 帳號裡的其他電腦:看畫面、操作畫面各自要使用者允許(可以一律允許);改檔案和指令照 SSH 電腦的規則問。 - 帳號裡的其他電腦:看畫面、操作畫面各自要使用者允許(可以一律允許);改檔案和指令照 SSH 電腦的規則問。
- `send_to_device`:工作資料夾外的檔案先問,機密檔案不傳;從使用者的其他電腦拿檔案最多 20 MB。沒登入帳號就找不到其他裝置。 - `send_to_device`:工作資料夾外的檔案先問,機密檔案不傳;從使用者的其他電腦拿檔案最多 20 MB。沒登入帳號就找不到其他裝置。

View File

@ -31,7 +31,7 @@
## 怎麼操作 ## 怎麼操作
- Bot:沒有登入、配對或改這一頁的工具。登入帳號後多兩個工具:`send_to_device`(把檔案傳到帳號裡另一台或「手機」)和 `publish_site`(發布成公開網站,見 [files](files.md));開了裝置連結的電腦會出現在它的電腦清單([computers](computers.md))。外面的訊息和團隊成員的訊息拿不到這兩個工具。 - Bot:沒有登入、配對或改這一頁的工具。登入帳號後多兩個工具:`send_to_device`(把檔案傳到帳號裡另一台或「手機」)和 `publish_site`(發布成公開網站,見 [files](files.md));開了裝置連結的電腦會出現在它的電腦清單([computers](computers.md))。外面的訊息和團隊成員的訊息拿不到這兩個工具。
- 驗證:設手機密碼、勾「讓手機直接連這台電腦」,用手機(或另一台的瀏覽器)打開列出的網址、信任憑證、輸入密碼,要看到 Bot 清單;叫 Bot 在你的電腦執行一個要核准的指令,手機出現允許卡片,在手機按「允許一次」(或「允許」)後電腦上的卡片也消失、步驟繼續;用帳號登入的手機開通知、按「送一則測試通知」要跳出貓圖示的通知,關掉「做完了」後 Bot 做完不再推、需要你允許照樣推;「直接連線的裝置」多一行,按「登出」後那支手機要重新登入。在電腦上把 設定 › 一般 › 外觀 的強調色換成靛藍、主題換成深色,手機(外觀「跟著電腦」)重新整理後要變成深色、新訊息的點變靛藍。自動測試:`cargo test remote::`、`cargo test remote_ui::`、`cargo test httpd::`、`cargo test drops::`;帳號伺服器的通知種類在 `relay/` 的 `cargo test`。(`remote::tests::phone_login_and_api` 也檢查 api/state 帶著主題和兩組顏色。) - 驗證:設手機密碼、勾「讓手機直接連這台電腦」,用手機(或另一台的瀏覽器)打開列出的網址、信任憑證、輸入密碼,要看到 Bot 清單;叫 Bot 在你的電腦執行一個要核准的指令,手機出現允許卡片,在手機按「允許一次」(或「允許」)後電腦上的卡片也消失、步驟繼續;手機上的卡還開著時先在電腦上答掉、等 Bot 問下一件,再按手機上那張舊的,下一張要還在等、聊天寫「沒有用上」;用帳號登入的手機開通知、按「送一則測試通知」要跳出貓圖示的通知,關掉「做完了」後 Bot 做完不再推、需要你允許照樣推;「直接連線的裝置」多一行,按「登出」後那支手機要重新登入。在電腦上把 設定 › 一般 › 外觀 的強調色換成靛藍、主題換成深色,手機(外觀「跟著電腦」)重新整理後要變成深色、新訊息的點變靛藍。自動測試:`cargo test remote::`、`cargo test remote_ui::`、`cargo test mirror_ui::`、`cargo test httpd::`、`cargo test drops::`;回答落在哪張卡:`.claude/skills/verify-approval-routing/run.sh --replay`;帳號伺服器的通知種類在 `relay/` 的 `cargo test`。(`remote::tests::phone_login_and_api` 也檢查 api/state 帶著主題和兩組顏色。)
## 陷阱 ## 陷阱
@ -39,10 +39,11 @@
- 「要通知我的事」全部關掉,這支手機就收不到 Bot 的通知(測試通知照樣會到);通知被手機系統擋下時,開關是灰的,要到手機的設定 › 通知打開。 - 「要通知我的事」全部關掉,這支手機就收不到 Bot 的通知(測試通知照樣會到);通知被手機系統擋下時,開關是灰的,要到手機的設定 › 通知打開。
- 通知開關顯示的是帳號伺服器上這支手機的狀態,按下去就照它顯示的開或關:帳號伺服器已經沒有這支手機的訂閱(一個帳號最多 16 支,或推播服務退回)時顯示「關閉中」,打開會重新訂閱;暫時連不上帳號伺服器時,開關照這支手機上的設定,「要通知我的事」和測試通知等連上再用。 - 通知開關顯示的是帳號伺服器上這支手機的狀態,按下去就照它顯示的開或關:帳號伺服器已經沒有這支手機的訂閱(一個帳號最多 16 支,或推播服務退回)時顯示「關閉中」,打開會重新訂閱;暫時連不上帳號伺服器時,開關照這支手機上的設定,「要通知我的事」和測試通知等連上再用。
- App 圖示上的數字要手機支援(iPhone 主畫面 App、Android Chrome 安裝的 App);在瀏覽器分頁裡看不到。 - App 圖示上的數字要手機支援(iPhone 主畫面 App、Android Chrome 安裝的 App);在瀏覽器分頁裡看不到。
- 電腦上的「Bot 做完或等你時通知」關掉,手機也收不到「需要你允許」「做完了」(例行任務暫停照樣推);而且只在你不在電腦前(視窗不在最前面,或 90 秒沒動)才推。 - 電腦上的「Bot 做完或等你時通知」關掉,手機也收不到「需要你允許」「做完了」(例行任務暫停照樣推);而且只在你不在電腦前(視窗不在最前面,或 90 秒沒動)才推。等你的卡只由大腦推(看的是大腦那台在不在前面),螢幕電腦不推。
- 直接連線的連接埠預設 8793,被占用會往後找;照設定頁列出的網址打開。不要把它開放到網際網路,從外面連用帳號或 Tailscale。 - 直接連線的連接埠預設 8793,被占用會往後找;照設定頁列出的網址打開。不要把它開放到網際網路,從外面連用帳號或 Tailscale。
- 第一次用 https 打開,手機會警告憑證:選「繼續」;要確認沒連錯台,比對設定頁上的 SHA-256 指紋。 - 第一次用 https 打開,手機會警告憑證:選「繼續」;要確認沒連錯台,比對設定頁上的 SHA-256 指紋。
- 換手機密碼會把所有直接連線的手機登出。 - 換手機密碼會把所有直接連線的手機登出。
- 團隊成員的訊息跟訊息管道一樣不受信任:不帶你的記憶、沒有 App 操作工具;要核准的事只通知你和管理員,成員只看到「等擁有者或管理員決定」。 - 團隊成員的訊息跟訊息管道一樣不受信任:不帶你的記憶、沒有 App 操作工具;要核准的事只通知你和管理員,成員只看到「等擁有者或管理員決定」。
- 「登出帳號」會把這台從帳號移除:手機從外面連、裝置連結、分享都會斷;這台的 Bot 和聊天還在。 - 「登出帳號」會把這台從帳號移除:手機從外面連、裝置連結、分享都會斷;這台的 Bot 和聊天還在。
- 手機看不到保險庫,也看不到模型金鑰(只能寫入新的)。 - 手機看不到保險庫,也看不到模型金鑰(只能寫入新的)。
- 手機上的卡(允許、需要處理、問題卡)只答它畫出來的那一張:那張已經在電腦或另一支手機上回答、被停止、或換成下一張時,按了不算,聊天裡寫「手機上的回答沒有用上…」,要看現在在等什麼再按;開了很久沒重新整理的舊頁面也一樣(重新整理)。螢幕電腦上的卡也是;比大腦舊的螢幕電腦答不了任何卡,要在那台 設定 › 更新 換新版(重新整理沒用)。支線的卡沒用上時,寫在主線的聊天。用帳號登入的手機,頁面是帳號伺服器給的:伺服器還沒更新時,手機上的卡都答不了,要在電腦上答。

View File

@ -43,7 +43,7 @@ Bot 要動到你的電腦、對外送出或做收不回來的事時,先問你
- 在任何聊天打「/always-approve」(「/」清單裡有),或 設定 › 權限 ›「一律放行」的開關「什麼都不問,全部直接做」。手機用擁有者身分打也可以;團隊成員、管理員打的不算指令(會變成「【名字】/always-approve」給 Bot)。 - 在任何聊天打「/always-approve」(「/」清單裡有),或 設定 › 權限 ›「一律放行」的開關「什麼都不問,全部直接做」。手機用擁有者身分打也可以;團隊成員、管理員打的不算指令(會變成「【名字】/always-approve」給 Bot)。
- 設定 › 權限:「直接操作」的開關「讓 Bot 直接動手,不一個個問你」;「自動審核」的開關「照我寫的規則審核 Bot 的操作」,下面兩張規則卡片,「新增規則」或「刪除」。 - 設定 › 權限:「直接操作」的開關「讓 Bot 直接動手,不一個個問你」;「自動審核」的開關「照我寫的規則審核 Bot 的操作」,下面兩張規則卡片,「新增規則」或「刪除」。
- 設定 › 電腦 ›「你的電腦」:「在這台電腦上執行」的選單。被管理員鎖住時寫「由你的管理員設定,無法變更」。 - 設定 › 電腦 ›「你的電腦」:「在這台電腦上執行」的選單。被管理員鎖住時寫「由你的管理員設定,無法變更」。
- 手機:一樣的卡片和 設定 › 權限([phone](phone.md))。 - 手機:一樣的卡片(只答它畫出來的那一張)和 設定 › 權限([phone](phone.md))。
- Hooks:資料夾的 hooks/hooks.json(使用者的);管理員的放 /Library/Application Support/AnyBot/hooks.json(Mac)、/etc/anybot/hooks.json、%ProgramData%\AnyBot\hooks.json,最後跑(看得到你的 hook 改過的參數)、AnyBot 裡改不了。/doctor 寫有幾個 hook、檔案看不看得懂。 - Hooks:資料夾的 hooks/hooks.json(使用者的);管理員的放 /Library/Application Support/AnyBot/hooks.json(Mac)、/etc/anybot/hooks.json、%ProgramData%\AnyBot\hooks.json,最後跑(看得到你的 hook 改過的參數)、AnyBot 裡改不了。/doctor 寫有幾個 hook、檔案看不看得懂。
## 怎麼操作 ## 怎麼操作

View File

@ -1108,7 +1108,8 @@ function apply(v) {
// An approval answered from a notification banner, and a home-screen shortcut (主要 Bot, 未讀). // An approval answered from a notification banner, and a home-screen shortcut (主要 Bot, 未讀).
if (S.answer && S.token) { if (S.answer && S.token) {
const a = S.answer; S.answer = null; const a = S.answer; S.answer = null;
api(base() + `api/bots/${a.bot}/answer`, {json: {answer: a.answer, call: a.call}}).then(() => toast("已從通知回覆")).catch((e) => toast(e.message)); // (from: "notice" — a notification's buttons answer only a request to allow, never a hand-off.)
api(base() + `api/bots/${a.bot}/answer`, {json: {answer: a.answer, call: a.call, from: "notice"}}).then(() => toast("已從通知回覆")).catch((e) => toast(e.message));
} }
if (S.sc && !S.open) { if (S.sc && !S.open) {
const want = S.sc === "unread" ? S.bots.find((b) => b.unread) : (S.bots.find((b) => b.primary) || S.bots[0]); const want = S.sc === "unread" ? S.bots.find((b) => b.unread) : (S.bots.find((b) => b.primary) || S.bots[0]);
@ -1587,12 +1588,14 @@ function renderDock() {
$("ask").querySelectorAll("button[data-a]").forEach((x) => x.onclick = async () => { $("ask").querySelectorAll("button[data-a]").forEach((x) => x.onclick = async () => {
if (navigator.vibrate) navigator.vibrate(8); if (navigator.vibrate) navigator.vibrate(8);
$("ask").innerHTML = ""; $("ask").innerHTML = "";
try { await api(base() + `api/bots/${(a && a.target) || S.open}/answer`, {json: {answer: x.dataset.a}}); } catch (e) { toast(e.message); } // call: this card's key — the brain applies the answer only to the card drawn here, not
// one that took its place since.
try { await api(base() + `api/bots/${(a && a.target) || S.open}/answer`, {json: {answer: x.dataset.a, call: a.key || ""}}); } catch (e) { toast(e.message); }
}); });
const d = $("ask").querySelector("[data-direct]"); const d = $("ask").querySelector("[data-direct]");
if (d) d.onclick = async () => { if (d) d.onclick = async () => {
if (!await confirmSheet("打開「直接操作」?", "Bot 會直接做事,只有危險操作和你的「一律詢問」規則會停下來問你。", "打開", false)) return; if (!await confirmSheet("打開「直接操作」?", "Bot 會直接做事,只有危險操作和你的「一律詢問」規則會停下來問你。", "打開", false)) return;
if (await act("setting", {key: "direct_mode", value: true}, "已打開直接操作")) api(base() + `api/bots/${(a && a.target) || S.open}/answer`, {json: {answer: a.can_always ? "always" : "once"}}).catch(() => {}); if (await act("setting", {key: "direct_mode", value: true}, "已打開直接操作")) api(base() + `api/bots/${(a && a.target) || S.open}/answer`, {json: {answer: a.can_always ? "always" : "once", call: a.key || ""}}).catch(() => {});
}; };
renderDockRest(b); renderDockRest(b);
} }
@ -1608,8 +1611,9 @@ function askAnswer(q, i) {
function renderQuestion(a, force) { function renderQuestion(a, force) {
const qs = a.questions || []; const qs = a.questions || [];
if (!qs.length) return; if (!qs.length) return;
if (!ASKF || ASKF.id !== a.call_id) { // (A card is told apart by its key: call ids repeat, call_0 every round.)
ASKF = {id: a.call_id, step: 0, drawn: -1, picks: qs.map((q) => { const k = (q.options || []).indexOf(q.default); return k >= 0 && q.default ? [k] : []; }), typed: qs.map((q) => (q.options || []).length ? "" : (q.default || ""))}; if (!ASKF || ASKF.id !== (a.key || a.call_id)) {
ASKF = {id: a.key || a.call_id, step: 0, drawn: -1, picks: qs.map((q) => { const k = (q.options || []).indexOf(q.default); return k >= 0 && q.default ? [k] : []; }), typed: qs.map((q) => (q.options || []).length ? "" : (q.default || ""))};
} }
// Drawn already: leave it, or what is being typed would be lost on every refresh. // Drawn already: leave it, or what is being typed would be lost on every refresh.
if (!force && ASKF.drawn === ASKF.step && $("askq").querySelector(".own")) return; if (!force && ASKF.drawn === ASKF.step && $("askq").querySelector(".own")) return;
@ -1626,7 +1630,8 @@ function renderQuestion(a, force) {
}); });
const ready = () => { go.disabled = !askAnswer(q, i); }; const ready = () => { go.disabled = !askAnswer(q, i); };
ready(); ready();
const send = async (body) => { ASKF = null; box.innerHTML = ""; try { await api(base() + `api/bots/${(a && a.target) || S.open}/answer`, {json: body}); } catch (e) { toast(e.message); } }; // (With this card's key: an answer for these questions never reaches the next card.)
const send = async (body) => { ASKF = null; box.innerHTML = ""; try { await api(base() + `api/bots/${(a && a.target) || S.open}/answer`, {json: Object.assign({call: a.key || ""}, body)}); } catch (e) { toast(e.message); } };
const next = () => { const next = () => {
if (!askAnswer(q, i)) return; if (!askAnswer(q, i)) return;
if (!last) { ASKF.step = i + 1; return renderQuestion(a, true); } if (!last) { ASKF.step = i + 1; return renderQuestion(a, true); }
@ -3463,7 +3468,7 @@ if ("serviceWorker" in navigator) navigator.serviceWorker.addEventListener("mess
if (d.host && d.host !== S.host && S.relay) { S.host = d.host; localStorage.setItem("anybot.host", S.host); S.version = 0; } if (d.host && d.host !== S.host && S.relay) { S.host = d.host; localStorage.setItem("anybot.host", S.host); S.version = 0; }
if (d.answer && d.ask && d.bot) { if (d.answer && d.ask && d.bot) {
// (Not signed in yet: kept, and sent once the phone is — apply.) // (Not signed in yet: kept, and sent once the phone is — apply.)
if (S.token) api(base() + `api/bots/${d.bot}/answer`, {json: {answer: d.answer, call: d.ask}}).then(() => toast("已從通知回覆")).catch((e) => toast(e.message)); if (S.token) api(base() + `api/bots/${d.bot}/answer`, {json: {answer: d.answer, call: d.ask, from: "notice"}}).then(() => toast("已從通知回覆")).catch((e) => toast(e.message));
else S.answer = {bot: +d.bot, answer: d.answer, call: d.ask}; else S.answer = {bot: +d.bot, answer: d.answer, call: d.ask};
} }
if (d.bot && S.token) go("chat", {bot: +d.bot}); else if (d.bot) S.open = +d.bot; if (d.bot && S.token) go("chat", {bot: +d.bot}); else if (d.bot) S.open = +d.bot;

View File

@ -215,10 +215,15 @@ pub struct App {
doctor_out: Arc<Mutex<Vec<(u64, String)>>>, doctor_out: Arc<Mutex<Vec<(u64, String)>>>,
/// Lines for a bot's chat that work on another thread finished (/rewind's files…). /// Lines for a bot's chat that work on another thread finished (/rewind's files…).
later_notes: Arc<Mutex<Vec<(u64, String)>>>, later_notes: Arc<Mutex<Vec<(u64, String)>>>,
/// The key a phone banner's 允許/拒絕 must carry to answer a bot's waiting request: made /// The key every answer from afar (the phone's card, a notification, a screen) must carry to
/// new for every request (the tool call's id repeats — one step may ask three times, and /// answer a bot's waiting request: made new for every request (the tool call's id repeats —
/// some models number their calls from 0 every turn), and not guessable from a link. /// one step may ask three times, and some models number their calls from 0 every turn), and
/// not guessable from a link.
pub(crate) ask_keys: HashMap<u64, String>, pub(crate) ask_keys: HashMap<u64, String>,
/// Keys of the cards 直接操作 let through as it came on (the "may I use the computer?" ones):
/// the phone's own 「全部允許,之後直接操作」 still sends its answer for that card after, and
/// it is already done — not a stale answer to tell the person about.
settled_by_direct: std::collections::HashSet<String>,
/// 「/compact」 summaries finished on their thread: (bot, (messages replaced, summary, first kept message's time)). /// 「/compact」 summaries finished on their thread: (bot, (messages replaced, summary, first kept message's time)).
#[allow(clippy::type_complexity)] #[allow(clippy::type_complexity)]
compact_out: Arc<Mutex<Vec<(u64, Option<(usize, Message, i64)>)>>>, compact_out: Arc<Mutex<Vec<(u64, Option<(usize, Message, i64)>)>>>,
@ -503,6 +508,7 @@ impl App {
doctor_out: Default::default(), doctor_out: Default::default(),
later_notes: Default::default(), later_notes: Default::default(),
ask_keys: Default::default(), ask_keys: Default::default(),
settled_by_direct: Default::default(),
compact_out: Default::default(), compact_out: Default::default(),
managed: if demo { policy::Managed::default() } else { policy::read() }, managed: if demo { policy::Managed::default() } else { policy::read() },
settings_was_open: false, settings_was_open: false,
@ -2798,6 +2804,10 @@ impl App {
for id in waiting { for id in waiting {
if let Some(a) = self.approvals.remove(&id) { if let Some(a) = self.approvals.remove(&id) {
let _ = a.reply.send(ApprovalAnswer::Always(a.grant.clone())); let _ = a.reply.send(ApprovalAnswer::Always(a.grant.clone()));
// (The phone that turned this on sends its answer for the card right after.)
if let Some(k) = self.ask_keys.get(&id) {
self.settled_by_direct.insert(k.clone());
}
} }
} }
self.notice = Some("已打開「直接操作」:Bot 會直接做事,只有危險操作和你的「一律詢問」規則會停下來問你。".into()); self.notice = Some("已打開「直接操作」:Bot 會直接做事,只有危險操作和你的「一律詢問」規則會停下來問你。".into());
@ -2822,7 +2832,10 @@ impl App {
}; };
self.approvals.remove(&bot_id); self.approvals.remove(&bot_id);
self.popup_hidden.remove(&bot_id); self.popup_hidden.remove(&bot_id);
self.mirror_act(serde_json::json!({"bot": bot_id, "action": "answer", "answer": a, "text": text})); // The brain's key for the card shown here: the brain takes it only for that card,
// not one that came after it (an older brain gave no key, and takes none).
let call = self.mir.keys.get(&bot_id).cloned().unwrap_or_default();
self.mirror_act(serde_json::json!({"bot": bot_id, "action": "answer", "answer": a, "text": text, "call": call}));
return; return;
} }
if self.want_direct.replace(false) { if self.want_direct.replace(false) {
@ -4191,7 +4204,10 @@ impl App {
fn question_card(&mut self, ui: &mut egui::Ui, ctx: &egui::Context, bot: &Bot) { fn question_card(&mut self, ui: &mut egui::Ui, ctx: &egui::Context, bot: &Bot) {
let p = self.pal; let p = self.pal;
let Some(a) = self.approvals.get(&bot.id) else { return }; let Some(a) = self.approvals.get(&bot.id) else { return };
let call_id = a.call_id.clone(); // Which card this is: its key (on_new_approval; a screen's is the brain's). Call ids
// repeat — call_0 every round — and a question that took another's place with the same
// id and as many questions took its step and picks: 送出 sent what nobody chose here.
let call_id = self.ask_keys.get(&bot.id).filter(|k| !k.is_empty()).cloned().unwrap_or_else(|| a.call_id.clone());
let Ok(qs) = crate::ask::parse(&a.reason) else { let Ok(qs) = crate::ask::parse(&a.reason) else {
self.answer(ctx, bot.id, ApprovalAnswer::Reject); self.answer(ctx, bot.id, ApprovalAnswer::Reject);
return; return;
@ -4455,11 +4471,19 @@ impl App {
/// A new request: show it as a pop-up (even over another bot's chat) and get the person's /// A new request: show it as a pop-up (even over another bot's chat) and get the person's
/// attention (the Dock icon bounces when AnyBot isn't in front, and the 提示音 rings). /// attention (the Dock icon bounces when AnyBot isn't in front, and the 提示音 rings).
/// The card gets its own key: every answer from afar (the phone's card, a notification, a
/// screen) names it, and only this card takes it (remote_ui's Cmd::Answer).
fn on_new_approval(&mut self, ctx: &egui::Context, bot_id: u64) { fn on_new_approval(&mut self, ctx: &egui::Context, bot_id: u64) {
let key = crate::httpd::random_hex(16);
self.new_approval_keyed(ctx, bot_id, key);
}
/// on_new_approval with the card's key given (a screen takes the brain's, so what it sends
/// back names the card the brain is waiting on).
fn new_approval_keyed(&mut self, ctx: &egui::Context, bot_id: u64, key: String) {
self.popup_hidden.remove(&bot_id); self.popup_hidden.remove(&bot_id);
// (A new card waits its own moment before it takes Enter / Esc.) // (A new card waits its own moment before it takes Enter / Esc.)
self.ask_shown.remove(&bot_id); self.ask_shown.remove(&bot_id);
let key = crate::httpd::random_hex(16);
self.ask_keys.insert(bot_id, key.clone()); self.ask_keys.insert(bot_id, key.clone());
// (A brain on a server has nobody to hear it.) // (A brain on a server has nobody to hear it.)
let chime = !self.demo && !self.headless && self.state.alert_sound; let chime = !self.demo && !self.headless && self.state.alert_sound;
@ -4472,9 +4496,6 @@ impl App {
if self.state.notify && self.away() { if self.state.notify && self.away() {
if let (Some(b), Some(a)) = (self.state.bot(bot_id), self.approvals.get(&bot_id)) { if let (Some(b), Some(a)) = (self.state.bot(bot_id), self.approvals.get(&bot_id)) {
let mut what = a.reason.split('\n').next().unwrap_or("").to_string(); let mut what = a.reason.split('\n').next().unwrap_or("").to_string();
// 允許 on a banner must be about all of it: a request that doesn't fit there
// whole (a command of several lines) is answered in the chat.
let whole = a.reason.lines().filter(|l| !l.starts_with("(在 ")).count() <= 1 && what.chars().count() <= 170;
// 「{callee} 需要你」 for a step only the person can do. // 「{callee} 需要你」 for a step only the person can do.
let mut title = if a.kind == ApprovalKind::Handoff { format!("{}:需要你", b.name) } else { format!("{} 需要你允許", b.name) }; let mut title = if a.kind == ApprovalKind::Handoff { format!("{}:需要你", b.name) } else { format!("{} 需要你允許", b.name) };
if a.kind == ApprovalKind::Question { if a.kind == ApprovalKind::Question {
@ -4485,9 +4506,16 @@ impl App {
// The banner doesn't ring a second time when the 提示音 just did. // The banner doesn't ring a second time when the 提示音 just did.
notify::banner_for(&title, &what, !chime, Some(bot_id)); notify::banner_for(&title, &what, !chime, Some(bot_id));
} }
// 允許/拒絕 on the banner only for a request to allow (a question, or a step // To the phone: not from a screen — its push would open the phone on the
// only the person can do, opens the chat). // screen, which runs nothing from a phone and shows it nothing (the 允許
if whole && a.tool != crate::hooks::MANAGE_TOOL && matches!(a.kind, ApprovalKind::Action | ApprovalKind::EnableTools | ApprovalKind::EnableThisComputer) { // vanished). The brain pushes its own for this card (the same 通知 setting,
// when it is away). A screen's own Notification hooks still run (hooks are
// each computer's own, and they 跟著通知跑): only the push is the brain's.
// 允許/拒絕 on the banner only where notice_answers says so (the brain checks
// the same rule when the answer comes back).
if self.mir.on {
crate::hooks::notification(&title, &what, bot_id);
} else if notice_answers(a) {
crate::remote::notify_approval(&title, &what, bot_id, &key); crate::remote::notify_approval(&title, &what, bot_id, &key);
} else { } else {
crate::remote::notify(crate::remote::Notice::Need, &title, &what, bot_id); crate::remote::notify(crate::remote::Notice::Need, &title, &what, bot_id);
@ -6971,6 +6999,17 @@ struct Live {
turn: u64, turn: u64,
} }
/// Whether a notification may carry 允許/拒絕 for this card: only a request to allow (a
/// question, or a step only the person can do, opens the chat — 允許 must never mean 我完成了),
/// not a hook change, and only when the request fits there whole (a command of several lines is
/// answered in the chat, where all of it shows). on_new_approval puts the buttons on by this
/// rule; Cmd::Answer takes a notification's answer only by it.
fn notice_answers(a: &Approval) -> bool {
let first = a.reason.split('\n').next().unwrap_or("");
let whole = a.reason.lines().filter(|l| !l.starts_with("(在 ")).count() <= 1 && first.chars().count() <= 170;
whole && a.tool != crate::hooks::MANAGE_TOOL && matches!(a.kind, ApprovalKind::Action | ApprovalKind::EnableTools | ApprovalKind::EnableThisComputer)
}
/// How an "always allow" grant reads in the UI. /// How an "always allow" grant reads in the UI.
fn grant_label(g: &str) -> String { fn grant_label(g: &str) -> String {
match g { match g {
@ -8225,6 +8264,43 @@ mod tests {
} }
} }
/// 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
/// nobody chose for it.
#[test]
fn a_question_in_anothers_place_starts_with_nothing_picked() {
let ctx = egui::Context::default();
let mut app = super::App::new(&ctx, Some(std::env::temp_dir().join("anybot-question-replaced.png")));
let id = app.state.bots[0].id;
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 });
let bot = app.state.bot(id).unwrap().clone();
// The bot asks (NeedApproval, as a turn sends it): two questions, call_0.
let ask = |app: &mut super::App, first: &str| {
let (reply, got) = std::sync::mpsc::channel();
let qs = crate::ask::parse(&serde_json::json!({"questions": [{"question": first, "options": ["是", "否"]}, {"question": "還有呢?", "options": ["有", "沒有"]}]}).to_string()).unwrap_or_default();
app.tx.send((id, 1, StreamEvent::NeedApproval(Approval { call_id: "call_0".into(), tool: crate::ask::TOOL.into(), reason: crate::ask::to_json(&qs), grant: String::new(), reply, kind: ApprovalKind::Question }))).unwrap();
app.drain_events(&ctx);
got
};
let frame = |app: &mut super::App| {
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| app.approval_card(ui, &ctx, &bot));
out.textures_delta.clear();
};
let _first = ask(&mut app, "要備份嗎?");
frame(&mut app);
// Answered the first question here: 「否」, and on to the second.
let f = app.ask_forms.get_mut(&id).expect("the form is kept between frames");
f.picks[0] = vec![1];
f.step = 1;
// That card is answered on the phone; the same step asks something else.
app.answer(&ctx, id, ApprovalAnswer::Reject);
let _second = ask(&mut app, "要刪掉嗎?");
frame(&mut app);
let f = app.ask_forms.get(&id).expect("the form is kept between frames");
assert_eq!((f.step, f.picks[0].clone()), (0, vec![]), "the new card starts at its first question, nothing picked");
}
/// Esc that closes a menu closes the menu: it isn't a no to the step waiting in the chat. /// Esc that closes a menu closes the menu: it isn't a no to the step waiting in the chat.
/// And a card that comes into view (a field let go) takes keys only after a moment. /// And a card that comes into view (a field let go) takes keys only after a moment.
#[test] #[test]

View File

@ -523,6 +523,9 @@ pub struct Mirror {
pub(super) mcp_state: Value, pub(super) mcp_state: Value,
/// When each bot's last turn ended, as last heard (a newer one ending well is read aloud). /// When each bot's last turn ended, as last heard (a newer one ending well is read aloud).
settled: HashMap<u64, i64>, settled: HashMap<u64, i64>,
/// The brain's key for each card waiting here (by bot id): an answer from this screen names
/// it, so the brain applies it only to that card.
pub(super) keys: HashMap<u64, String>,
/// The last answer from the brain: when (ms), how many bytes came over the lasting /// The last answer from the brain: when (ms), how many bytes came over the lasting
/// connection for it, and how long it took (ms) — the 大腦 section says the line's speed. /// connection for it, and how long it took (ms) — the 大腦 section says the line's speed.
pub(super) last_sync: Arc<Mutex<Option<(i64, u64, u64)>>>, pub(super) last_sync: Arc<Mutex<Option<(i64, u64, u64)>>>,
@ -690,7 +693,8 @@ impl App {
ApprovalKind::Handoff => "handoff", ApprovalKind::Handoff => "handoff",
ApprovalKind::Question => "question", ApprovalKind::Question => "question",
}; };
json!({"bot": id, "call_id": a.call_id, "tool": a.tool, "reason": a.reason, "grant": a.grant, "kind": kind}) // key: this card's (on_new_approval); the screen sends it back with its answer.
json!({"bot": id, "call_id": a.call_id, "tool": a.tool, "reason": a.reason, "grant": a.grant, "kind": kind, "key": self.ask_keys.get(id).cloned().unwrap_or_default()})
}) })
.collect(); .collect();
// The connectors run here too: whether each is connected, or why not. // The connectors run here too: whether each is connected, or why not.
@ -949,6 +953,7 @@ impl App {
self.mir.outbox = None; self.mir.outbox = None;
self.streams.clear(); self.streams.clear();
self.approvals.clear(); self.approvals.clear();
self.mir.keys.clear();
self.mir.settled.clear(); self.mir.settled.clear();
if let Some(mut local) = self.mir.local.take() { if let Some(mut local) = self.mir.local.take() {
let mut remote = self.state.remote.clone(); let mut remote = self.state.remote.clone();
@ -1206,15 +1211,28 @@ impl App {
}; };
let (reply, _) = channel(); let (reply, _) = channel();
let s = |k: &str| a[k].as_str().unwrap_or("").to_string(); let s = |k: &str| a[k].as_str().unwrap_or("").to_string();
waiting.insert(id, Approval { call_id: s("call_id"), tool: s("tool"), reason: s("reason"), grant: s("grant"), reply, kind }); waiting.insert(id, (Approval { call_id: s("call_id"), tool: s("tool"), reason: s("reason"), grant: s("grant"), reply, kind }, s("key")));
} }
let ctx = self.ctx_handle.clone(); let ctx = self.ctx_handle.clone();
for (id, a) in waiting { for (id, (a, key)) in waiting {
let new = self.approvals.get(&id).map(|o| o.call_id != a.call_id).unwrap_or(true); // A new card is told by the brain's key (call ids repeat: call_0 every round); an
// older brain sends none, and then by its call id, as before.
let new = match key.is_empty() {
true => self.approvals.get(&id).map(|o| o.call_id != a.call_id).unwrap_or(true),
false => !self.approvals.contains_key(&id) || self.mir.keys.get(&id) != Some(&key),
};
self.approvals.insert(id, a); self.approvals.insert(id, a);
if key.is_empty() {
self.mir.keys.remove(&id);
} else {
self.mir.keys.insert(id, key.clone());
}
if new { if new {
if let Some(c) = &ctx { if let Some(c) = &ctx {
self.on_new_approval(c, id); match key.is_empty() {
true => self.on_new_approval(c, id),
false => self.new_approval_keyed(c, id, key),
}
} }
} }
} }
@ -1232,6 +1250,7 @@ impl App {
} }
let keep: Vec<u64> = v["approvals"].as_array().into_iter().flatten().filter_map(|a| a["bot"].as_u64()).collect(); let keep: Vec<u64> = v["approvals"].as_array().into_iter().flatten().filter_map(|a| a["bot"].as_u64()).collect();
self.approvals.retain(|id, _| keep.contains(id)); self.approvals.retain(|id, _| keep.contains(id));
self.mir.keys.retain(|id, _| keep.contains(id));
if self.state.bot(self.state.selected).is_none() { if self.state.bot(self.state.selected).is_none() {
self.state.selected = self.state.primary_bot; self.state.selected = self.state.primary_bot;
} }
@ -1555,6 +1574,102 @@ mod tests {
use super::*; use super::*;
/// 螢幕電腦上回答的卡帶著大腦給那張卡的 key(.claude/skills/verify-approval-routing 的
/// ScreenRefreshes → YouAnswerOnScreen → BrainTakesAnswer):大腦只把它交給那張卡。以前
/// 不帶,大腦交給那時候在等的卡(F1)。
#[test]
fn a_screen_answers_only_the_card_it_shows() {
let ctx = egui::Context::default();
let mut brain = App::new(&ctx, Some(std::env::temp_dir().join("anybot-screen-key-brain.png")));
let id = brain.state.bots[0].id;
let card = |app: &mut App, reason: &str, key: &str| {
let (tx, rx) = channel();
app.approvals.insert(id, Approval { call_id: "call_0".into(), tool: "shell".into(), reason: reason.into(), grant: "rm".into(), reply: tx, kind: ApprovalKind::Action });
app.ask_keys.insert(id, key.into());
rx
};
let first = card(&mut brain, "執行指令:ls", "k1");
// ScreenRefreshes:螢幕電腦拿到大腦的 approvals(和每張卡的 key)。
let pulled = brain.brain_pull("screen-test", 0);
// (The demo data has another bot's card too.)
let ours = pulled["approvals"].as_array().into_iter().flatten().find(|a| a["bot"] == id).cloned().unwrap_or_default();
assert_eq!(ours["key"], "k1", "{}", pulled["approvals"]);
let mut screen = App::new(&ctx, Some(std::env::temp_dir().join("anybot-screen-key-screen.png")));
screen.mir.on = true;
screen.mir.online = true;
let (otx, orx) = channel();
screen.mir.outbox = Some(otx);
screen.mirror_apply(json!({"approvals": pulled["approvals"].clone()}));
assert!(screen.approvals.contains_key(&id) && screen.mir.keys.get(&id).map(String::as_str) == Some("k1"));
// 大腦那邊,第一張卡在電腦上回答了,第二張(同一個 call_0)在等。
brain.answer(&ctx, id, ApprovalAnswer::Once);
assert_eq!(first.try_recv(), Ok(ApprovalAnswer::Once));
let second = card(&mut brain, "執行指令:rm -rf ~/Documents/報告", "k2");
// YouAnswerOnScreen:螢幕上還是第一張,按「一律允許」。
screen.answer(&ctx, id, ApprovalAnswer::Always("rm".into()));
let body = match orx.try_recv() {
Ok(Out::Act(b)) => b,
_ => panic!("the brain wasn't told"),
};
assert_eq!(body["call"], "k1", "{body}");
// BrainTakesAnswer:api/sync/act 的 answer 照 remote.rs 變成 Cmd::Answer。
let as_sent = |b: &Value| crate::remote::Cmd::Answer { bot: id, answer: b["answer"].as_str().unwrap_or("reject").into(), text: b["text"].as_str().unwrap_or("").into(), call: b["call"].as_str().unwrap_or("").into(), notice: b["from"].as_str() == Some("notice"), screen: true };
brain.remote_cmd(&ctx, as_sent(&body));
assert!(second.try_recv().is_err() && brain.state.bot(id).unwrap().allow_rules.is_empty(), "the screen showed ls, not rm -rf");
// 螢幕同步到第二張以後,它的回答才算數。
screen.mirror_apply(json!({"approvals": brain.brain_pull("screen-test", 0)["approvals"].clone()}));
screen.answer(&ctx, id, ApprovalAnswer::Reject);
let body = match orx.try_recv() {
Ok(Out::Act(b)) => b,
_ => panic!("the brain wasn't told"),
};
brain.remote_cmd(&ctx, as_sent(&body));
assert_eq!(second.try_recv(), Ok(ApprovalAnswer::Reject));
}
/// The brain asks the same thing again (same call_0, same words) while the screen still
/// shows the first card: only the brain's key tells the two apart. The screen takes the new
/// key as its own card's (ask_keys, which its Enter/Esc and its own notifications go by) in
/// step with mir.keys, starts the new card's wait for keys over, and answers with that key.
#[test]
fn a_screen_keeps_its_cards_key_in_step_with_the_brains() {
let ctx = egui::Context::default();
let mut brain = App::new(&ctx, Some(std::env::temp_dir().join("anybot-screen-step-brain.png")));
let id = brain.state.bots[0].id;
let card = |app: &mut App, key: &str| {
let (tx, rx) = channel();
app.approvals.insert(id, Approval { call_id: "call_0".into(), tool: "shell".into(), reason: "執行指令:rm -rf build".into(), grant: "rm".into(), reply: tx, kind: ApprovalKind::Action });
app.ask_keys.insert(id, key.into());
rx
};
let mut screen = App::new(&ctx, Some(std::env::temp_dir().join("anybot-screen-step-screen.png")));
screen.mir.on = true;
screen.mir.online = true;
screen.ctx_handle = Some(ctx.clone());
let (otx, orx) = channel();
screen.mir.outbox = Some(otx);
let first = card(&mut brain, "k1");
screen.mirror_apply(json!({"approvals": brain.brain_pull("screen-step", 0)["approvals"].clone()}));
assert_eq!((screen.ask_keys.get(&id).map(String::as_str), screen.mir.keys.get(&id).map(String::as_str)), (Some("k1"), Some("k1")));
// The card has been up a while on the screen (its Enter would answer it now).
screen.ask_shown.insert(id, Instant::now() - std::time::Duration::from_secs(2));
// At the brain: answered on its own window, and the same step asks again.
brain.answer(&ctx, id, ApprovalAnswer::Once);
assert_eq!(first.try_recv(), Ok(ApprovalAnswer::Once));
let second = card(&mut brain, "k2");
screen.mirror_apply(json!({"approvals": brain.brain_pull("screen-step", 0)["approvals"].clone()}));
assert_eq!((screen.ask_keys.get(&id).map(String::as_str), screen.mir.keys.get(&id).map(String::as_str)), (Some("k2"), Some("k2")), "the screen's card is the new one");
assert!(!screen.ask_shown.contains_key(&id), "a new card waits its own moment before Enter/Esc");
screen.answer(&ctx, id, ApprovalAnswer::Once);
let body = match orx.try_recv() {
Ok(Out::Act(b)) => b,
_ => panic!("the brain wasn't told"),
};
assert_eq!(body["call"], "k2", "{body}");
brain.remote_cmd(&ctx, crate::remote::Cmd::Answer { bot: id, answer: body["answer"].as_str().unwrap_or("").into(), text: String::new(), call: body["call"].as_str().unwrap_or("").into(), notice: false, screen: true });
assert_eq!(second.try_recv(), Ok(ApprovalAnswer::Once));
}
/// 每次更新強調色都變回橘色:外觀是這台自己的,連到大腦時、大腦的設定來時、存檔時都用這台的。 /// 每次更新強調色都變回橘色:外觀是這台自己的,連到大腦時、大腦的設定來時、存檔時都用這台的。
/// Every key on the two lists is set off its default here and must come across — a key added /// Every key on the two lists is set off its default here and must come across — a key added
/// to a list but not to copy_own (or not here) fails. /// to a list but not to copy_own (or not here) fails.

View File

@ -51,7 +51,9 @@ fn address_only(url: &str) -> String {
format!("{scheme}{}{path}", host.rsplit('@').next().unwrap_or(host)) format!("{scheme}{}{path}", host.rsplit('@').next().unwrap_or(host))
} }
fn approval_json(bot: &Bot, a: &Approval) -> serde_json::Value { /// A card as the phone draws it. `key`: the card's own (on_new_approval) — the phone sends it
/// back with the answer, so the brain applies it only to this card.
fn approval_json(bot: &Bot, a: &Approval, key: &str) -> serde_json::Value {
let what = remote::tool_label(&a.tool); let what = remote::tool_label(&a.tool);
let title = match a.kind { let title = match a.kind {
ApprovalKind::EnableTools => format!("允許 {} 使用電腦工具嗎?", bot.name), ApprovalKind::EnableTools => format!("允許 {} 使用電腦工具嗎?", bot.name),
@ -63,10 +65,10 @@ fn approval_json(bot: &Bot, a: &Approval) -> serde_json::Value {
// 問題卡: the questions themselves, for the phone to draw. // 問題卡: the questions themselves, for the phone to draw.
if a.kind == ApprovalKind::Question { if a.kind == ApprovalKind::Question {
let questions: serde_json::Value = serde_json::from_str(&a.reason).unwrap_or(json!([])); let questions: serde_json::Value = serde_json::from_str(&a.reason).unwrap_or(json!([]));
return json!({"bot": bot.id, "title": title, "reason": crate::ask::describe(&a.reason), "tool": a.tool, "can_always": false, "kind": "question", "computer": "", "call_id": a.call_id, "questions": questions}); return json!({"bot": bot.id, "title": title, "reason": crate::ask::describe(&a.reason), "tool": a.tool, "can_always": false, "kind": "question", "computer": "", "call_id": a.call_id, "questions": questions, "key": key});
} }
let handoff = a.kind == ApprovalKind::Handoff; let handoff = a.kind == ApprovalKind::Handoff;
json!({"bot": bot.id, "title": title, "reason": a.reason, "tool": a.tool, "can_always": !handoff && (a.kind != ApprovalKind::Action || !a.grant.is_empty()), "kind": if handoff { "handoff" } else { "ask" }, "computer": if handoff { a.grant.as_str() } else { "" }}) json!({"bot": bot.id, "title": title, "reason": a.reason, "tool": a.tool, "can_always": !handoff && (a.kind != ApprovalKind::Action || !a.grant.is_empty()), "kind": if handoff { "handoff" } else { "ask" }, "computer": if handoff { a.grant.as_str() } else { "" }, "key": key})
} }
/// A teammate's messages waiting for a busy bot (more than this are not taken). /// A teammate's messages waiting for a busy bot (more than this are not taken).
@ -291,7 +293,9 @@ impl App {
if let Some(l) = self.streams.get(&b.id) { if let Some(l) = self.streams.get(&b.id) {
(1u8, &l.status, l.paused, l.steer.lock().unwrap().len()).hash(&mut h); (1u8, &l.status, l.paused, l.steer.lock().unwrap().len()).hash(&mut h);
} }
self.approvals.get(&b.id).map(|a| a.call_id.clone()).hash(&mut h); // (With its key: call ids repeat — call_0 every round — and a new card has to reach
// the phone with its own key.)
self.approvals.get(&b.id).map(|a| (a.call_id.clone(), self.ask_keys.get(&b.id).cloned())).hash(&mut h);
// The phone's home and bot sheet: its model, computer, routines and past chats. // The phone's home and bot sheet: its model, computer, routines and past chats.
(b.provider, &b.model, &b.default_computer, b.threads.len(), b.id == self.state.primary_bot).hash(&mut h); (b.provider, &b.model, &b.default_computer, b.threads.len(), b.id == self.state.primary_bot).hash(&mut h);
for r in &b.routines { for r in &b.routines {
@ -301,6 +305,10 @@ impl App {
for (id, _, online) in self.rm.peers.lock().unwrap().iter() { for (id, _, online) in self.rm.peers.lock().unwrap().iter() {
(id, online).hash(&mut h); (id, online).hash(&mut h);
} }
// A 支線's card (shown in its main bot's chat), with its key.
for br in &self.state.branch_bots {
self.approvals.get(&br.id).map(|a| (br.id, a.call_id.clone(), self.ask_keys.get(&br.id).cloned())).hash(&mut h);
}
crate::cloudbox::run_state().label().hash(&mut h); crate::cloudbox::run_state().label().hash(&mut h);
// A connector connected or failing: screens and phones hear of it now, not at the next // A connector connected or failing: screens and phones hear of it now, not at the next
// long poll's end. // long poll's end.
@ -313,6 +321,27 @@ impl App {
h.finish() h.finish()
} }
/// The cards the phone shows in bot `b`'s chat, each with its own key (the phone sends it
/// back, and the brain applies the answer only to that card): `b`'s own, and its 支線's —
/// shown in the main bot's chat (`bot`), answered for the 支線 (`target`), with the 支線's key.
fn phone_cards(&self, b: &Bot) -> Vec<serde_json::Value> {
let key = |id: u64| self.ask_keys.get(&id).map(String::as_str).unwrap_or("");
let mut out = vec![];
if let Some(a) = self.approvals.get(&b.id) {
out.push(approval_json(b, a, key(b.id)));
}
for br in self.state.branch_bots.iter().filter(|x| x.branch_of == b.id) {
if let Some(a) = self.approvals.get(&br.id) {
let mut j = approval_json(br, a, key(br.id));
j["bot"] = json!(b.id);
j["target"] = json!(br.id);
j["title"] = json!(format!("支線:{}", j["title"].as_str().unwrap_or("")));
out.push(j);
}
}
out
}
pub(super) fn remote_publish(&mut self) { pub(super) fn remote_publish(&mut self) {
let sig = self.remote_signature(); let sig = self.remote_signature();
if sig == self.rm.sig { if sig == self.rm.sig {
@ -460,19 +489,7 @@ impl App {
}) })
.collect(); .collect();
view.messages.insert(b.id, msgs); view.messages.insert(b.id, msgs);
if let Some(a) = self.approvals.get(&b.id) { view.approvals.extend(self.phone_cards(b));
view.approvals.push(approval_json(b, a));
}
// A 支線's step waiting for a yes: shown in its main bot's chat, answered for it.
for br in self.state.branch_bots.iter().filter(|x| x.branch_of == b.id) {
if let Some(a) = self.approvals.get(&br.id) {
let mut j = approval_json(br, a);
j["bot"] = json!(b.id);
j["target"] = json!(br.id);
j["title"] = json!(format!("支線:{}", j["title"].as_str().unwrap_or("")));
view.approvals.push(j);
}
}
} }
view.pages = self.state.pages.clone(); view.pages = self.state.pages.clone();
// The models a bot can be switched to from the phone: each provider that is ready. // The models a bot can be switched to from the phone: each provider that is ready.
@ -610,13 +627,38 @@ impl App {
} }
self.mark(); self.mark();
} }
Cmd::Answer { bot, answer, text, call } => { Cmd::Answer { bot, answer, text, call, notice, screen } => {
// From a notification banner: only the request it showed (it may have been // Only the card it was given for: every answer from afar (the phone's card, a
// answered since, and another one be waiting). // notification, a screen) names its card by the key on_new_approval gave it. A
// (And only a request to allow: 「允許」 on a hand-off would mean 「我完成了」.) // card answered, gone or replaced since — or a page too old to name one — takes
let allowable = self.approvals.get(&bot).is_some_and(|a| matches!(a.kind, ApprovalKind::Action | ApprovalKind::EnableTools | ApprovalKind::EnableThisComputer)); // nothing (it used to answer whatever waited by then: an 允許 for one step went
if !call.is_empty() && !(allowable && self.ask_keys.get(&bot) == Some(&call)) { // to the next, and 一律允許 remembered the next one's kind).
self.goal_note(bot, "通知上的「允許/拒絕」沒有用上:那個請求已經不在等了(回答過,或換成了別的)。打開聊天看現在在等什麼。"); let waiting = self.approvals.get(&bot);
let this_card = waiting.is_some() && !call.is_empty() && self.ask_keys.get(&bot) == Some(&call);
// A notification's 允許/拒絕 only on a card notice_answers gave the buttons to:
// never 「我完成了」 on a hand-off or 「略過」 on a question, whatever the key.
let fits = !notice || (waiting.is_some_and(super::notice_answers) && matches!(answer.as_str(), "once" | "reject"));
if !(this_card && fits) {
// Said only while something waits: with nothing waiting the answer was for a
// card already settled. Nor for a card 直接操作 let through as it came on (the
// phone's 「全部允許」 sends its answer for that card after) — already done.
if waiting.is_some() && !(!call.is_empty() && self.settled_by_direct.contains(&call)) {
// What to do about it depends on where it came from: a phone page too old
// to name its card is refreshed; a screen computer that old is updated.
let note = match (notice, screen, call.is_empty()) {
(true, ..) => "通知上的「允許/拒絕」沒有用上:那個請求已經不在等了(回答過,或換成了別的)。打開聊天看現在在等什麼。",
(_, true, true) => "螢幕電腦上的回答沒有用上:那台電腦的 AnyBot 比這台舊,說不出是哪一張卡。在那台打開 設定 › 更新 換新版,或在這台回答。",
(_, true, false) => "螢幕電腦上的回答沒有用上:那張卡已經不在等了(回答過,或換成了別的)。看現在在等什麼再回答。",
// (Refreshing gets the page again from where it came: an account
// server not yet updated serves the old one again.)
(_, false, true) => "手機上的回答沒有用上:這個頁面太舊,說不出是哪一張卡。重新整理再回答;還是不行(帳號伺服器還沒更新),就在電腦上回答。",
(_, false, false) => "手機上的回答沒有用上:那張卡已經不在等了(回答過,或換成了別的)。看現在在等什麼再回答。",
};
// In the chat the person reads: a 支線's card is shown, and answered, in
// its main bot's chat — the 支線's own messages aren't shown anywhere.
let home = self.state.home_of(bot);
self.goal_note(home, note);
}
return; return;
} }
let grant = self.approvals.get(&bot).map(|a| a.grant.clone()).unwrap_or_default(); let grant = self.approvals.get(&bot).map(|a| a.grant.clone()).unwrap_or_default();
@ -1864,35 +1906,167 @@ mod phone_act_tests {
} }
/// 允許/拒絕 on a phone notification answers only the request it showed: once that one /// 允許/拒絕 on a phone notification answers only the request it showed: once that one
/// is gone and another waits, the old banner answers nothing (a note says so). /// is gone and another waits, the old banner answers nothing (a note says so). And only a
/// request to allow that fits on the banner: never 我完成了, 略過 or 一律允許 from there.
#[test] #[test]
fn a_banner_answers_only_its_own_request() { fn a_banner_answers_only_its_own_request() {
let (ctx, mut app) = demo(); let (ctx, mut app) = demo();
let bot = app.state.bots[0].id; let bot = app.state.bots[0].id;
let wait = |app: &mut App, call: &str| { let card = |app: &mut App, kind: ApprovalKind, reason: &str, key: &str| {
let (tx, rx) = std::sync::mpsc::channel(); let (tx, rx) = std::sync::mpsc::channel();
// (The same tool call asking again, as one step does: a new key each time.) // (The same tool call asking again, as one step does: a new key each time.)
app.approvals.insert(bot, crate::providers::Approval { call_id: "c0".into(), tool: "shell".into(), reason: "刪除 build".into(), grant: String::new(), reply: tx, kind: ApprovalKind::Action }); app.approvals.insert(bot, crate::providers::Approval { call_id: "c0".into(), tool: "shell".into(), reason: reason.into(), grant: "rm".into(), reply: tx, kind });
app.ask_keys.insert(bot, call.into()); app.ask_keys.insert(bot, key.into());
rx rx
}; };
let rx = wait(&mut app, "call-2"); let banner = |answer: &str, call: &str| Cmd::Answer { bot, answer: answer.into(), text: String::new(), call: call.into(), notice: true, screen: false };
app.remote_cmd(&ctx, Cmd::Answer { bot, answer: "once".into(), text: String::new(), call: "call-1".into() }); let rx = card(&mut app, ApprovalKind::Action, "刪除 build", "call-2");
app.remote_cmd(&ctx, banner("once", "call-1"));
assert!(rx.try_recv().is_err(), "an old banner doesn't allow the new request"); assert!(rx.try_recv().is_err(), "an old banner doesn't allow the new request");
assert!(app.approvals.contains_key(&bot)); assert!(app.approvals.contains_key(&bot));
assert!(app.state.bot(bot).unwrap().messages.iter().any(|m| m.note && m.text.contains("沒有用上"))); assert!(app.state.bot(bot).unwrap().messages.iter().any(|m| m.note && m.text.contains("通知上的「允許/拒絕」沒有用上")));
app.remote_cmd(&ctx, Cmd::Answer { bot, answer: "once".into(), text: String::new(), call: "call-2".into() }); // Its key, but 一律允許 (a banner has none) or a command too long for the banner: no.
app.remote_cmd(&ctx, banner("always", "call-2"));
assert!(rx.try_recv().is_err() && app.state.bot(bot).unwrap().allow_rules.is_empty());
app.remote_cmd(&ctx, banner("once", "call-2"));
assert!(matches!(rx.try_recv(), Ok(ApprovalAnswer::Once))); assert!(matches!(rx.try_recv(), Ok(ApprovalAnswer::Once)));
// A hand-off isn't answered from a banner, even with its key. let rx = card(&mut app, ApprovalKind::Action, "執行指令:\nrm -rf build\nrm -rf dist", "long");
let (tx, rx2) = std::sync::mpsc::channel(); app.remote_cmd(&ctx, banner("once", "long"));
app.approvals.insert(bot, crate::providers::Approval { call_id: "c0".into(), tool: "x".into(), reason: "登入".into(), grant: String::new(), reply: tx, kind: ApprovalKind::Handoff }); assert!(rx.try_recv().is_err(), "the banner showed only its first line");
app.ask_keys.insert(bot, "k".into()); // A hand-off or a question isn't answered from a banner, even with its key…
app.remote_cmd(&ctx, Cmd::Answer { bot, answer: "once".into(), text: String::new(), call: "k".into() }); let rx = card(&mut app, ApprovalKind::Handoff, "登入", "h");
assert!(rx2.try_recv().is_err()); app.remote_cmd(&ctx, banner("once", "h"));
// From the app itself (no request id): as before. assert!(rx.try_recv().is_err(), "允許 on a banner is never 我完成了");
let rx = wait(&mut app, "call-3"); // …but the phone's own card answers it, with that key.
app.remote_cmd(&ctx, Cmd::Answer { bot, answer: "reject".into(), text: String::new(), call: String::new() }); app.remote_cmd(&ctx, Cmd::Answer { bot, answer: "once".into(), text: String::new(), call: "h".into(), notice: false, screen: false });
assert!(matches!(rx.try_recv(), Ok(ApprovalAnswer::Reject))); assert!(matches!(rx.try_recv(), Ok(ApprovalAnswer::Once)), "我完成了 on the phone's card");
let rx = card(&mut app, ApprovalKind::Question, r#"[{"question":"哪一天?"}]"#, "q");
app.remote_cmd(&ctx, banner("reject", "q"));
assert!(rx.try_recv().is_err(), "拒絕 on a banner is never 略過");
app.remote_cmd(&ctx, Cmd::Answer { bot, answer: "answered".into(), text: r#"["週五"]"#.into(), call: "q".into(), notice: false, screen: false });
assert_eq!(rx.try_recv(), Ok(ApprovalAnswer::Answered(r#"["週五"]"#.into())));
}
/// The phone's own card (and a screen) names its card too: a page too old to send a key, or
/// a card answered and replaced since, answers nothing while the next one waits — and the
/// note says what to do about it where it came from (refresh the phone's page; update the
/// screen computer's AnyBot). With nothing waiting there is nothing to say.
#[test]
fn a_phone_answer_without_its_cards_key_answers_nothing() {
let (ctx, mut app) = demo();
let bot = app.state.bots[0].id;
let from = |screen: bool, answer: &str, call: &str| Cmd::Answer { bot, answer: answer.into(), text: String::new(), call: call.into(), notice: false, screen };
let (tx, rx) = std::sync::mpsc::channel();
app.approvals.insert(bot, crate::providers::Approval { call_id: "c0".into(), tool: "shell".into(), reason: "刪除 build".into(), grant: "rm".into(), reply: tx, kind: ApprovalKind::Action });
app.ask_keys.insert(bot, "now".into());
let last_note = |app: &App| app.state.bot(bot).unwrap().messages.iter().rev().find(|m| m.note).map(|m| m.text.clone()).unwrap_or_default();
let notes = |app: &App| app.state.bot(bot).unwrap().messages.iter().filter(|m| m.note && m.text.contains("沒有用上")).count();
app.remote_cmd(&ctx, from(false, "always", ""));
// (And when refreshing doesn't help — an account server not yet updated — the computer.)
assert!(last_note(&app).starts_with("手機上的回答沒有用上") && last_note(&app).contains("頁面太舊") && last_note(&app).contains("重新整理") && last_note(&app).contains("在電腦上回答"), "{}", last_note(&app));
app.remote_cmd(&ctx, from(false, "once", "before"));
assert!(last_note(&app).starts_with("手機上的回答沒有用上") && last_note(&app).contains("已經不在等了") && !last_note(&app).contains("頁面太舊"), "{}", last_note(&app));
// An older screen computer sends no key: refreshing does nothing there — updating does.
app.remote_cmd(&ctx, from(true, "once", ""));
assert!(last_note(&app).starts_with("螢幕電腦上的回答沒有用上") && last_note(&app).contains("設定 › 更新") && !last_note(&app).contains("重新整理"), "{}", last_note(&app));
app.remote_cmd(&ctx, from(true, "once", "before"));
assert!(last_note(&app).starts_with("螢幕電腦上的回答沒有用上") && last_note(&app).contains("已經不在等了"), "{}", last_note(&app));
assert!(rx.try_recv().is_err() && app.state.bot(bot).unwrap().allow_rules.is_empty(), "no key, or an old one: nothing");
assert_eq!(notes(&app), 4, "each one says so");
app.remote_cmd(&ctx, from(false, "reject", "now"));
assert_eq!(rx.try_recv(), Ok(ApprovalAnswer::Reject));
// Nothing waits now: an answer that comes late says nothing.
app.remote_cmd(&ctx, from(false, "once", "now"));
assert_eq!(notes(&app), 4);
}
/// A 支線's card on the phone: in its main bot's chat (`bot`), answered for the 支線
/// (`target`), with the 支線's own key — the main bot's would answer nothing (or, if the main
/// bot waits too, be refused as another card's). An answer that can't be taken is said in
/// the main bot's chat, where the 支線's card is shown: its own messages aren't shown anywhere.
#[test]
fn a_branch_card_on_the_phone_carries_its_own_key_and_target() {
let (ctx, mut app) = demo();
let main = app.state.bots[0].clone();
let mut br = main.clone();
br.id = 9001;
br.branch_of = main.id;
br.messages.clear();
app.state.branch_bots.push(br);
let card = |app: &mut App, id: u64, reason: &str, key: &str| {
let (tx, rx) = std::sync::mpsc::channel();
app.approvals.insert(id, crate::providers::Approval { call_id: "call_0".into(), tool: "shell".into(), reason: reason.into(), grant: String::new(), reply: tx, kind: ApprovalKind::Action });
app.ask_keys.insert(id, key.into());
rx
};
let main_rx = card(&mut app, main.id, "執行指令:ls", "km");
let branch_rx = card(&mut app, 9001, "執行指令:rm -rf build", "kb");
let cards = app.phone_cards(&main);
let b = cards.iter().find(|c| c["target"] == 9001).cloned().unwrap_or_default();
assert_eq!((b["bot"].as_u64(), b["key"].as_str()), (Some(main.id), Some("kb")), "{cards:?}");
let m = cards.iter().find(|c| c["target"].is_null()).cloned().unwrap_or_default();
assert_eq!(m["key"], "km", "{cards:?}");
// A stale answer for the 支線 (its last card's key): refused, said in the main chat.
app.remote_cmd(&ctx, Cmd::Answer { bot: 9001, answer: "once".into(), text: String::new(), call: "old".into(), notice: false, screen: false });
assert!(branch_rx.try_recv().is_err());
let said = |app: &App, id: u64| app.state.bot(id).unwrap().messages.iter().any(|m| m.note && m.text.contains("沒有用上"));
assert!(said(&app, main.id) && !said(&app, 9001), "the note is in the main bot's chat");
// The phone answers it as renderDock does: api/bots/{target}/answer with its key.
let target = b["target"].as_u64().unwrap_or(0);
app.remote_cmd(&ctx, Cmd::Answer { bot: target, answer: "once".into(), text: String::new(), call: b["key"].as_str().unwrap_or("").into(), notice: false, screen: false });
assert_eq!(branch_rx.try_recv(), Ok(ApprovalAnswer::Once));
assert!(main_rx.try_recv().is_err() && app.approvals.contains_key(&main.id), "the main bot's card still waits");
}
/// A card that takes another's place with the same call id (call_0 every round) and the same
/// words — the same step asking again — is published again (the view's signature changes),
/// so the phone and the screens get the new card's key: with the old one every answer would
/// be refused. A 支線's card the same.
#[test]
fn a_card_in_anothers_place_is_published_again() {
let (_ctx, mut app) = demo();
let main = app.state.bots[0].clone();
let mut br = main.clone();
br.id = 9002;
br.branch_of = main.id;
br.messages.clear();
app.state.branch_bots.push(br);
let card = |app: &mut App, id: u64, key: &str| {
let (tx, _) = std::sync::mpsc::channel();
app.approvals.insert(id, crate::providers::Approval { call_id: "call_0".into(), tool: "shell".into(), reason: "執行指令:rm -rf build".into(), grant: String::new(), reply: tx, kind: ApprovalKind::Action });
app.ask_keys.insert(id, key.into());
};
card(&mut app, main.id, "k1");
let before = app.remote_signature();
card(&mut app, main.id, "k2");
assert_ne!(app.remote_signature(), before, "the main bot's new card is published");
card(&mut app, 9002, "b1");
let before = app.remote_signature();
card(&mut app, 9002, "b2");
assert_ne!(app.remote_signature(), before, "the 支線's new card is published");
}
/// 「全部允許,之後直接操作」 on a "may I use the computer?" card: 直接操作 lets that card
/// through as it comes on, then the phone's answer for it arrives — maybe after the next card
/// is already up. That answer takes nothing, and isn't told as a stale one (the card was done).
#[test]
fn the_answer_after_direct_mode_let_its_card_through_says_nothing() {
let (ctx, mut app) = demo();
let bot = app.state.bots[0].id;
let (tx, first) = std::sync::mpsc::channel();
app.approvals.insert(bot, crate::providers::Approval { call_id: "call_0".into(), tool: "shell".into(), reason: "在你的電腦上執行任務:ls".into(), grant: String::new(), reply: tx, kind: ApprovalKind::EnableThisComputer });
app.ask_keys.insert(bot, "k1".into());
app.enable_direct_mode();
assert!(matches!(first.try_recv(), Ok(ApprovalAnswer::Always(_))), "直接操作 let it through");
let (tx, second) = std::sync::mpsc::channel();
app.approvals.insert(bot, crate::providers::Approval { call_id: "call_0".into(), tool: "shell".into(), reason: "執行指令:rm -rf build".into(), grant: "rm".into(), reply: tx, kind: ApprovalKind::Action });
app.ask_keys.insert(bot, "k2".into());
app.remote_cmd(&ctx, Cmd::Answer { bot, answer: "once".into(), text: String::new(), call: "k1".into(), notice: false, screen: false });
assert!(second.try_recv().is_err() && app.approvals.contains_key(&bot), "the next card still waits");
assert!(!app.state.bot(bot).unwrap().messages.iter().any(|m| m.note && m.text.contains("沒有用上")), "no stale-answer note");
// Any other old key still is one.
app.remote_cmd(&ctx, Cmd::Answer { bot, answer: "once".into(), text: String::new(), call: "k0".into(), notice: false, screen: false });
assert!(app.state.bot(bot).unwrap().messages.iter().any(|m| m.note && m.text.contains("沒有用上")));
} }
#[test] #[test]
@ -2148,34 +2322,44 @@ mod approval_routing_replay {
assert_eq!(first.try_recv(), Ok(ApprovalAnswer::Once)); assert_eq!(first.try_recv(), Ok(ApprovalAnswer::Once));
// BotAsks + CardShows:下一件事。 // BotAsks + CardShows:下一件事。
let second = bot_asks(&mut app, &ctx, id, "執行指令:rm -rf ~/Documents/報告", "rm"); let second = bot_asks(&mut app, &ctx, id, "執行指令:rm -rf ~/Documents/報告", "rm");
// YouTapBanner + BrainTakesAnswer:舊通知上的「允許」(sw.js:answer=once、call=d.ask)。 // YouTapBanner + BrainTakesAnswer:舊通知上的「允許」(sw.js:answer=once、call=d.ask;
app.remote_cmd(&ctx, Cmd::Answer { bot: id, answer: "once".into(), text: String::new(), call: banner_key }); // 頁面送出時加 from: "notice")。
app.remote_cmd(&ctx, Cmd::Answer { bot: id, answer: "once".into(), text: String::new(), call: banner_key, notice: true, screen: false });
assert!(second.try_recv().is_err(), "第一張卡的通知讓第二件事通過了"); assert!(second.try_recv().is_err(), "第一張卡的通知讓第二件事通過了");
assert!(app.approvals.contains_key(&id), "the second card still waits"); assert!(app.approvals.contains_key(&id), "the second card still waits");
} }
/// 已知發現 F1(AllSurfaces.cfg 的反例):手機頁面上畫的還是第一張卡,第一張已經不在了 /// F1(以前 AllSurfaces.cfg 的反例,已修好):手機頁面上畫的還是第一張卡,第一張已經不在了
/// (電腦上回答了),Bot 問了第二件事;這時在手機上按「一律允許」,第二件事不該通過, /// (電腦上回答了),Bot 問了第二件事;這時在手機上按「一律允許」,第二件事不能通過,
/// 也不該把第二件事的類別記成一律允許。螢幕電腦的回答到大腦也是同一條路(api/sync/act /// 也不能把第二件事的類別記成一律允許——不管手機送的是它畫的那張卡的 key(現在的頁面),
/// 不帶 call)。修好 F1 之後拿掉 #[ignore]。 /// 還是什麼都沒送(開了很久的舊頁面)。照舊的程式(沒帶 call 就交給那時候在等的卡)這個
/// 測試會失敗。最後,帶著第二張卡自己的 key 才算數。
#[test] #[test]
#[ignore = "已知發現 F1(不是實機測試):手機頁面和螢幕電腦的回答不帶 call。見 .claude/skills/verify-approval-routing/SKILL.md"]
fn a_phone_card_tapped_after_it_changed_answers_nothing_else() { fn a_phone_card_tapped_after_it_changed_answers_nothing_else() {
let (ctx, mut app, id) = brain("anybot-replay-page.png"); let (ctx, mut app, id) = brain("anybot-replay-page.png");
let first = bot_asks(&mut app, &ctx, id, "執行指令:npm install", "npm install"); let first = bot_asks(&mut app, &ctx, id, "執行指令:npm install", "npm install");
// PageRefreshes:手機輪詢 api/state,renderDock 畫出 approval_json 給的這張卡。 // PageRefreshes:手機輪詢 api/state,renderDock 畫出 approval_json 給的這張卡(和它的 key)。
let shown = approval_json(app.state.bot(id).unwrap(), app.approvals.get(&id).unwrap()); let shown = approval_json(app.state.bot(id).unwrap(), app.approvals.get(&id).unwrap(), app.ask_keys.get(&id).map(String::as_str).unwrap_or(""));
assert!(shown["reason"].as_str().unwrap_or("").contains("npm install"), "{shown}"); assert!(shown["reason"].as_str().unwrap_or("").contains("npm install"), "{shown}");
let seen_key = shown["key"].as_str().unwrap_or("").to_string();
assert!(!seen_key.is_empty(), "the phone gets the card's key: {shown}");
// YouAnswerOnDesk:電腦上按「允許」。 // YouAnswerOnDesk:電腦上按「允許」。
app.answer(&ctx, id, ApprovalAnswer::Once); app.answer(&ctx, id, ApprovalAnswer::Once);
assert_eq!(first.try_recv(), Ok(ApprovalAnswer::Once)); assert_eq!(first.try_recv(), Ok(ApprovalAnswer::Once));
// BotAsks + CardShows:下一件事。 // BotAsks + CardShows:下一件事。
let second = bot_asks(&mut app, &ctx, id, "執行指令:rm -rf ~/Documents/報告", "rm"); let second = bot_asks(&mut app, &ctx, id, "執行指令:rm -rf ~/Documents/報告", "rm");
// YouTapOnPage + BrainTakesAnswer:手機上還是 npm install 那張,按「一律允許」: // YouTapOnPage + BrainTakesAnswer:手機上還是 npm install 那張,按「一律允許」:
// renderDock POST {answer: "always"},remote.rs 把沒有的 call 當成 ""。 // renderDock POST {answer: "always", call: a.key};舊頁面 POST {answer: "always"}。
app.remote_cmd(&ctx, Cmd::Answer { bot: id, answer: "always".into(), text: String::new(), call: String::new() }); for call in [seen_key, String::new()] {
let got = second.try_recv(); app.remote_cmd(&ctx, Cmd::Answer { bot: id, answer: "always".into(), text: String::new(), call, notice: false, screen: false });
let rules = app.state.bot(id).map(|b| b.allow_rules.clone()).unwrap_or_default(); let got = second.try_recv();
assert!(got.is_err() && !rules.iter().any(|g| g == "rm"), "手機上看到的是 npm install;rm -rf 那張收到 {got:?},一律允許記下 {rules:?}"); let rules = app.state.bot(id).map(|b| b.allow_rules.clone()).unwrap_or_default();
assert!(got.is_err() && !rules.iter().any(|g| g == "rm"), "手機上看到的是 npm install;rm -rf 那張收到 {got:?},一律允許記下 {rules:?}");
}
assert!(app.state.bot(id).unwrap().messages.iter().any(|m| m.note && m.text.contains("沒有用上")), "the person is told");
// 第二張卡畫到手機上以後,帶它自己的 key 才算數。
let now = approval_json(app.state.bot(id).unwrap(), app.approvals.get(&id).unwrap(), app.ask_keys.get(&id).map(String::as_str).unwrap_or(""));
app.remote_cmd(&ctx, Cmd::Answer { bot: id, answer: "reject".into(), text: String::new(), call: now["key"].as_str().unwrap_or("").into(), notice: false, screen: false });
assert_eq!(second.try_recv(), Ok(ApprovalAnswer::Reject));
} }
} }

View File

@ -197,8 +197,12 @@ pub enum Cmd {
Send { bot: u64, text: String, attachments: Vec<String>, from: String, memories: Option<Vec<String>>, member: bool }, Send { bot: u64, text: String, attachments: Vec<String>, from: String, memories: Option<Vec<String>>, member: bool },
Stop { bot: u64 }, Stop { bot: u64 },
/// (`text`: the answers of a 問題卡.) /// (`text`: the answers of a 問題卡.)
/// `call`: from a notification's 允許/拒絕 — the request it was about ("" from the app). /// `call`: the key of the card it answers (on_new_approval gives each card one; the phone's
Answer { bot: u64, answer: String, text: String, call: String }, /// card, a notification and a screen all send it back). `notice`: from a notification's
/// 允許/拒絕 (`from: "notice"`), which answer only a request to allow. `screen`: it came
/// from a screen computer (api/sync/act), not a phone (api/bots/…/answer) — what to do about
/// an answer that can't be taken differs (update that AnyBot, not refresh a page).
Answer { bot: u64, answer: String, text: String, call: String, notice: bool, screen: bool },
Read { bot: u64 }, Read { bot: u64 },
NewThread { bot: u64 }, NewThread { bot: u64 },
/// The time zone of the phone the person uses (a brain on a server only knows UTC). /// The time zone of the phone the person uses (a brain on a server only knows UTC).
@ -757,7 +761,7 @@ pub fn handle(req: Req, via_relay: bool) -> Resp {
Cmd::Send { bot, text, attachments, from: String::new(), memories: if role == "owner" { picks_of(&b) } else { Some(vec![]) }, member } Cmd::Send { bot, text, attachments, from: String::new(), memories: if role == "owner" { picks_of(&b) } else { Some(vec![]) }, member }
} }
"stop" => Cmd::Stop { bot }, "stop" => Cmd::Stop { bot },
"answer" => Cmd::Answer { bot, answer: b["answer"].as_str().unwrap_or("reject").to_string(), text: b["text"].as_str().unwrap_or("").to_string(), call: b["call"].as_str().unwrap_or("").to_string() }, "answer" => Cmd::Answer { bot, answer: b["answer"].as_str().unwrap_or("reject").to_string(), text: b["text"].as_str().unwrap_or("").to_string(), call: b["call"].as_str().unwrap_or("").to_string(), notice: b["from"].as_str() == Some("notice"), screen: false },
"read" => Cmd::Read { bot }, "read" => Cmd::Read { bot },
"new" => Cmd::NewThread { bot }, "new" => Cmd::NewThread { bot },
"regenerate" => Cmd::Regenerate { bot }, "regenerate" => Cmd::Regenerate { bot },
@ -891,7 +895,7 @@ pub fn handle(req: Req, via_relay: bool) -> Resp {
member: false, member: false,
}, },
"stop" => Cmd::Stop { bot }, "stop" => Cmd::Stop { bot },
"answer" => Cmd::Answer { bot, answer: b["answer"].as_str().unwrap_or("reject").to_string(), text: b["text"].as_str().unwrap_or("").to_string(), call: b["call"].as_str().unwrap_or("").to_string() }, "answer" => Cmd::Answer { bot, answer: b["answer"].as_str().unwrap_or("reject").to_string(), text: b["text"].as_str().unwrap_or("").to_string(), call: b["call"].as_str().unwrap_or("").to_string(), notice: b["from"].as_str() == Some("notice"), screen: true },
"read" => Cmd::Read { bot }, "read" => Cmd::Read { bot },
"new" => Cmd::NewThread { bot }, "new" => Cmd::NewThread { bot },
"regenerate" => Cmd::Regenerate { bot }, "regenerate" => Cmd::Regenerate { bot },