From 43cdb06e482df341a0994d793d5666281d56dd02 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=80=A7=E9=A9=8A?= Date: Tue, 24 Nov 2026 16:12:56 +0800 Subject: [PATCH] =?UTF-8?q?=E8=A3=9D=E7=BD=AE=E9=A1=AF=E7=A4=BA=E9=9B=A2?= =?UTF-8?q?=E7=B7=9A=E6=99=82=E8=AA=AA=E5=BE=97=E5=87=BA=E5=8E=9F=E5=9B=A0?= =?UTF-8?q?=EF=BC=8C=E5=90=8C=E5=90=8D=E7=9A=84=E9=9B=BB=E8=85=A6=E4=B8=8D?= =?UTF-8?q?=E5=86=8D=E4=BA=92=E8=B8=A2=E3=80=81=E5=90=8C=E4=B8=80=E5=80=8B?= =?UTF-8?q?=E7=99=BB=E5=85=A5=E7=9A=84=E5=85=A9=E4=BB=BD=E4=B8=8D=E5=86=8D?= =?UTF-8?q?=E5=81=87=E8=A3=9D=E5=9C=A8=E7=B7=9A=EF=BC=9A=E5=B8=B3=E8=99=9F?= =?UTF-8?q?=E4=BC=BA=E6=9C=8D=E5=99=A8=E6=8A=8A=E6=AF=8F=E5=8F=B0=E9=9B=BB?= =?UTF-8?q?=E8=85=A6=E9=80=A3=E4=B8=8A=E3=80=81=E6=96=B7=E7=B7=9A=E5=92=8C?= =?UTF-8?q?=E5=8E=9F=E5=9B=A0=EF=BC=88=E5=AE=83=E9=82=A3=E9=82=8A=E9=97=9C?= =?UTF-8?q?=E6=8E=89=E4=BA=86=E9=80=A3=E7=B7=9A=E3=80=81=E8=B6=85=E9=81=8E?= =?UTF-8?q?=2060=20=E7=A7=92=E6=B2=92=E6=9C=89=E8=A8=8A=E8=99=9F=E3=80=81?= =?UTF-8?q?=E9=80=A3=E7=B7=9A=E8=A2=AB=E5=88=87=E6=96=B7=E2=80=A6=EF=BC=89?= =?UTF-8?q?=E5=AF=AB=E9=80=B2=E7=B4=80=E9=8C=84=EF=BC=88deploy/server/setu?= =?UTF-8?q?p.sh=20--log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=E8=AA=AA=E8=A6=81=E9=87=8D=E6=96=B0=E7=99=BB?= =?UTF-8?q?=E5=85=A5=EF=BC=8C=E6=89=8B=E8=85=B3=E9=9B=BB=E8=85=A6=E8=AA=AA?= =?UTF-8?q?=E8=A6=81=E6=96=B0=E7=9A=84=E9=85=8D=E5=B0=8D=E7=A2=BC=EF=BC=89?= =?UTF-8?q?=E3=80=82=E5=8A=9F=E8=83=BD=E5=9C=B0=E5=9C=96=20computers?= =?UTF-8?q?=EF=BC=88=E6=96=B0=E7=9A=84=20computers-online=E3=80=81?= =?UTF-8?q?=E5=AE=83=E7=9A=84=E9=A9=97=E8=AD=89=E6=AD=A5=E9=A9=9F=E5=92=8C?= =?UTF-8?q?=E8=88=8A=E7=89=88=E5=85=A9=E4=BB=BD=E8=BC=AA=E6=B5=81=E7=9A=84?= =?UTF-8?q?=E9=99=B7=E9=98=B1=EF=BC=89=E3=80=81garden=E3=80=81server=20?= =?UTF-8?q?=E5=92=8C=20FEATURES=20=E8=B7=9F=E8=91=97=E6=94=B9=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 已驗證: cargo test 全部(909)、relay/ cargo test(31 個,含新的:同名不互踢、帶證明重新登入只換自己那列並保留「名字 (2)」、被取代的連線結束並說原因、me_online)、cargo test tunnel::(被取代會說明並等、位置空了才回來)、featuremap::;四輪乾淨脈絡的獨立審查——第一輪 P1「兩份每 5 分鐘輪流」、第三輪 P1「帶證明重新登入仍換掉睡著的同名電腦」都改了並加了測試,第二輪指出「登入後改用帳號給的名字」會讓 Bot 的做事電腦對到別台,已拿掉;第四輪沒有 P0/P1,之後只改 4 個 P2(保留自己的「(2)」、紀錄格式、手腳電腦的提示、位置查詢走 self_hop);verify-anybot 照功能地圖實跑:garden「量連線」(✓ 這台的登入;移出帳號後 ✗、結束碼 1)、computers「離線說得出原因」(scratch 帳號伺服器+--serve:relay.log 連上/斷線和原因、手機頂端「那台 AnyBot 目前離線:…。連上後自動更新」截圖、/relay/me 的 why 和時間;拿失效金鑰連線時兩邊的紀錄)。 未驗證: 真的帳號伺服器(nobledesktop、ai、mindroad)還沒換新版——要 make update-server,會重開雲端大腦,等使用者同意;兩份 AnyBot 真的在兩台電腦同時跑、真的手機、Cloudflare 後面的長連線:靠自動測試和 scratch,沒有實機。留著的 P2:全新登入(沒有原本那列的金鑰)時仍會把睡著的同名電腦當成這台以前的換掉,要靠機器指紋才分得出;帶證明重新登入的那一刻,舊連線會用失效的金鑰再敲一次門(多一行紀錄)。relay 測試有一次偶發失敗(主程式同時在建置),之後連跑 25 次都過,新加的兩個連跑 12 次都過。 Co-Authored-By: Claude Opus 5.5 --- FEATURES.md | 6 +- docs/feature-map/computers.md | 3 + docs/feature-map/garden.md | 4 +- docs/feature-map/server.md | 1 + mobile/index.html | 11 +- relay/src/main.rs | 362 ++++++++++++++++++++++++++++++++-- src/remote.rs | 87 ++++++-- src/setup.rs | 6 +- src/tunnel.rs | 129 +++++++++++- 9 files changed, 567 insertions(+), 42 deletions(-) diff --git a/FEATURES.md b/FEATURES.md index 29c11f1..1e9eb0c 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -1651,7 +1651,7 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - 聊天打 /doctor:這台電腦的 AnyBot 一項一行 ✓ 或 ✗:版本、資料夾、今天的紀錄檔;這台 ↔ 帳號伺服器(長連線的狀態);帳號伺服器是 *.ts.net 時,Tailscale 是直連還是走它在哪裡的中繼(`tailscale ping`;走中繼會寫延遲和「多半是中間擋了 UDP 41641」);帳號伺服器 ↔ 大腦(帳號伺服器說在不在線上);螢幕連不連得到大腦和原因;上次同步的大小和速度(1 MB 以上、每秒不到 300 KB 算慢);每個 Bot 用到的模型服務連不連得到(列模型清單);Bot 的電腦;每個開著的連接器;磁碟剩多少(少於 2 GB 算 ✗);指令有沒有沙盒(macOS 的 sandbox-exec、Linux 的 Landlock 第幾版,沒有就 ✗);上次內部出錯。要上網的檢查在背景跑,好了一次留一行。 - 在連到大腦的螢幕電腦上檢查的是這台本身(大腦連不到時正是要用的時候),結果跳成提示;手機打的是大腦檢查自己。 -- **連線體檢**:每一段量真的數字。這台 ↔ 帳號伺服器:小請求連打四次,第一次含建立連線(和 TLS)另外寫,其餘取中位數當來回時間;再下載 256 KB(帳號伺服器的 `/api/speed`,給的是壓不小的亂數,Cloudflare、Caddy 都縮不了,量到的是真的線速)。螢幕電腦再量到大腦:大腦的 `/api/sync/ping` 由網路那條執行緒直接回、不經過視窗,三次取中位數,扣掉第一段就是帳號伺服器 ↔ 大腦。來回超過 400 ms、或每秒不到 300 KB 是 ✗,寫「每個動作都會等」「同步和檔案會等很久」或「問題在大腦那台的網路」。帳號伺服器或大腦是舊版(沒有這兩個網址)就說量不到、更新後就有,不算錯。沒有視窗的電腦用 `anybot --doctor`(只讀設定,AnyBot 開著也能跑;有 ✗ 結束碼 1)。 +- **連線體檢**:每一段量真的數字。這台 ↔ 帳號伺服器:小請求連打四次,第一次含建立連線(和 TLS)另外寫,其餘取中位數當來回時間;再下載 256 KB(帳號伺服器的 `/api/speed`,給的是壓不小的亂數,Cloudflare、Caddy 都縮不了,量到的是真的線速)。螢幕電腦再量到大腦:大腦的 `/api/sync/ping` 由網路那條執行緒直接回、不經過視窗,三次取中位數,扣掉第一段就是帳號伺服器 ↔ 大腦。來回超過 400 ms、或每秒不到 300 KB 是 ✗,寫「每個動作都會等」「同步和檔案會等很久」或「問題在大腦那台的網路」。帳號伺服器或大腦是舊版(沒有這兩個網址)就說量不到、更新後就有,不算錯。再問帳號伺服器還認不認得這台的登入:不認得就 ✗「被移出帳號,或被同名的電腦換掉了」、要重新登入(長連線現在的狀態是 App 裡的檢查原本第一行「這台 ↔ 帳號伺服器」)。沒有視窗的電腦用 `anybot --doctor`(只讀設定,AnyBot 開著也能跑;有 ✗ 結束碼 1)。 ### 自動審核的固定樣式規則 @@ -2369,6 +2369,10 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - 裝置連結:讓帳號裡其他的 AnyBot 操作這台電腦。 - **直接連線的裝置**:列出手機和最近使用時間,可以個別登出。 - **帳號裡的電腦**:列出每台 AnyBot 在線或離線。 + - 離線的寫原因:帳號伺服器記下每台電腦的連線為什麼結束(「它那邊關掉了連線(AnyBot 關了、電腦睡眠,或網路換了)」「超過 60 秒沒有它的任何訊號」「連線被切斷(…代理把它切了)」「送資料給它時斷了」),手機的電腦清單寫「離線(時間)· 原因」,正在用的大腦斷線時手機頂端寫「那台 AnyBot 目前離線:原因。連上後自動更新」(提示左右留邊、太長就換行),`anybot setup` 的大腦清單也寫。帳號伺服器重開過就只剩時間。斷線那一刻就記下最後在線的時間(以前每分鐘才記,連不到一分鐘就斷的寫「從未連線」)。 + - 同名的電腦不互踢:登入時帳號裡已經有一台同名、而且正連著的,新的這台在帳號裡叫「名字 (2)」(這台自己的名字不變,Bot 設定裡指到它的名字照舊有效;以前把正連著的那台換掉並掛斷,它之後一直拿失效的金鑰重試,只看得到「離線」);同名但沒連著的那一列當成這台以前的(重裝、金鑰掉了)換掉;在同一台帳號伺服器重新登入時,帶著原本那一列的金鑰(只送給發它的那台),只換掉自己那一列:同名的別台就算睡著也不動,自己原本是「名字 (2)」就還是「名字 (2)」。 + - 同一個登入跑兩份 AnyBot(同一台開了兩份、資料夾被複製到別台):以前新的連線接手請求、舊的連線還掛著,新的斷了以後舊的讓這台一直顯示在線上,送過去的事卻 8 秒後都說離線。現在被取代的那條連線會被告知並結束,那一份的狀態寫「另一份 AnyBot 正用這台電腦的登入連著帳號伺服器…它斷了這份才連回去」,15 秒後先問一次、之後每 5 分鐘問帳號伺服器(`/relay/host/peers` 的 `me_online`),另一份還連著就繼續等(搶回來的話兩份會一直輪流,手機一下看到這個大腦、一下看到那個)。同一台換了網路、在帳號伺服器發現舊連線斷掉以前就重新連上的,舊的那條只是被接手,不算兩份(帳號伺服器看舊的那條被告知後有沒有回應關閉);接手的那條自己也斷了時,舊的那條被請去重新連上,不是叫它等。兩份舊版 AnyBot 用同一個登入時,舊版一被告知就馬上連回去,兩份會每十幾秒輪流,要把兩份都更新。 + - 紀錄:電腦這邊,跟帳號伺服器的連線狀態變了就寫進紀錄(「連線中…」除外),雲端大腦和沒有視窗的電腦也查得到;帳號伺服器那邊寫每台連上、斷線和原因、被取代和兩份輪流連上(同一台十分鐘寫一次)、被移出、同名改名,和拿不認得的金鑰來連的位址(同一個位址十分鐘寫一次;完全沒帶金鑰的不寫)——伺服器上 `deploy/server/setup.sh --logs relay`。電腦的名字寫進紀錄前換掉換行這類控制字元。 ### 不開視窗執行(`anybot --serve`) diff --git a/docs/feature-map/computers.md b/docs/feature-map/computers.md index 404980d..7b53b42 100644 --- a/docs/feature-map/computers.md +++ b/docs/feature-map/computers.md @@ -9,6 +9,7 @@ - 這台電腦(AnyBot 開著的這台,名字可以改):從 Bot 的「起始資料夾」開始。大腦放在伺服器上時,伺服器本身不在清單裡。 - SSH 電腦:自己加的,一個名稱加一個位址(例如 me@studio.local)。 - 帳號裡的其他電腦:登入同一個帳號、打開「讓帳號裡的其他電腦使用這台」、而且現在在線上的 AnyBot(螢幕電腦、手腳電腦),經過帳號伺服器操作檔案、指令、瀏覽器、看畫面和點擊。 +- `computers-online` 在線、離線:離線的寫帳號伺服器看到的原因(「離線(…)· 超過 60 秒沒有它的任何訊號…」)——手機的電腦清單、大腦斷線時頂端的提示、`anybot setup` 的大腦清單(帳號伺服器重開過就只剩時間)。同名:另一台同名的正連著時,新登入的在帳號裡叫「名字 (2)」,不踢掉它;沒連著的同名那列當成這台以前的、換掉;重新登入帶著原本那列的金鑰,只換自己那列(同名的別台睡著也不動)。同一個登入開了兩份 AnyBot(或資料夾被複製到別台):後連上的留著,前一份的狀態寫「另一份 AnyBot 正用這台電腦的登入…」,15 秒後、之後每 5 分鐘問一次,等那一份斷了才連回去。這台跟帳號伺服器的連線狀態變了就寫進這台的紀錄(雲端大腦、沒有視窗的電腦也查得到),帳號伺服器那邊也記([server](server.md))。 - `computers-default` 預設電腦:沒選就在 Bot 自己的電腦上做;使用者在 Bot 設定選了別台,或在訊息裡指名別台,才換過去。選了別台之後,瀏覽器和螢幕步驟只在那台做:那台開不了瀏覽器或沒有螢幕,那一步失敗並說為什麼(要 Bot 先問使用者),不會改開在使用者自己的 Mac;Bot 自己指名別台也拉回選的那台,除非使用者在訊息裡指名。 - `computers-allowed` 可以用的電腦:每個 Bot 勾自己能用哪幾台,它自己的電腦一定可以;沒勾的看不到也不能用。同事名冊會寫每個 Bot 在哪幾台做事。 - `computers-local` 「在這台電腦上執行」:一律允許/每次詢問(預設)/永不允許。只有使用者能打開,Bot 不能自己開。 @@ -36,10 +37,12 @@ - **指名不存在的電腦**(covers `computers-default`):Bot 在「工作站」跑指令,再請它把做事的電腦改成工作站、你按允許。指令:`$CTL phone send '[[call shell {"command":"pwd","computer":"工作站"}]]' && $CTL phone wait-text '「工作站」現在連不到' --in '#msgs' && $CTL phone send '換電腦 [[call update_bot {"default_computer":"工作站"}]]' && $CTL phone wait-text '預設電腦 → 工作站' --in '#ask' && $CTL phone click '#ask button[data-a="once"]' && $CTL phone wait-text '沒有「工作站」這台電腦' --in '#msgs' && $CTL api GET /api/bots/1 --jq '[.messages[].tools[]? | .status]'`。看到:「「工作站」現在連不到…絕對不要自己換到清單上的別台做同一件事」,沒有在別台跑;卡片「修改 Bot 自己:預設電腦 → 工作站」,允許後「沒有「工作站」這台電腦。可以用:驗證小幫手 的電腦」;這兩步都是 failed。 - **傳到別的裝置**(covers `computers-send`):Bot 想傳到手機;你自己從帳戶選單打開「傳送到其他裝置」。指令:`$CTL phone send '[[call send_to_device {"path":"x.txt","to":"手機"}]]' && $CTL phone wait-text '這一輪沒有 send_to_device 這個工具' --in '#msgs' && $CTL phone click '[data-back]' && $CTL phone click '#b-me' && $CTL phone click '#sheet-in .opt' --text 傳送到其他裝置 && $CTL phone wait '#drop-say' && $CTL phone shot computers-drops && $CTL api GET /api/drop/targets`。看到:沒登入帳號,Bot 沒有 `send_to_device`;「傳送到其他裝置」打得開,能選的只有大腦「驗證用 AnyBot」(API 的 targets 是 this 和這支手機)。 - **在這台電腦上執行、SSH、加一台**(covers `computers-kinds`、`computers-local`、`computers-pair`):指令:要開視窗——`$CTL stop && ABV_ALLOW_WINDOW=1 $CTL desktop-shot computers ANYBOT_SHOT_REAL=1 ANYBOT_SHOT_VIEW=computers`;其餘走不到——每次詢問的卡片、永不允許要「這台電腦」(`--serve` 沒有),SSH 要一台真的 SSH 主機,帳號裡的電腦、配對碼要帳號伺服器。看到:設定 › 電腦「你的電腦」的名字、「在這台電腦上執行」選單和「其他電腦」;行為靠自動測試(關卡順序)。實機時:設成每次詢問,請 Bot 在這台跑 `pwd` 要跳允許卡片;改成永不允許要被擋下,並請它改用自己的電腦。 +- **離線說得出原因**(covers `computers-online`):前提:relay/ 建好、`$CTL up --no-serve`。指令:照 [garden](garden.md)「量連線」開 scratch 的帳號伺服器(紀錄寫進證據資料夾的 `relay.log`)、用配對碼讓 scratch 加入,`$CTL serve`;手機開帳號伺服器的網址登入(`$CTL phone open http://127.0.0.1:<埠>/`,`#f-user`、`#f-pass`、`#b-login`),進到 Bot 清單;再 `$CTL stop`。看到:`relay.log`「amy/…(…)連上了(127.0.0.1)」、`serve.log`「帳號伺服器的連線:已連線」;停掉後 `relay.log`「…斷線:它那邊關掉了連線(AnyBot 關了、電腦睡眠,或網路換了)(…,連了 N 秒)」,手機頂端「那台 AnyBot 目前離線:它那邊關掉了連線…。連上後自動更新」(左右留邊、可以換行),`GET /relay/me` 的這台 `online: false`、`why` 是同一句、`last_seen_text` 是時間不是「從未連線」。同名、兩份同一個登入:靠自動測試(`relay/` 的 `cargo test same_name_is_not_kicked`、`cargo test a_replaced_connection_ends`,`cargo test tunnel::`)。 - 自動測試:`cargo test tools::`、`cargo test agent::`、`cargo test app::`、`cargo test remote::`、`cargo test drops::`。 ## 陷阱 +- 兩份舊版 AnyBot 用同一個登入、帳號伺服器已經是新版:兩份每十幾秒輪流連上(舊版一被告知就馬上連回去),手機一下看到這份、一下看到那份——把兩份都更新,或關掉一份。 - Bot 不能自己換電腦:工具指定了別台,但使用者最近三則訊息沒提到那台,這一步會被移回使用者選的那台,結果裡會說。真的要別台先問使用者。 - 使用者選的那台沒開機、或那台的 AnyBot 沒開沒登入,就不在清單上:Bot 先待在自己的電腦,`list_computers` 會寫那台「現在沒有連線」。 - 在 Bot 自己的電腦上做事不用問,但它看不到使用者的檔案;檔案工具只碰得到自己的資料夾(大家共用同一台)。 diff --git a/docs/feature-map/garden.md b/docs/feature-map/garden.md index df5a773..cf3fb62 100644 --- a/docs/feature-map/garden.md +++ b/docs/feature-map/garden.md @@ -5,7 +5,7 @@ AnyBot 自己照顧自己:Bot 做事遇到 AnyBot 本身的問題會記成「 ## 子功能 - `garden-issues` 待改進:一輪做完、自動整理做法時,AnyBot 本身的問題(工具回錯的結果、明明開著卻說找不到、一用就出錯、要繞路才做得到、Bot 一直誤用某個工具)另外記下來,不寫進技能。同一個工具的問題合併計次,最多留 50 條;出現 2 次以上的會標出來。 -- `garden-doctor` 診斷(/doctor):在聊天打 /doctor,一項一行 ✓/✗:版本和資料夾、紀錄檔在哪、這台 ↔ 帳號伺服器、Tailscale 是直連還是走它的中繼(走中繼很慢,多半是兩台之間擋了 UDP)、帳號伺服器 ↔ 大腦、**每一段量出來的數字**(這台 ↔ 帳號伺服器的來回 ms 和第一次連上的 ms、下載 256 KB 每秒幾 KB;螢幕電腦再加帳號伺服器 ↔ 大腦約幾 ms——來回超過 400 ms 或每秒不到 300 KB 是 ✗,寫慢在哪一段;帳號伺服器或大腦是舊版就說量不到,不算錯)、上次同步的速度、每個 Bot 用的模型服務連不連得到、Bot 的電腦、每個連接器、磁碟、指令有沒有沙盒、上次內部出錯。在連到大腦的螢幕電腦上檢查的是這台(連不到大腦時也能用),結果跳成提示;手機打的檢查的是大腦。沒有視窗的電腦(手腳、伺服器)在終端機打 `anybot --doctor`,印出量連線的那幾行(有 ✗ 結束碼是 1)。 +- `garden-doctor` 診斷(/doctor):在聊天打 /doctor,一項一行 ✓/✗:版本和資料夾、紀錄檔在哪、這台 ↔ 帳號伺服器、Tailscale 是直連還是走它的中繼(走中繼很慢,多半是兩台之間擋了 UDP)、帳號伺服器 ↔ 大腦、**每一段量出來的數字**(這台 ↔ 帳號伺服器的來回 ms 和第一次連上的 ms、下載 256 KB 每秒幾 KB;螢幕電腦再加帳號伺服器 ↔ 大腦約幾 ms——來回超過 400 ms 或每秒不到 300 KB 是 ✗,寫慢在哪一段;帳號伺服器或大腦是舊版就說量不到,不算錯)、帳號伺服器還認不認得這台的登入(不認得:被移出帳號或被同名的電腦換掉,要重新登入)、上次同步的速度、每個 Bot 用的模型服務連不連得到、Bot 的電腦、每個連接器、磁碟、指令有沒有沙盒、上次內部出錯。在連到大腦的螢幕電腦上檢查的是這台(連不到大腦時也能用),結果跳成提示;手機打的檢查的是大腦。沒有視窗的電腦(手腳、伺服器)在終端機打 `anybot --doctor`,印出量連線的那幾行(有 ✗ 結束碼是 1)。 - `garden-logs` 紀錄檔:AnyBot 自己的訊息寫在資料夾的 `logs/anybot-日期.log`(一天一個、留 7 天、一天最多 20 MB),同時照舊印在終端機(伺服器的 `make server-logs` 看得到)。等級用環境變數 ANYBOT_LOG(error、warn、info 預設、debug)。寫進去前先遮掉金鑰、Token、密碼(glpat-、ghp_、sk-、xai-、AKIA、Bearer、JWT、私鑰、名字像 TOKEN/SECRET/PASSWORD 的變數值 → ••••);手機上的步驟細節也一樣遮。 - `garden-crash` 當掉報告:程式內部出錯(任何一條執行緒)時寫 `logs/crash-時間.txt`(版本、執行緒、位置、訊息、backtrace,一樣遮過);下次打開在主要 Bot 的聊天留一行「AnyBot 上次執行時內部出錯…」(連到大腦的螢幕電腦是跳一則提示),並記一條待改進。每份報告只說一次。 - `garden-daily` 園丁每日報告(平日 8:44 起)「園丁:過去一天有 N 件事值得看一下。」:過去一天失敗或被打斷的執行、走冤枉路的執行(10 步以上且 3 成以上沒成功)、被自動暫停的例行任務、重複出現的待改進。 @@ -33,7 +33,7 @@ AnyBot 自己照顧自己:Bot 做事遇到 AnyBot 本身的問題會記成「 - **待改進合併計次**(covers `garden-issues`):一輪做五步,整理做法時存一個技能、回報同一個工具的問題兩次。指令:`$CTL model-reply 整理經驗 '{"save":true,"name":"跑五步","description":"跑五步","instructions":"一步一行","replay":[],"tool_issues":["browser_fill_contact 填不進電話欄","browser_fill_contact 又填錯欄"]}' && $CTL phone send '[[call shell {"command":"sleep 4; echo 1"}]]' && $CTL wait-api /api/bots/1 '[.messages[].tools[]?] | length == 2' && $CTL phone send '[[call shell {"command":"sleep 4; echo 2"}]]' && $CTL wait-api /api/bots/1 '[.messages[].tools[]?] | length == 3' && $CTL phone send '[[call shell {"command":"sleep 4; echo 3"}]]' && $CTL wait-api /api/bots/1 '[.messages[].tools[]?] | length == 4' && $CTL phone send '[[call shell {"command":"sleep 4; echo 4"}]]' && $CTL wait-api /api/bots/1 '[.messages[].tools[]?] | length == 5' && $CTL phone send '[[call shell {"command":"echo 5"}]]' && $CTL phone wait-text '學會了新做法「跑五步」' --in '#msgs' 60 && $CTL state '{skill: (.skills[] | select(.name == "跑五步") | .instructions), issue: (.improvements[] | {text, count, bots})}'`。看到:技能照存,做法裡沒有那兩句;待改進一條「browser_fill_contact 填不進電話欄」count 2(同一個工具合併)、bots 是驗證小幫手。 - **版本**(covers `garden-update`):帳戶選單 › 設定 › 更新。指令:`$CTL phone open --listed && $CTL phone click '#b-me' && $CTL phone click '#sheet-in .opt' --text 設定 && $CTL phone click '[data-go="updates"]' && $CTL phone wait-text 已是最新版 --in '#list' && $CTL api GET /api/settings --jq '{version, newer}'`。看到:版本(這個 checkout 的 HEAD)和建置時間、「已是最新版」。 - **電腦版 設定 › 更新**(covers `garden-issues`、`garden-update`、`garden-daily`):指令:要開視窗——`$CTL stop && ABV_ALLOW_WINDOW=1 $CTL desktop-shot garden-updates ANYBOT_SHOT_TAB=updates`(示範資料:真資料的截圖打不開 更新;有新版:加 `ANYBOT_SHOT_NEWER=0`)。看到:「自動更新」「園丁報告」開關、「重新啟動」;示範資料沒有待改進,「待改進」那一條的 ×2 和「全部清除」靠上面那一步的 state 和 `cargo test garden::`。 -- **量連線**(covers `garden-doctor`):前提:relay/ 建好、`$CTL up --no-serve`。指令:在 scratch 開一台 `relay/target/debug/anybot-relay --port <空的埠> --data /relay`,`/relay/signup`、`/relay/login` 拿登入、`/relay/pair` 拿配對碼,`scripts/scratch-env /target/debug/anybot setup <網址> <配對碼> --brain --no-service`,再 `scripts/scratch-env /target/debug/anybot --doctor`;換成只認 /api/hello 的舊伺服器、關掉伺服器各跑一次。看到:「✓ 這台 ↔ 帳號伺服器:來回 … ms(第一次連上 … ms)」「✓ 下載 256 KB 用了 … ms:每秒 … KB」;舊伺服器「下載速度:帳號伺服器是舊版,量不到」;關掉「✗ … 連不到」、結束碼 1。到大腦那一段要兩台(大腦+螢幕電腦):走不到,靠自動測試。 +- **量連線**(covers `garden-doctor`):前提:relay/ 建好、`$CTL up --no-serve`。指令:在 scratch 開一台 `relay/target/debug/anybot-relay --port <空的埠> --data /relay`,`/relay/signup`、`/relay/login` 拿登入、`/relay/pair` 拿配對碼,`scripts/scratch-env /target/debug/anybot setup <網址> <配對碼> --brain --no-service`,再 `scripts/scratch-env /target/debug/anybot --doctor`;換成只認 /api/hello 的舊伺服器、關掉伺服器各跑一次。看到:「✓ 這台 ↔ 帳號伺服器:來回 … ms(第一次連上 … ms)」「✓ 下載 256 KB 用了 … ms:每秒 … KB」「✓ 這台的登入:帳號伺服器認得這台電腦」;在帳號伺服器把這台移出帳號(`/relay/hosts//remove`)再跑:「✗ 這台的登入:帳號伺服器已經不認得這台電腦…」;舊伺服器「下載速度:帳號伺服器是舊版,量不到」;關掉「✗ … 連不到」、結束碼 1。到大腦那一段要兩台(大腦+螢幕電腦):走不到,靠自動測試。 - **有事的報告、當掉**(covers `garden-daily`、`garden-weekly`、`garden-crash`):指令:走不到——scratch 一開就把今天那份看過(沒事不報),下一份要明天平日 8:44、每週要週一;「園丁報告」開關只在電腦版;當掉要程式真的出錯。看到:最接近的真路是自動測試(有失敗才報、一天一次、每週只列花太多的、當掉報告只說一次又遮過);關掉「園丁報告」兩種都不出現要在電腦版看。 - 自動測試:`cargo test garden::`、`cargo test anybots_own_problems`(整理做法時另外記;一輪做完之後才回報的也記進清單)、`cargo test logfile::`、`cargo test doctor::`、`cargo test the_connection_check`、`cargo test a_screen_pings_its_brain`、relay 的 `cargo test speed`。 diff --git a/docs/feature-map/server.md b/docs/feature-map/server.md index dee90c3..c86b65d 100644 --- a/docs/feature-map/server.md +++ b/docs/feature-map/server.md @@ -33,6 +33,7 @@ ## 陷阱 +- 裝置顯示離線、查原因:帳號伺服器的紀錄寫每台電腦連上、斷線和原因、被同一個登入的另一條連線取代、被移出帳號、同名改了名字,和拿不認得的金鑰來連的位址(同一個位址 10 分鐘寫一次):`deploy/server/setup.sh --logs relay`。 - 舊的伺服器(`.env` 有 `ANYBOT_USER`、沒有 `ANYBOT_RELAY_INVITE`)不開放註冊:要讓別人註冊,在 `.env` 加 `ANYBOT_RELAY_INVITE` 再 `make update-server`。 - 大腦管理員的 API(`/relay/manager/…`)只給伺服器裡面的管理員:沒有金鑰、或經過前面的 Caddy 進來,一律 404。 - `Caddyfile` 是單一檔案掛進 caddy:換了檔案要重開 caddy 容器,`caddy reload` 讀到的還是舊的。 diff --git a/mobile/index.html b/mobile/index.html index 8da88dc..9b46276 100644 --- a/mobile/index.html +++ b/mobile/index.html @@ -490,8 +490,8 @@ textarea.field{min-height:96px;line-height:1.5} corners. It was a black capsule, and two or three lines swelled it into an oval. */ .toast{position:fixed;left:50%;top:calc(var(--safe-t) + 60px);transform:translate(-50%,-10px);width:max-content;max-width:min(360px,calc(100vw - 32px));background:color-mix(in srgb,var(--elev) 78%,transparent);-webkit-backdrop-filter:blur(18px) saturate(1.6);backdrop-filter:blur(18px) saturate(1.6);color:var(--text);padding:11px 16px;border-radius:var(--r-l);box-shadow:inset 0 0 0 .5px var(--line),0 12px 32px -8px var(--shade),0 2px 6px -2px var(--shade);font-size:var(--fs-ui);line-height:1.5;text-align:left;opacity:0;pointer-events:none;transition:opacity .2s,transform .2s;z-index:40} .toast.on{opacity:1;transform:translate(-50%,0)} -.net{position:fixed;left:50%;top:calc(var(--safe-t) + 64px);transform:translate(-50%,-12px);background:var(--elev);color:var(--text2);border:1px solid var(--line);box-shadow:0 2px 10px #0000001a;padding:5px 12px;border-radius:999px;font-size:var(--fs-small);opacity:0;pointer-events:none;transition:.2s;z-index:39;white-space:nowrap} -.net.on{opacity:1;transform:translate(-50%,0)} +.net{position:fixed;left:16px;right:16px;margin:0 auto;top:calc(var(--safe-t) + 64px);transform:translateY(-12px);background:var(--elev);color:var(--text2);border:1px solid var(--line);box-shadow:0 2px 10px #0000001a;padding:5px 12px;border-radius:16px;font-size:var(--fs-small);opacity:0;pointer-events:none;transition:.2s;z-index:39;width:fit-content;text-align:center;overflow-wrap:anywhere} +.net.on{opacity:1;transform:none} /* ---- sign in ---- */ .login{max-width:360px;margin:auto;padding:24px;display:flex;flex-direction:column;gap:10px;width:100%} @@ -1342,13 +1342,13 @@ async function pickHost() { const t = target(S.host); if (byId[t] && byId[t].online) { toHost(t); return start(); } // Already in, with what this phone kept of it: stays there until it is back (not another one). - if (S.entered && byId[t]) { netDown(true, `「${byId[t].name}」目前沒有連線,連上後自動更新`); hostRetry = setTimeout(pickHost, 3000); return; } + if (S.entered && byId[t]) { netDown(true, byId[t].why ? `「${byId[t].name}」目前離線:${byId[t].why}。連上後自動更新` : `「${byId[t].name}」目前沒有連線,連上後自動更新`); hostRetry = setTimeout(pickHost, 3000); return; } } if (live.length === 1) { toHost(live[0].id); return start(); } const note = (h) => { const n = sharers(h.id); return n.length ? " · " + esc(n.join("、")) + " 也用這個大腦" : ""; }; const wanted = (S.host && byId[target(S.host)]) || (all.find((h) => sharers(h.id).length)) || hosts[0]; const waiting = hosts.length && !live.length && wanted ? `
「${esc(wanted.name)}」暫時沒有連線(可能正在重新啟動,或那台電腦睡著了)。
連上後會自動進入,不用重新整理。
` : ""; - $("hosts").innerHTML = waiting + (hosts.length ? hosts.map((h) => `
${ic(h.online ? "monitor" : "power", 18)}
${esc(h.name)}
${h.online ? "在線上" : "離線(" + esc(h.last_seen_text || "很久沒連線") + ")"}${note(h)}
`).join("") + $("hosts").innerHTML = waiting + (hosts.length ? hosts.map((h) => `
${ic(h.online ? "monitor" : "power", 18)}
${esc(h.name)}
${h.online ? "在線上" : "離線(" + esc(h.last_seen_text || "很久沒連線") + ")" + (h.why ? " · " + esc(h.why) : "")}${note(h)}
`).join("") : `
這個帳號還沒有連上任何 AnyBot。
在電腦上打開 AnyBot › 設定 › 手機與帳號,登入同一個帳號。
`); document.querySelectorAll("#hosts .row").forEach((r) => r.onclick = () => { clearTimeout(hostRetry); toHost(r.dataset.h); if (!S.entered) show("gate"); start(); }); // (In on a kept copy and now asked which computer: out again, so the one picked is gone into.) @@ -1415,7 +1415,8 @@ async function start() { if (pollCtl.signal.aborted) continue; fails++; if (e.transient) netDown(true); - if (S.relay && /離線|offline|not connected/i.test(e.message)) netDown(true, "那台 AnyBot 目前沒有連線,連上後自動更新"); + // (With why, when the account server saw it go: 「那台 AnyBot 目前離線:…」.) + if (S.relay && /離線|offline|not connected/i.test(e.message)) netDown(true, /^那台 AnyBot 目前離線:/.test(e.message) ? e.message + "。連上後自動更新" : "那台 AnyBot 目前沒有連線,連上後自動更新"); await rest(backoff(fails - 1, 15000)); } } diff --git a/relay/src/main.rs b/relay/src/main.rs index ab837ee..827519b 100644 --- a/relay/src/main.rs +++ b/relay/src/main.rs @@ -342,6 +342,14 @@ struct Relay { pairs: Mutex>, /// When each host last asked (in memory; saved now and then). seen: Mutex>, + /// Why each host's connection last ended, and when (unix seconds): shown beside 「離線」, so + /// an offline computer says what happened instead of only when (in memory: a restarted + /// server says only when). + gone: Mutex>, + /// Lines written down at most once in ten minutes each, and when that was last (see + /// `once_in`): a computer whose sign-in was replaced knocks every 30 s, two copies of one + /// computer hand the place back and forth. + quiet: Mutex>, fails: Mutex>, /// 2FA: a right password opens a five-minute challenge (user, device, made, tries) awaiting the code. challenges: Mutex>, @@ -383,6 +391,11 @@ impl Ticket { } } +/// A name as it goes into the log: on one line (a computer's name is whatever it said it was). +fn plain(s: &str) -> String { + s.chars().map(|c| if c.is_control() { ' ' } else { c }).collect() +} + fn now() -> i64 { chrono::Utc::now().timestamp() } @@ -446,6 +459,8 @@ impl Relay { tickets: Mutex::new(HashMap::new()), pairs: Mutex::new(HashMap::new()), seen: Mutex::new(HashMap::new()), + gone: Mutex::new(HashMap::new()), + quiet: Mutex::new(HashMap::new()), fails: Mutex::new(HashMap::new()), dirty: std::sync::atomic::AtomicBool::new(false), challenges: Mutex::new(HashMap::new()), @@ -506,6 +521,19 @@ impl Relay { if let Some(s) = self.sockets.lock().unwrap().remove(id) { let _ = s.tx.send(wire::pack(&json!({"t": "bye"}), &[])); } + self.gone.lock().unwrap().remove(id); + } + + /// True once in ten minutes for each `key` (a line worth writing down, not every 30 s). + /// (Bounded: knocks from very many addresses aren't each written down.) + fn once_in(&self, key: &str) -> bool { + let mut q = self.quiet.lock().unwrap(); + q.retain(|_, t| t.elapsed() < Duration::from_secs(600)); + if q.contains_key(key) || (key.starts_with("refused ") && q.len() >= 10_000) { + return false; + } + q.insert(key.to_string(), Instant::now()); + true } /// This host is still one of an account's computers (its key was not replaced or removed @@ -724,7 +752,7 @@ impl Relay { fn forward_raw(&self, host_id: &str, method: &str, path: &str, query: &HashMap, body: &[u8], z: bool, who: (&str, &str), z_ok: bool, from: &str) -> Answer { use base64::Engine; if !self.online(host_id) { - return Answer::error(503, OFFLINE); + return Answer::error(503, &self.offline_words(host_id)); } let id = httpd::random_hex(12); let secs = if path == "/api/device/run" { LONG_FORWARD_SECS } else { FORWARD_SECS }; @@ -783,7 +811,16 @@ impl Relay { if req.path != "/relay/host/ws" { return httpd::write_response(&mut c, &Resp::error(404, "沒有這個網址")); } - let Some(h) = self.host(&req) else { return httpd::write_response(&mut c, &Resp::error(401, "這台電腦的金鑰無效")) }; + let ip = Self::peer_ip(&req); + let Some(h) = self.host(&req) else { + // (Written down: a computer whose row was replaced or removed knocks here every + // 30 s for ever, and from the outside it only looked 「離線」. Not a knock with no key + // at all: anything on the internet.) + if !req.bearer().is_empty() && self.once_in(&format!("refused {ip}")) { + eprintln!("AnyBot 帳號伺服器:{ip} 用這裡不認得的金鑰連線(那台電腦被移出帳號,或被同名的電腦換掉了):它要重新登入"); + } + return httpd::write_response(&mut c, &Resp::error(401, "這台電腦的金鑰無效")); + }; if !httpd::accept_websocket(&req, &mut c) { return; } @@ -793,8 +830,16 @@ impl Relay { let mut ws = WebSocket::from_raw_socket(Counted { inner: c, got: 0 }, Role::Server, Some(cfg)); let serial = SERIAL.fetch_add(1, Ordering::SeqCst); let (tx, rx) = channel::>(); - self.sockets.lock().unwrap().insert(h.id.clone(), Sock { tx: tx.clone(), serial }); + let before = self.sockets.lock().unwrap().insert(h.id.clone(), Sock { tx: tx.clone(), serial }); self.seen.lock().unwrap().insert(h.id.clone(), Instant::now()); + let who = format!("{}/{}({})", plain(&h.user), plain(&h.name), h.id); + // (Taking the place of a connection still there: once in ten minutes — two copies of an + // older AnyBot hand it back and forth every few seconds.) + if before.is_none() || self.once_in(&format!("again {}", h.id)) { + eprintln!("AnyBot 帳號伺服器:{who}連上了({ip}){}", if before.is_some() { ",換掉它前一條還沒斷的連線(十分鐘只寫一次)" } else { "" }); + } + let since = Instant::now(); + let mut why = "它那邊關掉了連線(AnyBot 關了、電腦睡眠,或網路換了)"; let (mut heard, mut pinged, mut marked) = (Instant::now(), Instant::now(), Instant::now()); let mut pace = wire::Pace::new(); let mut got = 0u64; @@ -815,33 +860,74 @@ impl Relay { Ok(Message::Close(_)) => break, Ok(_) => heard = Instant::now(), Err(tungstenite::Error::Io(e)) if matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut) => {} - Err(_) => break, + // Its end closed without a goodbye (an AnyBot that quit, a computer going to + // sleep): what `why` already says. + Err(tungstenite::Error::Protocol(tungstenite::error::ProtocolError::ResetWithoutClosingHandshake) | tungstenite::Error::ConnectionClosed | tungstenite::Error::AlreadyClosed) => break, + Err(tungstenite::Error::Io(e)) if matches!(e.kind(), std::io::ErrorKind::ConnectionReset | std::io::ErrorKind::ConnectionAborted) => { + why = "連線被切斷(AnyBot 被強制關掉,或中間的網路、代理把它切了)"; + break; + } + Err(_) => { + why = "連線斷了(網路中斷)"; + break; + } } for _ in 0..32 { let Ok(f) = rx.try_recv() else { break }; pace.moved(); if ws.write(Message::Binary(f.into())).is_err() { + why = "送資料給它時斷了(網路中斷)"; break 'live; } } if pinged.elapsed().as_secs() >= WS_PING_SECS { pinged = Instant::now(); if ws.write(Message::Ping(Vec::new().into())).is_err() { + why = "送資料給它時斷了(網路中斷)"; break; } } match ws.flush() { Err(tungstenite::Error::Io(e)) if matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut) => {} - Err(_) => break, + Err(_) => { + why = "送資料給它時斷了(網路中斷)"; + break; + } Ok(()) => {} } if heard.elapsed().as_secs() >= WS_DEAD_SECS { + why = "超過 60 秒沒有它的任何訊號(網路斷了,或電腦睡著了)"; break; } if marked.elapsed().as_secs() >= 10 { marked = Instant::now(); // Taken off the account while connected: the connection ends here. if !self.still_registered(&h) { + why = "這台被移出帳號了(或被同名的電腦換掉)"; + break; + } + // Another connection with this computer's key took its place: this one ends — + // it used to stay, keep the computer 「在線上」 by its `seen`, while every + // request went to a queue nobody read and failed 8 s later (目前離線). The + // other end is told, so a second copy of the same AnyBot waits instead of + // taking the place back at once. + let current = self.sockets.lock().unwrap().get(&h.id).map(|s| s.serial); + if current.is_none() { + // The newer connection that took this one's place has gone too: this one is + // asked to connect again (anew, saying what it is), not told its place is + // taken — it would have waited five minutes for nobody. + let _ = ws.write(Message::Binary(wire::pack(&json!({"t": "bye"}), &[]).into())); + let _ = ws.flush(); + why = "後來那條連線也斷了,請它重新連上"; + break; + } + if current != Some(serial) { + let _ = ws.write(Message::Binary(wire::pack(&json!({"t": "bye", "why": "replaced"}), &[]).into())); + let _ = ws.flush(); + // A second copy of this computer answers the goodbye (it closes); the same + // one, back on a new line (a laptop that changed networks) before this one + // was found dead, doesn't. + why = if Self::answers_close(&mut ws, &mut |b| self.on_frame(&h, b, &tx)) { "replaced" } else { "superseded" }; break; } self.seen.lock().unwrap().insert(h.id.clone(), Instant::now()); @@ -851,9 +937,24 @@ impl Relay { // (Only the ones opened on this connection: when the host had already connected anew, // the old connection's end used to cut the new one's viewers.) self.streams.lock().unwrap().retain(|_, (_, host, on)| !(*host == h.id && *on == serial)); + let held = since.elapsed().as_secs(); + let held = if held >= 3600 { format!("{} 小時", held / 3600) } else if held >= 60 { format!("{} 分鐘", held / 60) } else { format!("{held} 秒") }; + let mut was_current = false; + // (Written once the connections' lock is let go: a log that blocks mustn't hold up + // every request.) + let note; { let mut socks = self.sockets.lock().unwrap(); - if socks.get(&h.id).map(|s| s.serial) == Some(serial) { + if socks.get(&h.id).map(|s| s.serial) != Some(serial) { + note = match why { + "replaced" => self.once_in(&format!("replaced {}", h.id)).then(|| format!("AnyBot 帳號伺服器:{who}這條連線({ip},連了 {held})被同一個登入的另一條連線取代:同一台電腦開了兩份 AnyBot,或資料夾被複製到別台(十分鐘只寫一次)")), + "superseded" => Some(format!("AnyBot 帳號伺服器:{who}前一條已經沒有聲音的連線({ip},連了 {held})由它重新連上的那條接手")), + _ => Some(format!("AnyBot 帳號伺服器:{who}的連線結束:{why}({ip},連了 {held})")), + }; + } else { + note = Some(format!("AnyBot 帳號伺服器:{who}斷線:{why}({ip},連了 {held})")); + self.gone.lock().unwrap().insert(h.id.clone(), (now(), why.to_string())); + was_current = true; socks.remove(&h.id); self.seen.lock().unwrap().remove(&h.id); // (What it said of itself — which brain it shows, that it is hands — and its @@ -866,6 +967,18 @@ impl Relay { } } } + if let Some(n) = note { + eprintln!("{n}"); + } + // When it was last there, now (the minute's save kept it only once it had been there a + // minute: one gone sooner said 「從未連線」). (After the connections' lock: the account + // data is locked first elsewhere.) + if was_current { + if let Some(x) = self.data.lock().unwrap().hosts.iter_mut().find(|x| x.id == h.id) { + x.last_seen = now(); + } + self.dirty.store(true, Ordering::Relaxed); + } let lost: Vec = self.flights.lock().unwrap().iter().filter(|(_, (host, s))| *host == h.id && *s == serial).map(|(id, _)| id.clone()).collect(); for id in lost { if let Some((w, _)) = self.waiting.lock().unwrap().remove(&id) { @@ -1304,8 +1417,17 @@ impl Relay { if self.data.lock().unwrap().hosts.iter().any(|x| x.user == user && x.name == name && x.managed) { return Resp::error(409, &format!("這個帳號已經有伺服器開的「{name}」,這台換個名字")); } - let (h, token) = self.add_host(&user, &name, false); - Resp::json(&json!({"id": h.id, "token": token})) + // The row this computer had (signing in again): proved with that row's key, and + // never a computer the server's manager made. + let body = req.json(); + let was = { + let (id, key) = (body["was"]["id"].as_str().unwrap_or(""), body["was"]["token"].as_str().unwrap_or("")); + let hash = httpd::sha256_hex(key); + let d = self.data.lock().unwrap(); + d.hosts.iter().find(|x| !id.is_empty() && !key.is_empty() && x.id == id && x.user == user && !x.managed && httpd::constant_time_eq(&x.token_hash, &hash)).map(|x| x.id.clone()) + }; + let (h, token) = self.add_host_was(&user, &name, false, was.as_deref()); + Resp::json(&json!({"id": h.id, "token": token, "name": h.name})) } // 加一台電腦: a signed-in phone or non-paired AnyBot asks for a code; the new computer gives it back. ("POST", ["relay", "pair"]) => { @@ -1379,6 +1501,7 @@ impl Relay { // Its open connection goes with it (a computer taken off the list — lost, // sold — stayed connected, and kept asking the account's other computers). if removed { + eprintln!("AnyBot 帳號伺服器:{user} 把電腦 {id} 移出帳號"); self.hang_up(id); } Resp::json(&json!({"ok": true})) @@ -1545,7 +1668,9 @@ impl Relay { ("GET", ["relay", "host", "peers"]) => { let Some(me) = self.host(&req) else { return Resp::error(401, "這台電腦的金鑰無效") }; let d = self.data.lock().unwrap(); - Resp::json(&json!({"hosts": d.hosts.iter().filter(|h| h.user == me.user).map(|h| self.host_json(h)).collect::>()})) + // `me_online`: this computer is connected (by another copy of it, when asked by + // one that was told its place was taken — see tunnel::run). + Resp::json(&json!({"hosts": d.hosts.iter().filter(|h| h.user == me.user).map(|h| self.host_json(h)).collect::>(), "me_online": self.online(&me.id)})) } // Signing out of the app unregisters this machine: its own key removes its own // registration, so a key left on a borrowed computer dies with the sign-out. @@ -1625,18 +1750,69 @@ impl Relay { } } - /// Register an AnyBot of `user`. The same name again replaces its old key (keeping who it's - /// shared with, and hanging up the replaced connection). + /// Whether the other end of a connection told goodbye closes it (a live AnyBot does, within a + /// moment; a connection nobody is on anymore doesn't). + /// (What comes meanwhile goes to `frame`: answers to jobs it was still running.) + fn answers_close(ws: &mut tungstenite::WebSocket, frame: &mut dyn FnMut(&[u8])) -> bool { + let until = Instant::now() + Duration::from_secs(3); + while Instant::now() < until { + match ws.read() { + Ok(tungstenite::Message::Close(_)) => return true, + Ok(tungstenite::Message::Binary(b)) => frame(&b), + Ok(_) => {} + Err(tungstenite::Error::Io(e)) if matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut) => std::thread::sleep(Duration::from_millis(20)), + Err(tungstenite::Error::ConnectionClosed | tungstenite::Error::AlreadyClosed | tungstenite::Error::Protocol(tungstenite::error::ProtocolError::ResetWithoutClosingHandshake)) => return true, + Err(_) => return false, + } + } + false + } + + /// A computer joins the account (or signs in again). `was`: the row it had until now on this + /// server (it proved it with that row's key), which this one replaces. Another row of the same + /// name is taken to be this computer from before (a reinstall, a lost key) and replaced too — + /// unless that one is connected right now: then it is another computer that happens to have + /// the same name (two 「MacBook Pro」s), and this one gets 「名字 (2)」. (It used to be + /// replaced and hung up: it then knocked with a dead key for ever and only looked 「離線」.) + /// The server's manager (`managed`) always replaces its own brain of that name. fn add_host(&self, user: &str, name: &str, managed: bool) -> (Host, String) { + self.add_host_was(user, name, managed, None) + } + + fn add_host_was(&self, user: &str, name: &str, managed: bool, was: Option<&str>) -> (Host, String) { let token = httpd::random_hex(32); let mut h = Host { id: httpd::random_hex(8), name: name.to_string(), user: user.to_string(), token_hash: httpd::sha256_hex(&token), created: now(), last_seen: 0, paired: false, members: vec![], managed }; + // (Who is connected, read before the account data is locked.) + let ids_now: Vec = self.data.lock().unwrap().hosts.iter().filter(|x| x.user == user && x.name == name && Some(x.id.as_str()) != was).map(|x| x.id.clone()).collect(); + // Proved which row it is (`was`): only that row is its own — another of the same name is + // another computer even while it sleeps (a 「名字 (2)」 signing in again still calls + // itself 「名字」). + let busy = !managed && ((was.is_some() && !ids_now.is_empty()) || ids_now.iter().any(|id| self.online(id))); + let mut notes = vec![]; let replaced: Vec = { let mut d = self.data.lock().unwrap(); - if let Some(old) = d.hosts.iter().find(|x| x.user == user && x.name == name) { + // Its own row's 「名字 (2)」 when it proves it (the other computers' bots know it by that + // name), whether or not 「名字」 is taken now. + let own = was.and_then(|w| d.hosts.iter().find(|x| x.id == w)).map(|x| x.name.clone()).filter(|n| n.starts_with(&format!("{name} ("))); + if let Some(n) = &own { + h.name = n.clone(); + } else if busy { + // The first free 「名字 (n)」. + h.name = (2..1000).map(|n| format!("{name} ({n})")).find(|cand| !d.hosts.iter().any(|x| x.user == user && x.name == *cand && Some(x.id.as_str()) != was)).unwrap_or_else(|| format!("{name}-{}", httpd::random_hex(2))); + if was.is_none() { + notes.push(format!("AnyBot 帳號伺服器:{} 的「{}」正在線上,新登入的這台改叫「{}」(不再把它踢掉)", plain(user), plain(name), plain(&h.name))); + } + } + let gone = |x: &Host| x.user == user && (Some(x.id.as_str()) == was || (!busy && x.name == name)); + // (Who it's shared with: its own row's first.) + if let Some(old) = d.hosts.iter().find(|x| was.is_some_and(|w| x.id == w)).or_else(|| d.hosts.iter().find(|x| gone(x))) { h.members = old.members.clone(); } - let mut ids: Vec = d.hosts.iter().filter(|x| x.user == user && x.name == name).map(|x| x.id.clone()).collect(); - d.hosts.retain(|x| !(x.user == user && x.name == name)); + let mut ids: Vec = d.hosts.iter().filter(|x| gone(x)).map(|x| x.id.clone()).collect(); + if !ids.is_empty() { + notes.push(format!("AnyBot 帳號伺服器:{} 的「{}」重新登入,換掉它原本的那一列({})", plain(user), plain(&h.name), ids.join("、"))); + } + d.hosts.retain(|x| !gone(x)); // (An account's computers are bounded: the one unseen longest makes room.) while d.hosts.iter().filter(|x| x.user == user).count() >= MAX_HOSTS_PER_USER { let Some(i) = d.hosts.iter().enumerate().filter(|(_, x)| x.user == user).min_by_key(|(_, x)| x.last_seen.max(x.created)).map(|(i, _)| i) else { break }; @@ -1646,6 +1822,9 @@ impl Relay { self.save(&d); ids }; + for n in notes { + eprintln!("{n}"); + } for id in replaced { self.hang_up(&id); } @@ -1669,9 +1848,19 @@ impl Relay { (h, token) } + /// 「目前離線」, with why when this server saw it go (the phone shows it at the top). + fn offline_words(&self, id: &str) -> String { + match self.gone.lock().unwrap().get(id) { + Some((_, why)) => format!("那台 AnyBot 目前離線:{why}"), + None => OFFLINE.to_string(), + } + } + fn host_json(&self, h: &Host) -> Value { let online = self.online(&h.id); - json!({"id": h.id, "name": h.name, "online": online, "uses": self.uses.lock().unwrap().get(&h.id).cloned().unwrap_or_default(), "hands": self.hands.lock().unwrap().contains(&h.id), "last_seen_text": if online { "在線上".to_string() } else if h.last_seen > 0 { chrono::DateTime::from_timestamp(h.last_seen, 0).map(|t| t.format("%m/%d %H:%M UTC").to_string()).unwrap_or_default() } else { "從未連線".into() }}) + // Why it went offline, when this server saw it go (since it last started). + let why = if online { String::new() } else { self.gone.lock().unwrap().get(&h.id).map(|(_, w)| w.clone()).unwrap_or_default() }; + json!({"id": h.id, "name": h.name, "online": online, "managed": h.managed, "uses": self.uses.lock().unwrap().get(&h.id).cloned().unwrap_or_default(), "hands": self.hands.lock().unwrap().contains(&h.id), "last_seen_text": if online { "在線上".to_string() } else if h.last_seen > 0 { chrono::DateTime::from_timestamp(h.last_seen, 0).map(|t| t.format("%m/%d %H:%M UTC").to_string()).unwrap_or_default() } else { "從未連線".into() }, "why": why}) } fn signup(&self, req: &Req) -> Resp { @@ -2222,6 +2411,149 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + /// A relay with its WebSocket side (as the real server runs) on a port of its own. + fn relay_with_ws(tag: &str) -> (Arc, u16) { + let dir = std::env::temp_dir().join(format!("anybot-relay-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let relay = Arc::new(Relay::load(dir)); + let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = l.local_addr().unwrap().port(); + let (r, w) = (relay.clone(), relay.clone()); + std::thread::spawn(move || httpd::serve_upgrade(l, Arc::new(move |req| r.handle(req)), Some(Arc::new(move |req, c| w.ws(req, c))), Arc::new(|| true))); + (relay, port) + } + + /// A computer's lasting connection, as AnyBot opens it (its key in the header). + fn host_link(port: u16, token: &str) -> tungstenite::WebSocket { + use tungstenite::client::IntoClientRequest; + let mut req = format!("ws://127.0.0.1:{port}/relay/host/ws").into_client_request().unwrap(); + req.headers_mut().insert("Authorization", format!("Bearer {token}").parse().unwrap()); + let tcp = std::net::TcpStream::connect(("127.0.0.1", port)).unwrap(); + let (ws, _) = tungstenite::client::client(req, tcp).unwrap(); + ws.get_ref().set_read_timeout(Some(Duration::from_millis(300))).unwrap(); + ws + } + + /// What the relay says of the account's computers (`hosts` of /relay/me). + fn hosts_of(port: u16, session: &str) -> Vec { + let (_, body) = get(port, "/relay/me", session); + serde_json::from_slice::(&body).unwrap()["hosts"].as_array().cloned().unwrap_or_default() + } + + /// Two copies of one computer (the same key): the newer connection used to take the + /// requests while the older one stayed, kept the computer 「在線上」 after the newer left, + /// and every request then failed 8 s later. Now the older is told it was replaced and ends, + /// the computer stays reachable through the newer, and once offline it says why. + #[test] + fn a_replaced_connection_ends_and_an_offline_computer_says_why() { + let (_relay, port) = relay_with_ws("replaced"); + post(port, "/relay/signup", "", json!({"user": "amy", "password": "12345678"})); + let session = post(port, "/relay/login", "", json!({"user": "amy", "password": "12345678", "device": "phone"})).1["token"].as_str().unwrap().to_string(); + let mac = post(port, "/relay/hosts", &session, json!({"name": "Mac"})).1; + let token = mac["token"].as_str().unwrap().to_string(); + let mut older = host_link(port, &token); + let mut newer = host_link(port, &token); + // The older one hears 「replaced」 at the relay's next ten-second look, then is closed. + let deadline = Instant::now() + Duration::from_secs(25); + let mut told = Value::Null; + while Instant::now() < deadline && told.is_null() { + match older.read() { + Ok(tungstenite::Message::Binary(b)) => { + if let Some((head, _)) = wire::unpack(&b) { + if head["t"] == "bye" { + told = head; + } + } + } + Ok(_) => {} + Err(tungstenite::Error::Io(e)) if matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut) => {} + Err(_) => break, + } + let _ = newer.read(); + } + assert_eq!(told["why"], "replaced", "the older connection is told it was replaced"); + // Asking with its key, the replaced copy hears its place is held (so it keeps waiting). + let (_, peers) = get(port, "/relay/host/peers", &token); + assert_eq!(serde_json::from_slice::(&peers).unwrap()["me_online"], true); + let row = |port, s: &str| hosts_of(port, s).into_iter().find(|h| h["name"] == "Mac").unwrap(); + assert_eq!(row(port, &session)["online"], true, "still there through the newer one"); + assert_eq!(row(port, &session)["why"], ""); + // The newer one goes: offline at once, with what happened. + drop(older); + let _ = newer.close(None); + let _ = newer.flush(); + drop(newer); + let deadline = Instant::now() + Duration::from_secs(5); + while Instant::now() < deadline && row(port, &session)["online"] == true { + std::thread::sleep(Duration::from_millis(100)); + } + let h = row(port, &session); + assert_eq!(h["online"], false); + assert!(h["why"].as_str().unwrap_or("").contains("關掉了連線"), "{h}"); + assert_ne!(h["last_seen_text"], "從未連線", "it was there a moment ago: {h}"); + // Asked for while it is away, the phone hears why. + let (st, body) = get(port, &format!("/h/{}/api/state", mac["id"].as_str().unwrap()), &session); + assert_eq!(st, 503); + assert!(String::from_utf8_lossy(&body).contains("目前離線:它那邊關掉了連線"), "{}", String::from_utf8_lossy(&body)); + } + + /// Two computers of one account with the same name (two 「MacBook Pro」s): signing in on + /// the second used to replace the first and hang it up — it then knocked with a dead key for + /// ever. One that is connected is kept, and the newcomer is 「名字 (2)」; one that isn't is + /// this computer from before and is replaced as before; a computer signing in again with the + /// key of its row replaces exactly that row. + #[test] + fn a_connected_computer_of_the_same_name_is_not_kicked_out() { + let (_relay, port) = relay_with_ws("samename"); + post(port, "/relay/signup", "", json!({"user": "amy", "password": "12345678"})); + let session = post(port, "/relay/login", "", json!({"user": "amy", "password": "12345678", "device": "phone"})).1["token"].as_str().unwrap().to_string(); + let first = post(port, "/relay/hosts", &session, json!({"name": "MacBook Pro"})).1; + let first_token = first["token"].as_str().unwrap().to_string(); + let link = host_link(port, &first_token); + let (st, second) = post(port, "/relay/hosts", &session, json!({"name": "MacBook Pro"})); + assert_eq!(st, 200); + assert_eq!(second["name"], "MacBook Pro (2)", "the newcomer gets a name of its own"); + assert_eq!(get(port, "/relay/host/peers", &first_token).0, 200, "the connected one keeps its key"); + let names: Vec = hosts_of(port, &session).iter().map(|h| h["name"].as_str().unwrap_or("").to_string()).collect(); + assert_eq!(names.len(), 2, "{names:?}"); + // The first signs in again, proving which row it was: that row is replaced (even while + // connected), and its old key ends. + let (_, again) = post(port, "/relay/hosts", &session, json!({"name": "MacBook Pro", "was": {"id": first["id"], "token": first_token}})); + assert_eq!(again["name"], "MacBook Pro"); + assert_eq!(get(port, "/relay/host/peers", &first_token).0, 401, "its old key is gone"); + assert_eq!(hosts_of(port, &session).len(), 2, "no third row"); + drop(link); + // A row of the same name nobody is connected with: this computer from before (a + // reinstall), replaced. + let second_token = second["token"].as_str().unwrap().to_string(); + let (_, third) = post(port, "/relay/hosts", &session, json!({"name": "MacBook Pro (2)"})); + assert_eq!(third["name"], "MacBook Pro (2)"); + assert_eq!(get(port, "/relay/host/peers", &second_token).0, 401); + assert_eq!(hosts_of(port, &session).len(), 2); + // A 「名字 (2)」 signing in again (it still calls itself 「名字」), proving its row, while + // the first one sleeps: only its own row is replaced, it keeps its 「(2)」, and the + // sleeping one keeps its key. + let (_, a) = post(port, "/relay/hosts", &session, json!({"name": "Mini"})); + let (_, b) = post(port, "/relay/hosts", &session, json!({"name": "Mini (2)"})); + let a_token = a["token"].as_str().unwrap().to_string(); + let (_, b2) = post(port, "/relay/hosts", &session, json!({"name": "Mini", "was": {"id": b["id"], "token": b["token"]}})); + assert_eq!(b2["name"], "Mini (2)", "{b2}"); + assert_eq!(get(port, "/relay/host/peers", &a_token).0, 200, "the sleeping one keeps its key"); + assert_eq!(get(port, "/relay/host/peers", b["token"].as_str().unwrap()).0, 401, "its own old key is gone"); + let minis: Vec = hosts_of(port, &session).iter().filter_map(|h| h["name"].as_str().filter(|n| n.starts_with("Mini")).map(String::from)).collect(); + assert_eq!(minis.len(), 2, "{minis:?}"); + // The first one leaves the account: signing in again, the 「(2)」 keeps its name (the + // account's other computers know it by it). + post(port, &format!("/relay/hosts/{}/remove", a["id"].as_str().unwrap()), &session, json!({})); + let (_, b3) = post(port, "/relay/hosts", &session, json!({"name": "Mini", "was": {"id": b2["id"], "token": b2["token"]}})); + assert_eq!(b3["name"], "Mini (2)", "{b3}"); + post(port, "/relay/hosts", &session, json!({"name": "Mini"})); + // Someone else's key proves nothing. + let (_, fourth) = post(port, "/relay/hosts", &session, json!({"name": "Studio", "was": {"id": again["id"], "token": "not-its-key"}})); + assert_eq!(fourth["name"], "Studio"); + assert_eq!(hosts_of(port, &session).len(), 5, "the row with the wrong key stays"); + } + /// 看畫面的票證:網址裡那張一換就作廢;換新票要在最後一次使用後十分鐘內、而且當初要票的 /// 手機還登入著;開「新」連線只認發出十分鐘內的票(舊票續不了命,只能換)。 #[test] diff --git a/src/remote.rs b/src/remote.rs index bb45c97..b5aeb77 100644 --- a/src/remote.rs +++ b/src/remote.rs @@ -377,7 +377,15 @@ impl Hub { self.relay_status.lock().unwrap().clone() } fn set_relay_status(&self, s: &str) { - *self.relay_status.lock().unwrap() = s.to_string(); + let changed = std::mem::replace(&mut *self.relay_status.lock().unwrap(), s.to_string()) != s; + // Written down when it changes: a cloud brain or a computer without a window only ever + // showed 「離線」 on the phone, and the reason (a refused http:// road, a key the server + // no longer knows, another copy holding the connection) was in no log. (「連線中…」 is + // only the moment before one of the others. Written once the status is let go: the + // window reads it every frame.) + if changed && !s.is_empty() && s != "連線中…" { + log::info!("AnyBot:帳號伺服器的連線:{s}"); + } } /// The view once it is newer than `since` (or after the wait). fn wait_newer(&self, since: u64, secs: u64) -> Arc { @@ -2732,7 +2740,14 @@ pub fn relay_join(base_settings: &Settings, url: &str, user: &str, password: &st } } let session = relay_login(&url, user, password, host_name, code)?; - let h = relay_post(&format!("{url}/relay/hosts"), &session, &json!({"name": host_name}))?; + // Signing in again on this same server: the row this computer had is named (with its key, the + // proof), so that row is replaced — not another computer that happens to have this name. + // (Only to the server that gave the key.) + let mut ask = json!({"name": host_name}); + if base(&base_settings.relay_url) == url && !base_settings.host_id.is_empty() && !base_settings.host_token.is_empty() { + ask["was"] = json!({"id": base_settings.host_id, "token": base_settings.host_token}); + } + let h = relay_post(&format!("{url}/relay/hosts"), &session, &ask)?; // The desktop doesn't need to stay signed in as a person; only the host key is kept. let _ = relay_post(&format!("{url}/relay/logout"), &session, &json!({})); let mut s = base_settings.clone(); @@ -2774,6 +2789,13 @@ fn alive(gen: u64) -> bool { } fn relay_worker(url: &str, token: &str, gen: u64) { + // (Said only while this is still the live worker: one left from before a restart overwrote, + // and now wrote down, the status of the one after it.) + let say = |m: &str| { + if alive(gen) { + hub().set_relay_status(m); + } + }; let mut backoff = 1u64; while alive(gen) { let next = self_hop(&format!("{url}/relay/host/next")); @@ -2781,7 +2803,7 @@ fn relay_worker(url: &str, token: &str, gen: u64) { let mut resp = match r { Ok(r) => r, Err(e) => { - hub().set_relay_status(&format!("連不上帳號伺服器:{}", why_unreachable(&e))); + say(&format!("連不上帳號伺服器:{}", why_unreachable(&e))); std::thread::sleep(Duration::from_secs(backoff)); backoff = (backoff * 2).min(30); continue; @@ -2789,11 +2811,11 @@ fn relay_worker(url: &str, token: &str, gen: u64) { }; let st = resp.status().as_u16(); if st == 401 { - hub().set_relay_status("這台電腦的金鑰失效了,請重新登入帳號"); + say("這台電腦的金鑰失效了,請重新登入帳號"); return; } if st == 204 { - hub().set_relay_status("已連線"); + say("已連線"); backoff = 1; continue; } @@ -2802,18 +2824,18 @@ fn relay_worker(url: &str, token: &str, gen: u64) { // time. (Its JSON body was read as a job and answered at once — a tight loop of // requests and threads exactly when the server was overloaded.) if st != 200 { - hub().set_relay_status(&format!("連不上帳號伺服器:{}", why_refused(st, &serde_json::from_str(&text).unwrap_or(Value::Null), "帳號伺服器"))); + say(&format!("連不上帳號伺服器:{}", why_refused(st, &serde_json::from_str(&text).unwrap_or(Value::Null), "帳號伺服器"))); std::thread::sleep(Duration::from_secs(backoff)); backoff = (backoff * 2).min(30); continue; } let Ok(job) = serde_json::from_str::(&text) else { - hub().set_relay_status(&format!("連不上帳號伺服器:{}", why_refused(st, &Value::Null, "帳號伺服器"))); + say(&format!("連不上帳號伺服器:{}", why_refused(st, &Value::Null, "帳號伺服器"))); std::thread::sleep(Duration::from_secs(backoff)); backoff = (backoff * 2).min(30); continue; }; - hub().set_relay_status("已連線"); + say("已連線"); backoff = 1; let id = job["id"].as_str().unwrap_or("").to_string(); let req = req_from_json(&job); @@ -3349,6 +3371,14 @@ pub fn pair_claim(base_settings: &Settings, url: &str, code: &str) -> Result bool { + let at = self_hop(&format!("{}/relay/host/peers", url.trim_end_matches('/'))); + let Ok(mut r) = relay_agent(15, &at).get(&at).header("Authorization", &format!("Bearer {token}")).call() else { return false }; + serde_json::from_str::(&r.body_mut().read_to_string().unwrap_or_default()).is_ok_and(|v| v["me_online"] == true) +} + pub fn peers(s: &Settings) -> Result, String> { let mut r = relay_agent(15, &s.relay_url).get(&format!("{}/relay/host/peers", s.relay_url)).header("Authorization", &format!("Bearer {}", s.host_token)).call().map_err(|e| format!("連不到帳號伺服器:{}", why_unreachable(&e)))?; let st = r.status().as_u16(); @@ -3488,6 +3518,23 @@ pub fn net_check(s: &Settings) -> Vec { Ok((st, _, _)) => out.push(bad(format!("下載速度:帳號伺服器回了 HTTP {st}"))), Err(e) => out.push(bad(format!("下載速度:{e}"))), } + // This computer's own sign-in: the road above can be fine while the server no longer knows + // this computer's key — it then only ever looked 「離線」. (The lasting connection's own state + // is the in-app check's line before these: doctor_ui.) + if !s.host_token.is_empty() { + match timed("/relay/host/peers", true, 15) { + Ok((200, _, _)) => out.push(ok("這台的登入:帳號伺服器認得這台電腦".to_string())), + Ok((401, _, _)) => out.push(bad(if s.hands_for.is_empty() { + "這台的登入:帳號伺服器已經不認得這台電腦(被移出帳號,或被同名的電腦換掉了):到「設定 › 手機與帳號」重新登入".to_string() + } else { + "這台的登入:帳號伺服器已經不認得這台電腦(被移出帳號了):在大腦那邊「加一台電腦」產生新的配對碼,這台重新加入(anybot setup),不用重新登入".to_string() + })), + // (An account server older than the computers' list: nothing to ask.) + Ok((404, _, _)) => {} + Ok((st, _, _)) => out.push(bad(format!("這台的登入:帳號伺服器回了 HTTP {st}"))), + Err(e) => out.push(bad(format!("這台的登入:{e}"))), + } + } // On to the brain (a screen): the whole road, minus the first leg. if !s.brain_id.is_empty() && !s.host_token.is_empty() { let name = if s.brain_name.trim().is_empty() { "大腦".to_string() } else { format!("大腦「{}」", s.brain_name.trim()) }; @@ -4243,28 +4290,40 @@ mod tests { let at = |url: String| Settings { relay_url: url, ..s.clone() }; let speed = |p: &str| p.starts_with("/api/speed?bytes="); // The whole road. - let url = stand_in_relay(8, move |p, b| match p { + let url = stand_in_relay(12, move |p, b| match p { "/api/hello" => Resp::json(&json!({"app": "anybot-relay"})), _ if speed(p) => Resp::bytes("application/octet-stream", vec![7u8; 256 * 1024]), "/relay/hosts/brain-9/api/sync/ping" if b == "key-1" => Resp::json(&json!({"ok": true})), + "/relay/host/peers" if b == "key-1" => Resp::json(&json!({"hosts": []})), _ => Resp::error(401, "這台電腦的金鑰無效"), }); let lines = net_check(&at(url)); let texts: Vec<&str> = lines.iter().map(|l| l.text.as_str()).collect(); - assert_eq!(lines.len(), 3, "{texts:?}"); + assert_eq!(lines.len(), 4, "{texts:?}"); assert!(lines.iter().all(|l| l.ok), "{texts:?}"); assert!(texts[0].starts_with("這台 ↔ 帳號伺服器:來回 ") && texts[0].contains("第一次連上"), "{texts:?}"); assert!(texts[1].starts_with("下載 256 KB 用了 ") && texts[1].contains("每秒"), "{texts:?}"); - assert!(texts[2].starts_with("帳號伺服器 ↔ 大腦「雲端大腦」:約 ") && texts[2].contains("全程"), "{texts:?}"); + assert_eq!(texts[2], "這台的登入:帳號伺服器認得這台電腦", "{texts:?}"); + assert!(texts[3].starts_with("帳號伺服器 ↔ 大腦「雲端大腦」:約 ") && texts[3].contains("全程"), "{texts:?}"); + // The account server no longer knows this computer's key (taken off the account, or + // replaced by a computer of the same name): said, with what to do. + let url = stand_in_relay(12, move |p, b| match p { + "/api/hello" => Resp::json(&json!({"app": "anybot-relay"})), + _ if speed(p) => Resp::bytes("application/octet-stream", vec![7u8; 1024]), + "/relay/hosts/brain-9/api/sync/ping" if b == "key-1" => Resp::json(&json!({"ok": true})), + _ => Resp::error(401, "這台電腦的金鑰無效"), + }); + let lines = net_check(&at(url)); + assert!(lines.iter().any(|l| !l.ok && l.text.contains("已經不認得這台電腦") && l.text.contains("重新登入")), "{lines:?}"); // An old account server and an old brain: they can't be timed, which is no fault. - let url = stand_in_relay(8, move |p, _| match p { + let url = stand_in_relay(12, move |p, _| match p { "/api/hello" => Resp::json(&json!({"app": "anybot-relay"})), _ => Resp::error(404, NO_SUCH_PATH), }); let lines = net_check(&at(url)); assert!(lines.iter().all(|l| l.ok) && lines[1].text.contains("帳號伺服器是舊版") && lines[2].text.contains("是舊版"), "{lines:?}"); // The brain is off: said, with the account server's words. - let url = stand_in_relay(8, move |p, _| match p { + let url = stand_in_relay(12, move |p, _| match p { "/api/hello" => Resp::json(&json!({"app": "anybot-relay"})), _ if speed(p) => Resp::bytes("application/octet-stream", vec![7u8; 1024]), _ => Resp::error(503, "那台 AnyBot 目前離線(電腦可能關機、睡眠、斷網,或 AnyBot 沒開)"), @@ -4278,7 +4337,7 @@ mod tests { let lines = net_check(&at(format!("http://127.0.0.1:{port}"))); assert!(lines.len() == 1 && !lines[0].ok && lines[0].text.contains("連不到"), "{lines:?}"); // A slow brain leg is called slow, and on whose side. - let url = stand_in_relay(8, move |p, _| match p { + let url = stand_in_relay(12, move |p, _| match p { "/api/hello" => Resp::json(&json!({"app": "anybot-relay"})), _ if speed(p) => Resp::bytes("application/octet-stream", vec![7u8; 1024]), _ => { diff --git a/src/setup.rs b/src/setup.rs index e172310..2896efb 100644 --- a/src/setup.rs +++ b/src/setup.rs @@ -666,7 +666,11 @@ fn list_brains(s: &Settings) -> Result, String> { id: h["id"].as_str().unwrap_or("").into(), name: h["name"].as_str().unwrap_or("").into(), online: h["online"].as_bool().unwrap_or(false), - last: h["last_seen_text"].as_str().unwrap_or("").into(), + // (With why it went offline, when the account server saw it go.) + last: match h["why"].as_str().unwrap_or("") { + "" => h["last_seen_text"].as_str().unwrap_or("").into(), + why => format!("{},{why}", h["last_seen_text"].as_str().unwrap_or("")), + }, }) .collect(); v.sort_by_key(|p| !p.online); diff --git a/src/tunnel.rs b/src/tunnel.rs index 2dac626..f23e166 100644 --- a/src/tunnel.rs +++ b/src/tunnel.rs @@ -285,6 +285,10 @@ fn open(url: &str, token: &str) -> Result, NoLink> { } } +/// Said while another copy of this AnyBot holds the connection (see `keep`). +pub const REPLACED: &str = "另一份 AnyBot 正用這台電腦的登入連著帳號伺服器(同一台開了兩份,或資料夾被複製到別台):先讓它用,它斷了這份才連回去(每 5 分鐘看一次)"; +static REPLACED_WAIT_SECS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(300); + /// Keep the connection for as long as `alive()`. Returns false when the account server has no /// WebSocket (the caller then uses the old way). pub fn run(url: &str, token: &str, alive: &dyn Fn() -> bool, status: &dyn Fn(&str)) -> bool { @@ -294,7 +298,11 @@ pub fn run(url: &str, token: &str, alive: &dyn Fn() -> bool, status: &dyn Fn(&st match open(url, token) { Err(NoLink { old: true, .. }) => return false, Err(e) => { - status(&format!("連不上帳號伺服器:{}", e.why)); + // (Only while this is still the live tunnel: an old one, after 換網址, finishing a + // ten-second try after the new one had connected, said 「連不上」 over 「已連線」.) + if alive() { + status(&format!("連不上帳號伺服器:{}", e.why)); + } // Wait, but notice at once when told to stop. let until = Instant::now() + Duration::from_secs(backoff); while Instant::now() < until && alive() { @@ -303,10 +311,35 @@ pub fn run(url: &str, token: &str, alive: &dyn Fn() -> bool, status: &dyn Fn(&st backoff = (backoff * 2).min(30); } Ok(ws) => { + if !alive() { + break; + } status("已連線"); let serial = SERIAL.fetch_add(1, std::sync::atomic::Ordering::SeqCst); let since = Instant::now(); - keep(ws, serial, alive); + if keep(ws, serial, alive) { + // Another copy of this AnyBot (the same sign-in) is connected: it keeps the + // place. This one looks again in a while, and comes back only once the place is + // free — taking it back at once (or every few minutes), the two handed it back + // and forth, and a phone saw one brain, then the other. + if alive() { + status(REPLACED); + } + // (The first look soon: the copy that took the place may have gone again at once.) + let mut wait = REPLACED_WAIT_SECS.load(std::sync::atomic::Ordering::Relaxed).min(15); + loop { + let until = Instant::now() + Duration::from_secs(wait); + wait = REPLACED_WAIT_SECS.load(std::sync::atomic::Ordering::Relaxed); + while Instant::now() < until && alive() { + std::thread::sleep(Duration::from_millis(200)); + } + if !alive() || !crate::remote::place_taken(url, token) { + break; + } + } + backoff = 1; + continue; + } if alive() { status("連線中斷,正在重新連線…"); } @@ -326,7 +359,9 @@ pub fn run(url: &str, token: &str, alive: &dyn Fn() -> bool, status: &dyn Fn(&st true } -fn keep(mut ws: WebSocket, serial: u64, alive: &dyn Fn() -> bool) { +/// Keep one connection until it ends. True when the relay ended it because another connection +/// with this computer's key took its place (two copies of the same AnyBot running). +fn keep(mut ws: WebSocket, serial: u64, alive: &dyn Fn() -> bool) -> bool { let mut pace = wire::Pace::new(); let (tx, rx) = channel::>(); let calls: Calls = Arc::default(); @@ -335,6 +370,7 @@ fn keep(mut ws: WebSocket, serial: u64, alive: &dyn Fn() -> bool) { let _ = tx.send(wire::pack(&json!({"t": "hello", "brain": s.brain_id, "hands": s.device_link}), &[])); let (mut heard, mut pinged) = (Instant::now(), Instant::now()); let mut got = bytes_in(); + let mut replaced = false; 'live: while alive() { pace.tune(ws.get_ref().tcp()); match ws.read() { @@ -342,8 +378,11 @@ fn keep(mut ws: WebSocket, serial: u64, alive: &dyn Fn() -> bool) { heard = Instant::now(); pace.moved(); if let Some((head, body)) = wire::unpack(&b) { - // The relay says this machine was unregistered (signed out): stop for good. + // The relay ends this connection: this machine was unregistered (signed out, + // or replaced by a computer of the same name), or another connection with its + // key took the place of this one. if head["t"] == "bye" { + replaced = head["why"] == "replaced"; break; } on_frame(head, body, &tx, &calls); @@ -397,6 +436,7 @@ fn keep(mut ws: WebSocket, serial: u64, alive: &dyn Fn() -> bool) { for (_, w) in calls.lock().unwrap().drain() { let _ = w.send(Err(CUT.into())); } + replaced } /// People watching the bots' computer through the account server: one VNC stream each, by the @@ -660,6 +700,87 @@ mod tests { *super::link().lock().unwrap_or_else(|e| e.into_inner()) = None; } + /// The account server ends this connection because another one with this computer's key took + /// its place (a second copy of the same AnyBot): it says so, and waits before taking the place + /// back — at once, the two copies handed it back and forth. + #[test] + fn replaced_by_another_copy_it_says_so_and_waits() { + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + let _link = super::LINK_TESTS.lock().unwrap_or_else(|e| e.into_inner()); + let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = l.local_addr().unwrap().port(); + let opened = std::sync::Arc::new(AtomicUsize::new(0)); + let opened2 = opened.clone(); + std::thread::spawn(move || { + for s in l.incoming() { + let Ok(s) = s else { break }; + opened2.fetch_add(1, Ordering::SeqCst); + let mut ws = tungstenite::accept(s).unwrap(); + let _ = ws.send(tungstenite::Message::Binary(super::wire::pack(&serde_json::json!({"t": "bye", "why": "replaced"}), &[]).into())); + std::thread::sleep(std::time::Duration::from_millis(200)); + } + }); + let said = std::sync::Arc::new(std::sync::Mutex::new(Vec::::new())); + let (said2, stop) = (said.clone(), std::sync::Arc::new(AtomicBool::new(false))); + let stop2 = stop.clone(); + let h = std::thread::spawn(move || { + super::run(&format!("http://127.0.0.1:{port}"), "token", &|| !stop2.load(Ordering::Relaxed), &|m| said2.lock().unwrap().push(m.to_string())); + }); + std::thread::sleep(std::time::Duration::from_millis(3_000)); + assert_eq!(said.lock().unwrap().last().map(String::as_str), Some(super::REPLACED), "{:?}", said.lock().unwrap()); + assert_eq!(opened.load(Ordering::SeqCst), 1, "it didn't take the place back at once"); + stop.store(true, Ordering::Relaxed); + let _ = h.join(); + *super::link().lock().unwrap_or_else(|e| e.into_inner()) = None; + } + + /// After its wait, a replaced copy asks whether its place is still held: held, it keeps + /// waiting (two copies used to swap every five minutes); free, it connects again. + #[test] + fn a_replaced_copy_comes_back_only_when_its_place_is_free() { + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + let _link = super::LINK_TESTS.lock().unwrap_or_else(|e| e.into_inner()); + super::REPLACED_WAIT_SECS.store(1, Ordering::Relaxed); + let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = l.local_addr().unwrap().port(); + let (opened, asked, held) = (std::sync::Arc::new(AtomicUsize::new(0)), std::sync::Arc::new(AtomicUsize::new(0)), std::sync::Arc::new(AtomicBool::new(true))); + let (opened2, asked2, held2) = (opened.clone(), asked.clone(), held.clone()); + std::thread::spawn(move || { + for s in l.incoming() { + let Ok(mut s) = s else { break }; + let mut head = [0u8; 2048]; + let n = s.peek(&mut head).unwrap_or(0); + if String::from_utf8_lossy(&head[..n]).starts_with("GET /relay/host/peers") { + use std::io::{Read, Write}; + let _ = s.read(&mut head); + asked2.fetch_add(1, Ordering::SeqCst); + let body = format!("{{\"hosts\":[],\"me_online\":{}}}", held2.load(Ordering::SeqCst)); + let _ = write!(s, "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()); + continue; + } + opened2.fetch_add(1, Ordering::SeqCst); + let mut ws = tungstenite::accept(s).unwrap(); + let _ = ws.send(tungstenite::Message::Binary(super::wire::pack(&serde_json::json!({"t": "bye", "why": "replaced"}), &[]).into())); + std::thread::sleep(std::time::Duration::from_millis(200)); + } + }); + let stop = std::sync::Arc::new(AtomicBool::new(false)); + let stop2 = stop.clone(); + let h = std::thread::spawn(move || { + super::run(&format!("http://127.0.0.1:{port}"), "token", &|| !stop2.load(Ordering::Relaxed), &|_| {}); + }); + std::thread::sleep(std::time::Duration::from_millis(3_500)); + assert!(asked.load(Ordering::SeqCst) >= 2, "it asked after each wait"); + assert_eq!(opened.load(Ordering::SeqCst), 1, "held: it kept waiting"); + held.store(false, Ordering::SeqCst); + std::thread::sleep(std::time::Duration::from_millis(2_500)); + assert!(opened.load(Ordering::SeqCst) >= 2, "free: it came back"); + stop.store(true, Ordering::Relaxed); + let _ = h.join(); + super::REPLACED_WAIT_SECS.store(300, Ordering::Relaxed); + *super::link().lock().unwrap_or_else(|e| e.into_inner()) = None; + } + #[test] fn the_public_certificates_are_always_trusted() { // The system's list comes on top; a computer without one still reaches public servers.