csess 0.8.1

Fast lister for Claude Code sessions in a folder and its subprojects
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
use crate::session::Session;
use anyhow::{Context, Result};
use chrono::{DateTime, Utc};
use comfy_table::presets::UTF8_BORDERS_ONLY;
use comfy_table::Table;
use serde::Serialize;
use serde_json::Value;
use std::fs;
use std::io::{BufRead, BufReader};

/// Version of the --json contract. Bump on any breaking change to JSON shape
/// (field rename/removal/retype). Additive fields don't require a bump.
pub const SCHEMA_VERSION: u32 = 3;

/// The list `--json` payload: a version tag wrapping the session array.
#[derive(Serialize)]
struct SessionList<'a> {
    schema_version: u32,
    sessions: &'a [Session],
}

/// Pretty JSON of the session list, tagged with `schema_version` (always valid, even when empty).
pub fn render_json(sessions: &[Session]) -> Result<String> {
    Ok(serde_json::to_string_pretty(&SessionList {
        schema_version: SCHEMA_VERSION,
        sessions,
    })?)
}

/// Human-readable aligned table with a trailing count.
pub fn render_table(sessions: &[Session], now: DateTime<Utc>) -> String {
    let mut table = Table::new();
    table.load_preset(UTF8_BORDERS_ONLY);
    table.set_header(vec![
        "SHORT",
        "NAME",
        "LAST ACTIVE",
        "MSGS",
        "SIZE",
        "BRANCH",
        "PATH",
    ]);
    for s in sessions {
        let name = truncate(&s.name.replace('\n', " "), 50);
        table.add_row(vec![
            s.short.clone(),
            name,
            relative_time(s.last_active, now),
            s.message_count.to_string(),
            human_size(s.size_bytes),
            s.git_branch.clone(),
            truncate(&s.cwd, 45),
        ]);
    }
    format!("{table}\n{} sessions", sessions.len())
}

/// One message in a session transcript, shaped for re-rendering a chat UI.
/// `content` is the raw Anthropic content (a string, or the array of
/// text/thinking/tool_use/tool_result blocks) exactly as Claude Code logged it.
///
/// The `is_meta`/`is_sidechain`/`user_type`/`entry_type`/`tool_use_result`
/// fields are verbatim passthroughs of the raw JSONL entry keys — csess does no
/// classification, so a consumer can suppress plumbing turns and attribute
/// subagent turns itself.
#[derive(Serialize)]
pub struct Message {
    /// csess's normalized side: "user" or "assistant".
    pub role: &'static str,
    /// Raw entry-level `type`. Mirrors `role` today (--show only surfaces
    /// user/assistant entries); passed through for a faithful contract.
    pub entry_type: String,
    pub timestamp: Option<DateTime<Utc>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub uuid: Option<String>,
    /// Raw `isMeta` — flags injected plumbing turns (skill-load / image-read /
    /// attachment echoes). Only the synthetic resume pair is dropped upstream,
    /// so genuine meta turns reach here tagged `true` for the consumer to suppress.
    pub is_meta: bool,
    /// Raw `isSidechain` — marks subagent (Task/Agent) turns.
    pub is_sidechain: bool,
    /// Raw `userType` (e.g. "external" for genuine human input). Absent when the
    /// entry omits it (typically assistant turns).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub user_type: Option<String>,
    pub content: Value,
    /// Raw `toolUseResult` sidecar Claude Code logs alongside a tool_result
    /// message (`structuredPatch` for Edit/Write, `stdout`/`stderr` for Bash,
    /// etc). Passed through verbatim so a UI can render diffs/output; only
    /// present on tool-result-carrying user messages.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_use_result: Option<Value>,
}

/// Full session object plus its messages, for `--show --json`.
#[derive(Serialize)]
struct Transcript<'a> {
    schema_version: u32,
    session_id: &'a str,
    name: &'a str,
    cwd: &'a str,
    created: Option<DateTime<Utc>>,
    git_branch: &'a str,
    version: &'a str,
    message_count: usize,
    messages: Vec<Message>,
}

