AnyBot/src/app/chat_ui.rs

1103 lines
58 KiB
Rust
Raw Normal View History

// 對話內容, 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),
}
}
/// 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}") }
};
// `computer` and `browser` carry the action in their arguments until the step ends.
let name = match name {
crate::computer::TOOL => crate::computer::top_action_tool(&s("action")).unwrap_or("computer_use"),
crate::browser::TOOL => crate::browser::action_tool(&s("action")).unwrap_or("browser"),
n => n,
};
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(),
"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")),
"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(),
// mcp__<server>__<tool>: the connector by its name.
n if n.starts_with(crate::mcp::PREFIX) => with("正在用連接器", n[crate::mcp::PREFIX.len()..].split("__").next().unwrap_or("").to_string()),
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 {
/// 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") || !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(12.0).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 {
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(14).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(12.5).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);
}
// 目標: AnyBot's own line about the goal (set, met, paused…).
_ if m.note => self.goal_note_row(ui, m),
A turn cut off by a crash leaves a 「繼續」 card, and nothing it may have done runs twice Each bot keeps a work log (oplog/bot-<id>.jsonl, after pi's durable-harness design, cut down): before something happens a line says it is about to — the turn, each model call, each step once its checks passed (with the arguments it runs with and whether it may run again), each message typed mid-turn — synced to disk first. When the turn ends the file shrinks to the messages still waiting, usually nothing. On the next start after AnyBot was killed mid-turn, the log puts the chat right before anything runs: the message the turn answered comes back if the chat lost it; a step that was running and reaches outside (a text, a click, a file, a published site) shows as 「可能已經執行了」, both to the person and in the result the bot reads — no longer as "not allowed"; a step that only looked shows as cut off; messages typed mid-turn that never reached the bot go back into the chat. The chat is saved, then the log closes the turn. A turn the person didn't stop ends with a 「繼續」 card (what it was doing, what may have run, the messages put back); it goes on only when they press it — in the window, on a screen of the brain, or on the phone — from where its steps stand, never running a step that may have run again. Pressing stop is on disk at once, and a stopped turn stays stopped. Also in the turn loop: - 自動審核 that doesn't answer (or answers something that isn't a verdict) asks the person; in 直接操作 mode it used to let the step through unchecked. - "Too long for this model" folds older messages into a summary and asks the same step again, once per thing the person said, instead of ending the turn. - Folding keeps the person's chat whole: the summary goes in at the fold and the model reads from the newest summary on (it used to delete what it folded). - A step moved to the chosen computer runs there, but the chat keeps the call as the model wrote it; the result says where it ran. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha5F5gJt93t3yEx3XcS
2026-11-08 16:49:12 +00:00
// 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(14).inner_margin(Margin::symmetric(12, 10)).show(ui, |ui| {
ui.label(RichText::new(&m.text).size(13.0).color(p.text2));
if can_go_on {
ui.add_space(6.0);
go_on = ui.button(RichText::new(t("繼續")).size(13.0)).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 = self.user_bubble(bot);
let text_col = if fill != p.bubble_user { Color32::WHITE } else if p.bubble_user.a() < 0xff { p.text } else { p.on_primary };
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);
Frame::new().fill(fill).corner_radius(BUBBLE_RADIUS).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() {
ctx.copy_text(m.text.clone());
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);
}
});
}
記憶: a page to see it, a few lines picked while typing, a local model The memory had grown into a list carried whole, a top-14 recalled by a trigram index and pasted into the system prompt with the clock, and a page that broke its own layout. Nobody could see what went to the model, the prompt cache missed every message, and 「記住」 kept saying the same thing twice. Rebuilt per the spec (docs/memory.md): - Three kinds in memory.db: 記得的事 (fact), 做過的事 (event, a line per finished turn), 整理過的 (rollup). Each keeps pinned, uses, last_used, deleted, superseded_by, span. state.json keeps the facts as the copy that syncs; the page reads SQLite. - Search: jieba words ∪ CJK bigrams in an FTS5 unicode61 table (Traditional text goes through Simplified first), weighted share of query terms hit; plus local vectors, vec = clamp((cos−0.35)/0.35). score = max + 0.15×min, events ×0.9. ≥0.15 suggested, ≥0.5 ticked, ≥0.55 carried when nobody chose (3 at most). - What the model gets: the system prompt has the time zone and the pinned memories only, the same every turn. Each person message gets 〔送出時間〕 and 〔相關記憶〕 from Message.memories, built in group_history into a transient Message.context, so the beginning of a chat reads the same next turn (cache hits) and the event log, skills and audit see only what was typed. A memory already carried in view isn't carried again; each carry counts a use. - Picks travel with the message: Cmd::Send / POST send / sync act "memories" (empty = none; absent = the brain chooses, once, saved). - remember finds the like one (cos ≥ 0.85 or the same words) and asks for `replaces`; the old one is superseded, never carried. A fact forgotten and remembered again comes back. New search_memory (query, kind), with dates; read-only. - Nightly on the brain, no model: events past 30 days fold into a line per week (「11/3–11/9 做過的事(14 件):整理照片 ×3…」, ≤400 chars, like with like by words or vectors), weeks past 180 days into months; the folded go to 最近刪除 for 30 days. Facts are never removed. The page offers duplicates, facts unused for half a year, and what can fold now. - Local model: minishlab/potion-multilingual-128M through m2v.rs (same token ids as model2vec-rs on 13/13 sentences, cos ≥ 0.9999, without tokenizers' 1.1 GB). Converted while downloading: vocab.bin, table.i8 (int8 + row scales), dims.json, 137 MB kept of 530 MB; ANYBOT_HF_BASE picks a mirror (now passed into the server's brain container too). Loaded when first needed (34 ms), let go after 10 idle minutes. The brain loads it; a screen only with a document folder set; hands and phones never. 設定 › 一般 › 語意搜尋: 本機模型/Ollama/關閉; a new engine clears every vector. - Three files, three connections: memory.db (backed up nightly, 7 kept), docs.db (a cache), oplog/audit.db (30 days). An old audit.db hands its memories and documents over once and shrinks (a real one: 172 MB → 16 KB). docs_search scans every chunk now, vectors cached in RAM (it stopped at 8000); FTS optimize + VACUUM daily (260 MB of tombstones over 31 MB of text). - API: POST /api/memory (owner) and /api/sync/memory (mirror). Reads answer on the HTTP thread; writes go through phone_act("memory"). - Screens: a memory dialog (Bot menu 記憶…, Bot settings 打開記憶) with counts, live search, filters, suggestions, per-item kind/date/uses and pin/edit/forget/restore; chips above the composer 300 ms after typing stops, with a token estimate; 「帶了 N 條記憶」 under person messages. The phone has the same as a 記憶 tab, chips and tag. Checked: make test passes (app 297, relay 16), with new tests for the scores and thresholds, Traditional Chinese segmentation, remember's dedupe and replaces, two turns sending the same beginning, no double carry, weekly/monthly folding and the trash, and the audit.db move. Brain idle 37 MB as before, ~230 MB with the model loaded; search on the brain 0.2–0.5 ms, 7–44 ms from the phone page. A deadlock found on the way (stats re-taking the lock) is fixed and tested. Docs: docs/memory.md has the whole design; FEATURES.md, protocol, architecture (zh/en), multi-device and install say what changed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha3SYw9JJ9dXwaNvYh4
2026-11-10 23:46:50 +00:00
// 記憶 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(11.5).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);
// 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(12.0).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());
let fill = if m.error { p.danger.gamma_multiply(0.12) } else { files_ui::agent_fill(p) };
let col = if m.error { p.danger } else { p.text };
Frame::new().fill(fill).corner_radius(BUBBLE_RADIUS).inner_margin(bubble_margin()).show(ui, |ui| {
ui.set_max_width(max_w);
ui.with_layout(Layout::top_down(Align::Min), |ui| self.markdown(ui, &m.text, col, 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(20.0)).frame(false).min_size(vec2(34.0, 34.0)).corner_radius(10)).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(18.0)).frame(false).min_size(vec2(30.0, 30.0)).corner_radius(8)).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() {
ctx.copy_text(m.text.clone());
ui.close();
}
if menu_ui::item(ui, p, Icon::Reply, "回覆").clicked() {
self.quoting.insert(bot.id, m.text.clone());
ui.close();
}
if last && menu_ui::item(ui, p, Icon::Refresh, "重新產生").clicked() {
self.regenerate(ctx, 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);
}
// 頁面 written in this reply: the card (the page as it is now).
for id in crate::pages::ids_in(&m.tool_calls) {
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);
}
/// 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| c.name != "show_card").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(12).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(12.5).color(p.text3)).id_salt(("think", bot.id, i)).show(ui, |ui| {
ui.label(RichText::new(&m.thinking).size(12.5).color(p.text3));
});
}
for c in m.tool_calls.iter().filter(|c| c.name != "show_card") {
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(12.5).color(p.text2));
let l = ui.add(egui::Label::new(RichText::new(detail.chars().take(80).collect::<String>()).monospace().size(11.5).color(p.text3)).truncate());
if let Some(r) = result {
l.on_hover_text(r);
}
});
}
}
});
ui.add_space(4.0);
}
/// The working row at the end of the chat: ring + shimmering phrase.
pub(super) fn working_row(&mut self, ui: &mut egui::Ui, bot: &Bot) {
let p = self.pal;
let Some(live) = self.streams.get(&bot.id) else { return };
let waiting = self.approvals.contains_key(&bot.id);
let last = bot.messages.iter().rev().find(|m| m.role == Role::Assistant);
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));
// The words change every few seconds while nothing new is running (the ring keeps the
// window drawing, so no extra repaint is needed).
let tick = seed.wrapping_add((ui.input(|i| i.time) / PHRASE_SECS) as u64);
let place = named.as_deref().filter(|_| !on_box);
let phrase = live.status.clone().unwrap_or_else(|| t(&status_phrase(running.map(|c| (c.name.as_str(), c.args.as_str())), place, waiting, has_text, did_steps, tick)));
ui.add_space(4.0);
ui.horizontal(|ui| {
ui.add_space(6.0);
ui.spacing_mut().item_spacing.x = 8.0;
spinner(ui, 16.0, if waiting { p.accent } else { p.text2 });
shimmer(ui, &phrase, p.text3, p.text, 14.0);
});
ui.add_space(10.0);
}
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(14.0 * 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();
}
}
技能: / in the input picks one; on a brain's screen the brain adds, installs and deletes them; 設定 › 整合's lists keep their buttons clear - Typing / at the start of the input (computer and phone) lists the skills that are on: names that start with what is typed first, then names containing it, then descriptions (「/簡報」 finds pptx). A click, or ↑↓ and Enter/Tab, puts 「/name 」 in the input; Esc closes the list. Sent, the brain recognises 「/name」 and adds a line after the message telling the model to read that skill with use_skill first, so a phone or a message channel gets it too; a / that names no skill (a path) gets nothing. The phone asks the brain for the list again at each new /, so a skill added since is there. - On a screen, 加入 / 安裝 / 刪除 ran on the screen's own disk and only the list entry reached the brain: a GitHub skill's scripts stayed on the screen's computer, an install also pushed every skill in that computer's folder into the brain's list, and a deleted skill's folder stayed on the brain and came back at its next start. These now go to the brain (/api/sync/skill, the phone's own 「skill」 action): it fetches an address itself, a folder or .md file on the screen's computer goes up whole with its files, and a delete takes the folder too. 「把這台的 Bot 搬到大腦」 hands over skills the same way. A refused package leaves no folder behind. - 技能, 技能市集 and 連接器市集 rows: a long description took the whole row and 開啟 / 檢視 / 刪除 / 已加入 / 安裝 were drawn over it. The buttons are laid out first and the description ends in … before them (the whole of it on hover). - Screenshot mode: ANYBOT_SHOT_KEYS="ArrowDown@60;Enter@64" presses keys at given frames. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 08:54:58 +00:00
/// 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.
pub(super) fn slash_list(&mut self, draft: &str) -> Vec<(String, String)> {
if !draft.starts_with('/') {
self.slash.closed = false;
}
if self.slash.closed {
return vec![];
}
// AnyBot's own commands first (a skill by the same name can't be reached: the command
// takes the words), then the skills.
let mut list: Vec<(String, String)> = slash_commands(draft).into_iter().map(|(n, d)| (n.to_string(), t(d))).collect();
list.extend(crate::memory::slash_matches(draft, &self.state.skills).unwrap_or_default().into_iter().filter(|k| !SLASH_COMMANDS.iter().any(|(n, _)| *n == k.name)).map(|k| (k.name.clone(), k.description.clone())));
技能: / in the input picks one; on a brain's screen the brain adds, installs and deletes them; 設定 › 整合's lists keep their buttons clear - Typing / at the start of the input (computer and phone) lists the skills that are on: names that start with what is typed first, then names containing it, then descriptions (「/簡報」 finds pptx). A click, or ↑↓ and Enter/Tab, puts 「/name 」 in the input; Esc closes the list. Sent, the brain recognises 「/name」 and adds a line after the message telling the model to read that skill with use_skill first, so a phone or a message channel gets it too; a / that names no skill (a path) gets nothing. The phone asks the brain for the list again at each new /, so a skill added since is there. - On a screen, 加入 / 安裝 / 刪除 ran on the screen's own disk and only the list entry reached the brain: a GitHub skill's scripts stayed on the screen's computer, an install also pushed every skill in that computer's folder into the brain's list, and a deleted skill's folder stayed on the brain and came back at its next start. These now go to the brain (/api/sync/skill, the phone's own 「skill」 action): it fetches an address itself, a folder or .md file on the screen's computer goes up whole with its files, and a delete takes the folder too. 「把這台的 Bot 搬到大腦」 hands over skills the same way. A refused package leaves no folder behind. - 技能, 技能市集 and 連接器市集 rows: a long description took the whole row and 開啟 / 檢視 / 刪除 / 已加入 / 安裝 were drawn over it. The buttons are laid out first and the description ends in … before them (the whole of it on hover). - Screenshot mode: ANYBOT_SHOT_KEYS="ArrowDown@60;Enter@64" presses keys at given frames. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 08:54:58 +00:00
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;
}
技能: / in the input picks one; on a brain's screen the brain adds, installs and deletes them; 設定 › 整合's lists keep their buttons clear - Typing / at the start of the input (computer and phone) lists the skills that are on: names that start with what is typed first, then names containing it, then descriptions (「/簡報」 finds pptx). A click, or ↑↓ and Enter/Tab, puts 「/name 」 in the input; Esc closes the list. Sent, the brain recognises 「/name」 and adds a line after the message telling the model to read that skill with use_skill first, so a phone or a message channel gets it too; a / that names no skill (a path) gets nothing. The phone asks the brain for the list again at each new /, so a skill added since is there. - On a screen, 加入 / 安裝 / 刪除 ran on the screen's own disk and only the list entry reached the brain: a GitHub skill's scripts stayed on the screen's computer, an install also pushed every skill in that computer's folder into the brain's list, and a deleted skill's folder stayed on the brain and came back at its next start. These now go to the brain (/api/sync/skill, the phone's own 「skill」 action): it fetches an address itself, a folder or .md file on the screen's computer goes up whole with its files, and a delete takes the folder too. 「把這台的 Bot 搬到大腦」 hands over skills the same way. A refused package leaves no folder behind. - 技能, 技能市集 and 連接器市集 rows: a long description took the whole row and 開啟 / 檢視 / 刪除 / 已加入 / 安裝 were drawn over it. The buttons are laid out first and the description ends in … before them (the whole of it on hover). - Screenshot mode: ANYBOT_SHOT_KEYS="ArrowDown@60;Enter@64" presses keys at given frames. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 08:54:58 +00:00
(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(14)
.inner_margin(Margin::symmetric(6, 6))
.show(ui, |ui| {
ui.set_width(ui.available_width());
ui.horizontal(|ui| {
ui.add_space(10.0);
ui.label(RichText::new(t("指令和技能 · ↑↓ 選擇,Enter 帶入,Esc 關閉")).size(11.0).color(p.text3));
技能: / in the input picks one; on a brain's screen the brain adds, installs and deletes them; 設定 › 整合's lists keep their buttons clear - Typing / at the start of the input (computer and phone) lists the skills that are on: names that start with what is typed first, then names containing it, then descriptions (「/簡報」 finds pptx). A click, or ↑↓ and Enter/Tab, puts 「/name 」 in the input; Esc closes the list. Sent, the brain recognises 「/name」 and adds a line after the message telling the model to read that skill with use_skill first, so a phone or a message channel gets it too; a / that names no skill (a path) gets nothing. The phone asks the brain for the list again at each new /, so a skill added since is there. - On a screen, 加入 / 安裝 / 刪除 ran on the screen's own disk and only the list entry reached the brain: a GitHub skill's scripts stayed on the screen's computer, an install also pushed every skill in that computer's folder into the brain's list, and a deleted skill's folder stayed on the brain and came back at its next start. These now go to the brain (/api/sync/skill, the phone's own 「skill」 action): it fetches an address itself, a folder or .md file on the screen's computer goes up whole with its files, and a delete takes the folder too. 「把這台的 Bot 搬到大腦」 hands over skills the same way. A refused package leaves no folder behind. - 技能, 技能市集 and 連接器市集 rows: a long description took the whole row and 開啟 / 檢視 / 刪除 / 已加入 / 安裝 were drawn over it. The buttons are laid out first and the description ends in … before them (the whole of it on hover). - Screenshot mode: ANYBOT_SHOT_KEYS="ArrowDown@60;Enter@64" presses keys at given frames. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 08:54:58 +00:00
});
// 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, 9, 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}")).strong().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
}
}
技能: / in the input picks one; on a brain's screen the brain adds, installs and deletes them; 設定 › 整合's lists keep their buttons clear - Typing / at the start of the input (computer and phone) lists the skills that are on: names that start with what is typed first, then names containing it, then descriptions (「/簡報」 finds pptx). A click, or ↑↓ and Enter/Tab, puts 「/name 」 in the input; Esc closes the list. Sent, the brain recognises 「/name」 and adds a line after the message telling the model to read that skill with use_skill first, so a phone or a message channel gets it too; a / that names no skill (a path) gets nothing. The phone asks the brain for the list again at each new /, so a skill added since is there. - On a screen, 加入 / 安裝 / 刪除 ran on the screen's own disk and only the list entry reached the brain: a GitHub skill's scripts stayed on the screen's computer, an install also pushed every skill in that computer's folder into the brain's list, and a deleted skill's folder stayed on the brain and came back at its next start. These now go to the brain (/api/sync/skill, the phone's own 「skill」 action): it fetches an address itself, a folder or .md file on the screen's computer goes up whole with its files, and a delete takes the folder too. 「把這台的 Bot 搬到大腦」 hands over skills the same way. A refused package leaves no folder behind. - 技能, 技能市集 and 連接器市集 rows: a long description took the whole row and 開啟 / 檢視 / 刪除 / 已加入 / 安裝 were drawn over it. The buttons are laid out first and the description ends in … before them (the whole of it on hover). - Screenshot mode: ANYBOT_SHOT_KEYS="ArrowDown@60;Enter@64" presses keys at given frames. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 08:54:58 +00:00
/// 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,
lit: usize,
moved: bool,
pub(super) closed: bool,
pub(super) focused: bool,
}
const SLASH_ROWS: f32 = 6.0;
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); 1] = [("goal", "設一個目標,一直做到達成為止(/goal clear 清除)")];
/// 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 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!(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);
}
}