AnyBot/src/pages.rs

634 lines
33 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多系列:首行 `| 1月 | 2月`(第一格留空),每列 `名稱 | 120 | 320`。圖表用原生繪製(可縮放、hover 看數值,下方自動附數據表),優於 ```mermaid 的圖片。\n> [!NOTE] / [!TIP] / [!WARNING] / [!IMPORTANT] call-outs.\n\n寫法(讀者是先掃一眼、要深才細讀的人,不是讀報告的人):\n• 選 kind(data 數據分析 / compare 比較評測 / decision 決策備忘 / howto 教學步驟 / timeline 時間線 / prose 純敘述 / notes 筆記),第一屏跟著它:data → 一句結論+kpis 三個真數字+主圖表;compare → 一句取捨+verdict+對比表;decision → 結論先行(verdict)+三條證據+風險;howto → 適合誰/成品+步驟(steps);timeline → 時間軸(mermaid timeline);prose/notes → 直接內文,不準硬湊 KPI 卡。\n• kpis 只放真資料算得出的數字(附 delta,如 +12%);湊不出三個就少放或不放。verdict 只在有明確結論時寫。\n• 每段不超過 4 行;連續段落不超過 3 段,中間改用列表/表格/圖。\n• 有數字就出 ```chart,圖標題直接寫結論並帶數字(如「Q3 營收創新高 42 萬」),軸標籤帶單位;細節數字放表格。\n• 每節先一句結論再給證據;來源放最後,帶連結與日期。更新時把整頁維持成現況(不是日誌),並在 `note` 寫出改了什麼。",
"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| c.name == "write_page") {
if let Some(id) = serde_json::from_str::<Value>(&c.args).ok().and_then(|v| v["id"].as_u64()) {
if !out.contains(&id) {
out.push(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()
}
#[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;
}
let cells: Vec<String> = line.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())];
}
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 })
}
/// 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- [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 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");
}
#[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);
}
}