AnyBot/src/app/commands.rs

356 lines
19 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.

// AnyBot's own slash commands (not the bot's): told apart and carried out in one place, whether
// typed here, on a screen of a brain (it sends the words; the brain carries them out) or on the
// phone. They used to be listed twice (send and the remote path), and a new one had to be added
// to both.
//
// 分岔 (/fork, M5): a copy of this conversation goes to 過去的對話 as 「分岔:…」 and the person
// goes on here; opening it later puts this one aside, so the two go their own ways from that point
// (like grok-build's /fork, Claude Code's /branch). A copy of the bot instead would run its
// routines and answer its channels twice.
use super::*;
/// One of AnyBot's commands.
pub(super) enum AppCommand {
Btw(String),
Goal(crate::goal::Command),
Plan(crate::plan::Command),
Always(crate::always::Command),
Usage,
Context,
Compact,
Doctor,
Fork(String),
Rewind(Result<crate::checkpoint::Rewind, String>),
}
impl AppCommand {
/// Whether carrying it out lets the bots do more without asking — what a phone on a direct
/// connection may not type (remote.rs refuses those words before they reach the app; it used
/// to let 「/always-approve」 turn 直接操作 and 一律放行 on). Every command is named here, so a
/// new one has to be decided.
fn loosens(&self) -> bool {
match self {
AppCommand::Always(crate::always::Command::On) => true,
AppCommand::Always(crate::always::Command::Off | crate::always::Command::Status) => false,
AppCommand::Btw(_) | AppCommand::Goal(_) | AppCommand::Plan(_) | AppCommand::Usage | AppCommand::Context | AppCommand::Compact | AppCommand::Doctor | AppCommand::Fork(_) | AppCommand::Rewind(_) => false,
}
}
}
/// Words that, sent in a chat, are one of AnyBot's commands that would loosen a guard.
pub(crate) fn words_loosen(text: &str) -> bool {
app_command(text).is_some_and(|c| c.loosens())
}
/// How many of the person's messages /rewind offers.
const REWIND_POINTS: usize = 10;
/// A branch's title: 「分岔:」 and the name given, or the conversation's first words.
pub(super) const FORK_PREFIX: &str = "分岔:";
/// 「/fork」 or 「/fork 名字」: the name (empty when none), or None.
pub(super) fn fork_command(text: &str) -> Option<String> {
let rest = text.trim_start().strip_prefix("/fork")?;
(rest.is_empty() || rest.starts_with(char::is_whitespace)).then(|| rest.trim().chars().take(40).collect())
}
/// The command these words are, if they are one.
pub(super) fn app_command(text: &str) -> Option<AppCommand> {
if let Some(task) = branch::command(text) {
return Some(AppCommand::Btw(task));
}
if let Some(c) = crate::goal::command(text) {
return Some(AppCommand::Goal(c));
}
if let Some(c) = crate::plan::command(text) {
return Some(AppCommand::Plan(c));
}
if let Some(c) = crate::always::command(text) {
return Some(AppCommand::Always(c));
}
if crate::usage::command(text) {
return Some(AppCommand::Usage);
}
if crate::doctor::command(text) {
return Some(AppCommand::Doctor);
}
if let Some(name) = fork_command(text) {
return Some(AppCommand::Fork(name));
}
if let Some(r) = crate::checkpoint::command(text) {
return Some(AppCommand::Rewind(r));
}
match text.trim() {
"/context" => Some(AppCommand::Context),
"/compact" => Some(AppCommand::Compact),
_ => None,
}
}
impl App {
/// The command these words are for this bot: AnyBot's own, or 「/技能 …」 for one of its skills
/// marked `context: fork` (技能帶參數, M4), which goes to a 支線 as it was typed.
pub(super) fn command_for(&self, bot_id: u64, text: &str) -> Option<AppCommand> {
app_command(text).or_else(|| {
let b = self.state.bot(bot_id).filter(|b| b.members.is_empty())?;
let mine = crate::profile::skills_of(b, &self.state.skills);
crate::memory::named_skill(text, &mine).filter(|k| k.fork).map(|_| AppCommand::Btw(text.trim().to_string()))
})
}
/// Carry out one of AnyBot's commands for this bot.
pub(super) fn run_app_command(&mut self, ctx: &egui::Context, bot_id: u64, cmd: AppCommand, text: &str, attachments: Vec<crate::attach::Attachment>, picks: Option<Vec<String>>) {
match cmd {
AppCommand::Btw(task) => self.btw_command(ctx, bot_id, &task, attachments),
AppCommand::Goal(c) => self.goal_command(ctx, bot_id, c, text, attachments, picks),
AppCommand::Plan(c) => self.plan_command(ctx, bot_id, c, text, attachments, picks),
AppCommand::Always(c) => self.always_command(ctx, bot_id, c),
AppCommand::Usage => self.usage_note(bot_id),
AppCommand::Context => self.context_note(bot_id),
AppCommand::Compact => self.compact_now(bot_id),
AppCommand::Doctor => self.doctor_start(bot_id),
AppCommand::Fork(name) => self.fork_now(bot_id, &name),
AppCommand::Rewind(Err(e)) => self.goal_note(bot_id, &e),
AppCommand::Rewind(Ok(r)) => self.rewind(bot_id, r),
}
}
/// Lines that work on another thread finished, into their chats.
pub(super) fn later_tick(&mut self) {
let later = std::mem::take(&mut *self.later_notes.lock().unwrap());
for (bot_id, text) in later {
self.goal_note(bot_id, &text);
self.save_now = true;
}
}
/// 監看 (shell with monitor): what watched commands printed wakes their bots — a turn now,
/// or one of its own after the one it is in.
pub(super) fn monitor_tick(&mut self, ctx: &egui::Context) {
let c = ctx.clone();
crate::tools::set_monitor_repaint(Arc::new(move || c.request_repaint()));
for (bot_id, text) in crate::tools::monitor_take(|b| self.state.bot(b).is_some()) {
self.wake(ctx, bot_id, Message { wake: true, ..Message::user(&text) });
}
}
/// The points 「/rewind」 can go back to: the person's messages in this conversation, newest
/// first (index in the chat, its time, its words).
fn rewind_points(&self, bot_id: u64) -> Vec<(usize, i64, String)> {
let Some(b) = self.state.bot(bot_id) else { return vec![] };
b.messages.iter().enumerate().rev().filter(|(_, m)| m.role == Role::User && !m.note && !m.wake && m.at > 0).take(REWIND_POINTS).map(|(i, m)| (i, m.at, m.text.clone())).collect()
}
/// 「/rewind」 (the points) or 「/rewind N [檔案|對話]」 (back to one).
pub(super) fn rewind(&mut self, bot_id: u64, r: crate::checkpoint::Rewind) {
use crate::checkpoint::Rewind;
let points = self.rewind_points(bot_id);
let kept = crate::checkpoint::entries(bot_id);
let Some(b) = self.state.bot(bot_id) else { return };
let name = b.name.clone();
// (This conversation's turns only: up to its newest message.)
let until = b.messages.iter().map(|m| m.at).max().unwrap_or(0);
let (n, files, chat) = match r {
Rewind::List => {
if points.is_empty() {
self.goal_note(bot_id, "這個對話還沒有可以退回的點。");
return;
}
let now = crate::model::now_ms();
let mut text = format!("可以退回的點(最新的在最上面):退回去會把那句話之後 {name} 用 edit_file 改的檔案還原;用指令(shell、git…)改的不在裡面。");
for (k, (_, at, words)) in points.iter().enumerate() {
let n = crate::checkpoint::files_since(&kept, *at, until).len();
text.push_str(&format!("\n{}. {}「{}」:{}", k + 1, crate::pages::ago(*at, now), first_line(words, 30), if n == 0 { "之後沒有改過檔案".to_string() } else { format!("之後改過 {n} 個檔案") }));
}
text.push_str("\n打「/rewind 編號」檔案和對話都退回那句話之前;「/rewind 編號 檔案」只退檔案;「/rewind 編號 對話」只退對話。");
self.goal_note(bot_id, &text);
return;
}
Rewind::To { n, files, chat } => (n, files, chat),
};
if self.streams.contains_key(&bot_id) {
self.goal_note(bot_id, &format!("{name} 正在做事:等它做完(或按停止)再 /rewind。"));
return;
}
let Some((i, at, words)) = points.get(n - 1).cloned() else {
self.goal_note(bot_id, &format!("沒有第 {n} 個點:打 /rewind 看有哪些。"));
return;
};
if chat {
let Some(b) = self.state.bot_mut(bot_id) else { return };
// The whole conversation first goes to 過去的對話: a rewind can be taken back.
let mut copy = b.messages.clone();
copy.iter_mut().for_each(|m| m.images.clear());
let title = format!("退回前:{}", first_line(&words, 24));
b.threads.insert(0, (title.clone(), copy));
b.threads.truncate(50);
b.messages.truncate(i);
b.regen_undo.clear();
b.draft = words.clone();
self.drafts.insert(bot_id, words.clone());
self.goal_note(bot_id, &format!("對話退回到你說「{}」之前,那句話放回輸入框了(在別台打的就照這裡再打一次)。退回前的整段對話收在過去的對話「{title}」。", first_line(&words, 40)));
}
if files {
let out = self.later_notes.clone();
let repaint = self.repaint_fn();
self.goal_note(bot_id, "正在還原檔案…");
std::thread::spawn(move || {
let lines = crate::checkpoint::restore(bot_id, at, until);
let text = if lines.is_empty() { "檔案:那句話之後沒有用 edit_file 改過檔案,沒有要還原的(用指令改的不在檢查點裡)。".to_string() } else { format!("檔案退回到那句話之前:\n{}", lines.iter().map(|l| format!("- {l}")).collect::<Vec<_>>().join("\n")) };
out.lock().unwrap().push((bot_id, text));
repaint();
});
}
self.mark();
}
/// 「/fork」: this conversation, as it is now, kept in 過去的對話 too.
pub(super) fn fork_now(&mut self, bot_id: u64, name: &str) {
let Some(b) = self.state.bot(bot_id) else { return };
if self.streams.contains_key(&bot_id) {
let note = format!("{} 正在做事:等它做完(或按停止)再 /fork。", b.name);
self.goal_note(bot_id, &note);
return;
}
let words: Vec<&Message> = b.messages.iter().filter(|m| !m.note).collect();
if words.is_empty() {
self.goal_note(bot_id, "對話還是空的,沒有東西可以分岔。");
return;
}
let what = if name.is_empty() { words.iter().find(|m| m.role == Role::User).map(|m| first_line(&m.text, 24)).unwrap_or_else(|| "對話".into()) } else { name.to_string() };
let title = format!("{FORK_PREFIX}{what}");
let Some(b) = self.state.bot_mut(bot_id) else { return };
let mut copy = b.messages.clone();
// (Like any conversation put aside: its words, not its screenshots in memory.)
copy.iter_mut().for_each(|m| m.images.clear());
b.threads.insert(0, (title.clone(), copy));
b.threads.truncate(50);
self.goal_note(bot_id, &format!("已分岔:這段對話到這裡為止存了一份「{title}」。接著在這裡做;要回到這一點走另一條路,從 Bot 的選單 › 過去的對話 打開它(這邊會自動收進過去的對話,不會不見)。"));
self.mark();
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn commands_are_told_apart() {
assert!(matches!(app_command("/fork"), Some(AppCommand::Fork(n)) if n.is_empty()));
assert!(matches!(app_command("/fork 試另一個做法"), Some(AppCommand::Fork(n)) if n == "試另一個做法"));
assert!(app_command("/forkx").is_none() && app_command("請 /fork").is_none());
assert!(matches!(app_command("/btw 查天氣"), Some(AppCommand::Btw(t)) if t == "查天氣"));
assert!(matches!(app_command("/goal 測試通過"), Some(AppCommand::Goal(_))));
assert!(matches!(app_command(" /compact "), Some(AppCommand::Compact)));
assert!(matches!(app_command("/doctor"), Some(AppCommand::Doctor)));
assert!(app_command("你好").is_none() && app_command("/Users/me/a.txt").is_none());
}
/// The commands that loosen a guard — what a direct connection may not type.
#[test]
fn turning_always_approve_on_is_the_command_that_loosens() {
for on in ["/always-approve", "/yolo", " /always-approve on ", "/yolo 開", "/always-approve 打開"] {
assert!(words_loosen(on), "{on}");
}
for not in ["/always-approve off", "/yolo 關", "/always-approve status", "/always-approve 現在呢", "/goal 測試通過", "/plan 整理", "/btw 查", "/rewind", "/doctor", "你好", "請 /always-approve"] {
assert!(!words_loosen(not), "{not}");
}
}
#[test]
fn a_fork_keeps_a_copy_and_goes_on_here() {
let ctx = egui::Context::default();
let mut app = App::new(&ctx, Some(std::env::temp_dir().join("anybot-fork.png")));
// (A bot not shown as working in the sample.)
let id = app.state.bots.iter().find(|b| b.members.is_empty() && !app.streams.contains_key(&b.id)).unwrap().id;
app.state.bot_mut(id).unwrap().messages = vec![Message::user("幫我寫一份報告"), Message::assistant("好,第一版在 report.md", "m")];
app.run_app_command(&ctx, id, AppCommand::Fork("改寫成表格".into()), "/fork 改寫成表格", vec![], None);
let b = app.state.bot(id).unwrap();
assert_eq!(b.threads[0].0, "分岔:改寫成表格");
assert_eq!(b.threads[0].1.len(), 2);
assert!(b.messages.len() == 3 && b.messages[2].note && b.messages[2].text.contains("已分岔"), "{:?}", b.messages.last());
// The two go their own ways: what is said here doesn't reach the copy.
app.state.bot_mut(id).unwrap().messages.push(Message::user("改用圖表"));
assert_eq!(app.state.bot(id).unwrap().threads[0].1.len(), 2);
// Opening the branch puts this one aside, and comes back at the point it was made.
app.open_thread(id, 0);
let b = app.state.bot(id).unwrap();
assert_eq!(b.messages.len(), 2);
assert!(b.threads[0].1.iter().any(|m| m.text == "改用圖表"));
// Nothing to fork, or busy: a line says why.
app.state.bot_mut(id).unwrap().messages.clear();
app.fork_now(id, "");
assert!(app.state.bot(id).unwrap().messages[0].text.contains("空的"));
app.state.bot_mut(id).unwrap().messages = vec![Message::user("x")];
let busy = app.state.bots.iter().find(|b| app.streams.contains_key(&b.id)).map(|b| b.id);
if let Some(busy) = busy {
app.state.bot_mut(busy).unwrap().messages.push(Message::user("在做"));
app.fork_now(busy, "");
assert!(app.state.bot(busy).unwrap().messages.iter().any(|m| m.note && m.text.contains("正在做事")));
}
}
/// 「/rewind」 lists the person's messages with how many files changed after each; going
/// back to one puts the files back, the chat back to before it (its words in the input box,
/// the whole chat in 過去的對話).
#[test]
fn rewind_takes_files_and_chat_back() {
let ctx = egui::Context::default();
let mut app = App::new(&ctx, Some(std::env::temp_dir().join("anybot-rewind.png")));
let id = app.state.bots.iter().find(|b| b.members.is_empty() && !app.streams.contains_key(&b.id)).unwrap().id;
let w = std::env::temp_dir().join(format!("anybot-rewind-app-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&w);
std::fs::create_dir_all(&w).unwrap();
std::fs::write(w.join("README.md"), "中文版").unwrap();
let t = crate::tools::Target { name: "你的電腦".into(), place: crate::tools::Place::Local { workdir: w.clone() } };
let said = |text: &str, at: i64| Message { at, ..Message::user(text) };
app.state.bot_mut(id).unwrap().messages = vec![said("把 README 改成英文", 1_000), Message::assistant("改好了", "m"), said("再加一段安裝說明", 2_000), Message::assistant("加好了", "m")];
crate::checkpoint::before_edit(id, 1_000, &t, r#"{"path":"README.md"}"#);
std::fs::write(w.join("README.md"), "English").unwrap();
crate::checkpoint::before_edit(id, 2_000, &t, r#"{"path":"INSTALL.md"}"#);
std::fs::write(w.join("INSTALL.md"), "install").unwrap();
let run = |app: &mut App, text: &str| {
let cmd = app_command(text).unwrap();
app.run_app_command(&ctx, id, cmd, text, vec![], None);
};
run(&mut app, "/rewind");
let list = app.state.bot(id).unwrap().messages.last().unwrap().text.clone();
assert!(list.contains("1. ") && list.contains("再加一段安裝說明") && list.contains("之後改過 1 個檔案") && list.contains("把 README 改成英文") && list.contains("之後改過 2 個檔案"), "{list}");
run(&mut app, "/rewind 9");
assert!(app.state.bot(id).unwrap().messages.last().unwrap().text.contains("沒有第 9 個"));
run(&mut app, "/rewind 2");
let b = app.state.bot(id).unwrap();
assert!(b.messages.iter().all(|m| m.note), "only AnyBot's lines are left: {:?}", b.messages);
assert_eq!(b.draft, "把 README 改成英文");
assert!(b.threads[0].0.starts_with("退回前:") && b.threads[0].1.len() >= 4);
let until = std::time::Instant::now() + std::time::Duration::from_secs(10);
while app.later_notes.lock().unwrap().is_empty() && std::time::Instant::now() < until {
std::thread::sleep(std::time::Duration::from_millis(20));
}
app.later_tick();
let report = app.state.bot(id).unwrap().messages.last().unwrap().text.clone();
assert!(report.contains("README.md") && report.contains("INSTALL.md"), "{report}");
assert_eq!(std::fs::read_to_string(w.join("README.md")).unwrap(), "中文版");
assert!(!w.join("INSTALL.md").exists());
let _ = std::fs::remove_dir_all(&w);
}
/// 「/技能 …」 for a skill marked context: fork goes to a 支線; other skills and words don't.
#[test]
fn a_fork_skill_runs_off_the_main_chat() {
let ctx = egui::Context::default();
let mut app = App::new(&ctx, Some(std::env::temp_dir().join("anybot-fork-skill.png")));
let id = app.state.bots.iter().find(|b| b.members.is_empty()).unwrap().id;
app.state.skills.push(crate::memory::Skill { name: "研究".into(), description: "查資料".into(), instructions: "查 $ARGUMENTS".into(), fork: true, ..Default::default() });
app.state.skills.push(crate::memory::Skill { name: "簡報".into(), description: "做簡報".into(), instructions: "做".into(), ..Default::default() });
if let Some(b) = app.state.bot_mut(id) {
b.skills = None;
}
assert!(matches!(app.command_for(id, "/研究 台灣的太陽能"), Some(AppCommand::Btw(t)) if t == "/研究 台灣的太陽能"));
assert!(app.command_for(id, "/簡報 Q3").is_none());
assert!(app.command_for(id, "研究一下").is_none());
assert!(matches!(app.command_for(id, "/fork"), Some(AppCommand::Fork(_))));
}
}