Add per-session claude token/cost usage panel (WSL, v1)
Reads ~/.claude/projects/*.jsonl transcripts from the open WSL panes'
distros and shows per-session token counts + estimated USD cost, with a
running total in the titlebar.
Backend (src-tauri/src/usage.rs): new get_claude_usage command. For each
distro it probes $HOME once via wsl.exe, reaches the transcripts over the
\\wsl.localhost UNC share, and tallies message.usage per model per
session (summed by each line's model, since a session can switch models).
Results cached by (path,size,mtime) so polling only re-parses the file
that grew; recency-capped (30d / 50 sessions) to bound scan cost.
Windows-only; returns [] elsewhere. quiet_command made pub(crate).
Frontend: src/lib/usage.ts holds the pricing table (per-MTok rates,
matched by model-family substring) + cost/format helpers, so rates are
editable without recompiling Rust. UsagePanel.tsx mirrors the MCP panel
modal; rows whose transcript cwd matches an open pane are highlighted
with a [pane: label] tag. App polls every 20s (visible windows) for the
titlebar 💰 total and every 5s while the panel is open. Ctrl+Shift+U
opens it; added to shortcuts.ts + regenerated README.
tsc clean. Rust builds on the Windows host; needs runtime verification.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
a6d3f8a9f9
commit
1df8c3181b
10 changed files with 813 additions and 2 deletions
|
|
@ -6,6 +6,7 @@ mod hosts;
|
|||
mod mcp;
|
||||
mod mcp_policy;
|
||||
mod pty;
|
||||
mod usage;
|
||||
mod window_state;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
|
@ -66,6 +67,7 @@ pub fn run() {
|
|||
.manage(pending_actions)
|
||||
.manage(windows_state)
|
||||
.manage(pending_inits)
|
||||
.manage(usage::UsageCache::default())
|
||||
.on_window_event(move |window, event| {
|
||||
// When a non-main window closes, drop its workspaces from the
|
||||
// aggregator AND any unconsumed pending-init payload so neither
|
||||
|
|
@ -108,6 +110,7 @@ pub fn run() {
|
|||
commands::mcp_policy_load,
|
||||
commands::mcp_policy_save,
|
||||
commands::mcp_hard_deny_labels,
|
||||
usage::get_claude_usage,
|
||||
])
|
||||
.run(tauri::generate_context!())
|
||||
.expect("error while running tauri application");
|
||||
|
|
|
|||
|
|
@ -495,7 +495,7 @@ fn looks_like_password_prompt(buf: &[u8]) -> bool {
|
|||
// ---- distro enumeration -----------------------------------------------------
|
||||
|
||||
/// Run a process without flashing a console window on Windows.
|
||||
fn quiet_command(program: &str) -> std::process::Command {
|
||||
pub(crate) fn quiet_command(program: &str) -> std::process::Command {
|
||||
let mut c = std::process::Command::new(program);
|
||||
#[cfg(windows)]
|
||||
{
|
||||
|
|
|
|||
278
src-tauri/src/usage.rs
Normal file
278
src-tauri/src/usage.rs
Normal file
|
|
@ -0,0 +1,278 @@
|
|||
//! Reads claude-code session transcripts and tallies token usage per session
|
||||
//! for the usage panel.
|
||||
//!
|
||||
//! claude writes one JSONL transcript per session at
|
||||
//! `~/.claude/projects/<mangled-cwd>/<sessionId>.jsonl`. Every assistant line
|
||||
//! carries `cwd`, `sessionId`, `message.model`, and `message.usage`
|
||||
//! (input/output/cache tokens). We read those straight out of the file, so the
|
||||
//! reported cwd/model are accurate regardless of where the pane was spawned.
|
||||
//!
|
||||
//! Windows-only: the transcripts live inside each WSL distro, reached via the
|
||||
//! `\\wsl.localhost\<distro>\…` 9p share. Returns empty on non-Windows.
|
||||
//!
|
||||
//! Cost is computed on the frontend (see src/lib/usage.ts) so the rate table is
|
||||
//! easy to tweak; this module only returns raw per-model token tallies.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use parking_lot::Mutex;
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::pty::quiet_command;
|
||||
|
||||
/// Ignore sessions older than this, and cap the number returned — bounds the
|
||||
/// scan cost on machines with a large transcript history.
|
||||
const MAX_AGE_MS: i64 = 30 * 24 * 60 * 60 * 1000;
|
||||
const MAX_SESSIONS: usize = 50;
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ModelUsage {
|
||||
pub model: String,
|
||||
pub input_tokens: u64,
|
||||
pub output_tokens: u64,
|
||||
pub cache_creation_tokens: u64,
|
||||
pub cache_read_tokens: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SessionUsage {
|
||||
pub session_id: String,
|
||||
pub cwd: String,
|
||||
pub project_dir: String,
|
||||
pub distro: String,
|
||||
pub last_active_ms: i64,
|
||||
pub models: Vec<ModelUsage>,
|
||||
}
|
||||
|
||||
/// Parsed-file cache entry, validated by (size, mtime) so we only re-parse the
|
||||
/// one transcript that actually grew between polls.
|
||||
struct CachedFile {
|
||||
size: u64,
|
||||
mtime_ms: i64,
|
||||
cwd: String,
|
||||
models: Vec<ModelUsage>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct UsageCache {
|
||||
files: Mutex<HashMap<PathBuf, CachedFile>>,
|
||||
/// distro -> resolved `$HOME` (one wsl.exe probe per distro per process).
|
||||
homes: Mutex<HashMap<String, String>>,
|
||||
}
|
||||
|
||||
/// Read + tally claude usage across the given WSL distros (the distinct distros
|
||||
/// of currently-open WSL panes). Newest sessions first, capped to MAX_SESSIONS.
|
||||
#[tauri::command]
|
||||
pub async fn get_claude_usage(
|
||||
distros: Vec<String>,
|
||||
cache: tauri::State<'_, UsageCache>,
|
||||
) -> Result<Vec<SessionUsage>, String> {
|
||||
if !cfg!(windows) {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let cache = cache.inner();
|
||||
let mut out: Vec<SessionUsage> = Vec::new();
|
||||
let mut seen = HashSet::new();
|
||||
for distro in distros.into_iter().filter(|d| !d.is_empty() && seen.insert(d.clone())) {
|
||||
match collect_distro(&distro, cache) {
|
||||
Ok(mut v) => out.append(&mut v),
|
||||
Err(e) => tracing::warn!("usage scan for distro {distro} failed: {e}"),
|
||||
}
|
||||
}
|
||||
out.sort_by(|a, b| b.last_active_ms.cmp(&a.last_active_ms));
|
||||
out.truncate(MAX_SESSIONS);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn collect_distro(distro: &str, cache: &UsageCache) -> Result<Vec<SessionUsage>, String> {
|
||||
let home = resolve_home(distro, cache)?;
|
||||
let projects = projects_dir(distro, &home)
|
||||
.ok_or_else(|| format!("no ~/.claude/projects reachable for {distro}"))?;
|
||||
|
||||
// Gather candidate transcripts (path, project-dir name, mtime), newest first.
|
||||
let now = now_ms();
|
||||
let mut candidates: Vec<(PathBuf, String, i64)> = Vec::new();
|
||||
for proj in std::fs::read_dir(&projects).map_err(|e| e.to_string())?.flatten() {
|
||||
let proj_path = proj.path();
|
||||
if !proj_path.is_dir() {
|
||||
continue;
|
||||
}
|
||||
let proj_name = proj.file_name().to_string_lossy().into_owned();
|
||||
let inner = match std::fs::read_dir(&proj_path) {
|
||||
Ok(it) => it,
|
||||
Err(_) => continue,
|
||||
};
|
||||
for f in inner.flatten() {
|
||||
let p = f.path();
|
||||
if p.extension().and_then(|e| e.to_str()) != Some("jsonl") {
|
||||
continue;
|
||||
}
|
||||
let mtime = std::fs::metadata(&p)
|
||||
.ok()
|
||||
.and_then(|m| m.modified().ok())
|
||||
.and_then(sys_to_ms)
|
||||
.unwrap_or(0);
|
||||
if now - mtime > MAX_AGE_MS {
|
||||
continue;
|
||||
}
|
||||
candidates.push((p, proj_name.clone(), mtime));
|
||||
}
|
||||
}
|
||||
candidates.sort_by(|a, b| b.2.cmp(&a.2));
|
||||
candidates.truncate(MAX_SESSIONS);
|
||||
|
||||
let mut out = Vec::new();
|
||||
for (path, proj_name, mtime) in candidates {
|
||||
let (cwd, models) = match parse_or_cache(&path, cache) {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
tracing::debug!("skip transcript {}: {e}", path.display());
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let session_id = path
|
||||
.file_stem()
|
||||
.map(|s| s.to_string_lossy().into_owned())
|
||||
.unwrap_or_default();
|
||||
out.push(SessionUsage {
|
||||
session_id,
|
||||
cwd,
|
||||
project_dir: proj_name,
|
||||
distro: distro.to_string(),
|
||||
last_active_ms: mtime,
|
||||
models,
|
||||
});
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Probe `$HOME` inside the distro once and cache it. `sh -c` (not a login
|
||||
/// shell) so rc-file output can't contaminate stdout.
|
||||
fn resolve_home(distro: &str, cache: &UsageCache) -> Result<String, String> {
|
||||
if let Some(h) = cache.homes.lock().get(distro) {
|
||||
return Ok(h.clone());
|
||||
}
|
||||
let out = quiet_command("wsl.exe")
|
||||
.args(["-d", distro, "--", "sh", "-c", "printf %s \"$HOME\""])
|
||||
.output()
|
||||
.map_err(|e| format!("wsl.exe $HOME probe: {e}"))?;
|
||||
if !out.status.success() {
|
||||
return Err(format!("wsl.exe $HOME probe exited {:?}", out.status.code()));
|
||||
}
|
||||
let home = String::from_utf8_lossy(&out.stdout).trim().to_string();
|
||||
if home.is_empty() {
|
||||
return Err("empty $HOME".into());
|
||||
}
|
||||
cache.homes.lock().insert(distro.to_string(), home.clone());
|
||||
Ok(home)
|
||||
}
|
||||
|
||||
/// `~/.claude/projects` as a Windows UNC path into the distro. Tries the newer
|
||||
/// `\\wsl.localhost\` share first, then the legacy `\\wsl$\` alias.
|
||||
fn projects_dir(distro: &str, home: &str) -> Option<PathBuf> {
|
||||
let home_rel = home.trim_start_matches('/');
|
||||
for prefix in [
|
||||
format!(r"\\wsl.localhost\{distro}"),
|
||||
format!(r"\\wsl$\{distro}"),
|
||||
] {
|
||||
let p = PathBuf::from(prefix)
|
||||
.join(home_rel)
|
||||
.join(".claude")
|
||||
.join("projects");
|
||||
if p.is_dir() {
|
||||
return Some(p);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn parse_or_cache(path: &Path, cache: &UsageCache) -> Result<(String, Vec<ModelUsage>), String> {
|
||||
let meta = std::fs::metadata(path).map_err(|e| e.to_string())?;
|
||||
let size = meta.len();
|
||||
let mtime = meta.modified().ok().and_then(sys_to_ms).unwrap_or(0);
|
||||
if let Some(c) = cache.files.lock().get(path) {
|
||||
if c.size == size && c.mtime_ms == mtime {
|
||||
return Ok((c.cwd.clone(), c.models.clone()));
|
||||
}
|
||||
}
|
||||
let (cwd, models) = parse_file(path)?;
|
||||
cache.files.lock().insert(
|
||||
path.to_path_buf(),
|
||||
CachedFile {
|
||||
size,
|
||||
mtime_ms: mtime,
|
||||
cwd: cwd.clone(),
|
||||
models: models.clone(),
|
||||
},
|
||||
);
|
||||
Ok((cwd, models))
|
||||
}
|
||||
|
||||
fn parse_file(path: &Path) -> Result<(String, Vec<ModelUsage>), String> {
|
||||
let content = std::fs::read_to_string(path).map_err(|e| e.to_string())?;
|
||||
let mut cwd = String::new();
|
||||
let mut by_model: HashMap<String, ModelUsage> = HashMap::new();
|
||||
|
||||
for line in content.lines() {
|
||||
let line = line.trim();
|
||||
if line.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let v: serde_json::Value = match serde_json::from_str(line) {
|
||||
Ok(v) => v,
|
||||
Err(_) => continue, // tolerate a truncated final line / stray text
|
||||
};
|
||||
if cwd.is_empty() {
|
||||
if let Some(c) = v.get("cwd").and_then(|x| x.as_str()) {
|
||||
cwd = c.to_string();
|
||||
}
|
||||
}
|
||||
if v.get("type").and_then(|x| x.as_str()) != Some("assistant") {
|
||||
continue;
|
||||
}
|
||||
let msg = match v.get("message") {
|
||||
Some(m) => m,
|
||||
None => continue,
|
||||
};
|
||||
let usage = match msg.get("usage") {
|
||||
Some(u) => u,
|
||||
None => continue,
|
||||
};
|
||||
let model = msg
|
||||
.get("model")
|
||||
.and_then(|x| x.as_str())
|
||||
.unwrap_or("unknown")
|
||||
.to_string();
|
||||
let tok = |k: &str| usage.get(k).and_then(|x| x.as_u64()).unwrap_or(0);
|
||||
let entry = by_model.entry(model.clone()).or_insert_with(|| ModelUsage {
|
||||
model,
|
||||
input_tokens: 0,
|
||||
output_tokens: 0,
|
||||
cache_creation_tokens: 0,
|
||||
cache_read_tokens: 0,
|
||||
});
|
||||
entry.input_tokens += tok("input_tokens");
|
||||
entry.output_tokens += tok("output_tokens");
|
||||
entry.cache_creation_tokens += tok("cache_creation_input_tokens");
|
||||
entry.cache_read_tokens += tok("cache_read_input_tokens");
|
||||
}
|
||||
|
||||
let mut models: Vec<ModelUsage> = by_model.into_values().collect();
|
||||
models.sort_by(|a, b| b.output_tokens.cmp(&a.output_tokens));
|
||||
Ok((cwd, models))
|
||||
}
|
||||
|
||||
fn now_ms() -> i64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|d| d.as_millis() as i64)
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
fn sys_to_ms(t: SystemTime) -> Option<i64> {
|
||||
t.duration_since(UNIX_EPOCH).ok().map(|d| d.as_millis() as i64)
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue