AnyBot/src/app/layout_audit.rs

328 lines
17 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.

// 版面檢查: draws AnyBot's screens without a window (the demo data, each font of 設定 › 一般 ›
// 字型, the narrowest window and a wide one) and looks at every piece of text that was drawn:
//
// - 被切掉: text that runs past the left or right edge of the area it is drawn in (a field, a
// panel, a dialog) — the person sees half a word, or nothing after the cut.
// - 疊在一起: two pieces of text in the same area drawn over each other (a long label running
// into the button or value next to it).
//
// Scrolling is not a problem (a row half under the bottom edge is fine): only left and right.
use super::*;
use eframe::App as _;
use egui::epaint::{ClippedShape, Shape};
/// One piece of text as drawn: where, inside which clip, and what it says.
struct Word {
clip: egui::Rect,
rect: egui::Rect,
text: String,
}
fn words(shapes: &[ClippedShape]) -> Vec<Word> {
fn walk(clip: egui::Rect, s: &Shape, out: &mut Vec<Word>) {
match s {
Shape::Text(t) => {
let text = t.galley.text().trim().to_string();
if !text.is_empty() {
out.push(Word { clip, rect: t.visual_bounding_rect(), text });
}
}
Shape::Vec(v) => v.iter().for_each(|x| walk(clip, x, out)),
_ => {}
}
}
let mut out = vec![];
for c in shapes {
walk(c.clip_rect, &c.shape, &mut out);
}
out
}
/// What is wrong with the text in one drawn frame, in words a person can find on screen.
/// `long_fields`: long words typed into a one-line field scroll inside it (that is how a field
/// works), so they are not counted then.
pub fn problems(shapes: &[ClippedShape], long_fields: bool) -> Vec<String> {
let ws: Vec<Word> = words(shapes).into_iter().filter(|w| w.clip.intersects(w.rect) && w.clip.width() > 4.0).collect();
let short = |s: &str| s.chars().take(40).collect::<String>().replace('\n', " ");
let mut out = vec![];
for w in &ws {
let over = (w.rect.max.x - w.clip.max.x).max(w.clip.min.x - w.rect.min.x);
let in_field = w.clip.height() < 40.0 && w.rect.min.x >= w.clip.min.x - 1.0;
if over > 1.5 && !(long_fields && in_field) {
out.push(format!("被切掉 {over:.0}px:「{}」", short(&w.text)));
}
}
for (i, a) in ws.iter().enumerate() {
for b in &ws[i + 1..] {
if a.clip != b.clip || a.text == b.text {
continue;
}
let both = a.rect.intersect(b.rect);
if both.width() > 2.0 && both.height() > 5.0 {
out.push(format!("疊在一起:「{}」和「{}」", short(&a.text), short(&b.text)));
}
}
}
out.sort();
out.dedup();
out
}
/// Draw the app a few frames (layouts settle over two or three) and return the last frame's shapes.
fn draw(app: &mut App, ctx: &egui::Context, size: egui::Vec2) -> Vec<ClippedShape> {
let mut frame = eframe::Frame::_new_kittest();
let mut shapes = vec![];
for _ in 0..4 {
let input = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, size)), ..Default::default() };
let mut out = ctx.run_ui(input, |ui| app.ui(ui, &mut frame));
out.textures_delta.clear();
shapes = out.shapes;
}
shapes
}
/// How to open one screen on a fresh demo app.
type Open = Box<dyn Fn(&mut App)>;
/// The screens checked: a name, and how to open it.
fn scenes() -> Vec<(&'static str, Open)> {
let tab = |t: SettingsTab| -> Open {
Box::new(move |a: &mut App| {
a.show_settings = true;
a.settings_tab = t;
})
};
vec![
("設定 › 一般", tab(SettingsTab::General)),
("設定 › 手機與帳號", tab(SettingsTab::Remote)),
("設定 › 模型", tab(SettingsTab::Providers)),
("設定 › 整合 › 訊息管道", tab(SettingsTab::Channels)),
(
"設定 › 整合 › 連接器",
Box::new(|a: &mut App| {
a.show_settings = true;
a.settings_tab = SettingsTab::Channels;
a.ch.sub = 1;
}),
),
(
"設定 › 整合 › 技能",
Box::new(|a: &mut App| {
a.show_settings = true;
a.settings_tab = SettingsTab::Channels;
a.ch.sub = 2;
}),
),
("設定 › 電腦", tab(SettingsTab::Computers)),
("設定 › 權限", tab(SettingsTab::Review)),
("設定 › 保險庫", tab(SettingsTab::Vault)),
("設定 › 語音", tab(SettingsTab::Voice)),
("設定 › 更新", tab(SettingsTab::Updates)),
(
"右側面板(進行中,長的重試訊息)",
Box::new(|a: &mut App| {
a.state.selected = 5;
a.popup_hidden.extend(a.state.bots.iter().map(|b| b.id));
a.panel = Some(panel_ui::PanelTab::Activity);
for l in a.streams.values_mut() {
l.status = Some("模型服務回應錯誤(429 Too Many Requests):{\"type\":\"error\",\"error\":{\"type\":\"rate_limit_error\"}},12 秒後再試".into());
}
}),
),
(
"右側面板 › 資料庫",
Box::new(|a: &mut App| {
a.state.selected = 1;
a.panel = Some(panel_ui::PanelTab::Library);
}),
),
(
"聊天:工作中(長狀態、長網址、超長單字)",
Box::new(|a: &mut App| {
let id = a.state.selected;
if let Some(b) = a.state.bot_mut(id) {
b.messages.push(Message::user("看看這個 https://example.com/a/very/very/long/url/that/keeps/going/through/the/whole/window/path/segment?query=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaEND 還有 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaEND"));
b.messages.push(Message::assistant("文字裡的超長英數混合字串會把氣泡撐破:supercalifragilisticexpialidocioussupercalifragilisticexpialidocioussupercalifragilisticexpialidociousEND 还有中文夹在中间很长的句子不分隔的情况测试测试测试END", "模型"));
}
let (reply, _keep) = std::sync::mpsc::channel::<ApprovalAnswer>();
let _ = &reply;
a.streams.insert(id, Live { cancel: Arc::new(AtomicBool::new(false)), started: Instant::now(), last: Instant::now(), produced: true, status: Some("執行中:npm run build --progress=false --some-really-long-flag-name-abcdefghijklmnopqrstuvwxyz-0123456789 --more".into()), paused: false, paused_at: None, unattended: false, steer: Arc::new(Mutex::new(vec![])), direct: Arc::new(AtomicBool::new(false)), turn_id: "audit-turn".into(), turn: 0 });
}),
),
(
"聊天:需要你允許(長理由)",
Box::new(|a: &mut App| {
let id = a.state.selected;
let (reply, _keep) = std::sync::mpsc::channel::<ApprovalAnswer>();
let _ = &reply;
a.approvals.insert(id, Approval { call_id: "audit-ask".into(), tool: "shell".into(), reason: format!("執行:{}", "rm -rf ./build && very_long_command --with-a-single-unbreakable-token-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ".repeat(3)), grant: String::new(), reply, kind: ApprovalKind::Action });
}),
),
(
"聊天:問題卡(長問題長選項)",
Box::new(|a: &mut App| {
let id = a.state.selected;
let (reply, _keep) = std::sync::mpsc::channel::<ApprovalAnswer>();
let _ = &reply;
let qs = serde_json::json!({"questions": [
{"question": "請選一個要彙整的資料夾(名字很長的資料夾在伺服器上的深層路徑裡)", "options": [
"客戶服務與售後追蹤小組・每週報表整理專用資料夾(台北辦公室)",
"Extremely Long Option Name That Keeps Going And Going And Going Without Breaking Anywhere",
], "multiple": true},
{"question": "寄件日期", "default": "2026-07-30"}
]});
a.approvals.insert(id, Approval { call_id: "audit-q".into(), tool: crate::ask::TOOL.into(), reason: qs.to_string(), grant: String::new(), reply, kind: ApprovalKind::Question });
}),
),
(
"聊天:需要處理(長指示)",
Box::new(|a: &mut App| {
let id = a.state.selected;
let (reply, _keep) = std::sync::mpsc::channel::<ApprovalAnswer>();
let _ = &reply;
a.approvals.insert(id, Approval { call_id: "audit-h".into(), tool: String::new(), reason: format!("請在這台電腦上登入公司入口網站並通過驗證碼,帳號是 someone@example-company.com.tw,驗證說明:{}", "請依畫面上的提示完成驗證".repeat(8)), grant: crate::model::BOT_COMPUTER_NAME.into(), reply, kind: ApprovalKind::Handoff });
}),
),
(
"Bot 設定",
Box::new(|a: &mut App| {
if let Some(b) = a.state.bots.first().cloned() {
a.edit_bot = Some((b, false));
}
}),
),
(
"例行任務",
Box::new(|a: &mut App| {
let id = a.state.bots.iter().find(|b| !b.routines.is_empty()).map(|b| b.id).unwrap_or(1);
a.show_routines = Some(id);
}),
),
(
"頁面(圖表:長條排序、多線、圓餅、stats)",
Box::new(|a: &mut App| {
let (pages, next, id) = crate::pages::demo(crate::model::now_ms());
a.state.pages = pages;
a.state.next_page_id = next;
if let Some(pg) = a.state.pages.iter_mut().find(|pg| pg.id == id) {
pg.body.push_str("\n\n## 圖表\n```chart\nbar 各季下載量(個)\n北部 | 940\n中部 | 620\n南部 | 780\n東部 | 90\n```\n\n```chart\nline 月度下載(個)\n| 1月 | 2月 | 3月 | 4月\n去年 | 120 | 180 | 150 | 210\n今年 | 200 | 260 | 320 | 390\n```\n\n```chart\npie 裝置\n手機 | 550\n桌面 | 300\n平板 | 150\n```\n\n```stats\n本季下載 | 2,430 | ↑ 18% 較上季\n上季 | 2,060\n```\n");
}
a.state.selected = 1;
a.page_view = Some((id, None));
}),
),
]
}
/// The demo data with every name and line as long as a person's real ones get: long bot names
/// and descriptions, connectors with long commands, skills with long descriptions, a channel, a
/// few SSH computers, routines with long titles, folders deep in the disk.
fn worst_case(app: &mut App) {
let long = "客戶服務與售後追蹤小組・每週報表整理專用助理(台北辦公室)";
for (i, b) in app.state.bots.iter_mut().enumerate() {
b.name = format!("{long}{i}");
b.description = "負責整理每週的客戶回饋、追蹤未結案的工單、彙整成報表後寄給主管,並在 Slack 上提醒負責的同事".into();
for r in &mut b.routines {
r.title = "每天早上九點整理昨天所有客戶回饋與未結案工單,寄出摘要給主管並在頻道提醒".into();
}
}
let server = |name: &str, command: &str, url: &str| -> crate::mcp::Server {
serde_json::from_value(serde_json::json!({"name": name, "command": command, "args": ["-y", "@modelcontextprotocol/server-filesystem", "/Users/someone/Documents/Projects/very-long-folder-name/another-level"], "url": url})).expect("server")
};
app.state.mcp_servers = vec![
server("playwright-browser-automation-for-testing", "npx", ""),
server("company-internal-knowledge-base-search", "", "https://mcp.internal.example-company.com.tw/v1/knowledge-base/streamable-http"),
server("fetch", "uvx", ""),
];
for sk in &mut app.state.skills {
sk.name = format!("{}-with-a-much-longer-name-than-usual", sk.name);
sk.description = "建立、編輯、分析試算表檔案(.xlsx、.xlsm、.csv、.tsv),包含公式、格式、圖表、樞紐分析與資料清理,並在完成後驗證每個儲存格的計算結果".into();
}
app.state.channels = vec![serde_json::from_value(serde_json::json!({"id": 1, "kind": "Telegram", "name": "客戶服務群組・台北辦公室與高雄辦公室共用的通知頻道", "bot_id": app.state.bots[0].id, "token": "123456:ABC", "target": "-1001234567890123"})).expect("channel")];
app.state.remote_computers = (0..3)
.map(|i| serde_json::from_value(serde_json::json!({"name": format!("辦公室三樓會議室旁邊的 Linux 伺服器 {i}"), "ssh_target": format!("administrator@build-server-{i}.internal.example-company.com.tw"), "dir": "/srv/projects/customer-service/reports/weekly"})).expect("computer"))
.collect();
app.state.doc_folders = vec!["/Users/someone/Library/Mobile Documents/com~apple~CloudDocs/工作/客戶服務/2026 年度報表與會議紀錄".into()];
app.state.review_allow_rules = vec!["在工作資料夾(~/Documents/Projects/customer-service/reports)裡建立或修改文字檔與試算表".into()];
app.state.review_ask_rules = vec!["刪除任何檔案、清空資料夾,或是把檔案移到垃圾桶之外的任何地方".into()];
}
/// One font and one set of data, every screen at every width.
fn audit_one(font: &str, worst: bool) -> Vec<String> {
let data = if worst { "長資料" } else { "示範" };
let mut report = vec![];
// The narrowest window AnyBot allows, a usual one, and a wide one.
for w in [SIDEBAR_MIN_WIDTH + CHAT_MIN_WIDTH, 1000.0, 1440.0] {
for (name, open) in scenes() {
let ctx = egui::Context::default();
crate::load_fonts_as(&ctx, font);
let mut app = App::new(&ctx, Some(std::env::temp_dir().join("anybot-layout-audit.png")));
app.popup_hidden.extend(app.state.bots.iter().map(|b| b.id));
if worst {
worst_case(&mut app);
}
open(&mut app);
// Dialogs show part of a page at a time: down the page until nothing new shows.
let mut seen: std::collections::HashSet<String> = Default::default();
for step in 0..12 {
super::DIALOG_SCROLL.with(|c| c.set(Some(step as f32 * 400.0)));
let shapes = draw(&mut app, &ctx, vec2(w, 1000.0));
let texts: Vec<String> = words(&shapes).into_iter().filter(|x| x.clip.intersects(x.rect)).map(|x| x.text).collect();
let fresh = texts.iter().filter(|t| !seen.contains(*t)).count();
seen.extend(texts);
for p in problems(&shapes, worst) {
report.push(format!("[{data} {font} {w:.0}] {name}: {p}"));
}
if step > 0 && fresh == 0 {
break;
}
}
super::DIALOG_SCROLL.with(|c| c.set(None));
}
}
report
}
/// Every screen, font and width: what is cut off or drawn over something else (each font and
/// set of data on a thread of its own).
fn audit() -> Vec<String> {
let runs: Vec<_> = ["noto", "huninn", "system"]
.into_iter()
.flat_map(|f| [(f, false), (f, true)])
.map(|(font, worst)| std::thread::Builder::new().stack_size(64 << 20).spawn(move || audit_one(font, worst)).expect("thread"))
.collect();
let mut report: Vec<String> = runs.into_iter().flat_map(|h| h.join().expect("layout check")).collect();
report.sort();
report.dedup();
report
}
#[test]
fn text_stays_inside_its_place_on_every_screen() {
let report = audit();
assert!(report.is_empty(), "{} 個版面問題:\n{}", report.len(), report.join("\n"));
}
#[test]
fn the_check_sees_cut_and_overlapping_text() {
// A label running into its neighbour, and a word past its field's edge, are both found.
let ctx = egui::Context::default();
let mut shapes = vec![];
for _ in 0..2 {
let input = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(400.0, 200.0))), ..Default::default() };
let mut out = ctx.run_ui(input, |ui| {
let p = ui.painter();
let font = egui::FontId::proportional(13.0);
p.text(egui::pos2(10.0, 10.0), egui::Align2::LEFT_TOP, "模型服務回應錯誤(429 Too Many Requests)", font.clone(), Color32::WHITE);
p.text(egui::pos2(120.0, 10.0), egui::Align2::LEFT_TOP, "停止", font.clone(), Color32::WHITE);
ui.painter().with_clip_rect(egui::Rect::from_min_size(egui::pos2(10.0, 60.0), vec2(30.0, 20.0))).text(egui::pos2(10.0, 60.0), egui::Align2::LEFT_TOP, "03:00", font, Color32::WHITE);
});
out.textures_delta.clear();
shapes = out.shapes;
}
let found = problems(&shapes, false);
assert!(found.iter().any(|p| p.starts_with("疊在一起") && p.contains("停止")), "{found:?}");
assert!(found.iter().any(|p| p.starts_with("被切掉") && p.contains("03:00")), "{found:?}");
}