mod picker;
use std::io::{self, IsTerminal, Write};
use std::path::Path;
use std::process::ExitCode;
use std::time::{Duration, SystemTime};
use anyhow::{Context, Result};
use ratatui::crossterm::queue;
use ratatui::crossterm::style::{Color, Print, ResetColor, SetForegroundColor};
use crate::agents::Agent;
use crate::engine::note::{Note, ShellNote, TerminalRef};
use crate::engine::rules::Liveness;
use crate::engine::rules::TabState;
use crate::engine::tabs::{self, Seen, Tab};
use crate::os;
use crate::procs::{self, system::SystemTable};
use crate::shells::{self, Shell};
use crate::store::{self, Store, StoredNote};
use crate::terminals::{self, Env, TabToOpen};
use picker::{Choice, Entry, Picker};
pub const CLOSE_THIS_TAB: u8 = 4;
const NEW_TAB_VAR: &str = "KAERU_NEW_TAB";
const SHELL_PID_VAR: &str = "KAERU_SHELL_PID";
const PAUSE: Duration = Duration::from_secs(1);
pub fn pick() -> Result<ExitCode> {
let store = Store::open()?;
let config = store.config();
let env: Env = std::env::vars().collect();
let mut table = SystemTable::snapshot();
let lineage = table.lineage(std::process::id());
if let Some((_, terminal)) = terminals::tab_of(&terminals::all(), &env, &lineage) {
let wait = shells::restore_settle(&terminal, shells::now_ms());
if !wait.is_zero() {
std::thread::sleep(wait);
table = SystemTable::snapshot();
}
}
let session = os::session_id()?;
let reviewed = store::review(&store, &table, &session, config.single_window_close);
let waiting: Vec<StoredNote> = reviewed
.iter()
.filter(|one| one.state == TabState::Waiting)
.filter(|one| !shells::left_to_its_terminal(&one.stored.note, &reviewed))
.map(|one| one.stored.clone())
.collect();
let notes: Vec<(Note, Seen)> = waiting
.iter()
.map(|stored| (stored.note.clone(), store::last_seen(stored)))
.collect();
let tabs = tabs::to_offer(¬es, &config);
if tabs.is_empty() {
for stored in &waiting {
store.remove(stored);
}
if !env.contains_key(NEW_TAB_VAR) {
println!("No tabs are waiting to come back. To change the options, run kaeru options.");
}
return Ok(ExitCode::SUCCESS);
}
let entries: Vec<Entry> = tabs.iter().map(entry).collect();
if !can_draw() {
for line in picker::columns(&entries) {
println!("{line}");
}
if std::env::var_os("MSYSTEM").is_some() && std::io::stdin().is_terminal() {
println!("To choose which tabs to reopen, run winpty kaeru in this window.");
} else {
println!("Run kaeru in a terminal to choose which tabs to reopen.");
}
return Ok(ExitCode::SUCCESS);
}
let Some(_lock) = store.try_lock()? else {
println!("kaeru's list is already open in another tab. Choose there, or close it first.");
return Ok(ExitCode::SUCCESS);
};
let mut picker = Picker::new(entries, config);
picker.color = colors_wanted();
let choice = picker::run(&mut picker)?;
if picker.config != config {
store.save_config(&picker.config)?;
}
if choice == Choice::Later {
return Ok(ExitCode::SUCCESS);
}
let to_open = in_opening_order(&tabs, &picker.checked);
let shells: Vec<ShellNote> = store
.notes()
.into_iter()
.filter_map(|stored| match stored.note {
Note::Shell(shell) => Some(shell),
Note::Agent(_) => None,
})
.collect();
let lineage = table.lineage(std::process::id());
let found = terminals::tab_or_noted(&terminals::all(), &env, &lineage, &shells);
let asking = env
.get(SHELL_PID_VAR)
.and_then(|pid| pid.parse::<u32>().ok())
.or_else(|| {
let (index, _) = found.as_ref()?;
Some(lineage.get(*index)?.pid)
});
let here = found.map(|(_, terminal)| terminal).or_else(|| {
shells
.iter()
.find(|shell| Some(shell.process.pid) == asking)?
.terminal
.clone()
});
let close = env.contains_key(NEW_TAB_VAR)
&& !to_open.is_empty()
&& to_open.iter().all(|tab| {
here.as_ref()
.is_some_and(|here| same_terminal(here, &tab.terminal))
});
let reopened = reopen(&store, &waiting, &to_open)?;
let forgotten = picker.checked.iter().filter(|checked| !**checked).count();
if forgotten > 0 {
println!("Forgot {}.", count(forgotten));
}
if close && reopened == to_open.len() {
for stored in store.notes() {
if let Note::Shell(shell) = &stored.note
&& Some(shell.process.pid) == asking
{
store.remove(&stored);
}
}
Ok(ExitCode::from(CLOSE_THIS_TAB))
} else {
Ok(ExitCode::SUCCESS)
}
}
fn in_opening_order<'a>(tabs: &'a [Tab], checked: &[bool]) -> Vec<&'a Tab> {
let mut chosen: Vec<&Tab> = tabs
.iter()
.zip(checked)
.filter(|(_, checked)| **checked)
.map(|(tab, _)| tab)
.collect();
chosen.sort_by_key(|tab| tab.started_ms);
chosen
}
fn same_terminal(a: &TerminalRef, b: &TerminalRef) -> bool {
a.adapter == b.adapter
&& a.exe.as_deref().map(str::to_ascii_lowercase)
== b.exe.as_deref().map(str::to_ascii_lowercase)
}
fn reopen(store: &Store, waiting: &[StoredNote], tabs: &[&Tab]) -> Result<usize> {
let chosen: Vec<usize> = tabs
.iter()
.flat_map(|tab| tab.notes.iter().copied())
.collect();
for (index, stored) in waiting.iter().enumerate() {
if !chosen.contains(&index) {
store.remove(stored);
}
}
let adapters = terminals::all();
let mut opened = 0;
let mut failure = None;
for (number, tab) in tabs.iter().enumerate() {
if number > 0 {
std::thread::sleep(PAUSE);
}
let notes: Vec<Note> = tab
.notes
.iter()
.map(|&index| {
let mut note = waiting[index].note.clone();
if let Note::Shell(shell) = &mut note {
shell.cwd = store::last_seen(&waiting[index]).cwd;
}
note
})
.collect();
for &index in &tab.notes {
store.remove(&waiting[index]);
}
if !Path::new(&tab.cwd).is_dir() {
println!("Not reopened, because its folder is gone: {}", tab.cwd);
continue;
}
println!(
"Reopening {} of {}: {}",
number + 1,
tabs.len(),
folder_name(&tab.cwd)
);
let id = tab.terminal.adapter.as_str();
let result = match adapters.iter().find(|adapter| adapter.id() == id) {
Some(adapter) => {
let exe = tab.terminal.exe.as_deref().map(Path::new);
let mut open = tab_to_open(tab);
if runs_in_bash(&open, &tab.terminal) {
shells::write_bash_run_file(store.dir(), &open.cwd, &open.run).map(|file| {
open.rcfile = Some(file.display().to_string());
})?;
}
adapter.reopen(exe, &[open])
}
None => Err(anyhow::anyhow!(
"this version of kaeru doesn't know the terminal {id}"
)),
};
match result {
Ok(()) => opened += 1,
Err(error) => {
for note in ¬es {
let _ = store.save(note);
}
failure.get_or_insert(error);
}
}
}
if opened > 0 {
println!("Reopened {}.", count(opened));
}
failure.map_or(Ok(opened), Err)
}
fn tab_to_open(tab: &Tab) -> TabToOpen {
let run = tab
.agent
.as_ref()
.and_then(|note| Some(Agent::from_id(¬e.agent)?.resume_command(note)))
.unwrap_or_default();
TabToOpen {
title: folder_name(&tab.cwd).to_string(),
cwd: tab.cwd.clone(),
profile: tab.terminal.profile.clone(),
shell: tab.shell.clone(),
run,
shell_exe: tab.agent.as_ref().and_then(|note| note.shell_exe.clone()),
rcfile: None,
}
}
fn runs_in_bash(tab: &TabToOpen, terminal: &TerminalRef) -> bool {
cfg!(windows)
&& !tab.run.is_empty()
&& (tab
.shell
.as_deref()
.is_some_and(|shell| shell.eq_ignore_ascii_case("bash"))
|| terminal.adapter == "mintty")
}
fn entry(tab: &Tab) -> Entry {
let (what, when) = match &tab.agent {
Some(note) => match Agent::from_id(¬e.agent) {
Some(agent) => {
let when = agent
.conversation_file(note)
.map_or_else(|| "no messages yet".to_string(), |file| last_used(&file));
(agent.name().to_string(), when)
}
None => (note.agent.clone(), String::new()),
},
None => (shell_name(tab.shell.as_deref()), String::new()),
};
Entry {
agent: tab.agent.is_some(),
name: folder_name(&tab.cwd).to_string(),
what,
when,
folder: home_as_tilde(&tab.cwd),
terminal: terminals::name_of(&tab.terminal.adapter),
}
}
pub fn list() -> Result<()> {
let store = Store::open()?;
let config = store.config();
let table = SystemTable::snapshot();
let session = os::session_id()?;
let reviewed = store::review(&store, &table, &session, config.single_window_close);
let notes_in = |state: TabState| -> Vec<(Note, Seen)> {
reviewed
.iter()
.filter(|reviewed| reviewed.state == state)
.map(|reviewed| {
(
reviewed.stored.note.clone(),
store::last_seen(&reviewed.stored),
)
})
.collect()
};
let open = tabs::group(¬es_in(TabState::Open));
let waiting = tabs::to_offer(¬es_in(TabState::Waiting), &config);
if open.is_empty() && waiting.is_empty() {
println!("No tabs are tracked yet.");
return Ok(());
}
let entries: Vec<Entry> = open.iter().chain(&waiting).map(entry).collect();
let lines = picker::columns(&entries);
let (open_lines, waiting_lines) = lines.split_at(open.len());
for (title, lines) in [
("Open", open_lines),
("Waiting to come back", waiting_lines),
] {
if !lines.is_empty() {
println!("{title}:");
for line in lines {
println!(" {line}");
}
}
}
Ok(())
}
const GREETING: [(&str, &str); 4] = [
(" (o)____(o) ", " kaeru"),
(
" / \\ ",
" Your tabs come back after the terminal closes.",
),
(" | \\______/ |", ""),
(" \\__________/ ", ""),
];
pub fn greet() -> io::Result<()> {
let color = colors_wanted() && io::stdout().is_terminal();
let mut out = io::stdout().lock();
for (frog, text) in GREETING {
let frog = if text.is_empty() {
frog.trim_end()
} else {
frog
};
if color {
queue!(
out,
SetForegroundColor(Color::DarkGreen),
Print(frog),
ResetColor
)?;
} else {
queue!(out, Print(frog))?;
}
queue!(out, Print(text), Print("\n"))?;
}
queue!(out, Print("\n"))?;
out.flush()
}
pub fn resume(shell: Option<Shell>) -> Result<ExitCode> {
let say = |message: String| {
if shell.is_some() {
eprintln!("{message}");
} else {
println!("{message}");
}
};
let store = Store::open()?;
let config = store.config();
let mut table = SystemTable::snapshot();
let session = os::session_id()?;
let env: Env = std::env::vars().collect();
let lineage = table.lineage(std::process::id());
let Some(here) = terminals::tab_of(&terminals::all(), &env, &lineage)
.map(|(_, terminal)| terminal)
.filter(|terminal| terminal.tab_id.is_some())
else {
say("This isn't a tab that its terminal restored, so no session waits in it.".into());
return Ok(ExitCode::SUCCESS);
};
let reviewed = store::review(&store, &table, &session, config.single_window_close);
let found = reviewed.into_iter().find_map(|reviewed| {
let Note::Agent(note) = &reviewed.stored.note else {
return None;
};
let old = note.terminal.as_ref()?;
let from_before = old.adapter == here.adapter
&& old.tab_id == here.tab_id
&& old.process != here.process
&& procs::liveness(&table, &old.process) != Liveness::Running;
let orphan = procs::liveness(&table, ¬e.process) == Liveness::Running;
(from_before && (reviewed.state == TabState::Waiting || orphan))
.then(|| (reviewed.stored.clone(), note.clone(), orphan))
});
let Some((stored, note, orphan)) = found else {
say("No agent session waits to be resumed in this tab.".into());
return Ok(ExitCode::SUCCESS);
};
let Some(agent) = Agent::from_id(¬e.agent) else {
return Ok(ExitCode::SUCCESS);
};
if orphan {
table.end(¬e.process);
if let Some(shell) = ¬e.shell {
table.end(shell);
}
std::thread::sleep(PAUSE);
say(format!(
"Ended the {} session that ran without a window.",
agent.name()
));
}
store.remove(&stored);
let note = ¬e;
let words = agent.resume_command(note);
say(format!(
"Resuming the {} session: {}",
agent.name(),
words.join(" ")
));
if let Some(shell) = shell {
println!("{}", shells::run_code(shell, ¬e.cwd, &words));
return Ok(ExitCode::SUCCESS);
}
let status = command_for(&words)?
.current_dir(¬e.cwd)
.status()
.with_context(|| format!("can't start {}", words.join(" ")))?;
Ok(ExitCode::from(
status
.code()
.and_then(|code| u8::try_from(code).ok())
.unwrap_or(1),
))
}
fn command_for(words: &[String]) -> Result<std::process::Command> {
let (program, arguments) = words.split_first().context("there is nothing to run")?;
if cfg!(windows)
&& let Some(found) = find_program(program)
{
let extension = found
.extension()
.map(|extension| extension.to_string_lossy().to_ascii_lowercase());
if matches!(extension.as_deref(), Some("cmd" | "bat")) {
let mut command = std::process::Command::new("cmd.exe");
command.arg("/c").arg(found).args(arguments);
return Ok(command);
}
let mut command = std::process::Command::new(found);
command.args(arguments);
return Ok(command);
}
let mut command = std::process::Command::new(program);
command.args(arguments);
Ok(command)
}
fn find_program(program: &str) -> Option<std::path::PathBuf> {
let extensions = std::env::var("PATHEXT").unwrap_or_else(|_| ".COM;.EXE;.BAT;.CMD".into());
std::env::split_paths(&std::env::var_os("PATH")?).find_map(|folder| {
extensions
.split(';')
.filter(|extension| !extension.is_empty())
.map(|extension| folder.join(format!("{program}{extension}")))
.find(|candidate| candidate.is_file())
})
}
pub fn options() -> Result<()> {
let store = Store::open()?;
let config = store.config();
if !can_draw() {
print!("{}", toml::to_string(&config)?);
if std::env::var_os("MSYSTEM").is_some() && io::stdin().is_terminal() {
println!(
"These are kaeru's options. To change them in this window, run winpty kaeru options."
);
} else {
println!("These are kaeru's options. Run kaeru options in a terminal to change them.");
}
return Ok(());
}
let mut picker = Picker::options(config);
picker.color = colors_wanted();
picker::run(&mut picker)?;
if picker.config == config {
println!("The options stay as they were.");
} else {
store.save_config(&picker.config)?;
println!("Saved the options.");
}
Ok(())
}
fn can_draw() -> bool {
let console = cfg!(not(windows)) || console_input();
io::stdin().is_terminal() && io::stdout().is_terminal() && console
}
#[cfg(windows)]
fn console_input() -> bool {
os::has_console_input()
}
#[cfg(not(windows))]
fn console_input() -> bool {
true
}
pub fn colors_wanted() -> bool {
picker::colors_allowed(std::env::var_os("NO_COLOR").as_deref())
}
fn shell_name(shell: Option<&str>) -> String {
match shell {
Some(shell)
if shell.eq_ignore_ascii_case("powershell") || shell.eq_ignore_ascii_case("pwsh") =>
{
"PowerShell".into()
}
Some(shell) if shell.eq_ignore_ascii_case("bash") => "Bash".into(),
Some(shell) => shell.into(),
None => "shell".into(),
}
}
fn folder_name(cwd: &str) -> &str {
let trimmed = cwd.trim_end_matches(['\\', '/']);
trimmed
.rsplit(['\\', '/'])
.next()
.filter(|name| !name.is_empty())
.unwrap_or(cwd)
}
fn home_as_tilde(cwd: &str) -> String {
let Some(home) = dirs::home_dir() else {
return cwd.into();
};
let home = home.display().to_string();
let rest = cwd.get(home.len()..).filter(|_| {
cwd.get(..home.len())
.is_some_and(|start| start.eq_ignore_ascii_case(&home))
});
match rest {
Some(rest) if rest.is_empty() || rest.starts_with(['\\', '/']) => format!("~{rest}"),
_ => cwd.into(),
}
}
fn last_used(file: &Path) -> String {
let seconds = std::fs::metadata(file)
.and_then(|metadata| metadata.modified())
.ok()
.and_then(|modified| SystemTime::now().duration_since(modified).ok())
.map_or(0, |elapsed| elapsed.as_secs());
ago(seconds)
}
fn ago(seconds: u64) -> String {
let (count, unit) = match seconds {
0..60 => return "just now".into(),
60..3_600 => (seconds / 60, "minute"),
3_600..86_400 => (seconds / 3_600, "hour"),
_ => (seconds / 86_400, "day"),
};
let plural = if count == 1 { "" } else { "s" };
format!("{count} {unit}{plural} ago")
}
fn count(tabs: usize) -> String {
if tabs == 1 {
"1 tab".into()
} else {
format!("{tabs} tabs")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_tab_is_named_after_its_folder() {
assert_eq!(folder_name(r"C:\Users\demo\code\mobile-app"), "mobile-app");
assert_eq!(folder_name("/home/demo/code/api-server/"), "api-server");
assert_eq!(folder_name(r"D:\"), "D:");
}
#[test]
fn time_spans_read_as_words() {
assert_eq!(ago(5), "just now");
assert_eq!(ago(60), "1 minute ago");
assert_eq!(ago(40 * 60), "40 minutes ago");
assert_eq!(ago(2 * 3_600), "2 hours ago");
assert_eq!(ago(3 * 86_400), "3 days ago");
}
#[test]
fn shells_are_shown_by_their_names() {
assert_eq!(shell_name(Some("pwsh")), "PowerShell");
assert_eq!(shell_name(Some("powershell")), "PowerShell");
assert_eq!(shell_name(Some("bash")), "Bash");
assert_eq!(shell_name(Some("fish")), "fish");
}
fn terminal(exe: &str) -> TerminalRef {
TerminalRef {
adapter: "windows-terminal".into(),
process: crate::engine::note::ProcessRef {
pid: 1,
started_ms: 100,
},
shape: crate::engine::rules::TerminalShape::Tabs,
tab_id: None,
profile: None,
exe: Some(exe.into()),
}
}
fn tab(cwd: &str, started_ms: u64) -> Tab {
Tab {
notes: Vec::new(),
cwd: cwd.into(),
shell: None,
agent: None,
terminal: terminal(r"C:\Apps\WindowsTerminal.exe"),
started_ms,
}
}
#[test]
fn checked_tabs_come_back_in_the_order_they_were_opened() {
let tabs = [
tab("agent-opened-third", 3_000),
tab("agent-opened-first", 1_000),
tab("shell-opened-second", 2_000),
tab("shell-unchecked", 500),
];
let order: Vec<&str> = in_opening_order(&tabs, &[true, true, true, false])
.iter()
.map(|tab| tab.cwd.as_str())
.collect();
assert_eq!(
order,
[
"agent-opened-first",
"shell-opened-second",
"agent-opened-third"
]
);
}
#[test]
fn tabs_of_another_copy_of_the_terminal_are_elsewhere() {
let here = terminal(r"C:\Apps\WindowsTerminal.exe");
assert!(same_terminal(
&here,
&terminal(r"c:\apps\windowsterminal.exe")
));
assert!(!same_terminal(
&here,
&terminal(r"D:\Portable\WindowsTerminal.exe")
));
}
#[test]
fn the_frog_lines_have_one_width_so_that_the_text_lines_up() {
let width = GREETING[0].0.len();
assert!(GREETING.iter().all(|(frog, _)| frog.len() == width));
}
#[test]
fn folders_outside_home_keep_their_path() {
assert_eq!(home_as_tilde("Q:\\elsewhere"), "Q:\\elsewhere");
}
}