kaeru 0.1.9

Reopens your terminal tabs, and the coding agent sessions in them, after the terminal closes or the computer restarts.
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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
//! Codex: how to recognize its process, which runs are interactive, where it
//! keeps its files, and how to resume a session. Its `SessionStart` hook
//! sends the same fields as Claude Code's, which `agents::HookInput` reads.
//!
//! Codex runs the sessions of its windows in one shared background server,
//! unless a window starts with `--no-daemon`. Then the server runs the hooks,
//! so the hook's process tree doesn't lead to the window's tab, and
//! [`window_of`] works out which window shows the session.

use std::path::{Path, PathBuf};

/// The subcommands of Codex (0.172) that don't open its interactive screen,
/// so that their runs are not tabs. `resume`, `fork` and `agents` open it,
/// and so does `codex` alone.
pub const ONE_OFF_COMMANDS: [&str; 33] = [
    "a",
    "app",
    "app-server",
    "apply",
    "archive",
    "cloud",
    "cloud-tasks",
    "completion",
    "debug",
    "delete",
    "doctor",
    "e",
    "exec",
    "exec-server",
    "execpolicy",
    "features",
    "git-credential",
    "help",
    "login",
    "logout",
    "mcp",
    "mcp-server",
    "migrate-nfs-db",
    "migrate-rollouts",
    "plugin",
    "queue",
    "remote-control",
    "responses-api-proxy",
    "review",
    "sandbox",
    "tcp-tunnel",
    "unarchive",
    "update",
];

/// How long after a Codex window starts it can create its first session.
/// Codex creates it right away, unless it first asks something, such as
/// whether to trust a new hook.
const FIRST_SESSION_MS: u64 = 10_000;

/// The originator that Codex writes into the files of sessions that one of
/// its windows created.
const WINDOW_ORIGINATOR: &str = "codex-tui";

/// Returns the command that brings a session back: `codex resume <id>`, or
/// plain `codex` when the conversation can't be resumed because it never got
/// a message or its file is gone.
pub fn resume_command(session_id: &str, conversation_exists: bool) -> Vec<String> {
    if conversation_exists && super::is_uuid(session_id) {
        vec!["codex".into(), "resume".into(), session_id.into()]
    } else {
        vec!["codex".into()]
    }
}

/// Returns whether a process is the Codex CLI: its native executable, named
/// `codex` or, as in its release downloads, `codex-<target>`, or Node running
/// the launcher of the npm package `@openai/codex`. On Windows the launcher
/// starts the native executable as a child, which is nearer to the hook.
pub fn is_codex_process(name: &str, command_line: &str) -> bool {
    let name = name.to_ascii_lowercase();
    let stem = name.strip_suffix(".exe").unwrap_or(&name);
    match stem {
        "codex" => true,
        "node" => command_line.contains("@openai/codex") || command_line.contains(r"@openai\codex"),
        _ => stem.starts_with("codex-"),
    }
}

/// Returns whether a process with this executable name may be the Codex CLI,
/// before its command line is read: Codex's own names, and Node.
pub fn may_be_codex(name: &str) -> bool {
    is_codex_process(name, "") || {
        let name = name.to_ascii_lowercase();
        name == "node" || name == "node.exe"
    }
}

/// Returns Codex's own arguments: those after its executable, or, for the npm
/// launcher, after its script.
fn codex_arguments(arguments: &[String]) -> &[String] {
    let start = arguments
        .iter()
        .position(|argument| argument.ends_with("codex.js"))
        .map_or(1, |script| script + 1);
    arguments.get(start..).unwrap_or_default()
}

/// Returns whether a Codex process's arguments open Codex's interactive
/// screen. One-off runs, such as `codex exec`, are not tabs, so kaeru ignores
/// them. Each argument is compared whole, so that a prompt such as
/// `codex "review my code"` isn't taken for the `review` subcommand.
pub fn is_interactive(arguments: &[String]) -> bool {
    !codex_arguments(arguments)
        .iter()
        .any(|argument| ONE_OFF_COMMANDS.contains(&argument.as_str()))
}

