AnyBot/src/app/layout_audit.rs

689 lines
38 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 and very long data, in the
// app's fonts — 思源黑體 and 思源宋體 — 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,
size: f32,
}
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, size: t.galley.job.sections.first().map(|s| s.format.font_id.size).unwrap_or(13.0) });
}
}
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. `sideways`: strips whose content scrolls sideways (a
/// wide table) — a word cut at their edge is scrolled out of view, not cut by mistake.
pub fn problems(shapes: &[ClippedShape], long_fields: bool, sideways: &[egui::Rect]) -> Vec<String> {
// (Clipped by the strip across — its clip's sides are the strip's — and inside it down.)
let scrolled = |w: &Word| sideways.iter().any(|r| w.clip.min.x >= r.min.x - 1.0 && w.clip.max.x <= r.max.x + 1.0 && r.y_range().expand(1.0).contains(w.rect.center().y));
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) && !scrolled(w) {
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 {
// (Only the last frame's sideways strips are kept.)
super::take_sideways();
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;
}),
),
// Each item's own page, the markets and the form (a list with pages, like other apps).
(
"設定 › 整合 › 連接器 › 一個連接器",
Box::new(|a: &mut App| {
a.show_settings = true;
a.settings_tab = SettingsTab::Channels;
a.ch.sub = 1;
a.ch.mcp_page = channels_ui::Page::Item(a.state.mcp_servers.last().map(|s| s.name.clone()).unwrap_or_default());
// Connected, with many tools (long names, long descriptions, none at all).
a.mir.mcp_state = channels_ui::demo_mcp_state(&a.state.mcp_servers, 24);
}),
),
(
"設定 › 整合 › 連接器 › 瀏覽市集",
Box::new(|a: &mut App| {
a.show_settings = true;
a.settings_tab = SettingsTab::Channels;
a.ch.sub = 1;
a.ch.mcp_page = channels_ui::Page::Market;
}),
),
(
"設定 › 整合 › 連接器 › 新增連接器",
Box::new(|a: &mut App| {
a.show_settings = true;
a.settings_tab = SettingsTab::Channels;
a.ch.sub = 1;
a.ch.mcp_page = channels_ui::Page::Add;
}),
),
(
"設定 › 整合 › 技能 › 一個技能",
Box::new(|a: &mut App| {
a.show_settings = true;
a.settings_tab = SettingsTab::Channels;
a.ch.sub = 2;
a.ch.skill_page = channels_ui::Page::Item(a.state.skills.first().map(|s| s.name.clone()).unwrap_or_default());
}),
),
(
"設定 › 整合 › 技能 › 瀏覽市集",
Box::new(|a: &mut App| {
a.show_settings = true;
a.settings_tab = SettingsTab::Channels;
a.ch.sub = 2;
a.ch.skill_page = channels_ui::Page::Market;
}),
),
("設定 › 電腦", 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;
// 目標, 計畫 and 一律放行 at once: three icons beside the face's words.
a.state.always_approve = true;
let long = "把客戶服務與售後追蹤小組的每週報表從舊的共用資料夾搬到新的雲端硬碟並保留所有版本紀錄";
let args = |n: &str| serde_json::json!({"summary": format!("{long},做完後兩邊的檔案數量和最後修改時間都一樣。"), "steps": [
{"title": format!("{n}備份舊資料夾到 /Volumes/Backup/very/deep/path/that/keeps/going/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaEND"), "detail": "Extremely-long-unbreakable-detail-token-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaEND"},
{"title": long}, {"title": "檢查兩邊的檔案數量"}],
"check": "兩邊 find | wc -l 一樣", "notes": format!("會用掉約 2 GB 空間;{long}")}).to_string();
if let Some(b) = a.state.bot_mut(id) {
let call = |cid: &str, n: &str| crate::model::ToolCall { id: cid.into(), name: crate::plan::SUBMIT_TOOL.into(), args: args(n), status: ToolStatus::Done };
b.messages.push(Message::user(&format!("/plan {long}")));
b.messages.push(Message { tool_calls: vec![call("audit-p1", "")], ..Message::assistant("", "模型") });
b.messages.push(Message::tool_result("audit-p1", crate::plan::SUBMIT_TOOL, &crate::plan::approved_result(&[])));
b.messages.push(Message { tool_calls: vec![call("audit-p2", "新版:")], ..Message::assistant("", "模型") });
b.goal = Some(crate::goal::Goal::new(long, 0));
b.plan = Some(crate::plan::Plan { task: long.into(), since: 0, stage: crate::plan::Stage::Doing, revisions: 0, steps: vec![
crate::plan::Step { title: "備份舊資料夾到 /Volumes/Backup/very/deep/path/that/keeps/going/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaEND".into(), status: crate::plan::Status::Done },
crate::plan::Step { title: long.into(), status: crate::plan::Status::InProgress },
crate::plan::Step { title: "檢查兩邊的檔案數量".into(), status: crate::plan::Status::Pending }] });
}
}),
),
(
"聊天:需要處理(長指示)",
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));
}
}),
),
(
// 自訂顏色: its sliders used to push the whole window wider than its title bar.
"Bot 設定(自訂顏色)",
Box::new(|a: &mut App| {
if let Some(mut b) = a.state.bots.first().cloned() {
b.color = "#6b4a55".into();
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.kind = "data".into();
pg.verdict = "機箱本身健康(CMM Normal、BMC 可連)。問題在 A1 槽 25G 交換模組:近 30 天瞬斷 9 次,每次 1~2 秒自解。".into();
pg.kpis = vec![
crate::pages::Kpi { label: "Switch A1 瞬斷(近 30 天)".into(), value: "9 次".into(), delta: "每次 1~2 秒自解".into() },
crate::pages::Kpi { label: "未確認 Critical".into(), value: "8 筆".into(), delta: "累計 21 筆".into() },
crate::pages::Kpi { label: "槽位可見度".into(), value: "2 / 5".into(), delta: "A1、A7、A8 無健康資料".into() },
crate::pages::Kpi { label: "實際電源模組".into(), value: "6 顆".into(), delta: "B2、B3 槽為空板".into() },
];
pg.body.push_str("\n\n## 刀鋒\n| 槽位 | 序號 | 型號 | 健康 | CPU | 記憶體 | BMC | BIOS | IP | 電源 |\n|---|---|---|---|---|---|---|---|---|---|\n| A8-1 | FruPS202505211418 | SBI-612B-1C2N | **無資料** | Xeon 6737P | 128 GB | 1.5 | 01.11.05.00 | 10.184.17.71 | 關 |\n");
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(&ctx);
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, &super::take_sideways()) {
report.push(format!("[{data} {font} {w:.0}] {name}: {p}"));
}
for (title, over) in super::take_wider_dialogs() {
report.push(format!("[{data} {font} {w:.0}] {name}: 「{title}」視窗被內容撐寬 {over:.0}px"));
}
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"]
.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:?}");
}
/// One frame with these events (a press, a key, typing).
fn step(app: &mut App, ctx: &egui::Context, size: egui::Vec2, events: Vec<egui::Event>) -> Vec<ClippedShape> {
let mut frame = eframe::Frame::_new_kittest();
let input = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, size)), events, ..Default::default() };
let mut out = ctx.run_ui(input, |ui| app.ui(ui, &mut frame));
out.textures_delta.clear();
out.shapes
}
fn key(k: egui::Key) -> egui::Event {
egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }
}
/// 連接器's own page: the name field keeps the keyboard while the tools above come and go (a
/// reconnect), the name changes only when it is done (Enter), and a name another connector has
/// is refused — typing 「github」 down to 「git」 used to jump to the other connector and make two
/// of the same name.
#[test]
fn a_connector_is_renamed_when_done_and_its_field_keeps_the_keyboard() {
let ctx = egui::Context::default();
crate::load_fonts(&ctx);
let mut app = App::new(&ctx, Some(std::env::temp_dir().join("anybot-rename-test.png")));
app.popup_hidden.extend(app.state.bots.iter().map(|b| b.id));
let server = |n: &str| crate::mcp::Server { name: n.into(), url: format!("https://{n}.example/mcp"), enabled: true, ..Default::default() };
app.state.mcp_servers = vec![server("git"), server("github")];
app.mir.mcp_state = channels_ui::demo_mcp_state(&app.state.mcp_servers, 3);
app.show_settings = true;
app.settings_tab = SettingsTab::Channels;
app.ch.sub = 1;
app.ch.mcp_page = channels_ui::Page::Item("github".into());
let size = vec2(1000.0, 1600.0);
draw(&mut app, &ctx, size);
// The name field, given the keyboard as a press would (by its id, not where it is drawn:
// other tests switch the language, and the page's layout with it, while this one runs).
let field = app.ch.name_field.expect("the name field");
ctx.memory_mut(|m| m.request_focus(field));
step(&mut app, &ctx, size, vec![]);
step(&mut app, &ctx, size, vec![key(egui::Key::End)]);
let typing = ctx.memory(|m| m.focused()).expect("the name field has the keyboard");
for _ in 0..3 {
step(&mut app, &ctx, size, vec![key(egui::Key::Backspace)]);
}
assert_eq!(app.state.mcp_servers[1].name, "github", "not renamed while typing");
assert_eq!(app.ch.mcp_page, channels_ui::Page::Item("github".into()));
// It reconnects (its tools go away for a moment): the field keeps the keyboard.
app.mir.mcp_state = channels_ui::demo_mcp_state(&[], 0);
step(&mut app, &ctx, size, vec![]);
assert_eq!(ctx.memory(|m| m.focused()), Some(typing), "the field kept the keyboard");
// 「git」 is taken: not renamed, and the page says why.
step(&mut app, &ctx, size, vec![key(egui::Key::Enter)]);
let shapes = step(&mut app, &ctx, size, vec![]);
assert_eq!(app.state.mcp_servers.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(), ["git", "github"]);
// (Not by its words: other tests switch the language while this one runs, and the page
// translates what it shows. A line naming 「git」 is drawn, beyond the names themselves.)
let why = app.ch.mcp_note.lock().unwrap().clone();
assert!(why.contains("git"), "says why: {why:?}");
assert!(words(&shapes).iter().any(|w| w.text.contains("git") && w.text.chars().count() > 12 && !w.text.starts_with("http")), "the reason is drawn");
// A free name: taken when done, and the page follows it. (The same field, given the
// keyboard directly: a second press read as a double press is timing, not what's tested.)
let _ = &shapes;
ctx.memory_mut(|m| m.request_focus(typing));
step(&mut app, &ctx, size, vec![]);
step(&mut app, &ctx, size, vec![key(egui::Key::End)]);
step(&mut app, &ctx, size, vec![egui::Event::Text("-work".into())]);
step(&mut app, &ctx, size, vec![key(egui::Key::Enter)]);
step(&mut app, &ctx, size, vec![]);
assert_eq!(app.state.mcp_servers[1].name, "github-work");
assert_eq!(app.ch.mcp_page, channels_ui::Page::Item("github-work".into()));
// Typing a name and going to another tab (the field isn't drawn again): taken at once, not
// left to come back later. (The same field, given the keyboard directly: two presses on one
// spot in frames without time read as a double press.)
ctx.memory_mut(|m| m.request_focus(typing));
step(&mut app, &ctx, size, vec![]);
step(&mut app, &ctx, size, vec![key(egui::Key::End)]);
step(&mut app, &ctx, size, vec![egui::Event::Text("-x".into())]);
assert_eq!(ctx.memory(|m| m.focused()), Some(typing));
app.ch.sub = 2;
step(&mut app, &ctx, size, vec![]);
assert_eq!(app.state.mcp_servers[1].name, "github-work-x", "taken on leaving");
assert!(app.ch.mcp_name.is_none(), "nothing left to come back later");
}
/// Esc while typing a connector's new name puts the old one back.
#[test]
fn esc_puts_a_connectors_name_back() {
let ctx = egui::Context::default();
crate::load_fonts(&ctx);
let mut app = App::new(&ctx, Some(std::env::temp_dir().join("anybot-rename-esc-test.png")));
app.popup_hidden.extend(app.state.bots.iter().map(|b| b.id));
app.state.mcp_servers = vec![crate::mcp::Server { name: "notion".into(), url: "https://notion.example/mcp".into(), enabled: true, ..Default::default() }];
app.show_settings = true;
app.settings_tab = SettingsTab::Channels;
app.ch.sub = 1;
app.ch.mcp_page = channels_ui::Page::Item("notion".into());
let size = vec2(1000.0, 1600.0);
draw(&mut app, &ctx, size);
ctx.memory_mut(|m| m.request_focus(app.ch.name_field.expect("the name field")));
step(&mut app, &ctx, size, vec![]);
step(&mut app, &ctx, size, vec![key(egui::Key::End)]);
step(&mut app, &ctx, size, vec![egui::Event::Text("-work".into())]);
step(&mut app, &ctx, size, vec![key(egui::Key::Escape)]);
step(&mut app, &ctx, size, vec![]);
app.ch.sub = 2;
step(&mut app, &ctx, size, vec![]);
assert_eq!(app.state.mcp_servers[0].name, "notion");
}
/// 天地審計(手動跑:`cargo test layout_audit::report -- --ignored --nocapture`):
/// 每一屏在 1000×800 畫一次,量「看得見的最近內容」離窗邊多遠——頂、底、左、右。
/// 頂/底 < 8px 或左右 < 6px 視為貼邊(破版候補:滾動列表頂部貼邊是常見原因)。
#[test]
#[ignore]
fn report_breathing_room() {
let (w, h) = (1000.0f32, 800.0f32);
let mut lines = vec![];
for (name, open) in scenes() {
let ctx = egui::Context::default();
crate::load_fonts(&ctx);
let mut app = App::new(&ctx, Some(std::env::temp_dir().join("anybot-breathing.png")));
app.popup_hidden.extend(app.state.bots.iter().map(|b| b.id));
open(&mut app);
let shapes = draw(&mut app, &ctx, vec2(w, h));
let ws = words(&shapes);
let ws: Vec<&Word> = ws.iter().filter(|x| x.clip.intersects(x.rect) && x.clip.width() > 4.0 && x.rect.min.y < h).collect();
// 分欄量:側欄(左)、主欄(右);主欄再分上半(內容)與下半(輸入區 y > h-120)。
for (zone, sel, x0, x1) in [
("側欄", 0..=2, 0.0f32, 400.0f32),
("主欄上", 0..=2, 400.0f32, w),
("輸入區", 0..=2, 400.0f32, w),
] {
let top_lim = if zone == "輸入區" { h - 140.0 } else { 0.0 };
let bot_lim = if zone == "輸入區" { h } else { h - 140.0 };
let pick: Vec<&&Word> = ws.iter().filter(|x| x.rect.center().x >= x0 && x.rect.center().x < x1 && x.rect.center().y >= top_lim && x.rect.center().y < bot_lim).collect();
if pick.is_empty() {
continue;
}
let top = pick.iter().map(|x| x.rect.min.y).fold(f32::MAX, f32::min);
let bottom = pick.iter().map(|x| x.rect.max.y).fold(f32::MIN, f32::max);
let left = pick.iter().map(|x| x.rect.min.x).fold(f32::MAX, f32::min);
let right = pick.iter().map(|x| x.rect.max.x).fold(f32::MIN, f32::max);
let flag = |v: f32, lim: f32| if v < lim { "⚠️" } else { " " };
lines.push(format!(
"{}{}{}{} {name} [{zone}]:頂 {top:.0} 底 {:.0} 左 {left:.0} 右 {:.0}",
flag(top, 8.0), flag(h - bottom, 8.0), flag(left, 6.0), flag(w - right, 6.0),
h - bottom, w - right
));
}
let _ = 0..2;
}
for l in &lines {
println!("{l}");
}
}
/// 設計審計(手動跑:`cargo test layout_audit::report_design -- --ignored --nocapture`):
/// 每一屏(1000×800)量四件事,都是肉眼會覺得「破版、擠、亂」的來源:
/// 1. 左緣起點:主欄文字從哪些 x 開始(2px 一桶)——起點越多種,版面越像随机。
/// 2. 擠:主欄裡上下相鄰、x 重疊、垂直縫 <3px 的文字對(沒呼吸)。
/// 3. 字級:用了幾種字級(含大小寫同字号不計)——层次該收斂。
/// 4. 貼邊:小框(卡、按鈕)裡文字離框左緣 <2px 的。
#[test]
#[ignore]
fn report_design() {
let (w, h) = (1000.0f32, 800.0f32);
for (name, open) in scenes() {
let ctx = egui::Context::default();
crate::load_fonts(&ctx);
let mut app = App::new(&ctx, Some(std::env::temp_dir().join("anybot-design.png")));
app.popup_hidden.extend(app.state.bots.iter().map(|b| b.id));
open(&mut app);
let shapes = draw(&mut app, &ctx, vec2(w, h));
let all = words(&shapes);
let ws: Vec<&Word> = all.iter().filter(|x| x.clip.intersects(x.rect) && x.clip.width() > 4.0 && x.rect.min.y < h && x.rect.max.y > 0.0).collect();
// 1. 左緣起點(主欄)。
let mut starts: std::collections::BTreeMap<i32, usize> = Default::default();
for x in &ws {
if x.rect.center().x >= 400.0 {
*starts.entry((x.rect.min.x / 2.0).round() as i32 * 2).or_default() += 1;
}
}
let mut starts: Vec<(i32, usize)> = starts.into_iter().collect();
starts.sort_by_key(|(x, n)| (std::cmp::Reverse(*n), *x));
// 2. 擠。
let mut cramped = 0;
let mut samples = vec![];
let main: Vec<&&Word> = ws.iter().filter(|x| x.rect.center().x >= 400.0).collect();
for a in &main {
for b in &main {
if std::ptr::eq(*a, *b) {
continue;
}
let gap = b.rect.min.y - a.rect.max.y;
if (0.0..3.0).contains(&gap)
&& a.rect.min.x < b.rect.max.x && b.rect.min.x < a.rect.max.x
&& !samples.iter().any(|s: &(String, String)| s.0 == a.text)
{
cramped += 1;
if samples.len() < 3 {
samples.push((a.text.chars().take(14).collect(), b.text.chars().take(14).collect()));
}
}
}
}
// 3. 字級。
let sizes: std::collections::BTreeSet<i32> = ws.iter().map(|x| (x.size * 2.0).round() as i32).collect();
// 4. 貼邊(小框)。
let edge: Vec<String> = ws.iter().filter(|x| x.clip.width() < 940.0 && x.clip.width() > 40.0 && x.rect.min.x - x.clip.min.x < 2.0 && x.clip.min.x > 100.0).map(|x| x.text.chars().take(14).collect()).collect();
println!("── {name}\n 左緣起點 {} 種:{:?}\n 擠:<3px 對 {cramped} {:?}", starts.len(), &starts[..starts.len().min(6)], samples);
println!(" 字級 {} 種:{:?} 貼邊小框文字 {}:{:?}", sizes.len(), sizes.iter().map(|s| *s as f32 / 2.0).collect::<Vec<_>>(), edge.len(), &edge[..edge.len().min(3)]);
}
}
/// 誰貼著窗底(手動):印出底部 12px 內、左半边的文字。
#[test]
#[ignore]
fn report_who_touches_the_floor() {
let (w, h) = (1000.0f32, 800.0f32);
for (name, open) in scenes() {
let ctx = egui::Context::default();
crate::load_fonts(&ctx);
let mut app = App::new(&ctx, Some(std::env::temp_dir().join("anybot-floor.png")));
app.popup_hidden.extend(app.state.bots.iter().map(|b| b.id));
open(&mut app);
let shapes = draw(&mut app, &ctx, vec2(w, h));
let hits: Vec<String> = words(&shapes).iter().filter(|x| x.clip.intersects(x.rect) && x.rect.max.y > h - 12.0 && x.rect.center().x < 500.0).map(|x| format!("「{}」y底 {:.0} x {:.0}", x.text.chars().take(18).collect::<String>(), x.rect.max.y, x.rect.min.x)).collect();
if !hits.is_empty() {
println!("{name}: {}", hits.join("、"));
}
}
}
/// 左緣起點是谁(手動):主欄每個左緣 x(2px 桶)的前三個字。
#[test]
#[ignore]
fn report_who_starts_where() {
let (w, h) = (1000.0f32, 800.0f32);
for (name, open) in scenes() {
let ctx = egui::Context::default();
crate::load_fonts(&ctx);
let mut app = App::new(&ctx, Some(std::env::temp_dir().join("anybot-starts.png")));
app.popup_hidden.extend(app.state.bots.iter().map(|b| b.id));
open(&mut app);
let shapes = draw(&mut app, &ctx, vec2(w, h));
let mut by: std::collections::BTreeMap<i32, Vec<String>> = Default::default();
for x in words(&shapes).iter().filter(|x| x.clip.intersects(x.rect) && x.rect.center().x >= 400.0 && x.rect.min.y < h) {
by.entry((x.rect.min.x / 2.0).round() as i32 * 2).or_default().push(x.text.chars().take(10).collect());
}
if by.len() > 5 {
println!("── {name}");
for (x, t) in &by {
println!(" x={x}: {}", t[..t.len().min(3)].join("、"));
}
}
}
}