個人資料與用量(計畫 C4、C5,照 OpenBot 的排版):設定多一頁「個人資料」(左下角選單也有「個人資料與用量…」)。名字和「過去一年有 N 個活躍日」;五張卡——Token(過去一年,不算快取命中)、最活躍的一天、訊息、目前連續天數(今天還沒用不算斷)、最長連續天數;「活動」一年的熱度格子(53 週,越忙越深,滑過看日期、token、訊息數);「用量」7/30/90 天/一年:token(新讀、寫、快取讀到)、呼叫次數、花費(只算模型服務回報的,沒回報寫「未定價」,不是 0 元)、每天一條、依模型、依 Bot。

全部從已經有的紀錄算(stats.rs:usage/YYYY-MM.jsonl 和每則訊息的時間,usage::since_any 讀一年),用大腦的時區切日子,打開時在背景算、一分鐘內不重算。螢幕電腦向大腦要(api/sync/stats),手機的路是 api/stats(擁有者才有,手機頁面還沒做)。卡片做成 kit.rs 的 stat_card(設計檢查不准散落的手工卡片)。功能地圖 settings.md(settings-me、驗證步驟)、FEATURES.md、計畫 C4/C5 狀態、版面檢查加「設定 › 個人資料」。

已驗證: cargo test 全綠(831),新測試 stats::a_year_in_figures(不算快取命中、最忙的一天、訊息、今天還沒用不斷、最長、台北時區 23:30 還算那天、熱度四級、7 天的依模型依 Bot、檢查算在它的 Bot、刪掉的 Bot、花費和未定價)、counts_and_costs_are_said_plainly、me_ui 的日期;layout_audit 過(第一版卡片的邊框讓頁面寬了 4 px,被它抓到);clippy 錯誤數跟之前一樣(12);桌面截圖(scratch 寫進一年假的用量紀錄):五張卡、熱度格子、用量的 30 天、每日條、依模型、依 Bot;verify-anybot:api/stats 回 371 天、四個期間,沒登入 401。
未驗證: 螢幕電腦向大腦要(要兩台);真的一年資料的大腦算多久(Jenny 那台 3.5 萬則舊訊息)。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uirha2uBHmbnuWBhNzjbJm
This commit is contained in:
王性驊 2026-11-21 13:54:31 +08:00
parent 261a7fd260
commit f42891de7f
13 changed files with 668 additions and 4 deletions

View File

@ -1565,6 +1565,14 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開)
- 指令輸出、連接器的回答太長時,給模型的只留開頭和結尾各 6000 字,中間寫「…(中間省略 N 個字;完整內容用 read_result 讀:id=r…)…」;完整的存在資料夾的 `outputs/`(一份最多 20 MB、留 7 天,同樣的內容同一個 id)。較早的結果為了騰出空間被收起時也一樣寫 id。
- 每個 Bot 都有 `read_result`(id、從第幾個字、一次最多兩萬字),只是看,計畫模式也能用。以前叫 Bot「再做一次這一步」看完整的:會改東西的步驟重做很危險,答案也可能不一樣,長紀錄的中間就這樣不見了。
### 個人資料與用量(設定 › 個人資料)
- 設定多一頁「個人資料」(一般的下一頁;左下角選單也有「個人資料與用量…」)。最上面名字和「過去一年有 N 個活躍日」。
- 五張卡:**Token**(過去一年,不算快取命中:模型新讀的、寫進快取的和寫出來的)、**最活躍的一天**(token 最多那天和日期)、**訊息**(你和 Bot 寫的,不算步驟和 AnyBot 自己的提示行)、**目前連續天數**(今天還沒用不算斷,寫「自 11月22日 起」)、**最長連續天數**(起訖日期)。視窗夠寬三張一排,否則兩張。
- **活動**:一年的熱度格子(53 週,一週一欄、週日在上),依最忙那天分四級深淺,沒有用量只有訊息的那天照訊息算;滑過看「2026年11月20日:3,610 token、12 則訊息」。
- **用量**:7 天/30 天/90 天/一年。token(新讀、寫、快取讀到)、呼叫次數、花費——只算模型服務自己回報的(例如 OpenRouter),沒回報的寫「未定價」(部分有部分沒有:「US$0.97(另有 694 次呼叫未定價)」),不是 0 元;每天一條(滑過看數字)、依模型、依 Bot(前 8 名,發布前檢查、目標檢查各自一列,刪掉的 Bot 寫「Bot 9(已刪除)」)。
- 都從已經有的紀錄算(`usage/YYYY-MM.jsonl` 和每則訊息的時間),不另外存;用大腦的時區切日子;打開時在背景算,一分鐘內再看不重算。螢幕電腦向大腦要(`api/sync/stats`),手機用 `api/stats`(擁有者才有)。
### Bot 在哪一台(左下角)
- 左下角你的名字下面多一行:Bot 在哪一台——「這台電腦」,或「大腦「雲端大腦」」(綠點連得到、灰點連不到)。不用打開設定就看得出現在看的是哪一台的 Bot。

View File

