// 目標 (/goal) in the window: 「/goal …」 typed to this brain (here, on one of its screens, on the // phone), the check after each turn, and the line above the input. What a goal is, how it is // judged and when it stops: goal.rs. // // The loop: a turn ends (settle) → its goal, if one is going, is checked by a second model on a // thread of its own (goal_tick → goal_judge) → the verdict comes back as StreamEvent::Goal // (goal_verdict) → not yet: AnyBot's 「[目標]還沒達成:…」 wakes the bot for another turn; met, // impossible or paused: a line in the chat (a note, never sent to the model) and, when the // person is away, a notification. Only a brain does this: a screen's turns run on its brain. use super::*; use crate::goal::{self, Command, Goal, Judged, Next}; impl App { /// 「/goal …」: show, clear, or set the goal and start on it. pub(super) fn goal_command(&mut self, ctx: &egui::Context, bot_id: u64, cmd: Command, text: &str, attachments: Vec, picks: Option>) { let now = crate::model::now_ms(); let Some(b) = self.state.bot(bot_id) else { return }; match cmd { Command::Status => { let s = goal::status(b.goal.as_ref(), now); self.goal_note(bot_id, &s); } Command::Clear => { let s = match self.state.bot_mut(bot_id).and_then(|b| b.goal.take()) { Some(g) => format!("已清除目標:{}", g.condition), None => "沒有設定目標。".into(), }; self.goal_checking.remove(&bot_id); self.goal_note(bot_id, &s); } Command::Set(cond) => { if !b.members.is_empty() { self.goal_note(bot_id, "群組聊天還不能設目標。"); return; } if cond.chars().count() > goal::MAX_CONDITION_CHARS { self.goal_note(bot_id, &format!("目標太長了(最多 {} 字)。", goal::MAX_CONDITION_CHARS)); return; } self.goal_checking.remove(&bot_id); if self.streams.contains_key(&bot_id) { // Working: the running turn hears it at its next step, and its end is the // first one checked. if let Some(b) = self.state.bot_mut(bot_id) { b.goal = Some(Goal::new(&cond, now)); } self.queue_steer(bot_id, text.trim().to_string()); } else { let m = Message { goal: cond.clone(), ..person_message(&self.state, bot_id, text.trim(), attachments, picks) }; if let Some(b) = self.state.bot_mut(bot_id) { b.goal = Some(Goal::new(&cond, m.at)); b.messages.push(m); } self.start_reply(ctx, bot_id); } } } self.dirty = true; self.save_now = true; } /// The person wrote to the bot (not 「/goal」): a paused goal goes on with this turn. pub(super) fn goal_heard(&mut self, bot_id: u64) { if let Some(g) = self.state.bot_mut(bot_id).and_then(|b| b.goal.as_mut()) { g.resume(); } } /// 清除目標 above the input: on a screen the brain clears it, as if typed there. pub(super) fn goal_clear(&mut self, ctx: &egui::Context, bot_id: u64) { if self.mir.on { self.mirror_send(bot_id, "/goal clear".into(), vec![], None); return; } self.goal_command(ctx, bot_id, Command::Clear, "/goal clear", vec![], None); } /// AnyBot's own line in the chat. While the bot works, its newest message is the one the /// words stream into, so the line goes just before it. fn goal_note(&mut self, bot_id: u64, text: &str) { let streaming = self.streams.contains_key(&bot_id); let selected = self.state.selected; if let Some(b) = self.state.bot_mut(bot_id) { let m = Message { note: true, ..Message::assistant(text, "") }; match b.messages.len() { n if streaming && n > 0 => b.messages.insert(n - 1, m), _ => b.messages.push(m), } if bot_id != selected { b.unread = true; } } self.dirty = true; } /// Tell the person how the goal stands, the way a finished turn is told (only when away). fn goal_tell(&self, bot_id: u64, title: &str, note: &str) { if self.demo || !(self.away() && self.state.notify) { return; } let body = first_line(¬e.replace('\n', " "), 120); if !self.headless { notify::banner(title, &body); } crate::remote::notify(title, &body, bot_id); } /// A turn of this bot's goal has ended and its check hasn't spoken yet. pub(super) fn goal_pending(&self, bot_id: u64) -> bool { self.goal_checking.contains(&bot_id) || self.goal_due.iter().any(|(id, _)| *id == bot_id) } /// Turns that ended since the last frame: check the ones working toward a goal. pub(super) fn goal_tick(&mut self, ctx: &egui::Context) { for (bot_id, outcome) in std::mem::take(&mut self.goal_due) { // Another turn is on its way (typed meanwhile, the next group member): its end is // the one checked. if self.streams.contains_key(&bot_id) || self.pending_turns.iter().any(|(id, _)| *id == bot_id) || self.group_next.contains(&bot_id) { continue; } let Some(b) = self.state.bot_mut(bot_id) else { continue }; let Some(g) = b.goal.as_mut().filter(|g| g.active()) else { continue }; match outcome { TurnOutcome::Success => { let start = b.messages.iter().rposition(|m| m.role == Role::User && !m.steer).unwrap_or(0); g.after_turn(b.messages[start..].iter().any(|m| m.role == Role::Assistant && !m.tool_calls.is_empty())); let g = g.clone(); self.goal_judge(ctx, bot_id, g); } TurnOutcome::Cancelled | TurnOutcome::Error => { let note = goal::after_trouble(g, outcome == TurnOutcome::Cancelled); let title = format!("{} 的目標暫停了", b.name); self.goal_note(bot_id, ¬e); self.goal_tell(bot_id, &title, ¬e); } } self.dirty = true; } } /// Ask the bot's quick model (or its own, as its 執行步驟用的模型 setting says) whether the /// goal holds, on a thread; the answer comes back as StreamEvent::Goal. fn goal_judge(&mut self, ctx: &egui::Context, bot_id: u64, g: Goal) { let Some(b) = self.state.bot(bot_id) else { return }; 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(b.provider, &ps.api_key), model, system: goal::JUDGE_SYSTEM.into(), history: vec![Message::user(&goal::brief(&g, &b.messages, crate::model::now_ms()))], tools: vec![], session: format!("anybot-goal-{bot_id}"), }; self.goal_checking.insert(bot_id); let (tx, ctx) = (self.tx.clone(), ctx.clone()); std::thread::spawn(move || { let cancel = AtomicBool::new(false); let judged = match providers::run_step(&req, &cancel, &|_| {}) { Ok(o) => goal::read_verdict(&o.text), Err(e) => Judged::Failed(e), }; eprintln!("AnyBot:Bot {bot_id} 的目標檢查:{judged:?}"); let _ = tx.send((bot_id, 0, StreamEvent::Goal(g.since, judged))); ctx.request_repaint(); }); } /// The check has spoken: another turn, or a line saying it is over or paused. pub(super) fn goal_verdict(&mut self, ctx: &egui::Context, bot_id: u64, since: i64, judged: Judged) { self.goal_checking.remove(&bot_id); // The person already started another turn: its end is checked instead. if self.streams.contains_key(&bot_id) { return; } let Some(b) = self.state.bot_mut(bot_id) else { return }; let name = b.name.clone(); // Cleared, or set again, while it was being checked. let Some(g) = b.goal.as_mut().filter(|g| g.since == since && g.active()) else { return }; let next = goal::after_verdict(g, judged, crate::model::now_ms()); let condition = g.condition.clone(); match next { Next::Over { note, title } => { b.goal = None; self.goal_note(bot_id, ¬e); self.goal_tell(bot_id, &format!("{name} {title}"), ¬e); } Next::Pause { note, title } => { self.goal_note(bot_id, ¬e); self.goal_tell(bot_id, &format!("{name} {title}"), ¬e); } Next::Again { text } => self.wake(ctx, bot_id, Message { wake: true, goal: condition, ..Message::user(&text) }), } self.dirty = true; self.save_now = true; } /// The line above the input while there is a goal: how it stands (the goal and the newest /// check on hover) and 清除目標. The words end in … before the button on a narrow window. pub(super) fn goal_bar(&mut self, ui: &mut egui::Ui, ctx: &egui::Context, bot: &Bot) { let Some(g) = bot.goal.as_ref() else { return }; let p = self.pal; let now = crate::model::now_ms(); let text = if g.active() && self.goal_checking.contains(&bot.id) { t("目標 · 正在檢查有沒有達成…") } else { goal::bar_text(g, now) }; let mut tip = format!("{}{}", t("目標:"), g.condition); if !g.reason.is_empty() { tip.push_str(&format!("\n\n{}{}", t("最近一次檢查:"), g.reason)); } let col = if g.active() { p.text2 } else { p.text3 }; let mut clear = false; ui.horizontal(|ui| { ui.add_space(14.0); ui.with_layout(Layout::right_to_left(Align::Center), |ui| { ui.add_space(10.0); clear = small_button(ui, "清除目標", p).clicked(); ui.with_layout(Layout::left_to_right(Align::Center), |ui| { ui.spacing_mut().item_spacing.x = 6.0; let (r, _) = ui.allocate_exact_size(vec2(13.0, 14.0), egui::Sense::hover()); crate::icons::paint(ui.painter(), egui::Rect::from_center_size(r.center(), vec2(12.0, 12.0)), crate::icons::Icon::Target, if g.active() { p.accent } else { col }); ui.add(egui::Label::new(RichText::new(&text).size(FONT_XS).color(col)).truncate().selectable(false)).on_hover_text(&tip); }); }); }); ui.add_space(2.0); if clear { self.goal_clear(ctx, bot.id); } if g.active() { // The minutes count on. ctx.request_repaint_after(std::time::Duration::from_secs(30)); } } /// A goal's line in the chat (AnyBot's, not the bot's): small, in the middle. pub(super) fn goal_note_row(&self, ui: &mut egui::Ui, m: &Message) { let p = self.pal; ui.add_space(2.0); ui.vertical_centered(|ui| { let w = message_max_width(ui.available_width()); ui.set_max_width(w); Frame::new().fill(p.hover).corner_radius(12).inner_margin(Margin::symmetric(12, 7)).show(ui, |ui| { ui.horizontal_top(|ui| { ui.spacing_mut().item_spacing.x = 6.0; let (r, _) = ui.allocate_exact_size(vec2(13.0, 16.0), egui::Sense::hover()); crate::icons::paint(ui.painter(), egui::Rect::from_center_size(r.center(), vec2(12.0, 12.0)), crate::icons::Icon::Target, p.text3); ui.add(egui::Label::new(RichText::new(&m.text).size(12.5).line_height(Some(18.0)).color(p.text2)).wrap()); }); }); }); ui.add_space(10.0); } }