/// Filter applied to a session's messages: by `role` and/or a case-insensitive
/// substring `grep` over the flattened (human-readable) message text.
#[derive(Clone, Copy, Default)]
pub struct MsgFilter<'a> {
    pub role: Option<&'a str>,
    pub grep: Option<&'a str>,
}

/// Collect a session's matching messages with no paging — for cross-session `--grep`.
pub fn collect_filtered(path: &str, filter: MsgFilter) -> Result<Vec<Message>> {
    collect_messages(path, None, None, filter)
}

/// Walk the .jsonl and pull out user/assistant messages with their timestamps.
/// `filter` (role/grep) is applied first, then `before` (a message uuid) drops it
/// and everything after — a scroll-up cursor; `limit` keeps only the last N (the tail).
fn collect_messages(
    path: &str,
    limit: Option<usize>,
    before: Option<&str>,
    filter: MsgFilter,
) -> Result<Vec<Message>> {
    let file = fs::File::open(path).with_context(|| format!("opening {path}"))?;
    let mut msgs = Vec::new();
    for line in BufReader::new(file).lines() {
        let line = match line {
            Ok(l) => l,
            Err(_) => continue,
        };
        let line = line.trim();
        if line.is_empty() {
            continue;
        }
        let v: Value = match serde_json::from_str(line) {
            Ok(v) => v,
            Err(_) => continue,
        };
        let role = match v.get("type").and_then(|t| t.as_str()) {
            Some("user") => "user",
            Some("assistant") => "assistant",
            _ => continue,
        };
        if crate::session::is_synthetic_entry(&v) {
            continue;
        }
        let content = match v.get("message").and_then(|m| m.get("content")) {
            Some(c) => c.clone(),
            None => continue,
        };
        let timestamp = v
            .get("timestamp")
            .and_then(|x| x.as_str())
            .and_then(|s| DateTime::parse_from_rfc3339(s).ok())
            .map(|d| d.with_timezone(&Utc));
        let uuid = v
            .get("uuid")
            .and_then(|x| x.as_str())
            .map(|s| s.to_string());
        let is_meta = v.get("isMeta").and_then(|b| b.as_bool()).unwrap_or(false);
        let is_sidechain = v
            .get("isSidechain")
            .and_then(|b| b.as_bool())
            .unwrap_or(false);
        let user_type = v
            .get("userType")
            .and_then(|x| x.as_str())
            .map(|s| s.to_string());
        msgs.push(Message {
            role,
            entry_type: role.to_string(),
            timestamp,
            uuid,
            is_meta,
            is_sidechain,
            user_type,
            content,
            tool_use_result: v.get("toolUseResult").cloned(),
        });
    }
    if let Some(r) = filter.role {
        msgs.retain(|m| m.role == r);
    }
    if let Some(pat) = filter.grep {
        let pat = pat.to_lowercase();
        msgs.retain(|m| {
            flatten_content(&m.content).is_some_and(|t| t.to_lowercase().contains(&pat))
        });
    }
    if let Some(cur) = before {
        if let Some(i) = msgs.iter().position(|m| m.uuid.as_deref() == Some(cur)) {
            msgs.truncate(i);
        }
    }
    if let Some(n) = limit {
        let start = msgs.len().saturating_sub(n);
        msgs.drain(..start);
    }
    Ok(msgs)
}

/// Full conversation transcript for a single session, header followed by each message.
pub fn render_transcript(
    s: &Session,
    limit: Option<usize>,
    before: Option<&str>,
    filter: MsgFilter,
) -> Result<String> {
    let mut out = format!("# {}\n", s.name.replace('\n', " "));
    out.push_str(&format!("id: {}\n", s.session_id));
    out.push_str(&format!("cwd: {}\n", s.cwd));
    if let Some(c) = s.created {
        out.push_str(&format!("created: {}\n", c.to_rfc3339()));
    }
    out.push_str(&format!("messages: {}\n", s.message_count));

    for m in collect_messages(&s.file_path, limit, before, filter)? {
        let text = match flatten_content(&m.content) {
            Some(t) if !t.trim().is_empty() => t,
            _ => continue,
        };
        match m.timestamp {
            Some(ts) => out.push_str(&format!(
                "\n## {} · {}\n{}\n",
                m.role,
                ts.to_rfc3339(),
                text
            )),
            None => out.push_str(&format!("\n## {}\n{}\n", m.role, text)),
        }
    }
    Ok(out)
}

