AnyBot/src/app/goal_ui.rs

324 lines
15 KiB
Rust
Raw Normal View History

// 目標 (/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<crate::attach::Attachment>, picks: Option<Vec<String>>) {
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));
}
Bot 之間溝通:ask_bot 問同事並等回答、群組 @點名、共用頁面/「關於你」記憶/教技能;修正插話丟附件、Enter 核准失效等 問同事(ask_bot) - A 問 B 並等它回答:問題放進 B 自己的聊天,B 用自己的模型、工具、記憶和電腦做,最後的回覆交回 A - 最多轉 3 手、不能互等(避免卡死)、對方忙就排隊(10 分鐘逾時)、停止 A 時 B 也停 - message_bot 也加轉手上限;別的 Bot 叫的不算使用者的話(改不了自己的設定) 群組 @點名 - 「@名字」只叫被點到的成員回答;成員在回覆裡 @ 別人就接著說(一輪最多 8 則) - 電腦和手機的輸入框打 @ 會列出成員 - 修正:每個成員帶自己的記憶;成員回覆的每一步都記得是誰說的 共用資源 - Bot 可以讀其他 Bot 的頁面(只能讀,改要請作者改) - 共用的「關於你」記憶:每個 Bot 都帶著,記憶頁可切換查看、編輯;外人的訊息不帶 - teach_skill:把自己會的技能教給同事(先問你);同事名冊列出每個 Bot 會的技能 修正 - 插話(Bot 工作中傳訊息)會帶附件:聊天有檔案卡片,模型看得到圖片;當機復原也帶著 - 輸入框有焦點、框是空的時 Enter 允許待核准的步驟(原本被當成空白送出吃掉) - 大腦的螢幕連不到大腦時,引用、附件、記憶不會先被用掉 - 「還原上一個答案」存在 Bot 上:重開還在,連大腦的畫面和手機都能還原;停止的回合也留著 - Bot 忙時被叫醒(例行任務、message_bot、觸發器)改成排隊開自己的一輪,不再壓成純文字插話 - 停止時結果已回來的步驟標成完成;輸入法剛選字的那一格不送出 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha3a7riWESpv471gDgC
2026-11-13 13:34:03 +00:00
self.queue_steer(bot_id, text.trim().to_string(), attachments);
} 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.
/btw 支線、送出先顯示;公測前的安全與資源修正(帳號盜用、灌爆、團隊權限、背景指令與連線的上限和清理) 支線與介面 - /btw:Bot 的分身帶著同一段對話和記憶平行做另一件事,做完回報到主聊天;主線在忙時先判斷會不會衝突,會就等主線做完 - 螢幕一次只給一輪工作操作(所有 Bot 適用) - 「/」只列指令,打字才找這個 Bot 自己的技能 - Bot 工作中送出的訊息立刻以淡色顯示(電腦、手機) - 支線修正:沒被讀到的回報照常進聊天、卡片顯示結果、可回答支線的問題、重新產生不吃掉卡片和回報 安全(中繼伺服器) - 大腦回傳的內容只放行安全類型並加沙箱;團隊改成邀請制;手機不照大腦說的類型開檔案 - 沒登入的請求最多 256 KB、接收中的上傳有總量上限、單一 IP 連線上限、常駐連線另計 - 登入次數加上每帳號上限並先計數再驗證;密碼雜湊同時最多 4 個 - 新增電腦要 15 分鐘內剛登入;可改密碼;註冊限速,有邀請碼時第一個帳號也要 - 發布的網站不能送表單和對外連線;Caddy 加安全標頭 安全(大腦) - 區網(明文)不能打開直接操作、加一律允許規則、加連接器;區網登入 30 天沒用失效 - 團隊成員只看得到勾選「團隊成員可以使用」的 Bot - 沒有角色的請求一律拒絕;環境變數的金鑰只送官方位址 資源 - 中繼:小變動每分鐘寫一次、回應有總時限、每台電腦呼叫上限、網站/登入/電腦/配對碼上限、資料檔壞掉不啟動 - App:伺服器回錯誤和連線秒斷時逐次退避;區網看螢幕偵測斷線 - 背景指令:刪 Bot 和支線結束時停掉、最多 24 個、結束 10 分鐘後移除、可用 stop 停掉 - 截圖在收起和歸檔時釋放;刪 Bot 時刪附件和對照表;每晚清稽核資料和暫存;手機圖片快取上限 Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha3a7riWESpv471gDgC
2026-11-13 15:36:34 +00:00
pub(super) 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, "") };
let at = note_index(&b.messages, streaming);
b.messages.insert(at, 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(&note.replace('\n', " "), 120);
if !self.headless {
notify::banner(title, &body);
}
crate::remote::notify(title, &body, bot_id);
}
/// 清除聊天記錄 / 開始新對話: the goal goes with the chat it was set in (Claude Code's /clear
/// removes it too). Before the turn is stopped, so stopping doesn't leave a 「目標暫停」 line
/// in the new chat.
pub(super) fn goal_drop(&mut self, bot_id: u64) {
if let Some(b) = self.state.bot_mut(bot_id) {
b.goal = None;
}
self.goal_checking.remove(&bot_id);
self.goal_due.retain(|(id, _)| *id != bot_id);
}
/// 停止 pressed between two turns of a goal (the check is reading the chat; nothing is
/// running to stop): the goal pauses, or the next turn would start a moment later anyway.
pub(super) fn goal_stop(&mut self, bot_id: u64) {
if self.streams.contains_key(&bot_id) || !self.goal_pending(bot_id) {
return;
}
self.goal_checking.remove(&bot_id);
self.goal_due.retain(|(id, _)| *id != bot_id);
let Some(g) = self.state.bot_mut(bot_id).and_then(|b| b.goal.as_mut()).filter(|g| g.active()) else { return };
let note = goal::after_trouble(g, true);
self.goal_note(bot_id, &note);
self.save_now = true;
}
/// 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, &note);
self.goal_tell(bot_id, &title, &note);
}
}
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),
/btw 支線、送出先顯示;公測前的安全與資源修正(帳號盜用、灌爆、團隊權限、背景指令與連線的上限和清理) 支線與介面 - /btw:Bot 的分身帶著同一段對話和記憶平行做另一件事,做完回報到主聊天;主線在忙時先判斷會不會衝突,會就等主線做完 - 螢幕一次只給一輪工作操作(所有 Bot 適用) - 「/」只列指令,打字才找這個 Bot 自己的技能 - Bot 工作中送出的訊息立刻以淡色顯示(電腦、手機) - 支線修正:沒被讀到的回報照常進聊天、卡片顯示結果、可回答支線的問題、重新產生不吃掉卡片和回報 安全(中繼伺服器) - 大腦回傳的內容只放行安全類型並加沙箱;團隊改成邀請制;手機不照大腦說的類型開檔案 - 沒登入的請求最多 256 KB、接收中的上傳有總量上限、單一 IP 連線上限、常駐連線另計 - 登入次數加上每帳號上限並先計數再驗證;密碼雜湊同時最多 4 個 - 新增電腦要 15 分鐘內剛登入;可改密碼;註冊限速,有邀請碼時第一個帳號也要 - 發布的網站不能送表單和對外連線;Caddy 加安全標頭 安全(大腦) - 區網(明文)不能打開直接操作、加一律允許規則、加連接器;區網登入 30 天沒用失效 - 團隊成員只看得到勾選「團隊成員可以使用」的 Bot - 沒有角色的請求一律拒絕;環境變數的金鑰只送官方位址 資源 - 中繼:小變動每分鐘寫一次、回應有總時限、每台電腦呼叫上限、網站/登入/電腦/配對碼上限、資料檔壞掉不啟動 - App:伺服器回錯誤和連線秒斷時逐次退避;區網看螢幕偵測斷線 - 背景指令:刪 Bot 和支線結束時停掉、最多 24 個、結束 10 分鐘後移除、可用 stop 停掉 - 截圖在收起和歸檔時釋放;刪 Bot 時刪附件和對照表;每晚清稽核資料和暫存;手機圖片快取上限 Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha3a7riWESpv471gDgC
2026-11-13 15:36:34 +00:00
api_key: providers::resolve_key_for(b.provider, &ps.api_key, &ps.base_url),
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}"),
effort: String::new(),
};
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, set again or stopped 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, &note);
self.goal_tell(bot_id, &format!("{name} {title}"), &note);
}
Next::Pause { note, title } => {
self.goal_note(bot_id, &note);
self.goal_tell(bot_id, &format!("{name} {title}"), &note);
}
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);
}
}
/// Where AnyBot's own line goes in a chat. At the end — but never between a step and its result
/// or after the reply being written (while the bot works, the newest message is the one its
/// words stream into), and above a 「繼續」 card, which has to stay the newest thing to be pressed.
/btw 支線、送出先顯示;公測前的安全與資源修正(帳號盜用、灌爆、團隊權限、背景指令與連線的上限和清理) 支線與介面 - /btw:Bot 的分身帶著同一段對話和記憶平行做另一件事,做完回報到主聊天;主線在忙時先判斷會不會衝突,會就等主線做完 - 螢幕一次只給一輪工作操作(所有 Bot 適用) - 「/」只列指令,打字才找這個 Bot 自己的技能 - Bot 工作中送出的訊息立刻以淡色顯示(電腦、手機) - 支線修正:沒被讀到的回報照常進聊天、卡片顯示結果、可回答支線的問題、重新產生不吃掉卡片和回報 安全(中繼伺服器) - 大腦回傳的內容只放行安全類型並加沙箱;團隊改成邀請制;手機不照大腦說的類型開檔案 - 沒登入的請求最多 256 KB、接收中的上傳有總量上限、單一 IP 連線上限、常駐連線另計 - 登入次數加上每帳號上限並先計數再驗證;密碼雜湊同時最多 4 個 - 新增電腦要 15 分鐘內剛登入;可改密碼;註冊限速,有邀請碼時第一個帳號也要 - 發布的網站不能送表單和對外連線;Caddy 加安全標頭 安全(大腦) - 區網(明文)不能打開直接操作、加一律允許規則、加連接器;區網登入 30 天沒用失效 - 團隊成員只看得到勾選「團隊成員可以使用」的 Bot - 沒有角色的請求一律拒絕;環境變數的金鑰只送官方位址 資源 - 中繼:小變動每分鐘寫一次、回應有總時限、每台電腦呼叫上限、網站/登入/電腦/配對碼上限、資料檔壞掉不啟動 - App:伺服器回錯誤和連線秒斷時逐次退避;區網看螢幕偵測斷線 - 背景指令:刪 Bot 和支線結束時停掉、最多 24 個、結束 10 分鐘後移除、可用 stop 停掉 - 截圖在收起和歸檔時釋放;刪 Bot 時刪附件和對照表;每晚清稽核資料和暫存;手機圖片快取上限 Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha3a7riWESpv471gDgC
2026-11-13 15:36:34 +00:00
pub(super) fn note_index(msgs: &[Message], streaming: bool) -> usize {
let mut i = msgs.len();
if streaming {
while i > 0 && msgs[i - 1].role == Role::Tool {
i -= 1;
}
i = i.saturating_sub(1);
} else if msgs.last().is_some_and(|m| m.interrupted) {
i -= 1;
}
i
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_note_never_splits_a_step_from_its_result() {
let user = Message::user("做事");
let step = Message { tool_calls: vec![crate::model::ToolCall { id: "1".into(), name: "shell".into(), args: "{}".into(), status: Default::default() }], ..Message::assistant("", "") };
let result = Message::tool_result("1", "shell", "ok");
let reply = Message::assistant("好了", "");
// Idle: at the end.
assert_eq!(note_index(&[user.clone(), reply.clone()], false), 2);
assert_eq!(note_index(&[], false), 0);
// Working: before the reply being written…
assert_eq!(note_index(&[user.clone(), reply.clone()], true), 1);
// …and before a step whose result is the newest message.
assert_eq!(note_index(&[user.clone(), step.clone(), result.clone()], true), 1);
assert_eq!(note_index(&[], true), 0);
// A 「繼續」 card stays the newest thing.
let card = Message { interrupted: true, ..Message::assistant("被中斷了", "") };
assert_eq!(note_index(&[user, step, result, card], false), 3);
}
}