Skip to content

Commit 39911e4

Browse files
wesbillmanBrain
andauthored
fix(desktop): scope agent sweep to the owning app instance (#808)
Signed-off-by: Wes <[email protected]> Co-authored-by: Brain <21994759fc7a6fa6b965551d35cfd7897d262f2495467f2d78694ddcfa6a5c7e@sprout-oss.stage.blox.sqprod.co>
1 parent f2c266b commit 39911e4

4 files changed

Lines changed: 66 additions & 26 deletions

File tree

‎desktop/scripts/check-file-sizes.mjs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ const overrides = new Map([
5252
["src-tauri/src/commands/agents.rs", 881], // remote agent lifecycle routing (local + provider branches) + scope enforcement + persona pack metadata wiring + mcp_toolsets field + NIP-OA auth_tag in deploy payload
5353
["src-tauri/src/commands/messages.rs", 515], // feed multi-query + NIP-50 search + forum thread resolution + thread ref + reactions via REQ + edit_message media_tags param (Slack-style attachment-editable edits)
5454
["src-tauri/src/nostr_convert.rs", 1150], // 12 Nostr event→model converters (channels, profiles, members, notes, search, agents, relay members) + rank_user_search_results helper for NIP-50 user search + 33 unit tests
55-
["src-tauri/src/managed_agents/runtime.rs", 1300], // ... + respond-to gate env (SPROUT_ACP_RESPOND_TO[_ALLOWLIST]) + per-mode env builder + tests + persona/agent env_vars spawn merge (helper + tests now in env_vars.rs) + system-wide orphan sweep (proc_listallpids/proc on macOS, /proc on Linux) + SPROUT_MANAGED_AGENT env marker check (KERN_PROCARGS2 on macOS, /proc/environ on Linux)
55+
["src-tauri/src/managed_agents/runtime.rs", 1330], // ... + respond-to gate env (SPROUT_ACP_RESPOND_TO[_ALLOWLIST]) + per-mode env builder + tests + persona/agent env_vars spawn merge (helper + tests now in env_vars.rs) + system-wide orphan sweep (proc_listallpids/proc on macOS, /proc on Linux) + SPROUT_MANAGED_AGENT env marker check (KERN_PROCARGS2 on macOS, /proc/environ on Linux), instance-scoped by app identifier so coexisting Sprout instances don't reap each other's agents
5656
["src-tauri/src/managed_agents/discovery.rs", 680], // KNOWN_ACP_PROVIDERS catalog + resolve_command cache + login_shell_path + classify_provider (four-state: Available/AdapterMissing/CliMissing/NotInstalled) + discover_acp_providers with dynamic install_hint + known_acp_provider/known_acp_provider_exact + normalize_agent_args + 15 unit tests
5757
["src-tauri/src/managed_agents/types.rs", 745], // ManagedAgentRecord/Summary + Create/Update request structs + AcpProviderCatalogEntry + InstallRuntimeResult + RespondTo enum + validate_respond_to_allowlist + tests + persona/agent env_vars field
5858
["src-tauri/src/managed_agents/backend.rs", 700], // provider IPC, validation, discovery, binary resolution + tests + redact_secrets_with for user env values + env_secrets_from_request + redact_env_values_in (shared with model discovery)

‎desktop/src-tauri/src/lib.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -152,7 +152,7 @@ fn shutdown_managed_agents(app: &tauri::AppHandle) -> Result<(), String> {
152152
// in their own process groups by sprout-acp, so group-kills above only
153153
// reach the harness, not the workers. Scan all user processes and kill any
154154
// known agent binaries that are still running.
155-
managed_agents::sweep_system_agent_processes(&[]);
155+
managed_agents::sweep_system_agent_processes(&managed_agents::current_instance_id(app), &[]);
156156

157157
if changed {
158158
save_managed_agents(app, &records)?;

‎desktop/src-tauri/src/managed_agents/restore.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ pub fn restore_managed_agents_on_launch(
5757
// agent binaries not tracked by this session. Catches orphans whose
5858
// PID files were already cleaned up (e.g. agent workers in their own
5959
// process group whose parent harness exited).
60-
super::sweep_system_agent_processes(&tracked_pids);
60+
super::sweep_system_agent_processes(&super::current_instance_id(app), &tracked_pids);
6161

6262
let candidates: Vec<String> = records
6363
.iter()

‎desktop/src-tauri/src/managed_agents/runtime.rs‎

Lines changed: 63 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -118,11 +118,32 @@ pub(crate) fn process_belongs_to_us(_pid: u32) -> bool {
118118
false
119119
}
120120

121-
/// Check if a running process has `SPROUT_MANAGED_AGENT=1` in its environment,
122-
/// distinguishing Sprout-spawned agent trees from independently-launched ones.
121+
/// The value stamped into the `SPROUT_MANAGED_AGENT` env var of every agent we
122+
/// spawn, identifying *which* desktop instance owns it. We use the app's bundle
123+
/// identifier (`xyz.block.sprout.app` for release, `xyz.block.sprout.app.dev`
124+
/// for `just dev`) because it is stable across restarts — a relaunched dev
125+
/// instance still recognizes its own previously-spawned agents as reclaimable,
126+
/// while never matching another instance's (e.g. a dev build never reaps a DMG
127+
/// build's agents, and vice versa). This is what lets two Sprouts coexist on
128+
/// one machine without one's cleanup nuking the other's agents.
129+
pub(crate) fn current_instance_id(app: &AppHandle) -> String {
130+
app.config().identifier.clone()
131+
}
132+
133+
/// Build the full `SPROUT_MANAGED_AGENT=<instance-id>` env entry we match
134+
/// against when scanning processes. Kept here so the spawn stamp and the sweep
135+
/// matcher can never drift apart.
136+
fn sprout_marker_entry(instance_id: &str) -> Vec<u8> {
137+
format!("SPROUT_MANAGED_AGENT={instance_id}").into_bytes()
138+
}
139+
140+
/// Check if a running process is one of *our* managed agents: it must carry
141+
/// `SPROUT_MANAGED_AGENT=<instance_id>` in its environment, where `instance_id`
142+
/// is this desktop instance's id. A process stamped with a *different* instance
143+
/// id belongs to another live Sprout app and must never be reaped here.
123144
#[cfg(target_os = "macos")]
124-
fn process_has_sprout_marker(pid: u32) -> bool {
125-
const MARKER: &[u8] = b"SPROUT_MANAGED_AGENT=1";
145+
fn process_has_sprout_marker(pid: u32, instance_id: &str) -> bool {
146+
let marker = sprout_marker_entry(instance_id);
126147

127148
let mut mib: [libc::c_int; 3] = [libc::CTL_KERN, libc::KERN_PROCARGS2, pid as libc::c_int];
128149
let mut buf_size: libc::size_t = 0;
@@ -192,20 +213,20 @@ fn process_has_sprout_marker(pid: u32) -> bool {
192213
args_remaining -= 1;
193214
}
194215
// Remaining bytes are null-delimited environment strings.
195-
buf[pos..].split(|&b| b == 0).any(|entry| entry == MARKER)
216+
buf[pos..].split(|&b| b == 0).any(|entry| entry == marker)
196217
}
197218

198219
#[cfg(all(unix, not(target_os = "macos")))]
199-
fn process_has_sprout_marker(pid: u32) -> bool {
220+
fn process_has_sprout_marker(pid: u32, instance_id: &str) -> bool {
221+
let marker = sprout_marker_entry(instance_id);
200222
let Ok(data) = std::fs::read(format!("/proc/{pid}/environ")) else {
201223
return false;
202224
};
203-
data.split(|&b| b == 0)
204-
.any(|entry| entry == b"SPROUT_MANAGED_AGENT=1")
225+
data.split(|&b| b == 0).any(|entry| entry == marker)
205226
}
206227

207228
#[cfg(not(unix))]
208-
fn process_has_sprout_marker(_pid: u32) -> bool {
229+
fn process_has_sprout_marker(_pid: u32, _instance_id: &str) -> bool {
209230
false
210231
}
211232

@@ -347,12 +368,13 @@ pub(crate) fn sweep_orphaned_agent_processes(app: &AppHandle, _skip_pids: &[u32]
347368
}
348369

349370
/// Enumerate all processes on the system owned by the current user and kill any
350-
/// that match `KNOWN_AGENT_BINARIES` but aren't in `skip_pids`. This catches
351-
/// orphans that escaped PID-file-based cleanup (e.g. agent workers spawned with
352-
/// their own process group whose parent harness already exited and had its PID
353-
/// file removed).
371+
/// agent binary stamped with *this* instance's `SPROUT_MANAGED_AGENT` marker
372+
/// (`instance_id`) that isn't in `skip_pids`. This catches orphans that escaped
373+
/// PID-file-based cleanup (e.g. agent workers spawned with their own process
374+
/// group whose parent harness already exited and had its PID file removed),
375+
/// while leaving another live Sprout instance's agents untouched.
354376
#[cfg(target_os = "macos")]
355-
pub(crate) fn sweep_system_agent_processes(skip_pids: &[u32]) {
377+
pub(crate) fn sweep_system_agent_processes(instance_id: &str, skip_pids: &[u32]) {
356378
extern "C" {
357379
fn proc_listallpids(buffer: *mut libc::c_int, buffersize: libc::c_int) -> libc::c_int;
358380
fn proc_pidinfo(
@@ -426,7 +448,7 @@ pub(crate) fn sweep_system_agent_processes(skip_pids: &[u32]) {
426448
if info.pbi_uid != my_uid {
427449
continue;
428450
}
429-
if !process_has_sprout_marker(upid) {
451+
if !process_has_sprout_marker(upid, instance_id) {
430452
continue;
431453
}
432454
orphans.push(pid);
@@ -442,7 +464,7 @@ pub(crate) fn sweep_system_agent_processes(skip_pids: &[u32]) {
442464
}
443465

444466
#[cfg(all(unix, not(target_os = "macos")))]
445-
pub(crate) fn sweep_system_agent_processes(skip_pids: &[u32]) {
467+
pub(crate) fn sweep_system_agent_processes(instance_id: &str, skip_pids: &[u32]) {
446468
let my_uid = unsafe { libc::getuid() };
447469
let mut orphans: Vec<i32> = Vec::new();
448470
let my_pid = std::process::id() as i32;
@@ -473,7 +495,7 @@ pub(crate) fn sweep_system_agent_processes(skip_pids: &[u32]) {
473495
if meta.uid() != my_uid {
474496
continue;
475497
}
476-
if process_belongs_to_us(upid) && process_has_sprout_marker(upid) {
498+
if process_belongs_to_us(upid) && process_has_sprout_marker(upid, instance_id) {
477499
orphans.push(pid);
478500
}
479501
}
@@ -488,7 +510,7 @@ pub(crate) fn sweep_system_agent_processes(skip_pids: &[u32]) {
488510
}
489511

490512
#[cfg(not(unix))]
491-
pub(crate) fn sweep_system_agent_processes(_skip_pids: &[u32]) {}
513+
pub(crate) fn sweep_system_agent_processes(_instance_id: &str, _skip_pids: &[u32]) {}
492514

493515
/// Kill stale agent processes from a previous session whose PID is still alive
494516
/// but not tracked in the current `runtimes` map. Updates the record fields and
@@ -982,11 +1004,13 @@ pub fn spawn_agent_child(
9821004
command.env(key, value);
9831005
}
9841006

985-
// Mark as Sprout-managed so the system-wide orphan sweep can
986-
// distinguish our processes from independently-launched agent binaries.
987-
// Propagates automatically through the full tree (sprout-acp → goose →
988-
// MCP servers) because neither sprout-acp nor goose calls env_clear().
989-
command.env("SPROUT_MANAGED_AGENT", "1");
1007+
// Mark as Sprout-managed *and* which desktop instance owns us, so the
1008+
// system-wide orphan sweep only reaps this instance's own agents and never
1009+
// another live Sprout's (e.g. a `just dev` build won't kill a DMG build's
1010+
// agents). Propagates automatically through the full tree (sprout-acp →
1011+
// goose → MCP servers) because neither sprout-acp nor goose calls
1012+
// env_clear().
1013+
command.env("SPROUT_MANAGED_AGENT", current_instance_id(app));
9901014

9911015
// Spawn the harness in its own process group so we can kill the entire
9921016
// tree (harness + MCP servers + agent subprocesses) on shutdown.
@@ -1125,6 +1149,22 @@ pub fn stop_managed_agent_process(
11251149
mod tests {
11261150
use crate::managed_agents::known_acp_provider;
11271151

1152+
#[test]
1153+
fn marker_entry_is_namespaced_by_instance_id() {
1154+
// The spawn stamp and the sweep matcher must produce identical bytes;
1155+
// both go through sprout_marker_entry, so this pins the on-the-wire
1156+
// format and guards against a dev build (`...app.dev`) matching a
1157+
// release build's (`...app`) agents.
1158+
assert_eq!(
1159+
super::sprout_marker_entry("xyz.block.sprout.app"),
1160+
b"SPROUT_MANAGED_AGENT=xyz.block.sprout.app".to_vec()
1161+
);
1162+
assert_ne!(
1163+
super::sprout_marker_entry("xyz.block.sprout.app"),
1164+
super::sprout_marker_entry("xyz.block.sprout.app.dev")
1165+
);
1166+
}
1167+
11281168
#[test]
11291169
fn sprout_agent_has_mcp_hooks() {
11301170
let p = known_acp_provider("sprout-agent").expect("should resolve");

0 commit comments

Comments
 (0)