diff --git a/FEATURES.md b/FEATURES.md index f644f63..4ea29a7 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -319,7 +319,11 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。 ### 大腦的螢幕連不到大腦時 -- 按送出會說「連不到大腦,訊息沒有送出。」,打的字、引用、附件和勾選的記憶都留在輸入框,連上後再按一次就好(以前引用、附件和記憶會先被用掉,只剩文字)。 +- 照樣能送:訊息(連引用、附件、勾選的記憶)馬上出現在聊天最下面,淡淡的,下面寫「等連上大腦後送出」(正在送的那一刻是「傳送中…」,連上了還輪不到的是「排隊中…」),還沒送出去過的,旁邊「取消」把它放回輸入框(字、引用、附件都回去);送過一次、可能已經到了大腦的不能取消。排著的訊息存在這台(`brain-queue-<大腦>.json`,每個大腦一份,跟大腦的副本放一起,金鑰封存;讀不懂、或裡面的金鑰現在打不開的檔案改名成 `….unread-時間.json` 留著,不送),關掉 App 再開還在;連上後依序送出,斷線多久都等;附件傳上去的記在那則裡,重試不再傳一次(大檔案的期限照大小放寬)。大腦用每則的編號只收一次(記 10 分鐘);離第一次送出超過 9 分鐘才再送的,先看大腦的聊天裡有沒有這句(回答在路上掉了、其實已經送到),有就不再送。大腦自己拒收的,或大腦一直連得到、這則卻連續 20 次都送不過去,才放棄、放回輸入框並說原因(試過的會提醒它也可能已經到了),後面的照送;放棄的設定改動退回大腦的設定並說原因。離線時新增的 Bot、例行任務,編號從大腦上次的編號之後 1000–9000 起跳(每台螢幕不同),不用副本裡的下一個:大腦在這期間可能已經把下一個給了別的 Bot、支線或例行任務,這台之後對它的改動、傳給它的訊息會送錯對象。「下一個編號」照舊隨改動送回大腦、大腦取比較大的,所以離線時新增過 Bot 或例行任務,之後的編號會往後跳一大段(不影響使用;只是讓出編號、沒新增東西的不會送);大腦收到例行任務時也會自己數過它們的編號。重開 App 後還在離線,新的編號也會排在已經新增的後面。帳號伺服器要重新登入、太忙、網路回了不是大腦的頁面(公共 Wi-Fi 登入頁)都算網路問題,繼續等。 +- 照樣能改設定:改動先排著(一樣存在這台),連上後疊在大腦那時的設定上送出,大腦那邊同時改的別的項目不會被蓋掉(同一個項目以這台改的為準);秘密欄位照舊只送「已設定」的替身,大腦用自己的;例行任務的「上次執行、下次執行」以大腦的為準,舊副本不會讓它多跑一次。順便修好:大腦送來的設定裡沒有觸發條件的例行任務多了一個空的 `trigger`,螢幕電腦每次存檔都把所有 Bot 的例行任務當成改動送回去。 +- 停止、重新產生、還原、執行例行任務、新對話、清除、回答卡片、按鈕送的指令(清除目標、清除計畫、關掉一律放行):這些動到大腦上正在跑的東西,要連上才能做,不排隊、也不存起來;斷線不到約 100 秒的照樣送、連回來就到,更久的不做,輸入框下說「這個動作要連上才能做」。它們走自己的路,不會卡在等連線的訊息後面(只讓剛排進去的訊息和設定改動先走,最多等 10 秒:改完例行任務馬上按執行,跑的是改過的;回答卡片不等)。 +- 不擋畫面:聊天頂端「分享」旁邊一個小小的「離線」(有在等的寫「離線 · N 則等送出」,剛打開還沒連上是「連線中…」),滑鼠移上去說原因、顯示的是幾點同步的內容、做的事連上後送出。以前是聊天上方一整塊紅色提示,佔掉聊天的高度。輸入框的提示字換成「離線:訊息會在連上大腦後送出」。 +- 打開 App 時有這個大腦的副本就直接進去顯示副本,不等網路(以前一定先停在「正在連到「…」…」等大腦第一次回答,香港中繼慢的時候要等好幾秒到一分鐘);只有第一次、還沒有副本時才等。 ### 輸入框下方的小字(11 px 置中,擇一顯示) diff --git a/docs/feature-map/account.md b/docs/feature-map/account.md index 9a8ba7a..b4142ba 100644 --- a/docs/feature-map/account.md +++ b/docs/feature-map/account.md @@ -6,7 +6,7 @@ - `account-login` AnyBot 帳號:帳號伺服器(自己架,在 `relay/`)保管帳號、裝置清單、加密備份,也替手機轉送連線;電腦主動連過去,不用開連接埠。可以順便建立新帳號(伺服器要求時填邀請碼);開了兩步驗證要填六位碼或恢復碼。帳號伺服器的網址要 https://;http:// 只給這台電腦、一個字的名字(同一個 Docker 網路),或經 Tailscale 通道連到的 Tailscale 位址(Wi-Fi 上的 100.x 不算)。登入、還原、配對和之後的每個請求都照這個查(長連線在連上、重連時查,連著時不中途重查)。帳號伺服器轉給手機的回答,電腦那段壓縮著上傳(家裡網路的上傳最慢),到帳號伺服器才打開。不符合時,登入、還原、配對回到表單說原因;長連線和備用連線在「AnyBot 帳號」的狀態寫原因、之後自己再試(`--serve` 的 `ANYBOT_ACCOUNT` 寫進紀錄、每 30 秒再試)。 - `account-backup` 備份:「每天自動備份到帳號」和「立刻備份」,在電腦上加密後才上傳,伺服器打不開;「從帳號備份還原」把這台的 Bot 換成帳號裡最新的備份。 -- `account-brain` 大腦:登入後可以選帳號裡一台 AnyBot 當大腦,其他電腦當螢幕或手腳;「加一台電腦」產生配對碼(10 分鐘有效,[computers](computers.md))。螢幕電腦上的大腦那一欄分段寫「這台 ↔ 帳號伺服器:…」「帳號伺服器 ↔ 大腦「…」:在線上/不在線上」和「上次同步 10:31(1.2 MB,11 秒,約 110 KB/s)」,看得出是哪一段斷、線有多慢。長連線只要還有資料進來就不算斷(很慢的線上傳大份資料不會被切掉);斷了重新連上的那一刻,大腦的資料就重新要,不用等,而且只要斷線之後變了的。螢幕電腦連上大腦、拿到最新資料前,整個視窗停在「正在連到「…」…」,不先顯示舊的副本;等了 10 秒以上多一顆「改回用這台自己的 Bot」;大腦的設定讀不出來(版本不同)時照樣進去,說原因。重開 App 只向大腦要上次之後變了的。傳出的訊息和動作各帶編號:網路斷一下自己重送(約 100 秒內,提示「網路不穩,正在重新傳送…」),大腦同一個只做一次;真的送不到,文字放回輸入框。按過的允許卡片不會再跳一次。 +- `account-brain` 大腦:登入後可以選帳號裡一台 AnyBot 當大腦,其他電腦當螢幕或手腳;「加一台電腦」產生配對碼(10 分鐘有效,[computers](computers.md))。螢幕電腦上的大腦那一欄分段寫「這台 ↔ 帳號伺服器:…」「帳號伺服器 ↔ 大腦「…」:在線上/不在線上」和「上次同步 10:31(1.2 MB,11 秒,約 110 KB/s)」,看得出是哪一段斷、線有多慢。長連線只要還有資料進來就不算斷(很慢的線上傳大份資料不會被切掉);斷了重新連上的那一刻,大腦的資料就重新要,不用等,而且只要斷線之後變了的。螢幕電腦存著這個大腦上次同步的副本時,打開 App(或從這台自己的 Bot 換回同一個大腦)就直接顯示副本,不等網路,之後大腦的資料來了只補變了的;第一次(還沒有副本,或副本是另一個大腦的)才整個視窗停在「正在連到「…」…」,等了 10 秒以上多一顆「改回用這台自己的 Bot」;大腦的設定讀不出來(版本不同)時照樣進去,說原因。重開 App 只向大腦要上次之後變了的。連不到大腦超過幾秒,聊天頂端「分享」旁邊只多一個小小的「離線」(有訊息在等就是「離線 · N 則等送出」;剛打開還沒連上是「連線中…」),不佔聊天的高度;滑鼠移上去說連不到的原因、顯示的是幾點同步的內容、做的事連上後才送。離線照樣能傳訊息(連附件)和改設定:訊息馬上出現在聊天最下面,標「等連上大腦後送出」(送的那一刻是「傳送中…」),還沒送出去過的可以按「取消」放回輸入框(送過一次、可能已經到了的就不能取消);排著的訊息和改動存在這台(每個大腦各一份),關掉 App 再開還在,連上後依序送出,斷線多久都等;附件傳上去的不會再傳一次。改的設定疊在大腦那時的設定上,大腦那邊同時改的別的項目不會被蓋掉(同一個項目以這台改的為準)。傳出的訊息和動作各帶編號,大腦同一個只做一次。大腦自己拒收的,或大腦一直連得到、這則卻試了 20 次都送不過去(例如檔案太大、線太慢),才放棄、放回輸入框並說原因(試過的會提醒「它也可能已經到了,先看聊天裡有沒有再傳」),後面排著的照送;放棄的設定改動退回大腦的設定並說原因。離線時新增的 Bot 和例行任務,編號從大腦上次的編號之後 1000 起跳(每台不同),大腦那邊同時新增的不會跟它撞號,之後對它的改動和傳給它的訊息都到這台新增的那個。停止、重新產生、還原、執行例行任務、新對話、清除、回答卡片、按鈕送的指令(清除目標、清除計畫…)要連上才能做,不排隊:斷線不到約 100 秒的照樣送、連回來就到(提示「網路不穩,正在重新傳送…」),更久的不做,輸入框下說「這個動作要連上才能做」。按過的允許卡片不會再跳一次。 - `account-computers` 帳號裡的電腦:同一個帳號的每台 AnyBot,在線或離線;那台打開「裝置連結」後,會出現在 Bot 可以用的電腦裡。 - `account-share` 分享給團隊(登入後):把這台的 Bot 分享給帳號伺服器上的其他帳號,選成員或管理員([team](team.md))。 - `account-direct` 同一個網路直接連:先設手機密碼(至少 8 個字)才能打開;列出這台的網址(同一個 Wi-Fi,或都裝了 Tailscale)。區網用 https(這台自己做的憑證);http 只收從 Tailscale 連到這台 Tailscale 位址(Tailscale 通道介面上的 100.x)的,其他一律轉到 https——Wi-Fi 自己發 100.64.x 位址(電信業者 NAT 那一段)時也是區網。同一個位址密碼錯 5 次要等一分鐘。 @@ -36,7 +36,7 @@ - **錯 5 次要等**(covers `account-direct`):同一個位址連打 5 次錯的密碼。指令:`(for i in 1 2 3 4 5; do $CTL api --no-auth --expect 401 POST /api/login '{"password":"wrong","device":"lockout"}' || exit 1; done) && $CTL api --no-auth --expect 429 POST /api/login '{"password":"wrong","device":"lockout"}'`。看到:前 5 次「密碼不對」,第 6 次「密碼錯太多次,請一分鐘後再試」。 - **桌面的手機與帳號頁**(covers `account-direct`、`account-devices`、`account-can`):指令:要開視窗——`$CTL stop && ABV_ALLOW_WINDOW=1 $CTL desktop-shot account ANYBOT_SHOT_REAL=1 ANYBOT_SHOT_VIEW=remote`。看到:「同一個網路直接連」的開關和網址、「手機可以做什麼」兩個關著的開關、「直接連線的裝置」。 - **帳號、備份、大腦、分享、推播**(covers `account-login`、`account-backup`、`account-brain`、`account-computers`、`account-share`、`account-push`):指令:走不到——要帳號伺服器(`relay/`)和真的手機;scratch 不准帶 `ANYBOT_ACCOUNT`。看到:最接近的真路是 `relay/` 的 `cargo test`(帳號、通知種類)和下面的自動測試(帳號網址的規則、同步、大腦那一欄)。 -- 自動測試:`cargo test remote::`、`cargo test remote_ui::`、`cargo test mirror_ui::`(`a_lost_answer_costs_only_what_changed`、`an_edit_sent_twice_is_done_once`)、`cargo test httpd::`、`cargo test lantls::`(哪些連線可以不加密)、`cargo test drops::`;帳號伺服器在 `relay/` 的 `cargo test`。 +- 自動測試:`cargo test remote::`、`cargo test remote_ui::`、`cargo test mirror_ui::`(`a_lost_answer_costs_only_what_changed`、`an_edit_sent_twice_is_done_once`、`a_screen_with_a_copy_goes_in_at_once`、`a_message_sent_offline_reaches_the_brain_once`、`a_message_tried_long_ago_is_looked_for_first`、`an_edit_made_offline_lands_on_the_brains_newer_settings`、`a_job_that_never_goes_while_the_brain_answers_is_given_up`、`a_screen_away_doesnt_take_the_brains_numbers`、`the_brains_settings_read_back_the_same`)、`cargo test an_offline_screen_queues_what_is_sent`、`cargo test httpd::`、`cargo test lantls::`(哪些連線可以不加密)、`cargo test drops::`;帳號伺服器在 `relay/` 的 `cargo test`。 ## 陷阱 @@ -46,5 +46,7 @@ - 電腦上的「Bot 做完或等你時通知」關掉,手機也收不到「需要你允許」「做完了」(例行任務暫停照樣推);而且只在你不在電腦前(視窗不在最前面,或 90 秒沒動)才推。等你的卡只由大腦推(看大腦那台在不在前面),螢幕電腦不推。 - 不要把直接連線的連接埠開放到網際網路,從外面連用帳號或 Tailscale。Tailscale 通道:macOS 是帶著 Tailscale IPv6 位址(fd7a:115c:a1e0::)的 utun,Linux 是 tailscale… 介面,Windows 是名字有 Tailscale 的介面卡;只有 100.x 的其他通道(PPPoE、電信 NAT、Cloudflare WARP)不算。認不出來時(介面卡改過名字、讀不到介面),用 Tailscale 位址打開 http 也會轉到 https,信任一次憑證就好。 - 第一次用 https 打開,手機會警告憑證:選「繼續」;要確認沒連錯台,比對設定頁上的 SHA-256 指紋。 +- 螢幕電腦離線時看到的是上次同步的副本:大腦那邊後來的對話、Bot 正在做的事,連上才出現。排著的訊息只送到原本那個大腦:換到別的大腦時先留著,換回來才送。副本只存一份:從大腦 A 換到大腦 B 再換回 A,A 要等第一次回答才進得去。 +- 一則訊息其實送到了、只是大腦的回答在路上掉了:大腦記得編號 10 分鐘,這之內重送只算一次;離第一次送出超過 9 分鐘才再送的,先看大腦的聊天裡有沒有這句(從第一次送出起),有就不再送。靠的是聊天裡的字:指令(/compact 這類不留在聊天的)、Bot 正在做事時插進去還沒讀到的,看不到就會再送一次;別台剛好打了一模一樣的字,會被當成已經到了。大腦在這之間重新啟動過就認不得編號,訊息可能多收一次,設定改動裡的「新增 Bot」可能變成兩個。 - 「登出帳號」會把這台從帳號移除:手機從外面連、裝置連結、分享都會斷;這台的 Bot 和聊天還在。 - (驗證)錯 5 次之後,127.0.0.1 一分鐘內誰都登不進來(`ctl login-cli`、手機都是):放在最後一步。 diff --git a/docs/multi-device.md b/docs/multi-device.md index ebb5cd8..b6c49ca 100644 --- a/docs/multi-device.md +++ b/docs/multi-device.md @@ -119,12 +119,12 @@ ANYBOT_ACCOUNT_PASSWORD=… anybot setup --server https://… --user 帳號 [--b | 這台電腦沒有連上網路 | 這台斷網 | 檢查 Wi-Fi 或網路線 | | 連不到帳號伺服器:伺服器沒有開 | 帳號伺服器沒在跑 | 伺服器上 `docker compose ps`;Mac 上看 `launchctl list | grep anybot` | | 帳號伺服器暫時無法使用 | 正在重開或 HTTPS 憑證還沒好 | 等一下,會自動重連 | -| 大腦目前離線 | 大腦關機、睡眠或 AnyBot 沒開 | 打開大腦;這段時間還能看之前的對話 | +| 大腦目前離線 | 大腦關機、睡眠或 AnyBot 沒開 | 打開大腦;這段時間還能看之前的對話,傳的訊息先排著 | | 大腦收到了,但太久沒有回應 | 大腦太忙或網路很慢 | 稍後再試 | | 這台電腦的帳號登入失效了 | 帳號被登出或金鑰換了 | 重新登入 | | 這台電腦只讓大腦「…」使用 | 別台想用這台當手腳 | 正常:配對時就限定了 | -大腦連不到時:之前的對話還能看,不能傳訊息;連回來會自動恢復,不用重開。 +大腦連不到時:顯示上次同步的內容(打開 App 時有副本就直接進去,不用等);照樣能傳訊息、改設定,先排著(關掉 App 也還在),連回來後依序送出;停止、重新產生這類動作要連上才能做。 **忘記帳號密碼**:在帳號伺服器那台,先停掉它,再執行(輸入兩次新密碼,畫面不顯示): diff --git a/src/app.rs b/src/app.rs index cc615b6..4949226 100644 --- a/src/app.rs +++ b/src/app.rs @@ -1469,17 +1469,12 @@ impl App { self.doctor_start(bot_id); return; } - // A screen that can't reach its brain: say so, and keep the quote, the files and the - // memories picked (they used to be used up, leaving only the words to send again). A - // moment's drop isn't that: the message waits in line and goes when the line is back. - if self.mir.on && !self.mirror_can_send() { - *self.mir.error.lock().unwrap() = "連不到大腦,訊息沒有送出。".into(); - return; - } - // 先顯示: while it works (or the words travel to the brain) they aren't in the chat - // yet — the person sees them at once all the same. (A command here draws its own line.) + // (A screen of a brain sends even while the brain is out of reach: the message waits in + // its queue, shown under the chat, and goes once the brain is back — mirror_send.) + // 先顯示: while it works the words aren't in the chat yet — the person sees them at once + // all the same. (A command here draws its own line; a screen's queue shows its own.) let local_command = !self.mir.on && self.command_for(bot_id, &text).is_some(); - if self.streams.contains_key(&bot_id) && !text.trim().is_empty() && !local_command { + if !self.mir.on && self.streams.contains_key(&bot_id) && !text.trim().is_empty() && !local_command { self.sending.entry(bot_id).or_default().push((text.trim().to_string(), Instant::now())); } // 引用: the quoted words go first, as a Markdown quote. @@ -3955,6 +3950,7 @@ impl App { } } self.sending_bubbles(ui, &bot); + self.mirror_queue_bubbles(ui, &bot); // (What it is doing, and a request, sit above the input: see composer. // A hand-off keeps its card here, with the live screen; so does a // question — it scrolls with the chat instead of covering it.) @@ -4010,6 +4006,8 @@ impl App { } }); } + // A screen of a brain out of reach: 離線, small, beside 分享 (not a band over the chat). + self.mirror_chip(&mut right); if self.meeting_on() { let red = p.danger; if crate::icons::pill(&mut right, crate::icons::Icon::Record, &t("正在錄會議 · 結束"), red, Color32::WHITE, 36.0).on_hover_text(t("停止錄音,轉成文字記錄")).clicked() { @@ -4831,8 +4829,8 @@ impl App { let right_w = 28.0 * 2.0 + 8.0 + 4.0; let text_w = (ui.available_width() - 28.0 - 8.0 - right_w).max(60.0); // (A long bot name ends in … so the hint stays inside the box.) - let hint = if self.mir.on && !self.mirror_can_send() { - t("連不到大腦,現在只能看") + let hint = if self.mirror_offline() { + t("離線:訊息會在連上大腦後送出") } else { let words = t("傳訊息給 {name}"); let rest = ui.painter().layout_no_wrap(words.replace("{name}", ""), egui::FontId::proportional(COMPOSER_FONT), p.text).size().x; @@ -8564,21 +8562,29 @@ mod tests { assert_eq!(steer.lock().unwrap().first().map(|q| q.text.clone()).as_deref(), Some("等一下,先別跑")); } - /// A screen that can't reach its brain keeps the quote, the files and the words. + /// A screen that can't reach its brain sends all the same: the message — its quote, files + /// and words — waits in the queue (shown under the chat) and goes once the brain is back; + /// 取消 puts it back into the input. #[test] - fn an_offline_screen_keeps_what_was_about_to_be_sent() { + fn an_offline_screen_queues_what_is_sent() { let ctx = egui::Context::default(); let mut app = super::App::new(&ctx, Some(std::env::temp_dir().join("anybot-offline-send.png"))); let id = app.state.bots[0].id; app.mir.on = true; app.mir.online = false; + let n = app.state.bots[0].messages.len(); app.drafts.insert(id, "看這個".into()); app.quoting.insert(id, "上一個回答".into()); app.att.pending.entry(id).or_default().push(crate::attach::Attachment { name: "a.txt".into(), path: "/tmp/a.txt".into(), bytes: 1, image: false, on_box: String::new() }); app.send(&ctx, id); - assert_eq!(app.drafts.get(&id).map(String::as_str), Some("看這個")); - assert!(app.quoting.contains_key(&id) && app.has_pending_attachments(id), "nothing used up"); - assert!(app.mir.error.lock().unwrap().contains("連不到大腦")); + assert!(app.drafts.get(&id).is_none_or(|d| d.is_empty()) && !app.has_pending_attachments(id), "sent, not kept back"); + assert!(app.mir.error.lock().unwrap().is_empty(), "no error: it waits"); + let waiting = app.mirror_waiting(id); + assert_eq!(waiting.len(), 1); + assert_eq!(app.state.bots[0].messages.len(), n, "the brain's chat isn't written here: the queue shows it"); + assert!(app.mirror_unqueue(&waiting[0].key())); + assert!(app.drafts[&id].contains("> 上一個回答") && app.drafts[&id].contains("看這個") && app.has_pending_attachments(id), "taken back: in the input again"); + assert!(app.mirror_waiting(id).is_empty()); } /// 重新產生 keeps what it replaced on the bot — an answer, or a stopped turn's steps — and diff --git a/src/app/chat_ui.rs b/src/app/chat_ui.rs index 02df556..3d7b2e3 100644 --- a/src/app/chat_ui.rs +++ b/src/app/chat_ui.rs @@ -449,6 +449,17 @@ pub fn shimmer(ui: &mut egui::Ui, text: &str, base: Color32, bright: Color32, si ui.ctx().request_repaint_after(std::time::Duration::from_millis(50)); } +/// A message of yours the chat doesn't have yet (on its way, or waiting for the brain): a +/// dimmed bubble on the right. +pub(super) fn pending_bubble(ui: &mut egui::Ui, p: Palette, add: impl FnOnce(&mut egui::Ui)) { + ui.with_layout(Layout::right_to_left(Align::Min), |ui| { + Frame::new().fill(p.hover).stroke(Stroke::new(1.0, p.border)).corner_radius(BUBBLE_RADIUS).inner_margin(bubble_margin()).show(ui, |ui| { + ui.set_max_width(message_max_width(ui.available_width())); + add(ui); + }); + }); +} + impl App { /// 先顯示: the words just sent that the chat doesn't have yet, dimmed, under the newest /// message. One goes once the chat shows it (the bot read it, or the brain sent it back), @@ -463,11 +474,8 @@ impl App { !shown && at.elapsed().as_secs() < if working { 600 } else { 8 } }); for (text, at) in list.iter() { - ui.with_layout(Layout::right_to_left(Align::Min), |ui| { - Frame::new().fill(p.hover).stroke(Stroke::new(1.0, p.border)).corner_radius(BUBBLE_RADIUS).inner_margin(bubble_margin()).show(ui, |ui| { - ui.set_max_width(message_max_width(ui.available_width())); - ui.label(RichText::new(text).size(FONT_BASE).color(p.text2)); - }); + pending_bubble(ui, p, |ui| { + ui.label(RichText::new(text).size(FONT_BASE).color(p.text2)); }); ui.with_layout(Layout::right_to_left(Align::Min), |ui| { let note = if at.elapsed().as_millis() < 1200 { t("傳送中…") } else if working { t("已排入,它下一步會看到") } else { t("已送出") }; diff --git a/src/app/mirror_ui.rs b/src/app/mirror_ui.rs index 565e23a..1deca7a 100644 --- a/src/app/mirror_ui.rs +++ b/src/app/mirror_ui.rs @@ -6,7 +6,8 @@ // their chats) when they changed, and for each bot only the messages from the first one that // changed. The screen side keeps a copy, sends the person's edits back as small operations, and // turns chat actions (send, stop, approve…) into requests. When the brain can't be reached the -// window stays readable and waits. +// window shows its copy and keeps working: messages and edits wait in a queue (kept on disk) and +// go once the brain is back; only what acts on what runs there (stop, regenerate…) needs it. use super::*; use crate::memory::Skill; @@ -126,8 +127,13 @@ fn redact(top: &mut Value) { } } for b in top["bots"].as_array_mut().into_iter().flatten() { + // (Only a trigger there is: `r["trigger"]` put a `null` into every routine without one, + // and the screen's own copy — which has none — then differed from it, so each save + // sent every bot's routines back as an edit.) for r in b["routines"].as_array_mut().into_iter().flatten() { - redact_triggers(&mut r["trigger"]); + if let Some(t) = r.get_mut("trigger") { + redact_triggers(t); + } } } } @@ -339,7 +345,12 @@ pub(super) fn apply_ops(cfg: &mut Value, ops: &[Value]) { match op["op"].as_str().unwrap_or("") { "set" => { if let Some(k) = op["key"].as_str() { - cfg[k] = op["value"].clone(); + // (Counters never go back, as at the brain: an edit on its way doesn't undo + // numbers the brain gave meanwhile.) + cfg[k] = match (k.starts_with("next_"), cfg[k].as_u64(), op["value"].as_u64()) { + (true, Some(now), Some(new)) => json!(now.max(new)), + _ => op["value"].clone(), + }; } } "patch" => { @@ -432,9 +443,238 @@ pub enum Incoming { Offline(String), /// A file from the brain arrived (its local copy's path). File(String), - /// A message that couldn't reach the brain however long it was tried: its words go back + /// A message the brain refused (not the line: that only waits): its words go back /// into that bot's input (when the person hasn't typed something else there since). Unsent { bot: u64, text: String, atts: Vec }, + /// A message the brain took: shown as 已送出 until its chat, on the way, has it. + Sent { bot: u64, text: String }, +} + +/// What waits in this screen's queue for the brain: a message, or an edit of the settings. +#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub(super) enum Job { + /// `typed`: the person's own words from the input (they go back there if the brain refuses + /// them); a button's command (「/goal clear」) is not. + Send { + bot: u64, + id: String, + text: String, + #[serde(default)] + atts: Vec, + #[serde(default)] + memories: Option>, + #[serde(default)] + typed: bool, + /// Where the brain keeps the files already sent up (the first of `atts`, in order): a + /// try again sends only the rest — a big file over a slow line was sent whole every time. + #[serde(default)] + uploaded: Vec, + }, + Edit { seq: u64, ops: Vec }, +} + +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] +pub(super) struct Queued { + pub(super) job: Job, + /// When it was made (ms). + #[serde(default)] + pub(super) at: i64, + /// When the last try left (ms; 0: not tried yet): the brain's chat is looked at only from an + /// answer that came after it. + #[serde(default)] + tried: i64, + /// When the first try that may have arrived left (ms; 0: none — never tried, or looked for + /// in the brain's chat and not there). A try may arrive although its answer doesn't; the brain + /// knows the id for 10 minutes from then, so past that it is looked for before it goes again + /// — and it can't be taken back (取消) meanwhile: it may be at the brain already. + #[serde(default)] + pub(super) first: i64, + /// A try is on its way now (it can't be taken back meanwhile). + #[serde(skip)] + pub(super) trying: bool, + /// Waiting for this window to look in the brain's chat (see mirror_check_queue). + #[serde(skip)] + check: bool, +} + +impl Queued { + pub(super) fn key(&self) -> String { + match &self.job { + Job::Send { id, .. } => format!("send:{id}"), + Job::Edit { seq, .. } => format!("edit:{seq}"), + } + } +} + +/// The queue, kept on disk beside the copy of the brain (brain-queue.json, keys sealed) so +/// closing AnyBot doesn't lose it: which brain it is for, this screen's name there, the jobs. +#[derive(Default, serde::Serialize, serde::Deserialize)] +pub(super) struct Outq { + brain: String, + client: String, + pub(super) items: Vec, + /// Where it is kept (empty: nowhere — not showing a brain, or one left since). + #[serde(skip)] + path: PathBuf, +} + +impl Outq { + fn load(path: &std::path::Path) -> Outq { + let raw = std::fs::read_to_string(path).ok(); + let read = raw.as_deref().and_then(|s| serde_json::from_str::(s).ok()).and_then(|mut v| { + crate::vault_store::walk_secrets(&mut v, false); + // (A key that can't be opened now — the keychain locked or refused — would go to the + // brain as its sealed text, in place of the brain's real key.) + fn sealed(v: &Value) -> bool { + match v { + Value::String(s) => s.starts_with(crate::vault_store::SEALED), + Value::Array(a) => a.iter().any(sealed), + Value::Object(o) => o.values().any(sealed), + _ => false, + } + } + if sealed(&v) { + return None; + } + serde_json::from_value::(v).ok() + }); + // (One this AnyBot can't read — written by another version, or its keys locked away — is + // kept aside, not written over with an empty queue.) + if raw.is_some() && read.is_none() { + let _ = std::fs::rename(path, path.with_extension(format!("unread-{}.json", crate::model::now_ms()))); + } + let mut q = read.unwrap_or_default(); + q.path = path.to_path_buf(); + q + } + + /// Written at every change (small: a few messages and edits), under its lock — the window + /// and the sending thread never write over each other's newer one. + fn save(&self) { + if self.path.as_os_str().is_empty() { + return; + } + if self.items.is_empty() { + let _ = std::fs::remove_file(&self.path); + return; + } + if let Ok(mut v) = serde_json::to_value(self) { + crate::vault_store::walk_secrets(&mut v, true); + let _ = crate::httpd::write_private(&self.path, v.to_string().as_bytes()); + } + } + + fn find(&mut self, key: &str) -> Option<&mut Queued> { + self.items.iter_mut().find(|i| i.key() == key) + } +} + +/// How long the brain remembers a message's id (remote.rs DELIVERY_TTL, 10 minutes), less a +/// margin: a message whose first try that may have arrived is older than this isn't simply sent +/// again — if that try arrived and only its answer was lost, the brain would no longer know it +/// and do it twice. +const ASK_BEFORE_AGAIN_MS: i64 = 9 * 60_000; + +/// Tries in a row that failed on the line while the brain answered all along: then it isn't the +/// line — the message (or edit) is given up, said so, and the queue goes on. +const GIVE_UP_AFTER: u32 = 20; + +/// Its words are in the chat, from `since` on (less a margin for the two clocks): the message +/// arrived. +fn arrived_in(msgs: &[Message], text: &str, atts: &[crate::attach::Attachment], since: i64) -> bool { + let from = since - 120_000; + msgs.iter() + .rev() + .take_while(|m| m.at == 0 || m.at >= from) + .any(|m| m.role == Role::User && m.text.trim() == text.trim() && (!text.trim().is_empty() || m.attachments.iter().map(|a| &a.name).eq(atts.iter().map(|a| &a.name)))) +} + +/// One try of a job: the files not yet up first (each kept in `uploaded` once there), then the +/// words; or the edit. +fn try_job(s: &crate::remote::Settings, client: &str, job: &mut Job) -> Result { + match job { + Job::Edit { seq, ops } => remote::sync_try(s, "/edit", &[], json!({"ops": ops, "client": client, "seq": seq}).to_string().as_bytes(), 20), + Job::Send { bot, id, text, atts, memories, uploaded, .. } => { + // (One file that can't go keeps the whole message here — words without their file + // would be a different message.) + for a in atts.iter().skip(uploaded.len()) { + let bytes = std::fs::read(&a.path).map_err(|e| (false, format!("讀不到「{}」({e})", a.name)))?; + // (Time for a big file on a slow line: about 30 KB/s.) + let secs = 120 + bytes.len() as u64 / 30_000; + let v = remote::sync_try(s, &format!("/upload/{bot}"), &[("name", a.name.clone())], &bytes, secs).map_err(|(line, e)| (line, format!("「{}」沒有傳到大腦:{e}", a.name)))?; + uploaded.push(v["path"].as_str().map(String::from).ok_or((false, "大腦沒有收下檔案".to_string()))?); + } + let paths = uploaded.clone(); + let mut body = json!({"bot": bot, "action": "send", "id": id, "text": text, "attachments": paths}); + if let Some(m) = memories { + body["memories"] = json!(m); + } + remote::sync_try(s, "/act", &[], body.to_string().as_bytes(), 20) + } + } +} + +/// Take one job of the queue to the brain: tried while the brain is in reach (`reach`), waited +/// on (`pause`, told how many tries in a row the line failed) while it isn't — as long as it +/// takes, while this window shows that brain (`stay`). Gives the job back with the brain's +/// answer, or its refusal (or, after GIVE_UP_AFTER line failures in a row while the brain +/// answered, the last of them); None when it was taken back (取消), found already there, or this +/// window left the brain (the job stays on disk). +fn deliver(q: &Mutex, key: &str, now_ms: &dyn Fn() -> i64, go: &mut dyn FnMut(&mut Job) -> Result, reach: &dyn Fn() -> bool, stay: &dyn Fn() -> bool, pause: &dyn Fn(u32)) -> Option<(Job, Result)> { + let mut fails = 0; + loop { + if !stay() { + return None; + } + let mut job = { + let mut g = q.lock().unwrap_or_else(|e| e.into_inner()); + let now = now_ms(); + let it = g.find(key)?; + let ask_first = matches!(it.job, Job::Send { .. }) && it.first > 0 && now - it.first > ASK_BEFORE_AGAIN_MS; + if ask_first { + it.check = true; + } + let near = reach(); + if it.check || !near { + drop(g); + // (Out of reach in between: the failures before were the line's.) + if !near { + fails = 0; + } + pause(0); + continue; + } + it.trying = true; + it.tried = now; + if it.first == 0 { + it.first = now; + } + let job = it.job.clone(); + g.save(); + job + }; + let r = go(&mut job); + let mut g = q.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(it) = g.find(key) { + it.trying = false; + // (The files that went up stay up.) + it.job = job.clone(); + } + match r { + Err((true, _)) if fails + 1 < GIVE_UP_AFTER => { + g.save(); + drop(g); + fails += 1; + pause(fails); + } + done => { + g.items.retain(|i| i.key() != key); + g.save(); + return Some((job, done)); + } + } + } } /// Each message and chat action from this screen gets a name of its own (this screen's, then a @@ -450,11 +690,9 @@ fn act_id(client: &str) -> String { /// What a screen sends to the brain, one at a time and in order. enum Out { - Edit { seq: u64, ops: Vec }, + /// A job of the queue (by its key): a message or an edit, sent however long it takes. + Queued(String), Act(Value), - /// `typed`: the person's own words from the input (they go back there if they can't be - /// sent); a button's command (「/goal clear」) is not. - Send { bot: u64, id: String, text: String, atts: Vec, memories: Option>, typed: bool }, Move { ops: Vec, n: usize, skills: Vec }, /// 技能 on a screen: done at the brain (see [`App::mirror_skill`]); the answer goes to `note`. Skill { body: Value, note: SkillNote, busy: Arc }, @@ -556,14 +794,26 @@ pub struct Mirror { /// The brain's version of the last answer taken in here (what the copy on disk is, when /// written with it: the next start asks only for what changed since). applied: u64, - /// Messages handed to the outbox and not yet through: a copy written meanwhile holds one the - /// brain doesn't have yet, so it isn't one to resume from. - sending: Arc, + /// Messages and edits waiting for the brain, in order (kept on disk too). + pub(super) queue: Arc>, + /// The last ask for news got an answer (the queue goes while it did, waits while it didn't). + reach: Arc, + /// The brain's own settings came since this window started showing it (until then it shows + /// the copy on disk, and nothing done to what runs at the brain — stop, regenerate — goes). + synced: bool, + /// When what is shown came from the brain (ms): the last answer taken in, or the copy's. + pub(super) synced_ms: i64, + /// Where the copy and the queue are kept (empty: beside state.json; a test's own folder). + pub(super) dir: PathBuf, + /// The brain's counts of bots and routines as last known (its settings, or the copy's). + counts: Option<(u64, u64)>, + /// Chat actions' own lane to the brain (body, when pressed in ms): see mirror_out. + acts: Option>, /// Cards answered here, by the brain's key, and when: an update the brain sent before it /// took the answer in still has the card — it isn't shown (and chimed) a second time. pub(super) answered: HashMap, - /// The brain's first answer since this screen came to it is in (its settings taken, or - /// found unreadable and said so): the door opens. + /// The window shows the brain: from its copy on disk at once, or (no copy: the first time) + /// once the brain's first answer is in (its settings taken, or found unreadable and said so). entered: bool, /// When this screen started knocking (the door's way back shows after a while). door_since: Option, @@ -576,14 +826,22 @@ struct CopyAt { brain: String, client: String, version: u64, + /// When the brain's answer it holds came (ms; 0 from before this was kept). + #[serde(default)] + at: i64, } -fn copy_at_path() -> PathBuf { - State::path().with_file_name("brain-copy.at.json") +fn copy_at_path(dir: &std::path::Path) -> PathBuf { + dir.join("brain-copy.at.json") } -fn read_copy_at() -> CopyAt { - std::fs::read_to_string(copy_at_path()).ok().and_then(|s| serde_json::from_str(&s).ok()).unwrap_or_default() +fn read_copy_at(dir: &std::path::Path) -> CopyAt { + std::fs::read_to_string(copy_at_path(dir)).ok().and_then(|s| serde_json::from_str(&s).ok()).unwrap_or_default() +} + +/// Each brain's queue its own file: going to another brain and back keeps what waited for this one. +fn queue_path(dir: &std::path::Path, brain: &str) -> PathBuf { + dir.join(format!("brain-queue-{}.json", &crate::httpd::sha256_hex(brain)[..12])) } /// The copy on disk is written at most this often (it is only for opening while the brain is @@ -625,8 +883,8 @@ fn local_copy(brain_path: &str, name: &str) -> PathBuf { State::path().with_file_name("brain-files").join(format!("{}-{name}", &h[..16])) } -fn cache_path() -> PathBuf { - State::path().with_file_name("brain-copy.json") +fn cache_path(dir: &std::path::Path) -> PathBuf { + dir.join("brain-copy.json") } impl App { @@ -976,6 +1234,11 @@ impl App { unredact(&mut value, &v[key]); if key == "routines" { keep_run_times(&mut value, &v["routines"]); + // (The brain counts on past every number a screen gave a routine, whatever count + // the screen sends.) + for n in value.as_array().into_iter().flatten().filter_map(|r| r["id"].as_u64()) { + self.state.next_routine_id = self.state.next_routine_id.max(n + 1); + } } v[key] = value; let ok = match serde_json::from_value::(v) { @@ -1000,9 +1263,12 @@ impl App { } self.mir.started = true; // The same name at the brain as last time (it remembers what this screen holds for a - // day), so a start asks only for what changed since the copy on disk. - let at = read_copy_at(); - self.mir.client = if !at.client.is_empty() && at.brain == self.state.remote.brain_id { at.client } else { crate::httpd::random_hex(8) }; + // day), so a start asks only for what changed since the copy on disk — and the edits + // still in the queue go under the name the brain may already have done them for. + let dir = self.mirror_dir(); + let (at, q) = (read_copy_at(&dir), Outq::load(&queue_path(&dir, &self.state.remote.brain_id))); + let brain = &self.state.remote.brain_id; + self.mir.client = [(at.brain, at.client), (q.brain, q.client)].into_iter().find(|(b, c)| b == brain && !c.is_empty()).map(|(_, c)| c).unwrap_or_else(|| crate::httpd::random_hex(8)); // Edits are numbered from the clock: always past the last run's (the brain does each // number once, see brain_edit). self.mir.seq = crate::model::now_ms().max(0) as u64; @@ -1013,39 +1279,112 @@ impl App { /// Start showing the brain: this computer's own bots are kept aside, untouched. fn mirror_enter(&mut self) { + self.mirror_open(); + // The bots' computer is the brain's now; this one's box isn't kept awake. + crate::cloudbox::set_brain(false); + self.mirror_worker(); + self.mirror_outbox(); + crate::tunnel::hello(&self.state.remote.brain_id, self.state.remote.device_link); + } + + /// Where the copy of the brain and the queue are kept. + fn mirror_dir(&self) -> PathBuf { + if !self.mir.dir.as_os_str().is_empty() { + return self.mir.dir.clone(); + } + State::path().parent().map(std::path::Path::to_path_buf).unwrap_or_default() + } + + /// The brain as this computer last knew it, at once — no network: its copy on disk, with + /// what waits in the queue on top. 有副本就直接進去: the window shows it and works (messages + /// and edits wait in the queue); only a first time, with no copy, waits at the door. The + /// brain's answers then come in as usual (only what changed since the copy). + fn mirror_open(&mut self) { let ids: Vec = self.streams.keys().copied().collect(); for id in ids { self.stop(id); } self.approvals.clear(); let local = self.state.clone(); - let at = read_copy_at(); + let dir = self.mirror_dir(); + let brain = self.state.remote.brain_id.clone(); + let at = read_copy_at(&dir); let mut resume = 0; - if let Some(copy) = std::fs::read_to_string(cache_path()).ok().and_then(|s| serde_json::from_str::(&s).ok()).filter(|s| !s.bots.is_empty()) { + // Only this brain's copy, and only one that says so (another brain's bots aren't this + // one's; a copy without its marker was cut short while written). + let copy = (at.brain == brain && !brain.is_empty()).then(|| std::fs::read_to_string(cache_path(&dir)).ok().and_then(|s| serde_json::from_str::(&s).ok())).flatten().filter(|s| !s.bots.is_empty()); + let have_copy = copy.is_some(); + if let Some(copy) = copy { self.state = copy; self.keep_local_fields(&local); - // Edits wait for the brain's own answer; the copy may be old. - if at.brain == self.state.remote.brain_id && at.client == self.mir.client { + if at.client == self.mir.client { resume = at.version; } } + // The queue: this brain's (each brain has its own file; what waits for another stays + // there, for when this window shows that one again). + let mut q = if brain.is_empty() { Outq::default() } else { Outq::load(&queue_path(&dir, &brain)) }; + if q.brain != brain { + q.items.clear(); + } + (q.brain, q.client) = (brain, self.mir.client.clone()); + let edits: Vec = q.items.iter().filter_map(|i| if let Job::Edit { seq, ops } = &i.job { Some((*seq, ops.clone())) } else { None }).collect(); + // (The window's earlier queue, if it showed a brain before: its thread stops, and it no + // longer writes to the file.) + std::mem::take(&mut self.mir.queue.lock().unwrap_or_else(|e| e.into_inner()).path); + self.mir.queue = Arc::new(Mutex::new(q)); self.mir.base = Value::Null; + self.mir.counts = have_copy.then_some((self.state.next_id, self.state.next_routine_id)); + if have_copy { + // Edits made before AnyBot closed show although the copy may be from before them + // (doing one again is doing nothing: each sets what it sets). + if !edits.is_empty() { + let mut cfg = config_json(&mut self.state); + apply_ops(&mut cfg, &edits.iter().flat_map(|(_, o)| o.clone()).collect::>()); + let _ = self.mirror_take_config(cfg); + } + // What the brain had, as last known: edits made from here on are what differs. + self.mir.base = config_json(&mut self.state); + } + *self.mir.pending.lock().unwrap() = edits; self.mir.local = Some(local); self.mir.on = true; - // The bots' computer is the brain's now; this one's box isn't kept awake. - crate::cloudbox::set_brain(false); self.mir.online = false; + self.mir.reach.store(false, Ordering::SeqCst); self.mir.version.store(resume, Ordering::SeqCst); self.mir.applied = resume; - self.mir.entered = false; + self.mir.entered = have_copy; + self.mir.synced = false; + // (A copy from before its marker said when: when the file was written.) + let written = || std::fs::metadata(cache_path(&dir)).and_then(|m| m.modified()).ok().and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map_or(0, |d| d.as_millis() as i64); + self.mir.synced_ms = if !have_copy { 0 } else if at.at > 0 { at.at } else { written() }; self.mir.door_since = Some(Instant::now()); - self.mir.pending.lock().unwrap().clear(); self.mir.reason.clear(); self.mir.down_since = None; *self.mir.status.lock().unwrap() = "正在連到大腦…".into(); - self.mirror_worker(); - self.mirror_outbox(); - crate::tunnel::hello(&self.state.remote.brain_id, self.state.remote.device_link); + } + + /// Settings (as config_json gives them) in place of the window's own, the chats kept. + fn mirror_take_config(&mut self, cfg: Value) -> Result<(), String> { + let local = std::mem::replace(&mut self.state, State::first_run()); + match serde_json::from_value::(cfg) { + Ok(mut st) => { + let mut old = local.bots.clone(); + for b in st.bots.iter_mut() { + if let Some(o) = old.iter_mut().find(|o| o.id == b.id) { + b.messages = std::mem::take(&mut o.messages); + b.threads = std::mem::take(&mut o.threads); + } + } + self.state = st; + self.keep_local_fields(&local); + Ok(()) + } + Err(e) => { + self.state = local; + Err(e.to_string()) + } + } } /// Back to this computer's own bots. @@ -1056,6 +1395,10 @@ impl App { crate::cloudbox::set_brain(true); self.mir.online = false; self.mir.outbox = None; + self.mir.acts = None; + // What still waits stays on disk for this brain (and goes when this window shows it + // again); this window's copy of the queue is done with. + *self.mir.queue.lock().unwrap_or_else(|e| e.into_inner()) = Outq::default(); self.streams.clear(); self.approvals.clear(); self.mir.keys.clear(); @@ -1105,6 +1448,7 @@ impl App { self.mir.rx = Some(rx); self.mir.tx = Some(tx.clone()); let (g, version, client, s, resync, last_sync) = (self.mir.gen.clone(), self.mir.version.clone(), self.mir.client.clone(), self.state.remote.clone(), self.mir.resync.clone(), self.mir.last_sync.clone()); + let reach = self.mir.reach.clone(); let repaint = self.repaint_fn(); std::thread::spawn(move || { let mut backoff = 1u64; @@ -1128,9 +1472,11 @@ impl App { let (bytes, ms) = (crate::tunnel::bytes_in().saturating_sub(bytes_before), t0.elapsed().as_millis() as u64); *last_sync.lock().unwrap_or_else(|e| e.into_inner()) = Some((crate::model::now_ms(), bytes, if bytes >= 100_000 { ms } else { 0 })); version.store(v["version"].as_u64().unwrap_or(0), Ordering::SeqCst); + reach.store(v.get("error").is_none(), Ordering::SeqCst); let _ = tx.send(Incoming::Pull(v)); } Err(e) => { + reach.store(false, Ordering::SeqCst); let _ = tx.send(Incoming::Offline(e)); retry = true; // (A request for everything that failed is asked for again.) @@ -1223,6 +1569,12 @@ impl App { *draft = if draft.trim().is_empty() { text } else { format!("{text}\n{draft}") }; self.att.pending.entry(bot).or_default().extend(atts); } + Incoming::Sent { bot, text } => { + // (One the chat already shows — its update came first — sending_bubbles drops.) + if !text.trim().is_empty() { + self.sending.entry(bot).or_default().push((text.trim().to_string(), Instant::now())); + } + } Incoming::Pull(v) => { if let Some(e) = v["error"].as_str() { self.mir.online = false; @@ -1242,19 +1594,79 @@ impl App { } } } + self.mirror_check_queue(); + self.mirror_spare_numbers(); + } + + /// Away from the brain, a new bot or routine made here gets a number far past the brain's + /// last known count (1000–9000 past, by this screen's name), not the next one: the brain + /// may give the next ones meanwhile (a new bot elsewhere, a 支線), and a later edit or a + /// message by that number would have gone to the brain's. Connected, numbers come from the + /// brain's count as always. (Always past every number already here too: one made away + /// before AnyBot closed, or before the brain's settings came back, keeps its own. The count + /// goes to the brain with the next edit, as it always did; the brain keeps the larger.) + pub(super) fn mirror_spare_numbers(&mut self) { + let Some((bots, routines)) = self.mir.counts.filter(|_| self.mir.on) else { return }; + let spare = if self.mir.online { 0 } else { 1000 + crate::httpd::sha256_hex(&self.mir.client).bytes().take(4).fold(0u64, |n, b| n * 31 + b as u64) % 8000 }; + let top_bot = self.state.bots.iter().chain(&self.state.branch_bots).map(|b| b.id).max().unwrap_or(0); + let top_routine = self.state.bots.iter().flat_map(|b| &b.routines).map(|r| r.id).max().unwrap_or(0); + let (next, next_routine) = (self.state.next_id.max(bots + spare).max(top_bot + 1), self.state.next_routine_id.max(routines + spare).max(top_routine + 1)); + // Only moving the count on isn't an edit: `base` moves too, so the count goes to the + // brain only with a bot or routine made with it (else every blip pushed the brain's + // count on by thousands). + for (key, from, to) in [("next_id", self.state.next_id, next), ("next_routine_id", self.state.next_routine_id, next_routine)] { + if to != from && self.mir.base.is_object() && self.mir.base[key].as_u64().is_some_and(|b| b == from) { + self.mir.base[key] = json!(to); + } + } + (self.state.next_id, self.state.next_routine_id) = (next, next_routine); + } + + /// A message last tried long ago waits for a look in the brain's chat (as it is now, from an + /// answer that came after that try): there already (that try arrived; only its answer was + /// lost) — it is done; not there — it goes again. + pub(super) fn mirror_check_queue(&mut self) { + let queue = self.mir.queue.clone(); + let mut q = queue.lock().unwrap_or_else(|e| e.into_inner()); + if !self.mir.online || !q.items.iter().any(|i| i.check) { + return; + } + let fresh = self.mir.synced_ms; + let mut changed = false; + q.items.retain_mut(|it| { + if !it.check || it.tried >= fresh { + return true; + } + changed = true; + // (From the first try that may have arrived, not the last.) + let arrived = match &it.job { + Job::Send { bot, text, atts, .. } => self.state.bot(*bot).is_some_and(|b| arrived_in(&b.messages, text, atts, it.first)), + Job::Edit { .. } => false, + }; + it.check = false; + it.tried = 0; + it.first = 0; + !arrived + }); + if changed { + q.save(); + } } fn mirror_apply(&mut self, v: Value) { self.mir.applied = v["version"].as_u64().unwrap_or(0); + self.mir.synced_ms = crate::model::now_ms(); // (A brain from before `config=1` may answer a resumed screen without its settings: ask - // for everything once more rather than wait at the door — once, before going in.) - if !v["config"].is_object() && !self.mir.entered { + // for everything once more — once, until its settings are in.) + if !v["config"].is_object() && !self.mir.synced { self.mir.resync.store(true, Ordering::SeqCst); } // Edits the brain has taken in are no longer "on the way". let acked = v["edit_seq"].as_u64().unwrap_or(0); self.mir.pending.lock().unwrap().retain(|(s, _)| *s > acked); if v["config"].is_object() { + let count = |k: &str| v["config"][k].as_u64().unwrap_or(1); + self.mir.counts = Some((count("next_id"), count("next_routine_id"))); // What the brain will have once the edits on the way arrive, and on top of that what // the person changed here and hasn't sent yet. let inflight: Vec = self.mir.pending.lock().unwrap().iter().flat_map(|(_, o)| o.clone()).collect(); @@ -1266,29 +1678,15 @@ impl App { if !unsaved.is_empty() { self.dirty = true; } - let local = std::mem::replace(&mut self.state, State::first_run()); - match serde_json::from_value::(cfg.clone()) { - Ok(mut st) => { - // Chats stay as they are (they come separately). - let mut old = local.bots.clone(); - for b in st.bots.iter_mut() { - if let Some(o) = old.iter_mut().find(|o| o.id == b.id) { - b.messages = std::mem::take(&mut o.messages); - b.threads = std::mem::take(&mut o.threads); - } - } - self.state = st; - self.keep_local_fields(&local); - self.mir.base = base; - } - Err(e) => { - self.state = local; - *self.mir.error.lock().unwrap() = format!("大腦的設定讀不出來(兩邊 AnyBot 版本不同?):{e}"); - } + // (Chats stay as they are: they come separately.) + match self.mirror_take_config(cfg) { + Ok(()) => self.mir.base = base, + Err(e) => *self.mir.error.lock().unwrap() = format!("大腦的設定讀不出來(兩邊 AnyBot 版本不同?):{e}"), } // In either way: settings taken, or unreadable and said so (waiting would not help, // and asking for everything again would only repeat it). self.mir.entered = true; + self.mir.synced = true; } for d in v["bots"].as_array().into_iter().flatten() { let id = d["id"].as_u64().unwrap_or(0); @@ -1449,22 +1847,20 @@ impl App { self.mir.copy_dirty = false; self.mir.copy_at = Some(Instant::now()); let snap = self.state.clone(); - // (Version 0: a message was still on its way — this copy is not one to resume from.) - let at = CopyAt { - brain: self.state.remote.brain_id.clone(), - client: self.mir.client.clone(), - version: if self.mir.sending.load(Ordering::Acquire) == 0 { self.mir.applied } else { 0 }, - }; + // (Messages not yet at the brain are in the queue, not in the chats: every copy is one + // to resume from.) + let at = CopyAt { brain: self.state.remote.brain_id.clone(), client: self.mir.client.clone(), version: self.mir.applied, at: self.mir.synced_ms }; + let dir = self.mirror_dir(); let writing = self.mir.copy_writing.clone(); writing.store(true, Ordering::Release); let write = move || { - // The copy first, then what it is: a stop between the two leaves an older marker, - // which only means more is asked for next time. - let _ = std::fs::remove_file(copy_at_path()); + // The copy first, then what it is: a stop between the two leaves no marker, and the + // next start waits for the brain instead of showing a copy cut short. + let _ = std::fs::remove_file(copy_at_path(&dir)); if let Ok(s) = serde_json::to_string(&snap) { - if crate::httpd::write_private(&cache_path(), s.as_bytes()).is_ok() { + if crate::httpd::write_private(&cache_path(&dir), s.as_bytes()).is_ok() { if let Ok(a) = serde_json::to_vec(&at) { - let _ = crate::httpd::write_private(©_at_path(), &a); + let _ = crate::httpd::write_private(©_at_path(&dir), &a); } } } @@ -1483,7 +1879,10 @@ impl App { copy_own(local, &self.state); local.save(); } - if !self.mir.online || !self.mir.base.is_object() { + // (Nothing of the brain to compare with yet — at the door, the first time — nothing is + // edited.) Connected or not: the edit waits in the queue and goes once the brain is in + // reach, laid over whatever the brain has by then (mirror_apply). + if !self.mir.base.is_object() { return; } let cur = config_json(&mut self.state); @@ -1495,40 +1894,162 @@ impl App { self.mir.seq += 1; let seq = self.mir.seq; self.mir.pending.lock().unwrap().push((seq, ops.clone())); - self.mirror_out(Out::Edit { seq, ops }); + self.mirror_queue(Job::Edit { seq, ops }); } fn mirror_out(&mut self, o: Out) { + // Chat actions have a lane of their own: one never waits behind a message that waits + // for the brain (an answer or a stop pressed now goes now, as before the queue). + if let (Out::Act(body), Some(lane)) = (&o, &self.mir.acts) { + let _ = lane.send((body.clone(), crate::model::now_ms())); + return; + } if let Some(tx) = &self.mir.outbox { let _ = tx.send(o); } } + /// Into the queue (and onto disk) and to the sending thread. + fn mirror_queue(&mut self, job: Job) { + let it = Queued { job, at: crate::model::now_ms(), tried: 0, first: 0, trying: false, check: false }; + let key = it.key(); + { + let mut q = self.mir.queue.lock().unwrap_or_else(|e| e.into_inner()); + q.items.push(it); + q.save(); + } + self.mirror_out(Out::Queued(key)); + } + + /// 取消 on a message still waiting: out of the queue, its words and files back in the input. + /// Not one on its way this moment (it may arrive). + pub(super) fn mirror_unqueue(&mut self, key: &str) -> bool { + let job = { + let mut q = self.mir.queue.lock().unwrap_or_else(|e| e.into_inner()); + let Some(i) = q.items.iter().position(|i| i.key() == key && !i.trying && i.first == 0) else { return false }; + let it = q.items.remove(i); + q.save(); + it.job + }; + if let Job::Send { bot, text, atts, typed: true, .. } = job { + let draft = self.drafts.entry(bot).or_default(); + *draft = if draft.trim().is_empty() { text } else { format!("{text}\n{draft}") }; + self.att.pending.entry(bot).or_default().extend(atts); + } + true + } + /// One worker sends everything to the brain in order (a rename before the message that uses - /// it, two quick edits in the order they were made). + /// it, two quick edits in the order they were made). What waited in the queue on disk goes + /// first. fn mirror_outbox(&mut self) { let (tx, rx) = channel::(); + for it in self.mir.queue.lock().unwrap_or_else(|e| e.into_inner()).items.iter() { + let _ = tx.send(Out::Queued(it.key())); + } self.mir.outbox = Some(tx); let (s, err, client, pending, resync) = (self.state.remote.clone(), self.mir.error.clone(), self.mir.client.clone(), self.mir.pending.clone(), self.mir.resync.clone()); let (note, busy) = (self.mir.move_note.clone(), self.mir.moving.clone()); + let (queue, reach, g) = (self.mir.queue.clone(), self.mir.reach.clone(), self.mir.gen.clone()); + let gen = g.load(Ordering::SeqCst); let repaint = self.repaint_fn(); let back = self.mir.tx.clone(); - let sending = self.mir.sending.clone(); + // The chat actions' lane: each tried for up to SURE_SECS, as it always was. One pressed + // just after an edit or a message lets those go first (a moment, not as long as they + // wait): 執行 right after changing a routine runs the changed one. + let (atx, arx) = channel::<(Value, i64)>(); + self.mir.acts = Some(atx); + { + let (s, err, queue, g, repaint) = (s.clone(), err.clone(), queue.clone(), g.clone(), repaint.clone()); + std::thread::spawn(move || { + let waiting = || { + *err.lock().unwrap() = "網路不穩,正在重新傳送…".into(); + repaint(); + }; + for (body, made) in arx { + if g.load(Ordering::SeqCst) != gen { + break; + } + // (A card's answer doesn't wait: it goes to the card it names, whatever else + // is on the way.) + let wait = if body["action"] == "answer" { 0 } else { 10 }; + let until = std::time::Instant::now() + std::time::Duration::from_secs(wait); + while std::time::Instant::now() < until && queue.lock().unwrap_or_else(|e| e.into_inner()).items.iter().any(|i| i.at <= made) { + std::thread::sleep(std::time::Duration::from_millis(100)); + } + if let Err(e) = remote::sync_post_sure(&s, "act", &body, &waiting) { + *err.lock().unwrap() = format!("大腦沒有收到:{e}"); + } + repaint(); + } + }); + } std::thread::spawn(move || { // Said while a try is sent again (the line is down for a moment). let waiting = || { *err.lock().unwrap() = "網路不穩,正在重新傳送…".into(); repaint(); }; + let stay = || g.load(Ordering::SeqCst) == gen; + // Between tries: a moment (waiting for the brain to be in reach), or longer after the + // line failed (1, 2, 4… up to 20 s) — cut short the moment the lasting connection is + // back. + let shown = std::cell::Cell::new(std::time::Instant::now()); + let pause = |fails: u32| { + // (While it only waits, the window is told now and then, not three times a second.) + if fails > 0 || shown.get().elapsed().as_secs() >= 2 { + shown.set(std::time::Instant::now()); + repaint(); + } + let ms = if fails == 0 { 300 } else { (1000u64 << (fails - 1).min(5)).min(20_000) }; + let (until, link) = (std::time::Instant::now() + std::time::Duration::from_millis(ms), crate::tunnel::link_serial()); + while std::time::Instant::now() < until && stay() { + if fails > 0 && crate::tunnel::link_serial() != link { + break; + } + std::thread::sleep(std::time::Duration::from_millis(100)); + } + }; for o in rx { + if !stay() { + break; + } match o { - Out::Edit { seq, ops } => { - if let Err(e) = remote::sync_post_sure(&s, "edit", &json!({"ops": ops, "client": client, "seq": seq}), &waiting) { - *err.lock().unwrap() = format!("剛才的改動沒有存到大腦:{e}"); - pending.lock().unwrap().retain(|(n, _)| *n != seq); - resync.store(true, Ordering::SeqCst); + Out::Queued(key) => { + let mut go = |job: &mut Job| { + repaint(); + try_job(&s, &client, job) + }; + match deliver(&queue, &key, &crate::model::now_ms, &mut go, &|| reach.load(Ordering::SeqCst), &stay, &pause) { + Some((Job::Send { bot, text, .. }, Ok(_))) => { + if let Some(tx) = &back { + let _ = tx.send(Incoming::Sent { bot, text }); + } + } + // The brain itself said no — or, with the brain in reach all along, it + // still couldn't go however often it was tried (a line that only + // drops waits as long as it takes). + Some((Job::Send { bot, text, atts, typed, .. }, Err((gave_up, e)))) => { + let back_in = if typed { "(已放回輸入框)" } else { "" }; + // (Given up after tries that may have arrived, their answers lost: + // the person looks before sending it again.) + let maybe = if gave_up { ";它也可能已經到了,先看聊天裡有沒有再傳" } else { "" }; + *err.lock().unwrap() = format!("訊息沒有送到大腦{back_in}:{e}{maybe}"); + // (A command a button sent — 「/goal clear」 — isn't the person's words: it + // doesn't go into the input, where it would join what they type next.) + if let Some(tx) = back.as_ref().filter(|_| typed) { + let _ = tx.send(Incoming::Unsent { bot, text, atts }); + } + } + Some((Job::Edit { seq, .. }, Err((_, e)))) => { + *err.lock().unwrap() = format!("剛才的改動沒有存到大腦:{e}"); + pending.lock().unwrap().retain(|(n, _)| *n != seq); + resync.store(true, Ordering::SeqCst); + } + _ => {} } } + // (Actions go on their own lane — see mirror_out; here only without one.) Out::Act(body) => { if let Err(e) = remote::sync_post_sure(&s, "act", &body, &waiting) { *err.lock().unwrap() = format!("大腦沒有收到:{e}"); @@ -1544,44 +2065,6 @@ impl App { *err.lock().unwrap() = format!("大腦沒有改連接器的名稱:{e}"); } } - Out::Send { bot, id, text, atts, memories, typed } => { - // The files first (each asked again while the line is down); one that can't - // go keeps the whole message here — words without their file would be a - // different message. - let mut paths = vec![]; - let mut failed = None; - for a in &atts { - match std::fs::read(&a.path).map_err(|e| format!("讀不到這個檔案({e})")).and_then(|b| remote::sync_upload_sure(&s, bot, &a.name, &b, &waiting)) { - Ok(p) => paths.push(p), - Err(e) => { - failed = Some(format!("「{}」沒有傳到大腦:{e}", a.name)); - break; - } - } - } - let sent = match failed { - Some(e) => Err(e), - None => { - let mut body = json!({"bot": bot, "action": "send", "id": id, "text": text, "attachments": paths}); - if let Some(m) = memories { - body["memories"] = json!(m); - } - remote::sync_post_sure(&s, "act", &body, &waiting).map(|_| ()) - } - }; - if let Err(e) = sent { - let back_in = if typed { "(已放回輸入框)" } else { "" }; - *err.lock().unwrap() = format!("訊息沒有送到大腦{back_in}:{e}"); - // Take back the message shown ahead of time; its words and files go back to the input. - resync.store(true, Ordering::SeqCst); - // (A command a button sent — 「/goal clear」 — isn't the person's words: it - // doesn't go into the input, where it would join what they type next.) - if let Some(tx) = back.as_ref().filter(|_| typed) { - let _ = tx.send(Incoming::Unsent { bot, text: text.clone(), atts: atts.clone() }); - } - } - sending.fetch_sub(1, Ordering::AcqRel); - } Out::Move { ops, n, skills } => { let mut said = match remote::sync_post(&s, "edit", &json!({"ops": ops})) { Ok(_) if n == 0 => "已同步:大腦上已經有這台的 Bot;模型金鑰、技能和連接器有缺的已補上".to_string(), @@ -1613,10 +2096,12 @@ impl App { } /// A chat action on a screen goes to the brain (named, so a try sent again is done once). - /// While the line is down for a moment it waits in line and goes when it is back. + /// While the line is down for a moment it is sent again, for up to SURE_SECS. pub(super) fn mirror_act(&mut self, body: Value) { + // (Stop, regenerate, a card's answer…: done to what runs at the brain now, they don't + // wait in the queue for later.) if !self.mirror_can_send() { - *self.mir.error.lock().unwrap() = "連不到大腦,現在只能看。".into(); + *self.mir.error.lock().unwrap() = "連不到大腦:這個動作要連上才能做(訊息可以照樣傳,連上後送出)。".into(); return; } let mut body = body; @@ -1626,11 +2111,22 @@ impl App { self.mirror_out(Out::Act(body)); } - /// Whether what the person does here can go to the brain: connected, or connected before - /// and only away for a moment (it is queued and sent when the line is back, for up to a - /// minute). Before the first answer from the brain, nothing can. + /// Whether an action on what runs at the brain (stop, regenerate, a card's answer…) can go: + /// connected, or connected before and only away for a moment (it is sent again when the line + /// is back, for up to SURE_SECS). Before the first answer from the brain, none can. (Messages + /// and edits always can: they wait in the queue.) pub(super) fn mirror_can_send(&self) -> bool { - self.mir.online || (self.mir.base.is_object() && self.mir.down_since.is_none_or(|t| t.elapsed() < std::time::Duration::from_secs(remote::SURE_SECS))) + self.mir.online || (self.mir.synced && self.mir.down_since.is_none_or(|t| t.elapsed() < std::time::Duration::from_secs(remote::SURE_SECS))) + } + + /// Out of reach for more than a moment (a blip — the account server restarting — isn't). + pub(super) fn mirror_offline(&self) -> bool { + self.mir.on && !self.mir.online && self.mir.down_since.is_some_and(|t| t.elapsed().as_secs() >= 4) + } + + /// The messages waiting in the queue for one bot (all bots: 0). + pub(super) fn mirror_waiting(&self, bot: u64) -> Vec { + self.mir.queue.lock().unwrap_or_else(|e| e.into_inner()).items.iter().filter(|i| matches!(i.job, Job::Send { bot: b, .. } if bot == 0 || b == bot)).cloned().collect() } /// 連接器 › 重新連線 on a screen: the brain connects it again; its line says 連線中… until @@ -1641,7 +2137,7 @@ impl App { pub(super) fn mirror_mcp_reconnect(&mut self, name: &str) { if !self.mir.online { - *self.mir.error.lock().unwrap() = "連不到大腦,現在只能看。".into(); + *self.mir.error.lock().unwrap() = "連不到大腦:重新連線要連上才能做。".into(); return; } if self.mir.mcp_state["servers"].is_object() { @@ -1681,24 +2177,27 @@ impl App { self.mirror_send_from(bot, text.to_string(), vec![], None, false) } + /// A message into the queue: shown at once under the chat (傳送中…, or 等連上大腦後送出 with + /// 取消), sent in order however long the brain is out of reach — kept on disk while AnyBot is + /// closed — and done once at the brain (by its id). A button's command (not `typed`) is + /// done to the brain now, like stop: only with the brain in reach. fn mirror_send_from(&mut self, bot: u64, text: String, atts: Vec, memories: Option>, typed: bool) -> bool { - if !self.mirror_can_send() { - *self.mir.error.lock().unwrap() = "連不到大腦,訊息沒有送出。".into(); - return false; - } - // Shown at once; the brain's copy replaces it. - if !self.streams.contains_key(&bot) { - if let Some(b) = self.state.bot_mut(bot) { - b.messages.push(Message { attachments: atts.clone(), memories: memories.clone().unwrap_or_default(), ..Message::user(&text) }); - } - } // Settings changed just before go first. if self.dirty { self.mirror_save(); } + // (A button's command goes as an action: now, or not — never kept for later, when a + // 「/goal clear」 would clear a goal set since.) + if !typed { + if !self.mirror_can_send() { + *self.mir.error.lock().unwrap() = "連不到大腦:這個動作要連上才能做。".into(); + return false; + } + self.mirror_act(json!({"bot": bot, "action": "send", "text": text, "attachments": []})); + return true; + } let id = act_id(&self.mir.client); - self.mir.sending.fetch_add(1, Ordering::AcqRel); - self.mirror_out(Out::Send { bot, id, text, atts, memories, typed }); + self.mirror_queue(Job::Send { bot, id, text, atts, memories, typed, uploaded: vec![] }); true } @@ -1737,9 +2236,9 @@ impl App { self.mirror_out(Out::Move { ops, n, skills }); } - /// 連上才進去: a screen of a brain shows nothing of the brain until the brain's first answer - /// is in — then everything it shows is the brain as it is, and works (no old copy to read - /// while edits silently go nowhere, no 「只能看」). + /// The first time only (no copy of this brain on disk): nothing of the brain to show until its + /// first answer is in. With a copy the window shows it at once (mirror_open), and what is + /// done there waits in the queue — no edits that silently go nowhere, no 「只能看」. pub(super) fn mirror_waiting_at_door(&self) -> bool { self.mir.on && !self.demo && !self.mir.entered } @@ -1772,41 +2271,101 @@ impl App { ui.ctx().request_repaint_after(std::time::Duration::from_millis(500)); } - /// The bar above the chat while showing a brain. - pub(super) fn mirror_banner(&mut self, ui: &mut egui::Ui) { + /// What went wrong with a request to the brain: said once, in the line under the message box + /// (no band over the chat — the window stays as tall and as usable as when connected). + pub(super) fn mirror_banner(&mut self, _ui: &mut egui::Ui) { if !self.mir.on { return; } - let p = self.pal; let err = std::mem::take(&mut *self.mir.error.lock().unwrap()); if !err.is_empty() { self.notice = Some(err); } - if self.mir.online { + } + + /// 離線 (or 連線中…, before the brain's first answer): a small mark in the chat's top bar, + /// with how many messages wait; the pointer on it says what is shown and what happens to + /// what is done meanwhile. Nothing while connected, or away for only a moment. + pub(super) fn mirror_chip(&mut self, ui: &mut egui::Ui) { + if !self.mir.on || self.mir.online { return; } - // A blip (the account server restarting) isn't worth a warning. - let connecting = self.mir.down_since.is_none(); - let (title, reason, tail) = match self.mir.down_since { - None => (format!("正在連到大腦「{}」…", self.state.remote.brain_name), String::new(), String::new()), - Some(t) if t.elapsed().as_secs() < 4 => return, - Some(_) => (format!("連不到大腦「{}」", self.state.remote.brain_name), self.mir.reason.clone(), t("之前的對話還能看,但現在不能傳訊息。連回來後會自動恢復。")), + let p = self.pal; + let waiting = self.mirror_waiting(0).len(); + let offline = self.mirror_offline(); + let word = if offline { + if waiting > 0 { t("離線 · {n} 則等送出").replace("{n}", &waiting.to_string()) } else { t("離線") } + } else if self.mir.down_since.is_none() && !self.mir.synced { + t("連線中…") + } else { + // (A blip: shown if it lasts.) + ui.ctx().request_repaint_after(std::time::Duration::from_secs(1)); + return; }; + let name = if self.state.remote.brain_name.trim().is_empty() { t("大腦") } else { self.state.remote.brain_name.clone() }; + let mut tip = if offline { t("連不到大腦「{name}」").replace("{name}", &name) } else { t("正在連到大腦「{name}」…").replace("{name}", &name) }; + if offline && !self.mir.reason.is_empty() { + tip.push_str(&format!(":{}", self.mir.reason)); + } + tip.push('\n'); + if self.mir.synced_ms > 0 { + let when = chrono::DateTime::from_timestamp_millis(self.mir.synced_ms).map(|t| t.with_timezone(&chrono::Local)).map(|t| if t.date_naive() == chrono::Local::now().date_naive() { t.format("%H:%M").to_string() } else { t.format("%m/%d %H:%M").to_string() }).unwrap_or_default(); + tip.push_str(&t("顯示的是 {when} 同步的內容。").replace("{when}", &when)); + } + tip.push_str(&t("你傳的訊息和改的設定會先排著,連上後依序送出;停止、重新產生這類動作要連上才能做。")); + let font = egui::FontId::proportional(FONT_SM); + let galley = ui.painter().layout_no_wrap(word, font, p.text2); + let (rect, r) = ui.allocate_exact_size(vec2(10.0 + 6.0 + galley.size().x + 16.0, 28.0), egui::Sense::hover()); + let dot = egui::pos2(rect.left() + 8.0 + 4.0, rect.center().y); + ui.painter().circle_stroke(dot, 3.5, Stroke::new(1.5, p.text3)); + ui.painter().galley(egui::pos2(dot.x + 4.0 + 6.0, rect.center().y - galley.size().y / 2.0), galley, p.text2); + r.on_hover_text(tip); ui.ctx().request_repaint_after(std::time::Duration::from_secs(1)); - ui.vertical_centered(|ui| { - ui.set_max_width(TRANSCRIPT_MAX_WIDTH.min(ui.available_width() - 48.0)); - Frame::new().fill(if connecting { p.hover } else { p.danger.gamma_multiply(0.08) }).corner_radius(R_M).inner_margin(Margin::symmetric(12, 8)).show(ui, |ui| { + } + + /// Messages still in the queue for this bot, under its chat: faded, with where they stand + /// (傳送中…, 排隊中…, 等連上大腦後送出) and 取消 — back into the input — while one isn't on + /// its way this moment. + pub(super) fn mirror_queue_bubbles(&mut self, ui: &mut egui::Ui, bot: &Bot) { + if !self.mir.on { + return; + } + let p = self.pal; + let waiting = self.mirror_waiting(bot.id); + let mut cancel = None; + for it in &waiting { + let Job::Send { text, atts, .. } = &it.job else { continue }; + super::chat_ui::pending_bubble(ui, p, |ui| { ui.vertical(|ui| { - ui.label(RichText::new(title).size(FONT_SM).strong().family(crate::bold()).color(p.text)); - for line in [reason, tail] { - if !line.is_empty() { - ui.add(egui::Label::new(RichText::new(line).size(FONT_SM).color(p.text2)).wrap()); - } + if !text.trim().is_empty() { + ui.label(RichText::new(text.trim()).size(FONT_BASE).color(p.text2)); + } + for a in atts { + ui.label(RichText::new(t("附件:{name}").replace("{name}", &a.name)).size(FONT_SM).color(p.text3)); } }); }); - }); - ui.add_space(6.0); + ui.with_layout(Layout::right_to_left(Align::Min), |ui| { + if !it.trying && it.first == 0 && ui.add(egui::Label::new(RichText::new(t("取消")).size(FONT_XS).color(p.text2).underline()).sense(egui::Sense::click())).on_hover_text(t("不送了,放回輸入框")).on_hover_cursor(egui::CursorIcon::PointingHand).clicked() { + cancel = Some(it.key()); + } + let note = if it.trying { + t("傳送中…") + } else if self.mir.online { + t("排隊中…") + } else { + t("等連上大腦後送出") + }; + ui.label(RichText::new(note).size(FONT_XS).color(p.text3)); + }); + ui.add_space(6.0); + } + if let Some(key) = cancel { + self.mirror_unqueue(&key); + } + if !waiting.is_empty() { + ui.ctx().request_repaint_after(std::time::Duration::from_millis(500)); + } } } @@ -1840,6 +2399,247 @@ mod tests { use super::*; + /// A screen of brain "brain-1" keeping its copy and queue in `dir` (a test's own folder), + /// without the network: its threads aren't started, and nothing is written to this + /// computer's own file. + fn screen_in(ctx: &egui::Context, dir: &std::path::Path) -> App { + let mut s = App::new(ctx, Some(dir.join("shot.png"))); + s.state.remote.brain_id = "brain-1".into(); + s.state.remote.brain_name = "大腦".into(); + s.mir.client = "screen-1".into(); + s.mir.dir = dir.to_path_buf(); + // (Made from the screenshot data, but a screen like any other: the door is shown.) + s.demo = false; + s.mirror_open(); + s.mir.local = None; + s + } + + /// A screen holding just the brain's settings has no edit to send: the settings as the brain + /// sends them read back the same (a routine without a trigger used to come with + /// `"trigger": null`, and every save sent all routines back — from an old copy, too). + #[test] + fn the_brains_settings_read_back_the_same() { + let ctx = egui::Context::default(); + let mut brain = App::new(&ctx, Some(std::env::temp_dir().join("anybot-read-back.png"))); + assert!(brain.state.bots.iter().any(|b| b.routines.iter().any(|r| r.trigger.is_none())), "the demo has a routine without a trigger"); + let c = brain.brain_pull("read-back", 0, true, false)["config"].clone(); + let mut st: State = serde_json::from_value(c.clone()).unwrap(); + assert_eq!(diff_ops(&c, &config_json(&mut st)), Vec::::new()); + } + + fn fresh_dir(name: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("anybot-screen-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d + } + + /// A brain whose first bot is called 「大腦的 Bot」, and a screen that took its first answer + /// (and wrote its copy). + fn brain_and_screen(ctx: &egui::Context, dir: &std::path::Path) -> (App, App) { + let mut brain = App::new(ctx, Some(dir.join("brain.png"))); + brain.state.bots[0].name = "大腦的 Bot".into(); + let mut screen = screen_in(ctx, dir); + screen.mir.online = true; + screen.mirror_apply(brain.brain_pull("screen-1", 0, true, false)); + screen.mir.copy_at = None; + screen.mirror_flush_copy(true); + while screen.mir.copy_writing.load(Ordering::Acquire) { + std::thread::sleep(std::time::Duration::from_millis(5)); + } + (brain, screen) + } + + /// 有副本就直接進去: a screen that has this brain's copy shows it at once, with no network — + /// the brain's bots, edits possible; only the first time (no copy), or with another brain's + /// copy, it waits at the door. + #[test] + fn a_screen_with_a_copy_goes_in_at_once() { + let ctx = egui::Context::default(); + let dir = fresh_dir("copy-door"); + let first = screen_in(&ctx, &dir); + assert!(first.mirror_waiting_at_door(), "no copy yet: it waits for the brain"); + let (brain, screen) = brain_and_screen(&ctx, &dir); + assert!(!screen.mirror_waiting_at_door()); + // Started again, the brain out of reach. + let again = screen_in(&ctx, &dir); + assert!(!again.mirror_waiting_at_door(), "in at once, from the copy"); + assert_eq!(again.state.bots[0].name, "大腦的 Bot"); + assert_eq!(again.state.bots.len(), brain.state.bots.len()); + assert!(again.mir.base.is_object(), "edits can be made: what the brain had is known"); + assert!(again.mir.synced_ms > 0, "and when it was"); + assert!(!again.mirror_can_send(), "stop, regenerate…: only once the brain answers"); + // Another brain: its bots aren't this copy's. + let mut other = App::new(&ctx, Some(dir.join("other.png"))); + other.state.remote.brain_id = "brain-2".into(); + other.mir.dir = dir.clone(); + other.demo = false; + other.mirror_open(); + assert!(other.mirror_waiting_at_door()); + let _ = std::fs::remove_dir_all(&dir); + } + + /// 沒網路照樣能送: a message sent while the brain is out of reach waits in the queue (on + /// disk: a restart keeps it), goes once the brain is back, and — when the first try arrived + /// but its answer was lost — the try again is the same message (its id): the brain does it + /// once, and the screen shows it once. + #[test] + fn a_message_sent_offline_reaches_the_brain_once() { + let ctx = egui::Context::default(); + let dir = fresh_dir("offline-send"); + let (mut brain, mut screen) = brain_and_screen(&ctx, &dir); + let id = brain.state.bots[0].id; + screen.mir.online = false; + screen.mir.down_since = Some(Instant::now() - std::time::Duration::from_secs(30)); + assert!(screen.mirror_offline()); + assert!(screen.mirror_send(id, "離線時打的".into(), vec![], None)); + assert!(screen.mir.error.lock().unwrap().is_empty()); + // AnyBot closed and opened again: it still waits. + let mut screen = screen_in(&ctx, &dir); + let waiting = screen.mirror_waiting(id); + assert_eq!(waiting.len(), 1, "the queue was kept on disk"); + let key = waiting[0].key(); + // The sending thread: nothing goes while the brain is out of reach; once it is back, the + // first try arrives but its answer is lost on the way; the next is the same message. + let up = std::cell::Cell::new(false); + let (mut tries, mut ids) = (0, std::collections::HashSet::new()); + let seen = screen.mir.queue.clone(); + let mut go = |job: &mut Job| { + tries += 1; + if tries == 2 { + // A try may have arrived (its answer was lost): it can't be taken back now. + assert!(seen.lock().unwrap().items[0].first > 0); + } + let Job::Send { bot, id, text, .. } = job else { panic!("{job:?}") }; + assert!(up.get(), "not tried while out of reach"); + // (What the brain does: remote.rs first_delivery, by the message's id.) + if ids.insert(id.clone()) { + brain.state.bot_mut(*bot).unwrap().messages.push(Message::user(text)); + } + if tries == 1 { Err((true, "和大腦的連線到一半斷掉了".into())) } else { Ok(json!({"ok": true, "again": true})) } + }; + let q = screen.mir.queue.clone(); + let out = deliver(&q, &key, &crate::model::now_ms, &mut go, &|| up.get(), &|| true, &|_| up.set(true)); + assert!(matches!(out, Some((Job::Send { .. }, Ok(_)))), "{out:?}"); + assert_eq!(tries, 2); + let count = |b: &Bot| b.messages.iter().filter(|m| m.text == "離線時打的").count(); + assert_eq!(count(brain.state.bot(id).unwrap()), 1, "done once at the brain"); + assert!(screen.mirror_waiting(id).is_empty() && !queue_path(&dir, "brain-1").exists(), "out of the queue, and off the disk: {:?}", screen.mir.queue.lock().unwrap().items); + // The brain's next answer brings it into the screen's chat, once. + screen.mir.online = true; + let since = screen.mir.applied; + screen.mirror_apply(brain.brain_pull("screen-1", since, true, false)); + assert_eq!(count(screen.state.bot(id).unwrap()), 1); + let _ = std::fs::remove_dir_all(&dir); + } + + /// A message whose first try that may have arrived is older than the brain remembers ids + /// isn't sent blind — even when later tries (that never got there) were recent: the window + /// looks in the brain's chat first, from that first try on — there (it arrived, its answer + /// was lost): done; not there: it goes again (and can be taken back meanwhile). + #[test] + fn a_message_tried_long_ago_is_looked_for_first() { + let ctx = egui::Context::default(); + let dir = fresh_dir("tried-long-ago"); + let (_brain, mut screen) = brain_and_screen(&ctx, &dir); + let id = screen.state.bots[0].id; + let now = crate::model::now_ms(); + let long_ago = now - 15 * 60_000; + for (n, text) in ["到了的", "沒到的"].into_iter().enumerate() { + screen.mirror_queue(Job::Send { bot: id, id: format!("x-{n}"), text: text.into(), atts: vec![], memories: None, typed: true, uploaded: vec![] }); + let mut q = screen.mir.queue.lock().unwrap(); + (q.items[n].first, q.items[n].tried) = (long_ago, now - 60_000); + } + assert!(!screen.mirror_unqueue("send:x-1"), "it may be at the brain: not taken back"); + // The sending thread doesn't try it: it asks the window to look. + let q = screen.mir.queue.clone(); + let pauses = std::cell::Cell::new(0); + let out = deliver(&q, "send:x-0", &crate::model::now_ms, &mut |_: &mut Job| -> Result { panic!("sent blind") }, &|| true, &|| pauses.get() < 3, &|_| pauses.set(pauses.get() + 1)); + assert!(out.is_none()); + q.lock().unwrap().items[1].check = true; + // The brain's chat (as an answer after the last try brought it) has the first — it + // arrived with the first try, long before the last — and not the second. + screen.state.bot_mut(id).unwrap().messages.push(Message { at: long_ago + 2_000, ..Message::user("到了的") }); + screen.mir.online = true; + screen.mir.synced_ms = now; + screen.mirror_check_queue(); + let left = screen.mirror_waiting(id); + assert_eq!(left.len(), 1); + assert!(matches!(&left[0].job, Job::Send { text, .. } if text == "沒到的")); + assert!(!left[0].check && left[0].tried == 0 && left[0].first == 0, "it goes again"); + assert!(screen.mirror_unqueue("send:x-1"), "known not to be there: it can be taken back"); + let _ = std::fs::remove_dir_all(&dir); + } + + /// The brain answers all along, yet a message can't go (a file too big for the line, the + /// brain's disk full): after GIVE_UP_AFTER tries it is given up and said so — the queue isn't + /// stuck behind it. A line that only drops (the brain out of reach between tries) waits on. + #[test] + fn a_job_that_never_goes_while_the_brain_answers_is_given_up() { + let q = Mutex::new(Outq::default()); + let job = Job::Send { bot: 1, id: "big".into(), text: "看這個".into(), atts: vec![], memories: None, typed: true, uploaded: vec![] }; + q.lock().unwrap().items.push(Queued { job, at: 0, tried: 0, first: 0, trying: false, check: false }); + let tries = std::cell::Cell::new(0u32); + let up = std::cell::Cell::new(true); + let mut go = |_: &mut Job| -> Result { + tries.set(tries.get() + 1); + // (Out of reach once, midway: the count starts over.) + if tries.get() == 10 { + up.set(false); + } + Err((true, "逾時".into())) + }; + let out = deliver(&q, "send:big", &crate::model::now_ms, &mut go, &|| up.get(), &|| true, &|f| if f == 0 { up.set(true) }); + assert!(matches!(out, Some((_, Err(_))))); + assert_eq!(tries.get(), 10 + GIVE_UP_AFTER, "the line's failures before it was out of reach don't count"); + assert!(q.lock().unwrap().items.is_empty()); + // Files already up aren't sent again on the next try. + let mut sent = Job::Send { bot: 1, id: "f".into(), text: String::new(), atts: vec![crate::attach::Attachment { name: "a.png".into(), path: "/nonexistent/a.png".into(), image: true, bytes: 1, on_box: String::new() }], memories: None, typed: true, uploaded: vec!["/brain/a.png".into()] }; + let s = crate::remote::Settings::default(); + let r = try_job(&s, "c", &mut sent); + assert!(r.is_err_and(|(_, e)| !e.contains("讀不到")), "the file here wasn't read again"); + } + + /// 沒網路照樣能改設定: an edit made while the brain is out of reach waits in the queue; the + /// brain's newer settings, when they come, keep it on top (nothing the brain changed + /// meanwhile is undone), and once it is sent the brain has both. + #[test] + fn an_edit_made_offline_lands_on_the_brains_newer_settings() { + let ctx = egui::Context::default(); + let dir = fresh_dir("offline-edit"); + let (mut brain, mut screen) = brain_and_screen(&ctx, &dir); + let (a, b) = (brain.state.bots[0].id, brain.state.bots[1].id); + screen.mir.online = false; + screen.mir.down_since = Some(Instant::now() - std::time::Duration::from_secs(30)); + screen.state.bot_mut(a).unwrap().name = "螢幕上改的".into(); + screen.mirror_save(); + let edits: Vec = screen.mir.queue.lock().unwrap().items.clone(); + assert_eq!(edits.len(), 1); + // Meanwhile, at the brain. + brain.state.bot_mut(b).unwrap().name = "大腦上改的".into(); + // Back: the brain's answer comes before the edit has gone. + screen.mir.online = true; + let since = screen.mir.applied; + screen.mirror_apply(brain.brain_pull("screen-1", since, false, false)); + let names = |app: &App| (app.state.bot(a).unwrap().name.clone(), app.state.bot(b).unwrap().name.clone()); + assert_eq!(names(&screen), ("螢幕上改的".into(), "大腦上改的".into()), "the edit stays on top of the brain's newer settings"); + // The edit goes (twice: its answer lost the first time) — done once. + let mut go = |job: &mut Job| { + let Job::Edit { seq, ops } = job else { panic!() }; + Ok(brain.brain_edit(&json!({"ops": ops, "client": "screen-1", "seq": seq}))) + }; + let q = screen.mir.queue.clone(); + deliver(&q, &edits[0].key(), &crate::model::now_ms, &mut go, &|| true, &|| true, &|_| {}).unwrap().1.unwrap(); + let Job::Edit { seq, ops } = &edits[0].job else { panic!() }; + assert_eq!(brain.brain_edit(&json!({"ops": ops, "client": "screen-1", "seq": seq}))["again"], true); + assert_eq!(names(&brain), ("螢幕上改的".into(), "大腦上改的".into())); + screen.mirror_apply(brain.brain_pull("screen-1", screen.mir.applied, false, false)); + assert_eq!(names(&screen), names(&brain)); + assert!(screen.mir.pending.lock().unwrap().is_empty(), "the brain has it: no longer laid on top"); + let _ = std::fs::remove_dir_all(&dir); + } + /// 螢幕電腦上回答的卡帶著大腦給那張卡的 key(.claude/skills/verify-approval-routing 的 /// ScreenRefreshes → YouAnswerOnScreen → BrainTakesAnswer):大腦只把它交給那張卡。以前 /// 不帶,大腦交給那時候在等的卡(F1)。 @@ -2020,6 +2820,61 @@ mod tests { assert_eq!(back["bots"][0]["from"], m, "the lost change again"); } + /// Away from the brain, the next numbers may be given at the brain meanwhile (a new bot + /// elsewhere, a 支線). A bot or routine made on the screen while away is numbered far past + /// them, so the screen's later edits (and messages) by that number reach its own, never the + /// brain's; and the brain counts on past it. + #[test] + fn a_screen_away_doesnt_take_the_brains_numbers() { + let ctx = egui::Context::default(); + let dir = fresh_dir("numbers"); + let (mut brain, mut screen) = brain_and_screen(&ctx, &dir); + let (n, r) = (brain.state.next_id, brain.state.next_routine_id); + screen.mir.online = false; + screen.mirror_spare_numbers(); + screen.mirror_save(); + assert!(screen.mir.queue.lock().unwrap().items.is_empty(), "only moving the count on isn't an edit"); + // Away: a new bot, renamed after; a new routine on the first bot. + let mine = screen.state.next_id; + let mut b = screen.state.bots[0].clone(); + (b.id, b.name, b.routines) = (mine, "螢幕上新增的".into(), vec![]); + screen.state.bots.push(b); + screen.state.next_id += 1; + screen.mirror_save(); + screen.state.bot_mut(mine).unwrap().name = "螢幕上改過名的".into(); + screen.mirror_save(); + let first = screen.state.bots[0].id; + let rid = screen.state.next_routine_id; + let mut routine = brain.state.bots.iter().flat_map(|b| &b.routines).next().expect("the demo has a routine").clone(); + (routine.id, routine.title) = (rid, "螢幕的".into()); + screen.state.bot_mut(first).unwrap().routines.push(routine.clone()); + screen.mirror_save(); + assert!(mine >= n + 1000 && rid >= r + 1000, "{mine} {rid}"); + // Meanwhile at the brain: bot n and routine r. + let mut theirs = brain.state.bots[0].clone(); + (theirs.id, theirs.name) = (n, "大腦這邊新的".into()); + brain.state.bots.push(theirs); + (routine.id, routine.title) = (r, "大腦的".into()); + brain.state.bot_mut(first).unwrap().routines.push(routine); + (brain.state.next_id, brain.state.next_routine_id) = (n + 1, r + 1); + // Back: the edits go. + // (AnyBot closed and opened again, still away: the next numbers are past those made.) + let mut again = screen_in(&ctx, &dir); + again.mirror_spare_numbers(); + assert!(again.state.next_id > mine && again.state.next_routine_id > rid, "{} {}", again.state.next_id, again.state.next_routine_id); + let jobs: Vec = screen.mir.queue.lock().unwrap().items.clone(); + for j in &jobs { + let Job::Edit { seq, ops } = &j.job else { panic!() }; + brain.brain_edit(&json!({"ops": ops, "client": "screen-1", "seq": seq})); + } + assert_eq!(brain.state.bot(n).unwrap().name, "大腦這邊新的", "the brain's bot untouched"); + assert_eq!(brain.state.bot(mine).unwrap().name, "螢幕上改過名的"); + let titles: Vec<(u64, String)> = brain.state.bot(first).unwrap().routines.iter().map(|x| (x.id, x.title.clone())).collect(); + assert!(titles.contains(&(r, "大腦的".into())) && titles.contains(&(rid, "螢幕的".into())), "{titles:?}"); + assert!(brain.state.next_id > mine && brain.state.next_routine_id > rid, "the brain counts on past them"); + let _ = std::fs::remove_dir_all(&dir); + } + /// The same edit sent again (its answer was lost): done once — 「新增 Bot」 twice was two bots. #[test] fn an_edit_sent_twice_is_done_once() { diff --git a/src/app/remote_ui.rs b/src/app/remote_ui.rs index 227c42b..dd1b56c 100644 --- a/src/app/remote_ui.rs +++ b/src/app/remote_ui.rs @@ -918,7 +918,7 @@ impl App { setting_card(ui, p, |ui| { ui.horizontal(|ui| { ui.label(RichText::new(t("大腦")).size(FONT_BASE).strong().family(crate::bold())); - help_mark(ui, "帳號裡選一台 AnyBot 當大腦(通常是跟帳號伺服器放在一起、一直開著的那台)。所有 Bot、聊天、記憶和例行任務都放在大腦上,由它思考和排程。其他電腦打開 AnyBot 看到的都是同一份,同時也是大腦的手腳:大腦的 Bot 可以透過裝置連結操作它們。大腦連不到時,這裡還能看之前的對話,但不能傳訊息,連回來就恢復。", p); + help_mark(ui, "帳號裡選一台 AnyBot 當大腦(通常是跟帳號伺服器放在一起、一直開著的那台)。所有 Bot、聊天、記憶和例行任務都放在大腦上,由它思考和排程。其他電腦打開 AnyBot 看到的都是同一份,同時也是大腦的手腳:大腦的 Bot 可以透過裝置連結操作它們。大腦連不到時,照樣看得到上次同步的內容,也能傳訊息、改設定:先排著,連回來後依序送出;停止、重新產生這類動作要連上才能做。", p); }); let s = &self.state.remote; let status = self.mir.status.lock().unwrap().clone(); diff --git a/src/remote.rs b/src/remote.rs index b77c051..0a832c5 100644 --- a/src/remote.rs +++ b/src/remote.rs @@ -2676,11 +2676,19 @@ pub fn sync_post_sure(s: &Settings, what: &str, body: &Value, waiting: &dyn Fn() post_sure(s, &format!("/{what}"), &[], body.to_string().as_bytes(), SURE_TRY_SECS, waiting) } -/// sync_upload, asked again while the line is down (a file sent twice is only a second copy at -/// the brain, never a second message). -pub fn sync_upload_sure(s: &Settings, bot: u64, name: &str, bytes: &[u8], waiting: &dyn Fn()) -> Result { - let v = post_sure(s, &format!("/upload/{bot}"), &[("name", name.to_string())], bytes, 120, waiting)?; - v["path"].as_str().map(String::from).ok_or("大腦沒有收下檔案".into()) +/// One try of a screen's queued message, edit or file for one (`rest`: "/act", "/edit", +/// "/upload/"), telling the line from the brain: Err((true, why)) — the line, the account +/// server (out of reach, busy, its sign-in to be done again) or a brain out of reach stood in +/// between, worth trying again later; Err((false, why)) — the brain itself said no, and trying +/// again won't change that. +pub fn sync_try(s: &Settings, rest: &str, query: &[(&str, String)], bytes: &[u8], secs: u64) -> Result { + let (st, b) = to_brain_any(s, "POST", rest, query, bytes, secs).map_err(|e| (true, e))?; + if st == 404 && serde_json::from_slice::(&b).map(|v| v["error"] == NO_SUCH_PATH).unwrap_or(false) { + return Err((false, brain_too_old(&s.brain_name))); + } + // (A 200 that isn't JSON: a page of the network's own, a Wi-Fi sign-in, not the brain.) + let line = matches!(st, 401 | 403 | 408 | 429 | 502..=504) || ((200..300).contains(&st) && serde_json::from_slice::(&b).is_err()); + answer_value(st, &b, "大腦").map_err(|e| (line, e)) } fn post_sure(s: &Settings, rest: &str, query: &[(&str, String)], bytes: &[u8], try_secs: u64, waiting: &dyn Fn()) -> Result {