// 支線 (/btw): the person sends 「/btw 順便查一下…」 and the bot branches. A copy of it — the same // soul, abilities, skills, computers and model, this chat as it stands, and its memories (what // the branch keeps, the main bot keeps) — does that one thing alongside, and reports back here. // // Not getting in each other's way: // - Before it starts, while the main line is working, a quick model reads what the main line is // doing and the new task, and says whether they would clash (the same screen or window, the // same files or data, an account they'd both act on, a result the main line is waiting for). // No clash: it starts now. A clash: it waits for the main line's turn to end, saying why. // - While both work, a screen is one turn's at a time (agent::lease_screen): a step that would // click on a screen another turn is using isn't run, and the bot is told who has it. On the // bots' computer a branch has a temporary screen of its own (cloudbox::branch_screen; its // browser a copy of the main bot's), closed when the branch ends. // - Its report goes to the main line: into the turn that is running (it reads it at its next // step), or into the chat as the branch's words when nothing is running. // // A branch lives in State::branch_bots while it works (found by id, never listed) and is gone // when it ends; its record (Bot::branches) and the chat keep what it did. use super::*; use crate::model::{Branch, BranchState}; /// A clash check on its way: (main bot, branch, (clash, why) once it answers). pub(super) type ClashCheck = (u64, u64, Receiver<(bool, String)>); /// What a report handed to the main line's running turn starts with. pub(super) const REPORT_TAG: &str = "〔支線回報〕"; /// Finished branches a bot keeps the record of (the newest). const KEEP_FINISHED: usize = 20; /// Why a 支線 ended when AnyBot was closed (a clean shutdown; after a crash the restart says it). pub(super) const QUIT_NOTE: &str = "AnyBot 關掉了,這條支線停了"; /// Most branches one bot has open at once. pub(super) const MAX_BRANCHES: usize = 3; /// How often a running branch's card is brought up to date. const LIVE_EVERY: std::time::Duration = std::time::Duration::from_secs(2); /// 「/btw 要做的事」: the words after it (empty for a bare /btw), or None. pub fn command(text: &str) -> Option { let t = text.trim_start(); let rest = t.strip_prefix("/btw").or_else(|| t.strip_prefix("/BTW"))?; (rest.is_empty() || rest.starts_with(char::is_whitespace)).then(|| rest.trim().to_string()) } /// The quick check: would the branch get in the main line's way? const CLASH_SYSTEM: &str = "你判斷兩件工作能不能同時做。主線是一個 Bot 正在做的事;支線是使用者要它開一個分身、同時去做的另一件事。會衝突的情況:兩邊都要操作同一個螢幕或同一個視窗、改同一個檔案或同一份資料、對同一個帳號做會互相影響的事、支線的結果會改掉或推翻主線正在做的東西、支線要等主線的結果才能做。只是查資料、讀東西、在不同的地方做不同的事,就不衝突。只回一行 JSON:{\"conflict\": true 或 false, \"reason\": \"一句話\"}"; /// The check's answer: (clash, why). Unreadable counts as no clash — the screens are guarded /// while they work anyway. pub fn read_clash(text: &str) -> (bool, String) { let j = text.find('{').and_then(|a| text.rfind('}').filter(|b| *b > a).map(|b| &text[a..=b])).and_then(|s| serde_json::from_str::(s).ok()); match j { Some(v) => (v["conflict"].as_bool().unwrap_or(false), v["reason"].as_str().unwrap_or("").trim().to_string()), None => (false, String::new()), } } /// The chat as the branch takes it: what the model reads now, with a turn still running cut /// back to its last finished step (a step asked but not answered can't be sent to a model). pub fn fork_history(msgs: &[Message]) -> Vec { let from = crate::model::model_view_start(msgs); let mut out: Vec = msgs[from..].iter().filter(|m| !m.interrupted && !m.note).cloned().collect(); let answered: std::collections::HashSet = out.iter().filter(|m| m.role == Role::Tool).map(|m| m.tool_call_id.clone()).collect(); let asked: std::collections::HashSet = out.iter().flat_map(|m| m.tool_calls.iter().map(|c| c.id.clone())).collect(); for m in out.iter_mut() { let n = m.tool_calls.len(); m.tool_calls.retain(|c| answered.contains(&c.id)); // (Claude's own blocks would carry the dropped calls; the others stay as they were, so // the branch's first request is the main line's, word for word — the cache holds.) if m.tool_calls.len() != n { m.blocks.clear(); } } out.retain(|m| match m.role { Role::Tool => asked.contains(&m.tool_call_id), Role::Assistant => !m.text.trim().is_empty() || !m.tool_calls.is_empty() || m.summary, _ => true, }); out } impl App { /// 「/btw …」 in `bot_id`'s chat (from the window, a screen or the phone). pub(super) fn btw_command(&mut self, ctx: &egui::Context, bot_id: u64, task: &str, attachments: Vec) { let Some(b) = self.state.bot(bot_id) else { return }; let refuse = if task.is_empty() { Some("用法:/btw 要它順便去做的事。它會開一條支線,帶著這段對話和記憶同時去做,做完回報到這裡。".to_string()) } else if !b.members.is_empty() { Some("群組聊天還不能開支線。".into()) } else if b.branch_of != 0 { Some("支線不能再開支線。".into()) } else if b.branches.iter().filter(|r| r.state.open()).count() >= MAX_BRANCHES { Some(format!("已經有 {MAX_BRANCHES} 條支線在做了,等其中一條做完再開。")) } else { None }; if let Some(why) = refuse { self.goal_note(bot_id, &why); self.dirty = true; return; } // The id the branch will have (taken now: the card and the record carry it). let id = self.state.next_id; self.state.next_id += 1; let now = crate::model::now_ms(); let streaming = self.streams.contains_key(&bot_id); let selected = self.state.selected; if let Some(b) = self.state.bot_mut(bot_id) { b.branches.push(Branch { id, task: task.to_string(), at: now, ..Default::default() }); // The open ones, and the newest finished ones (an older one's card goes with it). let finished = b.branches.iter().filter(|r| !r.state.open()).count(); let mut drop = finished.saturating_sub(KEEP_FINISHED); let mut gone = vec![]; b.branches.retain(|r| { if drop > 0 && !r.state.open() { drop -= 1; gone.push(r.id); return false; } true }); b.messages.retain(|m| !(m.note && gone.contains(&m.branch))); // Its card, where it was asked (while the main line works, above its running reply). let card = Message { note: true, branch: id, attachments, ..Message::assistant(&format!("/btw {task}"), "") }; let at = super::goal_ui::note_index(&b.messages, streaming); b.messages.insert(at, card); if bot_id != selected { b.unread = true; } } self.mark(); if streaming { self.check_clash(ctx, bot_id, id, task); } else { self.start_branch(ctx, bot_id, id); } } /// Ask the bot's quick model whether the branch would get in the main line's way. fn check_clash(&mut self, ctx: &egui::Context, main: u64, id: u64, task: &str) { let Some(b) = self.state.bot(main) else { return }; let from = b.messages.iter().rposition(|m| m.role == Role::User && !m.steer && !m.interrupted && m.branch == 0).unwrap_or(0); let doing = b.messages.get(from).map(|m| m.text.chars().take(1500).collect::()).unwrap_or_default(); let steps: Vec = b.messages[from..].iter().flat_map(|m| m.tool_calls.iter()).rev().take(10).map(|c| format!("- {} {}", crate::remote::tool_label(&c.name), crate::remote::tool_detail(&c.name, &c.args))).collect::>().into_iter().rev().collect(); let brief = format!("主線正在做:{doing}\n\n主線最近的步驟:\n{}\n\n支線要做:{task}", if steps.is_empty() { "(還沒有)".into() } else { steps.join("\n") }); let ps = self.state.provider(b.provider); let model = match b.step_model.trim() { "off" => b.model.clone(), "" => b.provider.quick_model(&b.model).map(String::from).unwrap_or_else(|| b.model.clone()), m => m.to_string(), }; let req = ChatRequest { kind: b.provider, base_url: providers::resolve_base(b.provider, &ps.base_url), api_key: providers::resolve_key_for(b.provider, &ps.api_key, &ps.base_url), model, system: CLASH_SYSTEM.into(), history: vec![Message::user(&brief)], tools: vec![], session: format!("anybot-btw-{id}"), effort: String::new(), }; let (tx, rx) = channel(); self.branch_checks.push((main, id, rx)); let ctx = ctx.clone(); std::thread::spawn(move || { let cancel = AtomicBool::new(false); let verdict = match providers::run_step(&req, &cancel, &|_| {}) { Ok(o) => read_clash(&o.text), Err(_) => (false, String::new()), }; let _ = tx.send(verdict); ctx.request_repaint(); }); } /// The branch's record on its main bot. fn branch_rec(&mut self, main: u64, id: u64) -> Option<&mut Branch> { self.state.bot_mut(main)?.branches.iter_mut().find(|r| r.id == id) } /// Fork the main bot and start the branch's turn. fn start_branch(&mut self, ctx: &egui::Context, main: u64, id: u64) { let Some(m) = self.state.bot(main).cloned() else { return }; let Some(rec) = m.branches.iter().find(|r| r.id == id).cloned() else { return }; let files = m.messages.iter().find(|x| x.branch == id && x.note).map(|x| x.attachments.clone()).unwrap_or_default(); let mut b = m.clone(); b.id = id; b.branch_of = main; b.messages = fork_history(&m.messages).into(); b.messages.push(Message { attachments: files, ..Message::user(&rec.task) }); b.routines.clear(); b.branches.clear(); b.threads.clear(); b.regen_undo.clear(); b.draft.clear(); b.goal = None; // (A 支線 does its one thing now: the main line's plan, being written or followed, isn't its.) b.plan = None; b.pinned = false; b.unread = false; b.last_turn = None; self.state.branch_bots.push(b); if let Some(r) = self.branch_rec(main, id) { r.state = BranchState::Running; r.note.clear(); } self.start_reply(ctx, id); // It couldn't start (no key, no model…): what it said is why. if !self.streams.contains_key(&id) { let why = self.state.bot(id).and_then(|b| b.messages.last()).filter(|m| m.role == Role::Assistant).map(|m| m.text.clone()).unwrap_or_else(|| "沒辦法開始".into()); self.state.branch_bots.retain(|b| b.id != id); if let Some(r) = self.branch_rec(main, id) { r.state = BranchState::Failed; r.note = why; } } self.mark(); } /// Every frame: checks that came back, branches whose main line is free now, live lines. pub(super) fn tick_branches(&mut self, ctx: &egui::Context) { // The clash checks. let mut i = 0; while i < self.branch_checks.len() { let Ok((clash, why)) = self.branch_checks[i].2.try_recv() else { i += 1; continue; }; let (main, id, _) = self.branch_checks.remove(i); let busy = self.streams.contains_key(&main); if clash && busy { if let Some(r) = self.branch_rec(main, id) { r.state = BranchState::Waiting; r.note = if why.is_empty() { "會跟主線正在做的事衝突".into() } else { why }; } self.mark(); } else { self.start_branch(ctx, main, id); } } // Waiting ones whose main line is free now; ones whose bot is gone. let mut start = vec![]; let mut gone = vec![]; for b in &self.state.bots { for r in b.branches.iter().filter(|r| r.state == BranchState::Waiting) { if !self.streams.contains_key(&b.id) { start.push((b.id, r.id)); } } } for b in &self.state.branch_bots { if self.state.bots.iter().all(|m| m.id != b.branch_of) { gone.push(b.id); } } for (main, id) in start { self.start_branch(ctx, main, id); } for id in gone { self.stop(id); self.state.branch_bots.retain(|b| b.id != id); } // What each running branch is doing, for its card (here, on screens, on the phone). if self.branch_live.elapsed() >= LIVE_EVERY { self.branch_live = Instant::now(); let now = ctx.input(|i| i.time); let lines: Vec<(u64, u64, String, usize)> = self .state .branch_bots .iter() .map(|b| { let from = b.messages.iter().rposition(|m| m.role == Role::User && !m.steer).unwrap_or(0); let steps = b.messages[from..].iter().map(|m| m.tool_calls.len()).sum(); (b.branch_of, b.id, self.working_phrase(now, b).unwrap_or_default(), steps) }) .collect(); for (main, id, doing, steps) in lines { if let Some(r) = self.branch_rec(main, id) { if r.doing != doing || r.steps != steps { r.doing = doing; r.steps = steps; self.dirty = true; } } } } } /// A branch's turn has ended: its record, its report to the main line, and it is gone. pub(super) fn branch_settled(&mut self, id: u64, outcome: TurnOutcome) { let Some(b) = self.state.branch_bots.iter().find(|b| b.id == id).cloned() else { return }; let main = b.branch_of; let from = b.messages.iter().rposition(|m| m.role == Role::User && !m.steer).unwrap_or(0); let after = &b.messages[from + 1..]; let said = after.iter().rev().find(|m| m.role == Role::Assistant && !m.note && !m.text.trim().is_empty()).map(|m| m.text.trim().to_string()).unwrap_or_default(); let files: Vec = after.iter().flat_map(|m| m.attachments.iter().cloned()).collect(); // The record of its work: a line a step, and what it said. let mut log = vec![]; for m in after { for c in &m.tool_calls { let mark = match c.status { ToolStatus::Done => "✓", ToolStatus::Failed => "✗", _ => "—", }; log.push(format!("{mark} {} {}", crate::remote::tool_label(&c.name), crate::remote::tool_detail(&c.name, &c.args))); } } log.truncate(120); let (state, note) = match outcome { TurnOutcome::Success => (BranchState::Done, String::new()), // (Closing AnyBot stops every turn: that isn't the person stopping this one.) TurnOutcome::Cancelled if self.quitting => (BranchState::Stopped, QUIT_NOTE.to_string()), TurnOutcome::Cancelled => (BranchState::Stopped, "被停止了".to_string()), _ => (BranchState::Failed, if said.is_empty() { "出錯了".to_string() } else { said.chars().take(300).collect() }), }; let task = self.state.bot(main).and_then(|m| m.branches.iter().find(|r| r.id == id)).map(|r| r.task.clone()).unwrap_or_default(); if let Some(r) = self.branch_rec(main, id) { r.state = state; r.note = note.clone(); r.result = said.clone(); r.log = log; r.doing.clear(); } // Skills it learned are the main bot's. if let (Some(learned), Some(m)) = (b.skills.clone(), self.state.bot_mut(main)) { if let Some(mine) = m.skills.as_mut() { for k in learned { if !mine.contains(&k) { mine.push(k); } } } } self.state.branch_bots.retain(|x| x.id != id); // (Its background commands stop with it: nobody could reach them again. So does its // temporary screen on the bots' computer, with its copy of the browser.) self.forget_bot(id, false); if !self.demo { let key = crate::cloudbox::branch_screen(&crate::cloudbox::screen_of_bot(self.state.home_of(main)), id); if !key.is_empty() { std::thread::spawn(move || crate::cloudbox::close_screen(&key)); } } // The report: into the main line's running turn, or into the chat as the branch's words. if state != BranchState::Stopped { let text = match state { BranchState::Done if said.is_empty() => format!("支線「{task}」做完了,但沒有寫結果。"), BranchState::Done => format!("支線「{task}」做完了:\n{said}"), _ => format!("支線「{task}」沒有做完:{note}"), }; if self.streams.contains_key(&main) { self.queue_branch_report(main, id, format!("{REPORT_TAG}{text}"), files); } else { let selected = self.state.selected; let via = b.messages.iter().rev().find(|m| m.role == Role::Assistant).map(|m| m.via.clone()).unwrap_or_default(); if let Some(m) = self.state.bot_mut(main) { m.messages.push(Message { branch: id, error: state == BranchState::Failed, attachments: files, ..Message::assistant(&text, &via) }); if main != selected { m.unread = true; } } } } self.mark(); } // ---------- the card ---------- /// A branch's card in the main chat: what it was asked, how it stands, its steps, and what /// it found; its approval and its stop button while it works. pub(super) fn branch_card(&mut self, ui: &mut egui::Ui, ctx: &egui::Context, bot: &Bot, m: &Message) { let p = self.pal; let Some(rec) = bot.branches.iter().find(|r| r.id == m.branch).cloned() else { return }; let open_id = egui::Id::unique(("branch-open", bot.id, rec.id)); let mut open = ctx.data(|d| d.get_temp::(open_id)).unwrap_or(false); let say_id = egui::Id::unique(("branch-say", bot.id, rec.id)); let mut say = ctx.data(|d| d.get_temp::(say_id)).unwrap_or_default(); let mut stop = false; let mut answer: Option = None; let running = rec.state == BranchState::Running; ui.add_space(6.0); Frame::new().fill(p.hover).stroke(Stroke::new(1.0, p.border)).corner_radius(R_L).inner_margin(Margin::symmetric(12, 10)).show(ui, |ui| { ui.set_max_width(message_max_width(ui.available_width())); ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = 6.0; crate::icons::label(ui, crate::icons::Icon::Template, &t("支線"), 12.0, p.text3); ui.label(RichText::new(&rec.task).size(FONT_SM).strong().family(crate::bold()).color(p.text)); }); ui.add_space(4.0); let line = |ui: &mut egui::Ui, text: &str, col: Color32| { ui.label(RichText::new(text).size(FONT_XS).color(col)); }; match rec.state { BranchState::Checking => { ui.horizontal(|ui| { super::chat_ui::spinner(ui, 12.0, ui.visuals().strong_text_color()); line(ui, &t("先看看會不會跟主線正在做的事衝突…"), p.text2); }); } BranchState::Waiting => line(ui, &format!("{}:{}", t("等主線這一輪做完再開始"), rec.note), p.text2), BranchState::Running => { ui.horizontal(|ui| { super::chat_ui::spinner(ui, 12.0, ui.visuals().strong_text_color()); let doing = if rec.doing.is_empty() { t("正在做…") } else { rec.doing.clone() }; line(ui, &format!("{doing}{}", if rec.steps > 0 { format!("({} 步)", rec.steps) } else { String::new() }), p.text2); }); ctx.request_repaint_after(std::time::Duration::from_millis(500)); } // Its result (or why it didn't finish) is the message posted below when it ends — // said once there, not again in this card. BranchState::Done => line(ui, &format!("✓ {}", t("做完了")), p.up), BranchState::Failed => line(ui, &t("沒有做完"), p.danger), BranchState::Stopped => line(ui, &t("已停止"), p.text3), } // What it waits on the person for — a yes, an answer, a step only they can do — // is answered right here (the docks above the input are the open bot's own). if let Some((kind, reason)) = self.approvals.get(&rec.id).map(|a| (a.kind, a.reason.clone())) { ui.add_space(6.0); Frame::new().fill(p.attention_bg).stroke(Stroke::new(1.0, p.attention)).corner_radius(R_M).inner_margin(Margin::symmetric(10, 8)).show(ui, |ui| { let words = if kind == ApprovalKind::Question { crate::ask::describe(&reason) } else { reason }; ui.label(RichText::new(words).size(FONT_SM).color(p.text)); if kind == ApprovalKind::Question { ui.add(egui::TextEdit::singleline(&mut say).hint_text(t("你的回答")).desired_width(f32::INFINITY)); } ui.horizontal(|ui| { let (yes, no) = match kind { ApprovalKind::Question => ("回答", "略過"), ApprovalKind::Handoff => ("我完成了", "跳過"), _ => ("允許", "拒絕"), }; if ui.add(secondary_button(yes)).clicked() && (kind != ApprovalKind::Question || !say.trim().is_empty()) { answer = Some(if kind == ApprovalKind::Question { ApprovalAnswer::Answered(std::mem::take(&mut say)) } else { ApprovalAnswer::Once }); } if ui.add(secondary_button(no)).clicked() { answer = Some(ApprovalAnswer::Reject); } }); }); } // (Only when it has a button: an empty row left a blank strip under 「沒有做完」.) if running || !rec.log.is_empty() { ui.horizontal(|ui| { if running && ui.add(egui::Button::new(RichText::new(t("停止支線")).size(FONT_XS).color(p.text3)).frame(false)).clicked() { stop = true; } if !rec.log.is_empty() && ui.add(egui::Button::new(RichText::new(if open { t("收起過程") } else { format!("{}({})", t("看過程"), rec.log.len()) }).size(FONT_XS).color(p.text3)).frame(false)).clicked() { open = !open; } }); } if open { for l in &rec.log { ui.label(RichText::new(l).size(FONT_XS).color(p.text3)); } } }); ctx.data_mut(|d| { d.insert_temp(open_id, open); d.insert_temp(say_id, say); }); if stop { self.stop(rec.id); } if let Some(a) = answer { self.answer(ctx, rec.id, a); } } } #[cfg(test)] mod tests { use super::*; #[test] fn the_command_and_the_check_are_read() { assert_eq!(command("/btw 順便查一下匯率").as_deref(), Some("順便查一下匯率")); assert_eq!(command("/btw").as_deref(), Some("")); assert_eq!(command("/btwx 不是"), None); assert_eq!(command("不是 /btw"), None); assert_eq!(read_clash("好的 {\"conflict\": true, \"reason\": \"都要用同一個螢幕\"}"), (true, "都要用同一個螢幕".into())); assert!(!read_clash("{\"conflict\":false,\"reason\":\"只是查資料\"}").0); assert_eq!(read_clash("看不懂"), (false, String::new())); } #[test] fn a_branch_takes_the_chat_up_to_its_last_finished_step() { use crate::model::ToolCall; let call = |id: &str| ToolCall { id: id.into(), name: "shell".into(), args: "{}".into(), status: ToolStatus::Done }; let msgs = vec![ Message::user("整理資料夾"), Message { tool_calls: vec![call("a")], ..Message::assistant("先看看", "x") }, Message::tool_result("a", "shell", "ok"), // The running step: asked, not answered yet. Message { tool_calls: vec![call("b")], ..Message::assistant("", "x") }, Message { note: true, ..Message::assistant("目標進行中", "") }, ]; let f = fork_history(&msgs); assert_eq!(f.len(), 3, "{f:?}"); assert_eq!(f[1].tool_calls.len(), 1); assert!(f.iter().all(|m| !m.note)); // Claude's own blocks stay where no step was dropped; an earlier branch's report stays, // its card doesn't. let block = serde_json::json!({"type": "thinking"}); let msgs = vec![ Message::user("a"), Message { blocks: vec![block.clone()], tool_calls: vec![call("a")], ..Message::assistant("", "x") }, Message::tool_result("a", "shell", "ok"), Message { note: true, branch: 7, ..Message::assistant("/btw x", "") }, Message { branch: 7, ..Message::assistant("支線回報", "") }, Message { blocks: vec![block], tool_calls: vec![call("b")], ..Message::assistant("", "x") }, ]; let f = fork_history(&msgs); assert_eq!(f.len(), 4, "{f:?}"); assert_eq!(f[1].blocks.len(), 1); assert!(f.iter().any(|m| m.branch == 7 && !m.note) && f.iter().all(|m| !m.note)); } }