/// Structured JSON for a single session's transcript (session metadata + messages).
pub fn render_transcript_json(
    s: &Session,
    limit: Option<usize>,
    before: Option<&str>,
    filter: MsgFilter,
) -> Result<String> {
    let t = Transcript {
        schema_version: SCHEMA_VERSION,
        session_id: &s.session_id,
        name: &s.name,
        cwd: &s.cwd,
        created: s.created,
        git_branch: &s.git_branch,
        version: &s.version,
        message_count: s.message_count,
        messages: collect_messages(&s.file_path, limit, before, filter)?,
    };
    Ok(serde_json::to_string_pretty(&t)?)
}

/// A session plus its matching messages, for cross-session `--grep`.
pub struct SessionHits<'a> {
    pub session: &'a Session,
    pub messages: Vec<Message>,
}

/// Cross-session grep, human view: one block per session, each match a one-line snippet.
pub fn render_grep(hits: &[SessionHits], now: DateTime<Utc>) -> String {
    let mut out = String::new();
    let total: usize = hits.iter().map(|h| h.messages.len()).sum();
    for h in hits {
        out.push_str(&format!(
            "{}  {}  ({}, {})\n",
            h.session.short,
            truncate(&h.session.name.replace('\n', " "), 50),
            relative_time(h.session.last_active, now),
            h.messages.len(),
        ));
        for m in &h.messages {
            let snippet = flatten_content(&m.content)
                .map(|t| truncate(&t.replace('\n', " "), 120))
                .unwrap_or_default();
            out.push_str(&format!("  [{}] {}\n", m.role, snippet));
        }
    }
    out.push_str(&format!("{total} matches in {} sessions", hits.len()));
    out
}

/// Cross-session grep, JSON view.
#[derive(Serialize)]
struct GrepSession<'a> {
    session_id: &'a str,
    short: &'a str,
    name: &'a str,
    cwd: &'a str,
    messages: &'a [Message],
}

#[derive(Serialize)]
struct GrepResult<'a> {
    schema_version: u32,
    matches: Vec<GrepSession<'a>>,
}

pub fn render_grep_json(hits: &[SessionHits]) -> Result<String> {
    let matches = hits
        .iter()
        .map(|h| GrepSession {
            session_id: &h.session.session_id,
            short: &h.session.short,
            name: &h.session.name,
            cwd: &h.session.cwd,
            messages: &h.messages,
        })
        .collect();
    Ok(serde_json::to_string_pretty(&GrepResult {
        schema_version: SCHEMA_VERSION,
        matches,
    })?)
}

/// Flatten content into readable text; tool calls/results/thinking become bracketed markers.
/// Used only for the human-readable text view — JSON keeps the raw content blocks.
fn flatten_content(content: &Value) -> Option<String> {
    if let Some(s) = content.as_str() {
        return Some(s.to_string());
    }
    let mut parts = Vec::new();
    for block in content.as_array()? {
        match block.get("type").and_then(|t| t.as_str()) {
            Some("text") => {
                if let Some(t) = block.get("text").and_then(|x| x.as_str()) {
                    parts.push(t.to_string());
                }
            }
            Some("thinking") => {
                let t = block.get("thinking").and_then(|x| x.as_str()).unwrap_or("");
                parts.push(format!("[thinking]\n{t}"));
            }
            Some("tool_use") => {
                let name = block.get("name").and_then(|x| x.as_str()).unwrap_or("tool");
                let input = block
                    .get("input")
                    .map(|i| serde_json::to_string(i).unwrap_or_default())
                    .unwrap_or_default();
                parts.push(format!("[tool_use: {name}] {input}"));
            }
            Some("tool_result") => {
                let body = tool_result_text(block.get("content"));
                parts.push(format!("[tool_result] {body}"));
            }
            _ => {}
        }
    }
    if parts.is_empty() {
        None
    } else {
        Some(parts.join("\n"))
    }
}

