diff --git a/Cargo.lock b/Cargo.lock
index 4096ad6..f4fb8ea 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -367,6 +367,8 @@ dependencies = [
"libc",
"memmap2",
"mermaid-rs-renderer",
+ "objc2 0.6.5",
+ "objc2-foundation 0.3.2",
"pdf-extract",
"portable-pty",
"pulldown-cmark",
diff --git a/Cargo.toml b/Cargo.toml
index 631a71a..be1a76f 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -97,6 +97,10 @@ async-io = "2"
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.
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]
# Copying text from a thread of its own (platform::copy_text); already in the build through egui.
diff --git a/docs/feature-map/chat.md b/docs/feature-map/chat.md
index fa71000..ab7a4b6 100644
--- a/docs/feature-map/chat.md
+++ b/docs/feature-map/chat.md
@@ -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 在同一輪回應那句;按停止,送出鈕變回來、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::`(最窄的視窗裡允許卡片的按鈕會換行、「已排入…」和輸入框的提示不會被切掉)。
## 陷阱
diff --git a/docs/feature-map/phone.md b/docs/feature-map/phone.md
index 8008a6d..a7d8f9d 100644
--- a/docs/feature-map/phone.md
+++ b/docs/feature-map/phone.md
@@ -13,22 +13,26 @@
- 手機可以做什麼:聊天、核准、看 Bot 的電腦一律可以;「從手機看這台電腦的螢幕並操作」和「裝置連結」預設關閉。
- 分享給團隊(登入後):把這台的 Bot 分享給帳號伺服器上的其他帳號,選成員或管理員([team](team.md))。
- 手機頁面:Bot 清單(分區、工作中/等你)、聊天(附檔、拍照、語音輸入、插話、停止)、允許請求卡片(「一律允許」「允許一次」或「允許」、「拒絕」、「全部允許,之後直接操作」)、問題卡、「需要處理」與接管、Bot 設定、例行任務(詳細頁有最近幾次執行和送出證據)、頁面、記憶、檔案預覽、Bot 的電腦畫面、設定、傳送到其他裝置。
-- 通知:需要你允許、問你、需要你處理,你不在時做完事,例行任務暫停,收到傳來的檔案——推播到開了通知的手機,點了直接打開那個 Bot。
+- 通知:需要你允許、問你、需要你處理,你不在時做完事,例行任務暫停,收到傳來的檔案——推播到開了通知的手機,點了直接打開那個 Bot。每支手機自己選要哪幾種(需要你/做完了/例行任務暫停/收到傳來的檔案),可以送一則測試通知。通知的圖示是 AnyBot 的貓,Android 狀態列是貓的單色剪影;App 圖示上的數字是正在等你的 Bot。
+- 像 App 一樣:加入主畫面後全螢幕、沒有網址列(瀏海、動態島、底部手勢條、橫放都避開);首頁會提示「把 AnyBot 裝成 App」(Android 直接安裝,iPhone 教你加入主畫面,可以關掉);換畫面會左右滑動;iPhone 主畫面 App 從左邊緣往右滑回上一頁。
## 使用者怎麼到
- 電腦:設定 › 一般 › 帳戶 ›「登入」(登入後是「管理帳戶」)打開「手機與帳號」頁,左上「‹ 一般」回去。由上到下:「手機與帳號」「AnyBot 帳號」、大腦(登入後)、「同一個網路直接連」「手機可以做什麼」「直接連線的裝置」「分享給團隊」「帳號裡的電腦」(最後兩個登入後才有)。
- 手機:打開帳號伺服器的網址用帳號登入;或打開設定頁列出的網址用手機密碼登入。可以「加入主畫面」當 App。
+- 手機:左上角帳戶選單 ›「通知」(開關、要通知哪幾種、測試通知)、「安裝成 App」(還沒裝時才有)。
- 手機的 設定 › 手機與帳號:直接連線的手機;用帳號登入時另有通知、兩步驗證、登入的裝置、「加一台電腦」(擁有者)、「切換到別台 AnyBot」;最下面「登出這支手機」。
## 怎麼操作
- 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 秒沒動)才推。
- 直接連線的連接埠預設 8793,被占用會往後找;照設定頁列出的網址打開。不要把它開放到網際網路,從外面連用帳號或 Tailscale。
- 第一次用 https 打開,手機會警告憑證:選「繼續」;要確認沒連錯台,比對設定頁上的 SHA-256 指紋。
diff --git a/docs/feature-map/settings.md b/docs/feature-map/settings.md
index 64bc1e6..8999b72 100644
--- a/docs/feature-map/settings.md
+++ b/docs/feature-map/settings.md
@@ -8,7 +8,7 @@
- 「一般」:
- 外觀:主題、聊天的顏色、字型、語言(選單和 Bot 回答用的語言)。
- 記憶與文件:用意思找記憶(本機模型/Ollama/關閉)、Bot 可以翻的資料夾([memory](memory.md))。
- - 通知:Bot 做完或等你時通知、需要你時響一聲([phone](phone.md))。
+ - 通知:Bot 做完或等你時通知、需要你時響一聲([phone](phone.md))。Mac 上的通知是 AnyBot.app 自己發的(貓的圖示),點一下打開那個 Bot;從建置資料夾直接跑(不是 .app)時改用系統的 display notification,圖示會是「工序指令編寫程式」。
- Bot:時區,例行任務和提醒用([routines](routines.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 換深色主題、時區改 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 設定要按「儲存」才算;關掉或按「取消」就不存。
- 連到別台大腦的螢幕電腦上,模型金鑰、語音這些是大腦的設定,改了存在大腦;主題、強調色、「在這台電腦上執行」、手機與帳號還是這台自己的([computers](computers.md))。
- 被管理員鎖住的開關是灰的,旁邊寫「由你的管理員設定,無法變更」([safety](safety.md))。
+- 「Bot 做完或等你時通知」開著卻沒有橫幅:看 macOS 系統設定 › 通知 › AnyBot 是不是被關掉;`anybot --banner 標題 內文`(用 AnyBot.app 裡的那個程式)會送一則並說是怎麼送的。
diff --git a/mobile/badge-96.png b/mobile/badge-96.png
new file mode 100644
index 0000000..2a3614b
Binary files /dev/null and b/mobile/badge-96.png differ
diff --git a/mobile/icon-maskable-192.png b/mobile/icon-maskable-192.png
new file mode 100644
index 0000000..51cc971
Binary files /dev/null and b/mobile/icon-maskable-192.png differ
diff --git a/mobile/icon-maskable-512.png b/mobile/icon-maskable-512.png
new file mode 100644
index 0000000..714c143
Binary files /dev/null and b/mobile/icon-maskable-512.png differ
diff --git a/mobile/index.html b/mobile/index.html
index 81f93d1..6c33c51 100644
--- a/mobile/index.html
+++ b/mobile/index.html
@@ -4,6 +4,9 @@
+
+
+
@@ -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}
.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}
+/* ---- 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}
@@ -486,6 +521,7 @@ textarea.field{min-height:96px;line-height:1.5}
+
@@ -644,6 +680,7 @@ const LUCIDE = {
"users": '',
"bookmark": '',
"power": '',
+ "share": '',
"download": '',
"globe": '',
"key": '',
@@ -699,7 +736,7 @@ function plain(t) { return String(t || "").replace(/\[([^\]]+)\]\([^)]+\)/g, "$1
// 外觀 of this phone: follow it, or light or dark by hand.
const THEMES = [["", "跟著手機"], ["light", "淺色"], ["dark", "深色"]];
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();
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 ----------
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) {
+ S.dir = replace ? "" : "in-fwd";
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}, "");
draw(v, arg);
@@ -810,6 +863,7 @@ window.addEventListener("popstate", () => {
NAV.pop();
if (!NAV.length) { NAV.push({v: "home", arg: {}}); history.pushState({n: 1}, ""); }
const t = NAV[NAV.length - 1];
+ S.dir = S.swiped ? "" : "in-back"; S.swiped = false;
closeSheet();
draw(t.v, t.arg);
});
@@ -937,7 +991,7 @@ async function start() {
function apply(v) {
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.voice = v.voice || {}; micShown();
+ S.voice = v.voice || {}; micShown(); appBadge();
const t = cur();
if (t.v === "home") renderHome();
else if (t.v === "chat") {
@@ -967,6 +1021,7 @@ function botRow(b) {
return `${`
${avatarSvg(b.shape, b.color)}${st.dot ? `` : ""}
`}
${esc(b.name)}${b.members ? '群組' : ""}
${esc(st.text)}
${ago(b.time)}
`;
}
function renderHome() {
+ installHint();
$("host-name").textContent = S.hostName ? "· " + S.hostName : "";
$("b-me").textContent = (S.hostName || "A").slice(0, 1).toUpperCase();
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(); }})));
}});
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.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(); }});
@@ -2820,23 +2876,103 @@ async function pair() {
}
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)); }
+// 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() {
- if (!pushOK()) { sheet("通知", [], `${/iPhone|iPad/.test(navigator.userAgent) ? "iPhone 要先按分享 › 加入主畫面,從主畫面打開 AnyBot 才能開通知。" : "這個瀏覽器不支援通知。"}
`); return; }
- const reg = await navigator.serviceWorker.getRegistration();
- const sub = reg && await reg.pushManager.getSubscription();
- sheet("通知", [{icon: "bell", label: sub ? "關閉通知" : "開啟通知", on: async () => {
+ if (!pushOK()) {
+ const why = !S.relay ? "直接連線(同一個網路)收不到推播:用 AnyBot 帳號登入的手機才收得到。" : navigator.standalone === false ? "iPhone 要先按分享 › 加入主畫面,從主畫面打開 AnyBot 才能開通知。" : "這個瀏覽器不支援通知。";
+ sheet("通知", [], `${why}
`); return;
+ }
+ 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 = `` + item({icon: "bell", k: "這支手機的通知", v: blocked ? "被系統擋下了:到手機的設定 › 通知 › AnyBot 打開" : st.on ? "Bot 需要你時,會跳出通知" : "關閉中", sw: st.on && !blocked, swdata: 'data-push="1"', disabled: blocked}) + `
`;
+ if (st.on) {
+ h += `要通知我的事
` + KINDS.map(([k, n, v]) => item({k: n, v, sw: st.kinds.includes(k), swdata: `data-kind="${k}"`})).join("") + `
`;
+ h += ``;
+ }
+ h += `通知的圖示是 AnyBot 的貓;App 圖示上的數字是正在等你的 Bot。${navigator.standalone ? "聲音和橫幅樣式在 iPhone 的設定 › 通知 › AnyBot 調整。" : ""}
`;
+ const el = sheet("通知", [], h);
+ const on = el.querySelector("[data-push]");
+ if (on) on.onchange = async () => {
+ on.disabled = true;
try {
const r = await navigator.serviceWorker.register("sw.js"); await navigator.serviceWorker.ready;
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 {
- if (await Notification.requestPermission() !== "granted") { toast("沒有允許通知(可在系統設定裡打開)"); return; }
+ if (await Notification.requestPermission() !== "granted") { toast("沒有允許通知(可在手機的設定裡打開)"); notifySheet(); return; }
const {key} = await api("relay/push/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); }
- }}], `Bot 需要你允許、或在你不在時做完事,手機會跳通知。
`);
+ 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("加入主畫面", [], `1. 按 Safari 下方的分享按鈕 ${ic("share", 15)}\n2. 選「加入主畫面」\n3. 之後從主畫面的 AnyBot 打開:全螢幕、沒有網址列,也能開通知。
`);
+}
+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 = `
把 AnyBot 裝成 App全螢幕、從主畫面打開,Bot 需要你時會跳通知。
`;
+ $("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(() => {});
// A tapped notification opens that chat.
diff --git a/mobile/manifest.webmanifest b/mobile/manifest.webmanifest
new file mode 100644
index 0000000..056d96c
--- /dev/null
+++ b/mobile/manifest.webmanifest
@@ -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"}
+ ]
+}
diff --git a/mobile/sw.js b/mobile/sw.js
new file mode 100644
index 0000000..96bed7f
--- /dev/null
+++ b/mobile/sw.js
@@ -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);
+ }));
+});
diff --git a/relay/src/main.rs b/relay/src/main.rs
index d5e2a2f..6722ba4 100644
--- a/relay/src/main.rs
+++ b/relay/src/main.rs
@@ -32,10 +32,23 @@ const PAGE: &str = include_str!("../../mobile/index.html");
/// The bots' computer, watched and used in a browser (noVNC).
const SCREEN_PAGE: &str = include_str!("../../mobile/screen.html");
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"}]}"##;
-/// AnyBot's icon (the same drawing as the app's), and PNGs for the iPhone home screen and Android.
+/// The phone app's manifest and service worker (notifications), shared with the desktop's own
+/// 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_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".
const HOST_POLL_SECS: u64 = 25;
@@ -149,6 +162,31 @@ struct Sub {
user: String,
sub: Value,
created: i64,
+ /// What this phone wants to be told about (NOTICE_KINDS); empty: everything.
+ #[serde(default)]
+ kinds: Vec,
+}
+
+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> {
+ 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)]
@@ -164,23 +202,6 @@ struct Data {
sites: HashMap,
}
-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.
struct Answer {
@@ -277,7 +298,9 @@ struct Relay {
/// Two-step codes used in the last two minutes (see code_is_new).
used_codes: Mutex>,
/// One-time links for a browser to watch a host's computer: ticket → (account, host, made).
- tickets: Mutex>,
+ /// Screen tickets: who, which AnyBot's screen, when last good, and who asked (`s:`: a signed-in phone; `h:`: a computer of the account).
+ tickets: Mutex>,
/// 配對碼: code → (account, the AnyBot it is for, when made). Ten minutes, once.
pairs: Mutex>,
/// When each host last asked (in memory; saved now and then).
@@ -470,12 +493,13 @@ impl Relay {
/// admins only.
fn vnc_viewer(self: &Arc, req: Req, mut c: std::net::TcpStream, host: &str) {
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 user = match req.query.get("ticket").filter(|t| !t.is_empty()) {
- Some(t) => self.tickets.lock().unwrap().get(t).filter(|(_, h, made)| h == host && made.elapsed() < TICKET_LIFE).map(|(u, _, _)| u.clone()),
- None => self.session(&req),
+ let ticket = req.query.get("ticket").filter(|t| !t.is_empty()).cloned();
+ let session_hash = ticket.is_none().then(|| httpd::sha256_hex(&req.bearer()));
+ let who = match &ticket {
+ 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")));
if !allowed {
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::Text(t)) => Some(("vtext", t.as_bytes().to_vec())),
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(_) => 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 sess_ok = match &session_hash {
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
};
@@ -850,13 +885,14 @@ impl Relay {
// 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
// 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 !self.data.lock().unwrap().hosts.iter().any(|x| x.id == want && x.user == h.user) {
return Resp::error(404, "找不到這台 AnyBot");
}
- h.user
+ let asker = format!("h:{}", h.id);
+ (h.user, asker)
}
None => {
let Some(user) = self.session(&req) else { return Resp::error(401, "請先登入") };
@@ -864,13 +900,13 @@ impl Relay {
if !may {
return Resp::error(404, "找不到這台 AnyBot");
}
- user
+ (user, format!("s:{}", httpd::sha256_hex(&req.bearer())))
}
};
let t = httpd::random_hex(24);
let mut all = self.tickets.lock().unwrap();
- all.retain(|_, (_, _, made)| made.elapsed() < TICKET_LIFE);
- all.insert(t.clone(), (user, want, Instant::now()));
+ all.retain(|_, (_, _, made, _)| made.elapsed() < TICKET_LIFE);
+ all.insert(t.clone(), (user, want, Instant::now(), asker));
Resp::json(&json!({"ticket": t}))
}
("GET", ["manifest.webmanifest"]) => Resp::bytes("application/manifest+json", MANIFEST.as_bytes().to_vec()),
@@ -889,6 +925,7 @@ impl Relay {
return Resp::error(400, "通知訂閱資料不完整");
}
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();
d.subs.retain(|s| s.sub["endpoint"].as_str() != Some(endpoint.as_str()));
while d.subs.iter().filter(|s| s.user == user).count() >= 16 {
@@ -898,10 +935,44 @@ impl Relay {
break;
}
}
- d.subs.push(Sub { user, sub: clean, created: now() });
+ d.subs.push(Sub { user, sub: clean, created: now(), kinds });
self.save(&d);
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"]) => {
let Some(user) = self.session(&req) else { return Resp::error(401, "請先登入") };
let endpoint = req.json()["endpoint"].as_str().unwrap_or("").to_string();
@@ -914,8 +985,12 @@ impl Relay {
("POST", ["relay", "host", "notify"]) => {
let Some(h) = self.host(&req) else { return Resp::error(401, "這台電腦的金鑰無效") };
let v = req.json();
- let payload = json!({"title": v["title"].as_str().unwrap_or("AnyBot").chars().take(80).collect::(), "body": v["body"].as_str().unwrap_or("").chars().take(200).collect::(), "bot": v["bot"], "host": h.id});
- let subs: Vec = self.data.lock().unwrap().subs.iter().filter(|s| matches!(h.role_of(&s.user).as_deref(), Some("owner") | Some("admin"))).cloned().collect();
+ let kind = v["kind"].as_str().filter(|k| NOTICE_KINDS.contains(k)).unwrap_or("");
+ let mut payload = json!({"title": v["title"].as_str().unwrap_or("AnyBot").chars().take(80).collect::(), "body": v["body"].as_str().unwrap_or("").chars().take(200).collect::(), "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 = 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 sent = 0;
for s in &subs {
@@ -1688,7 +1763,7 @@ impl Relay {
self.save(&d);
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));
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!(post(port, "/relay/screen-ticket", paired_tok, json!({"host": brain["id"]})).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.
assert_eq!(post(port, "/relay/pair/claim", "", json!({"code": code, "name": "x"})).0, 404);
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/unsubscribe", "", json!({"endpoint": "https://push.example/1"})).0, 401);
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!(relay.data.lock().unwrap().subs.is_empty());
+ assert_eq!(state(&s)["on"], false);
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
diff --git a/src/app.rs b/src/app.rs
index d943023..7a0d24f 100644
--- a/src/app.rs
+++ b/src/app.rs
@@ -49,6 +49,8 @@ static STOPPING: AtomicBool = AtomicBool::new(false);
mod branch;
mod talk_ui;
mod group;
+#[cfg(test)]
+mod layout_audit;
// Sidebar rules from index.eager-app: defaults `FT={expandedWidth:280}` (),
// clamp `jT(..,240,400)` (), and the drag rule in `QJe` ():
@@ -559,6 +561,10 @@ impl App {
crate::i18n::set(&app.state.language);
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).
if !app.demo {
if let Some(h) = crate::remote::load_person_host() {
@@ -1092,6 +1098,35 @@ impl App {
if std::env::var("ANYBOT_SHOT_NOPOPUP").is_ok() {
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=: 設定 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=: 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);
// Real-data screenshots can open 設定 › 手機與帳號 (to press its buttons with ANYBOT_SHOT_CLICK)
@@ -1972,9 +2007,9 @@ impl App {
if 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.
@@ -2035,9 +2070,9 @@ impl App {
self.dirty = true;
if let Some((name, title, why)) = paused {
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.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 { "允許這一次" };
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() {
@@ -3756,9 +3793,9 @@ impl App {
}
if !self.headless {
// 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.)
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 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
// wrap) up to about two fifths of the window, then scrolls.
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
// away on its own (see update), so it can't sit on the queue forever.
if let Some(n) = ¬ice {
- ui.horizontal(|ui| {
- ui.label(RichText::new(n).size(11.0).color(p.accent));
+ ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
if small_button(ui, "知道了", p).clicked() {
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() {
let first: String = queued.last().unwrap().chars().take(30).collect();
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);
@@ -4461,7 +4508,8 @@ impl App {
ui.label(RichText::new(t("Bot 名稱")).size(FONT_XS).color(p.text2));
ui.add(egui::TextEdit::singleline(&mut b.name).desired_width(w));
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);
@@ -4695,8 +4743,8 @@ impl App {
});
});
dialog_footer(ui, p, |ui| {
- ui.checkbox(&mut b.pinned, t("釘選到側邊欄"));
- ui.checkbox(&mut b.team, t("團隊成員可以使用這個 Bot(看得到它的聊天、頁面和檔案)"));
+ // The buttons first, from the right; the two choices stack in the room left of
+ // them and wrap there (the long one used to run under 取消 and 儲存).
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() {
save = true;
@@ -4704,6 +4752,12 @@ impl App {
if ui.add(secondary_button("取消")).clicked() {
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() {
Frame::new().fill(p.elevated).corner_radius(8).inner_margin(Margin::symmetric(10, 4)).show(ui, |ui| {
ui.set_width(ui.available_width());
- ui.horizontal(|ui| {
- ui.label(r);
- 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() {
- remove = Some(i);
- }
+ // 刪除 keeps its place at the right; a long rule wraps
+ // in the room left of it (it ran under 刪除).
+ 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() {
+ 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 };
ui.add_space(2.0);
- ui.horizontal(|ui| {
- let w = ui.available_width() - 96.0;
- ui.add(egui::TextEdit::singleline(draft).hint_text(if which == 0 { "例如:在工作資料夾裡建立文字檔" } else { "例如:刪除任何檔案" }).desired_width(w));
+ // The button first (its own width in any font), the field
+ // takes the rest.
+ ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
if ui.add_enabled(!draft.trim().is_empty(), secondary_button("新增規則")).clicked() {
rules.push(draft.trim().to_string());
draft.clear();
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")));
}
}
+ // 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.
if let Some(n) = bot_jump_key(ctx) {
if let Some(id) = self.sidebar_order().get(n).copied() {
@@ -6799,10 +6863,24 @@ fn bot_jump_key(ctx: &egui::Context) -> Option {
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