diff --git a/FEATURES.md b/FEATURES.md index b858926..479dce1 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -865,7 +865,8 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。 - 還沒有快照時按鈕是灰的。 - **「重設電腦」**(紅色按鈕):全部清空,換一台全新的電腦。步驟:正在拆除舊電腦 → 正在清除資料 → 正在建立。 - **同時只能有一個更新**:再按會顯示「已經有一個更新在進行中」。開始後就不能取消。 -- **忙碌時按更新會排隊**:有 Bot 正在用電腦時按「更新」(或排程更新遇到忙碌),會被擋下並記住這次請求(「已排隊,它一閒下來就自動更新」);電腦沒人用滿一分鐘就自動開始。自動更新失敗會自動重試,每次失敗多等 30 秒(30、60、90 秒…),成功後歸零。 +- **忙碌時按更新會排隊**:有 Bot 正在用電腦時按「更新」(或排程更新遇到忙碌),會被擋下並記住這次請求(「已排隊,它一閒下來就自動更新」);電腦沒人用滿一分鐘就自動開始。自動更新失敗會自動重試,等的時間從失敗那一刻算、每次多等 30 秒(30、60、90 秒…;以前從開始更新算,重建要好幾分鐘,等於失敗完馬上又來),重試沿用第一次存的快照(以前每試一次就多存一份整個家目錄,保留一週,會把磁碟塞滿);連續失敗 5 次就不再自動重試(記錄寫「更新連續失敗 5 次」),處理好原因再按「更新」或等排程重來。成功後歸零。 +- **命令列更新**:`make update-box`(就是 `anybot --update-box`)等於按「更新」:AnyBot 開著就請它做(通常 20 秒內接手,回一句話:開始了、已排隊、已經是最新、這台不是大腦),沒開就自己做完再結束;伺服器上請伺服器的大腦做(`docker compose exec`)。永遠用裝好的 AnyBot 帶的電腦版本和它設定的 Docker 主機(Lima、ssh://、伺服器的)。以前它照原始碼另外建映像、用預設的 docker:版本跟大腦帶的不同,大腦一分鐘內就換回自己的版本;大腦設了別的 Docker 主機時還建錯地方。要新版的電腦,先更新 AnyBot 本身(make update、make update-server),它會自己把電腦換新。 - **中斷了會接續**:更新做到一半 App 被關掉,下次打開時,如果紀錄在 10 分鐘內、而且電腦不正常,就自動接續;超過 10 分鐘就清掉紀錄,電腦正常時也不重做(都取自原版)。 - 進度在設定頁用步驟列和進度條顯示。 - **新版本與排程更新**(原版:「有新映像檔就在指定的當地時間自動更新,錯過有一小時的補執行時間」): @@ -901,7 +902,7 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。 - 同一個網路的手機(不經帳號伺服器):同一個網頁,連 AnyBot 自己的 `/api/vnc`。 - 這台電腦自己的 Bot 的電腦:直接開它的 noVNC。 - **網頁**:最上面是返回、電腦名稱、狀態(即時觀看/你在操作)和「接管/交還給 Bot」。預設只看,按「接管」才會把你的滑鼠鍵盤送過去;需要處理卡片的「接管」直接打開接管。接管時有「打字」:打中文或任何語言(貼進目前的視窗),還有 Enter、Esc、Tab、⌫。斷線會自己重連。 -- **你在操作時 Bot 會等**:你點擊或按鍵後 8 秒內,Bot 的滑鼠鍵盤操作會收到「使用者正在自己操作這台電腦」。不用另外按什麼;停下 8 秒它就繼續。需要處理卡片的「接管」會讓 Bot 一直等,直到你按「我完成了」或「跳過」。 +- **你在操作時 Bot 會等**:你點擊或按鍵後 8 秒內,在你正在看的那個螢幕上做事的 Bot,滑鼠鍵盤操作會收到「使用者正在自己操作這台電腦」(別的螢幕上的 Bot 照做)。開著看畫面的螢幕不算閒置、不會被收掉,不管從哪裡開的(第 13 版起 Bot 的電腦自己看有沒有人連著)。不用另外按什麼;停下 8 秒它就繼續。需要處理卡片的「接管」會讓 Bot 一直等,直到你按「我完成了」或「跳過」。 - **VNC 密碼不出大腦**:大腦用 Bot 的電腦自己的 VNC 密碼登入,給看的人的是「不用密碼」;能連到這裡的人已經過帳號伺服器(或手機密碼)。 - 以前的做法(每 0.45~1 秒拍一張 1 MB 的圖、解開再壓、經過帳號伺服器傳;點擊另走一條路)已經拆掉。 diff --git a/Makefile b/Makefile index 8a44027..6dea974 100644 --- a/Makefile +++ b/Makefile @@ -43,8 +43,9 @@ help: @echo " make update-hands 只更新 Linux 手腳(換新程式、重新啟動背景服務)" @echo " make update-server 只更新伺服器(帳號伺服器 + 大腦,Docker)" @echo " 加 PULL=0:不拉新版,裝現在這份原始碼" - @echo " make update-box 重建「Bot 的電腦」映像並換上新電腦(檔案和登入保留)" - @echo " 有視窗的大腦請優先用設定 › 電腦 › 更新 Bot 的電腦(會先存快照)" + @echo " make update-box 請這台的 AnyBot(大腦)現在更新「Bot 的電腦」=設定 › 電腦 › 更新" + @echo " (先存快照、檔案和登入保留;用它帶的版本和它設定的 Docker 主機)" + @echo " 要新版的電腦:先 make update(伺服器 make update-server),它會自己換新" @echo "" @echo " make deps 裝好建置需要的東西:系統套件和 Rust(Linux 會問 sudo 密碼)" @echo " make doctor 檢查這台缺什麼" @@ -154,21 +155,23 @@ update-hands: update-server: @PULL=$(PULL) MAKE="$(MAKE)" sh deploy/update.sh server -# The box (Bot 的電腦): rebuild the image from box/ and take the container down, so the running -# brain opens a new computer from the new image the next time a bot uses one (create_container -# on demand). The home volume (anybot-box-home) is untouched: files and browser logins stay. -# Same effect as 設定 › 電腦 › 更新 Bot 的電腦, minus its snapshot and progress display — on a -# brain with a window, prefer the settings page. A box renamed per brain (ANYBOT_BOX_NAME) and a -# box image of its own (ANYBOT_BOX_IMAGE) are respected. +# The box (Bot 的電腦): ask the AnyBot installed here (the brain) to update its computer now — +# the same as 設定 › 電腦 › 更新: a snapshot first, queued while a bot is using it, files and +# logins kept. `anybot --update-box` asks the AnyBot running on its data folder, or with none +# running does it itself and waits. It is always that AnyBot's own box version, on the Docker +# host it is set to use (Lima, ssh://, the server's). This target used to build box/ from this +# checkout beside it with plain `docker`: another version than the brain's (which put its own +# back within a minute), and often another Docker than the brain's. A newer box comes with a +# newer AnyBot: make update / make update-server, and it updates the box by itself. update-box: - @if [ "$(PULL)" = "1" ]; then git pull --ff-only || { echo " ✗ git pull 沒成功(有未送出的修改?),先處理好再更新"; exit 1; }; fi - @command -v docker >/dev/null 2>&1 || { echo " ✗ 這台沒有 docker,建不了 Bot 的電腦"; exit 1; } - @V=$$(sed -n 's/^LABEL anybot.box.version="\([0-9]*\)"/\1/p' box/Dockerfile); \ - echo "建立 Bot 的電腦映像(box 第 $$V 版,第一次要幾分鐘)…"; \ - docker build -q -t $${ANYBOT_BOX_IMAGE:-anybot-box:1} box/ >/dev/null || { echo " ✗ 建立映像檔失敗"; exit 1; }; \ - echo "映像檔完成。" - @docker rm -f $${ANYBOT_BOX_NAME:-anybot-box} >/dev/null 2>&1 && echo "舊電腦已停。" || true - @echo "Bot 下次用電腦時會用新映像開機(檔案和登入保留)。" + @if [ -f deploy/server/.env ]; then \ + s=$$(sed -n "s/^DOCKER_SOCKET=['\"]\{0,1\}\([^'\"]*\)['\"]\{0,1\}\$$/\1/p" deploy/server/.env | tail -n 1); \ + cd deploy/server && env $${s:+DOCKER_HOST=unix://$$s} docker compose exec -T anybot anybot --update-box; \ + else \ + b="$(HOME)/.local/bin/anybot"; [ -x "$$b" ] || b="$(APPDIR)/AnyBot.app/Contents/MacOS/AnyBot"; \ + [ -x "$$b" ] || { echo " ✗ 這台還沒裝 AnyBot(make install),沒有 Bot 的電腦可以更新"; exit 1; }; \ + "$$b" --update-box; \ + fi || { echo " ✗ 沒有更新。上面說不認得「--update-box」的話,裝好的 AnyBot 是舊版:先 make update(伺服器 make update-server)"; exit 1; } # The author, once: sign every commit so installs can check where an update came from. sign-setup: diff --git a/box/Dockerfile b/box/Dockerfile index af9f41e..897c854 100644 --- a/box/Dockerfile +++ b/box/Dockerfile @@ -107,6 +107,6 @@ RUN chmod +x /usr/local/bin/anybot-box-start /usr/local/bin/anybot-a11y /usr/loc # unset, so one command can still ask for LANG=C. ENV LANG=zh_TW.UTF-8 LANGUAGE=zh_TW:zh:en DISPLAY=:1 SCREEN_SIZE=1280x800x24 XDG_CURRENT_DESKTOP=XFCE GTK_MODULES=gail:atk-bridge GTK_A11Y=atspi GNOME_ACCESSIBILITY=1 NO_AT_BRIDGE=0 EXPOSE 6080 -LABEL anybot.box.version="12" +LABEL anybot.box.version="13" ENTRYPOINT ["/usr/bin/tini", "--"] CMD ["/usr/local/bin/anybot-box-start"] diff --git a/box/screen b/box/screen index aea5962..b3d3b5a 100755 --- a/box/screen +++ b/box/screen @@ -130,18 +130,43 @@ up() { print_env "$key" } +# Someone is watching display :$1 right now: a viewer holds a connection to its VNC port — +# noVNC through websockify (the desktop's 開啟電腦, the browser) or AnyBot's own proxy (the +# phone, the account server). Seen here, so it counts however the viewer was opened. +# (NET_TCP: the socket tables to read, for the tests.) +watched() { + [[ "${1:-}" =~ ^[0-9]+$ ]] || return 1 + local hex f files=() + hex=$(printf '%04X' $((5900 + $1))) + for f in ${NET_TCP:-/proc/net/tcp /proc/net/tcp6}; do [ -r "$f" ] && files+=("$f"); done + [ ${#files[@]} -gt 0 ] || return 1 + # The server's end of an established connection: local port 5900+n, state 01. + awk -v p=":$hex" 'substr($2, length($2) - 4) == p && $4 == "01" { f = 1 } END { exit !f }' "${files[@]}" +} + reap() { local limit=$1 now; now=$(date +%s) for s in "$DIR"/*/; do [ -d "$s" ] || continue local k; k=$(basename "$s") local last; last=$(stat -c %Y "$s/last" 2>/dev/null || echo 0) - if [ $((now - last)) -ge "$limit" ] || ! alive "$(head -1 "$s/pids" 2>/dev/null)"; then close "$k"; echo "closed $k"; fi + if ! alive "$(head -1 "$s/pids" 2>/dev/null)"; then + close "$k"; echo "closed $k" + elif [ $((now - last)) -ge "$limit" ]; then + # Watched is not idle (開著看畫面的不算閒置): it counts as used now. + if watched "$(cat "$s/display" 2>/dev/null)"; then touch "$s/last"; continue; fi + close "$k"; echo "closed $k" + fi done } cmd=${1:-}; arg=${2:-} -exec 8>"$DIR/.lock" +# One lock for every caller, whoever made its file. It used to be opened for writing: a `list` +# run as root made it root's, the bot user couldn't open it after that, and every screen failed +# with ERROR=busy. flock needs only a read-only open — any user can make one of a file anyone can +# read, and one without O_CREAT isn't refused in this sticky folder (fs.protected_regular). +[ -e "$DIR/.lock" ] || { : >>"$DIR/.lock"; chmod 644 "$DIR/.lock"; } 2>/dev/null +exec 8<"$DIR/.lock" || { echo "ERROR=lock"; exit 1; } flock -w 20 8 || { echo "ERROR=busy"; exit 1; } case "$cmd" in up) key_ok "$arg" || { echo "ERROR=bad key"; exit 2; }; up "$arg" ;; diff --git a/docs/feature-map/computers.md b/docs/feature-map/computers.md index 86d6493..80393fe 100644 --- a/docs/feature-map/computers.md +++ b/docs/feature-map/computers.md @@ -30,12 +30,13 @@ ## 陷阱 -- 按「更新」時有 Bot 正在用電腦:會被擋下並排隊(訊息說「已排隊,它一閒下來就自動更新」),box 沒人用滿 60 秒就自動開始;自動更新失敗會自己重試,越錯越慢(30、60、90 秒…),成功後歸零。自動更新只在「大腦」那台發生;連別台大腦的 app(手腳)自己的「Bot 的電腦」沒有可更新的東西,是大腦的手腳:要更新請到大腦的介面按。 +- 按「更新」時有 Bot 正在用電腦:會被擋下並排隊(訊息說「已排隊,它一閒下來就自動更新」),box 沒人用滿 60 秒就自動開始;自動更新失敗會自己重試,從失敗那一刻起越等越久(30、60、90 秒…),重試沿用第一次存的快照(不會每次再存一份);連續失敗 5 次就不再自動重試,記錄寫「更新連續失敗 5 次」,處理好原因再按「更新」重來。成功後歸零。自動更新只在「大腦」那台發生;連別台大腦的 app(手腳)自己的「Bot 的電腦」沒有可更新的東西,是大腦的手腳:要更新請到大腦的介面按。 +- 命令列的 `make update-box`(就是 `anybot --update-box`)等於按「更新」:AnyBot 開著就請它做(通常 20 秒內接手、回一句話;忙著存快照時晚一點),沒開就自己做完再結束;伺服器上是請伺服器的大腦做。用的永遠是裝好的 AnyBot 帶的電腦版本和它設定的 Docker 主機(Lima、ssh://)。要新版的電腦先更新 AnyBot 本身(make update、make update-server),它會自己把電腦換新;另外照原始碼建一台別的版本,大腦一分鐘內就會換回它自己的版本。 - Bot 不能自己換電腦:工具指定了別台,但使用者最近三則訊息沒提到那台,這一步會被移回使用者選的那台,結果裡會說。真的要別台先問使用者。 - 使用者選的那台沒開機、或那台的 AnyBot 沒開沒登入,就不在清單上:Bot 先待在自己的電腦,`list_computers` 會寫那台「現在沒有連線」。 - 在 Bot 自己的電腦上做事不用問,但它看不到使用者的檔案;檔案工具只碰得到自己的資料夾(大家共用同一台)。 - Bot 的電腦的桌面是第 12 版起換的(照 LazyBoy2 的 box:XFCE 工作列、深色主題、粉圓字型、繁中、台北時間);第 11 版以前是 fluxbox,只有右鍵選單和一條細工作列,設定 › 電腦「更新 Bot 的電腦」換新版。桌面設定每次開機照映像檔重放,在桌面上改的外觀、工作列不會留下;留下的是檔案和瀏覽器的登入。工作列鎖住(xfconf 的鎖要寫使用者名稱 bot,寫「*」不算數);它的「面板 › 登出 › 結束」只關掉工作列,一秒後自己回來。網頁上傳檔案的視窗開機時設好大小和位置(GTK 沒有記著位置就照字型算大小,比螢幕大)。時區是 /etc/localtime(台北),沒有 TZ 變數,Bot 改了就生效。 -- 檔案視窗的「取消」「開啟」在視窗最上面(第 11 版以前在最下面、被螢幕切掉,網頁上傳圖片選得到檔案卻送不出去——設定 › 電腦「更新 Bot 的電腦」換新版)。看畫面時可以跟自己的電腦互相複製貼上;在畫面裡打的字進到正在看的那個螢幕(Bot 自己的螢幕也一樣,不會打到共用的)。 +- 檔案視窗的「取消」「開啟」在視窗最上面(第 11 版以前在最下面、被螢幕切掉,網頁上傳圖片選得到檔案卻送不出去——設定 › 電腦「更新 Bot 的電腦」換新版)。看畫面時可以跟自己的電腦互相複製貼上;在畫面裡打的字進到正在看的那個螢幕(Bot 自己的螢幕也一樣,不會打到共用的)。那個 Bot 的螢幕沒開時,看到的是共用桌面,點擊和打字也都算在共用桌面(共用桌面上的 Bot 會停手);畫面中途關掉,之後打的字不會另外開一個看不到的螢幕。 - 從帳號看 Bot 電腦的畫面,只要開著就不會斷;之前靜止畫面一分鐘、或看超過十分鐘會被帳號伺服器切掉,要更新帳號伺服器(make update-server)。 - 「在這台電腦上執行」設成永不允許(或被管理員鎖住)時,這台的檔案也不能傳出去、打開或發佈。 - SSH 電腦上的檔案不能直接傳到聊天、打開給使用者看或發佈網站,要先複製到 Bot 自己的電腦。 diff --git a/docs/feature-map/screen.md b/docs/feature-map/screen.md index 593f07d..fbada91 100644 --- a/docs/feature-map/screen.md +++ b/docs/feature-map/screen.md @@ -11,7 +11,7 @@ Bot 用一個 `computer` 工具看一台電腦的螢幕、動滑鼠和鍵盤: - `intent`:系統捷徑(音量、Wi-Fi、鎖螢幕、深淺色、清空垃圾桶,Mac 還有退出磁碟)一步做完。電腦現況列了「系統捷徑」才有:macOS 和 Linux 桌面有,Windows 和 Bot 自己的電腦沒有。 - 交給使用者:`hand_over_computer` 在聊天放一張「需要處理」卡和那台電腦的畫面,使用者做完按「我完成了」或「跳過」。 - 示範教學(macOS、Linux X11):使用者自己做一次,AnyBot 記成步驟和每一步的畫面;Bot 用 `view_demo_step` 看某一步當時的畫面。 -- Bot 自己的電腦:每個 Bot 有自己的螢幕(照 Grok Bot 的分法:一台電腦、每個 Bot 一個螢幕),Bot 第一次看畫面或用瀏覽器時才開,大家同時做互不干擾。支線另開一個暫時的螢幕(瀏覽器從主線那份複製),支線結束就關掉、複製的那份也刪掉。同時最多開 6 個,閒置 10 分鐘的會自己關掉(瀏覽器的登入留著);開著看畫面的那個不算閒置,不會被關。原本那個共用的桌面還在。 +- Bot 自己的電腦:每個 Bot 有自己的螢幕(照 Grok Bot 的分法:一台電腦、每個 Bot 一個螢幕),Bot 第一次看畫面或用瀏覽器時才開,大家同時做互不干擾。支線另開一個暫時的螢幕(瀏覽器從主線那份複製),支線結束就關掉、複製的那份也刪掉。同時最多開 6 個,閒置 10 分鐘的會自己關掉(瀏覽器的登入留著);開著看畫面的那個不算閒置,不會被關——不管是從電腦版「開啟電腦」、「全部螢幕」、手機或帳號開的(Bot 的電腦自己看有沒有人連著那個螢幕;第 13 版起,舊版只算手機和帳號開的)。原本那個共用的桌面還在。 - 使用者自己的電腦只有一個實體螢幕:一次只給一個 Bot 操作,別人在用時會被擋下,對方停手 120 秒後輪到。只看畫面不受影響。 - 截圖上的卡號和驗證碼會先塗黑,才交給模型。 diff --git a/src/app/computers_ui.rs b/src/app/computers_ui.rs index 364f827..2d29eea 100644 --- a/src/app/computers_ui.rs +++ b/src/app/computers_ui.rs @@ -1029,6 +1029,10 @@ impl App { // so a starting box can't freeze the window for its timeout. self.box_task(move || { let key = if cloudbox::open_screens().iter().any(|(k, _)| *k == key) { key } else { String::new() }; + // This viewer is noVNC straight to the box (AnyBot never sees it): marked used now, + // so a screen idle for almost 10 minutes isn't reaped before the page connects; from + // then on the box sees the connection itself (box/screen's reap: watched). + cloudbox::touch_screen(&key); let url = cloudbox::viewer_url_of(&key, control)?; crate::preview::open_with_system(&url); Ok(String::new()) diff --git a/src/cloudbox.rs b/src/cloudbox.rs index 85ea48b..8687306 100644 --- a/src/cloudbox.rs +++ b/src/cloudbox.rs @@ -309,10 +309,62 @@ pub fn is_busy() -> bool { /// The person asked for an update while the box was in use (or a rebuild failed): run it at the /// next quiet moment (update_when_idle) instead of dropping the request on the floor. static PENDING_UPDATE: AtomicBool = AtomicBool::new(false); -/// The next allowed retry of a failed auto-update (longer waits after each failure). -fn next_try() -> &'static std::sync::Mutex> { - static N: std::sync::OnceLock>> = std::sync::OnceLock::new(); - N.get_or_init(|| std::sync::Mutex::new(None)) + +/// Automatic tries of a failing update stop after this many failures in a row; the person's 更新 +/// (or a schedule they set) starts over with a full set. +const UPDATE_TRIES_MAX: u32 = 5; + +/// Updates that failed in a row, and when the next automatic try may start. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +struct UpdateRetry { + fails: u32, + not_before: Option, +} + +impl UpdateRetry { + /// After a failure at `now`: wait 30 s × the failures so far — counted from the failure. (A + /// rebuild takes minutes: counted from its start, the wait was over before it failed and the + /// next try began at once.) + fn failed(self, now: Instant) -> Self { + let fails = self.fails.saturating_add(1); + UpdateRetry { fails, not_before: Some(now + Duration::from_secs(30 * u64::from(fails.min(UPDATE_TRIES_MAX)))) } + } + fn gave_up(self) -> bool { + self.fails >= UPDATE_TRIES_MAX + } +} + +static UPDATE_RETRY: Mutex = Mutex::new(UpdateRetry { fails: 0, not_before: None }); + +fn update_retry() -> UpdateRetry { + *UPDATE_RETRY.lock().unwrap_or_else(|e| e.into_inner()) +} + +fn set_update_retry(r: UpdateRetry) { + *UPDATE_RETRY.lock().unwrap_or_else(|e| e.into_inner()) = r; +} + +/// What the idle loop does about the update this AnyBot carries. +#[derive(Debug, PartialEq)] +enum AutoUpdate { + No, + /// Asked, but a failed try's wait isn't over. + NotYet, + /// Go; a retry keeps the snapshot its first try saved (each try used to save the whole home + /// folder again, and a week of them is kept: a failing update filled the disk). + Go { snapshot: bool }, +} + +/// `first`: not tried yet for this version; `asked`: queued (the person pressed 更新 while a bot +/// worked, or a try failed). +fn auto_update(first: bool, asked: bool, r: UpdateRetry, now: Instant) -> AutoUpdate { + if !first && !asked || r.gave_up() { + return AutoUpdate::No; + } + if r.not_before.is_some_and(|t| now < t) { + return AutoUpdate::NotYet; + } + AutoUpdate::Go { snapshot: r.fails == 0 } } #[cfg(test)] @@ -470,12 +522,15 @@ pub fn wanted_version() -> String { DOCKERFILE.lines().find_map(|l| l.trim().strip_prefix("LABEL anybot.box.version=")).map(|v| v.trim_matches('"').to_string()).unwrap_or_default() } -/// The running computer is older than the one this AnyBot carries. +/// The running computer is older than the one this AnyBot carries. (Any other version counts: +/// the box is always the one its AnyBot carries — one built beside it is put back.) pub fn update_available() -> bool { - match dk(&["inspect", "-f", "{{index .Config.Labels \"anybot.box.version\"}}", container()]) { - Ok(v) => v.trim() != wanted_version(), - Err(_) => false, - } + box_version().is_some_and(|v| v != wanted_version()) +} + +/// The box's version (its image's label); None when there is no box or Docker can't be asked. +fn box_version() -> Option { + dk(&["inspect", "-f", "{{index .Config.Labels \"anybot.box.version\"}}", container()]).ok().map(|v| v.trim().to_string()) } /// Is `now` inside the window [at, at + grace)? (`at` is "HH:MM"). @@ -1148,7 +1203,15 @@ fn screen_cdp_port(fresh: bool) -> Result { /// bot's browser step needs one. For a check that must never wake a screen, see /// `browser_open_port`.) pub fn browser_running() -> bool { - screen_cdp_port(false).and_then(box_cdp_forward).map(box_cdp_alive).unwrap_or(false) + screen_cdp_port(false).ok().and_then(|p| answering(p, box_cdp_forward, box_cdp_alive)).is_some() +} + +/// The local port that reaches DevTools port `box_port` in the box, when a browser answers there. +/// Asked and given on this side's forward: the box's own port (9222, 9300+n) on this computer is +/// nothing — or a browser of the person's own. +fn answering(box_port: u16, forward: impl Fn(u16) -> Result, alive: impl Fn(u16) -> bool) -> Option { + let local = forward(box_port).ok()?; + alive(local).then_some(local) } /// The current screen's Chromium's local port when it is answering already — and nothing else: @@ -1167,8 +1230,7 @@ pub fn browser_open_port() -> Option { let out = dk_timeout(&["exec", "-u", "bot", container(), "sh", "-c", &format!("command -v anybot-screen >/dev/null || {{ echo CDP_PORT={BOX_CDP_PORT}; exit 0; }}; cat /tmp/anybot-screens/{key}/env 2>/dev/null")], 10_000).ok()?; String::from_utf8_lossy(&out).lines().find_map(|l| l.trim().strip_prefix("CDP_PORT=")?.parse::().ok())? }; - box_cdp_forward(port).ok()?; - box_cdp_alive(port).then_some(port) + answering(port, box_cdp_forward, box_cdp_alive) } /// The current screen's Chromium (each bot its own, on its own screen, with its own profile that @@ -1308,6 +1370,8 @@ pub fn start_background() { loop { // (First wait a little: a computer showing another brain says so right after start.) std::thread::sleep(Duration::from_secs(20)); + // `anybot --update-box` from a terminal (make update-box): as the settings page's 更新. + answer_update_request(); let (idle, rebuilding) = { let s = shared().lock().unwrap(); (s.last_used.elapsed().as_secs(), s.rebuilding) @@ -1345,7 +1409,8 @@ pub fn start_background() { /// controls, the browser launcher): update it by itself once nobody has used it for a minute. /// The first try per version happens on its own; a request the person made while the box was /// busy (PENDING_UPDATE) keeps asking at every quiet moment, and a rebuild that failed retries -/// with longer waits (30 s, 60 s, 90 s…). Files and logins stay (they live in the home volume). +/// with longer waits counted from the failure (30 s, 60 s, 90 s…), at most UPDATE_TRIES_MAX in a +/// row, keeping the first try's snapshot (auto_update). Files and logins stay (the home volume). fn update_when_idle(idle_secs: u64) { static TRIED: Mutex = Mutex::new(String::new()); if !IS_BRAIN.load(Ordering::SeqCst) || idle_secs < 60 || is_busy() || HELD_BY_PERSON.load(Ordering::SeqCst) || viewer_open() { @@ -1355,35 +1420,142 @@ fn update_when_idle(idle_secs: u64) { PENDING_UPDATE.store(false, Ordering::SeqCst); return; } - // A failed rebuild waits: 30 s, 60 s, 90 s… so a broken update can't spam the log. - if let Ok(mut n) = next_try().lock() { - if let Some((at, _)) = *n { - if Instant::now() < at { - return; - } - } - let fails = n.as_ref().map(|(_, f)| *f).unwrap_or(0); - *n = Some((Instant::now() + Duration::from_secs(30 * u64::from(fails + 1)), fails + 1)); - } let want = wanted_version(); - let asked = PENDING_UPDATE.load(Ordering::SeqCst); - { - let mut t = TRIED.lock().unwrap_or_else(|e| e.into_inner()); - if *t == want && !asked { - return; - } - // Only the first try per version announces itself; retries (a busy box) stay quiet. - if *t != want { - *t = want.clone(); - log(&format!("Bot 的電腦是舊版,自動更新到第 {want} 版(檔案和登入都會保留)。")); - } + let first = *TRIED.lock().unwrap_or_else(|e| e.into_inner()) != want; + let AutoUpdate::Go { snapshot } = auto_update(first, PENDING_UPDATE.load(Ordering::SeqCst), update_retry(), Instant::now()) else { + return; + }; + // Only the first try per version announces itself; retries (a busy box, a failed try) are + // in the log already. + if first { + *TRIED.lock().unwrap_or_else(|e| e.into_inner()) = want.clone(); + log(&format!("Bot 的電腦是舊版,自動更新到第 {want} 版(檔案和登入都會保留)。")); } PENDING_UPDATE.store(false, Ordering::SeqCst); - if let Err(e) = rebuild(Rebuild::Update) { + if let Err(e) = start_rebuild(Rebuild::Update, snapshot) { log(&format!("自動更新沒有成功:{e}")); } } +// ---------- 更新 from a terminal (make update-box) ---------- +// Always by the AnyBot that owns the box, with its own box files and the Docker host it is set to +// use (設定 › 電腦: this Mac's, a Lima VM, ssh://, a server's). A box built beside it from a +// checkout (what make update-box used to do) carried another version than the brain's, and the +// brain put its own back within a minute (update_available: any other version is "old"). + +fn update_request_path() -> PathBuf { + data_dir().join("update-request") +} + +fn update_answer_path() -> PathBuf { + data_dir().join("update-answer") +} + +/// The answer to `anybot --update-box`: (accepted, what to say). As the settings page's 更新: +/// refused off the brain, nothing to do when the box is this AnyBot's version already, queued +/// while a bot works. +fn update_box_now() -> (bool, String) { + let want = wanted_version(); + if !IS_BRAIN.load(Ordering::SeqCst) { + return (false, "這台 AnyBot 現在是別的大腦的螢幕:Bot 用的是大腦那台的電腦,請在大腦那台執行 make update-box(或在它的 設定 › 電腦 按「更新」)。".into()); + } + match box_version() { + None => return (true, format!("這裡還沒有 Bot 的電腦(或 Docker 沒在執行):Bot 第一次用時,會照這個 AnyBot 帶的第 {want} 版建立。")), + Some(v) if v == want => { + return (true, format!("Bot 的電腦已經是這個 AnyBot 帶的第 {want} 版,不用更新。要更新的電腦版本,先更新 AnyBot 本身(make update;伺服器 make update-server),它會自己把電腦換新。")) + } + Some(_) => {} + } + match rebuild(Rebuild::Update) { + Ok(()) => (true, format!("開始把 Bot 的電腦更新到第 {want} 版(先存快照,檔案和登入都會保留);進度在 設定 › 電腦。")), + Err(e) => (PENDING_UPDATE.load(Ordering::SeqCst), e), + } +} + +/// The running AnyBot's side: a request left by `anybot --update-box` is taken and answered. +fn answer_update_request() { + if std::fs::remove_file(update_request_path()).is_err() { + return; + } + let (ok, text) = update_box_now(); + log(&format!("命令列要求更新 Bot 的電腦:{text}")); + let _ = std::fs::write(update_answer_path(), format!("{}\n{text}", if ok { "ok" } else { "no" })); +} + +/// `anybot --update-box` (make update-box): 更新 Bot 的電腦 from a terminal. An AnyBot running on +/// this data folder is asked (it looks every 20 s) and does it as its 更新 button would; with none +/// running, it is done here and waited for. Gives the exit code. +pub fn update_box_cli() -> i32 { + match crate::lock::take(Duration::ZERO) { + Err(_) => ask_running_update(), + Ok(_folder) => update_box_here(), + } +} + +fn ask_running_update() -> i32 { + let _ = std::fs::create_dir_all(data_dir()); + let _ = std::fs::remove_file(update_answer_path()); + if let Err(e) = std::fs::write(update_request_path(), now_ms().to_string()) { + eprintln!("寫不進 AnyBot 的資料夾({e})。"); + return 1; + } + println!("AnyBot 正在執行:請它更新它的 Bot 的電腦(最多等兩分鐘)…"); + let start = Instant::now(); + while start.elapsed() < Duration::from_secs(120) { + if let Ok(a) = std::fs::read_to_string(update_answer_path()) { + let _ = std::fs::remove_file(update_answer_path()); + let (head, text) = a.split_once('\n').unwrap_or(("no", a.as_str())); + println!("{text}"); + return if head == "ok" { 0 } else { 1 }; + } + std::thread::sleep(Duration::from_millis(500)); + } + // (Left for it: one busy saving the day's snapshot takes it a little later.) + eprintln!("正在執行的 AnyBot 還沒接手:忙著(例如在存快照)的話,它一有空就會更新,進度在 設定 › 電腦;開著的是還不認得這個要求的舊版的話,到 設定 › 電腦 按「更新」。"); + 1 +} + +fn update_box_here() -> i32 { + let r = crate::model::State::load().remote; + set_brain(r.brain_id.is_empty() || r.host_token.is_empty()); + // (Docker on a Lima VM that is asleep: probe wakes it.) + let start = Instant::now(); + while matches!(probe(), Run::Starting(_)) && start.elapsed() < Duration::from_secs(120) { + std::thread::sleep(Duration::from_secs(2)); + } + if let Run::NoDocker(why) = probe() { + eprintln!("{why}"); + return 1; + } + let (ok, text) = update_box_now(); + println!("{text}"); + if !ok || !shared().lock().unwrap().rebuilding { + return if ok { 0 } else { 1 }; + } + // Here, nothing else would finish it: wait, saying each step as the settings page would. + let mut seen = shared().lock().unwrap().log.len(); + loop { + std::thread::sleep(Duration::from_millis(500)); + let (lines, rebuilding, run) = { + let s = shared().lock().unwrap(); + (s.log.iter().skip(seen).cloned().collect::>(), s.rebuilding, s.run.clone()) + }; + seen += lines.len(); + for l in lines { + println!(" {l}"); + } + if !rebuilding { + return match run { + Run::Failed(e) => { + eprintln!("沒有更新成功:{e}"); + 1 + } + _ => 0, + }; + } + } +} + /// This AnyBot shows another brain: the bots work on that brain's computer (and borrow only this /// one's screen, browser and apps), so this box — and on a Mac the Lima VM it runs in — only held /// memory: the VM grew to its whole 6 GB, which the Mac never gets back while it runs. The person @@ -1600,8 +1772,18 @@ fn now_ms() -> u64 { SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0) } -/// Start a rebuild in the background. Err = refused (already running, busy, no snapshot…). +/// Start a rebuild in the background, as the person asked for it (settings, the phone, a schedule +/// they set, `anybot --update-box`): an update starts over with a full set of automatic tries and +/// a snapshot first. Err = refused (already running, busy, no snapshot…). pub fn rebuild(kind: Rebuild) -> Result<(), String> { + if kind == Rebuild::Update { + set_update_retry(UpdateRetry::default()); + } + start_rebuild(kind, true) +} + +/// `snapshot`: an update saves the home folder first (an automatic retry keeps its first try's). +fn start_rebuild(kind: Rebuild, snapshot: bool) -> Result<(), String> { { let mut s = shared().lock().unwrap(); if s.rebuilding { @@ -1623,15 +1805,13 @@ pub fn rebuild(kind: Rebuild) -> Result<(), String> { log(&format!("{}:{d}", phase_label(p))); shared().lock().unwrap().run = Run::Rebuilding(p.into(), d.into()); }; - let r = run_rebuild(kind, &phase); + let r = run_rebuild(kind, snapshot, &phase); let _ = std::fs::remove_file(resume_path()); match r { Ok(()) => { log(&format!("{}完成。", kind.title())); PENDING_UPDATE.store(false, Ordering::SeqCst); - if let Ok(mut n) = next_try().lock() { - *n = None; - } + set_update_retry(UpdateRetry::default()); let mut s = shared().lock().unwrap(); s.rebuilding = false; s.run = Run::Running; @@ -1639,9 +1819,17 @@ pub fn rebuild(kind: Rebuild) -> Result<(), String> { } Err(e) => { log(&format!("{}失敗:{e}", kind.title())); - // An update that broke half way is worth another go when things are quiet. + // An update that broke half way is worth another go when things are quiet — a few + // times, each wait longer and counted from now. if kind == Rebuild::Update { - PENDING_UPDATE.store(true, Ordering::SeqCst); + let r = update_retry().failed(Instant::now()); + set_update_retry(r); + if r.gave_up() { + PENDING_UPDATE.store(false, Ordering::SeqCst); + log(&format!("更新連續失敗 {} 次,先不再自動重試;處理好原因後到 設定 › 電腦 按「更新」再試。", r.fails)); + } else { + PENDING_UPDATE.store(true, Ordering::SeqCst); + } } let mut s = shared().lock().unwrap(); s.rebuilding = false; @@ -1652,15 +1840,19 @@ pub fn rebuild(kind: Rebuild) -> Result<(), String> { Ok(()) } -fn run_rebuild(kind: Rebuild, phase: &dyn Fn(&str, &str)) -> Result<(), String> { +fn run_rebuild(kind: Rebuild, snapshot: bool, phase: &dyn Fn(&str, &str)) -> Result<(), String> { match kind { Rebuild::Update => { let had = matches!(probe(), Run::Running); - phase("backing-up", "儲存一份快照"); - if had { - if let Err(e) = save_snapshot() { - log(&format!("快照沒有存成功({e}),改以掛載的資料為準。")); + if snapshot { + phase("backing-up", "儲存一份快照"); + if had { + if let Err(e) = save_snapshot() { + log(&format!("快照沒有存成功({e}),改以掛載的資料為準。")); + } } + } else if had { + log("重試更新:沿用第一次存的快照。"); } let had_files = had && home_has_files(); phase("creating", "更新電腦的映像檔"); @@ -2000,7 +2192,9 @@ pub fn open_screens() -> Vec<(String, u64)> { if !run_state().is_running() { return vec![]; } - dk_timeout(&["exec", container(), "sh", "-c", "command -v anybot-screen >/dev/null && anybot-screen list"], 5_000) + // As the bot user, like every other call: run as root, a box before version 13 made the + // screens' lock file root's, and the bot user's screens all failed with ERROR=busy. + dk_timeout(&["exec", "-u", "bot", container(), "sh", "-c", "command -v anybot-screen >/dev/null && anybot-screen list"], 5_000) .map(|out| String::from_utf8_lossy(&out).lines().filter_map(|l| { let mut p = l.split_whitespace(); Some((p.next()?.to_string(), p.nth(1)?.parse().ok()?)) }).collect()) .unwrap_or_default() } @@ -2231,7 +2425,17 @@ const SETTLE_SH: &str = "{ probe() { { import -window root -crop 160x140+80+30 - /// Run a script in the box (as the bot user, on its desktop). Gives back what it printed. fn box_exec(script: &str) -> Result { - let full = format!("{} {script}", screen_sh(¤t_screen())); + box_exec_with(&screen_sh(¤t_screen()), script) +} + +/// A screen's key as the box names it ("" the shared screen): what goes into a shell line. +fn key_ok(key: &str) -> bool { + key.len() <= 48 && key.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') +} + +/// box_exec with `screen` (screen_sh or open_screen_sh) putting the script on its screen. +fn box_exec_with(screen: &str, script: &str) -> Result { + let full = format!("{screen} {script}"); // An stdin closed at once, as `docker exec -i` expects. match dk_with_input(&["exec", "-i", "-u", "bot", "-e", "DISPLAY=:1", container(), "sh", "-c", &full], Some(b""), 30_000) { Ok(o) => Ok(String::from_utf8_lossy(&o).to_string()), @@ -2371,6 +2575,17 @@ fn screen_sh(key: &str) -> String { format!("if command -v anybot-screen >/dev/null 2>&1; then o=$(anybot-screen up {key} 2>&1) || {{ printf '%s\\n' \"$o\" >&2; exit 3; }}; eval \"$o\"; export DISPLAY DBUS_SESSION_BUS_ADDRESS; else export DISPLAY=:1; fi;") } +/// Like screen_sh, but only onto a screen that is open: never makes one. For what a person does +/// on a screen they are watching — one closed meanwhile (reaped, a 支線 that ended) is not made +/// again for them (a new screen nobody sees, holding one of the six). +fn open_screen_sh(key: &str) -> String { + if key.is_empty() { + return "export DISPLAY=:1;".into(); + } + let env = format!("/tmp/anybot-screens/{key}/env"); + format!("if [ -r {env} ]; then . {env}; export DISPLAY DBUS_SESSION_BUS_ADDRESS; else echo '這個螢幕已經關了' >&2; exit 4; fi;") +} + /// Which screen each bot is on now (the brain's window sets it every few seconds: a group chat /// shows the member speaking). What viewers, thumbnails and takeovers from elsewhere — the phone, /// a screen computer, the account server — go by, since they only name the bot. @@ -2772,11 +2987,14 @@ fn box_batch(v: &Value, scale: (f64, f64)) -> Result<(String, Option), S // ---------- text a person types in a viewer ---------- -/// Text from a person's viewer (any language): typed or pasted into the window in front, like -/// the bot's typing. (Their mouse and keys go through VNC itself.) -pub fn viewer_text(text: &str) { - if !text.is_empty() { - let _ = box_exec(&type_script(text)); +/// Text from a person's viewer (any language): typed or pasted into the window in front of the +/// screen that viewer is connected to (`key`, "" the shared one), like the bot's typing — only +/// while that screen is open (open_screen_sh). (Their mouse and keys go through VNC itself.) +pub fn viewer_text(key: &str, text: &str) { + if !text.is_empty() && key_ok(key) { + on_screen(key, || { + let _ = box_exec_with(&open_screen_sh(key), &type_script(text)); + }); } touch(); } @@ -2918,14 +3136,102 @@ mod tests { /// 更新 pressed while a bot is working is not dropped: it queues and the idle loop runs it. #[test] fn an_update_asked_while_busy_is_queued() { + // (A run of failed automatic tries that gave up before: the person's 更新 starts over.) + let mut gave_up = UpdateRetry::default(); + for _ in 0..UPDATE_TRIES_MAX { + gave_up = gave_up.failed(Instant::now()); + } + set_update_retry(gave_up); let busy = Busy::new(true); assert!(is_busy()); let e = rebuild(Rebuild::Update).unwrap_err(); assert!(e.contains("已排隊") && e.contains("自動更新"), "{e}"); assert!(pending_update(), "the request must survive the busy box"); + assert_eq!(update_retry(), UpdateRetry::default(), "the person's 更新 gets a full set of tries again"); + assert_eq!(auto_update(false, true, update_retry(), Instant::now()), AutoUpdate::Go { snapshot: true }); drop(busy); } + /// A failing update is tried again when things are quiet: each wait longer and counted from + /// the failure (a rebuild takes minutes — counted from its start, the next try came at once), + /// without a new snapshot each time, and not for ever. + #[test] + fn a_failing_update_backs_off_from_the_failure_and_gives_up() { + let t0 = Instant::now(); + // Nothing asked, this version tried already: nothing to do. + assert_eq!(auto_update(false, false, UpdateRetry::default(), t0), AutoUpdate::No); + // The first try for a version, or a queued request: go, saving a snapshot first. + assert_eq!(auto_update(true, false, UpdateRetry::default(), t0), AutoUpdate::Go { snapshot: true }); + assert_eq!(auto_update(false, true, UpdateRetry::default(), t0), AutoUpdate::Go { snapshot: true }); + // A rebuild that ran five minutes and failed: 30 s from the failure, not from the start. + let failed_at = t0 + Duration::from_secs(300); + let once = UpdateRetry::default().failed(failed_at); + assert_eq!(once.not_before, Some(failed_at + Duration::from_secs(30))); + assert_eq!(auto_update(false, true, once, failed_at + Duration::from_secs(29)), AutoUpdate::NotYet); + assert_eq!(auto_update(false, true, once, failed_at + Duration::from_secs(30)), AutoUpdate::Go { snapshot: false }, "a retry keeps the first try's snapshot"); + // Longer each time: 30, 60, 90 s… + let twice = once.failed(failed_at); + assert_eq!(twice.not_before, Some(failed_at + Duration::from_secs(60))); + assert_eq!(twice.failed(failed_at).not_before, Some(failed_at + Duration::from_secs(90))); + // UPDATE_TRIES_MAX failures in a row: no more automatic tries, however long it waits. + let mut r = UpdateRetry::default(); + for i in 0..UPDATE_TRIES_MAX { + assert!(!r.gave_up(), "gave up after {i}"); + r = r.failed(t0); + } + assert!(r.gave_up()); + assert_eq!(auto_update(true, true, r, t0 + Duration::from_secs(24 * 3600)), AutoUpdate::No); + // (The count never wraps.) + assert_eq!(UpdateRetry { fails: u32::MAX, not_before: None }.failed(t0).fails, u32::MAX); + } + + /// A screen someone is watching is not idle, however the viewer was opened (the desktop's + /// 開啟電腦 is noVNC straight to the box: AnyBot never sees it): box/screen's reap asks the + /// box's own socket table for a connection to that screen's VNC port before closing it. + #[test] + fn a_watched_screen_is_not_reaped() { + let screen = BOX_FILES.iter().find(|(n, _)| *n == "screen").unwrap().1; + let start = screen.find("\nwatched() {").expect("box/screen has watched()") + 1; + let end = start + screen[start..].find("\n}\n").unwrap() + 3; + let func = &screen[start..end]; + let dir = std::env::temp_dir().join(format!("anybot-watched-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let tcp = dir.join("tcp"); + // :10's VNC (5910 = 0x1716) listening and a viewer connected to it; :11's (5911 = 0x1717) + // only listening — and a connection whose other end is 5911 (that is a client, not it). + let rows = [ + " sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode", + " 0: 0100007F:1716 00000000:0000 0A 00000000:00000000 00:00000000 00000000 1000 0 11 1", + " 1: 0100007F:1717 00000000:0000 0A 00000000:00000000 00:00000000 00000000 1000 0 12 1", + " 2: 0100007F:1716 0100007F:D2F0 01 00000000:00000000 00:00000000 00000000 1000 0 13 1", + " 3: 0100007F:D2F1 0100007F:1717 01 00000000:00000000 00:00000000 00000000 1000 0 14 1", + ]; + std::fs::write(&tcp, rows.join("\n") + "\n").unwrap(); + let watched = |disp: &str| { + Command::new("bash").arg("-c").arg(format!("{func}\nwatched \"$1\"")).arg("_").arg(disp).env("NET_TCP", &tcp).status().unwrap().success() + }; + assert!(watched("10"), "a viewer is connected to :10"); + assert!(!watched("11"), "only listening; the other connection is a client's"); + assert!(!watched("12")); + assert!(!watched("") && !watched("1x"), "no display, no answer"); + // Reap asks it before closing an idle screen, and a watched one counts as used now. + assert!(screen.contains("if watched \"$(cat \"$s/display\" 2>/dev/null)\"; then touch \"$s/last\"; continue; fi")); + // The lock is taken on a read-only open: whoever made its file, every caller can. + assert!(screen.contains("exec 8<\"$DIR/.lock\"") && !screen.contains("exec 8>")); + let _ = std::fs::remove_dir_all(&dir); + } + + /// A bot's browser on its own screen is reached through a forward on this side: the answer + /// is the local port — the box's own (9310) on this computer is nothing, or a browser of the + /// person's (a turn's tidy-up then closed the person's tabs, or never found the bot's). + #[test] + fn an_open_box_browser_is_reached_on_its_local_port() { + let forward = |p: u16| if p == 9310 { Ok(54321) } else { Err("no forward".to_string()) }; + assert_eq!(answering(9310, forward, |p| p == 54321), Some(54321)); + assert_eq!(answering(9310, forward, |p| p == 9310), None, "probed on the box's port, which isn't here"); + assert_eq!(answering(9311, forward, |_| true), None); + } + /// 復原 reads the snapshot through before it throws the home away: one cut short, empty or /// gone is refused while the computer is still whole. #[test] @@ -3549,7 +3855,7 @@ mod tests { use chrono::TimeZone; let at = chrono::Utc.with_ymd_and_hms(2026, 11, 6, 19, 0, 0).unwrap().with_timezone(&chrono_tz::Asia::Taipei); assert!(in_schedule_window("03:00", at.time())); - assert_eq!(wanted_version(), "12"); + assert_eq!(wanted_version(), "13"); // Every file the Dockerfile copies is one this app carries (build_image writes them), and // every file carried is copied. let copied: Vec<&str> = DOCKERFILE.lines().filter_map(|l| l.trim().strip_prefix("COPY ")).map(|l| l.split_whitespace().next().unwrap()).collect(); @@ -3572,6 +3878,11 @@ mod tests { assert_eq!(screen_of_dir("/home/bot"), ""); assert_eq!(screen_of_dir("/home/bot/bot-x1"), ""); assert!(screen_sh("").contains("DISPLAY=:1") && screen_sh("bot12").contains("anybot-screen up bot12")); + // What a person types in a viewer goes only onto a screen that is open: never made for it. + assert!(open_screen_sh("").contains("DISPLAY=:1")); + assert!(open_screen_sh("bot12").contains("[ -r /tmp/anybot-screens/bot12/env ]") && open_screen_sh("bot12").contains("exit 4")); + assert!(!open_screen_sh("bot12").contains("anybot-screen up")); + assert!(key_ok("") && key_ok("bot12-t3") && !key_ok("bot1;rm") && !key_ok(&"b".repeat(49))); assert!(screen_full("FULL=bot1 bot2 bot3").unwrap().contains("3 個")); assert!(screen_full("xdotool: oops").is_none()); // Each screen remembers its own numbers. diff --git a/src/main.rs b/src/main.rs index 38886f9..5c1f5f4 100644 --- a/src/main.rs +++ b/src/main.rs @@ -306,6 +306,7 @@ const USAGE: &str = "用法: anybot --ask 問題… 問第一個 Bot 一句,印出回答(測試用) anybot setup … 在沒有螢幕的機器上設定 anybot --install-skill 來源 安裝技能(GitHub 網址、owner/repo/path、SKILL.md 網址或本機資料夾) + anybot --update-box 更新 Bot 的電腦(同 設定 › 電腦 › 更新;AnyBot 開著就請它做) anybot --screenshot 檔名 把視窗畫成一張圖 anybot --banner 標題 內文 送一則通知,看它怎麼送出(Mac:AnyBot.app 自己的通知) anybot --version 印出版本(v0.0.1-36bc2be · 建置時間) @@ -318,6 +319,11 @@ fn main() -> eframe::Result<()> { println!("AnyBot {}", version::full(version::exe_modified())); return Ok(()); } + // `anybot --update-box` (make update-box): 更新 Bot 的電腦 from a terminal, by this AnyBot — + // or the one running on this data folder (cloudbox::update_box_cli). + if args.get(1).map(String::as_str) == Some("--update-box") { + std::process::exit(cloudbox::update_box_cli()); + } // P7: install a skill package (a GitHub folder/URL, SKILL.md URL, or local folder/file). if let Some(i) = args.iter().position(|a| a == "--install-skill") { let src = args.get(i + 1).cloned().unwrap_or_default(); diff --git a/src/remote.rs b/src/remote.rs index 3800927..7b675ad 100644 --- a/src/remote.rs +++ b/src/remote.rs @@ -1591,8 +1591,9 @@ fn lan_vnc(req: Req, mut c: std::net::TcpStream, gen: u64) { } Ok(Message::Text(t)) => { heard = Instant::now(); - // Words typed in the viewer go to the screen this viewer is on (每個 Bot 一個螢幕). - crate::vnc::person_typed(&t, &screen) + // Words typed in the viewer go to the screen this viewer is connected to (每個 Bot + // 一個螢幕): the shared one when the bot's wasn't open. + crate::vnc::person_typed(&t, session.screen()) } Ok(Message::Close(_)) => break, Ok(_) => heard = Instant::now(), diff --git a/src/tunnel.rs b/src/tunnel.rs index 1af6969..239b9ba 100644 --- a/src/tunnel.rs +++ b/src/tunnel.rs @@ -333,6 +333,11 @@ fn streams() -> &'static Mutex> { S.get_or_init(Default::default) } +/// The screen viewer `sid` is connected to (None when it isn't: gone, or not open yet). +fn typing_screen(sid: &str) -> Option { + streams().lock().unwrap_or_else(|e| e.into_inner()).get(sid).map(|s| s.screen().to_string()) +} + fn on_stream(kind: &str, sid: String, bot: String, body: Vec, tx: &Sender>) { let send = { let (tx, sid) = (tx.clone(), sid.clone()); @@ -376,12 +381,15 @@ fn on_stream(kind: &str, sid: String, bot: String, body: Vec, tx: &Sender { - // 每個 Bot 一個螢幕: the words go to the screen this viewer is on, not always the - // shared one (the account server passes the bot the viewer was opened for). - let screen = crate::cloudbox::screen_for_bot(&bot); - let _ = std::thread::Builder::new().spawn(move || { - crate::vnc::person_typed(&String::from_utf8_lossy(&body), &screen); - }); + // 每個 Bot 一個螢幕: the words go to the screen this viewer is connected to, as its + // session knows it (a bot's own, or the shared one when that bot had none open) — not + // the bot's screen asked again: in a group chat that follows whoever speaks, and a + // bot's screen that isn't open would be made for the words. No viewer, no typing. + if let Some(screen) = typing_screen(&sid) { + let _ = std::thread::Builder::new().spawn(move || { + crate::vnc::person_typed(&String::from_utf8_lossy(&body), &screen); + }); + } } _ => { streams().lock().unwrap().remove(&sid); @@ -543,4 +551,18 @@ mod tests { assert!(!super::maybe_zip(noise).1); assert!(super::maybe_zip(text.into_bytes()).1); } + + /// Words typed in a viewer go to the screen its session is on (the shared one when the bot's + /// wasn't open), whatever bot the account server names; a viewer that isn't there types + /// nothing (it used to make that bot's screen, unseen, for the words). + #[test] + fn typed_words_go_to_the_screen_the_viewer_is_on() { + super::streams().lock().unwrap().insert("vt-shared".into(), crate::vnc::Session::for_test("")); + super::streams().lock().unwrap().insert("vt-own".into(), crate::vnc::Session::for_test("bot7")); + assert_eq!(super::typing_screen("vt-shared").as_deref(), Some("")); + assert_eq!(super::typing_screen("vt-own").as_deref(), Some("bot7")); + assert_eq!(super::typing_screen("vt-gone"), None); + super::streams().lock().unwrap().remove("vt-shared"); + super::streams().lock().unwrap().remove("vt-own"); + } } diff --git a/src/vnc.rs b/src/vnc.rs index 7f277b7..6ad1875 100644 --- a/src/vnc.rs +++ b/src/vnc.rs @@ -23,15 +23,19 @@ use std::time::{Duration, Instant}; const HELD_AFTER_INPUT: Duration = Duration::from_secs(8); /// Joins the box's VNC server to stdin/stdout, and ends when either side does (a loop left in -/// the box would hold the connection open). +/// the box would hold the connection open). Its first line says which screen it joined: the +/// bot's asked for, or "" when that one isn't open and the shared screen is shown instead — so a +/// person's input there holds the shared screen's bots and their words are typed there. const BRIDGE: &str = r#"import os,select,socket,sys port=5900 k=sys.argv[1] if len(sys.argv)>1 else '' +on='' if k: try: for l in open('/tmp/anybot-screens/%s/env'%k): - if l.startswith('VNC_PORT='): port=int(l.split('=',1)[1]) + if l.startswith('VNC_PORT='): port=int(l.split('=',1)[1]); on=k except OSError: pass +os.write(1,(on+'\n').encode()) s=socket.create_connection(('127.0.0.1',port)) while True: r=select.select([s,0],[],[])[0] @@ -87,10 +91,31 @@ pub struct Session { sniffing: bool, /// The viewer's ClientInit (one byte) is still to come. init: bool, - /// The screen this viewer watches ("" is the shared one): input pauses that screen's bot only. + /// The screen this viewer is connected to ("" is the shared one) — as the box joined it, not + /// as asked: input pauses that screen's bot only, and words typed go there. screen: String, } +fn screen_key(key: &str) -> String { + key.chars().filter(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '-').take(48).collect() +} + +/// BRIDGE's first line: the screen it joined ("" the shared one). +fn joined_screen(r: &mut impl Read) -> Result { + let mut line = Vec::new(); + let mut b = [0u8; 1]; + loop { + r.read_exact(&mut b).map_err(|_| "畫面伺服器沒有回應".to_string())?; + if b[0] == b'\n' { + return Ok(screen_key(&String::from_utf8_lossy(&line))); + } + line.push(b[0]); + if line.len() > 64 { + return Err("畫面伺服器的回應看不懂".into()); + } + } +} + /// Open a viewer's way to `key`'s screen on the box (a bot's own, 每個 Bot 一個螢幕; "" or one not /// open: the shared one): sign in to its VNC server, and start sending what the server says to /// `out` (from a thread of its own; `out` returns false when the viewer is gone, and gets an empty @@ -98,8 +123,7 @@ pub struct Session { /// for the viewer's answer). pub fn open_on(key: &str, out: impl Fn(&[u8]) -> bool + Send + 'static) -> Result { crate::cloudbox::ensure_running()?; - let key: String = key.chars().filter(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '-').take(48).collect(); - let mut child = crate::cloudbox::exec_piped(&["python3", "-c", BRIDGE, &key])?; + let mut child = crate::cloudbox::exec_piped(&["python3", "-c", BRIDGE, &screen_key(key)])?; let mut stdin = child.stdin.take().ok_or("連不上這台電腦的畫面")?; let mut stdout = child.stdout.take().ok_or("連不上這台電腦的畫面")?; let fail = |child: &mut Child, why: &str| -> String { @@ -107,6 +131,11 @@ pub fn open_on(key: &str, out: impl Fn(&[u8]) -> bool + Send + 'static) -> Resul let _ = child.wait(); format!("連不上這台電腦的畫面:{why}") }; + // The screen really shown: a bot's that isn't open is the shared one. + let key = match joined_screen(&mut stdout) { + Ok(k) => k, + Err(e) => return Err(fail(&mut child, &e)), + }; let mut read = |n: usize| -> Result, String> { let mut b = vec![0u8; n]; stdout.read_exact(&mut b).map(|_| b).map_err(|_| "畫面伺服器沒有回應".to_string()) @@ -144,9 +173,10 @@ pub fn open_on(key: &str, out: impl Fn(&[u8]) -> bool + Send + 'static) -> Resul crate::cloudbox::set_viewer_open(true); // A person watching a bot's screen keeps it from being reaped as idle: touch its stamp now // and while the viewer lives (a still screen sends no frames, so the read loop below sleeps). + // (A box from version 13 also sees any viewer's connection itself: box/screen's reap.) crate::cloudbox::touch_screen(&key); let alive = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true)); - { + if !key.is_empty() { let (alive, k) = (alive.clone(), key.clone()); std::thread::spawn(move || { while alive.load(Ordering::SeqCst) { @@ -186,6 +216,21 @@ pub fn open_on(key: &str, out: impl Fn(&[u8]) -> bool + Send + 'static) -> Resul } impl Session { + /// The screen this viewer is connected to ("" the shared one): where its typed words go. + pub fn screen(&self) -> &str { + &self.screen + } + + /// A session on `screen` with nothing behind it (for the tests of the code that keeps them). + #[cfg(test)] + pub fn for_test(screen: &str) -> Session { + let child = std::process::Command::new("sleep").arg("30").spawn().expect("sleep"); + let (writer, _) = std::sync::mpsc::sync_channel(1); + // (Its Drop counts it out.) + OPEN.fetch_add(1, Ordering::SeqCst); + Session { child, writer, greeting: 13, pending: Vec::new(), sniffing: true, init: true, screen: screen_key(screen) } + } + /// Bytes from the viewer. False when the box's side is gone. pub fn feed(&mut self, mut b: &[u8], reply: impl Fn(&[u8]) -> bool) -> bool { if self.greeting > 0 { @@ -323,11 +368,12 @@ pub fn person_active(key: &str) -> bool { } /// Text the person typed in the viewer's own box (any language): pasted into the box, on the -/// screen that viewer watches — not always the shared one (每個 Bot 一個螢幕). +/// screen that viewer is connected to (`key`: its Session's screen) — not always the shared one +/// (每個 Bot 一個螢幕), and never onto a screen made for it (one closed meanwhile gets nothing). pub fn person_typed(text: &str, key: &str) { if !text.is_empty() { person_acted(key); - crate::cloudbox::on_screen(key, || crate::cloudbox::viewer_text(text)); + crate::cloudbox::viewer_text(key, text); } } @@ -383,6 +429,27 @@ mod tests { assert!(!person_active("bot13"), "another bot's screen is free"); } + /// A viewer asked for a bot's screen that isn't open is shown the shared one: the session is + /// on the screen the box joined, so the person's input holds the shared screen's bots and + /// their typed words go there — not onto a new screen of that bot nobody sees. + #[test] + fn a_viewer_is_on_the_screen_the_box_joined() { + use std::io::Cursor; + let mut r = Cursor::new(b"bot12\nRFB 003.008\n".to_vec()); + assert_eq!(joined_screen(&mut r).unwrap(), "bot12"); + let mut rest = [0u8; 12]; + r.read_exact(&mut rest).unwrap(); + assert_eq!(&rest, b"RFB 003.008\n", "the VNC greeting is left whole"); + assert_eq!(joined_screen(&mut Cursor::new(b"\nRFB 003.008\n".to_vec())).unwrap(), "", "not open: the shared screen"); + assert!(joined_screen(&mut Cursor::new(vec![b'x'; 100])).is_err()); + assert!(joined_screen(&mut Cursor::new(Vec::new())).is_err()); + assert_eq!(joined_screen(&mut Cursor::new(b"bot1; rm -rf /\n".to_vec())).unwrap(), "bot1rm-rf"); + // The bridge says it first, and names a bot's screen only when it found it open. + let said = BRIDGE.find("os.write(1,(on+'\\n').encode())").expect("the bridge names its screen"); + assert!(said < BRIDGE.find("create_connection").unwrap() && BRIDGE.contains("port=int(l.split('=',1)[1]); on=k")); + assert_eq!(Session::for_test("bot12").screen(), "bot12"); + } + #[test] fn vnc_password_answer_matches_the_standard() { // Password "password", challenge 00..0f: DES-ECB with the bit-reversed key 0e86ceceeef64e26