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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
use assert_cmd::Command;
use predicates::prelude::*;
use std::fs;

fn seed(root: &std::path::Path, dir: &str, file: &str, cwd: &str, prompt: &str) {
    let proj = root.join(dir);
    fs::create_dir_all(&proj).unwrap();
    let line = format!(
        "{{\"type\":\"user\",\"cwd\":\"{cwd}\",\"timestamp\":\"2026-06-16T01:00:00.000Z\",\"message\":{{\"role\":\"user\",\"content\":\"{prompt}\"}}}}\n"
    );
    fs::write(proj.join(file), line).unwrap();
}

fn setup() -> tempfile::TempDir {
    let root = tempfile::tempdir().unwrap();
    seed(
        root.path(),
        "-home-sibin-my-works-demo",
        "11111111-aaaa-bbbb-cccc-dddddddddddd.jsonl",
        "/home/sibin/my-works/demo",
        "Build the thing",
    );
    // dashed sibling: loose pre-filter includes it, cwd verify must drop it
    seed(
        root.path(),
        "-home-sibin-my-works-demo-backup",
        "22222222-aaaa-bbbb-cccc-dddddddddddd.jsonl",
        "/home/sibin/my-works/demo-backup",
        "Sibling session",
    );
    root
}

#[test]
fn lists_sessions_as_table() {
    let root = setup();
    Command::cargo_bin("csess")
        .unwrap()
        .args([
            "/home/sibin/my-works/demo",
            "--projects-dir",
            root.path().to_str().unwrap(),
        ])
        .assert()
        .success()
        .stdout(predicate::str::contains("Build the thing"))
        .stdout(predicate::str::contains("11111111"))
        .stdout(predicate::str::contains("Sibling session").not());
}

