diff --git a/mobile/index.html b/mobile/index.html index 5c9b140..83815bd 100644 --- a/mobile/index.html +++ b/mobile/index.html @@ -50,6 +50,14 @@ a{color:var(--accent-ink)} .app{height:100dvh;display:flex;flex-direction:column;overflow:hidden} .view{flex:1;display:none;flex-direction:column;min-height:0;background:var(--pane)} .view.on{display:flex} +/* Push navigation: a new screen slides in from the right, a 返回 one from the left. */ +@keyframes pushIn{from{transform:translateX(26%);opacity:.35}to{transform:none;opacity:1}} +@keyframes popIn{from{transform:translateX(-18%);opacity:.35}to{transform:none;opacity:1}} +.view.on.dirF{animation:pushIn .2s cubic-bezier(.25,.75,.4,1)} +.view.on.dirB{animation:popIn .2s cubic-bezier(.25,.75,.4,1)} +@keyframes msgIn{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:none}} +.m.fresh{animation:msgIn .18s ease-out} +@media (prefers-reduced-motion:reduce){.view.on.dirF,.view.on.dirB,.m.fresh{animation:none}} .scroll{flex:1;overflow-y:auto;-webkit-overflow-scrolling:touch;min-height:0} /* ---- bars ---- */ @@ -198,7 +206,8 @@ a{color:var(--accent-ink)} .sug .ic{color:var(--text2)} .sug .tt{font-size:14px;font-weight:500}.sug .dd{font-size:12px;color:var(--text3)} /* the dock: approvals, queued steering, attachments, the composer */ -.dock{flex:none;padding:6px 10px calc(var(--safe-b) + 8px);background:linear-gradient(to bottom,transparent,var(--chrome) 40%)} +/* --kb: the iOS keyboard floats over the page; the script measures it and lifts the composer. */ +.dock{flex:none;padding:6px 10px calc(var(--safe-b) + 8px + var(--kb,0px));background:linear-gradient(to bottom,transparent,var(--chrome) 40%)} /* 需要你: yellow is the one colour for what waits for the person. */ .ask{max-width:560px;margin:0 auto 8px;padding:14px 16px;border-radius:20px;background:var(--attention-bg);box-shadow:inset 0 0 0 2px var(--attention)} .ask .q{font-weight:600;font-size:15px} @@ -696,6 +705,7 @@ applyTheme(); const S = { voice: {}, relay: false, token: localStorage.getItem("anybot.token") || "", host: localStorage.getItem("anybot.host") || "", version: 0, bots: [], approvals: [], pages: [], models: [], hostName: "", mac: false, box: "", boxOn: false, role: "owner", + prevShown: 0, answer: null, sc: "", open: 0, msgs: [], pending: [], quote: null, unfold: {}, openSteps: {}, detail: {}, audit: {}, settings: null, polling: false, chatSig: "", file: null, search: "", size: [0, 0], right: false, @@ -788,11 +798,19 @@ 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, dir = 0) { + document.querySelectorAll(".view").forEach((x) => x.classList.toggle("on", x.id === "v-" + v)); + if (dir && v !== "home") { + const el = document.getElementById("v-" + v); + el.classList.remove("dirF", "dirB"); void el.offsetWidth; // restart the slide + el.classList.add(dir > 0 ? "dirF" : "dirB"); + } + S.view = v; if (v !== "screen") stopFrames(); if (v !== "list") stopListTimer(); +} function go(v, arg = {}, replace = false) { 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); + draw(v, arg, replace ? 0 : 1); } function back() { if (NAV.length > 1) history.back(); else go("home", {}, true); } window.addEventListener("popstate", () => { @@ -802,11 +820,11 @@ window.addEventListener("popstate", () => { if (!NAV.length) { NAV.push({v: "home", arg: {}}); history.pushState({n: 1}, ""); } const t = NAV[NAV.length - 1]; closeSheet(); - draw(t.v, t.arg); + draw(t.v, t.arg, -1); }); document.querySelectorAll("[data-back]").forEach((b) => { b.innerHTML = ic("chevron-left", 24); b.onclick = back; }); -function draw(v, arg) { - show(v); +function draw(v, arg, dir = 0) { + show(v, dir); if (v === "home") renderHome(); else if (v === "chat") openChat(arg.bot); else if (v === "details") renderDetails(arg.bot, arg.tab); @@ -919,6 +937,16 @@ async function start() { } function apply(v) { S.bots = v.bots || []; S.approvals = v.approvals || []; S.hostName = v.host || ""; S.mac = !!v.mac; + // An approval answered from a notification banner, and a home-screen shortcut (主要 Bot, 未讀). + if (S.answer && S.token) { + const a = S.answer; S.answer = null; + api(base() + `api/bots/${a.bot}/answer`, {json: {answer: a.answer}}).then(() => toast("已從通知回覆")).catch((e) => toast(e.message)); + } + if (S.sc && !S.open) { + const want = S.sc === "unread" ? S.bots.find((b) => b.unread) : (S.bots.find((b) => b.primary) || S.bots[0]); + S.sc = ""; + if (want) { S.open = want.id; go("chat", {bot: want.id}); } + } 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(); const t = cur(); @@ -1099,7 +1127,7 @@ function chatHead() { } $("island").onclick = () => go("details", {bot: S.open}); function openChat(id) { - if (S.open !== id) { S.msgs = []; S.pending = []; S.quote = null; S.unfold = {}; S.openSteps = {}; S.chatSig = ""; $("msgs").innerHTML = ""; } + if (S.open !== id) { S.msgs = []; S.pending = []; S.quote = null; S.unfold = {}; S.openSteps = {}; S.chatSig = ""; S.prevShown = 0; $("msgs").innerHTML = ""; } S.open = id; // The chat takes its bot's colour: the person's bubble and the send button. const ob = bot(id) || {}, chat = $("v-chat"); @@ -1186,6 +1214,11 @@ function renderMsgs() { const lastMsg = S.msgs[S.msgs.length - 1]; const shown = {}; let day = ""; let h = ""; + // A message that arrived since the last draw slides up into place; the whole history on + // opening a chat draws plain (no animation on every old message). + const freshFrom = S.prevShown > 0 && S.msgs.length > S.prevShown ? S.prevShown : S.msgs.length; + S.prevShown = S.msgs.length; + const fr = (i) => (i >= freshFrom ? " fresh" : ""); S.msgs.forEach((m, i) => { if (m.at) { const d = dayLabel(m.at); if (d !== day) { day = d; h += `
${esc(d)}
`; } } const reacts = (m.reactions || []).length ? `
${m.reactions.map((e) => ``).join("")}
` : ""; @@ -1215,7 +1248,7 @@ function renderMsgs() { const mems = m.memories || []; const open = S.carried.has(String(m.at || i)); const carried = mems.length ? `${open ? `
${mems.map((x) => "• " + esc(x)).join("
")}
` : ""}` : ""; - h += `
${tag}${m.text ? `
${quote}${esc(text)}
` : ""}${(m.attachments || []).map(attHtml).join("")}${reacts}${carried}
`; + h += `
${tag}${m.text ? `
${quote}${esc(text)}
` : ""}${(m.attachments || []).map(attHtml).join("")}${reacts}${carried}
`; return; } const t = turnOf[i]; @@ -1236,7 +1269,7 @@ function renderMsgs() { const bub = m.text ? `
${pageMd(m.text, 0)}
` : ""; const atts = (m.attachments || []).map(attHtml).join(""); const meta = end && m.text ? `
${esc(m.via || "")}${m.at ? " · " + clock(m.at) : ""}${owner() && m === lastBot && t === lastTurn ? `` : ""}
` : ""; - h += `
${who}${think}${bub}${steps ? `
${steps}
` : ""}${extra}${atts}${reacts}${meta}
`; + h += `
${who}${think}${bub}${steps ? `
${steps}
` : ""}${extra}${atts}${reacts}${meta}
`; }); // Still working: what it is doing now; a message nobody answered yet can be sent again. if (busy) h += (lastMsg && lastMsg.role !== "user" && !lastMsg.text && !(lastMsg.tools || []).length) || lastMsg?.role === "user" ? `
` : ""; @@ -1316,6 +1349,7 @@ function renderDock() { $("ask").innerHTML = `
${esc(a.title)}
${esc(a.reason)}
${a.can_always ? `` : ``}
${isOwner() ? `${ic("zap", 13)} 全部允許,之後直接操作` : ""}
`; } $("ask").querySelectorAll("button[data-a]").forEach((x) => x.onclick = async () => { + if (navigator.vibrate) navigator.vibrate(8); $("ask").innerHTML = ""; try { await api(base() + `api/bots/${S.open}/answer`, {json: {answer: x.dataset.a}}); } catch (e) { toast(e.message); } }); @@ -1483,7 +1517,7 @@ async function send() { memReset(); input.value = ""; input.style.height = "auto"; $("composer").classList.remove("tall"); S.pending = []; renderChips(); renderSlash(); const quiet = /^\/goal(\s+(clear|stop|off|reset|none|cancel|清除|取消|停止))?\s*$/i.test(text); - if (!b.busy && !quiet) { S.msgs.push({role: "user", text, attachments: [], memories: memories || []}); renderMsgs(); $("scroller").scrollTop = 1e9; } + if (!b.busy && !quiet) { if (navigator.vibrate) navigator.vibrate(8); S.msgs.push({role: "user", text, attachments: [], memories: memories || []}); renderMsgs(); $("scroller").scrollTop = 1e9; } const body = {text, attachments}; if (memories) body.memories = memories; try { await api(base() + `api/bots/${S.open}/send`, {json: body}); if (quiet) loadChat(); else if (b.busy) toast("已排入,Bot 會在下一步看到"); } catch (e) { toast(e.message); input.value = text; } } @@ -2715,14 +2749,29 @@ function openFromHash() { if (h.get("host")) { S.host = h.get("host"); localStorage.setItem("anybot.host", S.host); } const b = +h.get("bot"); if (b) S.open = b; - if (location.hash) history.replaceState(null, "", location.pathname); + // Tapping 允許/拒絕 on a notification: answer it once the token is in place. + const ans = h.get("answer"); + if (ans && b && (ans === "once" || ans === "reject")) S.answer = {bot: b, answer: ans}; + const sc = new URLSearchParams(location.search).get("sc"); + if (sc) S.sc = sc; + if (location.hash || location.search) history.replaceState(null, "", location.pathname); } openFromHash(); if ("serviceWorker" in navigator) navigator.serviceWorker.addEventListener("message", (e) => { const d = e.data && e.data.open; if (!d) return; if (d.host && d.host !== S.host && S.relay) { S.host = d.host; localStorage.setItem("anybot.host", S.host); S.version = 0; } + if (d.answer && S.token && d.bot) api(base() + `api/bots/${d.bot}/answer`, {json: {answer: d.answer}}).then(() => toast("已從通知回覆")).catch((e) => toast(e.message)); if (d.bot) go("chat", {bot: +d.bot}); }); +// iOS: the keyboard floats over the page instead of shrinking it; measure it and lift the composer. +if (window.visualViewport) { + const kb = () => { + const k = Math.max(0, Math.round(innerHeight - visualViewport.height - visualViewport.offsetTop)); + document.documentElement.style.setProperty("--kb", k + "px"); + }; + visualViewport.addEventListener("resize", kb); + visualViewport.addEventListener("scroll", kb); +} document.addEventListener("visibilitychange", () => { if (!document.hidden && S.view === "screen") startFrames(); }); hello(); diff --git a/relay/src/main.rs b/relay/src/main.rs index f48e6ad..6c45363 100644 --- a/relay/src/main.rs +++ b/relay/src/main.rs @@ -32,7 +32,7 @@ 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"}]}"##; +const MANIFEST: &str = r##"{"id":"anybot","name":"AnyBot","short_name":"AnyBot","lang":"zh-Hant","start_url":"./","display":"standalone","display_override":["standalone","minimal-ui"],"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"}],"shortcuts":[{"name":"主要 Bot 對話","short_name":"主要 Bot","url":"./?sc=main","icons":[{"src":"icon-192.png","sizes":"192x192"}]},{"name":"未讀對話","short_name":"未讀","url":"./?sc=unread","icons":[{"src":"icon-192.png","sizes":"192x192"}]}]}"##; /// AnyBot's icon (the same drawing as the app's), and PNGs for the iPhone home screen and Android. 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"))]; @@ -152,14 +152,18 @@ 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"})); + const opt = {body: d.body || "", tag: "bot-" + (d.bot || 0), renotify: true, data: d, icon: "icon-192.png", badge: "icon-192.png"}; + // An approval: answer it straight from the banner (Android shows the buttons; iOS opens the chat). + if (d.ask) opt.actions = [{action: "allow", title: "允許"}, {action: "deny", title: "拒絕"}]; + e.waitUntil(self.registration.showNotification(d.title || "AnyBot", opt)); }); self.addEventListener("notificationclick", (e) => { e.notification.close(); const d = e.notification.data || {}; - const url = "./#host=" + encodeURIComponent(d.host || "") + "&bot=" + (d.bot || ""); + const answer = e.action === "allow" ? "once" : e.action === "deny" ? "reject" : ""; + const url = "./#host=" + encodeURIComponent(d.host || "") + "&bot=" + (d.bot || "") + (answer ? "&answer=" + answer : ""); e.waitUntil(self.clients.matchAll({type: "window", includeUncontrolled: true}).then((cs) => { - for (const c of cs) { c.postMessage({open: d}); return c.focus(); } + for (const c of cs) { c.postMessage({open: Object.assign({}, d, {answer})}); return c.focus(); } return self.clients.openWindow(url); })); }); @@ -773,7 +777,7 @@ 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 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"], "ask": v["ask"].as_bool().unwrap_or(false), "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 mut gone = vec![]; let mut sent = 0; diff --git a/src/app.rs b/src/app.rs index 0506d30..7bbe0f5 100644 --- a/src/app.rs +++ b/src/app.rs @@ -1675,7 +1675,7 @@ impl App { if !self.headless { notify::banner(&format!("{} 完成了", b.name), &last); } - crate::remote::notify(&format!("{} 完成了", b.name), &last, bot_id); + crate::remote::notify(&format!("{} 完成了", b.name), &last, bot_id, false); } } // Messages that arrived too late to steer start the next turn. @@ -3298,7 +3298,7 @@ impl App { // The banner doesn't ring a second time when the 提示音 just did. notify::banner_with(&title, &what, !chime); } - crate::remote::notify(&title, &what, bot_id); + crate::remote::notify(&title, &what, bot_id, true); } } } diff --git a/src/app/goal_ui.rs b/src/app/goal_ui.rs index d29afe3..1bca542 100644 --- a/src/app/goal_ui.rs +++ b/src/app/goal_ui.rs @@ -101,7 +101,7 @@ impl App { if !self.headless { notify::banner(title, &body); } - crate::remote::notify(title, &body, bot_id); + crate::remote::notify(title, &body, bot_id, false); } /// 清除聊天記錄 / 開始新對話: the goal goes with the chat it was set in (Claude Code's /clear diff --git a/src/drops.rs b/src/drops.rs index 3d87701..eef6699 100644 --- a/src/drops.rs +++ b/src/drops.rs @@ -622,7 +622,7 @@ pub fn kick() { let before: Vec = 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| { 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(&format!("{} 傳來的", p.from), &what, 0, false); }); // What was for this brain's own computer landed without the device road. let new: Vec = o.received().into_iter().filter(|r| !before.contains(&r.id)).collect(); diff --git a/src/remote.rs b/src/remote.rs index 69bf92c..8cb3e1a 100644 --- a/src/remote.rs +++ b/src/remote.rs @@ -1853,14 +1853,15 @@ pub fn sync_file(s: &Settings, path: &str) -> Result, String> { } /// A notification on the person's phones (through the relay; phones that turned them on). -pub fn notify(title: &str, body: &str, bot: u64) { +/// `ask` marks an approval: the banner gets 允許 / 拒絕 buttons that answer without opening the app. +pub fn notify(title: &str, body: &str, bot: u64, ask: bool) { let s = hub().settings(); if s.relay_url.is_empty() || s.host_token.is_empty() { return; } let (title, body) = (title.to_string(), body.to_string()); 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, "ask": ask})); }); } @@ -2106,7 +2107,7 @@ const PAGE: &str = include_str!("../mobile/index.html"); /// The bots' computer, watched and used in a browser (noVNC; see vnc.rs). const SCREEN_PAGE: &str = include_str!("../mobile/screen.html"); 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 = r##"{"id":"anybot","name":"AnyBot","short_name":"AnyBot","lang":"zh-Hant","start_url":"./","display":"standalone","display_override":["standalone","minimal-ui"],"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"}],"shortcuts":[{"name":"主要 Bot 對話","short_name":"主要 Bot","url":"./?sc=main","icons":[{"src":"icon-192.png","sizes":"192x192"}]},{"name":"未讀對話","short_name":"未讀","url":"./?sc=unread","icons":[{"src":"icon-192.png","sizes":"192x192"}]}]}"##; /// 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"); /// PNG sizes for the iPhone home screen (it ignores SVG) and Android.