kaeru 0.1.8

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
//! `kaeru adopt`: notes for the tabs that were already open when kaeru was
//! set up. Their shells never ran kaeru's line, and the agent sessions in
//! them never ran the hook, so kaeru reads what it can about them from
//! outside, and keeps their folders current each time it runs.
//! docs/architecture.md explains it under Adopting open tabs.

use std::path::Path;

use anyhow::{Result, bail};

use super::{Checklist, Outcome};
use crate::agents::{self, Agent, claude, codex};
use crate::engine::note::{AgentNote, Note, ProcessRef, ShellNote};
use crate::os;
use crate::procs::system::SystemTable;
use crate::procs::{ProcInfo, START_TOLERANCE_MS};
use crate::shells::{self, shell_name};
use crate::store::Store;
use crate::terminals::{self, Env, windows_terminal};

/// The shells whose tabs kaeru adopts: the ones it has a line for, so that
/// a tab that comes back is tracked fully.
const SHELLS: [&str; 5] = ["powershell", "pwsh", "bash", "zsh", "fish"];

/// The shells that don't tell the OS when you change folders. PowerShell
/// keeps its location to itself, so the folder that the OS knows of is the
/// one the tab started in.
const KEEPS_ITS_FOLDER: [&str; 2] = ["powershell", "pwsh"];

/// How long after its process started Claude Code can record a session in
/// its list of running sessions.
const CLAUDE_START_MS: u64 = 60_000;

/// A running shell that may be a tab to adopt.
pub struct Candidate {
    /// The shell and its ancestors, nearest first, with the shell's folder.
    pub lineage: Vec<ProcInfo>,
    /// The shell's environment, as the OS keeps it: on Windows the one it
    /// has now, and on macOS and Linux the one it started with, which holds
    /// the terminal's variables all the same.
    pub env: Env,
}

/// What `kaeru adopt` would write: the notes of the open tabs that kaeru
/// doesn't track, and of the agent sessions in them.
#[derive(Debug, Default)]
pub struct Found {
    pub shells: Vec<ShellNote>,
    pub agents: Vec<AgentNote>,
}

/// Adopts the open tabs, for `kaeru adopt`, and prints a line for each.
///
/// # Errors
///
/// Fails when the state folder or the session id can't be read, when
/// another tab holds the lock, or when a note can't be written.
pub fn adopt() -> Result<()> {
    let store = Store::open()?;
    let Some(_lock) = store.try_lock()? else {
        bail!("kaeru's list is open in another tab. Try again once you closed it.");
    };
    let found = untracked(&store)?;
    if found.shells.is_empty() {
        println!("No open tabs to adopt. kaeru already tracks every tab that it can see.");
        return Ok(());
    }
    let names: Vec<String> = found.shells.iter().map(terminal_name).collect();
    let names: Vec<&str> = names.iter().map(String::as_str).collect();
    let mut list = Checklist::new(&names);
    save(&store, &found, &mut list)?;
    Ok(())
}

/// Asks whether to adopt the open tabs that kaeru doesn't track, as the
/// last step of `kaeru install`, and adopts them when you say yes. It says
/// nothing when there are none.
///
/// # Errors
///
/// Fails when it can't ask, or when a note can't be written.
pub(super) fn offer(list: &mut Checklist) -> Result<()> {
    let store = Store::open()?;
    let Some(_lock) = store.try_lock()? else {
        return Ok(());
    };
    let found = untracked(&store)?;
    let count = found.shells.len();
    if count == 0 {
        return Ok(());
    }
    let (tabs, them) = if count == 1 {
        ("1 tab is".to_string(), "it")
    } else {
        (format!("{count} tabs are"), "them")
    };
    println!(
        "\nOpen tabs: {tabs} already open, from before kaeru was set up, so kaeru can't bring \
         {them} back yet.\n  kaeru can track {them} from outside, which doesn't change the tabs."
    );
    if super::ask(&format!("  Track {them} too?"))? {
        save(&store, &found, list)?;
    } else {
        list.line(
            Outcome::Skipped,
            "Open tabs",
            "to track them later, run kaeru adopt",
        );
    }
    Ok(())
}