#[test]
fn json_output_is_valid() {
    let root = setup();
    let out = Command::cargo_bin("csess")
        .unwrap()
        .args([
            "/home/sibin/my-works/demo",
            "--json",
            "--projects-dir",
            root.path().to_str().unwrap(),
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let v: serde_json::Value = serde_json::from_slice(&out).unwrap();
    assert_eq!(v["schema_version"], 3);
    assert_eq!(v["sessions"][0]["name"], "Build the thing");
    assert_eq!(v["sessions"].as_array().unwrap().len(), 1);
}

#[test]
fn show_prints_transcript() {
    let root = setup();
    Command::cargo_bin("csess")
        .unwrap()
        .args([
            "/home/sibin/my-works/demo",
            "--show",
            "11111111",
            "--projects-dir",
            root.path().to_str().unwrap(),
        ])
        .assert()
        .success()
        .stdout(predicate::str::contains("## user"))
        .stdout(predicate::str::contains("Build the thing"));
}

#[test]
fn show_json_has_messages_with_timestamps() {
    let root = setup();
    let out = Command::cargo_bin("csess")
        .unwrap()
        .args([
            "/home/sibin/my-works/demo",
            "--show",
            "11111111",
            "--json",
            "--projects-dir",
            root.path().to_str().unwrap(),
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let v: serde_json::Value = serde_json::from_slice(&out).unwrap();
    assert_eq!(v["schema_version"], 3);
    assert_eq!(v["session_id"], "11111111-aaaa-bbbb-cccc-dddddddddddd");
    assert_eq!(v["messages"][0]["role"], "user");
    assert_eq!(v["messages"][0]["entry_type"], "user");
    assert_eq!(v["messages"][0]["content"], "Build the thing");
    assert_eq!(v["messages"][0]["timestamp"], "2026-06-16T01:00:00Z");
}

#[test]
fn show_json_passes_through_tool_result_sidecar() {
    // A tool_result user line carries a top-level `toolUseResult` sidecar
    // (structuredPatch for Edit). csess must pass it through verbatim on the
    // message's `tool_use_result` field so a UI can render the diff.
    let root = tempfile::tempdir().unwrap();
    let proj = root.path().join("-home-sibin-my-works-demo");
    fs::create_dir_all(&proj).unwrap();
    let line = r#"{"type":"user","cwd":"/home/sibin/my-works/demo","timestamp":"2026-06-16T01:00:00.000Z","toolUseResult":{"filePath":"/home/sibin/my-works/demo/a.txt","structuredPatch":[{"oldStart":1,"oldLines":1,"newStart":1,"newLines":2,"lines":["-old","+new1","+new2"]}]},"message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_x","content":"ok"}]}}
"#;
    fs::write(
        proj.join("11111111-aaaa-bbbb-cccc-dddddddddddd.jsonl"),
        line,
    )
    .unwrap();

    let out = Command::cargo_bin("csess")
        .unwrap()
        .args([
            "/home/sibin/my-works/demo",
            "--show",
            "11111111",
            "--json",
            "--projects-dir",
            root.path().to_str().unwrap(),
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let v: serde_json::Value = serde_json::from_slice(&out).unwrap();
    let patch = &v["messages"][0]["tool_use_result"]["structuredPatch"][0];
    assert_eq!(patch["newLines"], 2);
    assert_eq!(patch["lines"][1], "+new1");
}

#[test]
fn show_json_passes_through_meta_and_user_type() {
    // A genuine external turn + a skill-load isMeta echo + the resume pair. csess
    // drops only the `<synthetic>` reply; both isMeta turns (skill echo AND the
    // "Continue…" line) survive tagged is_meta:true, and userType passes through
    // verbatim so a consumer classifies/suppresses them itself.
    let root = tempfile::tempdir().unwrap();
    let proj = root.path().join("-home-sibin-my-works-demo");
    fs::create_dir_all(&proj).unwrap();
    let lines = concat!(
        "{\"type\":\"user\",\"userType\":\"external\",\"cwd\":\"/home/sibin/my-works/demo\",\"timestamp\":\"2026-06-16T01:00:00.000Z\",\"message\":{\"role\":\"user\",\"content\":\"real prompt\"}}\n",
        "{\"type\":\"user\",\"isMeta\":true,\"cwd\":\"/home/sibin/my-works/demo\",\"timestamp\":\"2026-06-16T01:01:00.000Z\",\"message\":{\"role\":\"user\",\"content\":[{\"type\":\"text\",\"text\":\"Base directory for this skill: /x\"}]}}\n",
        "{\"type\":\"user\",\"isMeta\":true,\"cwd\":\"/home/sibin/my-works/demo\",\"timestamp\":\"2026-06-16T01:02:00.000Z\",\"message\":{\"role\":\"user\",\"content\":[{\"type\":\"text\",\"text\":\"Continue from where you left off.\"}]}}\n",
        "{\"type\":\"assistant\",\"cwd\":\"/home/sibin/my-works/demo\",\"timestamp\":\"2026-06-16T01:03:00.000Z\",\"message\":{\"role\":\"assistant\",\"model\":\"<synthetic>\",\"content\":[{\"type\":\"text\",\"text\":\"No response requested.\"}]}}\n",
    );
    fs::write(
        proj.join("11111111-aaaa-bbbb-cccc-dddddddddddd.jsonl"),
        lines,
    )
    .unwrap();

    let out = Command::cargo_bin("csess")
        .unwrap()
        .args([
            "/home/sibin/my-works/demo",
            "--show",
            "11111111",
            "--json",
            "--projects-dir",
            root.path().to_str().unwrap(),
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let v: serde_json::Value = serde_json::from_slice(&out).unwrap();
    let msgs = v["messages"].as_array().unwrap();
    // genuine turn + skill-load meta + "Continue…" meta survive; only the
    // `<synthetic>` reply is dropped.
    assert_eq!(msgs.len(), 3);
    assert_eq!(msgs[0]["is_meta"], false);
    assert_eq!(msgs[0]["user_type"], "external");
    assert_eq!(msgs[1]["is_meta"], true); // skill-load echo
    assert_eq!(msgs[2]["is_meta"], true); // "Continue from where you left off."
}

#[test]
fn show_limit_returns_last_n_messages() {
    let root = tempfile::tempdir().unwrap();
    let proj = root.path().join("-home-sibin-my-works-demo");
    fs::create_dir_all(&proj).unwrap();
    let mut lines = String::new();
    for i in 0..5 {
        lines.push_str(&format!(
            "{{\"type\":\"user\",\"cwd\":\"/home/sibin/my-works/demo\",\"timestamp\":\"2026-06-16T01:0{i}:00.000Z\",\"message\":{{\"role\":\"user\",\"content\":\"msg{i}\"}}}}\n"
        ));
    }
    fs::write(
        proj.join("11111111-aaaa-bbbb-cccc-dddddddddddd.jsonl"),
        lines,
    )
    .unwrap();

    let out = Command::cargo_bin("csess")
        .unwrap()
        .args([
            "/home/sibin/my-works/demo",
            "--show",
            "11111111",
            "--json",
            "-n",
            "2",
            "--projects-dir",
            root.path().to_str().unwrap(),
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let v: serde_json::Value = serde_json::from_slice(&out).unwrap();
    let msgs = v["messages"].as_array().unwrap();
    assert_eq!(msgs.len(), 2);
    assert_eq!(msgs[0]["content"], "msg3");
    assert_eq!(msgs[1]["content"], "msg4");
}

#[test]
fn show_before_returns_messages_older_than_cursor() {
    let root = tempfile::tempdir().unwrap();
    let proj = root.path().join("-home-sibin-my-works-demo");
    fs::create_dir_all(&proj).unwrap();
    let mut lines = String::new();
    for i in 0..5 {
        lines.push_str(&format!(
            "{{\"type\":\"user\",\"uuid\":\"u{i}\",\"cwd\":\"/home/sibin/my-works/demo\",\"timestamp\":\"2026-06-16T01:0{i}:00.000Z\",\"message\":{{\"role\":\"user\",\"content\":\"msg{i}\"}}}}\n"
        ));
    }
    fs::write(
        proj.join("11111111-aaaa-bbbb-cccc-dddddddddddd.jsonl"),
        lines,
    )
    .unwrap();

    // cursor at msg3 → only the strictly-older msg0..=msg2 remain; -n 2 keeps the last two of those
    let out = Command::cargo_bin("csess")
        .unwrap()
        .args([
            "/home/sibin/my-works/demo",
            "--show",
            "11111111",
            "--before",
            "u3",
            "--json",
            "-n",
            "2",
            "--projects-dir",
            root.path().to_str().unwrap(),
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let v: serde_json::Value = serde_json::from_slice(&out).unwrap();
    let msgs = v["messages"].as_array().unwrap();
    assert_eq!(msgs.len(), 2);
    assert_eq!(msgs[0]["content"], "msg1");
    assert_eq!(msgs[1]["content"], "msg2");
}

#[test]
fn role_and_grep_filter_messages() {
    let root = tempfile::tempdir().unwrap();
    let proj = root.path().join("-home-sibin-my-works-demo");
    fs::create_dir_all(&proj).unwrap();
    let lines = concat!(
        "{\"type\":\"user\",\"cwd\":\"/home/sibin/my-works/demo\",\"timestamp\":\"2026-06-16T01:00:00.000Z\",\"message\":{\"role\":\"user\",\"content\":\"please fix the parser\"}}\n",
        "{\"type\":\"assistant\",\"cwd\":\"/home/sibin/my-works/demo\",\"timestamp\":\"2026-06-16T01:01:00.000Z\",\"message\":{\"role\":\"assistant\",\"content\":\"done with the parser\"}}\n",
    );
    fs::write(
        proj.join("11111111-aaaa-bbbb-cccc-dddddddddddd.jsonl"),
        lines,
    )
    .unwrap();
    let pd = root.path().to_str().unwrap();

    // --role user: only the user message survives
    let out = Command::cargo_bin("csess")
        .unwrap()
        .args([
            "/home/sibin/my-works/demo",
            "--show",
            "11111111",
            "--role",
            "user",
            "--json",
            "--projects-dir",
            pd,
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let v: serde_json::Value = serde_json::from_slice(&out).unwrap();
    let msgs = v["messages"].as_array().unwrap();
    assert_eq!(msgs.len(), 1);
    assert_eq!(msgs[0]["role"], "user");

    // cross-session --grep (no --show): session appears with only matching messages
    let out = Command::cargo_bin("csess")
        .unwrap()
        .args([
            "/home/sibin/my-works/demo",
            "--grep",
            "fix",
            "--json",
            "--projects-dir",
            pd,
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let v: serde_json::Value = serde_json::from_slice(&out).unwrap();
    let matches = v["matches"].as_array().unwrap();
    assert_eq!(matches.len(), 1);
    let mm = matches[0]["messages"].as_array().unwrap();
    assert_eq!(mm.len(), 1);
    assert_eq!(mm[0]["content"], "please fix the parser");
}

#[test]
fn show_json_broken_pipe_exits_clean() {
    // A reader that hangs up mid-transcript (head, less quit, a lazy-load UI)
    // must not make csess panic on the broken pipe — it should exit cleanly.
    use std::io::Read;
    use std::process::{Command, Stdio};

    let root = tempfile::tempdir().unwrap();
    let proj = root.path().join("-home-sibin-my-works-demo");
    fs::create_dir_all(&proj).unwrap();
    // >64KB of output so the child is still writing when we drop the read end
    // (a single small write could fit the pipe buffer and finish before we hang up).
    let mut lines = String::new();
    for i in 0..1500 {
        lines.push_str(&format!(
            "{{\"type\":\"user\",\"cwd\":\"/home/sibin/my-works/demo\",\"timestamp\":\"2026-06-16T01:00:00.000Z\",\"message\":{{\"role\":\"user\",\"content\":\"message number {i} padded out with text to make each line reasonably long\"}}}}\n"
        ));
    }
    fs::write(
        proj.join("11111111-aaaa-bbbb-cccc-dddddddddddd.jsonl"),
        lines,
    )
    .unwrap();

    let mut child = Command::new(assert_cmd::cargo::cargo_bin("csess"))
        .args([
            "/home/sibin/my-works/demo",
            "--show",
            "11111111",
            "--json",
            "--projects-dir",
            root.path().to_str().unwrap(),
        ])
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();

    // read a tiny prefix, then hang up by dropping the read end
    {
        let mut out = child.stdout.take().unwrap();
        let mut buf = [0u8; 64];
        let _ = out.read(&mut buf);
    }

    let output = child.wait_with_output().unwrap();
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        !stderr.contains("panicked"),
        "csess panicked on broken pipe: {stderr}"
    );
    assert!(
        output.status.success(),
        "expected clean exit on broken pipe, got {:?}",
        output.status
    );
}

#[test]
fn show_no_match_exits_2() {
    let root = setup();
    Command::cargo_bin("csess")
        .unwrap()
        .args([
            "/home/sibin/my-works/demo",
            "--show",
            "nope-no-such",
            "--projects-dir",
            root.path().to_str().unwrap(),
        ])
        .assert()
        .code(2);
}

#[test]
fn missing_projects_dir_exits_2() {
    Command::cargo_bin("csess")
        .unwrap()
        .args(["/tmp/whatever", "--projects-dir", "/nonexistent/path/xyz"])
        .assert()
        .code(2);
}

#[test]
fn after_cursor_pages_the_session_list() {
    let root = tempfile::tempdir().unwrap();
    let dir = "-home-sibin-my-works-page";
    let cwd = "/home/sibin/my-works/page";
    // names "aaa"/"bbb"/"ccc" so `--sort name` gives a deterministic order
    seed(
        root.path(),
        dir,
        "aaaaaaaa-0000-0000-0000-000000000001.jsonl",
        cwd,
        "aaa",
    );
    seed(
        root.path(),
        dir,
        "bbbbbbbb-0000-0000-0000-000000000002.jsonl",
        cwd,
        "bbb",
    );
    seed(
        root.path(),
        dir,
        "cccccccc-0000-0000-0000-000000000003.jsonl",
        cwd,
        "ccc",
    );

    // page 1: first 2 by name
    Command::cargo_bin("csess")
        .unwrap()
        .args([
            cwd,
            "--sort",
            "name",
            "-n",
            "2",
            "--projects-dir",
            root.path().to_str().unwrap(),
        ])
        .assert()
        .success()
        .stdout(predicate::str::contains("aaa"))
        .stdout(predicate::str::contains("bbb"))
        .stdout(predicate::str::contains("ccc").not());

    // page 2: everything after the cursor (bbb's id) — just ccc
    Command::cargo_bin("csess")
        .unwrap()
        .args([
            cwd,
            "--sort",
            "name",
            "-n",
            "2",
            "--after",
            "bbbbbbbb-0000-0000-0000-000000000002",
            "--projects-dir",
            root.path().to_str().unwrap(),
        ])
        .assert()
        .success()
        .stdout(predicate::str::contains("ccc"))
        .stdout(predicate::str::contains("aaa").not())
        .stdout(predicate::str::contains("bbb").not());
}