AnyBot/src/pages.rs

899 lines
48 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.

// 頁面: pages a bot makes and keeps up to date — a tracker ("台灣 Tesla FSD 追蹤"), a report, a
// comparison — like the original's canvases. The bot writes Markdown (with tables, Mermaid charts
// and a few page blocks: ```stats tiles, ```steps progress, > [!NOTE] call-outs); the chat shows a
// card under the reply, `[標題](page:12)` links open it, and a routine can update it later (each
// update keeps the previous version). Pages live in State, so a brain's pages reach its screens
// and phones with everything else.
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
/// Older versions kept per page.
pub const KEEP_VERSIONS: usize = 10;
pub const MAX_BODY: usize = 200_000;
const MAX_TITLE: usize = 120;
#[derive(Clone, Debug, Serialize, Deserialize, Default, PartialEq)]
pub struct Page {
pub id: u64,
/// The bot that made it (and may change it).
pub bot: u64,
pub title: String,
/// One line under the title on the card ("現況:還在審查第一步").
#[serde(default)]
pub summary: String,
/// Markdown.
pub body: String,
/// ms since 1970.
pub created: i64,
pub updated: i64,
/// 1 for a new page; +1 on every change.
#[serde(default = "one")]
pub revision: u32,
/// What kind of document this is ("data", "compare", "decision", "howto", "timeline",
/// "prose", "notes"): the page's first screen is laid out for its kind, and a page with
/// nothing to show (no numbers, no verdict) keeps its plain reading shape — the shape
/// follows the content, never a template filled with empties.
#[serde(default, skip_serializing_if = "String::is_empty")]
pub kind: String,
/// 3-4 real numbers, only when the page is about data (KPI tiles; never invented).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub kpis: Vec<Kpi>,
/// The page's one-line conclusion (decision/compare pages: shown as a card before the text).
#[serde(default, skip_serializing_if = "String::is_empty")]
pub verdict: String,
/// What changed last time (the bot's words), shown as 「更新:…」.
#[serde(default, skip_serializing_if = "String::is_empty")]
pub note: String,
/// Older versions, oldest first.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub history: Vec<Version>,
}
#[derive(Clone, Debug, Serialize, Deserialize, Default, PartialEq)]
pub struct Kpi {
pub label: String,
pub value: String,
/// ""、"+12%"、"-3 天"(箭頭和顏色由渲染器加)。
#[serde(default, skip_serializing_if = "String::is_empty")]
pub delta: String,
}
#[derive(Clone, Debug, Serialize, Deserialize, Default, PartialEq)]
pub struct Version {
pub revision: u32,
pub at: i64,
pub title: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub summary: String,
pub body: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub note: String,
}
fn one() -> u32 {
1
}
pub fn specs() -> Vec<Value> {
vec![
json!({"name": "write_page", "description": "Make or update a page: a lasting, nicely laid-out document the person can open from the chat and that you keep up to date — a tracker (e.g. 「台灣 Tesla FSD 追蹤」), a report, a comparison, a plan, research notes. Use it whenever the person asks you to track, follow, summarise or compare something they will come back to; then link it in your reply as [標題](page:ID). With an id (or the same title) it replaces that page's content and keeps the old version. Write Markdown: headings, short paragraphs, lists, tables, links to sources, Mermaid charts (```mermaid: pie, xychart-beta bar/line, timeline, gantt, flowchart), and these page blocks:\n```stats\n狀態 | 審查中 | 第 1 步\n預計開放 | 2027 Q2 | 媒體推估\n```\n```steps\n[x] 道路測試計畫審查 | 7/9 月開過兩次會\n[>] 道路測試 | 等交通部核定\n[ ] 正式開放\n```\n```chart\nbar 標題(bar | line | pie 換圖型)\n1月 | 120\n2月 | 320\n```\n```details 指令與原始數據\n(預設收起的 Markdown:證據、長清單、指令)\n```\n多系列:首行 `| 1月 | 2月`(第一格留空),每列 `名稱 | 120 | 320`。圖表用原生繪製(可縮放、hover 看數值,下方自動附數據表),優於 ```mermaid 的圖片。排版由渲染器接手:長條圖自動由大到小排序(月份/年份等自有順序的標籤不排);單系列把數字直接標在圖上、不畫 y 軸;多條線在線尾標系列名——你只要把圖標題寫成結論。\n> [!NOTE] / [!TIP] / [!WARNING] / [!IMPORTANT] call-outs.\n\n寫法(Anthropic 的報告寫法:讀者先掃一眼,需要才往下讀):\n• 選 kind(data 數據分析 / compare 比較評測 / decision 決策備忘 / howto 教學步驟 / timeline 時間線 / prose 純敘述 / notes 筆記),第一屏跟著它:data → 一句結論+kpis 三個真數字+主圖表;compare → 一句取捨+verdict+對比表;decision → verdict 先講+三個理由+風險;howto → 適合誰+steps;timeline → mermaid timeline;prose/notes → 直接內文,不硬湊 KPI 卡。kpis 只放算得出的真數字(附 delta 如 +12%),verdict 只在有明確結論時寫。\n• 每一節的標題就是結論(「240 環境是測試場」,不是「240 環境的現實」),下面第一句補一個理由,再最多三點清單。\n• 數字放 ```stats 或表格,不塞在句子和括號裡;有趨勢或比較就出 ```chart,圖標題寫結論並帶數字,軸標籤帶單位。\n• 粗體一節最多一處(或不用);不用「→」帶結論、不用分隔線(---)、標題不編號(一、二、1.)——標題本身就是分段。\n• 待辦寫成 ```steps 勾選清單;指令放程式碼區塊,不放進表格。\n• 證據、長清單、指令、原始數據放進 ```details 標題(預設收起);第一屏只留結論、數字和下一步。\n• 句子短、主動語氣、用讀者的話(說「通知」不說「webhook 設定」);不寫「值得注意的是」這類套話。\n• 來源放最後,帶連結與日期。更新時把整頁維持成現況(不是日誌),並在 `note` 寫出改了什麼。\n• 存檔時會自動檢查寫法:被退回就照列出的地方改,用同樣的標題再送一次。",
"parameters": {"type": "object", "properties": {
"title": {"type": "string", "description": "Short title, e.g. 台灣 Tesla FSD 追蹤"},
"content": {"type": "string", "description": "The whole page in Markdown (without the title)"},
"summary": {"type": "string", "description": "One line for the card: the current state in a few words"},
"note": {"type": "string", "description": "When updating: what changed, in one short sentence"},
"kind": {"type": "string", "enum": ["data", "compare", "decision", "howto", "timeline", "prose", "notes"], "description": "What kind of document this is; it decides the first screen. Omit for a plain page."},
"kpis": {"type": "array", "description": "Only for data pages: the 2-4 real numbers a reader must see first (never invented, never placeholders).", "items": {"type": "object", "properties": {"label": {"type": "string"}, "value": {"type": "string"}, "delta": {"type": "string", "description": "Change, e.g. +12% / -3 天 (empty when none)"}}, "required": ["label", "value"]}},
"verdict": {"type": "string", "description": "One-line conclusion, for decision/compare pages (rendered as a card before the text)"},
"id": {"type": "integer", "description": "The page to update (from list_pages or an earlier write_page)"}},
"required": ["title", "content"]}}),
json!({"name": "read_page", "description": "Read a page (its Markdown): one of yours before updating it, or another bot's to use what it already found (theirs you can read, not change).", "parameters": {"type": "object", "properties": {"id": {"type": "integer"}, "title": {"type": "string"}}}}),
json!({"name": "list_pages", "description": "List the pages you made, then the other bots' pages you can read (id, title, whose, last update). Look here before researching something a colleague may already track.", "parameters": {"type": "object", "properties": {}}}),
]
}
pub const NAMES: [&str; 3] = ["write_page", "read_page", "list_pages"];
pub fn label(name: &str) -> &'static str {
match name {
"write_page" => "寫頁面",
"read_page" => "讀頁面",
_ => "查看頁面",
}
}
/// A friendly name for the kind, for the page header and card. None for plain pages.
pub fn kind_label(k: &str) -> Option<&'static str> {
Some(match k {
"data" => "數據分析",
"compare" => "比較評測",
"decision" => "決策備忘",
"howto" => "教學步驟",
"timeline" => "時間線",
"prose" => "長文",
"notes" => "筆記",
_ => return None,
})
}
pub fn describe(name: &str, args: &Value) -> String {
match name {
"write_page" | "read_page" => args["title"].as_str().map(String::from).or_else(|| args["id"].as_u64().map(|i| format!("#{i}"))).unwrap_or_default(),
_ => String::new(),
}
}
fn find<'a>(pages: &'a [Page], bot: u64, id: Option<u64>, title: &str) -> Option<&'a Page> {
// A page belongs to the bot that made it: ids are guesses a model can make, and reading
// (or overwriting) another bot's page by id must not work.
match id {
Some(i) => pages.iter().find(|p| p.id == i && p.bot == bot),
None => pages.iter().find(|p| p.bot == bot && same_title(&p.title, title)),
}
}
fn same_title(a: &str, b: &str) -> bool {
let n = |s: &str| s.chars().filter(|c| !c.is_whitespace()).collect::<String>().to_lowercase();
!b.trim().is_empty() && n(a) == n(b)
}
/// What write_page did: the page's id and the text for the model.
pub struct Written {
pub id: u64,
pub text: String,
}
/// write_page: make a page, or replace one (by id, or the same title from this bot).
pub fn write(pages: &mut Vec<Page>, next_id: &mut u64, bot: u64, args: &Value, now: i64) -> Result<Written, String> {
let title: String = args["title"].as_str().unwrap_or("").trim().chars().take(MAX_TITLE).collect();
let body = args["content"].as_str().unwrap_or("").trim().to_string();
let summary: String = args["summary"].as_str().unwrap_or("").trim().chars().take(200).collect();
let note: String = args["note"].as_str().unwrap_or("").trim().chars().take(300).collect();
if title.is_empty() {
return Err("頁面要有標題".into());
}
if body.is_empty() {
return Err("頁面內容是空的".into());
}
if body.len() > MAX_BODY {
return Err(format!("頁面太長了(最多 {} 字)。請精簡,或拆成幾頁。", MAX_BODY));
}
let id = args["id"].as_u64();
// 結構由內容決定:kind 決定第一屏怎麼排,kpis/verdict 有真資料才填、有才渲染。
const KINDS: [&str; 7] = ["data", "compare", "decision", "howto", "timeline", "prose", "notes"];
let kind: String = args["kind"].as_str().unwrap_or("").trim().to_lowercase().chars().take(12).collect();
let kind = if KINDS.contains(&kind.as_str()) { kind } else { String::new() };
let kpis: Vec<Kpi> = args["kpis"].as_array().map(|a| a.iter().filter_map(|k| Some(Kpi { label: k["label"].as_str()?.trim().chars().take(40).collect(), value: k["value"].as_str()?.trim().chars().take(40).collect(), delta: k["delta"].as_str().unwrap_or("").trim().chars().take(20).collect() })).take(4).collect()).unwrap_or_default();
let verdict: String = args["verdict"].as_str().unwrap_or("").trim().chars().take(300).collect();
let existing = find(pages, bot, id, &title).map(|p| p.id);
if id.is_some() && existing.is_none() {
return Err(format!("找不到頁面 #{}。用 list_pages 看有哪些頁面,或不帶 id 建立新的。", id.unwrap_or(0)));
}
match existing {
Some(pid) => {
let p = pages.iter_mut().find(|p| p.id == pid).unwrap();
if p.bot != bot {
return Err("這是別的 Bot 的頁面,不能改".into());
}
if p.body == body && p.title == title && (summary.is_empty() || p.summary == summary) && (kind.is_empty() || p.kind == kind) && (kpis.is_empty() || p.kpis == kpis) && (verdict.is_empty() || p.verdict == verdict) {
return Ok(Written { id: pid, text: format!("頁面「{}」內容沒有變化,沒有更新。連結:[{}](page:{})", p.title, p.title, pid) });
}
p.history.push(Version { revision: p.revision, at: p.updated, title: p.title.clone(), summary: p.summary.clone(), body: std::mem::take(&mut p.body), note: std::mem::take(&mut p.note) });
if p.history.len() > KEEP_VERSIONS {
let extra = p.history.len() - KEEP_VERSIONS;
p.history.drain(..extra);
}
p.title = title;
p.body = body;
if !summary.is_empty() {
p.summary = summary;
}
p.note = note;
if !kind.is_empty() {
p.kind = kind;
}
if !kpis.is_empty() {
p.kpis = kpis;
}
if !verdict.is_empty() {
p.verdict = verdict;
}
p.revision += 1;
p.updated = now;
Ok(Written { id: pid, text: format!("已更新頁面「{}」(第 {} 版,上一版留著)。在回答裡用 [{}](page:{}) 連到它。", p.title, p.revision, p.title, pid) })
}
None => {
let pid = *next_id;
*next_id += 1;
let text = format!("已建立頁面「{title}」。在回答裡用 [{title}](page:{pid}) 連到它;要更新時用 write_page 帶 id {pid}。");
pages.push(Page { id: pid, bot, title, summary, body, created: now, updated: now, revision: 1, note, history: vec![], kind, kpis, verdict });
Ok(Written { id: pid, text })
}
}
}
/// read_page: its own first; then another bot's (同事的頁面, to read — what a colleague already
/// tracks needn't be looked up again). `name` gives a bot's name.
pub fn read(pages: &[Page], bot: u64, args: &Value, name: impl Fn(u64) -> String) -> Result<String, String> {
let title = args["title"].as_str().unwrap_or("");
let id = args["id"].as_u64();
let p = find(pages, bot, id, title).or_else(|| find_any(pages, id, title)).ok_or("找不到這個頁面。用 list_pages 看有哪些。")?;
let whose = if p.bot == bot { String::new() } else { format!("「{}」的頁面,你只能讀,要改請它改;", name(p.bot)) };
Ok(format!("# {}\n({whose}頁面 #{},第 {} 版,更新於 {}{})\n\n{}", p.title, p.id, p.revision, when(p.updated), if p.summary.is_empty() { String::new() } else { format!(";摘要:{}", p.summary) }, p.body))
}
/// Any bot's page, by id or title (the newest of that title).
fn find_any<'a>(pages: &'a [Page], id: Option<u64>, title: &str) -> Option<&'a Page> {
match id {
Some(i) => pages.iter().find(|p| p.id == i),
None => pages.iter().filter(|p| same_title(&p.title, title)).max_by_key(|p| p.updated),
}
}
/// The most of the colleagues' pages listed (the newest).
const OTHERS_LISTED: usize = 30;
/// list_pages: its own, then the other bots' it can read (newest first).
pub fn list(pages: &[Page], bot: u64, name: impl Fn(u64) -> String) -> String {
let line = |p: &Page| format!("#{} 「{}」 第 {} 版,更新於 {}{}", p.id, p.title, p.revision, when(p.updated), if p.summary.is_empty() { String::new() } else { format!(" — {}", p.summary) });
let mine: Vec<String> = pages.iter().filter(|p| p.bot == bot).map(line).collect();
let mut others: Vec<&Page> = pages.iter().filter(|p| p.bot != bot).collect();
others.sort_by_key(|p| std::cmp::Reverse(p.updated));
let mut s = if mine.is_empty() { "你還沒有做任何頁面。".to_string() } else { format!("你的頁面:\n{}", mine.join("\n")) };
if !others.is_empty() {
s.push_str("\n\n其他 Bot 的頁面(可以用 read_page 讀,不能改):\n");
s.push_str(&others.iter().take(OTHERS_LISTED).map(|p| format!("{}({})", line(p), name(p.bot))).collect::<Vec<_>>().join("\n"));
if others.len() > OTHERS_LISTED {
s.push_str(&format!("\n(還有 {} 頁比較舊的,用標題 read_page 也讀得到)", others.len() - OTHERS_LISTED));
}
}
s
}
/// Whose page this id is, when it isn't this bot's (write_page refuses it, saying whose).
pub fn owner_of(pages: &[Page], bot: u64, id: Option<u64>) -> Option<u64> {
pages.iter().find(|p| Some(p.id) == id && p.bot != bot).map(|p| p.bot)
}
/// "11/5 09:33" in the local time zone.
pub fn when(ms: i64) -> String {
use chrono::TimeZone;
crate::routines::person_tz().timestamp_millis_opt(ms).single().map(|t| t.format("%-m/%-d %H:%M").to_string()).unwrap_or_default()
}
/// 「剛剛」「5 分鐘前」「昨天 09:33」「11/3」.
pub fn ago(ms: i64, now: i64) -> String {
use chrono::TimeZone;
let d = (now - ms).max(0) / 1000;
if d < 60 {
return "剛剛".into();
}
if d < 3600 {
return format!("{} 分鐘前", d / 60);
}
let tz = crate::routines::person_tz();
let (Some(t), Some(n)) = (tz.timestamp_millis_opt(ms).single(), tz.timestamp_millis_opt(now).single()) else { return String::new() };
let days = (n.date_naive() - t.date_naive()).num_days();
match days {
0 => format!("今天 {}", t.format("%H:%M")),
1 => format!("昨天 {}", t.format("%H:%M")),
_ if t.format("%Y").to_string() == n.format("%Y").to_string() => t.format("%-m/%-d").to_string(),
_ => t.format("%Y/%-m/%-d").to_string(),
}
}
/// A few lines of plain text for the card: the summary, then the page's first words (no
/// Markdown marks, no code or chart blocks).
pub fn preview(p: &Page, lines: usize) -> Vec<String> {
let mut out = vec![];
if !p.summary.is_empty() {
out.push(p.summary.clone());
}
let mut fence = false;
for l in p.body.lines() {
let t = l.trim();
if t.starts_with("```") {
fence = !fence;
continue;
}
if fence || t.is_empty() || t.starts_with('|') || t.starts_with("---") || t.starts_with('#') {
continue;
}
let t = t.trim_start_matches(['-', '*', '>', ' ']).trim();
let t = callout(t).map(|(_, rest)| rest).unwrap_or_else(|| t.to_string());
let t = plain(&t);
if !t.is_empty() && !out.contains(&t) {
out.push(t);
}
if out.len() >= lines {
break;
}
}
out
}
/// Markdown marks off: **b**, `c`, [text](url) → text.
pub fn plain(s: &str) -> String {
let mut out = String::new();
let mut rest = s;
while let Some(i) = rest.find('[') {
out.push_str(&rest[..i]);
let after = &rest[i + 1..];
match (after.find("]("), after.find(')')) {
(Some(a), Some(b)) if a < b => {
out.push_str(&after[..a]);
rest = &after[b + 1..];
}
_ => {
out.push('[');
rest = after;
}
}
}
out.push_str(rest);
out.replace("**", "").replace('`', "").replace("__", "")
}
/// The id in a `page:12` link.
pub fn link_id(url: &str) -> Option<u64> {
url.strip_prefix("page:").or_else(|| url.strip_prefix("anybot://page/")).and_then(|s| s.trim_matches('/').parse().ok())
}
/// For the phone: the card in a chat, and the whole page.
pub fn card_json(p: &Page, now: i64) -> Value {
json!({"id": p.id, "title": p.title, "preview": preview(p, 4), "revision": p.revision, "updated": ago(p.updated, now), "note": p.note})
}
pub fn page_json(p: &Page, bot_name: &str, now: i64) -> Value {
json!({"id": p.id, "title": p.title, "summary": p.summary, "body": p.body, "revision": p.revision, "note": p.note, "kind": p.kind, "kpis": p.kpis, "verdict": p.verdict,
"updated": when(p.updated), "updated_ago": ago(p.updated, now), "created": when(p.created), "bot": bot_name,
"versions": p.history.iter().rev().map(|v| json!({"revision": v.revision, "at": when(v.at), "note": v.note})).collect::<Vec<_>>()})
}
/// One older version as a whole page (for 「看上一版」).
pub fn version_of(p: &Page, revision: u32) -> Option<Page> {
p.history.iter().find(|v| v.revision == revision).map(|v| Page { id: p.id, bot: p.bot, title: v.title.clone(), summary: v.summary.clone(), body: v.body.clone(), created: p.created, updated: v.at, revision: v.revision, note: v.note.clone(), history: vec![], kind: p.kind.clone(), kpis: p.kpis.clone(), verdict: p.verdict.clone() })
}
/// The page's ```mermaid blocks, in order (the phone asks for them one by one as SVG).
pub fn mermaid_blocks(body: &str) -> Vec<String> {
let mut out = vec![];
let mut cur: Option<String> = None;
for l in body.lines() {
let t = l.trim_start();
match &mut cur {
None if t.starts_with("```mermaid") => cur = Some(String::new()),
Some(s) if t.starts_with("```") => {
out.push(std::mem::take(s));
cur = None;
}
Some(s) => {
s.push_str(l);
s.push('\n');
}
None => {}
}
}
out
}
/// The pages written in one reply (its write_page calls), each once, in order.
pub fn ids_in(calls: &[crate::model::ToolCall]) -> Vec<u64> {
let mut out = vec![];
for c in calls.iter().filter(|c| saved(c)) {
if let Some(id) = written_id(c) {
if !out.contains(&id) {
out.push(id);
}
}
}
out
}
/// A write_page call that saved its page. A refused try (another bot's page) or one sent back by
/// the 寫法檢查 changed nothing — its card showed someone else's page, or the page as a later
/// try left it.
fn saved(c: &crate::model::ToolCall) -> bool {
c.name == "write_page" && c.status == crate::model::ToolStatus::Done
}
/// The page a write_page call names (the app writes the id in once it has saved a new page).
fn written_id(c: &crate::model::ToolCall) -> Option<u64> {
serde_json::from_str::<Value>(&c.args).ok().and_then(|v| v["id"].as_u64())
}
/// For each message, the pages whose card shows under it: each page a reply saved, once, under the
/// step that saved it last (a reply that wrote its page three times — sent back, fixed, updated —
/// showed three cards of the same 第 3 版). A reply runs from one message of yours to the next.
pub fn cards_by_message(messages: &[crate::model::Message]) -> Vec<Vec<u64>> {
let mut out = vec![vec![]; messages.len()];
let mut shown: Vec<u64> = vec![];
for (i, m) in messages.iter().enumerate().rev() {
if m.role == crate::model::Role::User {
shown.clear();
continue;
}
for id in ids_in(&m.tool_calls).into_iter().rev() {
if !shown.contains(&id) {
shown.push(id);
out[i].insert(0, id);
}
}
}
out
}
/// ```stats lines: 標籤 | 數值 | 說明
pub fn stats(src: &str) -> Vec<(String, String, String)> {
src.lines()
.filter_map(|l| {
let c: Vec<&str> = l.split('|').map(str::trim).collect();
(c.len() >= 2 && !c[0].is_empty()).then(|| (plain(c[0]), plain(c[1]), c.get(2).map(|s| plain(s)).unwrap_or_default()))
})
.collect()
}
/// 寫法檢查 (Anthropic's way of writing a report: the conclusion first, short sentences, one
/// emphasis at most, numbers in tiles or tables, nothing decorative). What a page breaks, each
/// as a fix the bot can make; empty when the page reads well. Fenced blocks (code, ```stats,
/// ```details …) aren't checked — they are where long or dense things belong.
pub fn review(body: &str) -> Vec<String> {
let mut out: Vec<String> = vec![];
let mut push = |s: String| {
if !out.contains(&s) {
out.push(s);
}
};
let short = |s: &str| {
let t: String = s.chars().filter(|c| *c != '*').take(14).collect();
if s.chars().count() > 14 { format!("{t}…") } else { t }
};
let mut fenced = false;
let mut section = String::from("開頭");
let mut bolds = 0usize;
let mut para = String::new();
let mut prose_chars = 0usize;
let mut has_details = false;
let flush_para = |para: &mut String, push: &mut dyn FnMut(String)| {
let n = para.chars().filter(|c| *c != '*').count();
if n > 120 {
push(format!("「{}」這段 {n} 字:先寫一句結論,其餘拆成清單,或放進 ```details", short(para)));
}
para.clear();
};
let flush_section = |section: &str, bolds: usize, push: &mut dyn FnMut(String)| {
if bolds > 1 {
push(format!("「{section}」這節有 {bolds} 處粗體:最多留一處,或都不用"));
}
};
for raw in body.lines() {
let line = raw.trim();
if line.starts_with("```") {
if !fenced && line.trim_start_matches('`').trim_start().starts_with("details") {
has_details = true;
}
fenced = !fenced;
flush_para(&mut para, &mut push);
continue;
}
if fenced {
continue;
}
if line.is_empty() {
flush_para(&mut para, &mut push);
continue;
}
if let Some(h) = line.strip_prefix('#') {
flush_para(&mut para, &mut push);
flush_section(&section, bolds, &mut push);
let h = h.trim_start_matches('#').trim();
section = h.chars().filter(|c| *c != '*').collect();
bolds = 0;
let numbered = ["一、", "二、", "三、", "四、", "五、", "六、", "七、", "八、", "九、", "十、", "第一", "第二", "第三", "(1)", "(1)"].iter().any(|k| h.starts_with(k))
|| h.split_once(['.', '、', ')', ')']).is_some_and(|(n, _)| !n.is_empty() && n.chars().all(|c| c.is_ascii_digit()));
if numbered {
push(format!("標題「{}」不用編號(一、二、1. …):標題本身就是分段", short(h)));
}
continue;
}
if line.chars().all(|c| matches!(c, '-' | '*' | '_' | ' ')) && line.chars().filter(|c| !c.is_whitespace()).count() >= 3 {
push("不用分隔線(---):用標題分段就好".into());
continue;
}
bolds += line.matches("**").count() / 2;
if line.starts_with('|') {
// A command in a table cell: `…` with a space inside.
let mut parts = line.split('`');
parts.next();
if parts.step_by(2).any(|code| code.trim().contains(' ')) {
push("表格裡放了指令:待辦用 ```steps 寫成清單,指令放程式碼區塊(或 ```details)".into());
}
continue;
}
if line.starts_with('→') || line.starts_with("->") || line.starts_with("=>") {
push("結論不用「→」帶出來:寫在那一節的第一句".into());
}
// (1, 2, 3)-style runs of numbers inside parentheses.
for open in ['(', '('] {
for seg in line.split(open).skip(1) {
let inner = seg.split([')', ')']).next().unwrap_or("");
let numbers = inner.split(|c: char| !(c.is_ascii_digit() || c == '.' || c == ',')).filter(|w| w.chars().any(|c| c.is_ascii_digit())).count();
if numbers >= 3 {
push(format!("「({})」括號裡一串數字:放進 ```stats 數字卡或表格", short(inner)));
}
}
}
let is_list = line.starts_with("- ") || line.starts_with("* ") || line.starts_with('>') || line.split_once(". ").is_some_and(|(n, _)| !n.is_empty() && n.chars().all(|c| c.is_ascii_digit()));
prose_chars += line.chars().count();
if !is_list {
if !para.is_empty() {
para.push(' ');
}
para.push_str(line);
} else {
flush_para(&mut para, &mut push);
}
}
flush_para(&mut para, &mut push);
flush_section(&section, bolds, &mut push);
if prose_chars > 1800 && !has_details {
push(format!("全頁正文 {prose_chars} 字:第一屏只留結論、數字和下一步,細節放進 ```details"));
}
out
}
/// A stats value's or note's direction: `Some(true)` up (↑, +), `Some(false)` down (↓, −, and
/// the plain "-" bots usually type), `None` neither. A sign counts only when something follows
/// it right away — a lone "-" is "no data", not a drop. (mobile/index.html `trend` is the same rule.)
pub fn stat_trend(s: &str) -> Option<bool> {
let mut it = s.trim_start().chars();
let first = it.next()?;
let signed = it.next().is_some_and(|c| !c.is_whitespace());
match first {
'↑' => Some(true),
'↓' => Some(false),
'+' if signed => Some(true),
'−' | '-' if signed => Some(false),
_ => None,
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Step {
Done,
Now,
Todo,
}
/// ```steps lines: [x] 名稱 | 說明 ([>] = now, [ ] = to do)
pub fn steps(src: &str) -> Vec<(Step, String, String)> {
src.lines()
.filter_map(|l| {
let t = l.trim().trim_start_matches(['-', '*']).trim();
let (st, rest) = if let Some(r) = t.strip_prefix("[x]").or_else(|| t.strip_prefix("[X]")).or_else(|| t.strip_prefix("[✓]")) {
(Step::Done, r)
} else if let Some(r) = t.strip_prefix("[>]").or_else(|| t.strip_prefix("[~]")).or_else(|| t.strip_prefix("[-]")) {
(Step::Now, r)
} else {
let r = t.strip_prefix("[ ]")?;
(Step::Todo, r)
};
let mut c = rest.splitn(2, '|');
let name = plain(c.next().unwrap_or("").trim());
(!name.is_empty()).then(|| (st, name, plain(c.next().unwrap_or("").trim())))
})
.collect()
}
/// ```chart: a native chart in the chat and on pages (bar / line / pie). Drawn by egui itself
/// — no raster image, so it is Retina-sharp, hoverable, and its text can never break layout
/// the way a Mermaid → resvg picture does when fonts measure widths differently.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum ChartKind {
Bar,
Line,
Pie,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Chart {
pub kind: ChartKind,
pub title: String,
pub labels: Vec<String>,
/// (series name, one value per label). One series with no name for the plain form.
pub series: Vec<(String, Vec<f64>)>,
}
/// A number with spaces, thousands commas, % and trailing units (元/個/次/人) stripped.
fn num(s: &str) -> Option<f64> {
let t: String = s.trim().chars().filter(|c| !c.is_ascii_whitespace() && *c != ',').collect();
let t = t.trim_end_matches(['%', '元', '個', '次', '人', '台']);
t.parse::<f64>().ok().filter(|v| v.is_finite())
}
/// ```chart
/// bar 月度下載 ← optional first line: bar | line | pie, then a title
/// 1月 | 120 ← plain form: 標籤 | 數值
/// 2月 | 320
/// ```
/// Multi-series: a header line `| 1月 | 2月 | 3月` (first cell empty), then `名稱 | 120 | 320 | 240`.
pub fn chart(src: &str) -> Option<Chart> {
let mut kind = ChartKind::Bar;
let mut title = String::new();
let mut labels: Vec<String> = vec![];
let mut series: Vec<(String, Vec<f64>)> = vec![];
for line in src.lines().map(str::trim).filter(|l| !l.is_empty() && !l.starts_with("#")) {
// The first line, before any data, is [kind] [title].
if title.is_empty() && labels.is_empty() && series.is_empty() && !line.contains('|') {
let (k, t) = line.split_once(char::is_whitespace).unwrap_or((line, ""));
match k.to_ascii_lowercase().as_str() {
"bar" | "long" | "長條" => kind = ChartKind::Bar,
"line" | "折線" => kind = ChartKind::Line,
"pie" | "圓餅" => kind = ChartKind::Pie,
_ => {
title = line.to_string();
continue;
}
}
title = t.trim().to_string();
continue;
}
// (A closing "|", as Markdown tables are often typed, is not one more empty column.)
let cells: Vec<String> = line.trim_end_matches('|').split('|').map(|c| plain(c.trim())).collect();
if cells[0].is_empty() && labels.is_empty() {
labels = cells[1..].to_vec();
continue;
}
let vals: Vec<Option<f64>> = cells[1..].iter().map(|c| num(c)).collect();
if vals.iter().any(|v| v.is_some()) && !cells[0].is_empty() {
series.push((cells[0].clone(), vals.iter().filter_map(|v| *v).collect()));
}
}
// The plain 標籤 | 數值 form: each row became a mini-series — fold them into one series.
if labels.is_empty() && !series.is_empty() && series.iter().all(|(_, v)| v.len() == 1) && kind != ChartKind::Pie {
labels = series.iter().map(|(s, _)| s.clone()).collect();
series = vec![(String::new(), series.iter().map(|(_, v)| v[0]).collect())];
}
// A pie of one plain row: its one slice is named after that row (not 「1」).
if kind == ChartKind::Pie && labels.is_empty() && series.len() == 1 && series[0].1.len() == 1 {
labels = vec![series[0].0.clone()];
}
let n = labels.len().max(series.iter().map(|(_, v)| v.len()).max().unwrap_or(0));
if series.is_empty() || n == 0 {
return None;
}
labels.resize(n, String::new());
for (i, l) in labels.iter_mut().enumerate() {
if l.is_empty() {
*l = (i + 1).to_string();
}
}
for (_, v) in series.iter_mut() {
v.resize(n, 0.0);
}
series.retain(|(_, v)| v.iter().any(|x| *x != 0.0));
(!series.is_empty()).then_some(Chart { kind, title, labels, series })
}
/// Whether the value axis starts at 0. Bars always (their length is the value); a line only when
/// 0 is within reach of its data — a reading of 1,649–1,796 W drawn from 0 was a flat line pressed
/// against the top. Within reach: the smallest value is 0 or less, or no bigger than the data's
/// own spread. (mobile/index.html chartFromZero says the same.)
pub fn chart_from_zero(c: &Chart) -> bool {
if c.kind != ChartKind::Line {
return true;
}
let all = c.series.iter().flat_map(|(_, v)| v.iter().copied()).filter(|v| v.is_finite());
let (lo, hi) = all.fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), v| (lo.min(v), hi.max(v)));
!lo.is_finite() || lo <= 0.0 || lo <= hi - lo
}
/// A number for an axis, a tooltip, a legend: no trailing .0, at most 2 decimals.
pub fn chart_num(v: f64) -> String {
if v == v.round() && v.abs() < 1e15 {
format!("{v:.0}")
} else {
format!("{v:.2}").trim_end_matches('0').trim_end_matches('.').to_string()
}
}
/// `> [!WARNING] text` → ("warning", text).
pub fn callout(first_line: &str) -> Option<(&'static str, String)> {
let t = first_line.trim();
let rest = t.strip_prefix("[!")?;
let end = rest.find(']')?;
let kind = match rest[..end].to_ascii_uppercase().as_str() {
"NOTE" | "INFO" => "note",
"TIP" => "tip",
"WARNING" | "CAUTION" => "warning",
"IMPORTANT" => "important",
_ => return None,
};
Some((kind, rest[end + 1..].trim().to_string()))
}
/// A sample tracking page (screenshots, and the look the bots are asked for).
pub fn demo(now: i64) -> (Vec<Page>, u64, u64) {
let body = "## 現況\n台灣 FSD **現在還不能用**:交通部把它當 L2 輔助駕駛,走「新技術駕駛系統審查」,不用修法;目前卡在第 1 步,路測計畫還沒核准。\n\n```stats\n目前階段 | 第 1 步 | 道路測試計畫審查\n預計開放 | 2027 Q2 | 媒體推估,官方未公布\n月費 | 未公布 | 網路數字是美國價換算\n你的車 | HW4 | 柏林廠,硬體不卡\n```\n\n## 審查進度\n```steps\n[x] 專家審查會議 | 7 月、9 月各開一次\n[>] 道路測試計畫審查 | 特斯拉依會議結論補件中\n[ ] 道路測試 | 計畫核定後才開始\n[ ] 正式開放\n```\n\n> [!WARNING] 你 12 月交車時多半還不能用,現在先別花錢。等正式開放後先訂閱一個月最划算。\n\n## 時間線\n| 日期 | 消息 | 來源 |\n|---|---|---|\n| 11/4 | 交通部:希望年底前完成相關審查,但不保證年底開放 | NOWnews |\n| 10/2 | 特斯拉:7–9 月完成第一輪技術審查,提出修改後的路測計畫 | 特斯拉 |\n| 6/30 | FSD 買斷停賣 | 特斯拉官網 |\n\n```mermaid\npie title 媒體預估開放時間\n \"2026 年底\" : 1\n \"2027 上半年\" : 3\n \"2027 下半年\" : 4\n```\n\n## 各月討論熱度\n```chart\nline 新聞提及(篇)\n| 7月 | 8月 | 9月 | 10月 | 11月\n媒體報導 | 12 | 9 | 21 | 18 | 34\n官方聲明 | 2 | 1 | 3 | 2 | 5\n```\n\n```chart\npie 車主意向\n想訂閱 | 520\n觀望 | 300\n不買 | 180\n```\n\n## 來源\n- [NOWnews 專訪交通部監理司](https://www.nownews.com)(11/4)\n- [車安中心 新技術駕駛系統審查流程](https://www.vscc.org.tw)\n";
let mut pages = vec![];
let mut next = 1;
let first = body.replace("交通部:希望年底前完成相關審查,但不保證年底開放", "(還沒有新消息)");
let _ = write(&mut pages, &mut next, 1, &json!({"title": "台灣 Tesla FSD 追蹤", "content": first, "summary": "還不能用:審查第一步,路測計畫未核准"}), now - 86_400_000);
let id = write(&mut pages, &mut next, 1, &json!({"title": "台灣 Tesla FSD 追蹤", "content": body, "note": "交通部 11/4 的新說法:希望年底前完成審查"}), now - 3_600_000).map(|w| w.id).unwrap_or(1);
(pages, next, id)
}
#[cfg(test)]
mod tests {
use super::*;
/// 寫法檢查:使用者那頁「改善計畫」的毛病一個一個抓得到;照規矩寫的頁面一個都不報。
#[test]
fn review_points_at_what_makes_a_page_hard_to_read() {
let messy = "## 一、證據(2026-11-14 實查)\n332 個操作裡有 **156 個是寫入/破壞性**(POST 83、PUT 28、DELETE 28、PATCH 17)。現在全在一組 **admin 帳密**後面。\n\n→ 這是測試場,不是生產場。\n\n---\n\n## 二、今天就收\n| # | 動作 |\n|---|---|\n| 1 | `cd ~/Documents/AnyMetal && git init` |\n";
let found = review(messy);
let has = |k: &str| found.iter().any(|f| f.contains(k));
assert!(has("編號"), "{found:?}");
assert!(has("粗體"), "{found:?}");
assert!(has("一串數字"), "{found:?}");
assert!(has("→"), "{found:?}");
assert!(has("分隔線"), "{found:?}");
assert!(has("指令"), "{found:?}");
let long = format!("## 現況\n{}", "交通部把它當輔助駕駛,走新技術駕駛系統審查,不用修法。".repeat(6));
assert!(review(&long).iter().any(|f| f.contains("字")), "a long paragraph");
let clean = "## 240 環境是測試場\n護欄要有能放大規模的目標才測得出來。\n\n```stats\n機器 | 375 台 | 362 台狀態不明\n韌體符合 | 33.6% | 110 台裡 73 台不合格\n```\n\n## 今天收尾\n```steps\n[ ] AnyMetal 加上版本控制\n[ ] facade 那 5 個檔案:提交或還原\n```\n\n```details 指令\n```\n\n| 檔案 | 狀態 |\n|---|---|\n| facade | 未提交 |\n";
assert!(review(clean).is_empty(), "{:?}", review(clean));
// Inside a fence (code, a details block) nothing is checked.
assert!(review("```\n→ (1, 2, 3) **a** **b**\n---\n```").is_empty());
}
/// 數字卡的漲跌(桌面和手機同一套規則):箭頭、+、全形 −,還有 Bot 最常寫的一般「-」。
/// 單獨一個符號(「-」當作「沒有資料」)不算漲跌。
#[test]
fn stat_trend_reads_arrows_and_both_minus_signs() {
assert_eq!(stat_trend("↑ 12%"), Some(true));
assert_eq!(stat_trend("+12%"), Some(true));
assert_eq!(stat_trend("↓ 3"), Some(false));
assert_eq!(stat_trend("−5%"), Some(false));
assert_eq!(stat_trend("-12%"), Some(false));
assert_eq!(stat_trend("-"), None);
assert_eq!(stat_trend("+"), None);
assert_eq!(stat_trend("- 待補"), None);
assert_eq!(stat_trend("—"), None);
assert_eq!(stat_trend("2027 Q2"), None);
assert_eq!(stat_trend(""), None);
}
#[test]
fn chart_parses_plain_multi_series_and_pie() {
let c = chart("bar 月度下載\n1月 | 120\n2月 | 320\n3月 | 240").unwrap();
assert_eq!(c.kind, ChartKind::Bar);
assert_eq!(c.title, "月度下載");
assert_eq!(c.labels, vec!["1月", "2月", "3月"]);
assert_eq!(c.series, vec![(String::new(), vec![120.0, 320.0, 240.0])]);
let c = chart("line\n| 1月 | 2月\n下載 | 120 | 320\n上傳 | 90,100 | 140").unwrap();
assert_eq!(c.kind, ChartKind::Line);
assert_eq!(c.series[1], ("上傳".into(), vec![90100.0, 140.0]));
let c = chart("pie 媒體預估開放時間\n\"2026 年底\" : 1").is_none(); // ':' is not a separator
assert!(c);
let c = chart("pie\n2026 年底 | 1\n2027 上半年 | 3").unwrap();
assert_eq!(c.kind, ChartKind::Pie);
assert_eq!(c.series.len(), 2, "pie keeps one slice per row");
assert!(chart("bar 只有標題").is_none());
assert!(chart("").is_none());
assert_eq!(chart_num(2.5), "2.5");
}
/// Markdown 表格習慣在列尾多打一個「|」:不會多出一欄空的「3」。只有一行的圓餅,那一片叫
/// 那一行的名字,不是「1」。(手機的 chartParse 同樣這麼讀。)
#[test]
fn a_line_far_from_zero_fits_its_data_and_bars_start_at_zero() {
let watts = chart("line 用電\n| 0時 | 1時 | 2時\n用電 | 1699 | 1651 | 1796").unwrap();
assert!(!chart_from_zero(&watts), "1,651–1,796 spread 145: drawn from 0 it is a flat line");
let news = chart("line\n| 7月 | 8月 | 9月\n媒體 | 12 | 1 | 34").unwrap();
assert!(chart_from_zero(&news), "1–34: 0 is within reach");
let below = chart("line\n| a | b\n溫度 | -3 | 8").unwrap();
assert!(chart_from_zero(&below));
let bars = chart("bar\n客廳 | 1699\n廚房 | 1796").unwrap();
assert!(chart_from_zero(&bars), "a bar's length is its value");
}
/// 一個回覆裡:想改別的 Bot 的頁面被擋、寫法檢查退回一次、再存兩次——只出一張卡,在最後
/// 存的那一步下面;被擋的那頁不出卡。下一個回覆又寫同一頁,就再出一張。
#[test]
fn a_reply_shows_each_saved_page_once_under_its_last_save() {
use crate::model::{Message, ToolCall, ToolStatus};
let call = |id: &str, page: u64, st: ToolStatus| ToolCall { id: id.into(), name: "write_page".into(), args: json!({"id": page, "title": "SCC 機房狀態報告"}).to_string(), status: st };
let step = |calls: Vec<ToolCall>| {
let mut m = Message::assistant("", "");
m.tool_calls = calls;
m
};
let msgs = vec![
Message::user("做成報告"),
step(vec![call("a", 3, ToolStatus::Failed)]),
step(vec![call("b", 7, ToolStatus::Failed)]),
step(vec![call("c", 7, ToolStatus::Done)]),
step(vec![call("d", 7, ToolStatus::Done)]),
Message::assistant("資料齊了,我做成一份報告頁面。", ""),
Message::user("再補一點"),
step(vec![call("e", 7, ToolStatus::Done)]),
];
let cards = cards_by_message(&msgs);
assert_eq!(cards, vec![vec![], vec![], vec![], vec![], vec![7], vec![], vec![], vec![7]]);
}
#[test]
fn chart_ignores_a_closing_pipe_and_names_a_lone_pie_slice() {
let c = chart("bar\n| 1月 | 2月 |\n下載 | 120 | 320 |\n上傳 | 90 | 140 |").unwrap();
assert_eq!(c.labels, vec!["1月", "2月"]);
assert_eq!(c.series[0], ("下載".into(), vec![120.0, 320.0]));
let c = chart("bar 月度\n1月 | 120 |\n2月 | 320 |").unwrap();
assert_eq!(c.labels, vec!["1月", "2月"]);
assert_eq!(c.series, vec![(String::new(), vec![120.0, 320.0])]);
let c = chart("pie 車主意向\n想訂閱 | 520").unwrap();
assert_eq!(c.labels, vec!["想訂閱"]);
assert_eq!(c.series.len(), 1);
}
#[test]
fn a_colleagues_page_is_listed_and_read_but_stays_its() {
let mut pages = vec![];
let mut next = 1;
write(&mut pages, &mut next, 2, &json!({"title": "FSD 追蹤", "content": "審查中"}), 10).unwrap();
write(&mut pages, &mut next, 1, &json!({"title": "我的筆記", "content": "a"}), 20).unwrap();
let name = |id: u64| format!("Bot{id}");
let l = list(&pages, 1, name);
assert!(l.starts_with("你的頁面:\n#2 「我的筆記」") && l.contains("其他 Bot 的頁面") && l.contains("「FSD 追蹤」") && l.contains("(Bot2)"), "{l}");
assert!(read(&pages, 1, &json!({"id": 1}), name).unwrap().contains("「Bot2」的頁面"));
assert!(!read(&pages, 1, &json!({"id": 2}), name).unwrap().contains("只能讀"), "its own");
assert_eq!(owner_of(&pages, 1, Some(1)), Some(2));
assert_eq!(owner_of(&pages, 1, Some(2)), None);
assert!(read(&pages, 1, &json!({"id": 99}), name).is_err());
}
#[test]
fn write_makes_then_updates_and_keeps_versions() {
let mut pages = vec![];
let mut next = 1;
let w = write(&mut pages, &mut next, 7, &json!({"title": "台灣 Tesla FSD 追蹤", "content": "# 現況\n還在審查", "summary": "審查第一步"}), 1000).unwrap();
assert_eq!(w.id, 1);
assert!(w.text.contains("page:1"));
// Same title, no id: the same page.
let w2 = write(&mut pages, &mut next, 7, &json!({"title": "台灣 Tesla FSD 追蹤", "content": "# 現況\n交通部有新說法", "note": "交通部新說法"}), 2000).unwrap();
assert_eq!(w2.id, 1);
assert_eq!(pages.len(), 1);
assert_eq!(pages[0].revision, 2);
assert_eq!(pages[0].summary, "審查第一步", "kept when not given");
assert_eq!(pages[0].history.len(), 1);
assert_eq!(pages[0].history[0].body, "# 現況\n還在審查");
// Nothing changed: no new version.
let w3 = write(&mut pages, &mut next, 7, &json!({"id": 1, "title": "台灣 Tesla FSD 追蹤", "content": "# 現況\n交通部有新說法"}), 3000).unwrap();
assert!(w3.text.contains("沒有變化"));
assert_eq!(pages[0].revision, 2);
// Another bot can't change it; an unknown id is an error.
assert!(write(&mut pages, &mut next, 8, &json!({"id": 1, "title": "x", "content": "y"}), 4000).is_err());
assert!(write(&mut pages, &mut next, 7, &json!({"id": 99, "title": "x", "content": "y"}), 4000).is_err());
for i in 0..15 {
write(&mut pages, &mut next, 7, &json!({"id": 1, "title": "台灣 Tesla FSD 追蹤", "content": format!("v{i}")}), 5000 + i).unwrap();
}
assert_eq!(pages[0].history.len(), KEEP_VERSIONS);
assert!(version_of(&pages[0], pages[0].revision - 1).is_some());
}
#[test]
fn preview_and_blocks() {
let p = Page { title: "t".into(), summary: "還不能用".into(), body: "# 現況\n\n```stats\n狀態 | 審查中\n```\n交通部說**年底前**完成審查,見 [來源](https://x.com)。\n\n| a | b |\n|---|---|\n".into(), ..Default::default() };
assert_eq!(preview(&p, 3), vec!["還不能用", "交通部說年底前完成審查,見 來源。"]);
assert_eq!(stats("狀態 | 審查中 | 第 1 步\n預計 | 2027"), vec![("狀態".into(), "審查中".into(), "第 1 步".into()), ("預計".into(), "2027".into(), String::new())]);
let s = steps("[x] 審查 | 開過兩次會\n[>] 路測\n[ ] 開放\n不是步驟");
assert_eq!(s.len(), 3);
assert_eq!((s[0].0, s[1].0, s[2].0), (Step::Done, Step::Now, Step::Todo));
assert_eq!(s[0].2, "開過兩次會");
assert_eq!(callout("[!WARNING] 先別花錢"), Some(("warning", "先別花錢".into())));
assert_eq!(link_id("page:12"), Some(12));
assert_eq!(link_id("https://x"), None);
}
}