@ -11,6 +11,7 @@
- Bot:時區,例行任務和提醒用([routines](routines.md))。
- 帳戶:「登入」或「管理帳戶」打開「手機與帳號」頁;資料放在哪。
- `settings-whose` 左下角(你的名字):名字下面一行寫 Bot 在哪一台——「這台電腦」,或「大腦「名字」」(綠點連得到、灰點連不到)。點一下開「Bot 在哪一台」選單:「這台電腦(這台的名字)」、帳號裡每台可以當大腦的電腦(現在用的打勾,離線的灰、不能點),點一下就換——跟「手機與帳號」頁大腦那一欄的「改用它當大腦」「改回用這台自己的 Bot」一樣([account](account.md));沒登入帳號多一行「登入帳號,才能換到別台大腦…」;最下面「設定…」(⌘, 也可以)。
- `settings-me` 「個人資料」:名字、過去一年有幾個活躍日;五張卡——Token(過去一年,不算快取命中)、最活躍的一天、訊息、目前連續天數(今天還沒用不算斷)、最長連續天數;「活動」一年的熱度格子(一週一欄、越忙顏色越深,滑過看日期、token、訊息數);「用量」選 7 天/30 天/90 天/一年:token(新讀、寫、快取讀到)、呼叫次數、花費(模型服務回報的,沒回報寫「未定價」,不是 0 元)、每天一條、依模型、依 Bot。左下角選單也有「個人資料與用量…」。螢幕電腦上算的是大腦的(向大腦要);手機和螢幕的路是 `api/stats`、`api/sync/stats`(擁有者才有)。
- `settings-account` 「手機與帳號」頁(從 一般 › 帳戶 進去,[account](account.md)):「AnyBot 帳號」(登入、備份、還原)、大腦和「加一台電腦」([computers](computers.md))、「同一個網路直接連」、「手機可以做什麼」、「直接連線的裝置」、「分享給團隊」([team](team.md))、「帳號裡的電腦」。
- `settings-models` 「模型」:每家 AI 供應商的 API 金鑰、服務網址、新 Bot 預設模型、「測試連線並取得模型清單」([models](models.md));本機或區網的供應商多「看不到圖時,請雲端模型看截圖和附件」(預設關,[chat](chat.md))。「ChatGPT 方案」沒有金鑰和網址欄,改成「ChatGPT 帳號」:登入狀態、「使用 ChatGPT 繼續」「登出」「換帳號」「打開登入頁」「管理用量」;連到別台大腦時多一格貼回登入網址和「完成登入」。
- `settings-integrations` 「整合」,三個小分頁:
@ -46,11 +47,12 @@
- 基本前提和「手機已登入」(README),開著 Bot 1 的聊天:`$CTL phone click '.row[data-bot="1"]'`。
- **左下角:Bot 在哪一台**(covers `settings-whose`):前提:要開視窗。指令:`$CTL stop && ABV_ALLOW_WINDOW=1 $CTL desktop-shot whose ANYBOT_SHOT_VIEW=whose ANYBOT_SHOT_SIZE=1000x620 'ANYBOT_SHOT_CLICK=90,595@6' ANYBOT_SHOT_FRAMES=14`(示範資料:已登入、是「雲端大腦」的螢幕、jenny-Host 離線),再不帶 `ANYBOT_SHOT_VIEW` 跑一次(沒登入)。看到:左下角「daniel/● 大腦「雲端大腦」」;選單「Bot 在哪一台」下「這台電腦(…)」「✓ 雲端大腦」「jenny-Host(離線)」(灰),分隔線下「設定…」;沒登入時是「✓ 這台電腦(…)」「登入帳號,才能換到別台大腦…」「設定…」。真的切換要帳號裡有另一台大腦:走不到,和「手機與帳號」頁的按鈕是同一段(`mir.want`、`mir.leave`)。
- **個人資料與用量**(covers `settings-me`):指令:`$CTL api GET /api/stats --jq '{tokens_year, messages_year, streak_now, active_days, d: (.days|length), p: (.periods|keys)}'`;桌面要開視窗:`$CTL stop && ABV_ALLOW_WINDOW=1 $CTL desktop-shot me ANYBOT_SHOT_TAB=me ANYBOT_SHOT_SIZE=1000x900`。看到:API 有 371 天的 days、periods 7/30/90/365;畫面上五張卡、熱度格子、「用量」和那四個期間、依模型、依 Bot。scratch 的假模型不回報用量,token 是 0、花費「未定價」(真的數字靠 `cargo test stats::`)。
- **Bot 改三樣**(covers `settings-by-bot`、`settings-general`):請 Bot 換深色、只用黑色、時區紐約,再傳一句。指令:`$CTL phone send '改 [[call update_settings {"theme":"dark","accent":"black","timezone":"America/New_York"}]]' && $CTL phone wait-text '時區 → America/New_York' --in '#msgs' && $CTL phone send 幾點 && $CTL phone wait-text 'FAKE-MODEL 回答:幾點' --in '#msgs' && $CTL model 'select(.kind == "turn") | .user' && TZ=America/New_York date +%H:%M`。看到:不用卡片,「已更新:主題 → dark、聊天的顏色 → black、時區 → America/New_York」;Bot 收到的〔送出時間〕是紐約時間。
- **錯的時區**(covers `settings-by-bot`):指令:`$CTL phone send '錯 [[call update_settings {"timezone":"Mars/Base"}]]' && $CTL phone wait-text '不是有效的時區名稱' --in '#msgs' && $CTL state .timezone`。看到:「「Mars/Base」不是有效的時區名稱(例如 Asia/Taipei)」;還是 America/New_York。
- **手機的設定**(covers `settings-general`、`settings-account`、`settings-models`、`settings-integrations`、`settings-computers`、`settings-perms`、`settings-vault`、`settings-updates`):重新整理,帳戶選單 › 設定 › 一般。指令:`$CTL phone open --listed && $CTL phone click '#b-me' && $CTL phone click '#sheet-in .opt' --text 設定 && $CTL phone wait '[data-go="updates"]' && $CTL phone shot settings-tabs && $CTL phone click '[data-go="general"]' && $CTL phone wait-text America/New_York --in '#list' && $CTL phone wait-text 只用黑色 --in '#list' && $CTL phone shot settings-general`。看到:八列(沒有語音);一般裡主題「深色」、聊天的顏色「只用黑色」、時區、通知、這支手機的外觀。
- **桌面每個分頁、Bot 設定**(covers `settings-voice`、`settings-bot`、`settings-account`、`settings-computers`):每個分頁和 Bot 設定。指令:要開視窗——`$CTL stop && (for t in general remote providers channels computers review vault voice updates; do ABV_ALLOW_WINDOW=1 $CTL desktop-shot settings-$t ANYBOT_SHOT_TAB=$t || exit 1; done) && ABV_ALLOW_WINDOW=1 $CTL desktop-shot settings-bot ANYBOT_SHOT_VIEW=editor`。看到:各分頁的區塊照上面順序;Bot 設定最下面「儲存」。問候照時區(紐約晚上「晚上好」)也只在桌面。
- 自動測試:`cargo test featuremap::`(每個分頁和區塊標題、Bot 能改的設定都要在這份)、`cargo test appctl::`、`cargo test policy::`、`cargo test the_greeting_follows_the_timezone_setting`、`cargo test layout_audit::`(每個分頁、Bot 設定、例行任務、右側面板,用三種字型、最窄和一般的視窗、示範和很長的資料畫:字被切、疊在一起,或對話框被撐得比標題列寬就失敗)。
- 自動測試:`cargo test stats::`、`cargo test featuremap::`(每個分頁和區塊標題、Bot 能改的設定都要在這份)、`cargo test appctl::`、`cargo test policy::`、`cargo test the_greeting_follows_the_timezone_setting`、`cargo test layout_audit::`(每個分頁、Bot 設定、例行任務、右側面板,用三種字型、最窄和一般的視窗、示範和很長的資料畫:字被切、疊在一起,或對話框被撐得比標題列寬就失敗)。
## 陷阱

View File

