diff --git a/FEATURES.md b/FEATURES.md index f59595e..9e7833c 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -446,7 +446,7 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。 - 「在這台電腦上執行」算開著(選了「永不允許」或被管理員鎖住的除外)。 - 所有 Bot 的電腦工具算開著。 -- Bot 的步驟照「一律詢問」規則審核(自動審核關著也一樣);規則是空的時候用三條預設規則: +- Bot 的步驟照「一律詢問」規則審核(自動審核關著也一樣),另外一定先問三條預設規則(不寫進你的規則;你加了別的規則也照樣問;權限頁上列著): - 「刪除檔案或資料夾」 - 「付款、購買或轉帳」 - 「用我的帳號發文、留言,或傳訊息給別人」 diff --git a/docs/feature-map/autonomy.md b/docs/feature-map/autonomy.md index ae5eb2f..31594d0 100644 --- a/docs/feature-map/autonomy.md +++ b/docs/feature-map/autonomy.md @@ -4,7 +4,7 @@ ## 子功能 -- `autonomy-direct` 直接操作:疊在其他設定上的模式,不改它們——開著時「在這台電腦上執行」和每個 Bot 的電腦工具都算開,照「一律詢問」審核(空的用三條預設:刪除檔案/付款、購買或轉帳/用我的帳號發文、留言、傳訊息給別人);關掉就回到原樣。進行中的工作下一步起不再問;別的 Bot 在等的「可以用電腦嗎」自動允許。 +- `autonomy-direct` 直接操作:疊在其他設定上的模式,不改它們——開著時「在這台電腦上執行」和每個 Bot 的電腦工具都算開,照「一律詢問」審核(另外一定問三條:刪除檔案/付款、購買或轉帳/用我的帳號發文、留言、傳訊息給別人,權限頁列著);關掉就回到原樣。進行中的工作下一步起不再問;別的 Bot 在等的「可以用電腦嗎」自動允許。 - `autonomy-yolo` 一律放行(/always-approve,也可以打 /yolo):你自己打的指令,一把全開——打開直接操作,之後所有 Bot 要等「允許」的都自動允許,連直接操作還會問的也不問,自動審核也略過。仍然擋:安全規則一律拒絕的;別人傳來的訊息(訊息管道、團隊成員)那一輪照樣等你按;問題卡、「需要處理」和 /plan 的計畫卡照樣等你。打開時已經在等的卡片(你自己的)一起放行。開著時輸入列旁有個紅色閃電圖示,點一下有「關閉一律放行」。「/always-approve off」關掉:要核准的又會問;直接操作是它順手打開的就一起關。「/always-approve status」看現在是不是。管理員鎖了直接操作或「在這台電腦上執行」就打不開。 - `autonomy-smart` 智慧模式(一直開著;/smart off 只回「不能關」):詢問和一律放行中間。卡片多了「這輪都准」(同一授權範圍這一輪不再問,下一輪再問);幾分鐘沒回的卡片自己回答:看檔案、上網、Bot 電腦上的直接做(寫在步驟),付款、傳送這類點擊、你的螢幕和 App、保險庫、寄信傳訊息自動拒絕並叫 Bot 停下。每次都問的敏感操作、安全規則拒絕的、問題卡、「需要處理」、計畫卡、hook 要問的、別人的訊息照樣。設定 › 權限 只剩逾時滑桿(30–1800 秒,預設 300)。只有管理員鎖直接操作或本地執行時是關的。 - `autonomy-still-asks` 直接操作仍會問或擋:安全規則擋的;符合「一律詢問」規則的(連接器的工具、瀏覽器開本機網址和上傳也算;「一律允許」過的只比對樣式);畫面上目標寫著付款、傳送、刪除這類字的點擊;用「郵件」「訊息」寄送(「訊息」開了「無需詢問直接傳送」除外);沙盒外的 AppleScript(選「一律允許」前);打電話、傳簡訊、在 X 發文;用保險庫的卡片。問題卡和「需要處理」也照樣等你。 @@ -28,10 +28,10 @@ - 基本前提和「手機已登入」(README),開著 Bot 1 的聊天:`$CTL phone click '.row[data-bot="1"]'`。 -- **一律放行**(covers `autonomy-yolo`、`autonomy-direct`、`autonomy-remote`):手機 設定 › 權限(還沒有規則),手機打「/always-approve」打不開,改在這台電腦上打,再請 Bot 改名。指令:`$CTL phone click '[data-back]' && $CTL phone click '#b-me' && $CTL phone click '#sheet-in .opt' --text 設定 && $CTL phone click '[data-go="perms"]' && $CTL phone wait-text '還沒有規則' --in '#list' && $CTL phone click '[data-back]' && $CTL phone click '[data-back]' && $CTL phone click '.row[data-bot="1"]' && $CTL phone send '/always-approve' && $CTL phone wait-text '只能收緊、不能放寬' --in '#toast' && $CTL phone shot autonomy-yolo-lan && $CTL api GET /api/settings --jq .direct_mode && $CTL stop && $CTL ask '/always-approve' && $CTL serve && $CTL phone open --listed && $CTL phone click '.row[data-bot="1"]' && $CTL phone wait-text '已一律放行' --in '#msgs' && $CTL wait-api /api/settings '.direct_mode == true' && $CTL phone send '改名 [[call update_bot {"name":"放行後的名字"}]]' && $CTL phone wait-text 放行後的名字 --in '#isl-name' && $CTL api GET /api/bots/1 --jq '[.messages[].tools[]? | select(.name == "update_bot") | .status]'`。看到:手機上打「/always-approve」跳出「這會放寬 Bot 能做的事:同一個網路直接連的裝置只能收緊、不能放寬…」;在這台電腦上打就「已一律放行:…仍然會擋:…」;直接操作跟著開;改名沒有跳卡片。 +- **一律放行**(covers `autonomy-yolo`、`autonomy-direct`、`autonomy-remote`):手機 設定 › 權限(還沒有規則),手機打「/always-approve」打不開,改在這台電腦上打,再請 Bot 改名。指令:`$CTL phone click '[data-back]' && $CTL phone click '#b-me' && $CTL phone click '#sheet-in .opt' --text 設定 && $CTL phone click '[data-go="perms"]' && $CTL phone wait-text '還沒有規則' --in '#list' && $CTL phone click '[data-back]' && $CTL phone click '[data-back]' && $CTL phone click '.row[data-bot="1"]' && $CTL phone send '/always-approve' && $CTL phone wait-text '只能收緊、不能放寬' --in '#toast' && $CTL phone shot autonomy-yolo-lan && $CTL api GET /api/settings --jq .direct_mode && $CTL stop && $CTL ask '/always-approve' && $CTL serve && $CTL phone open --listed && $CTL phone click '.row[data-bot="1"]' && $CTL phone wait-text '已一律放行' --in '#msgs' && $CTL wait-api /api/settings '.direct_mode == true' && $CTL phone send '改名 [[call update_bot {"name":"放行後的名字"}]]' && $CTL phone wait-text 放行後的名字 --in '#isl-name' && $CTL api GET /api/bots/1 --jq '[.messages[].tools[]? | select(.name == "update_bot") | .status]'`。看到:手機上打「/always-approve」跳出「這會放寬 Bot 能做的事:同一個網路直接連的裝置只能收緊、不能放寬…」;在這台電腦上打就「已一律放行:…仍然會擋:…」;直接操作跟著開;改名不跳卡片。 - **hook 照樣問、擋下一步**(covers `autonomy-hooks`、`autonomy-yolo`):一律放行開著,請 Bot 加一個擋 `shell` 的 hook,按允許,再請它跑指令。指令:`$CTL phone send '加 hook [[call manage_hooks {"action":"add","event":"PreToolUse","matcher":"shell","command":"echo 這一步被 hook 擋下 >&2; exit 2"}]]' && $CTL phone wait '#ask .ask' && $CTL phone shot autonomy-hook-card && $CTL phone click '#ask button[data-a="once"]' && $CTL wait-api /api/bots/1 '[.messages[].tools[]? | select(.name == "manage_hooks") | .status] == ["done"]' && $CTL datafile hooks/hooks.json && $CTL phone send '跑 [[call shell {"command":"echo hi"}]]' && $CTL phone wait-text 'hook 擋下了這一步' --in '#msgs'`。看到:一律放行也跳「新增一個 hook…」卡片;hooks.json 有那條;指令沒跑,「hook 擋下了這一步」。 - **看狀態、關掉**(covers `autonomy-yolo`):打 status、off,再請它改名。指令:`$CTL phone send '/always-approve status' && $CTL phone wait-text '現在是一律放行' --in '#msgs' && $CTL phone send '/always-approve off' && $CTL phone wait-text '已關閉一律放行' --in '#msgs' && $CTL wait-api /api/settings '.direct_mode == false' && $CTL phone send '再改 [[call update_bot {"name":"關掉後的名字"}]]' && $CTL phone click '#ask button[data-a="reject"]' && $CTL phone wait-text '使用者拒絕了這個操作' --in '#msgs'`。看到:「現在是一律放行…」「已關閉一律放行…」;改名又跳卡片。 -- **手機的權限頁、打不開直接操作**(covers `autonomy-remote`、`autonomy-direct`、`autonomy-review`):不重新整理,到 設定 › 權限;另一台裝置加一條「一律詢問」規則;再按「直接操作」。指令:`$CTL phone click '[data-back]' && $CTL phone click '#b-me' && $CTL phone click '#sheet-in .opt' --text 設定 && $CTL phone click '[data-go="perms"]' && $CTL phone wait-text '刪除檔案或資料夾' --in '#list' && $CTL api POST /api/act/setting '{"key":"rule_add","list":"ask","value":"寄信前先問我"}' && $CTL phone wait-text '寄信前先問我' --in '#list' && $CTL api --expect 403 POST /api/act/setting '{"key":"rule_remove","list":"ask","value":"寄信前先問我"}' && $CTL api --expect 400 POST /api/act/setting '{"key":" rule_add","list":"allow","value":"全部直接做"}' && $CTL api --expect 403 POST /api/act/setting '{"key":"auto_review","value":true}' && $CTL state '{ask: .review_ask_rules, allow: .review_allow_rules}' && $CTL phone click 'label.sw:has([data-sset="direct_mode"])' && $CTL phone click '#sheet-in .opt' --text 打開 && $CTL phone wait-text '只能收緊、不能放寬' && $CTL phone shot autonomy-perms && $CTL wait-api /api/settings '.direct_mode == false'`。看到:「一律詢問(優先)」裡三條預設規則;另一台加的「寄信前先問我」自己出現;直接連線拿掉它回 403、「 rule_add」回 400、打開自動審核回 403,state 裡詢問規則還在、允許是空的;按「打開」直接操作後跳出「只能收緊、不能放寬…」,直接操作還是關的。 +- **手機的權限頁、打不開直接操作**(covers `autonomy-remote`、`autonomy-direct`、`autonomy-review`):不重新整理,到 設定 › 權限;另一台裝置加一條「一律詢問」規則;再按「直接操作」。指令:`$CTL phone click '[data-back]' && $CTL phone click '#b-me' && $CTL phone click '#sheet-in .opt' --text 設定 && $CTL phone click '[data-go="perms"]' && $CTL phone wait-text '還沒有規則' --in '#list' && $CTL api POST /api/act/setting '{"key":"rule_add","list":"ask","value":"寄信前先問我"}' && $CTL phone wait-text '寄信前先問我' --in '#list' && $CTL api --expect 403 POST /api/act/setting '{"key":"rule_remove","list":"ask","value":"寄信前先問我"}' && $CTL api --expect 400 POST /api/act/setting '{"key":" rule_add","list":"allow","value":"全部直接做"}' && $CTL api --expect 403 POST /api/act/setting '{"key":"auto_review","value":true}' && $CTL state '{ask: .review_ask_rules, allow: .review_allow_rules}' && $CTL phone click 'label.sw:has([data-sset="direct_mode"])' && $CTL phone click '#sheet-in .opt' --text 打開 && $CTL phone wait-text '只能收緊、不能放寬' && $CTL phone shot autonomy-perms && $CTL wait-api /api/settings '.direct_mode == false'`。看到:「一律詢問(優先)」沒有規則(直接操作不寫進去);另一台加的「寄信前先問我」自己出現;直接連線拿掉它回 403、「 rule_add」回 400、打開自動審核回 403,state 裡詢問規則還在、允許是空的;按「打開」直接操作後跳出「只能收緊、不能放寬…」,直接操作還是關的。 - **智慧模式一直開著**(covers `autonomy-smart`):打「/smart off」關不掉。指令:`$CTL stop && $CTL ask '/smart off' && $CTL ask '/smart status' && $CTL serve && $CTL wait-api /api/settings '.smart_mode == true'`。看到:「…不能關…」「智慧模式一直開著:…300 秒…」;smart_mode 還是 true。 - **桌面的閃電圖示**(covers `autonomy-yolo`):指令:要開視窗——第一步之後 `$CTL stop && ABV_ALLOW_WINDOW=1 $CTL desktop-shot autonomy-yolo ANYBOT_SHOT_REAL=1 && $CTL serve`。看到:臉的同一行右邊一個紅色閃電圖示。 - **直接操作照樣問、允許的樣式**(covers `autonomy-still-asks`、`autonomy-patterns`):指令:走不到——手機打不開直接操作和允許規則(403),scratch 沒有你的電腦。看到:連接器的樣式在 [connectors](connectors.md) 的「一律允許也照樣式問」,瀏覽器在 [browser](browser.md) 的「照你的「一律詢問」」;最接近的真路是 `cargo test direct_mode_still_asks_a_connector_step_its_ask_rule_names`(符合 `connector(…)` 的步驟跳卡片、沒有「一律允許」)和 `agent::` 的幾個。 @@ -41,8 +41,8 @@ - 一律放行重開也開著,例行任務半夜照樣直接做;用完「/always-approve off」。只有你打的指令或設定的開關打得開。 - hook 在大腦上、用使用者的身分、在沙盒外跑:只加看得懂的指令。每一步跑 PreToolUse,慢的會拖住 Bot(預設最多 60 秒)。 -- 外面的訊息和團隊成員的訊息不用你的直接操作和自動審核:要核准的都得你親手按。 -- 自動審核靠模型讀規則,寫得含糊會判錯。內建的安全規則不靠它。 +- 外面的訊息和團隊成員的訊息不用你的直接操作和自動審核:要核准的都得你按。 +- 自動審核靠模型讀規則,寫得含糊會判錯;內建安全規則不靠它。 - 「一律允許」過的連接器只再比對樣式的「一律詢問」(例如 `connector(slack__post_message)`);用話寫的,包括直接操作的三條預設,擋不住。指令、檔案「一律允許」過的不再看規則。 -- 直接操作開著、「一律詢問」有用話寫的規則時,沒「一律允許」過的連接器每一步都先等審核模型(慢一點);例行任務碰到符合的會停下來等你。 +- 直接操作開著時(三條預設是用話寫的),沒「一律允許」過的連接器每一步都先等審核模型(慢一點);例行任務碰到符合的會停下來等你。 - (驗證)hook 擋 `update_bot` 會擋掉後面的改名;示範用不用問的 `shell`。 diff --git a/docs/feature-map/computers.md b/docs/feature-map/computers.md index edb75ca..f39524a 100644 --- a/docs/feature-map/computers.md +++ b/docs/feature-map/computers.md @@ -17,7 +17,7 @@ ## 使用者怎麼到 -- Bot 設定 ›「電腦操作」:「讓這個 Bot 查看、修改檔案和執行指令」,勾了(或直接操作開著)才出現下面幾項;右側面板的「做事的電腦」只顯示,點了打開這裡:「做事的電腦」(旁邊寫「聊天時指名別台就會換」);「可以用的電腦」(有兩台以上才出現);「起始資料夾」。 +- Bot 設定 ›「電腦操作」:「讓這個 Bot 查看、修改檔案和執行指令」;「做事的電腦」一直在(旁邊寫「聊天時指名別台就會換」;右側面板的那一列只顯示,點了打開這裡);勾了(或直接操作開著)才有:「可以用的電腦」(有兩台以上才出現);「起始資料夾」。 - 設定 ›「電腦」›「你的電腦」:鉛筆改這台的名字、「在這台電腦上執行」、「其他電腦」展開看帳號裡的電腦和 SSH 電腦,填「SSH 電腦名稱,例如 工作站」和位址按「新增」,或「移除」,還有「讓帳號裡的其他電腦使用這台」。 - 設定 › 一般 ›「手機與帳號」:「大腦」那一欄選哪台當大腦(「改用它當大腦」),「加一台電腦」按「產生配對碼」([account](account.md))。 - 側邊欄底部名字右邊的「↑」(「傳送檔案或文字到其他裝置」)。手機:首頁上面一排的「電腦」;聊天「⋯」›「對話詳細資訊」›「電腦」(做事的電腦——只顯示,點了到 Bot 設定改——和電腦清單);帳戶選單 ›「傳送到其他裝置」。 diff --git a/mobile/index.html b/mobile/index.html index 39a5495..395cab5 100644 --- a/mobile/index.html +++ b/mobile/index.html @@ -3235,7 +3235,9 @@ function drawSettings(kind, quiet) { if (kind === "perms") { h += group("", item({icon: "zap", k: "直接操作", v: st.direct_locked ? "已由管理員關閉" : "Bot 直接做事,只有危險操作和「一律詢問」規則會先問你", sw: !!st.direct_mode, swdata: 'data-sset="direct_mode"', disabled: !isOwner() || st.direct_locked}) + item({icon: "shield", k: "自動審核", v: "照下面的規則自動允許或先問你", sw: !!st.auto_review, swdata: 'data-sset="auto_review"', disabled: !isOwner()})); h += rulesGroup("一律詢問(優先)", st.ask_rules, "ask") + rulesGroup("無需詢問直接允許", st.allow_rules, "allow"); - h += `
用一般的話寫,例如「付款前先問我」。兩邊都符合時先問。${st.direct_mode ? "直接操作開著:「一律詢問」照樣檢查(沒寫就用預設的),「直接允許」用不到。" : st.auto_review === false ? "自動審核關著時不會用這些規則。" : ""}
`; + // 直接操作 always asks about these three too (not written into the rules: turning it off leaves nothing behind). + if (st.direct_mode) h += group("直接操作開著時也一定先問", ["刪除檔案或資料夾", "付款、購買或轉帳", "用我的帳號發文、留言,或傳訊息給別人"].map((r) => item({icon: "hand", k: r})).join("")); + h += `
用一般的話寫,例如「付款前先問我」。兩邊都符合時先問。${st.direct_mode ? "直接操作開著:「一律詢問」照樣檢查,「直接允許」用不到。" : st.auto_review === false ? "自動審核關著時不會用這些規則。" : ""}
`; } if (kind === "integrations") { const dot = (ok, on) => ``; diff --git a/src/app.rs b/src/app.rs index c1aa203..978fb73 100644 --- a/src/app.rs +++ b/src/app.rs @@ -2111,9 +2111,11 @@ impl App { // 直接操作: the person's 「一律詢問」 rules are checked whatever 自動審核 says (none written: // the default ones, for this turn — not saved into the person's rules). let direct_now = self.direct_on(); - let review = (!untrusted && (self.state.auto_review || direct_now) && !self.always_on()).then(|| { - let ask = if direct_now && self.state.review_ask_rules.is_empty() { crate::model::DEFAULT_ASK_RULES.iter().map(|s| s.to_string()).collect() } else { self.state.review_ask_rules.clone() }; - agent::Review { allow: self.state.review_allow_rules.clone(), ask } + let review = (!untrusted && (self.state.auto_review || direct_now) && !self.always_on()).then(|| agent::Review { + // (Under 直接操作 they don't matter — it goes ahead anyway; and if it is turned off + // mid-turn with 自動審核 off, they mustn't start allowing on their own.) + allow: if self.state.auto_review { self.state.review_allow_rules.clone() } else { vec![] }, + ask: ask_rules(&self.state.review_ask_rules, direct_now), }); if untrusted { self.strangers.insert(bot_id); @@ -6052,8 +6054,10 @@ impl App { if self.direct_on() && !b.tools_enabled { note(ui, "「直接操作」開著:這個 Bot 現在照樣可以用電腦;關掉直接操作才照這裡。", p); } - if b.tools_enabled || self.direct_on() { - ui.add_space(6.0); + // 做事的電腦 even with 電腦操作 off (then it asks before each use; the panel's + // row opens here, and the phone's Bot 設定 shows it too). + ui.add_space(6.0); + { form_row(ui, "做事的電腦", p, |ui| { let (choices, current) = self.computer_choices(&b); let mut pick = None; @@ -6070,6 +6074,8 @@ impl App { } ui.label(RichText::new(t("聊天時指名別台就會換")).size(FONT_XS).color(p.text3)); }); + } + if b.tools_enabled || self.direct_on() { self.profile_computers(ui, &mut b); form_row(ui, "起始資料夾", p, |ui| { ui.add(egui::TextEdit::singleline(&mut b.workdir).hint_text(t("在你的電腦上,例如 ~/Documents/專案")).desired_width(ui.available_width())); @@ -6697,7 +6703,8 @@ impl App { }); hint(ui, "為每種操作寫一條簡短的自然語言規則。規則衝突時,「先詢問」優先。這些規則只對你生效。內建的安全檢查一律有效。也可以寫成固定樣式,每次判斷都一樣、不用等模型:shell(git *)、file(~/Projects/**)、connector(gitlab__*)、web(domain:example.com)、tool(browser_click)。", p); if self.direct_on() { - note(ui, "「直接操作」開著:「一律詢問」規則照樣會檢查(這裡關著也一樣;沒寫規則時用預設的),「無需詢問」規則用不到(本來就直接做)。", p); + let defaults = crate::model::DEFAULT_ASK_RULES.map(|r| format!("「{r}」")).join("、"); + note(ui, format!("「直接操作」開著:「一律詢問」規則照樣會檢查(這裡關著也一樣),另外一定先問:{defaults};「無需詢問」規則用不到(本來就直接做)。"), p); } else if !self.state.auto_review { hint(ui, "自動審核關閉時不會使用規則", p); } @@ -8421,6 +8428,21 @@ fn composer_box_h(text_h: f32, max_h: f32) -> f32 { (text_h + COMPOSER_TOP + 3.0).clamp(28.0, max_h.max(28.0)) } +/// The 「一律詢問」 rules a turn is reviewed by: the person's, and under 直接操作 the three it +/// always asks about too (a rule added later never drops them — a phone that may only tighten +/// would otherwise loosen). +fn ask_rules(mine: &[String], direct: bool) -> Vec { + let mut all = mine.to_vec(); + if direct { + for r in crate::model::DEFAULT_ASK_RULES { + if !all.iter().any(|x| x == r) { + all.push(r.to_string()); + } + } + } + all +} + /// What an empty chat offers to start with. const EMPTY_STARTS: [&str; 3] = ["幫我規劃這個週末的行程", "把這段文字改得更清楚好讀", "查一件事,整理成三個重點"]; @@ -9865,6 +9887,20 @@ mod tests { crate::mcp::sync(&[]); } + /// Under 直接操作 the three it always asks about stay with the person's own rules: adding + /// 「寄信前先問我」 (a phone that may only tighten can) never drops 「刪除檔案或資料夾」. Off, only + /// the person's own. + #[test] + fn direct_mode_keeps_its_three_asks_beside_the_persons_rules() { + let mine = vec!["寄信前先問我".to_string(), "刪除檔案或資料夾".to_string()]; + let on = super::ask_rules(&mine, true); + assert_eq!(on.len(), 4, "{on:?}"); + assert!(crate::model::DEFAULT_ASK_RULES.iter().all(|r| on.iter().filter(|x| x == r).count() == 1)); + assert!(on.contains(&"寄信前先問我".to_string())); + assert_eq!(super::ask_rules(&mine, false), mine); + assert_eq!(super::ask_rules(&[], true).len(), 3); + } + /// 直接操作 on and off changes nothing else: 在這台電腦上執行, 自動審核, each bot's 電腦操作 /// and the 「一律詢問」 rules are as the person left them. #[test] diff --git a/src/app/mirror_ui.rs b/src/app/mirror_ui.rs index f8314ad..5b56372 100644 --- a/src/app/mirror_ui.rs +++ b/src/app/mirror_ui.rs @@ -258,8 +258,7 @@ pub(super) fn patch_of(old: &Value, new: &Value) -> Value { /// that is itself a map or a keyed list, also goes as its own smaller change ("edit", by key) — /// so a screen moving one card doesn't put the whole workflow back over a step a bot added at /// the brain meanwhile. ("put" still carries the whole item: a brain from before this applies -/// that, as it always did.) The items the screen made are named in "new": one whose key the -/// brain has given to another meanwhile is added under a fresh id, not over it. +/// that, as it always did.) pub(super) fn deep_patch_of(old: &Value, new: &Value) -> Value { let mut p = patch_of(old, new); match (old, new) { @@ -277,48 +276,109 @@ pub(super) fn deep_patch_of(old: &Value, new: &Value) -> Value { (Value::Array(o), Value::Array(n)) if p.get("list").is_some() => { let key = |x: &Value| item_key(x).unwrap_or(Value::Null); let mut edit = serde_json::Map::new(); - let mut fresh = vec![]; for x in n { - match o.iter().find(|y| key(y) == key(x)) { - Some(y) if y != x => { - let d = deep_patch_of(y, x); - if d.get("value").is_none() { - edit.insert(key(x).to_string(), d); - } + if let Some(y) = o.iter().find(|y| key(y) == key(x)).filter(|y| *y != x) { + let d = deep_patch_of(y, x); + if d.get("value").is_none() { + edit.insert(key(x).to_string(), d); } - Some(_) => {} - None => fresh.push(key(x)), } } if !edit.is_empty() { p["list"]["edit"] = Value::Object(edit); } - if !fresh.is_empty() { - p["list"]["new"] = Value::Array(fresh); - } } _ => {} } p } -/// At the brain, before a screen's change to a list is applied (once: edits come numbered): an -/// item the screen made whose number the brain has given to another meanwhile gets a fresh -/// one, so it is added beside that one instead of over it. -pub(super) fn renumber_new(cur: &Value, p: &mut Value) { +/// Which workflow it is whatever its number (its uid; one from before uids: when it was made). +fn workflow_identity(w: &Value) -> String { + match (w["uid"].as_str().filter(|u| !u.is_empty()), w["created_at"].as_i64().filter(|t| *t != 0)) { + (Some(u), _) => u.to_string(), + (None, Some(t)) => format!("t{t}"), + _ => String::new(), + } +} + +/// A screen's change to the workflows (card by card, see deep_patch_of), with which workflow +/// each number meant on the screen ("born"), so the brain finds it even under another number. +pub(super) fn workflow_patch(old: &Value, new: &Value) -> Value { + let mut p = deep_patch_of(old, new); + if p.get("list").is_some() { + let born: serde_json::Map = old + .as_array() + .into_iter() + .flatten() + .chain(new.as_array().into_iter().flatten()) + .filter_map(|w| Some((w["id"].as_u64()?.to_string(), json!(workflow_identity(w))))) + .filter(|(_, b)| b != "") + .collect(); + p["list"]["born"] = Value::Object(born); + } + p +} + +/// At the brain, before a screen's change to the workflows is applied (once: edits come +/// numbered): each number the screen used is matched to the workflow it meant. One the brain +/// gave another number to (it was made on the screen while the brain made its own under the +/// same number) is changed, or deleted, where it is now — never the other one under its old +/// number; one made on the screen whose number is taken is added under a fresh one; a change to +/// one the brain no longer has, under a number now another's, is let go. +pub(super) fn resolve_workflows(cur: &Value, p: &mut Value) { let Some(l) = p.get_mut("list") else { return }; - let taken: Vec = cur.as_array().into_iter().flatten().filter_map(|x| x["id"].as_u64()).collect(); - let made: Vec = l["new"].as_array().cloned().unwrap_or_default(); - let clashing = made.iter().filter(|k| k.as_u64().is_some_and(|id| taken.contains(&id))); - for (next, k) in (taken.iter().copied().max().unwrap_or(0) + 1..).zip(clashing) { - let fresh = json!(next); - for item in l["put"].as_array_mut().into_iter().flatten().filter(|x| x["id"] == *k) { - item["id"] = fresh.clone(); + let brain: Vec<(u64, String)> = cur.as_array().into_iter().flatten().filter_map(|w| Some((w["id"].as_u64()?, workflow_identity(w)))).collect(); + let born = |k: u64| l["born"].get(k.to_string()).and_then(Value::as_str).unwrap_or("").to_string(); + let ids = |v: &Value| v.as_array().into_iter().flatten().filter_map(|x| x.as_u64().or_else(|| x["id"].as_u64())).collect::>(); + let put = ids(&l["put"]); + let mut seen: Vec = put.iter().chain(ids(&l["del"]).iter()).chain(ids(&l["order"]).iter()).copied().collect(); + seen.extend(l["edit"].as_object().into_iter().flatten().filter_map(|(k, _)| k.parse::().ok())); + seen.sort_unstable(); + seen.dedup(); + let mut next = brain.iter().map(|b| b.0).chain(put.iter().copied()).max().unwrap_or(0) + 1; + // The screen's number → the brain's (None: not there any more — leave it be). + let mut map: std::collections::HashMap> = Default::default(); + for k in seen { + let me = born(k); + let at_k = brain.iter().find(|b| b.0 == k); + if at_k.is_some_and(|b| me.is_empty() || b.1.is_empty() || b.1 == me) { + continue; } - for o in l["order"].as_array_mut().into_iter().flatten().filter(|x| *x == k) { - *o = fresh.clone(); + if let Some(moved) = brain.iter().find(|b| !me.is_empty() && b.1 == me) { + map.insert(k, Some(moved.0)); + } else if at_k.is_some() { + if put.contains(&k) { + map.insert(k, Some(next)); + next += 1; + } else { + map.insert(k, None); + } } } + if map.is_empty() { + return; + } + let to = |k: u64| map.get(&k).copied().unwrap_or(Some(k)); + if let Some(a) = l["put"].as_array_mut() { + a.retain(|x| x["id"].as_u64().is_none_or(|k| to(k).is_some())); + for x in a.iter_mut() { + if let Some(n) = x["id"].as_u64().and_then(to) { + x["id"] = json!(n); + } + } + } + for list in ["del", "order"] { + if let Some(a) = l[list].as_array_mut() { + *a = a.iter().filter_map(|x| x.as_u64().map(|k| to(k).map(|n| json!(n))).unwrap_or(Some(x.clone()))).collect(); + } + } + if let Some(e) = l["edit"].as_object_mut() { + *e = std::mem::take(e).into_iter().filter_map(|(k, v)| match k.parse::() { + Ok(n) => to(n).map(|n| (n.to_string(), v)), + Err(_) => Some((k, v)), + }).collect(); + } } /// Apply a change made by `patch_of` (or `deep_patch_of`) to whatever the value is now. @@ -374,7 +434,7 @@ pub(super) fn diff_ops(base: &Value, cur: &Value) -> Vec { } if b.get(k) != Some(v) { // (工作流 card by card: see deep_patch_of.) - let p = if k == "workflows" { deep_patch_of(b.get(k).unwrap_or(&Value::Null), v) } else { patch_of(b.get(k).unwrap_or(&Value::Null), v) }; + let p = if k == "workflows" { workflow_patch(b.get(k).unwrap_or(&Value::Null), v) } else { patch_of(b.get(k).unwrap_or(&Value::Null), v) }; ops.push(if p.get("value").is_some() { json!({"op": "set", "key": k, "value": v}) } else { json!({"op": "patch", "key": k, "patch": p}) }); } } @@ -1210,7 +1270,7 @@ impl App { let mut v = self.top_value(key); let mut patch = op["patch"].clone(); if key == "workflows" { - renumber_new(&v, &mut patch); + resolve_workflows(&v, &mut patch); } apply_patch(&mut v, &patch); self.brain_set_top(key, v) @@ -2840,6 +2900,72 @@ mod tests { assert!(first.edges.iter().any(|e| e.from == 2 && e.to == 3), "and its line"); let names: Vec<(u64, &str)> = ws.iter().map(|w| (w.id, w.name.as_str())).collect(); assert_eq!(names, vec![(1, "晚報"), (2, "Bot 做的"), (3, "螢幕做的")], "both new ones, under their own numbers"); + // The screen, not having heard back yet, goes on with "its #2": renames it and adds a + // card — that lands on the one it made (#3 at the brain), never on the bot's #2. + let mut later = cur.clone(); + later["workflows"][1]["name"] = json!("螢幕改名"); + later["workflows"][1]["nodes"].as_array_mut().unwrap().push(serde_json::to_value(Node { id: 2, kind: NodeKind::Notify { text: "好".into() }, x: 0.0, y: 190.0 }).unwrap()); + let ops = diff_ops(&cur, &later); + let r = brain.brain_edit(&json!({"ops": ops, "client": "screen-1", "seq": 2})); + assert_eq!(r["applied"], json!(ops.len()), "{r}"); + let ws = &brain.state.workflows; + let names: Vec<(u64, &str, usize)> = ws.iter().map(|w| (w.id, w.name.as_str(), w.nodes.len())).collect(); + assert_eq!(names, vec![(1, "晚報", 3), (2, "Bot 做的", 1), (3, "螢幕改名", 2)], "the bot's #2 untouched"); + // And deleting "its #2" deletes that one. + let mut gone = later.clone(); + gone["workflows"].as_array_mut().unwrap().remove(1); + let ops = diff_ops(&later, &gone); + brain.brain_edit(&json!({"ops": ops, "client": "screen-1", "seq": 3})); + let names: Vec<(u64, &str)> = brain.state.workflows.iter().map(|w| (w.id, w.name.as_str())).collect(); + assert_eq!(names, vec![(1, "晚報"), (2, "Bot 做的")]); + // Two made on the screen at once, the first's number taken: both kept. + let base = serde_json::to_value(&brain.state).unwrap(); + brain.state.workflows.push(Workflow::new(3, "Bot 又做的", 0)); + let mut two = base.clone(); + for (id, name) in [(3, "甲"), (4, "乙")] { + two["workflows"].as_array_mut().unwrap().push(serde_json::to_value(Workflow::new(id, name, 0)).unwrap()); + } + let ops = diff_ops(&base, &two); + brain.brain_edit(&json!({"ops": ops, "client": "screen-1", "seq": 4})); + let mut names: Vec<&str> = brain.state.workflows.iter().map(|w| w.name.as_str()).collect(); + names.sort_unstable(); + let mut want = vec!["Bot 又做的", "Bot 做的", "乙", "晚報", "甲"]; + want.sort_unstable(); + assert_eq!(names, want); + let mut ids: Vec = brain.state.workflows.iter().map(|w| w.id).collect(); + ids.dedup(); + assert_eq!(ids.len(), 5, "no two share a number: {ids:?}"); + } + + /// The screen, taking the brain's workflows in, keeps open the one it was on even when the + /// brain gave it another number. Workflows from before uids are told apart by when they were + /// made. + #[test] + fn a_renumbered_workflow_stays_open_on_the_screen() { + use crate::workflow::Workflow; + let ctx = egui::Context::default(); + let dir = fresh_dir("screen-workflow-renumbered"); + let (_brain, mut screen) = brain_and_screen(&ctx, &dir); + let mine = Workflow::new(2, "螢幕做的", 100); + let old = vec![mine.clone()]; + let mut moved = mine.clone(); + moved.id = 3; + screen.state.workflows = vec![Workflow::new(2, "Bot 做的", 100), moved]; + screen.wf.open = true; + screen.wf.current = 2; + screen.wf_remote_changes(&old); + assert_eq!(screen.wf.current, 3); + // Without uids: by when it was made. + let (mut a, mut b) = (Workflow::new(2, "舊的", 100), Workflow::new(2, "Bot 的", 200)); + a.uid.clear(); + b.uid.clear(); + let brain_side = serde_json::to_value(vec![b.clone()]).unwrap(); + let mut patch = workflow_patch(&json!([]), &serde_json::to_value(vec![a.clone()]).unwrap()); + resolve_workflows(&brain_side, &mut patch); + let mut after = brain_side.clone(); + apply_patch(&mut after, &patch); + let names: Vec<(u64, &str)> = after.as_array().unwrap().iter().map(|w| (w["id"].as_u64().unwrap(), w["name"].as_str().unwrap())).collect(); + assert_eq!(names, vec![(2, "Bot 的"), (3, "舊的")]); } /// 沒網路照樣能改設定: an edit made while the brain is out of reach waits in the queue; the diff --git a/src/app/workflow_run.rs b/src/app/workflow_run.rs index 4ba8cf9..d9b6476 100644 --- a/src/app/workflow_run.rs +++ b/src/app/workflow_run.rs @@ -82,6 +82,15 @@ impl App { /// edits coming back) lights up, and opens beside the chat of the bot that changed it, as on /// the brain itself. pub(super) fn wf_remote_changes(&mut self, old: &[crate::workflow::Workflow]) { + // The one open here may be under another number now (made here while a bot made its own + // under the same one, the brain gave it the next): it stays the one open. + if let Some(me) = old.iter().find(|w| w.id == self.wf.current).map(|w| w.uid.clone()).filter(|u| !u.is_empty()) { + if self.state.workflows.iter().find(|w| w.id == self.wf.current).is_none_or(|w| w.uid != me) { + if let Some(w) = self.state.workflows.iter().find(|w| w.uid == me) { + self.wf.current = w.id; + } + } + } let changed = crate::workflow::changes(old, &self.state.workflows); if changed.is_empty() { return; diff --git a/src/workflow.rs b/src/workflow.rs index ca77cba..421926b 100644 --- a/src/workflow.rs +++ b/src/workflow.rs @@ -62,6 +62,10 @@ pub struct Workflow { /// ends — none is dropped without a word (at most QUEUED_KEPT). #[serde(default, skip_serializing_if = "Vec::is_empty")] pub queued: Vec, + /// Which one it is whatever its number: made once, kept for good. (A screen's workflow the + /// brain gave another number to is still found by it — see mirror_ui::resolve_workflows.) + #[serde(default, skip_serializing_if = "String::is_empty")] + pub uid: String, } /// A run waiting for the one on to end. @@ -326,7 +330,7 @@ impl Run { impl Workflow { pub fn new(id: u64, name: &str, now: i64) -> Workflow { - Workflow { id, name: name.to_string(), nodes: vec![Node { id: 1, kind: NodeKind::Trigger { schedule: None, event: None }, x: 0.0, y: 0.0 }], created_at: now, updated_at: now, ..Default::default() } + Workflow { id, name: name.to_string(), nodes: vec![Node { id: 1, kind: NodeKind::Trigger { schedule: None, event: None }, x: 0.0, y: 0.0 }], created_at: now, updated_at: now, uid: new_secret(), ..Default::default() } } pub fn trigger(&self) -> Option<&Node> { self.nodes.iter().find(|n| matches!(n.kind, NodeKind::Trigger { .. })) @@ -505,7 +509,7 @@ impl Workflow { } /// The same canvas under another name and id, without its runs or versions. pub fn copy_as(&self, id: u64, now: i64) -> Workflow { - Workflow { id, name: format!("{} 的副本", self.name), nodes: self.nodes.clone(), edges: self.edges.clone(), notes: self.notes.clone(), created_at: now, updated_at: now, next_run: None, ..Default::default() } + Workflow { id, name: format!("{} 的副本", self.name), nodes: self.nodes.clone(), edges: self.edges.clone(), notes: self.notes.clone(), created_at: now, updated_at: now, next_run: None, uid: new_secret(), ..Default::default() } } /// Lay the steps out tidily: the trigger at the top, each step one row below the lowest of /// the steps leading to it, side by side where one leads to several (left to right as they