Skip to content

Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.

fix(host): keep the Linux service and agent start reliable

leepokai4121bee9b809
diff --git a/host/src/agent/backends.rs b/host/src/agent/backends.rs
index 344d1d02..cc9846d2 100644
--- a/host/src/agent/backends.rs
+++ b/host/src/agent/backends.rs
@@ -388,36 +388,37 @@ pub fn harness(id: &str) -> Option<&'static Harness> {
static SEARCH_PATH: Mutex<Vec<PathBuf>> = Mutex::new(Vec::new());
/// Login-shell PATH, via `$SHELL -ilc` with a timeout (nvm/conda can make shells slow).
-/// Windows has no login shell: every process already gets the user's PATH.
+/// The shell writes it to a file: a background job started by an rc file can hold a stdout
+/// pipe open long after the shell exits. Windows has no login shell: every process already
+/// gets the user's PATH.
fn login_shell_path() -> Option<String> {
- const MARK: &str = "__CODYNC_PATH__";
if cfg!(windows) {
return None;
}
let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/zsh".into());
+ let file = std::env::temp_dir().join(format!("codync-path-{}", uuid::Uuid::new_v4()));
+ let target = file.to_string_lossy().replace('\'', r"'\''");
let mut child = std::process::Command::new(shell)
- .args(["-ilc", &format!("printf '%s%s%s' '{MARK}' \"$PATH\" '{MARK}'")])
+ .args(["-ilc", &format!("printf '%s' \"$PATH\" > '{target}'")])
.stdin(std::process::Stdio::null())
- .stdout(std::process::Stdio::piped())
+ .stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()
.ok()?;
let deadline = std::time::Instant::now() + Duration::from_secs(8);
- loop {
+ let exited = loop {
match child.try_wait() {
- Ok(Some(_)) => break,
+ Ok(Some(_)) => break true,
Ok(None) if std::time::Instant::now() < deadline => std::thread::sleep(Duration::from_millis(50)),
_ => {
let _ = child.kill();
- return None;
+ break false;
}
}
- }
- let mut out = String::new();
- std::io::Read::read_to_string(&mut child.stdout.take()?, &mut out).ok()?;
- let start = out.find(MARK)? + MARK.len();
- let end = start + out[start..].find(MARK)?;
- Some(out[start..end].to_owned())
+ };
+ let path = std::fs::read_to_string(&file).ok().filter(|p| exited && !p.is_empty());
+ let _ = std::fs::remove_file(&file);
+ path
}
/// `…/v22.1.0` → `[22, 1, 0]` (unparseable parts count as 0).
diff --git a/host/src/agent/bot/queue.rs b/host/src/agent/bot/queue.rs
index e937096d..0cb760e7 100644
--- a/host/src/agent/bot/queue.rs
+++ b/host/src/agent/bot/queue.rs
@@ -234,7 +234,8 @@ impl Actor {
self.finish_routine(crate::routines::Status::Failed, Some(format!("Could not start routine: {e:#}")), None);
self.complete_request(Err(anyhow!("couldn't start recipient: {e:#}")), false);
self.complete_group(Err(anyhow!("couldn't start: {e:#}")));
- let mut msg = format!("Couldn't start the agent: {e}");
+ // `{:#}` keeps the reason ("starting `npx …`: EACCES"), not just "agent process exited".
+ let mut msg = format!("Couldn't start the agent: {e:#}");
if e.to_string().to_lowercase().contains("auth")
&& let Some(h) = crate::agent::backends::harness(&self.cfg.backend)
{
diff --git a/host/src/service/unix.rs b/host/src/service/unix.rs
index a01e5009..88dfe1a2 100644
--- a/host/src/service/unix.rs
+++ b/host/src/service/unix.rs
@@ -46,7 +46,8 @@ pub fn require_executable(expected: &Path) -> Result<()> {
let command =
unit.lines().find_map(|line| line.strip_prefix("ExecStart=")).context("service has no ExecStart")?;
let args = shlex::split(command).context("invalid service ExecStart")?;
- PathBuf::from(args.first().context("service has no executable")?)
+ let exe = args.first().context("service has no executable")?;
+ PathBuf::from(exe.replace("%%", "%").replace("$$", "$"))
};
if configured.canonicalize()? != expected.canonicalize()? {
bail!("the installed service runs another host binary; run that binary's update command");
@@ -66,6 +67,13 @@ fn xml_escape(s: &str) -> String {
s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;")
}
+/// One quoted systemd word: a PATH with spaces (WSL's `Program Files`) stays whole, and `%`
+/// is never read as a specifier. `ExecStart` also expands `$`, so it is doubled there.
+fn systemd_quote(s: &str, exec: bool) -> String {
+ let s = s.replace('\\', "\\\\").replace('"', "\\\"").replace('%', "%%");
+ format!("\"{}\"", if exec { s.replace('$', "$$") } else { s })
+}
+
/// Installs and starts the host as a per-user background service. The current
/// PATH is captured so the service finds `npx`, `claude`, `codex`, …
pub fn install(port: u16) -> Result<()> {
@@ -107,8 +115,10 @@ pub fn install(port: u16) -> Result<()> {
run("launchctl", &["bootstrap", &format!("gui/{uid}"), &file.to_string_lossy()])?;
} else {
let unit = format!(
- "[Unit]\nDescription=Codync host\nAfter=network-online.target\n\n[Service]\nExecStart={exe} serve --port {port}\nEnvironment=PATH={path}\nEnvironment=\"CODYNC_HOME={data}\"\nRestart=always\nRestartSec=3\n\n[Install]\nWantedBy=default.target\n",
- data = data_dir().display(),
+ "[Unit]\nDescription=Codync host\nAfter=network-online.target\n\n[Service]\nExecStart={exe} serve --port {port}\nEnvironment={path}\nEnvironment={data}\nRestart=always\nRestartSec=3\n\n[Install]\nWantedBy=default.target\n",
+ exe = systemd_quote(&exe, true),
+ path = systemd_quote(&format!("PATH={path}"), false),
+ data = systemd_quote(&format!("CODYNC_HOME={}", data_dir().display()), false),
);
let file = systemd_unit();
create_parent(&file)?;
@@ -149,3 +159,21 @@ fn current_uid() -> String {
.and_then(|o| String::from_utf8(o.stdout).ok())
.map_or_else(|| "501".into(), |s| s.trim().to_owned())
}
+
+#[cfg(test)]
+mod tests {
+ use super::systemd_quote;
+
+ #[test]
+ fn unit_values_stay_one_word() {
+ let path = r#"/usr/bin:/mnt/c/Program Files/a"b\c:/x%y"#;
+ assert_eq!(
+ systemd_quote(&format!("PATH={path}"), false),
+ r#""PATH=/usr/bin:/mnt/c/Program Files/a\"b\\c:/x%%y""#
+ );
+ let exe = systemd_quote("/home/me/My $bin/codync-host", true);
+ assert_eq!(exe, r#""/home/me/My $$bin/codync-host""#);
+ let parsed = shlex::split(&format!("{exe} serve")).unwrap();
+ assert_eq!(parsed[0].replace("%%", "%").replace("$$", "$"), "/home/me/My $bin/codync-host");
+ }
+}