Onset: version control where nobody waits and nothing gets lost. The on command, its core and onset-server.
| 6 | //! never reaches git. Nothing is recorded between lands, and nothing but |
| 7 | //! the agent's own session. `on sessions off` stops it on this machine |
| 8 | //! (`ONSET_SESSIONS=0` for one command); `on sessions delete` removes what |
| 9 | //! was kept, here and on the host. |
| 10 | //! |
| 11 | //! Agents found: Claude Code (by its session ID), Codex (its session in |
| 12 | //! this folder, written to in the last 10 minutes), and any other that |
| 13 | //! names its session file in ONSET_SESSION_FILE. |
| 14 |
| 15 | use std::path::{Path, PathBuf}; |
| 16 | use std::time::{Duration, SystemTime}; |
| 17 |
| 18 | use anyhow::{Result, anyhow}; |
| 19 | use serde::Deserialize; |
| 20 | use serde_json::{Value, json}; |
| 21 |
| 22 | use crate::app::{App, Session}; |
| 23 | use crate::db::{Change, Project, SessionRow}; |
| 24 | use crate::ids; |
| 25 | use crate::out::{Fail, Out, Report}; |
| 26 | use crate::paths; |
| 27 | use crate::remote::Remote; |
| 28 |
| 29 | /// The most of one session kept with a change. |
| 30 | const MAX_BYTES: usize = 50 << 20; |
| 31 | /// How recently a session found by its folder must have been written to. |
| 32 | const RECENT: Duration = Duration::from_secs(600); |
| 33 |
| 34 | fn off_file() -> PathBuf { |
| 35 | paths::home().join("sessions-off") |
| 36 | } |
| 37 |
| 38 | /// Whether sessions are kept on this machine (and for this command). |
| 39 | pub fn enabled() -> bool { |
| 40 | crate::paths::var("SESSIONS").as_deref() != Some("0") && !off_file().exists() |
| 41 | } |
| 42 |
| 43 | /// An agent session that's working in a workspace. |
| 44 | struct Found { |
| 45 | agent: String, |
| 46 | /// What it's known by across lands (its ID, or its file). |
| 47 | key: String, |
| 48 | path: PathBuf, |
| 49 | } |
| 50 |
| 51 | fn user_home() -> Option<PathBuf> { |
| 52 | std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" }).map(PathBuf::from) |
| 53 | } |
| 54 |
| 55 | fn recent(path: &Path) -> bool { |
| 56 | path.metadata().and_then(|m| m.modified()).ok().and_then(|t| SystemTime::now().duration_since(t).ok()).is_some_and(|age| age < RECENT) |
| 57 | } |
| 58 |
| 59 | /// Claude Code keeps a session per project folder, named as the folder with |
| 60 | /// everything but letters, digits and dashes turned into dashes. |
| 61 | fn claude_slug(dir: &Path) -> String { |
| 62 | dir.to_string_lossy().chars().map(|c| if c.is_ascii_alphanumeric() || c == '-' { c } else { '-' }).collect() |
| 63 | } |
| 64 |
| 65 | fn find_session(root: &Path) -> Option<Found> { |
| 66 | if let Some(file) = crate::paths::var_os("SESSION_FILE").map(PathBuf::from).filter(|p| p.is_file()) { |
| 67 | let agent = crate::paths::var("SESSION_AGENT").filter(|a| !a.trim().is_empty()).unwrap_or_else(|| "agent".into()); |
| 68 | return Some(Found { agent, key: format!("file:{}", file.display()), path: file }); |
| 69 | } |
| 70 | let claude = std::env::var_os("CLAUDE_CONFIG_DIR").map(PathBuf::from).or_else(|| user_home().map(|h| h.join(".claude")))?.join("projects"); |
| 71 | if let Ok(id) = std::env::var("CLAUDE_CODE_SESSION_ID") |
| 72 | && !id.is_empty() |
| 73 | && !id.contains(['/', '\\']) |
| 74 | { |
| 75 | for dir in std::fs::read_dir(&claude).ok()?.flatten() { |
| 76 | let file = dir.path().join(format!("{id}.jsonl")); |
| 77 | if file.is_file() { |
| 78 | return Some(Found { agent: "Claude Code".into(), key: format!("claude:{id}"), path: file }); |
| 79 | } |
| 80 | } |
| 81 | } |
| 82 | if std::env::var("CLAUDECODE").ok().as_deref() == Some("1") { |
| 83 | // An older Claude Code: its newest session in this folder or one holding it. |
| 84 | for dir in root.ancestors() { |
| 85 | let newest = std::fs::read_dir(claude.join(claude_slug(dir))) |
| 86 | .ok() |
| 87 | .into_iter() |
| 88 | .flatten() |
| 89 | .flatten() |
| 90 | .map(|e| e.path()) |
| 91 | .filter(|p| p.extension().is_some_and(|x| x == "jsonl") && recent(p)) |
| 92 | .max_by_key(|p| p.metadata().and_then(|m| m.modified()).ok()); |
| 93 | if let Some(path) = newest { |
| 94 | let id = path.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default(); |
| 95 | return Some(Found { agent: "Claude Code".into(), key: format!("claude:{id}"), path }); |
| 96 | } |
| 97 | } |
| 98 | } |
| 99 | codex_session(root) |
| 100 | } |
| 101 |
| 102 | /// Codex writes each session to CODEX_HOME/sessions/<year>/<month>/<day>/, |
| 103 | /// its first line naming the folder it works in. |
| 104 | fn codex_session(root: &Path) -> Option<Found> { |
| 105 | let base = std::env::var_os("CODEX_HOME").map(PathBuf::from).or_else(|| user_home().map(|h| h.join(".codex")))?.join("sessions"); |
| 106 | let mut best: Option<(SystemTime, PathBuf, String)> = None; |
| 107 | let mut stack = vec![(base, 0)]; |
| 108 | while let Some((dir, depth)) = stack.pop() { |
| 109 | for e in std::fs::read_dir(&dir).ok()?.flatten() { |
| 110 | let path = e.path(); |
| 111 | let Ok(meta) = e.metadata() else { continue }; |
| 112 | let Ok(modified) = meta.modified() else { continue }; |
| 113 | // Only folders and files touched lately. |
| 114 | if SystemTime::now().duration_since(modified).is_ok_and(|age| age > if meta.is_dir() { Duration::from_secs(3 * 86_400) } else { RECENT }) { |
| 115 | continue; |
| 116 | } |
| 117 | if meta.is_dir() && depth < 3 { |
| 118 | stack.push((path, depth + 1)); |
| 119 | } else if meta.is_file() && path.extension().is_some_and(|x| x == "jsonl") && best.as_ref().is_none_or(|(t, _, _)| modified > *t) { |
| 120 | let first = std::io::BufRead::lines(std::io::BufReader::new(std::fs::File::open(&path).ok()?)).next()?.ok()?; |
| 121 | let meta: Value = serde_json::from_str(&first).ok()?; |
| 122 | let cwd = meta["payload"]["cwd"].as_str().map(PathBuf::from)?; |
| 123 | let cwd = crate::sys::canonical(&cwd).unwrap_or(cwd); |
| 124 | if root.starts_with(&cwd) || cwd.starts_with(root) { |
| 125 | let id = meta["payload"]["id"].as_str().unwrap_or_default().to_string(); |
| 126 | best = Some((modified, path, id)); |
| 127 | } |
| 128 | } |
| 129 | } |
| 130 | } |
| 131 | best.map(|(_, path, id)| Found { agent: "Codex".into(), key: format!("codex:{id}"), path }) |
| 132 | } |
| 133 |
| 134 | /// The messages in a session's turns (what someone asked and what the agent said), and the commands it ran. |
| 135 | fn counts(turns: &[(String, String)]) -> (u64, u64) { |
| 136 | let messages = turns.iter().filter(|(who, _)| who == "you" || who == "agent" || who == "text").count() as u64; |
| 137 | (messages, turns.len() as u64 - messages) |
| 138 | } |
| 139 |
| 140 | /// What a session file gained since a land. |
| 141 | enum New { |
| 142 | /// No new whole line. |
| 143 | Nothing, |
| 144 | /// The new whole lines, and where they end. |
| 145 | Text(Vec<u8>, u64), |
| 146 | /// More than the most kept, not read; where it ends. |
| 147 | TooBig(u64), |
| 148 | } |
| 149 |
| 150 | /// What `path` gained after byte `from`, up to the end of its last whole |
| 151 | /// line (the agent may be writing one). Only that part is read: sessions |
| 152 | /// grow to hundreds of megabytes. |
| 153 | fn read_new(path: &Path, from: u64, max: usize) -> std::io::Result<New> { |
| 154 | use std::io::{Read, Seek, SeekFrom}; |
| 155 | let mut file = std::fs::File::open(path)?; |
| 156 | let len = file.metadata()?.len(); |
| 157 | let from = if from <= len { from } else { 0 }; |
| 158 | let tail = (len - from).min(1 << 20); |
| 159 | let mut buf = vec![0u8; tail as usize]; |
| 160 | file.seek(SeekFrom::Start(len - tail))?; |
| 161 | file.read_exact(&mut buf)?; |
| 162 | let end = match buf.iter().rposition(|b| *b == b'\n') { |
| 163 | Some(i) => len - tail + i as u64 + 1, |
| 164 | // One line longer than what was looked at: past the most kept, or not finished yet. |
| 165 | None if len - from > tail => return Ok(New::TooBig(len - tail)), |
| 166 | None => return Ok(New::Nothing), |
| 167 | }; |
| 168 | if end - from > max as u64 { |
| 169 | return Ok(New::TooBig(end)); |
| 170 | } |
| 171 | let mut out = vec![0u8; (end - from) as usize]; |
| 172 | file.seek(SeekFrom::Start(from))?; |
| 173 | file.read_exact(&mut out)?; |
| 174 | Ok(New::Text(out, end)) |
| 175 | } |
| 176 |
| 177 | /// Keeps the session of the agent working in this workspace with change `c` |
| 178 | /// (when sessions are on and there is one). Answers a line for the land's |
| 179 | /// report; a failure to keep it never stops a land. |
| 180 | pub fn keep_for(app: &App, s: &Session, c: &Change) -> Option<String> { |
| 181 | if !enabled() { |
| 182 | return None; |
| 183 | } |
| 184 | let found = find_session(&s.root)?; |
| 185 | match keep(app, &s.project, c, &found) { |
| 186 | Ok(line) => line, |
| 187 | Err(e) => Some(format!("couldn't keep the agent session: {e:#}")), |
| 188 | } |
| 189 | } |
| 190 |
| 191 | fn keep(app: &App, project: &Project, c: &Change, found: &Found) -> Result<Option<String>> { |
| 192 | let mark = app.db.session_mark(&found.key)?; |
| 193 | let (bytes, end) = match read_new(&found.path, mark, MAX_BYTES)? { |
| 194 | New::Nothing => return Ok(None), |
| 195 | New::TooBig(end) => { |
| 196 | app.db.set_session_mark(&found.key, end)?; |
| 197 | return Ok(Some(format!("{}'s session since the last land is over 50 MB, so it wasn't kept", found.agent))); |
| 198 | } |
| 199 | New::Text(bytes, end) => (bytes, end), |
| 200 | }; |
| 201 | let (text, removed) = onset_core::secrets::redact(&String::from_utf8_lossy(&bytes)); |
| 202 | let turns = render(&found.agent, &text); |
| 203 | // Nothing anyone said or ran (only the agent's bookkeeping): nothing to keep. |
| 204 | if turns.is_empty() { |
| 205 | app.db.set_session_mark(&found.key, end)?; |
| 206 | return Ok(None); |
| 207 | } |
| 208 | let (messages, commands) = counts(&turns); |
| 209 | let mut row = SessionRow { n: 0, agent: found.agent.clone(), file: app.store.put_file(text.as_bytes())?, bytes: text.len() as u64, messages, at: ids::now() }; |
| 210 | if project.hosted() { |
| 211 | let remote = Remote::for_project(project); |
| 212 | remote.upload(&app.store, &app.store.file_parts(&row.file)?)?; |
| 213 | #[derive(Deserialize)] |
| 214 | struct Kept { |
| 215 | n: u64, |
| 216 | } |
| 217 | let kept: Kept = remote.send_json("PUT", &format!("/changes/{}/sessions", c.id), &row)?; |
| 218 | row.n = kept.n; |
| 219 | } |
| 220 | app.db.add_session(&c.id, &row)?; |
| 221 | app.db.set_session_mark(&found.key, end)?; |
| 222 | let plural = |n: u64, one: &str, many: &str| format!("{n} {}", if n == 1 { one } else { many }); |
| 223 | let what = match (messages, commands) { |
| 224 | (m, 0) => plural(m, "message", "messages"), |
| 225 | (0, r) => plural(r, "command", "commands"), |
| 226 | (m, r) => format!("{} and {}", plural(m, "message", "messages"), plural(r, "command", "commands")), |
| 227 | }; |
| 228 | let mut line = format!("{}, {what}, kept with the change; only you see it", found.agent); |
| 229 | if removed > 0 { |
| 230 | line.push_str(&format!(" ({removed} {} removed)", if removed == 1 { "secret" } else { "secrets" })); |
| 231 | } |
| 232 | // The first time on this machine, how to stop it. |
| 233 | let told = paths::home().join("sessions-told"); |
| 234 | if !told.exists() { |
| 235 | let _ = std::fs::write(&told, ""); |
| 236 | line.push_str(". on sessions off stops this"); |
| 237 | } |
| 238 | Ok(Some(line)) |
| 239 | } |
| 240 |
| 241 | /// A session's text as turns: ("you" | "agent" | "ran", text). |
| 242 | pub fn render(agent: &str, text: &str) -> Vec<(String, String)> { |
| 243 | let mut out = Vec::new(); |
| 244 | let short = |s: &str| { |
| 245 | let s = s.trim().replace('\n', " "); |
| 246 | if s.chars().count() > 200 { format!("{}…", s.chars().take(200).collect::<String>()) } else { s } |
| 247 | }; |
| 248 | for line in text.lines() { |
| 249 | let Ok(v) = serde_json::from_str::<Value>(line) else { |
| 250 | if agent != "Claude Code" && agent != "Codex" && !line.trim().is_empty() { |
| 251 | out.push(("text".into(), line.to_string())); |
| 252 | } |
| 253 | continue; |
| 254 | }; |
| 255 | match agent { |
| 256 | "Claude Code" => { |
| 257 | let who = match v["type"].as_str() { |
| 258 | Some("user") => "you", |
| 259 | Some("assistant") => "agent", |
| 260 | _ => continue, |
| 261 | }; |
| 262 | match &v["message"]["content"] { |
| 263 | Value::String(s) if !s.trim().is_empty() => out.push((who.into(), s.trim().to_string())), |
| 264 | Value::Array(items) => { |
| 265 | for item in items { |
| 266 | match item["type"].as_str() { |
| 267 | Some("text") => { |
| 268 | let t = item["text"].as_str().unwrap_or("").trim(); |
| 269 | if !t.is_empty() { |
| 270 | out.push((who.into(), t.to_string())); |
| 271 | } |
| 272 | } |
| 273 | Some("tool_use") => { |
| 274 | let input = &item["input"]; |
| 275 | let what = ["command", "file_path", "path", "pattern", "url", "description", "prompt"].iter().find_map(|k| input[*k].as_str()).unwrap_or(""); |
| 276 | out.push(("ran".into(), format!("{} {}", item["name"].as_str().unwrap_or("tool"), short(what)))); |
| 277 | } |
| 278 | _ => {} |
| 279 | } |
| 280 | } |
| 281 | } |
| 282 | _ => {} |
| 283 | } |
| 284 | } |
| 285 | "Codex" => { |
| 286 | let p = &v["payload"]; |
| 287 | match (v["type"].as_str(), p["type"].as_str()) { |
| 288 | (Some("response_item"), Some("message")) => { |
| 289 | let who = match p["role"].as_str() { |
| 290 | Some("user") => "you", |
| 291 | Some("assistant") => "agent", |
| 292 | _ => continue, |
| 293 | }; |
| 294 | for item in p["content"].as_array().into_iter().flatten() { |
| 295 | let t = item["text"].as_str().unwrap_or("").trim(); |
| 296 | if !t.is_empty() { |
| 297 | out.push((who.into(), t.to_string())); |
| 298 | } |
| 299 | } |
| 300 | } |
| 301 | (Some("response_item"), Some("function_call" | "custom_tool_call")) => { |
| 302 | let args = p["arguments"].as_str().or(p["input"].as_str()).unwrap_or(""); |
| 303 | let what = serde_json::from_str::<Value>(args).ok().and_then(|a| a["command"].as_str().map(str::to_string).or_else(|| a["cmd"].as_str().map(str::to_string))).unwrap_or_else(|| args.to_string()); |
| 304 | out.push(("ran".into(), format!("{} {}", p["name"].as_str().unwrap_or("tool"), short(&what)))); |
| 305 | } |
| 306 | _ => {} |
| 307 | } |
| 308 | } |
| 309 | _ => out.push(("text".into(), line.to_string())), |
| 310 | } |
| 311 | } |
| 312 | out |
| 313 | } |
| 314 |
| 315 | /// One kept session's text: here, or from the host. |
| 316 | fn text_of(app: &App, project: &Project, change: &str, row: &SessionRow) -> Result<String> { |
| 317 | if let Ok(bytes) = app.store.read_file(&row.file) { |
| 318 | return Ok(String::from_utf8_lossy(&bytes).into_owned()); |
| 319 | } |
| 320 | if !project.hosted() { |
| 321 | return Err(anyhow!("session {} of change {change} isn't on this machine", row.n)); |
| 322 | } |
| 323 | app.store.ingest(&Remote::for_project(project).get_bytes(&format!("/changes/{change}/sessions/{}", row.n))?)?; |
| 324 | Ok(String::from_utf8_lossy(&app.store.read_file(&row.file)?).into_owned()) |
| 325 | } |
| 326 |
| 327 | /// A change's kept sessions: from the host for a hosted project (so another machine's too). |
| 328 | fn sessions_of(app: &App, project: &Project, change: &str) -> Result<Vec<SessionRow>> { |
| 329 | if !project.hosted() { |
| 330 | return Ok(app.db.sessions(change)?); |
| 331 | } |
| 332 | #[derive(Deserialize)] |
| 333 | struct List { |
| 334 | sessions: Vec<SessionRow>, |
| 335 | } |
| 336 | Ok(Remote::for_project(project).get_json::<List>(&format!("/changes/{change}/sessions"))?.sessions) |
| 337 | } |
| 338 |
| 339 | #[derive(Debug, Clone, clap::Subcommand)] |
| 340 | pub enum Action { |
| 341 | /// Keep agent sessions with changes on this machine (the default). |
| 342 | On, |
| 343 | /// Stop keeping them on this machine. |
| 344 | Off, |
| 345 | /// Print what the agent was asked, said and ran for a change. |
| 346 | Show { |
| 347 | change: String, |
| 348 | /// The session as it was kept, line by line. |
| 349 | #[arg(long)] |
| 350 | raw: bool, |
| 351 | }, |
| 352 | /// Delete the sessions kept with a change (or --all of yours in this project), here and on the host. |
| 353 | Delete { |
| 354 | change: Option<String>, |
| 355 | #[arg(long)] |
| 356 | all: bool, |
| 357 | }, |
| 358 | } |
| 359 |
| 360 | /// `on sessions [on | off | show <change> | delete <change> | delete --all]`. |
| 361 | pub fn run(app: &App, action: Option<Action>) -> Out { |
| 362 | let mut r = Report::new(); |
| 363 | match action { |
| 364 | None => { |
| 365 | let on = enabled(); |
| 366 | r.line("sessions", if on { "on: an agent's session is kept with each change it lands; only you see it" } else { "off on this machine" }); |
| 367 | r.set("on", on); |
| 368 | if let Ok(s) = app.session() { |
| 369 | let mine = if s.project.hosted() { |
| 370 | #[derive(Deserialize)] |
| 371 | struct Mine { |
| 372 | change: String, |
| 373 | #[serde(flatten)] |
| 374 | session: SessionRow, |
| 375 | } |
| 376 | #[derive(Deserialize)] |
| 377 | struct List { |
| 378 | sessions: Vec<Mine>, |
| 379 | } |
| 380 | Remote::for_project(&s.project).get_json::<List>("/sessions")?.sessions.into_iter().map(|m| (m.change, m.session)).collect() |
| 381 | } else { |
| 382 | app.db.project_sessions(&s.project.id)? |
| 383 | }; |
| 384 | for (change, row) in mine.iter().take(20) { |
| 385 | r.line("kept", format!("{} {}, {} messages, {}", app.short(&s.project, change), row.agent, row.messages, ids::ago(row.at))); |
| 386 | } |
| 387 | r.set("sessions", mine.iter().map(|(c, row)| json!({ "change": c, "session": row })).collect::<Vec<_>>()); |
| 388 | } |
| 389 | r.next(if on { "on sessions off to stop keeping them; on sessions delete --all removes the ones kept" } else { "on sessions on to keep them again" }); |
| 390 | } |
| 391 | Some(Action::On) => { |
| 392 | let _ = std::fs::remove_file(off_file()); |
| 393 | r.line("sessions", "on: an agent's session is kept with each change it lands; only you see it"); |
| 394 | r.set("on", true); |
| 395 | } |
| 396 | Some(Action::Off) => { |
| 397 | std::fs::create_dir_all(paths::home())?; |
| 398 | std::fs::write(off_file(), "")?; |
| 399 | r.line("sessions", "off: nothing more is kept on this machine"); |
| 400 | r.set("on", false); |
| 401 | r.next("on sessions delete --all removes the ones already kept"); |
| 402 | } |
| 403 | Some(Action::Show { change, raw }) => { |
| 404 | let s = app.session()?; |
| 405 | let c = app.find_change(&s.project, &change)?; |
| 406 | let list = sessions_of(app, &s.project, &c.id)?; |
| 407 | if list.is_empty() { |
| 408 | r.line("sessions", format!("none kept with {} (or you can't see them)", app.short(&s.project, &c.id))); |
| 409 | } |
| 410 | let mut turns = Vec::new(); |
| 411 | for row in &list { |
| 412 | let text = text_of(app, &s.project, &c.id, row)?; |
| 413 | r.raw(format!("── {} session {}, {} messages, {}\n", row.agent, row.n, row.messages, ids::ago(row.at))); |
| 414 | if raw { |
| 415 | r.raw(text.clone()); |
| 416 | continue; |
| 417 | } |
| 418 | for (who, what) in render(&row.agent, &text) { |
| 419 | r.raw(match who.as_str() { |
| 420 | "ran" => format!(" ran {what}\n"), |
| 421 | "text" => format!("{what}\n"), |
| 422 | _ => format!("{who}: {what}\n\n"), |
| 423 | }); |
| 424 | turns.push(json!({ "session": row.n, "who": who, "text": what })); |
| 425 | } |
| 426 | } |
| 427 | r.set("change", c.id.clone()).set("sessions", serde_json::to_value(&list).unwrap_or_default()).set("turns", turns); |
| 428 | } |
| 429 | Some(Action::Delete { change, all }) => { |
| 430 | let s = app.session()?; |
| 431 | let which = match (change, all) { |
| 432 | (Some(text), false) => Some(app.find_change(&s.project, &text)?.id), |
| 433 | (None, true) => None, |
| 434 | _ => return Err(Fail::new("bad_usage", "name a change, or --all for every session of yours in this project").state("nothing changed")), |
| 435 | }; |
| 436 | if s.project.hosted() { |
| 437 | let remote = Remote::for_project(&s.project); |
| 438 | let _: Value = match &which { |
| 439 | Some(id) => remote.send_json("POST", &format!("/changes/{id}/sessions/delete"), &json!({}))?, |
| 440 | None => remote.send_json("POST", "/sessions/delete", &json!({}))?, |
| 441 | }; |
| 442 | } |
| 443 | let files: Vec<onset_core::Id> = match &which { |
| 444 | Some(id) => app.db.sessions(id)?.into_iter().map(|r| r.file).collect(), |
| 445 | None => app.db.project_sessions(&s.project.id)?.into_iter().map(|(_, r)| r.file).collect(), |
| 446 | }; |
| 447 | let gone = app.db.delete_sessions(&s.project.id, which.as_deref())?; |
| 448 | // Their text goes from this machine too, unless something else here has the same bytes. |
| 449 | let live = crate::gc::live_objects(app, 0)?; |
| 450 | for file in files { |
| 451 | for part in app.store.file_parts(&file).unwrap_or_else(|_| vec![file]) { |
| 452 | if !live.contains(&part) { |
| 453 | app.store.remove(&part); |
| 454 | } |
| 455 | } |
| 456 | } |
| 457 | r.line("deleted", match &which { |
| 458 | Some(id) => format!("the sessions kept with {}", app.short(&s.project, id)), |
| 459 | None => "every session of yours kept in this project".to_string(), |
| 460 | }); |
| 461 | r.set("deleted", gone); |
| 462 | } |
| 463 | } |
| 464 | Ok(r) |
| 465 | } |
| 466 |
| 467 | #[cfg(test)] |
| 468 | mod tests { |
| 469 | use super::*; |
| 470 |
| 471 | #[test] |
| 472 | fn renders_claude_code_turns() { |
| 473 | let text = [ |
| 474 | r#"{"type":"user","message":{"role":"user","content":"add a login page"}}"#, |
| 475 | r#"{"type":"assistant","message":{"content":[{"type":"text","text":"Adding it."},{"type":"tool_use","name":"Bash","input":{"command":"on land -m 'Login'"}}]}}"#, |
| 476 | r#"{"type":"user","message":{"content":[{"type":"tool_result","content":"landed"}]}}"#, |
| 477 | ] |
| 478 | .join("\n"); |
| 479 | let turns = render("Claude Code", &text); |
| 480 | assert_eq!(turns, vec![("you".into(), "add a login page".into()), ("agent".into(), "Adding it.".into()), ("ran".into(), "Bash on land -m 'Login'".into())]); |
| 481 | assert_eq!(counts(&turns), (2, 1)); |
| 482 | } |
| 483 |
| 484 | #[test] |
| 485 | fn reads_only_what_came_after_the_mark() { |
| 486 | let dir = tempfile::tempdir().unwrap(); |
| 487 | let path = dir.path().join("s.jsonl"); |
| 488 | std::fs::write(&path, "one\ntwo\nthr").unwrap(); |
| 489 | // Up to the last whole line. |
| 490 | let New::Text(text, end) = read_new(&path, 0, 1 << 20).unwrap() else { panic!() }; |
| 491 | assert_eq!((text.as_slice(), end), (&b"one\ntwo\n"[..], 8)); |
| 492 | // Nothing whole after it yet. |
| 493 | assert!(matches!(read_new(&path, 8, 1 << 20).unwrap(), New::Nothing)); |
| 494 | std::fs::write(&path, "one\ntwo\nthree\n").unwrap(); |
| 495 | let New::Text(text, _) = read_new(&path, 8, 1 << 20).unwrap() else { panic!() }; |
| 496 | assert_eq!(text, b"three\n"); |
| 497 | // More than the most kept: skipped, up to its last line. |
| 498 | assert!(matches!(read_new(&path, 0, 4).unwrap(), New::TooBig(14))); |
| 499 | // A file that shrank (a new session under the same name) starts over. |
| 500 | let New::Text(text, _) = read_new(&path, 99, 1 << 20).unwrap() else { panic!() }; |
| 501 | assert_eq!(text, b"one\ntwo\nthree\n"); |
| 502 | } |
| 503 |
| 504 | #[test] |
| 505 | fn renders_codex_turns() { |
| 506 | let text = [ |
| 507 | r#"{"type":"session_meta","payload":{"id":"x","cwd":"/w"}}"#, |
| 508 | r#"{"type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"fix the test"}]}}"#, |
| 509 | r#"{"type":"response_item","payload":{"type":"function_call","name":"shell","arguments":"{\"command\":\"cargo test\"}"}}"#, |
| 510 | r#"{"type":"response_item","payload":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"Fixed."}]}}"#, |
| 511 | ] |
| 512 | .join("\n"); |
| 513 | assert_eq!(render("Codex", &text), vec![("you".into(), "fix the test".into()), ("ran".into(), "shell cargo test".into()), ("agent".into(), "Fixed.".into())]); |
| 514 | } |
| 515 |
| 516 | #[test] |
| 517 | fn claude_folders() { |
| 518 | assert_eq!(claude_slug(Path::new("/home/u/coline-app/.claude/worktrees/a_b")), "-home-u-coline-app--claude-worktrees-a-b"); |
| 519 | } |
| 520 | } |
| 521 |