AnyBot/src/app/tasks_ui.rs

313 lines
16 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.

// 任務 in the window. The brain works the list out (tasks.rs) every few seconds and at each
// turn's end, notes on the bots what changed, and hands the same list to the phone (remote_ui),
// the screens (mirror_ui) and the bots' `list_tasks`. A screen shows the list its brain sent.
//
// The list itself stays out of the chat: a quiet 任務 button at the top of the sidebar (a small
// number on it while something goes on or failed today) opens a dialog with every bot's tasks,
// the newest first; a click opens that chat at the task's first message.
use super::*;
use crate::tasks::{self, Dlv, Status, Task};
use std::hash::{Hash, Hasher};
/// How often the brain works the list out again (ms; a turn's end does it at once).
const EVERY_MS: u128 = 3_000;
#[derive(Default)]
pub struct TasksUi {
/// The list as last worked out (on the brain): what every screen shows.
pub(super) list: Vec<Task>,
/// Its fingerprint: the phone and the screens get it again when it changes.
pub(super) sig: u64,
at: Option<Instant>,
/// The dialog is open.
pub(super) open: bool,
/// A screen without its brain's list yet: worked out from its own copy (no live state).
copy: Option<Vec<Task>>,
}
/// The colour a state is drawn in: going on in the accent, waiting for the person in the
/// attention colour, failed in red, there and confirmed in green, the rest quiet.
fn status_color(s: Status, p: Palette) -> Color32 {
match s {
Status::Waiting => p.attention,
Status::Running | Status::Following | Status::Verifying => p.accent,
Status::Failed => p.danger,
Status::Delivered | Status::Confirmed | Status::Verified => p.up,
Status::Produced | Status::Answered | Status::Stopped | Status::Unverified => p.text2,
}
}
/// A file's mark, as under it in the chat: ✓ in the chat, ✓✓ shown, ✓✓ opened, ! not shown.
fn mark(d: Dlv) -> &'static str {
match d {
Dlv::InChat => "✓",
Dlv::Shown | Dlv::Opened => "✓✓",
Dlv::Failed => "!",
}
}
impl App {
/// What runs and waits now, as tasks.rs takes it.
fn tasks_live(&self) -> tasks::Live {
let mut l = tasks::Live::default();
for id in self.streams.keys() {
let step = self
.state
.bot(*id)
.and_then(|b| b.messages.iter().rev().take(8).filter(|m| m.role == Role::Assistant).flat_map(|m| m.tool_calls.iter()).find(|c| matches!(c.status, ToolStatus::Running | ToolStatus::Waiting)).map(|c| crate::evidence::step_line(&c.name, &c.args)))
.unwrap_or_default();
l.running.insert(*id, step);
}
for (id, a) in &self.approvals {
let Some(b) = self.state.bot(*id) else { continue };
let what = match a.kind {
ApprovalKind::Question => format!("等你回答:{}", first_line(&crate::ask::describe(&a.reason), 80)),
ApprovalKind::Handoff => format!("等你處理:{}", first_line(&a.reason, 80)),
ApprovalKind::EnableTools => "等你允許使用電腦工具".into(),
ApprovalKind::EnableThisComputer => "等你允許在你的電腦上執行".into(),
ApprovalKind::Action => format!("等你允許:{}", remote_ui::card_what(b, a)),
};
l.waiting.insert(*id, what);
}
l.checking = self.goal_checking.iter().copied().chain(self.goal_due.iter().map(|(b, _)| *b)).collect();
l
}
/// The brain: the list again (every few seconds, or `now`), and on each bot what changed.
pub(super) fn tasks_tick(&mut self, now: bool) {
if self.mir.on || (!now && self.tk.at.is_some_and(|t| t.elapsed().as_millis() < EVERY_MS)) {
return;
}
self.tk.at = Some(Instant::now());
let live = self.tasks_live();
let ms = crate::model::now_ms();
let per: Vec<Vec<Task>> = self.state.bots.iter().map(|b| tasks::of_bot(b, &live, ms)).collect();
if !self.demo {
let mut added = false;
for (b, ts) in self.state.bots.iter_mut().zip(&per) {
added |= tasks::note(b, ts, ms);
}
if added {
self.mark();
}
}
let list = tasks::newest(per.into_iter().flatten().collect());
let mut h = std::collections::hash_map::DefaultHasher::new();
serde_json::to_string(&list).unwrap_or_default().hash(&mut h);
self.tk.sig = h.finish();
self.tk.list = list;
}
/// The list every screen of this AnyBot shows: the brain's own, or (a screen) the one its
/// brain sent.
pub(super) fn tasks_list(&self) -> &[Task] {
if self.mir.on {
self.mir.tasks.as_deref().or(self.tk.copy.as_deref()).unwrap_or(&[])
} else {
&self.tk.list
}
}
/// `list_tasks`: the list in words, as tasks::answer filters it for who started this turn.
pub(super) fn list_tasks_text(&mut self, bot_id: u64, args: &str) -> String {
self.tasks_tick(true);
let home = self.state.home_of(bot_id);
let v = crate::tools::args_of(args);
crate::tasks::answer(&self.tk.list, &self.state.bots, home, &v, &self.state.timezone)
}
/// The sidebar's 任務 button (beside 搜尋), with how many need a look.
pub(super) fn tasks_button(&mut self, ui: &mut egui::Ui) {
let p = self.pal;
let n = tasks::attention(self.tasks_list(), crate::model::now_ms());
let r = pill_icon(ui, crate::icons::Icon::CircleCheck, p);
if n > 0 {
let c = r.rect.right_top() + vec2(-9.0, 9.0);
let label = if n > 9 { "9+".to_string() } else { n.to_string() };
let font = egui::FontId::proportional(FONT_XS * 0.85);
let w = ui.painter().layout_no_wrap(label.clone(), font.clone(), p.on_primary).size().x.max(8.0);
ui.painter().rect_filled(egui::Rect::from_center_size(c, vec2(w + 6.0, 14.0)), 7.0, p.accent);
ui.painter().text(c, egui::Align2::CENTER_CENTER, label, font, p.on_primary);
}
let tip = if n > 0 { format!("{}({n} {})", t("任務"), t("件要看")) } else { t("任務") };
if r.on_hover_text(tip).clicked() {
self.tk.open = true;
// A screen without its brain's list: its own copy, said as such.
if self.mir.on && self.mir.tasks.is_none() {
self.tk.copy = Some(tasks::all(&self.state.bots, &tasks::Live::default(), crate::model::now_ms()));
}
}
}
/// The 任務 dialog: every bot's tasks, the newest first.
pub(super) fn tasks_window(&mut self, ctx: &egui::Context) {
if !self.tk.open {
return;
}
let p = self.pal;
let list: Vec<Task> = self.tasks_list().to_vec();
let from_copy = self.mir.on && self.mir.tasks.is_none();
let body_h = dialog_max_height(ctx) - 48.0;
let mut open_at: Option<(u64, i64)> = None;
let now = crate::model::now_ms();
let closed = dialog(ctx, "tasks", "任務", 560.0, true, p, |ui| {
dialog_body(ui, "tasks-body", body_h, |ui| {
let n = tasks::attention(&list, now);
let head = if from_copy {
t("還沒連上大腦:這是這台電腦存的副本算的,不知道現在在跑什麼。")
} else if list.is_empty() {
t("還沒有任務。交代 Bot 做一件事,它就會出現在這裡。")
} else if n > 0 {
format!("{n} {}", t("件進行中、等你或今天失敗。狀態由 AnyBot 從步驟和交付回報算出,不是 Bot 說的。"))
} else {
t("狀態由 AnyBot 從步驟和交付回報算出,不是 Bot 說的。")
};
hint(ui, head, p);
ui.add_space(10.0);
for (i, task) in list.iter().enumerate() {
if self.task_card(ui, task, i, now) {
open_at = Some((task.bot, task.at));
}
}
});
});
if closed {
self.tk.open = false;
self.tk.copy = None;
}
if let Some((bot, at)) = open_at {
self.tk.open = false;
self.open_task(ctx, bot, at);
}
}
/// That chat, scrolled to the task's first message (when the chat still has it).
pub(super) fn open_task(&mut self, ctx: &egui::Context, bot: u64, at: i64) {
if self.state.bot(bot).is_none() {
return;
}
self.show_settings = false;
self.select_bot(ctx, bot);
if let Some(index) = self.state.bot(bot).and_then(|b| b.messages.iter().position(|m| m.at == at && m.role == Role::User)) {
self.goto = Some(crate::find::Goto { bot, index, at, since: Instant::now() });
}
}
/// One task's card; true when clicked.
fn task_card(&mut self, ui: &mut egui::Ui, task: &Task, i: usize, now: i64) -> bool {
let p = self.pal;
let name = self.state.bot(task.bot).map(|b| b.name.clone()).unwrap_or_else(|| t("已刪除的 Bot"));
// (The kit's card: its content's rect, out to the card's edge, is what a click lands on.)
let card = setting_card(ui, p, |ui| {
ui.spacing_mut().item_spacing.y = 3.0;
ui.horizontal(|ui| {
let (face, _) = ui.allocate_exact_size(vec2(22.0, 22.0), egui::Sense::hover());
if self.state.bot(task.bot).is_some() {
self.live_face(ui, task.bot, face, false);
}
let from = task.source.label();
let gap = if from.ends_with(|c: char| c.is_ascii_alphabetic()) { " " } else { "" };
// The state's chip keeps its room on the right; a long bot name is cut before it.
let label = t(task.status.label());
let chip_w = ui.painter().layout_no_wrap(label.clone(), egui::FontId::new(FONT_XS, crate::bold()), p.text).size().x + 16.0;
let who_w = (ui.available_width() - chip_w - 8.0).max(40.0);
ui.allocate_ui_with_layout(vec2(who_w, 22.0), Layout::left_to_right(Align::Center), |ui| {
ui.set_max_width(who_w);
ui.add(egui::Label::new(RichText::new(format!("{name} · {from}{gap}{}", t("開的"))).size(FONT_SM).color(p.text2)).truncate());
});
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
let c = status_color(task.status, p);
Frame::new().fill(c.gamma_multiply(0.14)).corner_radius(R_M).inner_margin(Margin::symmetric(8, 2)).show(ui, |ui| {
ui.label(RichText::new(label).size(FONT_XS).color(c).strong());
});
});
});
ui.add(egui::Label::new(RichText::new(&task.text).size(FONT_BASE).color(p.text)).truncate());
let mut facts = vec![format!("{} {}", t("在"), task.computer)];
if task.steps > 0 {
facts.push(if task.failed > 0 { format!("{} {}({} {})", task.steps, t("步"), task.failed, t("步失敗")) } else { format!("{} {}", task.steps, t("步")) });
}
facts.push(format!("{} {}", t("最後動靜"), crate::pages::ago(task.heartbeat.max(task.at), now)));
ui.add(egui::Label::new(RichText::new(facts.join(" · ")).size(FONT_XS).color(p.text3)).truncate());
if !task.doing.is_empty() {
let lead = if task.status.active() { t("現在:") } else { t("最後一步:") };
ui.add(egui::Label::new(RichText::new(format!("{lead}{}", task.doing)).size(FONT_XS).color(p.text2)).truncate());
}
if !task.why.is_empty() && task.why != task.doing {
let c = if task.status == Status::Failed { p.danger } else { p.text2 };
ui.add(egui::Label::new(RichText::new(&task.why).size(FONT_XS).color(c)).truncate());
}
let files: Vec<String> = task.artifacts.iter().map(|a| format!("{} {}", a.name, mark(a.delivery))).collect();
let level = format!("{} {}", t("證據"), t(task.evidence.label()));
let foot = if files.is_empty() { level } else { format!("{}:{} · {level}", t("產物"), files.join("、")) };
let r = ui.add(egui::Label::new(RichText::new(foot).size(FONT_XS).color(p.text3)).truncate());
let mut tip: Vec<String> = task.artifacts.iter().map(|a| a.line()).collect();
tip.extend(task.proof.iter().cloned());
if !tip.is_empty() {
r.on_hover_text(tip.join("\n"));
}
ui.min_rect().expand2(vec2(16.0, 14.0))
});
// (Its place in the list too: two openings written in the same millisecond share a task
// id, and two cards on one id fought over one press.)
let r = ui.interact(card, egui::Id::unique(("task-card", &task.id, i)), egui::Sense::click());
if r.hovered() {
ui.painter().rect_stroke(card, R_L, Stroke::new(1.0, p.text3), egui::StrokeKind::Inside);
}
r.on_hover_cursor(egui::CursorIcon::PointingHand).clicked()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn test_app(ctx: &egui::Context, name: &str) -> App {
App::new(ctx, Some(std::env::temp_dir().join(format!("anybot-tasks-{name}.png"))))
}
/// The deliver wake tasks.rs follows is the one deliver_ui writes: the turn it starts goes on
/// with the task that handed the file over.
#[test]
fn a_deliver_wake_goes_on_with_the_task_that_sent_the_file() {
let ctx = egui::Context::default();
let mut app = test_app(&ctx, "deliver");
let id = app.state.bots[0].id;
let wake = super::super::deliver_ui::wake_text("a.png", "att9", "iPhone", "這台裝置讀不出這個檔案");
let b = app.state.bot_mut(id).unwrap();
b.messages = vec![
Message { at: 1_000, ..Message::user("畫一張圖") },
Message { at: 1_100, attachments: vec![crate::attach::Attachment { name: "a.png".into(), id: "att9".into(), ..Default::default() }], ..Message::assistant("好了", "") },
Message { at: 2_000, wake: true, ..Message::user(&wake) },
Message { at: 2_100, ..Message::assistant("換成 JPG 再傳一次", "") },
]
.into();
app.tasks_tick(true);
let mine: Vec<&Task> = app.tk.list.iter().filter(|t| t.bot == id).collect();
assert_eq!(mine.len(), 1, "{mine:?}");
assert_eq!((mine[0].text.as_str(), mine[0].heartbeat), ("畫一張圖", 2_100));
}
/// What waits on the brain reaches the task and the bots' list_tasks.
#[test]
fn a_card_waiting_makes_its_task_wait_and_the_bot_reads_it() {
let ctx = egui::Context::default();
let mut app = test_app(&ctx, "wait");
let id = app.state.bots[0].id;
app.state.bot_mut(id).unwrap().messages = vec![
Message { at: 1_000, ..Message::user("整理報表") },
Message { at: 1_100, tool_calls: vec![crate::model::ToolCall { id: "c1".into(), name: "shell".into(), args: r#"{"command":"ls"}"#.into(), status: ToolStatus::Waiting }], ..Message::assistant("", "") },
]
.into();
let (tx, _rx) = channel();
app.approvals.insert(id, Approval { call_id: "c1".into(), tool: "shell".into(), reason: "執行指令:ls".into(), grant: "ls".into(), reply: tx, kind: ApprovalKind::Action });
app.tasks_tick(true);
let t = app.tk.list.iter().find(|t| t.bot == id).unwrap();
assert_eq!((t.status, t.why.as_str()), (Status::Waiting, "等你允許:執行指令"));
assert!(tasks::attention(&app.tk.list, crate::model::now_ms()) >= 1);
let text = app.list_tasks_text(id, "{}");
assert!(text.contains("〔等你〕") && text.contains("整理報表") && text.contains("等你允許:執行指令"), "{text}");
}
}