From dd6fd5aec7f63fae8a9d85eaa415d405fca63d2e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=80=A7=E9=A9=8A?= Date: Sun, 15 Nov 2026 16:12:09 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=AF=8F=E5=80=8B=20Bot=20=E4=B8=80?= =?UTF-8?q?=E5=80=8B=E8=9E=A2=E5=B9=95=E2=80=94=E2=80=94Bot=20=E7=9A=84?= =?UTF-8?q?=E9=9B=BB=E8=85=A6=E4=B8=8A=E5=90=84=E6=9C=89=E8=87=AA=E5=B7=B1?= =?UTF-8?q?=E7=9A=84=E8=9E=A2=E5=B9=95=E5=92=8C=E7=80=8F=E8=A6=BD=E5=99=A8?= =?UTF-8?q?=EF=BC=8C=E6=94=AF=E7=B7=9A=E5=8F=A6=E9=96=8B=E6=9A=AB=E6=99=82?= =?UTF-8?q?=E7=9A=84=E8=9E=A2=E5=B9=95=EF=BC=8C=E5=8F=B3=E5=81=B4=E9=9D=A2?= =?UTF-8?q?=E6=9D=BF=E5=92=8C=E3=80=8C=E5=85=A8=E9=83=A8=E8=9E=A2=E5=B9=95?= =?UTF-8?q?=E3=80=8D=E7=9C=8B=E5=BE=97=E5=88=B0=E6=AF=8F=E4=B8=80=E5=80=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 照 Grok Bot 的分法:一台電腦、每個 Bot 一個螢幕,大家同時做互不干擾。使用者自己的電腦只有一個實體螢幕,還是一次一個 Bot。 - box:anybot-screen(up/down/list/reap)開關每個 Bot 的螢幕,同時最多 6 個,閒置 10 分鐘關掉;browser 每個螢幕自己的設定檔(第一次從共用的複製登入;支線 -t 從主線那份複製,關掉時刪掉);start.sh 給每個螢幕 VNC token;Bot 電腦升到版本 10 - cloudbox:每個螢幕有自己的狀態(編號、尺寸、貼上檔、瀏覽器埠),指令開的視窗出現在它的 Bot 的螢幕上;branch_screen、close_screen、open_screens、thumbnail_of - agent:在 Bot 的電腦上,一輪用它自己的螢幕(支線用暫時的),佔用照螢幕算 - 支線結束時關掉它的暫時螢幕 - 畫面:右側「電腦」顯示目前 Bot 的螢幕;群組跟著正在回答的成員,「成員」卡片點小畫面就固定顯示那個成員;「全部螢幕(N)」一格一個螢幕;接管時只停那個 Bot;手機和中繼帶上要看哪個 Bot 的螢幕 - 群組和支線的系統指示:看不到彼此開著的網頁,交棒時寫網址或檔案路徑 - 功能地圖:screen、team、computers、browser Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Uirha4mzWbjJAWAsDVuBun --- box/Dockerfile | 5 +- box/browser | 42 ++- box/screen | 147 ++++++++++ box/start.sh | 8 +- docs/feature-map/browser.md | 1 + docs/feature-map/computers.md | 2 +- docs/feature-map/screen.md | 8 +- docs/feature-map/team.md | 5 +- mobile/index.html | 2 +- mobile/screen.html | 4 +- relay/src/main.rs | 4 +- src/agent.rs | 71 ++++- src/app.rs | 9 +- src/app/branch.rs | 13 +- src/app/computers_ui.rs | 48 +++- src/app/mirror_ui.rs | 2 +- src/app/panel_ui.rs | 41 ++- src/app/screens_ui.rs | 279 +++++++++++++++++++ src/cloudbox.rs | 510 ++++++++++++++++++++++++++++------ src/remote.rs | 13 +- src/tunnel.rs | 9 +- src/vnc.rs | 25 +- 22 files changed, 1115 insertions(+), 133 deletions(-) create mode 100755 box/screen create mode 100644 src/app/screens_ui.rs diff --git a/box/Dockerfile b/box/Dockerfile index 3ba7703..ed78ed3 100644 --- a/box/Dockerfile +++ b/box/Dockerfile @@ -18,11 +18,12 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ COPY start.sh /usr/local/bin/anybot-box-start COPY a11y /usr/local/bin/anybot-a11y COPY browser /usr/local/bin/anybot-browser +COPY screen /usr/local/bin/anybot-screen COPY fluxbox-init /etc/anybot/fluxbox-init COPY overlay /etc/anybot/overlay COPY Xresources /etc/anybot/Xresources COPY menu /etc/anybot/menu -RUN chmod +x /usr/local/bin/anybot-box-start /usr/local/bin/anybot-a11y /usr/local/bin/anybot-browser \ +RUN chmod +x /usr/local/bin/anybot-box-start /usr/local/bin/anybot-a11y /usr/local/bin/anybot-browser /usr/local/bin/anybot-screen \ # Chromium has no sandbox inside a plain container (no user namespaces); the box itself is # the sandbox. Under gVisor (容器隔離=runsc) the box has its own virtualized kernel and # Chromium's sandbox works: AnyBot then starts the box with ANYBOT_BOX_SANDBOX=1 and the @@ -39,6 +40,6 @@ RUN chmod +x /usr/local/bin/anybot-box-start /usr/local/bin/anybot-a11y /usr/loc # without it — no numbers at all, only a picture to guess at. GTK 3 apps ignore it. ENV DISPLAY=:1 SCREEN_SIZE=1280x800x24 GTK_MODULES=gail:atk-bridge GTK_A11Y=atspi GNOME_ACCESSIBILITY=1 NO_AT_BRIDGE=0 EXPOSE 6080 -LABEL anybot.box.version="9" +LABEL anybot.box.version="10" ENTRYPOINT ["/usr/bin/tini", "--"] CMD ["/usr/local/bin/anybot-box-start"] diff --git a/box/browser b/box/browser index 117c179..245514d 100644 --- a/box/browser +++ b/box/browser @@ -16,7 +16,39 @@ fi # browser tools opened), so a site could be logged in in one and not the other. Chromium's own # is the one now (the other stays as it was); a box that only has AnyBot's keeps that. PROFILE=/home/bot/.config/anybot-profile -if [[ ! -e "$PROFILE" ]]; then +PORT=9222 +LOCK=/tmp/.anybot-browser.lock +LOG=/tmp/anybot-browser.log +# 每個 Bot 一個螢幕 (anybot-screen): ANYBOT_SCREEN= starts that bot's own browser on its own +# screen, with a profile of its own and its own DevTools port. The first time, the profile starts +# as a copy of the shared one, so the sites logged in there are logged in here too (the box keeps +# its cookies with --password-store=basic, readable by any profile of the same user). A 支線's +# temporary screen copies its main bot's instead (the logins that bot has now). +if [[ -n "${ANYBOT_SCREEN:-}" ]]; then + [[ "$ANYBOT_SCREEN" =~ ^[A-Za-z0-9_-]{1,48}$ ]] || { echo "bad screen" >&2; exit 2; } + ENV=/tmp/anybot-screens/$ANYBOT_SCREEN/env + [[ -r "$ENV" ]] || { echo "no screen $ANYBOT_SCREEN: anybot-screen up first" >&2; exit 2; } + # shellcheck disable=SC1090 + set -a; source "$ENV"; set +a + PORT=$CDP_PORT + LOCK=/tmp/.anybot-browser-$ANYBOT_SCREEN.lock + LOG=/tmp/anybot-browser-$ANYBOT_SCREEN.log + if [[ ! -d "$PROFILE/Default" ]]; then + SHARED=$(readlink -f /home/bot/.config/anybot-profile 2>/dev/null || true) + # A 支線's temporary screen (-t) starts from its main bot's browser when it has one. + if [[ "$ANYBOT_SCREEN" =~ ^(.+)-t[0-9]+$ && -d "/home/bot/.config/anybot-profiles/${BASH_REMATCH[1]}/Default" ]]; then + SHARED=/home/bot/.config/anybot-profiles/${BASH_REMATCH[1]} + fi + mkdir -p "$PROFILE/Default" + if [[ -n "$SHARED" && -d "$SHARED/Default" ]]; then + cp -a "$SHARED/Local State" "$PROFILE/" 2>/dev/null || true + for f in Cookies Cookies-journal "Login Data" "Login Data-journal" "Web Data" "Web Data-journal" Preferences "Secure Preferences" "Local Storage" "Session Storage" IndexedDB; do + [[ -e "$SHARED/Default/$f" ]] && cp -a "$SHARED/Default/$f" "$PROFILE/Default/" 2>/dev/null || true + done + fi + fi +fi +if [[ -z "${ANYBOT_SCREEN:-}" && ! -e "$PROFILE" ]]; then if [[ -d /home/bot/.config/chromium/Default || ! -d /home/bot/.config/anybot-browser/Default ]]; then mkdir -p /home/bot/.config/chromium && ln -s /home/bot/.config/chromium "$PROFILE" else @@ -28,14 +60,14 @@ fi # ANYBOT_BOX_SANDBOX=1 — Chromium's own sandbox works there, so keep it as a second wall. SANDBOX=(--no-sandbox --test-type) [ "${ANYBOT_BOX_SANDBOX:-0}" = 1 ] && SANDBOX=() -FLAGS=("${SANDBOX[@]}" --user-data-dir="$PROFILE" --remote-debugging-address=127.0.0.1 --remote-debugging-port=9222 +FLAGS=("${SANDBOX[@]}" --user-data-dir="$PROFILE" --remote-debugging-address=127.0.0.1 --remote-debugging-port=$PORT --remote-allow-origins=http://127.0.0.1 --force-renderer-accessibility --disable-blink-features=AutomationControlled --disable-dev-shm-usage --disable-gpu --use-angle=swiftshader --enable-unsafe-swiftshader --password-store=basic --no-first-run --no-default-browser-check --disable-session-crashed-bubble --hide-crash-restore-bubble --disable-features=TranslateUI --start-maximized) # Two starts in the same second (the bot and the person) would both find no browser and fight # over the profile ("in use"): one at a time until the first is listening. -exec 9>/tmp/.anybot-browser.lock +exec 9>"$LOCK" flock -w 30 9 || true if pgrep -u bot -f -- "--user-data-dir=$PROFILE" >/dev/null || pgrep -u bot -f -- "--user-data-dir=$(readlink -f "$PROFILE")" >/dev/null; then flock -u 9 @@ -45,8 +77,8 @@ fi rm -f "$PROFILE"/SingletonLock "$PROFILE"/SingletonSocket "$PROFILE"/SingletonCookie # (The lock's fd is not handed to the browser: it would hold the lock for its whole life, and the # next start would wait on it.) -setsid chromium "${FLAGS[@]}" "${@:-about:blank}" >/tmp/anybot-browser.log 2>&1 < /dev/null 9>&- & +setsid chromium "${FLAGS[@]}" "${@:-about:blank}" >"$LOG" 2>&1 < /dev/null 9>&- & for _ in $(seq 1 100); do - python3 -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:9222/json/version', timeout=1).close()" 2>/dev/null && break + python3 -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:$PORT/json/version', timeout=1).close()" 2>/dev/null && break sleep 0.25 done diff --git a/box/screen b/box/screen new file mode 100755 index 0000000..c146f3f --- /dev/null +++ b/box/screen @@ -0,0 +1,147 @@ +#!/bin/bash +# 每個 Bot 一個螢幕 (Grok Bot's split: one computer per account, a screen of its own per bot, so +# bots use the desktop and the browser side by side instead of waiting for each other on :1). +# The box's own screen :1 stays as it is (the person's shared desktop). +# +# anybot-screen up the screen of (a bot), made when it isn't there; prints +# KEY=VALUE lines: DISPLAY, DBUS_SESSION_BUS_ADDRESS, VNC_PORT, CDP_PORT, +# PROFILE. Using it marks it used (see reap). +# anybot-screen down close it (its browser too); the browser profile stays on disk +# anybot-screen list one line per open screen: key display seconds-since-used +# anybot-screen reap close the screens nobody used for that long +# +# Exit 3 when ANYBOT_MAX_SCREENS screens are open already: the keys holding them are printed. +# (What it starts in the background never keeps the lock: each gets 8>&-.) +# Runs as the bot user (how AnyBot calls it) or as root (the desktop is the bot user's either way). +# Each open screen is in /tmp/anybot-vnc-tokens, so the box's one web viewer (port 6080) shows any +# of them: ?path=websockify%3Ftoken%3D ("main" is the shared screen). +# -t is a temporary screen (a 支線's, beside its main bot ): its browser starts as a +# copy of 's (box/browser), and that copy is removed with the screen. +set -u +DIR=/tmp/anybot-screens +MAX=${ANYBOT_MAX_SCREENS:-6} +# Displays :10, :11, … — VNC on 5900+n and the browser's DevTools on 9300+n, both on 127.0.0.1. +FIRST=10 +mkdir -p "$DIR" 2>/dev/null; chmod 1777 "$DIR" 2>/dev/null + +TOKENS=/tmp/anybot-vnc-tokens + +key_ok() { [[ "$1" =~ ^[A-Za-z0-9_-]{1,48}$ ]]; } +# The bot user's side of the desktop (fluxbox, the buses): as is when we are the bot user. +as_bot() { if [ "$(id -u)" = 0 ]; then su bot -c "$1"; else sh -c "$1"; fi; } +token_set() { { grep -v "^$1: " "$TOKENS" 2>/dev/null; [ -n "${2:-}" ] && echo "$1: localhost:$2"; } > "$TOKENS.new"; mv -f "$TOKENS.new" "$TOKENS"; } +alive() { [ -n "${1:-}" ] && kill -0 "$1" 2>/dev/null; } + +# The screen's processes (Xtigervnc, its dbus, fluxbox, the accessibility bus, the browser), killed +# youngest first. +close() { + local d=$DIR/$1 + [ -d "$d" ] || return 0 + local disp; disp=$(cat "$d/display" 2>/dev/null) + if [ -n "$disp" ]; then + # (The browser gets a moment to write its profile before it is killed.) + local prof="--user-data-dir=/home/bot/.config/anybot-profiles/$1( |\$)" + if pkill -u bot -f -- "$prof" 2>/dev/null; then + for _ in $(seq 1 20); do pgrep -u bot -f -- "$prof" >/dev/null || break; sleep 0.1; done + pkill -9 -u bot -f -- "$prof" 2>/dev/null + fi + for p in $(cat "$d/pids" 2>/dev/null | tac); do kill "$p" 2>/dev/null; done + sleep 0.3 + for p in $(cat "$d/pids" 2>/dev/null); do kill -9 "$p" 2>/dev/null; done + rm -f "/tmp/.X$disp-lock" "/tmp/.X11-unix/X$disp" + fi + token_set "$1" + rm -rf "$d" + [[ "$1" =~ -t[0-9]+$ ]] && rm -rf "/home/bot/.config/anybot-profiles/$1" + return 0 +} + +print_env() { + local d=$DIR/$1 + touch "$d/last" + cat "$d/env" +} + +up() { + local key=$1 d=$DIR/$1 + # Already there and its X server alive: just say where. + if [ -f "$d/env" ] && alive "$(head -1 "$d/pids" 2>/dev/null)"; then + print_env "$key" + return 0 + fi + close "$key" + local open=() n disp="" + for s in "$DIR"/*/; do [ -f "$s/env" ] && open+=("$(basename "$s")"); done + if [ "${#open[@]}" -ge "$MAX" ]; then + printf 'FULL=%s\n' "${open[*]}" + exit 3 + fi + for ((n = FIRST; n < FIRST + 64; n++)); do + [ -e "/tmp/.X$n-lock" ] || [ -e "/tmp/.X11-unix/X$n" ] || grep -qx "$n" "$DIR"/*/display 2>/dev/null || { disp=$n; break; } + done + [ -n "$disp" ] || { echo "ERROR=no free display" ; exit 1; } + mkdir -p "$d" + echo "$disp" > "$d/display" + local geom="${SCREEN_SIZE:-1440x900x24}"; geom="${geom%x*}" + local sec="-SecurityTypes None" + [ -r /home/bot/.vnc/passwd ] && sec="-SecurityTypes VncAuth -rfbauth /home/bot/.vnc/passwd" + # shellcheck disable=SC2086 + Xtigervnc ":$disp" -geometry "$geom" -depth 24 -rfbport $((5900 + disp)) -localhost $sec -AlwaysShared -AcceptCutText -SendCutText \ + -UseBlacklist 0 -IdleTimeout 0 -MaxIdleTime 0 -MaxDisconnectionTime 0 -MaxConnectionTime 0 -s 0 -dpms -desktop "Bot 的電腦 · $key" -ac -noreset \ + >"$d/xvnc.log" 2>&1 8>&- & + echo $! > "$d/pids" + for _ in $(seq 1 50); do xdpyinfo -display ":$disp" >/dev/null 2>&1 && break; sleep 0.1; done + xdpyinfo -display ":$disp" >/dev/null 2>&1 || { echo "ERROR=the screen did not start"; close "$key"; exit 1; } + # A session bus and an accessibility registry of its own: the controls listed for this screen + # are this screen's apps only. + local out bus buspid + out=$(as_bot 'cd /home/bot && dbus-launch --sh-syntax' 8>&-) + bus=$(printf '%s\n' "$out" | sed -n "s/^DBUS_SESSION_BUS_ADDRESS='\(.*\)';\$/\1/p") + buspid=$(printf '%s\n' "$out" | sed -n 's/^DBUS_SESSION_BUS_PID=\([0-9]*\);$/\1/p') + [ -n "$buspid" ] && echo "$buspid" >> "$d/pids" + for c in /usr/libexec/at-spi-bus-launcher /usr/lib/at-spi2-core/at-spi-bus-launcher; do + [ -x "$c" ] && { as_bot "DISPLAY=:$disp DBUS_SESSION_BUS_ADDRESS=$bus setsid $c --launch-immediately >/dev/null 2>&1 & echo \$!" 8>&- >> "$d/pids"; break; } + done + for c in /usr/libexec/at-spi2-registryd /usr/lib/at-spi2-core/at-spi2-registryd; do + [ -x "$c" ] && { as_bot "DISPLAY=:$disp DBUS_SESSION_BUS_ADDRESS=$bus setsid $c >/dev/null 2>&1 & echo \$!" 8>&- >> "$d/pids"; break; } + done + as_bot "DISPLAY=:$disp xrdb -nocpp -merge /home/bot/.Xresources" 2>/dev/null + as_bot "DISPLAY=:$disp DBUS_SESSION_BUS_ADDRESS=$bus setsid fluxbox >/dev/null 2>&1 & echo \$!" 8>&- >> "$d/pids" + xsetroot -display ":$disp" -solid '#2b2f36' + { + echo "DISPLAY=:$disp" + echo "DBUS_SESSION_BUS_ADDRESS=$bus" + echo "VNC_PORT=$((5900 + disp))" + echo "CDP_PORT=$((9300 + disp))" + echo "PROFILE=/home/bot/.config/anybot-profiles/$key" + } > "$d/env" + chmod 644 "$d/env" "$d/display" + token_set "$key" $((5900 + disp)) + print_env "$key" +} + +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 + done +} + +cmd=${1:-}; arg=${2:-} +exec 8>"$DIR/.lock" +flock -w 20 8 || { echo "ERROR=busy"; exit 1; } +case "$cmd" in + up) key_ok "$arg" || { echo "ERROR=bad key"; exit 2; }; up "$arg" ;; + down) key_ok "$arg" || { echo "ERROR=bad key"; exit 2; }; close "$arg" ;; + list) + now=$(date +%s) + for s in "$DIR"/*/; do + [ -f "$s/env" ] || continue + echo "$(basename "$s") :$(cat "$s/display") $((now - $(stat -c %Y "$s/last" 2>/dev/null || echo "$now")))" + done ;; + reap) [[ "$arg" =~ ^[0-9]+$ ]] || { echo "ERROR=seconds"; exit 2; }; reap "$arg" ;; + *) sed -n '2,15p' "$0"; exit 2 ;; +esac diff --git a/box/start.sh b/box/start.sh index 1fdad23..7b6ab78 100644 --- a/box/start.sh +++ b/box/start.sh @@ -14,6 +14,8 @@ GEOM="${SCREEN_SIZE%x*}" if [ -n "${VNC_PASSWORD:-}" ]; then mkdir -p /home/bot/.vnc printf '%s\n' "$VNC_PASSWORD" | vncpasswd -f > /home/bot/.vnc/passwd && chmod 600 /home/bot/.vnc/passwd + # (The bot user opens the bots' own screens with the same password: anybot-screen.) + chown bot:bot /home/bot/.vnc /home/bot/.vnc/passwd VNC_SEC="-SecurityTypes VncAuth -rfbauth /home/bot/.vnc/passwd" else VNC_SEC="-SecurityTypes None" @@ -41,7 +43,11 @@ su bot -c "DISPLAY=:1 DBUS_SESSION_BUS_ADDRESS=$DBUS_SESSION_BUS_ADDRESS xrdb -n su bot -c "DISPLAY=:1 DBUS_SESSION_BUS_ADDRESS=$DBUS_SESSION_BUS_ADDRESS fluxbox >/tmp/fluxbox.log 2>&1 &" (sleep 1.5; xsetroot -display :1 -solid '#2b2f36') & xsetroot -display :1 -solid '#2b2f36' -websockify --web /usr/share/novnc 6080 localhost:5900 >/tmp/novnc.log 2>&1 & +# One web viewer for every screen: the shared one is "main"; anybot-screen adds each bot's own +# (每個 Bot 一個螢幕). A viewer picks one with ?path=websockify%3Ftoken%3D. +rm -rf /tmp/anybot-screens; mkdir -p /tmp/anybot-screens && chmod 1777 /tmp/anybot-screens +echo "main: localhost:5900" > /tmp/anybot-vnc-tokens && chown bot:bot /tmp/anybot-vnc-tokens +websockify --web /usr/share/novnc --token-plugin TokenFile --token-source /tmp/anybot-vnc-tokens 6080 >/tmp/novnc.log 2>&1 & WEBSOCKIFY_PID=$! # Say ready only once the viewer's port listens: the app opens noVNC on this flag, and a too # early file meant the first viewer load 404'd. diff --git a/docs/feature-map/browser.md b/docs/feature-map/browser.md index 31bfe92..36bc8c7 100644 --- a/docs/feature-map/browser.md +++ b/docs/feature-map/browser.md @@ -11,6 +11,7 @@ Bot 用 AnyBot 自己的瀏覽器上網、登入網站、點按、打字、送 - 打字:`type` 的換行會整段放進去(像貼上),結果會說欄位現在裝了什麼。 - 間隔:`wait` 加 `after_send: true`,從上一次送出起算(最多 900 秒),下一則可以先打好再等。 - 發布關卡(Bot 自己的瀏覽器送出時):送出前讀頁面,看是哪個帳號、回哪一篇;同一帳號回過同一篇就擋下(已送帳本,記 60 天);發布前檢查請另一個模型看過文字;送出後重讀頁面,確認文字出現、抓留言網址,結果寫「【系統】已送出…」。 +- Bot 自己的電腦上:每個 Bot 在自己的螢幕上有自己的瀏覽器;第一次開時從共用的那份複製登入過來,之後各自登入、互不影響。支線的瀏覽器從主線那份複製,支線結束就刪掉。 - 做完就關掉瀏覽器:一輪結束就把它用過的視窗關掉(別的 Bot 還在用的不關)。 ## 使用者怎麼到 diff --git a/docs/feature-map/computers.md b/docs/feature-map/computers.md index 2141a63..388fe79 100644 --- a/docs/feature-map/computers.md +++ b/docs/feature-map/computers.md @@ -5,7 +5,7 @@ ## 子功能 - 四種電腦,每台都用自己的名字稱呼: - - Bot 自己的電腦(「 的電腦」):一台 Linux(Debian,有桌面和 Chromium,可以 sudo 裝套件),跑在 Docker 裡,所有 Bot 共用、各有自己的資料夾,一直開著。沒有 Docker 時退回成一個封閉的資料夾,沒有桌面。 + - Bot 自己的電腦(「 的電腦」):一台 Linux(Debian,有桌面和 Chromium,可以 sudo 裝套件),跑在 Docker 裡,所有 Bot 共用一台,各有自己的資料夾、自己的螢幕和自己的瀏覽器(見 [screen](screen.md)),一直開著。沒有 Docker 時退回成一個封閉的資料夾,沒有桌面。 - 這台電腦(AnyBot 開著的這台,名字可以改):從 Bot 的「起始資料夾」開始。大腦放在伺服器上時,伺服器本身不在清單裡。 - SSH 電腦:自己加的,一個名稱加一個位址(例如 me@studio.local)。 - 帳號裡的其他電腦:登入同一個帳號、打開「讓帳號裡的其他電腦使用這台」、而且現在在線上的 AnyBot(螢幕電腦、手腳電腦),經過帳號伺服器操作檔案、指令、瀏覽器、看畫面和點擊。 diff --git a/docs/feature-map/screen.md b/docs/feature-map/screen.md index d90b126..257e62d 100644 --- a/docs/feature-map/screen.md +++ b/docs/feature-map/screen.md @@ -11,7 +11,8 @@ Bot 用一個 `computer` 工具看一台電腦的螢幕、動滑鼠和鍵盤: - `intent`:系統捷徑(音量、Wi-Fi、鎖螢幕、深淺色、清空垃圾桶,Mac 還有退出磁碟)一步做完。電腦現況列了「系統捷徑」才有:macOS 和 Linux 桌面有,Windows 和 Bot 自己的電腦沒有。 - 交給使用者:`hand_over_computer` 在聊天放一張「需要處理」卡和那台電腦的畫面,使用者做完按「我完成了」或「跳過」。 - 示範教學(macOS、Linux X11):使用者自己做一次,AnyBot 記成步驟和每一步的畫面;Bot 用 `view_demo_step` 看某一步當時的畫面。 -- 同一個螢幕一次只給一個 Bot 操作;別人在用時會被擋下,對方停手 120 秒後輪到。只看畫面不受影響。 +- Bot 自己的電腦:每個 Bot 有自己的螢幕(照 Grok Bot 的分法:一台電腦、每個 Bot 一個螢幕),Bot 第一次看畫面或用瀏覽器時才開,大家同時做互不干擾。支線另開一個暫時的螢幕(瀏覽器從主線那份複製),支線結束就關掉、複製的那份也刪掉。同時最多開 6 個,閒置 10 分鐘的會自己關掉(瀏覽器的登入留著)。原本那個共用的桌面還在。 +- 使用者自己的電腦只有一個實體螢幕:一次只給一個 Bot 操作,別人在用時會被擋下,對方停手 120 秒後輪到。只看畫面不受影響。 - 截圖上的卡號和驗證碼會先塗黑,才交給模型。 ## 使用者怎麼到 @@ -20,7 +21,9 @@ Bot 用一個 `computer` 工具看一台電腦的螢幕、動滑鼠和鍵盤: - 同一處的「一律允許的應用程式」(有授權才出現):每個 Bot 不用問就能操作的 App,可以逐一移除;「整個螢幕(看不出是哪個 App 時)」就是 `computer:control`。 - Bot 在這台電腦上動滑鼠鍵盤時,螢幕上方有「{Bot} 正在操作你的電腦」:按「取得控制權」Bot 先停手(變成「你正在操作,Bot 已暫停」,按「交還給 Bot」還它);按「停止」停掉那一輪。 - 設定 ›「電腦」›「示範教學」:替目前選的 Bot 輸入任務名稱,按「開始錄製」,照平常做,做完按上方「{Bot} 正在觀看並學習」的「完成」。之後跟 Bot 說「照示範做 名稱」。每個示範可以「播放錄影」、展開「步驟」看每一步的「畫面」、「刪除」。 -- 「需要處理」卡:Bot 自己的電腦可以在卡上按「接管」直接做;其他電腦要到那台去做。手機上也有同一張卡。 +- 「需要處理」卡:Bot 自己的電腦可以在卡上按「接管」直接做,打開的是那個 Bot 自己的螢幕,接管時只有它停手,別的 Bot 照做;其他電腦要到那台去做。手機上也有同一張卡。 +- 右側面板的「電腦」畫面和「開啟電腦」:顯示目前選的 Bot 自己的螢幕(還沒開過就顯示共用的桌面);群組聊天顯示正在回答的成員的螢幕,「成員」卡片上點某個成員的小畫面就改顯示它的(再點一次回到跟著回答的人)。 +- 「電腦」卡片下的「全部螢幕(N)」(有 Bot 開著自己的螢幕才出現):每個螢幕一格小畫面,寫是誰的、閒置多久;點一格打開那個螢幕看或接手。 - Bot 設定 ›「能力」›「看螢幕與操作」沒開,Bot 就沒有 `computer`。 ## 怎麼操作 @@ -36,6 +39,7 @@ Bot 用一個 `computer` 工具看一台電腦的螢幕、動滑鼠和鍵盤: - 按鍵和沒指定欄位的 `typing` 只送到上次截圖時在最前面的 App;中途換了 App 會「沒有按」:先截圖或 `open_app`。 - 結果說「畫面和上一步完全一樣」就是沒點到:換編號或換方法,不要重複同一步。 - Linux 上開著 IBus 輸入法(注音、拼音)時,`typing` 可能回「已打字(N 個字)」但字沒進去:N 是送出的字數,不是欄位裡的內容。一定看截圖確認;長字或中文改用剪貼簿貼上比較可靠。(Mac 會先直接寫進欄位或用貼上;Bot 自己的電腦中文和長字會自動貼上。) +- 「全部螢幕」和成員的小畫面每 3 秒更新一次,不是即時畫面;要看即時的點進去。 - `batch` 裡不能 `open_app`,也不能用 cmd+tab 這類切換 App 的鍵。 - 塗黑的卡號、驗證碼 Bot 讀不到:要碼的步驟用 `hand_over_computer`。 - Mac 沒開「螢幕與系統錄音」時 `screenshot` 只有清單沒有圖;沒開「輔助使用」不能點也不能打字。系統詢問最多每 10 分鐘跳一次。 diff --git a/docs/feature-map/team.md b/docs/feature-map/team.md index ecb3a18..bad8d3d 100644 --- a/docs/feature-map/team.md +++ b/docs/feature-map/team.md @@ -16,7 +16,7 @@ Bot 之間可以問問題、交辦工作、教技能;好幾個 Bot 可以在 ## 使用者怎麼到 -- 群組聊天:側邊欄 +(「新增」)›「群組聊天」,先放前三個 Bot 並打開設定,在「群組成員」勾選。群組的輸入框 + 裡寫「成員:…」,右側面板有「成員」。 +- 群組聊天:側邊欄 +(「新增」)›「群組聊天」,先放前三個 Bot 並打開設定,在「群組成員」勾選。群組的輸入框 + 裡寫「成員:…」,右側面板有「成員」;右側的「電腦」畫面跟著正在回答的成員,顯示它自己的螢幕;「成員」卡片上點某個成員的小畫面,改成固定顯示它的。 - 分區:+ ›「新增分區」;Bot 選單「移至」(還沒有分區時是「移至新分區」)。分區標題點一下收合、雙擊改名,右鍵或 ⋯(「分區操作」)有「重新命名」「上移」「下移」「刪除」。 - 支線:輸入框打「/」選 /btw。主聊天出現支線卡:狀態、「停止支線」、「看過程」,支線要你核准的步驟直接在卡上按;沒做完時有「重開這條支線」。 @@ -32,5 +32,6 @@ Bot 之間可以問問題、交辦工作、教技能;好幾個 Bot 可以在 - 一件事從使用者開始,最多在 Bot 之間轉 3 手;A 在等 B 時,B 不能反過來問 A(會說「正在等你」)。使用者停止 A,替 A 回答的 B 也會停。 - 不能問自己,不能問群組或把技能教給群組(改找裡面的成員);自己不會的技能不能教,對方已經會的不用教。 - 別的 Bot 問或交辦的那一輪不算使用者的話:B 不能因此改自己的設定。答案在發問的聊天裡整理給使用者,不要叫他自己去看別的 Bot 的聊天。被點名同事、卻沒有「和其他 Bot 合作」能力的 Bot,只能照實說,請使用者打開。 +- 群組成員在 Bot 的電腦上各有自己的螢幕和瀏覽器,看不到彼此開著的網頁:交棒時要把網址、檔案或頁面寫進回覆(系統指示會提醒成員這樣做)。 - 群組成員互相 @ 交棒時,兩則使用者訊息之間到 8 個回答就停,交還給使用者。群組自己的模型不會用到;群組不能開支線,輸入框上沒有記憶小卡片;成員至少留一個。 -- 支線:一個 Bot 同時最多 3 條;支線不能再開支線,也不能改設定;支線記的、做的頁面和例行任務都算主 Bot 的。主線在忙時,先用執行步驟用的模型判斷會不會衝突,會就等主線這一輪做完。AnyBot 重新啟動時,沒做完的支線會停掉(「AnyBot 重新啟動,這條支線停了」);被停止的支線不回報。 +- 支線:一個 Bot 同時最多 3 條;支線不能再開支線,也不能改設定;支線記的、做的頁面和例行任務都算主 Bot 的。主線在忙時,先用執行步驟用的模型判斷會不會衝突,會就等主線這一輪做完。在 Bot 的電腦上支線有自己的暫時螢幕和瀏覽器(登入從主線複製),看不到主線開著的網頁;在使用者的電腦上還是一次一個。AnyBot 重新啟動時,沒做完的支線會停掉(「AnyBot 重新啟動,這條支線停了」);被停止的支線不回報。 diff --git a/mobile/index.html b/mobile/index.html index 17aa896..81f93d1 100644 --- a/mobile/index.html +++ b/mobile/index.html @@ -2615,7 +2615,7 @@ function openBox(control) { const at = S.relay ? "host=" + encodeURIComponent(S.host) : "lan=1"; boxOpen = true; history.pushState({box: 1}, ""); - $("boxframe").src = "screen#" + at + "&name=" + encodeURIComponent(own ? own.name : "Bot 的電腦") + (control ? "&control=1" : "") + "&embed=1"; + $("boxframe").src = "screen#" + at + "&name=" + encodeURIComponent(own ? own.name : "Bot 的電腦") + (b.id ? "&bot=" + b.id : "") + (control ? "&control=1" : "") + "&embed=1"; $("boxwrap").style.display = "block"; } function closeBox() { diff --git a/mobile/screen.html b/mobile/screen.html index 9009dd7..6b5ffa4 100644 --- a/mobile/screen.html +++ b/mobile/screen.html @@ -116,7 +116,9 @@ async function ticketFor(path, body) { const lan = q.get("lan") === "1"; const given = q.get("ticket") || await ticketFor(lan ? "api/vnc/ticket" : "relay/screen-ticket", lan ? {} : {host: q.get("host") || ""}); const auth = given ? "ticket=" + encodeURIComponent(given) : "t=" + encodeURIComponent(token); -const url = lan ? `${wsBase}/api/vnc?${auth}` : `${wsBase}/relay/vnc/${encodeURIComponent(q.get("host") || "")}?${auth}`; +// 每個 Bot 一個螢幕: the bot whose screen this is (the AnyBot shows its own screen, or the shared one). +const botq = /^\d+$/.test(q.get("bot") || "") ? "&bot=" + q.get("bot") : ""; +const url = lan ? `${wsBase}/api/vnc?${auth}${botq}` : `${wsBase}/relay/vnc/${encodeURIComponent(q.get("host") || "")}?${auth}${botq}`; const $ = (id) => document.getElementById(id); document.title = name; diff --git a/relay/src/main.rs b/relay/src/main.rs index 8d4bacd..d5e2a2f 100644 --- a/relay/src/main.rs +++ b/relay/src/main.rs @@ -492,7 +492,9 @@ impl Relay { let sid = httpd::random_hex(8); let (tx, rx) = std::sync::mpsc::sync_channel::>(256); self.streams.lock().unwrap().insert(sid.clone(), (tx, host.to_string(), on)); - if to_host.send(wire::pack(&json!({"t": "vopen", "sid": sid}), &[])).is_err() { + // 每個 Bot 一個螢幕: which bot's screen (digits only; the AnyBot picks the screen). + let bot: String = req.query.get("bot").map(|b| b.chars().filter(|c| c.is_ascii_digit()).take(20).collect()).unwrap_or_default(); + if to_host.send(wire::pack(&json!({"t": "vopen", "sid": sid, "bot": bot}), &[])).is_err() { self.streams.lock().unwrap().remove(&sid); return; } diff --git a/src/agent.rs b/src/agent.rs index d84fee4..62b2d7b 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -359,6 +359,8 @@ enum BotBrowser { /// another job's, and the person's, stay (see botbrowser's "each job its own tabs"). struct UsedBrowsers { list: Vec, + /// The bot's screen on the bots' computer (its box browser is there). + screen: String, via_name: String, /// Close each browser when done (not only the tabs). close: bool, @@ -382,7 +384,7 @@ fn with_job(args: &str, job: &str) -> String { impl UsedBrowsers { fn new(via_name: &str, bot_id: u64, close: bool) -> Self { let n = JOB_SEQ.fetch_add(1, Ordering::Relaxed); - UsedBrowsers { list: vec![], via_name: via_name.to_string(), close, job: format!("{bot_id}-{}-{n}", crate::model::now_ms()) } + UsedBrowsers { list: vec![], screen: String::new(), via_name: via_name.to_string(), close, job: format!("{bot_id}-{}-{n}", crate::model::now_ms()) } } fn add(&mut self, b: BotBrowser) { @@ -407,7 +409,8 @@ impl UsedBrowsers { let _ = web::run_full("browser_tabs", &args(p), &never); } BotBrowser::Box(p) => { - let _ = crate::botbrowser::in_box(|| web::run_full("browser_tabs", &args(p), &never)); + // (Its own browser on its own screen: 每個 Bot 一個螢幕.) + let _ = crate::cloudbox::on_screen(&self.screen, || crate::botbrowser::in_box(|| web::run_full("browser_tabs", &args(p), &never))); } BotBrowser::Device(host, p) => { let _ = crate::remote::run_on_device(host, "browser_tabs", &args(p), &self.via_name); @@ -605,10 +608,11 @@ fn screen_leases() -> &'static Mutex { /// other work, or forgot to finish), or as soon as that turn ends. pub const SCREEN_IDLE: Duration = Duration::from_secs(120); -/// Which physical screen a computer is: the bots' computer is one desktop for all of them. +/// Which screen a computer is. The bots' computer has a screen for each bot (cloudbox: 每個 Bot +/// 一個螢幕), so bots there don't wait for each other; a person's computer has the one. fn screen_key(place: &tools::Place) -> Option { match place { - tools::Place::Box { .. } => Some("box".into()), + tools::Place::Box { dir } => Some(format!("box:{}", crate::cloudbox::screen_of_dir(dir))), tools::Place::Local { .. } => Some("local".into()), tools::Place::Device { host, .. } => Some(format!("device:{host}")), _ => None, @@ -1423,6 +1427,30 @@ fn untrusted_refusal(job: &Job, name: &str) -> Option<&'static str> { (job.untrusted && crate::profile::ability_of(name) == Some("browser")).then_some(UNTRUSTED_BROWSER) } +/// The screen of this turn's bot on the bots' computer (its own folder's; cloudbox::screen_of_dir). +fn box_screen_of(job: &Job, bot_id: u64) -> String { + job.computers.iter().find_map(|t| match &t.place { + tools::Place::Box { dir } => Some(box_screen_in(job, bot_id, dir)), + _ => None, + }).unwrap_or_default() +} + +/// The screen a turn uses in the box folder `dir`: that bot's own; a 支線 (it works in its main +/// bot's folder) gets a temporary one beside it. +fn box_screen_in(job: &Job, bot_id: u64, dir: &str) -> String { + let own = crate::cloudbox::screen_of_dir(dir); + if job.home != 0 { crate::cloudbox::branch_screen(&own, bot_id) } else { own } +} + +/// Which screen a step of this turn takes on `place` (screen_key; a 支線 on the bots' computer has +/// its own, so it doesn't wait for its main line there). +fn turn_screen_key(job: &Job, bot_id: u64, place: &tools::Place) -> Option { + match place { + tools::Place::Box { dir } => Some(format!("box:{}", box_screen_in(job, bot_id, dir))), + _ => screen_key(place), + } +} + /// Runs one browser step where the bot's browser is (name, arguments) → (text, ok, picture). type Look<'a> = &'a dyn Fn(&str, &str) -> (String, bool, Option); @@ -1566,6 +1594,7 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc< let mut tools_once = false; let mut local_once = false; let mut browsers = UsedBrowsers::new(&job.via_name, bot_id, job.close_browsers); + browsers.screen = box_screen_of(&job, bot_id); // 電腦現況: what someone at each computer already knows (system, sudo, network, apps…). // Added ONCE here, before the step loop: the turn's system prefix (instructions + facts) // and its tool list (and the deterministic `quick_tools` map of it) never change between @@ -2192,7 +2221,8 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc< Ok(v) => (v["text"].as_str().unwrap_or("").to_string(), v["ok"].as_bool().unwrap_or(false), v["image"].as_str().map(String::from)), Err(e) => (e, false, None), }, - BrowserAt::Box => crate::botbrowser::in_box(|| web::run_full(name, args, &cancel)), + // 每個 Bot 一個螢幕: its own browser, on its own screen. + BrowserAt::Box => crate::cloudbox::on_screen(&box_screen_of(&job, bot_id), || crate::botbrowser::in_box(|| web::run_full(name, args, &cancel))), BrowserAt::Here => web::run_full(name, args, &cancel), } }; @@ -2690,7 +2720,7 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc< } // (On this job's own tab, like its other browser steps: planned outside // it, every tab looked like another job's — "no open tab".) - BrowserAt::Box => crate::botbrowser::as_job(&tag, || crate::botbrowser::in_box(plan_here)), + BrowserAt::Box => crate::cloudbox::on_screen(&box_screen_of(&job, bot_id), || crate::botbrowser::as_job(&tag, || crate::botbrowser::in_box(plan_here))), BrowserAt::Here => crate::botbrowser::as_job(&tag, plan_here), }; let (output, status) = match planned { @@ -2732,7 +2762,7 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc< let a = serde_json::json!({"kind": "form", "values": crate::vault::contact_values(c), "site": host, "profile": profile}).to_string(); remote_vault_page(h, &job, &with_job(&a, &tag)).and_then(|page| crate::vault::contact_fill_text(c, &page)) } - (_, BrowserAt::Box) => crate::botbrowser::as_job(&tag, || crate::botbrowser::in_box(fill_here)), + (_, BrowserAt::Box) => crate::cloudbox::on_screen(&box_screen_of(&job, bot_id), || crate::botbrowser::as_job(&tag, || crate::botbrowser::in_box(fill_here))), (_, BrowserAt::Here) => crate::botbrowser::as_job(&tag, fill_here), }; match r { @@ -2820,6 +2850,11 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc< target_for(&job, &call.args) }; let on_box = matches!(target.as_ref().map(|t| &t.place), Ok(tools::Place::Box { .. })); + // 每個 Bot 一個螢幕: the screen of the bot whose folder this is (a 支線's own). + let box_screen = match target.as_ref().map(|t| &t.place) { + Ok(tools::Place::Box { dir }) => box_screen_in(&job, bot_id, dir), + _ => String::new(), + }; let on_device = match target.as_ref().map(|t| &t.place) { Ok(tools::Place::Device { host, .. }) => Some(host.clone()), _ => None, @@ -3073,7 +3108,7 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc< let mut image = None; // 螢幕一次給一個: acting on a screen another turn is working (not just looking). let busy_screen = match (&approved, &target) { - (Ok(()), Ok(t)) if is_screen && !only_looks(&call.name) => screen_key(&t.place).and_then(|k| lease_screen(&mut screen_leases().lock().unwrap(), &k, bot_id, &job.via_name, Instant::now()).err().map(|e| (t.name.clone(), e))), + (Ok(()), Ok(t)) if is_screen && !only_looks(&call.name) => turn_screen_key(&job, bot_id, &t.place).and_then(|k| lease_screen(&mut screen_leases().lock().unwrap(), &k, bot_id, &job.via_name, Instant::now()).err().map(|e| (t.name.clone(), e))), _ => None, }; let approved = match busy_screen { @@ -3098,7 +3133,7 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc< Err(e) => (e, false), } } else if is_screen && on_box { - match crate::cloudbox::computer_run(&call.name, &tools::args_of(&call.args)) { + match crate::cloudbox::on_screen(&box_screen, || crate::cloudbox::computer_run(&call.name, &tools::args_of(&call.args))) { Ok((out, img)) => { image = img; (out, true) @@ -3111,6 +3146,9 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc< (out, ok) } else if is_web { web::run(&call.name, &call.args, &cancel) + } else if on_box { + // (A window a command opens goes to this turn's screen.) + crate::cloudbox::on_screen(&box_screen, || tools::run_on(&call.name, &call.args, t, &cancel, &ids)) } else { tools::run_on(&call.name, &call.args, t, &cancel, &ids) }; @@ -3340,6 +3378,21 @@ mod tests { assert!(lease_screen(&mut l, "local", 2, "Bot(支線)", t0 + SCREEN_IDLE).is_ok(), "idle long enough: its turn"); assert_eq!(screen_key(&tools::Place::Device { host: "h1".into(), dir: String::new() }).as_deref(), Some("device:h1")); assert_eq!(screen_key(&tools::Place::Ssh { target: "x".into(), dir: String::new() }), None); + // The bots' computer: a screen for each bot, so two bots there never wait for each other. + let a = screen_key(&tools::Place::Box { dir: crate::cloudbox::bot_dir(3) }).unwrap(); + let b = screen_key(&tools::Place::Box { dir: crate::cloudbox::bot_dir(4) }).unwrap(); + assert_ne!(a, b); + let mut l = Leases::new(); + let t0 = Instant::now(); + assert!(lease_screen(&mut l, &a, 3, "甲", t0).is_ok() && lease_screen(&mut l, &b, 4, "乙", t0).is_ok()); + // A 支線 works in its main bot's folder but on a temporary screen of its own there: it + // doesn't wait for its main line (on the person's computer it still does). + let place = tools::Place::Box { dir: crate::cloudbox::bot_dir(3) }; + let main = turn_screen_key(&test_job(), 3, &place).unwrap(); + let branch = turn_screen_key(&Job { home: 3, ..test_job() }, 57, &place).unwrap(); + assert_eq!((main.as_str(), branch.as_str()), ("box:bot3", "box:bot3-t57")); + assert!(lease_screen(&mut l, &branch, 57, "甲(支線)", t0).is_ok(), "beside its main line"); + assert_eq!(turn_screen_key(&Job { home: 3, ..test_job() }, 57, &tools::Place::Local { workdir: std::path::PathBuf::new() }).as_deref(), Some("local")); } #[test] diff --git a/src/app.rs b/src/app.rs index 9bbada6..4b162b3 100644 --- a/src/app.rs +++ b/src/app.rs @@ -25,6 +25,7 @@ use crate::theme::{Palette, DARK, LIGHT}; mod attach_ui; mod channels_ui; mod computers_ui; +mod screens_ui; mod chat_ui; mod files_ui; mod panel_ui; @@ -1566,6 +1567,10 @@ impl App { if speaker.is_some() { let names: Vec = conv.members.iter().filter_map(|m| self.state.bot(*m)).map(|x| x.name.clone()).collect(); sys.push_str(&format!("\n\n你在群組聊天「{}」裡,成員:{}。其他成員的發言以【名字】標示。使用者用「@名字」點名時,只有被點到的成員回答;沒點名就輪流回答。只回答你擅長的部分,補充不同的觀點,不要重複別人說過的;沒有要補充就簡短說一句。要某位成員接著回答(問它、請它補充或檢查),在回覆裡寫「@它的名字」,它會接在你後面說;不要 @ 自己,沒必要就別 @,來回幾次後就交還給使用者。", conv.name, names.join("、"))); + // 每個 Bot 一個螢幕: a member handing work on can't show its screen to the next. + if computers.iter().any(|c| matches!(c.place, crate::tools::Place::Box { .. })) { + sys.push_str("在 Bot 的電腦上每個成員有自己的螢幕和瀏覽器(登入一樣),看不到彼此開著的畫面和網頁:交棒給別的成員時,把網址、檔案路徑或頁面名稱寫進回覆,讓它自己打開;不要只說「我開好了」。"); + } } sys }, @@ -2117,6 +2122,7 @@ impl App { } self.last_tick = Instant::now(); self.tend_garden(); + self.tend_screens(); self.resume_interrupted(ctx); let now = crate::routines::now(); let mut fire = vec![]; @@ -5858,6 +5864,7 @@ impl eframe::App for App { self.delete_dialog(ctx); self.delete_routine_dialog(ctx); self.routines_window(ctx); + self.screens_frame(ctx); self.rebuild_dialog(ctx); self.local_control_bar(ctx); self.teach_bar(ctx); @@ -6246,7 +6253,7 @@ fn system_prompt(b: &Bot, st: &State, computers: &[tools::Target], default_compu } // 支線: a copy of the bot doing one more thing alongside its main line. if b.branch_of != 0 { - s.push_str("\n\n你現在是一條支線:使用者用 /btw 開的分身,帶著同一段對話和記憶,跟主線(你的本尊)同時做對話最後交代的那件事。只做那件事,不要接手或重做主線正在做的事。做完用一段話寫清楚結果,它會原封不動送回主線的聊天。要使用者核准的步驟一樣會問他。同一個螢幕主線或別的 Bot 正在用時,那一步會被擋下:先做不用螢幕的部分、改用別台電腦,或晚點再試。不能再開支線,也不能改自己的設定。"); + s.push_str("\n\n你現在是一條支線:使用者用 /btw 開的分身,帶著同一段對話和記憶,跟主線(你的本尊)同時做對話最後交代的那件事。只做那件事,不要接手或重做主線正在做的事。做完用一段話寫清楚結果,它會原封不動送回主線的聊天。要使用者核准的步驟一樣會問他。在「Bot 的電腦」上你有自己的暫時螢幕和瀏覽器(登入從主線的瀏覽器複製過來,支線結束就關掉),不會跟主線搶,但看不到主線開著的網頁,要用就自己打開。在使用者的電腦上,同一個螢幕主線或別的 Bot 正在用時,那一步會被擋下:先做不用螢幕的部分、改用別台電腦,或晚點再試。不能再開支線,也不能改自己的設定。"); } // 個人檔案: what it is good at and what it leaves to others; then who the others are. // (Its soul — the 指示 — comes last, where it weighs most.) diff --git a/src/app/branch.rs b/src/app/branch.rs index 153c3bc..1c824e6 100644 --- a/src/app/branch.rs +++ b/src/app/branch.rs @@ -8,7 +8,9 @@ // same files or data, an account they'd both act on, a result the main line is waiting for). // No clash: it starts now. A clash: it waits for the main line's turn to end, saying why. // - While both work, a screen is one turn's at a time (agent::lease_screen): a step that would -// click on a screen another turn is using isn't run, and the bot is told who has it. +// click on a screen another turn is using isn't run, and the bot is told who has it. On the +// bots' computer a branch has a temporary screen of its own (cloudbox::branch_screen; its +// browser a copy of the main bot's), closed when the branch ends. // - Its report goes to the main line: into the turn that is running (it reads it at its next // step), or into the chat as the branch's words when nothing is running. // @@ -328,8 +330,15 @@ impl App { } } self.state.branch_bots.retain(|x| x.id != id); - // (Its background commands stop with it: nobody could reach them again.) + // (Its background commands stop with it: nobody could reach them again. So does its + // temporary screen on the bots' computer, with its copy of the browser.) self.forget_bot(id, false); + if !self.demo { + let key = crate::cloudbox::branch_screen(&crate::cloudbox::screen_of_bot(self.state.home_of(main)), id); + if !key.is_empty() { + std::thread::spawn(move || crate::cloudbox::close_screen(&key)); + } + } // The report: into the main line's running turn, or into the chat as the branch's words. if state != BranchState::Stopped { let text = match state { diff --git a/src/app/computers_ui.rs b/src/app/computers_ui.rs index 34136b3..734e881 100644 --- a/src/app/computers_ui.rs +++ b/src/app/computers_ui.rs @@ -61,6 +61,10 @@ pub struct ComputerUi { thumb_img: Arc>>, thumb_busy: Arc, thumb_at: Option, + /// Whose screen the picture is (每個 Bot 一個螢幕: the selected bot's own, else the shared one). + thumb_bot: u64, + /// 每個 Bot 一個螢幕: 全部螢幕, the member picked in a group chat, the small pictures. + pub(super) screens: super::screens_ui::ScreensUi, } /// (the Docker host has gVisor, the runtime the box runs on now) @@ -962,13 +966,19 @@ impl App { let brain = self.mir.on.then(|| self.state.remote.clone()); let running = if brain.is_some() { self.mir.box_state["running"].as_bool().unwrap_or(false) } else { cloudbox::run_state().is_running() }; let every = if running { 3 } else { 30 }; - if !self.cu.thumb_at.map(|t| t.elapsed().as_secs() < every).unwrap_or(false) && !self.cu.thumb_busy.swap(true, Ordering::SeqCst) { + // The selected bot's own screen (another bot picked: a new picture at once; in a group + // chat the member the person picked). + let bot = self.shown_bot(self.state.selected); + let fresh = self.cu.thumb_bot != bot; + if (fresh || !self.cu.thumb_at.map(|t| t.elapsed().as_secs() < every).unwrap_or(false)) && !self.cu.thumb_busy.swap(true, Ordering::SeqCst) { self.cu.thumb_at = Some(Instant::now()); + self.cu.thumb_bot = bot; + let key = self.screen_key_for(bot); let (slot, busy, c) = (self.cu.thumb_img.clone(), self.cu.thumb_busy.clone(), ctx.clone()); std::thread::spawn(move || { let img = match &brain { - Some(s) => crate::remote::sync_screen(s, true).ok().and_then(|b| image::load_from_memory(&b).ok()).map(|i| i.to_rgba8()), - None => cloudbox::thumbnail(320), + Some(s) => crate::remote::sync_screen(s, true, bot).ok().and_then(|b| image::load_from_memory(&b).ok()).map(|i| i.to_rgba8()), + None => cloudbox::thumbnail_of(&key, 320).or_else(|| cloudbox::thumbnail(320)), }; if let Some(img) = img { let size = [img.width() as usize, img.height() as usize]; @@ -990,13 +1000,19 @@ impl App { } fn open_screen(&mut self, control: bool) { + // 每個 Bot 一個螢幕: the selected bot's own screen (the shared one when it has none open). + self.open_screen_of(self.shown_bot(self.state.selected), control); + } + + /// `bot`'s own screen to watch (or take over), the shared one when it has none open. + pub(super) fn open_screen_of(&mut self, bot: u64, control: bool) { self.show_settings = false; - let name = self.state.bots.iter().find(|b| b.id == self.state.selected).map(|b| format!("{} 的電腦", b.name)).unwrap_or_else(|| "Bot 的電腦".into()); + let name = self.state.bot(bot).map(|b| format!("{} 的電腦", b.name)).unwrap_or_else(|| "Bot 的電腦".into()); if self.mir.on { let s = self.state.remote.clone(); self.box_task(move || { let ticket = crate::remote::screen_ticket(&s)?; - let url = format!("{}/screen#host={}&ticket={ticket}&name={}{}", s.relay_url.trim_end_matches('/'), s.brain_id, crate::httpd::url_encode(&name), if control { "&control=1" } else { "" }); + let url = format!("{}/screen#host={}&ticket={ticket}&name={}&bot={bot}{}", s.relay_url.trim_end_matches('/'), s.brain_id, crate::httpd::url_encode(&name), if control { "&control=1" } else { "" }); crate::preview::open_with_system(&url); Ok(String::new()) }); @@ -1005,8 +1021,10 @@ impl App { if self.demo { return; } + let key = self.screen_key_for(bot); + let key = if cloudbox::open_screens().iter().any(|(k, _)| *k == key) { key } else { String::new() }; self.box_task(move || { - let url = cloudbox::viewer_url(control)?; + let url = cloudbox::viewer_url_of(&key, control)?; crate::preview::open_with_system(&url); Ok(String::new()) }); @@ -1031,14 +1049,26 @@ impl App { self.hold_computer(false); } - fn hold_computer(&self, on: bool) { + fn hold_computer(&mut self, on: bool) { + // (The selected bot's screen: the bots on their own screens go on meanwhile. Given back + // is the screen taken, whichever bot is selected by then.) + let (bot, key) = match (on, self.cu.screens.held.take()) { + (false, Some(h)) => h, + _ => { + let bot = self.shown_bot(self.state.selected); + (bot, self.screen_key_for(bot)) + } + }; + if on { + self.cu.screens.held = Some((bot, key.clone())); + } if self.mir.on { let s = self.state.remote.clone(); std::thread::spawn(move || { - let _ = crate::remote::sync_post(&s, "screen", &serde_json::json!({"kind": "hold", "on": on})); + let _ = crate::remote::sync_post(&s, "screen", &serde_json::json!({"kind": "hold", "on": on, "bot": bot})); }); } else { - cloudbox::HELD_BY_PERSON.store(on, Ordering::SeqCst); + cloudbox::hold(&key, on); } } diff --git a/src/app/mirror_ui.rs b/src/app/mirror_ui.rs index 067434b..96c4a7f 100644 --- a/src/app/mirror_ui.rs +++ b/src/app/mirror_ui.rs @@ -655,7 +655,7 @@ impl App { out["mcp"] = self.mcp_state(); // The bots' computer lives here; a screen shows its state, not its own computer's. let run = crate::cloudbox::run_state(); - out["box"] = json!({"label": run.label(), "running": run.is_running(), "available": crate::cloudbox::available(), "busy": crate::cloudbox::is_busy()}); + out["box"] = json!({"label": run.label(), "running": run.is_running(), "available": crate::cloudbox::available(), "busy": crate::cloudbox::is_busy(), "screens": self.tiles_json()}); // Which computers each bot has (only the brain knows the account's other computers). out["computers"] = self .state diff --git a/src/app/panel_ui.rs b/src/app/panel_ui.rs index 88d5563..af70702 100644 --- a/src/app/panel_ui.rs +++ b/src/app/panel_ui.rs @@ -251,6 +251,17 @@ impl App { if let Some(n) = pick { self.set_computer(bot.id, &n); } + // 全部螢幕: every bot's own screen at once (when any is open). + let open = if available { self.screen_tiles().len() } else { 0 }; + if open > 0 { + let label = t("全部螢幕({n})").replace("{n}", &open.to_string()); + ui.horizontal(|ui| { + ui.add_space(10.0); + if ui.add(egui::Label::new(RichText::new(label).size(12.0).color(p.accent)).sense(egui::Sense::click())).on_hover_cursor(egui::CursorIcon::PointingHand).on_hover_text(t("每個 Bot 自己的螢幕,一次看")).clicked() { + self.cu.screens.open = true; + } + }); + } if view { if available { self.open_viewer(); @@ -265,8 +276,15 @@ impl App { let mut edit = false; let members: Vec = bot.members.iter().filter_map(|m| self.state.bot(*m).cloned()).collect(); let colors: Vec = members.iter().map(|b| self.bot_color(b)).collect(); + // 每個 Bot 一個螢幕: a member's own screen, small, when it has one open; a click + // shows it in the 電腦 card (again: back to the member speaking). + let pictures: Vec<_> = members.iter().map(|b| self.screen_tile(b.id)).collect(); + let shown = self.screen_key_for(self.shown_bot(bot.id)); + let keys: Vec = members.iter().map(|b| self.screen_key_for(b.id)).collect(); + let picked = self.cu.screens.pick.get(&bot.id).copied(); + let mut pick: Option> = None; panel_card(ui, p, |ui| { - for (b, col) in members.iter().zip(colors) { + for (((b, col), pic), key) in members.iter().zip(colors).zip(&pictures).zip(&keys) { let (rect, r) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_H), egui::Sense::click()); if r.hovered() { ui.painter().rect_filled(rect, 9, p.hover); @@ -274,9 +292,30 @@ impl App { let mut child = ui.new_child(egui::UiBuilder::new().max_rect(rect.shrink2(vec2(10.0, 0.0))).layout(Layout::left_to_right(Align::Center))); avatar::avatar(&mut child, 20.0, &b.shape, col); child.label(RichText::new(&b.name).size(13.0).color(p.text)); + if let Some((tex, size)) = pic { + let at = egui::Rect::from_min_size(egui::pos2(rect.right() - 10.0 - 40.0, rect.center().y - 12.5), vec2(40.0, 25.0)); + let on = *key == shown; + let tr = ui.interact(at, egui::Id::unique(("member-screen", b.id)), egui::Sense::click()); + egui::Image::new((*tex, *size)).fit_to_exact_size(at.size()).corner_radius(4).paint_at(ui, at); + ui.painter().rect_stroke(at, 4, Stroke::new(if on { 2.0 } else { 1.0 }, if on { p.accent } else { p.border }), egui::StrokeKind::Inside); + let tip = if on { t("右側正在顯示「{name}」的螢幕") } else { t("在右側顯示「{name}」的螢幕") }.replace("{name}", &b.name); + if tr.on_hover_cursor(egui::CursorIcon::PointingHand).on_hover_text(tip).clicked() { + pick = Some(if picked == Some(b.id) { None } else { Some(b.id) }); + continue; + } + } edit |= r.clicked(); } }); + match pick { + Some(Some(m)) => { + self.cu.screens.pick.insert(bot.id, m); + } + Some(None) => { + self.cu.screens.pick.remove(&bot.id); + } + None => {} + } if edit { self.edit_bot = Some((bot.clone(), false)); } diff --git a/src/app/screens_ui.rs b/src/app/screens_ui.rs new file mode 100644 index 0000000..1970dc2 --- /dev/null +++ b/src/app/screens_ui.rs @@ -0,0 +1,279 @@ +// 每個 Bot 一個螢幕, as the window shows it (Grok Bot's split: one computer for the account, a +// screen of its own for each bot; cloudbox has the box's side). +// +// - The 電腦 card shows the selected bot's own screen. In a group chat it is the member speaking, +// unless the person picked a member (the small pictures in the 成員 card). +// - 全部螢幕: every screen open on the bots' computer, a small live picture each; a click opens +// that screen to watch or take over. +// - On the brain, every few seconds: which bot is on which screen (what viewers from the phone, +// a screen computer or the account server go by), the screens open now, and the idle ones closed. + +use super::*; +use crate::cloudbox; + +/// A bot's own screen on the bots' computer nobody used this long is closed (its browser too). +const SCREEN_IDLE_SECS: u64 = 600; +/// How often the small pictures of 全部螢幕 and the 成員 card are taken again. +const TILE_EVERY: u64 = 3; +/// Their width in pixels. +const TILE_W: u32 = 240; + +#[derive(Default)] +pub struct ScreensUi { + /// 全部螢幕 is open. + pub(super) open: bool, + /// In a group chat (its id), the member whose screen the 電腦 card shows: picked by the + /// person; none, the member speaking. + pub(super) pick: HashMap, + /// The screen the person took over (bot, screen), to give that one back. + pub(super) held: Option<(u64, String)>, + /// The small pictures, by bot. + tiles: HashMap, + fresh: Arc>>, + busy: Arc, + tiles_at: Option, + /// When the brain last told the box which bot is on which screen, looked at the screens open, + /// and swept idle ones. + mapped_at: Option, + listed_at: Option, + listing: Arc, + reaped_at: Option, +} + +/// One open screen: whose it is, and how long since a bot used it. +#[derive(Clone, Debug, PartialEq)] +pub(super) struct Tile { + pub bot: u64, + pub name: String, + pub idle: u64, +} + +impl App { + /// The screen to show for `bot_id` on the bots' computer: its own, by the folder it works in; + /// a 支線's temporary one; in a group chat the member speaking now, else the first member. + /// "" when it isn't a bot. + pub(super) fn screen_key_for(&self, bot_id: u64) -> String { + let Some(b) = self.state.bot(bot_id) else { return String::new() }; + if b.branch_of != 0 { + return cloudbox::branch_screen(&cloudbox::screen_of_bot(b.branch_of), bot_id); + } + let who = if b.members.is_empty() { + bot_id + } else { + b.messages.iter().rev().find(|m| m.role == Role::Assistant && m.author != 0).map(|m| m.author).or_else(|| b.members.first().copied()).unwrap_or(bot_id) + }; + cloudbox::screen_of_bot(self.state.home_of(who)) + } + + /// Whose screen the 電腦 card shows for `bot_id`: in a group chat the member the person + /// picked (when still a member), else `bot_id` itself (screen_key_for goes on from there). + pub(super) fn shown_bot(&self, bot_id: u64) -> u64 { + let members = self.state.bot(bot_id).map(|b| b.members.clone()).unwrap_or_default(); + self.cu.screens.pick.get(&bot_id).copied().filter(|m| members.contains(m)).unwrap_or(bot_id) + } + + /// On the brain: tell the box side which bot is on which screen, look at the screens open, + /// and close the screens no bot used for 10 minutes (their browsers too; the profiles stay). + pub(super) fn tend_screens(&mut self) { + if self.mir.on || self.demo { + return; + } + let s = &mut self.cu.screens; + if !s.mapped_at.is_some_and(|t| t.elapsed().as_secs() < 2) { + s.mapped_at = Some(Instant::now()); + let ids: Vec = self.state.bots.iter().chain(self.state.branch_bots.iter()).map(|b| b.id).collect(); + let map = ids.into_iter().map(|id| (id, self.screen_key_for(id))).collect(); + cloudbox::set_bot_screens(map); + } + // (A box that stopped has none open: the list empties without asking it.) + let s = &mut self.cu.screens; + if !s.listed_at.is_some_and(|t| t.elapsed().as_secs() < 5) && !s.listing.swap(true, Ordering::SeqCst) { + s.listed_at = Some(Instant::now()); + let busy = s.listing.clone(); + std::thread::spawn(move || { + cloudbox::refresh_open_screens(); + busy.store(false, Ordering::SeqCst); + }); + } + if !s.reaped_at.is_some_and(|t| t.elapsed().as_secs() < 60) && cloudbox::run_state().is_running() { + s.reaped_at = Some(Instant::now()); + std::thread::spawn(|| cloudbox::reap_screens(SCREEN_IDLE_SECS)); + } + } + + /// The screens open on the bots' computer here, by bot (a 支線's under its bot's name). + pub(super) fn local_tiles(&self) -> Vec { + cloudbox::open_screens_seen() + .into_iter() + .filter_map(|(key, idle)| { + let (own, branch) = cloudbox::bot_of_screen(&key)?; + let (bot, name) = if branch != 0 { + (branch, format!("{}(支線)", self.state.bot(branch)?.name)) + } else { + (own, self.state.bots.iter().find(|b| b.id == own && b.members.is_empty())?.name.clone()) + }; + Some(Tile { bot, name, idle }) + }) + .collect() + } + + /// The screens open on the bots' computer (on a screen of a brain: the brain's, as it said). + pub(super) fn screen_tiles(&self) -> Vec { + if !self.mir.on { + return self.local_tiles(); + } + self.mir.box_state["screens"] + .as_array() + .map(|a| a.iter().filter_map(|t| Some(Tile { bot: t["bot"].as_u64()?, name: t["name"].as_str()?.to_string(), idle: t["idle"].as_u64().unwrap_or(0) })).collect()) + .unwrap_or_default() + } + + /// What a screen of this brain is told about the screens open (its 全部螢幕). + pub(super) fn tiles_json(&self) -> serde_json::Value { + self.local_tiles().iter().map(|t| serde_json::json!({"bot": t.bot, "name": t.name, "idle": t.idle})).collect() + } + + /// The small picture of `bot`'s screen, when there is one (screens_frame keeps it fresh). + pub(super) fn screen_tile(&self, bot: u64) -> Option<(egui::TextureId, egui::Vec2)> { + self.cu.screens.tiles.get(&bot).map(|t| (t.id(), t.size_vec2())) + } + + /// Pictures of the bots in `wanted` taken again every few seconds (in the background; on a + /// screen of a brain, from it). + fn refresh_tiles(&mut self, ctx: &egui::Context, wanted: &[u64]) { + let s = &mut self.cu.screens; + for (bot, img) in std::mem::take(&mut *s.fresh.lock().unwrap()) { + match s.tiles.get_mut(&bot) { + Some(t) => t.set(img, egui::TextureOptions::LINEAR), + None => { + s.tiles.insert(bot, ctx.load_texture(format!("screen-tile-{bot}"), img, egui::TextureOptions::LINEAR)); + } + } + } + if wanted.is_empty() { + return; + } + ctx.request_repaint_after(std::time::Duration::from_secs(TILE_EVERY)); + if s.tiles_at.is_some_and(|t| t.elapsed().as_secs() < TILE_EVERY) || s.busy.swap(true, Ordering::SeqCst) { + return; + } + s.tiles_at = Some(Instant::now()); + let (fresh, busy, c) = (s.fresh.clone(), s.busy.clone(), ctx.clone()); + let brain = self.mir.on.then(|| self.state.remote.clone()); + let jobs: Vec<(u64, String)> = wanted.iter().map(|&b| (b, self.screen_key_for(b))).collect(); + std::thread::spawn(move || { + for (bot, key) in jobs { + let img = match &brain { + Some(s) => crate::remote::sync_screen(s, true, bot).ok().and_then(|b| image::load_from_memory(&b).ok()).map(|i| i.to_rgba8()), + None if key.is_empty() => None, + None => cloudbox::thumbnail_of(&key, TILE_W), + }; + if let Some(img) = img { + let size = [img.width() as usize, img.height() as usize]; + fresh.lock().unwrap().push((bot, egui::ColorImage::from_rgba_unmultiplied(size, img.as_raw()))); + c.request_repaint(); + } + } + busy.store(false, Ordering::SeqCst); + }); + } + + /// Every frame: the pictures shown now (全部螢幕, the 成員 card of the group chat open) kept + /// fresh, and 全部螢幕 itself. + pub(super) fn screens_frame(&mut self, ctx: &egui::Context) { + let tiles = self.screen_tiles(); + let mut wanted: Vec = vec![]; + if self.cu.screens.open { + wanted.extend(tiles.iter().map(|t| t.bot)); + } + if let Some(b) = self.state.bot(self.state.selected).filter(|b| !b.members.is_empty()) { + wanted.extend(b.members.iter().filter(|m| tiles.iter().any(|t| t.bot == **m))); + } + wanted.sort_unstable(); + wanted.dedup(); + self.refresh_tiles(ctx, &wanted); + if self.cu.screens.open { + self.screens_window(ctx, &tiles); + } + } + + /// 全部螢幕: a small live picture of each screen open; a click opens it. + fn screens_window(&mut self, ctx: &egui::Context, tiles: &[Tile]) { + let p = self.pal; + let mut view: Option = None; + let pictures: Vec> = tiles.iter().map(|t| self.screen_tile(t.bot)).collect(); + let dismissed = dialog(ctx, "all-screens", &t("全部螢幕"), 560.0, true, p, |ui| { + if tiles.is_empty() { + ui.label(RichText::new(t("現在沒有 Bot 開著自己的螢幕。Bot 第一次看畫面或用瀏覽器時才會開,閒置 10 分鐘自動關掉。")).color(p.text2)); + return; + } + hint(ui, t("每個 Bot 在 Bot 的電腦上有自己的螢幕,互不干擾。點一格看它的畫面,也可以在那裡接手。"), p); + ui.add_space(6.0); + let w = 256.0; + let cols = ((ui.available_width() + 12.0) / (w + 12.0)).floor().max(1.0) as usize; + egui::Grid::new("all-screens-grid").spacing(vec2(12.0, 12.0)).show(ui, |ui| { + for (i, (tile, pic)) in tiles.iter().zip(&pictures).enumerate() { + let (rect, r) = ui.allocate_exact_size(vec2(w, w * 10.0 / 16.0 + 40.0), egui::Sense::click()); + let shot = egui::Rect::from_min_size(rect.min, vec2(w, w * 10.0 / 16.0)); + match pic { + Some((tex, size)) => egui::Image::new((*tex, *size)).fit_to_exact_size(shot.size()).corner_radius(8).paint_at(ui, shot), + None => { + ui.painter().rect_filled(shot, 8, p.active); + } + } + ui.painter().rect_stroke(shot, 8, Stroke::new(if r.hovered() { 2.0 } else { 1.0 }, if r.hovered() { p.accent } else { p.border }), egui::StrokeKind::Inside); + let when = if tile.idle < 60 { t("剛剛還在用") } else { t("閒置 {n} 分鐘").replace("{n}", &(tile.idle / 60).to_string()) }; + ui.painter().text(shot.left_bottom() + vec2(2.0, 8.0), egui::Align2::LEFT_TOP, super::sidebar_ui::shorten_width(ui, &tile.name, w - 4.0, 13.0), egui::FontId::proportional(13.0), p.text); + ui.painter().text(shot.left_bottom() + vec2(2.0, 25.0), egui::Align2::LEFT_TOP, when, egui::FontId::proportional(11.5), p.text3); + if r.on_hover_cursor(egui::CursorIcon::PointingHand).on_hover_text(t("看「{name}」的螢幕,也可以取得控制權自己操作").replace("{name}", &tile.name)).clicked() { + view = Some(tile.bot); + } + if (i + 1) % cols == 0 { + ui.end_row(); + } + } + }); + }); + if dismissed { + self.cu.screens.open = false; + } + if let Some(bot) = view { + self.open_screen_of(bot, false); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_branch_and_a_picked_member_have_their_own_screens() { + let ctx = egui::Context::default(); + let mut app = super::super::App::new(&ctx, Some(std::env::temp_dir().join("anybot-screens-ui.png"))); + let (a, b) = (app.state.bots[0].id, app.state.bots[1].id); + let mut branch = app.state.bot(a).cloned().unwrap(); + branch.id = 9_001; + branch.branch_of = a; + app.state.branch_bots.push(branch); + assert_eq!(app.screen_key_for(a), format!("bot{a}")); + assert_eq!(app.screen_key_for(9_001), format!("bot{a}-t9001"), "a branch beside its main bot"); + assert_eq!(cloudbox::bot_of_screen(&format!("bot{a}-t9001")), Some((a, 9_001))); + assert_eq!(cloudbox::bot_of_screen(&format!("bot{b}")), Some((b, 0))); + assert_eq!(cloudbox::bot_of_screen("main"), None); + // A group chat shows the member speaking; one the person picked instead. + let mut group = app.state.bots[0].clone(); + group.id = 9_002; + group.members = vec![a, b]; + group.messages = vec![Message { author: b, ..Message::assistant("我來", "") }]; + app.state.bots.push(group); + let g = 9_002; + assert_eq!(app.screen_key_for(g), format!("bot{b}")); + assert_eq!(app.shown_bot(g), g); + app.cu.screens.pick.insert(g, a); + assert_eq!(app.screen_key_for(app.shown_bot(g)), format!("bot{a}")); + // (Not a member any more: back to the one speaking.) + app.state.bot_mut(g).unwrap().members.retain(|m| *m != a); + assert_eq!(app.shown_bot(g), g); + } +} diff --git a/src/cloudbox.rs b/src/cloudbox.rs index 7de8e53..3d85d8f 100644 --- a/src/cloudbox.rs +++ b/src/cloudbox.rs @@ -133,6 +133,8 @@ const XRESOURCES: &str = include_str!("../box/Xresources"); const MENU: &str = include_str!("../box/menu"); const A11Y: &str = include_str!("../box/a11y"); const BROWSER: &str = include_str!("../box/browser"); +/// 每個 Bot 一個螢幕: opens, lists and closes the bots' own screens. +const SCREEN_SH: &str = include_str!("../box/screen"); // ---------- state ---------- @@ -218,15 +220,13 @@ struct Shared { last_used: Instant, rebuilding: bool, log: Vec, - /// The desktop's size in pixels (the bot's pictures are this, fitted; see box_scale). - size: Option<(u32, u32)>, tunnel: Option, host_port: u16, } fn shared() -> &'static Mutex { static S: OnceLock> = OnceLock::new(); - S.get_or_init(|| Mutex::new(Shared { run: Run::Absent, last_used: Instant::now(), rebuilding: false, log: vec![], size: None, tunnel: None, host_port: HOST_PORT })) + S.get_or_init(|| Mutex::new(Shared { run: Run::Absent, last_used: Instant::now(), rebuilding: false, log: vec![], tunnel: None, host_port: HOST_PORT })) } fn config() -> &'static Mutex { @@ -894,7 +894,7 @@ fn build_image(pull: bool) -> Result<(), String> { let dir = std::env::temp_dir().join(format!("anybot-box-build-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?; - for (name, body) in [("Dockerfile", DOCKERFILE), ("start.sh", START_SH), ("fluxbox-init", FLUXBOX_INIT), ("overlay", OVERLAY), ("Xresources", XRESOURCES), ("menu", MENU), ("a11y", A11Y), ("browser", BROWSER)] { + for (name, body) in [("Dockerfile", DOCKERFILE), ("start.sh", START_SH), ("fluxbox-init", FLUXBOX_INIT), ("overlay", OVERLAY), ("Xresources", XRESOURCES), ("menu", MENU), ("a11y", A11Y), ("browser", BROWSER), ("screen", SCREEN_SH)] { std::fs::write(dir.join(name), body).map_err(|e| e.to_string())?; } log("正在建立電腦的映像檔(第一次要幾分鐘)…"); @@ -929,7 +929,7 @@ fn free_port(start: u16) -> u16 { } fn create_container() -> Result<(), String> { - shared().lock().unwrap_or_else(|e| e.into_inner()).size = None; + screens().lock().unwrap_or_else(|e| e.into_inner()).clear(); if !image_exists() { build_image(false)?; } @@ -956,10 +956,10 @@ fn create_container() -> Result<(), String> { .iter() .flat_map(|c| ["--cap-add".to_string(), (*c).to_string()]) .collect(); - let mut args: Vec<&str> = vec!["run", "-d", "--name", container(), "--hostname", "bot-computer", "--shm-size", "1g", "--pids-limit", "4096", "--memory", "2g", "--cpus", "2", "--add-host", "host.docker.internal:host-gateway", "-p", &publish, "-v", &vol, "-e", &env, "-e", &vnc]; + let mut args: Vec<&str> = vec!["run", "-d", "--name", container(), "--hostname", "bot-computer", "--shm-size", "2g", "--pids-limit", "4096", "--memory", "4g", "--cpus", "2", "--add-host", "host.docker.internal:host-gateway", "-p", &publish, "-v", &vol, "-e", &env, "-e", &vnc]; if hardened { // (No swap on top of the 2 GB under gVisor; a standard box keeps Docker's default.) - args.extend(["--memory-swap", "2g"]); + args.extend(["--memory-swap", "4g"]); args.push("--runtime"); args.push(runtime); args.push("--cap-drop"); @@ -1056,11 +1056,11 @@ fn pump(from: &mut impl std::io::Read, to: &mut impl std::io::Write) { } } -/// A local port that reaches the box's DevTools port. -fn box_cdp_forward() -> Result { - static PORT: Mutex = Mutex::new(0); - let mut p = PORT.lock().unwrap(); - if *p != 0 { +/// A local port that reaches DevTools port `box_port` in the box (one per screen's browser). +fn box_cdp_forward(box_port: u16) -> Result { + static PORTS: OnceLock>> = OnceLock::new(); + let mut ports = PORTS.get_or_init(|| Mutex::new(std::collections::HashMap::new())).lock().unwrap_or_else(|e| e.into_inner()); + if let Some(p) = ports.get(&box_port) { return Ok(*p); } let l = std::net::TcpListener::bind("127.0.0.1:0").map_err(|e| e.to_string())?; @@ -1068,7 +1068,7 @@ fn box_cdp_forward() -> Result { std::thread::spawn(move || { for conn in l.incoming().flatten() { std::thread::spawn(move || { - let script = format!("exec 3<>/dev/tcp/127.0.0.1/{BOX_CDP_PORT} || exit 1; cat <&3 & cat >&3; kill $! 2>/dev/null"); + let script = format!("exec 3<>/dev/tcp/127.0.0.1/{box_port} || exit 1; cat <&3 & cat >&3; kill $! 2>/dev/null"); let Ok(mut child) = docker().args(["exec", "-i", container(), "bash", "-c", &script]).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null()).spawn() else { return }; let (Some(mut cin), Some(mut cout)) = (child.stdin.take(), child.stdout.take()) else { return }; let (Ok(mut r), Ok(mut w)) = (conn.try_clone(), conn.try_clone()) else { return }; @@ -1081,26 +1081,53 @@ fn box_cdp_forward() -> Result { }); } }); - *p = port; + ports.insert(box_port, port); Ok(port) } -/// Is the box's Chromium answering already? -pub fn browser_running() -> bool { - box_cdp_forward().map(box_cdp_alive).unwrap_or(false) +/// The current screen's DevTools port in the box (the shared screen's browser: 9222), opening the +/// screen when it isn't (and marking it used, at most once a minute, so a bot working only in its +/// browser doesn't have its screen closed as idle). +fn screen_cdp_port(fresh: bool) -> Result { + let key = current_screen(); + if key.is_empty() { + return Ok(BOX_CDP_PORT); + } + let known = with_screen(|st| st.cdp.filter(|_| !fresh && st.touched.is_some_and(|t| t.elapsed() < Duration::from_secs(60)))); + if let Some(p) = known { + return Ok(p); + } + 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; }}; anybot-screen up {key}")], 30_000) + .map(|o| String::from_utf8_lossy(&o).to_string()) + .map_err(|e| screen_full(&e).unwrap_or_else(|| format!("Bot 的電腦開不了這個 Bot 的螢幕:{e}")))?; + let port = out.lines().find_map(|l| l.trim().strip_prefix("CDP_PORT=")?.parse::().ok()).ok_or("Bot 的電腦沒有說這個 Bot 的瀏覽器在哪個埠")?; + with_screen(|st| { + st.cdp = Some(port); + st.touched = Some(Instant::now()); + }); + Ok(port) } -/// The box's Chromium, started on its desktop when it isn't running. Gives the local port. +/// Is the current screen's Chromium answering already? +pub fn browser_running() -> bool { + screen_cdp_port(false).and_then(box_cdp_forward).map(box_cdp_alive).unwrap_or(false) +} + +/// The current screen's Chromium (each bot its own, on its own screen, with its own profile that +/// started as a copy of the shared one's logins), started when it isn't running. Gives the local +/// port that reaches it. pub fn browser_port() -> Result { ensure_running()?; touch(); - let port = box_cdp_forward()?; + let port = box_cdp_forward(screen_cdp_port(false)?)?; if box_cdp_alive(port) { return Ok(port); } - // The box's one browser launcher (same profile and port as the person's menu entry, web - // pages exposed to accessibility). - dk_timeout(&["exec", "-u", "bot", container(), "anybot-browser"], 30_000).map_err(|e| format!("Bot 的電腦打不開瀏覽器:{e}"))?; + // Not answering: the screen may have been closed meanwhile — open it again, then the browser. + let key = current_screen(); + let port = box_cdp_forward(screen_cdp_port(true)?)?; + let start_cmd = if key.is_empty() { "anybot-browser".to_string() } else { format!("ANYBOT_SCREEN={key} anybot-browser") }; + dk_timeout(&["exec", "-u", "bot", container(), "sh", "-c", &start_cmd], 30_000).map_err(|e| format!("Bot 的電腦打不開瀏覽器:{e}"))?; let start = Instant::now(); while start.elapsed() < Duration::from_secs(20) { if box_cdp_alive(port) { @@ -1740,6 +1767,16 @@ pub fn exec_wrapper(dir: &str, cmd: &str, interactive: bool, tty: bool, job: &st (true, false) => " -i", _ => "", }; + // A window a command opens shows on its bot's own screen when that is open (每個 Bot 一個螢幕; + // a 支線's on its temporary one: the current screen), else on the shared one. A command + // doesn't open a screen by itself. + let key = match current_screen() { + k if k.is_empty() => screen_of_dir(dir), + k => k, + }; + if !key.is_empty() { + inner = format!("[ -r /tmp/anybot-screens/{key}/env ] && {{ . /tmp/anybot-screens/{key}/env; export DISPLAY DBUS_SESSION_BUS_ADDRESS; }}; {inner}"); + } format!("{} exec{flags} -u {user} -e DISPLAY={DISPLAY} -e HOME={HOME} -e USER=bot{}{env_arg} {box} bash -lc {}", docker_prefix(), egress_env(), sh_quote(&inner), r#box = container()) } @@ -1838,8 +1875,14 @@ pub fn copy_out(path_in_box: &str) -> Result { /// The latest picture of the box's screen, small (for the 電腦 card). While the box runs it is /// taken now (and kept on disk); while it sleeps the last one taken is shown. pub fn thumbnail(width: u32) -> Option { - let path = data_dir().join("last-screen.png"); - if let Some(img) = frame() { + thumbnail_of("", width) +} + +/// The same, of `key`'s screen ("" the shared one). None for a bot whose screen isn't open (and +/// never was): the caller shows the shared one. +pub fn thumbnail_of(key: &str, width: u32) -> Option { + let path = if key.is_empty() { data_dir().join("last-screen.png") } else { data_dir().join(format!("last-screen-{key}.png")) }; + if let Some(img) = frame_of(key) { let h = (img.height() as f32 * width as f32 / img.width().max(1) as f32).round() as u32; let small = image::imageops::resize(&img, width, h.max(1), image::imageops::FilterType::Triangle); let _ = std::fs::create_dir_all(data_dir()); @@ -1849,28 +1892,66 @@ pub fn thumbnail(width: u32) -> Option { image::open(&path).ok().map(|i| i.to_rgba8()) } -/// The screen now, for a small picture (no waking: None when the box isn't running). People watch -/// it live through VNC (vnc.rs). -pub fn frame() -> Option { +/// `key`'s screen now, for a small picture ("" the shared one; no waking: None when the box isn't +/// running, or the bot's screen isn't open). People watch it live through VNC (vnc.rs). +pub fn frame_of(key: &str) -> Option { if !run_state().is_running() { return None; } - let jpeg = dk_timeout(&["exec", container(), "import", "-window", "root", "-display", DISPLAY, "-quality", "80", "jpeg:-"], 5_000).ok()?; + let jpeg = if key.is_empty() { + dk_timeout(&["exec", container(), "import", "-window", "root", "-display", DISPLAY, "-quality", "80", "jpeg:-"], 5_000).ok()? + } else { + let script = format!(". /tmp/anybot-screens/{key}/env 2>/dev/null || exit 4; import -window root -display \"$DISPLAY\" -quality 80 jpeg:-"); + dk_timeout(&["exec", container(), "sh", "-c", &script], 5_000).ok()? + }; image::load_from_memory(&jpeg).ok().map(|i| i.to_rgba8()) } +/// The screens open in the box now: (key, seconds since a bot last used it). +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) + .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() +} + +/// The screens open in the box as last looked (refresh_open_screens, every few seconds while the +/// window runs): what the 全部螢幕 view and a screen of the brain list, without waiting on the box. +fn seen_screens() -> &'static Mutex> { + static S: OnceLock>> = OnceLock::new(); + S.get_or_init(|| Mutex::new(vec![])) +} + +pub fn refresh_open_screens() { + let open = open_screens(); + *seen_screens().lock().unwrap_or_else(|e| e.into_inner()) = open; +} + +pub fn open_screens_seen() -> Vec<(String, u64)> { + seen_screens().lock().unwrap_or_else(|e| e.into_inner()).clone() +} + +/// Close the screens no bot used for `secs` (their browsers too; profiles stay). +pub fn reap_screens(secs: u64) { + if run_state().is_running() { + let _ = dk_timeout(&["exec", "-u", "bot", container(), "sh", "-c", &format!("command -v anybot-screen >/dev/null && anybot-screen reap {secs}")], 10_000); + } +} + /// The desktop's size in pixels (asked once per box). fn box_size() -> Result<(u32, u32), String> { - if let Some(s) = shared().lock().unwrap_or_else(|e| e.into_inner()).size { + if let Some(s) = with_screen(|st| st.size) { return Ok(s); } - let out = dk(&["exec", "-u", "bot", "-e", "DISPLAY=:1", container(), "xdotool", "getdisplaygeometry"])?; + let out = box_exec("xdotool getdisplaygeometry")?; let mut it = out.split_whitespace().filter_map(|n| n.parse::().ok()); let size = match (it.next(), it.next()) { (Some(w), Some(h)) if w > 0 && h > 0 => (w, h), _ => return Err("讀不到這台電腦的螢幕大小".to_string()), }; - shared().lock().unwrap_or_else(|e| e.into_inner()).size = Some(size); + with_screen(|st| st.size = Some(size)); Ok(size) } @@ -1897,7 +1978,7 @@ pub fn box_script(name: &str, v: &Value, scale: (f64, f64)) -> Result<(String, S Value::Number(n) => n.to_string(), _ => return None, }; - let spots = BOX_SPOTS.lock().unwrap_or_else(|e| e.into_inner()).clone(); + let spots = with_screen(|st| st.spots.clone()); Some(spots.ok_or_else(|| "先用 computer_use_screenshot 看一下畫面,再照圖上的編號操作。".to_string()).and_then(|s| s.get(&r)).map(|((x, y), what)| ((x.round() as i64, y.round() as i64), format!("#{}({what})", crate::marks::number_of(&r).unwrap_or(0))))) }; let pt = |p: &Value| -> Result<(i64, i64), String> { @@ -2045,7 +2126,8 @@ fn type_script_as(text: &str, paste: bool) -> String { if !paste && text.is_ascii() && text.chars().count() <= TYPE_KEYS_MAX_CHARS { return format!("xdotool type --clearmodifiers --delay {TYPE_DELAY_MS} -- {q}"); } - format!("printf '%s' {q} > /tmp/anybot-paste.txt && for s in clipboard primary; do setsid xclip -selection $s -i /tmp/anybot-paste.txt /dev/null 2>&1 & done; sleep 0.15; \ + let f = format!("/tmp/anybot-paste-{}.txt", screen_tag(¤t_screen())); + format!("printf '%s' {q} > {f} && for s in clipboard primary; do setsid xclip -selection $s -i {f} /dev/null 2>&1 & done; sleep 0.15; \ case \"$(xprop -id $(xdotool getactivewindow) WM_CLASS 2>/dev/null | tr A-Z a-z)\" in *term*) k=shift+Insert;; *) k=ctrl+v;; esac; xdotool key --clearmodifiers $k") } @@ -2061,12 +2143,13 @@ 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())); // An stdin closed at once, as `docker exec -i` expects. - match dk_with_input(&["exec", "-i", "-u", "bot", "-e", "DISPLAY=:1", container(), "sh", "-c", script], Some(b""), 30_000) { + 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()), Err(e) if e == "逾時" => Err("這台電腦太久沒有回應".into()), Err(e) if e.is_empty() => Err("這一步沒有成功".into()), - Err(e) => Err(format!("xdotool:{e}")), + Err(e) => Err(screen_full(&e).unwrap_or_else(|| format!("xdotool:{e}"))), } } @@ -2110,10 +2193,159 @@ pub fn box_write(path: &str, bytes: &[u8]) -> Result<(), String> { dk_with_input(&["exec", "-i", "-u", "bot", container(), "sh", "-c", &script], Some(bytes), 60_000).map(|_| ()).map_err(|e| format!("存不進 Bot 的電腦:{e}")) } -/// The numbered controls of the box's latest look (centres in desktop pixels). -static BOX_SPOTS: Mutex> = Mutex::new(None); -/// The latest look's fingerprint (to say when a step changed nothing). -static BOX_LAST: Mutex> = Mutex::new(None); +// ---------- 每個 Bot 一個螢幕 ---------- +// Grok Bot's split: one computer for the account, a screen of its own for each bot (box/screen: +// `anybot-screen up ` makes display :10, :11, … with its own VNC, accessibility bus and +// browser port). Bots work side by side instead of taking turns on :1; :1 stays the shared +// desktop. A step runs on the current screen (`on_screen`); "" is the shared one. + +thread_local! { + static ON_SCREEN: std::cell::RefCell = const { std::cell::RefCell::new(String::new()) }; +} + +/// The screen of the bot whose folder is `dir` (/home/bot/bot-12 → "bot12"), "" for any other +/// folder (the shared screen). A branch works in its main bot's folder, so on its screen too. +pub fn screen_of_dir(dir: &str) -> String { + dir.trim_end_matches('/').rsplit('/').next().and_then(|f| f.strip_prefix("bot-")).filter(|id| !id.is_empty() && id.chars().all(|c| c.is_ascii_digit())).map(|id| format!("bot{id}")).unwrap_or_default() +} + +/// The screen of a bot by its id. +pub fn screen_of_bot(bot_id: u64) -> String { + screen_of_dir(&bot_dir(bot_id)) +} + +/// A 支線's screen: a temporary one beside its main bot's (`bot12-t57`), so a branch and its main +/// line don't click on one screen. Its browser starts as a copy of the main bot's (the same +/// logins); screen and copy go when the branch ends (close_screen). "" off a bot's own screen. +pub fn branch_screen(main_key: &str, branch: u64) -> String { + if main_key.is_empty() || branch == 0 { + return String::new(); + } + format!("{main_key}-t{branch}") +} + +/// The bot a screen is (its own bot, or a 支線 for a temporary one): (bot, branch or 0). +pub fn bot_of_screen(key: &str) -> Option<(u64, u64)> { + let rest = key.strip_prefix("bot")?; + let (own, branch) = match rest.split_once("-t") { + Some((a, b)) => (a, b.parse().ok()?), + None => (rest, 0), + }; + Some((own.parse().ok()?, branch)) +} + +/// Close `key`'s screen now (its browser too; a 支線's temporary browser profile goes with it). +pub fn close_screen(key: &str) { + if key.is_empty() || !key.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') { + return; + } + if run_state().is_running() { + let _ = dk_timeout(&["exec", "-u", "bot", container(), "sh", "-c", &format!("command -v anybot-screen >/dev/null && anybot-screen down {key}")], 10_000); + } + screens().lock().unwrap_or_else(|e| e.into_inner()).remove(key); +} + +fn current_screen() -> String { + ON_SCREEN.with(|s| s.borrow().clone()) +} + +/// Run `f` with `key`'s screen as the current one (the box's steps, looks and browser go there). +pub fn on_screen(key: &str, f: impl FnOnce() -> T) -> T { + let before = ON_SCREEN.with(|s| std::mem::replace(&mut *s.borrow_mut(), key.to_string())); + let out = f(); + ON_SCREEN.with(|s| *s.borrow_mut() = before); + out +} + +/// A screen's name in file names and viewer tokens: its key, or "main" for the shared one. +fn screen_tag(key: &str) -> &str { + if key.is_empty() { "main" } else { key } +} + +/// Shell lines that put what follows on `key`'s screen: made there when it isn't open (exit 3 and +/// the screens in use when the box is full). A box from before screens (no anybot-screen) and the +/// shared screen use :1. +fn screen_sh(key: &str) -> String { + if key.is_empty() { + return "export DISPLAY=:1;".into(); + } + 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;") +} + +/// 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. +fn bot_screens() -> &'static Mutex> { + static M: OnceLock>> = OnceLock::new(); + M.get_or_init(|| Mutex::new(std::collections::HashMap::new())) +} + +pub fn set_bot_screens(map: std::collections::HashMap) { + *bot_screens().lock().unwrap_or_else(|e| e.into_inner()) = map; +} + +/// The screen to show for `bot` (an id from a viewer's request; "" the shared one). +pub fn screen_for_bot(bot: &str) -> String { + let id: u64 = bot.trim().parse().unwrap_or(0); + bot_screens().lock().unwrap_or_else(|e| e.into_inner()).get(&id).cloned().unwrap_or_default() +} + +/// What a step that couldn't get its screen is told. +fn screen_full(err: &str) -> Option { + let keys = err.lines().find_map(|l| l.trim().strip_prefix("FULL="))?; + Some(format!("Bot 的電腦同時開的螢幕已經滿了({} 個,都有 Bot 在用)。先做不用螢幕的部分(指令、檔案),或晚一點再試;閒置 10 分鐘的螢幕會自己關掉。", keys.split_whitespace().count())) +} + +/// What one screen remembers between its steps. +#[derive(Default)] +struct ScreenState { + /// The numbered controls of its latest look (centres in desktop pixels). + spots: Option, + /// The latest look's fingerprint (to say when a step changed nothing). + last: Option, + /// Numbers kept from look to look where the same control is still there. + numbers: Option, + /// The latest look's controls (what moved since). + els: Vec, + /// Its size in pixels. + size: Option<(u32, u32)>, + /// Its browser's DevTools port in the box, and when the screen was last marked used. + cdp: Option, + touched: Option, +} + +fn screens() -> &'static Mutex> { + static S: OnceLock>> = OnceLock::new(); + S.get_or_init(|| Mutex::new(std::collections::HashMap::new())) +} + +/// The current screen's memory. +fn with_screen(f: impl FnOnce(&mut ScreenState) -> T) -> T { + let key = current_screen(); + let mut all = screens().lock().unwrap_or_else(|e| e.into_inner()); + f(all.entry(key).or_default()) +} + +/// The screens a person took over (their keys; "" the shared one): those bots' steps wait. +fn held() -> &'static Mutex> { + static H: OnceLock>> = OnceLock::new(); + H.get_or_init(|| Mutex::new(Default::default())) +} + +/// A person takes over (or gives back) `key`'s screen. +pub fn hold(key: &str, on: bool) { + let mut h = held().lock().unwrap_or_else(|e| e.into_inner()); + if on { + h.insert(key.to_string()); + } else { + h.remove(key); + } + HELD_BY_PERSON.store(!h.is_empty(), Ordering::SeqCst); +} + +fn is_held(key: &str) -> bool { + held().lock().unwrap_or_else(|e| e.into_inner()).contains(key) +} /// AT-SPI roles as words. fn role_words(role: &str) -> String { @@ -2182,19 +2414,23 @@ fn box_look(script: Option<&str>, after: Option, pointer: bool) -> Resul let t_all = Instant::now(); // The picture is captured by a background `import` while the controls are read (the a11y // read is the slow part on web pages); a JPEG costs less to make and to ship than a PNG. - let look = "( import -window root -quality 90 jpeg:- 2>/dev/null > /tmp/anybot-look.jpg & ip=$!; \ - sleep 0.18; anybot-a11y --budget 3 > /tmp/anybot-look.json 2>/dev/null || echo '{\"elements\":[]}' > /tmp/anybot-look.json; \ + let key = current_screen(); + let tag = screen_tag(&key); + let look = format!( + "( import -window root -quality 90 jpeg:- 2>/dev/null > /tmp/anybot-look-{tag}.jpg & ip=$!; \ + sleep 0.18; anybot-a11y --budget 3 > /tmp/anybot-look-{tag}.json 2>/dev/null || echo '{{\"elements\":[]}}' > /tmp/anybot-look-{tag}.json; \ printf '%s\\n' \"$(xdotool getactivewindow getwindowname 2>/dev/null | tr -d '\\n')\"; \ - wc -c < /tmp/anybot-look.json; cat /tmp/anybot-look.json; wait $ip; cat /tmp/anybot-look.jpg )"; + wc -c < /tmp/anybot-look-{tag}.json; cat /tmp/anybot-look-{tag}.json; wait $ip; cat /tmp/anybot-look-{tag}.jpg )" + ); let full = match script { - Some(s) => format!("{{ {s}; }} || exit $?; {SETTLE_SH}; {look}"), - None => look.to_string(), + Some(s) => format!("{} {{ {s}; }} || exit $?; {SETTLE_SH}; {look}", screen_sh(&key)), + None => format!("{} {look}", screen_sh(&key)), }; let out = match dk_with_input(&["exec", "-i", "-u", "bot", "-e", "DISPLAY=:1", container(), "sh", "-c", &full], Some(b""), 30_000) { Ok(o) => o, Err(e) if e == "逾時" => return Err("這台電腦太久沒有回應".into()), Err(e) if e.is_empty() => return Err("這一步沒有成功".into()), - Err(e) => return Err(format!("xdotool:{e}")), + Err(e) => return Err(screen_full(&e).unwrap_or_else(|| format!("xdotool:{e}"))), }; let exec_ms = t_all.elapsed().as_millis() as u64; // "\n\n" @@ -2207,20 +2443,17 @@ fn box_look(script: Option<&str>, after: Option, pointer: bool) -> Resul let tree: Value = serde_json::from_slice(&out[nl + 1..json_end]).unwrap_or(Value::Null); let img = image::load_from_memory(&out[json_end..]).map_err(|e| format!("截圖讀不出來:{e}"))?.to_rgb8(); let (w, h) = img.dimensions(); - shared().lock().unwrap_or_else(|e| e.into_inner()).size = Some((w, h)); + with_screen(|st| st.size = Some((w, h))); // The window in front comes first (its controls numbered first, never crowded out by a // window left open behind it), like a person looks at what's in front of them. let mut els = elements_of(&tree); if !front.is_empty() { els.sort_by_key(|e| e.window != front); } - // Numbers kept from the last look where the same control is still there (marks::Numbering). - static NUMBERS: Mutex> = Mutex::new(None); - let (numbered, lines, spots) = { - let mut m = NUMBERS.lock().unwrap_or_else(|e| e.into_inner()); - crate::marks::number_keeping(&els, false, m.get_or_insert_with(Default::default)) - }; - *BOX_SPOTS.lock().unwrap_or_else(|e| e.into_inner()) = Some(spots); + // Numbers kept from the last look where the same control is still there (marks::Numbering), + // each screen its own. + let (numbered, lines, spots) = with_screen(|st| crate::marks::number_keeping(&els, false, st.numbers.get_or_insert_with(Default::default))); + with_screen(|st| st.spots = Some(spots)); let (fw, fh, resize) = crate::computer::fit(w, h); let mut pic = if resize { image::imageops::resize(&img, fw, fh, image::imageops::FilterType::Triangle) } else { img }; let fp = crate::marks::fingerprint(&els) ^ crate::marks::picture_fingerprint(&pic).rotate_left(1); @@ -2236,12 +2469,11 @@ fn box_look(script: Option<&str>, after: Option, pointer: bool) -> Resul let mut text = after.clone().map(|n| format!("{n}\n")).unwrap_or_default(); text.push_str(&secret_note); text.push_str(&format!("螢幕截圖({fw}×{fh},Linux 桌面)。")); - let unchanged = { - let mut last = BOX_LAST.lock().unwrap_or_else(|e| e.into_inner()); - let same = pointer && after.is_some() && *last == Some(fp); - *last = Some(fp); + let unchanged = with_screen(|st| { + let same = pointer && after.is_some() && st.last == Some(fp); + st.last = Some(fp); same - }; + }); if unchanged { text.push_str(crate::computer::NOOP_NOTE); } @@ -2251,12 +2483,13 @@ fn box_look(script: Option<&str>, after: Option, pointer: bool) -> Resul text.push_str(&format!("\n可以操作的東西(圖上同樣的編號,用 ref 點):\n{}", lines.join("\n"))); } // What moved since the last look (same signal the Mac path gives the quick model). - static LAST_ELS: Mutex> = Mutex::new(Vec::new()); { let cur: Vec = numbered.iter().map(|(_, e)| e.clone()).collect(); - let mut last = LAST_ELS.lock().unwrap_or_else(|e| e.into_inner()); - let d = crate::marks::diff(&last, &cur); - *last = cur; + let d = with_screen(|st| { + let d = crate::marks::diff(&st.els, &cur); + st.els = cur; + d + }); if !d.is_empty() { text.push_str(&format!("\n跟上一張圖相比:\n{}", d.join("\n"))); } @@ -2329,14 +2562,19 @@ fn open_on_box(app: &str) -> Result { /// Run a computer_use tool on the box. Returns (text, screenshot as base64 JPEG). /// One screen step on the box at a time: two bots acting at once shared the picture files and the /// numbers (a torn picture, or a number resolved against the other bot's picture). -static BOX_STEP: Mutex<()> = Mutex::new(()); +/// Each screen its own: bots on their own screens don't wait for each other. +fn step_lock() -> std::sync::Arc> { + static L: OnceLock>>>> = OnceLock::new(); + L.get_or_init(|| Mutex::new(std::collections::HashMap::new())).lock().unwrap_or_else(|e| e.into_inner()).entry(current_screen()).or_default().clone() +} pub fn computer_run(name: &str, v: &Value) -> Result<(String, Option), String> { - let _one = BOX_STEP.lock().unwrap_or_else(|e| e.into_inner()); + let lock = step_lock(); + let _one = lock.lock().unwrap_or_else(|e| e.into_inner()); // A control named instead of numbered (「按 4」): its number in the latest look. let mut named = v.clone(); if matches!(name, "computer_use_click" | "computer_use_typing" | "computer_use_scroll" | "computer_use_mouse_move" | "computer_use_batch") { - let spots = BOX_SPOTS.lock().unwrap_or_else(|e| e.into_inner()).clone(); + let spots = with_screen(|st| st.spots.clone()); crate::marks::names_to_numbers(&mut named, spots.as_ref())?; } let v = &named; @@ -2346,14 +2584,15 @@ pub fn computer_run(name: &str, v: &Value) -> Result<(String, Option), S "computer_use_check_permissions" => return Ok(("這台電腦不需要另外的權限:可以截圖,也可以操作滑鼠和鍵盤。".into(), None)), "computer_use_screenshot" => return box_look(None, None, false), "computer_use_zoom" => { - let out = dk_with_input(&["exec", "-i", "-u", "bot", "-e", "DISPLAY=:1", container(), "sh", "-c", "import -window root png:- 2>/dev/null"], Some(b""), 30_000).map_err(|e| format!("拍不到畫面:{e}"))?; + let shot = format!("{} import -window root png:- 2>/dev/null", screen_sh(¤t_screen())); + let out = dk_with_input(&["exec", "-i", "-u", "bot", "-e", "DISPLAY=:1", container(), "sh", "-c", &shot], Some(b""), 30_000).map_err(|e| format!("拍不到畫面:{e}"))?; let img = image::load_from_memory(&out).map_err(|e| format!("截圖讀不出來:{e}"))?.to_rgb8(); return crate::computer::zoom(&img, v).map(|(t, j)| (t, Some(j))); } "computer_use_show" => return box_show(), _ => {} } - if HELD_BY_PERSON.load(Ordering::SeqCst) || crate::vnc::person_active() { + if is_held(¤t_screen()) || crate::vnc::person_active() { return Err("使用者正在自己操作這台電腦。請等他操作完(停下幾秒後)再繼續,或先截圖看看畫面。".into()); } if name == "computer_use_open_app" { @@ -2369,7 +2608,8 @@ pub fn computer_run(name: &str, v: &Value) -> Result<(String, Option), S /// The box's screen as the person would see it (no numbers), at the bot's picture size. fn box_show() -> Result<(String, Option), String> { - let out = dk_with_input(&["exec", "-i", "-u", "bot", "-e", "DISPLAY=:1", container(), "sh", "-c", "import -window root -quality 90 jpeg:- 2>/dev/null"], Some(b""), 30_000).map_err(|e| format!("拍不到畫面:{e}"))?; + let shot = format!("{} import -window root -quality 90 jpeg:- 2>/dev/null", screen_sh(¤t_screen())); + let out = dk_with_input(&["exec", "-i", "-u", "bot", "-e", "DISPLAY=:1", container(), "sh", "-c", &shot], Some(b""), 30_000).map_err(|e| format!("拍不到畫面:{e}"))?; let img = image::load_from_memory(&out).map_err(|e| format!("截圖讀不出來:{e}"))?.to_rgb8(); let (w, h) = img.dimensions(); let (fw, fh, resize) = crate::computer::fit(w, h); @@ -2378,7 +2618,10 @@ fn box_show() -> Result<(String, Option), String> { Ok((format!("{}({fw}×{fh})", crate::computer::SHOWN_NOTE), Some(base64::engine::general_purpose::STANDARD.encode(&jpeg)))) } -const BATCH_MARK: &str = "/tmp/anybot-batch.done"; +/// Where a batch counts its steps (one file per screen). +fn batch_mark() -> String { + format!("/tmp/anybot-batch-{}.done", screen_tag(¤t_screen())) +} /// Do a planned sequence of steps on the box in one round trip: the steps' scripts chained with /// `&&` (so the chain stops at the first failure), one marker line per step that ran, and one @@ -2397,13 +2640,14 @@ fn box_batch(v: &Value, scale: (f64, f64)) -> Result<(String, Option), S for (i, a) in acts.iter().enumerate() { let name = crate::computer::action_tool(a["action"].as_str().unwrap_or(""))?; let (script, note) = box_script(name, a, scale)?; - parts.push(format!("{{ {script} && echo x >> {BATCH_MARK}; }}")); + parts.push(format!("{{ {script} && echo x >> {}; }}", batch_mark())); notes.push(format!("{}. {note}", i + 1)); } // The chain runs in the same call as the picture; one more call reads how far it got. - let chain = format!("rm -f {BATCH_MARK}; {} ; true", parts.join(" && ")); + let mark = batch_mark(); + let chain = format!("rm -f {mark}; {} ; true", parts.join(" && ")); let (text, pic) = box_look(Some(&chain), Some(String::new()), false)?; - let done = dk(&["exec", container(), "sh", "-c", &format!("wc -l < {BATCH_MARK} 2>/dev/null || echo 0; rm -f {BATCH_MARK}")]) + let done = dk(&["exec", container(), "sh", "-c", &format!("wc -l < {mark} 2>/dev/null || echo 0; rm -f {mark}")]) .ok() .and_then(|s| s.trim().parse::().ok()) .unwrap_or(0) @@ -2509,6 +2753,11 @@ fn published_port() -> u16 { /// The noVNC address on this Mac (through an SSH tunnel when the box is on another host). pub fn viewer_url(control: bool) -> Result { + viewer_url_of("", control) +} + +/// The same, showing `key`'s screen (its own, 每個 Bot 一個螢幕; "" the shared one). +pub fn viewer_url_of(key: &str, control: bool) -> Result { ensure_running()?; let port = published_port(); let host = docker_host(); @@ -2541,7 +2790,9 @@ pub fn viewer_url(control: bool) -> Result { port }; // noVNC signs in with the box's VNC password (x11vnc refuses the keyless login now). - Ok(format!("http://127.0.0.1:{local_port}/vnc.html?autoconnect=1&resize=scale&reconnect=1&show_dot=1&password={}{}", vnc_password(), if control { "" } else { "&view_only=1" })) + // The box's one web viewer reaches every screen by its token (box/start.sh, box/screen). + let token = crate::httpd::url_encode(&format!("websockify?token={}", screen_tag(key))); + Ok(format!("http://127.0.0.1:{local_port}/vnc.html?autoconnect=1&resize=scale&reconnect=1&show_dot=1&password={}{}&path={token}", vnc_password(), if control { "" } else { "&view_only=1" })) } pub fn shutdown() { @@ -2586,7 +2837,7 @@ mod tests { // What the box runs: the field clicked, its text selected, the address pasted in one go. let els = vec![crate::marks::Element { kind: "輸入框".into(), name: "Address and search bar".into(), value: "about:blank".into(), x: 100.0, y: 50.0, w: 400.0, h: 30.0, active: true, flags: vec![], window: "Chromium".into() }]; let (_, _, spots) = crate::marks::number_keeping(&els, false, &mut Default::default()); - *BOX_SPOTS.lock().unwrap() = Some(spots); + with_screen(|st| st.spots = Some(spots)); let (script, _) = box_script("computer_use_typing", &serde_json::json!({"ref": "1", "value": "chrome://settings/search", "submit": true}), (1.0, 1.0)).unwrap(); assert!(script.contains("click 1") && script.contains("ctrl+a") && script.contains("xclip") && script.contains("ctrl+v") && !script.contains("xdotool type"), "{script}"); } @@ -2642,7 +2893,10 @@ mod tests { assert!(sc.starts_with(r"xdotool type --clearmodifiers --delay 12 -- 'it'\''s a '\''test'\'''") && sc.ends_with("xdotool key --clearmodifiers Return"), "{sc}"); // Another language, or long text: pasted (key by key, 2,000 letters outlasted the step). let (sc, _) = box_script("computer_use_typing", &serde_json::json!({"value": "中文"}), s).unwrap(); - assert!(sc.contains("printf '%s' '中文' > /tmp/anybot-paste.txt") && sc.contains("xclip"), "{sc}"); + assert!(sc.contains("printf '%s' '中文' > /tmp/anybot-paste-main.txt") && sc.contains("xclip"), "{sc}"); + // Each screen pastes from its own file (two bots typing at once don't swap texts). + let (sc, _) = on_screen("bot9", || box_script("computer_use_typing", &serde_json::json!({"value": "中文"}), s)).unwrap(); + assert!(sc.contains("/tmp/anybot-paste-bot9.txt"), "{sc}"); let (sc, _) = box_script("computer_use_typing", &serde_json::json!({"value": "a".repeat(TYPE_KEYS_MAX_CHARS + 1)}), s).unwrap(); assert!(sc.contains("xclip") && !sc.contains("xdotool type"), "{sc}"); // Keys by name, a character typed (without swallowing the keys after it), several in order. @@ -2754,7 +3008,7 @@ mod tests { std::thread::sleep(Duration::from_millis(500)); let page_spots = || -> Vec<(f64, f64, String)> { computer_run("computer_use_screenshot", &serde_json::json!({})).unwrap(); - let spots = BOX_SPOTS.lock().unwrap().clone().unwrap(); + let spots = with_screen(|st| st.spots.clone()).unwrap(); spots.by_number.values().filter(|(_, w)| w.contains("「L")).map(|((x, y), w)| (*x, *y, w.clone())).collect() }; let top = crate::botbrowser::in_box(|| crate::botbrowser::eval_current(None, "window.outerHeight - window.innerHeight")).map(|(_, v)| v.as_f64().unwrap_or(87.0)).unwrap_or(87.0); @@ -2778,6 +3032,76 @@ mod tests { println!("page links numbered: {} in view, {} with a terminal over the page (top of page area {top})", seen.len(), covered.len()); } + /// 每個 Bot 一個螢幕, on the real Docker (a box of its own: ANYBOT_BOX_NAME, ANYBOT_BOX_IMAGE, + /// ANYBOT_BOX_VOLUME and a scratch ANYBOT_DATA_DIR, so a box in use isn't touched): + /// `cargo test -- --ignored each_bot_has_its_own_screen --nocapture`. + /// Two bots open a terminal each, at once: each sees only its own; each one's typing lands in + /// its own; their browsers are two (two ports), the second bot's starting with the shared + /// logins; the viewer and the thumbnails reach each screen; a full box says so; idle closes. + #[test] + #[ignore] + fn each_bot_has_its_own_screen() { + ensure_running().expect("box starts"); + let titles = |key: &str| -> String { + on_screen(key, || box_exec("for w in $(xdotool search --onlyvisible --name . 2>/dev/null); do xdotool getwindowname $w; done | sort -u")).unwrap() + }; + // Two bots at once, each a terminal titled with its name (a plain shell keeps the title). + let (a, b) = ("bot901", "bot902"); + let one = std::thread::spawn(move || on_screen(a, || box_exec("(setsid xterm -T term-alpha -e bash --norc >/dev/null 2>&1 &); sleep 2; echo ok"))); + let two = std::thread::spawn(move || on_screen(b, || box_exec("(setsid xterm -T term-beta -e bash --norc >/dev/null 2>&1 &); sleep 2; echo ok"))); + assert!(one.join().unwrap().is_ok() && two.join().unwrap().is_ok()); + let (ta, tb) = (titles(a), titles(b)); + println!("bot901 sees: {ta:?}\nbot902 sees: {tb:?}"); + assert!(ta.contains("term-alpha") && !ta.contains("term-beta"), "{ta}"); + assert!(tb.contains("term-beta") && !tb.contains("term-alpha"), "{tb}"); + assert!(!titles("").contains("term-alpha"), "the shared screen has neither"); + // Each bot's look: its own numbers, each screen's own picture. + let (la, pa) = on_screen(a, || computer_run("computer_use_screenshot", &serde_json::json!({}))).unwrap(); + let (_, pb) = on_screen(b, || computer_run("computer_use_screenshot", &serde_json::json!({}))).unwrap(); + assert!(pa.is_some() && pb.is_some() && pa != pb, "two pictures"); + println!("bot901's look:\n{}", la.lines().take(6).collect::>().join("\n")); + // Typing goes to the bot's own terminal. + let _ = dk(&["exec", "-u", "bot", container(), "rm", "-f", "/tmp/screen-a.txt", "/tmp/screen-b.txt"]); + on_screen(a, || computer_run("computer_use_typing", &serde_json::json!({"value": "echo A > /tmp/screen-a.txt", "submit": true}))).unwrap(); + on_screen(b, || computer_run("computer_use_typing", &serde_json::json!({"value": "echo B > /tmp/screen-b.txt", "submit": true}))).unwrap(); + std::thread::sleep(Duration::from_millis(800)); + let got = dk(&["exec", "-u", "bot", container(), "sh", "-c", "cat /tmp/screen-a.txt /tmp/screen-b.txt"]).unwrap(); + assert_eq!(got.split_whitespace().collect::>(), vec!["A", "B"]); + // Two browsers, two ports; each on its own screen. + let pa = on_screen(a, browser_port).expect("bot901's browser"); + let pb = on_screen(b, browser_port).expect("bot902's browser"); + assert_ne!(pa, pb, "each bot its own browser"); + assert!(on_screen(a, browser_running) && on_screen(b, browser_running)); + assert!(titles(a).to_lowercase().contains("chromium") || titles(a).contains("about:blank"), "{}", titles(a)); + // The viewer reaches each screen by its token; thumbnails too. + let tokens = dk(&["exec", container(), "cat", "/tmp/anybot-vnc-tokens"]).unwrap(); + assert!(tokens.contains("main: localhost:5900") && tokens.contains("bot901: localhost:") && tokens.contains("bot902: localhost:"), "{tokens}"); + assert!(viewer_url_of(a, false).unwrap().contains("token%3Dbot901")); + assert!(thumbnail_of(a, 320).is_some() && thumbnail_of("bot999", 320).is_none()); + let open: Vec = open_screens().into_iter().map(|(k, _)| k).collect(); + assert!(open.contains(&a.to_string()) && open.contains(&b.to_string()), "{open:?}"); + // A 支線 beside bot901: a temporary screen of its own whose browser starts as a copy of + // bot901's (what bot901's profile has, the branch's has), and is gone with the screen. + let _ = dk(&["exec", "-u", "bot", container(), "sh", "-c", "mkdir -p '/home/bot/.config/anybot-profiles/bot901/Default/Local Storage' && echo yes > '/home/bot/.config/anybot-profiles/bot901/Default/Local Storage/anybot-branch-mark'"]); + let t = branch_screen(a, 57); + assert_eq!(t, "bot901-t57"); + let pt = on_screen(&t, browser_port).expect("the branch's browser"); + assert_ne!(Some(pt), on_screen(a, browser_port).ok()); + let copied = dk(&["exec", "-u", "bot", container(), "sh", "-c", "cat '/home/bot/.config/anybot-profiles/bot901-t57/Default/Local Storage/anybot-branch-mark'"]).unwrap_or_default(); + assert_eq!(copied.trim(), "yes", "the branch's browser starts from bot901's"); + assert!(titles(&t).to_lowercase().contains("chromium") || titles(&t).contains("about:blank"), "{}", titles(&t)); + assert!(!titles(a).contains("term-beta")); + close_screen(&t); + let left = dk(&["exec", container(), "sh", "-c", "ls /home/bot/.config/anybot-profiles"]).unwrap(); + assert!(left.contains("bot901") && !left.contains("bot901-t57"), "the copy goes with the screen: {left}"); + assert!(!open_screens().iter().any(|(k, _)| *k == t)); + // Idle: closed (the browser too). + reap_screens(0); + assert!(open_screens().is_empty(), "{:?}", open_screens()); + assert!(!titles("").contains("term-beta")); + println!("each bot had its own screen; idle ones closed"); + } + /// Uses the real Docker: `cargo test --release -- --ignored box_screen_is_exact --nocapture`. /// The bot's clicks land where its picture says, the same spot twice doesn't hang, typing (ASCII, Chinese, a key by name) reaches the app, /// and every step comes back with the screen after it. @@ -2794,7 +3118,7 @@ mod tests { let (fw, fh, _) = crate::computer::fit(w, h); println!("desktop {w}×{h}, picture {fw}×{fh}"); // A move, in the bot's picture pixels, with no screenshot taken first. - shared().lock().unwrap().size = None; + with_screen(|st| st.size = None); let (txt, img) = computer_run("computer_use_mouse_move", &serde_json::json!({"x": fw / 2, "y": fh / 2})).unwrap(); assert!(img.is_some(), "a picture comes back: {txt}"); assert_eq!(pointer(), ((w / 2) as i64, (h / 2) as i64)); @@ -3099,7 +3423,37 @@ 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(), "9"); + assert_eq!(wanted_version(), "10"); + // Every file the Dockerfile copies is one this app carries (build_image writes them). + let carried = ["start.sh", "fluxbox-init", "overlay", "Xresources", "menu", "a11y", "browser", "screen"]; + for l in DOCKERFILE.lines().filter_map(|l| l.trim().strip_prefix("COPY ")) { + let src = l.split_whitespace().next().unwrap(); + assert!(carried.contains(&src), "the Dockerfile copies {src}, which build_image doesn't write"); + } + // 每個 Bot 一個螢幕: a bot's folder names its screen; any other folder is the shared one. + assert_eq!(screen_of_dir("/home/bot/bot-12"), "bot12"); + assert_eq!(screen_of_dir("/home/bot/bot-12/"), "bot12"); + assert_eq!(screen_of_bot(7), "bot7"); + 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")); + assert!(screen_full("FULL=bot1 bot2 bot3").unwrap().contains("3 個")); + assert!(screen_full("xdotool: oops").is_none()); + // Each screen remembers its own numbers. + on_screen("bot1", || with_screen(|st| st.last = Some(1))); + on_screen("bot2", || with_screen(|st| st.last = Some(2))); + assert_eq!(on_screen("bot1", || with_screen(|st| st.last)), Some(1)); + assert_eq!(current_screen(), ""); + // A person holding one bot's screen doesn't stop the others. + hold("bot1", true); + assert!(is_held("bot1") && !is_held("bot2") && HELD_BY_PERSON.load(Ordering::SeqCst)); + hold("bot1", false); + assert!(!is_held("bot1") && !HELD_BY_PERSON.load(Ordering::SeqCst)); + // What viewers name (a bot) maps to the screen the brain published. + set_bot_screens([(5u64, "bot5".to_string())].into_iter().collect()); + assert_eq!(screen_for_bot("5"), "bot5"); + assert_eq!(screen_for_bot("6"), ""); + assert_eq!(screen_for_bot("x"), ""); } #[test] diff --git a/src/remote.rs b/src/remote.rs index 0983ba7..e168887 100644 --- a/src/remote.rs +++ b/src/remote.rs @@ -775,7 +775,8 @@ pub fn handle(req: Req, via_relay: bool) -> Resp { ("POST", ["api", "sync", "upload", id]) => upload(id.parse().unwrap_or(0), &req), // A screen of this brain shows the bots' own computer, which lives here: a small picture // (people watch it live through VNC, see vnc.rs). - ("GET", ["api", "sync", "screen"]) => match crate::cloudbox::thumbnail(320) { + // (Of the bot the screen asks about: its own screen when it has one open.) + ("GET", ["api", "sync", "screen"]) => match crate::cloudbox::thumbnail_of(&crate::cloudbox::screen_for_bot(req.query.get("bot").map(String::as_str).unwrap_or("")), 320).or_else(|| crate::cloudbox::thumbnail(320)) { Some(img) => match crate::computer::encode_jpeg(&image::DynamicImage::ImageRgba8(img).to_rgb8()) { Some(j) => Resp::bytes("image/jpeg", j), None => Resp::error(500, "畫面編碼失敗"), @@ -787,7 +788,8 @@ pub fn handle(req: Req, via_relay: bool) -> Resp { let v = req.json(); match v["kind"].as_str().unwrap_or("") { "hold" => { - crate::cloudbox::HELD_BY_PERSON.store(v["on"].as_bool().unwrap_or(false), Ordering::SeqCst); + let bot = v["bot"].as_u64().map(|b| b.to_string()).unwrap_or_default(); + crate::cloudbox::hold(&crate::cloudbox::screen_for_bot(&bot), v["on"].as_bool().unwrap_or(false)); Resp::json(&json!({"ok": true})) } "wake" => match crate::cloudbox::ensure_running() { @@ -1553,7 +1555,8 @@ fn lan_vnc(req: Req, mut c: std::net::TcpStream, gen: u64) { let mut ws = WebSocket::from_raw_socket(c, Role::Server, Some(cfg)); let (tx, rx) = std::sync::mpsc::channel::>(); let send = move |b: &[u8]| tx.send(b.to_vec()).is_ok(); - let Ok(mut session) = crate::vnc::open(send.clone()) else { return }; + let screen = crate::cloudbox::screen_for_bot(req.query.get("bot").map(String::as_str).unwrap_or("")); + let Ok(mut session) = crate::vnc::open_on(&screen, send.clone()) else { return }; if !send(crate::vnc::GREETING) { return; } @@ -2071,8 +2074,8 @@ pub fn sync_voice_voices(s: &Settings) -> Result, String> } /// The brain's bots' computer as a JPEG (`thumb`: the small picture that never wakes it). -pub fn sync_screen(s: &Settings, thumb: bool) -> Result, String> { - let (st, bytes) = to_brain_raw(s, "GET", "/screen", &[("thumb", if thumb { "1" } else { "0" }.to_string())], &[], 30)?; +pub fn sync_screen(s: &Settings, thumb: bool, bot: u64) -> Result, String> { + let (st, bytes) = to_brain_raw(s, "GET", "/screen", &[("thumb", if thumb { "1" } else { "0" }.to_string()), ("bot", bot.to_string())], &[], 30)?; if !(200..300).contains(&st) { return Err(why_refused(st, &serde_json::from_slice(&bytes).unwrap_or(Value::Null), "大腦")); } diff --git a/src/tunnel.rs b/src/tunnel.rs index 708db7a..88fafeb 100644 --- a/src/tunnel.rs +++ b/src/tunnel.rs @@ -333,7 +333,7 @@ fn streams() -> &'static Mutex> { S.get_or_init(Default::default) } -fn on_stream(kind: &str, sid: String, body: Vec, tx: &Sender>) { +fn on_stream(kind: &str, sid: String, bot: String, body: Vec, tx: &Sender>) { let send = { let (tx, sid) = (tx.clone(), sid.clone()); move |b: &[u8]| tx.send(wire::pack(&json!({"t": "vdata", "sid": sid}), b)).is_ok() @@ -352,7 +352,10 @@ fn on_stream(kind: &str, sid: String, body: Vec, tx: &Sender>) { let (send, close) = (send.clone(), close.clone()); move |b: &[u8]| if b.is_empty() { close("這台電腦的畫面關了"); false } else { send(b) } }; - match crate::vnc::open(out) { + // 每個 Bot 一個螢幕: the bot the viewer was opened for (an older account server + // names none: the shared screen). + let screen = crate::cloudbox::screen_for_bot(&bot); + match crate::vnc::open_on(&screen, out) { Ok(s) => { streams().lock().unwrap().insert(sid, s); // Only now: the viewer answers this at once. @@ -394,7 +397,7 @@ fn on_frame(head: Value, body: Vec, tx: &Sender>, calls: &Calls) { } let t = head["t"].as_str().unwrap_or(""); if matches!(t, "vopen" | "vdata" | "vtext" | "vclose") { - return on_stream(t, head["sid"].as_str().unwrap_or("").to_string(), body, tx); + return on_stream(t, head["sid"].as_str().unwrap_or("").to_string(), head["bot"].as_str().unwrap_or("").to_string(), body, tx); } match t { "job" => { diff --git a/src/vnc.rs b/src/vnc.rs index 0e02906..6b67475 100644 --- a/src/vnc.rs +++ b/src/vnc.rs @@ -24,8 +24,15 @@ 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). -const BRIDGE: &str = r#"import os,select,socket -s=socket.create_connection(('127.0.0.1',5900)) +const BRIDGE: &str = r#"import os,select,socket,sys +port=5900 +k=sys.argv[1] if len(sys.argv)>1 else '' +if k: + try: + for l in open('/tmp/anybot-screens/%s/env'%k): + if l.startswith('VNC_PORT='): port=int(l.split('=',1)[1]) + except OSError: pass +s=socket.create_connection(('127.0.0.1',port)) while True: r=select.select([s,0],[],[])[0] if s in r: @@ -77,13 +84,15 @@ pub struct Session { init: bool, } -/// Open a viewer's way to the box: 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 slice when the box's side ended). The caller then sends the viewer GREETING -/// (once it is ready for the viewer's answer). -pub fn open(out: impl Fn(&[u8]) -> bool + Send + 'static) -> Result { +/// 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 +/// slice when the box's side ended). The caller then sends the viewer GREETING (once it is ready +/// for the viewer's answer). +pub fn open_on(key: &str, out: impl Fn(&[u8]) -> bool + Send + 'static) -> Result { crate::cloudbox::ensure_running()?; - let mut child = crate::cloudbox::exec_piped(&["python3", "-c", BRIDGE])?; + 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 stdin = child.stdin.take().ok_or("連不上這台電腦的畫面")?; let mut stdout = child.stdout.take().ok_or("連不上這台電腦的畫面")?; let fail = |child: &mut Child, why: &str| -> String {