1use serde::{Deserialize, Serialize};
6use std::ffi::OsStr;
7use std::fs::OpenOptions;
8use std::io::{BufRead, BufReader, Write};
9use std::path::{Path, PathBuf};
10
11pub fn default_path() -> Option<PathBuf> {
19 path_from(
20 std::env::var_os("BLYTE_USAGE_LOG").as_deref(),
21 std::env::var_os("XDG_STATE_HOME").as_deref(),
22 std::env::var_os("HOME").as_deref(),
23 )
24}
25
26pub fn path_from(
28 log: Option<&OsStr>,
29 xdg: Option<&OsStr>,
30 home: Option<&OsStr>,
31) -> Option<PathBuf> {
32 if let Some(log) = log.filter(|s| !s.is_empty()) {
33 if log == "off" {
34 return None;
35 }
36 return Some(PathBuf::from(log));
37 }
38 if let Some(xdg) = xdg.filter(|s| !s.is_empty()) {
39 return Some(Path::new(xdg).join("blyte").join("usage.jsonl"));
40 }
41 if let Some(home) = home.filter(|s| !s.is_empty()) {
42 return Some(
43 Path::new(home)
44 .join(".local")
45 .join("state")
46 .join("blyte")
47 .join("usage.jsonl"),
48 );
49 }
50 None
51}
52
53pub fn session_from(blyte: Option<String>, claude: Option<String>) -> Option<String> {
57 blyte
58 .filter(|s| !s.trim().is_empty())
59 .or_else(|| claude.filter(|s| !s.trim().is_empty()))
60}
61
62pub const SURFACE_ID_ENV: &str = "BLYTE_SURFACE_ID";
63pub const SURFACE_NAME_ENV: &str = "BLYTE_SURFACE_NAME";
64
65pub fn surface_from(id: Option<String>, name: Option<String>) -> (Option<String>, Option<String>) {
67 let Some(id) = id.filter(|s| !s.trim().is_empty()) else {
68 return (None, None);
69 };
70 let name = name.filter(|s| !s.trim().is_empty());
71 (Some(id), name)
72}
73
74#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
76pub struct Entry {
77 pub ts: u64,
78 pub repo: String,
79 #[serde(default, skip_serializing_if = "Option::is_none")]
80 pub session: Option<String>,
81 #[serde(default, skip_serializing_if = "Option::is_none")]
82 pub surface: Option<String>,
83 #[serde(default, skip_serializing_if = "Option::is_none")]
84 pub surface_name: Option<String>,
85 #[serde(default, skip_serializing_if = "Option::is_none")]
86 pub dispatch: Option<String>,
87 pub research: bool,
88 pub model: String,
89 pub outcome: String,
90 pub turns: u32,
91 pub input: u64,
92 pub cached: u64,
93 pub output: u64,
94 pub thinking: u64,
95 #[serde(default)]
96 pub cost_usd: Option<f64>,
97}
98
99pub fn repo_of(root: &Path) -> String {
101 let mut prefix = PathBuf::new();
102 let mut found = false;
103 for component in root.components() {
104 if component.as_os_str() == ".wt" {
105 found = true;
106 break;
107 }
108 prefix.push(component);
109 }
110 if found {
111 prefix.to_string_lossy().into_owned()
112 } else {
113 root.to_string_lossy().into_owned()
114 }
115}
116
117pub fn append(path: &Path, entry: &Entry) -> std::io::Result<()> {
121 if let Some(parent) = path.parent() {
122 if !parent.as_os_str().is_empty() {
123 std::fs::create_dir_all(parent)?;
124 }
125 }
126 let mut file = OpenOptions::new().create(true).append(true).open(path)?;
127 let mut line = serde_json::to_vec(entry)
128 .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
129 line.push(b'\n');
130 file.write_all(&line)?;
131 Ok(())
132}
133
134pub fn read(path: &Path) -> Vec<Entry> {
138 let Ok(file) = std::fs::File::open(path) else {
139 return Vec::new();
140 };
141 let reader = BufReader::new(file);
142 let mut entries = Vec::new();
143 for line in reader.lines() {
144 let Ok(line) = line else {
145 continue;
146 };
147 let trimmed = line.trim();
148 if trimmed.is_empty() {
149 continue;
150 }
151 if let Ok(entry) = serde_json::from_str::<Entry>(trimmed) {
152 entries.push(entry);
153 }
154 }
155 entries
156}
157
158#[cfg(test)]
159pub(crate) static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
160
161#[cfg(test)]
162mod tests {
163 use super::*;
164 use std::ffi::OsStr;
165
166 #[test]
167 fn test_path_from() {
168 assert_eq!(
170 path_from(
171 Some(OsStr::new("/x/u.jsonl")),
172 Some(OsStr::new("/xdg")),
173 Some(OsStr::new("/home")),
174 ),
175 Some(PathBuf::from("/x/u.jsonl"))
176 );
177
178 assert_eq!(
180 path_from(
181 Some(OsStr::new("off")),
182 Some(OsStr::new("/xdg")),
183 Some(OsStr::new("/home")),
184 ),
185 None
186 );
187
188 assert_eq!(
190 path_from(None, Some(OsStr::new("/xdg")), Some(OsStr::new("/home"))),
191 Some(PathBuf::from("/xdg/blyte/usage.jsonl"))
192 );
193
194 assert_eq!(
196 path_from(None, None, Some(OsStr::new("/home"))),
197 Some(PathBuf::from("/home/.local/state/blyte/usage.jsonl"))
198 );
199
200 assert_eq!(
202 path_from(
203 Some(OsStr::new("")),
204 Some(OsStr::new("")),
205 Some(OsStr::new("/home")),
206 ),
207 Some(PathBuf::from("/home/.local/state/blyte/usage.jsonl"))
208 );
209 assert_eq!(
210 path_from(
211 Some(OsStr::new("")),
212 Some(OsStr::new("/xdg")),
213 Some(OsStr::new("")),
214 ),
215 Some(PathBuf::from("/xdg/blyte/usage.jsonl"))
216 );
217 assert_eq!(
218 path_from(
219 Some(OsStr::new("")),
220 Some(OsStr::new("")),
221 Some(OsStr::new("")),
222 ),
223 None
224 );
225
226 assert_eq!(path_from(None, None, None), None);
228 }
229
230 #[test]
231 fn test_repo_of() {
232 assert_eq!(repo_of(Path::new("/r/.wt/T1")), "/r");
233 assert_eq!(repo_of(Path::new("/r")), "/r");
234 assert_eq!(repo_of(Path::new("/r/.wtx/a")), "/r/.wtx/a");
235 }
236
237 #[test]
238 fn test_append_twice_and_read() {
239 let tmp = tempfile::tempdir().unwrap();
240 let log_path = tmp.path().join("parent").join("sub").join("usage.jsonl");
241
242 let entry1 = Entry {
243 ts: 1700000000,
244 repo: "/repo/one".into(),
245 session: Some("sess-1".into()),
246 surface: None,
247 surface_name: None,
248 dispatch: Some("disp-1".into()),
249 research: false,
250 model: "claude-3-7-sonnet".into(),
251 outcome: "verified".into(),
252 turns: 3,
253 input: 1000,
254 cached: 200,
255 output: 300,
256 thinking: 50,
257 cost_usd: Some(0.015),
258 };
259
260 let entry2 = Entry {
261 ts: 1700000010,
262 repo: "/repo/two".into(),
263 session: None,
264 surface: None,
265 surface_name: None,
266 dispatch: None,
267 research: true,
268 model: "gemini-3.8-flash".into(),
269 outcome: "budgetexhausted".into(),
270 turns: 15,
271 input: 5000,
272 cached: 1000,
273 output: 800,
274 thinking: 0,
275 cost_usd: None,
276 };
277
278 append(&log_path, &entry1).expect("first append should succeed");
279
280 {
282 let mut f = OpenOptions::new()
283 .append(true)
284 .open(&log_path)
285 .expect("open log file to inject garbage");
286 f.write_all(b"not valid json here at all\n")
287 .expect("write garbage");
288 }
289
290 append(&log_path, &entry2).expect("second append should succeed");
291
292 let entries = read(&log_path);
293 assert_eq!(entries.len(), 2);
294 assert_eq!(entries[0], entry1);
295 assert_eq!(entries[1], entry2);
296 }
297
298 #[test]
299 fn test_session_none_serialization() {
300 let entry = Entry {
301 ts: 1700000000,
302 repo: "/r".into(),
303 session: None,
304 surface: None,
305 surface_name: None,
306 dispatch: None,
307 research: false,
308 model: "m".into(),
309 outcome: "verified".into(),
310 turns: 1,
311 input: 10,
312 cached: 0,
313 output: 5,
314 thinking: 0,
315 cost_usd: None,
316 };
317
318 let json_str = serde_json::to_string(&entry).unwrap();
319 assert!(
320 !json_str.contains("\"session\""),
321 "session key must be omitted when None"
322 );
323 assert!(
324 !json_str.contains("\"dispatch\""),
325 "dispatch key must be omitted when None"
326 );
327
328 let parsed: Entry = serde_json::from_str(&json_str).unwrap();
329 assert_eq!(parsed, entry);
330 }
331
332 #[test]
333 fn test_session_from() {
334 assert_eq!(
335 session_from(Some("b".into()), Some("c".into())),
336 Some("b".into())
337 );
338 assert_eq!(session_from(None, Some("c".into())), Some("c".into()));
339 assert_eq!(
340 session_from(Some("".into()), Some("c".into())),
341 Some("c".into())
342 );
343 assert_eq!(session_from(Some(" ".into()), None), None);
344 assert_eq!(session_from(None, None), None);
345 }
346
347 #[test]
348 fn the_ledger_is_off_under_cargo_test() {
349 let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
350 assert_eq!(default_path(), None);
351 }
352}