@ -133,13 +133,13 @@
每列固定樣式:左邊標題+說明、右邊動作,至少 64 px 高;警告用整條橫幅+右邊按鈕;刪除類集中在最下面「危險區」,確認框預設停在「取消」。
這份登記表同時給 `featuremap::` 測試用(新增設定沒寫進地圖會被擋)。
**C4. 個人資料**:五個數字卡(過去一年的 token(不算快取命中)、最活躍的一天、訊息數、目前連續天數、最長連續天數),
**C4. 個人資料**(11/21 做了:設定 › 個人資料,五張卡、一年熱度格子;「分享」產生圖片還沒做):五個數字卡(過去一年的 token(不算快取命中)、最活躍的一天、訊息數、目前連續天數、最長連續天數),
(現況:完全沒有。現在的「個人檔案」是每個 Bot 的設定頁;使用者自己只在側邊欄左下角有名字縮寫;沒有統計、熱度圖、連續天數。)
今天還沒用不算斷;底下一年的熱度格子(53 週 × 7 天,依最忙那天的比例分 4 級,滑過顯示日期和 token),
再來是常用的供應商、模型、星期幾、估計花費、前 4 名 Bot;「分享」產生一張圖(過去半年+4 個數字),不產生連結。
全部從現有的每輪紀錄算,不另外存;用大腦的時區切日子。
**C5. 用量**:每一輪記四種 token(未快取輸入、快取輸入、寫入快取、輸出)+模型、供應商、Bot、時間,
**C5. 用量**(11/21 做了:同一頁的「用量」,期間、每日、依模型、依 Bot、花費只算回報的、未定價;照價目表估價、依技能分、手機頁面還沒做):每一輪記四種 token(未快取輸入、快取輸入、寫入快取、輸出)+模型、供應商、Bot、時間,
(現況:`src/usage.rs` 每次呼叫模型記一行到 `usage/YYYY-MM.jsonl`(輸入、輸出、快取讀寫、供應商回報的花費),但只能打 `/usage` 看一段文字(24 小時、7 天、前 8 名);沒有圖、沒有每日、沒有價目表估計,手機看不到。資料夠用,缺的是頁面和估價。)
花費記「供應商自己回報」或「照價目表估計」(`rate_basis`),不知道價錢的顯示「未定價」不是 $0;
用量頁可選 Bot/模型、花費或 token、7/30/90 天/一年,分頁看模型/Bot/日期/技能;註明是估計。

View File