/// Returns whether a Codex process is Codex's shared background server,
/// `codex app-server ... --managed-daemon`, which runs the sessions of the
/// windows that don't start with `--no-daemon`, and their hooks.
pub fn is_shared_server(arguments: &[String]) -> bool {
    let own = codex_arguments(arguments);
    own.iter().any(|argument| argument == "app-server")
        && own.iter().any(|argument| argument == "--managed-daemon")
}

/// Returns the folder that a Codex window works in: the one that its `--cd`
/// (`-C`) option names, or else the folder that its process works in.
pub fn window_folder(arguments: &[String], cwd: Option<&Path>) -> Option<PathBuf> {
    let own = codex_arguments(arguments);
    let named = own.iter().enumerate().find_map(|(index, argument)| {
        if argument == "-C" || argument == "--cd" {
            own.get(index + 1).cloned()
        } else {
            argument.strip_prefix("--cd=").map(String::from)
        }
    });
    match named.map(PathBuf::from) {
        Some(folder) if folder.is_absolute() => Some(folder),
        Some(folder) => cwd.map(|cwd| cwd.join(folder)),
        None => cwd.map(Path::to_path_buf),
    }
}

/// Returns when Codex created a session, in milliseconds since the Unix
/// epoch, from its id: Codex's session ids are version 7 UUIDs, whose first
/// 48 bits are that time.
pub fn created_ms(session_id: &str) -> Option<u64> {
    let digits: String = session_id.chars().filter(|&c| c != '-').collect();
    if digits.len() != 32 || digits.as_bytes()[12] != b'7' {
        return None;
    }
    u64::from_str_radix(&digits[..12], 16).ok()
}

/// Returns whether a Codex window created a session, from the first line of
/// the session's file. It is `false` only when that line names another
/// program, such as Codex's remote control, so that a file that can't be read
/// doesn't stop kaeru.
pub fn created_by_a_window(first_line: &str) -> bool {
    let Ok(record) = serde_json::from_str::<serde_json::Value>(first_line) else {
        return true;
    };
    record
        .pointer("/payload/originator")
        .and_then(serde_json::Value::as_str)
        .is_none_or(|originator| originator == WINDOW_ORIGINATOR)
}

/// A Codex window: a Codex process that shows sessions, which may run in
/// Codex's shared server rather than in it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Window {
    /// When the window started, in milliseconds since the Unix epoch, or 0
    /// when that can't be read.
    pub started_ms: u64,
    /// The arguments it started with, its executable first.
    pub arguments: Vec<String>,
    /// The folder it works in, if that can be read.
    pub folder: Option<String>,
}

/// A session that Codex's shared server runs, as its hook tells it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ServerSession<'a> {
    /// The session's id.
    pub id: &'a str,
    /// The folder the session runs in.
    pub cwd: &'a str,
    /// Why the hook runs: `startup`, `resume`, `clear`, `compact` or
    /// `fork`.
    pub source: Option<&'a str>,
    /// Whether a Codex window created the session, as
    /// [`created_by_a_window`] tells.
    pub from_window: bool,
}

/// Which window shows a session.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Shown {
    /// The window at this place in the list shows it. `exact` is `true` when
    /// the window was started with the session's id.
    In { window: usize, exact: bool },
    /// More than one window could show it, so kaeru doesn't guess. The text
    /// says why.
    Unsure(&'static str),
    /// No window shows it, because another program started it, or its
    /// window is gone.
    Nowhere,
}

