use std::path::Path;
use anyhow::Result;
use super::{Env, Restores, TabToOpen, TerminalAdapter, applescript, launch};
use crate::engine::rules::TerminalShape;
use crate::procs::ProcInfo;
use crate::shells;
pub struct Ghostty;
impl TerminalAdapter for Ghostty {
fn id(&self) -> &'static str {
"ghostty"
}
fn name(&self) -> &'static str {
"Ghostty"
}
fn shape(&self) -> TerminalShape {
TerminalShape::Tabs
}
fn find(&self, env: &Env, lineage: &[ProcInfo]) -> Option<ProcInfo> {
if cfg!(any(target_os = "macos", target_os = "linux")) {
ghostty_of(env, lineage)
} else {
None
}
}
fn restores_its_own_tabs(&self) -> Restores {
if cfg!(target_os = "macos") {
Restores::Sometimes
} else {
Restores::Never
}
}
fn reopen(&self, exe: Option<&Path>, tabs: &[TabToOpen]) -> Result<()> {
for tab in tabs {
if cfg!(target_os = "macos") {
applescript::run(NEW_TAB, &new_tab_arguments(tab))?;
} else {
let program = exe.unwrap_or(Path::new("ghostty"));
launch::start(program, &new_window_arguments(tab))?;
}
}
Ok(())
}
}
fn ghostty_of(env: &Env, lineage: &[ProcInfo]) -> Option<ProcInfo> {
if env.get("TERM_PROGRAM").map(String::as_str) != Some("ghostty") {
return None;
}
let is_terminal = |process: &ProcInfo| process.name == "ghostty";
match lineage.get(1) {
Some(parent) if is_terminal(parent) => Some(parent.clone()),
Some(parent) if parent.name == "login" || parent.name == "sh" => lineage
.get(2)
.filter(|process| is_terminal(process))
.cloned(),
_ => None,
}
}
#[cfg(target_os = "macos")]
const TERMINAL_WITH_TITLE: &str = r#"on run argv
set wanted to item 1 of argv
with timeout of 5 seconds
tell application id "com.mitchellh.ghostty"
repeat 20 times
set found to {}
repeat with candidate in terminals
if name of candidate is wanted then
set end of found to (id of candidate as text)
end if
end repeat
if (count of found) > 0 then
set AppleScript's text item delimiters to linefeed
return found as text
end if
delay 0.02
end repeat
end tell
end timeout
return ""
end run"#;
#[cfg(target_os = "macos")]
const PROBE_LIMIT: std::time::Duration = std::time::Duration::from_secs(2);
#[cfg(target_os = "macos")]
pub fn probe_tab_id() -> Option<String> {
use std::io::Write;
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |since| since.subsec_nanos());
let token = format!("kaeru-{}-{nanos:x}", std::process::id());
let mut tty = std::fs::OpenOptions::new()
.write(true)
.open("/dev/tty")
.ok()?;
tty.write_all(title_sequence(&token).as_bytes()).ok()?;
tty.flush().ok()?;
let printed = applescript::output(TERMINAL_WITH_TITLE, &[token], PROBE_LIMIT);
let _ = tty.write_all(title_sequence("").as_bytes());
let _ = tty.flush();
the_one_id(&printed.ok()?)
}
#[cfg(not(target_os = "macos"))]
pub fn probe_tab_id() -> Option<String> {
None
}
#[cfg(any(target_os = "macos", test))]
fn title_sequence(title: &str) -> String {
format!("\x1b]2;{title}\x07")
}
#[cfg(any(target_os = "macos", test))]
fn the_one_id(printed: &str) -> Option<String> {
let ids: Vec<&str> = printed
.lines()
.map(str::trim)
.filter(|line| !line.is_empty())
.collect();
match ids.as_slice() {
[id] if crate::agents::is_uuid(id) => Some((*id).to_string()),
_ => None,
}
}
const NEW_TAB: &str = r#"on run argv
set startFolder to item 1 of argv
set typed to item 2 of argv
with timeout of 30 seconds
tell application id "com.mitchellh.ghostty"
set settings to new surface configuration
set initial working directory of settings to startFolder
if typed is not "" then
set initial input of settings to typed & return
end if
if (count of windows) is 0 then
new window with configuration settings
else
new tab in front window with configuration settings
end if
end tell
end timeout
end run"#;
fn new_tab_arguments(tab: &TabToOpen) -> Vec<String> {
let typed = if tab.run.is_empty() {
String::new()
} else {
shells::bash_run_line(&tab.cwd, &tab.run)
};
vec![tab.cwd.clone(), typed]
}
fn new_window_arguments(tab: &TabToOpen) -> Vec<String> {
let mut args = vec![format!("--working-directory={}", tab.cwd)];
let command = launch::command(tab);
if !command.is_empty() {
args.push("-e".into());
args.extend(command);
}
args
}
#[cfg(test)]
mod tests {
use super::*;
use crate::procs::{fake::FakeTable, lineage};
const ID: &str = "00000000-0000-4000-8000-000000000001";
fn tab_env() -> Env {
Env::from([("TERM_PROGRAM".to_string(), "ghostty".to_string())])
}
fn tab_table() -> FakeTable {
FakeTable::new(&[
(50, Some(40), "zsh", Some(500)),
(40, Some(30), "zsh", Some(400)),
(30, Some(20), "login", Some(300)),
(20, Some(1), "ghostty", Some(200)),
])
}
#[test]
fn the_ghostty_that_started_a_tab_s_login_is_the_terminal() {
let found = ghostty_of(&tab_env(), &lineage(&tab_table(), 40));
assert_eq!(found.map(|process| process.pid), Some(20));
let tracked = Ghostty
.find(&tab_env(), &lineage(&tab_table(), 40))
.is_some();
assert_eq!(tracked, cfg!(any(target_os = "macos", target_os = "linux")));
}
#[test]
fn on_linux_the_ghostty_that_started_a_tab_s_sh_is_the_terminal() {
let table = FakeTable::new(&[
(40, Some(30), "bash", Some(400)),
(30, Some(20), "sh", Some(300)),
(20, Some(1), "ghostty", Some(200)),
]);
let found = ghostty_of(&tab_env(), &lineage(&table, 40));
assert_eq!(found.map(|process| process.pid), Some(20));
}
#[test]
fn on_linux_a_tab_opens_as_a_window_with_its_agent_session() {
let folder = "/home/demo/code/web ui";
let mut agent = tab(folder, &["claude", "--resume", ID]);
agent.shell = Some("bash".into());
assert_eq!(
new_window_arguments(&agent),
[
format!("--working-directory={folder}"),
"-e".into(),
"env".into(),
format!("KAERU_RUN=cd -- '{folder}' && claude --resume {ID}"),
"bash".into(),
]
);
assert_eq!(
new_window_arguments(&tab(folder, &[])),
[format!("--working-directory={folder}")]
);
}
#[test]
fn a_shell_inside_a_tab_is_not_a_tab() {
assert!(ghostty_of(&tab_env(), &lineage(&tab_table(), 50)).is_none());
assert!(ghostty_of(&Env::new(), &lineage(&tab_table(), 40)).is_none());
}
#[test]
fn the_probe_takes_one_terminal_id() {
let id = "00000000-0000-4000-8000-00000000000B";
assert_eq!(the_one_id(&format!("{id}\n")).as_deref(), Some(id));
assert_eq!(the_one_id(""), None);
assert_eq!(the_one_id(&format!("{id}\n{id}\n")), None);
assert_eq!(the_one_id("tab-1\n"), None);
assert_eq!(title_sequence("kaeru-1-a"), "\x1b]2;kaeru-1-a\x07");
}
#[test]
fn ghostty_restores_its_own_tabs_only_on_macos() {
let expected = if cfg!(target_os = "macos") {
Restores::Sometimes
} else {
Restores::Never
};
assert_eq!(Ghostty.restores_its_own_tabs(), expected);
}
#[test]
fn ghostty_gives_kaeru_no_tab_id() {
let mut env = tab_env();
env.insert("TERM_SESSION_ID".into(), ID.into());
assert_eq!(Ghostty.tab_id(&env), None);
}
fn tab(cwd: &str, run: &[&str]) -> TabToOpen {
TabToOpen {
title: "web-ui".into(),
cwd: cwd.into(),
shell: Some("zsh".into()),
run: run.iter().map(|word| word.to_string()).collect(),
..TabToOpen::default()
}
}
#[test]
fn a_plain_tab_opens_in_its_folder_and_types_nothing() {
let folder = "/Users/demo/code/it's my 프로젝트";
assert_eq!(new_tab_arguments(&tab(folder, &[])), [folder, ""]);
}
#[test]
fn an_agent_tab_types_the_line_that_resumes_its_session() {
let folder = "/Users/demo/code/web ui";
assert_eq!(
new_tab_arguments(&tab(folder, &["claude", "--resume", ID])),
[
folder.to_string(),
format!("cd -- '/Users/demo/code/web ui' && claude --resume {ID}")
]
);
}
}