/// Writes the notes that `found` holds, and prints a line for each tab.
fn save(store: &Store, found: &Found, list: &mut Checklist) -> Result<()> {
    for shell in &found.shells {
        store.save(&Note::Shell(shell.clone()))?;
    }
    for agent in &found.agents {
        store.save(&Note::Agent(agent.clone()))?;
    }
    for shell in &found.shells {
        let agent = found
            .agents
            .iter()
            .find(|agent| agent.shell == Some(shell.process))
            .and_then(|agent| Agent::from_id(&agent.agent))
            .map(|agent| format!(", with its {} session", agent.name()))
            .unwrap_or_default();
        list.line(
            Outcome::Added,
            &terminal_name(shell),
            &format!(
                "{} in {}{agent}",
                crate::tui::home_as_tilde(&shell.cwd),
                shell_title(&shell.shell)
            ),
        );
    }
    let stays = found.shells.iter().any(|shell| {
        KEEPS_ITS_FOLDER.contains(&shell.shell.as_str())
            && !found
                .agents
                .iter()
                .any(|agent| agent.shell == Some(shell.process))
    });
    if stays {
        list.line(
            Outcome::Note,
            "PowerShell",
            "PowerShell doesn't tell other programs when you change folders, so its adopted \
             tabs come back in the folder they started in. A tab that you open anew is tracked \
             fully.",
        );
    }
    Ok(())
}

/// Returns the name of the terminal a shell note's tab runs in.
fn terminal_name(shell: &ShellNote) -> String {
    shell
        .terminal
        .as_ref()
        .map_or_else(String::new, |terminal| {
            terminals::name_of(&terminal.adapter)
        })
}

/// Returns a shell's name as `kaeru adopt` prints it.
fn shell_title(shell: &str) -> &str {
    match shell {
        "powershell" => "Windows PowerShell",
        "pwsh" => "PowerShell",
        other => other,
    }
}

/// Returns the open tabs that kaeru doesn't track, and the agent sessions in
/// them that have no note, from the processes that run now.
///
/// # Errors
///
/// Fails when the session id can't be read.
pub fn untracked(store: &Store) -> Result<Found> {
    let session = os::session_id()?;
    let now = shells::now_ms();
    let mut table = SystemTable::snapshot();
    let notes = store.notes();
    let noted: Vec<ProcessRef> = notes.iter().map(|stored| *stored.note.process()).collect();
    let tracked: Vec<ShellNote> = notes
        .iter()
        .filter_map(|stored| match &stored.note {
            Note::Shell(shell) => Some(shell.clone()),
            Note::Agent(_) => None,
        })
        .collect();
    let candidates: Vec<Candidate> = table
        .find(is_shell)
        .into_iter()
        .filter(|shell| !noted.iter().any(|note| shell.is(note)))
        .map(|shell| {
            let mut lineage = table.lineage(shell.pid);
            let env: Env = table.environment(shell.pid).into_iter().collect();
            if let Some(first) = lineage.first_mut() {
                *first = shell;
            }
            Candidate { lineage, env }
        })
        .collect();
    let mut shells = shell_notes(&candidates, &session, now);
    let in_tabs: Vec<ShellNote> = tracked.iter().chain(&shells).cloned().collect();
    let claude_lineages: Vec<Vec<ProcInfo>> = table
        .find(|name| claude::is_claude_process(name, "claude-code") || is_node(name))
        .into_iter()
        .filter(|process| {
            let command_line = process.command_line.as_deref().unwrap_or_default();
            claude::is_claude_process(&process.name, command_line)
                && claude::is_interactive(command_line)
                && !noted.iter().any(|note| process.is(note))
        })
        .map(|process| {
            let mut lineage = table.lineage(process.pid);
            if let Some(first) = lineage.first_mut() {
                *first = process;
            }
            lineage
        })
        .collect();
    let running = claude::config_dir()
        .map(|dir| claude::running_sessions(&dir))
        .unwrap_or_default();
    let mut agents = claude_notes(&claude_lineages, &running, &in_tabs, &session);
    let found = table.find(codex::may_be_codex);
    let windows: Vec<(ProcInfo, Vec<ProcInfo>)> = agents::codex_windows(&table, &found)
        .into_iter()
        .filter(|(window, _)| !noted.iter().any(|note| window.is(note)))
        .collect();
    if let Some(home) = codex::home_dir().filter(|_| !windows.is_empty()) {
        let since = windows
            .iter()
            .filter_map(|(window, _)| window.started_ms)
            .min()
            .unwrap_or(now);
        let mut recorded = codex::sessions_created_since(&home, since);
        for (window, _) in &windows {
            if let Some(id) = codex::started_with(&window.arguments)
                && let Some(file) = codex::session_file(&home, id)
            {
                recorded.push(file);
            }
        }
        agents.extend(codex_notes(&windows, &recorded, &in_tabs, &session));
    }
    // A PowerShell tab's own folder is the one it started in, so the folder
    // of the session in it is a better guess.
    for shell in &mut shells {
        if KEEPS_ITS_FOLDER.contains(&shell.shell.as_str())
            && let Some(agent) = agents
                .iter()
                .find(|agent| agent.shell == Some(shell.process))
        {
            shell.cwd.clone_from(&agent.cwd);
        }
    }
    Ok(Found { shells, agents })
}