/// Returns which of the Codex windows shows a session that Codex's shared
/// server runs. Each rule is tried in turn, and a rule that fits more than one
/// window gives [`Shown::Unsure`] instead of a guess:
///
/// 1. A window started with the session's id, as `codex resume <id>` is.
/// 2. For a new session, the window in the session's folder that started
///    shortly before Codex created the session, which its id tells.
/// 3. Otherwise, such as after `/new` in a window, the only window in the
///    session's folder. A new session can't be shown by a window that
///    started after it.
///
/// Rules 2 and 3 only apply to sessions that a window created.
pub fn window_of(session: &ServerSession, windows: &[Window]) -> Shown {
    let matching = |fits: &dyn Fn(&Window) -> bool| -> Vec<usize> {
        (0..windows.len())
            .filter(|&index| fits(&windows[index]))
            .collect()
    };
    let by_id = matching(&|window| {
        codex_arguments(&window.arguments)
            .iter()
            .any(|a| a == session.id)
    });
    match by_id.as_slice() {
        [] => {}
        [window] => {
            return Shown::In {
                window: *window,
                exact: true,
            };
        }
        _ => return Shown::Unsure("more than one Codex window was started with its id"),
    }
    if !session.from_window {
        return Shown::Nowhere;
    }
    let is_new = matches!(session.source, Some("startup" | "clear" | "fork"));
    let created = created_ms(session.id).filter(|_| is_new);
    // A window whose folder can't be read could be in any folder.
    let here = |window: &Window| {
        window
            .folder
            .as_deref()
            .is_none_or(|folder| same_folder(folder, session.cwd))
    };
    if let Some(created) = created {
        let first = matching(&|window| {
            here(window)
                && window.started_ms <= created
                && created <= window.started_ms + FIRST_SESSION_MS
        });
        match first.as_slice() {
            [] => {}
            [window] => {
                return Shown::In {
                    window: *window,
                    exact: false,
                };
            }
            _ => {
                return Shown::Unsure(
                    "two Codex windows in its folder started at about the same time",
                );
            }
        }
    }
    let alone = matching(&|window| {
        here(window) && created.is_none_or(|created| window.started_ms <= created)
    });
    match alone.as_slice() {
        [] => Shown::Nowhere,
        [window] => Shown::In {
            window: *window,
            exact: false,
        },
        _ => Shown::Unsure("more than one Codex window runs in its folder"),
    }
}

/// Returns whether two paths name the same folder, ignoring a separator at
/// the end and, on Windows, the case of letters.
fn same_folder(a: &str, b: &str) -> bool {
    let a = a.trim_end_matches(['\\', '/']);
    let b = b.trim_end_matches(['\\', '/']);
    if cfg!(windows) {
        a.eq_ignore_ascii_case(b)
    } else {
        a == b
    }
}

/// A session that Codex keeps a file of, in the `sessions` folder of its
/// home folder.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Recorded {
    /// The session's id.
    pub id: String,
    /// The folder the session runs in, if its file says.
    pub cwd: Option<String>,
    /// Whether a Codex window created it, as [`created_by_a_window`] tells.
    pub from_window: bool,
    /// Its file.
    pub path: PathBuf,
    /// When its file last changed, in milliseconds since the Unix epoch.
    pub modified_ms: Option<u64>,
}

/// Returns the sessions that Codex created since `since_ms`, in
/// milliseconds since the Unix epoch, from their files. Codex keeps each
/// session in `sessions/<year>/<month>/<day>/rollout-<time>-<id>.jsonl`,
/// dated in local time, so the folders from a day before `since_ms` on are
/// read, and the time in each id decides.
pub fn sessions_created_since(home: &Path, since_ms: u64) -> Vec<Recorded> {
    let first_day = date_of(since_ms.saturating_sub(DAY_MS));
    let mut found = Vec::new();
    for (date, folder) in day_folders(&home.join("sessions")) {
        if date < first_day {
            continue;
        }
        let Ok(entries) = std::fs::read_dir(&folder) else {
            continue;
        };
        for path in entries.filter_map(|entry| Some(entry.ok()?.path())) {
            let Some(id) = rollout_id(&path) else {
                continue;
            };
            if created_ms(&id).is_none_or(|created| created < since_ms) {
                continue;
            }
            found.push(recorded(id, path));
        }
    }
    found
}

