Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(host-core): confirm macOS stopped group disappearance
cauliflower6cadb0e36084
diff --git a/crates/host-core/src/background_tasks.rs b/crates/host-core/src/background_tasks.rsindex e374720cf..01d87973c 100644--- a/crates/host-core/src/background_tasks.rs+++ b/crates/host-core/src/background_tasks.rs@@ -372,6 +372,7 @@ async fn supervise(let mut exit = None;let mut output_closed = false;let mut stopping = false;+ let mut stop_signal_sent = false;let mut lifecycle_failed = false;let mut stdout_decoder = tools::Utf8Decoder::default();let mut stderr_decoder = tools::Utf8Decoder::default();@@ -384,8 +385,13 @@ async fn supervise(// stop, and stopping takes precedence over a busy output pipe.biased;waited = &mut wait, if exit.is_none() => {+ let cleanup = if stop_signal_sent && matches!(waited, Ok(Ok(_))) {+ runner.ownership.cleanup_after_stopped_exit(runner.pid).await+ } else {+ runner.ownership.terminate_fail_closed(runner.pid)+ };exit = Some(waited);- if let Err(error) = runner.ownership.terminate_fail_closed(runner.pid) {+ if let Err(error) = cleanup {tracing::error!(task_id = %task.id, %error, "background task exit cleanup failed");lifecycle_failed = true;}@@ -393,9 +399,12 @@ async fn supervise(changed = stop_rx.changed(), if exit.is_none() && !stopping => {if changed.is_err() || *stop_rx.borrow() {stopping = true;- if let Err(error) = runner.ownership.terminate_fail_closed(runner.pid) {- tracing::error!(task_id = %task.id, %error, "background task stop failed");- lifecycle_failed = true;+ match runner.ownership.request_background_stop(runner.pid) {+ Ok(sent) => stop_signal_sent = sent,+ Err(error) => {+ tracing::error!(task_id = %task.id, %error, "background task stop failed");+ lifecycle_failed = true;+ }}}}diff --git a/crates/host-core/src/tools/mod.rs b/crates/host-core/src/tools/mod.rsindex 32226c270..5d85d21ba 100644--- a/crates/host-core/src/tools/mod.rs+++ b/crates/host-core/src/tools/mod.rs@@ -29,6 +29,8 @@ mod grep_rg;pub mod hashline;pub mod ignore_rules;mod image_dimensions;+#[cfg(any(unix, test))]+mod process_group;pub mod shell;#[cfg(windows)]mod windows_process_tree;@@ -226,19 +228,9 @@ impl ProcessOwnership {#[cfg(unix)]fn terminate(&self, pid: u32) -> Result<(), String> {- if pid == 0 {- return Err("shell runner has no process group".into());- }- let result = unsafe { libc::killpg(pid as libc::pid_t, libc::SIGKILL) };- if result == 0 {- return Ok(());- }- let error = io::Error::last_os_error();- if error.raw_os_error() == Some(libc::ESRCH) {- Ok(())- } else {- Err(format!("killpg failed for the shell runner: {error}"))- }+ process_group::signal(pid, libc::SIGKILL)+ .map(|_| ())+ .map_err(|error| format!("killpg failed for the shell runner: {error}"))}#[cfg(all(not(windows), not(unix)))]@@ -258,6 +250,30 @@ impl ProcessOwnership {#[cfg(not(windows))]fn close_now(&mut self) {}+ /// On macOS distinguish a delivered stop from an already absent group.+ pub(crate) fn request_background_stop(&mut self, pid: u32) -> Result<bool, String> {+ #[cfg(target_os = "macos")]+ {+ process_group::signal(pid, libc::SIGKILL)+ .map_err(|error| format!("killpg failed for the shell runner: {error}"))+ }+ #[cfg(not(target_os = "macos"))]+ self.terminate_fail_closed(pid).map(|()| true)+ }++ pub(crate) async fn cleanup_after_stopped_exit(&mut self, pid: u32) -> Result<(), String> {+ #[cfg(target_os = "macos")]+ {+ process_group::confirm_cleanup(process_group::signal(pid, libc::SIGKILL), || {+ process_group::signal(pid, 0)+ })+ .await+ .map_err(|error| format!("killpg failed for the shell runner: {error}"))+ }+ #[cfg(not(target_os = "macos"))]+ self.terminate_fail_closed(pid)+ }+pub(crate) fn terminate_fail_closed(&mut self, pid: u32) -> Result<(), String> {match self.terminate(pid) {Ok(()) => Ok(()),diff --git a/crates/host-core/src/tools/process_group.rs b/crates/host-core/src/tools/process_group.rsnew file mode 100644index 000000000..f59583c55--- /dev/null+++ b/crates/host-core/src/tools/process_group.rs@@ -0,0 +1,88 @@+use std::io;++/// Returns false only when the kernel reports that the group does not exist.+#[cfg(unix)]+pub(super) fn signal(pid: u32, signal: libc::c_int) -> io::Result<bool> {+ let pgid = libc::pid_t::try_from(pid)+ .ok()+ .filter(|pgid| *pgid > 0)+ .ok_or_else(|| {+ io::Error::new(io::ErrorKind::InvalidInput, "invalid shell process group")+ })?;+ if unsafe { libc::killpg(pgid, signal) } == 0 {+ return Ok(true);+ }+ let error = io::Error::last_os_error();+ if error.raw_os_error() == Some(libc::ESRCH) {+ Ok(false)+ } else {+ Err(error)+ }+}++#[cfg(any(target_os = "macos", test))]+pub(super) async fn confirm_cleanup(+ cleanup: io::Result<bool>,+ mut probe: impl FnMut() -> io::Result<bool>,+) -> io::Result<()> {+ let denial = match cleanup {+ Ok(_) => return Ok(()),+ Err(error) if error.kind() == io::ErrorKind::PermissionDenied => error,+ Err(error) => return Err(error),+ };+ // Darwin can deny exit cleanup briefly after a successful group stop.+ // Probe with signal 0 only: a PGID that outlives this window could be reused.+ for delay_ms in [10, 40, 100, 250] {+ tokio::time::sleep(std::time::Duration::from_millis(delay_ms)).await;+ match probe() {+ Ok(false) => return Ok(()),+ Ok(true) => {}+ Err(error) if error.kind() == io::ErrorKind::PermissionDenied => {}+ Err(error) => return Err(error),+ }+ }+ Err(denial)+}++#[cfg(test)]+mod tests {+ use super::*;++ fn denied() -> io::Error {+ io::ErrorKind::PermissionDenied.into()+ }++ #[tokio::test]+ async fn stopped_group_disappears_after_cleanup_denial() {+ let mut probes = [Err(denied()), Ok(false)].into_iter();+ confirm_cleanup(Err(denied()), || probes.next().unwrap())+ .await+ .unwrap();+ }++ #[tokio::test]+ async fn stopped_group_must_disappear_before_denial_can_be_cleared() {+ for accessible in [false, true] {+ let error = confirm_cleanup(Err(denied()), || {+ if accessible {+ Ok(true)+ } else {+ Err(denied())+ }+ })+ .await+ .unwrap_err();+ assert_eq!(error.kind(), io::ErrorKind::PermissionDenied);+ }+ }++ #[tokio::test]+ async fn other_cleanup_errors_are_not_retried() {+ let error = confirm_cleanup(Err(io::ErrorKind::InvalidInput.into()), || {+ panic!("unexpected process group probe")+ })+ .await+ .unwrap_err();+ assert_eq!(error.kind(), io::ErrorKind::InvalidInput);+ }+}diff --git a/docs/spec/03-runtime/03-tools-and-permissions.md b/docs/spec/03-runtime/03-tools-and-permissions.mdindex 1cf4acea1..9a300ba19 100644--- a/docs/spec/03-runtime/03-tools-and-permissions.md+++ b/docs/spec/03-runtime/03-tools-and-permissions.md@@ -1025,3 +1025,7 @@ the supervisor's process-tree cleanup and reports its actual settled outcomeor a still-running snapshot with stopRequested. The model's reads and desktopreads do not consume each other's logs. Retention and Host restart still boundhow long a finished ID can be queried.++On macOS, if exit cleanup is denied after the Host successfully signalled the+group and reaped the child, it briefly checks whether the process group still+exists. Only a confirmed disappearance clears that denial.diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 5ee166e85..4f5bcabbc 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -20508,6 +20508,9 @@ Scenario: E2E-REVIEW-ROUNDS (local desktop, implemented)controls and registration without a subagent catalog.- Host tests cover pre-settled observation, repeatable output, Unicode clipping,ownership lookup, idempotent stop and stop acknowledgement before termination.+ On macOS, after a successful group stop and child exit, check that a cleanup+ denial followed by a missing group settles as stopped; a persistent denial+ or still-present group must retain the cleanup failure.Existing Windows child/grandchild cleanup tests remain required; record nativefailures separately from protocol success.- Exercise a late stop with an already reaped child before the supervisor drains the pipes. Verify the original exit outcome, final output and stable elapsed time across reads. Stall capability discovery or the first Host observation to exercise the overall wait deadline. The Electron transcript fixture renders a pending Bash stop and a mixed job list.diff --git a/docs/zh-CN/spec/03-runtime/03-tools-and-permissions.md b/docs/zh-CN/spec/03-runtime/03-tools-and-permissions.mdindex 1c03164f4..faf187abf 100644--- a/docs/zh-CN/spec/03-runtime/03-tools-and-permissions.md+++ b/docs/zh-CN/spec/03-runtime/03-tools-and-permissions.md@@ -765,3 +765,5 @@ sidecar 不附加覆盖,委托使用会话的有效权限模式;因此父会Agent 模式下,模型通过 TaskList、TaskWait、TaskStop 管理本会话的后台 Bash,桌面和模型读取同一 Host 作业记录。runtime 带入已绑定会话身份,模型参数不能选择其他会话。Host 要求会话存在、属于本地并处于 Agent 模式,按 sessionId 与 id 校验读取和停止。未知与其他会话的 ID 均返回 NOT_FOUND。等待不会终止进程。单次 Host 观察最多一秒,可在新输入或取消时放弃,等待期间不持有全局状态锁。终态通知在输出收尾后发出。显式停止复用主管的进程树清理,并返回实际终态或带 stopRequested 的运行中快照。查询互不消耗日志。有限历史与 Host 重启仍限制旧 ID 可查询的时间。++在 macOS 上,如果 Host 已成功向进程组发送停止信号并回收了子进程,但退出清理被拒绝,Host 会在短时间内复查进程组是否仍存在。只有确认进程组已消失,才清除这次权限错误。diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.mdindex 7e7698b2b..0dbfa8044 100644--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md@@ -10478,6 +10478,7 @@ Electron 一侧——工具自动签发、指示器、"停止"中止轮次、绘- 使用隔离 Host 数据、工作目录、生产 runtime/pi 循环与本地 HTTP 模型夹具。- 后台启动测试,列举并等待失败结果;启动常驻命令,等待超时、无参停止,再显式停止并等待。- 验证退出码、两路末尾输出、UTF-8 上限、跨会话列表/读/停隔离、超时和无参停止保留 Bash、显式停止终态、重复查询及桌面输出一致;拒绝 Plan 模式。+- macOS 上,停止信号成功且子进程退出后,清理被拒绝但随后确认进程组消失,应得到 stopped;持续拒绝或进程组仍存在时,应保留清理失败。- runtime 测试补充新输入和父回合取消、延迟 RPC 错误、旧 Host/远程能力缺失、混合选择器拒绝、原委派控制及无子代理配置的工具注册。- Host 测试覆盖先完成后等待、重复读取、Unicode 截断、归属查找、幂等停止与停止请求待确认。Windows 子孙进程清理测试仍须执行,原生失败单独报告。- 在子进程已退出、监管任务尚未排空管道时请求停止,检查原退出结果、最终输出和重复读取的耗时。延迟能力探测或第一次 Host 观察,检查等待总时限。Electron 会话记录用例渲染尚待确认的 Bash 停止请求和混合作业列表。