/// Returns whether a process name is Node's, which runs the npm builds of
/// the agents.
fn is_node(name: &str) -> bool {
    name.eq_ignore_ascii_case("node") || name.eq_ignore_ascii_case("node.exe")
}

/// Returns whether a process name is one of the [`SHELLS`].
fn is_shell(name: &str) -> bool {
    SHELLS.contains(&plain_shell_name(name).to_ascii_lowercase().as_str())
}

/// Returns a shell's name as notes store it, without the `-` that marks a
/// login shell where the OS reports the name that the shell was started
/// with.
fn plain_shell_name(name: &str) -> String {
    shell_name(name.trim_start_matches('-'))
}

/// Returns the notes of the candidates that are the shells of tabs of a
/// known terminal, by the rule that `kaeru shell start` uses, so that a
/// shell inside another program in a tab, such as a nested shell or an
/// editor, isn't one. Git Bash's launcher in Windows Terminal starts the real
/// bash and only waits for it, so it isn't one either.
fn shell_notes(candidates: &[Candidate], session: &str, now_ms: u64) -> Vec<ShellNote> {
    let adapters = terminals::all();
    candidates
        .iter()
        .filter_map(|candidate| {
            let shell = candidate.lineage.first()?;
            if !is_shell(&shell.name) || windows_terminal::is_git_bash_launcher(shell) {
                return None;
            }
            let Some((0, terminal)) =
                terminals::tab_of(&adapters, &candidate.env, &candidate.lineage)
            else {
                return None;
            };
            Some(ShellNote {
                process: shell.to_ref()?,
                shell: plain_shell_name(&shell.name),
                cwd: folder(shell.cwd.as_deref())?,
                terminal: Some(terminal),
                session: session.into(),
                offered: false,
                adopted_ms: Some(now_ms),
            })
        })
        .collect()
}

/// Returns a folder as kaeru writes it: without a separator at the end,
/// except for the root of a drive or of the file system.
fn folder(cwd: Option<&Path>) -> Option<String> {
    let text = cwd?.display().to_string();
    let trimmed = text.trim_end_matches(['\\', '/']);
    if trimmed.is_empty() || trimmed.ends_with(':') {
        Some(text)
    } else {
        Some(trimmed.to_string())
    }
}

/// Returns the notes of the Claude Code sessions in tabs: for each Claude
/// Code process, given with its lineage, the session that Claude Code's
/// list of running sessions gives for it, when that runs in a tab, its id
/// is the process's and it started together with the process. A process
/// whose id another process had before doesn't get that one's session.
fn claude_notes(
    lineages: &[Vec<ProcInfo>],
    running: &[claude::Running],
    shells: &[ShellNote],
    session: &str,
) -> Vec<AgentNote> {
    lineages
        .iter()
        .filter_map(|lineage| {
            let process = lineage.first()?;
            let started = process.started_ms?;
            let found = running.iter().find(|running| {
                running.pid == process.pid
                    && running.is_interactive()
                    && running.started_ms.is_some_and(|at| {
                        at + START_TOLERANCE_MS >= started && at <= started + CLAUDE_START_MS
                    })
            })?;
            let cwd = found
                .cwd
                .clone()
                .or_else(|| folder(process.cwd.as_deref()))?;
            agent_note(
                Agent::Claude,
                lineage,
                found.session_id.clone(),
                cwd,
                None,
                shells,
                session,
            )
        })
        .collect()
}

