AnyBot/src/app/mirror_ui.rs

3204 lines
162 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 大腦: one AnyBot of the account keeps the bots, chats, memory and schedules (the brain, usually
// `anybot --serve` next to the account server). Every other AnyBot signed in to the account shows
// the brain's bots in its own window and lends its hands (screen, files, browser) through 裝置連結.
//
// The brain side answers "what changed since version N?" per screen: the settings (bots without
// their chats) when they changed, and for each bot only the messages from the first one that
// changed. The screen side keeps a copy, sends the person's edits back as small operations, and
// turns chat actions (send, stop, approve…) into requests. When the brain can't be reached the
// window shows its copy and keeps working: messages and edits wait in a queue (kept on disk) and
// go once the brain is back; only what acts on what runs there (stop, regenerate…) needs it.
use super::*;
use crate::memory::Skill;
use crate::remote::{self, SyncKind};
use serde_json::{json, Value};
use std::hash::{Hash, Hasher};
use std::sync::atomic::AtomicU64;
/// Settings that belong to each computer, never to the brain.
const LOCAL_KEYS: &[&str] = &["remote", "theme", "accent", "sidebar_collapsed", "sidebar_width", "selected", "machine_label", "local_execution", "local_never", "messages_send", "messages_no_ask"];
/// 外觀 (底色、強調色、對比、密度、慶祝動畫): kept in this computer's own file and put back over the
/// brain's whenever the brain's settings come — an update restarted the screen on its copy of the
/// brain's, and a brain that doesn't know these (an older one) answered with 紙 and its clay every
/// time, so the 強調色 picked here was orange again. Still sent to the brain when changed here: the
/// phone wears the brain's.
#[cfg(test)]
const LOOK_KEYS: &[&str] = &["shell_tone", "shell_accent", "shell_contrast", "dense", "celebrate"];
/// This computer's own settings (LOCAL_KEYS but `selected`, which names a bot of one side, and
/// LOOK_KEYS) from `from` onto `to`. The one list of them: four hand-kept lists had drifted apart.
fn copy_own(to: &mut State, from: &State) {
to.remote = from.remote.clone();
to.theme = from.theme;
to.accent = from.accent;
to.sidebar_collapsed = from.sidebar_collapsed;
to.sidebar_width = from.sidebar_width;
to.machine_label = from.machine_label.clone();
to.local_execution = from.local_execution;
to.local_never = from.local_never;
to.messages_send = from.messages_send;
to.messages_no_ask = from.messages_no_ask;
to.shell_tone = from.shell_tone;
to.shell_accent = from.shell_accent.clone();
to.shell_contrast = from.shell_contrast;
to.dense = from.dense;
to.celebrate = from.celebrate;
}
/// Bot fields the brain alone changes (its chat, and what a turn leaves behind).
const BOT_RUNTIME: &[&str] = &["id", "messages", "threads", "unread", "last_turn", "tasks", "context_tokens", "goal", "plan", "regen_undo", "branches", "branch_of"];
/// Stands in for a key or token the brain doesn't hand out.
pub const REDACTED: &str = "••••(已設定,在大腦上)";
// ---------- shared ----------
/// The settings as JSON: everything but the chats (messages and earlier conversations).
pub(super) fn config_json(st: &mut State) -> Value {
let mut bots = std::mem::take(&mut st.bots);
let mut top = serde_json::to_value(&*st).unwrap_or(Value::Null);
let mut arr = Vec::with_capacity(bots.len());
for b in bots.iter_mut() {
let m = std::mem::take(&mut b.messages);
let th = std::mem::take(&mut b.threads);
arr.push(serde_json::to_value(&*b).unwrap_or(Value::Null));
b.messages = m;
b.threads = th;
}
st.bots = bots;
top["bots"] = Value::Array(arr);
top
}
const TRIGGER_SECRETS: [&str; 4] = ["token", "apiKey", "secret", "api_key"];
fn redact_triggers(v: &mut Value) {
match v {
Value::Object(m) => {
for k in TRIGGER_SECRETS {
if m.get(k).and_then(Value::as_str).is_some_and(|s| !s.is_empty()) {
m.insert(k.to_string(), Value::String(REDACTED.into()));
}
}
for x in m.values_mut() {
redact_triggers(x);
}
}
Value::Array(a) => a.iter_mut().for_each(redact_triggers),
_ => {}
}
}
/// Keys and tokens stay on the brain.
fn redact(top: &mut Value) {
if let Some(o) = top.as_object_mut() {
o.remove("remote");
}
let hide = |v: &mut Value| {
if v.as_str().map(|s| !s.is_empty()).unwrap_or(false) {
*v = Value::String(REDACTED.into());
}
};
if let Some(ps) = top["providers"].as_object_mut() {
for p in ps.values_mut() {
hide(&mut p["api_key"]);
}
}
for c in top["channels"].as_array_mut().into_iter().flatten() {
hide(&mut c["token"]);
}
// 設定 › 語音's own keys (ElevenLabs, or one just for voice).
if let Some(v) = top.get_mut("voice").and_then(Value::as_object_mut) {
for side in ["listen", "speak"] {
if let Some(e) = v.get_mut(side).and_then(Value::as_object_mut) {
if let Some(k) = e.get_mut("api_key") {
hide(k);
}
}
}
}
for m in top["mcp_servers"].as_array_mut().into_iter().flatten() {
for k in ["env", "headers"] {
for v in m[k].as_object_mut().into_iter().flat_map(|o| o.values_mut()) {
hide(v);
}
}
if let Some(v) = m.get_mut("password") {
hide(v);
}
}
for b in top["bots"].as_array_mut().into_iter().flatten() {
// (Only a trigger there is: `r["trigger"]` put a `null` into every routine without one,
// and the screen's own copy — which has none — then differed from it, so each save
// sent every bot's routines back as an edit.)
for r in b["routines"].as_array_mut().into_iter().flatten() {
if let Some(t) = r.get_mut("trigger") {
redact_triggers(t);
}
}
}
}
fn clear_redacted(v: &mut Value) {
match v {
Value::String(s) if s == REDACTED => s.clear(),
Value::Object(o) => o.values_mut().for_each(clear_redacted),
Value::Array(a) => a.iter_mut().for_each(clear_redacted),
_ => {}
}
}
/// Put the brain's own keys back wherever an edit still carries the stand-in — unless the
/// target address or command of that object changed (otherwise changing `base_url`/`url` to an
/// attacker's server while keeping `REDACTED` would make the brain send its real secret there).
fn unredact(new: &mut Value, old: &Value) {
match new {
Value::String(s) if s == REDACTED => {
*new = old.as_str().map(|s| Value::String(s.to_string())).unwrap_or_else(|| Value::String(String::new()));
}
Value::Object(o) => {
let endpoint_changed = ["base_url", "url", "command", "args"].iter().any(|k| o.contains_key(*k) && o.get(*k) != old.get(*k));
if endpoint_changed {
for k in ["api_key", "token", "secret", "apiKey", "env", "headers", "password"] {
if let Some(v) = o.get_mut(k) {
clear_redacted(v);
}
}
}
for (k, v) in o.iter_mut() {
unredact(v, old.get(k).unwrap_or(&Value::Null));
}
}
Value::Array(a) => {
for (i, v) in a.iter_mut().enumerate() {
let key = |x: &Value| x.get("id").cloned().filter(|x| !x.is_null()).or_else(|| x.get("name").cloned().filter(|s| s.as_str().is_some_and(|t| !t.is_empty())));
let twin = old.as_array().and_then(|olds| match key(v) {
Some(k) => olds.iter().find(|o| key(o).as_ref() == Some(&k)),
None => olds.get(i),
});
unredact(v, twin.unwrap_or(&Value::Null));
}
}
_ => {}
}
}
/// A cheap fingerprint of one message: enough to see it changed (streaming, a tool finishing…).
fn msg_sig(m: &Message) -> u64 {
let mut h = std::collections::hash_map::DefaultHasher::new();
(m.role as u8, m.text.len(), m.thinking.len(), m.error, m.summary, m.images.len(), m.attachments.len(), m.at, &m.tool_call_id, &m.reactions).hash(&mut h);
m.text.chars().rev().take(48).collect::<String>().hash(&mut h);
for c in &m.tool_calls {
(&c.id, c.args.len(), c.status as u8).hash(&mut h);
}
// 交付確認: a device's word on a file reaches the screens too.
for a in &m.attachments {
a.seen.len().hash(&mut h);
}
// 完成宣稱關卡: so does the 「未驗證」 under a reply.
m.check.len().hash(&mut h);
h.finish()
}
fn threads_sig(b: &Bot) -> u64 {
let mut h = std::collections::hash_map::DefaultHasher::new();
for (t, msgs) in &b.threads {
(t, msgs.len()).hash(&mut h);
}
h.finish()
}
fn hash_value(v: &Value) -> u64 {
let mut h = std::collections::hash_map::DefaultHasher::new();
v.to_string().hash(&mut h);
h.finish()
}
/// What names an item in a list: its id, else its name, else (plain values) the value itself.
fn item_key(x: &Value) -> Option<Value> {
match x {
Value::Object(o) => o.get("id").filter(|v| !v.is_null()).or_else(|| o.get("name").filter(|v| v.is_string())).cloned(),
Value::Array(_) | Value::Null => None,
v => Some(v.clone()),
}
}
/// Every item has its own key, and no two share one.
fn keyed(a: &[Value]) -> bool {
let mut seen = std::collections::HashSet::new();
a.iter().all(|x| item_key(x).map(|k| seen.insert(k.to_string())).unwrap_or(false))
}
/// The smallest change from `old` to `new`: lists of named things and maps change item by item,
/// so two computers editing different items of one list don't undo each other.
pub(super) fn patch_of(old: &Value, new: &Value) -> Value {
match (old, new) {
(Value::Object(o), Value::Object(n)) => {
let put: serde_json::Map<String, Value> = n.iter().filter(|(k, v)| o.get(*k) != Some(*v)).map(|(k, v)| (k.clone(), v.clone())).collect();
let del: Vec<&String> = o.keys().filter(|k| !n.contains_key(*k)).collect();
json!({"map": {"put": put, "del": del}})
}
(Value::Array(o), Value::Array(n)) if keyed(o) && keyed(n) => {
let key = |x: &Value| item_key(x).unwrap_or(Value::Null);
let put: Vec<&Value> = n.iter().filter(|x| !o.iter().any(|y| key(y) == key(x) && y == *x)).collect();
let del: Vec<Value> = o.iter().map(key).filter(|k| !n.iter().any(|x| key(x) == *k)).collect();
let common_old: Vec<Value> = o.iter().map(key).filter(|k| n.iter().any(|x| key(x) == *k)).collect();
let common_new: Vec<Value> = n.iter().map(key).filter(|k| o.iter().any(|x| key(x) == *k)).collect();
let mut p = json!({"list": {"put": put, "del": del}});
if common_old != common_new {
p["list"]["order"] = Value::Array(n.iter().map(key).collect());
}
p
}
_ => json!({"value": new}),
}
}
/// Apply a change made by `patch_of` to whatever the value is now.
pub(super) fn apply_patch(cur: &mut Value, p: &Value) {
if let Some(v) = p.get("value") {
*cur = v.clone();
} else if let Some(m) = p.get("map") {
if !cur.is_object() {
*cur = json!({});
}
let o = cur.as_object_mut().expect("object");
for (k, v) in m["put"].as_object().into_iter().flatten() {
o.insert(k.clone(), v.clone());
}
for k in m["del"].as_array().into_iter().flatten().filter_map(Value::as_str) {
o.remove(k);
}
} else if let Some(l) = p.get("list") {
if !cur.is_array() {
*cur = json!([]);
}
let a = cur.as_array_mut().expect("array");
let key = |x: &Value| item_key(x).unwrap_or(Value::Null);
for item in l["put"].as_array().into_iter().flatten() {
match a.iter_mut().find(|x| key(x) == key(item)) {
Some(x) => *x = item.clone(),
None => a.push(item.clone()),
}
}
let del: Vec<Value> = l["del"].as_array().cloned().unwrap_or_default();
a.retain(|x| !del.contains(&key(x)));
if let Some(order) = l["order"].as_array() {
a.sort_by_key(|x| order.iter().position(|k| *k == key(x)).unwrap_or(usize::MAX));
}
}
}
/// The person's edits since `base`, as operations the brain applies one by one.
pub(super) fn diff_ops(base: &Value, cur: &Value) -> Vec<Value> {
let mut ops = vec![];
let (Some(b), Some(c)) = (base.as_object(), cur.as_object()) else { return ops };
for (k, v) in c {
if k == "bots" || LOCAL_KEYS.contains(&k.as_str()) {
continue;
}
if b.get(k) != Some(v) {
let p = patch_of(b.get(k).unwrap_or(&Value::Null), v);
ops.push(if p.get("value").is_some() { json!({"op": "set", "key": k, "value": v}) } else { json!({"op": "patch", "key": k, "patch": p}) });
}
}
let id = |x: &Value| x["id"].as_u64().unwrap_or(0);
let empty = vec![];
let old = base["bots"].as_array().unwrap_or(&empty);
let new = cur["bots"].as_array().unwrap_or(&empty);
for nb in new {
match old.iter().find(|o| id(o) == id(nb)) {
None => ops.push(json!({"op": "bot_add", "bot": nb})),
Some(ob) => {
for (k, v) in nb.as_object().into_iter().flatten() {
if k == "unread" {
if ob[k] == true && *v == false {
ops.push(json!({"op": "bot_read", "id": id(nb)}));
}
continue;
}
if BOT_RUNTIME.contains(&k.as_str()) {
continue;
}
if ob.get(k) != Some(v) {
let p = patch_of(ob.get(k).unwrap_or(&Value::Null), v);
ops.push(if p.get("value").is_some() { json!({"op": "bot_set", "id": id(nb), "key": k, "value": v}) } else { json!({"op": "bot_patch", "id": id(nb), "key": k, "patch": p}) });
}
}
}
}
}
for ob in old {
if !new.iter().any(|n| id(n) == id(ob)) {
ops.push(json!({"op": "bot_del", "id": id(ob)}));
}
}
let order = |a: &Vec<Value>| a.iter().map(id).collect::<Vec<_>>();
let (oo, no) = (order(old), order(new));
let kept: Vec<u64> = oo.iter().copied().filter(|i| no.contains(i)).collect();
let kept_new: Vec<u64> = no.iter().copied().filter(|i| oo.contains(i)).collect();
if kept != kept_new {
ops.push(json!({"op": "bot_order", "ids": no}));
}
ops
}
/// Replay edit operations on settings JSON: a screen keeps its own not-yet-confirmed edits on
/// top of what the brain last sent, so typing isn't undone by the brain's slightly older copy.
pub(super) fn apply_ops(cfg: &mut Value, ops: &[Value]) {
let id = |x: &Value| x["id"].as_u64().unwrap_or(0);
for op in ops {
let target = op["id"].as_u64().unwrap_or(0);
match op["op"].as_str().unwrap_or("") {
"set" => {
if let Some(k) = op["key"].as_str() {
// (Counters never go back, as at the brain: an edit on its way doesn't undo
// numbers the brain gave meanwhile.)
cfg[k] = match (k.starts_with("next_"), cfg[k].as_u64(), op["value"].as_u64()) {
(true, Some(now), Some(new)) => json!(now.max(new)),
_ => op["value"].clone(),
};
}
}
"patch" => {
if let Some(k) = op["key"].as_str() {
apply_patch(&mut cfg[k], &op["patch"]);
}
}
"bot_patch" => {
if let (Some(b), Some(k)) = (cfg["bots"].as_array_mut().and_then(|a| a.iter_mut().find(|b| id(b) == target)), op["key"].as_str()) {
apply_patch(&mut b[k], &op["patch"]);
}
}
"bot_add" => {
if let Some(a) = cfg["bots"].as_array_mut() {
if !a.iter().any(|b| id(b) == id(&op["bot"])) {
a.push(op["bot"].clone());
}
}
}
"bot_del" => {
if let Some(a) = cfg["bots"].as_array_mut() {
a.retain(|b| id(b) != target);
}
}
"bot_set" | "bot_read" => {
if let Some(b) = cfg["bots"].as_array_mut().and_then(|a| a.iter_mut().find(|b| id(b) == target)) {
if op["op"] == "bot_read" {
b["unread"] = json!(false);
} else if let Some(k) = op["key"].as_str() {
b[k] = op["value"].clone();
}
}
}
"bot_order" => {
let ids: Vec<u64> = op["ids"].as_array().into_iter().flatten().filter_map(Value::as_u64).collect();
if let Some(a) = cfg["bots"].as_array_mut() {
a.sort_by_key(|b| ids.iter().position(|i| *i == id(b)).unwrap_or(usize::MAX));
}
}
_ => {}
}
}
}
/// A schedule edited on a screen keeps what the brain knows about runs (when it last ran, when it
/// runs next), so an older copy can't make a routine run twice.
fn keep_run_times(new: &mut Value, old: &Value) {
for r in new.as_array_mut().into_iter().flatten() {
let Some(o) = old.as_array().and_then(|a| a.iter().find(|o| o["id"] == r["id"])) else { continue };
let last = |x: &Value| x["last_run"].as_i64();
if last(o) > last(r) || r["last_run"].is_null() {
r["last_run"] = o["last_run"].clone();
}
let same = ["schedule", "trigger", "paused"].iter().all(|k| r[*k] == o[*k]);
if same {
r["next_run"] = o["next_run"].clone();
}
}
}
// ---------- the brain's side ----------
/// What the brain last sent each screen.
#[derive(Default)]
pub struct Screens {
seen: HashMap<String, Seen>,
/// The settings fingerprint, refreshed now and then while something changes.
pub(super) cfg_hash: u64,
cfg_at: Option<Instant>,
/// The last edit (by number) each screen sent, so it knows which of its edits are in.
acked: HashMap<String, u64>,
}
#[derive(Default, Clone)]
struct Seen {
version: u64,
config: u64,
/// 任務: the fingerprint of the list it was sent last.
tasks: u64,
bots: HashMap<u64, Vec<u64>>,
threads: HashMap<u64, u64>,
at: Option<Instant>,
/// What the screen held before the last answer: when that answer was lost on the way (the
/// line dropped), the next pull starts from here instead of sending every chat again.
prev: Option<Box<Seen>>,
}
// ---------- the screen's side ----------
pub enum Incoming {
Pull(Value),
Offline(String),
/// A file from the brain arrived (its local copy's path).
File(String),
/// A message the brain refused (not the line: that only waits): its words go back
/// into that bot's input (when the person hasn't typed something else there since).
Unsent { bot: u64, text: String, atts: Vec<crate::attach::Attachment> },
/// A message the brain took: shown as 已送出 until its chat, on the way, has it.
Sent { bot: u64, text: String },
}
/// What waits in this screen's queue for the brain: a message, or an edit of the settings.
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub(super) enum Job {
/// `typed`: the person's own words from the input (they go back there if the brain refuses
/// them); a button's command (「/goal clear」) is not.
Send {
bot: u64,
id: String,
text: String,
#[serde(default)]
atts: Vec<crate::attach::Attachment>,
#[serde(default)]
memories: Option<Vec<String>>,
#[serde(default)]
typed: bool,
/// Where the brain keeps the files already sent up (the first of `atts`, in order): a
/// try again sends only the rest — a big file over a slow line was sent whole every time.
#[serde(default)]
uploaded: Vec<String>,
},
Edit { seq: u64, ops: Vec<Value> },
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub(super) struct Queued {
pub(super) job: Job,
/// When it was made (ms).
#[serde(default)]
pub(super) at: i64,
/// When the last try left (ms; 0: not tried yet): the brain's chat is looked at only from an
/// answer that came after it.
#[serde(default)]
tried: i64,
/// When the first try that may have arrived left (ms; 0: none — never tried, or looked for
/// in the brain's chat and not there). A try may arrive although its answer doesn't; the brain
/// knows the id for 10 minutes from then, so past that it is looked for before it goes again
/// — and it can't be taken back (取消) meanwhile: it may be at the brain already.
#[serde(default)]
pub(super) first: i64,
/// A try is on its way now (it can't be taken back meanwhile).
#[serde(skip)]
pub(super) trying: bool,
/// Waiting for this window to look in the brain's chat (see mirror_check_queue).
#[serde(skip)]
check: bool,
}
impl Queued {
pub(super) fn key(&self) -> String {
match &self.job {
Job::Send { id, .. } => format!("send:{id}"),
Job::Edit { seq, .. } => format!("edit:{seq}"),
}
}
}
/// The queue, kept on disk beside the copy of the brain (brain-queue.json, keys sealed) so
/// closing AnyBot doesn't lose it: which brain it is for, this screen's name there, the jobs.
#[derive(Default, serde::Serialize, serde::Deserialize)]
pub(super) struct Outq {
brain: String,
client: String,
pub(super) items: Vec<Queued>,
/// Where it is kept (empty: nowhere — not showing a brain, or one left since).
#[serde(skip)]
path: PathBuf,
}
impl Outq {
fn load(path: &std::path::Path) -> Outq {
let raw = std::fs::read_to_string(path).ok();
let read = raw.as_deref().and_then(|s| serde_json::from_str::<Value>(s).ok()).and_then(|mut v| {
crate::vault_store::walk_secrets(&mut v, false);
// (A key that can't be opened now — the keychain locked or refused — would go to the
// brain as its sealed text, in place of the brain's real key.)
fn sealed(v: &Value) -> bool {
match v {
Value::String(s) => s.starts_with(crate::vault_store::SEALED),
Value::Array(a) => a.iter().any(sealed),
Value::Object(o) => o.values().any(sealed),
_ => false,
}
}
if sealed(&v) {
return None;
}
serde_json::from_value::<Outq>(v).ok()
});
// (One this AnyBot can't read — written by another version, or its keys locked away — is
// kept aside, not written over with an empty queue.)
if raw.is_some() && read.is_none() {
let _ = std::fs::rename(path, path.with_extension(format!("unread-{}.json", crate::model::now_ms())));
}
let mut q = read.unwrap_or_default();
q.path = path.to_path_buf();
q
}
/// Written at every change (small: a few messages and edits), under its lock — the window
/// and the sending thread never write over each other's newer one.
fn save(&self) {
if self.path.as_os_str().is_empty() {
return;
}
if self.items.is_empty() {
let _ = std::fs::remove_file(&self.path);
return;
}
if let Ok(mut v) = serde_json::to_value(self) {
crate::vault_store::walk_secrets(&mut v, true);
let _ = crate::httpd::write_private(&self.path, v.to_string().as_bytes());
}
}
fn find(&mut self, key: &str) -> Option<&mut Queued> {
self.items.iter_mut().find(|i| i.key() == key)
}
}
/// How long the brain remembers a message's id (remote.rs DELIVERY_TTL, a day), less a margin:
/// a message whose first try that may have arrived is older than this isn't simply sent again —
/// if that try arrived and only its answer was lost, the brain would no longer know it and do it
/// twice.
const ASK_BEFORE_AGAIN_MS: i64 = 23 * 3_600_000;
/// Tries in a row that failed on the line while the brain answered all along: then it isn't the
/// line — the message (or edit) is given up, said so, and the queue goes on.
const GIVE_UP_AFTER: u32 = 20;
/// Its words are in the chat, from `since` on (less a margin for the two clocks): the message
/// arrived.
fn arrived_in(msgs: &[Message], text: &str, atts: &[crate::attach::Attachment], since: i64) -> bool {
let from = since - 120_000;
msgs.iter()
.rev()
.take_while(|m| m.at == 0 || m.at >= from)
.any(|m| m.role == Role::User && m.text.trim() == text.trim() && (!text.trim().is_empty() || m.attachments.iter().map(|a| &a.name).eq(atts.iter().map(|a| &a.name))))
}
/// One try of a job: the files not yet up first (each kept in `uploaded` once there), then the
/// words; or the edit.
fn try_job(s: &crate::remote::Settings, client: &str, job: &mut Job) -> Result<Value, (bool, String)> {
match job {
Job::Edit { seq, ops } => remote::sync_try(s, "/edit", &[], json!({"ops": ops, "client": client, "seq": seq}).to_string().as_bytes(), 20),
Job::Send { bot, id, text, atts, memories, uploaded, .. } => {
// (One file that can't go keeps the whole message here — words without their file
// would be a different message.)
for a in atts.iter().skip(uploaded.len()) {
let bytes = std::fs::read(&a.path).map_err(|e| (false, format!("讀不到「{}」({e})", a.name)))?;
// (Time for a big file on a slow line: about 30 KB/s.)
let secs = 120 + bytes.len() as u64 / 30_000;
let v = remote::sync_try(s, &format!("/upload/{bot}"), &[("name", a.name.clone())], &bytes, secs).map_err(|(line, e)| (line, format!("「{}」沒有傳到大腦:{e}", a.name)))?;
uploaded.push(v["path"].as_str().map(String::from).ok_or((false, "大腦沒有收下檔案".to_string()))?);
}
let paths = uploaded.clone();
let mut body = json!({"bot": bot, "action": "send", "id": id, "text": text, "attachments": paths});
if let Some(m) = memories {
body["memories"] = json!(m);
}
remote::sync_try(s, "/act", &[], body.to_string().as_bytes(), 20)
}
}
}
/// Take one job of the queue to the brain: tried while the brain is in reach (`reach`), waited
/// on (`pause`, told how many tries in a row the line failed) while it isn't — as long as it
/// takes, while this window shows that brain (`stay`). Gives the job back with the brain's
/// answer, or its refusal (or, after GIVE_UP_AFTER line failures in a row while the brain
/// answered, the last of them); None when it was taken back (取消), found already there, or this
/// window left the brain (the job stays on disk).
fn deliver(q: &Mutex<Outq>, key: &str, now_ms: &dyn Fn() -> i64, go: &mut dyn FnMut(&mut Job) -> Result<Value, (bool, String)>, reach: &dyn Fn() -> bool, stay: &dyn Fn() -> bool, pause: &dyn Fn(u32)) -> Option<(Job, Result<Value, (bool, String)>)> {
let mut fails = 0;
loop {
if !stay() {
return None;
}
let mut job = {
let mut g = q.lock().unwrap_or_else(|e| e.into_inner());
let now = now_ms();
let it = g.find(key)?;
let ask_first = matches!(it.job, Job::Send { .. }) && it.first > 0 && now - it.first > ASK_BEFORE_AGAIN_MS;
if ask_first {
it.check = true;
}
let near = reach();
if it.check || !near {
drop(g);
// (Out of reach in between: the failures before were the line's.)
if !near {
fails = 0;
}
pause(0);
continue;
}
it.trying = true;
it.tried = now;
if it.first == 0 {
it.first = now;
}
let job = it.job.clone();
g.save();
job
};
let r = go(&mut job);
let mut g = q.lock().unwrap_or_else(|e| e.into_inner());
if let Some(it) = g.find(key) {
it.trying = false;
// (The files that went up stay up.)
it.job = job.clone();
}
match r {
Err((true, _)) if fails + 1 < GIVE_UP_AFTER => {
g.save();
drop(g);
fails += 1;
pause(fails);
}
done => {
g.items.retain(|i| i.key() != key);
g.save();
return Some((job, done));
}
}
}
}
/// Each message and chat action from this screen gets a name of its own (this screen's, then a
/// count), sent again under the same name while the line is down: the brain does it once.
fn act_id(client: &str) -> String {
static N: AtomicU64 = AtomicU64::new(0);
// (With this run's own mark: the screen keeps its name at the brain across restarts, and a
// count from 1 again matched the last run's — the brain took the new message for a repeat.)
static RUN: std::sync::OnceLock<String> = std::sync::OnceLock::new();
let run = RUN.get_or_init(|| crate::httpd::random_hex(4));
format!("{client}-{run}-{}", N.fetch_add(1, Ordering::Relaxed) + 1)
}
/// What a screen sends to the brain, one at a time and in order.
enum Out {
/// A job of the queue (by its key): a message or an edit, sent however long it takes.
Queued(String),
Act(Value),
Move { ops: Vec<Value>, n: usize, skills: Vec<Skill> },
/// 技能 on a screen: done at the brain (see [`App::mirror_skill`]); the answer goes to `note`.
Skill { body: Value, note: SkillNote, busy: Arc<AtomicBool> },
/// 連接器 › 重新連線 on a screen: the servers run at the brain.
McpReconnect(String),
/// A connector renamed on a screen (old, new): the brain renames its own (see commit_mcp_name).
McpRename(String, String),
}
/// Where a skill request's answer is shown: (worked, words).
pub(super) type SkillNote = Arc<Mutex<Option<(bool, String)>>>;
/// What the brain is asked for a skill request: a folder or `.md` file named by its path on this
/// computer (`{"local": …}`) goes up whole, read here — the brain can't see this disk.
fn skill_request(body: Value) -> Result<Value, String> {
match body["local"].as_str() {
Some(p) => Ok(json!({"package": crate::skills::package_from_path(&crate::tools::expand_home(p))?})),
None => Ok(body),
}
}
/// The bots whose turn ended well since the last update (`seen` keeps when each bot's last turn
/// ended). Only an end heard while connected counts, and only a recent one: connecting, or coming
/// back after a while, never reads old answers out.
fn just_finished<'a>(seen: &mut HashMap<u64, i64>, turns: impl IntoIterator<Item = (u64, Option<&'a TurnSettlement>)>, now_ms: i64) -> Vec<u64> {
let mut out = vec![];
for (id, t) in turns {
let Some(t) = t else { continue };
let before = seen.insert(id, t.settled_at_ms);
if before.is_some_and(|s| s < t.settled_at_ms) && t.outcome == TurnOutcome::Success && now_ms - t.settled_at_ms < 120_000 {
out.push(id);
}
}
out
}
/// An edit sent to the brain and not yet confirmed: (its number, the operations).
type Pending = (u64, Vec<Value>);
#[derive(Default)]
pub struct Mirror {
/// This window shows a brain (instead of its own bots).
pub on: bool,
/// Heard from the brain lately.
pub online: bool,
/// The brain's settings as last received (edits are what differs from this).
pub(super) base: Value,
pub status: Arc<Mutex<String>>,
rx: Option<Receiver<Incoming>>,
tx: Option<Sender<Incoming>>,
gen: Arc<AtomicU64>,
version: Arc<AtomicU64>,
client: String,
/// This computer's own data, kept aside while it shows the brain.
local: Option<State>,
started: bool,
/// A request to the brain failed (shown above the message box).
pub(super) error: Arc<Mutex<String>>,
/// The person chose a brain in 設定 (applied on the next frame).
pub(super) want: Option<(String, String)>,
pub(super) leave: bool,
pub(super) moving: Arc<AtomicBool>,
/// Just signed in: copy this computer's bots to the brain once it answers.
pub(super) move_after_join: bool,
pub(super) move_note: Arc<Mutex<String>>,
/// Requests to the brain, sent in order by one worker.
outbox: Option<Sender<Out>>,
/// Edits sent but not yet confirmed (by number).
pending: Arc<Mutex<Vec<Pending>>>,
seq: u64,
/// Something didn't reach the brain: ask for everything again.
resync: Arc<AtomicBool>,
/// Why the brain can't be reached (shown above the chat), and since when.
pub(super) reason: String,
down_since: Option<Instant>,
/// Files from the brain being fetched (by local path).
fetching: std::collections::HashSet<String>,
/// 加一台電腦: the line to run on the new computer (or why there is none), and when it was made.
pub(super) pair: Arc<Mutex<(String, bool, Option<Instant>)>>,
/// The bots' own computer on the brain: {label, running, available, busy}.
pub(super) box_state: Value,
/// Each bot's computers on the brain, by bot id: {names: [{name, kind}], current, missing}.
pub(super) computers: HashMap<u64, Value>,
/// The connectors at the brain, as [`App::mcp_state`] gives them.
pub(super) mcp_state: Value,
/// 任務: the list the brain worked out (None until it sends one).
pub(super) tasks: Option<Vec<crate::tasks::Task>>,
/// When each bot's last turn ended, as last heard (a newer one ending well is read aloud).
settled: HashMap<u64, i64>,
/// The brain's key for each card waiting here (by bot id): an answer from this screen names
/// it, so the brain applies it only to that card.
pub(super) keys: HashMap<u64, String>,
/// The last answer from the brain: when (ms), how many bytes came over the lasting
/// connection for it, and how long it took (ms) — the 大腦 section says the line's speed.
pub(super) last_sync: Arc<Mutex<Option<(i64, u64, u64)>>>,
/// The copy of the brain kept on disk (brain-copy.json): when it was last written, whether
/// newer news is waiting, and whether a write is running now (it runs on its own thread).
copy_at: Option<Instant>,
copy_dirty: bool,
copy_writing: Arc<AtomicBool>,
/// The brain's version of the last answer taken in here (what the copy on disk is, when
/// written with it: the next start asks only for what changed since).
applied: u64,
/// Messages and edits waiting for the brain, in order (kept on disk too).
pub(super) queue: Arc<Mutex<Outq>>,
/// The last ask for news got an answer (the queue goes while it did, waits while it didn't).
reach: Arc<AtomicBool>,
/// The brain's own settings came since this window started showing it (until then it shows
/// the copy on disk, and nothing done to what runs at the brain — stop, regenerate — goes).
synced: bool,
/// When what is shown came from the brain (ms): the last answer taken in, or the copy's.
pub(super) synced_ms: i64,
/// Where the copy and the queue are kept (empty: beside state.json; a test's own folder).
pub(super) dir: PathBuf,
/// The brain's counts of bots and routines as last known (its settings, or the copy's).
counts: Option<(u64, u64)>,
/// Chat actions' own lane to the brain (body, when pressed in ms): see mirror_out.
acts: Option<Sender<(Value, i64)>>,
/// Cards answered here, by the brain's key, and when: an update the brain sent before it
/// took the answer in still has the card — it isn't shown (and chimed) a second time.
pub(super) answered: HashMap<String, Instant>,
/// The window shows the brain: from its copy on disk at once, or (no copy: the first time)
/// once the brain's first answer is in (its settings taken, or found unreadable and said so).
entered: bool,
/// When this screen started knocking (the door's way back shows after a while).
door_since: Option<Instant>,
}
/// What the copy on disk is: which brain, this screen's name there, and the brain's version it
/// holds. Beside brain-copy.json, written after it.
#[derive(serde::Serialize, serde::Deserialize, Default)]
struct CopyAt {
brain: String,
client: String,
version: u64,
/// When the brain's answer it holds came (ms; 0 from before this was kept).
#[serde(default)]
at: i64,
}
fn copy_at_path(dir: &std::path::Path) -> PathBuf {
dir.join("brain-copy.at.json")
}
fn read_copy_at(dir: &std::path::Path) -> CopyAt {
std::fs::read_to_string(copy_at_path(dir)).ok().and_then(|s| serde_json::from_str(&s).ok()).unwrap_or_default()
}
/// Each brain's queue its own file: going to another brain and back keeps what waited for this one.
fn queue_path(dir: &std::path::Path, brain: &str) -> PathBuf {
dir.join(format!("brain-queue-{}.json", &crate::httpd::sha256_hex(brain)[..12]))
}
/// The copy on disk is written at most this often (it is only for opening while the brain is
/// out of reach): every sync wrote all chats — megabytes — on the window's thread, ten times a
/// second while a bot answered.
const COPY_EVERY: std::time::Duration = std::time::Duration::from_secs(5);
/// The last sync in words: 「上次同步 10:31:05(1.2 MB,11 秒,約 110 KB/s)」.
pub(super) fn sync_words(at_ms: i64, bytes: u64, ms: u64) -> String {
let when = chrono::DateTime::from_timestamp_millis(at_ms).map(|t| t.with_timezone(&chrono::Local).format("%H:%M:%S").to_string()).unwrap_or_default();
if bytes < 100_000 || ms == 0 {
return format!("上次同步 {when}");
}
let size = if bytes >= 1_000_000 { format!("{:.1} MB", bytes as f64 / 1e6) } else { format!("{} KB", bytes / 1000) };
format!("上次同步 {when}({size},{} 秒,約 {} KB/s)", ms.div_ceil(1000), bytes * 1000 / ms / 1000)
}
/// What a computer is, in a word a screen can show next to its name.
pub(super) fn computer_kind(t: &crate::tools::Target, r: &crate::tools::Roles) -> &'static str {
use crate::tools::Place;
if t.name == r.own {
"own"
} else if r.person.as_deref() == Some(t.name.as_str()) {
"person"
} else {
match t.place {
Place::Local { .. } if r.server => "server",
Place::Local { .. } => "this",
Place::Device { .. } => "device",
_ => "ssh",
}
}
}
/// Where a screen keeps its copy of a file the brain has.
fn local_copy(brain_path: &str, name: &str) -> PathBuf {
let h = crate::httpd::sha256_hex(brain_path);
let name: String = name.chars().filter(|c| !matches!(c, '/' | '\\' | '\0' | ':')).take(80).collect();
State::path().with_file_name("brain-files").join(format!("{}-{name}", &h[..16]))
}
fn cache_path(dir: &std::path::Path) -> PathBuf {
dir.join("brain-copy.json")
}
impl App {
/// The brain: answer the screens' requests (on the app's thread, where the state is).
pub(super) fn brain_serve(&mut self, ctx: &egui::Context) {
let reqs = remote::hub().take_sync();
if reqs.is_empty() {
return;
}
for r in reqs {
let v = match r.kind {
// 手機 (not a screen): what the desktop does, done the same way.
SyncKind::Phone { action, body, role } => {
if self.mir.on {
json!({"error": "這台 AnyBot 連著別的大腦,請在大腦上操作"})
} else {
let mut out = self.phone_act(ctx, &action, &body, &role);
if out.get("error").is_none() {
self.remote_publish();
if let Some(o) = out.as_object_mut() {
o.entry("version").or_insert_with(|| json!(remote::hub().version()));
}
}
out
}
}
SyncKind::Pull { client, since, config, retry } => self.brain_pull(&client, since, config, retry),
SyncKind::Models(name) => {
let kind = serde_json::from_value::<crate::providers::ProviderKind>(json!(name)).ok();
match kind {
Some(kind) => {
let ps = self.state.provider(kind);
let (base, key) = (crate::providers::resolve_base(kind, &ps.base_url), crate::providers::resolve_key_for(kind, &ps.api_key, &ps.base_url));
let reply = r.reply;
// The list can take a while; the app doesn't wait for it.
std::thread::spawn(move || {
let _ = reply.send(match crate::providers::list_models(kind, &base, &key) {
Ok(models) => json!({"models": models}),
Err(e) => json!({"error": e}),
});
});
continue;
}
None => json!({"error": "大腦不認得這個模型服務(兩邊 AnyBot 版本不同?)"}),
}
}
SyncKind::Edit(body) => {
if self.mir.on {
json!({"error": "這台 AnyBot 本身連著別的大腦"})
} else {
self.brain_edit(&body)
}
}
};
let _ = r.reply.send(v);
}
}
/// Keep the settings fingerprint fresh (at most once a second) so screens hear of edits.
pub(super) fn brain_watch(&mut self) {
if self.mir.on || !self.dirty || self.scr.cfg_at.map(|t| t.elapsed().as_millis() < 1000).unwrap_or(false) {
return;
}
self.scr.cfg_at = Some(Instant::now());
let mut c = config_json(&mut self.state);
redact(&mut c);
self.scr.cfg_hash = hash_value(&c);
}
fn brain_pull(&mut self, client: &str, since: u64, config: bool, retry: bool) -> Value {
self.brain_pull_at(remote::hub().version(), client, since, config, retry)
}
/// brain_pull at the brain's `version` (what the hub has published). `retry`: the screen's
/// last pull failed — the answer may have been lost even when it carried the same version
/// (a long poll that ran out answers with what it has), so it counts from the answer before.
fn brain_pull_at(&mut self, version: u64, client: &str, since: u64, config: bool, retry: bool) -> Value {
if self.mir.on {
return json!({"error": "這台 AnyBot 本身連著別的大腦"});
}
// Forget screens not heard from in a day.
self.scr.seen.retain(|_, s| s.at.map(|t| t.elapsed().as_secs() < 86_400).unwrap_or(false));
let seen = self.scr.seen.entry(client.to_string()).or_default();
// A screen that missed the last answer starts again from the one before (what it still
// holds); one that is new, or missed more, gets everything again.
if since == 0 {
*seen = Seen::default();
} else {
// (From an answer older than what the screen holds is safe: it only sends more.)
let prev_fits = seen.prev.as_ref().is_some_and(|p| p.version == since || (retry && p.version <= since));
if prev_fits && (seen.version != since || retry) {
if let Some(p) = seen.prev.take() {
*seen = *p;
}
} else if seen.version != since {
*seen = Seen::default();
}
}
seen.prev = None;
seen.prev = Some(Box::new(seen.clone()));
// A screen that just started from its copy: the settings come along regardless.
if config {
seen.config = 0;
}
seen.at = Some(Instant::now());
seen.version = version;
let acked = self.scr.acked.get(client).copied().unwrap_or(0);
let mut out = json!({"version": version, "brain": self.state.remote.host_name, "edit_seq": acked});
let mut c = config_json(&mut self.state);
redact(&mut c);
let ch = hash_value(&c);
if seen.config != ch {
seen.config = ch;
out["config"] = c;
}
let mut bots = vec![];
let mut threads = vec![];
for b in &self.state.bots {
let sigs: Vec<u64> = b.messages.iter().map(msg_sig).collect();
let old = seen.bots.get(&b.id);
let from = match old {
Some(o) => o.iter().zip(sigs.iter()).position(|(a, b)| a != b).unwrap_or(o.len().min(sigs.len())),
None => 0,
};
if old.map(|o| o.len() != sigs.len() || from < sigs.len()).unwrap_or(true) {
bots.push(json!({"id": b.id, "from": from, "messages": &b.messages[from..]}));
}
seen.bots.insert(b.id, sigs);
let ts = threads_sig(b);
if seen.threads.get(&b.id) != Some(&ts) {
seen.threads.insert(b.id, ts);
threads.push(json!({"id": b.id, "threads": b.threads}));
}
}
seen.bots.retain(|id, _| self.state.bots.iter().any(|b| b.id == *id));
// 任務: the brain's list, when it changed since the screen was sent it.
if self.tk.sig != 0 && seen.tasks != self.tk.sig {
seen.tasks = self.tk.sig;
out["tasks"] = serde_json::to_value(&self.tk.list).unwrap_or_default();
}
out["bots"] = Value::Array(bots);
out["threads"] = Value::Array(threads);
out["live"] = self.streams.iter().map(|(id, l)| (id.to_string(), json!({"status": l.status, "paused": l.paused}))).collect::<serde_json::Map<_, _>>().into();
out["approvals"] = self
.approvals
.iter()
.map(|(id, a)| {
let kind = match a.kind {
ApprovalKind::Action => "action",
ApprovalKind::EnableTools => "tools",
ApprovalKind::EnableThisComputer => "local",
ApprovalKind::Handoff => "handoff",
ApprovalKind::Question => "question",
};
// key: this card's (on_new_approval); the screen sends it back with its answer.
json!({"bot": id, "call_id": a.call_id, "tool": a.tool, "reason": a.reason, "grant": a.grant, "kind": kind, "key": self.ask_keys.get(id).cloned().unwrap_or_default()})
})
.collect();
// The connectors run here too: whether each is connected, or why not.
out["mcp"] = self.mcp_state_for_screen();
// ChatGPT 方案: whether the brain's account can be used (never its tokens).
out["chatgpt"] = crate::chatgpt::view();
// The bots' computer lives here; a screen shows its state, not its own computer's.
let run = crate::cloudbox::run_state();
out["box"] = json!({"label": run.label(), "running": run.is_running(), "available": crate::cloudbox::available(), "busy": crate::cloudbox::is_busy(), "screens": self.tiles_json()});
// Which computers each bot has (only the brain knows the account's other computers).
out["computers"] = self
.state
.bots
.iter()
.map(|b| {
let t = self.targets_for(b);
let r = self.roles_for(b, &t);
let (current, missing) = Self::chosen_computer(b, &t, &r);
let names: Vec<Value> = t.iter().map(|x| json!({"name": x.name, "kind": computer_kind(x, &r)})).collect();
// (Every computer there is, for the editor's 可以用的電腦.)
let all: Vec<Value> = self.all_targets_for(b).iter().map(|x| json!({"name": x.name, "kind": computer_kind(x, &r)})).collect();
(b.id.to_string(), json!({"names": names, "all": all, "current": current, "missing": missing}))
})
.collect::<serde_json::Map<_, _>>()
.into();
out
}
/// A screen's edits.
pub(super) fn brain_edit(&mut self, body: &Value) -> Value {
// The same edit again (its answer was lost on the way and the screen sent it once more):
// done once — a 「新增 Bot」 done twice was two bots.
if let (Some(client), Some(seq)) = (body["client"].as_str(), body["seq"].as_u64()) {
if self.scr.acked.get(client).is_some_and(|&done| seq <= done) {
return json!({"ok": true, "applied": 0, "again": true});
}
}
let mut applied = 0;
let total = body["ops"].as_array().map(|a| a.len()).unwrap_or(0);
for op in body["ops"].as_array().into_iter().flatten() {
let ok = match op["op"].as_str().unwrap_or("") {
"set" => self.brain_set_top(op["key"].as_str().unwrap_or(""), op["value"].clone()),
"bot_add" => {
let mut v = op["bot"].clone();
unredact(&mut v, &Value::Null);
match serde_json::from_value::<Bot>(v.take()) {
Ok(mut b) => {
if b.id == 0 || self.state.bot(b.id).is_some() {
b.id = self.state.next_id.max(1);
}
self.state.next_id = self.state.next_id.max(b.id + 1);
self.state.bots.push(b);
self.state.fix_primary();
true
}
Err(_) => false,
}
}
"bot_del" => {
let id = op["id"].as_u64().unwrap_or(0);
if self.state.bot(id).is_none() {
false
} else {
self.stop(id);
self.bot_gone(id);
self.state.bots.retain(|b| b.id != id);
self.state.fix_primary();
true
}
}
"merge" => self.brain_merge_top(op["key"].as_str().unwrap_or(""), &op["value"]),
"patch" => {
let key = op["key"].as_str().unwrap_or("");
let mut v = self.top_value(key);
apply_patch(&mut v, &op["patch"]);
self.brain_set_top(key, v)
}
"bot_patch" => {
let (id, key) = (op["id"].as_u64().unwrap_or(0), op["key"].as_str().unwrap_or(""));
match self.state.bot(id).map(|b| serde_json::to_value(b).ok().map(|v| v[key].clone()).unwrap_or(Value::Null)) {
Some(mut v) => {
let old = v.clone();
apply_patch(&mut v, &op["patch"]);
unredact(&mut v, &old);
self.brain_set_bot(id, key, v)
}
None => false,
}
}
"bot_set" => self.brain_set_bot(op["id"].as_u64().unwrap_or(0), op["key"].as_str().unwrap_or(""), op["value"].clone()),
"bot_read" => match self.state.bot_mut(op["id"].as_u64().unwrap_or(0)) {
Some(b) => {
b.unread = false;
true
}
None => false,
},
"bot_order" => {
let ids: Vec<u64> = op["ids"].as_array().into_iter().flatten().filter_map(Value::as_u64).collect();
self.state.bots.sort_by_key(|b| ids.iter().position(|i| *i == b.id).unwrap_or(usize::MAX));
true
}
_ => false,
};
if ok {
applied += 1;
}
}
if let (Some(client), Some(seq)) = (body["client"].as_str(), body["seq"].as_u64()) {
self.scr.acked.insert(client.to_string(), seq);
// Something was refused: send that screen the settings again, so it drops it.
if applied < total {
if let Some(s) = self.scr.seen.get_mut(client) {
s.config = 0;
}
}
}
if applied > 0 {
self.mark();
// Screens hear of it at once.
self.scr.cfg_at = None;
self.brain_watch();
}
json!({"ok": true, "applied": applied})
}
/// One top-level setting as JSON (with the brain's real keys).
fn top_value(&mut self, key: &str) -> Value {
let bots = std::mem::take(&mut self.state.bots);
let v = serde_json::to_value(&self.state).map(|t| t[key].clone()).unwrap_or(Value::Null);
self.state.bots = bots;
v
}
fn brain_set_top(&mut self, key: &str, mut value: Value) -> bool {
if key.is_empty() || key == "bots" || LOCAL_KEYS.contains(&key) {
return false;
}
let bots = std::mem::take(&mut self.state.bots);
let mut top = serde_json::to_value(&self.state).unwrap_or(Value::Null);
unredact(&mut value, &top[key]);
// Counters never go back (a screen may be behind).
if key.starts_with("next_") {
value = json!(value.as_u64().unwrap_or(0).max(top[key].as_u64().unwrap_or(0)));
}
top[key] = value;
let ok = match serde_json::from_value::<State>(top) {
Ok(mut st) => {
st.remote = std::mem::take(&mut self.state.remote);
self.state = st;
true
}
Err(_) => false,
};
self.state.bots = bots;
ok
}
/// 搬到大腦: add what the brain doesn't have yet (keys it lacks, skills and connectors by name).
fn brain_merge_top(&mut self, key: &str, value: &Value) -> bool {
let bots = std::mem::take(&mut self.state.bots);
let top = serde_json::to_value(&self.state).unwrap_or(Value::Null);
self.state.bots = bots;
let mut cur = top[key].clone();
match (key, &mut cur) {
("providers", Value::Object(o)) => {
for (k, v) in value.as_object().into_iter().flatten() {
let missing = o.get(k).map(|x| x["api_key"].as_str().unwrap_or("").is_empty()).unwrap_or(true);
if missing && v["api_key"].as_str().map(|s| !s.is_empty() && s != REDACTED).unwrap_or(false) {
o.insert(k.clone(), v.clone());
}
}
}
("skills" | "mcp_servers", Value::Array(a)) => {
for v in value.as_array().into_iter().flatten() {
if !a.iter().any(|x| x["name"] == v["name"]) {
a.push(v.clone());
}
}
}
_ => return false,
}
self.brain_set_top(key, cur)
}
fn brain_set_bot(&mut self, id: u64, key: &str, value: Value) -> bool {
if BOT_RUNTIME.contains(&key) {
return false;
}
let Some(i) = self.state.bots.iter().position(|b| b.id == id) else { return false };
let b = &mut self.state.bots[i];
let msgs = std::mem::take(&mut b.messages);
let threads = std::mem::take(&mut b.threads);
let mut v = serde_json::to_value(&*b).unwrap_or(Value::Null);
let mut value = value;
unredact(&mut value, &v[key]);
if key == "routines" {
keep_run_times(&mut value, &v["routines"]);
// (The brain counts on past every number a screen gave a routine, whatever count
// the screen sends.)
for n in value.as_array().into_iter().flatten().filter_map(|r| r["id"].as_u64()) {
self.state.next_routine_id = self.state.next_routine_id.max(n + 1);
}
}
v[key] = value;
let ok = match serde_json::from_value::<Bot>(v) {
Ok(nb) => {
*b = nb;
true
}
Err(_) => false,
};
let b = &mut self.state.bots[i];
b.messages = msgs;
b.threads = threads;
ok
}
// ---------- the screen ----------
/// Once at start: a brain was chosen earlier, so show its copy.
pub(super) fn mirror_boot(&mut self) {
if self.mir.started || self.demo {
return;
}
self.mir.started = true;
// The same name at the brain as last time (it remembers what this screen holds for a
// day), so a start asks only for what changed since the copy on disk — and the edits
// still in the queue go under the name the brain may already have done them for.
let dir = self.mirror_dir();
let (at, q) = (read_copy_at(&dir), Outq::load(&queue_path(&dir, &self.state.remote.brain_id)));
let brain = &self.state.remote.brain_id;
self.mir.client = [(at.brain, at.client), (q.brain, q.client)].into_iter().find(|(b, c)| b == brain && !c.is_empty()).map(|(_, c)| c).unwrap_or_else(|| crate::httpd::random_hex(8));
// Edits are numbered from the clock: always past the last run's (the brain does each
// number once, see brain_edit).
self.mir.seq = crate::model::now_ms().max(0) as u64;
if !self.state.remote.brain_id.is_empty() && !self.state.remote.host_token.is_empty() {
self.mirror_enter();
}
}
/// Start showing the brain: this computer's own bots are kept aside, untouched.
fn mirror_enter(&mut self) {
self.mirror_open();
// The bots' computer is the brain's now; this one's box isn't kept awake.
crate::cloudbox::set_brain(false);
self.mirror_worker();
self.mirror_outbox();
crate::tunnel::hello(&self.state.remote.brain_id, self.state.remote.device_link);
}
/// Where the copy of the brain and the queue are kept.
fn mirror_dir(&self) -> PathBuf {
if !self.mir.dir.as_os_str().is_empty() {
return self.mir.dir.clone();
}
State::path().parent().map(std::path::Path::to_path_buf).unwrap_or_default()
}
/// The brain as this computer last knew it, at once — no network: its copy on disk, with
/// what waits in the queue on top. 有副本就直接進去: the window shows it and works (messages
/// and edits wait in the queue); only a first time, with no copy, waits at the door. The
/// brain's answers then come in as usual (only what changed since the copy).
fn mirror_open(&mut self) {
let ids: Vec<u64> = self.streams.keys().copied().collect();
for id in ids {
self.stop(id);
}
self.approvals.clear();
let local = self.state.clone();
let dir = self.mirror_dir();
let brain = self.state.remote.brain_id.clone();
let at = read_copy_at(&dir);
let mut resume = 0;
// Only this brain's copy, and only one that says so (another brain's bots aren't this
// one's; a copy without its marker was cut short while written).
let copy = (at.brain == brain && !brain.is_empty()).then(|| std::fs::read_to_string(cache_path(&dir)).ok().and_then(|s| serde_json::from_str::<State>(&s).ok())).flatten().filter(|s| !s.bots.is_empty());
let have_copy = copy.is_some();
if let Some(copy) = copy {
self.state = copy;
self.keep_local_fields(&local);
if at.client == self.mir.client {
resume = at.version;
}
}
// The queue: this brain's (each brain has its own file; what waits for another stays
// there, for when this window shows that one again).
let mut q = if brain.is_empty() { Outq::default() } else { Outq::load(&queue_path(&dir, &brain)) };
if q.brain != brain {
q.items.clear();
}
(q.brain, q.client) = (brain, self.mir.client.clone());
let edits: Vec<Pending> = q.items.iter().filter_map(|i| if let Job::Edit { seq, ops } = &i.job { Some((*seq, ops.clone())) } else { None }).collect();
// (The window's earlier queue, if it showed a brain before: its thread stops, and it no
// longer writes to the file.)
std::mem::take(&mut self.mir.queue.lock().unwrap_or_else(|e| e.into_inner()).path);
self.mir.queue = Arc::new(Mutex::new(q));
self.mir.base = Value::Null;
self.mir.counts = have_copy.then_some((self.state.next_id, self.state.next_routine_id));
if have_copy {
// Edits made before AnyBot closed show although the copy may be from before them
// (doing one again is doing nothing: each sets what it sets).
if !edits.is_empty() {
let mut cfg = config_json(&mut self.state);
apply_ops(&mut cfg, &edits.iter().flat_map(|(_, o)| o.clone()).collect::<Vec<_>>());
let _ = self.mirror_take_config(cfg);
}
// What the brain had, as last known: edits made from here on are what differs.
self.mir.base = config_json(&mut self.state);
}
*self.mir.pending.lock().unwrap() = edits;
self.mir.local = Some(local);
self.mir.on = true;
self.mir.online = false;
self.mir.reach.store(false, Ordering::SeqCst);
self.mir.version.store(resume, Ordering::SeqCst);
self.mir.applied = resume;
self.mir.entered = have_copy;
self.mir.synced = false;
// (A copy from before its marker said when: when the file was written.)
let written = || std::fs::metadata(cache_path(&dir)).and_then(|m| m.modified()).ok().and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map_or(0, |d| d.as_millis() as i64);
self.mir.synced_ms = if !have_copy { 0 } else if at.at > 0 { at.at } else { written() };
self.mir.door_since = Some(Instant::now());
self.mir.reason.clear();
self.mir.down_since = None;
*self.mir.status.lock().unwrap() = "正在連到大腦…".into();
}
/// Settings (as config_json gives them) in place of the window's own, the chats kept.
fn mirror_take_config(&mut self, cfg: Value) -> Result<(), String> {
let local = std::mem::replace(&mut self.state, State::first_run());
match serde_json::from_value::<State>(cfg) {
Ok(mut st) => {
let mut old = local.bots.clone();
for b in st.bots.iter_mut() {
if let Some(o) = old.iter_mut().find(|o| o.id == b.id) {
b.messages = std::mem::take(&mut o.messages);
b.threads = std::mem::take(&mut o.threads);
}
}
self.state = st;
self.keep_local_fields(&local);
Ok(())
}
Err(e) => {
self.state = local;
Err(e.to_string())
}
}
}
/// Back to this computer's own bots.
fn mirror_leave(&mut self) {
self.mirror_flush_copy(true);
self.mir.gen.fetch_add(1, Ordering::SeqCst);
self.mir.on = false;
crate::cloudbox::set_brain(true);
self.mir.online = false;
self.mir.outbox = None;
self.mir.acts = None;
// What still waits stays on disk for this brain (and goes when this window shows it
// again); this window's copy of the queue is done with.
*self.mir.queue.lock().unwrap_or_else(|e| e.into_inner()) = Outq::default();
self.streams.clear();
self.approvals.clear();
self.mir.keys.clear();
self.mir.settled.clear();
if let Some(mut local) = self.mir.local.take() {
let mut remote = self.state.remote.clone();
remote.brain_id.clear();
remote.brain_name.clear();
remote.hands_for.clear();
remote.hands_for_name.clear();
copy_own(&mut local, &self.state);
local.remote = remote;
if local.bot(local.selected).is_none() {
local.selected = local.primary_bot;
}
self.state = local;
} else {
// Never keep REDACTED placeholders as real keys when leaving mirror mode without a saved local state.
let mut v = serde_json::to_value(&self.state).unwrap_or(Value::Null);
clear_redacted(&mut v);
if let Ok(st) = serde_json::from_value::<State>(v) {
self.state = st;
}
self.state.remote.brain_id.clear();
self.state.remote.brain_name.clear();
self.state.remote.hands_for.clear();
self.state.remote.hands_for_name.clear();
}
self.state.save();
self.dirty = false;
crate::tunnel::hello("", self.state.remote.device_link);
}
fn keep_local_fields(&mut self, from: &State) {
copy_own(&mut self.state, from);
let st = &mut self.state;
if st.bot(from.selected).is_some() {
st.selected = from.selected;
} else if st.bot(st.selected).is_none() {
st.selected = st.primary_bot;
}
}
fn mirror_worker(&mut self) {
let gen = self.mir.gen.fetch_add(1, Ordering::SeqCst) + 1;
let (tx, rx) = channel();
self.mir.rx = Some(rx);
self.mir.tx = Some(tx.clone());
let (g, version, client, s, resync, last_sync) = (self.mir.gen.clone(), self.mir.version.clone(), self.mir.client.clone(), self.state.remote.clone(), self.mir.resync.clone(), self.mir.last_sync.clone());
let reach = self.mir.reach.clone();
let repaint = self.repaint_fn();
std::thread::spawn(move || {
let mut backoff = 1u64;
// The first answer lets the person in: it brings the settings, and doesn't wait.
let mut first = true;
// The last pull failed: its answer may have been lost on the way (see brain_pull).
let mut retry = false;
while g.load(Ordering::SeqCst) == gen {
let since = if resync.swap(false, Ordering::SeqCst) { 0 } else { version.load(Ordering::SeqCst) };
let (link_before, bytes_before, t0) = (crate::tunnel::link_serial(), crate::tunnel::bytes_in(), std::time::Instant::now());
match remote::sync_pull(&s, since, &client, first, retry) {
Ok(v) => {
backoff = 1;
first = false;
retry = false;
if g.load(Ordering::SeqCst) != gen {
break;
}
// (A long poll that waited for news isn't the line's speed: only answers
// that came quickly or were big count.)
let (bytes, ms) = (crate::tunnel::bytes_in().saturating_sub(bytes_before), t0.elapsed().as_millis() as u64);
*last_sync.lock().unwrap_or_else(|e| e.into_inner()) = Some((crate::model::now_ms(), bytes, if bytes >= 100_000 { ms } else { 0 }));
version.store(v["version"].as_u64().unwrap_or(0), Ordering::SeqCst);
reach.store(v.get("error").is_none(), Ordering::SeqCst);
let _ = tx.send(Incoming::Pull(v));
}
Err(e) => {
reach.store(false, Ordering::SeqCst);
let _ = tx.send(Incoming::Offline(e));
retry = true;
// (A request for everything that failed is asked for again.)
if since == 0 {
resync.store(true, Ordering::SeqCst);
}
// (The version stays: once it is back the brain sends only what changed
// since — it keeps the answer before last for a screen whose answer was
// lost. Starting over sent every chat again, megabytes, on every blip.)
// …and the moment the lasting connection is back, not after the wait:
// the account row said 已連線 while this one still waited up to 20 s.
let until = std::time::Instant::now() + std::time::Duration::from_secs(backoff);
let mut back = false;
while std::time::Instant::now() < until && g.load(Ordering::SeqCst) == gen {
let now = crate::tunnel::link_serial();
if now != 0 && now != link_before {
back = true;
break;
}
std::thread::sleep(std::time::Duration::from_millis(200));
}
backoff = if back { 1 } else { (backoff * 2).min(20) };
if back {
let _ = tx.send(Incoming::Offline("已重新連上帳號伺服器,正在向大腦要資料…".into()));
}
}
}
repaint();
}
});
}
pub(super) fn repaint_fn(&self) -> Arc<dyn Fn() + Send + Sync> {
match &self.ctx_handle {
Some(c) => {
let c = c.clone();
Arc::new(move || c.request_repaint())
}
None => Arc::new(|| {}),
}
}
/// Every frame on a screen: take in what the brain sent.
pub(super) fn mirror_tick(&mut self) {
// (A copy that waited for its turn: written once COPY_EVERY has passed.)
if self.mir.on {
self.mirror_flush_copy(false);
}
if let Some((id, name)) = self.mir.want.take() {
if self.mir.on {
self.mirror_leave();
}
// This computer's hands are for that brain only.
self.state.remote.hands_for = id.clone();
self.state.remote.hands_for_name = name.clone();
self.state.remote.brain_id = id;
self.state.remote.brain_name = name;
self.state.save();
self.mirror_enter();
}
if std::mem::take(&mut self.mir.leave) && self.mir.on {
self.mirror_leave();
}
if !self.mir.on {
return;
}
let mut got = vec![];
if let Some(rx) = &self.mir.rx {
while let Ok(m) = rx.try_recv() {
got.push(m);
}
}
for m in got {
match m {
Incoming::Offline(e) => {
self.mir.online = false;
// Keep `self.mir.base` so edits made during a brief disconnect are diffed
// and replayed on top of the brain's config when the connection returns.
self.mir.down_since.get_or_insert_with(Instant::now);
*self.mir.status.lock().unwrap() = format!("連不到大腦:{e}");
self.mir.reason = e;
}
Incoming::File(path) => {
self.mir.fetching.remove(&path);
self.att.thumbs.remove(&path);
}
Incoming::Unsent { bot, text, atts } => {
// (Put before what was typed since, never in place of it.)
let draft = self.drafts.entry(bot).or_default();
*draft = if draft.trim().is_empty() { text } else { format!("{text}\n{draft}") };
self.att.pending.entry(bot).or_default().extend(atts);
}
Incoming::Sent { bot, text } => {
// (One the chat already shows — its update came first — sending_bubbles drops.)
if !text.trim().is_empty() {
self.sending.entry(bot).or_default().push((text.trim().to_string(), Instant::now()));
}
}
Incoming::Pull(v) => {
if let Some(e) = v["error"].as_str() {
self.mir.online = false;
self.mir.down_since.get_or_insert_with(Instant::now);
*self.mir.status.lock().unwrap() = e.to_string();
self.mir.reason = e.to_string();
continue;
}
self.mir.online = true;
self.mir.down_since = None;
self.mir.reason.clear();
*self.mir.status.lock().unwrap() = format!("已連到大腦「{}」", v["brain"].as_str().unwrap_or(&self.state.remote.brain_name));
self.mirror_apply(v);
if std::mem::take(&mut self.mir.move_after_join) {
self.mirror_move_local();
}
}
}
}
self.mirror_check_queue();
self.mirror_spare_numbers();
}
/// Away from the brain, a new bot or routine made here gets a number far past the brain's
/// last known count (1000–9000 past, by this screen's name), not the next one: the brain
/// may give the next ones meanwhile (a new bot elsewhere, a 支線), and a later edit or a
/// message by that number would have gone to the brain's. Connected, numbers come from the
/// brain's count as always. (Always past every number already here too: one made away
/// before AnyBot closed, or before the brain's settings came back, keeps its own. The count
/// goes to the brain with the next edit, as it always did; the brain keeps the larger.)
pub(super) fn mirror_spare_numbers(&mut self) {
let Some((bots, routines)) = self.mir.counts.filter(|_| self.mir.on) else { return };
let spare = if self.mir.online { 0 } else { 1000 + crate::httpd::sha256_hex(&self.mir.client).bytes().take(4).fold(0u64, |n, b| n * 31 + b as u64) % 8000 };
let top_bot = self.state.bots.iter().chain(&self.state.branch_bots).map(|b| b.id).max().unwrap_or(0);
let top_routine = self.state.bots.iter().flat_map(|b| &b.routines).map(|r| r.id).max().unwrap_or(0);
let (next, next_routine) = (self.state.next_id.max(bots + spare).max(top_bot + 1), self.state.next_routine_id.max(routines + spare).max(top_routine + 1));
// Only moving the count on isn't an edit: `base` moves too, so the count goes to the
// brain only with a bot or routine made with it (else every blip pushed the brain's
// count on by thousands).
for (key, from, to) in [("next_id", self.state.next_id, next), ("next_routine_id", self.state.next_routine_id, next_routine)] {
if to != from && self.mir.base.is_object() && self.mir.base[key].as_u64().is_some_and(|b| b == from) {
self.mir.base[key] = json!(to);
}
}
(self.state.next_id, self.state.next_routine_id) = (next, next_routine);
}
/// A message last tried long ago waits for a look in the brain's chat (as it is now, from an
/// answer that came after that try): there already (that try arrived; only its answer was
/// lost) — it is done; not there — it goes again.
pub(super) fn mirror_check_queue(&mut self) {
let queue = self.mir.queue.clone();
let mut q = queue.lock().unwrap_or_else(|e| e.into_inner());
if !self.mir.online || !q.items.iter().any(|i| i.check) {
return;
}
let fresh = self.mir.synced_ms;
let mut changed = false;
q.items.retain_mut(|it| {
if !it.check || it.tried >= fresh {
return true;
}
changed = true;
// (From the first try that may have arrived, not the last.)
let arrived = match &it.job {
Job::Send { bot, text, atts, .. } => self.state.bot(*bot).is_some_and(|b| arrived_in(&b.messages, text, atts, it.first)),
Job::Edit { .. } => false,
};
it.check = false;
it.tried = 0;
it.first = 0;
!arrived
});
if changed {
q.save();
}
}
fn mirror_apply(&mut self, v: Value) {
self.mir.applied = v["version"].as_u64().unwrap_or(0);
self.mir.synced_ms = crate::model::now_ms();
// (A brain from before `config=1` may answer a resumed screen without its settings: ask
// for everything once more — once, until its settings are in.)
if !v["config"].is_object() && !self.mir.synced {
self.mir.resync.store(true, Ordering::SeqCst);
}
// Edits the brain has taken in are no longer "on the way".
let acked = v["edit_seq"].as_u64().unwrap_or(0);
self.mir.pending.lock().unwrap().retain(|(s, _)| *s > acked);
if v["config"].is_object() {
let count = |k: &str| v["config"][k].as_u64().unwrap_or(1);
self.mir.counts = Some((count("next_id"), count("next_routine_id")));
// What the brain will have once the edits on the way arrive, and on top of that what
// the person changed here and hasn't sent yet.
let inflight: Vec<Value> = self.mir.pending.lock().unwrap().iter().flat_map(|(_, o)| o.clone()).collect();
let unsaved = if self.mir.base.is_object() { diff_ops(&self.mir.base, &config_json(&mut self.state)) } else { vec![] };
let mut base = v["config"].clone();
apply_ops(&mut base, &inflight);
let mut cfg = base.clone();
apply_ops(&mut cfg, &unsaved);
if !unsaved.is_empty() {
self.dirty = true;
}
// (Chats stay as they are: they come separately.)
match self.mirror_take_config(cfg) {
Ok(()) => self.mir.base = base,
Err(e) => *self.mir.error.lock().unwrap() = format!("大腦的設定讀不出來(兩邊 AnyBot 版本不同?):{e}"),
}
// In either way: settings taken, or unreadable and said so (waiting would not help,
// and asking for everything again would only repeat it).
self.mir.entered = true;
self.mir.synced = true;
}
for d in v["bots"].as_array().into_iter().flatten() {
let id = d["id"].as_u64().unwrap_or(0);
let from = d["from"].as_u64().unwrap_or(0) as usize;
let mut msgs: Vec<Message> = serde_json::from_value(d["messages"].clone()).unwrap_or_default();
self.mirror_files(id, &mut msgs);
if let Some(b) = self.state.bot_mut(id) {
// The brain sends what changed from message `from` on, sure this copy has the
// ones before. A copy that is shorter (cleared here, or an answer lost on the
// way) would get them appended in the wrong place — the same message twice and
// half-written replies piling up. Ask for the whole chat again instead.
if b.messages.len() < from {
self.mir.resync.store(true, Ordering::SeqCst);
continue;
}
b.messages.truncate(from);
b.messages.extend(msgs);
}
}
for d in v["threads"].as_array().into_iter().flatten() {
if let Some(b) = self.state.bot_mut(d["id"].as_u64().unwrap_or(0)) {
b.threads = serde_json::from_value(d["threads"].clone()).unwrap_or_default();
}
}
// Who is working, and what waits for the person.
let live: HashMap<u64, (Option<String>, bool)> = v["live"].as_object().into_iter().flatten().filter_map(|(k, l)| Some((k.parse().ok()?, (l["status"].as_str().map(String::from), l["paused"].as_bool().unwrap_or(false))))).collect();
self.streams.retain(|id, _| live.contains_key(id));
for (id, (status, paused)) in live {
let l = self.streams.entry(id).or_insert_with(|| Live {
cancel: Arc::new(AtomicBool::new(false)),
started: Instant::now(),
last: Instant::now(),
produced: true,
status: None,
paused: false,
paused_at: None,
unattended: false,
steer: Arc::default(),
turn_id: String::new(),
direct: Arc::default(),
turn: 0,
});
l.status = status;
l.paused = paused;
l.last = Instant::now();
}
let mut waiting = HashMap::new();
self.mir.answered.retain(|_, t| t.elapsed() < std::time::Duration::from_secs(30));
for a in v["approvals"].as_array().into_iter().flatten() {
let id = a["bot"].as_u64().unwrap_or(0);
if a["key"].as_str().is_some_and(|k| !k.is_empty() && self.mir.answered.contains_key(k)) {
continue;
}
let kind = match a["kind"].as_str().unwrap_or("") {
"tools" => ApprovalKind::EnableTools,
"local" => ApprovalKind::EnableThisComputer,
"handoff" => ApprovalKind::Handoff,
"question" => ApprovalKind::Question,
_ => ApprovalKind::Action,
};
let (reply, _) = channel();
let s = |k: &str| a[k].as_str().unwrap_or("").to_string();
waiting.insert(id, (Approval { call_id: s("call_id"), tool: s("tool"), reason: s("reason"), grant: s("grant"), reply, kind }, s("key")));
}
let ctx = self.ctx_handle.clone();
for (id, (a, key)) in waiting {
// A new card is told by the brain's key (call ids repeat: call_0 every round); an
// older brain sends none, and then by its call id, as before.
let new = match key.is_empty() {
true => self.approvals.get(&id).map(|o| o.call_id != a.call_id).unwrap_or(true),
false => !self.approvals.contains_key(&id) || self.mir.keys.get(&id) != Some(&key),
};
self.approvals.insert(id, a);
if key.is_empty() {
self.mir.keys.remove(&id);
} else {
self.mir.keys.insert(id, key.clone());
}
if new {
if let Some(c) = &ctx {
match key.is_empty() {
true => self.on_new_approval(c, id),
false => self.new_approval_keyed(c, id, key),
}
}
}
}
if v["box"].is_object() {
self.mir.box_state = v["box"].clone();
}
// 任務: the brain's list, as it worked it out.
if v["tasks"].is_array() {
self.mir.tasks = serde_json::from_value(v["tasks"].clone()).ok();
}
if v["mcp"].is_object() {
self.mir.mcp_state = v["mcp"].clone();
}
if v["chatgpt"].is_object() {
crate::chatgpt::set_brain_view(v["chatgpt"].clone());
}
if let Some(c) = v["computers"].as_object() {
self.mir.computers = c.iter().filter_map(|(k, x)| Some((k.parse().ok()?, x.clone()))).collect();
}
let keep: Vec<u64> = v["approvals"].as_array().into_iter().flatten().filter_map(|a| a["bot"].as_u64()).collect();
self.approvals.retain(|id, _| keep.contains(id));
self.mir.keys.retain(|id, _| keep.contains(id));
if self.state.bot(self.state.selected).is_none() {
self.state.selected = self.state.primary_bot;
}
// 朗讀每個回答: the brain finishes the turns, this screen reads them (a brain on a server
// has nobody to read to). Its answer came in this same update.
let turns: Vec<(u64, Option<TurnSettlement>)> = self.state.bots.iter().map(|b| (b.id, b.last_turn.clone())).collect();
for id in just_finished(&mut self.mir.settled, turns.iter().map(|(id, t)| (*id, t.as_ref())), chrono::Utc::now().timestamp_millis()) {
self.read_reply(id);
}
self.mirror_save_copy();
}
/// Files in the brain's chats live on the brain: show local copies, fetched once. (The
/// file keeps its id: 交付確認 goes by it, not by where the file is.)
fn mirror_files(&mut self, bot: u64, msgs: &mut [Message]) {
for (by_bot, a) in msgs.iter_mut().flat_map(|m| {
let by_bot = m.role == Role::Assistant;
m.attachments.iter_mut().map(move |a| (by_bot, a))
}) {
if std::path::Path::new(&a.path).exists() {
continue;
}
let local = local_copy(&a.path, &a.name);
let lp = local.display().to_string();
let brain_path = std::mem::replace(&mut a.path, lp.clone());
if local.exists() || !self.mir.fetching.insert(lp.clone()) {
continue;
}
let (s, tx, repaint) = (self.state.remote.clone(), self.mir.tx.clone(), self.repaint_fn());
let att = if by_bot { a.id.clone() } else { String::new() };
std::thread::spawn(move || {
match remote::sync_file(&s, &brain_path) {
Ok(bytes) => {
if let Some(dir) = local.parent() {
crate::httpd::ensure_private_dir(dir);
}
let _ = crate::httpd::write_private(&local, &bytes);
}
// 交付確認: the brain answered and has no such file (not a line that is
// down — that is no one's failure): this screen couldn't show it.
Err((true, _)) if !att.is_empty() => {
let _ = remote::sync_post(&s, "act", &json!({"bot": bot, "action": "seen", "att": att, "kind": "failed", "why": "missing"}));
}
Err(_) => {}
}
if let Some(tx) = tx {
let _ = tx.send(Incoming::File(lp));
}
repaint();
});
}
}
/// The copy on disk, soon: at most every COPY_EVERY, serialized and written on a thread of
/// its own (cloning the state is cheap: the chats are shared, see shared.rs).
fn mirror_save_copy(&mut self) {
self.mir.copy_dirty = true;
self.mirror_flush_copy(false);
}
/// Write the waiting copy if it is time (or `now`: leaving the brain, quitting).
pub(super) fn mirror_flush_copy(&mut self, now: bool) {
if !self.mir.copy_dirty || self.mir.copy_writing.load(Ordering::Acquire) {
return;
}
if !now && self.mir.copy_at.is_some_and(|t| t.elapsed() < COPY_EVERY) {
return;
}
self.mir.copy_dirty = false;
self.mir.copy_at = Some(Instant::now());
let snap = self.state.clone();
// (Messages not yet at the brain are in the queue, not in the chats: every copy is one
// to resume from.)
let at = CopyAt { brain: self.state.remote.brain_id.clone(), client: self.mir.client.clone(), version: self.mir.applied, at: self.mir.synced_ms };
let dir = self.mirror_dir();
let writing = self.mir.copy_writing.clone();
writing.store(true, Ordering::Release);
let write = move || {
// The copy first, then what it is: a stop between the two leaves no marker, and the
// next start waits for the brain instead of showing a copy cut short.
let _ = std::fs::remove_file(copy_at_path(&dir));
if let Ok(s) = serde_json::to_string(&snap) {
if crate::httpd::write_private(&cache_path(&dir), s.as_bytes()).is_ok() {
if let Ok(a) = serde_json::to_vec(&at) {
let _ = crate::httpd::write_private(&copy_at_path(&dir), &a);
}
}
}
writing.store(false, Ordering::Release);
};
if now {
write();
} else {
std::thread::spawn(write);
}
}
/// Saving on a screen: edits go to the brain; this computer's own file keeps its own bots.
pub(super) fn mirror_save(&mut self) {
if let Some(local) = self.mir.local.as_mut() {
copy_own(local, &self.state);
local.save();
}
// (Nothing of the brain to compare with yet — at the door, the first time — nothing is
// edited.) Connected or not: the edit waits in the queue and goes once the brain is in
// reach, laid over whatever the brain has by then (mirror_apply).
if !self.mir.base.is_object() {
return;
}
let cur = config_json(&mut self.state);
let ops = diff_ops(&self.mir.base, &cur);
if ops.is_empty() {
return;
}
self.mir.base = cur;
self.mir.seq += 1;
let seq = self.mir.seq;
self.mir.pending.lock().unwrap().push((seq, ops.clone()));
self.mirror_queue(Job::Edit { seq, ops });
}
fn mirror_out(&mut self, o: Out) {
// Chat actions have a lane of their own: one never waits behind a message that waits
// for the brain (an answer or a stop pressed now goes now, as before the queue).
if let (Out::Act(body), Some(lane)) = (&o, &self.mir.acts) {
let _ = lane.send((body.clone(), crate::model::now_ms()));
return;
}
if let Some(tx) = &self.mir.outbox {
let _ = tx.send(o);
}
}
/// Into the queue (and onto disk) and to the sending thread.
fn mirror_queue(&mut self, job: Job) {
let it = Queued { job, at: crate::model::now_ms(), tried: 0, first: 0, trying: false, check: false };
let key = it.key();
{
let mut q = self.mir.queue.lock().unwrap_or_else(|e| e.into_inner());
q.items.push(it);
q.save();
}
self.mirror_out(Out::Queued(key));
}
/// 取消 on a message still waiting: out of the queue, its words and files back in the input.
/// Not one on its way this moment (it may arrive).
pub(super) fn mirror_unqueue(&mut self, key: &str) -> bool {
let job = {
let mut q = self.mir.queue.lock().unwrap_or_else(|e| e.into_inner());
let Some(i) = q.items.iter().position(|i| i.key() == key && !i.trying && i.first == 0) else { return false };
let it = q.items.remove(i);
q.save();
it.job
};
if let Job::Send { bot, text, atts, typed: true, .. } = job {
let draft = self.drafts.entry(bot).or_default();
*draft = if draft.trim().is_empty() { text } else { format!("{text}\n{draft}") };
self.att.pending.entry(bot).or_default().extend(atts);
}
true
}
/// One worker sends everything to the brain in order (a rename before the message that uses
/// it, two quick edits in the order they were made). What waited in the queue on disk goes
/// first.
fn mirror_outbox(&mut self) {
let (tx, rx) = channel::<Out>();
for it in self.mir.queue.lock().unwrap_or_else(|e| e.into_inner()).items.iter() {
let _ = tx.send(Out::Queued(it.key()));
}
self.mir.outbox = Some(tx);
let (s, err, client, pending, resync) = (self.state.remote.clone(), self.mir.error.clone(), self.mir.client.clone(), self.mir.pending.clone(), self.mir.resync.clone());
let (note, busy) = (self.mir.move_note.clone(), self.mir.moving.clone());
let (queue, reach, g) = (self.mir.queue.clone(), self.mir.reach.clone(), self.mir.gen.clone());
let gen = g.load(Ordering::SeqCst);
let repaint = self.repaint_fn();
let back = self.mir.tx.clone();
// The chat actions' lane: each tried for up to SURE_SECS, as it always was. One pressed
// just after an edit or a message lets those go first (a moment, not as long as they
// wait): 執行 right after changing a routine runs the changed one.
let (atx, arx) = channel::<(Value, i64)>();
self.mir.acts = Some(atx);
{
let (s, err, queue, g, repaint) = (s.clone(), err.clone(), queue.clone(), g.clone(), repaint.clone());
std::thread::spawn(move || {
let waiting = || {
*err.lock().unwrap() = "網路不穩,正在重新傳送…".into();
repaint();
};
for (body, made) in arx {
if g.load(Ordering::SeqCst) != gen {
break;
}
// (A card's answer doesn't wait: it goes to the card it names, whatever else
// is on the way.)
let wait = if body["action"] == "answer" { 0 } else { 10 };
let until = std::time::Instant::now() + std::time::Duration::from_secs(wait);
while std::time::Instant::now() < until && queue.lock().unwrap_or_else(|e| e.into_inner()).items.iter().any(|i| i.at <= made) {
std::thread::sleep(std::time::Duration::from_millis(100));
}
if let Err(e) = remote::sync_post_sure(&s, "act", &body, &waiting) {
*err.lock().unwrap() = format!("大腦沒有收到:{e}");
}
repaint();
}
});
}
std::thread::spawn(move || {
// Said while a try is sent again (the line is down for a moment).
let waiting = || {
*err.lock().unwrap() = "網路不穩,正在重新傳送…".into();
repaint();
};
let stay = || g.load(Ordering::SeqCst) == gen;
// Between tries: a moment (waiting for the brain to be in reach), or longer after the
// line failed (1, 2, 4… up to 20 s) — cut short the moment the lasting connection is
// back.
let shown = std::cell::Cell::new(std::time::Instant::now());
let pause = |fails: u32| {
// (While it only waits, the window is told now and then, not three times a second.)
if fails > 0 || shown.get().elapsed().as_secs() >= 2 {
shown.set(std::time::Instant::now());
repaint();
}
let ms = if fails == 0 { 300 } else { (1000u64 << (fails - 1).min(5)).min(20_000) };
let (until, link) = (std::time::Instant::now() + std::time::Duration::from_millis(ms), crate::tunnel::link_serial());
while std::time::Instant::now() < until && stay() {
if fails > 0 && crate::tunnel::link_serial() != link {
break;
}
std::thread::sleep(std::time::Duration::from_millis(100));
}
};
for o in rx {
if !stay() {
break;
}
match o {
Out::Queued(key) => {
let mut go = |job: &mut Job| {
repaint();
try_job(&s, &client, job)
};
match deliver(&queue, &key, &crate::model::now_ms, &mut go, &|| reach.load(Ordering::SeqCst), &stay, &pause) {
Some((Job::Send { bot, text, .. }, Ok(_))) => {
if let Some(tx) = &back {
let _ = tx.send(Incoming::Sent { bot, text });
}
}
// The brain itself said no — or, with the brain in reach all along, it
// still couldn't go however often it was tried (a line that only
// drops waits as long as it takes).
Some((Job::Send { bot, text, atts, typed, .. }, Err((gave_up, e)))) => {
let back_in = if typed { "(已放回輸入框)" } else { "" };
// (Given up after tries that may have arrived, their answers lost:
// the person looks before sending it again.)
let maybe = if gave_up { ";它也可能已經到了,先看聊天裡有沒有再傳" } else { "" };
*err.lock().unwrap() = format!("訊息沒有送到大腦{back_in}:{e}{maybe}");
// (A command a button sent — 「/goal clear」 — isn't the person's words: it
// doesn't go into the input, where it would join what they type next.)
if let Some(tx) = back.as_ref().filter(|_| typed) {
let _ = tx.send(Incoming::Unsent { bot, text, atts });
}
}
Some((Job::Edit { seq, .. }, Err((_, e)))) => {
*err.lock().unwrap() = format!("剛才的改動沒有存到大腦:{e}");
pending.lock().unwrap().retain(|(n, _)| *n != seq);
resync.store(true, Ordering::SeqCst);
}
_ => {}
}
}
// (Actions go on their own lane — see mirror_out; here only without one.)
Out::Act(body) => {
if let Err(e) = remote::sync_post_sure(&s, "act", &body, &waiting) {
*err.lock().unwrap() = format!("大腦沒有收到:{e}");
}
}
Out::McpReconnect(name) => {
if let Err(e) = remote::sync_post(&s, "mcp", &json!({"name": name})) {
*err.lock().unwrap() = format!("大腦沒有重新連線:{e}");
}
}
Out::McpRename(old, new) => {
if let Err(e) = remote::sync_post(&s, "mcp-rename", &json!({"name": old, "rename": new})) {
*err.lock().unwrap() = format!("大腦沒有改連接器的名稱:{e}");
}
}
Out::Move { ops, n, skills } => {
let mut said = match remote::sync_post(&s, "edit", &json!({"ops": ops})) {
Ok(_) if n == 0 => "已同步:大腦上已經有這台的 Bot;模型金鑰、技能和連接器有缺的已補上".to_string(),
Ok(_) => format!("已把 {n} 個 Bot(連同聊天)搬到大腦"),
Err(e) => format!("搬移失敗:{e}"),
};
// This computer's skills go up whole (with their files), one by one.
let failed: Vec<String> = skills
.iter()
.filter_map(|k| crate::skills::package_of(k).and_then(|p| remote::sync_post(&s, "skill", &json!({"package": p}))).err().map(|e| format!("「{}」:{e}", k.name)))
.collect();
if !failed.is_empty() {
said.push_str(&format!(";這些技能沒有搬過去:{}", failed.join("、")));
}
*note.lock().unwrap() = said;
busy.store(false, Ordering::SeqCst);
}
Out::Skill { body, note, busy } => {
*note.lock().unwrap() = Some(match skill_request(body).and_then(|b| remote::sync_post(&s, "skill", &b)) {
Ok(v) => (true, v["text"].as_str().unwrap_or("好了").to_string()),
Err(e) => (false, e),
});
busy.store(false, Ordering::SeqCst);
}
}
repaint();
}
});
}
/// 交付確認 from this screen: what it did with a file the bot handed over, to the brain, once
/// (not while the line is down — then it is told when the file is next drawn after it is back).
pub(super) fn mirror_seen(&mut self, body: Value) -> bool {
if !self.mir.online {
return false;
}
// (On a thread of its own: a slow line never holds up a message or an answer behind it.)
let s = self.state.remote.clone();
std::thread::spawn(move || {
let _ = remote::sync_post(&s, "act", &body);
});
true
}
/// A chat action on a screen goes to the brain (named, so a try sent again is done once).
/// While the line is down for a moment it is sent again, for up to SURE_SECS.
pub(super) fn mirror_act(&mut self, body: Value) {
// (Stop, regenerate, a card's answer…: done to what runs at the brain now, they don't
// wait in the queue for later.)
if !self.mirror_can_send() {
*self.mir.error.lock().unwrap() = "連不到大腦:這個動作要連上才能做(訊息可以照樣傳,連上後送出)。".into();
return;
}
let mut body = body;
if body.is_object() && body.get("id").is_none() {
body["id"] = json!(act_id(&self.mir.client));
}
self.mirror_out(Out::Act(body));
}
/// Whether an action on what runs at the brain (stop, regenerate, a card's answer…) can go:
/// connected, or connected before and only away for a moment (it is sent again when the line
/// is back, for up to SURE_SECS). Before the first answer from the brain, none can. (Messages
/// and edits always can: they wait in the queue.)
pub(super) fn mirror_can_send(&self) -> bool {
self.mir.online || (self.mir.synced && self.mir.down_since.is_none_or(|t| t.elapsed() < std::time::Duration::from_secs(remote::SURE_SECS)))
}
/// Out of reach for more than a moment (a blip — the account server restarting — isn't).
pub(super) fn mirror_offline(&self) -> bool {
self.mir.on && !self.mir.online && self.mir.down_since.is_some_and(|t| t.elapsed().as_secs() >= 4)
}
/// The messages waiting in the queue for one bot (all bots: 0).
pub(super) fn mirror_waiting(&self, bot: u64) -> Vec<Queued> {
self.mir.queue.lock().unwrap_or_else(|e| e.into_inner()).items.iter().filter(|i| matches!(i.job, Job::Send { bot: b, .. } if bot == 0 || b == bot)).cloned().collect()
}
/// 連接器 › 重新連線 on a screen: the brain connects it again; its line says 連線中… until
/// the brain's next word on it.
pub(super) fn mirror_mcp_rename(&mut self, old: &str, new: &str) {
self.mirror_out(Out::McpRename(old.to_string(), new.to_string()));
}
pub(super) fn mirror_mcp_reconnect(&mut self, name: &str) {
if !self.mir.online {
*self.mir.error.lock().unwrap() = "連不到大腦:重新連線要連上才能做。".into();
return;
}
if self.mir.mcp_state["servers"].is_object() {
self.mir.mcp_state["servers"][name] = json!({});
}
self.mir.mcp_state["busy"] = json!(true);
self.mirror_out(Out::McpReconnect(name.to_string()));
}
/// 技能 on a screen — add one from the market, install from an address or a folder here,
/// delete one — is done by the brain: the bots read skills from the brain's disk, and a
/// folder left there would bring a deleted skill back when the brain restarts. Turning one
/// on or off stays an ordinary edit. Edits made before go first.
pub(super) fn mirror_skill(&mut self, body: Value, note: SkillNote, busy: Arc<AtomicBool>) {
if !self.mir.online {
*note.lock().unwrap() = Some((false, "連不到大腦,技能沒有改。".into()));
return;
}
if busy.swap(true, Ordering::SeqCst) {
return;
}
*note.lock().unwrap() = None;
if self.dirty {
self.mirror_save();
}
self.mirror_out(Out::Skill { body, note, busy });
}
/// Send a message through the brain: files go up first, then the text.
pub(super) fn mirror_send(&mut self, bot: u64, text: String, atts: Vec<crate::attach::Attachment>, memories: Option<Vec<String>>) -> bool {
self.mirror_send_from(bot, text, atts, memories, true)
}
/// A command a button sends on a screen (「/goal clear」): like a message, but never put
/// back into the input when it can't be sent.
pub(super) fn mirror_command(&mut self, bot: u64, text: &str) -> bool {
self.mirror_send_from(bot, text.to_string(), vec![], None, false)
}
/// A message into the queue: shown at once under the chat (傳送中…, or 等連上大腦後送出 with
/// 取消), sent in order however long the brain is out of reach — kept on disk while AnyBot is
/// closed — and done once at the brain (by its id). A button's command (not `typed`) is
/// done to the brain now, like stop: only with the brain in reach.
fn mirror_send_from(&mut self, bot: u64, text: String, atts: Vec<crate::attach::Attachment>, memories: Option<Vec<String>>, typed: bool) -> bool {
// Settings changed just before go first.
if self.dirty {
self.mirror_save();
}
// (A button's command goes as an action: now, or not — never kept for later, when a
// 「/goal clear」 would clear a goal set since.)
if !typed {
if !self.mirror_can_send() {
*self.mir.error.lock().unwrap() = "連不到大腦:這個動作要連上才能做。".into();
return false;
}
self.mirror_act(json!({"bot": bot, "action": "send", "text": text, "attachments": []}));
return true;
}
let id = act_id(&self.mir.client);
self.mirror_queue(Job::Send { bot, id, text, atts, memories, typed, uploaded: vec![] });
true
}
/// 把這台的 Bot 搬到大腦: copy this computer's own bots (with their chats), keys, skills and
/// connectors to the brain, as new bots there.
pub(super) fn mirror_move_local(&mut self) {
let Some(local) = self.mir.local.clone() else { return };
if self.mir.moving.swap(true, Ordering::SeqCst) {
return;
}
let mut ops: Vec<Value> = vec![];
// Skip what the brain already has: the same starter bot never used here, or a bot moved
// before (same name, same chat).
let last = |b: &Bot| b.messages.last().map(|m| (m.at, m.text.clone()));
let moving: Vec<&Bot> = local
.bots
.iter()
.filter(|b| !self.state.bots.iter().any(|o| o.name == b.name && (b.messages.is_empty() || (o.messages.len() == b.messages.len() && last(o) == last(b)))))
.collect();
for b in moving.iter().copied() {
let mut v = serde_json::to_value(b).unwrap_or(Value::Null);
v["id"] = json!(0);
ops.push(json!({"op": "bot_add", "bot": v}));
}
let top = serde_json::to_value(&local).unwrap_or(Value::Null);
ops.push(json!({"op": "merge", "key": "providers", "value": top["providers"]}));
// Connectors run at the brain: one that names this computer's own folders (e.g.
// 「files」 on ~/Documents) would fail there, so it stays here.
let servers: Vec<&crate::mcp::Server> = local.mcp_servers.iter().filter(|s| !crate::mcp::names_this_computer(s)).collect();
ops.push(json!({"op": "merge", "key": "mcp_servers", "value": servers}));
// Skills the brain doesn't have yet go up with their files (a bare entry in the list
// would leave its scripts on this computer).
let skills: Vec<Skill> = local.skills.iter().filter(|k| !self.state.skills.iter().any(|b| b.name == k.name)).cloned().collect();
let n = moving.len();
*self.mir.move_note.lock().unwrap() = "搬移中…".into();
self.mirror_out(Out::Move { ops, n, skills });
}
/// The first time only (no copy of this brain on disk): nothing of the brain to show until its
/// first answer is in. With a copy the window shows it at once (mirror_open), and what is
/// done there waits in the queue — no edits that silently go nowhere, no 「只能看」.
pub(super) fn mirror_waiting_at_door(&self) -> bool {
self.mir.on && !self.demo && !self.mir.entered
}
/// The whole window while it waits at the door: what it is doing, why it can't yet, and a
/// way back to this computer's own bots when the brain stays out of reach.
pub(super) fn mirror_door(&mut self, ui: &mut egui::Ui) {
let p = self.pal;
let name = if self.state.remote.brain_name.trim().is_empty() { t("大腦") } else { self.state.remote.brain_name.clone() };
let status = self.mir.status.lock().unwrap().clone();
let waited = self.mir.door_since.map(|t| t.elapsed().as_secs()).unwrap_or(0);
let full = ui.max_rect();
ui.painter().rect_filled(full, 0.0, p.pane);
let w = 360.0f32.min(full.width() - 32.0);
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(egui::Rect::from_center_size(full.center(), vec2(w, 220.0))).layout(Layout::top_down(Align::Center)));
let ui = &mut child;
super::chat_ui::spinner(ui, 22.0, p.text2);
ui.add_space(12.0);
ui.label(RichText::new(t("正在連到「{name}」…").replace("{name}", &name)).size(FONT_BASE).strong().family(crate::bold()).color(p.text));
ui.add_space(6.0);
let line = if status.is_empty() || status.starts_with("已連到") { t("連上、拿到最新的資料就進去") } else { status };
ui.add(egui::Label::new(RichText::new(line).size(FONT_SM).color(p.text2)).wrap());
// Out of reach for a while: the way back (from 設定 › 手機與帳號 it can be joined again).
if waited >= 10 {
ui.add_space(14.0);
if ui.add(secondary_button("改回用這台自己的 Bot")).on_hover_text(t("之後要再用大腦,到 設定 › 手機與帳號 選它。")).clicked() {
self.mir.leave = true;
}
}
ui.ctx().request_repaint_after(std::time::Duration::from_millis(500));
}
/// What went wrong with a request to the brain: said once, in the line under the message box
/// (no band over the chat — the window stays as tall and as usable as when connected).
pub(super) fn mirror_banner(&mut self, _ui: &mut egui::Ui) {
if !self.mir.on {
return;
}
let err = std::mem::take(&mut *self.mir.error.lock().unwrap());
if !err.is_empty() {
self.notice = Some(err);
}
}
/// 離線 (or 連線中…, before the brain's first answer): a small mark in the chat's top bar,
/// with how many messages wait; the pointer on it says what is shown and what happens to
/// what is done meanwhile. Nothing while connected, or away for only a moment.
pub(super) fn mirror_chip(&mut self, ui: &mut egui::Ui) {
if !self.mir.on || self.mir.online {
return;
}
let p = self.pal;
let waiting = self.mirror_waiting(0).len();
let offline = self.mirror_offline();
let word = if offline {
if waiting > 0 { t("離線 · {n} 則等送出").replace("{n}", &waiting.to_string()) } else { t("離線") }
} else if self.mir.down_since.is_none() && !self.mir.synced {
t("連線中…")
} else {
// (A blip: shown if it lasts.)
ui.ctx().request_repaint_after(std::time::Duration::from_secs(1));
return;
};
let name = if self.state.remote.brain_name.trim().is_empty() { t("大腦") } else { self.state.remote.brain_name.clone() };
let mut tip = if offline { t("連不到大腦「{name}」").replace("{name}", &name) } else { t("正在連到大腦「{name}」…").replace("{name}", &name) };
if offline && !self.mir.reason.is_empty() {
tip.push_str(&format!(":{}", self.mir.reason));
}
tip.push('\n');
if self.mir.synced_ms > 0 {
let when = chrono::DateTime::from_timestamp_millis(self.mir.synced_ms).map(|t| t.with_timezone(&chrono::Local)).map(|t| if t.date_naive() == chrono::Local::now().date_naive() { t.format("%H:%M").to_string() } else { t.format("%m/%d %H:%M").to_string() }).unwrap_or_default();
tip.push_str(&t("顯示的是 {when} 同步的內容。").replace("{when}", &when));
}
tip.push_str(&t("你傳的訊息和改的設定會先排著,連上後依序送出;停止、重新產生這類動作要連上才能做。"));
let font = egui::FontId::proportional(FONT_SM);
let galley = ui.painter().layout_no_wrap(word, font, p.text2);
let (rect, r) = ui.allocate_exact_size(vec2(10.0 + 6.0 + galley.size().x + 16.0, 28.0), egui::Sense::hover());
let dot = egui::pos2(rect.left() + 8.0 + 4.0, rect.center().y);
ui.painter().circle_stroke(dot, 3.5, Stroke::new(1.5, p.text3));
ui.painter().galley(egui::pos2(dot.x + 4.0 + 6.0, rect.center().y - galley.size().y / 2.0), galley, p.text2);
r.on_hover_text(tip);
ui.ctx().request_repaint_after(std::time::Duration::from_secs(1));
}
/// Messages still in the queue for this bot, under its chat: faded, with where they stand
/// (傳送中…, 排隊中…, 等連上大腦後送出) and 取消 — back into the input — while one isn't on
/// its way this moment.
pub(super) fn mirror_queue_bubbles(&mut self, ui: &mut egui::Ui, bot: &Bot) {
if !self.mir.on {
return;
}
let p = self.pal;
let waiting = self.mirror_waiting(bot.id);
let mut cancel = None;
for it in &waiting {
let Job::Send { text, atts, .. } = &it.job else { continue };
super::chat_ui::pending_bubble(ui, p, |ui| {
ui.vertical(|ui| {
if !text.trim().is_empty() {
ui.label(RichText::new(text.trim()).size(FONT_BASE).color(p.text2));
}
for a in atts {
ui.label(RichText::new(t("附件:{name}").replace("{name}", &a.name)).size(FONT_SM).color(p.text3));
}
});
});
ui.with_layout(Layout::right_to_left(Align::Min), |ui| {
if !it.trying && it.first == 0 && ui.add(egui::Label::new(RichText::new(t("取消")).size(FONT_XS).color(p.text2).underline()).sense(egui::Sense::click())).on_hover_text(t("不送了,放回輸入框")).on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
cancel = Some(it.key());
}
let note = if it.trying {
t("傳送中…")
} else if self.mir.online {
t("排隊中…")
} else {
t("等連上大腦後送出")
};
ui.label(RichText::new(note).size(FONT_XS).color(p.text3));
});
ui.add_space(6.0);
}
if let Some(key) = cancel {
self.mirror_unqueue(&key);
}
if !waiting.is_empty() {
ui.ctx().request_repaint_after(std::time::Duration::from_millis(500));
}
}
}
#[cfg(test)]
mod tests {
/// A connector renamed on a screen is asked of the brain (queued for it, in order), not
/// renamed here — the brain's update brings the new name. Without the brain: not at all,
/// and the person is told.
#[test]
fn a_screen_asks_the_brain_to_rename_a_connector() {
let ctx = egui::Context::default();
let mut app = App::new(&ctx, Some(std::env::temp_dir().join("anybot-screen-rename.png")));
app.state.mcp_servers = vec![crate::mcp::Server { name: "gh".into(), url: "https://gh.example/mcp".into(), enabled: true, ..Default::default() }];
app.mir.on = true;
app.mir.online = false;
app.ch.mcp_name = Some(("gh".into(), "gh-work".into()));
app.settle_mcp_name();
assert_eq!(app.state.mcp_servers[0].name, "gh");
assert!(app.notice.as_deref().is_some_and(|n| n.contains("連不到大腦")), "{:?}", app.notice);
let (tx, rx) = channel();
app.mir.outbox = Some(tx);
app.mir.online = true;
app.ch.mcp_name = Some(("gh".into(), "gh-work".into()));
app.settle_mcp_name();
match rx.try_recv() {
Ok(Out::McpRename(a, b)) => assert_eq!((a.as_str(), b.as_str()), ("gh", "gh-work")),
_ => panic!("the brain wasn't asked"),
}
assert_eq!(app.state.mcp_servers[0].name, "gh", "renamed by the brain, not here first");
}
use super::*;
/// A screen of brain "brain-1" keeping its copy and queue in `dir` (a test's own folder),
/// without the network: its threads aren't started, and nothing is written to this
/// computer's own file.
fn screen_in(ctx: &egui::Context, dir: &std::path::Path) -> App {
let mut s = App::new(ctx, Some(dir.join("shot.png")));
s.state.remote.brain_id = "brain-1".into();
s.state.remote.brain_name = "大腦".into();
s.mir.client = "screen-1".into();
s.mir.dir = dir.to_path_buf();
// (Made from the screenshot data, but a screen like any other: the door is shown.)
s.demo = false;
s.mirror_open();
s.mir.local = None;
s
}
/// A screen holding just the brain's settings has no edit to send: the settings as the brain
/// sends them read back the same (a routine without a trigger used to come with
/// `"trigger": null`, and every save sent all routines back — from an old copy, too).
#[test]
fn the_brains_settings_read_back_the_same() {
let ctx = egui::Context::default();
let mut brain = App::new(&ctx, Some(std::env::temp_dir().join("anybot-read-back.png")));
assert!(brain.state.bots.iter().any(|b| b.routines.iter().any(|r| r.trigger.is_none())), "the demo has a routine without a trigger");
let c = brain.brain_pull("read-back", 0, true, false)["config"].clone();
let mut st: State = serde_json::from_value(c.clone()).unwrap();
assert_eq!(diff_ops(&c, &config_json(&mut st)), Vec::<Value>::new());
}
fn fresh_dir(name: &str) -> PathBuf {
let d = std::env::temp_dir().join(format!("anybot-screen-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
d
}
/// A brain whose first bot is called 「大腦的 Bot」, and a screen that took its first answer
/// (and wrote its copy).
fn brain_and_screen(ctx: &egui::Context, dir: &std::path::Path) -> (App, App) {
let mut brain = App::new(ctx, Some(dir.join("brain.png")));
brain.state.bots[0].name = "大腦的 Bot".into();
let mut screen = screen_in(ctx, dir);
screen.mir.online = true;
screen.mirror_apply(brain.brain_pull("screen-1", 0, true, false));
screen.mir.copy_at = None;
screen.mirror_flush_copy(true);
while screen.mir.copy_writing.load(Ordering::Acquire) {
std::thread::sleep(std::time::Duration::from_millis(5));
}
(brain, screen)
}
/// 有副本就直接進去: a screen that has this brain's copy shows it at once, with no network —
/// the brain's bots, edits possible; only the first time (no copy), or with another brain's
/// copy, it waits at the door.
#[test]
fn a_screen_with_a_copy_goes_in_at_once() {
let ctx = egui::Context::default();
let dir = fresh_dir("copy-door");
let first = screen_in(&ctx, &dir);
assert!(first.mirror_waiting_at_door(), "no copy yet: it waits for the brain");
let (brain, screen) = brain_and_screen(&ctx, &dir);
assert!(!screen.mirror_waiting_at_door());
// Started again, the brain out of reach.
let again = screen_in(&ctx, &dir);
assert!(!again.mirror_waiting_at_door(), "in at once, from the copy");
assert_eq!(again.state.bots[0].name, "大腦的 Bot");
assert_eq!(again.state.bots.len(), brain.state.bots.len());
assert!(again.mir.base.is_object(), "edits can be made: what the brain had is known");
assert!(again.mir.synced_ms > 0, "and when it was");
assert!(!again.mirror_can_send(), "stop, regenerate…: only once the brain answers");
// Another brain: its bots aren't this copy's.
let mut other = App::new(&ctx, Some(dir.join("other.png")));
other.state.remote.brain_id = "brain-2".into();
other.mir.dir = dir.clone();
other.demo = false;
other.mirror_open();
assert!(other.mirror_waiting_at_door());
let _ = std::fs::remove_dir_all(&dir);
}
/// 沒網路照樣能送: a message sent while the brain is out of reach waits in the queue (on
/// disk: a restart keeps it), goes once the brain is back, and — when the first try arrived
/// but its answer was lost — the try again is the same message (its id): the brain does it
/// once, and the screen shows it once.
#[test]
fn a_message_sent_offline_reaches_the_brain_once() {
let ctx = egui::Context::default();
let dir = fresh_dir("offline-send");
let (mut brain, mut screen) = brain_and_screen(&ctx, &dir);
let id = brain.state.bots[0].id;
screen.mir.online = false;
screen.mir.down_since = Some(Instant::now() - std::time::Duration::from_secs(30));
assert!(screen.mirror_offline());
assert!(screen.mirror_send(id, "離線時打的".into(), vec![], None));
assert!(screen.mir.error.lock().unwrap().is_empty());
// AnyBot closed and opened again: it still waits.
let mut screen = screen_in(&ctx, &dir);
let waiting = screen.mirror_waiting(id);
assert_eq!(waiting.len(), 1, "the queue was kept on disk");
let key = waiting[0].key();
// The sending thread: nothing goes while the brain is out of reach; once it is back, the
// first try arrives but its answer is lost on the way; the next is the same message.
let up = std::cell::Cell::new(false);
let (mut tries, mut ids) = (0, std::collections::HashSet::new());
let seen = screen.mir.queue.clone();
let mut go = |job: &mut Job| {
tries += 1;
if tries == 2 {
// A try may have arrived (its answer was lost): it can't be taken back now.
assert!(seen.lock().unwrap().items[0].first > 0);
}
let Job::Send { bot, id, text, .. } = job else { panic!("{job:?}") };
assert!(up.get(), "not tried while out of reach");
// (What the brain does: remote.rs first_delivery, by the message's id.)
if ids.insert(id.clone()) {
brain.state.bot_mut(*bot).unwrap().messages.push(Message::user(text));
}
if tries == 1 { Err((true, "和大腦的連線到一半斷掉了".into())) } else { Ok(json!({"ok": true, "again": true})) }
};
let q = screen.mir.queue.clone();
let out = deliver(&q, &key, &crate::model::now_ms, &mut go, &|| up.get(), &|| true, &|_| up.set(true));
assert!(matches!(out, Some((Job::Send { .. }, Ok(_)))), "{out:?}");
assert_eq!(tries, 2);
let count = |b: &Bot| b.messages.iter().filter(|m| m.text == "離線時打的").count();
assert_eq!(count(brain.state.bot(id).unwrap()), 1, "done once at the brain");
assert!(screen.mirror_waiting(id).is_empty() && !queue_path(&dir, "brain-1").exists(), "out of the queue, and off the disk: {:?}", screen.mir.queue.lock().unwrap().items);
// The brain's next answer brings it into the screen's chat, once.
screen.mir.online = true;
let since = screen.mir.applied;
screen.mirror_apply(brain.brain_pull("screen-1", since, true, false));
assert_eq!(count(screen.state.bot(id).unwrap()), 1);
let _ = std::fs::remove_dir_all(&dir);
}
/// A message whose first try that may have arrived is older than the brain remembers ids
/// isn't sent blind — even when later tries (that never got there) were recent: the window
/// looks in the brain's chat first, from that first try on — there (it arrived, its answer
/// was lost): done; not there: it goes again (and can be taken back meanwhile).
#[test]
fn a_message_tried_long_ago_is_looked_for_first() {
let ctx = egui::Context::default();
let dir = fresh_dir("tried-long-ago");
let (_brain, mut screen) = brain_and_screen(&ctx, &dir);
let id = screen.state.bots[0].id;
let now = crate::model::now_ms();
let long_ago = now - ASK_BEFORE_AGAIN_MS - 5 * 60_000;
for (n, text) in ["到了的", "沒到的"].into_iter().enumerate() {
screen.mirror_queue(Job::Send { bot: id, id: format!("x-{n}"), text: text.into(), atts: vec![], memories: None, typed: true, uploaded: vec![] });
let mut q = screen.mir.queue.lock().unwrap();
(q.items[n].first, q.items[n].tried) = (long_ago, now - 60_000);
}
assert!(!screen.mirror_unqueue("send:x-1"), "it may be at the brain: not taken back");
// The sending thread doesn't try it: it asks the window to look.
let q = screen.mir.queue.clone();
let pauses = std::cell::Cell::new(0);
let out = deliver(&q, "send:x-0", &crate::model::now_ms, &mut |_: &mut Job| -> Result<Value, (bool, String)> { panic!("sent blind") }, &|| true, &|| pauses.get() < 3, &|_| pauses.set(pauses.get() + 1));
assert!(out.is_none());
q.lock().unwrap().items[1].check = true;
// The brain's chat (as an answer after the last try brought it) has the first — it
// arrived with the first try, long before the last — and not the second.
screen.state.bot_mut(id).unwrap().messages.push(Message { at: long_ago + 2_000, ..Message::user("到了的") });
screen.mir.online = true;
screen.mir.synced_ms = now;
screen.mirror_check_queue();
let left = screen.mirror_waiting(id);
assert_eq!(left.len(), 1);
assert!(matches!(&left[0].job, Job::Send { text, .. } if text == "沒到的"));
assert!(!left[0].check && left[0].tried == 0 && left[0].first == 0, "it goes again");
assert!(screen.mirror_unqueue("send:x-1"), "known not to be there: it can be taken back");
let _ = std::fs::remove_dir_all(&dir);
}
/// The brain answers all along, yet a message can't go (a file too big for the line, the
/// brain's disk full): after GIVE_UP_AFTER tries it is given up and said so — the queue isn't
/// stuck behind it. A line that only drops (the brain out of reach between tries) waits on.
#[test]
fn a_job_that_never_goes_while_the_brain_answers_is_given_up() {
let q = Mutex::new(Outq::default());
let job = Job::Send { bot: 1, id: "big".into(), text: "看這個".into(), atts: vec![], memories: None, typed: true, uploaded: vec![] };
q.lock().unwrap().items.push(Queued { job, at: 0, tried: 0, first: 0, trying: false, check: false });
let tries = std::cell::Cell::new(0u32);
let up = std::cell::Cell::new(true);
let mut go = |_: &mut Job| -> Result<Value, (bool, String)> {
tries.set(tries.get() + 1);
// (Out of reach once, midway: the count starts over.)
if tries.get() == 10 {
up.set(false);
}
Err((true, "逾時".into()))
};
let out = deliver(&q, "send:big", &crate::model::now_ms, &mut go, &|| up.get(), &|| true, &|f| if f == 0 { up.set(true) });
assert!(matches!(out, Some((_, Err(_)))));
assert_eq!(tries.get(), 10 + GIVE_UP_AFTER, "the line's failures before it was out of reach don't count");
assert!(q.lock().unwrap().items.is_empty());
// Files already up aren't sent again on the next try.
let mut sent = Job::Send { bot: 1, id: "f".into(), text: String::new(), atts: vec![crate::attach::Attachment { name: "a.png".into(), path: "/nonexistent/a.png".into(), image: true, bytes: 1, ..Default::default() }], memories: None, typed: true, uploaded: vec!["/brain/a.png".into()] };
let s = crate::remote::Settings::default();
let r = try_job(&s, "c", &mut sent);
assert!(r.is_err_and(|(_, e)| !e.contains("讀不到")), "the file here wasn't read again");
}
/// 沒網路照樣能改設定: an edit made while the brain is out of reach waits in the queue; the
/// brain's newer settings, when they come, keep it on top (nothing the brain changed
/// meanwhile is undone), and once it is sent the brain has both.
#[test]
fn an_edit_made_offline_lands_on_the_brains_newer_settings() {
let ctx = egui::Context::default();
let dir = fresh_dir("offline-edit");
let (mut brain, mut screen) = brain_and_screen(&ctx, &dir);
let (a, b) = (brain.state.bots[0].id, brain.state.bots[1].id);
screen.mir.online = false;
screen.mir.down_since = Some(Instant::now() - std::time::Duration::from_secs(30));
screen.state.bot_mut(a).unwrap().name = "螢幕上改的".into();
screen.mirror_save();
let edits: Vec<Queued> = screen.mir.queue.lock().unwrap().items.clone();
assert_eq!(edits.len(), 1);
// Meanwhile, at the brain.
brain.state.bot_mut(b).unwrap().name = "大腦上改的".into();
// Back: the brain's answer comes before the edit has gone.
screen.mir.online = true;
let since = screen.mir.applied;
screen.mirror_apply(brain.brain_pull("screen-1", since, false, false));
let names = |app: &App| (app.state.bot(a).unwrap().name.clone(), app.state.bot(b).unwrap().name.clone());
assert_eq!(names(&screen), ("螢幕上改的".into(), "大腦上改的".into()), "the edit stays on top of the brain's newer settings");
// The edit goes (twice: its answer lost the first time) — done once.
let mut go = |job: &mut Job| {
let Job::Edit { seq, ops } = job else { panic!() };
Ok(brain.brain_edit(&json!({"ops": ops, "client": "screen-1", "seq": seq})))
};
let q = screen.mir.queue.clone();
deliver(&q, &edits[0].key(), &crate::model::now_ms, &mut go, &|| true, &|| true, &|_| {}).unwrap().1.unwrap();
let Job::Edit { seq, ops } = &edits[0].job else { panic!() };
assert_eq!(brain.brain_edit(&json!({"ops": ops, "client": "screen-1", "seq": seq}))["again"], true);
assert_eq!(names(&brain), ("螢幕上改的".into(), "大腦上改的".into()));
screen.mirror_apply(brain.brain_pull("screen-1", screen.mir.applied, false, false));
assert_eq!(names(&screen), names(&brain));
assert!(screen.mir.pending.lock().unwrap().is_empty(), "the brain has it: no longer laid on top");
let _ = std::fs::remove_dir_all(&dir);
}
/// 完成宣稱關卡: a reply marked on the brain changes its fingerprint, so the screens hear of it
/// (and get the mark with the message).
#[test]
fn a_replys_check_reaches_the_screens() {
let m = Message::assistant("已傳好了", "");
let before = msg_sig(&m);
let marked = Message { check: vec![crate::claims::Flag { kind: crate::claims::Kind::NoFile, why: "沒有檔案".into() }], ..m };
assert_ne!(msg_sig(&marked), before);
let back: Message = serde_json::from_value(serde_json::to_value(&marked).unwrap()).unwrap();
assert_eq!(back.check, marked.check);
}
/// 交付確認 on a screen computer: the brain's file is shown from a local copy, but keeps its
/// id; what the screen saw goes to the brain by that id (named there, by who asked); a
/// device's word on a file changes the message's fingerprint, so the screens hear of it.
#[test]
fn a_screen_keeps_the_files_id_and_tells_the_brain() {
let ctx = egui::Context::default();
let mut app = App::new(&ctx, Some(std::env::temp_dir().join("anybot-screen-seen.png")));
let bot = app.state.bots[0].id;
let a = crate::attach::Attachment { name: "貓.png".into(), path: "/brain/attachments/bot-1/x-貓.png".into(), image: true, id: "a1b2c3d4e5f6".into(), ..Default::default() };
let mut msgs = vec![Message { attachments: vec![a.clone()], ..Message::assistant("好了", "") }];
let before = msg_sig(&msgs[0]);
app.mirror_files(bot, &mut msgs);
let got = &msgs[0].attachments[0];
assert!(got.path != a.path && got.id == a.id, "{} {}", got.path, got.id);
msgs[0].attachments[0].note_seen("iPhone", crate::attach::SeenKind::Shown, "", 1);
assert_ne!(msg_sig(&msgs[0]), before);
app.mir.on = true;
app.mir.online = true;
// Told the brain (not kept here: the brain keeps it), once; not while it can't be reached.
app.mir.online = false;
app.delivery_here(&ctx, bot, "a1b2c3d4e5f6", crate::attach::SeenKind::Shown, "");
assert!(app.seen_told.is_empty());
app.mir.online = true;
app.delivery_here(&ctx, bot, "a1b2c3d4e5f6", crate::attach::SeenKind::Shown, "");
assert!(app.seen_told.contains(&("a1b2c3d4e5f6".to_string(), crate::attach::SeenKind::Shown)));
assert!(app.state.bot(bot).unwrap().messages.iter().all(|m| m.attachments.iter().all(|a| a.seen.is_empty())));
}
/// 任務: a screen shows the list its brain worked out — sent when it changes, not again.
#[test]
fn a_screen_gets_the_brains_task_list() {
let ctx = egui::Context::default();
let mut brain = App::new(&ctx, Some(std::env::temp_dir().join("anybot-screen-tasks-brain.png")));
let id = brain.state.bots[0].id;
brain.state.bot_mut(id).unwrap().messages = vec![Message { at: 1_000, ..Message::user("整理報表") }].into();
brain.streams.insert(id, Live { cancel: Arc::new(AtomicBool::new(false)), started: Instant::now(), last: Instant::now(), produced: true, status: None, paused: false, paused_at: None, unattended: false, steer: Default::default(), direct: Arc::new(AtomicBool::new(false)), turn_id: "t".into(), turn: 0 });
brain.tasks_tick(true);
let pulled = brain.brain_pull_at(5, "screen-tasks", 0, false, false);
let mine = pulled["tasks"].as_array().unwrap().iter().find(|t| t["bot"] == id).cloned().unwrap();
assert_eq!((mine["status"].as_str(), mine["text"].as_str()), (Some("running"), Some("整理報表")));
assert!(brain.brain_pull_at(6, "screen-tasks", 5, false, false).get("tasks").is_none(), "an unchanged list isn't sent again");
let mut screen = App::new(&ctx, Some(std::env::temp_dir().join("anybot-screen-tasks.png")));
screen.mir.on = true;
screen.mirror_apply(json!({"tasks": pulled["tasks"].clone()}));
assert_eq!(screen.tasks_list().len(), pulled["tasks"].as_array().unwrap().len());
assert!(screen.tasks_list().iter().any(|t| t.bot == id && t.status == crate::tasks::Status::Running));
}
/// 螢幕電腦上回答的卡帶著大腦給那張卡的 key(.claude/skills/verify-approval-routing 的
/// ScreenRefreshes → YouAnswerOnScreen → BrainTakesAnswer):大腦只把它交給那張卡。以前
/// 不帶,大腦交給那時候在等的卡(F1)。
#[test]
fn a_screen_answers_only_the_card_it_shows() {
let ctx = egui::Context::default();
let mut brain = App::new(&ctx, Some(std::env::temp_dir().join("anybot-screen-key-brain.png")));
let id = brain.state.bots[0].id;
let card = |app: &mut App, reason: &str, key: &str| {
let (tx, rx) = channel();
app.approvals.insert(id, Approval { call_id: "call_0".into(), tool: "shell".into(), reason: reason.into(), grant: "rm".into(), reply: tx, kind: ApprovalKind::Action });
app.ask_keys.insert(id, key.into());
rx
};
let first = card(&mut brain, "執行指令:ls", "k1");
// ScreenRefreshes:螢幕電腦拿到大腦的 approvals(和每張卡的 key)。
let pulled = brain.brain_pull("screen-test", 0, false, false);
// (The demo data has another bot's card too.)
let ours = pulled["approvals"].as_array().into_iter().flatten().find(|a| a["bot"] == id).cloned().unwrap_or_default();
assert_eq!(ours["key"], "k1", "{}", pulled["approvals"]);
let mut screen = App::new(&ctx, Some(std::env::temp_dir().join("anybot-screen-key-screen.png")));
screen.mir.on = true;
screen.mir.online = true;
let (otx, orx) = channel();
screen.mir.outbox = Some(otx);
screen.mirror_apply(json!({"approvals": pulled["approvals"].clone()}));
assert!(screen.approvals.contains_key(&id) && screen.mir.keys.get(&id).map(String::as_str) == Some("k1"));
// 大腦那邊,第一張卡在電腦上回答了,第二張(同一個 call_0)在等。
brain.answer(&ctx, id, ApprovalAnswer::Once);
assert_eq!(first.try_recv(), Ok(ApprovalAnswer::Once));
let second = card(&mut brain, "執行指令:rm -rf ~/Documents/報告", "k2");
// YouAnswerOnScreen:螢幕上還是第一張,按「一律允許」。
screen.answer(&ctx, id, ApprovalAnswer::Always("rm".into()));
let body = match orx.try_recv() {
Ok(Out::Act(b)) => b,
_ => panic!("the brain wasn't told"),
};
assert_eq!(body["call"], "k1", "{body}");
// BrainTakesAnswer:api/sync/act 的 answer 照 remote.rs 變成 Cmd::Answer。
let as_sent = |b: &Value| crate::remote::Cmd::Answer { bot: id, answer: b["answer"].as_str().unwrap_or("reject").into(), text: b["text"].as_str().unwrap_or("").into(), call: b["call"].as_str().unwrap_or("").into(), notice: b["from"].as_str() == Some("notice"), screen: true };
brain.remote_cmd(&ctx, as_sent(&body));
assert!(second.try_recv().is_err() && brain.state.bot(id).unwrap().allow_rules.is_empty(), "the screen showed ls, not rm -rf");
// 螢幕同步到第二張以後,它的回答才算數。
screen.mirror_apply(json!({"approvals": brain.brain_pull("screen-test", 0, false, false)["approvals"].clone()}));
screen.answer(&ctx, id, ApprovalAnswer::Reject);
let body = match orx.try_recv() {
Ok(Out::Act(b)) => b,
_ => panic!("the brain wasn't told"),
};
brain.remote_cmd(&ctx, as_sent(&body));
assert_eq!(second.try_recv(), Ok(ApprovalAnswer::Reject));
}
/// The brain asks the same thing again (same call_0, same words) while the screen still
/// shows the first card: only the brain's key tells the two apart. The screen takes the new
/// key as its own card's (ask_keys, which its Enter/Esc and its own notifications go by) in
/// step with mir.keys, starts the new card's wait for keys over, and answers with that key.
#[test]
fn a_screen_keeps_its_cards_key_in_step_with_the_brains() {
let ctx = egui::Context::default();
let mut brain = App::new(&ctx, Some(std::env::temp_dir().join("anybot-screen-step-brain.png")));
let id = brain.state.bots[0].id;
let card = |app: &mut App, key: &str| {
let (tx, rx) = channel();
app.approvals.insert(id, 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(id, key.into());
rx
};
let mut screen = App::new(&ctx, Some(std::env::temp_dir().join("anybot-screen-step-screen.png")));
screen.mir.on = true;
screen.mir.online = true;
screen.ctx_handle = Some(ctx.clone());
let (otx, orx) = channel();
screen.mir.outbox = Some(otx);
let first = card(&mut brain, "k1");
screen.mirror_apply(json!({"approvals": brain.brain_pull("screen-step", 0, false, false)["approvals"].clone()}));
assert_eq!((screen.ask_keys.get(&id).map(String::as_str), screen.mir.keys.get(&id).map(String::as_str)), (Some("k1"), Some("k1")));
// The card has been up a while on the screen (its Enter would answer it now).
screen.ask_shown.insert(id, Instant::now() - std::time::Duration::from_secs(2));
// At the brain: answered on its own window, and the same step asks again.
brain.answer(&ctx, id, ApprovalAnswer::Once);
assert_eq!(first.try_recv(), Ok(ApprovalAnswer::Once));
let second = card(&mut brain, "k2");
screen.mirror_apply(json!({"approvals": brain.brain_pull("screen-step", 0, false, false)["approvals"].clone()}));
assert_eq!((screen.ask_keys.get(&id).map(String::as_str), screen.mir.keys.get(&id).map(String::as_str)), (Some("k2"), Some("k2")), "the screen's card is the new one");
assert!(!screen.ask_shown.contains_key(&id), "a new card waits its own moment before Enter/Esc");
screen.answer(&ctx, id, ApprovalAnswer::Once);
let body = match orx.try_recv() {
Ok(Out::Act(b)) => b,
_ => panic!("the brain wasn't told"),
};
assert_eq!(body["call"], "k2", "{body}");
brain.remote_cmd(&ctx, crate::remote::Cmd::Answer { bot: id, answer: body["answer"].as_str().unwrap_or("").into(), text: String::new(), call: body["call"].as_str().unwrap_or("").into(), notice: false, screen: true });
assert_eq!(second.try_recv(), Ok(ApprovalAnswer::Once));
}
/// 每次更新強調色都變回橘色:外觀是這台自己的,連到大腦時、大腦的設定來時、存檔時都用這台的。
/// Every key on the two lists is set off its default here and must come across — a key added
/// to a list but not to copy_own (or not here) fails.
#[test]
fn a_screen_keeps_its_own_look_and_settings() {
let mut from = State::first_run();
from.remote.host_name = "這台".into();
from.theme = crate::model::Theme::Dark;
from.accent = crate::model::Accent::BotColor;
from.sidebar_collapsed = !from.sidebar_collapsed;
from.sidebar_width += 40.0;
from.machine_label = "工作機".into();
from.local_execution = !from.local_execution;
from.local_never = !from.local_never;
from.messages_send = !from.messages_send;
from.messages_no_ask = !from.messages_no_ask;
from.shell_tone = 0.25;
from.shell_accent = "indigo".into();
from.shell_contrast = 0.75;
from.dense = !from.dense;
from.celebrate = !from.celebrate;
let (base, want) = (serde_json::to_value(State::first_run()).unwrap(), serde_json::to_value(&from).unwrap());
let mut to = State::first_run();
copy_own(&mut to, &from);
let got = serde_json::to_value(&to).unwrap();
for k in LOCAL_KEYS.iter().chain(LOOK_KEYS).filter(|k| **k != "selected") {
assert_ne!(want[k], base[k], "{k}: set it off its default in this test");
assert_eq!(got[k], want[k], "{k} is this computer's own, but copy_own doesn't copy it");
}
}
#[test]
fn a_screen_reads_only_turns_it_saw_end() {
let turn = |at: i64, outcome| TurnSettlement { turn_id: format!("t{at}"), outcome, settled_at_ms: at };
let now = 1_000_000;
let mut seen = HashMap::new();
// Connecting: turns that ended before are not read out.
let (a, b) = (turn(now - 5_000, TurnOutcome::Success), turn(now - 9_000, TurnOutcome::Success));
assert!(just_finished(&mut seen, [(1, Some(&a)), (2, Some(&b)), (3, None)], now).is_empty());
// Nothing new: nothing read (every update says the same).
assert!(just_finished(&mut seen, [(1, Some(&a)), (2, Some(&b))], now).is_empty());
// Bot 1 finished again: read; bot 2 failed: not.
let (a2, b2) = (turn(now - 100, TurnOutcome::Success), turn(now - 50, TurnOutcome::Error));
assert_eq!(just_finished(&mut seen, [(1, Some(&a2)), (2, Some(&b2))], now), vec![1]);
// Long ago (heard only after being away): not read.
let a3 = turn(now - 600_000 + 1, TurnOutcome::Success);
let mut seen2 = HashMap::from([(1, now - 700_000)]);
assert!(just_finished(&mut seen2, [(1, Some(&a3))], now).is_empty());
}
/// A screen whose last answer was lost on the way (the line dropped) asks again from what it
/// still holds: the brain sends only what changed since then — not every chat again.
#[test]
fn a_lost_answer_costs_only_what_changed() {
let ctx = egui::Context::default();
let mut brain = App::new(&ctx, Some(std::env::temp_dir().join("anybot-lost-answer.png")));
let id = brain.state.bots[0].id;
let first = brain.brain_pull_at(10, "lost", 0, false, false);
assert!(first["bots"].as_array().unwrap().len() >= 2, "a new screen gets everything");
let n = brain.state.bots[0].messages.len();
brain.state.bot_mut(id).unwrap().messages.push(Message::user("新的一句"));
let second = brain.brain_pull_at(11, "lost", 10, false, false);
assert_eq!(second["bots"].as_array().unwrap().len(), 1);
// That answer (version 11) never arrived: the screen asks again from 10.
let again = brain.brain_pull_at(12, "lost", 10, false, false);
let bots = again["bots"].as_array().unwrap();
assert_eq!(bots.len(), 1, "only the bot that changed: {again}");
assert_eq!(bots[0]["id"], id);
assert_eq!(bots[0]["from"], n, "from the new message on, not from the start");
assert!(again.get("config").is_none(), "the settings didn't change");
// A screen that just started from its copy gets the settings all the same.
let fresh = brain.brain_pull_at(13, "lost", 12, true, false);
assert!(fresh["config"].is_object());
// An answer lost that carried no new version (a long poll that ran out): the next pull
// says so (retry), and the change comes again.
let m = brain.state.bots[0].messages.len();
brain.state.bot_mut(id).unwrap().messages.push(Message::user("又一句"));
let lost = brain.brain_pull_at(13, "lost", 13, false, false);
assert_eq!(lost["bots"][0]["from"], m);
let back = brain.brain_pull_at(13, "lost", 13, false, true);
assert_eq!(back["bots"].as_array().map(Vec::len), Some(1), "{back}");
assert_eq!(back["bots"][0]["from"], m, "the lost change again");
}
/// Away from the brain, the next numbers may be given at the brain meanwhile (a new bot
/// elsewhere, a 支線). A bot or routine made on the screen while away is numbered far past
/// them, so the screen's later edits (and messages) by that number reach its own, never the
/// brain's; and the brain counts on past it.
#[test]
fn a_screen_away_doesnt_take_the_brains_numbers() {
let ctx = egui::Context::default();
let dir = fresh_dir("numbers");
let (mut brain, mut screen) = brain_and_screen(&ctx, &dir);
let (n, r) = (brain.state.next_id, brain.state.next_routine_id);
screen.mir.online = false;
screen.mirror_spare_numbers();
screen.mirror_save();
assert!(screen.mir.queue.lock().unwrap().items.is_empty(), "only moving the count on isn't an edit");
// Away: a new bot, renamed after; a new routine on the first bot.
let mine = screen.state.next_id;
let mut b = screen.state.bots[0].clone();
(b.id, b.name, b.routines) = (mine, "螢幕上新增的".into(), vec![]);
screen.state.bots.push(b);
screen.state.next_id += 1;
screen.mirror_save();
screen.state.bot_mut(mine).unwrap().name = "螢幕上改過名的".into();
screen.mirror_save();
let first = screen.state.bots[0].id;
let rid = screen.state.next_routine_id;
let mut routine = brain.state.bots.iter().flat_map(|b| &b.routines).next().expect("the demo has a routine").clone();
(routine.id, routine.title) = (rid, "螢幕的".into());
screen.state.bot_mut(first).unwrap().routines.push(routine.clone());
screen.mirror_save();
assert!(mine >= n + 1000 && rid >= r + 1000, "{mine} {rid}");
// Meanwhile at the brain: bot n and routine r.
let mut theirs = brain.state.bots[0].clone();
(theirs.id, theirs.name) = (n, "大腦這邊新的".into());
brain.state.bots.push(theirs);
(routine.id, routine.title) = (r, "大腦的".into());
brain.state.bot_mut(first).unwrap().routines.push(routine);
(brain.state.next_id, brain.state.next_routine_id) = (n + 1, r + 1);
// Back: the edits go.
// (AnyBot closed and opened again, still away: the next numbers are past those made.)
let mut again = screen_in(&ctx, &dir);
again.mirror_spare_numbers();
assert!(again.state.next_id > mine && again.state.next_routine_id > rid, "{} {}", again.state.next_id, again.state.next_routine_id);
let jobs: Vec<Queued> = screen.mir.queue.lock().unwrap().items.clone();
for j in &jobs {
let Job::Edit { seq, ops } = &j.job else { panic!() };
brain.brain_edit(&json!({"ops": ops, "client": "screen-1", "seq": seq}));
}
assert_eq!(brain.state.bot(n).unwrap().name, "大腦這邊新的", "the brain's bot untouched");
assert_eq!(brain.state.bot(mine).unwrap().name, "螢幕上改過名的");
let titles: Vec<(u64, String)> = brain.state.bot(first).unwrap().routines.iter().map(|x| (x.id, x.title.clone())).collect();
assert!(titles.contains(&(r, "大腦的".into())) && titles.contains(&(rid, "螢幕的".into())), "{titles:?}");
assert!(brain.state.next_id > mine && brain.state.next_routine_id > rid, "the brain counts on past them");
let _ = std::fs::remove_dir_all(&dir);
}
/// The same edit sent again (its answer was lost): done once — 「新增 Bot」 twice was two bots.
#[test]
fn an_edit_sent_twice_is_done_once() {
let ctx = egui::Context::default();
let mut brain = App::new(&ctx, Some(std::env::temp_dir().join("anybot-edit-twice.png")));
let mut bot = serde_json::to_value(&brain.state.bots[0]).unwrap();
bot["id"] = json!(0);
bot["name"] = json!("新的 Bot");
let before = brain.state.bots.len();
let edit = json!({"ops": [{"op": "bot_add", "bot": bot}], "client": "twice", "seq": 7});
assert_eq!(brain.brain_edit(&edit)["applied"], 1);
assert_eq!(brain.brain_edit(&edit)["again"], true);
assert_eq!(brain.state.bots.len(), before + 1);
let next = json!({"ops": [{"op": "bot_read", "id": brain.state.bots[0].id}], "client": "twice", "seq": 8});
assert_eq!(brain.brain_edit(&next)["applied"], 1, "the next number is taken as usual");
}
#[test]
fn edits_become_small_operations() {
let base = json!({"theme": "light", "folders": ["a"], "bots": [{"id": 1, "name": "A", "unread": true}, {"id": 2, "name": "B"}]});
let cur = json!({"theme": "dark", "folders": ["a", "b"], "bots": [{"id": 1, "name": "A2", "unread": false}, {"id": 3, "name": "C"}]});
let ops = diff_ops(&base, &cur);
// theme is this computer's own; folders changed.
assert!(ops.iter().any(|o| o["op"] == "patch" && o["key"] == "folders" && o["patch"]["list"]["put"] == json!(["b"])));
assert!(!ops.iter().any(|o| o["key"] == "theme"));
assert!(ops.iter().any(|o| o["op"] == "bot_set" && o["key"] == "name" && o["value"] == "A2"));
assert!(ops.iter().any(|o| o["op"] == "bot_read" && o["id"] == 1));
assert!(ops.iter().any(|o| o["op"] == "bot_add" && o["bot"]["id"] == 3));
assert!(ops.iter().any(|o| o["op"] == "bot_del" && o["id"] == 2));
}
#[test]
fn keys_stay_on_the_brain() {
let mut v = json!({"remote": {"host_token": "x"}, "providers": {"xai": {"api_key": "sk-1"}, "openai": {"api_key": ""}}, "channels": [{"id": 4, "token": "t"}], "voice": {"listen": {"kind": "eleven_labs", "api_key": "el-1"}, "speak": {"kind": "xai", "api_key": ""}}});
let old = v.clone();
redact(&mut v);
assert_eq!((v["voice"]["listen"]["api_key"].as_str(), v["voice"]["speak"]["api_key"].as_str()), (Some(REDACTED), Some("")));
let mut voice = v["voice"].clone();
unredact(&mut voice, &old["voice"]);
assert_eq!(voice["listen"]["api_key"], "el-1");
assert!(v.get("remote").is_none());
assert_eq!(v["providers"]["xai"]["api_key"], REDACTED);
assert_eq!(v["providers"]["openai"]["api_key"], "");
assert_eq!(v["channels"][0]["token"], REDACTED);
// An edit that kept the stand-in keeps the real key.
let mut edit = v["providers"].clone();
edit["openai"]["api_key"] = json!("sk-new");
unredact(&mut edit, &old["providers"]);
assert_eq!(edit["xai"]["api_key"], "sk-1");
assert_eq!(edit["openai"]["api_key"], "sk-new");
let mut ch = v["channels"].clone();
unredact(&mut ch, &old["channels"]);
assert_eq!(ch[0]["token"], "t");
// Secrets are found by name only: a renamed item (the brain wasn't told) gets none — never
// another item's that happens to have the same address.
let servers = json!([{"name": "a", "url": "https://x.example/mcp", "password": "pa"}, {"name": "b", "url": "https://x.example/mcp", "password": "pb"}]);
let mut guessed = json!([{"name": "c", "url": "https://x.example/mcp", "password": REDACTED}]);
unredact(&mut guessed, &servers);
assert_eq!(guessed[0]["password"], "");
// Changing base_url while keeping REDACTED must NEVER send the brain's real key to the new server.
let mut exfil = v["providers"].clone();
exfil["xai"]["base_url"] = json!("https://evil.example/v1");
unredact(&mut exfil, &old["providers"]);
assert_eq!(exfil["xai"]["api_key"], "");
// Routine trigger tokens are redacted too.
let mut with_trig = json!({"bots": [{"id": 1, "routines": [{"id": 9, "trigger": {"kind": "github", "token": "ghp_secret"}}]}]});
redact(&mut with_trig);
assert_eq!(with_trig["bots"][0]["routines"][0]["trigger"]["token"], REDACTED);
}
#[test]
fn edits_replay_on_a_newer_copy() {
let base = json!({"folders": ["a"], "bots": [{"id": 1, "name": "A", "unread": true}, {"id": 2, "name": "B"}]});
let cur = json!({"folders": ["a", "b"], "bots": [{"id": 2, "name": "B"}, {"id": 1, "name": "A2", "unread": false}, {"id": 3, "name": "C"}]});
let ops = diff_ops(&base, &cur);
let mut again = base.clone();
apply_ops(&mut again, &ops);
assert_eq!(again, cur);
// The brain meanwhile renamed bot 2: the screen's own edit stays, the brain's shows too.
let mut newer = json!({"folders": ["a"], "bots": [{"id": 1, "name": "A", "unread": true}, {"id": 2, "name": "B from brain"}]});
apply_ops(&mut newer, &ops);
assert_eq!(newer["bots"][1]["name"], "A2");
assert_eq!(newer["bots"][0]["name"], "B from brain");
assert_eq!(newer["folders"], json!(["a", "b"]));
}
#[test]
fn an_old_copy_cant_make_a_routine_run_twice() {
let brain = json!([{"id": 7, "schedule": "daily", "trigger": null, "paused": false, "last_run": 200, "next_run": 300}]);
let mut edit = json!([{"id": 7, "title": "new", "schedule": "daily", "trigger": null, "paused": false, "last_run": 100, "next_run": 150}]);
keep_run_times(&mut edit, &brain);
assert_eq!(edit[0]["last_run"], 200);
assert_eq!(edit[0]["next_run"], 300);
assert_eq!(edit[0]["title"], "new");
// A new schedule gets worked out again.
let mut moved = json!([{"id": 7, "schedule": "weekly", "trigger": null, "paused": false, "last_run": 100, "next_run": null}]);
keep_run_times(&mut moved, &brain);
assert_eq!(moved[0]["last_run"], 200);
assert!(moved[0]["next_run"].is_null());
}
#[test]
fn failures_read_as_words_not_codes() {
let w = remote::why_refused(502, &Value::Null, "大腦");
assert!(!w.contains("502") && w.contains("帳號伺服器"));
let off = remote::why_refused(503, &json!({"error": "那台 AnyBot 目前離線(電腦關機、睡眠,或 AnyBot 沒開)"}), "大腦");
assert!(off.starts_with("大腦目前離線"));
assert!(remote::why_refused(401, &Value::Null, "大腦").contains("重新登入"));
assert!(remote::why_unreachable(&ureq::Error::HostNotFound).contains("網路"));
}
#[test]
fn two_computers_edit_one_list_without_undoing_each_other() {
let base = json!({"skills": [{"name": "a", "on": true}, {"name": "b", "on": true}], "providers": {"xai": {"model": "1"}, "openai": {"model": "1"}}, "bots": [{"id": 1, "memories": ["x", "y"]}]});
// Laptop turns skill a off, changes xai, forgets memory x.
let mut laptop = base.clone();
laptop["skills"][0]["on"] = json!(false);
laptop["providers"]["xai"]["model"] = json!("2");
laptop["bots"][0]["memories"] = json!(["y"]);
// Meanwhile the desk computer turned skill b off, changed openai, and the bot learned z.
let mut brain = base.clone();
brain["skills"][1]["on"] = json!(false);
brain["skills"].as_array_mut().unwrap().push(json!({"name": "c", "on": true}));
brain["providers"]["openai"]["model"] = json!("3");
brain["bots"][0]["memories"] = json!(["x", "y", "z"]);
let ops = diff_ops(&base, &laptop);
assert!(ops.iter().all(|o| o["op"] != "set" || o["key"] != "skills"), "{ops:?}");
apply_ops(&mut brain, &ops);
assert_eq!(brain["skills"], json!([{"name": "a", "on": false}, {"name": "b", "on": false}, {"name": "c", "on": true}]));
assert_eq!(brain["providers"], json!({"xai": {"model": "2"}, "openai": {"model": "3"}}));
assert_eq!(brain["bots"][0]["memories"], json!(["y", "z"]));
}
/// A skill folder named on a screen goes up read here (the brain can't see this disk); an
/// address, a market name or a delete goes as it is.
#[test]
fn a_skill_folder_here_goes_up_whole() {
let src = std::env::temp_dir().join(format!("anybot-screen-pkg-{}", std::process::id()));
std::fs::create_dir_all(src.join("references")).unwrap();
std::fs::write(src.join("SKILL.md"), "---\nname: 週報\ndescription: 整理每週進度\n---\n\n照 references/a.md 寫\n").unwrap();
std::fs::write(src.join("references/a.md"), "# 格式").unwrap();
let b = skill_request(json!({"local": src.display().to_string()})).unwrap();
assert!(b["package"]["skill_md"].as_str().unwrap().contains("name: 週報"));
assert_eq!(b["package"]["files"][0]["path"], "references/a.md");
assert!(b.get("local").is_none(), "no path of this computer goes to the brain");
std::fs::remove_dir_all(&src).unwrap();
for as_is in [json!({"install": "https://github.com/anthropics/skills/tree/main/skills/pdf"}), json!({"builtin": "pdf"}), json!({"name": "週報", "remove": true})] {
assert_eq!(skill_request(as_is.clone()).unwrap(), as_is);
}
assert!(skill_request(json!({"local": "/nonexistent/anybot-skill"})).is_err());
}
#[test]
fn lists_without_names_are_sent_whole() {
let p = patch_of(&json!([[1], [2]]), &json!([[2]]));
assert_eq!(p, json!({"value": [[2]]}));
let mut cur = json!([{"id": 1}, {"id": 2}]);
apply_patch(&mut cur, &patch_of(&json!([{"id": 1}, {"id": 2}]), &json!([{"id": 2}, {"id": 1}])));
assert_eq!(cur, json!([{"id": 2}, {"id": 1}]));
}
/// 連接器 on a screen: its switch decides whether the brain runs the server. Off, the brain
/// stops it and its tools are gone; on again, the brain starts it with the 密碼 it kept (a
/// screen only ever holds the stand-in).
#[test]
fn a_screens_switch_turns_the_brains_connector_off_and_on() {
let _one = crate::mcp::test_lock();
let ctx = egui::Context::default();
let mut brain = App::new(&ctx, Some(std::env::temp_dir().join("anybot-brain-mcp-test.png")));
let mut server = crate::mcp::fake_server("screen-switch", 0);
server.username = "amy".into();
server.password = "s3cret".into();
brain.state.mcp_servers = vec![server];
let running = |app: &App| crate::mcp::sync(&app.state.mcp_servers).is_empty() && crate::mcp::status().contains_key("screen-switch");
assert!(running(&brain));
// What a screen holds: the brain's settings with the secrets hidden.
let screen_view = |app: &App| {
let mut top = json!({"mcp_servers": serde_json::to_value(&app.state.mcp_servers).unwrap()});
redact(&mut top);
top
};
let base = screen_view(&brain);
assert_eq!(base["mcp_servers"][0]["password"], REDACTED);
assert!(!base.to_string().contains("s3cret"));
// The switch goes off on the screen.
let mut off = base.clone();
off["mcp_servers"][0]["enabled"] = json!(false);
let r = brain.brain_edit(&json!({"ops": diff_ops(&base, &off)}));
assert_eq!(r["applied"], 1, "{r}");
assert!(!brain.state.mcp_servers[0].enabled);
assert_eq!(brain.state.mcp_servers[0].password, "s3cret", "the brain's own password stays");
assert!(!running(&brain), "off: the brain stopped it");
assert!(crate::mcp::tools().iter().all(|t| t.server != "screen-switch"));
// And on again (from what the screen now holds).
let base = screen_view(&brain);
let mut on = base.clone();
on["mcp_servers"][0]["enabled"] = json!(true);
brain.brain_edit(&json!({"ops": diff_ops(&base, &on)}));
assert!(brain.state.mcp_servers[0].enabled && brain.state.mcp_servers[0].password == "s3cret");
assert!(running(&brain), "on: the brain runs it again");
assert!(crate::mcp::tools().iter().any(|t| t.server == "screen-switch" && t.name == "add"));
// A new 帳號 from the screen keeps the password; a new address drops it (it would
// otherwise be sent to wherever the address now points).
let base = screen_view(&brain);
let mut renamed = base.clone();
renamed["mcp_servers"][0]["username"] = json!("bob");
brain.brain_edit(&json!({"ops": diff_ops(&base, &renamed)}));
assert_eq!((brain.state.mcp_servers[0].username.as_str(), brain.state.mcp_servers[0].password.as_str()), ("bob", "s3cret"));
let base = screen_view(&brain);
let mut moved = base.clone();
moved["mcp_servers"][0]["command"] = json!("somewhere-else");
brain.brain_edit(&json!({"ops": diff_ops(&base, &moved)}));
assert_eq!(brain.state.mcp_servers[0].password, "");
crate::mcp::sync(&[]);
}
}