合併: 電腦版不再破版、通知用 AnyBot 的貓、手機網頁像 App、Bot 的電腦上傳圖片和看畫面不再斷線

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
王性驊 2026-11-16 00:06:17 +08:00
commit 21e14b46bb
27 changed files with 1057 additions and 107 deletions

2
Cargo.lock generated
View File

@ -367,6 +367,8 @@ dependencies = [
"libc", "libc",
"memmap2", "memmap2",
"mermaid-rs-renderer", "mermaid-rs-renderer",
"objc2 0.6.5",
"objc2-foundation 0.3.2",
"pdf-extract", "pdf-extract",
"portable-pty", "portable-pty",
"pulldown-cmark", "pulldown-cmark",

View File

@ -97,6 +97,10 @@ async-io = "2"
agent-desktop-macos = { git = "https://github.com/vercel-labs/agent-desktop", tag = "v1.1.0" } agent-desktop-macos = { git = "https://github.com/vercel-labs/agent-desktop", tag = "v1.1.0" }
# Typing by pasting (any input method, any language); already in the build through egui. # Typing by pasting (any input method, any language); already in the build through egui.
arboard = { version = "3.7", default-features = false } arboard = { version = "3.7", default-features = false }
# Banners from AnyBot.app itself (its own icon; a click opens that bot), not through osascript
# (Script Editor's icon, and a click opened Script Editor). Already in the build through egui.
objc2 = "0.6"
objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSString", "NSBundle", "NSUserNotification", "NSArray", "NSObject"] }
[target.'cfg(target_os = "windows")'.dependencies] [target.'cfg(target_os = "windows")'.dependencies]
# Copying text from a thread of its own (platform::copy_text); already in the build through egui. # Copying text from a thread of its own (platform::copy_text); already in the build through egui.

View File

@ -40,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. # 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 ENV DISPLAY=:1 SCREEN_SIZE=1280x800x24 GTK_MODULES=gail:atk-bridge GTK_A11Y=atspi GNOME_ACCESSIBILITY=1 NO_AT_BRIDGE=0
EXPOSE 6080 EXPOSE 6080
LABEL anybot.box.version="10" LABEL anybot.box.version="11"
ENTRYPOINT ["/usr/bin/tini", "--"] ENTRYPOINT ["/usr/bin/tini", "--"]
CMD ["/usr/local/bin/anybot-box-start"] CMD ["/usr/local/bin/anybot-box-start"]

View File

@ -107,6 +107,8 @@ up() {
done done
as_bot "DISPLAY=:$disp xrdb -nocpp -merge /home/bot/.Xresources" 2>/dev/null 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" as_bot "DISPLAY=:$disp DBUS_SESSION_BUS_ADDRESS=$bus setsid fluxbox >/dev/null 2>&1 & echo \$!" 8>&- >> "$d/pids"
# Copy and paste with the person's computer (as on the shared screen: start.sh).
as_bot "DISPLAY=:$disp setsid vncconfig -nowin >/dev/null 2>&1 & echo \$!" 8>&- >> "$d/pids"
xsetroot -display ":$disp" -solid '#2b2f36' xsetroot -display ":$disp" -solid '#2b2f36'
{ {
echo "DISPLAY=:$disp" echo "DISPLAY=:$disp"

View File

@ -5,6 +5,13 @@ mkdir -p /home/bot/.fluxbox /home/bot/Desktop && cp -n /etc/anybot/fluxbox-init
cp -n /etc/anybot/overlay /home/bot/.fluxbox/overlay 2>/dev/null cp -n /etc/anybot/overlay /home/bot/.fluxbox/overlay 2>/dev/null
cp -n /etc/anybot/Xresources /home/bot/.Xresources 2>/dev/null cp -n /etc/anybot/Xresources /home/bot/.Xresources 2>/dev/null
cp /etc/anybot/menu /home/bot/.fluxbox/menu 2>/dev/null cp /etc/anybot/menu /home/bot/.fluxbox/menu 2>/dev/null
# GTK's dialogs (a web page's 上傳檔案 in Chromium, e.g. Threads' 加入相片) with 取消 and 開啟 in a
# bar at the top, as on GNOME. Without GNOME's settings service GTK put them at the bottom of a
# file window taller than the screen, under the taskbar: a picture could be found but never sent.
GTKINI=/home/bot/.config/gtk-3.0/settings.ini
mkdir -p "${GTKINI%/*}"
grep -q '^\[Settings\]' "$GTKINI" 2>/dev/null || printf '[Settings]\n' >> "$GTKINI"
grep -q '^gtk-dialogs-use-header' "$GTKINI" || sed -i '/^\[Settings\]/a gtk-dialogs-use-header=true' "$GTKINI"
chown -R bot:bot /home/bot chown -R bot:bot /home/bot
rm -f /tmp/.X1-lock /tmp/.X11-unix/X1 rm -f /tmp/.X1-lock /tmp/.X11-unix/X1
# One TigerVNC server is the screen and the VNC server (was Xvfb + x11vnc, which polls the # One TigerVNC server is the screen and the VNC server (was Xvfb + x11vnc, which polls the
@ -39,15 +46,23 @@ for c in /usr/libexec/at-spi2-registryd /usr/lib/at-spi2-core/at-spi2-registryd;
[ -x "$c" ] && { su bot -c "DISPLAY=:1 DBUS_SESSION_BUS_ADDRESS=$DBUS_SESSION_BUS_ADDRESS $c >/tmp/atspi-registry.log 2>&1 &"; break; } [ -x "$c" ] && { su bot -c "DISPLAY=:1 DBUS_SESSION_BUS_ADDRESS=$DBUS_SESSION_BUS_ADDRESS $c >/tmp/atspi-registry.log 2>&1 &"; break; }
done done
su bot -c "DBUS_SESSION_BUS_ADDRESS=$DBUS_SESSION_BUS_ADDRESS gsettings set org.gnome.desktop.interface toolkit-accessibility true" 2>/dev/null || true su bot -c "DBUS_SESSION_BUS_ADDRESS=$DBUS_SESSION_BUS_ADDRESS gsettings set org.gnome.desktop.interface toolkit-accessibility true" 2>/dev/null || true
# The file window opens smaller than the screen, whatever size it was left at.
SW="${GEOM%x*}"; SH="${GEOM#*x}"
su bot -c "DBUS_SESSION_BUS_ADDRESS=$DBUS_SESSION_BUS_ADDRESS gsettings set org.gtk.Settings.FileChooser window-size '($((SW * 7 / 10)), $((SH * 3 / 4)))'" 2>/dev/null || true
su bot -c "DISPLAY=:1 DBUS_SESSION_BUS_ADDRESS=$DBUS_SESSION_BUS_ADDRESS xrdb -nocpp -merge /home/bot/.Xresources" su bot -c "DISPLAY=:1 DBUS_SESSION_BUS_ADDRESS=$DBUS_SESSION_BUS_ADDRESS xrdb -nocpp -merge /home/bot/.Xresources"
su bot -c "DISPLAY=:1 DBUS_SESSION_BUS_ADDRESS=$DBUS_SESSION_BUS_ADDRESS fluxbox >/tmp/fluxbox.log 2>&1 &" su bot -c "DISPLAY=:1 DBUS_SESSION_BUS_ADDRESS=$DBUS_SESSION_BUS_ADDRESS fluxbox >/tmp/fluxbox.log 2>&1 &"
# Copy and paste between the person's computer and this one: Xvnc hands the viewer's clipboard to
# the X selections (and back) only while vncconfig runs (after LazyBoy2's box).
su bot -c "DISPLAY=:1 vncconfig -nowin >/tmp/vncconfig.log 2>&1 &"
(sleep 1.5; xsetroot -display :1 -solid '#2b2f36') & (sleep 1.5; xsetroot -display :1 -solid '#2b2f36') &
xsetroot -display :1 -solid '#2b2f36' xsetroot -display :1 -solid '#2b2f36'
# One web viewer for every screen: the shared one is "main"; anybot-screen adds each bot's own # 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<key>. # (每個 Bot 一個螢幕). A viewer picks one with ?path=websockify%3Ftoken%3D<key>.
rm -rf /tmp/anybot-screens; mkdir -p /tmp/anybot-screens && chmod 1777 /tmp/anybot-screens 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 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 & # (A ping every 30 s: a proxy on the way — Tailscale serve, Caddy — doesn't drop a viewer that is
# only watching a still screen.)
websockify --heartbeat=30 --web /usr/share/novnc --token-plugin TokenFile --token-source /tmp/anybot-vnc-tokens 6080 >/tmp/novnc.log 2>&1 &
WEBSOCKIFY_PID=$! WEBSOCKIFY_PID=$!
# Say ready only once the viewer's port listens: the app opens noVNC on this flag, and a too # 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. # early file meant the first viewer load 404'd.

View File

@ -36,3 +36,4 @@ Bot 用 AnyBot 自己的瀏覽器上網、登入網站、點按、打字、送
- 雲端中繼資料位址永遠打不開;本機或內部網路的網址要使用者允許(直接操作模式除外)。 - 雲端中繼資料位址永遠打不開;本機或內部網路的網址要使用者允許(直接操作模式除外)。
- 發布關卡、已送帳本、送出後確認只管 AnyBot 自己的瀏覽器;用螢幕操作送出的,只能從步驟推算。頁面看不出回哪一篇時,只擋 24 小時內同一頁一模一樣的內容。 - 發布關卡、已送帳本、送出後確認只管 AnyBot 自己的瀏覽器;用螢幕操作送出的,只能從步驟推算。頁面看不出回哪一篇時,只擋 24 小時內同一頁一模一樣的內容。
- 送出後頁面上沒看到(例如從動態牆送出),結果寫「還沒確認」:不要因此再送一次,回原貼文看。 - 送出後頁面上沒看到(例如從動態牆送出),結果寫「還沒確認」:不要因此再送一次,回原貼文看。
- 網頁要上傳檔案(Threads、IG 加相片、表單附件):用 `upload` 直接放進頁面的檔案欄位。用螢幕去點「加入相片」會跳出 Bot 電腦的檔案視窗(「取消」「Open」在最上面),還要在裡面找檔案、按 Open。

View File

@ -29,7 +29,7 @@
## 怎麼操作 ## 怎麼操作
- Bot:要使用者做決定或補資料時用 `ask_person`(questions:question、options、multiple、default;已經知道的先填進 default),不要把一串問題寫成文字;查到航班、店家、天氣這類就用 `show_card`(kind、title、subtitle、rows、link);適合時用 `react`(emoji)按個表情;舊圖的摘要不夠(小字、精確數字)時用 `look_image`(index:0 是最新一張,附圖和截圖一起往回數;question 要具體)。 - Bot:要使用者做決定或補資料時用 `ask_person`(questions:question、options、multiple、default;已經知道的先填進 default),不要把一串問題寫成文字;查到航班、店家、天氣這類就用 `show_card`(kind、title、subtitle、rows、link);適合時用 `react`(emoji)按個表情;舊圖的摘要不夠(小字、精確數字)時用 `look_image`(index:0 是最新一張,附圖和截圖一起往回數;question 要具體)。
- 驗證:送一則要用工具的訊息,工作中再送一句,要看到「已排入…」,Bot 在同一輪回應那句;按停止,送出鈕變回來、Bot 不再動作;在最後一則回答的 ⋯ 按「重新產生」,再按「還原上一個答案」,舊答案要回來;請 Bot「用問題卡問我三件事」,卡片要一題一題走,按「略過」後 Bot 照自己的判斷繼續。自動測試:`cargo test agent::`、`cargo test ask::`、`cargo test app::chat_ui::`、`cargo test attach::`、`cargo test app::tests::`。 - 驗證:送一則要用工具的訊息,工作中再送一句,要看到「已排入…」,Bot 在同一輪回應那句;按停止,送出鈕變回來、Bot 不再動作;在最後一則回答的 ⋯ 按「重新產生」,再按「還原上一個答案」,舊答案要回來;請 Bot「用問題卡問我三件事」,卡片要一題一題走,按「略過」後 Bot 照自己的判斷繼續。自動測試:`cargo test agent::`、`cargo test ask::`、`cargo test app::chat_ui::`、`cargo test attach::`、`cargo test app::tests::`、`cargo test layout_audit::`(最窄的視窗裡允許卡片的按鈕會換行、「已排入…」和輸入框的提示不會被切掉)。
## 陷阱 ## 陷阱

View File

@ -32,6 +32,8 @@
- Bot 不能自己換電腦:工具指定了別台,但使用者最近三則訊息沒提到那台,這一步會被移回使用者選的那台,結果裡會說。真的要別台先問使用者。 - Bot 不能自己換電腦:工具指定了別台,但使用者最近三則訊息沒提到那台,這一步會被移回使用者選的那台,結果裡會說。真的要別台先問使用者。
- 使用者選的那台沒開機、或那台的 AnyBot 沒開沒登入,就不在清單上:Bot 先待在自己的電腦,`list_computers` 會寫那台「現在沒有連線」。 - 使用者選的那台沒開機、或那台的 AnyBot 沒開沒登入,就不在清單上:Bot 先待在自己的電腦,`list_computers` 會寫那台「現在沒有連線」。
- 在 Bot 自己的電腦上做事不用問,但它看不到使用者的檔案;檔案工具只碰得到自己的資料夾(大家共用同一台)。 - 在 Bot 自己的電腦上做事不用問,但它看不到使用者的檔案;檔案工具只碰得到自己的資料夾(大家共用同一台)。
- Bot 的電腦是精簡的 Linux 桌面(Debian + fluxbox):檔案視窗的「取消」「Open」在視窗最上面(第 11 版以前在最下面、被螢幕切掉,網頁上傳圖片選得到檔案卻送不出去——設定 › 電腦「更新 Bot 的電腦」換新版)。看畫面時可以跟自己的電腦互相複製貼上。
- 從帳號看 Bot 電腦的畫面,只要開著就不會斷;之前靜止畫面一分鐘、或看超過十分鐘會被帳號伺服器切掉,要更新帳號伺服器(make update-server)。
- 「在這台電腦上執行」設成永不允許(或被管理員鎖住)時,這台的檔案也不能傳出去、打開或發佈。 - 「在這台電腦上執行」設成永不允許(或被管理員鎖住)時,這台的檔案也不能傳出去、打開或發佈。
- SSH 電腦上的檔案不能直接傳到聊天、打開給使用者看或發佈網站,要先複製到 Bot 自己的電腦。 - SSH 電腦上的檔案不能直接傳到聊天、打開給使用者看或發佈網站,要先複製到 Bot 自己的電腦。
- 帳號裡的其他電腦:看畫面、操作畫面各自要使用者允許(可以一律允許);改檔案和指令照 SSH 電腦的規則問。 - 帳號裡的其他電腦:看畫面、操作畫面各自要使用者允許(可以一律允許);改檔案和指令照 SSH 電腦的規則問。

View File

@ -13,22 +13,26 @@
- 手機可以做什麼:聊天、核准、看 Bot 的電腦一律可以;「從手機看這台電腦的螢幕並操作」和「裝置連結」預設關閉。 - 手機可以做什麼:聊天、核准、看 Bot 的電腦一律可以;「從手機看這台電腦的螢幕並操作」和「裝置連結」預設關閉。
- 分享給團隊(登入後):把這台的 Bot 分享給帳號伺服器上的其他帳號,選成員或管理員([team](team.md))。 - 分享給團隊(登入後):把這台的 Bot 分享給帳號伺服器上的其他帳號,選成員或管理員([team](team.md))。
- 手機頁面:Bot 清單(分區、工作中/等你)、聊天(附檔、拍照、語音輸入、插話、停止)、允許請求卡片(「一律允許」「允許一次」或「允許」、「拒絕」、「全部允許,之後直接操作」)、問題卡、「需要處理」與接管、Bot 設定、例行任務(詳細頁有最近幾次執行和送出證據)、頁面、記憶、檔案預覽、Bot 的電腦畫面、設定、傳送到其他裝置。 - 手機頁面:Bot 清單(分區、工作中/等你)、聊天(附檔、拍照、語音輸入、插話、停止)、允許請求卡片(「一律允許」「允許一次」或「允許」、「拒絕」、「全部允許,之後直接操作」)、問題卡、「需要處理」與接管、Bot 設定、例行任務(詳細頁有最近幾次執行和送出證據)、頁面、記憶、檔案預覽、Bot 的電腦畫面、設定、傳送到其他裝置。
- 通知:需要你允許、問你、需要你處理,你不在時做完事,例行任務暫停,收到傳來的檔案——推播到開了通知的手機,點了直接打開那個 Bot。 - 通知:需要你允許、問你、需要你處理,你不在時做完事,例行任務暫停,收到傳來的檔案——推播到開了通知的手機,點了直接打開那個 Bot。每支手機自己選要哪幾種(需要你/做完了/例行任務暫停/收到傳來的檔案),可以送一則測試通知。通知的圖示是 AnyBot 的貓,Android 狀態列是貓的單色剪影;App 圖示上的數字是正在等你的 Bot。
- 像 App 一樣:加入主畫面後全螢幕、沒有網址列(瀏海、動態島、底部手勢條、橫放都避開);首頁會提示「把 AnyBot 裝成 App」(Android 直接安裝,iPhone 教你加入主畫面,可以關掉);換畫面會左右滑動;iPhone 主畫面 App 從左邊緣往右滑回上一頁。
## 使用者怎麼到 ## 使用者怎麼到
- 電腦:設定 › 一般 › 帳戶 ›「登入」(登入後是「管理帳戶」)打開「手機與帳號」頁,左上「‹ 一般」回去。由上到下:「手機與帳號」「AnyBot 帳號」、大腦(登入後)、「同一個網路直接連」「手機可以做什麼」「直接連線的裝置」「分享給團隊」「帳號裡的電腦」(最後兩個登入後才有)。 - 電腦:設定 › 一般 › 帳戶 ›「登入」(登入後是「管理帳戶」)打開「手機與帳號」頁,左上「‹ 一般」回去。由上到下:「手機與帳號」「AnyBot 帳號」、大腦(登入後)、「同一個網路直接連」「手機可以做什麼」「直接連線的裝置」「分享給團隊」「帳號裡的電腦」(最後兩個登入後才有)。
- 手機:打開帳號伺服器的網址用帳號登入;或打開設定頁列出的網址用手機密碼登入。可以「加入主畫面」當 App。 - 手機:打開帳號伺服器的網址用帳號登入;或打開設定頁列出的網址用手機密碼登入。可以「加入主畫面」當 App。
- 手機:左上角帳戶選單 ›「通知」(開關、要通知哪幾種、測試通知)、「安裝成 App」(還沒裝時才有)。
- 手機的 設定 › 手機與帳號:直接連線的手機;用帳號登入時另有通知、兩步驗證、登入的裝置、「加一台電腦」(擁有者)、「切換到別台 AnyBot」;最下面「登出這支手機」。 - 手機的 設定 › 手機與帳號:直接連線的手機;用帳號登入時另有通知、兩步驗證、登入的裝置、「加一台電腦」(擁有者)、「切換到別台 AnyBot」;最下面「登出這支手機」。
## 怎麼操作 ## 怎麼操作
- Bot:沒有登入、配對或改這一頁的工具。登入帳號後多兩個工具:`send_to_device`(把檔案傳到帳號裡另一台或「手機」)和 `publish_site`(發布成公開網站,見 [files](files.md));開了裝置連結的電腦會出現在它的電腦清單([computers](computers.md))。外面的訊息和團隊成員的訊息拿不到這兩個工具。 - Bot:沒有登入、配對或改這一頁的工具。登入帳號後多兩個工具:`send_to_device`(把檔案傳到帳號裡另一台或「手機」)和 `publish_site`(發布成公開網站,見 [files](files.md));開了裝置連結的電腦會出現在它的電腦清單([computers](computers.md))。外面的訊息和團隊成員的訊息拿不到這兩個工具。
- 驗證:設手機密碼、勾「讓手機直接連這台電腦」,用手機(或另一台的瀏覽器)打開列出的網址、信任憑證、輸入密碼,要看到 Bot 清單;叫 Bot 在你的電腦執行一個要核准的指令,手機出現允許卡片,在手機按「允許一次」(或「允許」)後電腦上的卡片也消失、步驟繼續;「直接連線的裝置」多一行,按「登出」後那支手機要重新登入。自動測試:`cargo test remote::`、`cargo test remote_ui::`、`cargo test httpd::`、`cargo test drops::`。 - 驗證:設手機密碼、勾「讓手機直接連這台電腦」,用手機(或另一台的瀏覽器)打開列出的網址、信任憑證、輸入密碼,要看到 Bot 清單;叫 Bot 在你的電腦執行一個要核准的指令,手機出現允許卡片,在手機按「允許一次」(或「允許」)後電腦上的卡片也消失、步驟繼續;用帳號登入的手機開通知、按「送一則測試通知」要跳出貓圖示的通知,關掉「做完了」後 Bot 做完不再推、需要你允許照樣推;「直接連線的裝置」多一行,按「登出」後那支手機要重新登入。自動測試:`cargo test remote::`、`cargo test remote_ui::`、`cargo test httpd::`、`cargo test drops::`;帳號伺服器的通知種類在 `relay/` 的 `cargo test`。
## 陷阱 ## 陷阱
- 推播只有用帳號登入的手機收得到,直接連線的沒有;iPhone 要先「加入主畫面」、從主畫面打開才開得了通知。 - 推播只有用帳號登入的手機收得到,直接連線的沒有(帳戶選單 ›「通知」會這樣說);iPhone 要先「加入主畫面」、從主畫面打開才開得了通知。
- 「要通知我的事」全部關掉,這支手機就收不到 Bot 的通知(測試通知照樣會到);通知被手機系統擋下時,開關是灰的,要到手機的設定 › 通知打開。
- App 圖示上的數字要手機支援(iPhone 主畫面 App、Android Chrome 安裝的 App);在瀏覽器分頁裡看不到。
- 電腦上的「Bot 做完或等你時通知」關掉,手機也收不到「需要你允許」「做完了」(例行任務暫停照樣推);而且只在你不在電腦前(視窗不在最前面,或 90 秒沒動)才推。 - 電腦上的「Bot 做完或等你時通知」關掉,手機也收不到「需要你允許」「做完了」(例行任務暫停照樣推);而且只在你不在電腦前(視窗不在最前面,或 90 秒沒動)才推。
- 直接連線的連接埠預設 8793,被占用會往後找;照設定頁列出的網址打開。不要把它開放到網際網路,從外面連用帳號或 Tailscale。 - 直接連線的連接埠預設 8793,被占用會往後找;照設定頁列出的網址打開。不要把它開放到網際網路,從外面連用帳號或 Tailscale。
- 第一次用 https 打開,手機會警告憑證:選「繼續」;要確認沒連錯台,比對設定頁上的 SHA-256 指紋。 - 第一次用 https 打開,手機會警告憑證:選「繼續」;要確認沒連錯台,比對設定頁上的 SHA-256 指紋。

View File

@ -8,7 +8,7 @@
- 「一般」: - 「一般」:
- 外觀:主題、聊天的顏色、字型、語言(選單和 Bot 回答用的語言)。 - 外觀:主題、聊天的顏色、字型、語言(選單和 Bot 回答用的語言)。
- 記憶與文件:用意思找記憶(本機模型/Ollama/關閉)、Bot 可以翻的資料夾([memory](memory.md))。 - 記憶與文件:用意思找記憶(本機模型/Ollama/關閉)、Bot 可以翻的資料夾([memory](memory.md))。
- 通知:Bot 做完或等你時通知、需要你時響一聲([phone](phone.md))。 - 通知:Bot 做完或等你時通知、需要你時響一聲([phone](phone.md))。Mac 上的通知是 AnyBot.app 自己發的(貓的圖示),點一下打開那個 Bot;從建置資料夾直接跑(不是 .app)時改用系統的 display notification,圖示會是「工序指令編寫程式」。
- Bot:時區,例行任務和提醒用([routines](routines.md))。 - Bot:時區,例行任務和提醒用([routines](routines.md))。
- 帳戶:「登入」或「管理帳戶」打開「手機與帳號」頁;資料放在哪。 - 帳戶:「登入」或「管理帳戶」打開「手機與帳號」頁;資料放在哪。
- 「手機與帳號」頁(從 一般 › 帳戶 進去,[phone](phone.md)):「AnyBot 帳號」(登入、備份、還原)、大腦和「加一台電腦」([computers](computers.md))、「同一個網路直接連」、「手機可以做什麼」、「直接連線的裝置」、「分享給團隊」([team](team.md))、「帳號裡的電腦」。 - 「手機與帳號」頁(從 一般 › 帳戶 進去,[phone](phone.md)):「AnyBot 帳號」(登入、備份、還原)、大腦和「加一台電腦」([computers](computers.md))、「同一個網路直接連」、「手機可以做什麼」、「直接連線的裝置」、「分享給團隊」([team](team.md))、「帳號裡的電腦」。
@ -47,7 +47,7 @@ Bot 設定(每個 Bot 一個視窗,[bots](bots.md)):
## 怎麼操作 ## 怎麼操作
- Bot:大部分設定改不了。`update_settings` 只能改三樣:`theme`(light/dark/system)、`accent`(bot_color/black)、`timezone`(像 Asia/Taipei);「在這台電腦上執行」只有使用者能打開。改自己的個人檔案、能力、技能、電腦、模型、頭像:先用 `my_profile` 看,再用 `update_my_profile` 改(使用者先看到確認卡片,按允許才生效)。其他設定告訴使用者在哪個分頁、哪一塊。 - Bot:大部分設定改不了。`update_settings` 只能改三樣:`theme`(light/dark/system)、`accent`(bot_color/black)、`timezone`(像 Asia/Taipei);「在這台電腦上執行」只有使用者能打開。改自己的個人檔案、能力、技能、電腦、模型、頭像:先用 `my_profile` 看,再用 `update_my_profile` 改(使用者先看到確認卡片,按允許才生效)。其他設定告訴使用者在哪個分頁、哪一塊。
- 驗證:打開設定,八個分頁都在,各區塊照上面的位置出現;請 Bot 換深色主題、時區改 Asia/Tokyo,設定 › 一般 的主題和時區要跟著變;給它不存在的時區,要回「不是有效的時區名稱」。自動測試:`cargo test featuremap::`(設定視窗的每個分頁和區塊標題、Bot 能改的設定都要寫在這份)、`cargo test appctl::`、`cargo test policy::`。 - 驗證:打開設定,八個分頁都在,各區塊照上面的位置出現;請 Bot 換深色主題、時區改 Asia/Tokyo,設定 › 一般 的主題和時區要跟著變;給它不存在的時區,要回「不是有效的時區名稱」。自動測試:`cargo test featuremap::`(設定視窗的每個分頁和區塊標題、Bot 能改的設定都要寫在這份)、`cargo test appctl::`、`cargo test policy::`、`cargo test layout_audit::`(每個設定分頁、Bot 設定、例行任務、右側面板,用三種字型、最窄和一般的視窗、示範和很長的資料畫一遍:字被切掉或疊在一起就失敗)。
## 陷阱 ## 陷阱
@ -59,3 +59,4 @@ Bot 設定(每個 Bot 一個視窗,[bots](bots.md)):
- Bot 設定要按「儲存」才算;關掉或按「取消」就不存。 - Bot 設定要按「儲存」才算;關掉或按「取消」就不存。
- 連到別台大腦的螢幕電腦上,模型金鑰、語音這些是大腦的設定,改了存在大腦;主題、強調色、「在這台電腦上執行」、手機與帳號還是這台自己的([computers](computers.md))。 - 連到別台大腦的螢幕電腦上,模型金鑰、語音這些是大腦的設定,改了存在大腦;主題、強調色、「在這台電腦上執行」、手機與帳號還是這台自己的([computers](computers.md))。
- 被管理員鎖住的開關是灰的,旁邊寫「由你的管理員設定,無法變更」([safety](safety.md))。 - 被管理員鎖住的開關是灰的,旁邊寫「由你的管理員設定,無法變更」([safety](safety.md))。
- 「Bot 做完或等你時通知」開著卻沒有橫幅:看 macOS 系統設定 › 通知 › AnyBot 是不是被關掉;`anybot --banner 標題 內文`(用 AnyBot.app 裡的那個程式)會送一則並說是怎麼送的。

BIN
mobile/badge-96.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 290 KiB

View File

@ -4,6 +4,9 @@
<meta charset="utf-8"> <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover, interactive-widget=resizes-content"> <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover, interactive-widget=resizes-content">
<meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-capable" content="yes">
<meta name="mobile-web-app-capable" content="yes">
<meta name="color-scheme" content="light dark">
<meta name="format-detection" content="telephone=no">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent"> <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<meta name="apple-mobile-web-app-title" content="AnyBot"> <meta name="apple-mobile-web-app-title" content="AnyBot">
<meta name="theme-color" content="#161616" media="(prefers-color-scheme: dark)"> <meta name="theme-color" content="#161616" media="(prefers-color-scheme: dark)">
@ -450,6 +453,38 @@ textarea.field{min-height:96px;line-height:1.5}
.live{display:inline-block;width:7px;height:7px;border-radius:50%;background:var(--ok);margin-right:5px} .live{display:inline-block;width:7px;height:7px;border-radius:50%;background:var(--ok);margin-right:5px}
.pair-code{font:600 32px/1.2 var(--mono);text-align:center;letter-spacing:4px;padding:10px} .pair-code{font:600 32px/1.2 var(--mono);text-align:center;letter-spacing:4px;padding:10px}
.pair-line{display:block;font:12px/1.5 var(--mono);background:var(--hover);padding:10px;border-radius:10px;margin:6px 16px;word-break:break-all} .pair-line{display:block;font:12px/1.5 var(--mono);background:var(--hover);padding:10px;border-radius:10px;margin:6px 16px;word-break:break-all}
/* ---- feels installed (a PWA on every phone) ---- */
:root{--safe-l:env(safe-area-inset-left,0px);--safe-r:env(safe-area-inset-right,0px)}
/* No font inflation when the phone turns sideways. */
html{-webkit-text-size-adjust:100%;text-size-adjust:100%}
/* A phone on its side with a notch: every screen paints edge to edge, its content stays clear of it. */
.view{padding-left:var(--safe-l);padding-right:var(--safe-r)}
.sheet{padding-left:var(--safe-l);padding-right:var(--safe-r)}
.boxwrap{padding:0 var(--safe-r) 0 var(--safe-l)}
/* Lists bounce on their own; the page behind them never moves. */
.scroll,.sheet{overscroll-behavior:contain}
/* Controls are not text: a long press doesn't select a button's label, and a tap answers at once. */
button,.row,.ib,.island,.opt,.chip,.tab,label.sw,[role="button"]{-webkit-user-select:none;user-select:none;-webkit-touch-callout:none;touch-action:manipulation}
/* (Under 16 px, iPhone zooms the page into the field and leaves it there.) */
.searchbox input{font-size:16px}
/* Screens slide like an app's: a new one comes in from the right, going back comes from the left. */
@media (prefers-reduced-motion: no-preference){
.view.in-fwd{animation:in-fwd .28s cubic-bezier(.22,.8,.24,1)}
.view.in-back{animation:in-back .28s cubic-bezier(.22,.8,.24,1)}
}
@keyframes in-fwd{from{transform:translateX(32%);opacity:.35}}
@keyframes in-back{from{transform:translateX(-14%);opacity:.6}}
/* The iPhone home-screen app has no browser to swipe back with: the edge swipe moves the screen. */
.view.dragging{transition:none!important;box-shadow:-12px 0 24px #0003}
/* Put AnyBot on the home screen (shown once, until installed or dismissed). */
.install{margin:2px 12px 8px;padding:12px 14px;border-radius:14px;background:var(--elev);box-shadow:inset 0 0 0 .5px var(--line);display:none;gap:12px;align-items:center}
.install.on{display:flex}
.install img{width:44px;height:44px;border-radius:11px;flex:none}
.install .mid{flex:1;min-width:0}
.install b{display:block;font-size:14.5px;font-weight:600}
.install span{display:block;font-size:12.5px;color:var(--text3);line-height:1.45;margin-top:2px}
.install .x{width:30px;height:30px;border-radius:15px;display:grid;place-items:center;color:var(--text3);flex:none}
.install .btn{flex:none}
</style> </style>
</head> </head>
<body> <body>
@ -486,6 +521,7 @@ textarea.field{min-height:96px;line-height:1.5}
<button class="ib" id="b-newbot" title="新 Bot"></button> <button class="ib" id="b-newbot" title="新 Bot"></button>
</div> </div>
<div class="searchbox" id="searchbox"><span id="search-ic"></span><input id="search" placeholder="搜尋 Bot" enterkeyhint="search"><button class="ib" id="b-search-x" style="width:28px;height:28px"></button></div> <div class="searchbox" id="searchbox"><span id="search-ic"></span><input id="search" placeholder="搜尋 Bot" enterkeyhint="search"><button class="ib" id="b-search-x" style="width:28px;height:28px"></button></div>
<div class="install" id="install"></div>
<div class="quick" id="quick"></div> <div class="quick" id="quick"></div>
<div class="scroll" id="home"></div> <div class="scroll" id="home"></div>
</section> </section>
@ -644,6 +680,7 @@ const LUCIDE = {
"users": '<path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/>', "users": '<path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/>',
"bookmark": '<path d="m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z"/>', "bookmark": '<path d="m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z"/>',
"power": '<path d="M12 2v10"/><path d="M18.4 6.6a9 9 0 1 1-12.77.04"/>', "power": '<path d="M12 2v10"/><path d="M18.4 6.6a9 9 0 1 1-12.77.04"/>',
"share": '<path d="M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8"/><polyline points="16 6 12 2 8 6"/><line x1="12" x2="12" y1="2" y2="15"/>',
"download": '<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" x2="12" y1="15" y2="3"/>', "download": '<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" x2="12" y1="15" y2="3"/>',
"globe": '<circle cx="12" cy="12" r="10"/><path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"/><path d="M2 12h20"/>', "globe": '<circle cx="12" cy="12" r="10"/><path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"/><path d="M2 12h20"/>',
"key": '<circle cx="7.5" cy="15.5" r="5.5"/><path d="m21 2-9.6 9.6"/><path d="m15.5 7.5 3 3L22 7l-3-3"/>', "key": '<circle cx="7.5" cy="15.5" r="5.5"/><path d="m21 2-9.6 9.6"/><path d="m15.5 7.5 3 3L22 7l-3-3"/>',
@ -699,7 +736,7 @@ function plain(t) { return String(t || "").replace(/\[([^\]]+)\]\([^)]+\)/g, "$1
// 外觀 of this phone: follow it, or light or dark by hand. // 外觀 of this phone: follow it, or light or dark by hand.
const THEMES = [["", "跟著手機"], ["light", "淺色"], ["dark", "深色"]]; const THEMES = [["", "跟著手機"], ["light", "淺色"], ["dark", "深色"]];
function phoneTheme() { try { return localStorage.getItem("anybot.theme") || ""; } catch (_) { return ""; } } function phoneTheme() { try { return localStorage.getItem("anybot.theme") || ""; } catch (_) { return ""; } }
function applyTheme() { const t = phoneTheme(); if (t) document.documentElement.dataset.theme = t; else delete document.documentElement.dataset.theme; } function applyTheme() { const t = phoneTheme(); if (t) document.documentElement.dataset.theme = t; else delete document.documentElement.dataset.theme; if (typeof barColor === "function") barColor(); }
applyTheme(); applyTheme();
const S = { sending: [], voice: {}, const S = { sending: [], voice: {},
@ -797,8 +834,24 @@ function confirmSheet(title, note, yes, danger = true) {
// ---------- screens: a stack, the phone's back gesture goes back ---------- // ---------- screens: a stack, the phone's back gesture goes back ----------
const NAV = []; const NAV = [];
function show(v) { document.querySelectorAll(".view").forEach((x) => x.classList.toggle("on", x.id === "v-" + v)); S.view = v; if (v !== "screen") stopFrames(); if (v !== "list") stopListTimer(); } function show(v) {
const was = S.view;
document.querySelectorAll(".view").forEach((x) => x.classList.toggle("on", x.id === "v-" + v));
S.view = v; if (v !== "screen") stopFrames(); if (v !== "list") stopListTimer();
// A new screen slides in (forward from the right, back from the left); redrawing the same one doesn't.
const el = $("v-" + v), dir = S.dir; S.dir = "";
if (el && dir && was && was !== v) { el.classList.remove("in-fwd", "in-back"); void el.offsetWidth; el.classList.add(dir); el.addEventListener("animationend", () => el.classList.remove(dir), {once: true}); }
barColor();
}
// Android's status bar (and the browser's own bar) in the colour of the top of the screen showing.
function barColor() {
const top = document.querySelector(".view.on .bar") || document.querySelector(".view.on") || document.body;
const c = getComputedStyle(top).backgroundColor;
if (!c || c === "rgba(0, 0, 0, 0)") return;
document.querySelectorAll('meta[name="theme-color"]').forEach((m) => m.setAttribute("content", c));
}
function go(v, arg = {}, replace = false) { function go(v, arg = {}, replace = false) {
S.dir = replace ? "" : "in-fwd";
if (replace && NAV.length) NAV[NAV.length - 1] = {v, arg}; else NAV.push({v, arg}); if (replace && NAV.length) NAV[NAV.length - 1] = {v, arg}; else NAV.push({v, arg});
if (replace) history.replaceState({n: NAV.length}, ""); else history.pushState({n: NAV.length}, ""); if (replace) history.replaceState({n: NAV.length}, ""); else history.pushState({n: NAV.length}, "");
draw(v, arg); draw(v, arg);
@ -810,6 +863,7 @@ window.addEventListener("popstate", () => {
NAV.pop(); NAV.pop();
if (!NAV.length) { NAV.push({v: "home", arg: {}}); history.pushState({n: 1}, ""); } if (!NAV.length) { NAV.push({v: "home", arg: {}}); history.pushState({n: 1}, ""); }
const t = NAV[NAV.length - 1]; const t = NAV[NAV.length - 1];
S.dir = S.swiped ? "" : "in-back"; S.swiped = false;
closeSheet(); closeSheet();
draw(t.v, t.arg); draw(t.v, t.arg);
}); });
@ -937,7 +991,7 @@ async function start() {
function apply(v) { function apply(v) {
S.bots = v.bots || []; S.approvals = v.approvals || []; S.hostName = v.host || ""; S.mac = !!v.mac; S.bots = v.bots || []; S.approvals = v.approvals || []; S.hostName = v.host || ""; S.mac = !!v.mac;
S.box = v.box || ""; S.boxOn = !!v.box_available; S.pages = v.pages || []; S.models = v.models || []; S.sections = v.sections || null; S.role = v.role || "owner"; S.box = v.box || ""; S.boxOn = !!v.box_available; S.pages = v.pages || []; S.models = v.models || []; S.sections = v.sections || null; S.role = v.role || "owner";
S.voice = v.voice || {}; micShown(); S.voice = v.voice || {}; micShown(); appBadge();
const t = cur(); const t = cur();
if (t.v === "home") renderHome(); if (t.v === "home") renderHome();
else if (t.v === "chat") { else if (t.v === "chat") {
@ -967,6 +1021,7 @@ function botRow(b) {
return `<div class="row" data-bot="${b.id}">${`<div class="av">${avatarSvg(b.shape, b.color)}${st.dot ? `<span class="dot ${st.dot}"></span>` : ""}</div>`}<div class="mid"><div class="nm"><span class="t">${esc(b.name)}</span>${b.members ? '<span class="pill">群組</span>' : ""}</div><div class="pv ${st.cls}">${esc(st.text)}</div></div><div class="tm">${ago(b.time)}</div><button class="more" data-botmenu="${b.id}" title="更多">${ic("ellipsis", 18)}</button></div>`; return `<div class="row" data-bot="${b.id}">${`<div class="av">${avatarSvg(b.shape, b.color)}${st.dot ? `<span class="dot ${st.dot}"></span>` : ""}</div>`}<div class="mid"><div class="nm"><span class="t">${esc(b.name)}</span>${b.members ? '<span class="pill">群組</span>' : ""}</div><div class="pv ${st.cls}">${esc(st.text)}</div></div><div class="tm">${ago(b.time)}</div><button class="more" data-botmenu="${b.id}" title="更多">${ic("ellipsis", 18)}</button></div>`;
} }
function renderHome() { function renderHome() {
installHint();
$("host-name").textContent = S.hostName ? "· " + S.hostName : ""; $("host-name").textContent = S.hostName ? "· " + S.hostName : "";
$("b-me").textContent = (S.hostName || "A").slice(0, 1).toUpperCase(); $("b-me").textContent = (S.hostName || "A").slice(0, 1).toUpperCase();
const q = S.search; const q = S.search;
@ -1085,7 +1140,8 @@ $("b-me").onclick = () => {
sheet("這支手機的外觀", THEMES.map(([k, n]) => ({label: n, check: phoneTheme() === k, on: () => { try { localStorage.setItem("anybot.theme", k); } catch (_) {} applyTheme(); }}))); sheet("這支手機的外觀", THEMES.map(([k, n]) => ({label: n, check: phoneTheme() === k, on: () => { try { localStorage.setItem("anybot.theme", k); } catch (_) {} applyTheme(); }})));
}}); }});
if (isOwner()) items.push({icon: "send", label: "傳送到其他裝置", on: dropsSheet}); if (isOwner()) items.push({icon: "send", label: "傳送到其他裝置", on: dropsSheet});
if (S.relay) items.push({icon: "bell", label: "通知", on: notifySheet}); items.push({icon: "bell", label: "通知", on: notifySheet});
if (!installed() && (S.installPrompt || navigator.standalone === false)) items.push({icon: "download", label: "安裝成 App", on: installApp});
if (S.mac) items.push({icon: "monitor", label: "看這台 Mac 的螢幕", on: () => go("screen")}); if (S.mac) items.push({icon: "monitor", label: "看這台 Mac 的螢幕", on: () => go("screen")});
if (S.relay && owner()) items.push({icon: "plus", label: "加一台電腦(Linux、伺服器)", on: pair}); if (S.relay && owner()) items.push({icon: "plus", label: "加一台電腦(Linux、伺服器)", on: pair});
if (S.relay) items.push({icon: "refresh", label: "切換到別台 AnyBot", on: () => { S.host = ""; localStorage.removeItem("anybot.host"); S.version = 0; NAV.length = 0; pickHost(); }}); if (S.relay) items.push({icon: "refresh", label: "切換到別台 AnyBot", on: () => { S.host = ""; localStorage.removeItem("anybot.host"); S.version = 0; NAV.length = 0; pickHost(); }});
@ -2820,23 +2876,103 @@ async function pair() {
} }
const pushOK = () => S.relay && "serviceWorker" in navigator && "PushManager" in window && "Notification" in window; const pushOK = () => S.relay && "serviceWorker" in navigator && "PushManager" in window && "Notification" in window;
function keyBytes(b64) { const s = atob(b64.replace(/-/g, "+").replace(/_/g, "/") + "===".slice((b64.length + 3) % 4)); return Uint8Array.from(s, (c) => c.charCodeAt(0)); } function keyBytes(b64) { const s = atob(b64.replace(/-/g, "+").replace(/_/g, "/") + "===".slice((b64.length + 3) % 4)); return Uint8Array.from(s, (c) => c.charCodeAt(0)); }
// What this phone is told about (the account server keeps the choice with this phone's subscription).
const KINDS = [["need", "需要你", "要你允許、回答問題,或接手一個步驟"], ["done", "做完了", "你不在電腦前時,Bot 做完一件事或達成目標"], ["routine", "例行任務暫停", "例行任務連續失敗、自己停下來了"], ["file", "收到傳來的檔案", "從其他裝置傳到這裡的檔案或文字"]];
async function pushSub() { const r = await navigator.serviceWorker.getRegistration(); return r && await r.pushManager.getSubscription(); }
async function notifySheet() { async function notifySheet() {
if (!pushOK()) { sheet("通知", [], `<div class="note">${/iPhone|iPad/.test(navigator.userAgent) ? "iPhone 要先按分享 › 加入主畫面,從主畫面打開 AnyBot 才能開通知。" : "這個瀏覽器不支援通知。"}</div>`); return; } if (!pushOK()) {
const reg = await navigator.serviceWorker.getRegistration(); const why = !S.relay ? "直接連線(同一個網路)收不到推播:用 AnyBot 帳號登入的手機才收得到。" : navigator.standalone === false ? "iPhone 要先按分享 › 加入主畫面,從主畫面打開 AnyBot 才能開通知。" : "這個瀏覽器不支援通知。";
const sub = reg && await reg.pushManager.getSubscription(); sheet("通知", [], `<div class="note">${why}</div>`); return;
sheet("通知", [{icon: "bell", label: sub ? "關閉通知" : "開啟通知", on: async () => { }
const sub = await pushSub().catch(() => null);
let st = {on: false, kinds: KINDS.map((k) => k[0])};
if (sub) st = await api("relay/push/state", {json: {endpoint: sub.endpoint}}).catch(() => st);
const blocked = Notification.permission === "denied";
let h = `<div class="group">` + item({icon: "bell", k: "這支手機的通知", v: blocked ? "被系統擋下了:到手機的設定 › 通知 › AnyBot 打開" : st.on ? "Bot 需要你時,會跳出通知" : "關閉中", sw: st.on && !blocked, swdata: 'data-push="1"', disabled: blocked}) + `</div>`;
if (st.on) {
h += `<div class="grp">要通知我的事</div><div class="group">` + KINDS.map(([k, n, v]) => item({k: n, v, sw: st.kinds.includes(k), swdata: `data-kind="${k}"`})).join("") + `</div>`;
h += `<div class="form"><button class="btn" id="push-test">${ic("send", 16)}送一則測試通知</button></div>`;
}
h += `<div class="note">通知的圖示是 AnyBot 的貓;App 圖示上的數字是正在等你的 Bot。${navigator.standalone ? "聲音和橫幅樣式在 iPhone 的設定 › 通知 › AnyBot 調整。" : ""}</div>`;
const el = sheet("通知", [], h);
const on = el.querySelector("[data-push]");
if (on) on.onchange = async () => {
on.disabled = true;
try { try {
const r = await navigator.serviceWorker.register("sw.js"); await navigator.serviceWorker.ready; const r = await navigator.serviceWorker.register("sw.js"); await navigator.serviceWorker.ready;
const old = await r.pushManager.getSubscription(); const old = await r.pushManager.getSubscription();
if (old) { await api("relay/push/unsubscribe", {json: {endpoint: old.endpoint}}); await old.unsubscribe(); toast("已關閉通知"); } if (old) { await api("relay/push/unsubscribe", {json: {endpoint: old.endpoint}}).catch(() => {}); await old.unsubscribe(); if (navigator.clearAppBadge) navigator.clearAppBadge().catch(() => {}); toast("已關閉通知"); }
else { else {
if (await Notification.requestPermission() !== "granted") { toast("沒有允許通知(可在系統設定裡打開)"); return; } if (await Notification.requestPermission() !== "granted") { toast("沒有允許通知(可在手機的設定裡打開)"); notifySheet(); return; }
const {key} = await api("relay/push/key"); const {key} = await api("relay/push/key");
const s2 = await r.pushManager.subscribe({userVisibleOnly: true, applicationServerKey: keyBytes(key)}); const s2 = await r.pushManager.subscribe({userVisibleOnly: true, applicationServerKey: keyBytes(key)});
await api("relay/push/subscribe", {json: s2.toJSON()}); toast("已開啟通知"); await api("relay/push/subscribe", {json: {...s2.toJSON(), kinds: st.kinds}}); toast("已開啟通知");
} }
} catch (e) { toast("通知設定失敗:" + e.message); } } catch (e) { toast("通知設定失敗:" + e.message); }
}}], `<div class="note">Bot 需要你允許、或在你不在時做完事,手機會跳通知。</div>`); notifySheet();
};
el.querySelectorAll("[data-kind]").forEach((c) => c.onchange = async () => {
const kinds = [...el.querySelectorAll("[data-kind]")].filter((x) => x.checked).map((x) => x.dataset.kind);
try { const s2 = await pushSub(); await api("relay/push/kinds", {json: {endpoint: s2.endpoint, kinds}}); toast(kinds.length ? "已更新" : "這支手機現在不會收到 Bot 的通知"); }
catch (e) { toast("沒有存到:" + e.message); c.checked = !c.checked; }
});
const test = el.querySelector("#push-test");
if (test) test.onclick = async () => {
try { const s2 = await pushSub(); await api("relay/push/test", {json: {endpoint: s2.endpoint}}); toast("送出了,幾秒內會跳出來"); }
catch (e) { toast("沒有送出:" + e.message); }
};
}
// The number on the app's icon: bots waiting for you (允許、問題、需要你處理). The notifications set
// it while the app is closed; here it follows what the app shows.
function appBadge() {
if (!navigator.setAppBadge) return;
const n = new Set((S.approvals || []).map((a) => a.bot)).size;
(n ? navigator.setAppBadge(n) : navigator.clearAppBadge()).catch(() => {});
}
// ---------- installed like an app ----------
const installed = () => matchMedia("(display-mode: standalone)").matches || navigator.standalone === true;
window.addEventListener("beforeinstallprompt", (e) => { e.preventDefault(); S.installPrompt = e; installHint(); });
window.addEventListener("appinstalled", () => { S.installPrompt = null; installHint(); toast("已安裝,之後從主畫面打開 AnyBot"); });
async function installApp() {
if (S.installPrompt) { const p = S.installPrompt; S.installPrompt = null; p.prompt(); await p.userChoice.catch(() => {}); installHint(); return; }
sheet("加入主畫面", [], `<div class="note">1. 按 Safari 下方的分享按鈕 ${ic("share", 15)}\n2. 選「加入主畫面」\n3. 之後從主畫面的 AnyBot 打開:全螢幕、沒有網址列,也能開通知。</div>`);
}
function installHint() {
const el = $("install"); if (!el) return;
let gone = false; try { gone = localStorage.getItem("anybot.install-hint") === "no"; } catch (_) {}
const can = !installed() && !gone && S.token && (S.installPrompt || navigator.standalone === false);
el.classList.toggle("on", !!can);
if (!can) { el.innerHTML = ""; return; }
el.innerHTML = `<img src="icon-180.png" alt=""><div class="mid"><b>把 AnyBot 裝成 App</b><span>全螢幕、從主畫面打開,Bot 需要你時會跳通知。</span></div><button class="btn main" id="install-go">${S.installPrompt ? "安裝" : "怎麼做"}</button><button class="x" id="install-no" title="不用了">${ic("x", 16)}</button>`;
$("install-go").onclick = installApp;
$("install-no").onclick = () => { try { localStorage.setItem("anybot.install-hint", "no"); } catch (_) {} installHint(); };
}
// The iPhone home-screen app has no browser around it, so no swipe from the left edge to go back:
// AnyBot does that itself (Android has its own back gesture; Safari in the browser has its own).
if (navigator.standalone === true) {
let el = null, sx = 0, sy = 0, dx = 0, t0 = 0;
document.addEventListener("touchstart", (e) => {
const t = e.touches[0];
el = null;
if (e.touches.length !== 1 || t.clientX > 22 || NAV.length < 2 || boxOpen || $("sheet").classList.contains("on")) return;
el = document.querySelector(".view.on"); sx = t.clientX; sy = t.clientY; dx = 0; t0 = performance.now();
}, {passive: true});
document.addEventListener("touchmove", (e) => {
if (!el) return;
const t = e.touches[0]; dx = Math.max(0, t.clientX - sx);
if (dx < 12 && Math.abs(t.clientY - sy) > 12) { el.classList.remove("dragging"); el.style.transform = ""; el = null; return; } // scrolling, not going back
el.classList.add("dragging"); el.style.transform = `translateX(${dx}px)`;
}, {passive: true});
const end = () => {
if (!el) return;
const v = el, goBack = dx > innerWidth * 0.33 || dx / Math.max(1, performance.now() - t0) > 0.45;
el = null;
v.classList.remove("dragging"); v.style.transition = "transform .2s cubic-bezier(.22,.8,.24,1)";
v.style.transform = goBack ? `translateX(${innerWidth}px)` : "";
setTimeout(() => { v.style.transition = ""; v.style.transform = ""; if (goBack) { S.swiped = true; back(); } }, 200);
};
document.addEventListener("touchend", end);
document.addEventListener("touchcancel", end);
} }
if (pushOK()) navigator.serviceWorker.register("sw.js").catch(() => {}); if (pushOK()) navigator.serviceWorker.register("sw.js").catch(() => {});
// A tapped notification opens that chat. // A tapped notification opens that chat.

View File

@ -0,0 +1,23 @@
{
"id": "./",
"name": "AnyBot",
"short_name": "AnyBot",
"description": "跟你的 Bot 聊天、允許它做事、看它的電腦",
"lang": "zh-Hant",
"dir": "ltr",
"start_url": "./",
"scope": "./",
"display": "standalone",
"orientation": "any",
"background_color": "#121212",
"theme_color": "#121212",
"categories": ["productivity", "utilities"],
"icons": [
{"src": "icon.svg", "sizes": "any", "type": "image/svg+xml", "purpose": "any"},
{"src": "icon-192.png", "sizes": "192x192", "type": "image/png", "purpose": "any"},
{"src": "icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "any"},
{"src": "icon-maskable-192.png", "sizes": "192x192", "type": "image/png", "purpose": "maskable"},
{"src": "icon-maskable-512.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable"},
{"src": "badge-96.png", "sizes": "96x96", "type": "image/png", "purpose": "monochrome"}
]
}

38
mobile/sw.js Normal file
View File

@ -0,0 +1,38 @@
// AnyBot 手機 App 的 Service Worker(帳號伺服器送出):推播通知、點通知打開那個 Bot、App 圖示上的數字。
// 通知的圖示是 AnyBot 的貓(黃色底);Android 狀態列的小圖示只能是單色,用那隻貓的剪影(badge-96.png)。
self.addEventListener("install", () => self.skipWaiting());
self.addEventListener("activate", (e) => e.waitUntil(self.clients.claim()));
// kind: need(需要你允許、問你、需要你處理)、done(做完了)、routine(例行任務暫停)、file(收到傳來的檔案)、test。
self.addEventListener("push", (e) => {
let d = {};
try { d = e.data ? e.data.json() : {}; } catch (_) { d = {body: e.data ? e.data.text() : ""}; }
const need = d.kind === "need";
const shown = self.registration.showNotification(d.title || "AnyBot", {
body: d.body || "",
// One notification per bot: the newest word about it replaces the last one, and still rings.
tag: d.kind === "test" ? "test" : "bot-" + (d.bot || 0),
renotify: true,
data: d,
icon: "icon-192.png",
badge: "badge-96.png",
timestamp: Date.now(),
// 需要你: stays until you look (Android, desktop), and buzzes twice.
requireInteraction: need,
vibrate: need ? [90, 70, 90] : [70],
});
// The number on the app's icon: bots waiting for you.
const n = typeof d.badge === "number" ? d.badge : null;
const badge = n === null || !self.navigator.setAppBadge ? null : n > 0 ? self.navigator.setAppBadge(n) : self.navigator.clearAppBadge();
e.waitUntil(Promise.all([shown, badge].filter(Boolean)).catch(() => {}));
});
self.addEventListener("notificationclick", (e) => {
e.notification.close();
const d = e.notification.data || {};
const url = "./#host=" + encodeURIComponent(d.host || "") + "&bot=" + (d.bot || "");
e.waitUntil(self.clients.matchAll({type: "window", includeUncontrolled: true}).then((cs) => {
for (const c of cs) { c.postMessage({open: d}); return c.focus(); }
return self.clients.openWindow(url);
}));
});

View File

@ -32,10 +32,23 @@ const PAGE: &str = include_str!("../../mobile/index.html");
/// The bots' computer, watched and used in a browser (noVNC). /// The bots' computer, watched and used in a browser (noVNC).
const SCREEN_PAGE: &str = include_str!("../../mobile/screen.html"); const SCREEN_PAGE: &str = include_str!("../../mobile/screen.html");
const NOVNC: &str = include_str!("../../mobile/novnc.js"); const NOVNC: &str = include_str!("../../mobile/novnc.js");
const MANIFEST: &str = r##"{"name":"AnyBot","short_name":"AnyBot","start_url":"./","display":"standalone","background_color":"#121212","theme_color":"#121212","icons":[{"src":"icon.svg","sizes":"any","type":"image/svg+xml"},{"src":"icon-192.png","sizes":"192x192","type":"image/png","purpose":"any maskable"},{"src":"icon-512.png","sizes":"512x512","type":"image/png","purpose":"any maskable"}]}"##; /// The phone app's manifest and service worker (notifications), shared with the desktop's own
/// AnyBot's icon (the same drawing as the app's), and PNGs for the iPhone home screen and Android. /// phone page (src/remote.rs).
const MANIFEST: &str = include_str!("../../mobile/manifest.webmanifest");
const SW: &str = include_str!("../../mobile/sw.js");
/// AnyBot's icon (the same drawing as the app's), and PNGs for the iPhone home screen, Android
/// (full-bleed ones for its masks) and the one-colour cat Android shows in the status bar.
const ICON: &str = include_str!("../../mobile/icon.svg"); const ICON: &str = include_str!("../../mobile/icon.svg");
const ICON_PNGS: [(&str, &[u8]); 3] = [("icon-180.png", include_bytes!("../../mobile/icon-180.png")), ("icon-192.png", include_bytes!("../../mobile/icon-192.png")), ("icon-512.png", include_bytes!("../../mobile/icon-512.png"))]; const ICON_PNGS: [(&str, &[u8]); 6] = [
("icon-180.png", include_bytes!("../../mobile/icon-180.png")),
("icon-192.png", include_bytes!("../../mobile/icon-192.png")),
("icon-512.png", include_bytes!("../../mobile/icon-512.png")),
("icon-maskable-192.png", include_bytes!("../../mobile/icon-maskable-192.png")),
("icon-maskable-512.png", include_bytes!("../../mobile/icon-maskable-512.png")),
("badge-96.png", include_bytes!("../../mobile/badge-96.png")),
];
/// What a phone can choose to be told about (手機 › 通知): 需要你, 做完了, 例行任務, 收到檔案.
const NOTICE_KINDS: [&str; 4] = ["need", "done", "routine", "file"];
/// How long a host's "next request?" waits before answering "nothing". /// How long a host's "next request?" waits before answering "nothing".
const HOST_POLL_SECS: u64 = 25; const HOST_POLL_SECS: u64 = 25;
@ -149,6 +162,31 @@ struct Sub {
user: String, user: String,
sub: Value, sub: Value,
created: i64, created: i64,
/// What this phone wants to be told about (NOTICE_KINDS); empty: everything.
#[serde(default)]
kinds: Vec<String>,
}
impl Sub {
fn wants(&self, kind: &str) -> bool {
self.kinds.is_empty() || kind.is_empty() || self.kinds.iter().any(|k| k == kind)
}
}
/// Whoever asked for a screen ticket may still watch: that phone is still signed in (`s:`), or
/// that computer is still in the person's account (`h:`).
fn asker_still_ok(d: &Data, asker: &str, user: &str) -> bool {
match asker.split_once(':') {
Some(("s", hash)) => d.sessions.iter().any(|s| httpd::constant_time_eq(&s.hash, hash)),
Some(("h", id)) => d.hosts.iter().any(|x| x.id == id && x.user == user),
_ => false,
}
}
/// The kinds a phone picked, only known ones (none picked: none of them).
fn clean_kinds(v: &Value) -> Option<Vec<String>> {
let list = v.as_array()?;
Some(NOTICE_KINDS.iter().filter(|k| list.iter().any(|x| x.as_str() == Some(k))).map(|k| k.to_string()).collect())
} }
#[derive(Serialize, Deserialize, Default)] #[derive(Serialize, Deserialize, Default)]
@ -164,23 +202,6 @@ struct Data {
sites: HashMap<String, String>, sites: HashMap<String, String>,
} }
const SW: &str = r#"self.addEventListener("install", () => self.skipWaiting());
self.addEventListener("activate", (e) => e.waitUntil(self.clients.claim()));
self.addEventListener("push", (e) => {
let d = {};
try { d = e.data ? e.data.json() : {}; } catch (_) { d = {body: e.data ? e.data.text() : ""}; }
e.waitUntil(self.registration.showNotification(d.title || "AnyBot", {body: d.body || "", tag: "bot-" + (d.bot || 0), renotify: true, data: d, icon: "icon-192.png", badge: "icon-192.png"}));
});
self.addEventListener("notificationclick", (e) => {
e.notification.close();
const d = e.notification.data || {};
const url = "./#host=" + encodeURIComponent(d.host || "") + "&bot=" + (d.bot || "");
e.waitUntil(self.clients.matchAll({type: "window", includeUncontrolled: true}).then((cs) => {
for (const c of cs) { c.postMessage({open: d}); return c.focus(); }
return self.clients.openWindow(url);
}));
});
"#;
/// A forwarded request's answer. /// A forwarded request's answer.
struct Answer { struct Answer {
@ -277,7 +298,9 @@ struct Relay {
/// Two-step codes used in the last two minutes (see code_is_new). /// Two-step codes used in the last two minutes (see code_is_new).
used_codes: Mutex<HashMap<String, Instant>>, used_codes: Mutex<HashMap<String, Instant>>,
/// One-time links for a browser to watch a host's computer: ticket → (account, host, made). /// One-time links for a browser to watch a host's computer: ticket → (account, host, made).
tickets: Mutex<HashMap<String, (String, String, Instant)>>, /// Screen tickets: who, which AnyBot's screen, when last good, and who asked (`s:<session
/// hash>`: a signed-in phone; `h:<host id>`: a computer of the account).
tickets: Mutex<HashMap<String, (String, String, Instant, String)>>,
/// 配對碼: code → (account, the AnyBot it is for, when made). Ten minutes, once. /// 配對碼: code → (account, the AnyBot it is for, when made). Ten minutes, once.
pairs: Mutex<HashMap<String, (String, String, Instant)>>, pairs: Mutex<HashMap<String, (String, String, Instant)>>,
/// When each host last asked (in memory; saved now and then). /// When each host last asked (in memory; saved now and then).
@ -470,12 +493,13 @@ impl Relay {
/// admins only. /// admins only.
fn vnc_viewer(self: &Arc<Self>, req: Req, mut c: std::net::TcpStream, host: &str) { fn vnc_viewer(self: &Arc<Self>, req: Req, mut c: std::net::TcpStream, host: &str) {
use tungstenite::{protocol::Role, Message, WebSocket}; use tungstenite::{protocol::Role, Message, WebSocket};
let session_hash = req.query.get("ticket").filter(|t| !t.is_empty()).is_none().then(|| httpd::sha256_hex(&req.bearer())); let ticket = req.query.get("ticket").filter(|t| !t.is_empty()).cloned();
let user = match req.query.get("ticket").filter(|t| !t.is_empty()) { let session_hash = ticket.is_none().then(|| httpd::sha256_hex(&req.bearer()));
Some(t) => self.tickets.lock().unwrap().get(t).filter(|(_, h, made)| h == host && made.elapsed() < TICKET_LIFE).map(|(u, _, _)| u.clone()), let who = match &ticket {
None => self.session(&req), Some(t) => self.tickets.lock().unwrap().get(t).filter(|(_, h, made, _)| h == host && made.elapsed() < TICKET_LIFE).map(|(u, _, _, by)| (u.clone(), by.clone())),
None => self.session(&req).map(|u| (u, String::new())),
}; };
let Some(user) = user else { return httpd::write_response(&mut c, &Resp::error(401, "請先登入")) }; let Some((user, asker)) = who else { return httpd::write_response(&mut c, &Resp::error(401, "請先登入")) };
let allowed = self.data.lock().unwrap().hosts.iter().any(|x| x.id == host && matches!(x.role_of(&user).as_deref(), Some("owner") | Some("admin"))); let allowed = self.data.lock().unwrap().hosts.iter().any(|x| x.id == host && matches!(x.role_of(&user).as_deref(), Some("owner") | Some("admin")));
if !allowed { if !allowed {
return httpd::write_response(&mut c, &Resp::error(404, "找不到這台 AnyBot")); return httpd::write_response(&mut c, &Resp::error(404, "找不到這台 AnyBot"));
@ -506,7 +530,13 @@ impl Relay {
Ok(Message::Binary(b)) => Some(("vdata", b.to_vec())), Ok(Message::Binary(b)) => Some(("vdata", b.to_vec())),
Ok(Message::Text(t)) => Some(("vtext", t.as_bytes().to_vec())), Ok(Message::Text(t)) => Some(("vtext", t.as_bytes().to_vec())),
Ok(Message::Close(_)) => break, Ok(Message::Close(_)) => break,
Ok(_) => None, // The viewer's answer to our ping: still there. (Not counting it cut every viewer
// watching a still screen after a minute: noVNC sends nothing until the picture
// changes or the person moves the mouse.)
Ok(_) => {
heard = Instant::now();
None
}
Err(tungstenite::Error::Io(e)) if matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut) => None, Err(tungstenite::Error::Io(e)) if matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut) => None,
Err(_) => break, Err(_) => break,
}; };
@ -537,7 +567,12 @@ impl Relay {
let role_ok = d.hosts.iter().any(|x| x.id == host && matches!(x.role_of(&user).as_deref(), Some("owner") | Some("admin"))); let role_ok = d.hosts.iter().any(|x| x.id == host && matches!(x.role_of(&user).as_deref(), Some("owner") | Some("admin")));
let sess_ok = match &session_hash { let sess_ok = match &session_hash {
Some(sh) => d.sessions.iter().any(|s| httpd::constant_time_eq(&s.hash, sh)), Some(sh) => d.sessions.iter().any(|s| httpd::constant_time_eq(&s.hash, sh)),
None => self.tickets.lock().unwrap().values().any(|(u, h, made)| u == &user && h == host && made.elapsed() < TICKET_LIFE), // A viewer let in with a ticket keeps going while whoever asked for it
// still may (that phone still signed in, that computer still in the
// account) — it used to be cut when the ticket turned ten minutes old,
// and could never come back with it. The ticket stays good while in
// use, and for its ten minutes after, to come back after a dropped line.
None => asker_still_ok(&d, &asker, &user) && ticket.as_ref().is_some_and(|t| self.tickets.lock().unwrap().get_mut(t).map(|e| e.2 = Instant::now()).is_some()),
}; };
role_ok && sess_ok role_ok && sess_ok
}; };
@ -850,13 +885,14 @@ impl Relay {
// A computer of the account — or the signed-in phone itself, so its lasting // A computer of the account — or the signed-in phone itself, so its lasting
// login never has to ride in the address of the screen's connection (addresses // login never has to ride in the address of the screen's connection (addresses
// end up in logs and histories; the ticket is good for ten minutes, one screen). // end up in logs and histories; the ticket is good for ten minutes, one screen).
let user = match self.host(&req) { let (user, asker) = match self.host(&req) {
Some(h) if h.paired => return Resp::error(403, "這台電腦是配對加入的手腳,不能要求觀看畫面"), Some(h) if h.paired => return Resp::error(403, "這台電腦是配對加入的手腳,不能要求觀看畫面"),
Some(h) => { Some(h) => {
if !self.data.lock().unwrap().hosts.iter().any(|x| x.id == want && x.user == h.user) { if !self.data.lock().unwrap().hosts.iter().any(|x| x.id == want && x.user == h.user) {
return Resp::error(404, "找不到這台 AnyBot"); return Resp::error(404, "找不到這台 AnyBot");
} }
h.user let asker = format!("h:{}", h.id);
(h.user, asker)
} }
None => { None => {
let Some(user) = self.session(&req) else { return Resp::error(401, "請先登入") }; let Some(user) = self.session(&req) else { return Resp::error(401, "請先登入") };
@ -864,13 +900,13 @@ impl Relay {
if !may { if !may {
return Resp::error(404, "找不到這台 AnyBot"); return Resp::error(404, "找不到這台 AnyBot");
} }
user (user, format!("s:{}", httpd::sha256_hex(&req.bearer())))
} }
}; };
let t = httpd::random_hex(24); let t = httpd::random_hex(24);
let mut all = self.tickets.lock().unwrap(); let mut all = self.tickets.lock().unwrap();
all.retain(|_, (_, _, made)| made.elapsed() < TICKET_LIFE); all.retain(|_, (_, _, made, _)| made.elapsed() < TICKET_LIFE);
all.insert(t.clone(), (user, want, Instant::now())); all.insert(t.clone(), (user, want, Instant::now(), asker));
Resp::json(&json!({"ticket": t})) Resp::json(&json!({"ticket": t}))
} }
("GET", ["manifest.webmanifest"]) => Resp::bytes("application/manifest+json", MANIFEST.as_bytes().to_vec()), ("GET", ["manifest.webmanifest"]) => Resp::bytes("application/manifest+json", MANIFEST.as_bytes().to_vec()),
@ -889,6 +925,7 @@ impl Relay {
return Resp::error(400, "通知訂閱資料不完整"); return Resp::error(400, "通知訂閱資料不完整");
} }
let clean = json!({"endpoint": endpoint, "keys": {"p256dh": p256dh, "auth": auth}}); let clean = json!({"endpoint": endpoint, "keys": {"p256dh": p256dh, "auth": auth}});
let kinds = clean_kinds(&sub["kinds"]).unwrap_or_default();
let mut d = self.data.lock().unwrap(); let mut d = self.data.lock().unwrap();
d.subs.retain(|s| s.sub["endpoint"].as_str() != Some(endpoint.as_str())); d.subs.retain(|s| s.sub["endpoint"].as_str() != Some(endpoint.as_str()));
while d.subs.iter().filter(|s| s.user == user).count() >= 16 { while d.subs.iter().filter(|s| s.user == user).count() >= 16 {
@ -898,10 +935,44 @@ impl Relay {
break; break;
} }
} }
d.subs.push(Sub { user, sub: clean, created: now() }); d.subs.push(Sub { user, sub: clean, created: now(), kinds });
self.save(&d); self.save(&d);
Resp::json(&json!({"ok": true})) Resp::json(&json!({"ok": true}))
} }
// This phone's notifications: on or off here, and which kinds.
("POST", ["relay", "push", "state"]) => {
let Some(user) = self.session(&req) else { return Resp::error(401, "請先登入") };
let endpoint = req.json()["endpoint"].as_str().unwrap_or("").to_string();
let d = self.data.lock().unwrap();
match d.subs.iter().find(|s| s.user == user && s.sub["endpoint"].as_str() == Some(endpoint.as_str())) {
Some(s) => Resp::json(&json!({"on": true, "kinds": if s.kinds.is_empty() { NOTICE_KINDS.iter().map(|k| k.to_string()).collect() } else { s.kinds.clone() }})),
None => Resp::json(&json!({"on": false, "kinds": NOTICE_KINDS})),
}
}
("POST", ["relay", "push", "kinds"]) => {
let Some(user) = self.session(&req) else { return Resp::error(401, "請先登入") };
let v = req.json();
let endpoint = v["endpoint"].as_str().unwrap_or("").to_string();
let Some(kinds) = clean_kinds(&v["kinds"]) else { return Resp::error(400, "要給一份通知種類") };
let mut d = self.data.lock().unwrap();
let Some(s) = d.subs.iter_mut().find(|s| s.user == user && s.sub["endpoint"].as_str() == Some(endpoint.as_str())) else { return Resp::error(404, "這支手機還沒開通知") };
// (None picked is kept as none: an empty list would mean everything.)
s.kinds = if kinds.is_empty() { vec!["-".into()] } else { kinds };
self.save(&d);
Resp::json(&json!({"ok": true}))
}
// A test notification to this phone only (手機 › 通知 › 送一則測試通知).
("POST", ["relay", "push", "test"]) => {
let Some(user) = self.session(&req) else { return Resp::error(401, "請先登入") };
let endpoint = req.json()["endpoint"].as_str().unwrap_or("").to_string();
let sub = self.data.lock().unwrap().subs.iter().find(|s| s.user == user && s.sub["endpoint"].as_str() == Some(endpoint.as_str())).cloned();
let Some(sub) = sub else { return Resp::error(404, "這支手機還沒開通知") };
let payload = json!({"title": "AnyBot", "body": "通知正常:Bot 需要你時,會像這樣跳出來。", "kind": "test"});
match push::send(&self.vapid, &sub.sub, &payload, &self.contact) {
Ok(()) => Resp::json(&json!({"ok": true})),
Err(_) => Resp::error(502, "推播服務沒有收下,關掉通知再打開一次試試"),
}
}
("POST", ["relay", "push", "unsubscribe"]) => { ("POST", ["relay", "push", "unsubscribe"]) => {
let Some(user) = self.session(&req) else { return Resp::error(401, "請先登入") }; let Some(user) = self.session(&req) else { return Resp::error(401, "請先登入") };
let endpoint = req.json()["endpoint"].as_str().unwrap_or("").to_string(); let endpoint = req.json()["endpoint"].as_str().unwrap_or("").to_string();
@ -914,8 +985,12 @@ impl Relay {
("POST", ["relay", "host", "notify"]) => { ("POST", ["relay", "host", "notify"]) => {
let Some(h) = self.host(&req) else { return Resp::error(401, "這台電腦的金鑰無效") }; let Some(h) = self.host(&req) else { return Resp::error(401, "這台電腦的金鑰無效") };
let v = req.json(); let v = req.json();
let payload = json!({"title": v["title"].as_str().unwrap_or("AnyBot").chars().take(80).collect::<String>(), "body": v["body"].as_str().unwrap_or("").chars().take(200).collect::<String>(), "bot": v["bot"], "host": h.id}); let kind = v["kind"].as_str().filter(|k| NOTICE_KINDS.contains(k)).unwrap_or("");
let subs: Vec<Sub> = self.data.lock().unwrap().subs.iter().filter(|s| matches!(h.role_of(&s.user).as_deref(), Some("owner") | Some("admin"))).cloned().collect(); let mut payload = json!({"title": v["title"].as_str().unwrap_or("AnyBot").chars().take(80).collect::<String>(), "body": v["body"].as_str().unwrap_or("").chars().take(200).collect::<String>(), "bot": v["bot"], "host": h.id, "kind": kind});
if let Some(n) = v["badge"].as_u64() {
payload["badge"] = json!(n.min(999));
}
let subs: Vec<Sub> = self.data.lock().unwrap().subs.iter().filter(|s| matches!(h.role_of(&s.user).as_deref(), Some("owner") | Some("admin")) && s.wants(kind)).cloned().collect();
let mut gone = vec![]; let mut gone = vec![];
let mut sent = 0; let mut sent = 0;
for s in &subs { for s in &subs {
@ -1688,7 +1763,7 @@ impl Relay {
self.save(&d); self.save(&d);
d.hosts.iter().filter(|h| h.user == user).map(|h| h.id.clone()).collect() d.hosts.iter().filter(|h| h.user == user).map(|h| h.id.clone()).collect()
}; };
self.tickets.lock().unwrap().retain(|_, (u, _, _)| u != &user); self.tickets.lock().unwrap().retain(|_, (u, _, _, _)| u != &user);
self.streams.lock().unwrap().retain(|_, (_, h, _)| !host_ids.contains(h)); self.streams.lock().unwrap().retain(|_, (_, h, _)| !host_ids.contains(h));
Resp::json(&json!({"ok": true})) Resp::json(&json!({"ok": true}))
} }
@ -2095,6 +2170,27 @@ mod tests {
assert_eq!(get(port, &format!("/relay/hosts/{}/api/sync", brain["id"].as_str().unwrap()), paired_tok).0, 403); assert_eq!(get(port, &format!("/relay/hosts/{}/api/sync", brain["id"].as_str().unwrap()), paired_tok).0, 403);
assert_eq!(post(port, "/relay/screen-ticket", paired_tok, json!({"host": brain["id"]})).0, 403); assert_eq!(post(port, "/relay/screen-ticket", paired_tok, json!({"host": brain["id"]})).0, 403);
assert_eq!(post(port, "/relay/pair", paired_tok, json!({})).0, 403); assert_eq!(post(port, "/relay/pair", paired_tok, json!({})).0, 403);
// A screen ticket remembers who asked: a viewer let in with it keeps going while that
// phone stays signed in (not only for the ticket's ten minutes), and stops once it isn't.
let (st, t) = post(port, "/relay/screen-ticket", &session, json!({"host": brain["id"]}));
assert_eq!(st, 200);
let asker = relay.tickets.lock().unwrap().get(t["ticket"].as_str().unwrap()).map(|e| e.3.clone()).unwrap();
assert_eq!(asker, format!("s:{}", httpd::sha256_hex(&session)));
assert!(asker_still_ok(&relay.data.lock().unwrap(), &asker, "amy"));
assert!(!asker_still_ok(&relay.data.lock().unwrap(), "h:no-such-computer", "amy"));
assert!(!asker_still_ok(&relay.data.lock().unwrap(), "", "amy"));
// A computer of the account asking: good while it is still this person's.
if let Some(brain_tok) = brain["token"].as_str() {
let (st, t2) = post(port, "/relay/screen-ticket", brain_tok, json!({"host": brain["id"]}));
assert_eq!(st, 200, "{t2}");
let by = relay.tickets.lock().unwrap().get(t2["ticket"].as_str().unwrap()).map(|e| e.3.clone()).unwrap();
assert_eq!(by, format!("h:{}", brain["id"].as_str().unwrap()));
assert!(asker_still_ok(&relay.data.lock().unwrap(), &by, "amy"));
assert!(!asker_still_ok(&relay.data.lock().unwrap(), &by, "bob"));
}
// That phone signed out: the viewer it opened stops.
relay.data.lock().unwrap().sessions.retain(|x| !httpd::constant_time_eq(&x.hash, &httpd::sha256_hex(&session)));
assert!(!asker_still_ok(&relay.data.lock().unwrap(), &asker, "amy"));
// Once only; a wrong code is refused, and guessing is stopped. // Once only; a wrong code is refused, and guessing is stopped.
assert_eq!(post(port, "/relay/pair/claim", "", json!({"code": code, "name": "x"})).0, 404); assert_eq!(post(port, "/relay/pair/claim", "", json!({"code": code, "name": "x"})).0, 404);
for _ in 0..10 { for _ in 0..10 {
@ -2218,8 +2314,22 @@ mod tests {
assert_eq!(post(port, "/relay/push/subscribe", &s, json!({"endpoint": "https://push.example/1", "keys": {"p256dh": "a", "auth": "b"}})).0, 200); assert_eq!(post(port, "/relay/push/subscribe", &s, json!({"endpoint": "https://push.example/1", "keys": {"p256dh": "a", "auth": "b"}})).0, 200);
assert_eq!(post(port, "/relay/push/unsubscribe", "", json!({"endpoint": "https://push.example/1"})).0, 401); assert_eq!(post(port, "/relay/push/unsubscribe", "", json!({"endpoint": "https://push.example/1"})).0, 401);
assert_eq!(relay.data.lock().unwrap().subs.len(), 1); assert_eq!(relay.data.lock().unwrap().subs.len(), 1);
// Which kinds this phone gets: all at first; picked ones after; none picked stays none.
let state = |s: &str| post(port, "/relay/push/state", s, json!({"endpoint": "https://push.example/1"})).1;
assert_eq!(state(&s)["on"], true);
assert_eq!(state(&s)["kinds"], json!(["need", "done", "routine", "file"]));
assert!(relay.data.lock().unwrap().subs[0].wants("done"));
assert_eq!(post(port, "/relay/push/kinds", &s, json!({"endpoint": "https://push.example/1", "kinds": ["need", "made-up"]})).0, 200);
assert_eq!(state(&s)["kinds"], json!(["need"]));
assert!(relay.data.lock().unwrap().subs[0].wants("need") && !relay.data.lock().unwrap().subs[0].wants("done"));
assert_eq!(post(port, "/relay/push/kinds", &s, json!({"endpoint": "https://push.example/1", "kinds": []})).0, 200);
assert!(!relay.data.lock().unwrap().subs[0].wants("need"));
assert_eq!(post(port, "/relay/push/kinds", &s, json!({"endpoint": "https://push.example/2", "kinds": ["need"]})).0, 404);
assert_eq!(post(port, "/relay/push/kinds", "", json!({"endpoint": "https://push.example/1", "kinds": ["need"]})).0, 401);
assert_eq!(state("")["error"].is_string(), true);
assert_eq!(post(port, "/relay/push/unsubscribe", &s, json!({"endpoint": "https://push.example/1"})).0, 200); assert_eq!(post(port, "/relay/push/unsubscribe", &s, json!({"endpoint": "https://push.example/1"})).0, 200);
assert!(relay.data.lock().unwrap().subs.is_empty()); assert!(relay.data.lock().unwrap().subs.is_empty());
assert_eq!(state(&s)["on"], false);
#[cfg(unix)] #[cfg(unix)]
{ {
use std::os::unix::fs::PermissionsExt; use std::os::unix::fs::PermissionsExt;

View File

@ -49,6 +49,8 @@ static STOPPING: AtomicBool = AtomicBool::new(false);
mod branch; mod branch;
mod talk_ui; mod talk_ui;
mod group; mod group;
#[cfg(test)]
mod layout_audit;
// Sidebar rules from index.eager-app: defaults `FT={expandedWidth:280}` (), // Sidebar rules from index.eager-app: defaults `FT={expandedWidth:280}` (),
// clamp `jT(..,240,400)` (), and the drag rule in `QJe` (): // clamp `jT(..,240,400)` (), and the drag rule in `QJe` ():
@ -559,6 +561,10 @@ impl App {
crate::i18n::set(&app.state.language); crate::i18n::set(&app.state.language);
app.computers_start(); app.computers_start();
// Banners come from AnyBot itself (its icon; a click opens that bot's chat).
if !app.demo && app.screenshot.is_none() {
notify::prepare();
}
// The computer the person used last time (a brain that restarted for an update). // The computer the person used last time (a brain that restarted for an update).
if !app.demo { if !app.demo {
if let Some(h) = crate::remote::load_person_host() { if let Some(h) = crate::remote::load_person_host() {
@ -1092,6 +1098,35 @@ impl App {
if std::env::var("ANYBOT_SHOT_NOPOPUP").is_ok() { if std::env::var("ANYBOT_SHOT_NOPOPUP").is_ok() {
app.popup_hidden.extend(app.state.bots.iter().map(|b| b.id)); app.popup_hidden.extend(app.state.bots.iter().map(|b| b.id));
} }
// ANYBOT_SHOT_PANEL=1: the right panel open on any demo view (without starting the box).
if std::env::var("ANYBOT_SHOT_PANEL").is_ok() {
app.panel = Some(panel_ui::PanelTab::Activity);
}
// ANYBOT_SHOT_TAB=<name>: 設定 open on that page (each page checked at any window size).
if let Ok(tab) = std::env::var("ANYBOT_SHOT_TAB") {
let tab = match tab.as_str() {
"general" => Some(SettingsTab::General),
"providers" => Some(SettingsTab::Providers),
"channels" => Some(SettingsTab::Channels),
"computers" => Some(SettingsTab::Computers),
"review" => Some(SettingsTab::Review),
"vault" => Some(SettingsTab::Vault),
"voice" => Some(SettingsTab::Voice),
"updates" => Some(SettingsTab::Updates),
"remote" => Some(SettingsTab::Remote),
_ => None,
};
if let Some(tab) = tab {
app.show_settings = true;
app.settings_tab = tab;
}
}
// ANYBOT_SHOT_STATUS=<text>: what a running turn says it is doing (a long retry message).
if let Ok(s) = std::env::var("ANYBOT_SHOT_STATUS") {
for l in app.streams.values_mut() {
l.status = Some(s.clone());
}
}
} }
app.apply_theme(ctx); app.apply_theme(ctx);
// Real-data screenshots can open 設定 › 手機與帳號 (to press its buttons with ANYBOT_SHOT_CLICK) // Real-data screenshots can open 設定 › 手機與帳號 (to press its buttons with ANYBOT_SHOT_CLICK)
@ -1972,9 +2007,9 @@ impl App {
if chime { if chime {
crate::voice::chime(); crate::voice::chime();
} }
notify::banner_with(&format!("{} 完成了", b.name), &last, !chime); notify::banner_for(&format!("{} 完成了", b.name), &last, !chime, Some(bot_id));
} }
crate::remote::notify(&format!("{} 完成了", b.name), &last, bot_id); crate::remote::notify(crate::remote::Notice::Done, &format!("{} 完成了", b.name), &last, bot_id);
} }
} }
// Messages that arrived too late to steer start the next turn. // Messages that arrived too late to steer start the next turn.
@ -2035,9 +2070,9 @@ impl App {
self.dirty = true; self.dirty = true;
if let Some((name, title, why)) = paused { if let Some((name, title, why)) = paused {
if !self.headless && !self.demo { if !self.headless && !self.demo {
notify::banner_with(&format!("{name} 的例行任務暫停了"), &format!("「{title}」{why}"), false); notify::banner_for(&format!("{name} 的例行任務暫停了"), &format!("「{title}」{why}"), false, Some(bot_id));
} }
crate::remote::notify(&format!("{name} 的例行任務暫停了"), &format!("「{title}」{why}"), bot_id); crate::remote::notify(crate::remote::Notice::Routine, &format!("{name} 的例行任務暫停了"), &format!("「{title}」{why}"), bot_id);
} }
} }
@ -3395,7 +3430,9 @@ impl App {
ui.label(RichText::new(format!("在:{machine}")).size(12.0).color(p.text3)); ui.label(RichText::new(format!("在:{machine}")).size(12.0).color(p.text3));
} }
ui.add_space(6.0); ui.add_space(6.0);
ui.horizontal(|ui| { // (Wrapped: in a narrow window the long 「一律允許…」 goes to the next line instead of
// running out of the card.)
ui.horizontal_wrapped(|ui| {
let once = if kind == ApprovalKind::Action { "允許" } else { "允許這一次" }; let once = if kind == ApprovalKind::Action { "允許" } else { "允許這一次" };
ui.spacing_mut().button_padding = vec2(14.0, 7.0); ui.spacing_mut().button_padding = vec2(14.0, 7.0);
if ui.add(egui::Button::new(RichText::new(once).strong().family(crate::bold()).color(p.on_primary)).fill(p.primary).corner_radius(12).min_size(vec2(0.0, if big { 34.0 } else { 0.0 }))).clicked() { if ui.add(egui::Button::new(RichText::new(once).strong().family(crate::bold()).color(p.on_primary)).fill(p.primary).corner_radius(12).min_size(vec2(0.0, if big { 34.0 } else { 0.0 }))).clicked() {
@ -3756,9 +3793,9 @@ impl App {
} }
if !self.headless { if !self.headless {
// The banner doesn't ring a second time when the 提示音 just did. // The banner doesn't ring a second time when the 提示音 just did.
notify::banner_with(&title, &what, !chime); notify::banner_for(&title, &what, !chime, Some(bot_id));
} }
crate::remote::notify(&title, &what, bot_id); crate::remote::notify(crate::remote::Notice::Need, &title, &what, bot_id);
} }
} }
} }
@ -3970,7 +4007,15 @@ impl App {
// (+, then the words, then two buttons: 28 px each, 8 px apart.) // (+, then the words, then two buttons: 28 px each, 8 px apart.)
let right_w = 28.0 * 2.0 + 8.0 + 4.0; let right_w = 28.0 * 2.0 + 8.0 + 4.0;
let text_w = (ui.available_width() - 28.0 - 8.0 - right_w).max(60.0); let text_w = (ui.available_width() - 28.0 - 8.0 - right_w).max(60.0);
let hint = if self.mir.on && !self.mir.online { t("連不到大腦,現在只能看") } else { t("傳訊息給 {name}").replace("{name}", &bot.name) }; // (A long bot name ends in … so the hint stays inside the box.)
let hint = if self.mir.on && !self.mir.online {
t("連不到大腦,現在只能看")
} else {
let words = t("傳訊息給 {name}");
let rest = ui.painter().layout_no_wrap(words.replace("{name}", ""), egui::FontId::proportional(COMPOSER_FONT), p.text).size().x;
let room = text_w - 8.0 - rest;
words.replace("{name}", &sidebar_ui::shorten_width(ui, &bot.name, room.max(24.0), COMPOSER_FONT))
};
// The words at the chat's size and spacing; the box grows with them (long lines // The words at the chat's size and spacing; the box grows with them (long lines
// wrap) up to about two fifths of the window, then scrolls. // wrap) up to about two fifths of the window, then scrolls.
let text_col = p.text; let text_col = p.text;
@ -4089,17 +4134,19 @@ impl App {
// The notice and the steer queue each get their own line; the notice also fades // The notice and the steer queue each get their own line; the notice also fades
// away on its own (see update), so it can't sit on the queue forever. // away on its own (see update), so it can't sit on the queue forever.
if let Some(n) = &notice { if let Some(n) = &notice {
ui.horizontal(|ui| { ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
ui.label(RichText::new(n).size(11.0).color(p.accent));
if small_button(ui, "知道了", p).clicked() { if small_button(ui, "知道了", p).clicked() {
self.notice = None; self.notice = None;
} }
ui.with_layout(Layout::left_to_right(Align::Center).with_main_wrap(true), |ui| {
ui.add(egui::Label::new(RichText::new(n).size(11.0).color(p.accent)).wrap());
});
}); });
} }
if !queued.is_empty() { if !queued.is_empty() {
let first: String = queued.last().unwrap().chars().take(30).collect(); let first: String = queued.last().unwrap().chars().take(30).collect();
let more = if queued.len() > 1 { format!(" 等 {} 則", queued.len()) } else { String::new() }; let more = if queued.len() > 1 { format!(" 等 {} 則", queued.len()) } else { String::new() };
ui.label(RichText::new(format!("已排入「{first}」{more},Bot 會在下一步看到")).size(11.0).color(p.accent)); ui.add(egui::Label::new(RichText::new(format!("已排入「{first}」{more},Bot 會在下一步看到")).size(11.0).color(p.accent)).wrap());
} }
}); });
ui.add_space(10.0); ui.add_space(10.0);
@ -4461,7 +4508,8 @@ impl App {
ui.label(RichText::new(t("Bot 名稱")).size(FONT_XS).color(p.text2)); ui.label(RichText::new(t("Bot 名稱")).size(FONT_XS).color(p.text2));
ui.add(egui::TextEdit::singleline(&mut b.name).desired_width(w)); ui.add(egui::TextEdit::singleline(&mut b.name).desired_width(w));
field_label(ui, "Bot 描述", p); field_label(ui, "Bot 描述", p);
ui.add(egui::TextEdit::singleline(&mut b.description).hint_text(t("它負責做什麼?")).desired_width(w)); // (Two lines that wrap: a description is a sentence, not a name.)
ui.add(egui::TextEdit::multiline(&mut b.description).hint_text(t("它負責做什麼?")).desired_width(w).desired_rows(2));
}); });
}); });
ui.add_space(16.0); ui.add_space(16.0);
@ -4695,8 +4743,8 @@ impl App {
}); });
}); });
dialog_footer(ui, p, |ui| { dialog_footer(ui, p, |ui| {
ui.checkbox(&mut b.pinned, t("釘選到側邊欄")); // The buttons first, from the right; the two choices stack in the room left of
ui.checkbox(&mut b.team, t("團隊成員可以使用這個 Bot(看得到它的聊天、頁面和檔案)")); // them and wrap there (the long one used to run under 取消 and 儲存).
ui.with_layout(Layout::right_to_left(Align::Center), |ui| { ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
if ui.add_enabled(!b.name.trim().is_empty() && !b.model.trim().is_empty(), primary_button(if is_new { "建立 Bot" } else { "儲存" }, p)).clicked() { if ui.add_enabled(!b.name.trim().is_empty() && !b.model.trim().is_empty(), primary_button(if is_new { "建立 Bot" } else { "儲存" }, p)).clicked() {
save = true; save = true;
@ -4704,6 +4752,12 @@ impl App {
if ui.add(secondary_button("取消")).clicked() { if ui.add(secondary_button("取消")).clicked() {
cancel = true; cancel = true;
} }
ui.add_space(8.0);
ui.with_layout(Layout::top_down(Align::Min), |ui| {
ui.spacing_mut().item_spacing.y = 4.0;
ui.checkbox(&mut b.pinned, t("釘選到側邊欄"));
ui.checkbox(&mut b.team, t("團隊成員可以使用這個 Bot(看得到它的聊天、頁面和檔案)"));
});
}); });
}); });
}); });
@ -5077,12 +5131,14 @@ impl App {
for (i, r) in rules.iter().enumerate() { for (i, r) in rules.iter().enumerate() {
Frame::new().fill(p.elevated).corner_radius(8).inner_margin(Margin::symmetric(10, 4)).show(ui, |ui| { Frame::new().fill(p.elevated).corner_radius(8).inner_margin(Margin::symmetric(10, 4)).show(ui, |ui| {
ui.set_width(ui.available_width()); ui.set_width(ui.available_width());
ui.horizontal(|ui| { // 刪除 keeps its place at the right; a long rule wraps
ui.label(r); // in the room left of it (it ran under 刪除).
ui.with_layout(Layout::right_to_left(Align::Center), |ui| { ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
if ui.add(egui::Button::new(RichText::new(t("刪除")).size(12.0).color(p.text3)).frame(false)).clicked() { if ui.add(egui::Button::new(RichText::new(t("刪除")).size(12.0).color(p.text3)).frame(false)).clicked() {
remove = Some(i); remove = Some(i);
} }
ui.with_layout(Layout::left_to_right(Align::Center).with_main_wrap(true), |ui| {
ui.add(egui::Label::new(r.as_str()).wrap());
}); });
}); });
}); });
@ -5093,14 +5149,15 @@ impl App {
} }
let draft = if which == 0 { &mut self.new_allow_rule } else { &mut self.new_ask_rule }; let draft = if which == 0 { &mut self.new_allow_rule } else { &mut self.new_ask_rule };
ui.add_space(2.0); ui.add_space(2.0);
ui.horizontal(|ui| { // The button first (its own width in any font), the field
let w = ui.available_width() - 96.0; // takes the rest.
ui.add(egui::TextEdit::singleline(draft).hint_text(if which == 0 { "例如:在工作資料夾裡建立文字檔" } else { "例如:刪除任何檔案" }).desired_width(w)); ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
if ui.add_enabled(!draft.trim().is_empty(), secondary_button("新增規則")).clicked() { if ui.add_enabled(!draft.trim().is_empty(), secondary_button("新增規則")).clicked() {
rules.push(draft.trim().to_string()); rules.push(draft.trim().to_string());
draft.clear(); draft.clear();
self.dirty = true; self.dirty = true;
} }
ui.add(egui::TextEdit::singleline(draft).hint_text(t(if which == 0 { "例如:在工作資料夾裡建立文字檔" } else { "例如:刪除任何檔案" })).desired_width(ui.available_width()));
}); });
}); });
} }
@ -5831,6 +5888,13 @@ impl eframe::App for App {
ctx.memory_mut(|m| m.request_focus(egui::Id::unique("sidebar-search"))); ctx.memory_mut(|m| m.request_focus(egui::Id::unique("sidebar-search")));
} }
} }
// A click on one of AnyBot's banners: that bot's chat (macOS brings AnyBot to the front).
for id in notify::take_clicked() {
if self.state.bot(id).is_some() {
self.show_settings = false;
self.select_bot(ctx, id);
}
}
// ⌘1–⌘9 (Ctrl on Windows and Linux): the first nine bots, in the sidebar's own order. // ⌘1–⌘9 (Ctrl on Windows and Linux): the first nine bots, in the sidebar's own order.
if let Some(n) = bot_jump_key(ctx) { if let Some(n) = bot_jump_key(ctx) {
if let Some(id) = self.sidebar_order().get(n).copied() { if let Some(id) = self.sidebar_order().get(n).copied() {
@ -6799,10 +6863,24 @@ fn bot_jump_key(ctx: &egui::Context) -> Option<usize> {
ctx.input(|i| (i.modifiers.command && !i.modifiers.shift && !i.modifiers.alt).then(|| NUM_KEYS.iter().position(|k| i.key_pressed(*k))).flatten()) ctx.input(|i| (i.modifiers.command && !i.modifiers.shift && !i.modifiers.alt).then(|| NUM_KEYS.iter().position(|k| i.key_pressed(*k))).flatten())
} }
thread_local! {
/// The layout check (layout_audit) scrolls dialogs to see their lower rows.
static DIALOG_SCROLL: std::cell::Cell<Option<f32>> = const { std::cell::Cell::new(None) };
}
/// Where dialogs are scrolled to for a picture or a check: ANYBOT_SHOT_SCROLL=<points> (a
/// screenshot of a dialog's lower rows), or the layout check's own.
fn forced_dialog_scroll() -> Option<f32> {
DIALOG_SCROLL.with(|c| c.get()).or_else(|| std::env::var("ANYBOT_SHOT_SCROLL").ok().and_then(|v| v.parse::<f32>().ok()))
}
/// The scrolling middle of a dialog, `reserve` px kept free for its footer. /// The scrolling middle of a dialog, `reserve` px kept free for its footer.
fn dialog_body<R>(ui: &mut egui::Ui, id: impl std::hash::Hash + std::fmt::Debug, max_height: f32, body: impl FnOnce(&mut egui::Ui) -> R) -> R { fn dialog_body<R>(ui: &mut egui::Ui, id: impl std::hash::Hash + std::fmt::Debug, max_height: f32, body: impl FnOnce(&mut egui::Ui) -> R) -> R {
egui::ScrollArea::vertical() let mut area = egui::ScrollArea::vertical();
.id_salt(id) if let Some(y) = forced_dialog_scroll() {
area = area.vertical_scroll_offset(y);
}
area.id_salt(id)
.max_height(max_height) .max_height(max_height)
.auto_shrink([false, true]) .auto_shrink([false, true])
.show(ui, |ui| { .show(ui, |ui| {

View File

@ -492,7 +492,10 @@ impl App {
let desc = if on { format!("每天 {}", at.trim()) } else { String::new() }; let desc = if on { format!("每天 {}", at.trim()) } else { String::new() };
sec_row_s(ui, p, "自動更新", &desc, "有新映像檔可用時,電腦會在你選的時間自動更新;錯過的話一小時內還會補做。開始後不能取消;有 Bot 在用電腦時會等它做完。", |ui| { sec_row_s(ui, p, "自動更新", &desc, "有新映像檔可用時,電腦會在你選的時間自動更新;錯過的話一小時內還會補做。開始後不能取消;有 Bot 在用電腦時會等它做完。", |ui| {
let changed = ui.add(toggle(&mut on)).changed(); let changed = ui.add(toggle(&mut on)).changed();
let r = ui.add(egui::TextEdit::singleline(&mut at).desired_width(56.0).char_limit(5).font(egui::TextStyle::Monospace)); // As wide as 「00:00」 in this font (a fixed 56 cut the last digit in some fonts).
let digits = ui.painter().layout_no_wrap("00:00".into(), egui::TextStyle::Monospace.resolve(ui.style()), p.text).size().x;
// (+ the field's own padding, 9 px each side, and room for the cursor.)
let r = ui.add(egui::TextEdit::singleline(&mut at).desired_width(digits + 26.0).char_limit(5).font(egui::TextStyle::Monospace));
typed |= r.changed(); typed |= r.changed();
if changed || r.lost_focus() { if changed || r.lost_focus() {
schedule_changed = true; schedule_changed = true;

View File

@ -99,9 +99,9 @@ impl App {
} }
let body = first_line(&note.replace('\n', " "), 120); let body = first_line(&note.replace('\n', " "), 120);
if !self.headless { if !self.headless {
notify::banner(title, &body); notify::banner_for(title, &body, true, Some(bot_id));
} }
crate::remote::notify(title, &body, bot_id); crate::remote::notify(crate::remote::Notice::Done, title, &body, bot_id);
} }
/// 清除聊天記錄 / 開始新對話: the goal goes with the chat it was set in (Claude Code's /clear /// 清除聊天記錄 / 開始新對話: the goal goes with the chat it was set in (Claude Code's /clear

269
src/app/layout_audit.rs Normal file
View File

@ -0,0 +1,269 @@
// 版面檢查: draws AnyBot's screens without a window (the demo data, each font of 設定 › 一般 ›
// 字型, the narrowest window and a wide one) and looks at every piece of text that was drawn:
//
// - 被切掉: text that runs past the left or right edge of the area it is drawn in (a field, a
// panel, a dialog) — the person sees half a word, or nothing after the cut.
// - 疊在一起: two pieces of text in the same area drawn over each other (a long label running
// into the button or value next to it).
//
// Scrolling is not a problem (a row half under the bottom edge is fine): only left and right.
use super::*;
use eframe::App as _;
use egui::epaint::{ClippedShape, Shape};
/// One piece of text as drawn: where, inside which clip, and what it says.
struct Word {
clip: egui::Rect,
rect: egui::Rect,
text: String,
}
fn words(shapes: &[ClippedShape]) -> Vec<Word> {
fn walk(clip: egui::Rect, s: &Shape, out: &mut Vec<Word>) {
match s {
Shape::Text(t) => {
let text = t.galley.text().trim().to_string();
if !text.is_empty() {
out.push(Word { clip, rect: t.visual_bounding_rect(), text });
}
}
Shape::Vec(v) => v.iter().for_each(|x| walk(clip, x, out)),
_ => {}
}
}
let mut out = vec![];
for c in shapes {
walk(c.clip_rect, &c.shape, &mut out);
}
out
}
/// What is wrong with the text in one drawn frame, in words a person can find on screen.
/// `long_fields`: long words typed into a one-line field scroll inside it (that is how a field
/// works), so they are not counted then.
pub fn problems(shapes: &[ClippedShape], long_fields: bool) -> Vec<String> {
let ws: Vec<Word> = words(shapes).into_iter().filter(|w| w.clip.intersects(w.rect) && w.clip.width() > 4.0).collect();
let short = |s: &str| s.chars().take(40).collect::<String>().replace('\n', " ");
let mut out = vec![];
for w in &ws {
let over = (w.rect.max.x - w.clip.max.x).max(w.clip.min.x - w.rect.min.x);
let in_field = w.clip.height() < 40.0 && w.rect.min.x >= w.clip.min.x - 1.0;
if over > 1.5 && !(long_fields && in_field) {
out.push(format!("被切掉 {over:.0}px:「{}」", short(&w.text)));
}
}
for (i, a) in ws.iter().enumerate() {
for b in &ws[i + 1..] {
if a.clip != b.clip || a.text == b.text {
continue;
}
let both = a.rect.intersect(b.rect);
if both.width() > 2.0 && both.height() > 5.0 {
out.push(format!("疊在一起:「{}」和「{}」", short(&a.text), short(&b.text)));
}
}
}
out.sort();
out.dedup();
out
}
/// Draw the app a few frames (layouts settle over two or three) and return the last frame's shapes.
fn draw(app: &mut App, ctx: &egui::Context, size: egui::Vec2) -> Vec<ClippedShape> {
let mut frame = eframe::Frame::_new_kittest();
let mut shapes = vec![];
for _ in 0..4 {
let input = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, size)), ..Default::default() };
let mut out = ctx.run_ui(input, |ui| app.ui(ui, &mut frame));
out.textures_delta.clear();
shapes = out.shapes;
}
shapes
}
/// How to open one screen on a fresh demo app.
type Open = Box<dyn Fn(&mut App)>;
/// The screens checked: a name, and how to open it.
fn scenes() -> Vec<(&'static str, Open)> {
let tab = |t: SettingsTab| -> Open {
Box::new(move |a: &mut App| {
a.show_settings = true;
a.settings_tab = t;
})
};
vec![
("設定 › 一般", tab(SettingsTab::General)),
("設定 › 手機與帳號", tab(SettingsTab::Remote)),
("設定 › 模型", tab(SettingsTab::Providers)),
("設定 › 整合 › 訊息管道", tab(SettingsTab::Channels)),
(
"設定 › 整合 › 連接器",
Box::new(|a: &mut App| {
a.show_settings = true;
a.settings_tab = SettingsTab::Channels;
a.ch.sub = 1;
}),
),
(
"設定 › 整合 › 技能",
Box::new(|a: &mut App| {
a.show_settings = true;
a.settings_tab = SettingsTab::Channels;
a.ch.sub = 2;
}),
),
("設定 › 電腦", tab(SettingsTab::Computers)),
("設定 › 權限", tab(SettingsTab::Review)),
("設定 › 保險庫", tab(SettingsTab::Vault)),
("設定 › 語音", tab(SettingsTab::Voice)),
("設定 › 更新", tab(SettingsTab::Updates)),
(
"右側面板(進行中,長的重試訊息)",
Box::new(|a: &mut App| {
a.state.selected = 5;
a.popup_hidden.extend(a.state.bots.iter().map(|b| b.id));
a.panel = Some(panel_ui::PanelTab::Activity);
for l in a.streams.values_mut() {
l.status = Some("模型服務回應錯誤(429 Too Many Requests):{\"type\":\"error\",\"error\":{\"type\":\"rate_limit_error\"}},12 秒後再試".into());
}
}),
),
(
"右側面板 › 資料庫",
Box::new(|a: &mut App| {
a.state.selected = 1;
a.panel = Some(panel_ui::PanelTab::Library);
}),
),
(
"Bot 設定",
Box::new(|a: &mut App| {
if let Some(b) = a.state.bots.first().cloned() {
a.edit_bot = Some((b, false));
}
}),
),
(
"例行任務",
Box::new(|a: &mut App| {
let id = a.state.bots.iter().find(|b| !b.routines.is_empty()).map(|b| b.id).unwrap_or(1);
a.show_routines = Some(id);
}),
),
]
}
/// The demo data with every name and line as long as a person's real ones get: long bot names
/// and descriptions, connectors with long commands, skills with long descriptions, a channel, a
/// few SSH computers, routines with long titles, folders deep in the disk.
fn worst_case(app: &mut App) {
let long = "客戶服務與售後追蹤小組・每週報表整理專用助理(台北辦公室)";
for (i, b) in app.state.bots.iter_mut().enumerate() {
b.name = format!("{long}{i}");
b.description = "負責整理每週的客戶回饋、追蹤未結案的工單、彙整成報表後寄給主管,並在 Slack 上提醒負責的同事".into();
for r in &mut b.routines {
r.title = "每天早上九點整理昨天所有客戶回饋與未結案工單,寄出摘要給主管並在頻道提醒".into();
}
}
let server = |name: &str, command: &str, url: &str| -> crate::mcp::Server {
serde_json::from_value(serde_json::json!({"name": name, "command": command, "args": ["-y", "@modelcontextprotocol/server-filesystem", "/Users/someone/Documents/Projects/very-long-folder-name/another-level"], "url": url})).expect("server")
};
app.state.mcp_servers = vec![
server("playwright-browser-automation-for-testing", "npx", ""),
server("company-internal-knowledge-base-search", "", "https://mcp.internal.example-company.com.tw/v1/knowledge-base/streamable-http"),
server("fetch", "uvx", ""),
];
for sk in &mut app.state.skills {
sk.name = format!("{}-with-a-much-longer-name-than-usual", sk.name);
sk.description = "建立、編輯、分析試算表檔案(.xlsx、.xlsm、.csv、.tsv),包含公式、格式、圖表、樞紐分析與資料清理,並在完成後驗證每個儲存格的計算結果".into();
}
app.state.channels = vec![serde_json::from_value(serde_json::json!({"id": 1, "kind": "Telegram", "name": "客戶服務群組・台北辦公室與高雄辦公室共用的通知頻道", "bot_id": app.state.bots[0].id, "token": "123456:ABC", "target": "-1001234567890123"})).expect("channel")];
app.state.remote_computers = (0..3)
.map(|i| serde_json::from_value(serde_json::json!({"name": format!("辦公室三樓會議室旁邊的 Linux 伺服器 {i}"), "ssh_target": format!("administrator@build-server-{i}.internal.example-company.com.tw"), "dir": "/srv/projects/customer-service/reports/weekly"})).expect("computer"))
.collect();
app.state.doc_folders = vec!["/Users/someone/Library/Mobile Documents/com~apple~CloudDocs/工作/客戶服務/2026 年度報表與會議紀錄".into()];
app.state.review_allow_rules = vec!["在工作資料夾(~/Documents/Projects/customer-service/reports)裡建立或修改文字檔與試算表".into()];
app.state.review_ask_rules = vec!["刪除任何檔案、清空資料夾,或是把檔案移到垃圾桶之外的任何地方".into()];
}
/// One font and one set of data, every screen at every width.
fn audit_one(font: &str, worst: bool) -> Vec<String> {
let data = if worst { "長資料" } else { "示範" };
let mut report = vec![];
// The narrowest window AnyBot allows, a usual one, and a wide one.
for w in [SIDEBAR_MIN_WIDTH + CHAT_MIN_WIDTH, 1000.0, 1440.0] {
for (name, open) in scenes() {
let ctx = egui::Context::default();
crate::load_fonts_as(&ctx, font);
let mut app = App::new(&ctx, Some(std::env::temp_dir().join("anybot-layout-audit.png")));
app.popup_hidden.extend(app.state.bots.iter().map(|b| b.id));
if worst {
worst_case(&mut app);
}
open(&mut app);
// Dialogs show part of a page at a time: down the page until nothing new shows.
let mut seen: std::collections::HashSet<String> = Default::default();
for step in 0..12 {
super::DIALOG_SCROLL.with(|c| c.set(Some(step as f32 * 400.0)));
let shapes = draw(&mut app, &ctx, vec2(w, 1000.0));
let texts: Vec<String> = words(&shapes).into_iter().filter(|x| x.clip.intersects(x.rect)).map(|x| x.text).collect();
let fresh = texts.iter().filter(|t| !seen.contains(*t)).count();
seen.extend(texts);
for p in problems(&shapes, worst) {
report.push(format!("[{data} {font} {w:.0}] {name}: {p}"));
}
if step > 0 && fresh == 0 {
break;
}
}
super::DIALOG_SCROLL.with(|c| c.set(None));
}
}
report
}
/// Every screen, font and width: what is cut off or drawn over something else (each font and
/// set of data on a thread of its own).
fn audit() -> Vec<String> {
let runs: Vec<_> = ["noto", "huninn", "system"]
.into_iter()
.flat_map(|f| [(f, false), (f, true)])
.map(|(font, worst)| std::thread::Builder::new().stack_size(64 << 20).spawn(move || audit_one(font, worst)).expect("thread"))
.collect();
let mut report: Vec<String> = runs.into_iter().flat_map(|h| h.join().expect("layout check")).collect();
report.sort();
report.dedup();
report
}
#[test]
fn text_stays_inside_its_place_on_every_screen() {
let report = audit();
assert!(report.is_empty(), "{} 個版面問題:\n{}", report.len(), report.join("\n"));
}
#[test]
fn the_check_sees_cut_and_overlapping_text() {
// A label running into its neighbour, and a word past its field's edge, are both found.
let ctx = egui::Context::default();
let mut shapes = vec![];
for _ in 0..2 {
let input = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(400.0, 200.0))), ..Default::default() };
let mut out = ctx.run_ui(input, |ui| {
let p = ui.painter();
let font = egui::FontId::proportional(13.0);
p.text(egui::pos2(10.0, 10.0), egui::Align2::LEFT_TOP, "模型服務回應錯誤(429 Too Many Requests)", font.clone(), Color32::WHITE);
p.text(egui::pos2(120.0, 10.0), egui::Align2::LEFT_TOP, "停止", font.clone(), Color32::WHITE);
ui.painter().with_clip_rect(egui::Rect::from_min_size(egui::pos2(10.0, 60.0), vec2(30.0, 20.0))).text(egui::pos2(10.0, 60.0), egui::Align2::LEFT_TOP, "03:00", font, Color32::WHITE);
});
out.textures_delta.clear();
shapes = out.shapes;
}
let found = problems(&shapes, false);
assert!(found.iter().any(|p| p.starts_with("疊在一起") && p.contains("停止")), "{found:?}");
assert!(found.iter().any(|p| p.starts_with("被切掉") && p.contains("03:00")), "{found:?}");
}

View File

@ -289,9 +289,14 @@ impl App {
if r.hovered() { if r.hovered() {
ui.painter().rect_filled(rect, 9, p.hover); ui.painter().rect_filled(rect, 9, p.hover);
} }
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))); // (The name stops before the member's screen, and ends in … when it is long.)
let mut words = rect.shrink2(vec2(10.0, 0.0));
if pic.is_some() {
words.max.x -= 48.0;
}
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(words).layout(Layout::left_to_right(Align::Center)));
avatar::avatar(&mut child, 20.0, &b.shape, col); avatar::avatar(&mut child, 20.0, &b.shape, col);
child.label(RichText::new(&b.name).size(13.0).color(p.text)); child.add(egui::Label::new(RichText::new(&b.name).size(13.0).color(p.text)).truncate());
if let Some((tex, size)) = pic { 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 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 on = *key == shown;
@ -505,8 +510,14 @@ fn panel_row(ui: &mut egui::Ui, p: Palette, icon: Option<crate::icons::Icon>, la
crate::icons::paint(ui.painter(), egui::Rect::from_center_size(egui::pos2(x + 8.0, rect.center().y), vec2(15.0, 15.0)), ic, p.text2); crate::icons::paint(ui.painter(), egui::Rect::from_center_size(egui::pos2(x + 8.0, rect.center().y), vec2(15.0, 15.0)), ic, p.text2);
x += 26.0; x += 26.0;
} }
ui.painter().text(egui::pos2(x, rect.center().y), egui::Align2::LEFT_CENTER, label, egui::FontId::proportional(13.0), p.text);
let right = rect.right() - 12.0; let right = rect.right() - 12.0;
// The value (or the chevron) keeps its place at the right; the label gets the room that is
// left and ends in … (a long retry message ran over 停止 and out of the card).
let value_w = if chevron { 14.0 } else if value.is_empty() { 0.0 } else { text_width(ui, value, 13.0) + 12.0 };
let shown = super::sidebar_ui::shorten_width(ui, label, (right - value_w - x).max(24.0), 13.0);
let cut = shown != label;
ui.painter().text(egui::pos2(x, rect.center().y), egui::Align2::LEFT_CENTER, shown, egui::FontId::proportional(13.0), p.text);
let r = if cut { r.on_hover_text(label) } else { r };
if chevron { if chevron {
let c = egui::pos2(right - 3.0, rect.center().y); let c = egui::pos2(right - 3.0, rect.center().y);
let st = Stroke::new(1.4, p.text3); let st = Stroke::new(1.4, p.text3);

View File

@ -3423,7 +3423,7 @@ mod tests {
use chrono::TimeZone; use chrono::TimeZone;
let at = chrono::Utc.with_ymd_and_hms(2026, 11, 6, 19, 0, 0).unwrap().with_timezone(&chrono_tz::Asia::Taipei); 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!(in_schedule_window("03:00", at.time()));
assert_eq!(wanted_version(), "10"); assert_eq!(wanted_version(), "11");
// Every file the Dockerfile copies is one this app carries (build_image writes them). // 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"]; 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 ")) { for l in DOCKERFILE.lines().filter_map(|l| l.trim().strip_prefix("COPY ")) {

View File

@ -622,7 +622,7 @@ pub fn kick() {
let before: Vec<String> = o.received().into_iter().map(|r| r.id).collect(); let before: Vec<String> = o.received().into_iter().map(|r| r.id).collect();
o.deliver(&me, &|host, args, who| crate::remote::run_on_device(host, PUT, args, who), &|p| { o.deliver(&me, &|host, args, who| crate::remote::run_on_device(host, PUT, args, who), &|p| {
let what = if p.text.is_empty() { format!("「{}」({})可以下載了", p.name, crate::attach::human(p.bytes)) } else { format!("一段文字:{}", p.name) }; let what = if p.text.is_empty() { format!("「{}」({})可以下載了", p.name, crate::attach::human(p.bytes)) } else { format!("一段文字:{}", p.name) };
crate::remote::notify(&format!("{} 傳來的", p.from), &what, 0); crate::remote::notify(crate::remote::Notice::File, &format!("{} 傳來的", p.from), &what, 0);
}); });
// What was for this brain's own computer landed without the device road. // What was for this brain's own computer landed without the device road.
let new: Vec<Received> = o.received().into_iter().filter(|r| !before.contains(&r.id)).collect(); let new: Vec<Received> = o.received().into_iter().filter(|r| !before.contains(&r.id)).collect();

View File

@ -144,6 +144,11 @@ pub fn font_choice() -> String {
} }
pub fn load_fonts(ctx: &egui::Context) { pub fn load_fonts(ctx: &egui::Context) {
load_fonts_as(ctx, &font_choice());
}
/// The fonts for one choice of 設定 › 一般 › 字型 ("noto", "huninn" or "system").
pub fn load_fonts_as(ctx: &egui::Context, choice: &str) {
let mut fonts = egui::FontDefinitions::default(); let mut fonts = egui::FontDefinitions::default();
// One font for Chinese *and* English: mixing egui's built-in Latin font with a Chinese // One font for Chinese *and* English: mixing egui's built-in Latin font with a Chinese
// fallback put the two on different baselines and sizes ("Bot 設定" looked broken). // fallback put the two on different baselines and sizes ("Bot 設定" looked broken).
@ -188,7 +193,7 @@ pub fn load_fonts(ctx: &egui::Context) {
// 粉圓體 (jf open 粉圓, SIL OFL 1.1, fonts/OFL.txt) goes first everywhere it has the letter; // 粉圓體 (jf open 粉圓, SIL OFL 1.1, fonts/OFL.txt) goes first everywhere it has the letter;
// the system font above fills in what it lacks (some simplified characters, symbols). // the system font above fills in what it lacks (some simplified characters, symbols).
// 思源黑體 the same way (the default). // 思源黑體 the same way (the default).
let bundled: Option<(&str, &'static [u8])> = match font_choice().as_str() { let bundled: Option<(&str, &'static [u8])> = match choice {
"huninn" => Some(("huninn", HUNINN)), "huninn" => Some(("huninn", HUNINN)),
"noto" => Some(("noto", NOTO_TC)), "noto" => Some(("noto", NOTO_TC)),
_ => None, _ => None,
@ -202,7 +207,7 @@ pub fn load_fonts(ctx: &egui::Context) {
} }
// Bold: the same list with the bold weight in front, where there is one. // Bold: the same list with the bold weight in front, where there is one.
let mut heavy = fonts.families.get(&egui::FontFamily::Proportional).cloned().unwrap_or_default(); let mut heavy = fonts.families.get(&egui::FontFamily::Proportional).cloned().unwrap_or_default();
let noto = font_choice() == "noto"; let noto = choice == "noto";
if noto { if noto {
fonts.font_data.insert("noto-bold".into(), egui::FontData::from_static(NOTO_TC_BOLD).into()); fonts.font_data.insert("noto-bold".into(), egui::FontData::from_static(NOTO_TC_BOLD).into());
heavy.insert(0, "noto-bold".into()); heavy.insert(0, "noto-bold".into());
@ -217,6 +222,11 @@ fn app_icon() -> egui::IconData {
svg_icon(include_str!("../icons/anybot.svg"), 256) svg_icon(include_str!("../icons/anybot.svg"), 256)
} }
/// AnyBot's icon (the cat on yellow) as straight RGBA, `px` square (notification banners).
pub fn app_icon_rgba(px: u32) -> Vec<u8> {
svg_icon(include_str!("../icons/anybot.svg"), px).rgba
}
/// An SVG drawn to a square RGBA picture of `px` pixels. /// An SVG drawn to a square RGBA picture of `px` pixels.
fn svg_icon(svg: &str, px: u32) -> egui::IconData { fn svg_icon(svg: &str, px: u32) -> egui::IconData {
let tree = resvg::usvg::Tree::from_str(svg, &resvg::usvg::Options::default()).expect("icon svg"); let tree = resvg::usvg::Tree::from_str(svg, &resvg::usvg::Options::default()).expect("icon svg");
@ -297,6 +307,7 @@ const USAGE: &str = "用法:
anybot setup … 在沒有螢幕的機器上設定 anybot setup … 在沒有螢幕的機器上設定
anybot --install-skill 來源 安裝技能(GitHub 網址、owner/repo/path、SKILL.md 網址或本機資料夾) anybot --install-skill 來源 安裝技能(GitHub 網址、owner/repo/path、SKILL.md 網址或本機資料夾)
anybot --screenshot 檔名 把視窗畫成一張圖 anybot --screenshot 檔名 把視窗畫成一張圖
anybot --banner 標題 內文 送一則通知,看它怎麼送出(Mac:AnyBot.app 自己的通知)
anybot --version 印出版本(v0.0.1-36bc2be · 建置時間) anybot --version 印出版本(v0.0.1-36bc2be · 建置時間)
資料夾:ANYBOT_DATA_DIR(沒設就用這個使用者的 AnyBot 資料夾)"; 資料夾:ANYBOT_DATA_DIR(沒設就用這個使用者的 AnyBot 資料夾)";
@ -341,6 +352,13 @@ fn main() -> eframe::Result<()> {
} }
return Ok(()); return Ok(());
} }
// `anybot --banner 標題 內文`: send one banner the way a bot's would (checks that AnyBot.app's
// own notifications work: its icon, allowed in 系統設定 › 通知).
if args.get(1).map(String::as_str) == Some("--banner") {
notify::prepare();
println!("{}", notify::banner_now(args.get(2).map(String::as_str).unwrap_or("AnyBot"), args.get(3).map(String::as_str).unwrap_or("通知測試")));
return Ok(());
}
if args.get(1).map(String::as_str) == Some("--write-icon") { if args.get(1).map(String::as_str) == Some("--write-icon") {
let out = args.get(2).cloned().unwrap_or_else(|| "anybot.png".into()); let out = args.get(2).cloned().unwrap_or_else(|| "anybot.png".into());
let px = args.get(3).and_then(|v| v.parse().ok()).unwrap_or(256); let px = args.get(3).and_then(|v| v.parse().ok()).unwrap_or(256);

View File

@ -118,22 +118,204 @@ pub fn banner_script_with(title: &str, body: &str, sound: bool) -> String {
} }
} }
/// Show a macOS banner. AnyBot isn't a signed .app bundle when run from a build folder, so it can't /// Show a banner, with the system's sound. Doesn't wait.
/// ask the notification center itself (the original's module needs a bundle); macOS's own
/// `display notification` is used instead. Doesn't wait.
pub fn banner(title: &str, body: &str) { pub fn banner(title: &str, body: &str) {
banner_with(title, body, true) banner_for(title, body, true, None)
} }
/// A banner, with or without the system's sound. /// A banner about one bot: a click on it opens that bot's chat (`take_clicked`).
pub fn banner_with(title: &str, body: &str, sound: bool) { ///
/// - macOS, inside AnyBot.app: the app's own banner (`center`), with AnyBot's icon (the cat on
/// yellow); a click brings AnyBot to the front on that bot. Run from a build folder (no bundle),
/// macOS's `display notification` instead (that banner shows Script Editor's icon).
/// - Linux: the desktop's notification service through notify-send, with AnyBot's icon.
pub fn banner_for(title: &str, body: &str, sound: bool, bot: Option<u64>) {
let body: String = body.chars().take(180).collect();
if !cfg!(target_os = "macos") { if !cfg!(target_os = "macos") {
// The desktop's notification service (GNOME, KDE, XFCE…) through notify-send. // The desktop's notification service (GNOME, KDE, XFCE…) through notify-send.
let body: String = body.chars().take(180).collect(); let mut cmd = Command::new("notify-send");
let _ = crate::computer::spawn_reaped(Command::new("notify-send").args(["-a", "AnyBot", title, &body]).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null())); cmd.args(["-a", "AnyBot"]);
if let Some(icon) = icon_png() {
cmd.arg("-i").arg(icon);
}
let _ = crate::computer::spawn_reaped(cmd.args([title, &body]).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()));
return; return;
} }
let _ = crate::computer::spawn_reaped(Command::new("osascript").arg("-e").arg(banner_script_with(title, body, sound)).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null())); #[cfg(target_os = "macos")]
if center::post(title, &body, sound, bot) {
return;
}
let _ = bot;
let _ = crate::computer::spawn_reaped(Command::new("osascript").arg("-e").arg(banner_script_with(title, &body, sound)).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()));
}
/// One banner from a command (`anybot --banner`): sends it and says which way it went.
pub fn banner_now(title: &str, body: &str) -> String {
banner_for(title, body, true, None);
#[cfg(target_os = "macos")]
{
if !center::usable() {
return "不在 AnyBot.app 裡:用 display notification 送出(圖示會是「工序指令編寫程式」)".into();
}
// (A moment for the system to take it before the program ends.)
std::thread::sleep(std::time::Duration::from_secs(1));
format!("AnyBot 自己的通知,通知中心裡有 {} 則 AnyBot 的通知", center::delivered())
}
#[cfg(not(target_os = "macos"))]
{
"notify-send".into()
}
}
/// Get ready to show banners (macOS: hear clicks on them, and show them while AnyBot is in front
/// but the person is idle). Call once at start, on the main thread.
pub fn prepare() {
#[cfg(target_os = "macos")]
center::prepare();
}
/// Bots whose banner the person clicked since the last call (the app opens that chat).
pub fn take_clicked() -> Vec<u64> {
#[cfg(target_os = "macos")]
{
center::take_clicked()
}
#[cfg(not(target_os = "macos"))]
{
vec![]
}
}
/// The identifier a banner gets: which bot it is about, and a number so each one is its own.
pub fn banner_id(bot: Option<u64>, n: u64) -> String {
format!("anybot-{}-{n}", bot.map(|b| b.to_string()).unwrap_or_else(|| "-".into()))
}
/// The bot a banner identifier is about.
pub fn bot_of_banner(id: &str) -> Option<u64> {
id.strip_prefix("anybot-")?.split('-').next()?.parse().ok()
}
/// AnyBot's icon as a PNG file for notify-send (drawn once into the data folder).
#[cfg_attr(target_os = "macos", allow(dead_code))]
fn icon_png() -> Option<std::path::PathBuf> {
static PATH: std::sync::OnceLock<Option<std::path::PathBuf>> = std::sync::OnceLock::new();
PATH.get_or_init(|| {
let path = crate::model::State::path().parent()?.join("anybot-icon.png");
if path.exists() {
return Some(path);
}
let icon = crate::app_icon_rgba(128);
image::RgbaImage::from_raw(128, 128, icon)?.save(&path).ok()?;
Some(path)
})
.clone()
}
/// AnyBot.app's own banners: NSUserNotificationCenter. The newer UNUserNotificationCenter only
/// lets apps signed by an Apple developer team send notifications (it answers "Notifications are
/// not allowed for this application"); AnyBot signs itself on each Mac (deploy/mac/sign.sh), and
/// the older center takes its banners, with the app's icon, without asking first. 系統設定 › 通知
/// › AnyBot still decides whether and how they show.
#[cfg(target_os = "macos")]
mod center {
use objc2::rc::Retained;
use objc2::runtime::{AnyClass, NSObject, NSObjectProtocol, ProtocolObject};
use objc2::{define_class, msg_send, ClassType};
#[allow(deprecated)]
use objc2_foundation::{NSBundle, NSString, NSUserNotification, NSUserNotificationCenter, NSUserNotificationCenterDelegate};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Mutex, Once};
static PREPARED: Once = Once::new();
static USABLE: AtomicBool = AtomicBool::new(false);
static NEXT: AtomicU64 = AtomicU64::new(1);
static CLICKED: Mutex<Vec<u64>> = Mutex::new(Vec::new());
define_class!(
// Shows AnyBot's banners while AnyBot is in front too (they're only sent when the person
// is away, and idle in front of it counts), and hears which banner was clicked.
#[unsafe(super(NSObject))]
#[name = "AnyBotBannerDelegate"]
struct Delegate;
unsafe impl NSObjectProtocol for Delegate {}
#[allow(deprecated)]
unsafe impl NSUserNotificationCenterDelegate for Delegate {
#[unsafe(method(userNotificationCenter:shouldPresentNotification:))]
fn should_present(&self, _center: &NSUserNotificationCenter, _n: &NSUserNotification) -> bool {
true
}
#[unsafe(method(userNotificationCenter:didActivateNotification:))]
fn did_activate(&self, _center: &NSUserNotificationCenter, n: &NSUserNotification) {
if let Some(bot) = n.identifier().and_then(|id| super::bot_of_banner(&id.to_string())) {
if let Ok(mut c) = CLICKED.lock() {
c.push(bot);
}
}
}
}
);
/// Inside a real .app with an identifier (the center is nil for a bare program), on a macOS
/// that still has the center.
fn in_bundle() -> bool {
let b = NSBundle::mainBundle();
AnyClass::get(c"NSUserNotificationCenter").is_some() && b.bundleIdentifier().is_some() && b.bundlePath().to_string().ends_with(".app")
}
pub fn prepare() {
PREPARED.call_once(|| {
if !in_bundle() {
return;
}
USABLE.store(true, Ordering::SeqCst);
let delegate: Retained<Delegate> = unsafe { msg_send![Delegate::class(), new] };
#[allow(deprecated)]
unsafe {
NSUserNotificationCenter::defaultUserNotificationCenter().setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
}
// The center keeps only a weak reference: the delegate lives as long as AnyBot.
std::mem::forget(delegate);
});
}
pub fn usable() -> bool {
prepare();
USABLE.load(Ordering::SeqCst)
}
/// Show the banner. False: not inside AnyBot.app (the caller uses display notification).
#[allow(deprecated)]
pub fn post(title: &str, body: &str, sound: bool, bot: Option<u64>) -> bool {
if !usable() {
return false;
}
let n = NSUserNotification::new();
n.setTitle(Some(&NSString::from_str(title)));
n.setInformativeText(Some(&NSString::from_str(body)));
n.setIdentifier(Some(&NSString::from_str(&super::banner_id(bot, NEXT.fetch_add(1, Ordering::SeqCst)))));
if sound {
n.setSoundName(Some(&NSString::from_str("Glass")));
}
NSUserNotificationCenter::defaultUserNotificationCenter().deliverNotification(&n);
true
}
/// How many of AnyBot's banners the system is keeping (`anybot --banner`'s check).
#[allow(deprecated)]
pub fn delivered() -> usize {
if !usable() {
return 0;
}
NSUserNotificationCenter::defaultUserNotificationCenter().deliveredNotifications().count()
}
pub fn take_clicked() -> Vec<u64> {
CLICKED.lock().map(|mut c| std::mem::take(&mut *c)).unwrap_or_default()
}
} }
#[cfg(test)] #[cfg(test)]
@ -169,6 +351,13 @@ mod tests {
assert_eq!(s, "display notification \"執行 \\\"rm\\\" \\\\ 指令下一行\" with title \"電腦助手 需要你允許\" sound name \"Glass\""); assert_eq!(s, "display notification \"執行 \\\"rm\\\" \\\\ 指令下一行\" with title \"電腦助手 需要你允許\" sound name \"Glass\"");
} }
#[test]
fn a_banner_click_finds_its_bot() {
assert_eq!(bot_of_banner(&banner_id(Some(42), 7)), Some(42));
assert_eq!(bot_of_banner(&banner_id(None, 7)), None);
assert_eq!(bot_of_banner("something-else"), None);
}
#[test] #[test]
fn a_banner_can_be_silent() { fn a_banner_can_be_silent() {
// (When AnyBot plays its own 提示音, the banner doesn't add a second sound.) // (When AnyBot plays its own 提示音, the banner doesn't add a second sound.)

View File

@ -2109,17 +2109,53 @@ pub fn sync_file(s: &Settings, path: &str) -> Result<Vec<u8>, String> {
} }
/// A notification on the person's phones (through the relay; phones that turned them on). /// A notification on the person's phones (through the relay; phones that turned them on).
pub fn notify(title: &str, body: &str, bot: u64) { pub fn notify(kind: Notice, title: &str, body: &str, bot: u64) {
let s = hub().settings(); let s = hub().settings();
if s.relay_url.is_empty() || s.host_token.is_empty() { if s.relay_url.is_empty() || s.host_token.is_empty() {
return; return;
} }
// The number on the app's icon: bots waiting for the person (this one too, when it just
// started waiting — the phone's view may not have it yet).
let mut waiting: std::collections::BTreeSet<u64> = hub().view.lock().unwrap().approvals.iter().filter_map(|a| a["bot"].as_u64()).collect();
match kind {
Notice::Need => {
waiting.insert(bot);
}
Notice::Done => {
waiting.remove(&bot);
}
_ => {}
}
let (title, body) = (title.to_string(), body.to_string()); let (title, body) = (title.to_string(), body.to_string());
std::thread::spawn(move || { std::thread::spawn(move || {
let _ = relay_post(&format!("{}/relay/host/notify", s.relay_url), &s.host_token, &json!({"title": title, "body": body, "bot": bot})); let _ = relay_post(&format!("{}/relay/host/notify", s.relay_url), &s.host_token, &json!({"title": title, "body": body, "bot": bot, "kind": kind.key(), "badge": waiting.len()}));
}); });
} }
/// What a phone notification is about; each phone picks which ones it gets (手機 › 通知).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Notice {
/// 需要你允許、問你、需要你處理.
Need,
/// Done while you were away (a turn, a goal).
Done,
/// 例行任務暫停了.
Routine,
/// Something sent to this computer arrived (傳送到其他裝置).
File,
}
impl Notice {
pub fn key(self) -> &'static str {
match self {
Notice::Need => "need",
Notice::Done => "done",
Notice::Routine => "routine",
Notice::File => "file",
}
}
}
/// 發布網站: upload a folder (or one page) to the account server; returns the public address. /// 發布網站: upload a folder (or one page) to the account server; returns the public address.
pub fn publish_site(name: &str, local: &std::path::Path) -> Result<String, String> { pub fn publish_site(name: &str, local: &std::path::Path) -> Result<String, String> {
use base64::Engine; use base64::Engine;
@ -2367,11 +2403,19 @@ const PAGE: &str = include_str!("../mobile/index.html");
/// The bots' computer, watched and used in a browser (noVNC; see vnc.rs). /// The bots' computer, watched and used in a browser (noVNC; see vnc.rs).
const SCREEN_PAGE: &str = include_str!("../mobile/screen.html"); const SCREEN_PAGE: &str = include_str!("../mobile/screen.html");
const NOVNC: &str = include_str!("../mobile/novnc.js"); const NOVNC: &str = include_str!("../mobile/novnc.js");
pub const MANIFEST: &str = r##"{"name":"AnyBot","short_name":"AnyBot","start_url":"./","display":"standalone","background_color":"#121212","theme_color":"#121212","icons":[{"src":"icon.svg","sizes":"any","type":"image/svg+xml"},{"src":"icon-192.png","sizes":"192x192","type":"image/png","purpose":"any maskable"},{"src":"icon-512.png","sizes":"512x512","type":"image/png","purpose":"any maskable"}]}"##; pub const MANIFEST: &str = include_str!("../mobile/manifest.webmanifest");
/// The app's icon, the same drawing everywhere (icons/anybot.svg is the Mac/Linux one). /// The app's icon, the same drawing everywhere (icons/anybot.svg is the Mac/Linux one).
pub const ICON: &str = include_str!("../mobile/icon.svg"); pub const ICON: &str = include_str!("../mobile/icon.svg");
/// PNG sizes for the iPhone home screen (it ignores SVG) and Android. /// PNGs for the iPhone home screen (it ignores SVG), Android (full-bleed ones for its masks) and
pub const ICON_PNGS: [(&str, &[u8]); 3] = [("icon-180.png", include_bytes!("../mobile/icon-180.png")), ("icon-192.png", include_bytes!("../mobile/icon-192.png")), ("icon-512.png", include_bytes!("../mobile/icon-512.png"))]; /// the one-colour cat Android shows in the status bar.
pub const ICON_PNGS: [(&str, &[u8]); 6] = [
("icon-180.png", include_bytes!("../mobile/icon-180.png")),
("icon-192.png", include_bytes!("../mobile/icon-192.png")),
("icon-512.png", include_bytes!("../mobile/icon-512.png")),
("icon-maskable-192.png", include_bytes!("../mobile/icon-maskable-192.png")),
("icon-maskable-512.png", include_bytes!("../mobile/icon-maskable-512.png")),
("badge-96.png", include_bytes!("../mobile/badge-96.png")),
];
pub fn page() -> Resp { pub fn page() -> Resp {
Resp::bytes("text/html; charset=utf-8", PAGE.as_bytes().to_vec()).with_header("Content-Security-Policy", &format!("default-src 'self'; img-src 'self' blob: data:; media-src 'self' blob:; frame-src 'self' blob:; style-src 'self' 'unsafe-inline'; {}; connect-src 'self' ws: wss:; base-uri 'none'; object-src 'none'; frame-ancestors 'none'", httpd::script_src(PAGE))) Resp::bytes("text/html; charset=utf-8", PAGE.as_bytes().to_vec()).with_header("Content-Security-Policy", &format!("default-src 'self'; img-src 'self' blob: data:; media-src 'self' blob:; frame-src 'self' blob:; style-src 'self' 'unsafe-inline'; {}; connect-src 'self' ws: wss:; base-uri 'none'; object-src 'none'; frame-ancestors 'none'", httpd::script_src(PAGE)))