/// Returns the notes of the Codex sessions in tabs: for each Codex window,
/// given with its lineage, the session that it shows, as
/// [`codex::window_of`] decides from the sessions that `recorded` holds.
/// When a window could show more than one of them, as after `/new`, it is
/// the one whose file changed last.
fn codex_notes(
    windows: &[(ProcInfo, Vec<ProcInfo>)],
    recorded: &[codex::Recorded],
    shells: &[ShellNote],
    session: &str,
) -> Vec<AgentNote> {
    let listed: Vec<codex::Window> = windows
        .iter()
        .map(|(window, _)| agents::as_window(window))
        .collect();
    let mut shown: Vec<Option<&codex::Recorded>> = vec![None; windows.len()];
    for one in recorded {
        let server_session = codex::ServerSession {
            id: &one.id,
            cwd: one.cwd.as_deref().unwrap_or_default(),
            source: Some("startup"),
            from_window: one.from_window,
        };
        if let codex::Shown::In { window, .. } = codex::window_of(&server_session, &listed)
            && shown[window].is_none_or(|known| known.modified_ms < one.modified_ms)
        {
            shown[window] = Some(one);
        }
    }
    windows
        .iter()
        .zip(shown)
        .filter_map(|((window, lineage), one)| {
            let one = one?;
            let cwd = one.cwd.clone().or_else(|| folder(window.cwd.as_deref()))?;
            agent_note(
                Agent::Codex,
                lineage,
                one.id.clone(),
                cwd,
                Some(one.path.display().to_string()),
                shells,
                session,
            )
        })
        .collect()
}

/// Returns the note of an agent session whose process starts `lineage`,
/// linked to the tab whose shell note is the nearest process above it, or
/// `None` when it doesn't run in a tab that kaeru tracks or adopts.
fn agent_note(
    agent: Agent,
    lineage: &[ProcInfo],
    conversation: String,
    cwd: String,
    transcript: Option<String>,
    shells: &[ShellNote],
    session: &str,
) -> Option<AgentNote> {
    let process = lineage.first()?.to_ref()?;
    let (shell_process, shell) = lineage.iter().skip(1).find_map(|above| {
        let shell = shells.iter().find(|shell| above.is(&shell.process))?;
        Some((above, shell))
    })?;
    Some(AgentNote {
        process,
        agent: agent.id().into(),
        conversation,
        cwd,
        shell: Some(shell.process),
        shell_name: Some(shell.shell.clone()),
        shell_exe: shell_process
            .exe
            .as_ref()
            .map(|exe| exe.display().to_string()),
        terminal: shell.terminal.clone(),
        transcript,
        session: session.into(),
        offered: false,
    })
}

/// Keeps the folders of adopted tabs current: for each adopted tab whose
/// shell still runs, it writes the folder that the shell is in now into the
/// note. It runs whenever kaeru does, and reads only the shells of adopted
/// tabs, so that it stays fast. A tab whose shell keeps its folder to
/// itself, as PowerShell does, keeps the folder it was adopted with.
pub fn refresh(store: &Store, table: &mut SystemTable) {
    let adopted: Vec<ShellNote> = store
        .notes()
        .into_iter()
        .filter_map(|stored| match stored.note {
            Note::Shell(shell)
                if shell.adopted() && !KEEPS_ITS_FOLDER.contains(&shell.shell.as_str()) =>
            {
                Some(shell)
            }
            _ => None,
        })
        .collect();
    if adopted.is_empty() {
        return;
    }
    let pids: Vec<u32> = adopted.iter().map(|shell| shell.process.pid).collect();
    let processes = table.details(&pids);
    for shell in &adopted {
        let Some(process) = processes
            .iter()
            .find(|process| process.pid == shell.process.pid)
        else {
            continue;
        };
        if let Some(updated) = refreshed(shell, process)
            && let Err(error) = store.save(&Note::Shell(updated))
        {
            store.log(&format!("refresh: {error:#}"));
        }
    }
}

