AnyBot/src/icons.rs

352 lines
15 KiB
Rust
Raw Normal View History

// Icons: one free set, Lucide (ISC licence, icons/lucide/LICENSE), drawn from its SVG files so
// every icon in the app has the same 2 px rounded line on a 24 px grid — no emoji anywhere.
// Each SVG is rendered once per size (white), kept as a texture and tinted when painted.
use eframe::egui::{self, vec2, Color32, Painter, Rect};
use std::collections::HashMap;
use std::sync::{Mutex, OnceLock};
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum Icon {
SidebarCollapse,
SidebarExpand,
Plus,
Search,
Gear,
More,
ArrowUp,
Stop,
Monitor,
Mic,
Sparkle,
Chat,
Shield,
Vault,
Key,
CreditCard,
Person,
Eye,
CloudDownload,
Clock,
Calendar,
Wave,
Close,
Download,
Smile,
Reply,
Apps,
Paperclip,
Record,
Pin,
Folder,
Bell,
Pencil,
Copy,
EyeOff,
Trash,
ArrowDown,
Refresh,
Star,
Share,
Upload,
NewChat,
History,
Eraser,
Bot,
Users,
Template,
Check,
FileSheet,
FileText,
FileCode,
FileImage,
FileVideo,
FileAudio,
File,
Lock,
Update,
Zap,
Alert,
Summary,
Plane,
MapPin,
CloudSun,
ShoppingBag,
Message,
Alarm,
CircleCheck,
CircleX,
Minus,
Loader,
Play,
Pause,
FileJson,
FileWord,
ChevronRight,
記憶: 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
Bookmark,
Brain,
}
impl Icon {
pub fn from_name(n: &str) -> Option<Icon> {
Some(match n {
"◧" => Icon::SidebarCollapse,
"◨" => Icon::SidebarExpand,
"+" => Icon::Plus,
"🔍" => Icon::Search,
"⚙" => Icon::Gear,
"⋯" => Icon::More,
"↑" => Icon::ArrowUp,
"■" => Icon::Stop,
"monitor" => Icon::Monitor,
"mic" => Icon::Mic,
_ => return None,
})
}
/// The Lucide file.
fn svg(self) -> &'static str {
match self {
Icon::ChevronRight => include_str!("../icons/lucide/chevron-right.svg"),
記憶: 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
Icon::Bookmark => include_str!("../icons/lucide/bookmark.svg"),
Icon::Brain => include_str!("../icons/lucide/brain.svg"),
Icon::SidebarCollapse => include_str!("../icons/lucide/panel-left-close.svg"),
Icon::SidebarExpand => include_str!("../icons/lucide/panel-left-open.svg"),
Icon::Plus => include_str!("../icons/lucide/plus.svg"),
Icon::Search => include_str!("../icons/lucide/search.svg"),
Icon::Gear => include_str!("../icons/lucide/settings.svg"),
Icon::More => include_str!("../icons/lucide/ellipsis.svg"),
Icon::ArrowUp => include_str!("../icons/lucide/arrow-up.svg"),
Icon::Stop => include_str!("../icons/lucide/square.svg"),
Icon::Monitor => include_str!("../icons/lucide/monitor.svg"),
Icon::Mic => include_str!("../icons/lucide/mic.svg"),
Icon::Sparkle => include_str!("../icons/lucide/sparkles.svg"),
Icon::Chat => include_str!("../icons/lucide/messages-square.svg"),
Icon::Shield => include_str!("../icons/lucide/shield-check.svg"),
Icon::Vault => include_str!("../icons/lucide/vault.svg"),
Icon::Key => include_str!("../icons/lucide/key-round.svg"),
Icon::CreditCard => include_str!("../icons/lucide/credit-card.svg"),
Icon::Person => include_str!("../icons/lucide/user-round.svg"),
Icon::Eye => include_str!("../icons/lucide/eye.svg"),
Icon::CloudDownload => include_str!("../icons/lucide/cloud-download.svg"),
Icon::Clock => include_str!("../icons/lucide/clock.svg"),
Icon::Calendar => include_str!("../icons/lucide/calendar.svg"),
Icon::Wave => include_str!("../icons/lucide/audio-lines.svg"),
Icon::Close => include_str!("../icons/lucide/x.svg"),
Icon::Download => include_str!("../icons/lucide/download.svg"),
Icon::Smile => include_str!("../icons/lucide/smile-plus.svg"),
Icon::Reply => include_str!("../icons/lucide/reply.svg"),
Icon::Apps => include_str!("../icons/lucide/layout-grid.svg"),
Icon::Paperclip => include_str!("../icons/lucide/paperclip.svg"),
Icon::Record => include_str!("../icons/lucide/circle-dot.svg"),
Icon::Pin => include_str!("../icons/lucide/pin.svg"),
Icon::Folder => include_str!("../icons/lucide/folder.svg"),
Icon::Bell => include_str!("../icons/lucide/bell-dot.svg"),
Icon::Pencil => include_str!("../icons/lucide/pencil.svg"),
Icon::Copy => include_str!("../icons/lucide/copy.svg"),
Icon::EyeOff => include_str!("../icons/lucide/eye-off.svg"),
Icon::Trash => include_str!("../icons/lucide/trash-2.svg"),
Icon::ArrowDown => include_str!("../icons/lucide/arrow-down.svg"),
Icon::Refresh => include_str!("../icons/lucide/refresh-cw.svg"),
Icon::Star => include_str!("../icons/lucide/star.svg"),
Icon::Share => include_str!("../icons/lucide/share.svg"),
Icon::Upload => include_str!("../icons/lucide/upload.svg"),
Icon::NewChat => include_str!("../icons/lucide/square-pen.svg"),
Icon::History => include_str!("../icons/lucide/history.svg"),
Icon::Eraser => include_str!("../icons/lucide/eraser.svg"),
Icon::Bot => include_str!("../icons/lucide/bot.svg"),
Icon::Users => include_str!("../icons/lucide/users.svg"),
Icon::Template => include_str!("../icons/lucide/layout-template.svg"),
Icon::Check => include_str!("../icons/lucide/check.svg"),
Icon::FileSheet => include_str!("../icons/lucide/file-spreadsheet.svg"),
Icon::FileText => include_str!("../icons/lucide/file-text.svg"),
Icon::FileCode => include_str!("../icons/lucide/file-code.svg"),
Icon::FileImage => include_str!("../icons/lucide/image.svg"),
Icon::FileVideo => include_str!("../icons/lucide/file-video.svg"),
Icon::FileAudio => include_str!("../icons/lucide/file-music.svg"),
Icon::File => include_str!("../icons/lucide/file.svg"),
Icon::Lock => include_str!("../icons/lucide/lock.svg"),
Icon::Update => include_str!("../icons/lucide/circle-arrow-up.svg"),
Icon::Zap => include_str!("../icons/lucide/zap.svg"),
Icon::Alert => include_str!("../icons/lucide/circle-alert.svg"),
Icon::Summary => include_str!("../icons/lucide/notebook-pen.svg"),
Icon::Plane => include_str!("../icons/lucide/plane.svg"),
Icon::MapPin => include_str!("../icons/lucide/map-pin.svg"),
Icon::CloudSun => include_str!("../icons/lucide/cloud-sun.svg"),
Icon::ShoppingBag => include_str!("../icons/lucide/shopping-bag.svg"),
Icon::Message => include_str!("../icons/lucide/message-circle.svg"),
Icon::Alarm => include_str!("../icons/lucide/alarm-clock.svg"),
Icon::CircleCheck => include_str!("../icons/lucide/circle-check.svg"),
Icon::CircleX => include_str!("../icons/lucide/circle-x.svg"),
Icon::Minus => include_str!("../icons/lucide/minus.svg"),
Icon::Loader => include_str!("../icons/lucide/loader.svg"),
Icon::Play => include_str!("../icons/lucide/play.svg"),
Icon::Pause => include_str!("../icons/lucide/pause.svg"),
Icon::FileJson => include_str!("../icons/lucide/file-json.svg"),
Icon::FileWord => include_str!("../icons/lucide/file-type.svg"),
}
}
/// Filled shapes (stop is a solid square, like a media stop button).
fn filled(self) -> bool {
matches!(self, Icon::Stop | Icon::Play | Icon::Pause)
}
}
/// The icon for a file name (cards, previews, the phone page).
pub fn for_file(name: &str) -> Icon {
match crate::preview::kind_of(name) {
"sheet" => Icon::FileSheet,
"image" => Icon::FileImage,
"video" => Icon::FileVideo,
"audio" => Icon::FileAudio,
"text" | "html" => Icon::FileCode,
"json" => Icon::FileJson,
"docx" | "doc" => Icon::FileWord,
"markdown" | "pdf" => Icon::FileText,
_ => Icon::File,
}
}
type Cache = Mutex<HashMap<(Icon, u32), egui::TextureHandle>>;
fn cache() -> &'static Cache {
static C: OnceLock<Cache> = OnceLock::new();
C.get_or_init(|| Mutex::new(HashMap::new()))
}
/// Render the SVG white at `px` × `px`.
fn rasterize(icon: Icon, px: u32) -> Option<egui::ColorImage> {
let mut svg = icon.svg().replace("currentColor", "#ffffff");
if icon.filled() {
svg = svg.replace("fill=\"none\"", "fill=\"#ffffff\"");
}
let tree = resvg::usvg::Tree::from_str(&svg, &resvg::usvg::Options::default()).ok()?;
let mut pixmap = resvg::tiny_skia::Pixmap::new(px, px)?;
let size = tree.size();
let scale = px as f32 / size.width().max(size.height());
resvg::render(&tree, resvg::tiny_skia::Transform::from_scale(scale, scale), &mut pixmap.as_mut());
// tiny-skia keeps premultiplied RGBA, which is what egui wants.
let data: Vec<Color32> = pixmap.pixels().iter().map(|p| Color32::from_rgba_premultiplied(p.red(), p.green(), p.blue(), p.alpha())).collect();
Some(egui::ColorImage { size: [px as usize, px as usize], pixels: data, source_size: vec2(px as f32, px as f32) })
}
/// Draw `icon` filling `rect` (square), in `col`.
pub fn paint(p: &Painter, rect: Rect, icon: Icon, col: Color32) {
let ppp = p.ctx().pixels_per_point();
let side = rect.width().min(rect.height());
// Quantised size (2 px steps, capped): a resized window used to create a new texture for
// every pixel width, so the cache grew without limit while the window was dragged.
let px = ((side * ppp).round().max(8.0) as u32 / 2 * 2).clamp(8, 512);
let tex = {
let mut c = cache().lock().unwrap();
match c.get(&(icon, px)) {
Some(t) => t.clone(),
None => {
let Some(img) = rasterize(icon, px) else { return };
// Roomy hard cap: past it, start the cache fresh (textures reload on demand).
if c.len() >= 1500 {
c.clear();
}
let t = p.ctx().load_texture(format!("icon-{icon:?}-{px}"), img, egui::TextureOptions::LINEAR);
c.insert((icon, px), t.clone());
t
}
}
};
let r = Rect::from_center_size(rect.center(), vec2(side, side));
p.image(tex.id(), r, Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), col);
}
/// An icon followed by words, on one line.
pub fn label(ui: &mut egui::Ui, icon: Icon, text: &str, size: f32, col: Color32) -> egui::Response {
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 6.0;
let (r, _) = ui.allocate_exact_size(vec2(size + 1.0, size + 2.0), egui::Sense::hover());
paint(ui.painter(), Rect::from_center_size(r.center(), vec2(size, size)), icon, col);
ui.label(egui::RichText::new(text).size(size).color(col));
})
.response
}
/// A rounded button with an icon and words (pills like 「需要你允許」).
pub fn pill(ui: &mut egui::Ui, icon: Icon, text: &str, fill: Color32, fg: Color32, height: f32) -> egui::Response {
let font = egui::FontId::proportional(13.0);
let galley = ui.painter().layout_no_wrap(text.to_string(), font, fg);
let icon_s = 14.0;
let w = 12.0 + icon_s + 6.0 + galley.size().x + 14.0;
let (rect, r) = ui.allocate_exact_size(vec2(w, height), egui::Sense::click());
let f = if r.hovered() { fill.gamma_multiply(0.88) } else { fill };
ui.painter().rect_filled(rect, height / 2.0, f);
paint(ui.painter(), Rect::from_center_size(egui::pos2(rect.left() + 12.0 + icon_s / 2.0, rect.center().y), vec2(icon_s, icon_s)), icon, fg);
ui.painter().galley(egui::pos2(rect.left() + 12.0 + icon_s + 6.0, rect.center().y - galley.size().y / 2.0), galley, fg);
r.on_hover_cursor(egui::CursorIcon::PointingHand)
}
/// A pill exactly `width` wide (a whole row), icon and words in the middle. The words are the
/// first of `texts` that fits, or else the last cut short with "…" — never wider than the row.
pub fn wide_pill(ui: &mut egui::Ui, icon: Icon, texts: &[String], fill: Color32, fg: Color32, height: f32, width: f32) -> egui::Response {
let font = egui::FontId::proportional(13.0);
let icon_s = 14.0;
let room = (width - 12.0 * 2.0 - icon_s - 6.0).max(0.0);
let measure = |t: &str| ui.painter().layout_no_wrap(t.to_string(), font.clone(), fg).size().x;
let text = texts.iter().find(|t| measure(t) <= room).cloned().unwrap_or_else(|| {
let mut chars: Vec<char> = texts.last().map(|t| t.chars().collect()).unwrap_or_default();
while !chars.is_empty() && measure(&format!("{}…", chars.iter().collect::<String>())) > room {
chars.pop();
}
format!("{}…", chars.into_iter().collect::<String>())
});
let galley = ui.painter().layout_no_wrap(text, font, fg);
let (rect, r) = ui.allocate_exact_size(vec2(width, height), egui::Sense::click());
let f = if r.hovered() { fill.gamma_multiply(0.88) } else { fill };
ui.painter().rect_filled(rect, height / 2.0, f);
let left = rect.center().x - (icon_s + 6.0 + galley.size().x) / 2.0;
paint(ui.painter(), Rect::from_center_size(egui::pos2(left + icon_s / 2.0, rect.center().y), vec2(icon_s, icon_s)), icon, fg);
ui.painter().galley(egui::pos2(left + icon_s + 6.0, rect.center().y - galley.size().y / 2.0), galley, fg);
r.on_hover_cursor(egui::CursorIcon::PointingHand)
}
/// A borderless icon button (hover shows a soft rounded square).
pub fn button(ui: &mut egui::Ui, icon: Icon, size: f32, col: Color32, hover_fill: Color32) -> egui::Response {
let (rect, r) = ui.allocate_exact_size(vec2(size, size), egui::Sense::click());
if r.hovered() {
ui.painter().rect_filled(rect, 7.0, hover_fill);
}
let inner = Rect::from_center_size(rect.center(), vec2(16.0, 16.0));
paint(ui.painter(), inner, icon, col);
r.on_hover_cursor(egui::CursorIcon::PointingHand)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_icon_renders() {
for icon in [Icon::Plus, Icon::Gear, Icon::Stop, Icon::FileSheet, Icon::Trash, Icon::Wave, Icon::Summary, Icon::Lock, Icon::Update, Icon::Play, Icon::Pause, Icon::FileJson, Icon::FileWord] {
let img = rasterize(icon, 32).expect("renders");
assert_eq!(img.size, [32, 32]);
assert!(img.pixels.iter().any(|p| p.a() > 0), "{icon:?} is empty");
}
assert_eq!(for_file("a.xlsx"), Icon::FileSheet);
assert_eq!(for_file("a.png"), Icon::FileImage);
}
/// A wide pill is exactly as wide as asked, however long its words (the sidebar's
/// 重新啟動以更新 ran past the sidebar's edge).
#[test]
fn a_wide_pill_never_outgrows_its_row() {
let ctx = egui::Context::default();
for width in [60.0, 160.0, 400.0] {
let mut got = 0.0;
let mut out = ctx.run_ui(egui::RawInput::default(), |root| {
let texts = ["重新啟動以更新(2026-11-11 17:23)".to_string(), "重新啟動以更新".to_string()];
got = wide_pill(root, Icon::Update, &texts, Color32::BLUE, Color32::WHITE, 30.0, width).rect.width();
});
out.textures_delta.clear(); // (no renderer here to hand the font atlas to)
assert_eq!(got, width);
}
}
}