/// Returns the session `id` from its file, wherever in the `sessions`
/// folder that is, for a window started with that id, whose session may be
/// from any day.
pub fn session_file(home: &Path, id: &str) -> Option<Recorded> {
    let ending = format!("-{id}.jsonl");
    day_folders(&home.join("sessions"))
        .into_iter()
        .rev()
        .find_map(|(_, folder)| {
            std::fs::read_dir(folder)
                .ok()?
                .filter_map(|entry| Some(entry.ok()?.path()))
                .find(|path| {
                    path.file_name()
                        .and_then(|name| name.to_str())
                        .is_some_and(|name| name.starts_with("rollout-") && name.ends_with(&ending))
                })
        })
        .map(|path| recorded(id.to_string(), path))
}

/// Returns what a session's file tells about the session `id`.
fn recorded(id: String, path: PathBuf) -> Recorded {
    let first = std::fs::File::open(&path)
        .ok()
        .and_then(|file| {
            std::io::BufRead::lines(std::io::BufReader::new(file))
                .next()?
                .ok()
        })
        .unwrap_or_default();
    let modified_ms = std::fs::metadata(&path)
        .and_then(|metadata| metadata.modified())
        .ok()
        .and_then(|modified| modified.duration_since(std::time::UNIX_EPOCH).ok())
        .and_then(|since| u64::try_from(since.as_millis()).ok());
    Recorded {
        id,
        cwd: session_folder(&first),
        from_window: created_by_a_window(&first),
        path,
        modified_ms,
    }
}

/// A day, in milliseconds.
const DAY_MS: u64 = 24 * 60 * 60 * 1000;

/// Returns the folders of `sessions` that hold one day's sessions, with
/// their dates as `(year, month, day)`.
fn day_folders(sessions: &Path) -> Vec<((u64, u64, u64), PathBuf)> {
    let numbered = |folder: &Path| -> Vec<(u64, PathBuf)> {
        std::fs::read_dir(folder)
            .map(|entries| {
                entries
                    .filter_map(|entry| {
                        let path = entry.ok()?.path();
                        let number = path.file_name()?.to_str()?.parse().ok()?;
                        Some((number, path))
                    })
                    .collect()
            })
            .unwrap_or_default()
    };
    let mut days = Vec::new();
    for (year, year_folder) in numbered(sessions) {
        for (month, month_folder) in numbered(&year_folder) {
            for (day, day_folder) in numbered(&month_folder) {
                days.push(((year, month, day), day_folder));
            }
        }
    }
    days
}

/// Returns the session id in the name of a session's file,
/// `rollout-<time>-<id>.jsonl`.
fn rollout_id(path: &Path) -> Option<String> {
    let name = path.file_name()?.to_str()?;
    let stem = name.strip_prefix("rollout-")?.strip_suffix(".jsonl")?;
    let id = stem.get(stem.len().checked_sub(36)?..)?;
    super::is_uuid(id).then(|| id.to_string())
}

/// Returns the folder that the first line of a session's file names.
fn session_folder(first_line: &str) -> Option<String> {
    let record: serde_json::Value = serde_json::from_str(first_line).ok()?;
    Some(record.pointer("/payload/cwd")?.as_str()?.to_string())
}

/// Returns the date, as `(year, month, day)` in UTC, of a time in
/// milliseconds since the Unix epoch, by the usual conversion from days to
/// the Gregorian calendar.
fn date_of(ms: u64) -> (u64, u64, u64) {
    let days = ms / DAY_MS + 719_468;
    let era = days / 146_097;
    let of_era = days % 146_097;
    let year_of_era = (of_era - of_era / 1_460 + of_era / 36_524 - of_era / 146_096) / 365;
    let of_year = of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
    let shifted_month = (5 * of_year + 2) / 153;
    let day = of_year - (153 * shifted_month + 2) / 5 + 1;
    let month = if shifted_month < 10 {
        shifted_month + 3
    } else {
        shifted_month - 9
    };
    let year = year_of_era + era * 400 + u64::from(month <= 2);
    (year, month, day)
}

