// 手機與帳號 in the window: what the phone sees (published when something changes), carrying out // what the phone asks, and the settings page (phone password, account at the relay, backups, // 裝置連結). use super::*; use crate::remote::{self, Cmd, Settings}; use serde_json::json; use std::hash::{Hash, Hasher}; /// 團隊 as the relay answered: each (user, role), or why it could not be loaded. type Members = Result, String>; #[derive(Default)] pub struct RemoteUi { sig: u64, last_publish: Option, /// The settings the server threads were last given. pushed: Option, /// And the voice service. voice: crate::speech::Engines, pw1: String, pw2: String, relay_url: String, user: String, pass: String, invite: String, create: bool, /// 兩步驗證: the code that goes with the password, asked once the account said it has it on. code: String, need_code: bool, pub(super) note: Arc>, join_rx: Option>>, restore_rx: Option, String>>>, /// 換網址: the form is open (it opens by itself while the account server can't be reached), /// the address typed, and the check under way (remote::relay_move). move_open: bool, move_url: String, move_rx: Option>>, busy: Arc, pub(super) peers: Arc>>, last_seen_mark: Option, peers_at: Option, /// 團隊: (user, role) shared with, loaded from the relay; the form to add one. members: Arc>>, new_member: String, new_admin: bool, started: bool, /// The layout check's account connection state (a long error) instead of the live one. #[cfg(test)] pub(super) relay_status_shown: Option, } /// Approvals as the phone shows them. /// An address without what may be secret in it: no 「user:password@」, no query, no fragment. fn address_only(url: &str) -> String { let (scheme, rest) = url.split_once("://").map(|(a, b)| (format!("{a}://"), b)).unwrap_or((String::new(), url)); let rest = rest.split(['?', '#']).next().unwrap_or(""); let (host, path) = rest.split_once('/').map(|(h, p)| (h, format!("/{p}"))).unwrap_or((rest, String::new())); format!("{scheme}{}{path}", host.rsplit('@').next().unwrap_or(host)) } /// A card as the phone draws it. `key`: the card's own (on_new_approval) — the phone sends it /// back with the answer, so the brain applies it only to this card. /// What a card asks to do, for its title: the tool's name — or, where the call says which /// (ChatGPT 方案: sign in, out, another account), that. pub(super) fn card_what(bot: &Bot, a: &Approval) -> String { if a.tool == crate::chatgpt::TOOL { let args = bot.messages.iter().rev().take(24).flat_map(|m| m.tool_calls.iter()).find(|c| c.id == a.call_id).map(|c| c.args.as_str()).unwrap_or(""); return crate::chatgpt::ask_label(args).to_string(); } remote::tool_label(&a.tool).to_string() } fn approval_json(bot: &Bot, a: &Approval, key: &str, smart: bool) -> serde_json::Value { let what = card_what(bot, a); let title = match a.kind { ApprovalKind::EnableTools => format!("允許 {} 使用電腦工具嗎?", bot.name), ApprovalKind::EnableThisComputer => format!("允許 {} 在你的電腦上執行任務嗎?", bot.name), ApprovalKind::Action => format!("{} 想要{what}", bot.name), ApprovalKind::Handoff => format!("{}:需要你", bot.name), ApprovalKind::Question => format!("{} 問你", bot.name), }; // 問題卡: the questions themselves, for the phone to draw. if a.kind == ApprovalKind::Question { let questions: serde_json::Value = serde_json::from_str(&a.reason).unwrap_or(json!([])); return json!({"bot": bot.id, "title": title, "reason": crate::ask::describe(&a.reason), "tool": a.tool, "can_always": false, "kind": "question", "computer": "", "call_id": a.call_id, "questions": questions, "key": key}); } let handoff = a.kind == ApprovalKind::Handoff; // 智慧模式: the phone's card gets 「這輪都准」 too — a yes smaller than 一律允許, // good for this turn only (the brain applies it to the card's own grant, never the phone's words). let can_scope = smart && a.kind == ApprovalKind::Action && !a.grant.is_empty(); json!({"bot": bot.id, "title": title, "reason": a.reason, "tool": a.tool, "can_always": !handoff && (a.kind != ApprovalKind::Action || !a.grant.is_empty()), "can_scope": can_scope, "kind": if handoff { "handoff" } else { "ask" }, "computer": if handoff { a.grant.as_str() } else { "" }, "key": key}) } /// A teammate's messages waiting for a busy bot (more than this are not taken). const MAX_WAITING_FROM_MEMBERS: usize = 8; /// 設定 › 一般 › 外觀 as the phone's colours: the shell the desktop draws, light and dark. pub(super) fn phone_palettes(st: &crate::model::State) -> serde_json::Value { let one = |dark| remote::palette_json(&crate::theme::palette_for(&st.shell_template, st.shell_tone, &st.shell_accent, st.shell_contrast, dark)); // (And the 風格's chat backdrop: dots, a grid, waves, or none.) json!({"light": one(false), "dark": one(true), "backdrop": crate::theme::backdrop(&st.shell_template)}) } impl App { pub(super) fn remote_start(&mut self, ctx: &egui::Context) { if self.demo || self.rm.started { return; } self.rm.started = true; self.ctx_handle = Some(ctx.clone()); let c = ctx.clone(); remote::hub().set_repaint(Arc::new(move || c.request_repaint())); self.remote_apply_settings(); self.mirror_boot(); // 傳送: whatever was still on its way when AnyBot stopped goes on. crate::drops::kick(); } /// Hand changed settings to the server threads (and restart what depends on them). fn remote_apply_settings(&mut self) { let s = self.state.remote.clone(); if self.rm.pushed.as_ref() == Some(&s) { return; } let old = self.rm.pushed.replace(s.clone()); remote::hub().set_settings(&s); let lan_changed = old.as_ref().map(|o| o.lan) != Some(s.lan); if lan_changed { match remote::set_lan(s.lan) { Ok(_) => {} Err(e) => *self.rm.note.lock().unwrap() = e, } } let relay_changed = old.as_ref().map(|o| (o.relay_url.clone(), o.host_token.clone())) != Some((s.relay_url.clone(), s.host_token.clone())); if relay_changed { remote::relay_restart(&s); } } /// Every frame: run what the phone asked and refresh what it sees. pub(super) fn remote_tick(&mut self, ctx: &egui::Context) { if self.demo { return; } self.remote_apply_settings(); // 設定 › 語音 with its keys, for the phone's and the screens' recordings. let voice = crate::speech::Engines::of(&self.state); if self.rm.voice != voice { remote::hub().set_voice(voice.clone()); self.rm.voice = voice; } let cmds = remote::hub().take_cmds(); let had_cmds = !cmds.is_empty(); for c in cmds { // A screen of another brain has no bots of its own to run phone requests on. if self.mir.on && !matches!(c, Cmd::DeviceAdded(_) | Cmd::DeviceSeen(_)) { continue; } self.remote_cmd(ctx, c); } self.brain_serve(ctx); self.brain_watch(); if let Some(rx) = &self.rm.join_rx { if let Ok(r) = rx.try_recv() { self.rm.join_rx = None; match r { Ok((s, found)) => { self.state.remote = s; self.rm.pass.clear(); self.rm.code.clear(); self.rm.need_code = false; self.account_sync(found); self.mark(); } Err(e) => { self.rm.need_code |= e.starts_with(remote::NEED_CODE); // (A code is good for one try.) self.rm.code.clear(); *self.rm.note.lock().unwrap() = e; } } } } if let Some(rx) = &self.rm.move_rx { if let Ok(r) = rx.try_recv() { self.rm.move_rx = None; match r { // Only the address: whatever else changed meanwhile (a name, backups) stays. // The connection restarts on it (remote_apply_settings sees the new address). Ok(s) if s.host_token == self.state.remote.host_token => { *self.rm.note.lock().unwrap() = format!("已改用 {}:帳號、大腦和還沒送出的訊息都照舊", s.relay_url); self.state.remote.relay_url = s.relay_url; self.rm.move_open = false; self.rm.move_url.clear(); self.mark(); } Ok(_) => *self.rm.note.lock().unwrap() = "這台在檢查時登出或換了帳號,網址沒有換".into(), Err(e) => *self.rm.note.lock().unwrap() = e, } } } if let Some(rx) = &self.rm.restore_rx { if let Ok(r) = rx.try_recv() { self.rm.restore_rx = None; match r.and_then(|bytes| serde_json::from_slice::(&bytes).map_err(|e| format!("備份內容讀不出來:{e}"))) { Ok(mut st) => { // Keep this computer's own phone and account settings. st.remote = self.state.remote.clone(); let n = st.bots.len(); self.state = st; self.state.save(); *self.rm.note.lock().unwrap() = format!("已從備份還原 {n} 個 Bot"); } Err(e) => { self.rm.need_code |= e.starts_with(remote::NEED_CODE); self.rm.code.clear(); *self.rm.note.lock().unwrap() = e; } } } } // 自動備份: once a day while signed in. let s = &self.state.remote; if !self.mir.on && s.auto_backup && !s.backup_key.is_empty() && !s.relay_url.is_empty() && chrono::Utc::now().timestamp() - s.last_backup > 86_400 && !self.rm.busy.load(Ordering::SeqCst) { self.remote_backup(); } // 裝置連結: keep the list of this account's computers fresh (every 15 s: a computer that // comes on is one the bots can use soon after). if !self.state.remote.host_token.is_empty() && !self.rm.peers_at.map(|t| t.elapsed().as_secs() < 15).unwrap_or(false) { self.rm.peers_at = Some(Instant::now()); let (peers, s) = (self.rm.peers.clone(), self.state.remote.clone()); std::thread::spawn(move || { let v = remote::devices_online(&s); if !v.is_empty() { *peers.lock().unwrap() = v; } }); } if !self.mir.on && (had_cmds || !self.rm.last_publish.map(|t| t.elapsed().as_millis() < 75).unwrap_or(false)) { self.remote_publish(); } } /// 加一台電腦: lines for Mac, any Linux (desktop or headless) and Windows. Each installs /// AnyBot if needed and joins as hands, including the first pairing, with nothing to answer. fn pair_section(&mut self, ui: &mut egui::Ui) { let p = self.pal; ui.add_space(6.0); ui.separator(); ui.horizontal(|ui| { // (As tall as its button, so the name and the button share a middle.) ui.set_min_height(30.0); ui.label(RichText::new(t("加一台電腦")).size(FONT_SM).strong().family(crate::bold())); help_mark(ui, "讓另一台電腦當大腦的手腳:Mac、任何 Linux(含沒有螢幕的)、已登入的 Windows。貼上對應的那一行就會裝好並完成第一次配對,不用帳號密碼。它會在開機或登入後自動執行,只讓這個大腦使用。", p); ui.with_layout(Layout::right_to_left(Align::Center), |ui| { if ui.add(secondary_button("產生配對碼")).clicked() { let (s, slot) = (self.state.remote.clone(), self.mir.pair.clone()); let for_host = if self.mir.on { s.brain_id.clone() } else { s.host_id.clone() }; *slot.lock().unwrap() = (t("正在產生…"), false, None); // This computer is the brain: a key goes with the code (in the line to // paste, never to the account server) and its commands to the new computer // are signed with it. (As a screen of a brain elsewhere there is none: the // key would have to cross the account server to reach that brain.) let key = if self.mir.on { String::new() } else { crate::remote::new_link_key() }; if !key.is_empty() { let keys = &mut self.state.remote.link_keys; keys.push(key.clone()); let extra = keys.len().saturating_sub(crate::remote::MAX_LINK_KEYS); keys.drain(..extra); remote::hub().set_settings(&self.state.remote); self.dirty = true; } std::thread::spawn(move || { *slot.lock().unwrap() = match crate::remote::pair_code(&s, &for_host) { Ok(code) if !key.is_empty() => (crate::remote::pair_block(&s.relay_url, &format!("{code}-{key}")), true, Some(Instant::now())), Ok(code) => (crate::remote::pair_block(&s.relay_url, &code), true, Some(Instant::now())), Err(e) => (e, false, None), }; }); } }); }); let (line, ok, at) = self.mir.pair.lock().unwrap().clone(); if line.is_empty() { return; } let left = at.map(|t| 600u64.saturating_sub(t.elapsed().as_secs())).unwrap_or(0); if ok && left == 0 { hint(ui, "配對碼過期了,再按一次「產生配對碼」。", p); return; } if !ok { let c = if line.ends_with('…') { p.text2 } else { p.danger }; ui.label(RichText::new(line).size(FONT_SM).color(c)); return; } Frame::new().fill(p.hover).corner_radius(R_M).inner_margin(Margin::symmetric(10, 8)).show(ui, |ui| { ui.horizontal(|ui| { ui.add(egui::Label::new(RichText::new(&line).monospace().size(FONT_SM)).selectable(true).wrap()); ui.with_layout(Layout::right_to_left(Align::Center), |ui| { if ui.add(secondary_button("複製")).clicked() { crate::platform::copy_text(ui.ctx(), &line); self.notice = Some(t("已複製。Mac 和 Linux 貼終端機那一行,Windows 貼 PowerShell 那一行")); } }); }); }); ui.label(RichText::new(format!("{}(還有 {} 分 {:02} 秒,只能用一次)", t("在那台電腦貼上對應的那一行"), left / 60, left % 60)).size(FONT_XS).color(p.text3)); // Just made: bring it into view. if at.map(|t| t.elapsed().as_millis() < 800).unwrap_or(false) { ui.scroll_to_cursor(Some(Align::Max)); } ui.ctx().request_repaint_after(std::time::Duration::from_secs(1)); } fn remote_signature(&self) -> u64 { let mut h = std::collections::hash_map::DefaultHasher::new(); self.state.remote.host_name.hash(&mut h); self.state.timezone.hash(&mut h); self.scr.cfg_hash.hash(&mut h); (&self.state.folders, self.state.loose_index, &self.state.pin_order, self.state.accent as u8, self.newer_build.is_some(), self.state.always_approve).hash(&mut h); // 外觀: the phone wears the desktop's theme and colours. (self.state.theme as u8, &self.state.shell_accent, &self.state.shell_template, self.state.shell_tone.to_bits(), self.state.shell_contrast.to_bits()).hash(&mut h); for b in &self.state.bots { (b.id, &b.name, &b.color, b.unread, b.messages.len(), &b.thinking, &b.step_model).hash(&mut h); // (What the phone's home, editor and reactions show.) (&b.description, &b.shape, b.pinned, &b.folder, b.members.len(), b.instructions.len(), b.memories.len(), b.tools_enabled).hash(&mut h); for m in b.messages.iter().rev().take(remote::PHONE_TAIL) { (m.role as u8, m.text.len(), m.thinking.len(), m.attachments.len(), m.tool_calls.len(), m.error, m.summary, m.interrupted, &m.reactions, m.memories.len()).hash(&mut h); for c in &m.tool_calls { (c.status as u8).hash(&mut h); } // 交付確認: a device's word on a file (the phone's ✓✓). for a in &m.attachments { a.seen.len().hash(&mut h); } // 完成宣稱關卡: the reply's 「未驗證」. m.check.len().hash(&mut h); } if let Some(l) = self.streams.get(&b.id) { (1u8, &l.status, l.paused, l.steer.lock().unwrap().len()).hash(&mut h); } // (With its key: call ids repeat — call_0 every round — and a new card has to reach // the phone with its own key.) self.approvals.get(&b.id).map(|a| (a.call_id.clone(), self.ask_keys.get(&b.id).cloned())).hash(&mut h); // The phone's home and bot sheet: its model, computer, routines and past chats. (b.provider, &b.model, &b.default_computer, b.threads.len(), b.id == self.state.primary_bot).hash(&mut h); for r in &b.routines { (r.id, &r.title, r.paused, r.next_run).hash(&mut h); } } for (id, _, online) in self.rm.peers.lock().unwrap().iter() { (id, online).hash(&mut h); } // A 支線's card (shown in its main bot's chat), with its key. for br in &self.state.branch_bots { self.approvals.get(&br.id).map(|a| (br.id, a.call_id.clone(), self.ask_keys.get(&br.id).cloned())).hash(&mut h); } crate::cloudbox::run_state().label().hash(&mut h); // 任務: the list the brain worked out (the phone's 任務 page and its count). self.tk.sig.hash(&mut h); // A connector connected or failing: screens and phones hear of it now, not at the next // long poll's end. let mut up: Vec<(String, usize)> = crate::mcp::status().into_iter().collect(); up.sort(); (up, self.ch.mcp_errors.lock().unwrap().clone(), self.ch.mcp_busy.load(Ordering::SeqCst)).hash(&mut h); for pg in &self.state.pages { (pg.id, pg.revision, pg.updated, &pg.title).hash(&mut h); } h.finish() } /// The cards the phone shows in bot `b`'s chat, each with its own key (the phone sends it /// back, and the brain applies the answer only to that card): `b`'s own, and its 支線's — /// shown in the main bot's chat (`bot`), answered for the 支線 (`target`), with the 支線's key. fn phone_cards(&self, b: &Bot) -> Vec { let key = |id: u64| self.ask_keys.get(&id).map(String::as_str).unwrap_or(""); let mut out = vec![]; let smart = self.smart_flag.load(std::sync::atomic::Ordering::Relaxed); if let Some(a) = self.approvals.get(&b.id) { out.push(approval_json(b, a, key(b.id), smart)); } for br in self.state.branch_bots.iter().filter(|x| x.branch_of == b.id) { if let Some(a) = self.approvals.get(&br.id) { let mut j = approval_json(br, a, key(br.id), smart); j["bot"] = json!(b.id); j["target"] = json!(br.id); j["title"] = json!(format!("支線:{}", j["title"].as_str().unwrap_or(""))); out.push(j); } } out } pub(super) fn remote_publish(&mut self) { let sig = self.remote_signature(); if sig == self.rm.sig { return; } self.rm.sig = sig; self.rm.last_publish = Some(Instant::now()); crate::routines::set_person_timezone(&self.state.timezone); let names: HashMap = self.state.bots.iter().map(|b| (b.id, b.name.clone())).collect(); let raw_order: HashMap = self.state.bots.iter().enumerate().map(|(i, b)| (b.id, i)).collect(); let mut bots: Vec<&Bot> = self.state.bots.iter().collect(); // Pinned first, then the most recently active. bots.sort_by_key(|b| (!b.pinned, -(b.last_turn.as_ref().map(|t| t.settled_at_ms).unwrap_or(0)))); // 聊天的顏色, in the names update_settings takes (the phone compares and sends these). let accent = match self.state.accent { crate::model::Accent::Quiet => "quiet", crate::model::Accent::Black => "black", crate::model::Accent::BotColor => "bot_color", } .to_string(); let mut view = remote::View { host: self.state.remote.host_name.clone(), person: self.person_name(), accent, pin_order: self.pinned_ids(), newer: self.newer_build.is_some(), always: self.always_on(), sections: self.section_order(), theme: match self.state.theme { crate::model::Theme::Light => "light", crate::model::Theme::Dark => "dark", crate::model::Theme::System => "system", } .to_string(), palettes: phone_palettes(&self.state), ..Default::default() }; let peers = self.rm.peers.lock().unwrap().clone(); for b in bots { // Its computers, each as the phone shows it: what it is and whether it is there now. let targets = self.targets_for(b); let roles = self.roles_for(b, &targets); let computer = Self::chosen_computer(b, &targets, &roles).0; let runs = crate::providers::runs_at(b.provider, &crate::providers::resolve_base(b.provider, &self.state.provider(b.provider).base_url)); let computers: Vec = targets.iter().map(|t| { let (kind, online) = match &t.place { tools::Place::Box { .. } => ("own", crate::cloudbox::available()), tools::Place::Sealed { .. } => ("own", false), tools::Place::Local { .. } => ("this", true), tools::Place::Device { host, .. } => ("device", peers.iter().any(|(id, _, on)| id == host && *on)), tools::Place::Ssh { .. } => ("ssh", true), }; json!({"name": t.name, "kind": kind, "online": online, "person": roles.person.as_deref() == Some(t.name.as_str())}) }).collect(); let live = self.streams.get(&b.id); // The last thing said (not an error the model service sent, which then sat on the home). let last = b.messages.iter().rev().find(|m| !m.text.trim().is_empty() && m.role != Role::Tool && !m.error).map(|m| first_line(&m.text, 60)).unwrap_or_default(); let c = crate::avatar::color(&b.color); let hex = format!("#{:02x}{:02x}{:02x}", c.r(), c.g(), c.b()); view.bots.push(json!({ "id": b.id, "name": b.name, "description": b.description, "color": hex, "shape": b.shape, "busy": live.is_some(), // (What it is doing now, in the same words as above the input on the computer.) "status": self.working_phrase(crate::model::now_ms() as f64 / 1000.0, b).unwrap_or_default(), "unread": b.unread, "last": last, "members": !b.members.is_empty(), "pinned": b.pinned, // 重新產生 replaced an answer: 「還原上一個答案」 can put it back. "can_restore": !b.regen_undo.is_empty(), // 團隊: whether teammates may use it (remote.rs shows a member only these). "team": b.team, // Its skills (null: every one), for the phone's 「/word」 list. "skills": b.skills, // @點名: a group's members, as the phone's @ list offers them. "member_names": self.member_names(b).into_iter().map(|(_, n)| n).collect::>(), "primary": b.id == self.state.primary_bot, "time": b.messages.iter().rev().find(|m| m.role != Role::Tool).map(|m| m.at).unwrap_or(0), "via": format!("{} · {}", b.provider.label(), b.model), // Where the model runs (本機/區網/雲端), for the phone: "this computer" is the brain. "runs": runs.short(), "runs_words": runs.words(Some(if self.state.remote.host_name.trim().is_empty() { "大腦" } else { self.state.remote.host_name.trim() })), "provider": serde_json::to_value(b.provider).unwrap_or_default(), "model": b.model, "computer": computer, "computers": computers, "routines": b.routines.iter().map(|r| json!({"id": r.id, "title": r.title, "paused": r.paused, "when": crate::appctl::routine_when(r)})).collect::>(), "threads": b.threads.iter().enumerate().rev().take(20).map(|(i, (title, msgs))| json!({"index": i, "title": title, "count": msgs.len(), "at": msgs.last().map(|m| m.at).unwrap_or(0)})).collect::>(), // The sidebar's sections, the colour by name (the editor), what is queued while it works. "folder": b.folder, "color_key": b.color, "order": raw_order.get(&b.id).copied().unwrap_or(0), // 聊天的顏色 (設定 › 一般): how the phone draws your bubbles — the same choice. "bubble": match self.state.accent { crate::model::Accent::Quiet => "quiet", crate::model::Accent::Black => "black", crate::model::Accent::BotColor => "bot", }, "thinking": b.thinking, "step_model": b.step_model, "queued": live.map(|l| l.steer.lock().unwrap().iter().map(|q| q.text.clone()).collect::>()).unwrap_or_default(), // 目標: how it stands (its icon's words above the input), worded here so the phone says it the same way. // 計畫: where it is (its icon's words above the input), worded here like the window's. "plan": b.plan.as_ref().map(|p| json!({ "task": p.task, "stage": p.stage, "line": crate::plan::bar_text(p), "steps": if p.stage == crate::plan::Stage::Doing { crate::plan::checklist(&p.steps) } else { String::new() }, })), "goal": b.goal.as_ref().map(|g| json!({ "condition": g.condition, "reason": g.reason, "active": g.active(), "line": if g.active() && self.goal_checking.contains(&b.id) { "目標 · 正在檢查有沒有達成…".to_string() } else { crate::goal::bar_text(g, crate::model::now_ms()) }, })), })); // (The newest PHONE_TAIL; 載入更早 asks for any stretch before it: phone_messages.) let (msgs, deliveries) = self.phone_messages(b, &names, b.messages.len().saturating_sub(remote::PHONE_TAIL), b.messages.len()); view.messages.insert(b.id, msgs); view.deliveries.insert(b.id, deliveries); view.approvals.extend(self.phone_cards(b)); } view.pages = self.state.pages.clone(); view.tasks = self.tk.list.iter().map(crate::tasks::json).collect(); // The models a bot can be switched to from the phone: each provider that is ready. view.models = crate::providers::ALL_PROVIDERS .iter() .filter(|&&k| crate::providers::ready(k, &self.state.provider(k).api_key)) // Only models that chat: an image or video generator picked for a bot would break it. .map(|&k| json!({"provider": serde_json::to_value(k).unwrap_or_default(), "label": k.label(), "runs": crate::providers::runs_at(k, &crate::providers::resolve_base(k, &self.state.provider(k).base_url)).short(), "models": self.models_for(k).into_iter().filter(|m| chats(m)).collect::>()})) .collect(); remote::hub().publish(view); } pub(super) fn remote_cmd(&mut self, ctx: &egui::Context, c: Cmd) { match c { Cmd::Meeting { bot, path, lang } => { // Only a recording the app itself stored (uploaded into its attachments). let root = crate::model::State::path().parent().map(|p| p.join("attachments")).and_then(|p| p.canonicalize().ok()); match (std::path::Path::new(&path).canonicalize().ok(), root) { (Some(f), Some(root)) if f.starts_with(&root) && f.is_file() => self.meeting_job(bot, f, lang, true), _ => {} } } Cmd::Send { bot, text, attachments, from, memories, member, seen } => { if self.state.bot(bot).is_none() { return; } // Typed on one of the account's computers: that one is the person's now (for // 「我的電腦」 and the model on their network). The phone isn't a computer. if !from.is_empty() && !member { remote::set_person_host(&from); // A computer this brain hasn't heard of yet (it just came on): look the // account's computers up now, or its 「我的電腦」 wouldn't be known for a minute. if !self.rm.peers.lock().unwrap().iter().any(|(id, _, online)| *id == from && *online) { let v = remote::devices_online(&self.state.remote); if !v.is_empty() { *self.rm.peers.lock().unwrap() = v; } self.rm.peers_at = Some(Instant::now()); } self.typed_on = Some(from); } // Only files the app itself stored in its attachments folder may ride along; // resolve first, so "../../" paths cannot escape it (the phone can name any path). let root = crate::model::State::path().parent().map(|p| p.join("attachments")).and_then(|p| p.canonicalize().ok()); let atts: Vec = attachments .iter() .filter_map(|p| { let f = std::path::Path::new(p).canonicalize().ok()?; if !root.as_ref().map(|r| f.starts_with(r) && f.is_file()).unwrap_or(false) { return None; } let meta = std::fs::metadata(&f).ok()?; let file = f.file_name()?.to_string_lossy().to_string(); let name = file.split_once('-').map(|x| x.1.to_string()).unwrap_or(file); // Also on the bot's own computer, where it works (a brain on a server // has no other computer of its own to read it from). let on_box = crate::cloudbox::copy_in(&f.display().to_string(), bot, &name).unwrap_or_default(); Some(crate::attach::Attachment { image: crate::attach::is_image_name(&name), name, path: f.display().to_string(), bytes: meta.len(), on_box, ..Default::default() }) }) .collect(); // 目標: 「/goal …」 is AnyBot's, not the bot's (owner/admin only); anything else takes a paused goal up again. if !member { // AnyBot's own commands from the phone or a screen (commands.rs): the owner's // only (a teammate's words arrive as 「【名字】…」, never a command). A // /doctor from there: the brain checks itself. if let Some(cmd) = self.command_for(bot, &text) { self.run_app_command(ctx, bot, cmd, &text, atts, memories); return; } self.goal_heard(bot); } if self.streams.contains_key(&bot) { if !member && self.others_turn(bot).is_some() { // (Someone else's turn — a routine's, a workflow step's, an outside // sender's: the words wait for one of their own.) self.pending_turns.push((bot, vec![agent::Queued::with_files(text, atts)])); } else if !member { self.queue_steer(bot, text, atts); } else if self.waiting_wakes.iter().filter(|(b, _)| *b == bot).count() < MAX_WAITING_FROM_MEMBERS { // A teammate's words never go into the owner's running turn (they are // not the owner's): they get a turn of their own once the bot is free. // (They used to be dropped without a word.) let mut m = super::person_message(&self.state, bot, &text, atts, Some(vec![])); m.untrusted_sender = true; self.waiting_wakes.push((bot, m)); } return; } let mut m = super::person_message(&self.state, bot, &text, atts, if member { Some(vec![]) } else { memories }); m.untrusted_sender = member; if !member { m.seen = seen; } if let Some(b) = self.state.bot_mut(bot) { b.messages.push(m); } self.start_reply(ctx, bot); } Cmd::Stop { bot } => self.stop(bot), // The server's own zone (UTC) was never the person's choice: take theirs. A zone the // person set on purpose stays. Cmd::PersonTimezone(tz) => { if crate::routines::is_server_default_zone(&self.state.timezone) && tz != self.state.timezone { self.state.timezone = tz; self.mark(); } } Cmd::SetBot { bot, provider, model, computer } => { let kind = serde_json::from_value::(json!(provider)).ok(); if let (Some(k), false) = (kind, model.is_empty()) { if let Some(b) = self.state.bot_mut(bot) { b.provider = k; b.model = model; } self.mark(); } if !computer.is_empty() { let _ = self.update_bot_computer(bot, &json!({"default_computer": computer}).to_string()); self.mark(); } } Cmd::Regenerate { bot } => self.regenerate(ctx, bot), Cmd::RestoreAnswer { bot } => self.restore_regenerated(bot), Cmd::Reply { bot } => { if !self.streams.contains_key(&bot) && self.state.bot(bot).and_then(|b| b.messages.last()).map(|m| m.role == Role::User).unwrap_or(false) { self.start_reply(ctx, bot); } } Cmd::Resume { bot } => self.resume_turn(ctx, bot), Cmd::RestoreThread { bot, index } => { self.stop(bot); if let Some(b) = self.state.bot_mut(bot) { if index < b.threads.len() { let (_, msgs) = b.threads.remove(index); if !b.messages.is_empty() { let title = b.messages.iter().find(|m| m.role == Role::User).map(|m| first_line(&m.text, 24)).unwrap_or_else(|| "對話".into()); let cur = std::mem::take(&mut b.messages); b.threads.insert(0, (title, cur.into_inner())); } b.messages = msgs.into(); } } self.mark(); } Cmd::Answer { bot, answer, text, call, notice, screen } => { // Only the card it was given for: every answer from afar (the phone's card, a // notification, a screen) names its card by the key on_new_approval gave it. A // card answered, gone or replaced since — or a page too old to name one — takes // nothing (it used to answer whatever waited by then: an 允許 for one step went // to the next, and 一律允許 remembered the next one's kind). let waiting = self.approvals.get(&bot); let this_card = waiting.is_some() && !call.is_empty() && self.ask_keys.get(&bot) == Some(&call); // A notification's 允許/拒絕 only on a card notice_answers gave the buttons to: // never 「我完成了」 on a hand-off or 「略過」 on a question, whatever the key. let fits = !notice || (waiting.is_some_and(super::notice_answers) && matches!(answer.as_str(), "once" | "reject")); if !(this_card && fits) { // Said only while something waits: with nothing waiting the answer was for a // card already settled. Nor for a card 直接操作 let through as it came on (the // phone's 「全部允許」 sends its answer for that card after) — already done. if waiting.is_some() && !(!call.is_empty() && self.settled_by_direct.contains(&call)) { // What to do about it depends on where it came from: a phone page too old // to name its card is refreshed; a screen computer that old is updated. let note = match (notice, screen, call.is_empty()) { (true, ..) => "通知上的「允許/拒絕」沒有用上:那個請求已經不在等了(回答過,或換成了別的)。打開聊天看現在在等什麼。", (_, true, true) => "螢幕電腦上的回答沒有用上:那台電腦的 AnyBot 比這台舊,說不出是哪一張卡。在那台打開 設定 › 更新 換新版,或在這台回答。", (_, true, false) => "螢幕電腦上的回答沒有用上:那張卡已經不在等了(回答過,或換成了別的)。看現在在等什麼再回答。", // (Refreshing gets the page again from where it came: an account // server not yet updated serves the old one again.) (_, false, true) => "手機上的回答沒有用上:這個頁面太舊,說不出是哪一張卡。重新整理再回答;還是不行(帳號伺服器還沒更新),就在電腦上回答。", (_, false, false) => "手機上的回答沒有用上:那張卡已經不在等了(回答過,或換成了別的)。看現在在等什麼再回答。", }; // In the chat the person reads: a 支線's card is shown, and answered, in // its main bot's chat — the 支線's own messages aren't shown anywhere. let home = self.state.home_of(bot); self.goal_note(home, note); } return; } let grant = self.approvals.get(&bot).map(|a| a.grant.clone()).unwrap_or_default(); let question = self.approvals.get(&bot).is_some_and(|a| a.kind == ApprovalKind::Question); let a = match answer.as_str() { // (Only a question takes an answer in words, and nothing else answers one.) "answered" if question => ApprovalAnswer::Answered(text), _ if question => ApprovalAnswer::Reject, "once" => ApprovalAnswer::Once, // 智慧模式's 「這輪都准」: the card's own grant, this turn only. The phone // names the card by its key, and the grant comes from the card here — the // phone's words never choose what a scope covers. "scope" => ApprovalAnswer::Scope(grant), "always" => ApprovalAnswer::Always(grant), _ => ApprovalAnswer::Reject, }; self.answer(ctx, bot, a); } Cmd::Read { bot } => { if let Some(b) = self.state.bot_mut(bot) { if b.unread { b.unread = false; self.mark(); } } } Cmd::Seen { bot, att, device, kind, why, trusted } => self.delivery_seen(ctx, bot, &att, &device, kind, &why, trusted), Cmd::Clear { bot } => { self.goal_drop(bot); self.stop(bot); if let Some(b) = self.state.bot_mut(bot) { b.messages.clear(); } self.mark(); } Cmd::RunRoutine { bot, routine } => { let now = crate::routines::now(); let mut wake = None; if let Some(b) = self.state.bot_mut(bot) { if let Some(r) = b.routines.iter_mut().find(|r| r.id == routine) { r.last_run = Some(now); wake = Some(appctl::run_now_message(r)); } } if let Some(m) = wake { self.wake(ctx, bot, m); self.mark(); } } // 工作流 from a screen: the brain runs them. Cmd::Workflow { wf, act } => { self.wf_do(ctx, wf, &act); self.mark(); } Cmd::NewThread { bot } => { self.goal_drop(bot); self.stop(bot); if let Some(b) = self.state.bot_mut(bot) { if !b.messages.is_empty() { let title = b.messages.iter().find(|m| m.role == Role::User).map(|m| first_line(&m.text, 24)).unwrap_or_else(|| "對話".into()); let msgs = std::mem::take(&mut b.messages); b.threads.insert(0, (title, msgs.into_inner())); b.threads.truncate(50); } } self.mark(); } Cmd::DeviceAdded(d) => { self.state.remote.devices.push(d); self.mark(); } Cmd::DeviceSeen(h) => { if let Some(gone) = h.strip_prefix('-') { self.state.remote.devices.retain(|d| d.token_hash != gone); self.mark(); } else if !self.rm.last_seen_mark.map(|t| t.elapsed().as_secs() < 60).unwrap_or(false) { self.rm.last_seen_mark = Some(Instant::now()); if let Some(d) = self.state.remote.devices.iter_mut().find(|d| d.token_hash == h) { d.last_seen = chrono::Utc::now().timestamp(); self.mark(); } } } } } /// 登入後同步: the account's bots and this computer's become one set. /// • Another AnyBot of the account is the brain → show it, and copy this computer's bots /// there (once it answers; bots it already has are skipped). /// • This one is the only one → take in the backup's bots it doesn't have, then back up /// the whole set, so the account has this computer's bots too. fn account_sync(&mut self, found: remote::AccountFind) { if let Some((id, name)) = found.brain { *self.rm.note.lock().unwrap() = format!("已登入,改用「{name}」當大腦:那邊的 Bot 會同步過來,這台的也會搬過去"); self.mir.want = Some((id, name)); self.mir.move_after_join = true; // The brain's bots may use this computer (each action still asks). self.state.remote.device_link = true; return; } let got = found.backup.and_then(|b| serde_json::from_slice::(&b).ok()); let n = got.map(|st| self.state.take_in_bots(&st)).unwrap_or(0); *self.rm.note.lock().unwrap() = if n > 0 { format!("已登入,帳號裡的 {n} 個 Bot 已同步到這台") } else { "已登入,這台 AnyBot 已加入帳號".into() }; if !self.state.bots.is_empty() && self.state.remote.auto_backup { self.remote_backup(); } } fn remote_backup(&mut self) { if self.rm.busy.swap(true, Ordering::SeqCst) { return; } self.state.remote.last_backup = chrono::Utc::now().timestamp(); self.mark(); let s = self.state.remote.clone(); let mut st = self.state.clone(); // The backup is for the bots; this computer's own keys to the relay and phones stay here. st.remote = Default::default(); let bytes = serde_json::to_vec(&st).unwrap_or_default(); let (note, busy) = (self.rm.note.clone(), self.rm.busy.clone()); std::thread::spawn(move || { *note.lock().unwrap() = match remote::backup_now(&s, &bytes) { Ok(n) => format!("已備份({},已加密)", crate::cloudbox::human(n as u64)), Err(e) => e, }; busy.store(false, Ordering::SeqCst); }); } /// The account connection's state as the page shows it. fn relay_status_now(&self) -> String { #[cfg(test)] if let Some(s) = &self.rm.relay_status_shown { return s.clone(); } remote::hub().relay_status() } pub(super) fn remote_page(&mut self, ui: &mut egui::Ui, _ctx: &egui::Context) { let p = self.pal; let mut changed = false; setting_card(ui, p, |ui| { setting_title(ui, "手機與帳號", "在手機上和 Bot 聊天、核准它要做的事、看著它的電腦。", p); hint(ui, "兩種連法:同一個網路(或 Tailscale)直接連這台電腦;或登入帳號,透過你的帳號伺服器從任何地方連,這台電腦不用開放任何連接埠。", p); }); // ── 帳號(薄後端) ── setting_card(ui, p, |ui| { setting_title(ui, "AnyBot 帳號", "帳號伺服器保管帳號、裝置清單和加密備份,手機從外面連進來也靠它轉送。", p); let status = self.relay_status_now(); let s = &self.state.remote; if !s.host_token.is_empty() { ui.horizontal(|ui| { let ok = status == "已連線"; let (r, _) = ui.allocate_exact_size(vec2(10.0, 10.0), egui::Sense::hover()); ui.painter().circle_filled(r.center(), 4.0, if ok { p.up } else { p.text3 }); ui.add(egui::Label::new(RichText::new(format!("{} · {}", s.relay_user, s.relay_url)).size(FONT_BASE)).truncate()); }); // The connection's state on a line of its own, wrapped: beside the account on one // line, an error (「連不上帳號伺服器:找不到伺服器:…」) pushed the card wider than // the window, and 登出 off its right edge. if !status.is_empty() { ui.add(egui::Label::new(RichText::new(status.as_str()).size(FONT_XS).color(p.text3)).wrap()); } hint(ui, format!("手機打開 {} 用同一個帳號登入就能用。可以「加入主畫面」當成 App。", s.relay_url), p); // (A field as wide as the card: a long name like 「…的MacBook Pro (2)」 was cut off.) form_row(ui, "這台電腦在手機上叫", p, |ui| { if ui.add(egui::TextEdit::singleline(&mut self.state.remote.host_name).desired_width(f32::INFINITY)).lost_focus() { changed = true; } }); ui.add_space(4.0); if ui.checkbox(&mut self.state.remote.auto_backup, t("每天自動備份到帳號(加密,金鑰由你的密碼產生,伺服器打不開)")).changed() { changed = true; } ui.horizontal(|ui| { let busy = self.rm.busy.load(Ordering::SeqCst); if ui.add_enabled(!busy, secondary_button(if busy { "備份中…" } else { "立刻備份" })).clicked() { self.remote_backup(); } if self.state.remote.last_backup > 0 { let t = chrono::DateTime::from_timestamp(self.state.remote.last_backup, 0).map(|d| d.with_timezone(&chrono::Local).format("%m/%d %H:%M").to_string()).unwrap_or_default(); ui.label(RichText::new(format!("上次備份 {t}")).size(FONT_XS).color(p.text3)); } }); // 換網址: the account server moved (another machine or port, another VPN — going // from Tailscale to headscale killed every *.ts.net name at once). Without this the // only way was to sign out and in again: a new computer in the account (the old // one left behind, its goodbye sent to the dead address) and the brain picked // again. Open by itself while the server can't be reached. let unreachable = status.starts_with("連不上帳號伺服器"); ui.add_space(6.0); ui.separator(); ui.horizontal(|ui| { ui.set_min_height(30.0); ui.label(RichText::new(t("帳號伺服器換了網址")).size(FONT_SM).strong().family(crate::bold())); help_mark(ui, "帳號伺服器搬到別的位址(換了機器、連接埠或 VPN)時,在這裡填新的網址:AnyBot 先用這台電腦的金鑰確認那邊是同一台帳號伺服器才換,不用登出、不用密碼,大腦、聊天和還沒送出的訊息都照舊。要改用另一台帳號伺服器,請先登出再登入。", p); if !unreachable && !self.rm.move_open { ui.with_layout(Layout::right_to_left(Align::Center), |ui| { if ui.add(secondary_button("換網址")).clicked() { self.rm.move_open = true; } }); } }); if unreachable || self.rm.move_open { if unreachable { hint(ui, "連不上現在的網址。帳號伺服器換了位址的話,填新的網址,不用登出:", p); } form_row(ui, "新的網址", p, |ui| { ui.add(egui::TextEdit::singleline(&mut self.rm.move_url).hint_text(t("https://anybot.你的網域,或 http://100.x.x.x")).desired_width(f32::INFINITY)); }); ui.horizontal(|ui| { let busy = self.rm.move_rx.is_some(); if ui.add_enabled(!busy && !self.rm.move_url.trim().is_empty(), primary_button(if busy { "確認中…" } else { "換過去" }, p)).clicked() { let (tx, rx) = channel(); self.rm.move_rx = Some(rx); let (base, url) = (self.state.remote.clone(), self.rm.move_url.trim().to_string()); std::thread::spawn(move || { let _ = tx.send(remote::relay_move(&base, &url)); }); } if !unreachable && ui.add(secondary_button("取消")).clicked() { self.rm.move_open = false; self.rm.move_url.clear(); } }); } // 登出帳號: a row of its own under a line, like 加一台電腦 (it was red words at the // end of the backup row, not a button and not about backups). ui.add_space(6.0); ui.separator(); ui.horizontal(|ui| { ui.set_min_height(30.0); ui.label(RichText::new(t("登出帳號")).size(FONT_SM).strong().family(crate::bold())); help_mark(ui, "這台電腦會從帳號移除:手機從外面連、裝置連結、分享都會斷。這台的 Bot 和聊天還在。", p); ui.with_layout(Layout::right_to_left(Align::Center), |ui| { if ui.add(danger_text_button("登出", p)).clicked() { let keep_name = self.state.remote.host_name.clone(); // Say goodbye to the account server: the machine's registration is // removed, so its key dies with the sign-out. let (url, token) = (self.state.remote.relay_url.clone(), self.state.remote.host_token.clone()); if !url.is_empty() && !token.is_empty() { std::thread::spawn(move || { let _ = remote::relay_post(&format!("{url}/relay/host/remove"), &token, &serde_json::json!({})); }); } let s = &mut self.state.remote; s.host_id.clear(); s.host_token.clear(); s.backup_key.clear(); s.host_name = keep_name; changed = true; } }); }); } else { let busy = self.rm.join_rx.is_some(); form_row(ui, "帳號伺服器", p, |ui| { ui.add(egui::TextEdit::singleline(&mut self.rm.relay_url).hint_text(t("https://anybot.你的網域")).desired_width(f32::INFINITY)); }); form_row(ui, "帳號", p, |ui| { ui.add(egui::TextEdit::singleline(&mut self.rm.user).desired_width(f32::INFINITY)); }); form_row(ui, "密碼", p, |ui| { ui.add(egui::TextEdit::singleline(&mut self.rm.pass).password(true).desired_width(f32::INFINITY)); }); if self.rm.need_code { form_row(ui, "驗證碼", p, |ui| { ui.add(egui::TextEdit::singleline(&mut self.rm.code).hint_text(t("驗證器 App 的六位碼,或一組恢復碼")).desired_width(f32::INFINITY)); }); } ui.checkbox(&mut self.rm.create, t("建立新帳號")); if self.rm.create { form_row(ui, "邀請碼", p, |ui| { ui.add(egui::TextEdit::singleline(&mut self.rm.invite).hint_text(t("伺服器設定了才需要")).desired_width(f32::INFINITY)); }); } ui.horizontal(|ui| { let ready = !self.rm.relay_url.trim().is_empty() && !self.rm.user.trim().is_empty() && self.rm.pass.len() >= 8; if ui.add_enabled(ready && !busy, primary_button(if busy { "連線中…" } else if self.rm.create { "建立並登入" } else { "登入" }, p)).clicked() { let (tx, rx) = channel(); self.rm.join_rx = Some(rx); let (url, user, pass, create, invite, base, code) = (self.rm.relay_url.clone(), self.rm.user.trim().to_string(), self.rm.pass.clone(), self.rm.create, self.rm.invite.clone(), self.state.remote.clone(), self.rm.code.clone()); let note = self.rm.note.clone(); let repaint = self.repaint_fn(); std::thread::spawn(move || { // Signed in: look right away for the bots the account already has (on // a server that gives each account a cloud brain, wait for it). let r = remote::relay_join(&base, &url, &user, &pass, create, &invite, &code).map(|s| { let found = remote::find_account_bots_noting(&s, &pass, &code, remote::BRAIN_WAIT, &|n| { *note.lock().unwrap() = n.to_string(); repaint(); }); (s, found) }); let _ = tx.send(r); }); } if ui.add_enabled(ready && self.rm.restore_rx.is_none(), secondary_button("從帳號備份還原")).on_hover_text(t("把這台電腦的 Bot 換成帳號裡最新的備份")).clicked() { let (tx, rx) = channel(); self.rm.restore_rx = Some(rx); let (url, user, pass, code) = (self.rm.relay_url.clone(), self.rm.user.trim().to_string(), self.rm.pass.clone(), self.rm.code.clone()); std::thread::spawn(move || { let _ = tx.send(remote::restore(&url, &user, &pass, &code)); }); } }); hint(ui, "密碼至少 8 個字。帳號伺服器在 relay/ 資料夾,可以放在任何一台小主機(說明見 relay/README.md)。", p); } let note = self.rm.note.lock().unwrap().clone(); if !note.is_empty() { ui.label(RichText::new(note).size(FONT_SM).color(p.text2)); } }); // ── 大腦 ── if !self.state.remote.host_token.is_empty() { setting_card(ui, p, |ui| { ui.horizontal(|ui| { ui.label(RichText::new(t("大腦")).size(FONT_BASE).strong().family(crate::bold())); help_mark(ui, "帳號裡選一台 AnyBot 當大腦(通常是跟帳號伺服器放在一起、一直開著的那台)。所有 Bot、聊天、記憶和例行任務都放在大腦上,由它思考和排程。其他電腦打開 AnyBot 看到的都是同一份,同時也是大腦的手腳:大腦的 Bot 可以透過裝置連結操作它們。大腦連不到時,照樣看得到上次同步的內容,也能傳訊息、改設定:先排著,連回來後依序送出;停止、重新產生這類動作要連上才能做。", p); }); let s = &self.state.remote; let status = self.mir.status.lock().unwrap().clone(); if self.mir.on { ui.horizontal(|ui| { let (r, _) = ui.allocate_exact_size(vec2(10.0, 10.0), egui::Sense::hover()); ui.painter().circle_filled(r.center(), 4.0, if self.mir.online { p.up } else { p.text3 }); // (Wrapped inside the card: a long 「連不到大腦:…」 widened it, like the account's.) ui.add(egui::Label::new(RichText::new(status).size(FONT_SM).color(p.text2)).wrap()); }); // Which leg: this computer ↔ the account server, the account server ↔ the // brain (as the account server last said), and the line's speed. let brain_on = self.rm.peers.lock().unwrap().iter().find(|(id, _, _)| *id == s.brain_id).map(|x| x.2); let legs = remote_legs(&self.relay_status_now(), brain_on, &s.brain_name, *self.mir.last_sync.lock().unwrap()); for line in legs { ui.add(egui::Label::new(RichText::new(line).size(FONT_XS).color(p.text3)).wrap()); } ui.horizontal(|ui| { let busy = self.mir.moving.load(Ordering::SeqCst); if ui.add_enabled(self.mir.online && !busy, secondary_button("把這台的 Bot 搬過去")).on_hover_text(t("把這台電腦原本的 Bot(連同聊天)、模型金鑰、技能和連接器複製到大腦。這台的原始資料不會刪掉。")).clicked() { self.mirror_move_local(); } if ui.add(secondary_button("改回用這台自己的 Bot")).clicked() { self.mir.leave = true; } }); let note = self.mir.move_note.lock().unwrap().clone(); if !note.is_empty() { ui.label(RichText::new(note).size(FONT_SM).color(p.text2)); } } else { ui.label(RichText::new(t("這台就是大腦:Bot 在這台電腦上思考和工作。")).size(FONT_SM).color(p.text2)); let me = s.host_id.clone(); let peers: Vec<(String, String, bool)> = self.rm.peers.lock().unwrap().iter().filter(|(id, _, _)| !id.is_empty() && *id != me && !remote::is_hands(id)).cloned().collect(); if peers.is_empty() { hint(ui, "帳號裡還沒有別台可以當大腦的 AnyBot。", p); } for (id, name, online) in peers { ui.horizontal(|ui| { let (r, _) = ui.allocate_exact_size(vec2(10.0, 10.0), egui::Sense::hover()); ui.painter().circle_filled(r.center(), 4.0, if online { p.up } else { p.text3 }); ui.label(RichText::new(&name).size(FONT_SM)); ui.with_layout(Layout::right_to_left(Align::Center), |ui| { if ui.add_enabled(online, secondary_button("改用它當大腦")).clicked() { self.mir.want = Some((id.clone(), name.clone())); // The brain's bots may use this computer (each action still asks). self.state.remote.device_link = true; changed = true; } }); }); } } self.pair_section(ui); }); } // ── 同一個網路 ── setting_card(ui, p, |ui| { setting_title(ui, "同一個網路直接連", "手機和這台電腦在同一個 Wi-Fi,或都裝了 Tailscale 時使用。", p); let has_pw = !self.state.remote.password.is_empty(); if ui.add_enabled(has_pw, egui::Checkbox::new(&mut self.state.remote.lan, t("讓手機直接連這台電腦"))).changed() { changed = true; } if self.state.remote.lan { if let Some(port) = remote::lan_port() { for a in remote::addresses(port) { ui.horizontal(|ui| { ui.label(RichText::new(&a).monospace().size(FONT_SM)); if ui.small_button(t("複製")).clicked() { crate::platform::copy_text(ui.ctx(), &a); } }); } if let Some(print) = remote::lan_fingerprint() { ui.add_space(2.0); ui.label(RichText::new(t("https 的連線有加密。第一次打開,手機會問要不要信任這台電腦自己做的憑證:選「繼續」(進階 › 繼續前往)。要確認沒連錯台,比對憑證的 SHA-256 指紋:")).size(FONT_XS).color(p.text3)); ui.label(RichText::new(print).monospace().size(FONT_XS).color(p.text3)); } else { ui.label(RichText::new(t("這個連線沒有加密:只在你信任的網路上使用。")).size(FONT_XS).color(p.danger)); } } else if let Some(why) = remote::lan_problem() { // Not listening yet (the address isn't there, the ports are taken): it keeps trying. ui.label(RichText::new(why).size(FONT_XS).color(p.danger)); } } ui.add_space(4.0); form_row(ui, if has_pw { "更改手機密碼" } else { "設定手機密碼" }, p, |ui| { ui.add(egui::TextEdit::singleline(&mut self.rm.pw1).password(true).hint_text(t("至少 8 個字")).desired_width(f32::INFINITY)); }); form_row(ui, "再輸入一次", p, |ui| { ui.add(egui::TextEdit::singleline(&mut self.rm.pw2).password(true).desired_width(f32::INFINITY)); }); let ok = self.rm.pw1.chars().count() >= 8 && self.rm.pw1 == self.rm.pw2; if ui.add_enabled(ok, secondary_button("儲存密碼")).clicked() { self.state.remote.password = crate::httpd::hash_password(&self.rm.pw1); // A new password signs every phone out. self.state.remote.devices.clear(); self.rm.pw1.clear(); self.rm.pw2.clear(); changed = true; } if !self.rm.pw2.is_empty() && self.rm.pw1 != self.rm.pw2 { hint(ui, "兩次輸入的密碼不一樣", p); } hint(ui, "不要把這個連接埠開放到網際網路上;從外面連請用上面的帳號,或 Tailscale。", p); }); // ── 允許手機做什麼 ── setting_card(ui, p, |ui| { setting_title(ui, "手機可以做什麼", "聊天、核准、看 Bot 的電腦一律可以。下面這些會碰到這台電腦本身,預設關閉。", p); if ui.checkbox(&mut self.state.remote.mac_from_phone, t("從手機看這台電腦的螢幕並操作(點、打字、按鍵)")).changed() { changed = true; } // (裝置連結 — other AnyBots of the account using this computer — has nothing to do // with phones: it is in 設定 › 電腦 ›「讓帳號裡的其他電腦使用這台」, its one place.) note(ui, "讓帳號裡其他的 AnyBot(例如放在伺服器上的)操作這台:在 設定 › 電腦 ›「讓帳號裡的其他電腦使用這台」。", p); }); // ── 已登入的裝置 ── setting_card(ui, p, |ui| { setting_title(ui, "直接連線的裝置", "用手機密碼登入過的手機和瀏覽器", p); if self.state.remote.devices.is_empty() { hint(ui, "還沒有", p); } let mut remove = None; for (i, d) in self.state.remote.devices.iter().enumerate() { ui.horizontal(|ui| { ui.label(RichText::new(&d.name).size(FONT_BASE)); let seen = chrono::DateTime::from_timestamp(d.last_seen.max(d.created), 0).map(|t| t.with_timezone(&chrono::Local).format("最近 %m/%d %H:%M").to_string()).unwrap_or_default(); ui.label(RichText::new(seen).size(FONT_XS).color(p.text3)); ui.with_layout(Layout::right_to_left(Align::Center), |ui| { if ui.add(egui::Button::new(RichText::new(t("登出")).size(FONT_XS).color(p.danger)).frame(false)).clicked() { remove = Some(i); } }); }); } if let Some(i) = remove { self.state.remote.devices.remove(i); changed = true; } }); // ── 團隊 ── if !self.state.remote.host_token.is_empty() { setting_card(ui, p, |ui| { setting_title(ui, "分享給團隊", "讓帳號伺服器上的其他帳號也能用這台 AnyBot 的 Bot。", p); hint(ui, "成員:可以和 Bot 聊天、附加檔案;Bot 會知道是誰在說話。管理員:另外可以核准 Bot 要做的事、停止、看和操作電腦畫面。需要你允許的事只通知你和管理員。", p); let loaded = self.rm.members.lock().unwrap().clone(); if loaded.is_none() { *self.rm.members.lock().unwrap() = Some(Ok(vec![])); let (m, s) = (self.rm.members.clone(), self.state.remote.clone()); std::thread::spawn(move || *m.lock().unwrap() = Some(remote::members(&s))); } let mut change: Option<(String, &str)> = None; match loaded { Some(Ok(list)) => { for (user, role) in list { ui.horizontal(|ui| { ui.label(RichText::new(&user).size(FONT_BASE)); let waits = role.ends_with('?'); let role = role.trim_end_matches('?').to_string(); ui.label(RichText::new(format!("{}{}", if role == "admin" { "管理員" } else { "成員" }, if waits { "(已邀請,等對方接受)" } else { "" })).size(FONT_XS).color(p.text3)); ui.with_layout(Layout::right_to_left(Align::Center), |ui| { if ui.add(egui::Button::new(RichText::new(t("移除")).size(FONT_XS).color(p.danger)).frame(false)).clicked() { change = Some((user.clone(), "remove")); } }); }); } } Some(Err(e)) => hint(ui, format!("讀不到分享清單:{e}"), p), None => {} } ui.horizontal(|ui| { ui.add(egui::TextEdit::singleline(&mut self.rm.new_member).hint_text(t("對方的帳號")).desired_width(160.0)); ui.checkbox(&mut self.rm.new_admin, t("管理員")); if ui.add_enabled(!self.rm.new_member.trim().is_empty(), secondary_button("分享")).clicked() { change = Some((self.rm.new_member.trim().to_string(), if self.rm.new_admin { "admin" } else { "member" })); self.rm.new_member.clear(); } }); // Talk to the relay off the window's thread, then show the new list. if let Some((user, role)) = change { let (m, note, s, role) = (self.rm.members.clone(), self.rm.note.clone(), self.state.remote.clone(), role.to_string()); std::thread::spawn(move || { let r = remote::set_member(&s, &user, &role); *note.lock().unwrap() = match r { Ok(()) if role == "remove" => format!("已停止分享給 {user}"), Ok(()) => format!("已分享給 {user}"), Err(e) => e, }; *m.lock().unwrap() = Some(remote::members(&s)); }); } }); } // ── 帳號裡的其他電腦 ── if !self.state.remote.host_token.is_empty() { setting_card(ui, p, |ui| { setting_title(ui, "帳號裡的電腦", "登入同一個帳號的 AnyBot。開了裝置連結的電腦,Bot 可以操作它。", p); if ui.small_button(t("重新整理")).clicked() || (self.rm.peers.lock().unwrap().is_empty() && !self.rm.busy.load(Ordering::SeqCst)) { let (peers, s) = (self.rm.peers.clone(), self.state.remote.clone()); let first = peers.lock().unwrap().is_empty(); if first { peers.lock().unwrap().push((String::new(), "讀取中…".into(), false)); } std::thread::spawn(move || { let v = remote::devices_online(&s); *peers.lock().unwrap() = if v.is_empty() { vec![(String::new(), "(沒有)".into(), false)] } else { v }; }); } for (id, name, online) in self.rm.peers.lock().unwrap().iter() { ui.horizontal(|ui| { let (r, _) = ui.allocate_exact_size(vec2(10.0, 10.0), egui::Sense::hover()); if !id.is_empty() { ui.painter().circle_filled(r.center(), 4.0, if *online { p.up } else { p.text3 }); } let me = *id == self.state.remote.host_id; ui.label(RichText::new(format!("{name}{}", if me { "(這台)" } else { "" })).size(FONT_SM)); }); } }); } if changed { self.mark(); } } /// Other AnyBots of this account that let bots operate them (裝置連結), as computers. pub(super) fn linked_devices(&self) -> Vec { if self.state.remote.host_token.is_empty() { return vec![]; } let has_hands = !remote::my_hands(&self.state.remote.host_id).is_empty(); self.rm .peers .lock() .unwrap() .iter() .filter(|(id, _, online)| !id.is_empty() && *online && *id != self.state.remote.host_id) // A brain with hands of its own works on those, not on the account's other brains. .filter(|(id, _, _)| !has_hands || remote::is_hands(id)) // A computer showing another brain lends its hands to that one, not to this. .filter(|(id, _, _)| { let uses = remote::peer_uses(id); uses.is_empty() || uses == self.state.remote.host_id }) .map(|(id, name, _)| tools::Target { name: name.clone(), place: tools::Place::Device { host: id.clone(), dir: String::new() } }) .collect() } } /// A model one can chat with (not an image, video, speech or embedding one). fn chats(model: &str) -> bool { let m = model.to_lowercase(); !["imagine", "image", "video", "embed", "tts", "whisper", "audio", "moderation", "dall-e", "sora", "veo"].iter().any(|k| m.contains(k)) } /// The 大腦 section's lines under its state: this computer ↔ the account server (the lasting /// connection's own words), the account server ↔ the brain (online or not, as the account server /// last said), and the last sync's size and speed. pub(super) fn remote_legs(relay: &str, brain_online: Option, brain: &str, last: Option<(i64, u64, u64)>) -> Vec { let mut out = vec![]; if !relay.is_empty() { out.push(format!("這台 ↔ 帳號伺服器:{relay}")); } match brain_online { Some(true) => out.push(format!("帳號伺服器 ↔ 大腦「{brain}」:在線上")), Some(false) => out.push(format!("帳號伺服器 ↔ 大腦「{brain}」:不在線上(大腦那台的 AnyBot 沒開、沒網路,或正在重新啟動)")), None => {} } if let Some((at, bytes, ms)) = last { out.push(super::mirror_ui::sync_words(at, bytes, ms)); } out } impl App { /// One workflow as the phone shows it (it is edited on the computer or by asking a bot; here /// it is looked at and run). fn workflow_json(&self, w: &crate::workflow::Workflow) -> serde_json::Value { use crate::workflow::{NodeKind as K, RunState, StepState}; let bot_name = |id: u64| self.state.bot(id).map(|b| b.name.clone()).unwrap_or_default(); let state = |s: &RunState| match s { RunState::Running => "running", RunState::Waiting => "waiting", RunState::Done => "done", RunState::Failed => "failed", RunState::Stopped => "stopped", }; let step_state = |s: StepState| match s { StepState::Waiting => "waiting", StepState::Running => "running", StepState::Done => "done", StepState::Failed => "failed", StepState::Skipped => "skipped", }; let steps: Vec = w .order() .iter() .filter_map(|id| w.node(*id)) .map(|n| { let who = match &n.kind { K::Step { bot, .. } | K::Media { bot, .. } | K::Check { bot, .. } | K::Deliver { bot } | K::Output { bot, .. } => bot_name(*bot), _ => String::new(), }; json!({"id": n.id, "kind": n.kind.label(), "words": clip(&n.kind.words(), 240), "bot": who}) }) .collect(); let run = |r: &crate::workflow::Run| { // (What a 審批 step asks, while the run waits on it.) let asks = (r.state == RunState::Waiting).then(|| r.order.get(r.at).and_then(|id| w.node(*id))).flatten().map(|n| n.kind.words()).unwrap_or_default(); json!({ "id": r.id, "state": state(&r.state), "words": crate::workflow::describe_run(r), "by": r.by, "started": r.started, "ended": r.ended, "why": r.why, "asks": asks, "steps": r.steps.iter().map(|s| json!({"node": s.node, "state": step_state(s.state), "output": clip(&s.output, 600)})).collect::>(), }) }; let trigger = w.trigger().map(|t| t.kind.words()).unwrap_or_else(|| "手動".into()); json!({ "id": w.id, "name": w.name, "when": trigger, "steps": steps, "step_count": w.step_count(), "next": w.next_run.map(|t| crate::routines::describe_when(t, &self.state.timezone)), "live": w.live_run().map(run), "runs": w.runs.iter().rev().take(10).map(run).collect::>(), }) } } #[cfg(test)] mod phone_tests { use super::*; /// 載入更早 walks back through the whole chat, not only the newest PHONE_TAIL the phone was /// sent: from any place, the messages just before it (steps' results folded into their /// steps, so a stretch of steps still gives `count` to show), and `more` until the start. /// (A turn of 65 steps filled the newest 120 by itself; the button then did nothing: jenny-Host, /// 2026-11-21.) #[test] fn loading_earlier_walks_the_whole_chat() { let ctx = egui::Context::default(); let mut app = App::new(&ctx, Some(std::env::temp_dir().join("anybot-older.png"))); let id = app.state.bots[0].id; { let b = app.state.bot_mut(id).unwrap(); b.messages.clear(); b.messages.push(Message::user("開始")); for i in 0..150 { let call = crate::model::ToolCall { id: format!("c{i}"), name: "web_fetch".into(), args: format!(r#"{{"url":"https://example.com/{i}"}}"#), status: ToolStatus::Done }; b.messages.push(Message { tool_calls: vec![call], ..Message::assistant(&format!("第 {i} 步"), "") }); b.messages.push(Message::tool_result(&format!("c{i}"), "web_fetch", &format!("結果 {i}"))); } } let n = app.state.bot(id).unwrap().messages.len(); assert_eq!(n, 301); // The phone holds the newest stretch; it asks for what is before index 241 (far past the // newest 120's start, 181, and far before it too). let ask = |app: &mut App, from: usize| app.phone_act(&ctx, "older", &json!({"bot": id, "from": from, "count": 60}), "owner"); let v = ask(&mut app, 181); let msgs = v["messages"].as_array().unwrap(); assert_eq!(msgs.len(), 60, "{v}"); assert!(msgs.iter().all(|m| m["index"].as_u64().unwrap() < 181), "{v}"); assert_eq!(msgs.last().unwrap()["index"], json!(179)); assert_eq!(v["more"], json!(true)); // Each step shows with what it brought back. assert!(msgs[0]["tools"][0]["result"].as_str().is_some_and(|r| r.starts_with("結果 ")), "{}", msgs[0]); // Near the start: what is left, and no more. let v = ask(&mut app, 9); let msgs = v["messages"].as_array().unwrap(); assert_eq!((msgs.first().unwrap()["index"].as_u64(), msgs.last().unwrap()["index"].as_u64(), v["more"].as_bool()), (Some(0), Some(7), Some(false)), "{v}"); // A reader who isn't the owner may too (it only looks). assert!(app.phone_act(&ctx, "older", &json!({"bot": id, "from": 50}), "admin").get("error").is_none()); } #[test] fn only_chat_models_are_offered() { assert!(super::chats("grok-4.7") && super::chats("claude-opus-5-5") && super::chats("gpt-5-mini")); assert!(!super::chats("grok-imagine-video-1.5") && !super::chats("text-embedding-3-large") && !super::chats("gpt-4o-mini-tts")); } } // ---------- 手機: everything the desktop does, from the phone ---------- // Each action calls what the desktop's own button calls (appctl for the actions a bot can take // too, set_pinned, restart_bot, toggle_reaction, enable_direct_mode, box_task…), so the phone // adds no ways of its own. Members never get here (remote::role_allows); some things are the // owner's alone: deleting a bot, permissions and rules, channels, connectors and the box's // runtime, update and schedule. Keys, tokens and the vault's secrets are never sent. /// Docker facts for the phone's 電腦 settings, refreshed in the background (asking Docker on the /// app's thread would stall the window): (when, update available, gVisor here, runs on). static BOX_FACTS: std::sync::Mutex> = std::sync::Mutex::new(None); static BOX_FACTS_BUSY: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); fn box_facts() -> serde_json::Value { let (stale, v) = { let g = BOX_FACTS.lock().unwrap_or_else(|e| e.into_inner()); (g.as_ref().map(|(t, _)| t.elapsed().as_secs() > 20).unwrap_or(true), g.as_ref().map(|(_, v)| v.clone()).unwrap_or_else(|| json!({}))) }; // (Unit tests don't ask Docker.) if stale && !cfg!(test) && !BOX_FACTS_BUSY.swap(true, std::sync::atomic::Ordering::SeqCst) { std::thread::spawn(|| { let (n, exec_ms, total_ms) = crate::cloudbox::step_stats(); // (What can't be known — no Docker to ask, no box yet — is null, and the phone says // so: it read 「已是 v14」 and 「這台 Docker 主機沒有 gVisor」 with no Docker at all.) let v = json!({ "update": crate::cloudbox::box_outdated(), "gvisor": crate::cloudbox::gvisor_on_host(), "running": crate::cloudbox::running_runtime(), "steps": {"n": n, "exec_ms": exec_ms, "total_ms": total_ms}, }); *BOX_FACTS.lock().unwrap_or_else(|e| e.into_inner()) = Some((Instant::now(), v)); BOX_FACTS_BUSY.store(false, std::sync::atomic::Ordering::SeqCst); }); } v } /// At most `n` characters (the phone shows excerpts). fn clip(s: &str, n: usize) -> String { if s.chars().count() <= n { s.to_string() } else { format!("{}…", s.chars().take(n).collect::()) } } impl App { /// The phone's form of the messages `start..end` of this bot's chat — each with its place in /// it, its thinking and what each step brought back, in short — and the ✓ marks of the files /// among them. The published view is the newest PHONE_TAIL; 載入更早 (phone_act "older") asks /// for the stretch before what the phone holds, from the whole chat. fn phone_messages(&self, b: &Bot, names: &HashMap, start: usize, end: usize) -> (Vec, Vec) { let end = end.min(b.messages.len()); let start = start.min(end); // 交付確認: the ✓ marks go beside the chat, not inside the messages — a phone opening // an old chat reports every file it shows, and inside the messages that re-signed the // whole chat on every report (see remote::chat_for). let mut deliveries: Vec = vec![]; // Each message with its place in the chat (表情回應), its thinking and, on each step, // what came back (the desktop's 顯示步驟 / 思考過程), in short. let results: HashMap<&str, &str> = b.messages[start..end].iter().filter(|m| m.role == Role::Tool).map(|m| (m.tool_call_id.as_str(), m.text.as_str())).collect(); // 頁面 cards: once a reply, under the step that saved the page last (over the whole chat, // so a reply cut by the tail still knows its later steps). let cards = crate::pages::cards_by_message(&b.messages); let msgs: Vec = b.messages[start..end] .iter() .enumerate() .filter_map(|(k, m)| { let mut v = remote::message_json(m, names, &self.state.pages, cards.get(start + k).map(Vec::as_slice).unwrap_or(&[]))?; if let Some(atts) = v["attachments"].as_array_mut() { for a in atts.iter_mut() { let Some(o) = a.as_object_mut() else { continue }; let id = o.get("id").and_then(serde_json::Value::as_str).unwrap_or("").to_string(); let (Some(d), has_seen) = (o.remove("delivery"), o.contains_key("seen")) else { continue }; if id.is_empty() { continue; } let seen = if has_seen { o.remove("seen").unwrap_or(json!([])) } else { json!([]) }; deliveries.push(json!({"id": id, "delivery": d, "seen": seen})); } } v["index"] = json!(start + k); // 支線: its record, for the card (and the report's label). if m.branch != 0 { if let Some(r) = b.branches.iter().find(|r| r.id == m.branch) { v["branch"] = json!({"id": r.id, "task": r.task, "state": r.state, "note": r.note, "doing": r.doing, "steps": r.steps, "log": r.log, "result": r.result}); } } if !m.thinking.trim().is_empty() { v["thinking"] = json!(clip(m.thinking.trim(), 1500)); } if let Some(tools) = v["tools"].as_array_mut() { for (t, c) in tools.iter_mut().zip(m.tool_calls.iter()) { if t["plan"].is_object() { let (state, live) = super::plan_ui::plan_card_state(b, c); t["plan"]["state"] = state; t["plan"]["live"] = live; continue; } if t.get("talk").is_some() { if let Some(r) = results.get(c.id.as_str()) { t["talk"]["answer"] = json!(clip(r.trim(), 2000)); } continue; } if t.get("label").is_some() { t["name"] = json!(c.name); if let Some(r) = results.get(c.id.as_str()) { // (秘密遮罩: what a step printed may hold a key; the phone shows it masked.) // (Masked on a window a little past what is shown, not on the whole // output: a long command's output was scanned whole on every publish.) t["result"] = json!(clip(&crate::secrets::mask(&clip(r.trim(), 1200)), 600)); } } } } Some(v) }) .collect(); (msgs, deliveries) } pub(super) fn phone_act(&mut self, ctx: &egui::Context, action: &str, b: &serde_json::Value, role: &str) -> serde_json::Value { let owner = role == "owner"; let bot = b["bot"].as_u64().unwrap_or(0); let s = |k: &str| b[k].as_str().unwrap_or("").trim().to_string(); // A setting's name, exactly as sent: 「direct_mode 」 isn't direct_mode. (Trimmed, it slipped // past the direct connection's guard, which reads names exactly — remote::lan_guard.) let name_of = |k: &str| b[k].as_str().unwrap_or("").to_string(); let fail = |e: &str| json!({"error": e}); let done = |t: &str| json!({"ok": true, "text": t}); let owner_only = || json!({"error": "這件事只有這台 AnyBot 的擁有者能做"}); // 團隊: an admin keeps what the phone always let them do (approve, stop, the screens, the // model and computer, a new chat, regenerate) plus looking and small chat things; making, // changing or deleting bots, routines, memories, pages and settings stays the owner's. let admin_ok = match action { "detail" | "settings" | "pages" | "search" | "export_bot" | "export_transcript" | "restart_bot" | "react" | "reply" | "resume" | "older" | "workflows" | "schedule" | "library" | "settings_find" => true, "bot" => b["key"].as_str() == Some("unread"), "box" => matches!(b["op"].as_str(), Some("wake" | "disk")), _ => false, }; if !owner && !admin_ok { return owner_only(); } match action { "search" => { let q = s("q"); let (hits, more) = crate::find::search(&self.state.bots, &q); let items: Vec = hits .into_iter() .map(|h| { let bname = self.state.bot(h.bot).map(|x| x.name.clone()).unwrap_or_default(); let tname = h.thread.and_then(|ti| self.state.bot(h.bot).and_then(|x| x.threads.get(ti)).map(|t| t.0.clone())); json!({"bot": h.bot, "bot_name": bname, "thread": h.thread, "thread_title": tname, "index": h.index, "at": h.at, "mine": h.mine, "file": h.file, "snippet": h.snippet}) }) .collect(); json!({"ok": true, "hits": items, "more": more}) } // 工作流 on the phone: each one's steps in order, what starts it, how its runs went, and // the question it waits on — read here; run, stop, 繼續 and 停止 below. "workflows" => json!({"ok": true, "workflows": self.state.workflows.iter().map(|w| self.workflow_json(w)).collect::>()}), // 搜尋設定 on the phone (the computer's index, with the phone page for each). "settings_find" => super::settings_find::find_for_phone(&s("q")), // 所有檔案 on the phone: every file the chats keep, across bots and conversations. "library" => self.library_json(), // 日程 on the phone: three days back to a week ahead — what ran on its own and how it // went, what is coming — and 即將執行 (each thing once, soonest first). "schedule" => { use crate::schedule::{self as sch, Status, What}; let now = crate::routines::now(); let tz = self.state.timezone.clone(); let today = sch::day_of(now, &tz); let from = sch::day_start(today - chrono::Duration::days(3), &tz); let to = sch::day_start(today + chrono::Duration::days(7), &tz); let one = |i: &sch::Item| { let (kind, id) = match i.what { What::Routine { id, .. } => ("routine", id), What::Workflow { id } => ("workflow", id), }; let status = match i.status { Status::Done => "done", Status::Failed => "failed", Status::Stopped => "stopped", Status::Running => "running", Status::Coming => "coming", Status::Paused => "paused", }; json!({"at": i.at, "clock": sch::clock(i.at, &tz), "day": sch::day_of(i.at, &tz).to_string(), "title": i.title, "when": i.when, "bot": i.bot, "kind": kind, "id": id, "status": status}) }; let items: Vec = sch::items(&self.state, from, to, now).iter().take(400).map(one).collect(); let coming: Vec = sch::coming(&self.state, now, 6).iter().map(one).collect(); json!({"ok": true, "today": today.to_string(), "items": items, "coming": coming}) } "workflow" => { let wf = b["wf"].as_u64().unwrap_or(0); let what = b["do"].as_str().unwrap_or(""); let Some(w) = self.state.workflows.iter().find(|w| w.id == wf) else { return fail("找不到這個工作流") }; if !["run", "stop", "go", "halt"].contains(&what) { return fail("不認得的操作"); } if what == "run" && !w.has_steps() { return fail(crate::workflow::NO_STEPS); } if what == "run" && w.live_run().is_some() { return fail("這個工作流正在執行"); } let name = w.name.clone(); self.wf_do(ctx, wf, what); self.mark(); done(&match what { "run" => format!("開始執行「{name}」"), "stop" => format!("已停止「{name}」"), "go" => "好,繼續".to_string(), _ => "停下來了".to_string(), }) } "export_bot" => match self.state.bot(bot) { Some(x) => json!({"ok": true, "filename": format!("{}.anybot", x.name), "content": crate::share::export(x)}), None => fail("找不到這個 Bot"), }, "export_transcript" => match self.state.bot(bot) { Some(x) => json!({"ok": true, "filename": format!("{} 對話.md", x.name), "content": super::transcript_markdown(x)}), None => fail("找不到這個 Bot"), }, "import_bot" => { if !owner { return owner_only(); } let content = b["content"].as_str().unwrap_or(""); let id = self.state.next_id; let mut next_rt = self.state.bots.iter().flat_map(|x| x.routines.iter()).map(|r| r.id).max().unwrap_or(0) + 1; match crate::share::import(content, id, &mut next_rt, crate::routines::now()) { Ok(nb) => { let name = nb.name.clone(); self.state.next_id += 1; self.state.bots.push(nb); self.dirty = true; json!({"ok": true, "bot": id, "text": format!("已匯入「{name}」")}) } Err(e) => fail(&e), } } "section_move" => { if !owner { return owner_only(); } let folder = b["folder"].as_str().map(str::trim).filter(|f| !f.is_empty()).map(String::from); let by = b["by"].as_i64().unwrap_or(0).clamp(-1, 1) as i32; if by != 0 { self.move_section(&folder, by); } done("好了") } "memory" => { let v = crate::memory::api_write(&mut self.state, b); if v.get("ok").is_some() { self.dirty = true; } v } // 載入更早: the `count` (at most 120) messages before index `from`, from the whole chat // (the published view holds only the newest PHONE_TAIL — the phone used to walk back // through those alone, and the button then did nothing at all). "older" => match self.state.bot(bot) { Some(x) => { let from = b["from"].as_u64().map(|f| f as usize).unwrap_or(x.messages.len()).min(x.messages.len()); let count = b["count"].as_u64().unwrap_or(60).clamp(1, 120) as usize; let names: HashMap = self.state.bots.iter().map(|y| (y.id, y.name.clone())).collect(); // (Steps take room: walk back until `count` show, or the chat begins.) let mut start = from.saturating_sub(count); let (mut msgs, mut deliveries) = self.phone_messages(x, &names, start, from); while msgs.len() < count && start > 0 { let more_from = start; start = start.saturating_sub(count); let (m2, d2) = self.phone_messages(x, &names, start, more_from); msgs.splice(0..0, m2); deliveries.extend(d2); } // (The last stretch can bring more than asked: `count` at most, the rest next time.) let mut more = start > 0; if msgs.len() > count { msgs.drain(..msgs.len() - count); more = true; } json!({"bot": bot, "messages": msgs, "deliveries": deliveries, "more": more}) } None => fail("找不到這個 Bot"), }, "detail" => match self.state.bot(bot) { Some(x) => self.phone_detail(x, owner), None => fail("找不到這個 Bot"), }, "settings" => self.phone_settings(owner), // 個人資料與用量: the owner's alone (whose tokens, which bots). "stats" => { if !owner { return owner_only(); } crate::stats::build(&crate::stats::inputs(&self.state), crate::model::now_ms()) } // Every page, newest first (the state the phone polls carries only the latest few). "pages" => { let now = crate::model::now_ms(); let mut list: Vec<&crate::pages::Page> = self.state.pages.iter().collect(); list.sort_by_key(|p| std::cmp::Reverse(p.updated)); let pages: Vec = list .into_iter() .map(|p| { let mut c = crate::pages::card_json(p, now); c["bot"] = json!(self.state.bot(p.bot).map(|x| x.name.clone()).unwrap_or_default()); c }) .collect(); json!({"ok": true, "pages": pages}) } // The actions a bot can take on the app (the same appctl path as its tools). "app" => { // (skillify and skill_install are the phone's 「教我做」 and 「從網址安裝技能」.) const ALLOWED: [&str; 17] = [ "create_bot", "update_bot", "remember", "forget", "save_skill", "delete_skill", "skillify", "skill_install", "create_routine", "update_routine", "delete_routine", "run_routine_now", "create_group", "move_to_group", "rename_group", "delete_group", "update_settings", ]; let name = s("name"); if !ALLOWED.contains(&name.as_str()) { return fail("手機不能做這件事"); } let args = match &b["args"] { serde_json::Value::String(t) => t.clone(), v if v.is_object() => v.to_string(), _ => "{}".to_string(), }; // (The bot it is about; the app-wide ones act as the main bot, as from its chat.) let id = [bot, self.state.primary_bot].into_iter().find(|i| self.state.bot(*i).is_some()).or_else(|| self.state.bots.first().map(|x| x.id)).unwrap_or(0); let next = self.state.next_id; let out = if name == "update_bot" && serde_json::from_str::(&args).map(|v| v["default_computer"].is_string()).unwrap_or(false) { self.update_bot_computer(id, &args) } else { appctl::apply(&mut self.state, id, &name, &args) }; if out.theme_changed { self.apply_theme(ctx); } for (target, msg) in out.wake { self.wake(ctx, target, msg); } self.dirty = true; if !out.ok { return fail(&out.text); } let made = (self.state.next_id > next).then_some(next); json!({"ok": true, "text": out.text, "bot": made}) } // A bot's switches from its menu and editor. "bot" => { if self.state.bot(bot).is_none() { return fail("找不到這個 Bot"); } let v = &b["value"]; let key = name_of("key"); if matches!(key.as_str(), "tools" | "allow_remove" | "strengths" | "not_for" | "abilities" | "skills" | "may_use") && !owner { return owner_only(); } match key.as_str() { "pinned" => self.set_pinned(bot, v.as_bool().unwrap_or(false), None), // 團隊: whether teammates may use this bot (the owner's choice only). "team" => { if !owner { return owner_only(); } if let Some(b) = self.state.bot_mut(bot) { b.team = v.as_bool().unwrap_or(false); } } "pin_at" => self.set_pinned(bot, true, v.as_u64().map(|n| n as usize)), "folder" => { let f = v.as_str().unwrap_or("").trim().to_string(); self.set_pinned(bot, false, None); if !f.is_empty() && !self.state.folders.contains(&f) { self.state.folders.push(f.clone()); } if let Some(x) = self.state.bot_mut(bot) { x.folder = f; } } "primary" => self.state.primary_bot = bot, "members" => { let ids: Vec = v.as_array().map(|a| a.iter().filter_map(|x| x.as_u64()).collect()).unwrap_or_default(); let ok: Vec = ids.into_iter().filter(|i| *i != bot && self.state.bot(*i).map(|x| x.members.is_empty()).unwrap_or(false)).collect(); if ok.is_empty() { return fail("群組至少要有一個成員"); } if let Some(x) = self.state.bot_mut(bot) { x.members = ok; } } // 個人檔案: 能力、技能、可以用的電腦 — the ticked ones; all of them is "no list". "abilities" | "skills" | "may_use" => { let ticked: Vec = v.as_array().map(|a| a.iter().filter_map(|x| x.as_str().map(String::from)).collect()).unwrap_or_default(); let every: Vec = match key.as_str() { "abilities" => crate::profile::ABILITIES.iter().map(|a| a.0.to_string()).collect(), "skills" => self.state.skills.iter().filter(|k| k.enabled).map(|k| k.name.clone()).collect(), _ => self.state.bot(bot).map(|x| self.every_computer(x).into_iter().skip(1).map(|c| c.0).collect()).unwrap_or_default(), }; // (In the list's own order, so what the bot is told reads the same every turn.) let kept: Vec = every.iter().filter(|n| ticked.contains(n)).cloned().collect(); let all = kept.len() == every.len(); let Some(x) = self.state.bot_mut(bot) else { return fail("找不到這個 Bot") }; let list = match (key.as_str(), &x.computers) { // 可以用的電腦 lists the computers there now: an account computer that is // off isn't. One not listed keeps how it was, allowed or not, and a // bot with a list keeps one — ticking every computer listed made it // "every computer", and one the person had left out came back in. ("may_use", Some(prev)) => Some(kept.into_iter().chain(prev.iter().filter(|c| !every.contains(c)).cloned()).collect()), _ if all => None, _ => Some(kept), }; match key.as_str() { "abilities" => x.abilities = list, "skills" => x.skills = list, _ => { // The computer it works on by default must be one it may use. let chosen = x.default_computer.trim().to_string(); let allowed = chosen.is_empty() || chosen == crate::model::BOT_COMPUTER_NAME || chosen == crate::model::own_computer_name(&x.name) || list.as_ref().is_none_or(|l| l.contains(&chosen)); if !allowed { x.default_computer = crate::model::BOT_COMPUTER_NAME.to_string(); } x.computers = list } } } k => { let Some(x) = self.state.bot_mut(bot) else { return fail("找不到這個 Bot") }; match k { "strengths" if v.is_string() => x.strengths = v.as_str().unwrap_or("").trim().chars().take(400).collect(), "not_for" if v.is_string() => x.not_for = v.as_str().unwrap_or("").trim().chars().take(400).collect(), "unread" => x.unread = v.as_bool().unwrap_or(true), "tools" => x.tools_enabled = v.as_bool().unwrap_or(true), "shape" if v.as_str().map(|t| crate::avatar::SHAPES.contains(&t)).unwrap_or(false) => x.shape = v.as_str().unwrap_or("").to_string(), // (A preset, or a colour of one's own as #rrggbb, as on the computer.) "color" if v.as_str().map(|t| crate::avatar::COLORS.iter().any(|c| c.0 == t) || (t.len() == 7 && t.starts_with('#') && t[1..].chars().all(|c| c.is_ascii_hexdigit()))).unwrap_or(false) => x.color = v.as_str().unwrap_or("").to_lowercase(), // 備用模型: tried in order when the main one fails (at most MAX_FALLBACKS). "fallbacks" if v.is_array() => { x.fallbacks = v.as_array().unwrap().iter().filter_map(|f| { let provider = crate::providers::ALL_PROVIDERS.iter().copied().find(|k| serde_json::to_value(k).ok().as_ref() == Some(&f["provider"]))?; let model = f["model"].as_str()?.trim().to_string(); (!model.is_empty()).then_some(crate::model::Fallback { provider, model }) }).take(crate::model::MAX_FALLBACKS).collect(); } // 語音聊天 for this bot: read every answer aloud, its voice, speed and language. "speak_replies" => x.speak_replies = v.as_bool().unwrap_or(false), "voice" if v.is_string() => x.voice = v.as_str().unwrap_or("").trim().to_string(), "voice_rate" if v.is_number() => x.voice_rate = (v.as_f64().unwrap_or(1.0) as f32).clamp(0.5, 2.0), "voice_lang" if v.is_string() => x.voice_lang = v.as_str().unwrap_or("").trim().to_string(), // 起始資料夾: where its files and commands start. "workdir" if v.as_str().is_some_and(|w| !w.trim().is_empty()) => x.workdir = v.as_str().unwrap_or("").trim().to_string(), "context" => x.context_tokens = v.as_u64().unwrap_or(x.context_tokens).clamp(4_000, 2_000_000), "thinking" if v.as_str().is_some_and(|t| ["", "low", "medium", "high"].contains(&t)) => x.thinking = v.as_str().unwrap_or("").to_string(), "step_model" if v.is_string() => x.step_model = v.as_str().unwrap_or("").trim().to_string(), "allow_remove" => x.allow_rules.retain(|r| Some(r.as_str()) != v.as_str()), _ => return fail("不認得這個設定"), } } } self.dirty = true; done("好了") } "group_chat" => { // 群組聊天, as the desktop's new-bot menu makes it. let ids: Vec = b["members"].as_array().map(|a| a.iter().filter_map(|x| x.as_u64()).collect()).unwrap_or_default(); let members: Vec = ids.into_iter().filter(|i| self.state.bot(*i).map(|x| x.members.is_empty()).unwrap_or(false)).collect(); if members.is_empty() { return fail("選至少一個 Bot 當成員"); } let id = self.state.next_id; let name = Some(s("name")).filter(|n| !n.is_empty()).unwrap_or_else(|| "群組聊天".into()); let sel = self.state.selected; let out = appctl::apply(&mut self.state, sel, "create_bot", &json!({"name": name, "description": "成員依序回答"}).to_string()); if !out.ok { return fail(&out.text); } if let Some(x) = self.state.bot_mut(id) { x.members = members; x.shape = "cloud".into(); } self.dirty = true; json!({"ok": true, "text": out.text, "bot": id}) } "delete_bot" => { if !owner { return owner_only(); } if self.state.bot(bot).is_none() { return fail("找不到這個 Bot"); } // As the desktop's 刪除 Bot dialog. self.stop(bot); self.bot_gone(bot); self.state.bots.retain(|x| x.id != bot); self.state.fix_primary(); self.dirty = true; done("已刪除") } "restart_bot" => { if self.state.bot(bot).is_none() { return fail("找不到這個 Bot"); } self.restart_bot(bot); done("已重新啟動") } "react" => { let idx = b["index"].as_u64().unwrap_or(u64::MAX) as usize; let emoji = s("emoji"); if emoji.is_empty() || emoji.chars().count() > 8 || self.state.bot(bot).map(|x| idx >= x.messages.len()).unwrap_or(true) { return fail("找不到這則訊息"); } self.toggle_reaction(bot, idx, &emoji); done("好了") } "reply" => { self.remote_cmd(ctx, Cmd::Reply { bot }); done("重新傳送中…") } "resume" => { self.remote_cmd(ctx, Cmd::Resume { bot }); done("繼續中…") } "clear" => { self.remote_cmd(ctx, Cmd::Clear { bot }); done("已清除聊天記錄") } "delete_page" => { let id = b["id"].as_u64().unwrap_or(0); let before = self.state.pages.len(); self.state.pages.retain(|x| x.id != id); if self.state.pages.len() == before { return fail("這個頁面已經刪除了"); } self.mark(); done("已刪除頁面") } // 設定 › 一般 / 權限 (the owner's). "setting" => { if !owner { return owner_only(); } let v = &b["value"]; let key = name_of("key"); match key.as_str() { "direct_mode" => { if v.as_bool().unwrap_or(false) { self.enable_direct_mode() } else { self.disable_direct_mode() } } // 智慧模式 is always on (smart.rs): nothing to switch from a phone. "smart_mode" => { if !v.as_bool().unwrap_or(true) { return fail(crate::smart::OFF_NOTE); } } "auto_review" => self.state.auto_review = v.as_bool().unwrap_or(false), "notify" => self.state.notify = v.as_bool().unwrap_or(true), // 一律放行 as the chat's /always-approve does it (direct mode with it, and back). "always_approve" => { let on = v.as_bool().unwrap_or(false); if on && !(self.managed.direct.allows() && self.managed.local.allows()) { return fail(crate::always::LOCKED_NOTE); } // (The line about it goes into the chat it was switched from; from the // settings page, into none.) let bot = b["bot"].as_u64().unwrap_or(0); self.always_command(ctx, bot, if on { crate::always::Command::On } else { crate::always::Command::Off }); return done(if on { "一律放行:開" } else { "一律放行:關" }); } "smart_timeout_secs" => self.state.smart_timeout_secs = v.as_u64().unwrap_or(0).clamp(crate::smart::MIN_TIMEOUT_SECS, 3600), // 外觀 from the phone: the accent (back to 自訂 from a 風格), the contrast, the language. "shell_accent" => { let name = v.as_str().unwrap_or(""); if !crate::theme::ACCENTS.iter().any(|a| a.0 == name) { return fail("不認得這個強調色"); } self.state.shell_accent = name.to_string(); self.state.shell_template.clear(); if let Some(ctx) = self.ctx_handle.clone() { self.apply_theme(&ctx); } } "shell_contrast" => { self.state.shell_contrast = (v.as_f64().unwrap_or(1.0) as f32).clamp(0.75, 1.35); if let Some(ctx) = self.ctx_handle.clone() { self.apply_theme(&ctx); } } "language" => { let tag = v.as_str().unwrap_or("auto"); if tag != "auto" && !crate::i18n::LANGS.iter().any(|l| l.0 == tag) { return fail("不認得這個語言"); } self.state.language = tag.to_string(); crate::i18n::set(tag); } "auto_update" => self.state.auto_update_when_away = v.as_bool().unwrap_or(true), "garden_reports" => self.state.garden_reports = v.as_bool().unwrap_or(true), "embed" => { self.state.embed_model = match v.as_str().unwrap_or("") { "off" => "off".into(), "ollama" => "ollama".into(), _ => String::new(), }; crate::embed::configure(&crate::embed::ollama_base(&self.state.provider(crate::providers::ProviderKind::Ollama).base_url), &self.state.embed_model); } "doc_folder_add" | "doc_folder_remove" => { let f = v.as_str().unwrap_or("").trim().to_string(); if f.is_empty() { return fail("資料夾是空的"); } if key == "doc_folder_add" { if !self.state.doc_folders.contains(&f) { self.state.doc_folders.push(f); } } else { self.state.doc_folders.retain(|x| *x != f); } *DOC_FOLDERS.write().unwrap_or_else(|e| e.into_inner()) = self.state.doc_folders.clone(); } "rule_add" | "rule_remove" => { let text = v.as_str().unwrap_or("").trim().to_string(); // (Any list but 「ask」 used to be the allow list.) let list = match name_of("list").as_str() { "ask" => &mut self.state.review_ask_rules, "allow" => &mut self.state.review_allow_rules, _ => return fail("不認得這個規則清單"), }; if key == "rule_add" { if text.is_empty() { return fail("規則是空的"); } let unknown = crate::gate::rule_warning(&text, &self.state.mcp_servers); if !list.contains(&text) { list.push(text); } self.dirty = true; return done(&unknown.map(|w| format!("已新增。不過{w}")).unwrap_or_else(|| "已新增".into())); } else { list.retain(|r| *r != text); } } _ => return fail("不認得這個設定"), } self.dirty = true; done("好了") } // 設定 › 語音 from the phone: 聽 or 說's service, its address, key (written, never read // back), model and (說) voice. "voice" => { if !owner { return owner_only(); } let mut v = self.state.voice.clone(); let e = match b["which"].as_str() { Some("listen") => &mut v.listen, Some("speak") => &mut v.speak, _ => return fail("要說是「聽」還是「說」"), }; if let Some(k) = b["kind"].as_str() { e.kind = match serde_json::from_value(json!(k)) { Ok(k) => k, Err(_) => return fail("不認得這個語音服務"), }; } for (field, slot) in [("base_url", &mut e.base_url), ("api_key", &mut e.api_key), ("model", &mut e.model), ("voice", &mut e.voice)] { if let Some(x) = b[field].as_str() { *slot = x.trim().to_string(); } } v.saved = true; self.state.voice = v; self.mark(); done("好了") } // 設定 › 模型: a provider's key (written, never read back) and new bots' model. "provider" => { if !owner { return owner_only(); } let Some(kind) = crate::providers::ALL_PROVIDERS.iter().copied().find(|k| serde_json::to_value(k).ok().as_ref() == Some(&b["provider"])) else { return fail("不認得這個模型服務") }; let ps = self.state.providers.entry(kind.key().to_string()).or_default(); if let Some(k) = b["key"].as_str() { ps.api_key = k.trim().to_string(); } if let Some(m) = b["default_model"].as_str() { ps.default_model = m.trim().to_string(); } // 服務網址 (empty: the service's own) and 看不到圖時請雲端模型看 (a local model's). if let Some(u) = b["base_url"].as_str() { ps.base_url = u.trim().to_string(); } if let Some(on) = b["cloud_eyes"].as_bool() { ps.cloud_eyes = on; } self.dirty = true; // 測試連線並取得模型清單: asked on its own thread; the page reads how it went. if b["fetch"].as_bool() == Some(true) { self.fetch_models(kind); return done("正在測試連線…"); } done("好了") } // 手機與帳號: sign a direct-connection phone out (as the desktop's list does). "device_remove" => { if !owner { return owner_only(); } let (name, created) = (s("name"), b["created"].as_i64().unwrap_or(0)); let before = self.state.remote.devices.len(); self.state.remote.devices.retain(|d| !(d.name == name && d.created == created)); if self.state.remote.devices.len() == before { return fail("找不到這支手機"); } self.dirty = true; done("已登出那支手機") } "channel" => { if !owner { return owner_only(); } let id = b["id"].as_u64().unwrap_or(0); if !self.state.channels.iter().any(|c| c.id == id) { return fail("找不到這個管道"); } if b["remove"].as_bool().unwrap_or(false) { self.state.channels.retain(|c| c.id != id); } else if let Some(c) = self.state.channels.iter_mut().find(|c| c.id == id) { c.enabled = b["enabled"].as_bool().unwrap_or(c.enabled); } self.dirty = true; self.channels_restart(ctx); done("好了") } "mcp" => { if !owner { return owner_only(); } // From the phone's 公用市集: a server reached by address, with its key filled in. if b["add"].is_object() { let a = &b["add"]; let (url, header) = (a["url"].as_str().unwrap_or("").trim(), a["header"].as_str().unwrap_or("").trim()); if !(url.starts_with("https://") || url.starts_with("http://")) { return fail("連接器要有網址"); } if url.contains('{') || header.contains('{') { return fail("還有「{…}」沒換成你的值"); } let name = crate::mcp::free_name(a["name"].as_str().filter(|n| !n.trim().is_empty()).unwrap_or("連接器"), &self.state.mcp_servers); self.state.mcp_servers.push(crate::mcp::remote_server(&name, url, header)); self.dirty = true; return done(&format!("已加入連接器「{name}」")); } let name = s("name"); if !self.state.mcp_servers.iter().any(|m| m.name == name) { return fail("找不到這個連接器"); } if b["reconnect"].as_bool().unwrap_or(false) { self.mcp_reconnect(&name); return done("重新連線中…"); } // Renamed (from a screen): this entry keeps its keys, its place and its sign-in. if let Some(new) = b["rename"].as_str().map(str::trim) { if new.is_empty() || self.state.mcp_servers.iter().any(|m| m.name == new) { return fail("名稱不能空白,也不能跟別的連接器一樣"); } if let Some(m) = self.state.mcp_servers.iter_mut().find(|m| m.name == name) { m.name = new.to_string(); } crate::mcp_oauth::rename(&name, new); self.ch.mcp_errors.lock().unwrap().retain(|e| e.0 != name); self.move_mcp_grants(&name, new); self.dirty = true; return done("好了"); } // (mcp_poll connects or drops it when the list changes.) if b["remove"].as_bool().unwrap_or(false) { self.state.mcp_servers.retain(|m| m.name != name); self.forget_mcp_grants(&name); } else if let Some(m) = self.state.mcp_servers.iter_mut().find(|m| m.name == name) { m.enabled = b["enabled"].as_bool().unwrap_or(m.enabled); } self.dirty = true; done("好了") } "skill" => { if !owner { return owner_only(); } if let Some(slug) = b["builtin"].as_str().filter(|s| !s.trim().is_empty()) { return match crate::skills::install_builtin(slug, &mut self.state.skills) { Ok(name) => { self.dirty = true; done(&format!("已加入技能「{name}」")) } Err(e) => fail(&e), }; } // From a screen (設定 › 整合 on a computer showing this brain): a GitHub or web // address is fetched here, and a folder on that computer arrives whole — the // bots read skills from this disk. if let Some(src) = b["install"].as_str().filter(|s| !s.trim().is_empty()) { return match crate::skills::install_from_source(src) { Ok(name) => { crate::memory::merge_skill_files(&mut self.state.skills); self.dirty = true; done(&format!("已安裝技能「{name}」")) } Err(e) => fail(&e), }; } if b["package"].is_object() { return match crate::skills::install_package(&b["package"]) { Ok(k) => { let name = k.name.clone(); crate::memory::upsert_skill(&mut self.state.skills, k); self.dirty = true; done(&format!("已安裝技能「{name}」")) } Err(e) => fail(&e), }; } let name = s("name"); if !self.state.skills.iter().any(|k| k.name == name) { return fail("找不到這個技能"); } if b["remove"].as_bool().unwrap_or(false) { self.state.skills.retain(|k| k.name != name); crate::memory::remove_skill_files(&name); } else if let Some(k) = self.state.skills.iter_mut().find(|k| k.name == name) { k.enabled = b["enabled"].as_bool().unwrap_or(k.enabled); } self.dirty = true; done("好了") } // 設定 › 電腦's buttons for Bot 的電腦. "box" => { let op = name_of("op"); if matches!(op.as_str(), "update" | "reset" | "runtime" | "auto_update") && !owner { return owner_only(); } match op.as_str() { "wake" => self.box_task(|| crate::cloudbox::ensure_running().map(|_| "Bot 的電腦已經開好了。".to_string())), "snapshot" => self.box_task(|| crate::cloudbox::save_snapshot().map(|n| format!("已儲存快照({})。", crate::cloudbox::human(n)))), "disk" => { let slot = self.cu.disk.clone(); *slot.lock().unwrap() = Some("檢查中…".into()); std::thread::spawn(move || { let r = crate::cloudbox::disk_report().unwrap_or_else(|e| e); *slot.lock().unwrap() = Some(r); }); } "update" => { // As the desktop's 更新: the bots stop first, the files and logins stay. let ids: Vec = self.streams.keys().copied().collect(); for id in ids { self.stop(id); } *self.cu.note.lock().unwrap() = match crate::cloudbox::rebuild(crate::cloudbox::Rebuild::Update) { Ok(()) => t("更新已開始。"), Err(e) => e, }; } "reset" => { // As the desktop's 重設: back to the last snapshot (the current box saved // first), or a brand-new computer when there is none. let ids: Vec = self.streams.keys().copied().collect(); for id in ids { self.stop(id); } let kind = if crate::cloudbox::snapshot_time().is_some() { crate::cloudbox::Rebuild::Restore } else { crate::cloudbox::Rebuild::Reset }; *self.cu.note.lock().unwrap() = match crate::cloudbox::rebuild(kind) { Ok(()) => t("已開始。"), Err(e) => e, }; } "runtime" => crate::cloudbox::set_box_runtime(&s("value")), "auto_update" => { let at = s("value"); if !at.is_empty() && chrono::NaiveTime::parse_from_str(&at, "%H:%M").is_err() { return fail("時間要寫成 HH:MM"); } crate::cloudbox::set_auto_update_at((!at.is_empty()).then_some(at)); } _ => return fail("不認得這個動作"), } *BOX_FACTS.lock().unwrap_or_else(|e| e.into_inner()) = None; done("好了") } _ => fail("沒有這個動作"), } } /// A bot as its editor and the panel beside the chat show it. fn phone_detail(&self, b: &Bot, owner: bool) -> serde_json::Value { let names: HashMap = self.state.bots.iter().map(|x| (x.id, x.name.clone())).collect(); let (choices, chosen) = self.computer_choices(b); let trig = crate::triggers::statuses().lock().unwrap().clone(); // 資料庫: the chat's files, newest first (pictures and documents the person or the bot sent). let mut files: Vec = vec![]; for m in b.messages.iter().rev() { for a in &m.attachments { if files.len() < 80 { files.push(json!({"name": a.name, "path": a.path, "image": a.image, "bytes": a.bytes, "kind": crate::preview::kind_label(&a.name), "at": m.at, "mine": m.role == Role::User})); } } } json!({ "id": b.id, "name": b.name, "description": b.description, "instructions": b.instructions, "shape": b.shape, "color": b.color, "provider": serde_json::to_value(b.provider).unwrap_or_default(), "model": b.model, "thinking": b.thinking, "step_model": b.step_model, "fallbacks": b.fallbacks.iter().map(|f| json!({"provider": serde_json::to_value(f.provider).unwrap_or_default(), "model": f.model, "label": f.provider.label()})).collect::>(), "workdir": b.workdir, "speak_replies": b.speak_replies, "voice": b.voice, "voice_rate": b.voice_rate, "voice_lang": b.voice_lang, // 個人檔案 (each list: every choice there is, and whether this bot has it). "strengths": b.strengths, "not_for": b.not_for, "abilities": crate::profile::ABILITIES.iter().map(|(k, label, what)| json!({"key": k, "name": label, "note": what, "on": b.abilities.as_ref().is_none_or(|a| a.iter().any(|x| x == k))})).collect::>(), "skills": self.state.skills.iter().filter(|k| k.enabled).map(|k| json!({"key": k.name, "name": k.name, "note": k.description, "on": b.skills.as_ref().is_none_or(|a| a.contains(&k.name))})).collect::>(), "may_use": self.every_computer(b).into_iter().enumerate().map(|(i, (name, kind))| json!({"key": name, "name": name, "note": kind, "on": i == 0 || b.computers.as_ref().is_none_or(|a| a.contains(&name)), "fixed": i == 0})).collect::>(), "computer": chosen, "computers": choices.iter().map(|(name, note)| json!({"name": name, "note": note})).collect::>(), "tools_enabled": b.tools_enabled, "context_tokens": b.context_tokens, "folder": b.folder, "pinned": b.pinned, "primary": b.id == self.state.primary_bot, "unread": b.unread, "team": b.team, "members": b.members.iter().map(|i| json!({"id": i, "name": names.get(i).cloned().unwrap_or_default()})).collect::>(), "memories": if owner { b.memories.clone() } else { vec![] }, "allow_rules": if owner { b.allow_rules.clone() } else { vec![] }, "demos": b.demos.iter().map(|d| json!({"name": d.name, "created": d.created, "steps": d.steps.len()})).collect::>(), "routines": b.routines.iter().map(|r| json!({ "id": r.id, "title": r.title, "prompt": r.prompt, "paused": r.paused, "when": appctl::routine_when(r), "schedule": serde_json::to_value(&r.schedule).unwrap_or_default(), "repeat": crate::routines::describe(&r.schedule), "trigger": r.trigger.as_ref().map(|t| t.describe()), "status": trig.get(&r.id).cloned(), "last": r.last_run.map(|t| crate::routines::describe_when(t, &r.schedule.timezone)), "computer": r.computer, "paused_why": if r.paused { r.paused_why.clone() } else { String::new() }, "runs": r.runs.iter().rev().take(5).map(|x| json!({"line": crate::routines::describe_run(x, &r.schedule.timezone), "bad": matches!(x.outcome, crate::routines::RunOutcome::Failed | crate::routines::RunOutcome::Interrupted), "sends": x.sends})).collect::>(), "target": crate::appctl::target_words(r), })).collect::>(), "threads": b.threads.iter().enumerate().rev().map(|(i, (title, msgs))| json!({"index": i, "title": title, "count": msgs.len(), "at": msgs.last().map(|m| m.at).unwrap_or(0)})).collect::>(), "files": files, }) } /// 設定 as the phone shows it (nothing secret: keys only as "set or not"). fn phone_settings(&self, owner: bool) -> serde_json::Value { let st = &self.state; let ch_status = crate::channels::statuses().lock().unwrap().iter().map(|(k, v)| (*k, (v.ok, v.note.clone(), v.received))).collect::>(); let mcp = crate::mcp::status(); let mcp_err = self.ch.mcp_errors.lock().unwrap().clone(); let bot_name = |id: u64| st.bot(id).map(|b| b.name.clone()).unwrap_or_else(|| "(Bot 已刪除)".into()); let log = crate::cloudbox::log_lines(); let mut out = json!({ "role": if owner { "owner" } else { "admin" }, "host": st.remote.host_name, "version": crate::version::LABEL, "built": crate::version::epoch_ms(self.exe_built), "newer": self.newer_build.is_some(), "theme": match st.theme { Theme::Light => "light", Theme::Dark => "dark", Theme::System => "system" }, // 聊天的顏色 in the words update_settings takes (the phone ticks the one in use; the // enum's own names, "Quiet", matched none of them). "accent": match st.accent { crate::model::Accent::Quiet => "quiet", crate::model::Accent::Black => "black", crate::model::Accent::BotColor => "bot_color", }, "timezone": st.timezone, "notify": st.notify, "language": st.language, // 風格: the one worn ("" = 自訂) and each one's colours for the phone's little pictures. "style": st.shell_template, "shell_accent": st.shell_accent, "shell_contrast": st.shell_contrast, "accents": crate::theme::ACCENTS.iter().map(|(n, label, l, d)| json!({"key": n, "name": label, "light": format!("#{:02x}{:02x}{:02x}", l.r(), l.g(), l.b()), "dark": format!("#{:02x}{:02x}{:02x}", d.r(), d.g(), d.b())})).collect::>(), "languages": crate::i18n::LANGS.iter().map(|(tag, endo, _)| json!([tag, endo])).collect::>(), "styles": crate::theme::TEMPLATES.iter().map(|t| { let look = |dark| { let p = crate::theme::palette_for(t.id, 1.0, "clay", st.shell_contrast, dark); let pj = remote::palette_json(&p); json!({"pane": pj["pane"], "side": pj["side"], "text3": pj["text3"], "hover": pj["hover"], "active": pj["active"], "bubble": pj["bubble-user"], "accent": pj["accent"], "line": pj["line"], "grid": pj["grid"]}) }; json!({"id": t.id, "name": t.name, "about": t.about, "backdrop": t.backdrop, "light": look(false), "dark": look(true)}) }).collect::>(), "direct_mode": st.direct_mode, "direct_locked": !self.managed.direct.allows() || !self.managed.local.allows(), "smart_mode": st.smart_mode, // 權限's 一律放行 and how long a 智慧模式 card waits; 更新's switches; 記憶與文件. // 語音: who hears (聽) and who reads aloud (說); a key is only said to be there. "voice": { "listen": {"kind": serde_json::to_value(st.voice.listen.kind).unwrap_or_default(), "base_url": st.voice.listen.base_url, "model": st.voice.listen.model, "has_key": !st.voice.listen.api_key.is_empty(), "ready": crate::speech::resolve(&st.voice.listen, st, false).is_some()}, "speak": {"kind": serde_json::to_value(st.voice.speak.kind).unwrap_or_default(), "base_url": st.voice.speak.base_url, "model": st.voice.speak.model, "voice": st.voice.speak.voice, "has_key": !st.voice.speak.api_key.is_empty(), "ready": crate::speech::resolve(&st.voice.speak, st, true).is_some()}, }, "always_approve": st.always_approve, "smart_timeout_secs": st.smart_timeout_secs, "auto_update": st.auto_update_when_away, "garden_reports": st.garden_reports, "embed": match st.embed_model.trim() { "" | "local" => "local", "off" => "off", _ => "ollama" }, "doc_folders": st.doc_folders, "auto_review": st.auto_review, "allow_rules": st.review_allow_rules, "ask_rules": st.review_ask_rules, "providers": crate::providers::ALL_PROVIDERS.iter().map(|&k| { let ps = st.provider(k); // (ChatGPT 方案 signs in with an account, not a key: `account`.) json!({"key": serde_json::to_value(k).unwrap_or_default(), "label": k.label(), "needs_key": k.needs_key() && k != crate::providers::ProviderKind::ChatGpt, "account": k == crate::providers::ProviderKind::ChatGpt, "ready": crate::providers::ready(k, &ps.api_key), "default_model": ps.default_model, "custom_url": !ps.base_url.is_empty(), "base_url": ps.base_url, "default_url": k.default_base_url(), "cloud_eyes": ps.cloud_eyes, "local": crate::providers::is_local_model(k, &crate::providers::resolve_base(k, &ps.base_url)), "known": ps.known_models.len(), "testing": self.model_fetch.contains_key(&k), "status": self.fetch_status.get(&k).cloned().unwrap_or_default(), "runs": crate::providers::runs_at(k, &crate::providers::resolve_base(k, &ps.base_url)).short()}) }).collect::>(), "skills": st.skills.iter().map(|k| json!({ "name": k.name, "description": k.description, "instructions": k.instructions, "enabled": k.enabled, "resources": k.resources, "steps": k.steps.len(), "source": k.source, })).collect::>(), "skill_market": crate::skills::BUILTIN_SKILLS.iter().map(|b| json!({ "name": b.slug, "title": b.title, "summary": b.summary, "source": format!("builtin:{}", b.slug), "remote": false, })).chain(crate::skills::REMOTE_MARKET.iter().map(|r| json!({ "name": r.name, "title": r.name, "summary": r.summary, "source": r.source, "remote": true, }))).collect::>(), "templates": crate::memory::TEMPLATES.iter().map(|t| { let c = crate::avatar::color(t.color); json!({"name": t.name, "description": t.description, "shape": t.shape, "color": format!("#{:02x}{:02x}{:02x}", c.r(), c.g(), c.b())}) }).collect::>(), "shapes": crate::avatar::SHAPES, "colors": crate::avatar::COLORS.iter().map(|(k, n, c)| json!({"key": k, "name": n, "hex": format!("#{:02x}{:02x}{:02x}", c[0], c[1], c[2])})).collect::>(), "folders": st.folders, "channels": st.channels.iter().map(|c| { let (ok, note, received) = ch_status.get(&c.id).cloned().unwrap_or((false, String::new(), 0)); json!({"id": c.id, "kind": c.kind.label(), "name": c.name, "bot": bot_name(c.bot_id), "target": c.target, "enabled": c.enabled, "ok": ok, "note": note, "received": received}) }).collect::>(), "mcp": st.mcp_servers.iter().map(|m| json!({ "name": m.name, "enabled": m.enabled, "tools": mcp.get(&m.name), "error": mcp_err.iter().find(|e| e.0 == m.name).map(|e| e.1.clone()), "what": if m.url.is_empty() { m.command.clone() } else { address_only(&m.url) }, })).collect::>(), "box": { "state": crate::cloudbox::run_state().label(), "available": crate::cloudbox::available(), "version": crate::cloudbox::wanted_version(), "runtime": crate::cloudbox::box_runtime(), "snapshot": crate::cloudbox::snapshot_time().map(|t| t.format("%m/%d %H:%M").to_string()), "auto_update": crate::cloudbox::auto_update_at(), "note": self.cu.note.lock().unwrap().clone(), "disk": self.cu.disk.lock().unwrap().clone(), "log": log.iter().rev().take(40).rev().cloned().collect::>(), "facts": box_facts(), }, }); if owner { out["devices"] = json!(st.remote.devices.iter().map(|d| json!({"name": d.name, "created": d.created, "last_seen": d.last_seen})).collect::>()); out["docker_host"] = json!(crate::cloudbox::docker_host()); } out } } #[cfg(test)] mod phone_act_tests { use super::*; /// The demo app (sample bots, nothing read from or saved to disk). fn demo() -> (egui::Context, App) { let ctx = egui::Context::default(); let app = App::new(&ctx, Some(std::env::temp_dir().join("anybot-phone-act-test.png"))); (ctx, app) } /// 允許/拒絕 on a phone notification answers only the request it showed: once that one /// is gone and another waits, the old banner answers nothing (a note says so). And only a /// request to allow that fits on the banner: never 我完成了, 略過 or 一律允許 from there. #[test] fn a_banner_answers_only_its_own_request() { let (ctx, mut app) = demo(); let bot = app.state.bots[0].id; let card = |app: &mut App, kind: ApprovalKind, reason: &str, key: &str| { let (tx, rx) = std::sync::mpsc::channel(); // (The same tool call asking again, as one step does: a new key each time.) app.approvals.insert(bot, crate::providers::Approval { call_id: "c0".into(), tool: "shell".into(), reason: reason.into(), grant: "rm".into(), reply: tx, kind }); app.ask_keys.insert(bot, key.into()); rx }; let banner = |answer: &str, call: &str| Cmd::Answer { bot, answer: answer.into(), text: String::new(), call: call.into(), notice: true, screen: false }; let rx = card(&mut app, ApprovalKind::Action, "刪除 build", "call-2"); app.remote_cmd(&ctx, banner("once", "call-1")); assert!(rx.try_recv().is_err(), "an old banner doesn't allow the new request"); assert!(app.approvals.contains_key(&bot)); assert!(app.state.bot(bot).unwrap().messages.iter().any(|m| m.note && m.text.contains("通知上的「允許/拒絕」沒有用上"))); // Its key, but 一律允許 (a banner has none) or a command too long for the banner: no. app.remote_cmd(&ctx, banner("always", "call-2")); assert!(rx.try_recv().is_err() && app.state.bot(bot).unwrap().allow_rules.is_empty()); app.remote_cmd(&ctx, banner("once", "call-2")); assert!(matches!(rx.try_recv(), Ok(ApprovalAnswer::Once))); let rx = card(&mut app, ApprovalKind::Action, "執行指令:\nrm -rf build\nrm -rf dist", "long"); app.remote_cmd(&ctx, banner("once", "long")); assert!(rx.try_recv().is_err(), "the banner showed only its first line"); // A hand-off or a question isn't answered from a banner, even with its key… let rx = card(&mut app, ApprovalKind::Handoff, "登入", "h"); app.remote_cmd(&ctx, banner("once", "h")); assert!(rx.try_recv().is_err(), "允許 on a banner is never 我完成了"); // …but the phone's own card answers it, with that key. app.remote_cmd(&ctx, Cmd::Answer { bot, answer: "once".into(), text: String::new(), call: "h".into(), notice: false, screen: false }); assert!(matches!(rx.try_recv(), Ok(ApprovalAnswer::Once)), "我完成了 on the phone's card"); let rx = card(&mut app, ApprovalKind::Question, r#"[{"question":"哪一天?"}]"#, "q"); app.remote_cmd(&ctx, banner("reject", "q")); assert!(rx.try_recv().is_err(), "拒絕 on a banner is never 略過"); app.remote_cmd(&ctx, Cmd::Answer { bot, answer: "answered".into(), text: r#"["週五"]"#.into(), call: "q".into(), notice: false, screen: false }); assert_eq!(rx.try_recv(), Ok(ApprovalAnswer::Answered(r#"["週五"]"#.into()))); } /// 智慧模式's 「這輪都准」 on the phone's card: the scope is the card's own grant (the phone's /// words never pick what it covers), it is offered on the card only while smart mode is on, /// and a banner never carries it (a notification has 允許/拒絕 only). #[test] fn the_phone_scope_answer_takes_the_cards_own_grant() { let (ctx, mut app) = demo(); let bot = app.state.bots[0].id; let card = |app: &mut App, key: &str| { let (tx, rx) = std::sync::mpsc::channel(); app.approvals.insert(bot, crate::providers::Approval { call_id: "c1".into(), tool: "shell".into(), reason: "執行指令:\ngit commit -m x".into(), grant: "shell:git commit".into(), reply: tx, kind: ApprovalKind::Action }); app.ask_keys.insert(bot, key.into()); rx }; let rx = card(&mut app, "k1"); let shown_off = approval_json(app.state.bot(bot).unwrap(), app.approvals.get(&bot).unwrap(), "k1", false); assert_eq!(shown_off["can_scope"], json!(false), "no 這輪都准 on the card while smart mode is off"); let shown_on = approval_json(app.state.bot(bot).unwrap(), app.approvals.get(&bot).unwrap(), "k1", true); assert_eq!(shown_on["can_scope"], json!(true)); app.remote_cmd(&ctx, Cmd::Answer { bot, answer: "scope".into(), text: String::new(), call: "k1".into(), notice: false, screen: false }); assert!(matches!(rx.try_recv(), Ok(ApprovalAnswer::Scope(g)) if g == "shell:git commit"), "the scope is the card's grant, this turn only"); let rx = card(&mut app, "k2"); app.remote_cmd(&ctx, Cmd::Answer { bot, answer: "scope".into(), text: String::new(), call: "k2".into(), notice: true, screen: false }); assert!(rx.try_recv().is_err(), "a banner has no 這輪都准"); } /// The phone's own card (and a screen) names its card too: a page too old to send a key, or /// a card answered and replaced since, answers nothing while the next one waits — and the /// note says what to do about it where it came from (refresh the phone's page; update the /// screen computer's AnyBot). With nothing waiting there is nothing to say. #[test] fn a_phone_answer_without_its_cards_key_answers_nothing() { let (ctx, mut app) = demo(); let bot = app.state.bots[0].id; let from = |screen: bool, answer: &str, call: &str| Cmd::Answer { bot, answer: answer.into(), text: String::new(), call: call.into(), notice: false, screen }; let (tx, rx) = std::sync::mpsc::channel(); app.approvals.insert(bot, crate::providers::Approval { call_id: "c0".into(), tool: "shell".into(), reason: "刪除 build".into(), grant: "rm".into(), reply: tx, kind: ApprovalKind::Action }); app.ask_keys.insert(bot, "now".into()); let last_note = |app: &App| app.state.bot(bot).unwrap().messages.iter().rev().find(|m| m.note).map(|m| m.text.clone()).unwrap_or_default(); let notes = |app: &App| app.state.bot(bot).unwrap().messages.iter().filter(|m| m.note && m.text.contains("沒有用上")).count(); app.remote_cmd(&ctx, from(false, "always", "")); // (And when refreshing doesn't help — an account server not yet updated — the computer.) assert!(last_note(&app).starts_with("手機上的回答沒有用上") && last_note(&app).contains("頁面太舊") && last_note(&app).contains("重新整理") && last_note(&app).contains("在電腦上回答"), "{}", last_note(&app)); app.remote_cmd(&ctx, from(false, "once", "before")); assert!(last_note(&app).starts_with("手機上的回答沒有用上") && last_note(&app).contains("已經不在等了") && !last_note(&app).contains("頁面太舊"), "{}", last_note(&app)); // An older screen computer sends no key: refreshing does nothing there — updating does. app.remote_cmd(&ctx, from(true, "once", "")); assert!(last_note(&app).starts_with("螢幕電腦上的回答沒有用上") && last_note(&app).contains("設定 › 更新") && !last_note(&app).contains("重新整理"), "{}", last_note(&app)); app.remote_cmd(&ctx, from(true, "once", "before")); assert!(last_note(&app).starts_with("螢幕電腦上的回答沒有用上") && last_note(&app).contains("已經不在等了"), "{}", last_note(&app)); assert!(rx.try_recv().is_err() && app.state.bot(bot).unwrap().allow_rules.is_empty(), "no key, or an old one: nothing"); assert_eq!(notes(&app), 4, "each one says so"); app.remote_cmd(&ctx, from(false, "reject", "now")); assert_eq!(rx.try_recv(), Ok(ApprovalAnswer::Reject)); // Nothing waits now: an answer that comes late says nothing. app.remote_cmd(&ctx, from(false, "once", "now")); assert_eq!(notes(&app), 4); } /// A 支線's card on the phone: in its main bot's chat (`bot`), answered for the 支線 /// (`target`), with the 支線's own key — the main bot's would answer nothing (or, if the main /// bot waits too, be refused as another card's). An answer that can't be taken is said in /// the main bot's chat, where the 支線's card is shown: its own messages aren't shown anywhere. #[test] fn a_branch_card_on_the_phone_carries_its_own_key_and_target() { let (ctx, mut app) = demo(); let main = app.state.bots[0].clone(); let mut br = main.clone(); br.id = 9001; br.branch_of = main.id; br.messages.clear(); app.state.branch_bots.push(br); let card = |app: &mut App, id: u64, reason: &str, key: &str| { let (tx, rx) = std::sync::mpsc::channel(); app.approvals.insert(id, crate::providers::Approval { call_id: "call_0".into(), tool: "shell".into(), reason: reason.into(), grant: String::new(), reply: tx, kind: ApprovalKind::Action }); app.ask_keys.insert(id, key.into()); rx }; let main_rx = card(&mut app, main.id, "執行指令:ls", "km"); let branch_rx = card(&mut app, 9001, "執行指令:rm -rf build", "kb"); let cards = app.phone_cards(&main); let b = cards.iter().find(|c| c["target"] == 9001).cloned().unwrap_or_default(); assert_eq!((b["bot"].as_u64(), b["key"].as_str()), (Some(main.id), Some("kb")), "{cards:?}"); let m = cards.iter().find(|c| c["target"].is_null()).cloned().unwrap_or_default(); assert_eq!(m["key"], "km", "{cards:?}"); // A stale answer for the 支線 (its last card's key): refused, said in the main chat. app.remote_cmd(&ctx, Cmd::Answer { bot: 9001, answer: "once".into(), text: String::new(), call: "old".into(), notice: false, screen: false }); assert!(branch_rx.try_recv().is_err()); let said = |app: &App, id: u64| app.state.bot(id).unwrap().messages.iter().any(|m| m.note && m.text.contains("沒有用上")); assert!(said(&app, main.id) && !said(&app, 9001), "the note is in the main bot's chat"); // The phone answers it as renderDock does: api/bots/{target}/answer with its key. let target = b["target"].as_u64().unwrap_or(0); app.remote_cmd(&ctx, Cmd::Answer { bot: target, answer: "once".into(), text: String::new(), call: b["key"].as_str().unwrap_or("").into(), notice: false, screen: false }); assert_eq!(branch_rx.try_recv(), Ok(ApprovalAnswer::Once)); assert!(main_rx.try_recv().is_err() && app.approvals.contains_key(&main.id), "the main bot's card still waits"); } /// An act from a direct connection: remote::lan_guard first (asked about the bot as the /// route asks), then phone_act — as remote.rs does it. fn over_lan(ctx: &egui::Context, app: &mut App, action: &str, body: serde_json::Value) -> Result { let detail = app.phone_act(ctx, "detail", &json!({"bot": body["bot"]}), "owner"); match crate::remote::lan_guard(action, &body, || detail, "runc") { crate::remote::Guard::Keeps => Ok(app.phone_act(ctx, action, &body, "owner")), other => Err(other), } } /// A direct connection only tightens, however a setting's name is spelled: 「direct_mode 」, /// 「 rule_add」, 「abilities 」 got past the guard (it read the name exactly) and were done /// anyway (phone_act trimmed it). Each loosening, padded, cased or with a wide space, leaves /// every guard as it was; the tightenings still go through. #[test] fn a_direct_connection_cannot_loosen_by_spelling_a_setting_differently() { let (ctx, mut app) = demo(); let b = app.state.bots[0].id; app.state.direct_mode = false; app.state.auto_review = false; app.state.review_ask_rules = vec!["付款前先問我".into()]; app.state.review_allow_rules = vec![]; { let x = app.state.bot_mut(b).unwrap(); x.abilities = Some(vec!["web".into()]); x.tools_enabled = false; x.team = false; x.allow_rules = vec!["rm".into()]; } let guards = |app: &App| { let x = app.state.bot(b).unwrap(); format!("{} {} {:?} {:?} {:?} {} {} {:?}", app.state.direct_mode, app.state.auto_review, app.state.review_ask_rules, app.state.review_allow_rules, x.abilities, x.tools_enabled, x.team, x.allow_rules) }; let before = guards(&app); let every = crate::profile::ABILITIES.iter().map(|a| a.0).collect::>(); let loosen: Vec<(&str, &str, serde_json::Value)> = vec![ ("setting", "key", json!({"key": "direct_mode", "value": true})), ("setting", "key", json!({"key": "auto_review", "value": true})), ("setting", "key", json!({"key": "rule_add", "list": "allow", "value": "全部直接做"})), ("setting", "list", json!({"key": "rule_add", "list": "allow", "value": "全部直接做"})), ("setting", "key", json!({"key": "rule_remove", "list": "ask", "value": "付款前先問我"})), ("setting", "list", json!({"key": "rule_remove", "list": "ask", "value": "付款前先問我"})), ("bot", "key", json!({"bot": b, "key": "abilities", "value": every})), ("bot", "key", json!({"bot": b, "key": "tools", "value": true})), ("bot", "key", json!({"bot": b, "key": "team", "value": true})), ]; for (action, field, body) in loosen { assert!(over_lan(&ctx, &mut app, action, body.clone()).is_err(), "as sent: {body}"); let name = body[field].as_str().unwrap().to_string(); for spelled in [format!("{name} "), format!(" {name}"), format!("\t{name}"), format!("{name}\u{3000}"), format!("{name}\u{a0}"), name.to_uppercase()] { let mut odd = body.clone(); odd[field] = json!(spelled); let _ = over_lan(&ctx, &mut app, action, odd.clone()); assert_eq!(guards(&app), before, "{odd}"); } } // Tightening still works from there: an ask rule in, an allow rule out, tools off. assert_eq!(over_lan(&ctx, &mut app, "setting", json!({"key": "rule_add", "list": "ask", "value": "寄信前先問我"})).unwrap()["ok"], true); assert_eq!(over_lan(&ctx, &mut app, "bot", json!({"bot": b, "key": "allow_remove", "value": "rm"})).unwrap()["ok"], true); assert_eq!(over_lan(&ctx, &mut app, "bot", json!({"bot": b, "key": "abilities", "value": []})).unwrap()["ok"], true); assert!(app.state.review_ask_rules.contains(&"寄信前先問我".to_string()) && app.state.bot(b).unwrap().allow_rules.is_empty()); assert_eq!(app.state.bot(b).unwrap().abilities, Some(vec![])); // An unknown list is said so, not taken as the allow list. assert!(app.phone_act(&ctx, "setting", &json!({"key": "rule_add", "list": "Ask", "value": "x"}), "owner")["error"].is_string()); assert!(app.state.review_allow_rules.is_empty()); } /// phone_act reads a setting's name exactly as sent, on every road in (the account's too): /// 「direct_mode 」, 「Tools」, 「update 」 aren't those, and change nothing. #[test] fn phone_act_reads_setting_names_exactly() { let (ctx, mut app) = demo(); let b = app.state.bots[0].id; app.state.direct_mode = false; app.state.bot_mut(b).unwrap().tools_enabled = false; for (action, body) in [ ("setting", json!({"key": "direct_mode ", "value": true})), ("setting", json!({"key": " auto_review", "value": true})), ("setting", json!({"key": "rule_add", "list": " allow", "value": "全部直接做"})), ("bot", json!({"bot": b, "key": "Tools", "value": true})), ("bot", json!({"bot": b, "key": "abilities\u{3000}", "value": []})), ("box", json!({"op": "update "})), ] { assert!(app.phone_act(&ctx, action, &body, "owner")["error"].is_string(), "{body}"); } assert!(!app.state.direct_mode && !app.state.auto_review && app.state.review_allow_rules.is_empty()); let x = app.state.bot(b).unwrap(); assert!(!x.tools_enabled && x.abilities.is_none()); } /// A bot file imported from a direct connection: a file that says 「team」 doesn't share the /// new bot with the team (it got past the guard as an action nobody had classified, and the /// file's sharing was kept). #[test] fn an_imported_bot_is_not_shared_with_the_team() { let (ctx, mut app) = demo(); let mut x = app.state.bots[0].clone(); x.team = true; let content = crate::share::export(&x).replacen("\"name\"", "\"team\":true,\"name\"", 1); let r = over_lan(&ctx, &mut app, "import_bot", json!({"content": content})).expect("importing changes no guard"); let id = r["bot"].as_u64().unwrap(); assert!(!app.state.bot(id).unwrap().team); } /// 可以用的電腦 from the phone while a computer of the account is off (so not listed): it /// keeps how it was. Ticking every computer listed used to make the list "every computer", /// and a computer the person had left out came back in. #[test] fn a_computer_that_is_off_keeps_its_place_in_the_list() { let (ctx, mut app) = demo(); let b = app.state.bots[0].id; app.state.remote.host_token = "t".into(); app.state.remote.host_id = "me".into(); *app.rm.peers.lock().unwrap() = vec![("dev1".into(), "筆電".into(), true), ("dev2".into(), "桌機".into(), true)]; let x = app.state.bot(b).unwrap().clone(); let names: Vec = app.every_computer(&x).into_iter().map(|c| c.0).collect(); assert!(names.contains(&"筆電".to_string()) && names.contains(&"桌機".to_string()), "{names:?}"); // Every computer but 筆電; then 筆電 and 桌機 go off. let kept: Vec = names.iter().skip(1).filter(|n| *n != "筆電").cloned().collect(); app.state.bot_mut(b).unwrap().computers = Some(kept.clone()); *app.rm.peers.lock().unwrap() = vec![("dev1".into(), "筆電".into(), false), ("dev2".into(), "桌機".into(), false)]; let ticked = |app: &mut App| -> Vec { let d = app.phone_act(&ctx, "detail", &json!({"bot": b}), "owner"); d["may_use"].as_array().unwrap().iter().filter(|m| m["on"] == true).filter_map(|m| m["key"].as_str().map(String::from)).collect() }; let now = ticked(&mut app); assert!(over_lan(&ctx, &mut app, "bot", json!({"bot": b, "key": "may_use", "value": now})).is_ok()); assert_eq!(app.state.bot(b).unwrap().computers, Some(kept.clone()), "筆電 stays out, 桌機 stays in"); // From the account too (no guard there): a list stays a list. let now = ticked(&mut app); app.phone_act(&ctx, "bot", &json!({"bot": b, "key": "may_use", "value": now}), "owner"); assert_eq!(app.state.bot(b).unwrap().computers, Some(kept)); // A bot with no list (every computer) keeps none while everything listed stays ticked. app.state.bot_mut(b).unwrap().computers = None; let now = ticked(&mut app); app.phone_act(&ctx, "bot", &json!({"bot": b, "key": "may_use", "value": now}), "owner"); assert_eq!(app.state.bot(b).unwrap().computers, None); } /// A ChatGPT card says what it asks — here a 支線 signing out — not the tool's name (it read /// 「支線:…想要ChatGPT 方案登入」 for a logout). #[test] fn a_chatgpt_card_says_whether_it_signs_in_or_out() { let (_ctx, mut app) = demo(); let main = app.state.bots[0].clone(); let mut br = main.clone(); br.id = 9003; br.branch_of = main.id; let call = crate::model::ToolCall { id: "c1".into(), name: crate::chatgpt::TOOL.into(), args: r#"{"action":"logout"}"#.into(), status: crate::model::ToolStatus::Waiting }; br.messages = vec![crate::model::Message::user("登出"), crate::model::Message { tool_calls: vec![call], ..crate::model::Message::assistant("", "x") }].into(); app.state.branch_bots.push(br); let (tx, _rx) = std::sync::mpsc::channel(); app.approvals.insert(9003, crate::providers::Approval { call_id: "c1".into(), tool: crate::chatgpt::TOOL.into(), reason: "登出 ChatGPT:用 ChatGPT 方案的 Bot 會沒辦法回答,直到再登入。".into(), grant: String::new(), reply: tx, kind: ApprovalKind::Action }); let cards = app.phone_cards(&main); let card = cards.iter().find(|c| c["target"] == 9003).cloned().unwrap_or_default(); assert_eq!(card["title"], format!("支線:{} 想要登出 ChatGPT 方案", main.name), "{cards:?}"); assert_eq!(crate::chatgpt::ask_label(r#"{"action":"switch_account"}"#), "換 ChatGPT 帳號"); } /// A card that takes another's place with the same call id (call_0 every round) and the same /// words — the same step asking again — is published again (the view's signature changes), /// so the phone and the screens get the new card's key: with the old one every answer would /// be refused. A 支線's card the same. /// 交付確認: a device's word on a file the bot handed over reaches the phones (the ✓✓). #[test] fn a_files_delivery_is_published() { let (ctx, mut app) = demo(); let bot = app.state.bots[0].id; let a = crate::attach::Attachment { name: "貓.png".into(), path: "/x/貓.png".into(), image: true, id: "a1b2c3d4e5f6".into(), ..Default::default() }; app.state.bot_mut(bot).unwrap().messages.push(Message { attachments: vec![a], ..Message::assistant("好了", "") }); let before = app.remote_signature(); app.delivery_seen(&ctx, bot, "a1b2c3d4e5f6", "iPhone", crate::attach::SeenKind::Shown, "", true); assert_ne!(app.remote_signature(), before); let a = &app.state.bot(bot).unwrap().messages.last().unwrap().attachments[0]; assert_eq!((a.seen[0].device.as_str(), a.delivery()), ("iPhone", crate::attach::Delivery::Shown)); } #[test] fn a_card_in_anothers_place_is_published_again() { let (_ctx, mut app) = demo(); let main = app.state.bots[0].clone(); let mut br = main.clone(); br.id = 9002; br.branch_of = main.id; br.messages.clear(); app.state.branch_bots.push(br); let card = |app: &mut App, id: u64, key: &str| { let (tx, _) = std::sync::mpsc::channel(); app.approvals.insert(id, crate::providers::Approval { call_id: "call_0".into(), tool: "shell".into(), reason: "執行指令:rm -rf build".into(), grant: String::new(), reply: tx, kind: ApprovalKind::Action }); app.ask_keys.insert(id, key.into()); }; card(&mut app, main.id, "k1"); let before = app.remote_signature(); card(&mut app, main.id, "k2"); assert_ne!(app.remote_signature(), before, "the main bot's new card is published"); card(&mut app, 9002, "b1"); let before = app.remote_signature(); card(&mut app, 9002, "b2"); assert_ne!(app.remote_signature(), before, "the 支線's new card is published"); } /// 「全部允許,之後直接操作」 on a "may I use the computer?" card: 直接操作 lets that card /// through as it comes on, then the phone's answer for it arrives — maybe after the next card /// is already up. That answer takes nothing, and isn't told as a stale one (the card was done). #[test] fn the_answer_after_direct_mode_let_its_card_through_says_nothing() { let (ctx, mut app) = demo(); let bot = app.state.bots[0].id; let (tx, first) = std::sync::mpsc::channel(); app.approvals.insert(bot, crate::providers::Approval { call_id: "call_0".into(), tool: "shell".into(), reason: "在你的電腦上執行任務:ls".into(), grant: String::new(), reply: tx, kind: ApprovalKind::EnableThisComputer }); app.ask_keys.insert(bot, "k1".into()); app.enable_direct_mode(); assert!(matches!(first.try_recv(), Ok(ApprovalAnswer::Always(_))), "直接操作 let it through"); let (tx, second) = std::sync::mpsc::channel(); app.approvals.insert(bot, crate::providers::Approval { call_id: "call_0".into(), tool: "shell".into(), reason: "執行指令:rm -rf build".into(), grant: "rm".into(), reply: tx, kind: ApprovalKind::Action }); app.ask_keys.insert(bot, "k2".into()); app.remote_cmd(&ctx, Cmd::Answer { bot, answer: "once".into(), text: String::new(), call: "k1".into(), notice: false, screen: false }); assert!(second.try_recv().is_err() && app.approvals.contains_key(&bot), "the next card still waits"); assert!(!app.state.bot(bot).unwrap().messages.iter().any(|m| m.note && m.text.contains("沒有用上")), "no stale-answer note"); // Any other old key still is one. app.remote_cmd(&ctx, Cmd::Answer { bot, answer: "once".into(), text: String::new(), call: "k0".into(), notice: false, screen: false }); assert!(app.state.bot(bot).unwrap().messages.iter().any(|m| m.note && m.text.contains("沒有用上"))); } #[test] fn the_phone_does_what_the_desktop_does() { let (ctx, mut app) = demo(); assert!(app.demo && app.state.bots.len() >= 2); let b = app.state.bots[0].id; let act = |app: &mut App, what: &str, body: serde_json::Value, role: &str| app.phone_act(&ctx, what, &body, role); // The actions a bot can take, by the same appctl path. let v = act(&mut app, "app", json!({"bot": b, "name": "create_routine", "args": {"title": "早報", "prompt": "整理新聞", "schedule": {"frequency": "daily", "time": "08:00"}}}), "owner"); assert_eq!(v["ok"], true, "{v}"); let rid = app.state.bot(b).unwrap().routines.iter().find(|r| r.title == "早報").map(|r| r.id).expect("routine made"); assert_eq!(act(&mut app, "app", json!({"bot": b, "name": "update_routine", "args": {"id": rid, "paused": true}}), "owner")["ok"], true); assert!(app.state.bot(b).unwrap().routines.iter().any(|r| r.id == rid && r.paused)); assert_eq!(act(&mut app, "app", json!({"bot": b, "name": "remember", "args": {"fact": "週末不排工作"}}), "owner")["ok"], true); assert!(app.state.bot(b).unwrap().memories.contains(&"週末不排工作".to_string())); // Only the app actions a bot has; nothing else through this door. assert!(act(&mut app, "app", json!({"bot": b, "name": "write_page", "args": {}}), "owner")["error"].is_string()); assert!(act(&mut app, "nothing", json!({}), "owner")["error"].is_string()); // A bot's switches, checked like the editor checks them. assert_eq!(act(&mut app, "bot", json!({"bot": b, "key": "shape", "value": "star"}), "owner")["ok"], true); assert_eq!(app.state.bot(b).unwrap().shape, "star"); assert!(act(&mut app, "bot", json!({"bot": b, "key": "shape", "value": "