Skip to main content

agent_hub_runtime/core/preview/
profile_processes.rs

1//! Explicit recovery only: terminate the browser holding one managed profile.
2use super::{browser::Browsers, runtime};
3use crate::core::error::AppError;
4use std::{
5    path::Path,
6    sync::{Arc, Mutex},
7    time::{Duration, Instant},
8};
9use sysinfo::{Pid, Process, ProcessRefreshKind, System, UpdateKind};
10
11fn process_details() -> ProcessRefreshKind {
12    ProcessRefreshKind::new()
13        .with_cmd(UpdateKind::Always)
14        .with_exe(UpdateKind::Always)
15}
16
17impl Browsers {
18    pub fn kill_profile_process(&self, id: &str) -> Result<(), AppError> {
19        let profile = self
20            .profiles()?
21            .into_iter()
22            .find(|profile| profile.id == id)
23            .ok_or_else(|| AppError::not_found("Browser profile unavailable"))?;
24        runtime::validate_profile(&profile)?;
25        if profile.ephemeral || profile.endpoint.is_some() || profile.deleting {
26            return Err(AppError::invalid_input(
27                "Only a local saved browser profile can be recovered",
28            ));
29        }
30        let gate = self
31            .state
32            .lock()
33            .map_err(|_| AppError::internal("Browser state unavailable"))?
34            .starting
35            .entry(id.into())
36            .or_insert_with(|| Arc::new(Mutex::new(())))
37            .clone();
38        let _gate = gate
39            .lock()
40            .map_err(|_| AppError::internal("Browser startup unavailable"))?;
41        {
42            let state = self
43                .state
44                .lock()
45                .map_err(|_| AppError::internal("Browser state unavailable"))?;
46            if state.closing
47                || state.runtimes.contains_key(id)
48                || state.pending.values().any(|profile| profile == id)
49                || state.reopening_profiles.contains_key(id)
50            {
51                return Err(AppError::invalid_input(
52                    "Close this profile's active pages before recovery",
53                ));
54            }
55        }
56        let executable = profile
57            .executable
58            .filter(|value| !value.trim().is_empty())
59            .map(std::path::PathBuf::from)
60            .or_else(runtime::discover)
61            .ok_or_else(|| AppError::not_found("PREVIEW_BROWSER_NOT_FOUND"))?;
62        terminate(&self.root.join("profiles").join(id), &executable)
63    }
64}
65
66fn matches(process: &Process, directory: &Path, executable: &Path) -> bool {
67    let argument = format!("--user-data-dir={}", directory.display());
68    process.pid() != Pid::from_u32(std::process::id())
69        && process
70            .exe()
71            .and_then(|path| path.canonicalize().ok())
72            .as_deref()
73            == Some(executable)
74        && process.cmd().iter().any(|arg| arg == &argument)
75        && process.cmd().iter().any(|arg| arg == "--headless=new")
76        && process
77            .cmd()
78            .iter()
79            .any(|arg| arg == "--remote-debugging-port=0")
80        && !process.cmd().iter().any(|arg| arg.starts_with("--type="))
81}
82
83fn terminate(directory: &Path, executable: &Path) -> Result<(), AppError> {
84    let executable = executable.canonicalize()?;
85    let mut system = System::new();
86    system.refresh_processes_specifics(process_details());
87    // Exact executable and profile arguments prevent touching normal browsers or other profiles.
88    let mut targets: Vec<_> = system
89        .processes()
90        .values()
91        .filter(|process| matches(process, directory, &executable))
92        .map(|process| process.pid())
93        .collect();
94    loop {
95        let children: Vec<_> = system
96            .processes()
97            .values()
98            .filter(|process| {
99                process
100                    .parent()
101                    .is_some_and(|parent| targets.contains(&parent))
102                    && !targets.contains(&process.pid())
103            })
104            .map(|process| process.pid())
105            .collect();
106        if children.is_empty() {
107            break;
108        }
109        targets.extend(children);
110    }
111    let identities: Vec<_> = targets
112        .iter()
113        .filter_map(|pid| {
114            system.process(*pid).map(|process| {
115                (
116                    *pid,
117                    process.start_time(),
118                    process.exe().map(Path::to_path_buf),
119                    process.cmd().to_vec(),
120                )
121            })
122        })
123        .collect();
124    // Stop roots first so they cannot launch replacements while their children are being killed.
125    // Recheck identity immediately before each signal to guard against PID reuse.
126    for (pid, started, exe, cmd) in &identities {
127        if !system.refresh_process_specifics(*pid, process_details()) {
128            continue;
129        }
130        if let Some(process) = system.process(*pid).filter(|process| {
131            process.start_time() == *started
132                && process.exe() == exe.as_deref()
133                && process.cmd() == cmd
134        }) {
135            if !process.kill() {
136                return Err(AppError::io("Could not terminate the old preview process"));
137            }
138        }
139    }
140    let deadline = Instant::now() + Duration::from_secs(5);
141    let mut exited_once = false;
142    loop {
143        // A fresh process record is needed on macOS: sysinfo 0.30 retains the
144        // original BSD status when refreshing an existing record, including zombies.
145        system = System::new();
146        let alive = identities.iter().any(|(pid, started, _, _)| {
147            system.refresh_process_specifics(*pid, process_details())
148                && system.process(*pid).is_some_and(|process| {
149                    process.start_time() == *started
150                        && process.status() != sysinfo::ProcessStatus::Zombie
151                })
152        });
153        if !alive && exited_once {
154            return Ok(());
155        }
156        exited_once = !alive;
157        if Instant::now() >= deadline {
158            return Err(AppError::network(
159                "Old preview process has not exited; retry recovery",
160            ));
161        }
162        std::thread::sleep(Duration::from_millis(50));
163    }
164}
165
166#[cfg(test)]
167mod tests;