fix: 手機頁面和螢幕電腦的回答只交給它畫出來的那張卡(F1);通知上的按鈕只答允許請求
- 每張卡的 key(on_new_approval 發的)給手機(approval_json;支線的卡用支線自己的)和螢幕電腦 (brain_pull 的 approvals → mir.keys)。手機的允許/一律允許/拒絕、「全部允許,之後直接操作」、 問題卡的送出和略過、螢幕電腦的回答都帶 call。 - Cmd::Answer:key 不是現在在等的那張卡的、或根本沒帶 key(開了很久的舊頁面、舊版螢幕電腦)→ 不收; 有卡在等時聊天寫「沒有用上」。通知送來的(from: "notice")另外要過 notice_answers——放通知按鈕和 收通知回答用同一條規則——而且只收 once/reject:絕不是「我完成了」「略過」或一律允許。 - 螢幕電腦用大腦的 key 分辨新卡(call id 會重複),自己的卡也用那把 key;手機問題卡的表單用 key 分辨;手機畫面的簽章帶 key,新卡一定送到手機。 - verify-approval-routing 跟到修好的程式:程式事實換成現在的、加上卡的種類和 NoticeNeverFinishesHandoff;AllSurfaces 通過,CanAnswer 確認手機頁面、通知、螢幕電腦都還答得到; F1 的重走測試不再 ignore(舊程式會失敗),新增 a_phone_answer_without_its_cards_key_answers_nothing、 a_screen_answers_only_the_card_it_shows;同步 commit 改成「最後一次改 coverage.tsv 的 commit」。 - 功能地圖 phone、safety 和 FEATURES.md 跟著改。 - 部署要注意:帳號伺服器(relay/)自己編進一份手機頁面。它更新以前,用帳號登入的手機送不出 key, 手機上的卡都答不了(安全,但要在電腦上答);直接連線的手機用大腦給的頁面,沒有這個問題。 已驗證: 完整 cargo test(env -u 各家金鑰、DOCKER_HOST=unix:///nonexistent、ANYBOT_HF_BASE=http://127.0.0.1:9)644 passed、0 failed,含 featuremap::、layout_audit::、tool_specs_are_locked、approval_decisions_are_characterized(鎖檔沒改);cargo clippy --bin anybot --all-targets -D warnings;deploy/ci/lint-sh.sh;verify-approval-routing 的 run.sh --replay:沒有漂移、AllSurfaces 通過(421324 個狀態)、CanAnswer 找到三個地方都答得到、5 個重走測試通過;暫時改壞兩次都抓到(大腦收沒帶 key 的回答 → AllSurfaces 違反 AllowOnlyWhatWasSeen、兩個回歸測試失敗;手機不送 key → CanAnswer 不預期地通過),改回後回到基準;verify-anybot(scratch AnyBot、假模型、無頭 Chrome 的手機頁面):手機上的允許、拒絕、問題卡照樣有用;第三張卡在等時,用第二張卡的 key、不帶 key、舊通知(from notice)各送一次都不算、聊天寫「沒有用上」、第三張卡和它的 key 還在,之後手機自己的「允許」才讓它通過(證據 target/verify-anybot/20261118-104552) 未驗證: 真的手機上的推播通知按鈕(要帳號伺服器和 Android 手機);螢幕電腦實機(要第二台電腦登入同一個帳號,只有 mirror_ui 的測試);帳號伺服器給的頁面(relay/ 要重新部署);支線的卡、需要處理卡在手機上的「我完成了」只有單元測試(scratch Bot 沒有可以交給使用者的螢幕);--ignored 的實機測試(會開真的視窗和瀏覽器,留給人跑);大腦視窗按住「允許」時卡被換掉:沒有新發現,沒改 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
e5c7461a85
commit
30c3895eac
|
|
@ -1,19 +1,23 @@
|
|||
---
|
||||
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 會拿使用者對另一件事說的「好」,去做一件他從沒看過的事(刪檔、送出、付款都可能)。
|
||||
- **RuleOnlyWhatWasSeen**:「一律允許」記到 Bot 身上的類別,一定是按下時那張卡上寫的。
|
||||
傷害:不然一個使用者沒看過的類別會被永久放行,之後同類的事都不再問。
|
||||
(在這個模型裡它壞的時候前一條一定也壞;分開寫是因為傷害不同:一次 vs 永久。)
|
||||
- **NoticeNeverFinishesHandoff**:手機通知上的「允許/拒絕」只回答「要你允許的事」,絕不會變成「需要處理」的「我完成了/跳過」。
|
||||
傷害:不然 Bot 以為你已經登入、通過驗證(其實沒有),接著在那個狀態下做事。
|
||||
- **路沒堵死**(`CanAnswer.cfg`,要「違反」`SomePlaceCannotAnswer`):有一種走法,手機頁面、手機通知、螢幕電腦的回答都各自真的交給了一張卡。
|
||||
傷害:修法要是讓某個地方再也答不了(例如手機不送 key),使用者在那裡按什麼都沒用。
|
||||
|
||||
## 什麼時候用
|
||||
|
||||
|
|
@ -24,58 +28,59 @@ Bot 要做會動到你電腦的事時,大腦放一張「允許/一律允許
|
|||
## 怎麼跑(一個指令,約 10 秒)
|
||||
|
||||
```sh
|
||||
.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 # 程式碼有沒有改過+兩個 cfg
|
||||
.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。
|
||||
- 結束碼:0 跟基準一樣;1 跟基準不一樣(新的破口,或已知發現 F1 不見了);2 工具出錯;3 跟基準一樣,但對照的程式碼改過了——結果還不能信,照「程式碼改了之後」做。
|
||||
- 結束碼:0 跟基準一樣;1 跟基準不一樣(新的破口,或某個地方再也答不了卡);2 工具出錯;3 跟基準一樣,但對照的程式碼改過了——結果還不能信,照「程式碼改了之後」做。
|
||||
- 基準(同步 commit 時的輸出):
|
||||
|
||||
```
|
||||
== 程式碼有沒有改過(對照 coverage.tsv,同步 commit 見 SKILL.md)
|
||||
沒有改:模型描述的還是現在這份程式碼。
|
||||
== Guarded:通過(界限內 1155 個狀態都看過)
|
||||
== AllSurfacesKeyed:通過(界限內 716889 個狀態都看過)
|
||||
== AllSurfaces:違反 AllowOnlyWhatWasSeen ——預期中的已知發現 F1(…)
|
||||
== AllSurfaces:通過(界限內 421324 個狀態都看過)
|
||||
== CanAnswer:違反 SomePlaceCannotAnswer ——預期中:找得到一種走法,手機頁面、通知、螢幕電腦的回答都交得出去
|
||||
TLC 的步驟(…)
|
||||
== 在真的程式上重走(--replay 才有)
|
||||
5 個都通過:真的程式也是(跟 AllSurfaces 一致)
|
||||
== 全部跟預期一樣。
|
||||
```
|
||||
|
||||
| cfg(`model/`) | 誰能回答 | 程式事實 | 預期 |
|
||||
| --- | --- | --- | --- |
|
||||
| `Guarded.cfg` | 大腦視窗、手機通知 | 照現在的程式 | 通過 |
|
||||
| `AllSurfacesKeyed.cfg` | 四個都能 | 假設手機頁面、螢幕電腦也帶那張卡的 key(F1 的修法,程式裡還沒有) | 通過:除了 F1 沒有別的破口 |
|
||||
| `AllSurfaces.cfg` | 四個都能 | 照現在的程式 | 違反:已知發現 F1 |
|
||||
| cfg(`model/`) | 檢查什麼 | 預期 |
|
||||
| --- | --- | --- |
|
||||
| `AllSurfaces.cfg` | 四個地方都能回答,照現在的程式;三條規則 | 通過 |
|
||||
| `CanAnswer.cfg` | 同一份模型,找「三個遠端都真的答到卡」的走法 | 違反 `SomePlaceCannotAnswer`(找到了) |
|
||||
|
||||
預期寫在 `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 和模型錯:**
|
||||
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`)寫一個測試,每一步對應模型的一個動作。它們示範了怎麼送 `NeedApproval`、怎麼呼叫 `answer()`、`remote_cmd(Cmd::Answer…)`、`brain_pull`、`mirror_apply`。
|
||||
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。
|
||||
2. 手機的長輪詢拿到 `api/state`,`renderDock` 畫出卡 A。
|
||||
3. 卡 A 在手機上沒被回答就不見了:你在電腦上回答了它(`answer()`),或按了停止、沒人在旁邊等超過 15 分鐘(`stop`、`watchdog`)。
|
||||
4. Bot 問下一件 B(同一輪的下一個工具呼叫,或你再傳訊息後的新一輪),`NeedApproval` 在路上。
|
||||
5. 手機上還是卡 A;你(或另一個能允許的人,例如管理員用他的手機)按「允許」或「一律允許」:`renderDock` POST `{answer: "always"}`,沒有 `call`。
|
||||
6. 大腦放上卡 B,key 換成 k2。(POST 比卡 B 早送出、晚到也行,網路就是這樣。)
|
||||
7. 大腦的 `Cmd::Answer`:`call` 是空的,跳過 key 的檢查;`grant` 讀現在這張卡(B)的;`answer()` 把 `Always(B 的 grant)` 交給卡 B,也把 B 的 grant 推進 `allow_rules`。
|
||||
1. 卡 A 放上來:`NeedApproval` → `approvals.insert`,`on_new_approval` 發 key k1。
|
||||
2. 手機的長輪詢拿到 `api/state`,`renderDock` 畫出卡 A(`approval_json` 沒給 key)。
|
||||
3. 卡 A 在手機上沒被回答就不見了:電腦上回答了(`answer()`),或按了停止、15 分鐘逾時。
|
||||
4. Bot 問下一件 B,卡 B 放上來,key 換成 k2。
|
||||
5. 手機上還是卡 A;有人按「一律允許」:`renderDock` POST `{answer: "always"}`,沒有 `call`。
|
||||
6. 大腦的 `Cmd::Answer`:`call` 是空的就跳過 key 的檢查,`grant` 讀卡 B 的,`answer()` 讓 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` 不跑。
|
||||
|
||||
會遇到的時候:兩個人都能允許(擁有者和管理員各拿一支手機)、你同時開著電腦和手機、或卡 A 被允許後 Bot 很快就問下一件。窗口是手機輪詢的延遲。
|
||||
|
||||
修法方向(沒有改,等人決定):`approval_json` 把這張卡的 ask key 給手機、`renderDock` 送成 `call`;螢幕電腦同步時拿到大腦的 key、回答時帶上(它自己的 `ask_keys` 是本機亂數,不能用)。`Cmd::Answer` 現有的檢查就會擋掉舊的回答——`AllSurfacesKeyed.cfg` 就是這個修法,模型裡通過。
|
||||
修法(這一版的程式):
|
||||
- `approval_json` 把卡的 key 給手機(支線的卡用支線自己的 key),`renderDock` 的三個按鈕、「全部允許,之後直接操作」、問題卡的送出和略過都送 `call: a.key`;問題卡的表單也用 key 分辨是哪一張(call id 會重複)。
|
||||
- 大腦給螢幕電腦的 `approvals` 帶 `key`;螢幕電腦把它記在 `mir.keys`、拿它當自己這張卡的 key(`new_approval_keyed`),回答時送 `call`;新卡用 key 分辨,不再只看 call id。舊版大腦沒給 key 時照舊(不送 call)。
|
||||
- `Cmd::Answer`:key 不是現在在等的那張卡的、或根本沒帶 key(開了很久的舊頁面、舊版螢幕電腦)→ 不收;有卡在等時聊天寫「沒有用上」。通知送來的(`from: "notice"`)另外要過 `notice_answers`——放通知按鈕和收通知回答用同一條規則——而且只收 once/reject。
|
||||
- 回歸測試:`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_screen_answers_only_the_card_it_shows`。
|
||||
|
||||
## 對照表:模型的每個動作 ↔ 程式碼
|
||||
|
||||
|
|
@ -84,68 +89,65 @@ TLC 在 `AllSurfaces.cfg` 找到的最短反例,用程式碼的話講:
|
|||
| 模型的動作 | 程式碼(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`)。 |
|
||||
| (Bot 收到回答) | `bot.wait_answer`(src/agent.rs `wait_answer`) | 收到哪個回答就是哪個;channel 斷了或按停止=拒絕。回答只會從這張卡自己的 reply 來。 |
|
||||
| `CardShows` | `brain.need_approval`、`brain.on_new_approval`(src/app.rs) | UI 執行緒一次做完:`approvals.insert`(同一個 Bot 只有一格)、`ask_keys` 換成新的亂數 key、不在 App 前面時推一則手機通知(帶這把 key)。 |
|
||||
| (Bot 收到回答) | `bot.wait_answer`(src/agent.rs) | 收到哪個回答就是哪個;channel 斷了或按停止=拒絕。回答只會從這張卡自己的 reply 來。 |
|
||||
| `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 和「允許/拒絕」。 |
|
||||
| `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()`:看到的就是現在的卡。 |
|
||||
| `PageRefreshes` | `page.approval_json`(src/app/remote_ui.rs)、`page.render_dock`(mobile/index.html) | 手機拿到的是大腦某一刻的 `approvals`,可以一直不更新;`approval_json` 給的卡沒有 key。 |
|
||||
| `YouTapOnPage` | `page.render_dock`、`remote.answer_routes`(src/remote.rs) | 按下就清掉手機上的卡,POST `{answer}`;沒有 `call`,remote.rs 把沒有的 `call` 當成 `""`。三個按鈕:允許(一次)、一律允許、拒絕。 |
|
||||
| `YouTapBanner` | `banner.notificationclick`(mobile/sw.js)、`page.banner_answer`(mobile/index.html) | 只有 allow → `once`、deny → `reject`;帶 `call = d.ask`(推通知時那張卡的 key)。同一個 Bot 新的通知蓋掉舊的。 |
|
||||
| `ScreenRefreshes` | `screen.sync`(src/app/mirror_ui.rs) | 螢幕電腦把大腦的 `approvals` 整份換進來,可以一直不更新。 |
|
||||
| `YouAnswerOnScreen` | `brain.answer` 的 `mir.on` 分支、`remote.answer_routes` | 螢幕電腦先拿掉自己的卡,送 `{"bot", "action": "answer", "answer", "text"}`,沒有 `call`。 |
|
||||
| `BrainTakesAnswer` | `brain.cmd_answer`(src/app/remote_ui.rs `Cmd::Answer`)、`brain.answer` | UI 執行緒一次做完:帶了 `call` 卻不是現在這張的 key(或卡不在)→ 寫「沒有用上」、不動;否則 `answer()` 交給現在的卡;「一律允許」的 grant 讀現在這張卡的。 |
|
||||
| `Settle`(上面幾個共用) | `brain.answer` | `approvals.remove` → `Always` 就把 grant 推進 `allow_rules` → `reply.send`。 |
|
||||
| `PageRefreshes` | `page.approval_json`、`page.view_keys`(src/app/remote_ui.rs)、`page.render_dock`、`page.question`(mobile/index.html) | 手機拿到的是大腦某一刻的 `approvals`,每張卡帶自己的 `key`(支線的卡帶支線的);可以一直不更新。 |
|
||||
| `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`、`page.open_from_hash`、`page.banner_message`(mobile/index.html) | 只有 allow → `once`、deny → `reject`;帶 `call = d.ask`(推通知時那張卡的 key)和 `from: "notice"`。同一個 Bot 新的通知蓋掉舊的。 |
|
||||
| `ScreenRefreshes` | `screen.view`、`screen.sync`(src/app/mirror_ui.rs) | 大腦給的每張卡帶 `key`;螢幕電腦把 `approvals` 整份換進來,key 記在 `mir.keys`,key 變了才算新卡;可以一直不更新。 |
|
||||
| `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.notice_answers`、`brain.answer` | UI 執行緒一次做完:有卡在等、帶了 key、key 是現在 `ask_keys` 那把(`ThisCard`),而且不是通知、或是 `notice_answers` 的卡加上 once/reject(`Fits`),才交給 `answer()`;不然不動,有卡在等時寫「沒有用上」。「一律允許」的 grant 讀現在這張卡的。 |
|
||||
| `Settle`(上面幾個共用) | `brain.answer` | `approvals.remove` → `Always` 而且是 Action 就把 grant 推進 `allow_rules` → `reply.send`。 |
|
||||
|
||||
## 程式事實(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());` |
|
||||
| `BannerKeyChecked` | TRUE | `brain.cmd_answer`:`if !call.is_empty() && !(allowable && self.ask_keys.get(&bot) == Some(&call)) {` … `return;` |
|
||||
| `PageSendsKey` | FALSE | `page.render_dock`:``api(base() + `api/bots/${(a && a.target) \|\| S.open}/answer`, {json: {answer: x.dataset.a}})`` |
|
||||
| `ScreenSendsKey` | FALSE | `brain.answer`:`self.mirror_act(serde_json::json!({"bot": bot_id, "action": "answer", "answer": a, "text": text}));` |
|
||||
| `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());` |
|
||||
| `KeyChecked` | TRUE | `brain.cmd_answer`:`self.ask_keys.get(&bot) == Some(&call)` |
|
||||
| `KeylessRefused` | TRUE | `brain.cmd_answer`:`let this_card = waiting.is_some() && !call.is_empty() && …` |
|
||||
| `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)。
|
||||
- 界限:一個 Bot;一段時間問 `N = 3` 件事;每個地方同時最多一個回答在路上(cfg 的 `CONSTRAINT OneAnswerOnTheWayPerSurface`,程式沒有這個限制);手機頁面一支(兩個人兩支手機是同一類順序);每張卡都是一般的「允許這個操作」(Action),而且都有「一律允許」的類別。
|
||||
- 假設:大腦視窗上「看到就回答」在同一個畫面格裡做完。
|
||||
- 證明的:在下面的界限裡,卡出現、卡不見、畫面同步、按下、回答到達的每一種先後順序(網路延遲任意、手機和螢幕電腦的畫面任意舊、回答可以任意晚到、手機頁面和螢幕電腦可能是更新前的舊版而不帶 key),三條規則都成立;而且手機頁面、通知、螢幕電腦的回答都還交得到卡上。
|
||||
- 界限:一個 Bot;一段時間問 `N = 3` 件事,前兩件是允許請求、第三件是「需要處理」;每個地方同時最多一個回答在路上(cfg 的 `CONSTRAINT OneAnswerOnTheWayPerSurface`,程式沒有這個限制);手機頁面一支(兩個人兩支手機是同一類順序)。
|
||||
- 假設:大腦視窗上「看到就回答」在同一個畫面格裡做完;`notice_answers` 在模型裡等於「是允許請求」(它另外擋掉太長的指令和 hooks 的改動,這兩種也只會讓通知「不答」)。
|
||||
- 沒有放進模型(這些地方改了,這個檢查不會發現):
|
||||
- 大腦視窗上按住「允許」不放、放開前卡被換成另一張:egui 的按鈕放開時才算按下,兩張卡的按鈕 id 一樣,可能也會落到新卡上。**沒驗證,建議當下一個目標。**
|
||||
- 問題卡(Question)和「需要處理」(Handoff):手機頁面上的「送出」「我完成了」也不帶 `call`,舊的「允許」落到 Handoff 上就是「我完成了」。沒驗證。
|
||||
- 大腦視窗上按住「允許」不放、放開前卡被換成另一張:egui 的按鈕放開時才算按下,兩張卡的按鈕 id 一樣,可能也會落到新卡上。沒驗證。
|
||||
- 一律放行(/always-approve)、直接操作、自動審核、hooks 替你回答的;打開直接操作時一起放行的「可以用電腦嗎」。
|
||||
- 支線(`a.target`)、群組聊天、同一個 Bot 兩輪同時在跑、`app_pending`(App 操作工具的卡)。
|
||||
- `call_id` 本身(模型用 ask key 分辨卡);`ToolStatus` 用 `call_id` 清卡;Enter/Esc 的 0.6 秒等待和對話框、游標的規則(那些有 `app::tests` 的測試)。
|
||||
- 群組聊天、同一個 Bot 兩輪同時在跑、`app_pending`(App 操作工具的卡;它也走 `on_new_approval`,所以一樣有 key)。
|
||||
- 問題卡的內容(模型把問題卡當成一般的卡:送出/略過都是一個帶 key 的回答)。
|
||||
- Enter/Esc 的 0.6 秒等待和對話框、游標的規則(那些有 `app::tests` 的測試)。
|
||||
- 手機通知什麼時候被別的通知蓋掉(模型讓舊通知一直留著,比真的寬)。
|
||||
- 帳號伺服器(`relay/`)自己編進去一份手機頁面:伺服器沒更新前,用帳號登入的手機送不出 key,回答全都不收(安全,但答不了)。這是部署的事,不在模型裡。
|
||||
|
||||
## 覆蓋紀錄和同步 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` 第一步重算、比對。
|
||||
- 看同步 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)
|
||||
|
||||
1. 對每個「改過了」的段落跑 `drift.py … --show <id>`,跟「對照表」那一列、「程式事實」那一列比:模型假設的事還成立嗎?還是一口氣做完嗎?
|
||||
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 的,抓不到這個。
|
||||
3. 跑 `run.sh`;不預期的違反照「讀結果」分辨,用 `/pstack:statechart` 讀。
|
||||
4. 確認模型描述現在的程式之後才跑 `drift.py … --rehash`,再把上面的同步 commit 改成你確認時的 commit。沒確認就不要動同步 commit,也不要 rehash。
|
||||
5. 段落搬家或改名(「找不到」)→ 改 `coverage.tsv` 那一行的「開始」「結束」,再走 1–4。新增了能回答卡片的地方 → 在模型加一個動作、在 `coverage.tsv` 加它的段落、在對照表加一列。
|
||||
|
||||
## 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。
|
||||
2. 不成立 → 改模型:程式事實就改兩個 cfg 的那個常數,別的就改 `ApprovalRouting.tla` 裡那個動作。是刻意的行為改變,連 `run.sh` 的 `EXPECT` 和這份檔一起改。不要改規則。
|
||||
例:`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 --replay`;不預期的結果照「讀結果」分辨,用 `/pstack:statechart` 讀。
|
||||
4. 確認模型描述現在的程式之後才跑 `drift.py … --rehash`,跟程式碼放進同一個 commit——那個 commit 就是新的同步 commit。沒確認就不要 rehash。
|
||||
5. 段落搬家或改名(「找不到」)→ 改 `coverage.tsv` 那一行的「開始」「結束」,再走 1–4。新增了能回答卡片的地方 → 在模型加一個動作、在 `coverage.tsv` 加它的段落、在對照表加一列、在 `REPLAY` 加它的測試。
|
||||
|
||||
## 檔案
|
||||
|
||||
- `model/ApprovalRouting.tla`:模型(每個動作的註解寫了對應的程式碼)。
|
||||
- `model/Guarded.cfg`、`model/AllSurfaces.cfg`、`model/AllSurfacesKeyed.cfg`:三種情況。
|
||||
- `model/AllSurfaces.cfg`、`model/CanAnswer.cfg`:三條規則;路沒堵死。
|
||||
- `model/statechart-view.ts`:給 `/pstack:statechart` 的白話標籤。
|
||||
- `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`;`src/app/mirror_ui.rs` 的 `tests::a_screen_answers_only_the_card_it_shows`。
|
||||
|
|
|
|||
|
|
@ -3,16 +3,23 @@
|
|||
desk.approval_body src/app.rs block ^ fn approval_body\( } fd8c84806d8b8867c011f463c3753f1960824a5df46535031ba1c0aaa5263d07
|
||||
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.on_new_approval src/app.rs block ^ fn on_new_approval\( } 64c8f015a02fc27d83d391928cd173e5440ab7c84b942af2969a41834dc35b5c
|
||||
brain.answer src/app.rs block ^ fn answer\(&mut self, ctx: &egui::Context, bot_id: u64, answer: ApprovalAnswer\) } 920ddafb3d2e905a08c2780f0bab8322b95ee8e292fc186007635d373c9bb48b
|
||||
brain.on_new_approval src/app.rs block ^ fn on_new_approval\( } c110c0341ae1b8cbcc59d0b4dc1dba7a2b8006885837e515ea6c0ef23a195205
|
||||
brain.new_approval_keyed src/app.rs block ^ fn new_approval_keyed\( } 5a6a4fd51e35a5f23b05d81e9974c2a00c2dcf511051f2adf0ce94d07b5583aa
|
||||
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.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
|
||||
page.approval_json src/app/remote_ui.rs block ^fn approval_json\( } 344450dd2ab853a7ff6422c9b2385fda22d7c50f4ff94d5fafff43b947975eac
|
||||
page.render_dock mobile/index.html block ^function renderDock\(\) \{ } dcd232baf47e82373b818f71b9a9525545d0b1ee70797631612d5434378cf331
|
||||
page.banner_answer mobile/index.html block ^ if \(S\.answer && S\.token\) \{ } 77366a55d5aaf8443edbac2825c4455d2462e18a2cb9d1ab23484ce748fbe07b
|
||||
brain.cmd_answer src/app/remote_ui.rs block ^ Cmd::Answer \{ bot, answer, text, call, notice \} => \{ } 9fc6b24edc6f4ed3414bf5d9b78171db44f5f68f085bcb80c6d43674680dadbf
|
||||
page.approval_json src/app/remote_ui.rs block ^fn approval_json\( } a5170e3eb427a05a10941d43ca7f43355955c4225cb361843d2435051c8a29c1
|
||||
page.view_keys src/app/remote_ui.rs grep ^\s+(view\.approvals\.push\(approval_json|let mut j = approval_json) - 710e5d4ae9cfd420558d5921a5dd85a8764810d2bcb4ab2521b76dfb84df7977
|
||||
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
|
||||
remote.answer_routes src/remote.rs grep => Cmd::Answer \{ - c3bfd841a0a304186b2a19701b56114d021956bd3b27e79310a26f40be6a59ca
|
||||
screen.sync src/app/mirror_ui.rs until ^ let mut waiting = HashMap::new\(\); self\.approvals\.retain\(\|id, _\| keep\.contains\(id\)\); b40f54c3e33188e3b5b1a02d11c177641f1b358eb7e4b192f799d2381f49fa55
|
||||
remote.answer_routes src/remote.rs grep => Cmd::Answer \{ - 16cca4132dfe07069f4250a03278381aba3b789d3e94d695644bf46051fc0b0e
|
||||
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.ask_person src/agent/steps.rs block ^ pub fn ask_person\( } 564d1660a7a3655a7ad995b8a3b578235fc3ea21a40ad7e45e454e352e2af7c5
|
||||
|
|
|
|||
|
Can't render this file because it has a wrong number of fields in line 2.
|
|
|
@ -1,16 +1,19 @@
|
|||
\* 四個地方都能回答,照現在的程式碼。已知發現 F1:手機頁面和螢幕電腦的回答不帶 call,
|
||||
\* 會落在後來的卡上。修好之前這個 cfg 會違反規則;run.sh 只確認違反的是 F1 那一種。
|
||||
\* 四個地方都能回答,照現在的程式碼(F1 修好之後):每個回答都帶那張卡的 key,大腦只交給那張卡;
|
||||
\* 更新前就開著的舊手機頁面、舊版螢幕電腦不帶 key,大腦不收。要通過。
|
||||
SPECIFICATION Spec
|
||||
CONSTANTS
|
||||
N = 3
|
||||
Surfaces = {"desk", "page", "banner", "screen"}
|
||||
FreshKeyPerCard = TRUE
|
||||
BannerKeyChecked = TRUE
|
||||
PageSendsKey = FALSE
|
||||
ScreenSendsKey = FALSE
|
||||
KeyChecked = TRUE
|
||||
KeylessRefused = TRUE
|
||||
NoticeFitsChecked = TRUE
|
||||
PageSendsKey = TRUE
|
||||
ScreenSendsKey = TRUE
|
||||
INVARIANTS
|
||||
TypeOK
|
||||
AllowOnlyWhatWasSeen
|
||||
RuleOnlyWhatWasSeen
|
||||
NoticeNeverFinishesHandoff
|
||||
CONSTRAINT
|
||||
OneAnswerOnTheWayPerSurface
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
@ -7,18 +7,24 @@
|
|||
(* 大腦(app.rs 的 App)把卡放在 approvals[bot],每張新卡在 on_new_approval *)
|
||||
(* 發一把 ask_keys[bot]。能回答的地方有四個: *)
|
||||
(* desk 大腦自己的視窗(approval_dock/approval_body → answer()) *)
|
||||
(* page 手機頁面上的卡(mobile/index.html renderDock) *)
|
||||
(* page 手機頁面上的卡(mobile/index.html renderDock、renderQuestion) *)
|
||||
(* banner 手機通知上的「允許/拒絕」(mobile/sw.js,帶 d.ask = key) *)
|
||||
(* screen 螢幕電腦(mirror:answer() 的 mir.on 分支) *)
|
||||
(* desk 在同一個畫面格裡看到卡、處理按鍵、呼叫 answer();另外三個看到的是 *)
|
||||
(* 某個時候抄過去的卡,回答要經過網路,到大腦時才由 remote_ui.rs 的 *)
|
||||
(* Cmd::Answer 交給「那時候」在等的卡。 *)
|
||||
(* 某個時候抄過去的卡(和它的 key),回答要經過網路,到大腦時由 *)
|
||||
(* remote_ui.rs 的 Cmd::Answer 決定收不收。手機頁面可能是更新前就開著的舊 *)
|
||||
(* 頁面、螢幕電腦可能是舊版:它們的回答不帶 key。 *)
|
||||
(* *)
|
||||
(* 卡有兩種:「允許這個操作」(allow:Action、要開電腦工具…)和「需要處理」*)
|
||||
(* (handoff:按鈕是「我完成了/跳過」,送出去也是 once/reject)。 *)
|
||||
(* *)
|
||||
(* 規則(cfg 的 INVARIANT): *)
|
||||
(* AllowOnlyWhatWasSeen 「允許」「一律允許」只會讓按的人當時看到的那張 *)
|
||||
(* 卡通過。 *)
|
||||
(* AllowOnlyWhatWasSeen 「允許」「一律允許」(在需要處理的卡上是「我完成 *)
|
||||
(* 了」)只會讓按的人當時看到的那張卡通過。 *)
|
||||
(* RuleOnlyWhatWasSeen 「一律允許」記到 Bot 身上的類別,一定是按的人當 *)
|
||||
(* 時看到的那張卡上寫的。 *)
|
||||
(* NoticeNeverFinishesHandoff 手機通知上的按鈕只回答「允許這個操作」的 *)
|
||||
(* 卡,絕不會變成「我完成了」。 *)
|
||||
(* *)
|
||||
(* 每個動作對應哪段程式碼:.claude/skills/verify-approval-routing/SKILL.md *)
|
||||
(* 的「對照表」。程式碼一改,先照那張表重新對過,再相信這裡的結果。 *)
|
||||
|
|
@ -26,22 +32,29 @@
|
|||
EXTENDS Naturals, FiniteSets
|
||||
|
||||
CONSTANTS
|
||||
N, \* 這段時間 Bot 會問幾次(請求 1..N,一個問完才問下一個)
|
||||
Surfaces, \* 有哪些地方能回答:{"desk", "page", "banner", "screen"} 的子集
|
||||
N, \* 這段時間 Bot 會問幾次(請求 1..N,一個問完才問下一個)
|
||||
Surfaces, \* 有哪些地方能回答:{"desk", "page", "banner", "screen"} 的子集
|
||||
\* 程式事實:每一條都對應程式裡的一行,見 SKILL.md「程式事實」。
|
||||
FreshKeyPerCard, \* on_new_approval:每張新卡一把新的 ask_keys(random_hex)
|
||||
BannerKeyChecked, \* Cmd::Answer:帶 call 的回答,call 要等於現在的 ask_keys 才算
|
||||
PageSendsKey, \* renderDock 的按鈕:POST 的 JSON 裡有 call
|
||||
ScreenSendsKey \* answer() 的 mir.on 分支:mirror_act 的 JSON 裡有 call
|
||||
FreshKeyPerCard, \* on_new_approval:每張新卡一把新的 ask_keys(random_hex)
|
||||
KeyChecked, \* Cmd::Answer:帶 key 的回答,key 要是現在在等的那張卡的才算
|
||||
KeylessRefused, \* Cmd::Answer:沒帶 key 的回答(舊頁面、舊版螢幕電腦)不算
|
||||
NoticeFitsChecked, \* Cmd::Answer:通知上的回答只收 notice_answers 的卡、只收 once/reject
|
||||
PageSendsKey, \* 手機頁面(renderDock、renderQuestion)送出 call = 那張卡的 key
|
||||
ScreenSendsKey \* 螢幕電腦 answer()(mir.on)送出 call = 大腦給那張卡的 key
|
||||
|
||||
None == 0 \* 沒有卡/沒有 key
|
||||
NoView == <<None, None>> \* 畫面上沒有卡;有卡時是 <<請求, 那張卡的 key>>
|
||||
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:允許/一律允許/拒絕
|
||||
PageButtons == {"once", "always", "reject"} \* renderDock:允許一次/一律允許/拒絕
|
||||
BannerButtons == {"once", "reject"} \* sw.js:allow → once、deny → reject
|
||||
\* 卡上的按鈕(大腦視窗 approval_body/handoff_card、手機 renderDock、螢幕電腦一樣):
|
||||
Buttons(r) == IF Kind(r) = "handoff" THEN {"once", "reject"} ELSE {"once", "always", "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
|
||||
bot, \* Bot 那一邊:"thinking" 下一步還沒問、"sent" NeedApproval 在路上、
|
||||
|
|
@ -50,17 +63,21 @@ VARIABLES
|
|||
card, \* 大腦的 approvals[bot]:正在等的請求,None 表示沒有
|
||||
askKey, \* 大腦的 ask_keys[bot](卡被回答後不清掉)
|
||||
keys, \* 發過幾把 key(新 key 就是下一個號碼)
|
||||
page, \* 手機頁面上畫的卡(S.approvals)
|
||||
screen, \* 螢幕電腦上畫的卡(它自己的 approvals,從大腦同步來)
|
||||
page, \* 手機頁面上畫的卡(S.approvals,含 key)
|
||||
screen, \* 螢幕電腦上畫的卡(它的 approvals 和 mir.keys,從大腦同步來)
|
||||
banner, \* 手機通知上的卡(同一個 Bot 新的通知蓋掉舊的:tag "bot-<id>")
|
||||
inflight, \* 已經送出、大腦還沒處理的回答
|
||||
allowed, \* 記錄:<<讓哪個請求通過, 按的人看到的請求>>
|
||||
rules \* 記錄:<<一律允許記下的類別, 按的人看到的請求>>
|
||||
\* 記錄(程式裡沒有這些值,只拿來檢查規則;規則成立時一直是 FALSE,不讓狀態變多):
|
||||
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)
|
||||
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 ==
|
||||
/\ bot \in {"thinking", "sent", "waiting", "done"}
|
||||
|
|
@ -70,8 +87,8 @@ TypeOK ==
|
|||
/\ keys \in 0..N
|
||||
/\ page \in Views /\ screen \in Views /\ banner \in Views
|
||||
/\ inflight \subseteq Msg
|
||||
/\ allowed \subseteq (1..N) \X (1..N)
|
||||
/\ rules \subseteq (1..N) \X (1..N)
|
||||
/\ wrongAllow \in BOOLEAN /\ wrongRule \in BOOLEAN /\ noticeOnHandoff \in BOOLEAN
|
||||
/\ landedFrom \subseteq {"page", "banner", "screen"}
|
||||
|
||||
Init ==
|
||||
/\ bot = "thinking"
|
||||
|
|
@ -83,16 +100,20 @@ Init ==
|
|||
/\ screen = NoView
|
||||
/\ banner = NoView
|
||||
/\ inflight = {}
|
||||
/\ allowed = {}
|
||||
/\ rules = {}
|
||||
/\ wrongAllow = FALSE
|
||||
/\ wrongRule = FALSE
|
||||
/\ noticeOnHandoff = FALSE
|
||||
/\ landedFrom = {}
|
||||
|
||||
(* 大腦把回答交給「現在在等的那張卡」:app.rs answer() — *)
|
||||
(* approvals.remove(&bot_id);Always 就把 g 推進 b.allow_rules; *)
|
||||
(* a.reply.send(answer)。Bot 的 wait_answer 收到後往下做。 *)
|
||||
(* `seen` 是按的人當時看到的請求:只拿來寫記錄,程式裡沒有這個值。 *)
|
||||
Settle(ans, seen) ==
|
||||
/\ allowed' = IF ans \in Allow THEN allowed \cup {<<card, seen>>} ELSE allowed
|
||||
/\ rules' = IF ans = "always" THEN rules \cup {<<Grant(card), seen>>} ELSE rules
|
||||
(* approvals.remove(&bot_id);Always 而且是 Action 就把 g 推進 *)
|
||||
(* b.allow_rules;a.reply.send(answer)。Bot 的 wait_answer 收到後往下做。 *)
|
||||
(* `seen`(按的人看到的請求)、`from`("desk" 是大腦自己的視窗)只拿來寫記錄。*)
|
||||
Settle(ans, seen, from) ==
|
||||
/\ wrongAllow' = (wrongAllow \/ (ans \in Allow /\ card # seen))
|
||||
/\ 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
|
||||
/\ bot' = IF asked = N THEN "done" ELSE "thinking"
|
||||
|
||||
|
|
@ -103,11 +124,12 @@ BotAsks ==
|
|||
/\ asked < N
|
||||
/\ asked' = asked + 1
|
||||
/\ 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),接著 *)
|
||||
(* on_new_approval:ask_keys.insert(bot_id, 新 key);不在 App 前面時推一則 *)
|
||||
(* 手機通知(remote::notify_approval,帶這把 key)。 *)
|
||||
(* on_new_approval → new_approval_keyed:ask_keys.insert(bot_id, 新 key); *)
|
||||
(* 不在 App 前面時推一則手機通知——notice_answers 的卡(允許請求)才帶 *)
|
||||
(* 這把 key 和「允許/拒絕」,其他的只是「打開聊天」。 *)
|
||||
CardShows ==
|
||||
/\ bot = "sent"
|
||||
/\ bot' = "waiting"
|
||||
|
|
@ -116,8 +138,8 @@ CardShows ==
|
|||
THEN /\ keys' = keys + 1
|
||||
/\ askKey' = keys + 1
|
||||
ELSE UNCHANGED <<keys, askKey>>
|
||||
/\ banner' \in IF "banner" \in Surfaces THEN {banner, <<asked, askKey'>>} ELSE {banner}
|
||||
/\ UNCHANGED <<asked, page, screen, inflight, allowed, rules>>
|
||||
/\ banner' \in IF "banner" \in Surfaces /\ Kind(asked) = "allow" THEN {banner, <<asked, askKey'>>} ELSE {banner}
|
||||
/\ UNCHANGED <<asked, page, screen, inflight, wrongAllow, wrongRule, noticeOnHandoff, landedFrom>>
|
||||
|
||||
(* 卡沒被回答就不見了:按停止、重新啟動 Bot、沒人在旁邊等超過 15 分鐘 *)
|
||||
(* (watchdog)。approvals.remove 丟掉 reply,wait_answer 拿到 Err → Reject;*)
|
||||
|
|
@ -127,75 +149,77 @@ TurnStops ==
|
|||
/\ bot \in {"sent", "waiting"}
|
||||
/\ card' = None
|
||||
/\ 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),同一格裡的 *)
|
||||
(* 按鈕或 Enter/Esc 直接呼叫 answer()。看到的就是現在的卡。 *)
|
||||
(* 大腦自己的視窗:approval_dock 畫出這張卡(approval_body,需要處理的是 *)
|
||||
(* handoff_card),同一格裡的按鈕或 Enter/Esc 直接呼叫 answer()。看到的就是 *)
|
||||
(* 現在的卡。 *)
|
||||
YouAnswerOnDesk ==
|
||||
/\ "desk" \in Surfaces
|
||||
/\ 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>>
|
||||
|
||||
(* 手機頁面的長輪詢 api/state 帶回 approvals(approval_json),apply() *)
|
||||
(* → renderDock 重畫。 *)
|
||||
(* 手機頁面的長輪詢 api/state 帶回 approvals(approval_json,含這張卡的 *)
|
||||
(* key),apply() → renderDock 重畫。 *)
|
||||
PageRefreshes ==
|
||||
/\ "page" \in Surfaces
|
||||
/\ 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 ==
|
||||
/\ "page" \in Surfaces
|
||||
/\ page # NoView
|
||||
/\ \E ans \in PageButtons :
|
||||
inflight' = inflight \cup {[from |-> "page", ans |-> ans,
|
||||
key |-> IF PageSendsKey THEN page[2] ELSE None,
|
||||
seen |-> page[1]]}
|
||||
/\ \E ans \in Buttons(page[1]), k \in PageKeys(page) :
|
||||
inflight' = inflight \cup {[from |-> "page", ans |-> ans, key |-> k, seen |-> page[1], notice |-> FALSE]}
|
||||
/\ 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 關掉通知, *)
|
||||
(* 打開頁面帶 answer 和 call = d.ask,apply() POST 出去。 *)
|
||||
(* 頁面 POST {answer, call: d.ask, from: "notice"}。 *)
|
||||
YouTapBanner ==
|
||||
/\ banner # NoView
|
||||
/\ \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
|
||||
/\ 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 ==
|
||||
/\ "screen" \in Surfaces
|
||||
/\ 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, *)
|
||||
(* mirror_act {"bot", "action": "answer", "answer", "text"} 送到大腦的 *)
|
||||
(* api/sync/act。 *)
|
||||
(* mirror_act {"bot", "action": "answer", "answer", "text", "call"} 送到 *)
|
||||
(* 大腦的 api/sync/act;舊版螢幕電腦不帶 call。 *)
|
||||
YouAnswerOnScreen ==
|
||||
/\ "screen" \in Surfaces
|
||||
/\ screen # NoView
|
||||
/\ \E ans \in DeskButtons :
|
||||
inflight' = inflight \cup {[from |-> "screen", ans |-> ans,
|
||||
key |-> IF ScreenSendsKey THEN screen[2] ELSE None,
|
||||
seen |-> screen[1]]}
|
||||
/\ \E ans \in Buttons(screen[1]), k \in ScreenKeys(screen) :
|
||||
inflight' = inflight \cup {[from |-> "screen", ans |-> ans, key |-> k, seen |-> screen[1], notice |-> FALSE]}
|
||||
/\ 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 ==
|
||||
/\ \E m \in inflight :
|
||||
/\ inflight' = inflight \ {m}
|
||||
/\ IF m.key # None /\ BannerKeyChecked /\ ~(card # None /\ askKey = m.key)
|
||||
THEN UNCHANGED <<bot, card, allowed, rules>>
|
||||
ELSE IF card = None
|
||||
THEN UNCHANGED <<bot, card, allowed, rules>>
|
||||
ELSE Settle(m.ans, m.seen)
|
||||
/\ IF ThisCard(m) /\ Fits(m)
|
||||
THEN Settle(m.ans, m.seen, m.from)
|
||||
ELSE UNCHANGED <<bot, card, wrongAllow, wrongRule, noticeOnHandoff, landedFrom>>
|
||||
/\ UNCHANGED <<asked, askKey, keys, page, screen, banner>>
|
||||
|
||||
(* 不再問了,什麼都不變(讓 TLC 不把結束當成卡死)。 *)
|
||||
|
|
@ -223,10 +247,18 @@ Spec == Init /\ [][Next]_vars
|
|||
OneAnswerOnTheWayPerSurface ==
|
||||
\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)
|
||||
|
||||
=============================================================================
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -1,14 +1,14 @@
|
|||
// /pstack:statechart 讀 ApprovalRouting 的結果時用的白話標籤(照 pstack 0.15.43 的 view 格式寫;
|
||||
// /pstack:statechart 現在的說明不一樣時,照它的說明改這個檔)。
|
||||
type Pair = { 1: number; 2: number };
|
||||
type Msg = { from: string; ans: string; key: number; seen: number };
|
||||
type V = { bot: string; card: number; page: Pair; screen: Pair; banner: Pair; inflight: Msg[]; allowed: Pair[]; rules: Pair[] };
|
||||
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[]; wrongAllow: boolean; wrongRule: boolean; noticeOnHandoff: boolean };
|
||||
|
||||
export const title = "等你允許的卡片:回答落在哪一張";
|
||||
|
||||
export const state = (v: V) => {
|
||||
const wrong = v.allowed.some((p) => p[1] !== p[2]);
|
||||
const brain = wrong ? "讓沒看到的卡通過了" : v.card !== 0 ? "有一張卡在等" : v.bot === "sent" ? "新的請求在路上" : "沒有卡在等";
|
||||
const wrong = v.wrongAllow || v.wrongRule ? "讓沒看到的卡通過了" : v.noticeOnHandoff ? "通知的按鈕回答了需要處理的卡" : "";
|
||||
const brain = wrong || (v.card !== 0 ? "有一張卡在等" : v.bot === "sent" ? "新的請求在路上" : "沒有卡在等");
|
||||
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 sent = v.inflight.length === 0 ? "沒有" : v.inflight.some((m) => m.seen !== v.card) ? "給舊卡的回答" : "給現在這張的回答";
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
#!/bin/sh
|
||||
# 驗證「等你允許的卡片」的回答路由(TLA+ 模型+程式碼有沒有改過)。
|
||||
# 用法:.claude/skills/verify-approval-routing/run.sh [--replay]
|
||||
# --replay 另外在真的程式上重走模型的反例(cargo test,第一次要編譯)。
|
||||
# 結束碼:0 跟預期一樣;1 結果跟預期不一樣(新的破口,或已知發現不見了);
|
||||
# --replay 另外在真的程式上重走模型的步驟(cargo test,第一次要編譯)。
|
||||
# 結束碼:0 跟預期一樣;1 結果跟預期不一樣(新的破口,或某個地方再也答不了卡);
|
||||
# 2 工具出錯;3 結果跟預期一樣,但模型對照的程式碼改過了(結果還不能信)。
|
||||
set -u
|
||||
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"
|
||||
jar="$tools/tla2tools-$TLA_VERSION.jar"
|
||||
|
||||
# 每個 cfg 預期的結果:pass 通過;fail 違反規則(AllSurfaces:已知發現 F1,手機頁面、
|
||||
# 螢幕電腦的回答不帶 call)。AllSurfacesKeyed 排在 AllSurfaces 前面:它通過,才能說
|
||||
# AllSurfaces 的違反只是 F1。
|
||||
EXPECT="Guarded:pass AllSurfacesKeyed:pass AllSurfaces:fail"
|
||||
# 每個 cfg 預期的結果:AllSurfaces 三條規則都要通過;CanAnswer 要「違反」它唯一的那條
|
||||
# (SomePlaceCannotAnswer)——那是 TLC 找到一種走法,手機頁面、手機通知、螢幕電腦的回答
|
||||
# 都各自交給了一張卡,證明修法沒有把路堵死。
|
||||
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"
|
||||
|
||||
say() { printf '%s\n' "$*"; }
|
||||
|
||||
|
|
@ -53,7 +56,7 @@ drift=$?
|
|||
[ $drift -eq 0 ] && say " 沒有改:模型描述的還是現在這份程式碼。"
|
||||
|
||||
unexpected=0
|
||||
keyed_ok=0; guarded=; everywhere=
|
||||
everywhere=
|
||||
for pair in $EXPECT; do
|
||||
cfg=${pair%%:*}; want=${pair#*:}
|
||||
log="$out/$cfg.out"
|
||||
|
|
@ -66,51 +69,36 @@ for pair in $EXPECT; do
|
|||
else
|
||||
say "== ${cfg}:TLC 出錯,看 ${log}"; tail -20 "$log"; exit 2
|
||||
fi
|
||||
[ "$cfg" = AllSurfacesKeyed ] && [ "$result" = pass ] && keyed_ok=1
|
||||
[ "$cfg" = Guarded ] && guarded=$result
|
||||
[ "$cfg" = AllSurfaces ] && everywhere=$result
|
||||
if [ "$result" = "$want" ] && { [ "$want" = pass ] || [ $keyed_ok -eq 1 ]; }; then
|
||||
[ "$want" = fail ] && line="${line} ——預期中的已知發現 F1(AllSurfacesKeyed 通過,所以只差在手機頁面、螢幕電腦不帶 call)"
|
||||
say "== ${cfg}:${line}"
|
||||
else
|
||||
unexpected=1
|
||||
if [ "$want" = pass ]; then
|
||||
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
|
||||
case "$cfg/$result/$want" in
|
||||
CanAnswer/fail/fail) say "== ${cfg}:${line} ——預期中:找得到一種走法,手機頁面、通知、螢幕電腦的回答都交得出去" ;;
|
||||
CanAnswer/pass/fail) unexpected=1; say "== ${cfg}:${line} ——不預期!有個地方(手機頁面、通知或螢幕電腦)的回答再也交不到卡上。照 SKILL.md「讀結果」。" ;;
|
||||
*/pass/pass) say "== ${cfg}:${line}" ;;
|
||||
*) unexpected=1; say "== ${cfg}:${line} ——不預期!這是新的破口,或模型錯了。照 SKILL.md「讀結果」分辨。" ;;
|
||||
esac
|
||||
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"
|
||||
say " 完整輸出:${log}"
|
||||
fi
|
||||
done
|
||||
|
||||
if [ "${1:-}" = "--replay" ]; then
|
||||
say "== 在真的程式上重走(cargo test approval_routing_replay)"
|
||||
(cd "$root" && cargo test --bin anybot approval_routing_replay -- --include-ignored >"$out/replay.out" 2>&1)
|
||||
if grep -q "an_old_banner_does_not_allow_the_next_card ... ok" "$out/replay.out"; then banner=pass
|
||||
elif grep -q "an_old_banner_does_not_allow_the_next_card ... FAILED" "$out/replay.out"; then banner=fail
|
||||
else say " cargo test 沒跑出結果,看 ${out}/replay.out"; exit 2; fi
|
||||
if grep -q "a_phone_card_tapped_after_it_changed_answers_nothing_else ... ok" "$out/replay.out"; then page=pass
|
||||
elif grep -q "a_phone_card_tapped_after_it_changed_answers_nothing_else ... FAILED" "$out/replay.out"; then page=fail
|
||||
else say " cargo test 沒跑出結果,看 ${out}/replay.out"; exit 2; fi
|
||||
# 真的程式跟模型要說同一件事:通過對通過、違反對失敗。
|
||||
case "$banner/$guarded" in
|
||||
pass/pass) say " 舊通知不會讓下一張卡通過:真的程式也是(跟 Guarded 一致)" ;;
|
||||
fail/fail) say " 真的程式也走得出 Guarded 的反例:$(grep -m1 '第一張卡的通知讓第二件事通過了' "$out/replay.out" | sed 's/^ *//')——是真的 bug" ;;
|
||||
pass/fail) unexpected=1; say " 真的程式走不出 Guarded 的反例:先當成模型錯(照 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" ;;
|
||||
say "== 在真的程式上重走(cargo test:${REPLAY})"
|
||||
# shellcheck disable=SC2086
|
||||
(cd "$root" && cargo test --bin anybot -- $REPLAY >"$out/replay.out" 2>&1)
|
||||
if ! grep -q "^test result:" "$out/replay.out"; then say " cargo test 沒跑出結果,看 ${out}/replay.out"; exit 2; fi
|
||||
passed=$(grep -c " \.\.\. ok$" "$out/replay.out")
|
||||
failed=$(grep " \.\.\. FAILED$" "$out/replay.out" | sed 's/^test //; s/ \.\.\. FAILED$//')
|
||||
# 真的程式跟模型要說同一件事:AllSurfaces 通過 ↔ 測試都過;違反 ↔ 有測試沒過。
|
||||
if [ -z "$failed" ] && [ "$passed" -ge 5 ]; then real=pass; else real=fail; fi
|
||||
case "$real/$everywhere" in
|
||||
pass/pass) say " ${passed} 個都通過:真的程式也是(跟 AllSurfaces 一致)" ;;
|
||||
fail/fail) unexpected=1; say " 真的程式也走得出 AllSurfaces 的反例——是真的 bug。沒過的有:"; printf '%s\n' "$failed" | sed 's/^/ /' ;;
|
||||
fail/pass) unexpected=1; say " 真的程式沒過、模型卻說 AllSurfaces 通過:模型漏了東西,或測試壞了。沒過的有:"; printf '%s\n' "$failed" | sed 's/^/ /' ;;
|
||||
pass/fail) unexpected=1; say " 真的程式走不出 AllSurfaces 的反例:先當成模型錯(照 SKILL.md「讀結果」),或這幾個測試沒走到那條路。" ;;
|
||||
esac
|
||||
[ "$real" = pass ] || say " 看 ${out}/replay.out"
|
||||
fi
|
||||
|
||||
if [ $unexpected -ne 0 ]; then exit 1; fi
|
||||
|
|
|
|||
|
|
@ -2142,6 +2142,7 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開)
|
|||
- 思考過程和工具步驟可以展開,看得到每步的結果;一輪做完會收起來;
|
||||
- 訊息下方:複製、重新產生;長按:複製、引用回覆、重新產生、重新送出、表情回應;
|
||||
- 允許請求卡片:允許一次、一律允許、拒絕,以及「全部允許,之後直接操作」;Bot 需要你接手時有電腦畫面縮圖;
|
||||
- 卡片(允許、需要處理、問題卡)只答它畫出來的那一張:回答帶著那張卡的編號,大腦只交給那張卡。那張已經被回答(電腦上、另一支手機上)、被停止、或換成了下一張時,按了不算,聊天裡留一行「手機(或螢幕電腦)上的回答沒有用上…」;開了很久沒重新整理的舊頁面送不出編號,也不算(重新整理再按)。螢幕電腦上的卡也一樣。以前沒帶編號,舊卡上的「允許」「一律允許」會落到後來的那張;
|
||||
- 輸入:工作中再傳是插話(顯示排隊)、空白時送出鍵變停止、附加照片/檔案(最大 30 MB)、拍照、語音輸入、建議問題;
|
||||
- 記憶小卡片(擁有者):打字停 300 ms 後出現在輸入框上方,排成一行可以左右滑,和電腦版一樣預先勾好、點一下加入或拿掉;
|
||||
- 你的訊息下面有「帶了 N 條記憶」,點開看是哪幾條;
|
||||
|
|
@ -2312,7 +2313,7 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開)
|
|||
|
||||
推播內容只有手機解得開(Web Push 加密),點通知會直接打開那個 Bot 的聊天。
|
||||
|
||||
- **在通知上直接允許/拒絕**(Android 會顯示按鈕;iPhone 點了打開聊天):只有「要你允許的事」才有按鈕(某個操作、讓 Bot 用電腦工具、在這台電腦上執行);問題卡和「需要處理」沒有,要打開來回答。按「允許」是允許一次。通知帶著那個請求的編號,大腦會確認它還是正在等的那一個:已經回答過、或換成別的請求時,不會被舊通知答到,聊天裡留一行「通知上的「允許/拒絕」沒有用上…」。
|
||||
- **在通知上直接允許/拒絕**(Android 會顯示按鈕;iPhone 點了打開聊天):只有「要你允許的事」才有按鈕(某個操作、讓 Bot 用電腦工具、在這台電腦上執行);問題卡和「需要處理」沒有,要打開來回答。按「允許」是允許一次。通知帶著那個請求的編號,大腦會確認它還是正在等的那一個:已經回答過、或換成別的請求時,不會被舊通知答到,聊天裡留一行「通知上的「允許/拒絕」沒有用上…」。大腦也記得這是通知送來的:通知上的按鈕只回答「要你允許的事」、只有允許一次或拒絕,不會變成「需要處理」的「我完成了」、問題卡的「略過」或一律允許(放按鈕和收回答用同一條規則)。
|
||||
- 手機網頁:新訊息從下面滑進來(打開聊天時舊訊息不動;系統設定減少動態時不動);iPhone 鍵盤蓋住畫面時輸入框跟著抬高;送出和按允許時輕震一下(支援的手機)。
|
||||
- 主畫面圖示長按有兩個捷徑:「主要 Bot 對話」「未讀對話」(第一個未讀的 Bot)。
|
||||
|
||||
|
|
|
|||
|
|
@ -31,7 +31,7 @@
|
|||
## 怎麼操作
|
||||
|
||||
- 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 帶著主題和兩組顏色。)
|
||||
|
||||
## 陷阱
|
||||
|
||||
|
|
@ -46,3 +46,4 @@
|
|||
- 團隊成員的訊息跟訊息管道一樣不受信任:不帶你的記憶、沒有 App 操作工具;要核准的事只通知你和管理員,成員只看到「等擁有者或管理員決定」。
|
||||
- 「登出帳號」會把這台從帳號移除:手機從外面連、裝置連結、分享都會斷;這台的 Bot 和聊天還在。
|
||||
- 手機看不到保險庫,也看不到模型金鑰(只能寫入新的)。
|
||||
- 手機上的卡(允許、需要處理、問題卡)只答它畫出來的那一張:那張已經在電腦或另一支手機上回答、被停止、或換成下一張時,按了不算,聊天裡寫「手機(或螢幕電腦)上的回答沒有用上…」,要看現在在等什麼再按;開了很久沒重新整理的舊頁面也一樣(重新整理)。螢幕電腦上的卡也是。用帳號登入的手機,頁面是帳號伺服器給的:伺服器還沒更新時,手機上的卡都答不了,要在電腦上答。
|
||||
|
|
|
|||
|
|
@ -43,7 +43,7 @@ Bot 要動到你的電腦、對外送出或做收不回來的事時,先問你
|
|||
- 在任何聊天打「/always-approve」(「/」清單裡有),或 設定 › 權限 ›「一律放行」的開關「什麼都不問,全部直接做」。手機用擁有者身分打也可以;團隊成員、管理員打的不算指令(會變成「【名字】/always-approve」給 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、檔案看不看得懂。
|
||||
|
||||
## 怎麼操作
|
||||
|
|
|
|||
|
|
@ -1108,7 +1108,8 @@ function apply(v) {
|
|||
// An approval answered from a notification banner, and a home-screen shortcut (主要 Bot, 未讀).
|
||||
if (S.answer && S.token) {
|
||||
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) {
|
||||
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 () => {
|
||||
if (navigator.vibrate) navigator.vibrate(8);
|
||||
$("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]");
|
||||
if (d) d.onclick = async () => {
|
||||
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);
|
||||
}
|
||||
|
|
@ -1608,8 +1611,9 @@ function askAnswer(q, i) {
|
|||
function renderQuestion(a, force) {
|
||||
const qs = a.questions || [];
|
||||
if (!qs.length) return;
|
||||
if (!ASKF || ASKF.id !== a.call_id) {
|
||||
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 || ""))};
|
||||
// (A card is told apart by its key: call ids repeat, call_0 every round.)
|
||||
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.
|
||||
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); };
|
||||
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 = () => {
|
||||
if (!askAnswer(q, i)) return;
|
||||
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.answer && d.ask && d.bot) {
|
||||
// (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};
|
||||
}
|
||||
if (d.bot && S.token) go("chat", {bot: +d.bot}); else if (d.bot) S.open = +d.bot;
|
||||
|
|
|
|||
35
src/app.rs
35
src/app.rs
|
|
@ -2822,7 +2822,10 @@ impl App {
|
|||
};
|
||||
self.approvals.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;
|
||||
}
|
||||
if self.want_direct.replace(false) {
|
||||
|
|
@ -4455,11 +4458,19 @@ impl App {
|
|||
|
||||
/// 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).
|
||||
/// 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) {
|
||||
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);
|
||||
// (A new card waits its own moment before it takes Enter / Esc.)
|
||||
self.ask_shown.remove(&bot_id);
|
||||
let key = crate::httpd::random_hex(16);
|
||||
self.ask_keys.insert(bot_id, key.clone());
|
||||
// (A brain on a server has nobody to hear it.)
|
||||
let chime = !self.demo && !self.headless && self.state.alert_sound;
|
||||
|
|
@ -4472,9 +4483,6 @@ impl App {
|
|||
if self.state.notify && self.away() {
|
||||
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();
|
||||
// 允許 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.
|
||||
let mut title = if a.kind == ApprovalKind::Handoff { format!("{}:需要你", b.name) } else { format!("{} 需要你允許", b.name) };
|
||||
if a.kind == ApprovalKind::Question {
|
||||
|
|
@ -4485,9 +4493,9 @@ impl App {
|
|||
// The banner doesn't ring a second time when the 提示音 just did.
|
||||
notify::banner_for(&title, &what, !chime, Some(bot_id));
|
||||
}
|
||||
// 允許/拒絕 on the banner only for a request to allow (a question, or a step
|
||||
// only the person can do, opens the chat).
|
||||
if whole && a.tool != crate::hooks::MANAGE_TOOL && matches!(a.kind, ApprovalKind::Action | ApprovalKind::EnableTools | ApprovalKind::EnableThisComputer) {
|
||||
// 允許/拒絕 on the banner only where notice_answers says so (the brain
|
||||
// checks the same rule when the answer comes back).
|
||||
if notice_answers(a) {
|
||||
crate::remote::notify_approval(&title, &what, bot_id, &key);
|
||||
} else {
|
||||
crate::remote::notify(crate::remote::Notice::Need, &title, &what, bot_id);
|
||||
|
|
@ -6971,6 +6979,17 @@ struct Live {
|
|||
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.
|
||||
fn grant_label(g: &str) -> String {
|
||||
match g {
|
||||
|
|
|
|||
|
|
@ -523,6 +523,9 @@ pub struct Mirror {
|
|||
pub(super) mcp_state: Value,
|
||||
/// When each bot's last turn ended, as last heard (a newer one ending well is read aloud).
|
||||
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
|
||||
/// 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)>>>,
|
||||
|
|
@ -690,7 +693,8 @@ impl App {
|
|||
ApprovalKind::Handoff => "handoff",
|
||||
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();
|
||||
// The connectors run here too: whether each is connected, or why not.
|
||||
|
|
@ -949,6 +953,7 @@ impl App {
|
|||
self.mir.outbox = None;
|
||||
self.streams.clear();
|
||||
self.approvals.clear();
|
||||
self.mir.keys.clear();
|
||||
self.mir.settled.clear();
|
||||
if let Some(mut local) = self.mir.local.take() {
|
||||
let mut remote = self.state.remote.clone();
|
||||
|
|
@ -1206,15 +1211,28 @@ impl App {
|
|||
};
|
||||
let (reply, _) = channel();
|
||||
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();
|
||||
for (id, a) in waiting {
|
||||
let new = self.approvals.get(&id).map(|o| o.call_id != a.call_id).unwrap_or(true);
|
||||
for (id, (a, key)) in waiting {
|
||||
// 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);
|
||||
if key.is_empty() {
|
||||
self.mir.keys.remove(&id);
|
||||
} else {
|
||||
self.mir.keys.insert(id, key.clone());
|
||||
}
|
||||
if new {
|
||||
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();
|
||||
self.approvals.retain(|id, _| keep.contains(id));
|
||||
self.mir.keys.retain(|id, _| keep.contains(id));
|
||||
if self.state.bot(self.state.selected).is_none() {
|
||||
self.state.selected = self.state.primary_bot;
|
||||
}
|
||||
|
|
@ -1555,6 +1574,59 @@ mod tests {
|
|||
|
||||
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") };
|
||||
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));
|
||||
}
|
||||
|
||||
/// 每次更新強調色都變回橘色:外觀是這台自己的,連到大腦時、大腦的設定來時、存檔時都用這台的。
|
||||
/// 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.
|
||||
|
|
|
|||
|
|
@ -51,7 +51,9 @@ fn address_only(url: &str) -> String {
|
|||
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 title = match a.kind {
|
||||
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.
|
||||
if a.kind == ApprovalKind::Question {
|
||||
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;
|
||||
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).
|
||||
|
|
@ -291,7 +293,9 @@ impl App {
|
|||
if let Some(l) = self.streams.get(&b.id) {
|
||||
(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.
|
||||
(b.provider, &b.model, &b.default_computer, b.threads.len(), b.id == self.state.primary_bot).hash(&mut h);
|
||||
for r in &b.routines {
|
||||
|
|
@ -301,6 +305,10 @@ impl App {
|
|||
for (id, _, online) in self.rm.peers.lock().unwrap().iter() {
|
||||
(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);
|
||||
// A connector connected or failing: screens and phones hear of it now, not at the next
|
||||
// long poll's end.
|
||||
|
|
@ -461,12 +469,12 @@ impl App {
|
|||
.collect();
|
||||
view.messages.insert(b.id, msgs);
|
||||
if let Some(a) = self.approvals.get(&b.id) {
|
||||
view.approvals.push(approval_json(b, a));
|
||||
view.approvals.push(approval_json(b, a, self.ask_keys.get(&b.id).map(String::as_str).unwrap_or("")));
|
||||
}
|
||||
// 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);
|
||||
let mut j = approval_json(br, a, self.ask_keys.get(&br.id).map(String::as_str).unwrap_or(""));
|
||||
j["bot"] = json!(b.id);
|
||||
j["target"] = json!(br.id);
|
||||
j["title"] = json!(format!("支線:{}", j["title"].as_str().unwrap_or("")));
|
||||
|
|
@ -610,13 +618,24 @@ impl App {
|
|||
}
|
||||
self.mark();
|
||||
}
|
||||
Cmd::Answer { bot, answer, text, call } => {
|
||||
// From a notification banner: only the request it showed (it may have been
|
||||
// answered since, and another one be waiting).
|
||||
// (And only a request to allow: 「允許」 on a hand-off would mean 「我完成了」.)
|
||||
let allowable = self.approvals.get(&bot).is_some_and(|a| matches!(a.kind, ApprovalKind::Action | ApprovalKind::EnableTools | ApprovalKind::EnableThisComputer));
|
||||
if !call.is_empty() && !(allowable && self.ask_keys.get(&bot) == Some(&call)) {
|
||||
self.goal_note(bot, "通知上的「允許/拒絕」沒有用上:那個請求已經不在等了(回答過,或換成了別的)。打開聊天看現在在等什麼。");
|
||||
Cmd::Answer { bot, answer, text, call, notice } => {
|
||||
// Only the card it was given for: every answer from afar (the phone's card, a
|
||||
// notification, a screen) names its card by the key on_new_approval gave it. A
|
||||
// card answered, gone or replaced since — or a page too old to name one — takes
|
||||
// nothing (it used to answer whatever waited by then: an 允許 for one step went
|
||||
// to the next, and 一律允許 remembered the next one's kind).
|
||||
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 — 直接操作 just let it through, say.)
|
||||
if waiting.is_some() {
|
||||
let note = if notice { "通知上的「允許/拒絕」沒有用上:那個請求已經不在等了(回答過,或換成了別的)。打開聊天看現在在等什麼。" } else { "手機(或螢幕電腦)上的回答沒有用上:那張卡已經不在等了(回答過,或換成了別的),或那個頁面太舊。重新整理,看現在在等什麼再回答。" };
|
||||
self.goal_note(bot, note);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let grant = self.approvals.get(&bot).map(|a| a.grant.clone()).unwrap_or_default();
|
||||
|
|
@ -1864,35 +1883,68 @@ mod phone_act_tests {
|
|||
}
|
||||
|
||||
/// 允許/拒絕 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]
|
||||
fn a_banner_answers_only_its_own_request() {
|
||||
let (ctx, mut app) = demo();
|
||||
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();
|
||||
// (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.ask_keys.insert(bot, call.into());
|
||||
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, key.into());
|
||||
rx
|
||||
};
|
||||
let rx = wait(&mut app, "call-2");
|
||||
app.remote_cmd(&ctx, Cmd::Answer { bot, answer: "once".into(), text: String::new(), call: "call-1".into() });
|
||||
let banner = |answer: &str, call: &str| Cmd::Answer { bot, answer: answer.into(), text: String::new(), call: call.into(), notice: true };
|
||||
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!(app.approvals.contains_key(&bot));
|
||||
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() });
|
||||
assert!(app.state.bot(bot).unwrap().messages.iter().any(|m| m.note && m.text.contains("通知上的「允許/拒絕」沒有用上")));
|
||||
// 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)));
|
||||
// A hand-off isn't answered from a banner, even with its key.
|
||||
let (tx, rx2) = std::sync::mpsc::channel();
|
||||
app.approvals.insert(bot, crate::providers::Approval { call_id: "c0".into(), tool: "x".into(), reason: "登入".into(), grant: String::new(), reply: tx, kind: ApprovalKind::Handoff });
|
||||
app.ask_keys.insert(bot, "k".into());
|
||||
app.remote_cmd(&ctx, Cmd::Answer { bot, answer: "once".into(), text: String::new(), call: "k".into() });
|
||||
assert!(rx2.try_recv().is_err());
|
||||
// From the app itself (no request id): as before.
|
||||
let rx = wait(&mut app, "call-3");
|
||||
app.remote_cmd(&ctx, Cmd::Answer { bot, answer: "reject".into(), text: String::new(), call: String::new() });
|
||||
assert!(matches!(rx.try_recv(), Ok(ApprovalAnswer::Reject)));
|
||||
let rx = card(&mut app, ApprovalKind::Action, "執行指令:\nrm -rf build\nrm -rf dist", "long");
|
||||
app.remote_cmd(&ctx, banner("once", "long"));
|
||||
assert!(rx.try_recv().is_err(), "the banner showed only its first line");
|
||||
// A hand-off or a question isn't answered from a banner, even with its key…
|
||||
let rx = card(&mut app, ApprovalKind::Handoff, "登入", "h");
|
||||
app.remote_cmd(&ctx, banner("once", "h"));
|
||||
assert!(rx.try_recv().is_err(), "允許 on a banner is never 我完成了");
|
||||
// …but the phone's own card answers it, with that key.
|
||||
app.remote_cmd(&ctx, Cmd::Answer { bot, answer: "once".into(), text: String::new(), call: "h".into(), notice: false });
|
||||
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 });
|
||||
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; 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 dock = |answer: &str, call: &str| Cmd::Answer { bot, answer: answer.into(), text: String::new(), call: call.into(), notice: false };
|
||||
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 notes = |app: &App| app.state.bot(bot).unwrap().messages.iter().filter(|m| m.note && m.text.contains("頁面太舊")).count();
|
||||
app.remote_cmd(&ctx, dock("always", ""));
|
||||
app.remote_cmd(&ctx, dock("once", "before"));
|
||||
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), 2, "each one says so");
|
||||
app.remote_cmd(&ctx, dock("reject", "now"));
|
||||
assert_eq!(rx.try_recv(), Ok(ApprovalAnswer::Reject));
|
||||
// Nothing waits now: an answer that comes late says nothing.
|
||||
app.remote_cmd(&ctx, dock("once", "now"));
|
||||
assert_eq!(notes(&app), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -2148,34 +2200,44 @@ mod approval_routing_replay {
|
|||
assert_eq!(first.try_recv(), Ok(ApprovalAnswer::Once));
|
||||
// BotAsks + CardShows:下一件事。
|
||||
let second = bot_asks(&mut app, &ctx, id, "執行指令:rm -rf ~/Documents/報告", "rm");
|
||||
// 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 });
|
||||
// YouTapBanner + BrainTakesAnswer:舊通知上的「允許」(sw.js:answer=once、call=d.ask;
|
||||
// 頁面送出時加 from: "notice")。
|
||||
app.remote_cmd(&ctx, Cmd::Answer { bot: id, answer: "once".into(), text: String::new(), call: banner_key, notice: true });
|
||||
assert!(second.try_recv().is_err(), "第一張卡的通知讓第二件事通過了");
|
||||
assert!(app.approvals.contains_key(&id), "the second card still waits");
|
||||
}
|
||||
|
||||
/// 已知發現 F1(AllSurfaces.cfg 的反例):手機頁面上畫的還是第一張卡,第一張已經不在了
|
||||
/// (電腦上回答了),Bot 問了第二件事;這時在手機上按「一律允許」,第二件事不該通過,
|
||||
/// 也不該把第二件事的類別記成一律允許。螢幕電腦的回答到大腦也是同一條路(api/sync/act
|
||||
/// 不帶 call)。修好 F1 之後拿掉 #[ignore]。
|
||||
/// F1(以前 AllSurfaces.cfg 的反例,已修好):手機頁面上畫的還是第一張卡,第一張已經不在了
|
||||
/// (電腦上回答了),Bot 問了第二件事;這時在手機上按「一律允許」,第二件事不能通過,
|
||||
/// 也不能把第二件事的類別記成一律允許——不管手機送的是它畫的那張卡的 key(現在的頁面),
|
||||
/// 還是什麼都沒送(開了很久的舊頁面)。照舊的程式(沒帶 call 就交給那時候在等的卡)這個
|
||||
/// 測試會失敗。最後,帶著第二張卡自己的 key 才算數。
|
||||
#[test]
|
||||
#[ignore = "已知發現 F1(不是實機測試):手機頁面和螢幕電腦的回答不帶 call。見 .claude/skills/verify-approval-routing/SKILL.md"]
|
||||
fn a_phone_card_tapped_after_it_changed_answers_nothing_else() {
|
||||
let (ctx, mut app, id) = brain("anybot-replay-page.png");
|
||||
let first = bot_asks(&mut app, &ctx, id, "執行指令:npm install", "npm install");
|
||||
// PageRefreshes:手機輪詢 api/state,renderDock 畫出 approval_json 給的這張卡。
|
||||
let shown = approval_json(app.state.bot(id).unwrap(), app.approvals.get(&id).unwrap());
|
||||
// PageRefreshes:手機輪詢 api/state,renderDock 畫出 approval_json 給的這張卡(和它的 key)。
|
||||
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}");
|
||||
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:電腦上按「允許」。
|
||||
app.answer(&ctx, id, ApprovalAnswer::Once);
|
||||
assert_eq!(first.try_recv(), Ok(ApprovalAnswer::Once));
|
||||
// BotAsks + CardShows:下一件事。
|
||||
let second = bot_asks(&mut app, &ctx, id, "執行指令:rm -rf ~/Documents/報告", "rm");
|
||||
// YouTapOnPage + BrainTakesAnswer:手機上還是 npm install 那張,按「一律允許」:
|
||||
// renderDock POST {answer: "always"},remote.rs 把沒有的 call 當成 ""。
|
||||
app.remote_cmd(&ctx, Cmd::Answer { bot: id, answer: "always".into(), text: String::new(), call: String::new() });
|
||||
let got = second.try_recv();
|
||||
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:?}");
|
||||
// renderDock POST {answer: "always", call: a.key};舊頁面 POST {answer: "always"}。
|
||||
for call in [seen_key, String::new()] {
|
||||
app.remote_cmd(&ctx, Cmd::Answer { bot: id, answer: "always".into(), text: String::new(), call, notice: false });
|
||||
let got = second.try_recv();
|
||||
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 });
|
||||
assert_eq!(second.try_recv(), Ok(ApprovalAnswer::Reject));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -197,8 +197,10 @@ pub enum Cmd {
|
|||
Send { bot: u64, text: String, attachments: Vec<String>, from: String, memories: Option<Vec<String>>, member: bool },
|
||||
Stop { bot: u64 },
|
||||
/// (`text`: the answers of a 問題卡.)
|
||||
/// `call`: from a notification's 允許/拒絕 — the request it was about ("" from the app).
|
||||
Answer { bot: u64, answer: String, text: String, call: String },
|
||||
/// `call`: the key of the card it answers (on_new_approval gives each card one; the phone's
|
||||
/// card, a notification and a screen all send it back). `notice`: from a notification's
|
||||
/// 允許/拒絕 (`from: "notice"`), which answer only a request to allow.
|
||||
Answer { bot: u64, answer: String, text: String, call: String, notice: bool },
|
||||
Read { bot: u64 },
|
||||
NewThread { bot: u64 },
|
||||
/// The time zone of the phone the person uses (a brain on a server only knows UTC).
|
||||
|
|
@ -757,7 +759,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 }
|
||||
}
|
||||
"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") },
|
||||
"read" => Cmd::Read { bot },
|
||||
"new" => Cmd::NewThread { bot },
|
||||
"regenerate" => Cmd::Regenerate { bot },
|
||||
|
|
@ -891,7 +893,7 @@ pub fn handle(req: Req, via_relay: bool) -> Resp {
|
|||
member: false,
|
||||
},
|
||||
"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") },
|
||||
"read" => Cmd::Read { bot },
|
||||
"new" => Cmd::NewThread { bot },
|
||||
"regenerate" => Cmd::Regenerate { bot },
|
||||
|
|
|
|||
Loading…
Reference in New Issue