use std::path::{Path, PathBuf};
#[cfg(any(windows, test))]
use std::process::Command;
use super::goose::goose_env;
use super::sandbox;
use super::{accepts_prompt, env_dir, exec_with_env, find_on_path, find_on_path_unless, server};
pub(super) const TRANSCRIPTION_MODEL_ENV: &str = "OPENAI_TRANSCRIPTION_MODEL";
pub(super) fn goose_desktop_env<'a>(
model: &'a str,
api_key: &'a str,
host: &'a str,
speech_model: Option<&'a str>,
) -> Vec<(&'a str, &'a str)> {
if !model.is_empty() {
return goose_env(model, api_key, host);
}
let mut env = vec![("OPENAI_API_KEY", api_key), ("OPENAI_HOST", host)];
env.extend(speech_model.map(|m| (TRANSCRIPTION_MODEL_ENV, m)));
env
}
pub(super) fn launch_goose_desktop(
model: &str,
api_key: &str,
extra_args: &[String],
) -> anyhow::Result<()> {
let bin = find_goose_desktop().ok_or_else(goose_desktop_missing)?;
if !cfg!(target_os = "macos") && !sandbox::active() {
match dirs::home_dir() {
Some(home) => {
let config = env_dir("XDG_CONFIG_HOME").unwrap_or_else(|| home.join(".config"));
match goose_desktop_instance(&bin, &home, &config) {
GooseInstance::Confirmed(pid) => {
offer_to_quit_goose_desktop(pid, &bin, &home, &config)?
}
GooseInstance::Held => anyhow::bail!(goose_desktop_lock_held(
&goose_desktop_user_data(&home, &config)
)),
GooseInstance::Unknown => eprintln!("{}", goose_desktop_unknown_warning()),
GooseInstance::Free => {}
}
}
None => eprintln!("{}", goose_desktop_unknown_warning()),
}
}
let host = server();
let speech = std::env::var(TRANSCRIPTION_MODEL_ENV).ok();
let speech = speech.as_deref().filter(|_| sandbox::active());
exec_with_env(
&bin,
extra_args,
&goose_desktop_env(model, api_key, &host, speech),
)
}
#[derive(Debug, PartialEq, Eq)]
enum GooseInstance {
Confirmed(u32),
Held,
Unknown,
Free,
}
pub(super) fn goose_desktop_user_data(home: &Path, config: &Path) -> PathBuf {
if cfg!(target_os = "macos") {
home.join("Library")
.join("Application Support")
.join("Goose")
} else if cfg!(windows) {
env_dir("APPDATA")
.unwrap_or_else(|| home.join("AppData").join("Roaming"))
.join("Goose")
} else {
config.join("Goose")
}
}
#[cfg(not(windows))]
fn single_instance_lock_holder(user_data: &Path, bin: &Path) -> GooseInstance {
let target = match std::fs::read_link(user_data.join("SingletonLock")) {
Ok(target) => target,
Err(e)
if matches!(
e.kind(),
std::io::ErrorKind::NotFound | std::io::ErrorKind::InvalidInput
) =>
{
return GooseInstance::Free;
}
Err(_) => return GooseInstance::Unknown,
};
let Some(pid) = target
.to_str()
.and_then(|t| t.rsplit_once('-'))
.and_then(|(_, pid)| pid.parse::<u32>().ok())
else {
return GooseInstance::Free;
};
let Ok(signed) = i32::try_from(pid) else {
return GooseInstance::Free;
};
if !pid_alive(signed) {
return GooseInstance::Free;
}
if process_is(signed, bin) {
GooseInstance::Confirmed(pid)
} else {
GooseInstance::Held
}
}
#[cfg(not(windows))]
fn pid_alive(pid: i32) -> bool {
if pid <= 0 {
return false;
}
if unsafe { libc::kill(pid, 0) } == 0 {
return true;
}
std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
}
#[cfg(not(windows))]
fn process_is(pid: i32, bin: &Path) -> bool {
if pid <= 0 {
return false;
}
let Ok(exe) = std::fs::read_link(format!("/proc/{pid}/exe")) else {
return false;
};
let canonical = |p: &Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
canonical(&exe) == canonical(bin)
}
#[cfg(windows)]
fn goose_desktop_instance(bin: &Path, _home: &Path, _config: &Path) -> GooseInstance {
goose_desktop_running_windows(bin)
}
#[cfg(not(windows))]
fn goose_desktop_instance(bin: &Path, home: &Path, config: &Path) -> GooseInstance {
if cfg!(target_os = "macos") {
return GooseInstance::Free;
}
single_instance_lock_holder(&goose_desktop_user_data(home, config), bin)
}
#[cfg(windows)]
fn goose_desktop_running_windows(bin: &Path) -> GooseInstance {
let out = Command::new("powershell")
.args([
"-NoProfile",
"-Command",
"Get-CimInstance Win32_Process -Filter \"Name='Goose.exe'\" | \
ForEach-Object { \"$($_.ProcessId)|$($_.ExecutablePath)|$($_.CommandLine)\" }",
])
.stderr(std::process::Stdio::null())
.output()
.ok()
.filter(|o| o.status.success());
match out {
Some(out) => goose_exe_pid(
&String::from_utf8_lossy(&out.stdout),
bin,
is_electron_bundle,
),
None => GooseInstance::Unknown,
}
}
#[cfg(any(windows, test))]
fn goose_exe_pid(listing: &str, bin: &Path, is_bundle: impl Fn(&Path) -> bool) -> GooseInstance {
let mut held = false;
let mut unreadable = false;
for line in listing.lines() {
let mut fields = line.trim().splitn(3, '|');
let Some(pid) = fields.next() else { continue };
let Some(path) = fields.next() else { continue };
let command = fields.next().unwrap_or_default();
if path.trim().is_empty() {
unreadable = true;
continue;
}
if !is_bundle(Path::new(path.trim())) {
continue;
}
held = true;
if command.contains("--type=") || !same_windows_path(path, bin) {
continue;
}
if let Ok(pid) = pid.trim().parse() {
return GooseInstance::Confirmed(pid);
}
}
if held {
GooseInstance::Held
} else if unreadable {
GooseInstance::Unknown
} else {
GooseInstance::Free
}
}
#[cfg(any(windows, test))]
fn same_windows_path(a: &str, b: &Path) -> bool {
let normalize = |s: &str| s.trim().replace('/', "\\").to_ascii_lowercase();
let a = normalize(a);
!a.is_empty() && a == normalize(&b.to_string_lossy())
}
fn quit_goose_desktop(pid: u32) {
#[cfg(unix)]
if let Ok(pid) = i32::try_from(pid) {
unsafe { libc::kill(pid, libc::SIGTERM) };
}
#[cfg(windows)]
{
let _ = Command::new("taskkill")
.args(["/PID", &pid.to_string(), "/T"])
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status();
}
#[cfg(not(any(unix, windows)))]
{
let _ = pid;
}
}
fn wait_for_goose_desktop_to_quit(bin: &Path, home: &Path, config: &Path) -> bool {
let deadline = std::time::Instant::now() + QUIT_TIMEOUT;
loop {
if goose_desktop_instance(bin, home, config) == GooseInstance::Free {
return true;
}
if std::time::Instant::now() >= deadline {
return false;
}
std::thread::sleep(std::time::Duration::from_millis(100));
}
}
const QUIT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
fn goose_desktop_refusal(pid: u32) -> String {
format!(
"Goose Desktop is already running (pid {pid}), and holds the lock that \
makes a second launch hand over to it — with the provider and model it \
already had, not llmman's.\n\
Quit it and run this again."
)
}
fn goose_desktop_lock_held(user_data: &Path) -> String {
let mut message = "Something is already holding Goose Desktop's single-instance lock, so \
this launch would be handed to it and keep that instance's provider \
and model, not llmman's.\n\
Quit Goose Desktop and run this again."
.to_string();
if !cfg!(windows) {
message.push_str(&format!(
" If it is not running, the lock is stale and can be removed:\n {}",
user_data.join("SingletonLock").display()
));
}
message
}
fn goose_desktop_unknown_warning() -> String {
"[llmman] could not determine whether Goose Desktop is already running. \
If it is, this launch is handed to it and keeps that instance's provider \
and model instead of the ones llmman resolved."
.to_string()
}
#[derive(Debug, PartialEq, Eq)]
enum QuitDecision {
Signal,
AlreadyGone,
Changed,
}
fn quit_decision(probe: &GooseInstance, approved: u32) -> QuitDecision {
match probe {
GooseInstance::Confirmed(pid) if *pid == approved => QuitDecision::Signal,
GooseInstance::Free => QuitDecision::AlreadyGone,
_ => QuitDecision::Changed,
}
}
fn offer_to_quit_goose_desktop(
pid: u32,
bin: &Path,
home: &Path,
config: &Path,
) -> anyhow::Result<()> {
use std::io::{BufRead, IsTerminal, Write};
let refusal = goose_desktop_refusal(pid);
anyhow::ensure!(
std::io::stdin().is_terminal() && std::io::stderr().is_terminal(),
"{refusal}"
);
eprint!("Goose Desktop is already running (pid {pid}) and would take this launch with its own provider and model. Quit it? [y/N] ");
std::io::stderr().flush()?;
let mut answer = String::new();
std::io::stdin().lock().read_line(&mut answer)?;
anyhow::ensure!(accepts_prompt(&answer), "{refusal}");
match quit_decision(&goose_desktop_instance(bin, home, config), pid) {
QuitDecision::Signal => {
eprintln!("[llmman] asking Goose Desktop to quit...");
quit_goose_desktop(pid);
}
QuitDecision::AlreadyGone => {
eprintln!("[llmman] Goose Desktop already quit; nothing to signal.");
return Ok(());
}
QuitDecision::Changed => anyhow::bail!(
"Goose Desktop (pid {pid}) is no longer the instance llmman \
confirmed, so nothing was signalled. Run this again."
),
}
anyhow::ensure!(
wait_for_goose_desktop_to_quit(bin, home, config),
"Goose Desktop (pid {pid}) did not quit, so this launch would still go \
to it. Quit it and run this again."
);
Ok(())
}
pub(super) fn find_goose_desktop() -> Option<PathBuf> {
find_on_path("goose-desktop")
.or_else(|| find_on_path("goose-gui"))
.or_else(goose_exe_on_path)
.or_else(|| goose_desktop_fallback(&dirs::home_dir()?))
}
pub(super) fn goose_desktop_missing() -> anyhow::Error {
anyhow::anyhow!(
"goose-desktop is not installed\n\
Install Goose Desktop from https://github.com/aaif-goose/goose, \
or run 'llmman launch goose' for the CLI."
)
}
fn goose_exe_on_path() -> Option<PathBuf> {
if !cfg!(windows) {
return None;
}
find_on_path_unless("Goose", |exe| !is_electron_bundle(exe))
}
pub(super) fn is_electron_bundle(exe: &Path) -> bool {
let resolved = std::fs::canonicalize(exe);
let Some(dir) = resolved.as_deref().unwrap_or(exe).parent() else {
return false;
};
if dir.join("resources").join("app.asar").is_file() {
return true;
}
dir.file_name() == Some(std::ffi::OsStr::new("MacOS"))
&& dir
.parent()
.is_some_and(|contents| contents.join("Resources").join("app.asar").is_file())
}
fn goose_desktop_fallback(home: &Path) -> Option<PathBuf> {
let mut candidates = Vec::new();
if cfg!(target_os = "macos") {
for root in [PathBuf::from("/Applications"), home.join("Applications")] {
candidates.push(
root.join("Goose.app")
.join("Contents")
.join("MacOS")
.join("Goose"),
);
}
}
if !cfg!(windows) {
for name in ["goose-desktop", "goose-gui"] {
candidates.push(home.join(".local").join("bin").join(name));
}
}
if cfg!(target_os = "linux") {
candidates.push(PathBuf::from("/usr/lib/goose/Goose"));
candidates.push(PathBuf::from("/usr/lib/Goose/Goose"));
}
candidates.into_iter().find(|p| p.is_file())
}
#[cfg(test)]
mod tests {
use super::super::goose::goose_fallback;
use super::*;
#[test]
fn goose_desktop_shares_the_cli_environment() {
let host = "http://127.0.0.1:17434";
let env = goose_env("m", "k", host);
let get = |k| env.iter().find(|(n, _)| *n == k).map(|(_, v)| *v);
assert_eq!(get("GOOSE_PROVIDER"), Some("openai"));
assert_eq!(get("GOOSE_MODEL"), Some("m"));
assert_eq!(get("OPENAI_API_KEY"), Some("k"));
assert_eq!(get("OPENAI_HOST"), Some(host));
assert_eq!(get("OPENAI_BASE_PATH"), Some("v1/chat/completions"));
}
#[test]
fn goose_desktop_env_with_and_without_a_model() {
let host = "http://127.0.0.1:17434";
for speech in [None, Some("speech")] {
assert_eq!(
goose_desktop_env("m", "k", host, speech),
goose_env("m", "k", host)
);
}
assert_eq!(
goose_desktop_env("", "k", host, None),
[("OPENAI_API_KEY", "k"), ("OPENAI_HOST", host)]
);
assert_eq!(
goose_desktop_env("", "k", host, Some("speech"))[2],
("OPENAI_TRANSCRIPTION_MODEL", "speech")
);
}
#[test]
fn only_an_electron_bundle_counts_as_the_desktop_app() {
let dir = std::env::temp_dir().join(format!(
"llmman-goose-bundle-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
std::fs::create_dir_all(&dir).unwrap();
let exe = dir.join("Goose.exe");
std::fs::write(&exe, "").unwrap();
assert!(!is_electron_bundle(&exe));
let resources = dir.join("resources");
std::fs::create_dir(&resources).unwrap();
assert!(!is_electron_bundle(&exe));
std::fs::write(resources.join("app.asar"), "").unwrap();
assert!(is_electron_bundle(&exe));
#[cfg(unix)]
{
let link_dir = dir.join("bin");
std::fs::create_dir(&link_dir).unwrap();
let link = link_dir.join("goose");
std::os::unix::fs::symlink(&exe, &link).unwrap();
assert!(is_electron_bundle(&link));
let target = link_dir.join("target");
let plain = link_dir.join("plain");
std::fs::write(&target, "").unwrap();
std::os::unix::fs::symlink(&target, &plain).unwrap();
assert!(!is_electron_bundle(&plain));
}
let macos = dir.join("Goose.app").join("Contents").join("MacOS");
std::fs::create_dir_all(&macos).unwrap();
let app = macos.join("Goose");
std::fs::write(&app, "").unwrap();
assert!(!is_electron_bundle(&app));
let res = dir.join("Goose.app").join("Contents").join("Resources");
std::fs::create_dir(&res).unwrap();
std::fs::write(res.join("app.asar"), "").unwrap();
assert!(is_electron_bundle(&app));
let fallback_home = dir.join("home");
let unpacked = if cfg!(windows) {
fallback_home.join("goose")
} else {
fallback_home.join(".local").join("bin")
};
std::fs::create_dir_all(unpacked.join("resources")).unwrap();
let bin = unpacked.join(if cfg!(windows) { "goose.exe" } else { "goose" });
std::fs::write(&bin, "").unwrap();
assert_eq!(goose_fallback(&fallback_home), Some(bin));
std::fs::write(unpacked.join("resources").join("app.asar"), "").unwrap();
assert_eq!(goose_fallback(&fallback_home), None);
if !cfg!(windows) {
assert_eq!(goose_exe_on_path(), None);
}
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn the_refusal_names_the_instance_and_what_to_do() {
let refusal = goose_desktop_refusal(4242);
assert!(refusal.contains("4242"), "{refusal}");
assert!(refusal.contains("Quit it and run this again"), "{refusal}");
assert!(refusal.contains("not llmman's"), "{refusal}");
}
#[test]
fn only_the_same_confirmed_instance_is_signalled_after_the_prompt() {
use GooseInstance::{Confirmed, Free, Held, Unknown};
assert_eq!(quit_decision(&Confirmed(4242), 4242), QuitDecision::Signal);
assert_eq!(quit_decision(&Confirmed(99), 4242), QuitDecision::Changed);
assert_eq!(quit_decision(&Free, 4242), QuitDecision::AlreadyGone);
assert_eq!(quit_decision(&Held, 4242), QuitDecision::Changed);
assert_eq!(quit_decision(&Unknown, 4242), QuitDecision::Changed);
}
#[test]
fn the_held_refusal_names_the_lock_to_remove() {
let user_data = Path::new("/home/me/.config/Goose");
let held = goose_desktop_lock_held(user_data);
assert!(held.contains("not llmman's"), "{held}");
assert!(held.contains("Quit Goose Desktop"), "{held}");
assert!(!held.contains("pid"), "{held}");
if cfg!(windows) {
assert!(!held.contains("SingletonLock"), "{held}");
assert!(!held.contains("stale"), "{held}");
} else {
assert!(
held.contains("/home/me/.config/Goose/SingletonLock"),
"{held}"
);
}
}
#[test]
fn the_unknown_warning_says_what_it_could_not_determine() {
let warning = goose_desktop_unknown_warning();
assert!(warning.starts_with("[llmman]"), "{warning}");
assert!(warning.contains("could not determine"), "{warning}");
assert!(warning.contains("provider"), "{warning}");
}
#[test]
#[cfg(unix)]
fn goose_desktop_instance_reads_the_lock_only_where_it_is_taken() {
let home = std::env::temp_dir().join(format!(
"llmman-goose-instance-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
let config = home.join(".config");
let user_data = goose_desktop_user_data(&home, &config);
std::fs::create_dir_all(&user_data).unwrap();
let bin = Path::new("/nonexistent/Goose");
assert_eq!(
goose_desktop_instance(bin, &home, &config),
GooseInstance::Free
);
let me = std::process::id();
std::os::unix::fs::symlink(format!("host-{me}"), user_data.join("SingletonLock")).unwrap();
let found = goose_desktop_instance(bin, &home, &config);
if cfg!(target_os = "macos") {
assert_eq!(found, GooseInstance::Free, "macOS never takes the lock");
} else {
assert_eq!(found, GooseInstance::Held);
}
let _ = std::fs::remove_dir_all(&home);
}
#[test]
fn goose_exe_pid_finds_the_main_process_only() {
use GooseInstance::{Confirmed, Free, Held, Unknown};
let bin = Path::new(r"C:\Users\me\Goose\Goose.exe");
let exe = r"C:\Users\me\Goose\Goose.exe";
let bundle = |_: &Path| true;
let listing = format!(
"1001|{exe}|\"{exe}\" --type=gpu-process --field-trial-handle=1\r\n\
1002|{exe}|\"{exe}\" --type=renderer --lang=en-GB\r\n\
1003|{exe}|\"{exe}\"\r\n"
);
assert_eq!(goose_exe_pid(&listing, bin, bundle), Confirmed(1003));
assert_eq!(
goose_exe_pid(
&format!("1002|{exe}|\"{exe}\" --type=renderer"),
bin,
bundle
),
Held
);
assert_eq!(
goose_exe_pid("9|c:/users/me/goose/GOOSE.EXE|x", bin, bundle),
Confirmed(9)
);
assert_eq!(
goose_exe_pid(&format!("9|{exe}|\"{exe}\" --logfile a|b"), bin, bundle),
Confirmed(9)
);
assert_eq!(goose_exe_pid("9||x", bin, bundle), Unknown);
assert_eq!(goose_exe_pid("9| |x", bin, bundle), Unknown);
assert_eq!(
goose_exe_pid("9|C:\\elsewhere\\Goose.exe|x", bin, bundle),
Held
);
assert_eq!(goose_exe_pid("", bin, bundle), Free);
assert_eq!(goose_exe_pid("nonsense", bin, bundle), Free);
let cli = r"C:\Users\me\.local\bin\goose.exe";
let not_a_bundle = |p: &Path| p != Path::new(cli);
assert_eq!(
goose_exe_pid(&format!("2001|{cli}|\"{cli}\" session"), bin, not_a_bundle),
Free
);
assert_eq!(
goose_exe_pid(
&format!("2001|{cli}|\"{cli}\" session\r\n1003|{exe}|\"{exe}\"\r\n"),
bin,
not_a_bundle
),
Confirmed(1003)
);
}
#[test]
#[cfg(not(windows))]
fn a_single_instance_lock_counts_only_for_the_app_that_holds_it() {
let user_data = std::env::temp_dir().join(format!(
"llmman-goose-lock-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
std::fs::create_dir_all(&user_data).unwrap();
let lock = user_data.join("SingletonLock");
let me = std::process::id() as i32;
let this_exe = std::env::current_exe().unwrap();
let elsewhere = Path::new("/nonexistent/Goose");
assert_eq!(
single_instance_lock_holder(&user_data, &this_exe),
GooseInstance::Free
);
std::os::unix::fs::symlink(format!("somehost-{me}"), &lock).unwrap();
assert_eq!(
single_instance_lock_holder(&user_data, elsewhere),
GooseInstance::Held
);
let confirmed = single_instance_lock_holder(&user_data, &this_exe);
if cfg!(target_os = "linux") {
assert_eq!(confirmed, GooseInstance::Confirmed(me as u32));
} else {
assert_eq!(confirmed, GooseInstance::Held);
}
for target in ["somehost-2147483646", "somehost-notapid", "nodash"] {
std::fs::remove_file(&lock).unwrap();
std::os::unix::fs::symlink(target, &lock).unwrap();
assert_eq!(
single_instance_lock_holder(&user_data, &this_exe),
GooseInstance::Free,
"{target}"
);
}
std::fs::remove_file(&lock).unwrap();
std::fs::write(&lock, "").unwrap();
assert_eq!(
single_instance_lock_holder(&user_data, &this_exe),
GooseInstance::Free
);
let _ = std::fs::remove_dir_all(&user_data);
}
#[test]
#[cfg(unix)]
fn an_unreadable_profile_is_unknown_rather_than_free() {
use std::os::unix::fs::PermissionsExt;
let user_data = std::env::temp_dir().join(format!(
"llmman-goose-perm-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
std::fs::create_dir_all(&user_data).unwrap();
let me = std::process::id();
std::os::unix::fs::symlink(format!("somehost-{me}"), user_data.join("SingletonLock"))
.unwrap();
std::fs::set_permissions(&user_data, std::fs::Permissions::from_mode(0o000)).unwrap();
let bin = std::env::current_exe().unwrap();
let found = single_instance_lock_holder(&user_data, &bin);
std::fs::set_permissions(&user_data, std::fs::Permissions::from_mode(0o755)).unwrap();
let _ = std::fs::remove_dir_all(&user_data);
if unsafe { libc::geteuid() } == 0 {
assert!(
matches!(found, GooseInstance::Confirmed(p) if p == me)
|| found == GooseInstance::Held,
"{found:?}"
);
} else {
assert_eq!(found, GooseInstance::Unknown);
}
}
#[test]
#[cfg(not(windows))]
fn pid_alive_sees_this_process_and_not_a_group_or_a_corpse() {
assert!(pid_alive(std::process::id() as i32));
assert!(!pid_alive(0));
assert!(!pid_alive(-1));
assert!(!pid_alive(-(std::process::id() as i32)));
let mut child = Command::new("true").spawn().expect("spawn true");
let pid = child.id() as i32;
child.wait().expect("wait");
assert!(!pid_alive(pid));
}
#[test]
fn goose_desktop_fallback_finds_the_installers_target() {
let installed = [
"/Applications/Goose.app/Contents/MacOS/Goose",
"/usr/lib/goose/Goose",
"/usr/lib/Goose/Goose",
]
.into_iter()
.map(Path::new)
.find(|p| p.is_file());
if let Some(installed) = installed {
assert_eq!(
goose_desktop_fallback(Path::new("/nonexistent")),
Some(installed.to_path_buf())
);
return;
}
if cfg!(windows) {
assert_eq!(goose_desktop_fallback(Path::new("/nonexistent")), None);
return;
}
let (parts, name): (&[&str], &str) = if cfg!(target_os = "macos") {
(&["Applications", "Goose.app", "Contents", "MacOS"], "Goose")
} else {
(&[".local", "bin"], "goose-desktop")
};
let home = std::env::temp_dir().join(format!(
"llmman-goose-desktop-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
let dir = parts.iter().fold(home.clone(), |p, part| p.join(part));
std::fs::create_dir_all(&dir).unwrap();
assert_eq!(goose_desktop_fallback(&home), None);
let bin = dir.join(name);
std::fs::create_dir(&bin).unwrap();
assert_eq!(goose_desktop_fallback(&home), None);
std::fs::remove_dir(&bin).unwrap();
std::fs::write(&bin, "").unwrap();
assert_eq!(goose_desktop_fallback(&home), Some(bin));
assert_eq!(goose_desktop_fallback(&home.join("nowhere")), None);
let _ = std::fs::remove_dir_all(&home);
}
}