/// Returns the session id that a Codex window was started with, as
/// `codex resume <id>` is, if it was.
pub fn started_with(arguments: &[String]) -> Option<&str> {
    codex_arguments(arguments)
        .iter()
        .map(String::as_str)
        .find(|argument| super::is_uuid(argument))
}

/// Returns Codex's home folder: `CODEX_HOME` when that is set, or else
/// `~/.codex`.
pub fn home_dir() -> Option<PathBuf> {
    std::env::var_os("CODEX_HOME")
        .map(PathBuf::from)
        .or_else(|| dirs::home_dir().map(|home| home.join(".codex")))
}

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

    const ID: &str = "00000000-0000-4000-8000-000000000001";

    /// When Codex created the new session in these tests.
    const CREATED: u64 = 100_000;

    /// Returns a made-up version 7 session id that Codex created at
    /// `created_ms`.
    fn new_id(created_ms: u64) -> String {
        format!(
            "{:08x}-{:04x}-7000-8000-000000000001",
            created_ms >> 16,
            created_ms & 0xffff
        )
    }

    fn args(words: &[&str]) -> Vec<String> {
        words.iter().map(|&word| word.into()).collect()
    }

    fn window(started_ms: u64, words: &[&str], folder: &str) -> Window {
        Window {
            started_ms,
            arguments: args(words),
            folder: Some(folder.into()),
        }
    }

    fn session<'a>(id: &'a str, source: &'a str) -> ServerSession<'a> {
        ServerSession {
            id,
            cwd: "/home/demo/code/api-server",
            source: Some(source),
            from_window: true,
        }
    }

    const HERE: &str = "/home/demo/code/api-server";
    const THERE: &str = "/home/demo/code/web-ui";

    #[test]
    fn resumes_only_conversations_that_exist() {
        assert_eq!(resume_command(ID, true), ["codex", "resume", ID]);
        assert_eq!(resume_command(ID, false), ["codex"]);
        assert_eq!(resume_command("bad", true), ["codex"]);
    }

    #[test]
    fn recognizes_the_codex_process() {
        assert!(is_codex_process("codex.exe", ""));
        assert!(is_codex_process("codex", ""));
        assert!(is_codex_process("codex-x86_64-pc-windows-msvc.exe", ""));
        assert!(is_codex_process(
            "node.exe",
            r"node C:\npm\node_modules\@openai\codex\bin\codex.js"
        ));
        assert!(!is_codex_process("node.exe", "node server.js"));
        assert!(!is_codex_process("codexx.exe", ""));
        assert!(may_be_codex("node.exe"));
        assert!(may_be_codex("codex"));
        assert!(!may_be_codex("bash"));
    }

    #[test]
    fn one_off_runs_are_not_interactive() {
        assert!(is_interactive(&args(&["codex"])));
        assert!(is_interactive(&args(&["codex", "resume", ID])));
        assert!(is_interactive(&args(&[
            r"C:\tools\codex.exe",
            "--model",
            "x"
        ])));
        assert!(is_interactive(&args(&["codex", "--no-daemon", "agents"])));
        assert!(!is_interactive(&args(&["codex", "exec", "fix the tests"])));
        assert!(!is_interactive(&args(&["codex", "app-server"])));
    }

    #[test]
    fn a_prompt_is_not_taken_for_a_subcommand() {
        assert!(is_interactive(&args(&["codex", "review my code"])));
        assert!(!is_interactive(&args(&["codex", "review"])));
    }

    #[test]
    fn the_npm_launcher_s_script_is_skipped() {
        let launcher = args(&[
            "node",
            "/usr/lib/node_modules/@openai/codex/bin/codex.js",
            "exec",
        ]);
        assert!(!is_interactive(&launcher));
        assert!(is_interactive(&args(&[
            "node",
            "/usr/lib/node_modules/@openai/codex/bin/codex.js"
        ])));
    }

    #[test]
    fn the_shared_server_is_recognized() {
        assert!(is_shared_server(&args(&[
            "codex",
            "app-server",
            "--listen",
            "unix://",
            "--managed-daemon"
        ])));
        // An editor's own app-server isn't the shared server.
        assert!(!is_shared_server(&args(&["codex", "app-server"])));
        assert!(!is_shared_server(&args(&["codex", "--no-daemon"])));
    }

    #[test]
    fn a_window_works_in_the_folder_it_names() {
        let cwd = Path::new("/home/demo");
        assert_eq!(
            window_folder(&args(&["codex"]), Some(cwd)),
            Some(PathBuf::from("/home/demo"))
        );
        assert_eq!(
            window_folder(&args(&["codex", "-C", "code"]), Some(cwd)),
            Some(PathBuf::from("/home/demo/code"))
        );
        assert_eq!(
            window_folder(&args(&["codex", "--cd=/srv/app"]), Some(cwd)),
            Some(PathBuf::from("/srv/app"))
        );
        assert_eq!(window_folder(&args(&["codex"]), None), None);
    }

    #[test]
    fn a_session_id_tells_when_it_was_created() {
        assert_eq!(created_ms(&new_id(CREATED)), Some(CREATED));
        assert_eq!(created_ms(ID), None, "not a version 7 UUID");
        assert_eq!(created_ms("bad"), None);
    }

    #[test]
    fn a_session_file_tells_which_program_created_it() {
        let made_by = |originator: &str| {
            format!(r#"{{"type":"session_meta","payload":{{"originator":"{originator}"}}}}"#)
        };
        assert!(created_by_a_window(&made_by("codex-tui")));
        assert!(!created_by_a_window(&made_by("some-other-client")));
        assert!(created_by_a_window(
            r#"{"type":"session_meta","payload":{}}"#
        ));
        assert!(created_by_a_window("not json"));
    }

    #[test]
    fn a_window_started_with_the_session_s_id_shows_it() {
        let windows = [
            window(0, &["codex"], HERE),
            window(0, &["codex", "resume", ID], THERE),
        ];
        assert_eq!(
            window_of(&session(ID, "resume"), &windows),
            Shown::In {
                window: 1,
                exact: true
            }
        );
    }

    #[test]
    fn a_new_session_belongs_to_the_window_that_just_started() {
        // Two windows in the folder: one from before, one that started 1
        // second before Codex created the session.
        let windows = [
            window(50_000, &["codex"], HERE),
            window(99_000, &["codex"], HERE),
            window(99_500, &["codex"], THERE),
        ];
        let id = new_id(CREATED);
        assert_eq!(
            window_of(&session(&id, "startup"), &windows),
            Shown::In {
                window: 1,
                exact: false
            }
        );
    }

    #[test]
    fn two_windows_started_together_are_not_guessed_between() {
        let windows = [
            window(98_000, &["codex"], HERE),
            window(99_000, &["codex"], HERE),
        ];
        let id = new_id(CREATED);
        assert!(matches!(
            window_of(&session(&id, "startup"), &windows),
            Shown::Unsure(_)
        ));
    }

    #[test]
    fn a_later_session_belongs_to_the_only_window_in_its_folder() {
        // After /new, the session is newer than every window.
        let windows = [
            window(10_000, &["codex"], HERE),
            window(20_000, &["codex"], THERE),
        ];
        let id = new_id(CREATED);
        assert_eq!(
            window_of(&session(&id, "startup"), &windows),
            Shown::In {
                window: 0,
                exact: false
            }
        );
        let crowded = [
            window(10_000, &["codex"], HERE),
            window(20_000, &["codex"], HERE),
        ];
        assert!(matches!(
            window_of(&session(&id, "clear"), &crowded),
            Shown::Unsure(_)
        ));
    }

    #[test]
    fn a_window_that_started_after_a_new_session_doesn_t_show_it() {
        let windows = [window(200_000, &["codex"], HERE)];
        let id = new_id(CREATED);
        assert_eq!(
            window_of(&session(&id, "startup"), &windows),
            Shown::Nowhere
        );
    }

    #[test]
    fn a_resumed_session_belongs_to_the_only_window_in_its_folder() {
        // `codex resume --last` doesn't name the session, and the session is
        // older than the window.
        let windows = [window(200_000, &["codex", "resume", "--last"], HERE)];
        let id = new_id(CREATED);
        assert_eq!(
            window_of(&session(&id, "resume"), &windows),
            Shown::In {
                window: 0,
                exact: false
            }
        );
    }

    #[test]
    fn a_window_whose_folder_is_unknown_could_be_anywhere() {
        let mut unknown = window(10_000, &["codex"], HERE);
        unknown.folder = None;
        let windows = [window(10_000, &["codex"], HERE), unknown];
        let id = new_id(CREATED);
        assert!(matches!(
            window_of(&session(&id, "startup"), &windows),
            Shown::Unsure(_)
        ));
    }

    #[test]
    fn a_session_that_another_program_started_has_no_window() {
        let windows = [window(99_000, &["codex"], HERE)];
        let id = new_id(CREATED);
        let remote = ServerSession {
            from_window: false,
            ..session(&id, "startup")
        };
        assert_eq!(window_of(&remote, &windows), Shown::Nowhere);
    }

    #[test]
    fn folders_are_compared_as_the_os_does() {
        assert!(same_folder(r"C:\Users\demo\code\", r"C:\Users\demo\code"));
        assert!(!same_folder("/home/demo/a", "/home/demo/b"));
        assert_eq!(
            same_folder(r"C:\Users\Demo", r"c:\users\demo"),
            cfg!(windows)
        );
    }

    #[test]
    fn dates_follow_the_calendar() {
        assert_eq!(date_of(0), (1970, 1, 1));
        assert_eq!(date_of(951_782_400_000), (2000, 2, 29));
        assert_eq!(date_of(4_102_444_800_000), (2100, 1, 1));
    }

    #[test]
    fn sessions_are_read_from_their_files_by_when_they_were_created() {
        let home = tempfile::tempdir().unwrap();
        let day = home
            .path()
            .join("sessions")
            .join("2030")
            .join("01")
            .join("02");
        std::fs::create_dir_all(&day).unwrap();
        let old = new_id(CREATED - 1);
        let new = new_id(CREATED + 1);
        for id in [&old, &new] {
            let line = format!(
                r#"{{"type":"session_meta","payload":{{"id":"{id}","cwd":"/home/demo/code","originator":"codex-tui"}}}}"#
            );
            std::fs::write(
                day.join(format!("rollout-2030-01-02T03-04-05-{id}.jsonl")),
                line + "\n",
            )
            .unwrap();
        }
        std::fs::write(day.join("notes.txt"), "").unwrap();
        // The folder's date is long after the time, so it is read.
        let found = sessions_created_since(home.path(), CREATED);
        assert_eq!(found.len(), 1);
        assert_eq!(found[0].id, new);
        assert_eq!(found[0].cwd.as_deref(), Some("/home/demo/code"));
        assert!(found[0].from_window);
        assert!(found[0].modified_ms.is_some());
        assert_eq!(
            session_file(home.path(), &old).map(|one| one.path),
            Some(day.join(format!("rollout-2030-01-02T03-04-05-{old}.jsonl")))
        );
        assert!(session_file(home.path(), ID).is_none());
        // A folder from before the day before is skipped.
        assert!(sessions_created_since(home.path(), 2_000_000_000_000).is_empty());
        assert_eq!(
            started_with(&args(&["codex", "resume", &new])),
            Some(new.as_str())
        );
        assert_eq!(started_with(&args(&["codex"])), None);
    }
}