AnyBot/src/app/settings_find.rs

408 lines
19 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 搜尋設定 (plan C3): every setting a person might look for — which page it is on, under which
// heading, and the other words they might type for it. The settings window's left column searches
// it (title starts with what was typed, then title contains it, then the heading or the other
// words do; at most 12); picking one turns to its page (and the page inside it), scrolls the row
// into view and outlines it for a moment — `jump_mark`, which the kit's headings and rows call.
// A test keeps the list whole: every heading and row title the settings pages draw is in it (or
// said here why not).
use super::channels_ui::Page;
use super::*;
use std::cell::RefCell;
pub(super) struct Entry {
pub tab: SettingsTab,
/// The heading it is under, as the page shows it (「外觀」); for a whole page, the page.
pub place: &'static str,
/// The row or heading as drawn — what is outlined; empty: the page itself.
pub title: &'static str,
/// Other words for it: what it does, what people call it.
pub words: &'static str,
/// How to get there inside the page (a folded row, the 整合 page's own pages).
pub open: Option<fn(&mut App)>,
}
const fn e(tab: SettingsTab, place: &'static str, title: &'static str, words: &'static str) -> Entry {
Entry { tab, place, title, words, open: None }
}
const fn o(tab: SettingsTab, place: &'static str, title: &'static str, words: &'static str, open: fn(&mut App)) -> Entry {
Entry { tab, place, title, words, open: Some(open) }
}
fn more_look(a: &mut App) {
a.appearance_more = true;
}
fn ch_channels(a: &mut App) {
a.ch.sub = 0;
}
fn ch_mcp(a: &mut App) {
a.ch.sub = 1;
a.ch.mcp_page = Page::List;
}
fn ch_mcp_market(a: &mut App) {
a.ch.sub = 1;
a.ch.mcp_page = Page::Market;
}
fn ch_mcp_add(a: &mut App) {
a.ch.sub = 1;
a.ch.mcp_page = Page::Add;
}
fn ch_skills(a: &mut App) {
a.ch.sub = 2;
a.ch.skill_page = Page::List;
}
fn ch_skill_market(a: &mut App) {
a.ch.sub = 2;
a.ch.skill_page = Page::Market;
}
use SettingsTab as S;
pub(super) const INDEX: &[Entry] = &[
// 一般
e(S::General, "一般", "", "設定 general"),
e(S::General, "外觀", "外觀", "樣子 顏色 appearance"),
e(S::General, "外觀", "主題", "淺色 深色 跟著系統 深色模式 夜間 dark mode light theme"),
e(S::General, "外觀", "強調色", "選中項 連結 新訊息點 圖表 accent color"),
e(S::General, "外觀", "聊天的顏色", "泡泡 訊息顏色 跟著 Bot 只用黑色 安靜"),
e(S::General, "外觀", "語言", "中文 英文 English 選單 回答的語言 language"),
e(S::General, "外觀", "更多外觀設定", "展開"),
o(S::General, "外觀", "底色", "色溫 藍灰 米白 背景", more_look),
o(S::General, "外觀", "對比", "分層 細線 文字階級 contrast", more_look),
o(S::General, "外觀", "密度", "緊湊 行距 按鈕大小 density", more_look),
o(S::General, "外觀", "慶祝動畫", "彩帶 動畫 完成", more_look),
o(S::General, "外觀", "頭像動態", "減少動態 動畫 呼吸 眼睛 表情 reduce motion", more_look),
o(S::General, "外觀", "外殼顏色重設", "預設 紙 還原 reset", more_look),
e(S::General, "記憶與文件", "記憶與文件", ""),
e(S::General, "記憶與文件", "用意思找記憶", "語意搜尋 向量 embedding 本機模型 Ollama 關閉"),
e(S::General, "記憶與文件", "Bot 可以翻的資料夾", "文件 資料夾 搜尋 md txt csv 程式碼 知識庫"),
e(S::General, "通知", "通知", "notification"),
e(S::General, "通知", "Bot 做完或等你時通知(電腦和手機)", "推播 提醒 手機通知"),
e(S::General, "通知", "需要你時響一聲", "聲音 音效 鈴聲 sound"),
e(S::General, "Bot", "Bot", ""),
e(S::General, "Bot", "時區", "Asia/Taipei 例行任務 提醒 時間 timezone"),
e(S::General, "帳戶", "帳戶", "登入 帳號 管理帳戶 account"),
e(S::General, "帳戶", "資料放在哪", "資料夾 Finder 聊天記錄 金鑰 data"),
// 一般 › 手機與帳號
e(S::Remote, "手機與帳號", "手機與帳號", "手機 iPhone Android phone"),
e(S::Remote, "手機與帳號", "AnyBot 帳號", "登入 登出 帳號伺服器 換網址 註冊 邀請碼 驗證碼 密碼"),
e(S::Remote, "手機與帳號", "同一個網路直接連", "Wi-Fi 區網 Tailscale 手機密碼 直接連線"),
e(S::Remote, "手機與帳號", "手機可以做什麼", "手機權限"),
e(S::Remote, "手機與帳號", "直接連線的裝置", "登出 裝置 瀏覽器"),
e(S::Remote, "手機與帳號", "分享給團隊", "團隊 同事 成員 team"),
e(S::Remote, "手機與帳號", "帳號裡的電腦", "大腦 手腳 螢幕 其他電腦 裝置"),
// 個人資料
e(S::Me, "個人資料", "", "名字 活躍日 Token 連續天數 最活躍 訊息數 profile"),
e(S::Me, "個人資料", "活動", "熱度 一年 格子 activity"),
e(S::Me, "個人資料", "用量", "花費 費用 token 呼叫次數 帳單 用了多少 billing usage cost"),
// 模型 (each provider is added by `find`)
e(S::Providers, "模型", "", "供應商 API 金鑰 key provider model"),
// 整合
e(S::Channels, "整合", "", "integrations"),
o(S::Channels, "訊息管道", "", "Slack Discord Telegram Teams iMessage 郵件 email 簡訊 SMS X 管道 channel", ch_channels),
o(S::Channels, "連接器", "連接器(MCP)", "MCP 伺服器 工具 GitHub Notion connector", ch_mcp),
o(S::Channels, "連接器", "連接器市集", "市集 MCP Registry 公用市集 加入", ch_mcp_market),
o(S::Channels, "連接器", "新增連接器", "自訂 指令 網址 環境變數 標頭", ch_mcp_add),
o(S::Channels, "技能", "技能", "SKILL.md 技能庫 作業流程 skill", ch_skills),
o(S::Channels, "技能", "內建技能包", "技能市集", ch_skill_market),
o(S::Channels, "技能", "Anthropic 開源技能", "技能市集", ch_skill_market),
o(S::Channels, "技能", "從 GitHub、網址或資料夾安裝", "安裝技能", ch_skill_market),
// 電腦
e(S::Computers, "電腦", "", "computer"),
e(S::Computers, "你的電腦", "你的電腦", "重新命名 這台電腦 名字"),
e(S::Computers, "你的電腦", "在這台電腦上執行", "一律允許 每次詢問 永不允許 本機 本地"),
e(S::Computers, "你的電腦", "經這台電腦轉送流量", "代理 proxy 出口 IP"),
e(S::Computers, "你的電腦", "其他電腦", ""),
e(S::Computers, "你的電腦", "讓帳號裡的其他電腦使用這台", "裝置連結 遠端 操作這台"),
e(S::Computers, "訊息", "訊息", "Messages"),
e(S::Computers, "訊息", "傳送訊息", "iMessage 簡訊 Messages"),
e(S::Computers, "訊息", "無需詢問直接傳送", "不用核准"),
e(S::Computers, "Bot 的電腦", "Bot 的電腦", "Docker Linux 容器 box 沙盒"),
e(S::Computers, "Bot 的電腦", "在大腦上", ""),
e(S::Computers, "Bot 的電腦", "更新 Bot 的電腦", ""),
e(S::Computers, "Bot 的電腦", "自動更新映像檔", "Bot 的電腦自動更新"),
e(S::Computers, "Bot 的電腦", "重設 Bot 的電腦", "重設 清空 reset"),
e(S::Computers, "Bot 的電腦", "磁碟", "空間 清理 容量 disk"),
e(S::Computers, "終端機與環境密鑰", "終端機與環境密鑰", "環境變數 secret 金鑰 env"),
e(S::Computers, "在哪裡執行", "在哪裡執行", ""),
e(S::Computers, "在哪裡執行", "Docker 主機", "DOCKER_HOST 遠端 Docker"),
e(S::Computers, "在哪裡執行", "容器隔離", "gVisor runsc 安全"),
e(S::Computers, "瀏覽器", "AnyBot 瀏覽器設定檔", "Chrome 瀏覽器 登入 設定檔 profile"),
e(S::Computers, "瀏覽器", "做完就關掉瀏覽器", "關閉瀏覽器"),
e(S::Computers, "瀏覽器", "發布前檢查", "簡體字 AI 腔 送出前檢查 留言 貼文"),
e(S::Computers, "AnyBot Computer Use", "AnyBot Computer Use", "操作畫面 computer use"),
e(S::Computers, "AnyBot Computer Use", "看畫面和操作", ""),
e(S::Computers, "AnyBot Computer Use", "螢幕錄製", "權限 macOS 看螢幕"),
e(S::Computers, "AnyBot Computer Use", "輔助使用", "Accessibility 權限 點擊 打字"),
e(S::Computers, "AnyBot Computer Use", "授予權限", "系統設定 隱私權"),
e(S::Computers, "AnyBot Computer Use", "一律允許的應用程式", "App 應用程式 允許"),
e(S::Computers, "示範教學", "示範教學", "教 錄製 示範"),
// 權限
e(S::Review, "權限", "", "安全 核准 允許 permission"),
e(S::Review, "權限", "直接操作", "不用問"),
e(S::Review, "權限", "智慧模式", ""),
e(S::Review, "權限", "一律放行", "全部允許"),
e(S::Review, "權限", "自動審核", "審核員 review"),
// 保險庫、語音
e(S::Vault, "保險庫", "", "密碼 帳密 登入資訊 鑰匙圈 vault password"),
e(S::Voice, "語音", "語音服務", "voice"),
e(S::Voice, "語音", "聽(語音轉文字)", "語音輸入 聽寫 Whisper STT 轉文字 會議錄音"),
e(S::Voice, "語音", "說(朗讀)", "朗讀 TTS 唸出來 聲音"),
// 更新
e(S::Updates, "更新", "AnyBot 更新", "新版本 升級 update"),
e(S::Updates, "更新", "版本", "version 哪一版"),
e(S::Updates, "更新", "自動更新", "離開時更新"),
e(S::Updates, "更新", "園丁報告", "例行任務 失敗 走冤枉路"),
e(S::Updates, "更新", "待改進", "改進 回報 回饋"),
e(S::Updates, "疑難排解", "疑難排解", ""),
e(S::Updates, "疑難排解", "重新啟動", "重開 restart 卡住 不對勁"),
];
/// Titles the settings pages draw that aren't searched for, and why.
#[cfg(test)]
const NOT_SEARCHED: &[&str] = &[
// The connector list's own headings and one connector's page: names, not settings.
"已加入",
"設定",
];
/// Where a hit leads.
#[derive(Clone)]
pub(super) enum Target {
Entry(usize),
Provider(crate::providers::ProviderKind),
}
pub(super) struct Hit {
pub title: String,
pub path: String,
pub target: Target,
}
/// A page's name in the list (and in a hit's path).
pub(super) fn tab_name(tab: SettingsTab) -> &'static str {
match tab {
S::General => "一般",
S::Remote => "一般 › 手機與帳號",
S::Me => "個人資料",
S::Providers => "模型",
S::Channels => "整合",
S::Computers => "電腦",
S::Review => "權限",
S::Vault => "保險庫",
S::Voice => "語音",
S::Updates => "更新",
}
}
const MAX_HITS: usize = 12;
/// 搜尋設定 for the phone: the same hits, each with the phone's page that has it (its 設定 pages
/// are named like the computer's tabs; a model service is under 模型).
pub(super) fn find_for_phone(q: &str) -> serde_json::Value {
let page = |tab: SettingsTab| match tab {
S::General => "general",
S::Remote => "account",
S::Me => "me",
S::Providers => "models",
S::Channels => "integrations",
S::Computers => "computers",
S::Review => "perms",
S::Vault => "vault",
S::Voice => "voice",
S::Updates => "updates",
};
let hits: Vec<serde_json::Value> = find(q)
.into_iter()
.map(|h| {
let go = match &h.target {
Target::Entry(i) => page(INDEX[*i].tab),
Target::Provider(_) => "models",
};
serde_json::json!({"title": h.title, "path": h.path, "page": go})
})
.collect();
serde_json::json!({"ok": true, "hits": hits})
}
/// What matches: titles that start with it, then titles that contain it, then the heading or the
/// other words.
pub(super) fn find(q: &str) -> Vec<Hit> {
let q = q.trim().to_lowercase();
if q.is_empty() {
return vec![];
}
let mut hits: Vec<(u8, usize, Hit)> = vec![];
for (i, x) in INDEX.iter().enumerate() {
let title = if x.title.is_empty() { x.place } else { x.title };
let tl = t(title).to_lowercase();
let rank = if tl.starts_with(&q) || title.to_lowercase().starts_with(&q) {
0
} else if tl.contains(&q) || title.to_lowercase().contains(&q) {
1
} else if x.place.to_lowercase().contains(&q) || x.words.to_lowercase().contains(&q) {
2
} else {
continue;
};
let (page, place) = (t(tab_name(x.tab)), t(x.place));
let path = if x.title.is_empty() && x.place == tab_name(x.tab) {
t("設定頁")
} else if x.title.is_empty() || page.ends_with(&place) {
page
} else {
format!("{page} › {place}")
};
hits.push((rank, i, Hit { title: t(title), path, target: Target::Entry(i) }));
}
for (j, k) in crate::providers::ALL_PROVIDERS.into_iter().enumerate() {
let name = k.label().to_lowercase();
let rank = if name.starts_with(&q) {
0
} else if name.contains(&q) {
1
} else {
continue;
};
hits.push((rank, INDEX.len() + j, Hit { title: k.label().to_string(), path: t("模型"), target: Target::Provider(k) }));
}
hits.sort_by_key(|(rank, i, _)| (*rank, *i));
hits.into_iter().take(MAX_HITS).map(|(_, _, h)| h).collect()
}
impl App {
/// Go to what was picked: its page, the page inside it, then outline its row.
pub(super) fn settings_go(&mut self, ctx: &egui::Context, target: &Target) {
match target {
Target::Entry(i) => {
let x = &INDEX[*i];
self.settings_tab = x.tab;
if let Some(open) = x.open {
open(self);
}
if !x.title.is_empty() {
jump_to(ctx, x.title);
}
}
Target::Provider(k) => {
self.settings_tab = SettingsTab::Providers;
self.settings_provider = *k;
self.settings_provider_open = true;
}
}
}
}
// ── The outline ──
struct Jump {
title: String,
/// When it was asked for, then when its row was first drawn.
at: f64,
drawn: bool,
}
thread_local! {
static JUMP: RefCell<Option<Jump>> = const { RefCell::new(None) };
}
/// How long the outline stays; a row never drawn (on another page, folded away) is given up after
/// as long.
const LIT_SECS: f64 = 1.8;
pub(super) fn jump_to(ctx: &egui::Context, title: &str) {
let now = ctx.input(|i| i.time);
JUMP.with(|j| *j.borrow_mut() = Some(Jump { title: title.to_string(), at: now, drawn: false }));
ctx.request_repaint();
}
/// Called with each heading and row as it is drawn: the one searched for is scrolled into view
/// (once) and outlined, fading.
pub(super) fn jump_mark(ui: &egui::Ui, title: &str, rect: egui::Rect, p: Palette) {
JUMP.with(|j| {
let mut j = j.borrow_mut();
let Some(x) = j.as_mut() else { return };
let now = ui.input(|i| i.time);
if now - x.at > LIT_SECS {
*j = None;
return;
}
if x.title != title {
return;
}
if !x.drawn {
ui.scroll_to_rect(rect, Some(Align::Center));
x.drawn = true;
x.at = now;
}
let fade = (1.0 - (now - x.at) / LIT_SECS).clamp(0.0, 1.0) as f32;
ui.painter().rect_stroke(rect.expand(3.0), R_M, Stroke::new(2.0, p.accent.gamma_multiply(fade)), egui::StrokeKind::Outside);
ui.ctx().request_repaint_after(anim_after(40));
});
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn what_is_typed_finds_titles_first_then_other_words() {
let titles = |q: &str| find(q).into_iter().map(|h| h.title).collect::<Vec<_>>();
// A title that starts with it comes before one that only contains it.
let mut v = titles("自動");
v.truncate(3);
v.sort();
assert_eq!(v, ["自動審核", "自動更新", "自動更新映像檔"]);
let v = titles("更新");
assert!(v.iter().position(|x| x == "更新 Bot 的電腦") < v.iter().position(|x| x == "AnyBot 更新"), "{v:?}");
// Other words find the row: 深色 is the 主題 row; billing is 用量.
assert_eq!(titles("深色")[0], "主題");
assert_eq!(titles("billing")[0], "用量");
// A provider by its name, on 模型.
let h = find("ollama");
assert!(h.iter().any(|h| matches!(h.target, Target::Provider(crate::providers::ProviderKind::Ollama)) && h.path == "模型"), "{:?}", h.iter().map(|h| &h.title).collect::<Vec<_>>());
// The path names the page and the heading.
let h = find("時區");
assert_eq!((h[0].title.as_str(), h[0].path.as_str()), ("時區", "一般 › Bot"));
assert!(find(" ").is_empty() && find("沒有這種設定xyz").is_empty());
assert!(find("的").len() <= MAX_HITS);
}
/// Every heading and row title the settings pages draw can be searched for — a new setting
/// that isn't added to INDEX fails here — and nothing in INDEX is gone from the pages.
#[test]
fn every_setting_on_the_pages_is_in_the_search() {
let sources: Vec<(&str, &str)> = vec![
("app.rs", include_str!("../app.rs")),
("remote_ui.rs", include_str!("remote_ui.rs")),
("vault_ui.rs", include_str!("vault_ui.rs")),
("voice_ui.rs", include_str!("voice_ui.rs")),
("channels_ui.rs", include_str!("channels_ui.rs")),
("computers_ui.rs", include_str!("computers_ui.rs")),
("me_ui.rs", include_str!("me_ui.rs")),
];
let heads = ["section(ui, \"", "section_with(ui, \"", "setting_title(ui, \"", "card_row(ui, p, \"", "sec_title(ui, \"", "sec_row(ui, p, \"", "sec_row_s(ui, p, \""];
let mut drawn: Vec<String> = vec![];
for (file, src) in &sources {
// The Bot editor (in app.rs) isn't a settings page.
let src = if *file == "app.rs" { src.split("fn bot_editor(").next().unwrap_or("").to_string() + src.split("fn bot_editor(").nth(1).and_then(|r| r.split_once("\n fn ").map(|(_, rest)| rest)).unwrap_or("") } else { src.to_string() };
for h in heads {
for part in src.split(h).skip(1) {
if let Some(name) = part.split('"').next().filter(|n| !n.is_empty()) {
drawn.push(name.to_string());
}
}
}
}
drawn.sort();
drawn.dedup();
assert!(drawn.len() > 60, "the scan found too little: {drawn:?}");
let listed: Vec<&str> = INDEX.iter().map(|x| x.title).filter(|x| !x.is_empty()).collect();
let missing: Vec<&String> = drawn.iter().filter(|d| !listed.contains(&d.as_str()) && !NOT_SEARCHED.contains(&d.as_str())).collect();
assert!(missing.is_empty(), "settings_find.rs INDEX doesn't have these settings (add them, with the words people would type): {missing:?}");
let gone: Vec<&&str> = listed.iter().filter(|l| !drawn.iter().any(|d| d == *l)).collect();
assert!(gone.is_empty(), "INDEX lists titles no settings page draws any more: {gone:?}");
}
}