/// Flatten a tool_result's `content` (string, or array of text blocks) into one string.
fn tool_result_text(content: Option<&Value>) -> String {
    match content {
        Some(Value::String(s)) => s.clone(),
        Some(Value::Array(arr)) => arr
            .iter()
            .filter_map(|b| b.get("text").and_then(|t| t.as_str()))
            .collect::<Vec<_>>()
            .join("\n"),
        _ => String::new(),
    }
}

/// Bytes as a compact human-readable size (e.g. 12.3K, 4.5M).
fn human_size(bytes: u64) -> String {
    const UNITS: [&str; 4] = ["B", "K", "M", "G"];
    let mut size = bytes as f64;
    let mut unit = 0;
    while size >= 1024.0 && unit < UNITS.len() - 1 {
        size /= 1024.0;
        unit += 1;
    }
    if unit == 0 {
        format!("{bytes}{}", UNITS[0])
    } else {
        format!("{size:.1}{}", UNITS[unit])
    }
}

fn truncate(s: &str, max: usize) -> String {
    let chars: Vec<char> = s.chars().collect();
    if chars.len() <= max {
        return s.to_string();
    }
    let cut = max.saturating_sub(1);
    let head: String = chars[..cut].iter().collect();
    format!("{head}")
}

fn relative_time(then: DateTime<Utc>, now: DateTime<Utc>) -> String {
    let d = now.signed_duration_since(then);
    let secs = d.num_seconds();
    if secs < 0 {
        return "in future".to_string();
    }
    if secs < 60 {
        return "just now".to_string();
    }
    if d.num_minutes() < 60 {
        return format!("{}m ago", d.num_minutes());
    }
    if d.num_hours() < 24 {
        return format!("{}h ago", d.num_hours());
    }
    let days = d.num_days();
    if days < 30 {
        return format!("{days}d ago");
    }
    if days < 365 {
        return format!("{}mo ago", days / 30);
    }
    format!("{}y ago", days / 365)
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::TimeZone;

    fn sample() -> Session {
        Session {
            session_id: "11111111-x".into(),
            short: "11111111".into(),
            name: "Build the thing".into(),
            cwd: "/home/sibin/demo".into(),
            last_active: Utc.with_ymd_and_hms(2026, 6, 16, 10, 0, 0).unwrap(),
            created: None,
            message_count: 4,
            git_branch: "main".into(),
            version: "1.0".into(),
            size_bytes: 10,
            file_path: "/x".into(),
        }
    }

    #[test]
    fn json_contains_name() {
        let out = render_json(&[sample()]).unwrap();
        let v: serde_json::Value = serde_json::from_str(&out).unwrap();
        assert_eq!(v["schema_version"], 3);
        assert_eq!(v["sessions"][0]["name"], "Build the thing");
    }

    #[test]
    fn table_has_short_and_footer() {
        let now = Utc.with_ymd_and_hms(2026, 6, 16, 12, 0, 0).unwrap();
        let out = render_table(&[sample()], now);
        assert!(out.contains("11111111"));
        assert!(out.contains("Build the thing"));
        assert!(out.contains("1 sessions"));
    }

    #[test]
    fn human_size_scales() {
        assert_eq!(human_size(512), "512B");
        assert_eq!(human_size(1536), "1.5K");
        assert_eq!(human_size(5 * 1024 * 1024), "5.0M");
    }

    #[test]
    fn truncate_and_relative() {
        assert_eq!(truncate("hello", 10), "hello");
        assert_eq!(truncate("hello", 3), "he…");
        let now = Utc.with_ymd_and_hms(2026, 6, 16, 12, 0, 0).unwrap();
        let then = Utc.with_ymd_and_hms(2026, 6, 16, 10, 0, 0).unwrap();
        assert_eq!(relative_time(then, now), "2h ago");
    }
}