use std::path::{Path, PathBuf};
use std::process::ExitCode;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use anyhow::{Context, Result, bail};
use crate::agents::{Agent, codex};
use crate::engine::config::Config;
use crate::engine::note::{Note, ShellNote};
use crate::engine::rules::Liveness;
use crate::engine::rules::TabState;
use crate::engine::tabs::{self, Seen};
use crate::os;
use crate::procs::system::SystemTable;
use crate::procs::{self, ProcInfo, ProcessTable};
use crate::store::{self, Reviewed, Store, StoredNote};
use crate::terminals::{self, Env};
const POWERSHELL: &str = include_str!("powershell.ps1");
const POWERSHELL_CODEX: &str = include_str!("powershell-codex.ps1");
const BASH: &str = include_str!("bash.sh");
const BASH_CODEX: &str = include_str!("bash-codex.sh");
const ASK: u8 = 3;
const ASK_THROUGH_WINPTY: u8 = 5;
const RESTORE_WAIT_MS: u64 = 120_000;
struct Started {
cwd_file: Option<PathBuf>,
ask: bool,
console: bool,
resume: Option<ToResume>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ToResume {
pub agent: String,
pub orphan: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum Shell {
Powershell,
Bash,
Zsh,
Fish,
}
impl Shell {
pub fn name(self) -> &'static str {
match self {
Shell::Powershell => "powershell",
Shell::Bash => "bash",
Shell::Zsh => "zsh",
Shell::Fish => "fish",
}
}
}
pub fn print_init(shell: Shell) -> Result<()> {
let config = || {
Store::open()
.map(|store| store.config())
.unwrap_or_default()
};
match shell {
Shell::Powershell => {
print!("{}", powershell_snippet(&config()));
Ok(())
}
Shell::Bash => {
print!("{}", bash_snippet(&config()));
Ok(())
}
_ => bail!(
"`kaeru init {}` is not built yet. See the roadmap in README.md.",
shell.name()
),
}
}
fn powershell_snippet(config: &Config) -> String {
let mut snippet = POWERSHELL.to_string();
if config.codex_no_daemon {
let one_off: Vec<String> = codex::ONE_OFF_COMMANDS
.iter()
.map(|command| format!("'{command}'"))
.collect();
snippet.push_str(&POWERSHELL_CODEX.replace("KAERU_ONE_OFF_COMMANDS", &one_off.join(", ")));
}
snippet
}
fn bash_snippet(config: &Config) -> String {
let mut snippet = BASH.to_string();
if config.codex_no_daemon {
snippet.push_str(&BASH_CODEX.replace(
"KAERU_ONE_OFF_COMMANDS",
&codex::ONE_OFF_COMMANDS.join(" | "),
));
}
snippet
}
pub fn start(pid: u32, parent: Option<u32>) -> ExitCode {
let Ok(store) = Store::open() else {
return ExitCode::SUCCESS;
};
match record(&store, pid, parent) {
Ok(started) => {
if let Some(cwd_file) = started.cwd_file {
println!("{}", cwd_file.display());
}
match started.resume {
Some(ToResume {
agent,
orphan: false,
}) => eprintln!(
"kaeru: this tab had a {agent} session. To resume it here, run kaeru resume."
),
Some(ToResume {
agent,
orphan: true,
}) => eprintln!(
"kaeru: this tab had a {agent} session, which still runs without a window \
since the terminal closed. To end it and resume it here, run kaeru resume."
),
None => {}
}
if started.ask {
return ExitCode::from(if started.console {
ASK
} else {
ASK_THROUGH_WINPTY
});
}
}
Err(error) => store.log(&format!("shell start: {error:#}")),
}
ExitCode::SUCCESS
}
fn record(store: &Store, pid: u32, parent: Option<u32>) -> Result<Started> {
let mut table = SystemTable::snapshot();
let mut lineage = table.lineage(pid);
if let Some(parent) = parent {
lineage = procs::with_parent(lineage, table.lineage(parent));
}
let env: Env = std::env::vars().collect();
let session = os::session_id()?;
let config = store.config();
let cwd = std::env::current_dir()?.display().to_string();
let note = shell_note(pid, &lineage, &env, &session, cwd)?;
let console = note
.as_ref()
.and_then(Note::terminal)
.is_none_or(|terminal| terminals::gives_a_console(&terminal.adapter));
let path = match note {
Some(note) if store.path_of(¬e).exists() => Some(store.path_of(¬e)),
Some(note) => Some(store.save(¬e)?),
None => None,
};
let reviewed = store::review(store, &table, &session, config.single_window_close);
let resume = path
.as_ref()
.and_then(|path| store.read(path).ok())
.and_then(|note| claim(store, &reviewed, ¬e, now_ms(), &table));
let ask = match &path {
Some(_) => {
let command_line = lineage
.first()
.and_then(|shell| shell.command_line.as_deref())
.unwrap_or_default();
offer(store, &reviewed, &config, runs_a_command(command_line))?
}
None => false,
};
Ok(Started {
cwd_file: path.map(|path| store::cwd_file(&path)),
ask,
console,
resume,
})
}
fn claim(
store: &Store,
reviewed: &[Reviewed],
note: &Note,
now_ms: u64,
table: &dyn ProcessTable,
) -> Option<ToResume> {
let terminal = note.terminal()?;
let tab_id = terminal.tab_id.as_deref()?;
if !terminals::restores_its_own_tabs(&terminal.adapter) {
return None;
}
let restored = now_ms.saturating_sub(terminal.process.started_ms) > RESTORE_WAIT_MS;
let mut resume = None;
for reviewed in reviewed {
let Some(old) = reviewed.stored.note.terminal() else {
continue;
};
let from_before = old.adapter == terminal.adapter
&& old.process != terminal.process
&& procs::liveness(table, &old.process) != Liveness::Running;
if !from_before {
continue;
}
if old.tab_id.as_deref() == Some(tab_id) {
match &reviewed.stored.note {
Note::Shell(_) => store.remove(&reviewed.stored),
Note::Agent(agent) => {
let orphan = procs::liveness(table, &agent.process) == Liveness::Running;
if reviewed.state == TabState::Waiting || orphan {
resume = Some(ToResume {
agent: Agent::from_id(&agent.agent).map_or_else(
|| agent.agent.clone(),
|known| known.name().to_string(),
),
orphan,
});
}
}
}
} else if restored && reviewed.state == TabState::Waiting {
store.remove(&reviewed.stored);
}
}
resume
}
fn now_ms() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.ok()
.and_then(|since| u64::try_from(since.as_millis()).ok())
.unwrap_or(0)
}
fn offer(
store: &Store,
reviewed: &[Reviewed],
config: &Config,
runs_a_command: bool,
) -> Result<bool> {
let waiting: Vec<&StoredNote> = reviewed
.iter()
.filter(|reviewed| reviewed.state == TabState::Waiting)
.map(|reviewed| &reviewed.stored)
.filter(|stored| !restored_by_its_terminal(&stored.note))
.collect();
let notes: Vec<(Note, Seen)> = waiting
.iter()
.map(|stored| (stored.note.clone(), store::last_seen(stored)))
.collect();
let count = tabs::to_offer(¬es, config).len();
if count == 0 {
for stored in &waiting {
store.remove(stored);
}
return Ok(false);
}
let Some(_lock) = store.try_lock()? else {
return Ok(false);
};
if config.ask_on_start && !runs_a_command {
let mut new = false;
for stored in &waiting {
if let Ok(mut note) = store.read(&stored.path)
&& !note.offered()
{
note.set_offered();
store.save(¬e)?;
new = true;
}
}
if new {
return Ok(true);
}
}
let (tabs, them) = if count == 1 {
("1 tab is".to_string(), "it")
} else {
(format!("{count} tabs are"), "them")
};
eprintln!("kaeru: {tabs} waiting to come back. Run kaeru to see {them}.");
Ok(false)
}
const RUN_FILE_PREFIX: &str = "kaeru-run-";
const RUN_FILE_AGE: Duration = Duration::from_secs(24 * 60 * 60);
pub fn bash_run_script(cwd: &str, run: &[String]) -> String {
format!(
"# kaeru wrote this file, for bash to read instead of ~/.bashrc when it\n\
# brings back a tab with its agent session. kaeru deletes it later.\n\
[ -f /etc/profile ] && . /etc/profile\n\
__kaeru_login=\n\
for __kaeru_file in ~/.bash_profile ~/.bash_login ~/.profile; do\n\
\x20 if [ -f \"$__kaeru_file\" ]; then\n\
\x20 . \"$__kaeru_file\"\n\
\x20 __kaeru_login=1\n\
\x20 break\n\
\x20 fi\n\
done\n\
[ -z \"$__kaeru_login\" ] && [ -f ~/.bashrc ] && . ~/.bashrc\n\
unset __kaeru_login __kaeru_file\n\
{}\n",
bash_run_line(cwd, run)
)
}
pub fn bash_run_line(cwd: &str, run: &[String]) -> String {
let words: Vec<String> = run.iter().map(|word| bash_word(word)).collect();
format!("cd -- {} && {}", bash_word(cwd), words.join(" "))
}
pub fn powershell_run_lines(cwd: &str, run: &[String]) -> String {
let words: Vec<String> = run.iter().map(|word| powershell_word(word)).collect();
format!(
"Set-Location -LiteralPath '{}'\n& {}",
cwd.replace('\'', "''"),
words.join(" ")
)
}
fn powershell_word(word: &str) -> String {
let plain = !word.is_empty()
&& word
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'));
if plain {
word.to_string()
} else {
format!("'{}'", word.replace('\'', "''"))
}
}
pub fn run_code(shell: Shell, cwd: &str, run: &[String]) -> Result<String> {
match shell {
Shell::Powershell => Ok(powershell_run_lines(cwd, run)),
Shell::Bash => Ok(bash_run_line(cwd, run)),
_ => bail!(
"`kaeru init {}` is not built yet. See the roadmap in README.md.",
shell.name()
),
}
}
fn bash_word(word: &str) -> String {
let plain = !word.is_empty()
&& word
.chars()
.all(|c| c.is_ascii_alphanumeric() || "-_./:=@%+,".contains(c));
if plain {
word.to_string()
} else {
format!("'{}'", word.replace('\'', r"'\''"))
}
}
pub fn write_bash_run_file(state: &Path, cwd: &str, run: &[String]) -> Result<PathBuf> {
let folder = state.join("run");
std::fs::create_dir_all(&folder)
.with_context(|| format!("can't create {}", folder.display()))?;
if let Ok(entries) = std::fs::read_dir(&folder) {
for entry in entries.flatten() {
let old = entry
.metadata()
.and_then(|metadata| metadata.modified())
.ok()
.and_then(|modified| modified.elapsed().ok())
.is_some_and(|age| age > RUN_FILE_AGE);
if old {
let _ = std::fs::remove_file(entry.path());
}
}
}
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |since| since.as_nanos());
let file = folder.join(format!("{RUN_FILE_PREFIX}{now}.sh"));
std::fs::write(&file, bash_run_script(cwd, run))
.with_context(|| format!("can't write {}", file.display()))?;
Ok(file)
}
pub fn restored_by_its_terminal(note: &Note) -> bool {
note.terminal()
.is_some_and(|terminal| terminals::restores_its_own_tabs(&terminal.adapter))
}
pub fn runs_a_command(command_line: &str) -> bool {
if command_line.contains(RUN_FILE_PREFIX) {
return true;
}
command_line.split_whitespace().skip(1).any(|argument| {
let Some(name) = argument.strip_prefix(['-', '/']) else {
return false;
};
let name = name.to_ascii_lowercase();
!name.is_empty()
&& name.chars().all(|c| c.is_ascii_alphabetic())
&& (name == "ec"
|| ["command", "file", "encodedcommand"]
.iter()
.any(|parameter| parameter.starts_with(&name)))
})
}
fn shell_note(
pid: u32,
lineage: &[ProcInfo],
env: &Env,
session: &str,
cwd: String,
) -> Result<Option<Note>> {
let shell = lineage
.first()
.filter(|process| process.pid == pid)
.context("the shell's process is gone")?;
let Some((0, terminal)) = terminals::tab_of(&terminals::all(), env, lineage) else {
return Ok(None);
};
Ok(Some(Note::Shell(ShellNote {
process: shell
.to_ref()
.context("the shell's start time can't be read")?,
shell: shell_name(&shell.name),
cwd,
terminal: Some(terminal),
session: session.into(),
offered: false,
})))
}
pub fn shell_name(executable: &str) -> String {
let path = Path::new(executable);
let is_exe = path
.extension()
.is_some_and(|extension| extension.eq_ignore_ascii_case("exe"));
let name = if is_exe {
path.file_stem()
} else {
path.file_name()
};
name.map_or_else(
|| executable.to_string(),
|name| name.to_string_lossy().into_owned(),
)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::procs::{fake::FakeTable, lineage};
fn tab_table() -> FakeTable {
FakeTable::new(&[
(30, Some(20), "pwsh.exe", Some(3_000)),
(20, Some(10), "powershell.exe", Some(2_000)),
(10, None, "WindowsTerminal.exe", Some(1_000)),
])
}
fn tab_env() -> Env {
Env::from([("WT_SESSION".to_string(), "x".to_string())])
}
#[test]
fn the_shell_of_a_tab_gets_a_note() {
let table = tab_table();
let note = shell_note(20, &lineage(&table, 20), &tab_env(), "win-1", "C:\\".into());
let Some(Note::Shell(note)) = note.unwrap() else {
panic!("no shell note");
};
assert_eq!(note.shell, "powershell");
assert_eq!(note.terminal.unwrap().process.pid, 10);
}
#[test]
fn a_shell_inside_a_tab_gets_no_note() {
let table = tab_table();
let note = shell_note(30, &lineage(&table, 30), &tab_env(), "win-1", "C:\\".into());
assert!(note.unwrap().is_none());
}
#[test]
fn a_shell_outside_known_terminals_gets_no_note() {
let table = tab_table();
let note = shell_note(
20,
&lineage(&table, 20),
&Env::new(),
"win-1",
"C:\\".into(),
);
assert!(note.unwrap().is_none());
}
#[test]
fn shell_names_drop_the_exe_extension() {
assert_eq!(shell_name("powershell.exe"), "powershell");
assert_eq!(shell_name("pwsh.EXE"), "pwsh");
assert_eq!(shell_name("zsh"), "zsh");
}
#[test]
fn the_powershell_snippet_is_ascii_and_starts_the_tab() {
assert!(POWERSHELL.is_ascii());
assert!(POWERSHELL.contains("kaeru shell start --pid $PID"));
}
#[test]
fn other_snippets_are_not_built_yet() {
assert!(print_init(Shell::Zsh).is_err());
}
#[test]
fn the_bash_snippet_is_ascii_and_starts_the_tab() {
assert!(BASH.is_ascii());
assert!(BASH.contains("kaeru shell start --pid \"$__kaeru_pid\""));
let with_codex = bash_snippet(&Config {
codex_no_daemon: true,
..Config::default()
});
assert!(with_codex.starts_with(BASH));
assert!(with_codex.contains("codex() {"));
assert!(with_codex.contains(" | exec | "));
assert!(!with_codex.contains("KAERU_ONE_OFF_COMMANDS"));
assert!(!bash_snippet(&Config::default()).contains("codex() {"));
}
fn test_bash() -> Option<std::path::PathBuf> {
let bash = if cfg!(windows) {
std::path::Path::new(&std::env::var_os("ProgramFiles")?).join(r"Git\bin\bash.exe")
} else {
std::path::PathBuf::from("/bin/bash")
};
bash.is_file().then_some(bash)
}
fn run_bash_snippet(bash: &Path, dir: &Path, script: &str) -> String {
run_bash_snippet_with(bash, dir, "", script)
}
fn run_bash_snippet_with(bash: &Path, dir: &Path, first: &str, script: &str) -> String {
let cwd_file = dir.join("tab.cwd");
let stand_in = dir.join("kaeru");
std::fs::write(
&stand_in,
format!(
"#!/bin/sh\n{first}\nprintf '%s\n' '{}'\n",
cwd_file.display()
),
)
.unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&stand_in, std::fs::Permissions::from_mode(0o755)).unwrap();
}
let snippet_file = dir.join("snippet.sh");
std::fs::write(&snippet_file, BASH).unwrap();
let output = std::process::Command::new(bash)
.args(["--norc", "--noprofile", "-i", "-c"])
.arg(format!("cd \"$1\" && PATH=\"$PWD:$PATH\" && {script}"))
.arg("bash")
.arg(dir)
.output()
.unwrap();
String::from_utf8_lossy(&output.stdout).trim().to_string()
}
#[test]
fn a_bash_run_file_goes_to_the_folder_and_runs_the_command() {
let script = bash_run_script(
r"C:\Users\demo\code\it's here",
&["claude".into(), "--resume".into(), "a b".into()],
);
assert!(
script.ends_with(
"cd -- 'C:\\Users\\demo\\code\\it'\\''s here' && claude --resume 'a b'\n"
)
);
assert!(script.contains(". /etc/profile"));
assert!(script.is_ascii());
}
#[test]
fn a_bash_tab_that_reads_kaeru_s_file_runs_a_command() {
assert!(runs_a_command(
r#""C:\Program Files\Git\usr\bin\bash.exe" --rcfile C:/state/run/kaeru-run-1.sh -i"#
));
assert!(runs_a_command("bash -c ls"));
assert!(!runs_a_command("bash -i -l"));
assert!(!runs_a_command("bash --login -i"));
}
#[test]
fn the_bash_run_file_runs_in_bash() {
let Some(bash) = test_bash() else { return };
let dir = tempfile::tempdir().unwrap();
let folder = dir.path().join("it's a folder");
std::fs::create_dir(&folder).unwrap();
let file = write_bash_run_file(
dir.path(),
&folder.display().to_string(),
&["echo".into(), "resumed".into()],
)
.unwrap();
let output = std::process::Command::new(bash)
.env("HOME", dir.path())
.args(["-c", ". \"$1\"; pwd", "bash"])
.arg(file.display().to_string().replace('\\', "/"))
.output()
.unwrap();
let printed = String::from_utf8_lossy(&output.stdout);
let mut lines = printed.lines();
assert_eq!(lines.next(), Some("resumed"), "{output:?}");
assert!(
lines
.next()
.is_some_and(|pwd| pwd.ends_with("it's a folder"))
);
}
#[test]
fn the_bash_prompt_theme_still_sees_whether_the_last_command_failed() {
let Some(bash) = test_bash() else { return };
let dir = tempfile::tempdir().unwrap();
let theme = "PROMPT_COMMAND='echo \"theme sees $?\"'";
let shown = |command: &str| {
let script = format!("{theme}; . ./snippet.sh; {command}; eval \"$PROMPT_COMMAND\"");
run_bash_snippet(&bash, dir.path(), &script)
};
assert_eq!(shown("false"), "theme sees 1");
assert_eq!(shown("true"), "theme sees 0");
}
#[test]
fn the_bash_prompt_writes_the_folder_and_loads_once() {
let Some(bash) = test_bash() else { return };
let dir = tempfile::tempdir().unwrap();
let shown = run_bash_snippet(
&bash,
dir.path(),
". ./snippet.sh; . ./snippet.sh; eval \"$PROMPT_COMMAND\"; echo \"$PROMPT_COMMAND\"",
);
assert_eq!(shown, "__kaeru_prompt", "one prompt function, once");
let written = std::fs::read_to_string(dir.path().join("tab.cwd")).unwrap();
let written = PathBuf::from(written.trim().replace('/', std::path::MAIN_SEPARATOR_STR));
assert_eq!(
written.canonicalize().unwrap(),
dir.path().canonicalize().unwrap()
);
}
#[test]
fn the_bash_function_runs_the_code_that_kaeru_resume_prints() {
let Some(bash) = test_bash() else { return };
let dir = tempfile::tempdir().unwrap();
std::fs::create_dir(dir.path().join("it's here")).unwrap();
let answer = format!(
"if [ \"$*\" = 'resume --shell bash' ]; then\n\
echo 'Resuming the session' >&2\n\
printf '%s\\n' {}\n\
exit 0\nfi",
bash_word(&bash_run_line("it's here", &["pwd".into()]))
);
let shown = run_bash_snippet_with(
&bash,
dir.path(),
&answer,
". ./snippet.sh; kaeru resume; kaeru list",
);
let mut lines = shown.lines();
assert!(
lines.next().is_some_and(|pwd| pwd.ends_with("/it's here")),
"{shown}"
);
assert!(lines.next().is_some_and(|line| line.ends_with("tab.cwd")));
}
#[test]
fn the_codex_function_comes_only_with_its_option() {
let plain = powershell_snippet(&Config::default());
assert!(!plain.contains("function global:codex"));
let with_codex = powershell_snippet(&Config {
codex_no_daemon: true,
..Config::default()
});
assert!(with_codex.starts_with(POWERSHELL));
assert!(with_codex.contains("function global:codex"));
assert!(with_codex.contains("'exec', "));
assert!(!with_codex.contains("KAERU_ONE_OFF_COMMANDS"));
assert!(with_codex.is_ascii());
}
#[cfg(windows)]
fn run_codex_function(calls: &str) -> String {
let dir = tempfile::tempdir().unwrap();
std::fs::write(
dir.path().join("codex.ps1"),
"foreach ($line in $input) { \"in:$line\" }\r\n\
foreach ($argument in $args) { \"arg:$argument\" }\r\n",
)
.unwrap();
std::fs::write(
dir.path().join("codex.cmd"),
"@echo off\r\n\
for /f \"delims=\" %%l in ('findstr \"^\"') do echo in:%%l\r\n\
:next\r\nif \"%~1\"==\"\" goto :eof\r\necho arg:%~1\r\nshift\r\ngoto next\r\n",
)
.unwrap();
let function = powershell_snippet(&Config {
codex_no_daemon: true,
..Config::default()
});
let function = &function[POWERSHELL.len()..];
let script = format!(
"$env:PATH = '{};' + $env:SystemRoot + '\\System32'\n\
$global:__kaeru_cwd_file = 'tracked'\n{function}\n{calls}",
dir.path().display()
);
let powershell = std::path::Path::new(&std::env::var("SystemRoot").unwrap())
.join(r"System32\WindowsPowerShell\v1.0\powershell.exe");
let output = std::process::Command::new(powershell)
.args([
"-NoProfile",
"-NonInteractive",
"-ExecutionPolicy",
"Bypass",
])
.args(["-Command", &script])
.output()
.unwrap();
assert!(output.status.success(), "{output:?}");
String::from_utf8_lossy(&output.stdout).replace("\r\n", "\n")
}
#[cfg(windows)]
fn prompt_after(commands: &str) -> String {
run_powershell_snippet("", &format!("{commands}\nprompt"))
}
#[cfg(windows)]
fn run_powershell_snippet(first: &str, commands: &str) -> String {
let dir = tempfile::tempdir().unwrap();
let cwd_file = dir.path().join("tab.cwd");
std::fs::write(
dir.path().join("kaeru.cmd"),
format!("@echo off\r\n{first}\r\necho {}\r\n", cwd_file.display()),
)
.unwrap();
let snippet = POWERSHELL.replace(
"$Host.Name -eq 'ConsoleHost' -and -not [Console]::IsInputRedirected -and",
"$true -and",
);
let script = format!(
"$env:PATH = '{};' + $env:SystemRoot + '\\System32'\n\
function global:prompt {{ \"theme sees $?\" }}\n{snippet}\n{commands}",
dir.path().display()
);
let powershell = std::path::Path::new(&std::env::var("SystemRoot").unwrap())
.join(r"System32\WindowsPowerShell\v1.0\powershell.exe");
let output = std::process::Command::new(powershell)
.args([
"-NoProfile",
"-NonInteractive",
"-ExecutionPolicy",
"Bypass",
])
.args(["-Command", &script])
.output()
.unwrap();
String::from_utf8_lossy(&output.stdout).trim().to_string()
}
#[cfg(windows)]
#[test]
fn the_powershell_function_runs_the_code_that_kaeru_resume_prints() {
let dir = tempfile::tempdir().unwrap();
let folder = dir.path().join("it's here");
std::fs::create_dir(&folder).unwrap();
let code = powershell_run_lines(
&folder.display().to_string(),
&["Convert-Path".into(), ".".into()],
);
let echoes: Vec<String> = code
.lines()
.map(|line| format!("echo {}", line.replace('&', "^&")))
.collect();
let answer = format!(
"if not \"%~1 %~2 %~3\"==\"resume --shell powershell\" goto other\r\n\
echo Resuming the session 1>&2\r\n{}\r\nexit /b 0\r\n:other",
echoes.join("\r\n")
);
let shown = run_powershell_snippet(&answer, "kaeru resume\nkaeru list");
let mut lines = shown.lines();
let end = format!(
r"{}\it's here",
dir.path().file_name().unwrap().to_string_lossy()
);
assert!(
lines.next().is_some_and(|line| line.trim().ends_with(&end)),
"{shown}"
);
assert!(
lines
.next()
.is_some_and(|line| line.trim().ends_with("tab.cwd"))
);
}
#[cfg(windows)]
#[test]
fn the_prompt_theme_still_sees_whether_the_last_command_failed() {
assert_eq!(
prompt_after("Get-Item 'C:\\no-such-folder' -ErrorAction SilentlyContinue"),
"theme sees False"
);
assert_eq!(
prompt_after("Get-Item 'C:\\' | Out-Null"),
"theme sees True"
);
}
#[cfg(windows)]
#[test]
fn the_codex_function_adds_no_daemon_only_for_the_interactive_screen() {
let printed = run_codex_function(
"'1'; codex\n\
'2'; codex resume --last\n\
'3'; codex exec 'fix the tests'\n\
'4'; codex --no-daemon\n\
'5'; codex --remote ws://localhost:1\n\
'6'; 'fix the tests' | codex exec -",
);
assert_eq!(
printed.trim_end(),
"1\narg:--no-daemon\n\
2\narg:--no-daemon\narg:resume\narg:--last\n\
3\narg:exec\narg:fix the tests\n\
4\narg:--no-daemon\n\
5\narg:--remote\narg:ws://localhost:1\n\
6\nin:fix the tests\narg:exec\narg:-"
);
}
#[test]
fn a_shell_started_to_run_something_is_recognized() {
assert!(runs_a_command(
"powershell.exe -NoExit -EncodedCommand AAAA"
));
assert!(runs_a_command("powershell -ec AAAA"));
assert!(runs_a_command("pwsh -c Get-Date"));
assert!(runs_a_command("powershell -File script.ps1"));
assert!(!runs_a_command("powershell.exe"));
assert!(!runs_a_command("powershell.exe -NoLogo -NoExit"));
assert!(!runs_a_command("pwsh -ExecutionPolicy Bypass"));
}
fn store_with_a_waiting_tab() -> (tempfile::TempDir, Store) {
use crate::engine::note::{ProcessRef, TerminalRef};
use crate::engine::rules::TerminalShape;
let dir = tempfile::tempdir().unwrap();
let store = Store::at(dir.path().to_path_buf()).unwrap();
let note = Note::Shell(ShellNote {
process: ProcessRef {
pid: 20,
started_ms: 2_000,
},
shell: "powershell".into(),
cwd: r"C:\Users\demo\code\web-ui".into(),
terminal: Some(TerminalRef {
adapter: "windows-terminal".into(),
process: ProcessRef {
pid: 10,
started_ms: 1_000,
},
shape: TerminalShape::Tabs,
tab_id: None,
profile: None,
exe: None,
}),
session: "win-1".into(),
offered: false,
});
store.save(¬e).unwrap();
(dir, store)
}
fn review_with_nothing_running(store: &Store) -> Vec<Reviewed> {
let table = FakeTable::new(&[]);
store::review(
store,
&table,
"win-1",
Config::default().single_window_close,
)
}
fn warp_tab(tab_id: &str, warp_started_ms: u64) -> crate::engine::note::TerminalRef {
use crate::engine::note::{ProcessRef, TerminalRef};
use crate::engine::rules::TerminalShape;
TerminalRef {
adapter: "warp".into(),
process: ProcessRef {
pid: 10,
started_ms: warp_started_ms,
},
shape: TerminalShape::Tabs,
tab_id: Some(tab_id.into()),
profile: None,
exe: None,
}
}
fn save_warp_tab(store: &Store, pid: u32, tab_id: &str, agent: bool) {
use crate::engine::note::{AgentNote, ProcessRef};
let shell = ProcessRef {
pid,
started_ms: 2_000,
};
store
.save(&Note::Shell(ShellNote {
process: shell,
shell: "powershell".into(),
cwd: r"C:\Users\demo\code\api-server".into(),
terminal: Some(warp_tab(tab_id, 1_000)),
session: "win-1".into(),
offered: false,
}))
.unwrap();
if agent {
store
.save(&Note::Agent(AgentNote {
process: ProcessRef {
pid: pid + 1,
started_ms: 3_000,
},
agent: "claude".into(),
conversation: "00000000-0000-4000-8000-000000000001".into(),
cwd: r"C:\Users\demo\code\api-server".into(),
shell: Some(shell),
shell_name: Some("powershell".into()),
shell_exe: None,
terminal: Some(warp_tab(tab_id, 1_000)),
transcript: None,
session: "win-1".into(),
offered: false,
}))
.unwrap();
}
}
fn restored_tab(tab_id: &str, warp_started_ms: u64) -> Note {
use crate::engine::note::ProcessRef;
Note::Shell(ShellNote {
process: ProcessRef {
pid: 90,
started_ms: warp_started_ms + 500,
},
shell: "powershell".into(),
cwd: r"C:\Users\demo\code\api-server".into(),
terminal: Some(warp_tab(tab_id, warp_started_ms)),
session: "win-1".into(),
offered: false,
})
}
#[test]
fn a_tab_that_warp_restored_takes_over_its_notes() {
let dir = tempfile::tempdir().unwrap();
let store = Store::at(dir.path().to_path_buf()).unwrap();
save_warp_tab(&store, 20, "tab-a", true);
save_warp_tab(&store, 30, "tab-b", false);
let reviewed = review_with_nothing_running(&store);
let now = 50_000;
assert_eq!(
claim(
&store,
&reviewed,
&restored_tab("tab-a", 40_000),
now,
&FakeTable::new(&[])
),
Some(ToResume {
agent: "Claude Code".into(),
orphan: false
})
);
let left: Vec<String> = store
.notes()
.iter()
.map(|stored| {
stored
.path
.file_name()
.unwrap()
.to_string_lossy()
.into_owned()
})
.collect();
assert!(left.iter().any(|name| name.starts_with("agent-21-")));
assert!(!left.iter().any(|name| name.starts_with("shell-20-")));
assert!(left.iter().any(|name| name.starts_with("shell-30-")));
let reviewed = review_with_nothing_running(&store);
assert!(
claim(
&store,
&reviewed,
&restored_tab("tab-c", 40_000),
40_000 + RESTORE_WAIT_MS + 1,
&FakeTable::new(&[])
)
.is_none()
);
assert!(store.notes().is_empty());
}
#[test]
fn a_session_that_outlived_its_crashed_warp_can_be_resumed() {
let dir = tempfile::tempdir().unwrap();
let store = Store::at(dir.path().to_path_buf()).unwrap();
save_warp_tab(&store, 20, "tab-a", true);
let table = FakeTable::new(&[
(21, Some(20), "claude.exe", Some(3_000)),
(20, None, "powershell.exe", Some(2_000)),
]);
let reviewed = store::review(
&store,
&table,
"win-1",
Config::default().single_window_close,
);
assert_eq!(
claim(
&store,
&reviewed,
&restored_tab("tab-a", 40_000),
50_000,
&table
),
Some(ToResume {
agent: "Claude Code".into(),
orphan: true
})
);
assert_eq!(store.notes().len(), 1);
}
#[test]
fn warp_s_waiting_tabs_are_left_out_of_the_picker() {
let dir = tempfile::tempdir().unwrap();
let store = Store::at(dir.path().to_path_buf()).unwrap();
save_warp_tab(&store, 20, "tab-a", true);
let reviewed = review_with_nothing_running(&store);
assert!(!offer(&store, &reviewed, &Config::default(), false).unwrap());
assert_eq!(store.notes().len(), 2, "the notes wait for Warp's tab");
}
#[test]
fn only_the_first_new_tab_asks() {
let (_dir, store) = store_with_a_waiting_tab();
let config = Config::default();
let reviewed = review_with_nothing_running(&store);
assert!(offer(&store, &reviewed, &config, false).unwrap());
let reviewed = review_with_nothing_running(&store);
assert!(!offer(&store, &reviewed, &config, false).unwrap());
assert_eq!(store.notes().len(), 1, "the tab still waits");
}
#[test]
fn a_new_tab_waits_quietly_while_another_tab_holds_the_list() {
let (_dir, store) = store_with_a_waiting_tab();
let held = store.try_lock().unwrap().unwrap();
let reviewed = review_with_nothing_running(&store);
assert!(!offer(&store, &reviewed, &Config::default(), false).unwrap());
assert!(!store.notes()[0].note.offered(), "it asks later, not now");
drop(held);
let reviewed = review_with_nothing_running(&store);
assert!(offer(&store, &reviewed, &Config::default(), false).unwrap());
}
#[test]
fn a_reopened_agent_tab_never_asks() {
let (_dir, store) = store_with_a_waiting_tab();
let reviewed = review_with_nothing_running(&store);
assert!(!offer(&store, &reviewed, &Config::default(), true).unwrap());
assert!(!store.notes()[0].note.offered());
}
#[test]
fn tabs_that_the_options_leave_out_are_forgotten() {
let (_dir, store) = store_with_a_waiting_tab();
let config = Config {
offer_shells: false,
..Config::default()
};
let reviewed = review_with_nothing_running(&store);
assert!(!offer(&store, &reviewed, &config, false).unwrap());
assert!(store.notes().is_empty());
}
}