Skip to content

Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.

fix(host): replace full usage readings instead of merging them

forwardxue9980b3bcdf0
diff --git a/host/src/usage/antigravity.rs b/host/src/usage/antigravity.rs
index acd4ce4b..c17104dd 100644
--- a/host/src/usage/antigravity.rs
+++ b/host/src/usage/antigravity.rs
@@ -91,11 +91,15 @@ fn flag(command: &str, name: &str) -> Option<String> {
None
}
+/// macOS `pgrep -a` includes ancestors and prints only pids. `-lf` prints the pid
+/// and the full argument list. Linux `-a -f` is the command that does the same.
#[cfg(unix)]
fn processes() -> Vec<(u32, String)> {
- let Ok(out) = std::process::Command::new("pgrep").args(["-a", "-f", "language_server|agy"]).output() else {
- return Vec::new();
- };
+ #[cfg(target_os = "macos")]
+ let args: &[&str] = &["-lf", "language_server|agy"];
+ #[cfg(not(target_os = "macos"))]
+ let args: &[&str] = &["-a", "-f", "language_server|agy"];
+ let Ok(out) = std::process::Command::new("pgrep").args(args).output() else { return Vec::new() };
String::from_utf8_lossy(&out.stdout)
.lines()
.filter_map(|line| {
@@ -149,9 +153,11 @@ fn listen_ports(pid: u32) -> Vec<u16> {
.collect()
}
+#[cfg(unix)]
fn ports_in(text: &str) -> Vec<u16> {
let mut ports = Vec::new();
- for token in text.split(|c: char| !c.is_ascii_digit() && c != ':') {
+ // Keep the IPv6 brackets, so `[::1]:port` stays one address instead of a stray port 1.
+ for token in text.split(|c: char| !c.is_ascii_digit() && c != ':' && c != '[' && c != ']') {
let Some(port) = token.rsplit(':').next().filter(|s| !s.is_empty()) else { continue };
if token.contains(':')
&& let Ok(port) = port.parse()
@@ -261,4 +267,13 @@ mod tests {
assert_eq!(flag(line, "--extension_server_port").as_deref(), Some("1234"));
assert!(!is_antigravity("agy --help"));
}
+
+ #[cfg(unix)]
+ #[test]
+ fn a_listen_line_keeps_the_port_once() {
+ let text = "codync-host 123 user 10u IPv4 TCP 127.0.0.1:19223 (LISTEN)\n\
+ codync-host 123 user 11u IPv6 TCP [::1]:19223 (LISTEN)\n\
+ codync-host 123 user 12u IPv4 TCP *:43122 (LISTEN)\n";
+ assert_eq!(ports_in(text), vec![19223, 43122]);
+ }
}
diff --git a/host/src/usage/cursor.rs b/host/src/usage/cursor.rs
index 781ab1ad..11c26d7e 100644
--- a/host/src/usage/cursor.rs
+++ b/host/src/usage/cursor.rs
@@ -32,8 +32,7 @@ pub(super) async fn collect() -> Option<Vec<Window>> {
return None;
}
let body: Value = response.json().await.ok()?;
- let windows = parse(&body);
- (!windows.is_empty()).then_some(windows)
+ Some(parse(&body))
}
fn db_path() -> Option<PathBuf> {
diff --git a/host/src/usage/mod.rs b/host/src/usage/mod.rs
index d0bf3981..48b8708f 100644
--- a/host/src/usage/mod.rs
+++ b/host/src/usage/mod.rs
@@ -93,7 +93,8 @@ impl Window {
}
impl Usage {
- /// Replaces `new` windows (by id) in provider `id`, keeping the provider's other windows.
+ /// One window at a time, for Claude's status line and rate-limit events.
+ /// The provider's other windows stay.
fn merge(&mut self, id: &'static str, name: &'static str, source: &'static str, new: Vec<Window>) {
let mut windows = self.providers.iter().find(|p| p.id == id).map(|p| p.windows.clone()).unwrap_or_default();
windows.retain(|w| !new.iter().any(|n| n.id == w.id));
@@ -103,6 +104,19 @@ impl Usage {
self.providers.push(Provider { id, name, windows, source, updated_at: crate::store::now_ms() });
self.providers.sort_by_key(|p| p.id);
}
+
+ /// A probe's full reading. Windows it no longer reports are dropped, and an
+ /// empty reading removes the provider.
+ fn replace(&mut self, id: &'static str, name: &'static str, source: &'static str, new: Vec<Window>) {
+ self.providers.retain(|p| p.id != id);
+ if new.is_empty() {
+ return;
+ }
+ let mut windows = new;
+ windows.sort_by(|a, b| a.id.cmp(&b.id));
+ self.providers.push(Provider { id, name, windows, source, updated_at: crate::store::now_ms() });
+ self.providers.sort_by_key(|p| p.id);
+ }
}
pub(super) fn merge(hub: &Hub, id: &'static str, name: &'static str, source: &'static str, windows: Vec<Window>) {
@@ -176,9 +190,10 @@ pub(super) fn finite_i64(n: f64) -> Option<i64> {
}
fn apply(hub: &Hub, windows: Option<Vec<Window>>, id: &'static str, name: &'static str, source: &'static str) {
- if let Some(windows) = windows.filter(|windows| !windows.is_empty()) {
- merge(hub, id, name, source, windows);
- }
+ let Some(windows) = windows else { return };
+ let mut usage = hub.usage.locked().clone();
+ usage.replace(id, name, source, windows);
+ hub.set_usage(usage);
}
#[cfg(test)]
@@ -202,6 +217,22 @@ mod tests {
assert_eq!(serde_json::to_value(&u).unwrap()["providers"][0]["windows"][1]["resetsAt"], Value::Null);
}
+ #[test]
+ fn a_full_reading_drops_windows_the_probe_no_longer_reports() {
+ let mut u = Usage::default();
+ u.replace(
+ "cursor",
+ "Cursor",
+ "Cursor",
+ vec![Window::new("monthly", "Monthly", 40.0, None), Window::note("on_demand", "On-Demand", "$1")],
+ );
+ u.replace("cursor", "Cursor", "Cursor", vec![Window::note("unlimited", "Monthly", "Unlimited")]);
+ assert_eq!(u.providers[0].windows.len(), 1);
+ assert_eq!(u.providers[0].windows[0].id, "unlimited");
+ u.replace("cursor", "Cursor", "Cursor", Vec::new());
+ assert_eq!(u.providers, []);
+ }
+
#[test]
fn a_note_is_not_serialized_as_a_missing_percent() {
let window = Window::note("cost", "Cost today", "$1.50");
diff --git a/host/src/usage/omp.rs b/host/src/usage/omp.rs
index 5cd7cbcd..80f3c9db 100644
--- a/host/src/usage/omp.rs
+++ b/host/src/usage/omp.rs
@@ -39,6 +39,7 @@ fn parse(text: &str) -> Vec<Window> {
let Some(provider) = report["provider"].as_str() else { continue };
let name = provider_name(provider);
let suffix = (per_provider.get(provider).copied().unwrap_or(0) > 1).then(|| discriminator(report, index));
+ let account = account_key(report, index);
let mut pools = HashSet::new();
let Some(limits) = report["limits"].as_array() else { continue };
for (n, limit) in limits.iter().enumerate() {
@@ -47,14 +48,21 @@ fn parse(text: &str) -> Vec<Window> {
{
continue;
}
- let Some(window) = one_limit(&name, suffix.as_deref(), provider, n, limit) else { continue };
+ let Some(window) = one_limit(&name, suffix.as_deref(), provider, &account, n, limit) else { continue };
windows.push(window);
}
}
windows
}
-fn one_limit(name: &str, suffix: Option<&str>, provider: &str, n: usize, limit: &Value) -> Option<Window> {
+fn one_limit(
+ name: &str,
+ suffix: Option<&str>,
+ provider: &str,
+ account: &str,
+ n: usize,
+ limit: &Value,
+) -> Option<Window> {
let amount = &limit["amount"];
let window_id = limit["scope"]["windowId"].as_str().or_else(|| limit["window"]["id"].as_str()).unwrap_or("limit");
let raw_label = limit["label"].as_str().map(str::trim).filter(|s| !s.is_empty());
@@ -64,7 +72,7 @@ fn one_limit(name: &str, suffix: Option<&str>, provider: &str, n: usize, limit:
(None, Some(suffix)) => format!("{name} · {suffix}"),
(None, None) => name.to_owned(),
};
- let id = format!("{provider}:{window_id}:{n}");
+ let id = format!("{provider}:{account}:{window_id}:{n}");
let resets = epoch_ms(&limit["window"]["resetsAt"]);
if amount["unit"].as_str().is_some_and(|u| u.eq_ignore_ascii_case("usd")) && amount["limit"].is_null() {
let spent = amount["used"].as_f64()?;
@@ -92,6 +100,20 @@ fn epoch_ms(v: &Value) -> Option<i64> {
Some(if n > 100_000_000_000 { n } else { n.saturating_mul(1000) })
}
+fn account_key(report: &Value, index: usize) -> String {
+ let raw = report["metadata"]["accountId"]
+ .as_str()
+ .filter(|s| !s.is_empty())
+ .or_else(|| report["metadata"]["email"].as_str().filter(|s| !s.is_empty()));
+ let Some(raw) = raw else { return format!("account-{}", index + 1) };
+ let key: String = raw
+ .chars()
+ .map(|c| if c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.' | '@') { c } else { '_' })
+ .take(80)
+ .collect();
+ if key.is_empty() { format!("account-{}", index + 1) } else { key }
+}
+
fn discriminator(report: &Value, index: usize) -> String {
let email = report["metadata"]["email"].as_str().filter(|s| s.contains('@'));
if let Some(email) = email {
@@ -154,6 +176,21 @@ mod tests {
assert_eq!(w[1].label, "Spend");
}
+ #[test]
+ fn two_accounts_keep_separate_window_ids() {
+ let text = r#"{"reports":[
+ {"provider":"anthropic","metadata":{"email":"[email protected]","accountId":"acct_ada"},
+ "limits":[{"label":"5h","scope":{"windowId":"5h"},"amount":{"usedFraction":0.1}}]},
+ {"provider":"anthropic","metadata":{"email":"[email protected]","accountId":"acct_grace"},
+ "limits":[{"label":"5h","scope":{"windowId":"5h"},"amount":{"usedFraction":0.2}}]}
+ ]}"#;
+ let w = parse(text);
+ assert_eq!(w[0].id, "anthropic:acct_ada:5h:0");
+ assert_eq!(w[1].id, "anthropic:acct_grace:5h:0");
+ assert_eq!(w[0].label, "5h · ada");
+ assert_eq!(w[1].label, "5h · grace");
+ }
+
#[test]
fn an_uncapped_dollar_spend_is_a_note() {
let text = r#"{"reports":[{"provider":"openai","limits":[
diff --git a/host/src/usage/opencode-both.sql b/host/src/usage/opencode-both.sql
index 0859c8be..52025bbf 100644
--- a/host/src/usage/opencode-both.sql
+++ b/host/src/usage/opencode-both.sql
@@ -1 +1 @@
-WITH spent AS ( SELECT id, CAST(COALESCE(json_extract(data, '$.time.created'), time_created) AS INTEGER) AS t, CAST(json_extract(data, '$.cost') AS REAL) AS cost FROM session_message WHERE type = 'assistant' AND json_valid(data) AND json_extract(data, '$.model.providerID') = 'opencode-go' AND json_type(data, '$.cost') IN ('integer', 'real') UNION ALL SELECT id, CAST(COALESCE(json_extract(data, '$.time.created'), time_created) AS INTEGER) AS t, CAST(json_extract(data, '$.cost') AS REAL) AS cost FROM message WHERE json_valid(data) AND json_extract(data, '$.providerID') = 'opencode-go' AND json_extract(data, '$.role') = 'assistant' AND json_type(data, '$.cost') IN ('integer', 'real') ), rows AS ( SELECT id, MAX(t) AS t, MAX(cost) AS cost FROM spent GROUP BY id ), clock AS ( SELECT CAST(strftime('%s', 'now') AS INTEGER) * 1000 AS now_ms, CAST(strftime('%s', date('now', '-6 days', 'weekday 1')) AS INTEGER) * 1000 AS week_ms ), anchor AS ( SELECT MIN(t) AS ms, CAST(strftime('%d', MIN(t) / 1000, 'unixepoch') AS INTEGER) AS day, strftime('%H:%M:%S', MIN(t) / 1000, 'unixepoch') AS at FROM rows ), months AS ( SELECT ms, day, at, date('now', 'start of month', '-1 month') AS m0, date('now', 'start of month') AS m1, date('now', 'start of month', '+1 month') AS m2 FROM anchor WHERE ms IS NOT NULL ), starts AS ( SELECT datetime(date(m0, '+' || (MIN(day, CAST(strftime('%d', date(m0, '+1 month', '-1 day')) AS INTEGER)) - 1) || ' days') || ' ' || at) AS s0, datetime(date(m1, '+' || (MIN(day, CAST(strftime('%d', date(m1, '+1 month', '-1 day')) AS INTEGER)) - 1) || ' days') || ' ' || at) AS s1, datetime(date(m2, '+' || (MIN(day, CAST(strftime('%d', date(m2, '+1 month', '-1 day')) AS INTEGER)) - 1) || ' days') || ' ' || at) AS s2 FROM months ), month AS ( SELECT CAST(strftime('%s', CASE WHEN s1 <= datetime('now') THEN s1 ELSE s0 END) AS INTEGER) * 1000 AS start_ms, CAST(strftime('%s', CASE WHEN s1 <= datetime('now') THEN s2 ELSE s1 END) AS INTEGER) * 1000 AS end_ms FROM starts ) SELECT (SELECT now_ms FROM clock) AS now_ms, (SELECT COALESCE(SUM(cost), 0) FROM rows, clock WHERE t >= now_ms - 18000000) AS five_hour_cost, (SELECT MIN(t) FROM rows, clock WHERE t >= now_ms - 18000000) AS five_hour_oldest_ms, (SELECT COALESCE(SUM(cost), 0) FROM rows, clock WHERE t >= week_ms) AS weekly_cost, (SELECT week_ms + 604800000 FROM clock) AS week_end_ms, (SELECT COALESCE(SUM(cost), 0) FROM rows, month WHERE t >= start_ms AND t < end_ms) AS monthly_cost, (SELECT start_ms FROM month) AS month_start_ms, (SELECT end_ms FROM month) AS month_end_ms
+WITH spent AS ( SELECT id, CAST(COALESCE(json_extract(data, '$.time.created'), time_created) AS INTEGER) AS t, CAST(json_extract(data, '$.cost') AS REAL) AS cost FROM session_message WHERE type = 'assistant' AND json_valid(data) AND json_extract(data, '$.model.providerID') = 'opencode-go' AND json_type(data, '$.cost') IN ('integer', 'real') UNION ALL SELECT id, CAST(COALESCE(json_extract(data, '$.time.created'), time_created) AS INTEGER) AS t, CAST(json_extract(data, '$.cost') AS REAL) AS cost FROM message WHERE json_valid(data) AND json_extract(data, '$.providerID') = 'opencode-go' AND json_extract(data, '$.role') = 'assistant' AND json_type(data, '$.cost') IN ('integer', 'real') ), rows AS ( SELECT id, MAX(t) AS t, MAX(cost) AS cost FROM spent GROUP BY id ), clock AS ( SELECT CAST(strftime('%s', 'now') AS INTEGER) * 1000 AS now_ms, CAST(strftime('%s', date('now', '-6 days', 'weekday 1')) AS INTEGER) * 1000 AS week_ms ), anchor AS ( SELECT MIN(t) AS ms, CAST(strftime('%d', MIN(t) / 1000, 'unixepoch') AS INTEGER) AS day, strftime('%H:%M:%S', MIN(t) / 1000, 'unixepoch') AS at FROM rows ), months AS ( SELECT ms, day, at, date('now', 'start of month', '-1 month') AS m0, date('now', 'start of month') AS m1, date('now', 'start of month', '+1 month') AS m2 FROM anchor WHERE ms IS NOT NULL ), starts AS ( SELECT datetime(date(m0, '+' || (MIN(day, CAST(strftime('%d', date(m0, '+1 month', '-1 day')) AS INTEGER)) - 1) || ' days') || ' ' || at) AS s0, datetime(date(m1, '+' || (MIN(day, CAST(strftime('%d', date(m1, '+1 month', '-1 day')) AS INTEGER)) - 1) || ' days') || ' ' || at) AS s1, datetime(date(m2, '+' || (MIN(day, CAST(strftime('%d', date(m2, '+1 month', '-1 day')) AS INTEGER)) - 1) || ' days') || ' ' || at) AS s2 FROM months ), month AS ( SELECT CAST(strftime('%s', CASE WHEN s1 <= datetime('now') THEN s1 ELSE s0 END) AS INTEGER) * 1000 AS start_ms, CAST(strftime('%s', CASE WHEN s1 <= datetime('now') THEN s2 ELSE s1 END) AS INTEGER) * 1000 AS end_ms FROM starts ) SELECT (SELECT now_ms FROM clock) AS now_ms, (SELECT COALESCE(SUM(cost), 0) FROM rows, clock WHERE t >= now_ms - 18000000) AS five_hour_cost, (SELECT MIN(t) FROM rows, clock WHERE t >= now_ms - 18000000) AS five_hour_oldest_ms, (SELECT COALESCE(SUM(cost), 0) FROM rows, clock WHERE t >= week_ms) AS weekly_cost, (SELECT week_ms + 604800000 FROM clock) AS week_end_ms, (SELECT COALESCE(SUM(cost), 0) FROM rows, month WHERE t >= start_ms AND t < end_ms) AS monthly_cost, (SELECT start_ms FROM month) AS month_start_ms, (SELECT end_ms FROM month) AS month_end_ms, (SELECT COUNT(*) FROM rows) AS go_messages
diff --git a/host/src/usage/opencode-message.sql b/host/src/usage/opencode-message.sql
index 71368095..d15ec5b2 100644
--- a/host/src/usage/opencode-message.sql
+++ b/host/src/usage/opencode-message.sql
@@ -1 +1 @@
-WITH rows AS ( SELECT id, CAST(COALESCE(json_extract(data, '$.time.created'), time_created) AS INTEGER) AS t, CAST(json_extract(data, '$.cost') AS REAL) AS cost FROM message WHERE json_valid(data) AND json_extract(data, '$.providerID') = 'opencode-go' AND json_extract(data, '$.role') = 'assistant' AND json_type(data, '$.cost') IN ('integer', 'real') ), clock AS ( SELECT CAST(strftime('%s', 'now') AS INTEGER) * 1000 AS now_ms, CAST(strftime('%s', date('now', '-6 days', 'weekday 1')) AS INTEGER) * 1000 AS week_ms ), anchor AS ( SELECT MIN(t) AS ms, CAST(strftime('%d', MIN(t) / 1000, 'unixepoch') AS INTEGER) AS day, strftime('%H:%M:%S', MIN(t) / 1000, 'unixepoch') AS at FROM rows ), months AS ( SELECT ms, day, at, date('now', 'start of month', '-1 month') AS m0, date('now', 'start of month') AS m1, date('now', 'start of month', '+1 month') AS m2 FROM anchor WHERE ms IS NOT NULL ), starts AS ( SELECT datetime(date(m0, '+' || (MIN(day, CAST(strftime('%d', date(m0, '+1 month', '-1 day')) AS INTEGER)) - 1) || ' days') || ' ' || at) AS s0, datetime(date(m1, '+' || (MIN(day, CAST(strftime('%d', date(m1, '+1 month', '-1 day')) AS INTEGER)) - 1) || ' days') || ' ' || at) AS s1, datetime(date(m2, '+' || (MIN(day, CAST(strftime('%d', date(m2, '+1 month', '-1 day')) AS INTEGER)) - 1) || ' days') || ' ' || at) AS s2 FROM months ), month AS ( SELECT CAST(strftime('%s', CASE WHEN s1 <= datetime('now') THEN s1 ELSE s0 END) AS INTEGER) * 1000 AS start_ms, CAST(strftime('%s', CASE WHEN s1 <= datetime('now') THEN s2 ELSE s1 END) AS INTEGER) * 1000 AS end_ms FROM starts ) SELECT (SELECT now_ms FROM clock) AS now_ms, (SELECT COALESCE(SUM(cost), 0) FROM rows, clock WHERE t >= now_ms - 18000000) AS five_hour_cost, (SELECT MIN(t) FROM rows, clock WHERE t >= now_ms - 18000000) AS five_hour_oldest_ms, (SELECT COALESCE(SUM(cost), 0) FROM rows, clock WHERE t >= week_ms) AS weekly_cost, (SELECT week_ms + 604800000 FROM clock) AS week_end_ms, (SELECT COALESCE(SUM(cost), 0) FROM rows, month WHERE t >= start_ms AND t < end_ms) AS monthly_cost, (SELECT start_ms FROM month) AS month_start_ms, (SELECT end_ms FROM month) AS month_end_ms
+WITH rows AS ( SELECT id, CAST(COALESCE(json_extract(data, '$.time.created'), time_created) AS INTEGER) AS t, CAST(json_extract(data, '$.cost') AS REAL) AS cost FROM message WHERE json_valid(data) AND json_extract(data, '$.providerID') = 'opencode-go' AND json_extract(data, '$.role') = 'assistant' AND json_type(data, '$.cost') IN ('integer', 'real') ), clock AS ( SELECT CAST(strftime('%s', 'now') AS INTEGER) * 1000 AS now_ms, CAST(strftime('%s', date('now', '-6 days', 'weekday 1')) AS INTEGER) * 1000 AS week_ms ), anchor AS ( SELECT MIN(t) AS ms, CAST(strftime('%d', MIN(t) / 1000, 'unixepoch') AS INTEGER) AS day, strftime('%H:%M:%S', MIN(t) / 1000, 'unixepoch') AS at FROM rows ), months AS ( SELECT ms, day, at, date('now', 'start of month', '-1 month') AS m0, date('now', 'start of month') AS m1, date('now', 'start of month', '+1 month') AS m2 FROM anchor WHERE ms IS NOT NULL ), starts AS ( SELECT datetime(date(m0, '+' || (MIN(day, CAST(strftime('%d', date(m0, '+1 month', '-1 day')) AS INTEGER)) - 1) || ' days') || ' ' || at) AS s0, datetime(date(m1, '+' || (MIN(day, CAST(strftime('%d', date(m1, '+1 month', '-1 day')) AS INTEGER)) - 1) || ' days') || ' ' || at) AS s1, datetime(date(m2, '+' || (MIN(day, CAST(strftime('%d', date(m2, '+1 month', '-1 day')) AS INTEGER)) - 1) || ' days') || ' ' || at) AS s2 FROM months ), month AS ( SELECT CAST(strftime('%s', CASE WHEN s1 <= datetime('now') THEN s1 ELSE s0 END) AS INTEGER) * 1000 AS start_ms, CAST(strftime('%s', CASE WHEN s1 <= datetime('now') THEN s2 ELSE s1 END) AS INTEGER) * 1000 AS end_ms FROM starts ) SELECT (SELECT now_ms FROM clock) AS now_ms, (SELECT COALESCE(SUM(cost), 0) FROM rows, clock WHERE t >= now_ms - 18000000) AS five_hour_cost, (SELECT MIN(t) FROM rows, clock WHERE t >= now_ms - 18000000) AS five_hour_oldest_ms, (SELECT COALESCE(SUM(cost), 0) FROM rows, clock WHERE t >= week_ms) AS weekly_cost, (SELECT week_ms + 604800000 FROM clock) AS week_end_ms, (SELECT COALESCE(SUM(cost), 0) FROM rows, month WHERE t >= start_ms AND t < end_ms) AS monthly_cost, (SELECT start_ms FROM month) AS month_start_ms, (SELECT end_ms FROM month) AS month_end_ms, (SELECT COUNT(*) FROM rows) AS go_messages
diff --git a/host/src/usage/opencode-session.sql b/host/src/usage/opencode-session.sql
index c84e9de4..525fc21d 100644
--- a/host/src/usage/opencode-session.sql
+++ b/host/src/usage/opencode-session.sql
@@ -1 +1 @@
-WITH rows AS ( SELECT id, CAST(COALESCE(json_extract(data, '$.time.created'), time_created) AS INTEGER) AS t, CAST(json_extract(data, '$.cost') AS REAL) AS cost FROM session_message WHERE type = 'assistant' AND json_valid(data) AND json_extract(data, '$.model.providerID') = 'opencode-go' AND json_type(data, '$.cost') IN ('integer', 'real') ), clock AS ( SELECT CAST(strftime('%s', 'now') AS INTEGER) * 1000 AS now_ms, CAST(strftime('%s', date('now', '-6 days', 'weekday 1')) AS INTEGER) * 1000 AS week_ms ), anchor AS ( SELECT MIN(t) AS ms, CAST(strftime('%d', MIN(t) / 1000, 'unixepoch') AS INTEGER) AS day, strftime('%H:%M:%S', MIN(t) / 1000, 'unixepoch') AS at FROM rows ), months AS ( SELECT ms, day, at, date('now', 'start of month', '-1 month') AS m0, date('now', 'start of month') AS m1, date('now', 'start of month', '+1 month') AS m2 FROM anchor WHERE ms IS NOT NULL ), starts AS ( SELECT datetime(date(m0, '+' || (MIN(day, CAST(strftime('%d', date(m0, '+1 month', '-1 day')) AS INTEGER)) - 1) || ' days') || ' ' || at) AS s0, datetime(date(m1, '+' || (MIN(day, CAST(strftime('%d', date(m1, '+1 month', '-1 day')) AS INTEGER)) - 1) || ' days') || ' ' || at) AS s1, datetime(date(m2, '+' || (MIN(day, CAST(strftime('%d', date(m2, '+1 month', '-1 day')) AS INTEGER)) - 1) || ' days') || ' ' || at) AS s2 FROM months ), month AS ( SELECT CAST(strftime('%s', CASE WHEN s1 <= datetime('now') THEN s1 ELSE s0 END) AS INTEGER) * 1000 AS start_ms, CAST(strftime('%s', CASE WHEN s1 <= datetime('now') THEN s2 ELSE s1 END) AS INTEGER) * 1000 AS end_ms FROM starts ) SELECT (SELECT now_ms FROM clock) AS now_ms, (SELECT COALESCE(SUM(cost), 0) FROM rows, clock WHERE t >= now_ms - 18000000) AS five_hour_cost, (SELECT MIN(t) FROM rows, clock WHERE t >= now_ms - 18000000) AS five_hour_oldest_ms, (SELECT COALESCE(SUM(cost), 0) FROM rows, clock WHERE t >= week_ms) AS weekly_cost, (SELECT week_ms + 604800000 FROM clock) AS week_end_ms, (SELECT COALESCE(SUM(cost), 0) FROM rows, month WHERE t >= start_ms AND t < end_ms) AS monthly_cost, (SELECT start_ms FROM month) AS month_start_ms, (SELECT end_ms FROM month) AS month_end_ms
+WITH rows AS ( SELECT id, CAST(COALESCE(json_extract(data, '$.time.created'), time_created) AS INTEGER) AS t, CAST(json_extract(data, '$.cost') AS REAL) AS cost FROM session_message WHERE type = 'assistant' AND json_valid(data) AND json_extract(data, '$.model.providerID') = 'opencode-go' AND json_type(data, '$.cost') IN ('integer', 'real') ), clock AS ( SELECT CAST(strftime('%s', 'now') AS INTEGER) * 1000 AS now_ms, CAST(strftime('%s', date('now', '-6 days', 'weekday 1')) AS INTEGER) * 1000 AS week_ms ), anchor AS ( SELECT MIN(t) AS ms, CAST(strftime('%d', MIN(t) / 1000, 'unixepoch') AS INTEGER) AS day, strftime('%H:%M:%S', MIN(t) / 1000, 'unixepoch') AS at FROM rows ), months AS ( SELECT ms, day, at, date('now', 'start of month', '-1 month') AS m0, date('now', 'start of month') AS m1, date('now', 'start of month', '+1 month') AS m2 FROM anchor WHERE ms IS NOT NULL ), starts AS ( SELECT datetime(date(m0, '+' || (MIN(day, CAST(strftime('%d', date(m0, '+1 month', '-1 day')) AS INTEGER)) - 1) || ' days') || ' ' || at) AS s0, datetime(date(m1, '+' || (MIN(day, CAST(strftime('%d', date(m1, '+1 month', '-1 day')) AS INTEGER)) - 1) || ' days') || ' ' || at) AS s1, datetime(date(m2, '+' || (MIN(day, CAST(strftime('%d', date(m2, '+1 month', '-1 day')) AS INTEGER)) - 1) || ' days') || ' ' || at) AS s2 FROM months ), month AS ( SELECT CAST(strftime('%s', CASE WHEN s1 <= datetime('now') THEN s1 ELSE s0 END) AS INTEGER) * 1000 AS start_ms, CAST(strftime('%s', CASE WHEN s1 <= datetime('now') THEN s2 ELSE s1 END) AS INTEGER) * 1000 AS end_ms FROM starts ) SELECT (SELECT now_ms FROM clock) AS now_ms, (SELECT COALESCE(SUM(cost), 0) FROM rows, clock WHERE t >= now_ms - 18000000) AS five_hour_cost, (SELECT MIN(t) FROM rows, clock WHERE t >= now_ms - 18000000) AS five_hour_oldest_ms, (SELECT COALESCE(SUM(cost), 0) FROM rows, clock WHERE t >= week_ms) AS weekly_cost, (SELECT week_ms + 604800000 FROM clock) AS week_end_ms, (SELECT COALESCE(SUM(cost), 0) FROM rows, month WHERE t >= start_ms AND t < end_ms) AS monthly_cost, (SELECT start_ms FROM month) AS month_start_ms, (SELECT end_ms FROM month) AS month_end_ms, (SELECT COUNT(*) FROM rows) AS go_messages
diff --git a/host/src/usage/opencode.rs b/host/src/usage/opencode.rs
index bf41414a..e7cb0679 100644
--- a/host/src/usage/opencode.rs
+++ b/host/src/usage/opencode.rs
@@ -50,10 +50,14 @@ fn from_db(path: &Path) -> Option<Vec<Window>> {
integer(row, 4),
number(row, 5),
integer(row, 7),
+ integer(row, 8),
))
})
.ok()?;
- let (now_ms, five_hour, oldest, weekly, week_end, monthly, month_end) = row;
+ let (now_ms, five_hour, oldest, weekly, week_end, monthly, month_end, go_messages) = row;
+ if go_messages.unwrap_or(0) == 0 {
+ return None;
+ }
let now_ms = now_ms?;
let five_reset = oldest.unwrap_or(now_ms).saturating_add(18_000_000);
Some(vec![
@@ -116,4 +120,24 @@ mod tests {
assert!((windows[2].percent - 10.0).abs() < 0.01, "month {}", windows[2].percent);
assert!(windows[0].resets_at.is_some());
}
+
+ #[test]
+ fn another_providers_messages_are_not_a_go_plan() {
+ let path = std::env::temp_dir().join(format!("codync-opencode-other-{}.db", std::process::id()));
+ let _ = std::fs::remove_file(&path);
+ let conn = Connection::open(&path).unwrap();
+ conn.execute("CREATE TABLE session_message (id TEXT, data TEXT, type TEXT, time_created INTEGER)", []).unwrap();
+ let millis = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_millis();
+ let now = i64::try_from(millis).unwrap();
+ let data = format!(r#"{{"cost":6,"time":{{"created":{now}}},"model":{{"providerID":"anthropic"}}}}"#);
+ conn.execute(
+ "INSERT INTO session_message (id, data, type, time_created) VALUES ('m', ?1, 'assistant', ?2)",
+ rusqlite::params![data, now],
+ )
+ .unwrap();
+ drop(conn);
+ let windows = from_db(&path);
+ let _ = std::fs::remove_file(&path);
+ assert!(windows.is_none());
+ }
}
diff --git a/host/src/usage/vibe.rs b/host/src/usage/vibe.rs
index ed698680..d7be843e 100644
--- a/host/src/usage/vibe.rs
+++ b/host/src/usage/vibe.rs
@@ -1,7 +1,12 @@
-//! Today's tokens and cost from Mistral Vibe's session logs. There is no plan
+//! Tokens and cost from Mistral Vibe's session logs. There is no plan
//! percent here — that lives behind a browser cookie — so these are notes,
//! not limit bars.
+//!
+//! A `messages.jsonl` line with a time and a token or cost count contributes
+//! only when that time is today, including a session opened yesterday. A
+//! session with no such lines counts only when its folder started today.
+use serde_json::Value;
use std::path::Path;
use super::Window;
@@ -13,43 +18,127 @@ pub(super) fn collect() -> Option<Vec<Window>> {
}
let now = crate::store::now_ms();
let start = local_midnight(now)?;
+ Some(windows_in(&root, start, now))
+}
+
+fn windows_in(root: &Path, start: i64, now: i64) -> Vec<Window> {
let mut tokens = 0.0;
let mut cost = 0.0;
- let mut any = false;
- let entries = std::fs::read_dir(&root).ok()?;
+ let mut from_stamp = false;
+ let mut from_dated = false;
+ let Some(entries) = std::fs::read_dir(root).ok() else { return Vec::new() };
+ let end = now.saturating_add(86_400_000);
for entry in entries.filter_map(Result::ok) {
let name = entry.file_name();
let Some(name) = name.to_str() else { continue };
let Some(at) = session_ms(name) else { continue };
- if at < start || at > now.saturating_add(86_400_000) {
+ if let Some((session_tokens, session_cost)) = dated_usage(&entry.path().join("messages.jsonl"), start, end) {
+ if session_tokens > 0.0 || session_cost > 0.0 {
+ from_dated = true;
+ tokens += session_tokens;
+ cost += session_cost;
+ }
+ continue;
+ }
+ if !(start..=end).contains(&at) {
+ continue;
+ }
+ let Some((session_tokens, session_cost)) = read_meta(&entry.path().join("meta.json")) else { continue };
+ if session_tokens > 0.0 || session_cost > 0.0 {
+ from_stamp = true;
+ tokens += session_tokens;
+ cost += session_cost;
+ }
+ }
+ notes(tokens, cost, from_stamp && !from_dated)
+}
+
+/// Today's totals when the file has dated usage lines. `None` when it does not,
+/// so the session total can be used for a folder started today.
+fn dated_usage(path: &Path, start: i64, end: i64) -> Option<(f64, f64)> {
+ let text = std::fs::read_to_string(path).ok()?;
+ let mut saw = false;
+ let mut tokens = 0.0;
+ let mut cost = 0.0;
+ for line in text.lines() {
+ let line = line.trim();
+ if line.is_empty() {
continue;
}
- let meta = entry.path().join("meta.json");
- let Some((session_tokens, session_cost)) = read_meta(&meta) else { continue };
- any = true;
- tokens += session_tokens;
- cost += session_cost;
+ let Ok(value) = serde_json::from_str::<Value>(line) else { continue };
+ let Some(record) = usage_record(&value) else { continue };
+ saw = true;
+ let Some(at) = record.at else { continue };
+ if !(start..=end).contains(&at) {
+ continue;
+ }
+ tokens += record.tokens;
+ cost += record.cost;
+ }
+ saw.then_some((tokens, cost))
+}
+
+struct Dated {
+ at: Option<i64>,
+ tokens: f64,
+ cost: f64,
+}
+
+fn usage_record(value: &Value) -> Option<Dated> {
+ let tokens = token_count(value);
+ let cost = json_f64(&value["cost"]).or_else(|| json_f64(&value["usage"]["cost"]));
+ if tokens.is_none() && cost.is_none() {
+ return None;
+ }
+ Some(Dated { at: message_time(value), tokens: tokens.unwrap_or(0.0), cost: cost.unwrap_or(0.0) })
+}
+
+fn token_count(value: &Value) -> Option<f64> {
+ let usage = value.get("usage").filter(|v| v.is_object()).unwrap_or(value);
+ if let Some(total) = json_f64(&usage["total_tokens"]) {
+ return Some(total);
+ }
+ let prompt = json_f64(&usage["prompt_tokens"]);
+ let completion = json_f64(&usage["completion_tokens"]);
+ if prompt.is_none() && completion.is_none() {
+ return json_f64(&usage["tokens"]);
+ }
+ Some(prompt.unwrap_or(0.0) + completion.unwrap_or(0.0))
+}
+
+fn message_time(value: &Value) -> Option<i64> {
+ let stamp = ["created_at", "timestamp"].iter().find_map(|key| value.get(*key).filter(|v| !v.is_null()))?;
+ if let Some(text) = stamp.as_str() {
+ return chrono::DateTime::parse_from_rfc3339(text).ok().map(|t| t.timestamp_millis());
}
- any.then(|| notes(tokens, cost))
+ let n = stamp.as_i64().or_else(|| stamp.as_f64().and_then(super::finite_i64))?;
+ Some(if n > 100_000_000_000 { n } else { n.saturating_mul(1000) })
+}
+
+#[allow(clippy::cast_precision_loss)]
+fn json_f64(value: &Value) -> Option<f64> {
+ value.as_f64().or_else(|| value.as_i64().map(|n| n as f64))
}
-fn notes(tokens: f64, cost: f64) -> Vec<Window> {
+fn notes(tokens: f64, cost: f64, stamp_only: bool) -> Vec<Window> {
+ let (token_label, cost_label) =
+ if stamp_only { ("Tokens · started today", "Cost · started today") } else { ("Tokens today", "Cost today") };
let mut windows = Vec::new();
if tokens > 0.0 {
- windows.push(Window::note("tokens", "Tokens today", token_text(tokens)));
+ windows.push(Window::note("tokens", token_label, token_text(tokens)));
}
if cost > 0.0 {
- windows.push(Window::note("cost", "Cost today", format!("${cost:.2}")));
+ windows.push(Window::note("cost", cost_label, format!("${cost:.2}")));
}
windows
}
fn read_meta(path: &Path) -> Option<(f64, f64)> {
let text = std::fs::read_to_string(path).ok()?;
- let value: serde_json::Value = serde_json::from_str(&text).ok()?;
+ let value: Value = serde_json::from_str(&text).ok()?;
let stats = &value["stats"];
- let tokens = stats["session_total_llm_tokens"].as_f64().unwrap_or(0.0);
- let cost = stats["session_cost"].as_f64().unwrap_or(0.0);
+ let tokens = json_f64(&stats["session_total_llm_tokens"]).unwrap_or(0.0);
+ let cost = json_f64(&stats["session_cost"]).unwrap_or(0.0);
Some((tokens, cost))
}
@@ -102,8 +191,60 @@ mod tests {
.and_utc()
.timestamp_millis()
);
- let notes = notes(1_500_000.0, 1.5);
- assert_eq!(notes[0].text.as_deref(), Some("1.5M tokens"));
- assert_eq!(notes[1].text.as_deref(), Some("$1.50"));
+ let rows = notes(1_500_000.0, 1.5, false);
+ assert_eq!(rows[0].label, "Tokens today");
+ assert_eq!(rows[0].text.as_deref(), Some("1.5M tokens"));
+ assert_eq!(rows[1].text.as_deref(), Some("$1.50"));
+ assert_eq!(notes(1.0, 0.0, true)[0].label, "Tokens · started today");
+ }
+
+ #[test]
+ fn a_session_opened_yesterday_counts_only_todays_lines() {
+ let now = chrono::NaiveDate::from_ymd_opt(2026, 10, 25)
+ .unwrap()
+ .and_hms_opt(12, 0, 0)
+ .unwrap()
+ .and_utc()
+ .timestamp_millis();
+ let start = local_midnight(now).unwrap();
+ let today = chrono::DateTime::from_timestamp_millis(start + 3_600_000).unwrap().to_rfc3339();
+ let yesterday = chrono::DateTime::from_timestamp_millis(start - 3_600_000).unwrap().to_rfc3339();
+ let root = std::env::temp_dir().join(format!("codync-vibe-dated-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&root);
+ let dir = root.join("session_20200101_000000");
+ std::fs::create_dir_all(&dir).unwrap();
+ std::fs::write(dir.join("meta.json"), r#"{"stats":{"session_total_llm_tokens":9999,"session_cost":99}}"#)
+ .unwrap();
+ std::fs::write(
+ dir.join("messages.jsonl"),
+ format!(
+ "{{\"role\":\"assistant\",\"content\":\"old\"}}\n{{\"created_at\":{yesterday:?},\"prompt_tokens\":100,\"completion_tokens\":0,\"cost\":1}}\n{{\"created_at\":{today:?},\"prompt_tokens\":10,\"completion_tokens\":5,\"cost\":0.25}}\n"
+ ),
+ )
+ .unwrap();
+ let windows = windows_in(&root, start, now);
+ let _ = std::fs::remove_dir_all(&root);
+ assert_eq!(windows[0].label, "Tokens today");
+ assert_eq!(windows[0].text.as_deref(), Some("15 tokens"));
+ assert_eq!(windows[1].text.as_deref(), Some("$0.25"));
+ }
+
+ #[test]
+ fn a_stamp_only_session_from_yesterday_adds_nothing() {
+ let now = chrono::NaiveDate::from_ymd_opt(2026, 10, 25)
+ .unwrap()
+ .and_hms_opt(12, 0, 0)
+ .unwrap()
+ .and_utc()
+ .timestamp_millis();
+ let start = local_midnight(now).unwrap();
+ let root = std::env::temp_dir().join(format!("codync-vibe-stamp-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&root);
+ let dir = root.join("session_20200101_000000");
+ std::fs::create_dir_all(&dir).unwrap();
+ std::fs::write(dir.join("meta.json"), r#"{"stats":{"session_total_llm_tokens":50,"session_cost":1}}"#).unwrap();
+ let windows = windows_in(&root, start, now);
+ let _ = std::fs::remove_dir_all(&root);
+ assert_eq!(windows, []);
}
}