@ -42,6 +42,7 @@ mod pages_ui;
mod voice_ui;
mod drops_ui;
mod tasks_ui;
mod me_ui;
mod memory_ui;
mod goal_ui;
mod context_ui;
@ -152,6 +153,7 @@ pub const SCREENSHOT_FRAMES: u32 = 120;
/// 模型 (its own AI keys) where the original has 用量與帳單, and 帳戶 opens from 一般.
enum SettingsTab {
General,
Me,
Providers,
Channels,
Computers,
@ -335,6 +337,7 @@ pub struct App {
drop_page: Option<drops_ui::DropPage>,
/// 任務: the list the brain works out, and its dialog.
tk: tasks_ui::TasksUi,
me: me_ui::MeUi,
drop_last: String,
nightly_checked: Option<Instant>,
/// Files and pictures waiting to go with the next message.
@ -600,6 +603,7 @@ impl App {
slash: Default::default(),
drop_page: None,
tk: Default::default(),
me: Default::default(),
drop_last: String::new(),
nightly_checked: None,
att: Default::default(),
@ -1333,6 +1337,7 @@ impl App {
let tab = match tab.as_str() {
"general" => Some(SettingsTab::General),
"providers" => Some(SettingsTab::Providers),
"me" => Some(SettingsTab::Me),
"channels" => Some(SettingsTab::Channels),
"computers" => Some(SettingsTab::Computers),
"review" => Some(SettingsTab::Review),
@ -5452,6 +5457,7 @@ impl App {
Some(match tab {
SettingsTab::General => (both, format!("外觀和帳戶是這台電腦的;時區、記憶、通知是{theirs}的,改了存在大腦")),
SettingsTab::Remote => (mine, "手機與帳號是這台電腦自己的".to_string()),
SettingsTab::Me => (theirs.clone(), format!("個人資料和用量算的是{theirs}上的 Bot 和它呼叫模型的紀錄")),
SettingsTab::Providers | SettingsTab::Channels | SettingsTab::Review | SettingsTab::Voice => (theirs, t("這一頁是大腦的設定:改了存在大腦,帳號裡每台看到的都一樣")),
SettingsTab::Computers => (both, format!("「在這台電腦上執行」「讓帳號裡的其他電腦使用這台」和訊息是這台電腦的;其餘是{theirs}的")),
SettingsTab::Updates => (both, format!("更新的是這台電腦的 AnyBot;Bot 的電腦在{theirs}上")),
@ -5829,7 +5835,7 @@ impl App {
ui.vertical(|ui| {
ui.spacing_mut().item_spacing.y = 2.0;
use crate::icons::Icon;
for (tab, name, icon) in [(SettingsTab::General, "一般", Icon::Gear), (SettingsTab::Providers, "模型", Icon::Sparkle), (SettingsTab::Channels, "整合", Icon::Chat), (SettingsTab::Computers, "電腦", Icon::Monitor), (SettingsTab::Review, "權限", Icon::Shield), (SettingsTab::Vault, "保險庫", Icon::Vault), (SettingsTab::Voice, "語音", Icon::Mic), (SettingsTab::Updates, "更新", Icon::CloudDownload)] {
for (tab, name, icon) in [(SettingsTab::General, "一般", Icon::Gear), (SettingsTab::Me, "個人資料", Icon::Person), (SettingsTab::Providers, "模型", Icon::Sparkle), (SettingsTab::Channels, "整合", Icon::Chat), (SettingsTab::Computers, "電腦", Icon::Monitor), (SettingsTab::Review, "權限", Icon::Shield), (SettingsTab::Vault, "保險庫", Icon::Vault), (SettingsTab::Voice, "語音", Icon::Mic), (SettingsTab::Updates, "更新", Icon::CloudDownload)] {
let (rect, r) = ui.allocate_exact_size(vec2(ui.available_width(), 38.0), egui::Sense::click());
let on = self.settings_tab == tab || (tab == SettingsTab::General && self.settings_tab == SettingsTab::Remote);
if on || r.hovered() {
@ -6139,6 +6145,9 @@ impl App {
SettingsTab::Vault => {
self.vault_page(ui);
}
SettingsTab::Me => {
self.me_page(ui);
}
SettingsTab::Computers => {
self.computers_page(ui);
}

View File

@ -191,6 +191,21 @@ pub(super) fn settings_side_line(ui: &mut egui::Ui, tag: &str, words: &str, p: P
ui.add_space(6.0);
}
/// A figure on its own card (個人資料): what it is, the number, a line under it — `w` wide.
pub(super) fn stat_card(ui: &mut egui::Ui, p: Palette, w: f32, label: &str, value: &str, sub: &str) {
Frame::new().fill(p.elevated).stroke(Stroke::new(1.0, p.border)).corner_radius(R_L).inner_margin(egui::Margin::symmetric(14, 12)).show(ui, |ui| {
// (The 14 px margins and the 1 px border on each side.)
ui.set_width(w - 30.0);
// (Stacked: a row of cards lays things side by side.)
ui.vertical(|ui| {
ui.spacing_mut().item_spacing.y = 4.0;
ui.label(RichText::new(label).size(FONT_SM).color(p.text2));
ui.label(RichText::new(value).size(FONT_H1).strong().family(crate::bold()).color(p.text));
ui.add(egui::Label::new(RichText::new(sub).size(FONT_XS).color(p.text3)).truncate());
});
});
}
/// A rounded group of related settings, like a macOS settings card.
pub(super) fn setting_card<R>(ui: &mut egui::Ui, p: Palette, body: impl FnOnce(&mut egui::Ui) -> R) -> R {
let r = Frame::new()

View File

@ -153,6 +153,7 @@ fn scenes() -> Vec<(&'static str, Open)> {
}),
),
("設定 › 模型", tab(SettingsTab::Providers)),
("設定 › 個人資料", tab(SettingsTab::Me)),
// A screen of a brain: each page says at its top whose settings it holds (the longest
// sentences are these two).
("設定 › 一般(螢幕電腦)", screen_of_brain(SettingsTab::General)),

295
src/app/me_ui.rs Normal file
View File

@ -0,0 +1,295 @@
// 設定 › 個人資料 (plan C4, C5): the year in figures — tokens, the busiest day, messages, the runs
// of days used — a heat map of the year, and 用量 by period, model and bot. Worked out on a thread
// from what is already kept (stats.rs); on a screen of a brain, asked of the brain (whose bots
// and usage these are). Read when the page opens and again after a minute.
use super::*;
use std::sync::mpsc::{channel, Receiver};
#[derive(Default)]
pub(super) struct MeUi {
data: Option<serde_json::Value>,
at: Option<Instant>,
rx: Option<Receiver<Result<serde_json::Value, String>>>,
error: Option<String>,
/// 用量's period: 7, 30, 90 or 365 days.
span: u16,
}
/// How long the figures stand before the page reads them again.
const FRESH_SECS: u64 = 60;
impl App {
/// Start working the figures out when there are none, or they are a minute old.
fn me_refresh(&mut self, ctx: &egui::Context) {
if let Some(rx) = &self.me.rx {
if let Ok(r) = rx.try_recv() {
match r {
Ok(v) => {
self.me.data = Some(v);
self.me.error = None;
}
Err(e) => self.me.error = Some(e),
}
self.me.rx = None;
self.me.at = Some(Instant::now());
}
return;
}
if self.me.at.is_some_and(|t| t.elapsed().as_secs() < FRESH_SECS) {
return;
}
let (tx, rx) = channel();
let repaint = ctx.clone();
if self.mir.on {
let s = self.state.remote.clone();
std::thread::spawn(move || {
let r = crate::remote::to_brain(&s, "GET", "/stats", &[], &[], 40);
let _ = tx.send(r);
repaint.request_repaint();
});
} else {
let inp = crate::stats::inputs(&self.state);
std::thread::spawn(move || {
let _ = tx.send(Ok(crate::stats::build(&inp, crate::model::now_ms())));
repaint.request_repaint();
});
}
self.me.rx = Some(rx);
self.me.at = Some(Instant::now());
}
/// The page.
pub(super) fn me_page(&mut self, ui: &mut egui::Ui) {
let p = self.pal;
let ctx = ui.ctx().clone();
self.me_refresh(&ctx);
if self.me.span == 0 {
self.me.span = 30;
}
// Who: the initials, the name, how many days of the year.
let name = self.person_name();
ui.horizontal(|ui| {
let (r, _) = ui.allocate_exact_size(vec2(56.0, 56.0), egui::Sense::hover());
ui.painter().circle_filled(r.center(), 28.0, p.active);
let initials: String = name.split_whitespace().filter_map(|w| w.chars().next()).take(2).collect::<String>().to_uppercase();
let initials = if initials.is_empty() { name.chars().take(1).collect() } else { initials };
ui.painter().text(r.center(), egui::Align2::CENTER_CENTER, initials, egui::FontId::new(FONT_H3, crate::bold()), p.accent);
ui.add_space(8.0);
ui.vertical(|ui| {
ui.add_space(6.0);
ui.label(RichText::new(&name).size(FONT_H2).strong().family(crate::bold()).color(p.text));
let days = self.me.data.as_ref().and_then(|d| d["active_days"].as_u64());
let whose = if self.mir.on { format!("{}「{}」上的 Bot", t("大腦"), self.state.remote.brain_name) } else { t("這台電腦上的 Bot") };
let line = match days {
Some(n) => format!("{whose}:過去一年有 {n} 個活躍日"),
None => whose,
};
ui.label(RichText::new(line).size(FONT_SM).color(p.text3));
});
});
ui.add_space(14.0);
let Some(d) = self.me.data.clone() else {
match &self.me.error {
Some(e) => hint(ui, format!("讀不到個人資料:{e}"), p),
None => {
ui.horizontal(|ui| {
chat_ui::spinner(ui, 14.0, p.text3);
ui.label(RichText::new(t("正在算過去一年的用量…")).size(FONT_SM).color(p.text3));
});
}
}
return;
};
self.me_cards(ui, &d);
ui.add_space(18.0);
self.me_heat(ui, &d);
ui.add_space(18.0);
self.me_usage(ui, &d);
if let Some(e) = &self.me.error {
hint(ui, format!("(這次沒有更新:{e})"), p);
}
}
/// The five figures.
fn me_cards(&mut self, ui: &mut egui::Ui, d: &serde_json::Value) {
let p = self.pal;
let g = |k: &str| d[k].as_u64().unwrap_or(0);
let date = |k: &str| d[k].as_str().map(long_date).unwrap_or_default();
let busiest = &d["busiest"];
let cards: Vec<(String, String, String)> = vec![
("Token".into(), crate::stats::wan(g("tokens_year")), t("過去一年(不算快取命中)")),
(t("最活躍的一天"), if busiest.is_object() { crate::stats::wan(busiest["tokens"].as_u64().unwrap_or(0)) } else { "—".into() }, busiest["date"].as_str().map(long_date).unwrap_or_else(|| t("還沒有用量紀錄"))),
(t("訊息"), crate::stats::wan(g("messages_year")), t("過去一年")),
(t("目前連續天數"), format!("{} 天", g("streak_now")), d["streak_now_since"].as_str().map(|s| format!("自 {} 起", short_date(s))).unwrap_or_else(|| t("今天開始就算一天"))),
(t("最長連續天數"), format!("{} 天", g("streak_best")), if g("streak_best") > 0 { format!("{} – {}", date("streak_best_from"), date("streak_best_to")) } else { String::new() }),
];
let gap = 10.0;
let width = ui.available_width();
let cols = if width >= 640.0 { 3 } else { 2 };
let w = ((width - gap * (cols as f32 - 1.0)) / cols as f32).floor();
for row in cards.chunks(cols) {
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = gap;
for (label, value, sub) in row {
stat_card(ui, p, w, label, value, sub);
}
});
ui.add_space(gap);
}
}
/// A year of days: a column a week, Sunday on top; the busier the day, the deeper the colour.
fn me_heat(&mut self, ui: &mut egui::Ui, d: &serde_json::Value) {
let p = self.pal;
section(ui, "活動", p);
let days = d["days"].as_array().cloned().unwrap_or_default();
let off = d["weekday_first"].as_u64().unwrap_or(0) as usize;
let weeks = (days.len() + off).div_ceil(7);
let avail = ui.available_width();
let cell = ((avail - 8.0) / weeks.max(1) as f32).clamp(6.0, 16.0);
let top = 16.0;
let (rect, resp) = ui.allocate_exact_size(vec2(cell * weeks as f32, top + cell * 7.0), egui::Sense::hover());
let paint = ui.painter_at(rect);
let shade = |lvl: u64| match lvl {
0 => p.hover,
1 => p.accent.gamma_multiply(0.3),
2 => p.accent.gamma_multiply(0.5),
3 => p.accent.gamma_multiply(0.75),
_ => p.accent,
};
let mut last_month = String::new();
let mut hovered: Option<&serde_json::Value> = None;
let pointer = resp.hover_pos();
for (i, day) in days.iter().enumerate() {
let k = i + off;
let (col, row) = (k / 7, k % 7);
let c = rect.min + vec2(col as f32 * cell + cell / 2.0, top + row as f32 * cell + cell / 2.0);
paint.circle_filled(c, cell * 0.38, shade(day[3].as_u64().unwrap_or(0)));
let date = day[0].as_str().unwrap_or("");
let month = date.get(5..7).unwrap_or("").to_string();
if (row == 0 || i == 0) && month != last_month && !month.is_empty() {
paint.text(rect.min + vec2(col as f32 * cell, 0.0), egui::Align2::LEFT_TOP, format!("{}月", month.trim_start_matches('0')), egui::FontId::proportional(FONT_XS), p.text3);
last_month = month;
}
if pointer.is_some_and(|q| (q - c).length() <= cell / 2.0) {
hovered = Some(day);
}
}
if let Some(day) = hovered {
let words = format!("{}:{} token、{} 則訊息", long_date(day[0].as_str().unwrap_or("")), crate::stats::wan(day[1].as_u64().unwrap_or(0)), day[2].as_u64().unwrap_or(0));
resp.on_hover_text(words);
}
ui.add_space(4.0);
ui.horizontal(|ui| {
ui.label(RichText::new(t("少")).size(FONT_XS).color(p.text3));
for lvl in 0..=4 {
let (r, _) = ui.allocate_exact_size(vec2(12.0, 12.0), egui::Sense::hover());
ui.painter().circle_filled(r.center(), 5.0, shade(lvl));
}
ui.label(RichText::new(t("多")).size(FONT_XS).color(p.text3));
});
}
/// 用量: a period's tokens and cost, a bar a day, and the models and bots that used them.
fn me_usage(&mut self, ui: &mut egui::Ui, d: &serde_json::Value) {
let p = self.pal;
section_with(ui, "用量", p, |ui| {
if let Some(s) = segmented(ui, p, self.me.span, &[(7, "7 天"), (30, "30 天"), (90, "90 天"), (365, "一年")]) {
self.me.span = s;
}
});
let u = &d["periods"][self.me.span.to_string()];
let g = |k: &str| u[k].as_u64().unwrap_or(0);
let words = format!(
"{} token(新讀 {}、寫 {}、快取讀到 {})· {} 次呼叫 · 花費 {}",
crate::stats::wan(g("tokens")),
crate::stats::wan(g("input") + g("cache_write")),
crate::stats::wan(g("output")),
crate::stats::wan(g("cache_read")),
crate::stats::wan(g("calls")),
crate::stats::cost_words(g("cost_micros"), g("unpriced"), g("calls"))
);
ui.add(egui::Label::new(RichText::new(words).size(FONT_SM).color(p.text2)).wrap());
hint(ui, "花費是模型服務自己回報的(例如 OpenRouter);沒回報的寫「未定價」,不是 0 元。", p);
ui.add_space(8.0);
// A bar a day.
let daily = u["daily"].as_array().cloned().unwrap_or_default();
if !daily.is_empty() {
let max = daily.iter().filter_map(|x| x[1].as_u64()).max().unwrap_or(0).max(1);
let w = ui.available_width();
let (rect, resp) = ui.allocate_exact_size(vec2(w, 90.0), egui::Sense::hover());
let paint = ui.painter_at(rect);
let slot = w / daily.len() as f32;
let mut hovered: Option<&serde_json::Value> = None;
for (i, x) in daily.iter().enumerate() {
let v = x[1].as_u64().unwrap_or(0);
let h = (v as f32 / max as f32 * (rect.height() - 4.0)).max(if v > 0 { 2.0 } else { 1.0 });
let r = egui::Rect::from_min_max(egui::pos2(rect.left() + i as f32 * slot + slot * 0.15, rect.bottom() - h), egui::pos2(rect.left() + (i as f32 + 1.0) * slot - slot * 0.15, rect.bottom()));
paint.rect_filled(r, 2.0, if v > 0 { p.accent } else { p.hover });
if resp.hover_pos().is_some_and(|q| q.x >= rect.left() + i as f32 * slot && q.x < rect.left() + (i as f32 + 1.0) * slot) {
hovered = Some(x);
}
}
if let Some(x) = hovered {
resp.on_hover_text(format!("{}:{} token", long_date(x[0].as_str().unwrap_or("")), crate::stats::wan(x[1].as_u64().unwrap_or(0))));
}
}
ui.add_space(10.0);
for (title, key) in [("依模型", "by_model"), ("依 Bot", "by_bot")] {
let rows = u[key].as_array().cloned().unwrap_or_default();
ui.label(RichText::new(t(title)).size(FONT_SM).strong().color(p.text));
if rows.is_empty() {
hint(ui, "這段時間沒有用量紀錄", p);
}
let top = rows.first().and_then(|r| r["tokens"].as_u64()).unwrap_or(0).max(1);
rows_card(ui, p, |ui| {
for r in rows.iter().take(8) {
let tokens = r["tokens"].as_u64().unwrap_or(0);
ui.horizontal(|ui| {
let w = ui.available_width();
let right = format!("{} · {}", crate::stats::wan(tokens), crate::stats::cost_words(r["cost_micros"].as_u64().unwrap_or(0), 0, 0));
ui.allocate_ui_with_layout(vec2((w * 0.55).max(80.0), 24.0), Layout::left_to_right(Align::Center), |ui| {
ui.set_width((w * 0.55).max(80.0));
ui.add(egui::Label::new(RichText::new(r["name"].as_str().unwrap_or("")).size(FONT_SM).color(p.text)).truncate());
});
let (bar, _) = ui.allocate_exact_size(vec2((w * 0.18).max(30.0), 8.0), egui::Sense::hover());
ui.painter().rect_filled(bar, 3.0, p.hover);
ui.painter().rect_filled(egui::Rect::from_min_size(bar.min, vec2(bar.width() * tokens as f32 / top as f32, bar.height())), 3.0, p.accent);
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
ui.label(RichText::new(right).size(FONT_XS).color(p.text3));
});
});
}
});
ui.add_space(8.0);
}
}
}
/// 2025-11-27 → 2025年11月27日.
fn long_date(s: &str) -> String {
let mut it = s.split('-');
match (it.next(), it.next(), it.next()) {
(Some(y), Some(m), Some(d)) => format!("{y}年{}月{}日", m.trim_start_matches('0'), d.trim_start_matches('0')),
_ => s.to_string(),
}
}
/// 2025-11-22 → 11月22日.
fn short_date(s: &str) -> String {
let mut it = s.split('-').skip(1);
match (it.next(), it.next()) {
(Some(m), Some(d)) => format!("{}月{}日", m.trim_start_matches('0'), d.trim_start_matches('0')),
_ => s.to_string(),
}
}
#[cfg(test)]
mod tests {
#[test]
fn dates_are_said_the_chinese_way() {
assert_eq!(super::long_date("2025-11-27"), "2025年11月27日");
assert_eq!(super::short_date("2025-01-02"), "1月2日");
}
}

View File

@ -1462,6 +1462,13 @@ impl App {
None => fail("找不到這個 Bot"),
},
"settings" => self.phone_settings(owner),
// 個人資料與用量: the owner's alone (whose tokens, which bots).
"stats" => {
if !owner {
return owner_only();
}
crate::stats::build(&crate::stats::inputs(&self.state), crate::model::now_ms())
}
// Every page, newest first (the state the phone polls carries only the latest few).
"pages" => {
let now = crate::model::now_ms();

View File

@ -995,6 +995,11 @@ impl App {
ui.close();
}
menu_ui::sep(ui, p);
if menu_ui::item(ui, p, crate::icons::Icon::Person, "個人資料與用量…").clicked() {
self.show_settings = true;
self.settings_tab = SettingsTab::Me;
ui.close();
}
if menu_ui::item(ui, p, crate::icons::Icon::Gear, "設定…").on_hover_text(t("⌘,")).clicked() {
self.show_settings = true;
self.settings_tab = SettingsTab::General;

View File

@ -54,6 +54,7 @@ mod m2v;
mod model;
mod notify;
mod oplog;
mod stats;
mod phone;
mod policy;
mod preview;

View File

@ -836,6 +836,9 @@ pub fn handle(req: Req, via_relay: bool) -> Resp {
}
}
("GET", ["api", "settings"]) => phone_act("settings", json!({}), &role),
// 個人資料與用量 (the owner's): the year in figures, worked out on the brain (stats.rs).
("GET", ["api", "stats"]) => phone_act("stats", json!({}), &role),
("GET", ["api", "sync", "stats"]) => phone_act_for("stats", json!({}), "owner", 40),
("GET", ["api", "box", "thumb"]) => box_thumb(),
// 看畫面 on 區網: a ticket for the screen's connection, so the login isn't in its address.
("POST", ["api", "vnc", "ticket"]) if !via_relay => {

295
src/stats.rs Normal file
View File

@ -0,0 +1,295 @@
//! 個人資料與用量 (plan C4, C5): what the person did with AnyBot over the past year, worked out
//! when asked from what is already kept — every model call's tokens (`usage/YYYY-MM.jsonl`) and
//! every message's time — nothing stored apart. Days are cut in the brain's time zone.
//!
//! The figures: tokens over the past year (not counting cache hits: what the model read anew and
//! wrote), the busiest day, messages, the current and the longest run of days used (today not
//! used yet doesn't end a run), a year of days for the heat map (53 weeks), and for 7 / 30 / 90 /
//! 365 days the tokens by kind, what the providers said it cost (a call none priced is counted as
//! 「未定價」, never $0), by model and by bot, and per day.
use crate::usage::Entry;
use chrono::{Datelike, NaiveDate, TimeZone};
use serde_json::{json, Value};
use std::collections::{BTreeMap, HashMap};
/// What the figures are made from (gathered on the app's thread: the chats live there).
pub struct Inputs {
/// When each message the person or a bot wrote was written (ms), any bot, any conversation.
pub messages: Vec<i64>,
/// Bots by id, for the names in 「依 Bot」.
pub names: HashMap<u64, String>,
/// The brain's time zone (設定 › 一般 › Bot › 時區).
pub timezone: String,
}
/// The days of the heat map: 53 weeks, ending today.
pub const DAYS: i64 = 53 * 7;
const DAY_MS: i64 = 86_400_000;
/// From the app's state: every message's time (the person's and the bots' words, not steps or
/// AnyBot's own lines), the bots' names, the time zone.
pub fn inputs(st: &crate::model::State) -> Inputs {
use crate::model::Role;
let from = crate::model::now_ms() - (DAYS + 2) * DAY_MS;
let counts = |m: &crate::model::Message| matches!(m.role, Role::User | Role::Assistant) && !m.note && m.at >= from && !(m.role == Role::Assistant && m.text.trim().is_empty());
let mut messages = vec![];
for b in &st.bots {
messages.extend(b.messages.iter().filter(|m| counts(m)).map(|m| m.at));
for (_, t) in b.threads.iter() {
messages.extend(t.iter().filter(|m| counts(m)).map(|m| m.at));
}
}
Inputs { messages, names: st.bots.iter().map(|b| (b.id, b.name.clone())).collect(), timezone: st.timezone.clone() }
}
/// Everything, from the inputs and the year's usage on disk.
pub fn build(inp: &Inputs, now_ms: i64) -> Value {
compute(inp, &crate::usage::since_any(now_ms - (DAYS + 2) * DAY_MS), now_ms)
}
/// Tokens that count: what the model read anew (and wrote to its cache) and what it wrote — a
/// cache hit is the same words read again, cheaply.
fn counted(u: &crate::providers::Usage) -> u64 {
u.input + u.cache_write + u.output
}
pub fn compute(inp: &Inputs, entries: &[Entry], now_ms: i64) -> Value {
let tz = crate::routines::tz_of(&inp.timezone);
let day_of = |ms: i64| tz.timestamp_millis_opt(ms).single().map(|t| t.date_naive());
let Some(today) = day_of(now_ms) else { return json!({}) };
let first = today - chrono::Duration::days(DAYS - 1);
// Per day of the past year: tokens, messages.
let mut days: BTreeMap<NaiveDate, (u64, u64)> = BTreeMap::new();
for e in entries {
if let Some(d) = day_of(e.at).filter(|d| *d >= first && *d <= today) {
days.entry(d).or_default().0 += counted(&e.usage);
}
}
for &at in &inp.messages {
if let Some(d) = day_of(at).filter(|d| *d >= first && *d <= today) {
days.entry(d).or_default().1 += 1;
}
}
let year_from = today - chrono::Duration::days(364);
let in_year = |d: &NaiveDate| *d >= year_from;
let tokens_year: u64 = days.iter().filter(|(d, _)| in_year(d)).map(|(_, v)| v.0).sum();
let messages_year: u64 = days.iter().filter(|(d, _)| in_year(d)).map(|(_, v)| v.1).sum();
let busiest = days.iter().filter(|(d, v)| in_year(d) && v.0 > 0).max_by_key(|(d, v)| (v.0, std::cmp::Reverse(**d))).map(|(d, v)| json!({"date": d.to_string(), "tokens": v.0}));
let active = |d: &NaiveDate| days.get(d).is_some_and(|v| v.0 > 0 || v.1 > 0);
// The run up to today (today not used yet: up to yesterday).
let mut end = today;
if !active(&end) {
end = today - chrono::Duration::days(1);
}
let mut start = end;
while active(&start) && start > first {
start -= chrono::Duration::days(1);
}
let start = if active(&start) { start } else { start + chrono::Duration::days(1) };
let now_run = if active(&end) { (end - start).num_days() + 1 } else { 0 };
// The longest run in the year.
let (mut best, mut best_from, mut best_to, mut run, mut run_from) = (0i64, first, first, 0i64, first);
let mut d = first;
while d <= today {
if active(&d) {
if run == 0 {
run_from = d;
}
run += 1;
if run > best {
(best, best_from, best_to) = (run, run_from, d);
}
} else {
run = 0;
}
d += chrono::Duration::days(1);
}
let active_days = days.iter().filter(|(d, v)| in_year(d) && (v.0 > 0 || v.1 > 0)).count();
// The heat map: every day from `first` (a Sunday-started week grid is the page's to draw).
let max = days.values().map(|v| v.0).max().unwrap_or(0).max(1);
let max_msgs = days.values().map(|v| v.1).max().unwrap_or(0).max(1);
let level = |t: u64, m: u64| -> u8 {
// Tokens when there are any; a day with only messages (a provider that reports none) by them.
let share = if t > 0 { t as f64 / max as f64 } else { m as f64 / max_msgs as f64 };
if t == 0 && m == 0 {
0
} else if share < 0.25 {
1
} else if share < 0.5 {
2
} else if share < 0.75 {
3
} else {
4
}
};
let mut grid = vec![];
let mut d = first;
while d <= today {
let (t, m) = days.get(&d).copied().unwrap_or_default();
grid.push(json!([d.to_string(), t, m, level(t, m)]));
d += chrono::Duration::days(1);
}
// 用量: the last 7 / 30 / 90 / 365 days.
let name = |id: u64, what: &str| -> String {
if id == 0 {
return format!("({what})");
}
let n = inp.names.get(&id).cloned().unwrap_or_else(|| format!("Bot {id}(已刪除)"));
if what == "回合" { n } else { format!("{n}({what})") }
};
let mut periods = serde_json::Map::new();
for span in [7i64, 30, 90, 365] {
let from = today - chrono::Duration::days(span - 1);
let mut total = crate::providers::Usage::default();
let (mut calls, mut unpriced) = (0u64, 0u64);
let mut by_model: BTreeMap<String, (u64, u64, u64)> = BTreeMap::new();
let mut by_bot: BTreeMap<String, (u64, u64, u64)> = BTreeMap::new();
let mut per_day: BTreeMap<NaiveDate, u64> = BTreeMap::new();
for e in entries {
let Some(d) = day_of(e.at).filter(|d| *d >= from && *d <= today) else { continue };
total.add(&e.usage);
calls += 1;
if e.usage.cost_micros == 0 {
unpriced += 1;
}
let t = counted(&e.usage);
let m = by_model.entry(format!("{} · {}", e.provider, e.model)).or_default();
(m.0, m.1, m.2) = (m.0 + t, m.1 + e.usage.cost_micros, m.2 + 1);
let (id, what) = e.whose();
let b = by_bot.entry(name(id, what)).or_default();
(b.0, b.1, b.2) = (b.0 + t, b.1 + e.usage.cost_micros, b.2 + 1);
*per_day.entry(d).or_default() += t;
}
let rows = |m: BTreeMap<String, (u64, u64, u64)>| -> Vec<Value> {
let mut v: Vec<(String, (u64, u64, u64))> = m.into_iter().collect();
v.sort_by_key(|(k, x)| (std::cmp::Reverse(x.0), k.clone()));
v.into_iter().map(|(k, x)| json!({"name": k, "tokens": x.0, "cost_micros": x.1, "calls": x.2})).collect()
};
let mut daily = vec![];
let mut d = from;
while d <= today {
daily.push(json!([d.to_string(), per_day.get(&d).copied().unwrap_or(0)]));
d += chrono::Duration::days(1);
}
periods.insert(
span.to_string(),
json!({
"tokens": counted(&total), "input": total.input, "output": total.output, "cache_read": total.cache_read, "cache_write": total.cache_write,
"cost_micros": total.cost_micros, "calls": calls, "unpriced": unpriced,
"by_model": rows(by_model), "by_bot": rows(by_bot), "daily": daily,
}),
);
}
json!({
"today": today.to_string(),
"first": first.to_string(),
"tokens_year": tokens_year,
"messages_year": messages_year,
"busiest": busiest,
"streak_now": now_run,
"streak_now_since": (now_run > 0).then(|| start.to_string()),
"streak_best": best,
"streak_best_from": (best > 0).then(|| best_from.to_string()),
"streak_best_to": (best > 0).then(|| best_to.to_string()),
"active_days": active_days,
"days": grid,
"periods": periods,
"weekday_first": first.weekday().num_days_from_sunday(),
})
}
/// A count the way the page says it: 9,999; 5993.4萬; 1.20億.
pub fn wan(n: u64) -> String {
match n {
0..=9_999 => {
let s = n.to_string();
if n >= 1_000 { format!("{},{}", &s[..s.len() - 3], &s[s.len() - 3..]) } else { s }
}
10_000..=99_999_999 => format!("{:.1}萬", n as f64 / 10_000.0),
_ => format!("{:.2}億", n as f64 / 100_000_000.0),
}
}
/// What the providers said it cost, or 「未定價」 when none did.
pub fn cost_words(micros: u64, unpriced: u64, calls: u64) -> String {
if micros == 0 {
return "未定價".into();
}
let s = format!("US${:.2}", micros as f64 / 1_000_000.0);
if unpriced > 0 && unpriced < calls {
format!("{s}(另有 {unpriced} 次呼叫未定價)")
} else {
s
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::providers::Usage;
fn at(tz: &str, y: i32, m: u32, d: u32, h: u32) -> i64 {
crate::routines::tz_of(tz).with_ymd_and_hms(y, m, d, h, 0, 0).unwrap().timestamp_millis()
}
fn entry(ms: i64, model: &str, session: &str, input: u64, output: u64, cache_read: u64, cost: u64) -> Entry {
Entry { at: ms, provider: "xAI Grok".into(), model: model.into(), session: session.into(), usage: Usage { input, output, cache_read, cache_write: 0, cost_micros: cost } }
}
/// The year in figures: tokens without cache hits, the busiest day, messages, the run up to
/// today (today not used yet doesn't end it), the longest run, days cut in the brain's zone.
#[test]
fn a_year_in_figures() {
let tz = "Asia/Taipei";
let now = at(tz, 2026, 11, 21, 15);
let inp = Inputs {
// 11/18, 11/19, 11/20 (one at 23:30 Taipei — 15:30 UTC, still the 20th there), nothing today.
messages: vec![at(tz, 2026, 11, 18, 10), at(tz, 2026, 11, 19, 10), at(tz, 2026, 11, 20, 23) + 30 * 60_000],
names: [(2u64, "賴桑".to_string())].into_iter().collect(),
timezone: tz.into(),
};
let entries = vec![
entry(at(tz, 2026, 11, 19, 9), "grok-4", "anybot-bot-2", 1_000, 200, 50_000, 0),
entry(at(tz, 2026, 11, 20, 9), "grok-4", "anybot-bot-2", 3_000, 500, 0, 0),
entry(at(tz, 2026, 11, 20, 10), "kimi-k3", "anybot-check-2", 100, 10, 0, 12_000),
// A year and more ago: not in the year.
entry(at(tz, 2025, 11, 1, 9), "grok-4", "anybot-bot-9", 9_999_999, 0, 0, 0),
// Two weeks ago, one day alone.
entry(at(tz, 2026, 11, 7, 9), "grok-4", "anybot-bot-9", 10, 0, 0, 0),
];
let s = compute(&inp, &entries, now);
assert_eq!(s["tokens_year"], 1_200 + 3_500 + 110 + 10, "cache hits aren't counted");
assert_eq!(s["busiest"], json!({"date": "2026-11-20", "tokens": 3_610}));
assert_eq!(s["messages_year"], 3);
assert_eq!((s["streak_now"].as_i64(), s["streak_now_since"].as_str()), (Some(3), Some("2026-11-18")), "today not used yet: the run still stands");
assert_eq!((s["streak_best"].as_i64(), s["streak_best_from"].as_str(), s["streak_best_to"].as_str()), (Some(3), Some("2026-11-18"), Some("2026-11-20")));
assert_eq!(s["active_days"], 4);
let days = s["days"].as_array().unwrap();
assert_eq!(days.len() as i64, DAYS);
assert_eq!(days.last().unwrap()[0], "2026-11-21");
let lvl = |date: &str| days.iter().find(|d| d[0] == date).map(|d| d[3].as_u64().unwrap()).unwrap();
assert_eq!((lvl("2026-11-20"), lvl("2026-11-19"), lvl("2026-11-21")), (4, 2, 0));
// 用量 for 7 days: by model, by bot (a check by its bot), what it cost, what wasn't priced.
let w = &s["periods"]["7"];
assert_eq!((w["calls"].as_u64(), w["unpriced"].as_u64(), w["cost_micros"].as_u64()), (Some(3), Some(2), Some(12_000)));
assert_eq!(w["by_model"][0]["name"], "xAI Grok · grok-4");
let bots: Vec<&str> = w["by_bot"].as_array().unwrap().iter().map(|r| r["name"].as_str().unwrap()).collect();
assert_eq!(bots, ["賴桑", "賴桑(發布前檢查)"]);
assert_eq!(w["daily"].as_array().unwrap().len(), 7);
assert_eq!(s["periods"]["30"]["by_bot"].as_array().unwrap().iter().find(|r| r["name"] == "Bot 9(已刪除)").map(|r| r["tokens"].as_u64()), Some(Some(10)));
// A day used today: the run goes through today.
let mut inp2 = inp;
inp2.messages.push(at(tz, 2026, 11, 21, 9));
assert_eq!(compute(&inp2, &entries, now)["streak_now"], 4);
}
#[test]
fn counts_and_costs_are_said_plainly() {
assert_eq!((wan(999), wan(9_999), wan(59_934_000), wan(294_000), wan(120_000_000)), ("999".into(), "9,999".into(), "5993.4萬".into(), "29.4萬".into(), "1.20億".into()));
assert_eq!(cost_words(0, 5, 5), "未定價");
assert_eq!(cost_words(1_230_000, 0, 4), "US$1.23");
assert_eq!(cost_words(1_230_000, 2, 4), "US$1.23(另有 2 次呼叫未定價)");
}
}

View File

@ -75,6 +75,29 @@ pub fn since(since: i64) -> Vec<Entry> {
out
}
/// What was written down since `since` (ms), however long ago: every month's file from then on
/// (個人資料 reads a year).
pub fn since_any(since: i64) -> Vec<Entry> {
use chrono::TimeZone;
let now = chrono::Local::now();
let mut month = chrono::Local.timestamp_millis_opt(since).single().unwrap_or(now);
let mut out = vec![];
for _ in 0..40 {
for line in std::fs::read_to_string(file_for(month)).unwrap_or_default().lines() {
if let Ok(e) = serde_json::from_str::<Entry>(line) {
if e.at >= since {
out.push(e);
}
}
}
if month.format("%Y-%m").to_string() >= now.format("%Y-%m").to_string() {
break;
}
month = month.checked_add_months(chrono::Months::new(1)).unwrap_or(now);
}
out
}
fn k(n: u64) -> String {
match n {
0..=999 => n.to_string(),