AnyBot/src/app/chat_ui.rs

1286 lines
70 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.

// 對話內容, like the original (captured from the reference assistant itself):
// • the bot's words in grey bubbles on the left (no avatar, no model name, no tool rows);
// the person's in the bot's colour on the right, text always reading left to right;
// • the date in small grey text between messages that are far apart;
// • on hover, three small buttons next to the bubble: 表情回應, 回覆, ⋯ (steps and thinking
// live behind ⋯);
// • files as cards that open a preview;
// • while it works: a spinning ring and a phrase that shimmers ("正在讀取檔案"…), picked from
// the original's own list by what the bot is doing;
// • motion from the original's tokens: rows fade/rise in over 240 ms, a reaction pops in over
// 500 ms with a little overshoot, the ring turns every 1.2 s, the shimmer sweeps every 1.4 s.
use super::*;
const ROW_ENTER: f32 = 0.24;
const REACTION_POP: f32 = 0.5;
const SPIN_SECS: f64 = 1.2;
const SHIMMER_SECS: f64 = 1.4;
/// Reactions offered at once (the rest are in "更多表情符號").
const QUICK: [&str; 6] = ["❤️", "👍", "😂", "🎉", "🙏", "👀"];
const MORE: [&str; 24] = ["😊", "😍", "🥹", "😮", "😢", "😡", "🤔", "👏", "🙌", "💪", "🔥", "✨", "✅", "❌", "💯", "🚀", "☕", "🍰", "🌟", "💡", "📌", "👌", "🤝", "🫶"];
/// 回到底部 shows once the chat is scrolled this far above its newest message (the phone's too).
const JUMP_BOTTOM_AFTER: f32 = 400.0;
/// A press keeps pulling the chat down at most this long, so the person can always scroll again.
const JUMP_BOTTOM_SECS: f64 = 1.0;
const JUMP_BOTTOM_FADE: f32 = 0.15;
const JUMP_BOTTOM_SIZE: f32 = 36.0;
/// Between the button and the bottom of the chat (the top of the composer).
const JUMP_BOTTOM_GAP: f32 = 12.0;
/// The working row's words when no step is running: thinking before the first step, looking at
/// what a step brought back between steps, writing once the answer has words. They take turns
/// every [`PHRASE_SECS`].
const THINKING: [&str; 3] = ["正在思考", "正在琢磨", "正在整理思緒"];
const BETWEEN: [&str; 3] = ["正在看剛才的結果", "正在想下一步", "正在確認進度"];
const WRITING: [&str; 2] = ["正在寫回覆", "正在整理回答"];
/// How long one phrase stays before the next takes its place.
pub const PHRASE_SECS: f64 = 3.0;
/// The longest detail in a phrase (a search, a site, a file, a command).
const DETAIL_CHARS: usize = 24;
/// What the bot is doing now, in a few words: the running step — what it is and what it is on
/// (「正在搜尋網頁:台北天氣」「正在打開網頁:github.com」「正在執行指令:cargo test」) — or, with
/// none running, a phrase that changes with `tick`. `place`: the computer a screen step is on,
/// when it isn't the bot's own.
pub fn status_phrase(call: Option<(&str, &str)>, place: Option<&str>, waiting: bool, has_text: bool, did_steps: bool, tick: u64) -> String {
let pick = |list: &[&str]| list[(tick as usize) % list.len()].to_string();
if waiting {
return "需要你的輸入".into();
}
match call {
Some((name, args)) => doing(name, args, place),
None if has_text => pick(&WRITING),
None if did_steps => pick(&BETWEEN),
None => pick(&THINKING),
}
}
/// A step's own name: `computer` and `browser` carry the action in their arguments until the
/// step ends (computer + click → computer_use_click).
fn step_name<'a>(name: &'a str, v: &serde_json::Value) -> &'a str {
let action = v["action"].as_str().unwrap_or("").trim();
match name {
crate::computer::TOOL => crate::computer::top_action_tool(action).unwrap_or("computer_use"),
crate::browser::TOOL => crate::browser::action_tool(action).unwrap_or("browser"),
n => n,
}
}
/// What kind of step runs, for the face above the input (its prop): the same reading of the
/// step as the words beside it (see doing).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StepKind {
/// Searching or reading the web, in a browser or not.
Web,
/// Looking at or working a computer's screen.
Screen,
Other,
}
pub fn step_kind(name: &str, args: &str) -> StepKind {
let v = tools::args_of(args);
let name = step_name(name, &v);
if name.starts_with("computer_use") && name != "computer_use_check_permissions" {
StepKind::Screen
} else if crate::web::is_web_tool(name) || name.starts_with("browser") {
StepKind::Web
} else {
StepKind::Other
}
}
/// One step, said the way a person would say what they're doing.
fn doing(name: &str, args: &str, place: Option<&str>) -> String {
let v = tools::args_of(args);
let s = |k: &str| v[k].as_str().unwrap_or("").trim().to_string();
let with = |what: &str, detail: String| {
let d = clip_detail(&detail);
if d.is_empty() { what.to_string() } else { format!("{what}:{d}") }
};
let name = step_name(name, &v);
if name.starts_with("computer_use") {
let verb = match name {
"computer_use_screenshot" => "看螢幕".to_string(),
"computer_use_zoom" => "放大看螢幕".into(),
"computer_use_show" => return "正在把畫面傳給你".into(),
"computer_use_click" => "點擊".into(),
"computer_use_typing" => "打字".into(),
"computer_use_press_key" => "按鍵".into(),
"computer_use_scroll" => "捲動畫面".into(),
"computer_use_mouse_move" => "移動滑鼠".into(),
"computer_use_drag" => "拖曳".into(),
"computer_use_open_app" => match clip_detail(&s("app")) {
a if a.is_empty() => "打開 App".into(),
a => format!("打開 {a}"),
},
"computer_use_menu_click" => "走選單".into(),
"computer_use_fill_form" => "填表單".into(),
"computer_use_wait_for" => "等畫面出現".into(),
"computer_use_batch" => "依序操作畫面".into(),
"computer_use_check_permissions" => "檢查螢幕權限".into(),
"computer_use_intent" => "調整電腦設定".into(),
_ => "操作畫面".into(),
};
return match place {
Some(p) => format!("正在「{p}」上{verb}"),
None => format!("正在{verb}"),
};
}
let url = s("url");
let file = || s("path").trim_end_matches('/').rsplit('/').next().unwrap_or("").to_string();
match name {
"web_fetch" => match search_words(&url) {
Some(q) => with("正在搜尋網頁", q),
None => with("正在讀取網頁", site(&url)),
},
"browser_open" => match search_words(&url) {
Some(q) => with("正在搜尋網頁", q),
None => with("正在打開網頁", site(&url)),
},
"browser_read" => "正在閱讀網頁".into(),
"browser_profiles" => "正在切換瀏覽器設定檔".into(),
"browser_elements" => "正在看網頁上有什麼".into(),
"browser_click" => "正在點網頁上的按鈕".into(),
"browser_hover" => "正在網頁上移動滑鼠".into(),
"browser_type" => "正在網頁上打字".into(),
"browser_press" => "正在網頁上按鍵".into(),
"browser_select" => "正在網頁上選擇".into(),
"browser_scroll" => "正在捲動網頁".into(),
"browser_wait" => "正在等網頁載入".into(),
"browser_find" => with("正在網頁上找字", s("text")),
"browser_table" => "正在讀網頁上的表格".into(),
"browser_screenshot" => "正在看網頁畫面".into(),
"browser_tabs" => "正在切換分頁".into(),
"browser_back" => "正在回上一頁".into(),
"browser_upload" => "正在上傳檔案到網頁".into(),
"browser_download" => "正在從網頁下載".into(),
"browser_pdf" => "正在把網頁存成 PDF".into(),
"browser_dialog" => "正在處理網頁對話框".into(),
"browser_eval" => "正在網頁上執行程式".into(),
"browser_fill_login" => with("正在用保險庫登入", s("site")),
"browser_fill_card" => "正在填入卡片資料".into(),
"browser_fill_contact" => "正在填入聯絡資訊".into(),
"vault_list" => "正在查看保險庫".into(),
"shell" => with("正在執行指令", s("command").lines().next().unwrap_or("").to_string()),
"read_terminal" => "正在看背景指令的結果".into(),
"write_terminal" => "正在輸入到背景指令".into(),
"read_file" => with("正在讀取檔案", file()),
"edit_file" => with("正在修改檔案", file()),
"list_dir" => with("正在查看資料夾", file()),
"search" => with("正在搜尋檔案", s("pattern")),
"search_documents" => with("正在翻你的文件", s("query")),
"open_for_person" => "正在打開給你看".into(),
"send_file" => "正在傳檔案給你".into(),
"send_to_device" => "正在傳到你的另一台裝置".into(),
"publish_site" => "正在發布網站".into(),
"show_card" => "正在整理成卡片".into(),
"submit_plan" => "正在交計畫給你看".into(),
"update_plan" => "正在更新計畫進度".into(),
"react" => "正在按表情".into(),
"view_demo_step" => "正在看示範".into(),
"place_call" => "正在打電話".into(),
"send_sms" => "正在傳簡訊".into(),
"post_to_x" => "正在 X 上發文".into(),
"remember" => "正在記下來".into(),
"forget" => "正在忘掉".into(),
"search_memory" => with("正在翻記憶", s("query")),
"use_skill" => with("正在讀技能", s("name")),
agent::REPLAY_TOOL => with("正在照技能重做", s("name")),
"save_skill" | "skillify" => "正在存成技能".into(),
"skill_install" => "正在安裝技能".into(),
"delete_skill" => "正在刪除技能".into(),
"message_bot" => with("正在交給另一個 Bot", s("bot")),
"ask_bot" => with("正在問另一個 Bot", s("bot")),
"teach_skill" => with("正在教技能給", s("bot")),
"list_routines" => "正在查看例行任務".into(),
"create_routine" | "update_routine" | "delete_routine" => "正在安排例行任務".into(),
"run_routine_now" => "正在執行例行任務".into(),
"list_bots" | "create_bot" | "update_bot" => "正在設定 Bot".into(),
"create_group" | "move_to_group" | "rename_group" | "delete_group" => "正在整理 Bot 群組".into(),
"list_computers" => "正在查看有哪些電腦".into(),
"update_settings" => "正在修改設定".into(),
"write_page" => with("正在寫頁面", s("title")),
"read_page" | "list_pages" => "正在看頁面".into(),
"ios_read_reminders" => "正在看提醒事項".into(),
"ios_write_reminders" => "正在修改提醒事項".into(),
"mobile_read_calendar" => "正在看行事曆".into(),
"mobile_write_calendar" => "正在修改行事曆".into(),
"mobile_read_contacts" => "正在查聯絡人".into(),
"mac_read_notes" => "正在讀備忘錄".into(),
"mac_write_notes" => "正在寫備忘錄".into(),
"mac_read_mail" => "正在讀郵件".into(),
"mac_draft_mail" => "正在起草郵件".into(),
"mac_send_mail" => "正在寄出郵件".into(),
"mac_mail_accounts" => "正在查看郵件帳號".into(),
crate::macapps::SEND_MESSAGE => "正在傳訊息".into(),
tools::HANDOFF_TOOL => "正在等你接手".into(),
crate::ask::TOOL => "正在等你回答".into(),
// mcp__<server>__<tool>: the connector by its name (also when run through use_connector_tool).
n if n.starts_with(crate::mcp::PREFIX) => with("正在用連接器", n[crate::mcp::PREFIX.len()..].split("__").next().unwrap_or("").to_string()),
crate::mcp::USE_TOOL => with("正在用連接器", s("tool").strip_prefix(crate::mcp::PREFIX).and_then(|r| r.split("__").next()).unwrap_or("").to_string()),
crate::mcp::FIND_TOOL => "正在找連接器的工具".into(),
n => match crate::remote::tool_label(n) {
"工具" | "App 操作" | "網頁" | "瀏覽器" | "Mac App" => "正在處理".into(),
l => format!("正在{l}"),
},
}
}
/// The words of a web search, when the address is one (Google, Bing, DuckDuckGo, Yahoo, Baidu,
/// Brave, or any 「…/search?q=…」).
pub fn search_words(url: &str) -> Option<String> {
let rest = url.split_once("://").map(|x| x.1).unwrap_or(url);
let (place, query) = rest.split_once('?')?;
let (host, path) = place.split_once('/').map(|(h, p)| (h.to_lowercase(), format!("/{p}"))).unwrap_or((place.to_lowercase(), String::new()));
let searchy = host.contains("duckduckgo.") || host.contains("bing.com") || host.contains("baidu.com") || host.starts_with("search.") || path.contains("search") || path == "/s";
if !searchy {
return None;
}
query.split('&').filter_map(|kv| kv.split_once('=')).find(|(k, _)| matches!(*k, "q" | "query" | "p" | "wd" | "text" | "keyword" | "search_query")).map(|(_, v)| url_decode(v)).filter(|w| !w.trim().is_empty())
}
/// 「https://www.github.com/a/b」 → 「github.com」.
fn site(url: &str) -> String {
let rest = url.split_once("://").map(|x| x.1).unwrap_or(url);
let host = rest.split(['/', '?', '#']).next().unwrap_or("");
host.strip_prefix("www.").unwrap_or(host).to_string()
}
fn url_decode(s: &str) -> String {
let b = s.as_bytes();
let mut out = Vec::with_capacity(b.len());
let mut i = 0;
while i < b.len() {
match b[i] {
b'+' => out.push(b' '),
b'%' if i + 2 < b.len() => {
let hex = |c: u8| (c as char).to_digit(16);
match (hex(b[i + 1]), hex(b[i + 2])) {
(Some(h), Some(l)) => {
out.push((h * 16 + l) as u8);
i += 2;
}
_ => out.push(b'%'),
}
}
c => out.push(c),
}
i += 1;
}
String::from_utf8_lossy(&out).trim().to_string()
}
fn clip_detail(s: &str) -> String {
let s = s.split_whitespace().collect::<Vec<_>>().join(" ");
if s.chars().count() <= DETAIL_CHARS {
return s;
}
format!("{}…", s.chars().take(DETAIL_CHARS).collect::<String>())
}
/// Shift+Enter in the input: a new line — and in a list, the next item's marker
/// (「1. 買菜」 → 「2. 」, 「- 」 → 「- 」). Shift+Enter on an item that is still empty ends the list
/// instead (the marker goes, like in a notes app). `start..end` is the selection, in characters.
/// Returns the text and where the caret goes.
pub fn list_newline(text: &str, start: usize, end: usize) -> (String, usize) {
let chars: Vec<char> = text.chars().collect();
let (start, end) = (start.min(chars.len()), end.min(chars.len()).max(start.min(chars.len())));
let line_start = chars[..start].iter().rposition(|c| *c == '\n').map(|i| i + 1).unwrap_or(0);
let line_end = chars[end..].iter().position(|c| *c == '\n').map(|i| end + i).unwrap_or(chars.len());
let line: String = chars[line_start..line_end].iter().collect();
let plain = |chars: &[char]| {
let mut out: Vec<char> = chars[..start].to_vec();
out.push('\n');
out.extend_from_slice(&chars[end..]);
(out.into_iter().collect::<String>(), start + 1)
};
let Some((marker_len, next)) = list_marker(&line) else { return plain(&chars) };
// The caret has to be past the marker (Shift+Enter inside 「1. 」 is just a new line).
if start < line_start + marker_len {
return plain(&chars);
}
let item_empty = line.chars().skip(marker_len).all(char::is_whitespace);
if item_empty && start == end {
// An empty item: the list ends here.
let indent: String = line.chars().take_while(|c| *c == ' ' || *c == '\t').collect();
let mut out: Vec<char> = chars[..line_start].to_vec();
out.extend(indent.chars());
let at = out.len();
out.extend_from_slice(&chars[line_end..]);
return (out.into_iter().collect(), at);
}
let mut out: Vec<char> = chars[..start].to_vec();
out.push('\n');
out.extend(next.chars());
let at = out.len();
out.extend_from_slice(&chars[end..]);
(out.into_iter().collect(), at)
}
/// A list item's marker at the start of `line`: its length in characters, and the marker the
/// next item gets (same indent; a number one up). 「1. 」「2) 」「3、」「- 」「* 」「• 」「- [ ] 」.
fn list_marker(line: &str) -> Option<(usize, String)> {
let indent: String = line.chars().take_while(|c| *c == ' ' || *c == '\t').collect();
let rest: Vec<char> = line.chars().skip(indent.chars().count()).collect();
let n = indent.chars().count();
let spaces = |from: usize| rest[from.min(rest.len())..].iter().take_while(|c| **c == ' ').count();
let digits = rest.iter().take_while(|c| c.is_ascii_digit()).count();
if (1..=3).contains(&digits) {
let num: u32 = rest[..digits].iter().collect::<String>().parse().ok()?;
let delim = *rest.get(digits)?;
let gap = spaces(digits + 1);
return match delim {
'.' | ')' if gap > 0 => Some((n + digits + 1 + gap, format!("{indent}{}{delim}{}", num + 1, " ".repeat(gap)))),
'、' => Some((n + digits + 1 + gap, format!("{indent}{}、{}", num + 1, " ".repeat(gap)))),
_ => None,
};
}
let bullet = *rest.first()?;
if !matches!(bullet, '-' | '*' | '•') {
return None;
}
let gap = spaces(1);
if gap == 0 {
return None;
}
let after: String = rest[1 + gap..].iter().take(4).collect();
if after.starts_with("[ ] ") || after.starts_with("[x] ") || after.starts_with("[X] ") {
return Some((n + 1 + gap + 4, format!("{indent}{bullet}{}[ ] ", " ".repeat(gap))));
}
Some((n + 1 + gap, format!("{indent}{bullet}{}", " ".repeat(gap))))
}
/// Enter and Shift+Enter in the input, taken before the text field sees them: Enter sends,
/// Shift+Enter makes a new line (list_newline). egui's own shortcut matching ignores Shift unless
/// it is asked for, which made Shift+Enter send too; these are read by hand. (Cmd/Ctrl/Alt+Enter
/// are left alone.)
pub fn take_enter(i: &mut egui::InputState) -> (bool, bool) {
let (mut plain, mut shift) = (false, false);
i.events.retain(|e| match e {
egui::Event::Key { key: Key::Enter, pressed: true, modifiers, .. } if !modifiers.command && !modifiers.ctrl && !modifiers.alt && !modifiers.mac_cmd => {
if modifiers.shift {
shift = true;
} else {
plain = true;
}
false
}
_ => true,
});
(plain, shift)
}
/// "11月2日週一 上午9:50" (today: just the time).
pub fn date_label(ms: i64) -> String {
use chrono::{Datelike, Local, TimeZone, Timelike};
let Some(d) = Local.timestamp_millis_opt(ms).single() else { return String::new() };
let now = Local::now();
let wd = ["週一", "週二", "週三", "週四", "週五", "週六", "週日"][d.weekday().num_days_from_monday() as usize];
let (h, ampm) = match d.hour() {
0 => (12, "上午"),
h @ 1..=11 => (h, "上午"),
12 => (12, "下午"),
h => (h - 12, "下午"),
};
let time = format!("{}{}:{:02}", t(ampm), h, d.minute());
if d.date_naive() == now.date_naive() {
time
} else if d.year() == now.year() {
format!("{}月{}日{} {time}", d.month(), d.day(), t(wd))
} else {
format!("{}年{}月{}日 {time}", d.year(), d.month(), d.day())
}
}
/// An ease with a small overshoot (the reaction pop).
fn pop(x: f32) -> f32 {
let x = x.clamp(0.0, 1.0);
let c1 = 1.70158;
let c3 = c1 + 1.0;
1.0 + c3 * (x - 1.0).powi(3) + c1 * (x - 1.0).powi(2)
}
fn ease_out(x: f32) -> f32 {
1.0 - (1.0 - x.clamp(0.0, 1.0)).powi(3)
}
/// The indeterminate ring (the original's working arc).
pub fn spinner(ui: &mut egui::Ui, size: f32, col: Color32) {
let (rect, _) = ui.allocate_exact_size(vec2(size, size), egui::Sense::hover());
let time = ui.input(|i| i.time);
let c = rect.center();
let r = size / 2.0 - 1.5;
ui.painter().circle_stroke(c, r, Stroke::new(2.0, col.gamma_multiply(0.2)));
let start = (time / SPIN_SECS * std::f64::consts::TAU) as f32;
let pts: Vec<egui::Pos2> = (0..=16).map(|i| {
let a = start + 1.7 * i as f32 / 16.0;
c + vec2(a.cos(), a.sin()) * r
}).collect();
ui.painter().add(egui::Shape::line(pts, Stroke::new(2.0, col)));
ui.ctx().request_repaint();
}
/// Text with a light band sweeping across it (the original's sand-shimmer-text).
pub fn shimmer(ui: &mut egui::Ui, text: &str, base: Color32, bright: Color32, size: f32) {
let time = ui.input(|i| i.time);
let chars: Vec<char> = text.chars().collect();
let n = chars.len() as f32;
let pos = ((time % SHIMMER_SECS) / SHIMMER_SECS) as f32 * (n + 6.0) - 3.0;
let mut job = egui::text::LayoutJob::default();
for (i, ch) in chars.iter().enumerate() {
let k = (1.0 - ((i as f32 - pos).abs() / 3.0)).clamp(0.0, 1.0);
let col = base.lerp_to_gamma(bright, k);
job.append(&ch.to_string(), 0.0, egui::TextFormat { font_id: egui::FontId::proportional(size), color: col, ..Default::default() });
}
ui.label(job);
ui.ctx().request_repaint();
}
impl App {
/// 先顯示: the words just sent that the chat doesn't have yet, dimmed, under the newest
/// message. One goes once the chat shows it (the bot read it, or the brain sent it back),
/// or after a while.
pub(super) fn sending_bubbles(&mut self, ui: &mut egui::Ui, bot: &Bot) {
let p = self.pal;
let working = self.streams.contains_key(&bot.id);
let Some(list) = self.sending.get_mut(&bot.id) else { return };
let tail: Vec<&str> = bot.messages.iter().rev().take(16).map(|m| m.text.as_str()).collect();
list.retain(|(text, at)| {
let shown = tail.iter().any(|t| t.trim() == text || t.trim_end().ends_with(text.as_str()));
!shown && at.elapsed().as_secs() < if working { 600 } else { 8 }
});
for (text, at) in list.iter() {
ui.with_layout(Layout::right_to_left(Align::Min), |ui| {
Frame::new().fill(p.hover).stroke(Stroke::new(1.0, p.border)).corner_radius(BUBBLE_RADIUS).inner_margin(bubble_margin()).show(ui, |ui| {
ui.set_max_width(message_max_width(ui.available_width()));
ui.label(RichText::new(text).size(FONT_BASE).color(p.text2));
});
});
ui.with_layout(Layout::right_to_left(Align::Min), |ui| {
let note = if at.elapsed().as_millis() < 1200 { t("傳送中…") } else if working { t("已排入,它下一步會看到") } else { t("已送出") };
ui.label(RichText::new(note).size(FONT_XS).color(p.text3));
});
ui.add_space(6.0);
}
if !list.is_empty() {
ui.ctx().request_repaint_after(std::time::Duration::from_millis(400));
}
}
/// One message of the chat.
pub(super) fn chat_message(&mut self, ui: &mut egui::Ui, ctx: &egui::Context, bot: &Bot, m: &Message, last: bool) {
let p = self.pal;
let idx = self.msg_index;
// Tool results and empty step messages stay out of the chat (⋯ › 顯示步驟 shows them).
if m.role == Role::Tool {
return;
}
let has_body = !m.text.trim().is_empty() || !m.attachments.is_empty() || m.tool_calls.iter().any(|c| c.name == "show_card" || c.name == crate::plan::SUBMIT_TOOL || is_talk(&c.name)) || !crate::pages::ids_in(&m.tool_calls).is_empty();
let steps_open = self.steps_open.contains(&(bot.id, idx));
if m.role == Role::Assistant && !has_body && !m.summary && !steps_open {
return;
}
// The date, when this message is far from the one before it.
if m.at > 0 {
let prev = bot.messages[..idx].iter().rev().find(|x| x.at > 0 && x.role != Role::Tool).map(|x| x.at);
let new_day = |a: i64, b: i64| {
use chrono::TimeZone;
let d = |ms| chrono::Local.timestamp_millis_opt(ms).single().map(|x| x.date_naive());
d(a) != d(b)
};
if prev.map(|pa| m.at - pa > 30 * 60_000 || new_day(pa, m.at)).unwrap_or(true) {
ui.add_space(10.0);
ui.vertical_centered(|ui| ui.label(RichText::new(date_label(m.at)).size(FONT_XS).color(p.text3)));
ui.add_space(10.0);
}
}
// New messages fade and rise in (240 ms).
let alpha = if m.at > self.started_ms {
let t0 = *self.appeared.entry((bot.id, idx)).or_insert_with(Instant::now);
let e = t0.elapsed().as_secs_f32() / ROW_ENTER;
if e < 1.0 {
ctx.request_repaint();
}
ease_out(e)
} else {
1.0
};
ui.scope(|ui| {
ui.set_opacity(alpha);
ui.add_space((1.0 - alpha) * 8.0);
match m.role {
// 支線回報 handed to the running turn: one small line (the card has the rest).
Role::User if m.branch != 0 => {
ui.vertical_centered(|ui| ui.label(RichText::new(t("(支線的結果已交給正在做事的主線)")).size(FONT_XS).color(p.text3)));
ui.add_space(6.0);
}
Role::User => self.user_message(ui, ctx, bot, m, last, idx),
_ if m.summary => {
Frame::new().stroke(Stroke::new(1.0, p.border)).corner_radius(R_L).inner_margin(Margin::symmetric(12, 8)).show(ui, |ui| {
crate::icons::label(ui, crate::icons::Icon::Summary, &t("較早的對話已整理成摘要"), 13.0, p.text2);
egui::CollapsingHeader::new(RichText::new(t("展開摘要")).size(FONT_SM).color(p.text3)).id_salt(("summary", bot.id, idx)).show(ui, |ui| {
self.markdown(ui, &m.text, p.text2, false);
});
});
ui.add_space(10.0);
}
// 支線: its card, where it was asked.
_ if m.note && m.branch != 0 => self.branch_card(ui, ctx, bot, m),
// 目標: AnyBot's own line about the goal (set, met, paused…).
_ if m.note => self.goal_note_row(ui, m),
// Where AnyBot stopping cut a turn off: what it was doing and what may have run,
// with 「繼續」 while it is the newest thing in the chat.
_ if m.interrupted => {
let can_go_on = last && !self.streams.contains_key(&bot.id);
let mut go_on = false;
Frame::new().stroke(Stroke::new(1.0, p.border)).corner_radius(R_L).inner_margin(Margin::symmetric(12, 10)).show(ui, |ui| {
ui.label(RichText::new(&m.text).size(FONT_SM).color(p.text2));
if can_go_on {
ui.add_space(6.0);
go_on = ui.button(RichText::new(t("繼續")).size(FONT_SM)).clicked();
}
});
ui.add_space(10.0);
if go_on {
self.resume_turn(ctx, bot.id);
}
}
_ => self.bot_message(ui, ctx, bot, m, last, idx),
}
});
}
fn user_message(&mut self, ui: &mut egui::Ui, ctx: &egui::Context, bot: &Bot, m: &Message, last: bool, idx: usize) {
let p = self.pal;
let streaming = self.streams.contains_key(&bot.id);
for a in m.attachments.clone() {
ui.with_layout(Layout::right_to_left(Align::Min), |ui| self.file_card(ui, &a));
ui.add_space(6.0);
}
// Messages that woke the bot (a routine, a trigger, a channel, another bot) carry a tag:
// shown as a small line with an icon above the bubble, not inside it.
let (tag, body) = wake_tag(&m.text);
if let Some((icon, label)) = tag {
ui.with_layout(Layout::right_to_left(Align::Min), |ui| {
crate::icons::label(ui, icon, &t(label), 12.0, p.text3);
});
ui.add_space(2.0);
}
let shown_text = body.to_string();
if !m.text.trim().is_empty() {
let hover_id = egui::Id::unique(("hover-user", bot.id, idx));
let was_hovered = ctx.data(|d| d.get_temp::<bool>(hover_id)).unwrap_or(false);
let row = ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
let (fill, text_col) = self.user_bubble(bot);
let max_w = message_max_width(ui.available_width());
// As wide as the words (up to the column's limit), lines reading left to right.
let rich = RichText::new(&shown_text).size(TRANSCRIPT_FONT).line_height(Some(TRANSCRIPT_LINE_HEIGHT)).color(text_col);
let text_w = egui::WidgetText::from(rich.clone()).into_galley(ui, Some(egui::TextWrapMode::Extend), f32::INFINITY, egui::FontSelection::Default).size().x;
let inner_w = text_w.min(max_w - 24.0).max(8.0);
// (Its corner toward the person is the small one.)
Frame::new().fill(fill).corner_radius(CornerRadius { nw: 20, ne: 20, sw: 20, se: 6 }).inner_margin(bubble_margin()).show(ui, |ui| {
ui.set_width(inner_w);
ui.with_layout(Layout::top_down(Align::Min), |ui| {
ui.add(egui::Label::new(rich).wrap());
});
});
// Hover: ↩ and ⋯ to the left of the bubble (kept while the menu is open).
let menu_open = self.menu_for == Some((bot.id, idx)) && egui::Popup::is_any_open(ctx);
if was_hovered || menu_open {
ui.add_space(4.0);
if hover_icon(ui, crate::icons::Icon::Reply, p).on_hover_text(t("回覆")).clicked() {
self.quoting.insert(bot.id, m.text.clone());
}
let more = hover_icon(ui, crate::icons::Icon::More, p).on_hover_text(t("更多訊息操作"));
if more.clicked() {
self.menu_for = Some((bot.id, idx));
}
egui::Popup::menu(&more).show(|ui| {
ui.set_min_width(menu_ui::MENU_W);
if menu_ui::item(ui, p, crate::icons::Icon::Copy, "複製").clicked() {
crate::platform::copy_text(ctx, &m.text);
ui.close();
}
if menu_ui::item(ui, p, crate::icons::Icon::Reply, "回覆").clicked() {
self.quoting.insert(bot.id, m.text.clone());
ui.close();
}
});
}
});
let hovered = row.response.contains_pointer();
if hovered != was_hovered {
ctx.data_mut(|d| d.insert_temp(hover_id, hovered));
ctx.request_repaint();
}
}
// The bot's reactions on this message.
if !m.reactions.is_empty() {
ui.with_layout(Layout::right_to_left(Align::Min), |ui| {
ui.add_space(6.0);
for r in m.reactions.iter().rev() {
self.reaction_pill(ui, bot.id, idx, r, false);
}
});
}
// 記憶 this message carried to the model.
if !m.memories.is_empty() {
let mems = m.memories.clone();
self.mem_carried(ui, ctx, bot.id, idx, &mems);
}
// A message that never got an answer can be sent again.
if last && !streaming {
ui.with_layout(Layout::right_to_left(Align::Min), |ui| {
if small_button(ui, "重新傳送", p).clicked() {
self.start_reply(ctx, bot.id);
}
ui.label(RichText::new(t("還沒有回覆")).size(FONT_XS).color(p.text3));
});
}
ui.add_space(10.0);
}
fn bot_message(&mut self, ui: &mut egui::Ui, ctx: &egui::Context, bot: &Bot, m: &Message, last: bool, idx: usize) {
let p = self.pal;
let streaming = last && self.streams.contains_key(&bot.id);
// 支線回報: whose words these are.
if let Some(r) = bot.branches.iter().find(|r| r.id == m.branch && m.branch != 0) {
ui.horizontal(|ui| {
ui.add_space(4.0);
crate::icons::label(ui, crate::icons::Icon::Template, &format!("{}「{}」", t("支線"), r.task.chars().take(40).collect::<String>()), 12.0, p.text3);
});
ui.add_space(2.0);
}
// In a group chat, who said it.
if let Some(a) = self.state.bot(m.author).filter(|_| m.author != 0) {
ui.horizontal(|ui| {
ui.add_space(4.0);
ui.label(RichText::new(&a.name).size(FONT_XS).color(p.text3));
});
ui.add_space(2.0);
}
if !m.text.trim().is_empty() {
let hover_id = egui::Id::unique(("hover-bot", bot.id, idx));
let was_hovered = ctx.data(|d| d.get_temp::<bool>(hover_id)).unwrap_or(false);
let row = ui.horizontal_top(|ui| {
let max_w = message_max_width(ui.available_width());
// The bot's words sit on the page like a document; only an error gets a block — a
// quiet one: the page's muted fill, a small red mark, the words in ink (red words
// on pink were the loudest thing in the chat).
let (fill, margin) = if m.error { (p.muted, bubble_margin()) } else { (Color32::TRANSPARENT, Margin::symmetric(2, 2)) };
Frame::new().fill(fill).corner_radius(R_L).inner_margin(margin).show(ui, |ui| {
ui.set_max_width(max_w);
if m.error {
ui.horizontal_top(|ui| {
ui.spacing_mut().item_spacing.x = crate::theme::sp::S2;
let (ir, _) = ui.allocate_exact_size(vec2(16.0, TRANSCRIPT_LINE_HEIGHT), egui::Sense::hover());
crate::icons::paint(ui.painter(), egui::Rect::from_center_size(ir.center(), vec2(15.0, 15.0)), crate::icons::Icon::Alert, p.danger);
ui.with_layout(Layout::top_down(Align::Min), |ui| self.markdown(ui, &m.text, p.text, streaming));
});
} else {
ui.with_layout(Layout::top_down(Align::Min), |ui| self.markdown(ui, &m.text, p.text, streaming));
}
});
// Hover: 表情回應, 回覆, ⋯ to the right of the bubble (like the original). They stay
// while one of their menus is open, so moving onto the menu doesn't close it.
let menu_open = self.menu_for == Some((bot.id, idx)) && egui::Popup::is_any_open(ctx);
if (was_hovered || menu_open) && !streaming {
ui.add_space(2.0);
ui.vertical(|ui| {
ui.add_space(6.0);
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 2.0;
let react = hover_icon(ui, crate::icons::Icon::Smile, p).on_hover_text(t("新增表情回應"));
egui::Popup::menu(&react).show(|ui| {
ui.add_space(2.0);
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 4.0;
ui.add_space(4.0);
for e in QUICK {
if ui.add(egui::Button::new(RichText::new(e).size(FONT_H3)).frame(false).min_size(vec2(34.0, 34.0)).corner_radius(R_M)).clicked() {
self.toggle_reaction(bot.id, idx, e);
ui.close();
}
}
});
menu_ui::sep(ui, p);
menu_ui::caption(ui, p, "更多表情符號");
ui.add_space(4.0);
egui::Grid::new(("more-emoji", bot.id, idx)).spacing(vec2(4.0, 4.0)).show(ui, |ui| {
for (i, e) in MORE.iter().enumerate() {
if ui.add(egui::Button::new(RichText::new(*e).size(FONT_H3)).frame(false).min_size(vec2(30.0, 30.0)).corner_radius(R_M)).clicked() {
self.toggle_reaction(bot.id, idx, e);
ui.close();
}
if i % 8 == 7 {
ui.end_row();
}
}
});
});
if hover_icon(ui, crate::icons::Icon::Reply, p).on_hover_text(t("回覆")).clicked() {
self.quoting.insert(bot.id, m.text.clone());
}
if react.clicked() {
self.menu_for = Some((bot.id, idx));
}
let more = hover_icon(ui, crate::icons::Icon::More, p).on_hover_text(t("更多訊息操作"));
if more.clicked() {
self.menu_for = Some((bot.id, idx));
}
egui::Popup::menu(&more).show(|ui| {
use crate::icons::Icon;
ui.set_min_width(menu_ui::MENU_W);
if menu_ui::item(ui, p, Icon::Copy, "複製").clicked() {
crate::platform::copy_text(ctx, &m.text);
ui.close();
}
if menu_ui::item(ui, p, Icon::Reply, "回覆").clicked() {
self.quoting.insert(bot.id, m.text.clone());
ui.close();
}
if last && m.branch == 0 && (m.author == 0 || !bot.members.is_empty()) && menu_ui::item(ui, p, Icon::Refresh, "重新產生").clicked() {
self.regenerate(ctx, bot.id);
ui.close();
}
// 「重新產生」 overwrites; one level of undo per bot, for the session.
if last && !self.streams.contains_key(&bot.id) && !bot.regen_undo.is_empty() && menu_ui::item(ui, p, Icon::History, "還原上一個答案").clicked() {
self.restore_regenerated(bot.id);
ui.close();
}
let steps = self.steps_of(bot, idx);
if steps > 0 || !m.thinking.is_empty() {
let open = self.steps_open.contains(&(bot.id, idx));
let label = if open { t("隱藏步驟") } else { format!("{}({steps})", t("顯示步驟")) };
if menu_ui::item_text(ui, p, Some(Icon::Template), &label).clicked() {
if open {
self.steps_open.remove(&(bot.id, idx));
} else {
self.steps_open.insert((bot.id, idx));
}
ui.close();
}
}
if !m.via.is_empty() {
menu_ui::sep(ui, p);
menu_ui::caption(ui, p, &tidy_dots(&m.via));
}
});
});
});
}
});
let hovered = row.response.contains_pointer();
if hovered != was_hovered {
ctx.data_mut(|d| d.insert_temp(hover_id, hovered));
ctx.request_repaint();
}
}
// Steps and thinking, when unfolded from ⋯.
if self.steps_open.contains(&(bot.id, idx)) {
self.steps_list(ui, bot, idx);
}
for c in m.tool_calls.iter().filter(|c| c.name == "show_card") {
ui.add_space(6.0);
card(ui, &c.args, p);
}
// 計畫: the plan handed in, as its card (how it stands; its steps tick while followed).
for c in m.tool_calls.iter().filter(|c| c.name == crate::plan::SUBMIT_TOOL) {
self.plan_card(ui, bot, c);
}
// 同事之間: asking a colleague, or handing it work, is a conversation shown here.
for c in m.tool_calls.iter().filter(|c| is_talk(&c.name)) {
self.talk_card(ui, ctx, bot, m, c);
}
// 頁面 saved in this reply: the card (the page as it is now) — once a reply, under the step
// that saved it last. (Worked out only for a message that saved one: few do.)
if !crate::pages::ids_in(&m.tool_calls).is_empty() {
for id in crate::pages::cards_by_message(&bot.messages).get(idx).cloned().unwrap_or_default() {
ui.add_space(8.0);
self.page_card(ui, id);
}
}
for a in m.attachments.clone() {
ui.add_space(6.0);
self.file_card(ui, &a);
}
if !m.reactions.is_empty() {
ui.add_space(4.0);
ui.horizontal(|ui| {
for r in m.reactions.clone() {
self.reaction_pill(ui, bot.id, idx, &r, true);
}
});
}
ui.add_space(6.0);
// A 支線 that didn't finish: open it again (「重試」 would redo the main line's answer).
if let Some(r) = bot.branches.iter().find(|r| r.id == m.branch && m.branch != 0 && m.error) {
let task = r.task.clone();
ui.horizontal(|ui| {
ui.add_space(4.0);
if ui.add(secondary_button("重開這條支線")).clicked() {
self.btw_command(ctx, bot.id, &task, vec![]);
}
});
ui.add_space(4.0);
} else if m.error && last && !self.streams.contains_key(&bot.id) {
// A failed turn: 「重試」 is the whole point of an error bubble — put it right there.
ui.horizontal(|ui| {
ui.add_space(4.0);
if ui.add(secondary_button("重試")).on_hover_text(t("再問一次這個問題")).clicked() {
self.regenerate(ctx, bot.id);
}
});
ui.add_space(4.0);
}
ui.add_space(6.0);
}
/// How many steps (tool calls) belong to the reply at `idx` and the step messages right
/// before it in the same turn.
fn steps_of(&self, bot: &Bot, idx: usize) -> usize {
self.step_range(bot, idx).map(|i| bot.messages[i].tool_calls.iter().filter(|c| !card_call(&c.name)).count()).sum()
}
fn step_range(&self, bot: &Bot, idx: usize) -> std::ops::Range<usize> {
let mut start = idx;
while start > 0 && bot.messages[start - 1].role != Role::User {
start -= 1;
}
start..idx + 1
}
fn steps_list(&mut self, ui: &mut egui::Ui, bot: &Bot, idx: usize) {
let p = self.pal;
Frame::new().stroke(Stroke::new(1.0, p.border)).corner_radius(R_M).inner_margin(Margin::symmetric(12, 8)).show(ui, |ui| {
ui.set_max_width(message_max_width(ui.available_width()));
for i in self.step_range(bot, idx) {
let m = &bot.messages[i];
if !m.thinking.is_empty() {
egui::CollapsingHeader::new(RichText::new(t("思考過程")).size(FONT_SM).color(p.text3)).id_salt(("think", bot.id, i)).show(ui, |ui| {
ui.label(RichText::new(&m.thinking).size(FONT_SM).color(p.text3));
});
}
for c in m.tool_calls.iter().filter(|c| !card_call(&c.name)) {
use crate::icons::Icon;
let (icon, col) = match c.status {
ToolStatus::Waiting => (Icon::Alert, p.accent),
ToolStatus::Running => (Icon::Loader, p.text2),
ToolStatus::Done => (Icon::CircleCheck, Color32::from_rgb(0x1f, 0xb3, 0x5d)),
ToolStatus::Denied => (Icon::Minus, p.text3),
ToolStatus::Failed => (Icon::CircleX, p.danger),
};
let what: String = crate::remote::tool_label(&c.name).to_string();
let detail: String = if appctl::is_app_tool(&c.name) { appctl::describe(&c.name, &c.args) } else if crate::computer::is_computer_tool(&c.name) { crate::computer::describe(&c.name, &c.args) } else if web::is_web_tool(&c.name) { web::describe(&c.name, &c.args) } else { tools::describe(&c.name, &c.args) };
let result = bot.messages.iter().find(|r| r.role == Role::Tool && r.tool_call_id == c.id).map(|r| r.text.chars().take(4000).collect::<String>());
ui.horizontal(|ui| {
let (r, _) = ui.allocate_exact_size(vec2(14.0, 14.0), egui::Sense::hover());
crate::icons::paint(ui.painter(), r, icon, col);
ui.label(RichText::new(t(&what)).size(FONT_SM).color(p.text2));
let l = ui.add(egui::Label::new(RichText::new(detail.chars().take(80).collect::<String>()).monospace().size(FONT_XS).color(p.text3)).truncate());
if let Some(r) = result {
l.on_hover_text(r);
}
});
}
}
});
ui.add_space(4.0);
}
/// What the bot is doing now, in a few words (None when it isn't working): shown beside its
/// face above the input. `now`: the window's clock, which turns the idle phrases.
pub(super) fn working_phrase(&self, now: f64, bot: &Bot) -> Option<String> {
let live = self.streams.get(&bot.id)?;
let waiting = self.approvals.contains_key(&bot.id);
let last = bot.messages[bot.messages.iter().rposition(|m| m.role == Role::User && !m.steer).unwrap_or(0)..]
.iter().rev().find(|m| m.role == Role::Assistant && !m.note); // this turn's words only
let running = last.and_then(|m| m.tool_calls.iter().rev().find(|c| matches!(c.status, ToolStatus::Running | ToolStatus::Waiting)));
// Where it works, by the computer's name (its own computer is 「<name> 的電腦」).
let named = running.and_then(|c| tools::args_of(&c.args)["computer"].as_str().map(String::from));
let own = crate::model::own_computer_name(&bot.name);
let on_box = running.is_some() && named.as_deref().map(|n| n == own || n == crate::model::BOT_COMPUTER_NAME).unwrap_or(true);
let has_text = last.map(|m| !m.text.trim().is_empty()).unwrap_or(false);
// Steps already done this turn (between them it is looking at what came back).
let from = bot.messages.iter().rposition(|m| m.role == Role::User && !m.steer).unwrap_or(0);
let did_steps = bot.messages[from..].iter().any(|m| m.role == Role::Tool);
let seed = live.turn_id.bytes().fold(0u64, |a, b| a.wrapping_mul(31).wrapping_add(b as u64));
let tick = seed.wrapping_add((now / PHRASE_SECS) as u64);
let place = named.as_deref().filter(|_| !on_box);
// 同事之間: thinking about a colleague's question (or work it handed over) says whose.
let colleague = bot.messages.get(from).filter(|m| m.from_bot != 0 && running.is_none() && !waiting).and_then(|m| self.state.bot(m.from_bot).map(|c| (m.asked, c.name.clone())));
if let (None, Some((asked, who))) = (&live.status, colleague) {
return Some(if asked { format!("正在回答「{who}」的問題…") } else { format!("正在做「{who}」交辦的事…") });
}
Some(live.status.as_deref().map(one_line).unwrap_or_else(|| t(&status_phrase(running.map(|c| (c.name.as_str(), c.args.as_str())), place, waiting, has_text, did_steps, tick))))
}
pub(super) fn toggle_reaction(&mut self, bot_id: u64, idx: usize, e: &str) {
if let Some(b) = self.state.bot_mut(bot_id) {
if let Some(m) = b.messages.get_mut(idx) {
if let Some(i) = m.reactions.iter().position(|x| x == e) {
m.reactions.remove(i);
} else {
m.reactions.push(e.to_string());
self.popped.insert((bot_id, idx, e.to_string()), Instant::now());
}
}
}
self.mark();
}
/// One reaction under a message; new ones pop in. The person can take theirs back.
fn reaction_pill(&mut self, ui: &mut egui::Ui, bot_id: u64, idx: usize, e: &str, mine: bool) {
let p = self.pal;
let scale = match self.popped.get(&(bot_id, idx, e.to_string())) {
Some(t0) if t0.elapsed().as_secs_f32() < REACTION_POP => {
ui.ctx().request_repaint();
pop(t0.elapsed().as_secs_f32() / REACTION_POP)
}
_ => 1.0,
};
let (rect, r) = ui.allocate_exact_size(vec2(34.0, 24.0), egui::Sense::click());
let fill = files_ui::agent_fill(p);
ui.painter().rect_filled(egui::Rect::from_center_size(rect.center(), rect.size() * scale.max(0.01)), 12, if r.hovered() && mine { p.hover } else { fill });
ui.painter().rect_stroke(egui::Rect::from_center_size(rect.center(), rect.size() * scale.max(0.01)), 12, Stroke::new(1.0, p.border), egui::StrokeKind::Inside);
ui.painter().text(rect.center(), egui::Align2::CENTER_CENTER, e, egui::FontId::proportional(FONT_BASE * scale.max(0.01)), p.text);
if mine {
if r.on_hover_text(t("移除這個回應")).clicked() {
self.toggle_reaction(bot_id, idx, e);
}
} else {
r.on_hover_text(t("Bot 的表情回應"));
}
}
/// 回到底部: a round ↓ over the bottom middle of the chat once it's scrolled well up. A press
/// scrolls smoothly to the newest message; from there the chat follows new words again.
pub(super) fn jump_bottom_button(&mut self, ui: &mut egui::Ui, view: egui::Rect, from_bottom: f32) {
let now = ui.input(|i| i.time);
self.jump_bottom = jump_still_on(self.jump_bottom, from_bottom, now);
if self.jump_bottom.is_some() {
ui.ctx().request_repaint();
}
let id = egui::Id::unique("jump-bottom");
let k = ui.ctx().animate_bool_with_time(id, jump_shows(from_bottom, self.jump_bottom.is_some()), JUMP_BOTTOM_FADE);
if k <= 0.0 {
return;
}
let p = self.pal;
// Fades in rising a few points, like the chat's rows.
let center = egui::pos2(view.center().x, view.bottom() - JUMP_BOTTOM_GAP - JUMP_BOTTOM_SIZE / 2.0 + (1.0 - k) * 6.0);
let rect = egui::Rect::from_center_size(center, vec2(JUMP_BOTTOM_SIZE, JUMP_BOTTOM_SIZE));
let sense = if k > 0.5 { egui::Sense::click() } else { egui::Sense::hover() };
let r = ui.interact(rect, id.with("button"), sense);
let radius = JUMP_BOTTOM_SIZE / 2.0;
let painter = ui.painter();
painter.add(egui::epaint::Shadow { offset: [0, 4], blur: 12, spread: 0, color: Color32::from_black_alpha((31.0 * k) as u8) }.as_shape(rect, radius as u8));
// Opaque first: it sits over the chat's words, and the hover tint is see-through.
painter.circle_filled(center, radius, p.elevated.gamma_multiply(k));
if r.hovered() {
painter.circle_filled(center, radius, p.hover.gamma_multiply(k));
}
painter.circle_stroke(center, radius - 0.5, Stroke::new(1.0, p.border.gamma_multiply(k)));
crate::icons::paint(painter, egui::Rect::from_center_size(center, vec2(16.0, 16.0)), crate::icons::Icon::ArrowDown, p.text2.gamma_multiply(k));
if r.on_hover_text(t("回到最新訊息")).on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
self.jump_bottom = Some(now);
ui.ctx().request_repaint();
}
}
/// The / list for this draft: each skill's name and what it is for (empty when the draft
/// isn't asking, or Esc closed it). A new draft lights the first row again. In a group chat,
/// an @ being typed at the end lists the members instead (@點名).
pub(super) fn slash_list(&mut self, draft: &str, bot: &Bot) -> Vec<(String, String)> {
let at = crate::mention::typing(draft);
if !draft.starts_with('/') && at.is_none() {
self.slash.closed = false;
}
if self.slash.closed {
return vec![];
}
self.slash.at = at.is_some();
self.slash.group = !bot.members.is_empty();
let list: Vec<(String, String)> = if let Some(q) = at {
let names = self.mentionable(bot);
crate::mention::matches(q, &names).into_iter().map(|(id, n)| (n.clone(), self.state.bot(*id).map(|b| b.description.clone()).unwrap_or_default())).collect()
} else {
// AnyBot's own commands (a skill by the same name can't be reached: the command takes
// the words). A bare 「/」 lists only them — the skills had grown to a wall, and the bot
// reads its own skills and uses them by itself. Typing a word after it also finds this
// bot's skills by it (a few), to make it use one.
let mut list: Vec<(String, String)> = slash_commands(draft).into_iter().map(|(n, d)| (n.to_string(), t(d))).collect();
if draft.len() > 1 {
let mine = crate::memory::slash_matches(draft, &self.state.skills).unwrap_or_default().into_iter().filter(|k| !SLASH_COMMANDS.iter().any(|(n, _)| *n == k.name) && crate::profile::has_skill(bot, &k.name));
list.extend(mine.take(SLASH_SKILLS).map(|k| (k.name.clone(), k.description.clone())));
}
list
};
if draft != self.slash.draft {
self.slash.draft = draft.to_string();
self.slash.lit = 0;
}
self.slash.lit = self.slash.lit.min(list.len().saturating_sub(1));
list
}
/// The keys the / list takes before the input sees them: ↑↓ move, Enter or Tab picks the
/// lit row. (Esc is the composer's: egui has taken the focus by the time it arrives.)
pub(super) fn slash_keys(&mut self, ui: &mut egui::Ui, n: usize) -> Option<usize> {
use egui::{Key, Modifiers};
ui.input_mut(|i| {
if i.consume_key(Modifiers::NONE, Key::ArrowDown) {
self.slash.lit = (self.slash.lit + 1) % n;
self.slash.moved = true;
}
if i.consume_key(Modifiers::NONE, Key::ArrowUp) {
self.slash.lit = (self.slash.lit + n - 1) % n;
self.slash.moved = true;
}
// (Plain Enter only: Shift+Enter is a new line, and egui's matching ignores Shift.)
if i.modifiers.shift {
return None;
}
(i.consume_key(Modifiers::NONE, Key::Enter) || i.consume_key(Modifiers::NONE, Key::Tab)).then_some(self.slash.lit)
})
}
/// The / list just above the input: 「/名稱」 and what it is for, the lit row shaded; a click
/// picks. Six rows show, the rest scroll.
pub(super) fn slash_menu(&mut self, ui: &mut egui::Ui, list: &[(String, String)]) -> Option<usize> {
let p = self.pal;
let mut picked = None;
let moved = std::mem::take(&mut self.slash.moved);
Frame::new()
.fill(p.elevated)
.stroke(Stroke::new(1.0, p.border))
.corner_radius(R_L)
.inner_margin(Margin::symmetric(6, 6))
.show(ui, |ui| {
ui.set_width(ui.available_width());
ui.horizontal(|ui| {
ui.add_space(10.0);
let only_commands = list.iter().all(|(n, _)| SLASH_COMMANDS.iter().any(|(c, _)| c == n));
let head = if !self.slash.at && only_commands { "指令 · ↑↓ 選擇,Enter 帶入,Esc 關閉(打字可以找技能)" } else if !self.slash.at { "指令和技能 · ↑↓ 選擇,Enter 帶入,Esc 關閉" } else if self.slash.group { "點名成員 · ↑↓ 選擇,Enter 帶入,Esc 關閉" } else { "找其他 Bot 一起來 · ↑↓ 選擇,Enter 帶入,Esc 關閉" };
ui.label(RichText::new(t(head)).size(FONT_XS).color(p.text3));
});
// Its full height even when the composer had less room last frame (the
// composer's room is last frame's height, so a squeezed list would stay squeezed).
let h = SLASH_ROWS.min(list.len() as f32) * SLASH_ROW_H;
egui::ScrollArea::vertical().id_salt("slash-list").max_height(h).min_scrolled_height(h).show(ui, |ui| {
ui.spacing_mut().item_spacing.y = 0.0;
for (i, (name, about)) in list.iter().enumerate() {
let (rect, r) = ui.allocate_exact_size(vec2(ui.available_width(), SLASH_ROW_H), egui::Sense::click());
let lit = i == self.slash.lit;
if lit || r.hovered() {
ui.painter().rect_filled(rect, R_M, if lit { p.active } else { p.hover });
}
if lit && moved {
r.scroll_to_me(None);
}
let mut row = ui.new_child(egui::UiBuilder::new().max_rect(rect.shrink2(vec2(10.0, 0.0))).layout(Layout::left_to_right(Align::Center)));
// Not selectable: a selectable label takes the click the row is waiting for.
row.add(egui::Label::new(RichText::new(format!("{}{name}", if self.slash.at { "@" } else { "/" })).strong().family(crate::bold()).size(FONT_SM).color(p.text)).selectable(false));
row.add(egui::Label::new(RichText::new(about).size(FONT_XS).color(p.text3)).truncate().selectable(false));
if r.on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
picked = Some(i);
}
}
});
});
ui.add_space(4.0);
picked
}
}
/// A step that is a conversation with a colleague (shown as a card, not a step line).
pub fn is_talk(name: &str) -> bool {
matches!(name, "ask_bot" | "message_bot")
}
/// The composer's / list (技能): the draft it was made for, which row is lit, whether ↑↓ just
/// moved it (so it scrolls into view), whether Esc closed it, and whether the input had the
/// focus last frame (Esc arrives after egui has taken it).
#[derive(Default)]
pub struct Slash {
draft: String,
/// The list is who can be named (an @ being typed), not commands and skills…
pub(super) at: bool,
/// …a group's members (else the other bots).
pub(super) group: bool,
lit: usize,
moved: bool,
pub(super) closed: bool,
pub(super) focused: bool,
}
const SLASH_ROWS: f32 = 6.0;
/// The most skills a typed word after 「/」 brings up.
const SLASH_SKILLS: usize = 6;
const SLASH_ROW_H: f32 = 30.0;
/// After a press of 回到底部: still pulling down (`Some`), or done once the chat is at its bottom
/// or [`JUMP_BOTTOM_SECS`] have passed (new words can keep it from ever quite arriving).
fn jump_still_on(since: Option<f64>, from_bottom: f32, now: f64) -> Option<f64> {
since.filter(|t0| from_bottom >= 1.0 && now - t0 <= JUMP_BOTTOM_SECS)
}
/// 回到底部 shows when the chat is scrolled well up, and not while a press is taking it down.
fn jump_shows(from_bottom: f32, jumping: bool) -> bool {
from_bottom > JUMP_BOTTOM_AFTER && !jumping
}
/// AnyBot's own / commands: (name, what it does). The brain acts on them itself (goal.rs).
pub const SLASH_COMMANDS: [(&str, &str); 5] = [("goal", "設一個目標,一直做到達成為止(/goal clear 清除)"), ("plan", "先規劃再動手:它先查清楚、寫出計畫給你核准,核准後才照計畫做(/plan clear 取消)"), ("btw", "開一條支線:帶著這段對話和記憶,同時去做另一件事,做完回報到這裡"), ("always-approve", "一律放行:Bot 做事不再一個個問你(/always-approve off 關閉)"), ("usage", "用量:最近一天和一週,各 Bot、各模型用了多少 token")];
/// What the bot is doing, in the one line beside its face (and on a colleague's card, the phone).
/// A status of several lines — a retry: the error, what it means, when it tries again — used to
/// stack up past the row into the input. It reads as the reason, then what happens now:
/// 「模型供應商目前負載過高,15 秒後重試(第 3 次,共 3 次)…」. The reason is the explanation's first
/// sentence, or the error itself when there is none.
pub(super) fn one_line(s: &str) -> String {
let lines: Vec<&str> = s.lines().map(str::trim).filter(|l| !l.is_empty()).collect();
let Some((now, before)) = lines.split_last() else { return String::new() };
if before.is_empty() {
return now.to_string();
}
let said = before.iter().rev().find(|l| !l.starts_with("錯誤")).or(before.first()).copied().unwrap_or("");
let why = said.split('。').next().unwrap_or(said).trim_end_matches([',', '。', ':']);
format!("{why},{now}")
}
/// Steps drawn as a card of their own (or as the line above the input), not as a step row.
fn card_call(name: &str) -> bool {
matches!(name, "show_card" | crate::plan::SUBMIT_TOOL | crate::plan::UPDATE_TOOL)
}
/// The commands a draft like 「/go」 asks for (none once a space ends the name).
pub fn slash_commands(draft: &str) -> Vec<(&'static str, &'static str)> {
let Some(q) = draft.strip_prefix('/').filter(|q| !q.chars().any(char::is_whitespace)) else { return vec![] };
let q = q.to_lowercase();
SLASH_COMMANDS.iter().copied().filter(|(n, _)| n.starts_with(&q)).collect()
}
/// "[例行任務]…" → (icon, label) and the words after the tag.
pub fn wake_tag(text: &str) -> (Option<(crate::icons::Icon, &'static str)>, &str) {
use crate::icons::Icon;
// (The emoji forms are what older chats were saved with.)
for (tag, icon, label) in [("[目標]", Icon::Target, "目標"), ("[例行任務]", Icon::Alarm, "例行任務"), ("[觸發]", Icon::Zap, "觸發"), ("[訊息管道]", Icon::Message, "訊息管道"), ("[來自 Bot]", Icon::Bot, "來自其他 Bot"), ("⏰ ", Icon::Alarm, "例行任務"), ("⚡ ", Icon::Zap, "觸發"), ("💬 ", Icon::Message, "訊息管道"), ("📨 ", Icon::Bot, "來自其他 Bot")] {
if let Some(rest) = text.strip_prefix(tag) {
return (Some((icon, label)), rest);
}
}
(None, text)
}
/// A 26 px quiet icon button (the hover actions).
fn hover_icon(ui: &mut egui::Ui, icon: crate::icons::Icon, p: Palette) -> egui::Response {
crate::icons::button(ui, icon, 26.0, p.text3, p.hover)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn phrases_follow_what_it_does() {
let say = |name: &str, args: &str| status_phrase(Some((name, args)), None, false, false, false, 0);
// What it is, and what it is on.
assert_eq!(say("web_fetch", r#"{"url":"https://www.google.com/search?q=%E5%8F%B0%E5%8C%97+%E5%A4%A9%E6%B0%A3&hl=zh"}"#), "正在搜尋網頁:台北 天氣");
assert_eq!(say("browser_open", r#"{"url":"https://duckduckgo.com/?q=rust+egui"}"#), "正在搜尋網頁:rust egui");
assert_eq!(say("browser_open", r#"{"url":"https://www.github.com/anybot/issues"}"#), "正在打開網頁:github.com");
assert_eq!(say("browser", r#"{"action":"open","url":"https://news.ycombinator.com"}"#), "正在打開網頁:news.ycombinator.com");
assert_eq!(say("web_fetch", r#"{"url":"https://example.com/a?id=3"}"#), "正在讀取網頁:example.com");
assert_eq!(say("shell", r#"{"command":"cargo test --release\necho done"}"#), "正在執行指令:cargo test --release");
assert_eq!(say("read_file", r#"{"path":"src/app/chat_ui.rs"}"#), "正在讀取檔案:chat_ui.rs");
assert_eq!(say("use_skill", r#"{"name":"pptx"}"#), "正在讀技能:pptx");
assert_eq!(say("mcp__notion__search", "{}"), "正在用連接器:notion");
assert_eq!(say("shell", &format!(r#"{{"command":"{}"}}"#, "x".repeat(60))), format!("正在執行指令:{}…", "x".repeat(24)));
// Screen steps: on the bot's own computer, or on another one by its name.
assert_eq!(say("computer", r#"{"action":"click"}"#), "正在點擊");
assert_eq!(say("computer_use_open_app", r#"{"app":"Safari"}"#), "正在打開 Safari");
assert_eq!(status_phrase(Some(("computer_use_typing", "{}")), Some("Mac mini"), false, false, false, 0), "正在「Mac mini」上打字");
// Every tool says something of its own (nothing falls back to a vague word).
for n in ["remember", "search_memory", "mac_read_mail", "browser_click", "send_file", "create_routine", "write_page", "computer_use_screenshot", "browser_profiles"] {
assert!(!say(n, "{}").contains("處理"), "{n}: {}", say(n, "{}"));
}
// No step running: words that take turns.
assert_eq!(status_phrase(None, None, true, false, false, 0), "需要你的輸入");
let thinking: Vec<String> = (0..3).map(|k| status_phrase(None, None, false, false, false, k)).collect();
assert!(thinking.iter().all(|p| THINKING.contains(&p.as_str())) && thinking[0] != thinking[1]);
assert!(BETWEEN.contains(&status_phrase(None, None, false, false, true, 1).as_str()));
assert!(WRITING.contains(&status_phrase(None, None, false, true, true, 1).as_str()));
assert!(search_words("https://www.google.com/maps/place/x").is_none());
// Broken or raw escapes don't trip it.
assert_eq!(search_words("https://www.bing.com/search?q=%E5%8F%B0%zz%"), Some("台%zz%".into()));
assert_eq!(search_words("https://www.bing.com/search?q=%台北"), Some("%台北".into()));
assert!((pop(1.0) - 1.0).abs() < 1e-4 && pop(0.6) > 1.0);
}
#[test]
fn a_status_of_several_lines_reads_as_one() {
assert_eq!(one_line("錯誤 503:Server busy: husky queue longer than 10 seconds\n模型供應商目前負載過高。通常是暫時的。\n15 秒後重試(第 3 次,共 3 次)…"), "模型供應商目前負載過高,15 秒後重試(第 3 次,共 3 次)…");
assert_eq!(one_line("錯誤 429:rate limited\n5 秒後重試(第 1 次,共 3 次)…"), "錯誤 429:rate limited,5 秒後重試(第 1 次,共 3 次)…");
assert_eq!(one_line("正在讀網頁…"), "正在讀網頁…");
assert_eq!(one_line(" \n"), "");
}
#[test]
fn the_slash_list_offers_goal_first() {
assert_eq!(slash_commands("/").len(), SLASH_COMMANDS.len());
assert_eq!(slash_commands("/go").first().map(|c| c.0), Some("goal"));
assert_eq!(slash_commands("/GOAL").first().map(|c| c.0), Some("goal"));
assert!(slash_commands("/pptx").is_empty());
assert_eq!(slash_commands("/pl").first().map(|c| c.0), Some("plan"));
assert!(slash_commands("/goal 測試通過").is_empty(), "a space ends the name");
assert!(slash_commands("goal").is_empty());
let (tag, body) = wake_tag("[目標]還沒達成:還有 1 個失敗");
assert_eq!((tag.map(|t| t.1), body), (Some("目標"), "還沒達成:還有 1 個失敗"));
}
#[test]
fn shift_enter_goes_on_with_a_list() {
let nl = |text: &str| list_newline(text, text.chars().count(), text.chars().count());
// Numbers count up; the delimiter and spacing stay.
assert_eq!(nl("待辦:\n1. 買菜"), ("待辦:\n1. 買菜\n2. ".into(), 13));
assert_eq!(nl("9) 九"), ("9) 九\n10) ".into(), 9));
assert_eq!(nl("1、買菜").0, "1、買菜\n2、");
// Bullets and checkboxes, with their indent.
assert_eq!(nl(" - 蘋果").0, " - 蘋果\n - ");
assert_eq!(nl("• 一").0, "• 一\n• ");
assert_eq!(nl("- [x] 做完的").0, "- [x] 做完的\n- [ ] ");
// An empty item ends the list: the marker goes, no new line.
assert_eq!(nl("1. 買菜\n2. "), ("1. 買菜\n".into(), 6));
assert_eq!(nl(" - "), (" ".into(), 2));
// Not a list: just a new line.
assert_eq!(nl("你好"), ("你好\n".into(), 3));
assert_eq!(nl("1.5 公斤"), ("1.5 公斤\n".into(), 7));
assert_eq!(nl("2026年"), ("2026年\n".into(), 6));
assert_eq!(nl("-1 度"), ("-1 度\n".into(), 5));
// In the middle of an item: the rest moves to the new item.
assert_eq!(list_newline("1. 買菜和水果", 5, 5), ("1. 買菜\n2. 和水果".into(), 9));
// A selection is replaced.
assert_eq!(list_newline("abcdef", 2, 4), ("ab\nef".into(), 3));
// Before the marker ends: a plain new line.
assert_eq!(list_newline("1. 買菜", 0, 0), ("\n1. 買菜".into(), 1));
}
#[test]
fn jump_to_bottom_shows_far_up_and_lets_go() {
// Near the newest message: no button. Far up: the button.
assert!(!jump_shows(0.0, false));
assert!(!jump_shows(JUMP_BOTTOM_AFTER, false));
assert!(jump_shows(JUMP_BOTTOM_AFTER + 1.0, false));
// While a press is taking it down, the button is gone.
assert!(!jump_shows(5000.0, true));
// A press keeps pulling until the bottom…
assert_eq!(jump_still_on(Some(10.0), 800.0, 10.2), Some(10.0));
assert_eq!(jump_still_on(Some(10.0), 0.0, 10.2), None);
// …or until a moment has passed, so scrolling up works again.
assert_eq!(jump_still_on(Some(10.0), 800.0, 10.0 + JUMP_BOTTOM_SECS + 0.01), None);
assert_eq!(jump_still_on(None, 800.0, 10.0), None);
}
}