All your AI agent sessions in one place — browse, search, resume. Rust + GPUI.
Rust
fix: accumulate Pi-family token usage and refresh existing indexes (#34)
Corey Chiu02716284b89e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4fd7694..c51ca8d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,7 @@- New: session cleanup from the sidebar — filter by date, agent or project, sort by size, and preview before moving session files to the system trash. Includes cleanup history.- New: Copy Session Path in the session detail toolbar copies the source file path directly, with inline confirmation. Database-backed sessions copy the shared database path; remote sessions copy the local mirror path, as indicated in the tooltip (#33, thanks @ItsRyanWu)+- Fix: Pi and Oh My Pi token usage now adds up each assistant call instead of keeping only the last one, including calls with no visible reply. The shared OpenClaw reader also adds up the calls in its active transcript. Existing indexes are recalculated once after upgrading (#34, thanks @AwadYoo for the report and proposed fix in #35)## [0.6.7] — 2026-09-15diff --git a/README.md b/README.mdindex 87515de..595f94c 100644--- a/README.md+++ b/README.md@@ -57,6 +57,8 @@ Codex writes its background threads — the guardian auto-review, `/review`, comCursor keeps two stores. A chat that has a full transcript under `~/.cursor/projects` is read from there (the transcript knows the project folder); chats that only live in Cursor's own database — older ones, or Cursor versions that leave nothing but a `turn_ended` marker in the transcript — are read from `state.vscdb`. Older IDE chats that Cursor stored without a workspace show up under *Unknown project*.+Token statistics depend on the usage recorded by each agent. Qoder CLI transcripts that contain only zero token counts leave token usage unknown in Wake, even when they include Credits or a context usage ratio. Those values measure different things and are not converted into tokens; the sessions remain visible in the Sessions and Prompts views of Insights.+Windsurf and Trae encrypt their local data; Amp, Factory (Droid), and Warp keep sessions in the cloud — none of those are supported. Reasonix stores sessions locally but hasn't been mapped yet.## Remote hostsdiff --git a/crates/wake-core/src/adapters/pi_format.rs b/crates/wake-core/src/adapters/pi_format.rsindex 0a9e36a..02dbfac 100644--- a/crates/wake-core/src/adapters/pi_format.rs+++ b/crates/wake-core/src/adapters/pi_format.rs@@ -89,6 +89,17 @@ impl PiRender {}fn push_assistant(&mut self, msg: &Value, content: &Value, ts: i64) {+ // Each assistant entry reports one API call, including cache tokens.+ // Account before display filtering: empty/thinking-only calls can still+ // consume tokens even when they produce no visible transcript message.+ if let Some(tokens) = msg+ .get("usage")+ .and_then(|u| u.get("totalTokens"))+ .and_then(Value::as_i64)+ .filter(|tokens| *tokens >= 0)+ {+ self.tokens_used = Some(self.tokens_used.unwrap_or(0).saturating_add(tokens));+ }let parsed = content_parts(content, self.decode_images);let mut tools: Vec<ToolCallView> = Vec::new();let mut thinking = String::new();@@ -125,13 +136,6 @@ impl PiRender {if model.is_some() {self.model = model.clone();}- if let Some(t) = msg- .get("usage")- .and_then(|u| u.get("totalTokens"))- .and_then(Value::as_i64)- {- self.tokens_used = Some(t);- }// 连续 assistant(中间只隔 toolResult)合并成一条,详情页每个回合一条助手消息if !matches!(self.messages.last(), Some(m) if m.role == Role::Assistant) {self.messages.push(text_msg(Role::Assistant, "", ts));@@ -169,3 +173,65 @@ impl PiRender {}}}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ #[test]+ fn tokens_include_hidden_calls_without_adding_transcript_rows() {+ let mut render = PiRender::new(PiRenderOptions::default(), false);+ for (content, tokens) in [+ (json!([{"type": "text", "text": "First reply"}]), 100),+ (json!([]), 20),+ (json!([{"type": "thinking", "thinking": "Hidden"}]), 30),+ (json!([{"type": "text", "text": "Final reply"}]), 200),+ ] {+ render.push(+ &json!({"role": "assistant", "content": content,+ "usage": {"totalTokens": tokens}}),+ 1,+ );+ }+ assert_eq!(render.tokens_used, Some(350));+ assert_eq!(render.messages.len(), 1);+ assert_eq!(render.messages[0].text, "First reply\n\nFinal reply");+ }++ #[test]+ fn missing_invalid_and_zero_usage_preserve_reported_totals() {+ let mut render = PiRender::new(PiRenderOptions::default(), false);+ for usage in [json!(null), json!({}), json!({"totalTokens": -1})] {+ render.push(&json!({"role": "assistant", "usage": usage}), 1);+ }+ assert_eq!(render.tokens_used, None);++ render.push(+ &json!({"role": "assistant", "usage": {"totalTokens": 0}}),+ 1,+ );+ assert_eq!(render.tokens_used, Some(0));+ for usage in [+ json!({"totalTokens": 42}),+ json!(null),+ json!({"totalTokens": -1}),+ json!({"totalTokens": 0}),+ ] {+ render.push(&json!({"role": "assistant", "usage": usage}), 1);+ }+ assert_eq!(render.tokens_used, Some(42));+ }++ #[test]+ fn token_sum_saturates_instead_of_overflowing_on_malformed_usage() {+ let mut render = PiRender::new(PiRenderOptions::default(), false);+ for tokens in [i64::MAX, 1] {+ render.push(+ &json!({"role": "assistant", "usage": {"totalTokens": tokens}}),+ 1,+ );+ }+ assert_eq!(render.tokens_used, Some(i64::MAX));+ }+}diff --git a/crates/wake-core/src/db.rs b/crates/wake-core/src/db.rsindex 7031c95..984baca 100644--- a/crates/wake-core/src/db.rs+++ b/crates/wake-core/src/db.rs@@ -130,10 +130,11 @@ CREATE VIRTUAL TABLE IF NOT EXISTS titles_fts USING fts5();"#;-/// FTS 单元的派生规则版本(`adapters::units_from_messages` 及其上游解析)。改了派生+/// 会话元数据和 FTS 单元的派生规则版本(`adapters::units_from_messages` 及其上游解析)。改了派生/// 规则就换个值:旧库首开时挂 fts_reindex 旗子,下一轮扫描强制重解析全部文件。-/// "1" = 2026-09-14 前(工具段不过滤 Wake 自指),"2" = 过滤自指回声-pub const FTS_FORMAT: &str = "2";+/// "1" = 2026-09-14 前(工具段不过滤 Wake 自指),"2" = 过滤自指回声,+/// "3" = Pi / omp / OpenClaw 累计每次 assistant 调用的 token。+pub const FTS_FORMAT: &str = "3";fn open_conn(path: &Path) -> Result<Connection> {if let Some(dir) = path.parent() {diff --git a/crates/wake-core/tests/adapter_contracts.rs b/crates/wake-core/tests/adapter_contracts.rsindex ec779bd..c078e07 100644--- a/crates/wake-core/tests/adapter_contracts.rs+++ b/crates/wake-core/tests/adapter_contracts.rs@@ -749,6 +749,46 @@ fn qoder_parse_contract() {assert!(rooted.file_ref(&sideagent).is_none());}+#[test]+fn qoder_credits_are_not_reported_as_tokens() {+ setup();+ let adapter = QoderAdapter::new();+ let original = qoder_ref();+ let source = fs::read_to_string(&original.file_path).unwrap();+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("credits-only.jsonl");++ for (has_real_tokens, expected) in [(false, None), (true, Some(40))] {+ let rows: Vec<String> = source+ .lines()+ .map(|line| {+ let mut row: serde_json::Value = serde_json::from_str(line).unwrap();+ if row["type"] == "assistant" {+ let reported = has_real_tokens && row["uuid"] == "q-assistant-2";+ row["message"]["usage"] = serde_json::json!({+ "input_tokens": if reported { 30 } else { 0 },+ "output_tokens": if reported { 10 } else { 0 },+ "cache_creation_input_tokens": 0,+ "cache_read_input_tokens": 0,+ "credits": 1.5362908,+ "context_usage_ratio": 0.1379833+ });+ }+ serde_json::to_string(&row).unwrap()+ })+ .collect();+ fs::write(&path, rows.join("\n")).unwrap();+ let r = fs_ref(AgentId::Qoder, &path, &original.native_id);+ let parsed = adapter.parse_session(&r).unwrap();+ assert_eq!(parsed.meta.tokens_used, expected);+ assert_eq!(parsed.meta.message_count, 4);+ assert_eq!(+ adapter.parse_transcript(&r).unwrap().meta.tokens_used,+ expected+ );+ }+}+#[test]fn qoder_explicit_null_active_leaf_is_empty() {setup();@@ -1408,7 +1448,8 @@ fn pi_parse_contract() {// cwd 来自 session 首行,不反推有损编码目录名assert_eq!(s.meta.project_path, "/Users/tester/Github/wakefx");assert_eq!(s.meta.model.as_deref(), Some("gpt-5.5"));- assert_eq!(s.meta.tokens_used, Some(4300)); // 最后一条 assistant 的 totalTokens+ assert_eq!(s.meta.tokens_used, Some(4242 + 4300)); // 两次调用,含合并前的工具调用+ assert_eq!(t.meta.tokens_used, s.meta.tokens_used);assert_eq!(s.meta.message_count, 2);assert_eq!(s.meta.created_at, ms("2026-08-06T10:00:00Z"));assert_eq!(s.meta.updated_at, ms("2026-08-06T10:00:12Z"));@@ -1447,6 +1488,14 @@ fn pi_parse_contract() {assert_eq!(s2.meta.agent, AgentId::Omp);assert_eq!(s2.meta.key, "omp:66666666-aaaa-bbbb-cccc-000000000006");assert_eq!(s2.meta.title, "Pi 查一下二维码组件的 useEffect() 清理");+ assert_eq!(s2.meta.tokens_used, Some(4242 + 4300));+ assert_eq!(+ omp.parse_transcript(&pi_ref(AgentId::Omp))+ .unwrap()+ .meta+ .tokens_used,+ s2.meta.tokens_used+ );}#[test]@@ -2099,7 +2148,8 @@ fn openclaw_parse_contract() {assert_eq!(s.meta.title, "Node label"); // 无 session_info 时取 node labelassert_eq!(s.meta.project_path, "/Users/tester/Github/wakefx"); // header cwdassert_eq!(s.meta.model.as_deref(), Some("claude-opus-5"));- assert_eq!(s.meta.tokens_used, Some(7300));+ assert_eq!(s.meta.tokens_used, Some(7100 + 7300)); // 活跃分支两次调用之和+ assert_eq!(t.meta.tokens_used, s.meta.tokens_used);assert_eq!(s.meta.source.as_deref(), Some("telegram"));assert_eq!(s.meta.created_at, ms("2026-08-08T09:00:00Z"));assert_eq!(s.meta.updated_at, ms("2026-08-08T09:00:30Z"));@@ -2157,7 +2207,8 @@ fn openclaw_parse_contract() {assert_eq!(s.meta.title, "OpenClaw QR cleanup"); // session_info 压过 sessions.json 的 labelassert_eq!(s.meta.project_path, "/Users/tester/Github/wakefx");assert_eq!(s.meta.model.as_deref(), Some("claude-opus-5"));- assert_eq!(s.meta.tokens_used, Some(5200));+ assert_eq!(s.meta.tokens_used, Some(5100 + 5200));+ assert_eq!(t.meta.tokens_used, s.meta.tokens_used);assert_eq!(s.meta.created_at, ms("2026-08-07T09:00:00Z"));assert_eq!(s.meta.updated_at, ms("2026-08-07T09:00:30Z"));// wibble-entry 是叶:回溯经 u3→c1→a2→r1→a1→u2→u1→i1→m1,死分支 a2-dead 不在链上;diff --git a/crates/wake-core/tests/scanner_finale.rs b/crates/wake-core/tests/scanner_finale.rsindex d7fc7fe..c6cc818 100644--- a/crates/wake-core/tests/scanner_finale.rs+++ b/crates/wake-core/tests/scanner_finale.rs@@ -360,6 +360,48 @@ fn fts_reindex_flag_reprocesses_unchanged_rows_once() {assert_eq!(title(&store), "after");}+#[test]+fn format_two_backfills_pi_tokens_without_source_changes() {+ use wake_core::adapters::pi::PiAdapter;++ let dir = tempfile::tempdir().unwrap();+ let db_path = dir.path().join("tokens.db");+ let adapters: Vec<Box<dyn AgentAdapter>> =+ vec![PiAdapter::new().with_custom_root(common::fixture("pi/agent/sessions"))];+ let r = adapters[0].list_session_files().unwrap().remove(0);+ let mut old = adapters[0].parse_session(&r).unwrap();+ old.meta.tokens_used = Some(4300); // Last call, as stored by format 2.+ {+ let store = Store::open(&db_path).unwrap();+ store+ .write_session(&old.meta, r.mtime_ms, &old.units)+ .unwrap();+ }+ rusqlite::Connection::open(&db_path)+ .unwrap()+ .execute(+ "UPDATE schema_meta SET value = '2' WHERE key = 'fts_format'",+ [],+ )+ .unwrap();++ let store = Arc::new(Store::open(&db_path).unwrap());+ assert!(store.needs_fts_reindex());+ run_scan(&adapters, &store, &Recorder::new(), false).unwrap();+ let updated = store.get_session(&old.meta.key).unwrap().unwrap();+ assert_eq!(updated.tokens_used, Some(4242 + 4300));+ assert_eq!(updated.message_count, old.meta.message_count);+ assert!(!store.needs_fts_reindex());+ drop(store);++ // The version is persisted: neither reopening nor a second scan repeats it.+ let store = Arc::new(Store::open(&db_path).unwrap());+ assert!(!store.needs_fts_reindex());+ let rec = Recorder::new();+ run_scan(&adapters, &store, &rec, false).unwrap();+ assert_eq!(rec.changed(), 0);+}+#[test]fn migration_backfill_retries_after_parse_failure() {let dir = tempfile::tempdir().unwrap();