Skip to content

armgit / Wake

Public Imported from GitHub
0

All your AI agent sessions in one place — browse, search, resume. Rust + GPUI.

Rust

Add Insights page with activity heatmap, distributions and leaderboards

Corey Chiu65bf186721ca
diff --git a/DESIGN.md b/DESIGN.md
index eff6647..5caf0e3 100644
--- a/DESIGN.md
+++ b/DESIGN.md
@@ -133,7 +133,7 @@ macOS 不设置横跨三栏的自定义 header。主窗口透明标题栏高 44p
- 线条图标比实心品牌图视觉轻,同档里给小一号:分组项 Lucide 14 / 品牌图 18,主导航 Lucide 15。
- 行内容 = 行首元素 + 标题 + 计数;计数一律 Label 档 muted。
- 组头 "Agents"/"Projects" 用 Body 档常规字重 + muted 色(与主导航同字号同字重,仅靠颜色和"无行首图标"区分——加粗会让组头压过它统辖的行),带 13px chevron 可折叠。
-- 底部工具条常驻,总高 44px(含顶部 1px hairline),按钮靠右排列(次要操作区:透明底、hover 才出色,不与导航行选中态抢注意力)——左为齿轮 "Settings",右为 refresh。Settings 同时进入 Wake 菜单并绑定 `⌘,`(其他平台 `Ctrl+,`),保持单例窗口。
+- 底部工具条常驻,总高 44px(含顶部 1px hairline),按钮靠右排列(次要操作区:透明底、hover 才出色,不与导航行选中态抢注意力)——依次为 chart-column "Insights"、齿轮 "Settings"、refresh。Insights 页打开时其图标以 primary 点亮,是工具条里唯一有激活态的按钮。Settings 同时进入 Wake 菜单并绑定 `⌘,`(其他平台 `Ctrl+,`),保持单例窗口。
- Settings 默认 820×600,采用 180px 窄侧栏 + 内容页结构,固定为 General / Locations / Data / Updates / About 五项;About 与功能设置分离并钉在侧栏底部,Wake 菜单的 About Wake 直达同一页。About 沿用 Kooky/Birth 的信息顺序:产品图标、名称、版本、tagline、GitHub、短分隔线、版权/许可证与作者署名。Updates 是独立功能页,仅在用户点击页面按钮或 macOS Wake 菜单的 Check for Updates 时读取 GitHub 最新正式 Release 元数据,明确呈现检查中/最新版/有新版/失败四种状态;有新版时打开 Release 页供用户下载,不后台检查、不自行覆盖应用包。内部常规文字按钮统一沿用主界面的 24px 高、6px 圆角和主题交互色,普通页面动作使用 muted 填充 + hairline;发现新版后的 View Update 是需要用户继续完成的主操作,使用 32px 高 primary 填充和轻阴影。Appearance 分段选择器也使用同一材质。General 只放真实可用的全局偏好,当前为持久化的 System / Light / Dark 外观选择;不提供默认 “Open In” 终端。Data 只展示 Wake 本地存储位置、会话数与磁盘占用并提供文件管理器入口,不重复放刷新或清库动作;常规 Refresh 的唯一入口仍是主侧栏底部。Locations 页按 AgentId 声明序以 agent 分组,品牌名只在组头出现一次;本机有数据的组优先,未检测到的 agent 默认收进可展开区。每条路径以路径为主信息、会话数/不可用状态为 muted 副信息,最右为逐路径开关;停用时只降低文字层级,开关与菜单保持完整对比度。行本身不承担编辑,`…` 菜单集中 Edit / Show in Finder / 自定义 Remove。顶部操作为低强调的 Add location,Restore defaults 收进页级 `…` 菜单且无偏离时禁用。添加/编辑仍复用 agent 下拉 + 可手输路径 + 目录选择表单;关闭 location 后保留配置、停止扫描/监听并从会话与搜索结果排除,重新开启即增量扫回;纯路径管理不做内容校验。
- 工具条内的**状态行"常态沉默"**:仅刷新中或监听不可用时出现在按钮行上方;文案须可 truncate,窄侧栏放不下长句(故为 "Live updates off" 而非带操作建议的整句)。
- 手动 Refresh 始终后台运行;进度复用侧栏状态行,完成后发通知,不用模态框阻断浏览、搜索或阅读。
@@ -196,6 +196,18 @@ emoji 不再承担界面或正文结构图标职责。
- 搜索始终覆盖全部会话;页脚左侧显示“搜索范围:全部会话”,右侧显示 `↑↓`、`↩`、`esc` 键盘路径。
- 指针回调中不得同步派发新的键盘事件。需要关闭旧浮层或转移输入焦点时,应通过对应组件 API 或延迟到下一事件周期处理,避免在 AppKit `mouseUp` 路径里重入 GPUI 事件分发;打开搜索面板前必须让 Root 先保存原焦点,关闭后 `⌘K` 才能继续生效。
+### Insights
+
+侧栏底部工具条的 chart-column 按钮进入;它是与全部导航行互斥的**整页目的地**——打开时替换会话流与阅读区,点任意导航行(或再点入口)退出并落回 All Sessions。设置仍是独立场景,Insights 不是。
+
+- 页面用 `background` 材质整片承载;顶部 88px 标题区与中栏同节奏(Insights 22px semibold + Label 11 副行,副行只说 "Since {首会话月份}"),兼窗口拖拽区。内容限 720px 阅读宽居中,区块之间只用 32px 留白与 Body 14 semibold 组头分隔——**不做卡片墙、零投影**,延续"避免每个区域加边框"的层级原则。
+- 统计口径与主 UI 一致(archived 不计):"Prompts" 一律指主线用户消息。数据在打开与每次 Refresh 后后台重算,不阻塞浏览。
+- 概览行:22px semibold 大数字 + Caption 标签,序为 Sessions / Tokens / Prompts / Agents / Projects / Active days(用户钉序,2026-08-27);Tokens 仅在有 agent 报过用量时出现。数字千分位。
+- 活跃热力图:53 周 × 7 天(周一起始,最右列为本周),10px 圆角格 + 3px 缝,总宽 715px。强度 = `muted` 空格 + `primary` 25/50/75/100% 四档(按窗口内峰值分位);未来日期留白。月份与 Mon/Wed/Fri 标签用 Label 11 muted;每格 tooltip 给 "N prompts · Aug 3, 2026"。底注左侧为 streak 与最忙一日(Label 11,` · ` 分隔),右侧 Less–More 固定满阶梯图例。
+- 分布图:hour(24 柱)/ weekday(7 柱)/ month(12 柱)三个维度共用一张竖柱图,组头右侧 ‹ › ghost 按钮循环切换(纯视图状态,数据三份常驻不重查);峰值柱全饱和 `primary`、其余 55%,零值保留 2px `muted` 基线;柱数越少缝越大(4/8/6px)。hour 只标 6 小时锚点(靠左),weekday/month 每柱标签与柱居中;组头副行点出峰值("Most active around 2 PM" / "on Sundays" / "in August")。
+- Agents / Projects / Models 三个榜单同构:条形行 = 行首(品牌图 15px 原色 / folder 图标 / 无)+ 名称列定宽 truncate + 6px 圆头轨道条(`muted` 轨、`primary` 填充,按组内峰值归一)+ 右对齐 Label 计数。三个组头都挂 ‹ › 切换度量,循环序与概览行一致:Sessions / Tokens / Prompts;**当前档位名(首字母大写的裸名词)显示在两键中间**——64px 定宽居中,Caption muted,按钮位置不随文本跳动;榜单组头因此为单行(标题与按钮组居中对齐),分布图组头保留 caption 双行、按钮中间无标签(其标题本身就是档位名)。每个榜单各自记忆档位,行按当前度量降序重排后取 top-N(Agents 全量、Projects/Models 各 6;截断在排序之后,换度量不漏项);Tokens 档只列报过用量的组、值用 K/M 缩写,组内无人报 token 时该档不进循环。
+- 空态沿用详情空态形制("No activity yet" + "Refresh sessions to see your activity here.");加载用居中 Spinner,已有数据时静默换新不闪烁。
+
## 图标、形状与层次
- UI chrome 只使用内嵌 Lucide 单线 SVG,不使用 Unicode 或 emoji 图标;Agent 身份用内嵌品牌 PNG,经 `img()` 渲染并**保持原色**(不得用 `text_color` 着色,选中态也不变色)。
diff --git a/crates/wake-core/src/db.rs b/crates/wake-core/src/db.rs
index 873ced5..4e3768b 100644
--- a/crates/wake-core/src/db.rs
+++ b/crates/wake-core/src/db.rs
@@ -141,6 +141,9 @@ pub fn open_or_rebuild(path: &Path) -> Result<(Store, Option<String>)> {
pub struct Store {
write: Mutex<Connection>,
read: Mutex<Connection>,
+ /// insights() 开临时连接用:统计要连扫 messages 几十毫秒,共用唯一
+ /// 读连接会让 UI 线程的列表查询排队等它(2026-08-27 Codex review)
+ path: std::path::PathBuf,
}
impl Store {
@@ -148,6 +151,7 @@ impl Store {
Ok(Self {
write: Mutex::new(open_conn(path)?),
read: Mutex::new(open_conn(path)?),
+ path: path.to_path_buf(),
})
}
@@ -721,6 +725,165 @@ impl Store {
Ok(counts)
}
+ /// Insights 页统计快照。`today` 由调用方传入(streak 相对它计算,
+ /// 也让测试不依赖真实时钟);SQL 侧 `'localtime'` 与 chrono `Local`
+ /// 同取系统时区,日界一致。messages 全表恰扫两遍(日×时分桶 + 榜单
+ /// prompts),量级几十万行、几十毫秒——调用方走后台任务,别在 UI
+ /// 线程等它。
+ pub fn insights(&self, today: chrono::NaiveDate) -> Result<InsightsData> {
+ use chrono::Datelike as _;
+ // "一条 prompt" 的行集(主线用户消息)——整页口径共用这一个片段,
+ // 内联多份的话谓词一漂移,总数就会与分桶/榜单悄悄不一致
+ const PROMPT_ROWS: &str = "FROM messages m JOIN sessions s ON s.key = m.session_key
+ WHERE s.archived = 0 AND m.role = 'user' AND m.sidechain_id IS NULL";
+
+ // 临时连接,不与 UI 的 read 连接抢锁:WAL 多读并发,几十毫秒的
+ // 统计扫描不该让导航点击的列表查询排队(2026-08-27 Codex review)
+ let conn = open_conn(&self.path)?;
+ let mut data = InsightsData {
+ as_of: today,
+ ..Default::default()
+ };
+
+ (
+ data.sessions,
+ data.tokens,
+ data.first_ts,
+ data.project_count,
+ ) = conn.query_row(
+ "SELECT COUNT(*), COALESCE(SUM(tokens_used),0),
+ COALESCE(MIN(NULLIF(created_at,0)),0),
+ COUNT(DISTINCT NULLIF(project_path,''))
+ FROM sessions WHERE archived = 0",
+ [],
+ |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)),
+ )?;
+
+ // 第一遍:按(日,时)组合分桶(行数 = 活跃日×活跃时段,千级)。
+ // 无 ts 的行落 NULL 桶只计入总数;weekday/monthly 由日期在 Rust 侧
+ // 派生,省去再让 SQL 各扫一遍 + 每行多次 strftime 时区换算
+ let mut stmt = conn.prepare_cached(&format!(
+ "SELECT CASE WHEN m.ts > 0 THEN date(m.ts/1000,'unixepoch','localtime') END d,
+ CASE WHEN m.ts > 0 THEN CAST(strftime('%H', m.ts/1000,'unixepoch','localtime') AS INTEGER) END h,
+ COUNT(*)
+ {PROMPT_ROWS}
+ GROUP BY d, h ORDER BY d"
+ ))?;
+ let rows = stmt.query_map([], |r| {
+ Ok((
+ r.get::<_, Option<String>>(0)?,
+ r.get::<_, Option<i64>>(1)?,
+ r.get::<_, i64>(2)?,
+ ))
+ })?;
+ for row in rows {
+ let (d, h, n) = row?;
+ data.prompts += n;
+ let Some(d) = d else { continue };
+ let Ok(day) = chrono::NaiveDate::parse_from_str(&d, "%Y-%m-%d") else {
+ continue;
+ };
+ // 时钟漂移的脏数据可能带未来日期:不进任何分桶(prompts 总数
+ // 无日期语义仍计入)。热力图不画未来格,streak/活跃天数若认了
+ // 就会与它互相矛盾(2026-08-27 Codex review)
+ if day > today {
+ continue;
+ }
+ if let Some(h) = h.filter(|h| (0..24).contains(h)) {
+ data.hourly[h as usize] += n;
+ }
+ data.weekday[day.weekday().num_days_from_monday() as usize] += n;
+ data.monthly[day.month0() as usize] += n;
+ // ORDER BY d 保证同日相邻,尾项聚合即可
+ match data.daily.last_mut() {
+ Some((last, c)) if *last == day => *c += n,
+ _ => data.daily.push((day, n)),
+ }
+ }
+ drop(stmt);
+
+ // 第二遍:榜单 prompts 按(agent,项目,模型)三键一次分组(行数 =
+ // distinct 组合,几百),拆三张 map 回填——免去每个榜单一遍全表子查询
+ let mut prompts_by_agent: HashMap<String, i64> = HashMap::new();
+ let mut prompts_by_project: HashMap<String, i64> = HashMap::new();
+ let mut prompts_by_model: HashMap<String, i64> = HashMap::new();
+ let mut stmt = conn.prepare_cached(&format!(
+ "SELECT s.agent_id, s.project_path, COALESCE(s.model,''), COUNT(*)
+ {PROMPT_ROWS}
+ GROUP BY 1, 2, 3"
+ ))?;
+ let rows = stmt.query_map([], |r| {
+ Ok((
+ r.get::<_, String>(0)?,
+ r.get::<_, String>(1)?,
+ r.get::<_, String>(2)?,
+ r.get::<_, i64>(3)?,
+ ))
+ })?;
+ for row in rows {
+ let (agent, project, model, n) = row?;
+ *prompts_by_agent.entry(agent).or_default() += n;
+ *prompts_by_project.entry(project).or_default() += n;
+ if !model.is_empty() {
+ *prompts_by_model.entry(model).or_default() += n;
+ }
+ }
+ drop(stmt);
+
+ // 榜单主体只查 sessions 表(几百行),prompts 由上面的 map 回填。
+ // display 与 group 分开传:项目按 path 分组、按名展示(同名异路径
+ // 各占一行,合并会把两个真实目录混作一处)。全量返回不截断——
+ // top-N 由 UI 按当前度量排序后取,否则换度量会漏项
+ let usage = |display: &str,
+ group: &str,
+ filter: &str,
+ prompts: &HashMap<String, i64>|
+ -> Result<Vec<UsageTally>> {
+ let sql = format!(
+ "SELECT {display}, {group}, COUNT(*), COALESCE(SUM(s.tokens_used),0)
+ FROM sessions s WHERE s.archived = 0{filter}
+ GROUP BY {group} ORDER BY COUNT(*) DESC, {display}"
+ );
+ let mut stmt = conn.prepare_cached(&sql)?;
+ let rows = stmt.query_map([], |r| {
+ Ok((
+ UsageTally {
+ name: r.get(0)?,
+ sessions: r.get(2)?,
+ tokens: r.get(3)?,
+ prompts: 0,
+ },
+ r.get::<_, String>(1)?,
+ ))
+ })?;
+ rows.map(|row| {
+ let (mut tally, key) = row?;
+ tally.prompts = prompts.get(&key).copied().unwrap_or(0);
+ Ok(tally)
+ })
+ .collect()
+ };
+ data.agents = usage("s.agent_id", "s.agent_id", "", &prompts_by_agent)?;
+ // 无 cwd 的会话 project_path 为空、name 是 "Unknown project" 占位:
+ // 概览 project_count 按空 path 排除,榜单必须同谓词——按 name 滤会
+ // 让页面一边数 0 一边列出 Unknown project(2026-08-27 Codex review)
+ data.projects = usage(
+ "s.project_name",
+ "s.project_path",
+ " AND s.project_path != ''",
+ &prompts_by_project,
+ )?;
+ data.models = usage(
+ "s.model",
+ "s.model",
+ " AND s.model IS NOT NULL AND s.model != ''",
+ &prompts_by_model,
+ )?;
+
+ (data.current_streak, data.longest_streak) = compute_streaks(&data.daily, today);
+ Ok(data)
+ }
+
/// 全文搜索:trigram MATCH(每段 ≥3 码点)或 LIKE 降级。返回 (hits, degraded)
pub fn search(
&self,
@@ -1002,6 +1165,28 @@ fn make_like_snippet(text: &str, first_seg: &str) -> String {
out
}
+/// (current, longest) 连续活跃天数。`daily` 须按日期升序(insights 的
+/// SQL 保证)。current 从 today 往回数;今天尚无活动时允许从昨天起算
+/// (GitHub 惯例:一天没结束不清零),更早断档即为 0。
+fn compute_streaks(daily: &[(chrono::NaiveDate, i64)], today: chrono::NaiveDate) -> (i64, i64) {
+ let mut longest = 0i64;
+ let mut run = 0i64;
+ let mut prev: Option<chrono::NaiveDate> = None;
+ for &(d, _) in daily {
+ run = match prev {
+ Some(p) if (d - p).num_days() == 1 => run + 1,
+ _ => 1,
+ };
+ longest = longest.max(run);
+ prev = Some(d);
+ }
+ let current = match prev {
+ Some(last) if (today - last).num_days() <= 1 => run,
+ _ => 0,
+ };
+ (current, longest)
+}
+
pub fn now_ms() -> i64 {
chrono::Utc::now().timestamp_millis()
}
diff --git a/crates/wake-core/src/models.rs b/crates/wake-core/src/models.rs
index 8cb8820..400a21e 100644
--- a/crates/wake-core/src/models.rs
+++ b/crates/wake-core/src/models.rs
@@ -350,6 +350,62 @@ pub struct SearchHit {
pub timestamp: Option<i64>,
}
+/// Insights 页统计快照(`Store::insights` 一次算好)。口径与主 UI 一致:
+/// 全部 `archived = 0`;"prompts" = 主线用户消息(role=user 且非 sidechain)。
+/// daily 是**全时段**活跃日谱(仅含有时间戳的行,升序)——热力图窗口、
+/// streak、busiest day 都由它派生,不另设第二份日数据。
+#[derive(Debug, Clone, Default)]
+pub struct InsightsData {
+ /// 快照的"今天"(查询时传入的本地日):streak 与热力图末列共用它,
+ /// 渲染层不再各自读时钟——跨午夜也不会互相错位
+ pub as_of: chrono::NaiveDate,
+ pub sessions: i64,
+ pub prompts: i64,
+ /// SUM(tokens_used);多数 adapter 无 token 数据,0 = 不展示
+ pub tokens: i64,
+ pub project_count: i64,
+ /// 最早会话 created_at(ms);0 = 库内无有效时间
+ pub first_ts: i64,
+ /// 截至 as_of 的连续活跃天数(今天尚无活动时从昨天起算,GitHub 惯例)
+ pub current_streak: i64,
+ pub longest_streak: i64,
+ pub daily: Vec<(chrono::NaiveDate, i64)>,
+ /// 本地时段分布(0–23 时)
+ pub hourly: [i64; 24],
+ /// 星期分布,周一起始(与热力图同序)
+ pub weekday: [i64; 7],
+ /// 月份分布(1–12 月聚合到 12 桶,跨年叠加)
+ pub monthly: [i64; 12],
+ /// 每家 agent 的三个度量,按会话数降序;UI 切换度量时自行重排
+ pub agents: Vec<UsageTally>,
+ /// 全量项目——不截断,top-N 由 UI 按当前度量排序后取(SQL 里加 LIMIT
+ /// 会让 Prompts/Tokens 榜漏掉会话数排不进前列的项)
+ pub projects: Vec<UsageTally>,
+ /// 全量模型,同上
+ pub models: Vec<UsageTally>,
+}
+
+impl InsightsData {
+ /// 活跃天数 = daily 长度(派生不另存,免第二个写入点失步)
+ pub fn active_days(&self) -> i64 {
+ self.daily.len() as i64
+ }
+
+ pub fn busiest_day(&self) -> Option<(chrono::NaiveDate, i64)> {
+ self.daily.iter().max_by_key(|(_, n)| *n).copied()
+ }
+}
+
+/// Insights 榜单的一行(agent/项目/模型共用)。tokens = 0 表示该组不报
+/// token(而非用了 0),UI 按此语义隐藏而不是画空条
+#[derive(Debug, Clone, Default, PartialEq, Eq)]
+pub struct UsageTally {
+ pub name: String,
+ pub sessions: i64,
+ pub prompts: i64,
+ pub tokens: i64,
+}
+
/// 搜索 snippet 高亮哨兵(UI 层替换为高亮样式)
pub const HL_OPEN: char = '\u{e000}';
pub const HL_CLOSE: char = '\u{e001}';
diff --git a/crates/wake-core/tests/db_roundtrip.rs b/crates/wake-core/tests/db_roundtrip.rs
index 5a2f3ed..ec87ce1 100644
--- a/crates/wake-core/tests/db_roundtrip.rs
+++ b/crates/wake-core/tests/db_roundtrip.rs
@@ -387,3 +387,151 @@ fn guarded_write_respects_winner() {
"/backup/g.jsonl"
);
}
+
+/// Insights 统计口径:archived=0、prompts 只数主线 user、daily/hourly 按
+/// 本地时区分桶(SQL 'localtime' 与 chrono Local 必须同界)、streak 允许
+/// 今天尚无活动时从昨天起算。日期全固定,不依赖真实时钟。
+#[test]
+fn insights_snapshot_and_streaks() {
+ use chrono::TimeZone;
+ let (_dir, store) = temp_store();
+ let ts = |d: u32, h: u32| {
+ chrono::Local
+ .with_ymd_and_hms(2026, 1, d, h, 30, 0)
+ .single()
+ .expect("unambiguous local time")
+ .timestamp_millis()
+ };
+ let at = |seq: i64, role: Role, t: Option<i64>| IndexUnit {
+ seq,
+ sidechain_id: None,
+ role,
+ timestamp: t,
+ text: format!("msg {seq}"),
+ };
+
+ // s1(claude-code):10/11/12 三连活跃日;含 assistant、sidechain、无 ts 行
+ let mut m1 = meta("claude-code:i1", "insights 甲");
+ m1.model = Some("claude-opus".into());
+ let mut units = vec![
+ at(0, Role::User, Some(ts(10, 9))),
+ at(1, Role::Assistant, Some(ts(10, 9))),
+ at(2, Role::User, Some(ts(11, 14))),
+ at(3, Role::User, Some(ts(11, 14))),
+ at(4, Role::User, Some(ts(12, 22))),
+ at(5, Role::User, None), // 无 ts:计入 prompts,不进 daily/hourly
+ ];
+ units.push(IndexUnit {
+ seq: 6,
+ sidechain_id: Some("side".into()),
+ role: Role::User,
+ timestamp: Some(ts(12, 22)),
+ text: "子代理里的 user 不算 prompt".into(),
+ });
+ store.write_session(&m1, m1.updated_at, &units).unwrap();
+
+ // s2(codex):1/7 孤立活跃日 + 1/11;带 tokens。另有一条 2/5 的
+ // "未来"消息(相对 today=1/13,模拟时钟漂移脏数据):prompts 总数计入,
+ // 分桶/streak/活跃天数全不认——与热力图不画未来格同口径
+ let mut m2 = meta("codex:i2", "insights 乙");
+ m2.agent = AgentId::Codex;
+ m2.file_path = "/tmp/fixtures/i2.jsonl".into();
+ m2.model = Some("gpt-5-codex".into());
+ m2.tokens_used = Some(500);
+ let future = chrono::Local
+ .with_ymd_and_hms(2026, 2, 5, 9, 30, 0)
+ .single()
+ .expect("unambiguous local time")
+ .timestamp_millis();
+ store
+ .write_session(
+ &m2,
+ m2.updated_at,
+ &[
+ at(0, Role::User, Some(ts(7, 9))),
+ at(1, Role::User, Some(ts(11, 14))),
+ at(2, Role::User, Some(future)),
+ ],
+ )
+ .unwrap();
+
+ // s3:archived,任何统计都不该出现
+ let mut m3 = meta("codex:i3", "已归档");
+ m3.agent = AgentId::Codex;
+ m3.file_path = "/tmp/fixtures/i3.jsonl".into();
+ m3.archived = true;
+ store
+ .write_session(&m3, m3.updated_at, &[at(0, Role::User, Some(ts(1, 9)))])
+ .unwrap();
+
+ let today = chrono::NaiveDate::from_ymd_opt(2026, 1, 13).unwrap();
+ let d = store.insights(today).unwrap();
+
+ assert_eq!(d.as_of, today);
+ assert_eq!(d.sessions, 2);
+ assert_eq!(d.prompts, 8, "主线 user:s1 五条(含无 ts)+ s2 三条(含未来)");
+ assert_eq!(d.tokens, 500);
+ assert_eq!(d.project_count, 1);
+ assert_eq!(d.active_days(), 4, "未来日不算活跃天");
+ assert_eq!(
+ d.busiest_day(),
+ Some((chrono::NaiveDate::from_ymd_opt(2026, 1, 11).unwrap(), 3))
+ );
+ assert_eq!((d.current_streak, d.longest_streak), (3, 3));
+ assert_eq!(d.hourly[9], 2);
+ assert_eq!(d.hourly[14], 3);
+ assert_eq!(d.hourly[22], 1);
+ assert_eq!(d.hourly.iter().sum::<i64>(), 6, "无 ts 与未来行不进 hourly");
+ // 2026-01-07 周三、01-10 周六、01-11 周日×3、01-12 周一(周一起始序)
+ assert_eq!(d.weekday, [1, 0, 1, 0, 0, 1, 3]);
+ assert_eq!(d.monthly[0], 6, "全部落在一月");
+ assert_eq!(d.monthly.iter().sum::<i64>(), 6);
+ assert_eq!(
+ d.agents,
+ vec![
+ UsageTally {
+ name: "claude-code".into(),
+ sessions: 1,
+ prompts: 5, // 四条有 ts + 一条无 ts;sidechain 不算
+ tokens: 0,
+ },
+ UsageTally {
+ name: "codex".into(),
+ sessions: 1,
+ prompts: 3, // 榜单 prompts 无日期语义,未来行也计
+ tokens: 500,
+ },
+ ]
+ );
+ assert_eq!(
+ d.projects,
+ vec![UsageTally {
+ name: "proj".into(),
+ sessions: 2,
+ prompts: 8, // 两家主线 user 之和(含无 ts 与未来行)
+ tokens: 500,
+ }]
+ );
+ assert_eq!(
+ d.models,
+ vec![
+ UsageTally {
+ name: "claude-opus".into(),
+ sessions: 1,
+ prompts: 5,
+ tokens: 0,
+ },
+ UsageTally {
+ name: "gpt-5-codex".into(),
+ sessions: 1,
+ prompts: 3,
+ tokens: 500,
+ },
+ ]
+ );
+
+ // 断档超过一天 → current 归零,longest 保留
+ let far = chrono::NaiveDate::from_ymd_opt(2026, 2, 1).unwrap();
+ let d = store.insights(far).unwrap();
+ assert_eq!((d.current_streak, d.longest_streak), (0, 3));
+}
diff --git a/crates/wake/assets/icons/chart-column.svg b/crates/wake/assets/icons/chart-column.svg
new file mode 100644
index 0000000..fd3f20f
--- /dev/null
+++ b/crates/wake/assets/icons/chart-column.svg
@@ -0,0 +1,18 @@
+<!-- @license lucide-static v0.462.0 - ISC -->
+<svg
+ class="lucide lucide-chart-column"
+ xmlns="http://www.w3.org/2000/svg"
+ width="24"
+ height="24"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="2"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+>
+ <path d="M3 3v16a2 2 0 0 0 2 2h16" />
+ <path d="M18 17V9" />
+ <path d="M13 17V5" />
+ <path d="M8 17v-3" />
+</svg>
diff --git a/crates/wake/assets/icons/chevron-left.svg b/crates/wake/assets/icons/chevron-left.svg
new file mode 100644
index 0000000..0f3cb92
--- /dev/null
+++ b/crates/wake/assets/icons/chevron-left.svg
@@ -0,0 +1,15 @@
+<!-- @license lucide-static v0.462.0 - ISC -->
+<svg
+ class="lucide lucide-chevron-left"
+ xmlns="http://www.w3.org/2000/svg"
+ width="24"
+ height="24"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="2"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+>
+ <path d="m15 18-6-6 6-6" />
+</svg>
diff --git a/crates/wake/src/assets.rs b/crates/wake/src/assets.rs
index d266a14..e12ed4b 100644
--- a/crates/wake/src/assets.rs
+++ b/crates/wake/src/assets.rs
@@ -92,6 +92,7 @@ icons!(
"refresh-cw",
"inbox",
"chevron-down",
+ "chevron-left",
"chevron-right",
"loader-circle",
"loader",
@@ -103,6 +104,7 @@ icons!(
"settings",
"plus",
"info",
+ "chart-column",
);
impl AssetSource for Assets {
diff --git a/crates/wake/src/format.rs b/crates/wake/src/format.rs
index 02c908a..964ac2e 100644
--- a/crates/wake/src/format.rs
+++ b/crates/wake/src/format.rs
@@ -42,6 +42,36 @@ pub fn abs_date(ts: i64) -> String {
.unwrap_or_default()
}
+/// epoch ms → "Mar 2026"(Insights 副标题);无效或 ≤0 给空串。
+/// ts→字符串一律住本模块,渲染层不直接碰 chrono
+pub fn month_year(ts: i64) -> String {
+ if ts <= 0 {
+ return String::new();
+ }
+ Local
+ .timestamp_millis_opt(ts)
+ .single()
+ .map(|dt| dt.format("%b %Y").to_string())
+ .unwrap_or_default()
+}
+
+/// 千分位分组(Insights 大数字用):1234567 → "1,234,567"
+pub fn thousands(n: i64) -> String {
+ let digits = n.unsigned_abs().to_string();
+ let mut out = String::with_capacity(digits.len() + digits.len() / 3 + 1);
+ for (i, ch) in digits.chars().enumerate() {
+ if i > 0 && (digits.len() - i) % 3 == 0 {
+ out.push(',');
+ }
+ out.push(ch);
+ }
+ if n < 0 {
+ format!("-{out}")
+ } else {
+ out
+ }
+}
+
pub fn fmt_tokens(n: Option<i64>) -> String {
match n {
None | Some(0) => String::new(),
diff --git a/crates/wake/src/workbench.rs b/crates/wake/src/workbench.rs
index bf8af65..ce890f3 100644
--- a/crates/wake/src/workbench.rs
+++ b/crates/wake/src/workbench.rs
@@ -45,7 +45,9 @@ use wake_core::scanner::{run_scan, ScanEvents, ScanProgress};
use wake_core::services::{exporter, terminal};
use wake_core::watcher::{start_watcher, SessionWatcher};
-use crate::format::{abs_date, expand_tilde, fmt_tokens, one_line, smart_time, tilde_path};
+use crate::format::{
+ abs_date, expand_tilde, fmt_tokens, month_year, one_line, smart_time, thousands, tilde_path,
+};
use crate::settings::{SettingsPage, SettingsView};
use crate::ui::*;
use crate::update::{self, UpdateStatus};
@@ -469,6 +471,17 @@ pub struct Workbench {
detail: Option<DetailState>,
+ /// Insights 页(侧栏底部入口):打开时替换中栏+右栏。与其他导航目的地
+ /// 互斥(侧栏单选模型);数据在 open/refresh 时后台重算,Rc 免深拷贝
+ insights_open: bool,
+ insights: Option<Rc<InsightsData>>,
+ insights_loading: bool,
+ insights_range: InsightsRange,
+ /// 三个榜单各自的度量档,按 UsageBoard 序数索引
+ insights_metrics: [InsightsMetric; 3],
+ /// 进行中的统计查询;新查询覆盖旧值即取消,扫描风暴下不堆积读锁竞争
+ insights_task: Option<Task<()>>,
+
scan_events: Arc<dyn ScanEvents>,
watcher: Option<SessionWatcher>,
/// 终端 id → 提取好的应用图标 png(后台 JXA 提取,详情页 Open In 用)
@@ -478,6 +491,118 @@ pub struct Workbench {
_subs: Vec<Subscription>,
}
+/// Insights 分布图的维度(‹ › 循环切换)。数据三份都在 InsightsData 里,
+/// 切换是纯视图状态,不触发重查
+#[derive(Clone, Copy, PartialEq, Eq)]
+enum InsightsRange {
+ Hour,
+ Weekday,
+ Month,
+}
+
+impl InsightsRange {
+ fn title(self) -> &'static str {
+ match self {
+ Self::Hour => "By hour",
+ Self::Weekday => "By weekday",
+ Self::Month => "By month",
+ }
+ }
+
+ fn prev(self) -> Self {
+ match self {
+ Self::Hour => Self::Month,
+ Self::Weekday => Self::Hour,
+ Self::Month => Self::Weekday,
+ }
+ }
+
+ fn next(self) -> Self {
+ match self {
+ Self::Hour => Self::Weekday,
+ Self::Weekday => Self::Month,
+ Self::Month => Self::Hour,
+ }
+ }
+}
+
+/// 榜单(Agents/Top projects/Models)的度量维度,‹ › 循环切换、每个榜单
+/// 各自记忆档位。Tokens 只在组内有人报过用量时进入循环——tokens=0 语义
+/// 是"不报"而非"用了 0"
+#[derive(Clone, Copy, PartialEq, Eq)]
+enum InsightsMetric {
+ Sessions,
+ Prompts,
+ Tokens,
+}
+
+impl InsightsMetric {
+ fn caption(self) -> &'static str {
+ match self {
+ Self::Sessions => "Sessions",
+ Self::Prompts => "Prompts",
+ Self::Tokens => "Tokens",
+ }
+ }
+
+ fn value(self, u: &UsageTally) -> i64 {
+ match self {
+ Self::Sessions => u.sessions,
+ Self::Prompts => u.prompts,
+ Self::Tokens => u.tokens,
+ }
+ }
+
+ fn display(self, u: &UsageTally) -> String {
+ match self {
+ Self::Tokens => fmt_tokens(Some(u.tokens)),
+ _ => thousands(self.value(u)),
+ }
+ }
+}
+
+/// 三个榜单的静态规格。`Workbench::insights_metrics` 按其序数索引各自
+/// 记忆档位——同一个渲染方法靠它读写自己的状态,不必外传 setter
+#[derive(Clone, Copy)]
+enum UsageBoard {
+ Agents,
+ Projects,
+ Models,
+}
+
+impl UsageBoard {
+ fn title(self) -> &'static str {
+ match self {
+ Self::Agents => "Agents",
+ Self::Projects => "Projects",
+ Self::Models => "Models",
+ }
+ }
+
+ fn arrow_id(self) -> &'static str {
+ match self {
+ Self::Agents => "agents-arrow",
+ Self::Projects => "projects-arrow",
+ Self::Models => "models-arrow",
+ }
+ }
+
+ /// Agents 全量列出(总共十四家);项目/模型长尾长,取前 6
+ fn limit(self) -> usize {
+ match self {
+ Self::Agents => usize::MAX,
+ _ => 6,
+ }
+ }
+
+ fn name_w(self) -> Pixels {
+ match self {
+ Self::Models => px(176.),
+ _ => px(128.),
+ }
+ }
+}
+
/// Settings/Locations 的一行(= 一个数据源路径)。文本字段用 SharedString,
/// 让跨窗口快照与菜单闭包的 clone 只做引用计数。
#[derive(Clone)]
@@ -640,6 +765,12 @@ impl Workbench {
palette_input,
_palette_search_task: None,
detail: None,
+ insights_open: false,
+ insights: None,
+ insights_loading: false,
+ insights_range: InsightsRange::Hour,
+ insights_metrics: [InsightsMetric::Sessions; 3],
+ insights_task: None,
scan_events,
watcher,
terminal_icons: HashMap::new(),
@@ -714,9 +845,54 @@ impl Workbench {
self.agent_counts = counts;
self.projects = self.store.list_projects().unwrap_or_default();
self.starred_count = self.store.starred_count().unwrap_or(0);
+ // Insights 打开着就顺带重算:扫描增量/收藏变更等一切走 refresh 的
+ // 路径都会让页面数据跟上,不设第二条失效通道
+ self.reload_insights(cx);
cx.notify();
}
+ /// 侧栏底部入口。再点一次(或点任意导航行)退回会话列表
+ fn toggle_insights(&mut self, cx: &mut Context<Self>) {
+ if self.insights_open {
+ self.insights_open = false;
+ cx.notify();
+ return;
+ }
+ self.insights_open = true;
+ // 互斥单选:Insights 是独立目的地,退出时落回 All Sessions
+ self.selected_agent = None;
+ self.selected_project = None;
+ self.favorite_only = false;
+ self.refresh(cx);
+ }
+
+ /// messages 全表分桶几十毫秒量级,走后台;已有数据时静默换新不闪 loading。
+ /// 扫描进行中 Changed 事件每秒都来,有旧数据就先按住——终态 Progress
+ /// 会补最后一次;新任务覆盖 insights_task 即取消旧查询,不堆积读锁竞争
+ fn reload_insights(&mut self, cx: &mut Context<Self>) {
+ if !self.insights_open {
+ return;
+ }
+ if self.scan.scanning && self.insights.is_some() {
+ return;
+ }
+ self.insights_loading = self.insights.is_none();
+ let store = self.store.clone();
+ let task =
+ cx.background_spawn(async move { store.insights(chrono::Local::now().date_naive()) });
+ self.insights_task = Some(cx.spawn(async move |this, cx| {
+ let data = task.await;
+ this.update(cx, |this, cx| {
+ if let Ok(data) = data {
+ this.insights = Some(Rc::new(data));
+ }
+ this.insights_loading = false;
+ cx.notify();
+ })
+ .ok();
+ }));
+ }
+
/// 手动全量重扫(菜单 File → Refresh Sessions,⌘R)。刷新中忽略重复触发。
/// 扫描在后台进行,侧栏持续显示进度;浏览、搜索和阅读不被阻断。
fn refresh_sessions(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
@@ -1604,6 +1780,10 @@ impl Workbench {
self.pending_rescan = false;
self.kick_incremental_scan(cx);
}
+ // 扫描期间 reload_insights 被按住(见其注释),终态补最后一次
+ if !self.scan.scanning {
+ self.reload_insights(cx);
+ }
cx.notify();
note
}
@@ -1968,13 +2148,26 @@ impl Workbench {
.detach();
}
+ /// 侧栏目的地互斥的唯一写入点:三个筛选字段与"离开 Insights"一起落,
+ /// 每个导航行只算自己的目标值——新目的地不必再逐个 listener 补互斥
+ fn set_scope(
+ &mut self,
+ agent: Option<AgentId>,
+ project: Option<String>,
+ favorite: bool,
+ cx: &mut Context<Self>,
+ ) {
+ self.selected_agent = agent;
+ self.selected_project = project;
+ self.favorite_only = favorite;
+ self.insights_open = false;
+ self.refresh(cx);
+ }
+
/// 清空过滤回 All Sessions 视图(侧栏点击与搜索打开共用;
/// 已在 All Sessions 时 refresh 幂等,微秒级)
fn show_all_sessions(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
- self.selected_agent = None;
- self.selected_project = None;
- self.favorite_only = false;
- self.refresh(cx);
+ self.set_scope(None, None, false, cx);
}
/// 搜索命中打开:侧栏切回 All Sessions(搜索是全库范围,过滤视图下
@@ -2220,8 +2413,10 @@ impl Workbench {
fn render_sidebar(&self, window: &Window, cx: &Context<Self>) -> impl IntoElement {
let theme = cx.theme();
- let all_active =
- self.selected_agent.is_none() && self.selected_project.is_none() && !self.favorite_only;
+ let all_active = self.selected_agent.is_none()
+ && self.selected_project.is_none()
+ && !self.favorite_only
+ && !self.insights_open;
// 常态沉默,仅刷新中/监听失效时出现;None 时状态栏整行不渲染。
// 文案在此按 scan 现算,不另存字段——存下来就会有第二个写入点要维护
let note = if self.scan.scanning {
@@ -2374,12 +2569,10 @@ impl Workbench {
self.favorite_only,
RowLevel::Primary,
cx.listener(|this, _, _window, cx| {
- this.favorite_only = !this.favorite_only;
- if this.favorite_only {
- this.selected_agent = None;
- this.selected_project = None;
- }
- this.refresh(cx);
+ // 取消收藏过滤时 agent/project 必已是 None(互斥),
+ // 两个方向都归 set_scope
+ let favorite = !this.favorite_only;
+ this.set_scope(None, None, favorite, cx);
}),
cx,
)),
@@ -2415,14 +2608,12 @@ impl Workbench {
self.selected_agent == Some(agent),
RowLevel::Sub,
cx.listener(move |this, _, _window, cx| {
- this.selected_agent = if this.selected_agent == Some(agent) {
+ let next = if this.selected_agent == Some(agent) {
None
} else {
Some(agent)
};
- this.selected_project = None;
- this.favorite_only = false;
- this.refresh(cx);
+ this.set_scope(next, None, false, cx);
}),
cx,
)
@@ -2449,16 +2640,14 @@ impl Workbench {
self.selected_project.as_deref() == Some(p.path.as_str()),
RowLevel::Sub,
cx.listener(move |this, _, _window, cx| {
- this.selected_project = if this.selected_project.as_deref()
+ let next = if this.selected_project.as_deref()
== Some(path.as_str())
{
None
} else {
Some(path.clone())
};
- this.selected_agent = None;
- this.favorite_only = false;
- this.refresh(cx);
+ this.set_scope(None, next, false, cx);
}),
cx,
)
@@ -2489,6 +2678,22 @@ impl Workbench {
.items_center()
.justify_end()
.gap(SPACE_XS)
+ .child(sidebar_tool_btn(
+ "insights",
+ "Insights",
+ true,
+ // 页面打开时图标点亮 primary(显式设色后不被
+ // hover 的容器 text_color 覆盖)
+ {
+ let mut ic = icon("icons/chart-column.svg").with_size(px(14.));
+ if self.insights_open {
+ ic = ic.text_color(theme.primary);
+ }
+ ic.into_any_element()
+ },
+ cx.listener(|this, _, _window, cx| this.toggle_insights(cx)),
+ cx,
+ ))
.child(sidebar_tool_btn(
"settings",
"Settings",
@@ -2864,6 +3069,304 @@ impl Workbench {
.into_any_element()
}
+ // ---------------- Insights ----------------
+
+ /// Insights 整页(替换中栏+右栏)。头部沿用中栏 88px 标题节奏兼窗口
+ /// 拖拽区;内容 720px 阅读宽居中,区块只用留白与组头分隔,不做卡片墙
+ fn render_insights(&self, cx: &Context<Self>) -> AnyElement {
+ let theme = cx.theme();
+ // 副标题只说 "Since {首会话月份}"(用户定稿);拿不到时间时回落默认句
+ let subtitle: SharedString = match &self.insights {
+ Some(d) if d.sessions > 0 => match month_year(d.first_ts) {
+ my if my.is_empty() => "Your coding agent activity".into(),
+ my => format!("Since {my}").into(),
+ },
+ _ => "Your coding agent activity".into(),
+ };
+
+ let body: AnyElement = match &self.insights {
+ Some(d) if d.sessions > 0 => self.render_insights_content(d, cx),
+ _ if self.insights_loading => div()
+ .flex_1()
+ .flex()
+ .items_center()
+ .justify_center()
+ .child(Spinner::new())
+ .into_any_element(),
+ _ => v_flex()
+ .flex_1()
+ .items_center()
+ .justify_center()
+ .child(empty_state_card(
+ "icons/chart-column.svg",
+ px(58.),
+ px(24.),
+ "No activity yet",
+ "Refresh sessions to see your activity here.",
+ cx,
+ ))
+ .into_any_element(),
+ };
+
+ v_flex()
+ .flex_1()
+ .min_w_0()
+ .h_full()
+ .bg(theme.background)
+ .child(
+ v_flex()
+ .id("insights-header")
+ .w_full()
+ .h(LIBRARY_IDENTITY_HEIGHT)
+ .flex_shrink_0()
+ .window_control_area(WindowControlArea::Drag)
+ .px(SPACE_XXL)
+ .justify_center()
+ .child(
+ v_flex()
+ .gap(px(2.))
+ .child(
+ div()
+ .text_size(FONT_TITLE)
+ .font_semibold()
+ .child("Insights"),
+ )
+ .child(
+ div()
+ .text_size(FONT_LABEL)
+ .text_color(theme.muted_foreground)
+ .child(subtitle),
+ ),
+ ),
+ )
+ .child(body)
+ .into_any_element()
+ }
+
+ fn render_insights_content(&self, d: &InsightsData, cx: &Context<Self>) -> AnyElement {
+ let theme = cx.theme();
+
+ // ---- 概览大数字行 ----
+ let stat = |value: String, label: &'static str| {
+ v_flex()
+ .gap(px(2.))
+ .child(
+ div()
+ .text_size(FONT_TITLE)
+ .font_semibold()
+ .text_color(theme.foreground)
+ .child(value),
+ )
+ .child(
+ div()
+ .text_size(FONT_CAPTION)
+ .text_color(theme.muted_foreground)
+ .child(label),
+ )
+ };
+ // 序:Sessions / Tokens / Prompts / Agents / Projects / Active days
+ // (用户钉的)
+ let overview = h_flex()
+ .gap(px(40.))
+ .child(stat(thousands(d.sessions), "Sessions"))
+ .when(d.tokens > 0, |row| {
+ row.child(stat(fmt_tokens(Some(d.tokens)), "Tokens"))
+ })
+ .child(stat(thousands(d.prompts), "Prompts"))
+ .child(stat(thousands(d.agents.len() as i64), "Agents"))
+ .child(stat(thousands(d.project_count), "Projects"))
+ .child(stat(thousands(d.active_days()), "Active days"));
+
+ // ---- 三个榜单的行首/名称(闭包只捕获 Copy 的色值) ----
+ let dark = theme.mode.is_dark();
+ let muted = theme.muted_foreground;
+ let agent_head = move |u: &UsageTally| match AgentId::from_str(&u.name) {
+ Some(agent) => (
+ Some(img(agent.brand_icon(dark)).size(px(15.)).into_any_element()),
+ agent.display_name().into(),
+ ),
+ // 库里出现未知 agent_id(降级防御):无图标裸名,比整行消失诚实
+ None => (None, u.name.clone().into()),
+ };
+ let project_head = move |u: &UsageTally| {
+ (
+ Some(
+ icon("icons/folder.svg")
+ .with_size(px(14.))
+ .text_color(muted)
+ .into_any_element(),
+ ),
+ u.name.clone().into(),
+ )
+ };
+ let model_head = |u: &UsageTally| (None, u.name.clone().into());
+
+ div()
+ .id("insights-scroll")
+ .flex_1()
+ .min_h_0()
+ .overflow_y_scroll()
+ .child(
+ div().w_full().flex().justify_center().px(SPACE_XXL).child(
+ v_flex()
+ .w_full()
+ .max_w(px(720.))
+ .pt(SPACE_SM)
+ .pb(px(40.))
+ .gap(px(32.))
+ .child(overview)
+ .child(
+ v_flex()
+ .gap(SPACE_MD)
+ .child(switch_section_head(
+ "Activity",
+ Some("Prompts you sent, day by day".into()),
+ None,
+ cx,
+ ))
+ .child(render_heatmap(d, cx)),
+ )
+ .child(self.render_distribution_section(d, cx))
+ .child(self.render_usage_section(
+ UsageBoard::Agents,
+ &d.agents,
+ agent_head,
+ cx,
+ ))
+ .when(!d.projects.is_empty(), |col| {
+ col.child(self.render_usage_section(
+ UsageBoard::Projects,
+ &d.projects,
+ project_head,
+ cx,
+ ))
+ })
+ .when(!d.models.is_empty(), |col| {
+ col.child(self.render_usage_section(
+ UsageBoard::Models,
+ &d.models,
+ model_head,
+ cx,
+ ))
+ }),
+ ),
+ )
+ .into_any_element()
+ }
+
+ /// 分布区块:标题右侧 ‹ › 在 hour/weekday/month 三个维度间循环切换
+ fn render_distribution_section(&self, d: &InsightsData, cx: &Context<Self>) -> AnyElement {
+ let range = self.insights_range;
+ let values: &[i64] = match range {
+ InsightsRange::Hour => &d.hourly,
+ InsightsRange::Weekday => &d.weekday,
+ InsightsRange::Month => &d.monthly,
+ };
+ // 峰值只算这一次:caption 点名的与图里高亮的必须是同一根柱
+ let (peak, peak_n) = values
+ .iter()
+ .enumerate()
+ .max_by_key(|(_, n)| **n)
+ .map(|(i, n)| (i, *n))
+ .unwrap_or((0, 0));
+ let arrows = insight_arrows(
+ "dist-arrow",
+ None,
+ cx.listener(move |this, _, _window, cx| {
+ this.insights_range = this.insights_range.prev();
+ cx.notify();
+ }),
+ cx.listener(move |this, _, _window, cx| {
+ this.insights_range = this.insights_range.next();
+ cx.notify();
+ }),
+ cx,
+ );
+ v_flex()
+ .gap(SPACE_MD)
+ .child(switch_section_head(
+ range.title(),
+ Some(dist_caption(range, peak, peak_n).into()),
+ Some(arrows.into_any_element()),
+ cx,
+ ))
+ .child(render_distribution(range, values, peak, cx))
+ .into_any_element()
+ }
+
+ /// 榜单区块(Agents/Projects/Models 同构):‹ 度量名 › 循环切换,行按
+ /// 当前度量降序重排再截断 top-N。可用档位就是一个切片:组内无人报
+ /// token 时 Tokens 不在其中,归一、循环、行过滤都从这一个事实推出
+ fn render_usage_section(
+ &self,
+ board: UsageBoard,
+ rows: &[UsageTally],
+ row_head: impl Fn(&UsageTally) -> (Option<AnyElement>, SharedString),
+ cx: &Context<Self>,
+ ) -> AnyElement {
+ use InsightsMetric::*;
+ let has_tokens = rows.iter().any(|u| u.tokens > 0);
+ // 循环序与概览行同:Sessions / Tokens / Prompts(用户钉的)
+ let avail: &[InsightsMetric] = if has_tokens {
+ &[Sessions, Tokens, Prompts]
+ } else {
+ &[Sessions, Prompts]
+ };
+ let slot = board as usize;
+ // position 找不到 = 存的档位已不可用(如数据刷新后 token 清零),
+ // 落回首档;循环即可用档位上的环形下标
+ let i = avail
+ .iter()
+ .position(|m| *m == self.insights_metrics[slot])
+ .unwrap_or(0);
+ let metric = avail[i];
+ let to_prev = avail[(i + avail.len() - 1) % avail.len()];
+ let to_next = avail[(i + 1) % avail.len()];
+ let arrows = insight_arrows(
+ board.arrow_id(),
+ Some(metric.caption().into()),
+ cx.listener(move |this, _, _window, cx| {
+ this.insights_metrics[slot] = to_prev;
+ cx.notify();
+ }),
+ cx.listener(move |this, _, _window, cx| {
+ this.insights_metrics[slot] = to_next;
+ cx.notify();
+ }),
+ cx,
+ );
+ let mut sorted: Vec<&UsageTally> = rows
+ .iter()
+ // Tokens 档只列报了用量的组:空条不是"用了 0",是没数据
+ .filter(|u| metric != Tokens || u.tokens > 0)
+ .collect();
+ // stable sort:平局保持 SQL 的 sessions desc + 名称序
+ sorted.sort_by_key(|u| std::cmp::Reverse(metric.value(u)));
+ sorted.truncate(board.limit());
+ let max = sorted.iter().map(|u| metric.value(u)).max().unwrap_or(1);
+ v_flex()
+ .gap(SPACE_MD)
+ .child(switch_section_head(
+ board.title(),
+ None,
+ Some(arrows.into_any_element()),
+ cx,
+ ))
+ .children(sorted.into_iter().map(|u| {
+ let (lead, label) = row_head(u);
+ usage_bar_row(
+ lead,
+ label,
+ metric.display(u).into(),
+ metric.value(u),
+ max,
+ board.name_w(),
+ cx,
+ )
+ }))
+ .into_any_element()
+ }
+
fn render_detail(&self, _window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
let theme = cx.theme();
let Some(detail) = &self.detail else {
@@ -2873,25 +3376,17 @@ impl Workbench {
.items_center()
.justify_center()
.bg(theme.background)
- .child(
- div()
- .w(px(360.))
- .px(SPACE_XXL)
- .py(SPACE_XXL)
- .rounded(theme.radius_lg)
- .bg(theme.popover)
- .child(empty_state(
- "icons/message-square.svg",
- px(58.),
- px(26.),
- "No session selected",
- format!(
- "Pick one from the list, or press {} to search.",
- search_key_hint()
- ),
- cx,
- )),
- )
+ .child(empty_state_card(
+ "icons/message-square.svg",
+ px(58.),
+ px(26.),
+ "No session selected",
+ format!(
+ "Pick one from the list, or press {} to search.",
+ search_key_hint()
+ ),
+ cx,
+ ))
.into_any_element();
};
let meta = &detail.meta;
@@ -3415,6 +3910,473 @@ enum RowLead {
Brand(&'static str),
}
+// ---------------- Insights 附件 ----------------
+
+/// 可切换区块共用的 ‹ › ghost 按钮组。label 显示在两键中间(当前档位名),
+/// 定宽居中让按钮位置不随文本长短跳动;分布图的档位名就是区块标题,传 None
+fn insight_arrows(
+ id: &'static str,
+ label: Option<SharedString>,
+ on_prev: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
+ on_next: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
+ cx: &App,
+) -> impl IntoElement {
+ let theme = cx.theme();
+ h_flex()
+ .flex_shrink_0()
+ .gap(SPACE_XS)
+ .child(
+ Button::new((id, 0usize))
+ .ghost()
+ .rounded(RADIUS_BUTTON)
+ .icon(icon("icons/chevron-left.svg").with_size(px(14.)))
+ .tooltip("Previous view")
+ .on_click(on_prev),
+ )
+ .when_some(label, |row, label| {
+ row.child(
+ div()
+ .w(px(64.))
+ .flex()
+ .justify_center()
+ .whitespace_nowrap()
+ .text_size(FONT_CAPTION)
+ .text_color(theme.muted_foreground)
+ .child(label),
+ )
+ })
+ .child(
+ Button::new((id, 1usize))
+ .ghost()
+ .rounded(RADIUS_BUTTON)
+ .icon(icon("icons/chevron-right.svg").with_size(px(14.)))
+ .tooltip("Next view")
+ .on_click(on_next),
+ )
+}
+
+/// Insights 区块头:标题 + 可选 caption + 可选右上角切换按钮组。
+/// caption 有则双行(按钮对齐首行),无则单行居中对齐
+fn switch_section_head(
+ title: &'static str,
+ caption: Option<SharedString>,
+ arrows: Option<AnyElement>,
+ cx: &App,
+) -> impl IntoElement {
+ let theme = cx.theme();
+ let two_line = caption.is_some();
+ h_flex()
+ .justify_between()
+ .map(|head| {
+ if two_line {
+ head.items_start()
+ } else {
+ head.items_center()
+ }
+ })
+ .child(
+ v_flex()
+ .gap(px(2.))
+ .child(
+ div()
+ .text_size(FONT_BODY)
+ .font_semibold()
+ .text_color(theme.foreground)
+ .child(title),
+ )
+ .when_some(caption, |head, caption| {
+ head.child(
+ div()
+ .text_size(FONT_CAPTION)
+ .text_color(theme.muted_foreground)
+ .child(caption),
+ )
+ }),
+ )
+ .when_some(arrows, |head, arrows| head.child(arrows))
+}
+
+/// 榜单行:行首 + 名称 + 轨道条 + 计数。value_text 与 count 分开传:
+/// Tokens 档显示 "1.2M" 缩写,条仍按原值归一
+fn usage_bar_row(
+ lead: Option<AnyElement>,
+ label: SharedString,
+ value_text: SharedString,
+ count: i64,
+ max: i64,
+ name_w: Pixels,
+ cx: &App,
+) -> impl IntoElement {
+ let theme = cx.theme();
+ let frac = (count as f32 / max.max(1) as f32).clamp(0., 1.);
+ h_flex()
+ .h(px(22.))
+ .gap(SPACE_SM)
+ .items_center()
+ .when_some(lead, |row, lead| {
+ row.child(
+ div()
+ .w(px(15.))
+ .flex_shrink_0()
+ .flex()
+ .items_center()
+ .justify_center()
+ .child(lead),
+ )
+ })
+ .child(
+ div()
+ .w(name_w)
+ .flex_shrink_0()
+ .min_w_0()
+ .text_size(FONT_CAPTION)
+ .text_color(theme.foreground)
+ .truncate()
+ .child(label),
+ )
+ .child(
+ div()
+ .flex_1()
+ .h(px(6.))
+ .rounded_full()
+ .bg(theme.muted)
+ .child(
+ div()
+ .h_full()
+ .w(relative(frac))
+ .rounded_full()
+ .bg(theme.primary),
+ ),
+ )
+ .child(
+ div()
+ .w(px(56.))
+ .flex_shrink_0()
+ .flex()
+ .justify_end()
+ .text_size(FONT_LABEL)
+ .text_color(theme.muted_foreground)
+ .child(value_text),
+ )
+}
+
+fn prompts_label(n: i64) -> String {
+ match n {
+ 0 => "No prompts".into(),
+ 1 => "1 prompt".into(),
+ n => format!("{} prompts", thousands(n)),
+ }
+}
+
+/// 0–23 时 → "12 AM" / "2 PM" 形制(与 smart_time 的 12 小时制一致)
+fn hour_label(h: usize) -> String {
+ match h % 24 {
+ 0 => "12 AM".into(),
+ 12 => "12 PM".into(),
+ h if h < 12 => format!("{h} AM"),
+ h => format!("{} PM", h - 12),
+ }
+}
+
+const DOW_SHORT: [&str; 7] = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
+const DOW_PLURAL: [&str; 7] = [
+ "Mondays",
+ "Tuesdays",
+ "Wednesdays",
+ "Thursdays",
+ "Fridays",
+ "Saturdays",
+ "Sundays",
+];
+const MONTH_SHORT: [&str; 12] = [
+ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
+];
+const MONTH_FULL: [&str; 12] = [
+ "January",
+ "February",
+ "March",
+ "April",
+ "May",
+ "June",
+ "July",
+ "August",
+ "September",
+ "October",
+ "November",
+ "December",
+];
+
+/// peak 由 render_distribution_section 算一次传入——caption 点名的与
+/// 图里高亮的必须是同一根柱
+fn dist_caption(range: InsightsRange, peak: usize, peak_n: i64) -> String {
+ if peak_n == 0 {
+ return "When you talk to your agents".into();
+ }
+ match range {
+ InsightsRange::Hour => format!("Most active around {}", hour_label(peak)),
+ InsightsRange::Weekday => format!("Most active on {}", DOW_PLURAL[peak]),
+ InsightsRange::Month => format!("Most active in {}", MONTH_FULL[peak]),
+ }
+}
+
+/// 竖柱分布图(hour 24 根 / weekday 7 根 / month 12 根共用)。峰值柱全饱和
+/// primary,其余 55%;零值留 2px muted 底座维持基线连续。宽柱配大缝:
+/// 柱数越少 gap 越大,免得 7 根 90px 宽柱糊成一片
+fn render_distribution(range: InsightsRange, values: &[i64], peak: usize, cx: &App) -> AnyElement {
+ let theme = cx.theme();
+ let max = values.iter().copied().max().unwrap_or(0).max(1);
+ let gap = match range {
+ InsightsRange::Hour => px(4.),
+ InsightsRange::Weekday => px(8.),
+ InsightsRange::Month => px(6.),
+ };
+ const CHART_H: f32 = 72.;
+ v_flex()
+ .gap(px(6.))
+ .child(
+ h_flex()
+ .items_end()
+ .gap(gap)
+ .h(px(CHART_H))
+ .children((0..values.len()).map(|i| {
+ let n = values[i];
+ let (height, bg) = if n == 0 {
+ (px(2.), theme.muted)
+ } else {
+ let frac = (n as f32 / max as f32).max(0.05);
+ (
+ px((frac * CHART_H).max(3.)),
+ if i == peak {
+ theme.primary
+ } else {
+ theme.primary.opacity(0.55)
+ },
+ )
+ };
+ let label: SharedString = match range {
+ InsightsRange::Hour => format!(
+ "{} · {} – {}",
+ prompts_label(n),
+ hour_label(i),
+ hour_label(i + 1)
+ ),
+ InsightsRange::Weekday => {
+ format!("{} · {}", prompts_label(n), DOW_PLURAL[i])
+ }
+ InsightsRange::Month => {
+ format!("{} · {}", prompts_label(n), MONTH_FULL[i])
+ }
+ }
+ .into();
+ div()
+ .id(("dist", i))
+ .flex_1()
+ .h(height)
+ .rounded(px(2.))
+ .bg(bg)
+ .tooltip(move |window, cx| {
+ gpui_component::tooltip::Tooltip::new(label.clone()).build(window, cx)
+ })
+ })),
+ )
+ .child(
+ // 刻度行:与柱同宽的等分槽。hour 只标 6 小时锚点(文字溢出槽宽
+ // 不裁剪),weekday/month 每柱都标
+ h_flex()
+ .gap(gap)
+ .text_size(FONT_LABEL)
+ .text_color(theme.muted_foreground)
+ .children((0..values.len()).map(|i| {
+ let tick: Option<&'static str> = match range {
+ InsightsRange::Hour => None,
+ InsightsRange::Weekday => Some(DOW_SHORT[i]),
+ InsightsRange::Month => Some(MONTH_SHORT[i]),
+ };
+ div().flex_1().whitespace_nowrap().map(|slot| match tick {
+ // 每柱都有标签时与柱居中;hour 的稀疏锚点靠左
+ Some(t) => slot.flex().justify_center().child(t),
+ None if i % 6 == 0 => slot.child(hour_label(i)),
+ None => slot,
+ })
+ })),
+ )
+ .into_any_element()
+}
+
+/// 热力图强度阶梯(primary 不透明度四档)。图例与格子同引本表,
+/// 调阶只改这里
+const HEAT: [f32; 4] = [0.25, 0.5, 0.75, 1.];
+
+/// GitHub 风活跃热力图:53 周 × 7 天(周一起始),最右列为本周(d.as_of,
+/// 与 streak 同一天,渲染层不再读时钟)。格子 9px:网格总宽 26 + 3 +
+/// 53×9 + 52×3 = 662,必须收进最小窗口的内容宽 668(940 − 224 侧栏 −
+/// 两侧 24 padding)——10px 格的 715 会在最小窗口被裁掉右缘
+/// (2026-08-27 Codex review)。daily 升序,二分出窗口后填定长数组——
+/// 渲染路径零哈希零日期运算;tooltip 文案 hover 才格式化
+fn render_heatmap(d: &InsightsData, cx: &App) -> AnyElement {
+ use chrono::Datelike as _;
+ let theme = cx.theme();
+ let today = d.as_of;
+ let this_monday = today - chrono::Days::new(today.weekday().num_days_from_monday() as u64);
+ let start = this_monday - chrono::Days::new(52 * 7);
+ let today_ix = (today - start).num_days();
+
+ const DAYS: usize = 53 * 7;
+ let mut window = [0i64; DAYS];
+ let mut heat_max = 1i64;
+ let from = d.daily.partition_point(|(day, _)| *day < start);
+ for &(day, n) in &d.daily[from..] {
+ let ix = (day - start).num_days();
+ if (0..DAYS as i64).contains(&ix) {
+ window[ix as usize] = n;
+ heat_max = heat_max.max(n);
+ }
+ }
+ let heat_color = |n: i64| -> Hsla {
+ if n == 0 {
+ return theme.muted;
+ }
+ let quartile = ((n as f32 / heat_max as f32) * 4.).ceil().clamp(1., 4.) as usize;
+ theme.primary.opacity(HEAT[quartile - 1])
+ };
+ const CELL: f32 = 9.;
+ const GAP: f32 = 3.;
+ const STEP: f32 = CELL + GAP;
+ const DOW_W: f32 = 26.;
+
+ // 月份标签:该列周一进入新月份时标注(与前一周比,首列同规则,
+ // 相邻标签由此天然隔开 ≥4 列不会叠)
+ let mut months = div()
+ .relative()
+ .w_full()
+ .h(px(14.))
+ .text_size(FONT_LABEL)
+ .text_color(theme.muted_foreground);
+ for c in 0..53u64 {
+ let monday = start + chrono::Days::new(c * 7);
+ if monday.month() != (monday - chrono::Days::new(7)).month() {
+ months = months.child(
+ div()
+ .absolute()
+ .top_0()
+ .left(px(DOW_W + GAP + c as f32 * STEP))
+ .child(MONTH_SHORT[monday.month0() as usize]),
+ );
+ }
+ }
+
+ // 星期标签列:行 r 的格子 y = r×STEP,文字行高 ≈13px,
+ // (CELL−13)/2 = −2 光学对行
+ let dow_col = div()
+ .relative()
+ .w(px(DOW_W))
+ .h(px(7. * STEP - GAP))
+ .flex_shrink_0()
+ .text_size(FONT_LABEL)
+ .text_color(theme.muted_foreground)
+ .children([0usize, 2, 4].map(|r| {
+ div()
+ .absolute()
+ .top(px(r as f32 * STEP - 2.))
+ .left_0()
+ .child(DOW_SHORT[r])
+ }));
+
+ let mut grid = h_flex().gap(px(GAP)).items_start().child(dow_col);
+ for c in 0..53usize {
+ let mut col = v_flex().gap(px(GAP));
+ for r in 0..7usize {
+ let ix = c * 7 + r;
+ if ix as i64 > today_ix {
+ col = col.child(div().size(px(CELL)));
+ continue;
+ }
+ let n = window[ix];
+ col = col.child(
+ div()
+ .id(("hm", ix))
+ .size(px(CELL))
+ .rounded(px(2.))
+ .bg(heat_color(n))
+ // 只捕获 Copy 的 (start, ix, n),hover 到的那格才格式化
+ .tooltip(move |window, cx| {
+ let day = start + chrono::Days::new(ix as u64);
+ let label = format!("{} · {}", prompts_label(n), day.format("%b %-d, %Y"));
+ gpui_component::tooltip::Tooltip::new(SharedString::from(label))
+ .build(window, cx)
+ }),
+ );
+ }
+ grid = grid.child(col);
+ }
+
+ // 底注:streak/最忙一天(左) + Less…More 图例(右)
+ let mut notes: Vec<String> = Vec::new();
+ if d.current_streak > 0 {
+ notes.push(format!("{}-day streak", d.current_streak));
+ }
+ if d.longest_streak > 0 {
+ notes.push(format!("Longest {} days", d.longest_streak));
+ }
+ if let Some((day, n)) = d.busiest_day() {
+ notes.push(format!(
+ "Busiest {} ({})",
+ day.format("%b %-d"),
+ prompts_label(n)
+ ));
+ }
+ let legend = h_flex()
+ .justify_between()
+ .items_center()
+ .text_size(FONT_LABEL)
+ .text_color(theme.muted_foreground)
+ .child(div().min_w_0().truncate().child(notes.join(" · ")))
+ .child(
+ h_flex()
+ .gap(px(GAP))
+ .items_center()
+ .flex_shrink_0()
+ .child("Less")
+ .children(std::iter::once(0.).chain(HEAT).map(|a: f32| {
+ div().size(px(CELL)).rounded(px(2.)).bg(if a == 0. {
+ theme.muted
+ } else {
+ theme.primary.opacity(a)
+ })
+ }))
+ .child("More"),
+ );
+
+ v_flex()
+ .gap(px(6.))
+ .child(months)
+ .child(grid)
+ .child(div().pt(SPACE_XS).child(legend))
+ .into_any_element()
+}
+
+/// 阅读材质空态卡(360px `popover` 圆角面):详情空态与 Insights 空态共用,
+/// 形制齐步走
+fn empty_state_card(
+ icon_path: &'static str,
+ circle: Pixels,
+ icon_size: Pixels,
+ title: impl Into<SharedString>,
+ caption: impl Into<SharedString>,
+ cx: &App,
+) -> Div {
+ let theme = cx.theme();
+ div()
+ .w(px(360.))
+ .px(SPACE_XXL)
+ .py(SPACE_XXL)
+ .rounded(theme.radius_lg)
+ .bg(theme.popover)
+ .child(empty_state(
+ icon_path, circle, icon_size, title, caption, cx,
+ ))
+}
+
/// 空态占位(⌘K 初始 / 列表空 / 详情未选中共用):muted 圆底图标 + 标题 + 说明。
/// 圆径/图标径按场景传入,字阶与间距固定,保证三处视觉一致。
fn empty_state(
@@ -3810,8 +4772,15 @@ impl Render for Workbench {
h_flex()
.size_full()
.child(self.render_sidebar(window, cx))
- .child(self.render_session_list(cx))
- .child(self.render_detail(window, cx)),
+ // Insights 是整页目的地:替换中栏+右栏,侧栏导航保持在场
+ .map(|this| {
+ if self.insights_open {
+ this.child(self.render_insights(cx))
+ } else {
+ this.child(self.render_session_list(cx))
+ .child(self.render_detail(window, cx))
+ }
+ }),
)
.children(Root::render_dialog_layer(window, cx))
.children(Root::render_notification_layer(window, cx))