Skip to content

Commit 87fd93b

Browse files
authored
fix(gateway): make the gateway the single owner of the agent home dir (#107)
1 parent cb521c6 commit 87fd93b

21 files changed

Lines changed: 973 additions & 233 deletions

‎apps/desktop/Cargo.lock‎

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎apps/desktop/Cargo.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[package]
22
name = "pizza-gui"
3-
version = "0.5.4"
3+
version = "0.5.5"
44
description = "Pizza desktop GUI"
55
edition = "2021"
66
rust-version = "1.90"

‎apps/desktop/src/bridge.rs‎

Lines changed: 58 additions & 123 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use crate::gateway_channel;
2+
use crate::pid_lock;
23
use crate::remote;
34
use crate::remote_deploy;
45
use base64::Engine;
@@ -868,118 +869,32 @@ fn main_agent_lock_path() -> Option<PathBuf> {
868869
persistent_chat_cwd().map(|cwd| PathBuf::from(cwd).join(".lock"))
869870
}
870871

871-
fn read_main_agent_lock_pid() -> Option<(PathBuf, u32)> {
872+
fn read_main_agent_lock() -> Option<(PathBuf, pid_lock::LockInfo)> {
872873
let lock_path = main_agent_lock_path()?;
873-
let raw = std::fs::read_to_string(&lock_path).ok()?;
874-
let pid = raw.trim().parse::<u32>().ok()?;
875-
Some((lock_path, pid))
876-
}
877-
878-
#[cfg(unix)]
879-
fn is_process_alive(pid: u32) -> bool {
880-
Command::new("kill")
881-
.args(["-0", &pid.to_string()])
882-
.status()
883-
.map(|status| status.success())
884-
.unwrap_or(false)
885-
}
886-
887-
#[cfg(windows)]
888-
fn is_process_alive(pid: u32) -> bool {
889-
// `tasklist /FI "PID eq <pid>" /FO CSV /NH` prints one CSV line per
890-
// matching process, or "INFO: No tasks..." when the pid is dead.
891-
Command::new("tasklist")
892-
.args(["/FI", &format!("PID eq {}", pid), "/FO", "CSV", "/NH"])
893-
.output()
894-
.map(|out| {
895-
String::from_utf8_lossy(&out.stdout).lines().any(|line| {
896-
line.split(',')
897-
.nth(1)
898-
.map(|field| field.trim_matches('"') == pid.to_string())
899-
.unwrap_or(false)
900-
})
901-
})
902-
.unwrap_or(false)
903-
}
904-
905-
#[cfg(not(any(unix, windows)))]
906-
fn is_process_alive(_pid: u32) -> bool {
907-
false
908-
}
909-
910-
#[cfg(unix)]
911-
fn process_command(pid: u32) -> Option<String> {
912-
let pid_arg = pid.to_string();
913-
let output = Command::new("ps")
914-
.args(["-p", &pid_arg, "-o", "command="])
915-
.output()
916-
.ok()?;
917-
if !output.status.success() {
918-
return None;
919-
}
920-
let command = String::from_utf8_lossy(&output.stdout).trim().to_string();
921-
if command.is_empty() {
922-
None
923-
} else {
924-
Some(command)
925-
}
926-
}
927-
928-
#[cfg(windows)]
929-
fn process_command(pid: u32) -> Option<String> {
930-
let output = Command::new("powershell")
931-
.args([
932-
"-NoProfile",
933-
"-Command",
934-
&format!(
935-
"(Get-CimInstance Win32_Process -Filter 'ProcessId={}').CommandLine",
936-
pid
937-
),
938-
])
939-
.output()
940-
.ok()?;
941-
if !output.status.success() {
942-
return None;
943-
}
944-
let command = String::from_utf8_lossy(&output.stdout).trim().to_string();
945-
if command.is_empty() {
946-
None
947-
} else {
948-
Some(command)
949-
}
950-
}
951-
952-
#[cfg(not(any(unix, windows)))]
953-
fn process_command(_pid: u32) -> Option<String> {
954-
None
955-
}
956-
957-
fn is_probably_pizza_main_agent(command: &str) -> bool {
958-
let lower = command.to_ascii_lowercase();
959-
command.contains("--main")
960-
&& (lower.contains("pizza")
961-
|| lower.contains("src/cli")
962-
|| lower.contains("src/main")
963-
|| lower.contains("dist/cli")
964-
|| lower.contains("dist/main"))
874+
let info = pid_lock::read_lock(&lock_path)?;
875+
Some((lock_path, info))
965876
}
966877

967878
fn current_main_agent_status() -> MainAgentStatus {
968879
let lock_path = main_agent_lock_path().unwrap_or_else(|| PathBuf::from("~/.pizza/main/.lock"));
969880
let lock_path_str = lock_path.to_string_lossy().to_string();
970-
let Some((_, pid)) = read_main_agent_lock_pid() else {
881+
let Some((_, info)) = read_main_agent_lock() else {
971882
return MainAgentStatus {
972883
running: false,
973884
pid: None,
974885
command: None,
975886
lock_path: lock_path_str,
976887
};
977888
};
978-
let running = is_process_alive(pid);
979-
let command = if running { process_command(pid) } else { None };
889+
let running = pid_lock::owner_alive(&info);
890+
let command = if running {
891+
pid_lock::process_command(info.pid)
892+
} else {
893+
None
894+
};
980895
MainAgentStatus {
981896
running,
982-
pid: Some(pid),
897+
pid: Some(info.pid),
983898
command,
984899
lock_path: lock_path_str,
985900
}
@@ -990,28 +905,57 @@ pub fn main_agent_status() -> Result<MainAgentStatus, String> {
990905
Ok(current_main_agent_status())
991906
}
992907

908+
/// Wait up to ~3s for `pid` to exit, then drop its lock if it left one.
909+
async fn wait_for_main_agent_exit(lock_path: &Path, pid: u32) -> bool {
910+
for _ in 0..30 {
911+
if !pid_lock::is_process_alive(pid) {
912+
if pid_lock::read_lock(lock_path).is_some_and(|info| info.pid == pid) {
913+
let _ = std::fs::remove_file(lock_path);
914+
}
915+
return true;
916+
}
917+
tokio::time::sleep(Duration::from_millis(100)).await;
918+
}
919+
false
920+
}
921+
993922
#[tauri::command]
994923
pub async fn stop_main_agent() -> Result<MainAgentStatus, String> {
995-
let Some((lock_path, pid)) = read_main_agent_lock_pid() else {
924+
let Some((lock_path, info)) = read_main_agent_lock() else {
996925
return Ok(current_main_agent_status());
997926
};
998-
if !is_process_alive(pid) {
927+
let pid = info.pid;
928+
if !pid_lock::owner_alive(&info) {
929+
// Dead owner, or its pid now belongs to an unrelated process.
999930
let _ = std::fs::remove_file(&lock_path);
1000931
return Ok(current_main_agent_status());
1001932
}
1002-
let command = process_command(pid).unwrap_or_default();
1003-
if !is_probably_pizza_main_agent(&command) {
1004-
return Err(format!(
1005-
"The process referenced by the lock file does not look like the Pizza main agent; aborting. PID: {}, command: {}",
1006-
pid,
1007-
if command.is_empty() {
1008-
"<unknown>"
1009-
} else {
1010-
&command
933+
934+
// A gateway respawns its main agent right after it is killed (scheduler
935+
// guard, next attach) and re-takes the lock. Stop that whole gateway
936+
// instead — unless it is the gateway this desktop is using.
937+
if let Some(owner_gateway) = info.str_field("gatewaySocket").map(PathBuf::from) {
938+
if Some(&owner_gateway) != gateway_channel::current_gateway_socket().as_ref() {
939+
let socket = owner_gateway.clone();
940+
let stopped = tauri::async_runtime::spawn_blocking(move || {
941+
gateway_channel::stop_gateway(&socket)
942+
})
943+
.await
944+
.unwrap_or(false);
945+
log_file(&format!(
946+
"stop_main_agent: stopped owning gateway {} (main agent pid {}): {}",
947+
owner_gateway.display(),
948+
pid,
949+
stopped
950+
));
951+
if stopped && wait_for_main_agent_exit(&lock_path, pid).await {
952+
return Ok(current_main_agent_status());
1011953
}
1012-
));
954+
}
1013955
}
1014956

957+
// owner_alive() matched the recorded start time, so `pid` is provably the
958+
// main agent that wrote the lock (not a reused pid) — safe to signal.
1015959
#[cfg(unix)]
1016960
let stop_result = Command::new("kill")
1017961
.args(["-TERM", &pid.to_string()])
@@ -1035,17 +979,8 @@ pub async fn stop_main_agent() -> Result<MainAgentStatus, String> {
1035979
));
1036980
}
1037981

1038-
for _ in 0..30 {
1039-
if !is_process_alive(pid) {
1040-
if std::fs::read_to_string(&lock_path)
1041-
.map(|raw| raw.trim() == pid.to_string())
1042-
.unwrap_or(false)
1043-
{
1044-
let _ = std::fs::remove_file(&lock_path);
1045-
}
1046-
return Ok(current_main_agent_status());
1047-
}
1048-
tokio::time::sleep(Duration::from_millis(100)).await;
982+
if wait_for_main_agent_exit(&lock_path, pid).await {
983+
return Ok(current_main_agent_status());
1049984
}
1050985

1051986
Err(format!(
@@ -2792,7 +2727,7 @@ pub async fn channel_op(
27922727
.ok_or_else(|| "HOME not set; cannot resolve gateway socket".to_string())?;
27932728
let (program, args) = gateway_command(resolve_pizza_command(&app));
27942729
tauri::async_runtime::spawn_blocking(move || {
2795-
gateway_channel::ensure_gateway(
2730+
let socket = gateway_channel::ensure_gateway(
27962731
&socket,
27972732
(&program, &args),
27982733
Some(env!("CARGO_PKG_VERSION")),
@@ -2986,7 +2921,7 @@ async fn init_sidecar_via_gateway(
29862921
// ensure_gateway, connect and attach all block (attach waits up to 15s
29872922
// for attach_ok): keep them off the async runtime's worker threads.
29882923
let (channel, resolved_cwd) = tauri::async_runtime::spawn_blocking(move || {
2989-
gateway_channel::ensure_gateway(
2924+
let socket = gateway_channel::ensure_gateway(
29902925
&socket,
29912926
(&program, &args),
29922927
Some(env!("CARGO_PKG_VERSION")),
@@ -3536,7 +3471,7 @@ pub async fn delete_workspace(
35363471
// sidecars alone leaves the gateway owner alive and able to recreate metadata.
35373472
if let Some(ref cwd) = cwd {
35383473
let existing = lock_ok(&state.channels).get(cwd).cloned();
3539-
let socket = gateway_channel::gateway_socket_path();
3474+
let socket = gateway_channel::current_gateway_socket();
35403475
let target = cwd.clone();
35413476
tauri::async_runtime::spawn_blocking(move || -> Result<(), String> {
35423477
if let Some(channel) = existing {

0 commit comments

Comments
 (0)