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};
const SHELLS: [&str; 5] = ["powershell", "pwsh", "bash", "zsh", "fish"];
const KEEPS_ITS_FOLDER: [&str; 2] = ["powershell", "pwsh"];
const CLAUDE_START_MS: u64 = 60_000;
pub struct Candidate {
pub lineage: Vec<ProcInfo>,
pub env: Env,
}
#[derive(Debug, Default)]
pub struct Found {
pub shells: Vec<ShellNote>,
pub agents: Vec<AgentNote>,
}
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(())
}
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(())
}
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(())
}
fn terminal_name(shell: &ShellNote) -> String {
shell
.terminal
.as_ref()
.map_or_else(String::new, |terminal| {
terminals::name_of(&terminal.adapter)
})
}
fn shell_title(shell: &str) -> &str {
match shell {
"powershell" => "Windows PowerShell",
"pwsh" => "PowerShell",
other => other,
}
}
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));
}
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 })
}
fn is_node(name: &str) -> bool {
name.eq_ignore_ascii_case("node") || name.eq_ignore_ascii_case("node.exe")
}
fn is_shell(name: &str) -> bool {
SHELLS.contains(&plain_shell_name(name).to_ascii_lowercase().as_str())
}
fn plain_shell_name(name: &str) -> String {
shell_name(name.trim_start_matches('-'))
}
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()
}
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())
}
}
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()
}
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()
}
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,
})
}
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:#}"));
}
}
}
fn refreshed(note: &ShellNote, process: &ProcInfo) -> Option<ShellNote> {
if !note.adopted()
|| KEEPS_ITS_FOLDER.contains(¬e.shell.as_str())
|| !process.is(¬e.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";
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() {
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"));
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());
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"));
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());
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());
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);
}
}