/// Returns an adopted tab's note with the folder that its shell is in now,
/// or `None` when nothing changed, the process isn't the tab's shell any
/// more, or the shell keeps its folder to itself.
fn refreshed(note: &ShellNote, process: &ProcInfo) -> Option<ShellNote> {
    if !note.adopted()
        || KEEPS_ITS_FOLDER.contains(&note.shell.as_str())
        || !process.is(&note.process)
    {
        return None;
    }
    let cwd = folder(process.cwd.as_deref())?;
    (cwd != note.cwd).then(|| ShellNote {
        cwd,
        ..note.clone()
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::procs::fake::FakeTable;
    use crate::procs::{ProcessTable, lineage};

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

    /// Windows Terminal (10) with three tabs: PowerShell (20) with Claude
    /// Code (40) in it, Git Bash through its launcher (21, 22), and a
    /// PowerShell (30) inside the first tab's shell, which isn't a tab.
    fn table() -> FakeTable {
        FakeTable::new(&[
            (10, None, "WindowsTerminal.exe", Some(1_000)),
            (20, Some(10), "powershell.exe", Some(2_000)),
            (21, Some(10), "bash.exe", Some(2_100)),
            (22, Some(21), "bash.exe", Some(2_200)),
            (30, Some(20), "pwsh.exe", Some(3_000)),
            (40, Some(20), "claude.exe", Some(4_000)),
            (50, None, "bash.exe", Some(5_000)),
        ])
        .with_exe(21, r"C:\Program Files\Git\bin\bash.exe")
        .with_exe(22, r"C:\Program Files\Git\usr\bin\bash.exe")
        .with_cwd(20, r"C:\Users\demo\")
        .with_cwd(21, r"C:\Users\demo\code\web-ui")
        .with_cwd(22, r"C:\Users\demo\code\web-ui\")
        .with_cwd(30, r"C:\Users\demo")
        .with_cwd(40, r"C:\Users\demo\code\api-server")
        .with_cwd(50, "/home/demo")
    }

    fn candidates(table: &FakeTable, pids: &[u32]) -> Vec<Candidate> {
        pids.iter()
            .map(|&pid| Candidate {
                lineage: lineage(table, pid),
                env: Env::from([("WT_SESSION".to_string(), format!("tab-{pid}"))]),
            })
            .collect()
    }

    #[test]
    fn the_shells_of_open_tabs_are_adopted() {
        let table = table();
        let shells = shell_notes(&candidates(&table, &[20, 21, 22, 30, 50]), "win-1", 9_000);
        let pids: Vec<u32> = shells.iter().map(|shell| shell.process.pid).collect();
        assert_eq!(pids, [20, 22], "not the launcher, a nested shell or no tab");
        assert_eq!(shells[0].cwd, r"C:\Users\demo");
        assert_eq!(shells[1].cwd, r"C:\Users\demo\code\web-ui");
        assert_eq!(shells[1].shell, "bash");
        assert!(shells.iter().all(ShellNote::adopted));
        assert_eq!(
            shells[0]
                .terminal
                .as_ref()
                .map(|terminal| terminal.process.pid),
            Some(10)
        );
    }

    #[test]
    fn the_shell_that_login_started_in_terminal_is_adopted() {
        // macOS's Terminal starts login, which runs as root and starts the
        // tab's shell. A zsh started in that shell isn't a tab.
        let table = FakeTable::new(&[
            (10, None, "Terminal", Some(1_000)),
            (15, Some(10), "login", Some(1_500)),
            (20, Some(15), "zsh", Some(2_000)),
            (30, Some(20), "zsh", Some(3_000)),
        ])
        .with_cwd(20, "/Users/demo/code/api-server")
        .with_cwd(30, "/Users/demo");
        let env = Env::from([
            ("TERM_PROGRAM".to_string(), "Apple_Terminal".to_string()),
            ("TERM_SESSION_ID".to_string(), "tab-1".to_string()),
        ]);
        let candidates: Vec<Candidate> = [20, 30]
            .iter()
            .map(|&pid| Candidate {
                lineage: lineage(&table, pid),
                env: env.clone(),
            })
            .collect();
        let shells = shell_notes(&candidates, "boot-1", 9_000);
        assert_eq!(shells.len(), 1);
        assert_eq!(shells[0].shell, "zsh");
        assert_eq!(shells[0].cwd, "/Users/demo/code/api-server");
        let terminal = shells[0].terminal.as_ref().unwrap();
        assert_eq!(terminal.adapter, "apple-terminal");
        assert_eq!(terminal.tab_id.as_deref(), Some("tab-1"));
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn a_shell_of_gnome_terminal_s_server_is_adopted() {
        let table = FakeTable::new(&[
            (10, None, "gnome-terminal-", Some(1_000)),
            (20, Some(10), "bash", Some(2_000)),
        ])
        .with_exe(10, "/usr/libexec/gnome-terminal-server")
        .with_cwd(20, "/home/demo/code/web-ui");
        let candidates = [Candidate {
            lineage: lineage(&table, 20),
            env: Env::from([("GNOME_TERMINAL_SERVICE".to_string(), ":1.2".to_string())]),
        }];
        let shells = shell_notes(&candidates, "boot-1", 9_000);
        assert_eq!(shells.len(), 1);
        assert_eq!(shells[0].cwd, "/home/demo/code/web-ui");
        assert_eq!(
            shells[0]
                .terminal
                .as_ref()
                .map(|terminal| terminal.adapter.as_str()),
            Some("gnome-terminal")
        );
    }

    #[test]
    fn a_claude_code_session_joins_its_tab_when_its_process_matches() {
        let table = table();
        let shells = shell_notes(&candidates(&table, &[20]), "win-1", 9_000);
        let running = |pid: u32, started_ms: u64| claude::Running {
            pid,
            session_id: ID.into(),
            cwd: Some(r"C:\Users\demo\code\api-server".into()),
            started_ms: Some(started_ms),
            kind: Some("interactive".into()),
        };
        let claude = vec![lineage(&table, 40)];
        let notes = claude_notes(&claude, &[running(40, 5_500)], &shells, "win-1");
        assert_eq!(notes.len(), 1);
        assert_eq!(notes[0].conversation, ID);
        assert_eq!(notes[0].shell, Some(shells[0].process));
        assert_eq!(notes[0].shell_name.as_deref(), Some("powershell"));
        // A session that started long after the process belongs to an
        // earlier process with the same id.
        assert!(claude_notes(&claude, &[running(40, 900_000)], &shells, "win-1").is_empty());
        assert!(claude_notes(&claude, &[running(41, 5_500)], &shells, "win-1").is_empty());
        // Without a tab, there is nothing to bring it back in.
        assert!(claude_notes(&claude, &[running(40, 5_500)], &[], "win-1").is_empty());
    }

    #[test]
    fn a_codex_window_shows_the_session_whose_file_changed_last() {
        let table = FakeTable::new(&[
            (10, None, "WindowsTerminal.exe", Some(1_000)),
            (20, Some(10), "powershell.exe", Some(2_000)),
            (40, Some(20), "codex.exe", Some(100_000)),
        ])
        .with_cwd(20, r"C:\Users\demo")
        .with_cwd(40, r"C:\Users\demo\code\api-server");
        let shells = shell_notes(&candidates(&table, &[20]), "win-1", 9_000);
        let window = table.get(40).unwrap();
        let windows = vec![(window, lineage(&table, 40))];
        let one = |created_ms: u64, modified_ms: u64| codex::Recorded {
            id: format!(
                "{:08x}-{:04x}-7000-8000-000000000001",
                created_ms >> 16,
                created_ms & 0xffff
            ),
            cwd: Some(r"C:\Users\demo\code\api-server".into()),
            from_window: true,
            path: format!("{created_ms}.jsonl").into(),
            modified_ms: Some(modified_ms),
        };
        let first = one(101_000, 5);
        let after_new = one(200_000, 9);
        let notes = codex_notes(&windows, &[first, after_new.clone()], &shells, "win-1");
        assert_eq!(notes.len(), 1);
        assert_eq!(notes[0].conversation, after_new.id);
        assert_eq!(notes[0].transcript.as_deref(), Some("200000.jsonl"));
        // A session that started before the window isn't its own.
        assert!(codex_notes(&windows, &[one(50_000, 9)], &shells, "win-1").is_empty());
    }

    #[test]
    fn an_adopted_tab_follows_its_shell_s_folder() {
        let table = table();
        let shells = shell_notes(&candidates(&table, &[20, 22]), "win-1", 9_000);
        let moved = FakeTable::new(&[(22, Some(21), "bash.exe", Some(2_200))])
            .with_cwd(22, r"C:\Users\demo\code\docs");
        let bash = &shells[1];
        let updated = refreshed(bash, &moved.get(22).unwrap()).unwrap();
        assert_eq!(updated.cwd, r"C:\Users\demo\code\docs");
        assert!(refreshed(&updated, &moved.get(22).unwrap()).is_none());
        // PowerShell's folder for the OS is the one it started in.
        let powershell = &shells[0];
        let moved = FakeTable::new(&[(20, Some(10), "powershell.exe", Some(2_000))])
            .with_cwd(20, r"C:\Windows");
        assert!(refreshed(powershell, &moved.get(20).unwrap()).is_none());
        // Another process with the shell's id isn't the shell.
        let other =
            FakeTable::new(&[(22, None, "bash.exe", Some(90_000))]).with_cwd(22, r"C:\Windows");
        assert!(refreshed(bash, &other.get(22).unwrap()).is_none());
    }

    #[test]
    fn folders_lose_the_separator_at_their_end() {
        assert_eq!(
            folder(Some(Path::new(r"C:\Users\demo\"))).as_deref(),
            Some(r"C:\Users\demo")
        );
        assert_eq!(folder(Some(Path::new(r"C:\"))).as_deref(), Some(r"C:\"));
        assert_eq!(folder(Some(Path::new("/"))).as_deref(), Some("/"));
        assert_eq!(folder(None), None);
    }
}